file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpFiltering.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 BP_FILTERING_H #define BP_FILTERING_H #include "PxvConfig.h" #include "foundation/PxAssert.h" namespace physx { namespace Bp { #define BP_USE_AGGREGATE_GROUP_TAIL #define BP_FILTERING_TYPE_SHIFT_BIT 3 #define BP_FILTERING_TYPE_MASK 7 /* \brief AABBManager volumes with the same filter group value are guaranteed never to generate an overlap pair. \note To ensure that static pairs never overlap, add static shapes with eSTATICS. The value eDYNAMICS_BASE provides a minimum recommended group value for dynamic shapes. If dynamics shapes are assigned group values greater than or equal to eDYNAMICS_BASE then they are allowed to generate broadphase overlaps with statics, and other dynamic shapes provided they have different group values. @see AABBManager::createVolume */ struct FilterGroup { enum Enum { eSTATICS = 0, eDYNAMICS_BASE = 1, #ifdef BP_USE_AGGREGATE_GROUP_TAIL eAGGREGATE_BASE = 0xfffffffe, #endif eINVALID = 0xffffffff }; }; struct FilterType { enum Enum { STATIC = 0, KINEMATIC = 1, DYNAMIC = 2, AGGREGATE = 3, SOFTBODY = 4, PARTICLESYSTEM = 5, FEMCLOTH = 6, HAIRSYSTEM = 7, COUNT = 8 }; }; PX_FORCE_INLINE Bp::FilterGroup::Enum getFilterGroup_Statics() { return Bp::FilterGroup::eSTATICS; } PX_FORCE_INLINE Bp::FilterGroup::Enum getFilterGroup_Dynamics(PxU32 rigidId, bool isKinematic) { const PxU32 group = rigidId + Bp::FilterGroup::eDYNAMICS_BASE; const PxU32 type = isKinematic ? FilterType::KINEMATIC : FilterType::DYNAMIC; return Bp::FilterGroup::Enum((group<< BP_FILTERING_TYPE_SHIFT_BIT)|type); } PX_FORCE_INLINE Bp::FilterGroup::Enum getFilterGroup(bool isStatic, PxU32 rigidId, bool isKinematic) { return isStatic ? getFilterGroup_Statics() : getFilterGroup_Dynamics(rigidId, isKinematic); } PX_FORCE_INLINE bool groupFiltering(const Bp::FilterGroup::Enum group0, const Bp::FilterGroup::Enum group1, const bool* PX_RESTRICT lut) { /* const int g0 = group0 & ~3; const int g1 = group1 & ~3; if(g0==g1) return false;*/ if(group0==group1) { PX_ASSERT((group0 & ~BP_FILTERING_TYPE_MASK)==(group1 & ~BP_FILTERING_TYPE_MASK)); return false; } const int type0 = group0 & BP_FILTERING_TYPE_MASK; const int type1 = group1 & BP_FILTERING_TYPE_MASK; return lut[type0*Bp::FilterType::COUNT+type1]; } class BpFilter { public: BpFilter(bool discardKineKine, bool discardStaticKine); ~BpFilter(); PX_FORCE_INLINE const bool* getLUT() const { return &mLUT[0][0]; } bool mLUT[Bp::FilterType::COUNT][Bp::FilterType::COUNT]; }; } } #endif
4,338
C
31.871212
137
0.729599
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpAABBManagerTasks.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 BP_AABB_MANAGER_TASKS_H #define BP_AABB_MANAGER_TASKS_H #include "foundation/PxUserAllocated.h" #include "CmTask.h" namespace physx { class PxcScratchAllocator; namespace Bp { class AABBManager; class Aggregate; class AggregateBoundsComputationTask : public Cm::Task, public PxUserAllocated { public: AggregateBoundsComputationTask(PxU64 contextId) : Cm::Task (contextId), mManager (NULL), mStart (0), mNbToGo (0), mAggregates (NULL) {} ~AggregateBoundsComputationTask() {} virtual const char* getName() const { return "AggregateBoundsComputationTask"; } virtual void runInternal(); void Init(AABBManager* manager, PxU32 start, PxU32 nb, Aggregate** aggregates) { mManager = manager; mStart = start; mNbToGo = nb; mAggregates = aggregates; } private: AABBManager* mManager; PxU32 mStart; PxU32 mNbToGo; Aggregate** mAggregates; AggregateBoundsComputationTask& operator=(const AggregateBoundsComputationTask&); }; class PreBpUpdateTask : public Cm::Task, public PxUserAllocated { public: PreBpUpdateTask(PxU64 contextId) : Cm::Task(contextId), mManager(NULL), mNumCpuTasks(0) {} ~PreBpUpdateTask() {} virtual const char* getName() const { return "PreBpUpdateTask"; } virtual void runInternal(); void Init(AABBManager* manager, PxU32 numCpuTasks) { mManager = manager; mNumCpuTasks = numCpuTasks; } private: AABBManager * mManager; PxU32 mNumCpuTasks; PreBpUpdateTask& operator=(const PreBpUpdateTask&); }; } } //namespace physx #endif // BP_AABB_MANAGER_TASKS_H
3,449
C
32.495145
86
0.709191
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpBroadPhase.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 BP_BROADPHASE_H #define BP_BROADPHASE_H #include "foundation/PxUserAllocated.h" #include "PxBroadPhase.h" #include "BpBroadPhaseUpdate.h" namespace physx { class PxcScratchAllocator; class PxBaseTask; namespace Bp { class BroadPhaseUpdateData; /** \brief Base broad phase class. Functions only relevant to MBP. */ class BroadPhaseBase : public PxBroadPhaseRegions, public PxUserAllocated { public: BroadPhaseBase() {} virtual ~BroadPhaseBase() {} /** \brief Gets broad-phase caps. \param caps [out] Broad-phase caps */ virtual void getCaps(PxBroadPhaseCaps& caps) const { caps.mMaxNbRegions = 0; } // PxBroadPhaseRegions virtual PxU32 getNbRegions() const PX_OVERRIDE { return 0; } virtual PxU32 getRegions(PxBroadPhaseRegionInfo*, PxU32, PxU32) const PX_OVERRIDE { return 0; } virtual PxU32 addRegion(const PxBroadPhaseRegion&, bool, const PxBounds3*, const PxReal*) PX_OVERRIDE { return 0xffffffff;} virtual bool removeRegion(PxU32) PX_OVERRIDE { return false; } virtual PxU32 getNbOutOfBoundsObjects() const PX_OVERRIDE { return 0; } virtual const PxU32* getOutOfBoundsObjects() const PX_OVERRIDE { return NULL; } //~PxBroadPhaseRegions }; /* \brief Structure used to report created and deleted broadphase pairs \note The indices mVolA and mVolB correspond to the bounds indices BroadPhaseUpdateData::mCreated used by BroadPhase::update @see BroadPhase::getCreatedPairs, BroadPhase::getDeletedPairs */ struct BroadPhasePair { BroadPhasePair(ShapeHandle volA, ShapeHandle volB) : mVolA (PxMin(volA, volB)), mVolB (PxMax(volA, volB)) { } BroadPhasePair() : mVolA (BP_INVALID_BP_HANDLE), mVolB (BP_INVALID_BP_HANDLE) { } ShapeHandle mVolA; // NB: mVolA < mVolB ShapeHandle mVolB; }; class BroadPhase : public BroadPhaseBase { public: /** \brief Instantiate a BroadPhase instance. \param[in] bpType - the bp type (either mbp or sap). This is typically specified in PxSceneDesc. \param[in] maxNbRegions is the expected maximum number of broad-phase regions. \param[in] maxNbBroadPhaseOverlaps is the expected maximum number of broad-phase overlaps. \param[in] maxNbStaticShapes is the expected maximum number of static shapes. \param[in] maxNbDynamicShapes is the expected maximum number of dynamic shapes. \param[in] contextID is the context ID parameter sent to the profiler \return The instantiated BroadPhase. \note maxNbRegions is only used if mbp is the chosen broadphase (PxBroadPhaseType::eMBP) \note maxNbRegions, maxNbBroadPhaseOverlaps, maxNbStaticShapes and maxNbDynamicShapes are typically specified in PxSceneLimits */ static BroadPhase* create( const PxBroadPhaseType::Enum bpType, const PxU32 maxNbRegions, const PxU32 maxNbBroadPhaseOverlaps, const PxU32 maxNbStaticShapes, const PxU32 maxNbDynamicShapes, PxU64 contextID); virtual PxBroadPhaseType::Enum getType() const = 0; /** \brief Shutdown of the broadphase. */ virtual void release() = 0; /** \brief Updates the broadphase and computes the lists of created/deleted pairs. \param[in] scratchAllocator - a PxcScratchAllocator instance used for temporary memory allocations. This must be non-null. \param[in] updateData a description of changes to the collection of aabbs since the last broadphase update. The changes detail the indices of the bounds that have been added/updated/removed as well as an array of all bound coordinates and an array of group ids used to filter pairs with the same id. @see BroadPhaseUpdateData \param[in] continuation the task that is in the queue to be executed immediately after the broadphase has completed its update. NULL is not supported. \note In PX_CHECKED and PX_DEBUG build configurations illegal input data (that does not conform to the BroadPhaseUpdateData specifications) triggers a special code-path that entirely bypasses the broadphase and issues a warning message to the error stream. No guarantees can be made about the correctness/consistency of broadphase behavior with illegal input data in PX_RELEASE and PX_PROFILE configs because validity checks are not active in these builds. */ virtual void update(PxcScratchAllocator* scratchAllocator, const BroadPhaseUpdateData& updateData, physx::PxBaseTask* continuation) = 0; /** \brief prepare broad phase data. */ virtual void preBroadPhase(const Bp::BroadPhaseUpdateData& updateData) = 0; /** \brief Fetch the results of any asynchronous broad phase work. */ virtual void fetchBroadPhaseResults() = 0; /* \brief Get created pairs. Note that each overlap pair is reported only on the frame when the overlap first occurs. The overlap persists until the pair appears in the list of deleted pairs or either of the bounds in the pair is removed from the broadphase. A created overlap must involve at least one of the bounds of the overlap pair appearing in either the created or updated list. It is impossible for the same pair to appear simultaneously in the list of created and deleted overlap pairs. An overlap is defined as a pair of bounds that overlap on all three axes; that is when maxA > minB and maxB > minA for all three axes. \param nbCreatedPairs [out] The number of created aabb overlap pairs computed in the execution of update() that has just completed. \return The array of created aabb overlap pairs computed in the execution of update() that has just completed. */ virtual const BroadPhasePair* getCreatedPairs(PxU32& nbCreatedPairs) const = 0; /** \brief Get deleted pairs. Note that a deleted pair can only be reported if that pair has already appeared in the list of created pairs in an earlier update. A lost overlap occurs when a pair of bounds previously overlapped on all three axes but have now separated on at least one axis. A lost overlap must involve at least one of the bounds of the lost overlap pair appearing in the updated list. Lost overlaps arising from removal of bounds from the broadphase do not appear in the list of deleted pairs. It is impossible for the same pair to appear simultaneously in the list of created and deleted pairs. \param nbDeletedPairs [out] The number of deleted overlap pairs computed in the execution of update() that has just completed. \return The array of deleted overlap pairs computed in the execution of update() that has just completed. */ virtual const BroadPhasePair* getDeletedPairs(PxU32& nbDeletedPairs) const = 0; /** \brief After the broadphase has completed its update() function and the created/deleted pairs have been queried with getCreatedPairs/getDeletedPairs it is desirable to free any memory that was temporarily acquired for the update but is is no longer required post-update. This can be achieved with the function freeBuffers(). */ virtual void freeBuffers() = 0; /** \brief Adjust internal structures after all bounds have been adjusted due to a scene origin shift. */ virtual void shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances) = 0; #if PX_CHECKED /** \brief Test that the created/updated/removed lists obey the rules that 1. object ids can only feature in the created list if they have never been previously added or if they were previously removed. 2. object ids can only be added to the updated list if they have been previously added without being removed. 3. objects ids can only be added to the removed list if they have been previously added without being removed. */ virtual bool isValid(const BroadPhaseUpdateData& updateData) const = 0; #endif }; } //namespace Bp } //namespace physx #endif //BP_BROADPHASE_H
9,389
C
42.674418
151
0.768985
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpAABBManagerBase.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 BP_AABBMANAGER_BASE_H #define BP_AABBMANAGER_BASE_H #include "foundation/PxPinnedArray.h" #include "foundation/PxBitMap.h" #include "foundation/PxSList.h" #include "foundation/PxBitUtils.h" #include "BpVolumeData.h" #include "BpBroadPhaseUpdate.h" #include "GuBounds.h" #include "PxFiltering.h" #include "PxAggregate.h" namespace physx { class PxcScratchAllocator; class PxRenderOutput; class PxBaseTask; namespace Cm { class FlushPool; } namespace Bp { typedef PxU32 BoundsIndex; //typedef PxU32 ActorHandle; /** \brief Changes to the configuration of overlap pairs are reported as void* pairs. \note Each void* in the pair corresponds to the void* passed to AABBManager::createVolume. @see AABBManager::createVolume, AABBManager::getCreatedOverlaps, AABBManager::getDestroyedOverlaps */ struct AABBOverlap { PX_FORCE_INLINE AABBOverlap() {} PX_FORCE_INLINE AABBOverlap(void* userData0, void* userData1/*, ActorHandle pairHandle*/) : mUserData0(userData0), mUserData1(userData1)/*, mPairHandle(pairHandle)*/ { // PT: TODO: why is this forbidden? PX_ASSERT(userData0 != userData1); } // PT: these will eventually be the userData pointers passed to addBounds(), i.e. Sc::ElementSim pointers in PhysX. This may not be // necessary at all, since in the current design the bounds indices themselves come from BP clients (they're not handles managed by the BP). // So there's a 1:1 mapping between bounds-indices (which are effectively edlement IDs in PhysX) and the userData pointers (Sc::ElementSim). // Thus we could just return bounds indices directly to users - at least in the context of PhysX, maybe the standalone BP is different. void* mUserData0; void* mUserData1; // PT: TODO: not sure what happened there but mPairUserData is not used inside the BP itself so we need to revisit this. /* union { ActorHandle mPairHandle; //For created pairs, this is the index into the pair in the pair manager void* mUserData; //For deleted pairs, this is the user data written by the application to the pair };*/ void* mPairUserData; //For deleted pairs, this is the user data written by the application to the pair }; struct BpCacheData : public PxSListEntry { PxArray<AABBOverlap> mCreatedPairs[2]; PxArray<AABBOverlap> mDeletedPairs[2]; void reset() { mCreatedPairs[0].resizeUninitialized(0); mCreatedPairs[1].resizeUninitialized(0); mDeletedPairs[0].resizeUninitialized(0); mDeletedPairs[1].resizeUninitialized(0); } }; typedef PxPinnedArray<Bp::FilterGroup::Enum> GroupsArrayPinned; typedef PxPinnedArray<VolumeData> VolumeDataArrayPinned; typedef PxPinnedArray<ShapeHandle> ShapeHandleArrayPinned; class BoundsArray : public PxUserAllocated { PX_NOCOPY(BoundsArray) public: BoundsArray(PxVirtualAllocator& allocator) : mBounds(allocator) {} PX_FORCE_INLINE void initEntry(PxU32 index) { index++; // PT: always pretend we need one more entry, to make sure reading the last used entry will be SIMD-safe. const PxU32 oldCapacity = mBounds.capacity(); if (index >= oldCapacity) { const PxU32 newCapacity = PxNextPowerOfTwo(index); mBounds.reserve(newCapacity); mBounds.forceSize_Unsafe(newCapacity); } } PX_FORCE_INLINE void updateBounds(const PxTransform& transform, const PxGeometry& geom, PxU32 index) { Gu::computeBounds(mBounds[index], geom, transform, 0.0f, 1.0f); mHasAnythingChanged = true; } PX_FORCE_INLINE void setBounds(const PxBounds3& bounds, PxU32 index) { // PX_CHECK_AND_RETURN(bounds.isValid() && !bounds.isEmpty(), "BoundsArray::setBounds - illegal bounds\n"); mBounds[index] = bounds; mHasAnythingChanged = true; } PX_FORCE_INLINE const PxBounds3* begin() const { return mBounds.begin(); } PX_FORCE_INLINE PxBounds3* begin() { return mBounds.begin(); } PX_FORCE_INLINE PxBoundsArrayPinned& getBounds() { return mBounds; } PX_FORCE_INLINE const PxBounds3& getBounds(PxU32 index) const { return mBounds[index]; } PX_FORCE_INLINE PxU32 getCapacity() const { return mBounds.size(); } PX_FORCE_INLINE bool hasChanged() const { return mHasAnythingChanged; } PX_FORCE_INLINE void resetChangedState() { mHasAnythingChanged = false; } PX_FORCE_INLINE void setChangedState() { mHasAnythingChanged = true; } void shiftOrigin(const PxVec3& shift) { // we shift some potential NaNs here because we don't know what's active, but should be harmless const PxU32 nbBounds = mBounds.size(); for(PxU32 i=0; i<nbBounds; i++) { mBounds[i].minimum -= shift; mBounds[i].maximum -= shift; } mHasAnythingChanged = true; } private: PxBoundsArrayPinned mBounds; bool mHasAnythingChanged; }; /** \brief A structure responsible for: * storing an aabb representation for each active shape in the related scene * managing the creation/removal of aabb representations when their related shapes are created/removed * updating all aabbs that require an update due to modification of shape geometry or transform * updating the aabb of all aggregates from the union of the aabbs of all shapes that make up each aggregate * computing and reporting the incremental changes to the set of overlapping aabb pairs */ class AABBManagerBase : public PxUserAllocated { PX_NOCOPY(AABBManagerBase) public: AABBManagerBase(BroadPhase& bp, BoundsArray& boundsArray, PxFloatArrayPinned& contactDistance, PxU32 maxNbAggregates, PxU32 maxNbShapes, PxVirtualAllocator& allocator, PxU64 contextID, PxPairFilteringMode::Enum kineKineFilteringMode, PxPairFilteringMode::Enum staticKineFilteringMode); virtual ~AABBManagerBase() {} virtual void destroy() = 0; virtual AggregateHandle createAggregate(BoundsIndex index, Bp::FilterGroup::Enum group, void* userData, PxU32 maxNumShapes, PxAggregateFilterHint filterHint) = 0; virtual bool destroyAggregate(BoundsIndex& index, Bp::FilterGroup::Enum& group, AggregateHandle aggregateHandle) = 0; virtual bool addBounds(BoundsIndex index, PxReal contactDistance, Bp::FilterGroup::Enum group, void* userdata, AggregateHandle aggregateHandle, ElementType::Enum volumeType) = 0; virtual bool removeBounds(BoundsIndex index) = 0; void reserveSpaceForBounds(BoundsIndex index); PX_FORCE_INLINE PxIntBool isMarkedForRemove(BoundsIndex index) const { return mRemovedHandleMap.boundedTest(index); } // PX_FORCE_INLINE PxIntBool isMarkedForAdd(BoundsIndex index) const { return mAddedHandleMap.boundedTest(index); } PX_FORCE_INLINE BroadPhase* getBroadPhase() const { return &mBroadPhase; } PX_FORCE_INLINE BoundsArray& getBoundsArray() { return mBoundsArray; } PX_FORCE_INLINE PxU32 getNbActiveAggregates() const { return mNbAggregates; } PX_FORCE_INLINE const float* getContactDistances() const { return mContactDistance.begin(); } PX_FORCE_INLINE PxBitMapPinned& getChangedAABBMgActorHandleMap() { return mChangedHandleMap; } PX_FORCE_INLINE void* getUserData(const BoundsIndex index) const { return (index<mVolumeData.size()) ? mVolumeData[index].getUserData() : NULL; } void setContactDistance(BoundsIndex handle, PxReal offset) { // PT: this works even for aggregated shapes, since the corresponding bit will also be set in the 'updated' map. mContactDistance.begin()[handle] = offset; setPersistentStateChanged(); mChangedHandleMap.growAndSet(handle); } void setBPGroup(BoundsIndex index, Bp::FilterGroup::Enum group) { PX_ASSERT((index + 1) < mVolumeData.size()); PX_ASSERT(group != Bp::FilterGroup::eINVALID); // PT: we use group == Bp::FilterGroup::eINVALID to mark removed/invalid entries mGroups[index] = group; } virtual void updateBPFirstPass(PxU32 numCpuTasks, Cm::FlushPool& flushPool, bool hasContactDistanceUpdated, PxBaseTask* continuation) = 0; virtual void updateBPSecondPass(PxcScratchAllocator* scratchAllocator, PxBaseTask* continuation) = 0; virtual void postBroadPhase(PxBaseTask*, Cm::FlushPool& flushPool) = 0; virtual void reallocateChangedAABBMgActorHandleMap(const PxU32 size) = 0; AABBOverlap* getCreatedOverlaps(ElementType::Enum type, PxU32& count) { PX_ASSERT(type < ElementType::eCOUNT); count = mCreatedOverlaps[type].size(); return mCreatedOverlaps[type].begin(); } AABBOverlap* getDestroyedOverlaps(ElementType::Enum type, PxU32& count) { PX_ASSERT(type < ElementType::eCOUNT); count = mDestroyedOverlaps[type].size(); return mDestroyedOverlaps[type].begin(); } void freeBuffers(); struct OutOfBoundsData { PxU32 mNbOutOfBoundsObjects; PxU32 mNbOutOfBoundsAggregates; void** mOutOfBoundsObjects; void** mOutOfBoundsAggregates; }; virtual bool getOutOfBoundsObjects(OutOfBoundsData&) { return false; } virtual void clearOutOfBoundsObjects() {} void shiftOrigin(const PxVec3& shift); virtual void visualize(PxRenderOutput& out) = 0; virtual void releaseDeferredAggregateIds() = 0; virtual void setGPUStateChanged() {} virtual void setPersistentStateChanged() {} protected: void reserveShapeSpace(PxU32 nbShapes); // PT: we have bitmaps here probably to quickly handle added/removed objects during same frame. // PT: TODO: consider replacing with plain arrays (easier to parse, already existing below, etc) PxBitMapPinned mAddedHandleMap; // PT: indexed by BoundsIndex PxBitMapPinned mRemovedHandleMap; // PT: indexed by BoundsIndex PxBitMapPinned mChangedHandleMap; //Returns true if the bounds was pending insert, false otherwise PX_FORCE_INLINE bool removeBPEntry(BoundsIndex index) // PT: only for objects passed to the BP { if (mAddedHandleMap.test(index)) // PT: if object had been added this frame... { mAddedHandleMap.reset(index); // PT: ...then simply revert the previous operation locally (it hasn't been passed to the BP yet). return true; } else mRemovedHandleMap.set(index); // PT: else we need to remove it from the BP return false; } PX_FORCE_INLINE void addBPEntry(BoundsIndex index) { if (mRemovedHandleMap.test(index)) mRemovedHandleMap.reset(index); else mAddedHandleMap.set(index); } //ML: we create mGroups and mContactDistance in the AABBManager constructor. PxArray will take PxVirtualAllocator as a parameter. Therefore, if GPU BP is using, //we will passed a pinned host memory allocator, otherwise, we will just pass a normal allocator. GroupsArrayPinned mGroups; // NOTE: we stick Bp::FilterGroup::eINVALID in this slot to indicate that the entry is invalid (removed or never inserted.) PxFloatArrayPinned& mContactDistance; VolumeDataArrayPinned mVolumeData; BpFilter mFilters; PX_FORCE_INLINE void initEntry(BoundsIndex index, PxReal contactDistance, Bp::FilterGroup::Enum group, void* userData) { if ((index + 1) >= mVolumeData.size()) reserveShapeSpace(index + 1); // PT: TODO: why is this needed at all? Why aren't size() and capacity() enough? mUsedSize = PxMax(index + 1, mUsedSize); PX_ASSERT(group != Bp::FilterGroup::eINVALID); // PT: we use group == Bp::FilterGroup::eINVALID to mark removed/invalid entries mGroups[index] = group; mContactDistance.begin()[index] = contactDistance; mVolumeData[index].setUserData(userData); } PX_FORCE_INLINE void initEntry(BoundsIndex index, PxReal contactDistance, Bp::FilterGroup::Enum group, void* userData, ElementType::Enum volumeType) { initEntry(index, contactDistance, group, userData); mVolumeData[index].setVolumeType(volumeType); // PT: must be done after setUserData } PX_FORCE_INLINE void resetEntry(BoundsIndex index) { mGroups[index] = Bp::FilterGroup::eINVALID; mContactDistance.begin()[index] = 0.0f; mVolumeData[index].reset(); } // PT: TODO: remove confusion between BoundsIndex and ShapeHandle here! ShapeHandleArrayPinned mAddedHandles; ShapeHandleArrayPinned mUpdatedHandles; // PT: TODO: only on CPU ShapeHandleArrayPinned mRemovedHandles; BroadPhase& mBroadPhase; BoundsArray& mBoundsArray; PxArray<AABBOverlap> mCreatedOverlaps[ElementType::eCOUNT]; PxArray<AABBOverlap> mDestroyedOverlaps[ElementType::eCOUNT]; PxU32 mUsedSize; // highest used value + 1 PxU32 mNbAggregates; #ifdef BP_USE_AGGREGATE_GROUP_TAIL // PT: TODO: even in the 3.4 trunk this stuff is a clumsy mess: groups are "BpHandle" suddenly passed // to BroadPhaseUpdateData as "ShapeHandle". //Free aggregate group ids. PxU32 mAggregateGroupTide; PxArray<Bp::FilterGroup::Enum> mFreeAggregateGroups; // PT: TODO: remove this useless array #endif PxU64 mContextID; bool mOriginShifted; #ifdef BP_USE_AGGREGATE_GROUP_TAIL PX_FORCE_INLINE void releaseAggregateGroup(const Bp::FilterGroup::Enum group) { PX_ASSERT(group != Bp::FilterGroup::eINVALID); mFreeAggregateGroups.pushBack(group); } PX_FORCE_INLINE Bp::FilterGroup::Enum getAggregateGroup() { PxU32 id; if (mFreeAggregateGroups.size()) id = mFreeAggregateGroups.popBack(); else { id = mAggregateGroupTide--; id <<= BP_FILTERING_TYPE_SHIFT_BIT; id |= FilterType::AGGREGATE; } const Bp::FilterGroup::Enum group = Bp::FilterGroup::Enum(id); PX_ASSERT(group != Bp::FilterGroup::eINVALID); return group; } #endif }; } //namespace Bp } //namespace physx #endif //BP_AABBMANAGER_BASE_H
16,588
C
43.714286
186
0.67796
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpAABBManager.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 BP_AABBMANAGER_H #define BP_AABBMANAGER_H #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "BpAABBManagerTasks.h" #include "BpAABBManagerBase.h" namespace physx { namespace Cm { class FlushPool; } namespace Bp { struct BroadPhasePair; class Aggregate; class PersistentPairs; class PersistentActorAggregatePair; class PersistentAggregateAggregatePair; class PersistentSelfCollisionPairs; struct AggPair { PX_FORCE_INLINE AggPair() {} PX_FORCE_INLINE AggPair(ShapeHandle index0, ShapeHandle index1) : mIndex0(index0), mIndex1(index1) {} ShapeHandle mIndex0; ShapeHandle mIndex1; PX_FORCE_INLINE bool operator==(const AggPair& p) const { return (p.mIndex0 == mIndex0) && (p.mIndex1 == mIndex1); } }; typedef PxCoalescedHashMap<AggPair, PersistentPairs*> AggPairMap; // PT: TODO: isn't there a generic pair structure somewhere? refactor with AggPair anyway struct Pair { PX_FORCE_INLINE Pair(PxU32 id0, PxU32 id1) : mID0(id0), mID1(id1) {} PX_FORCE_INLINE Pair(){} PX_FORCE_INLINE bool operator<(const Pair& p) const { const PxU64 value0 = *reinterpret_cast<const PxU64*>(this); const PxU64 value1 = *reinterpret_cast<const PxU64*>(&p); return value0 < value1; } PX_FORCE_INLINE bool operator==(const Pair& p) const { return (p.mID0 == mID0) && (p.mID1 == mID1); } PX_FORCE_INLINE bool operator!=(const Pair& p) const { return (p.mID0 != mID0) || (p.mID1 != mID1); } PxU32 mID0; PxU32 mID1; }; class AABBManager; class PostBroadPhaseStage2Task : public Cm::Task { Cm::FlushPool* mFlushPool; AABBManager& mManager; PX_NOCOPY(PostBroadPhaseStage2Task) public: PostBroadPhaseStage2Task(PxU64 contextID, AABBManager& manager) : Cm::Task(contextID), mFlushPool(NULL), mManager(manager) { } virtual const char* getName() const { return "PostBroadPhaseStage2Task"; } void setFlushPool(Cm::FlushPool* pool) { mFlushPool = pool; } virtual void runInternal(); }; class ProcessAggPairsBase; /** \brief A structure responsible for: * storing an aabb representation for each active shape in the related scene * managing the creation/removal of aabb representations when their related shapes are created/removed * updating all aabbs that require an update due to modification of shape geometry or transform * updating the aabb of all aggregates from the union of the aabbs of all shapes that make up each aggregate * computing and reporting the incremental changes to the set of overlapping aabb pairs */ class AABBManager : public AABBManagerBase { PX_NOCOPY(AABBManager) public: AABBManager(BroadPhase& bp, BoundsArray& boundsArray, PxFloatArrayPinned& contactDistance, PxU32 maxNbAggregates, PxU32 maxNbShapes, PxVirtualAllocator& allocator, PxU64 contextID, PxPairFilteringMode::Enum kineKineFilteringMode, PxPairFilteringMode::Enum staticKineFilteringMode); virtual ~AABBManager() {} // AABBManagerBase virtual void destroy() PX_OVERRIDE; virtual AggregateHandle createAggregate(BoundsIndex index, Bp::FilterGroup::Enum group, void* userData, PxU32 maxNumShapes, PxAggregateFilterHint filterHint) PX_OVERRIDE; virtual bool destroyAggregate(BoundsIndex& index, Bp::FilterGroup::Enum& group, AggregateHandle aggregateHandle) PX_OVERRIDE; virtual bool addBounds(BoundsIndex index, PxReal contactDistance, Bp::FilterGroup::Enum group, void* userdata, AggregateHandle aggregateHandle, ElementType::Enum volumeType) PX_OVERRIDE; virtual bool removeBounds(BoundsIndex index) PX_OVERRIDE; virtual void updateBPFirstPass(PxU32 numCpuTasks, Cm::FlushPool& flushPool, bool hasContactDistanceUpdated, PxBaseTask* continuation) PX_OVERRIDE; virtual void updateBPSecondPass(PxcScratchAllocator* scratchAllocator, PxBaseTask* continuation) PX_OVERRIDE; virtual void postBroadPhase(PxBaseTask*, Cm::FlushPool& flushPool) PX_OVERRIDE; virtual void reallocateChangedAABBMgActorHandleMap(const PxU32 size) PX_OVERRIDE; virtual bool getOutOfBoundsObjects(OutOfBoundsData& data) PX_OVERRIDE; virtual void clearOutOfBoundsObjects() PX_OVERRIDE; virtual void visualize(PxRenderOutput& out) PX_OVERRIDE; virtual void releaseDeferredAggregateIds() PX_OVERRIDE{} //~AABBManagerBase void preBpUpdate_CPU(PxU32 numCpuTasks); // PT: TODO: what is that BpCacheData for? BpCacheData* getBpCacheData(); void putBpCacheData(BpCacheData*); void resetBpCacheData(); PxMutex mMapLock; private: //void reserveShapeSpace(PxU32 nbShapes); void postBpStage2(PxBaseTask*, Cm::FlushPool&); void postBpStage3(PxBaseTask*); PostBroadPhaseStage2Task mPostBroadPhase2; Cm::DelegateTask<AABBManager, &AABBManager::postBpStage3> mPostBroadPhase3; PreBpUpdateTask mPreBpUpdateTask; PxU32 mTimestamp; PxU32 mFirstFreeAggregate; PxArray<Aggregate*> mAggregates; // PT: indexed by AggregateHandle PxArray<Aggregate*> mDirtyAggregates; AggPairMap mActorAggregatePairs; AggPairMap mAggregateAggregatePairs; PxArray<ProcessAggPairsBase*> mAggPairTasks; PxHashSet<Pair> mCreatedPairsTmp; // PT: temp hashset for dubious post filtering, persistent to minimize allocs PxSList mBpThreadContextPool; PxArray<void*> mOutOfBoundsObjects; PxArray<void*> mOutOfBoundsAggregates; PX_FORCE_INLINE Aggregate* getAggregateFromHandle(AggregateHandle handle) { PX_ASSERT(handle<mAggregates.size()); return mAggregates[handle]; } void startAggregateBoundsComputationTasks(PxU32 nbToGo, PxU32 numCpuTasks, Cm::FlushPool& flushPool); PersistentActorAggregatePair* createPersistentActorAggregatePair(ShapeHandle volA, ShapeHandle volB); PersistentAggregateAggregatePair* createPersistentAggregateAggregatePair(ShapeHandle volA, ShapeHandle volB); void updatePairs(PersistentPairs& p, BpCacheData* data = NULL); void handleOriginShift(); public: void processBPCreatedPair(const BroadPhasePair& pair); void processBPDeletedPair(const BroadPhasePair& pair); friend class PersistentActorAggregatePair; friend class PersistentAggregateAggregatePair; friend class ProcessSelfCollisionPairsParallel; friend class PostBroadPhaseStage2Task; }; } //namespace Bp } //namespace physx #endif //BP_AABBMANAGER_H
8,406
C
38.285047
196
0.730193
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpBroadPhaseUpdate.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 BP_BROADPHASE_UPDATE_H #define BP_BROADPHASE_UPDATE_H #include "BpFiltering.h" #include "foundation/PxBounds3.h" #include "foundation/PxUnionCast.h" namespace physx { namespace Bp { typedef PxU32 ShapeHandle; typedef PxU32 BpHandle; #define BP_INVALID_BP_HANDLE 0x3fffffff class BroadPhase; class BroadPhaseUpdateData { public: /** \brief A structure detailing the changes to the collection of aabbs, whose overlaps are computed in the broadphase. The structure consists of per-object arrays of object bounds and object groups, and three arrays that index into the per-object arrays, denoting the bounds which are to be created, updated and removed in the broad phase. * each entry in the object arrays represents the same shape or aggregate from frame to frame. * each entry in an index array must be less than the capacity of the per-object arrays. * no index value may appear in more than one index array, and may not occur more than once in that array. An index value is said to be "in use" if it has appeared in a created list in a previous update, and has not since occurred in a removed list. \param[in] created an array of indices describing the bounds that must be inserted into the broadphase. Each index in the array must not be in use. \param[in] updated an array of indices (referencing the boxBounds and boxGroups arrays) describing the bounds that have moved since the last broadphase update. Each index in the array must be in use, and each object whose index is in use and whose AABB has changed must appear in the update list. \param[in] removed an array of indices describing the bounds that must be removed from the broad phase. Each index in the array must be in use. \param[in] boxBounds an array of bounds coordinates for the AABBs to be processed by the broadphase. An entry is valid if its values are integer bitwise representations of floating point numbers that satisfy max>min in each dimension, along with a further rule that minima(maxima) must have even(odd) values. Each entry whose index is either in use or appears in the created array must be valid. An entry whose index is either not in use or appears in the removed array need not be valid. \param[in] boxGroups an array of group ids, one for each bound, used for pair filtering. Bounds with the same group id will not be reported as overlap pairs by the broad phase. Zero is reserved for static bounds. Entries in this array are immutable: the only way to change the group of an object is to remove it from the broad phase and reinsert it at a different index (recall that each index must appear at most once in the created/updated/removed lists). \param[in] boxesCapacity the length of the boxBounds and boxGroups arrays. @see BroadPhase::update */ BroadPhaseUpdateData( const ShapeHandle* created, PxU32 createdSize, const ShapeHandle* updated, PxU32 updatedSize, const ShapeHandle* removed, PxU32 removedSize, const PxBounds3* boxBounds, const Bp::FilterGroup::Enum* boxGroups, const PxReal* boxContactDistances, PxU32 boxesCapacity, const BpFilter& filter, bool stateChanged, bool gpuStateChanged ) : mCreated (created), mCreatedSize (createdSize), mUpdated (updated), mUpdatedSize (updatedSize), mRemoved (removed), mRemovedSize (removedSize), mBoxBounds (boxBounds), mBoxGroups (boxGroups), mBoxDistances (boxContactDistances), mBoxesCapacity (boxesCapacity), mFilter (filter), mStateChanged (stateChanged), mGpuStateChanged(gpuStateChanged) { } BroadPhaseUpdateData(const BroadPhaseUpdateData& other) : mCreated (other.mCreated), mCreatedSize (other.mCreatedSize), mUpdated (other.mUpdated), mUpdatedSize (other.mUpdatedSize), mRemoved (other.mRemoved), mRemovedSize (other.mRemovedSize), mBoxBounds (other.mBoxBounds), mBoxGroups (other.mBoxGroups), mBoxDistances (other.mBoxDistances), mBoxesCapacity (other.mBoxesCapacity), mFilter (other.mFilter), mStateChanged (other.mStateChanged), mGpuStateChanged(other.mGpuStateChanged) { } BroadPhaseUpdateData& operator=(const BroadPhaseUpdateData& other); PX_FORCE_INLINE const ShapeHandle* getCreatedHandles() const { return mCreated; } PX_FORCE_INLINE PxU32 getNumCreatedHandles() const { return mCreatedSize; } PX_FORCE_INLINE const ShapeHandle* getUpdatedHandles() const { return mUpdated; } PX_FORCE_INLINE PxU32 getNumUpdatedHandles() const { return mUpdatedSize; } PX_FORCE_INLINE const ShapeHandle* getRemovedHandles() const { return mRemoved; } PX_FORCE_INLINE PxU32 getNumRemovedHandles() const { return mRemovedSize; } PX_FORCE_INLINE const PxBounds3* getAABBs() const { return mBoxBounds; } PX_FORCE_INLINE const Bp::FilterGroup::Enum* getGroups() const { return mBoxGroups; } PX_FORCE_INLINE const PxReal* getContactDistance() const { return mBoxDistances; } PX_FORCE_INLINE PxU32 getCapacity() const { return mBoxesCapacity; } PX_FORCE_INLINE const BpFilter& getFilter() const { return mFilter; } PX_FORCE_INLINE bool getStateChanged() const { return mStateChanged; } PX_FORCE_INLINE bool getGpuStateChanged() const { return mGpuStateChanged; } #if PX_CHECKED static bool isValid(const BroadPhaseUpdateData& updateData, const BroadPhase& bp, const bool skipBoundValidation, PxU64 contextID); bool isValid(const bool skipBoundValidation) const; #endif private: const ShapeHandle* mCreated; const PxU32 mCreatedSize; const ShapeHandle* mUpdated; const PxU32 mUpdatedSize; const ShapeHandle* mRemoved; const PxU32 mRemovedSize; const PxBounds3* mBoxBounds; const Bp::FilterGroup::Enum* mBoxGroups; const PxReal* mBoxDistances; const PxU32 mBoxesCapacity; const BpFilter& mFilter; const bool mStateChanged; const bool mGpuStateChanged; }; } //namespace Bp } //namespace physx #endif
7,699
C
40.621621
135
0.756072
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/include/BpVolumeData.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 BP_VOLUME_DATA_H #define BP_VOLUME_DATA_H #include "PxvConfig.h" #include "foundation/PxAssert.h" namespace physx { namespace Bp { typedef PxU32 AggregateHandle; // PT: currently an index in mAggregates array struct ElementType { enum Enum { eSHAPE = 0, eTRIGGER, eCOUNT }; }; PX_COMPILE_TIME_ASSERT(ElementType::eCOUNT <= 4); // 2 bits reserved for type #define PX_CUDA_INLINE PX_CUDA_CALLABLE PX_FORCE_INLINE struct VolumeData { PX_CUDA_INLINE void reset() { mAggregate = PX_INVALID_U32; mUserData = NULL; } PX_CUDA_INLINE void setSingleActor() { mAggregate = PX_INVALID_U32; } PX_CUDA_INLINE bool isSingleActor() const { return mAggregate == PX_INVALID_U32; } PX_CUDA_INLINE void setUserData(void* userData) { // PX_ASSERT(!(size_t(userData) & 3)); mUserData = userData; } PX_CUDA_INLINE void* getUserData() const { return reinterpret_cast<void*>(size_t(mUserData)& (~size_t(3))); } PX_CUDA_INLINE void setVolumeType(ElementType::Enum volumeType) { PX_ASSERT(volumeType < 2); mUserData = reinterpret_cast<void*>(size_t(getUserData()) | size_t(volumeType)); } PX_CUDA_INLINE ElementType::Enum getVolumeType() const { return ElementType::Enum(size_t(mUserData) & 3); } PX_CUDA_INLINE void setAggregate(AggregateHandle handle) { PX_ASSERT(handle != PX_INVALID_U32); mAggregate = (handle << 1) | 1; } PX_CUDA_INLINE bool isAggregate() const { return !isSingleActor() && ((mAggregate & 1) != 0); } PX_CUDA_INLINE void setAggregated(AggregateHandle handle) { PX_ASSERT(handle != PX_INVALID_U32); mAggregate = (handle << 1) | 0; } PX_CUDA_INLINE bool isAggregated() const { return !isSingleActor() && ((mAggregate & 1) == 0); } PX_CUDA_INLINE AggregateHandle getAggregateOwner() const { return mAggregate >> 1; } PX_CUDA_INLINE AggregateHandle getAggregate() const { return mAggregate >> 1; } private: void* mUserData; // PT: in PhysX this is an Sc::ElementSim ptr // PT: TODO: consider moving this to a separate array, which wouldn't be allocated at all for people not using aggregates. // PT: current encoding: // aggregate == PX_INVALID_U32 => single actor // aggregate != PX_INVALID_U32 => aggregate index<<1|LSB. LSB==1 for aggregates, LSB==0 for aggregated actors. AggregateHandle mAggregate; }; } } #endif
4,447
C
34.870967
125
0.656173
NVIDIA-Omniverse/PhysX/physx/source/foundation/FdAssert.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/PxAssert.h" #include "foundation/PxString.h" #include <stdio.h> #if PX_WINDOWS_FAMILY #include <crtdbg.h> #elif PX_SWITCH #include "foundation/switch/PxSwitchAbort.h" #endif void physx::PxAssert(const char* expr, const char* file, int line, bool& ignore) { PX_UNUSED(ignore); // is used only in debug windows config char buffer[1024]; #if PX_WINDOWS_FAMILY sprintf_s(buffer, "%s(%d) : Assertion failed: %s\n", file, line, expr); #else sprintf(buffer, "%s(%d) : Assertion failed: %s\n", file, line, expr); #endif physx::PxPrintString(buffer); #if PX_WINDOWS_FAMILY&& PX_DEBUG && PX_DEBUG_CRT // _CrtDbgReport returns -1 on error, 1 on 'retry', 0 otherwise including 'ignore'. // Hitting 'abort' will terminate the process immediately. int result = _CrtDbgReport(_CRT_ASSERT, file, line, NULL, "%s", buffer); int mode = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_REPORT_MODE); ignore = _CRTDBG_MODE_WNDW == mode && result == 0; if(ignore) return; __debugbreak(); #elif PX_WINDOWS_FAMILY&& PX_CHECKED __debugbreak(); #elif PX_SWITCH abort(buffer); #else abort(); #endif }
2,801
C++
41.454545
84
0.740807
NVIDIA-Omniverse/PhysX/physx/source/foundation/FdMathUtils.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/PxSIMDHelpers.h" #include "foundation/PxMathUtils.h" #include "foundation/PxVec4.h" #include "foundation/PxAssert.h" #include "foundation/PxBasicTemplates.h" #include "foundation/PxUtilities.h" #include "foundation/PxTransform.h" using namespace physx; using namespace physx::intrinsics; PX_FOUNDATION_API PxTransform physx::PxTransformFromPlaneEquation(const PxPlane& plane) { PxPlane p = plane; p.normalize(); // special case handling for axis aligned planes const PxReal halfsqrt2 = 0.707106781f; PxQuat q; if(2 == (p.n.x == 0.0f) + (p.n.y == 0.0f) + (p.n.z == 0.0f)) // special handling for axis aligned planes { if(p.n.x > 0) q = PxQuat(PxIdentity); else if(p.n.x < 0) q = PxQuat(0, 0, 1.0f, 0); else q = PxQuat(0.0f, -p.n.z, p.n.y, 1.0f) * halfsqrt2; } else q = PxShortestRotation(PxVec3(1.f,0,0), p.n); return PxTransform(-p.n * p.d, q); } PX_FOUNDATION_API PxTransform physx::PxTransformFromSegment(const PxVec3& p0, const PxVec3& p1, PxReal* halfHeight) { const PxVec3 axis = p1-p0; const PxReal height = axis.magnitude(); if(halfHeight) *halfHeight = height/2; return PxTransform((p1+p0) * 0.5f, height<1e-6f ? PxQuat(PxIdentity) : PxShortestRotation(PxVec3(1.f,0,0), axis/height)); } PX_FOUNDATION_API PxQuat physx::PxShortestRotation(const PxVec3& v0, const PxVec3& v1) { const PxReal d = v0.dot(v1); const PxVec3 cross = v0.cross(v1); const PxQuat q = d > -1 ? PxQuat(cross.x, cross.y, cross.z, 1 + d) : PxAbs(v0.x) < 0.1f ? PxQuat(0.0f, v0.z, -v0.y, 0.0f) : PxQuat(v0.y, -v0.x, 0.0f, 0.0f); return q.getNormalized(); } // indexed rotation around axis, with sine and cosine of half-angle static PxQuat indexedRotation(PxU32 axis, PxReal s, PxReal c) { PxReal v[3] = { 0, 0, 0 }; v[axis] = s; return PxQuat(v[0], v[1], v[2], c); } PX_FOUNDATION_API PxVec3 physx::PxDiagonalize(const PxMat33& m, PxQuat& massFrame) { // jacobi rotation using quaternions (from an idea of Stan Melax, with fix for precision issues) const PxU32 MAX_ITERS = 24; PxQuat q(PxIdentity); PxMat33 d; for(PxU32 i = 0; i < MAX_ITERS; i++) { // PT: removed for now, it makes one UT fail because the error is slightly above the threshold //const PxMat33Padded axes(q); const PxMat33 axes(q); d = axes.getTranspose() * m * axes; const PxReal d0 = PxAbs(d[1][2]), d1 = PxAbs(d[0][2]), d2 = PxAbs(d[0][1]); const PxU32 a = PxU32(d0 > d1 && d0 > d2 ? 0 : d1 > d2 ? 1 : 2); // rotation axis index, from largest off-diagonal // element const PxU32 a1 = PxGetNextIndex3(a), a2 = PxGetNextIndex3(a1); if(d[a1][a2] == 0.0f || PxAbs(d[a1][a1] - d[a2][a2]) > 2e6f * PxAbs(2.0f * d[a1][a2])) break; PxReal w = (d[a1][a1] - d[a2][a2]) / (2.0f * d[a1][a2]); // cot(2 * phi), where phi is the rotation angle PxReal absw = PxAbs(w); PxQuat r; if(absw > 1000) r = indexedRotation(a, 1 / (4 * w), 1.f); // h will be very close to 1, so use small angle approx instead else { const PxReal t = 1 / (absw + PxSqrt(w * w + 1)); // absolute value of tan phi const PxReal h = 1 / PxSqrt(t * t + 1); // absolute value of cos phi PX_ASSERT(h != 1); // |w|<1000 guarantees this with typical IEEE754 machine eps (approx 6e-8) r = indexedRotation(a, PxSqrt((1 - h) / 2) * PxSign(w), PxSqrt((1 + h) / 2)); } q = (q * r).getNormalized(); } massFrame = q; return PxVec3(d.column0.x, d.column1.y, d.column2.z); } /** \brief computes a oriented bounding box around the scaled basis. \param basis Input = skewed basis, Output = (normalized) orthogonal basis. \return Bounding box extent. */ PxVec3 physx::PxOptimizeBoundingBox(PxMat33& basis) { PxVec3* PX_RESTRICT vec = &basis[0]; // PT: don't copy vectors if not needed... // PT: since we store the magnitudes to memory, we can avoid the FCMPs afterwards PxVec3 magnitude(vec[0].magnitudeSquared(), vec[1].magnitudeSquared(), vec[2].magnitudeSquared()); // find indices sorted by magnitude unsigned int i = magnitude[1] > magnitude[0] ? 1 : 0u; unsigned int j = magnitude[2] > magnitude[1 - i] ? 2 : 1 - i; const unsigned int k = 3 - i - j; if(magnitude[i] < magnitude[j]) PxSwap(i, j); PX_ASSERT(magnitude[i] >= magnitude[j] && magnitude[i] >= magnitude[k] && magnitude[j] >= magnitude[k]); // ortho-normalize basis PxReal invSqrt = PxRecipSqrt(magnitude[i]); magnitude[i] *= invSqrt; vec[i] *= invSqrt; // normalize the first axis PxReal dotij = vec[i].dot(vec[j]); PxReal dotik = vec[i].dot(vec[k]); magnitude[i] += PxAbs(dotij) + PxAbs(dotik); // elongate the axis by projection of the other two vec[j] -= vec[i] * dotij; // orthogonize the two remaining axii relative to vec[i] vec[k] -= vec[i] * dotik; magnitude[j] = vec[j].normalize(); PxReal dotjk = vec[j].dot(vec[k]); magnitude[j] += PxAbs(dotjk); // elongate the axis by projection of the other one vec[k] -= vec[j] * dotjk; // orthogonize vec[k] relative to vec[j] magnitude[k] = vec[k].normalize(); return magnitude; } void physx::PxIntegrateTransform(const PxTransform& curTrans, const PxVec3& linvel, const PxVec3& angvel, PxReal timeStep, PxTransform& result) { result.p = curTrans.p + linvel * timeStep; // from void DynamicsContext::integrateAtomPose(PxsRigidBody* atom, Cm::BitMap &shapeChangedMap) const: // Integrate the rotation using closed form quaternion integrator PxReal w = angvel.magnitudeSquared(); if (w != 0.0f) { w = PxSqrt(w); if (w != 0.0f) { const PxReal v = timeStep * w * 0.5f; const PxReal q = PxCos(v); const PxReal s = PxSin(v) / w; const PxVec3 pqr = angvel * s; const PxQuat quatVel(pqr.x, pqr.y, pqr.z, 0); PxQuat out; // need to have temporary, otherwise we may overwrite input if &curTrans == &result. out = quatVel * curTrans.q; out.x += curTrans.q.x * q; out.y += curTrans.q.y * q; out.z += curTrans.q.z * q; out.w += curTrans.q.w * q; result.q = out; return; } } // orientation stays the same - convert from quat to matrix: result.q = curTrans.q; }
7,798
C++
35.962085
122
0.673891
NVIDIA-Omniverse/PhysX/physx/source/foundation/FdTempAllocator.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/PxMath.h" #include "foundation/PxIntrinsics.h" #include "foundation/PxBitUtils.h" #include "foundation/PxArray.h" #include "foundation/PxMutex.h" #include "foundation/PxAtomic.h" #include "foundation/PxTempAllocator.h" #include "FdFoundation.h" #if PX_VC #pragma warning(disable : 4706) // assignment within conditional expression #endif namespace physx { namespace { typedef PxTempAllocatorChunk Chunk; typedef PxArray<Chunk*, PxAllocator> AllocFreeTable; PX_INLINE Foundation::AllocFreeTable& getFreeTable() { return getFoundation().getTempAllocFreeTable(); } PX_INLINE Foundation::Mutex& getMutex() { return getFoundation().getTempAllocMutex(); } const PxU32 sMinIndex = 8; // 256B min const PxU32 sMaxIndex = 17; // 128kB max } void* PxTempAllocator::allocate(size_t size, const char* filename, PxI32 line) { if(!size) return 0; PxU32 index = PxMax(PxHighestSetBit(PxU32(size) + sizeof(Chunk) - 1), sMinIndex); Chunk* chunk = 0; if(index < sMaxIndex) { Foundation::Mutex::ScopedLock lock(getMutex()); // find chunk up to 16x bigger than necessary Chunk** it = getFreeTable().begin() + index - sMinIndex; Chunk** end = PxMin(it + 3, getFreeTable().end()); while(it < end && !(*it)) ++it; if(it < end) { // pop top off freelist chunk = *it; *it = chunk->mNext; index = PxU32(it - getFreeTable().begin() + sMinIndex); } else // create new chunk chunk = reinterpret_cast<Chunk*>(PxAllocator().allocate(size_t(2 << index), filename, line)); } else { // too big for temp allocation, forward to base allocator chunk = reinterpret_cast<Chunk*>(PxAllocator().allocate(size + sizeof(Chunk), filename, line)); } chunk->mIndex = index; void* ret = chunk + 1; PX_ASSERT((size_t(ret) & 0xf) == 0); // SDK types require at minimum 16 byte alignment. return ret; } void PxTempAllocator::deallocate(void* ptr) { if(!ptr) return; Chunk* chunk = reinterpret_cast<Chunk*>(ptr) - 1; PxU32 index = chunk->mIndex; if(index >= sMaxIndex) return PxAllocator().deallocate(chunk); Foundation::Mutex::ScopedLock lock(getMutex()); index -= sMinIndex; if(getFreeTable().size() <= index) getFreeTable().resize(index + 1); chunk->mNext = getFreeTable()[index]; getFreeTable()[index] = chunk; } } // namespace physx
3,997
C++
30.984
97
0.725794
NVIDIA-Omniverse/PhysX/physx/source/foundation/FdFoundation.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_FOUNDATION_PSFOUNDATION_H #define PX_FOUNDATION_PSFOUNDATION_H #include "foundation/PxErrors.h" #include "foundation/PxProfiler.h" #include "foundation/PxFoundation.h" #include "foundation/PxAllocator.h" #include "foundation/PxHashMap.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxBroadcast.h" #include "foundation/PxTempAllocator.h" #include "foundation/PxMutex.h" #include <stdarg.h> namespace physx { #if PX_VC #pragma warning(push) #pragma warning(disable : 4251) // class needs to have dll-interface to be used by clients of class #endif class PX_FOUNDATION_API Foundation : public PxFoundation, public PxUserAllocated { PX_NOCOPY(Foundation) public: typedef PxMutexT<PxAllocator> Mutex; typedef PxArray<PxTempAllocatorChunk*, PxAllocator> AllocFreeTable; public: // factory // note, you MUST eventually call release if createInstance returned true! static Foundation* createInstance(PxU32 version, PxErrorCallback& errc, PxAllocatorCallback& alloc); static void setInstance(Foundation& foundation); void release(); static void incRefCount(); // this call requires a foundation object to exist already static void decRefCount(); // this call requires a foundation object to exist already static PxU32 getRefCount(); // Begin Errors virtual PxErrorCallback& getErrorCallback() { return mErrorCallback; } // Return the user's error callback PxErrorCallback& getInternalErrorCallback() { return mBroadcastingError; } // Return the broadcasting error callback virtual void registerErrorCallback(PxErrorCallback& listener); virtual void deregisterErrorCallback(PxErrorCallback& listener); virtual void setErrorLevel(PxErrorCode::Enum mask) { mErrorMask = mask; } virtual PxErrorCode::Enum getErrorLevel() const { return mErrorMask; } virtual bool error(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, ...); // Report errors with the // broadcasting virtual bool error(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, va_list); // error callback static PxU32 getWarnOnceTimestamp(); // End errors // Begin Allocations virtual PxAllocatorCallback& getAllocatorCallback() { return mAllocatorCallback; } // Return the user's allocator callback PxAllocatorCallback& getBroadcastAllocator() { return mBroadcastingAllocator; } // Return the broadcasting allocator virtual void registerAllocationListener(physx::PxAllocationListener& listener); virtual void deregisterAllocationListener(physx::PxAllocationListener& listener); virtual bool getReportAllocationNames() const { return mReportAllocationNames; } virtual void setReportAllocationNames(bool value) { mReportAllocationNames = value; } PX_INLINE AllocFreeTable& getTempAllocFreeTable() { return mTempAllocFreeTable; } PX_INLINE Mutex& getTempAllocMutex() { return mTempAllocMutex; } // End allocations //private: static void destroyInstance(); Foundation(PxErrorCallback& errc, PxAllocatorCallback& alloc); ~Foundation(); // init order is tricky here: the mutexes require the allocator, the allocator may require the error stream PxAllocatorCallback& mAllocatorCallback; PxErrorCallback& mErrorCallback; PxBroadcastingAllocator mBroadcastingAllocator; PxBroadcastingErrorCallback mBroadcastingError; bool mReportAllocationNames; PxErrorCode::Enum mErrorMask; Mutex mErrorMutex; AllocFreeTable mTempAllocFreeTable; Mutex mTempAllocMutex; Mutex mListenerMutex; PxU32 mRefCount; static PxU32 mWarnOnceTimestap; }; #if PX_VC #pragma warning(pop) #endif Foundation& getFoundation(); } // namespace physx #endif
5,433
C
31.345238
123
0.767532
NVIDIA-Omniverse/PhysX/physx/source/foundation/FdFoundation.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/PxProfiler.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxString.h" #include "foundation/PxAllocator.h" #include "foundation/PxPhysicsVersion.h" #include "FdFoundation.h" using namespace physx; static PxProfilerCallback* gProfilerCallback = NULL; static Foundation* gInstance = NULL; Foundation& physx::getFoundation() { PX_ASSERT(gInstance); return *gInstance; } Foundation::Foundation(PxErrorCallback& errc, PxAllocatorCallback& alloc) : mAllocatorCallback (alloc), mErrorCallback (errc), mBroadcastingAllocator (alloc, errc), mBroadcastingError (errc), #if PX_CHECKED mReportAllocationNames (true), #else mReportAllocationNames (false), #endif mErrorMask (PxErrorCode::Enum(~0)), mErrorMutex ("Foundation::mErrorMutex"), mTempAllocMutex ("Foundation::mTempAllocMutex"), mRefCount (0) { } Foundation::~Foundation() { // deallocate temp buffer allocations PxAllocator alloc; for(PxU32 i = 0; i < mTempAllocFreeTable.size(); ++i) { for(PxTempAllocatorChunk* ptr = mTempAllocFreeTable[i]; ptr;) { PxTempAllocatorChunk* next = ptr->mNext; alloc.deallocate(ptr); ptr = next; } } mTempAllocFreeTable.reset(); } void Foundation::setInstance(Foundation& foundation) { gInstance = &foundation; } PxU32 Foundation::getWarnOnceTimestamp() { PX_ASSERT(gInstance); return mWarnOnceTimestap; } bool Foundation::error(PxErrorCode::Enum c, const char* file, int line, const char* messageFmt, ...) { va_list va; va_start(va, messageFmt); error(c, file, line, messageFmt, va); va_end(va); return false; } bool Foundation::error(PxErrorCode::Enum e, const char* file, int line, const char* messageFmt, va_list va) { PX_ASSERT(messageFmt); if(e & mErrorMask) { // this function is reentrant but user's error callback may not be, so... Mutex::ScopedLock lock(mErrorMutex); // using a static fixed size buffer here because: // 1. vsnprintf return values differ between platforms // 2. va_start is only usable in functions with ellipses // 3. ellipses (...) cannot be passed to called function // which would be necessary to dynamically grow the buffer here static const size_t bufSize = 1024; char stringBuffer[bufSize]; Pxvsnprintf(stringBuffer, bufSize, messageFmt, va); mBroadcastingError.reportError(e, stringBuffer, file, line); } return false; } Foundation* Foundation::createInstance(PxU32 version, PxErrorCallback& errc, PxAllocatorCallback& alloc) { if(version != PX_PHYSICS_VERSION) { char* buffer = new char[256]; Pxsnprintf(buffer, 256, "Wrong version: physics version is 0x%08x, tried to create 0x%08x", PX_PHYSICS_VERSION, version); errc.reportError(PxErrorCode::eINVALID_PARAMETER, buffer, PX_FL); return 0; } if(!gInstance) { // if we don't assign this here, the Foundation object can't create member // subobjects which require the allocator gInstance = reinterpret_cast<Foundation*>(alloc.allocate(sizeof(Foundation), "Foundation", PX_FL)); if(gInstance) { PX_PLACEMENT_NEW(gInstance, Foundation)(errc, alloc); PX_ASSERT(gInstance->mRefCount == 0); gInstance->mRefCount = 1; // skip 0 which marks uninitialized timestaps in PX_WARN_ONCE mWarnOnceTimestap = (mWarnOnceTimestap == PX_MAX_U32) ? 1 : mWarnOnceTimestap + 1; return gInstance; } else { errc.reportError(PxErrorCode::eINTERNAL_ERROR, "Memory allocation for foundation object failed.", PX_FL); } } else { errc.reportError(PxErrorCode::eINVALID_OPERATION, "Foundation object exists already. Only one instance per process can be created.", PX_FL); } return 0; } void Foundation::destroyInstance() { PX_ASSERT(gInstance); if(gInstance->mRefCount == 1) { PxAllocatorCallback& alloc = gInstance->getAllocatorCallback(); gInstance->~Foundation(); alloc.deallocate(gInstance); gInstance = NULL; } else { gInstance->error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Foundation destruction failed due to pending module references. Close/release all depending modules first."); } } void Foundation::incRefCount() { PX_ASSERT(gInstance); if(gInstance->mRefCount > 0) gInstance->mRefCount++; else gInstance->error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Foundation: Invalid registration detected."); } void Foundation::decRefCount() { PX_ASSERT(gInstance); if(gInstance->mRefCount > 0) gInstance->mRefCount--; else gInstance->error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Foundation: Invalid deregistration detected."); } void Foundation::release() { Foundation::destroyInstance(); } PxU32 Foundation::getRefCount() { return gInstance->mRefCount; } PxU32 Foundation::mWarnOnceTimestap = 0; void Foundation::registerAllocationListener(PxAllocationListener& listener) { Mutex::ScopedLock lock(mListenerMutex); mBroadcastingAllocator.registerListener(listener); } void Foundation::deregisterAllocationListener(PxAllocationListener& listener) { Mutex::ScopedLock lock(mListenerMutex); mBroadcastingAllocator.deregisterListener(listener); } void Foundation::registerErrorCallback(PxErrorCallback& callback) { Mutex::ScopedLock lock(mListenerMutex); mBroadcastingError.registerListener(callback); } void Foundation::deregisterErrorCallback(PxErrorCallback& callback) { Mutex::ScopedLock lock(mListenerMutex); mBroadcastingError.deregisterListener(callback); } PxFoundation* PxCreateFoundation(PxU32 version, PxAllocatorCallback& allocator, PxErrorCallback& errorCallback) { return Foundation::createInstance(version, errorCallback, allocator); } void PxSetFoundationInstance(PxFoundation& foundation) { Foundation::setInstance(static_cast<Foundation&>(foundation)); } PxAllocatorCallback* PxGetAllocatorCallback() { return &gInstance->getAllocatorCallback(); } PxAllocatorCallback* PxGetBroadcastAllocator(bool* reportAllocationNames) { PX_ASSERT(gInstance); if(reportAllocationNames) *reportAllocationNames = gInstance->mReportAllocationNames; return &gInstance->getBroadcastAllocator(); } PxErrorCallback* PX_CALL_CONV PxGetErrorCallback() { return &gInstance->getErrorCallback(); } PxErrorCallback* PX_CALL_CONV PxGetBroadcastError() { return &gInstance->getInternalErrorCallback(); } PxFoundation& PxGetFoundation() { PX_ASSERT(gInstance); return *gInstance; } PxFoundation* PxIsFoundationValid() { return gInstance; } PxProfilerCallback* PxGetProfilerCallback() { return gProfilerCallback; } void PxSetProfilerCallback(PxProfilerCallback* profiler) { gProfilerCallback = profiler; } PxU32 PxGetWarnOnceTimeStamp() { return Foundation::getWarnOnceTimestamp(); } void PxDecFoundationRefCount() { Foundation::decRefCount(); } void PxIncFoundationRefCount() { Foundation::incRefCount(); }
8,462
C++
26.3
142
0.75455
NVIDIA-Omniverse/PhysX/physx/source/foundation/FdString.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/PxString.h" #include <stdarg.h> #include <stdio.h> #include <string.h> #if PX_WINDOWS_FAMILY #pragma warning(push) #pragma warning(disable : 4996) // unsafe string functions #endif #if PX_APPLE_FAMILY #pragma clang diagnostic push // error : format string is not a string literal #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif namespace physx { // cross-platform implementations int32_t Pxstrcmp(const char* str1, const char* str2) { return (str1 && str2) ? ::strcmp(str1, str2) : -1; } int32_t Pxstrncmp(const char* str1, const char* str2, size_t count) { return ::strncmp(str1, str2, count); } int32_t Pxsnprintf(char* dst, size_t dstSize, const char* format, ...) { va_list arg; va_start(arg, format); int32_t r = Pxvsnprintf(dst, dstSize, format, arg); va_end(arg); return r; } int32_t Pxsscanf(const char* buffer, const char* format, ...) { va_list arg; va_start(arg, format); #if (PX_VC < 12) && !PX_LINUX int32_t r = ::sscanf(buffer, format, arg); #else int32_t r = ::vsscanf(buffer, format, arg); #endif va_end(arg); return r; } size_t Pxstrlcpy(char* dst, size_t dstSize, const char* src) { size_t i = 0; if(dst && dstSize) { for(; i + 1 < dstSize && src[i]; i++) // copy up to dstSize-1 bytes dst[i] = src[i]; dst[i] = 0; // always null-terminate } while(src[i]) // read any remaining characters in the src string to get the length i++; return i; } size_t Pxstrlcat(char* dst, size_t dstSize, const char* src) { size_t i = 0, s = 0; if(dst && dstSize) { s = strlen(dst); for(; i + s + 1 < dstSize && src[i]; i++) // copy until total is at most dstSize-1 dst[i + s] = src[i]; dst[i + s] = 0; // always null-terminate } while(src[i]) // read any remaining characters in the src string to get the length i++; return i + s; } void Pxstrlwr(char* str) { for(; *str; str++) if(*str >= 'A' && *str <= 'Z') *str += 32; } void Pxstrupr(char* str) { for(; *str; str++) if(*str >= 'a' && *str <= 'z') *str -= 32; } int32_t Pxvsnprintf(char* dst, size_t dstSize, const char* src, va_list arg) { #if PX_VC // MSVC is not C99-compliant... int32_t result = dst ? ::vsnprintf(dst, dstSize, src, arg) : -1; if(dst && (result == int32_t(dstSize) || result < 0)) dst[dstSize - 1] = 0; // string was truncated or there wasn't room for the NULL if(result < 0) result = _vscprintf(src, arg); // work out how long the answer would have been. #else int32_t result = ::vsnprintf(dst, dstSize, src, arg); #endif return result; } int32_t Pxstricmp(const char* str, const char* str1) { #if PX_VC return (::_stricmp(str, str1)); #else return (::strcasecmp(str, str1)); #endif } int32_t Pxstrnicmp(const char* str, const char* str1, size_t n) { #if PX_VC return (::_strnicmp(str, str1, n)); #else return (::strncasecmp(str, str1, n)); #endif } }//namespace physx #if PX_APPLE_FAMILY #pragma clang diagnostic pop #endif #if PX_WINDOWS_FAMILY #pragma warning(pop) #endif
4,674
C++
26.339181
84
0.68849
NVIDIA-Omniverse/PhysX/physx/source/foundation/unix/FdUnixFPU.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/PxFPU.h" #if !defined(__CYGWIN__) #include <fenv.h> PX_COMPILE_TIME_ASSERT(8 * sizeof(uint32_t) >= sizeof(fenv_t)); #endif #if PX_OSX // osx defines SIMD as standard for floating point operations. #include <xmmintrin.h> #endif physx::PxFPUGuard::PxFPUGuard() { #if defined(__CYGWIN__) #pragma message "FPUGuard::FPUGuard() is not implemented" #elif PX_OSX mControlWords[0] = _mm_getcsr(); // set default (disable exceptions: _MM_MASK_MASK) and FTZ (_MM_FLUSH_ZERO_ON), DAZ (_MM_DENORMALS_ZERO_ON: (1<<6)) _mm_setcsr(_MM_MASK_MASK | _MM_FLUSH_ZERO_ON | (1 << 6)); #elif defined(__EMSCRIPTEN__) // not supported #else PX_COMPILE_TIME_ASSERT(sizeof(fenv_t) <= sizeof(mControlWords)); fegetenv(reinterpret_cast<fenv_t*>(mControlWords)); fesetenv(FE_DFL_ENV); #if PX_LINUX // need to explicitly disable exceptions because fesetenv does not modify // the sse control word on 32bit linux (64bit is fine, but do it here just be sure) fedisableexcept(FE_ALL_EXCEPT); #endif #endif } physx::PxFPUGuard::~PxFPUGuard() { #if defined(__CYGWIN__) #pragma message "PxFPUGuard::~PxFPUGuard() is not implemented" #elif PX_OSX // restore control word and clear exception flags // (setting exception state flags cause exceptions on the first following fp operation) _mm_setcsr(mControlWords[0] & ~_MM_EXCEPT_MASK); #elif defined(__EMSCRIPTEN__) // not supported #else fesetenv(reinterpret_cast<fenv_t*>(mControlWords)); #endif } PX_FOUNDATION_API void physx::PxEnableFPExceptions() { #if PX_LINUX && !defined(__EMSCRIPTEN__) feclearexcept(FE_ALL_EXCEPT); feenableexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW); #elif PX_OSX // clear any pending exceptions // (setting exception state flags cause exceptions on the first following fp operation) uint32_t control = _mm_getcsr() & ~_MM_EXCEPT_MASK; // enable all fp exceptions except inexact and underflow (common, benign) // note: denorm has to be disabled as well because underflow can create denorms _mm_setcsr((control & ~_MM_MASK_MASK) | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_DENORM); #endif } PX_FOUNDATION_API void physx::PxDisableFPExceptions() { #if PX_LINUX && !defined(__EMSCRIPTEN__) fedisableexcept(FE_ALL_EXCEPT); #elif PX_OSX // clear any pending exceptions // (setting exception state flags cause exceptions on the first following fp operation) uint32_t control = _mm_getcsr() & ~_MM_EXCEPT_MASK; _mm_setcsr(control | _MM_MASK_MASK); #endif }
4,152
C++
37.453703
116
0.740848
NVIDIA-Omniverse/PhysX/physx/source/foundation/unix/FdUnixSync.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/PxAssert.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxSync.h" #include <errno.h> #include <stdio.h> #include <pthread.h> #include <time.h> #include <sys/time.h> namespace physx { namespace { class SyncImpl { public: pthread_mutex_t mutex; pthread_cond_t cond; volatile int setCounter; volatile bool is_set; }; SyncImpl* getSync(PxSyncImpl* impl) { return reinterpret_cast<SyncImpl*>(impl); } } uint32_t PxSyncImpl::getSize() { return sizeof(SyncImpl); } struct PxUnixScopeLock { PxUnixScopeLock(pthread_mutex_t& m) : mMutex(m) { pthread_mutex_lock(&mMutex); } ~PxUnixScopeLock() { pthread_mutex_unlock(&mMutex); } private: pthread_mutex_t& mMutex; }; PxSyncImpl::PxSyncImpl() { int status = pthread_mutex_init(&getSync(this)->mutex, 0); PX_ASSERT(!status); status = pthread_cond_init(&getSync(this)->cond, 0); PX_ASSERT(!status); PX_UNUSED(status); getSync(this)->is_set = false; getSync(this)->setCounter = 0; } PxSyncImpl::~PxSyncImpl() { pthread_cond_destroy(&getSync(this)->cond); pthread_mutex_destroy(&getSync(this)->mutex); } void PxSyncImpl::reset() { PxUnixScopeLock lock(getSync(this)->mutex); getSync(this)->is_set = false; } void PxSyncImpl::set() { PxUnixScopeLock lock(getSync(this)->mutex); if(!getSync(this)->is_set) { getSync(this)->is_set = true; getSync(this)->setCounter++; pthread_cond_broadcast(&getSync(this)->cond); } } bool PxSyncImpl::wait(uint32_t ms) { PxUnixScopeLock lock(getSync(this)->mutex); int lastSetCounter = getSync(this)->setCounter; if(!getSync(this)->is_set) { if(ms == uint32_t(-1)) { // have to loop here and check is_set since pthread_cond_wait can return successfully // even if it was not signaled by pthread_cond_broadcast (OS efficiency design decision) int status = 0; while(!status && !getSync(this)->is_set && (lastSetCounter == getSync(this)->setCounter)) status = pthread_cond_wait(&getSync(this)->cond, &getSync(this)->mutex); PX_ASSERT((!status && getSync(this)->is_set) || (lastSetCounter != getSync(this)->setCounter)); } else { timespec ts; timeval tp; gettimeofday(&tp, NULL); uint32_t sec = ms / 1000; uint32_t usec = (ms - 1000 * sec) * 1000; // sschirm: taking into account that us might accumulate to a second // otherwise the pthread_cond_timedwait complains on osx. usec = tp.tv_usec + usec; uint32_t div_sec = usec / 1000000; uint32_t rem_usec = usec - div_sec * 1000000; ts.tv_sec = tp.tv_sec + sec + div_sec; ts.tv_nsec = rem_usec * 1000; // have to loop here and check is_set since pthread_cond_timedwait can return successfully // even if it was not signaled by pthread_cond_broadcast (OS efficiency design decision) int status = 0; while(!status && !getSync(this)->is_set && (lastSetCounter == getSync(this)->setCounter)) status = pthread_cond_timedwait(&getSync(this)->cond, &getSync(this)->mutex, &ts); PX_ASSERT((!status && getSync(this)->is_set) || (status == ETIMEDOUT) || (lastSetCounter != getSync(this)->setCounter)); } } return getSync(this)->is_set || (lastSetCounter != getSync(this)->setCounter); } } // namespace physx
4,906
C++
29.66875
98
0.710355
NVIDIA-Omniverse/PhysX/physx/source/foundation/unix/FdUnixThread.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/PxAssert.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxAtomic.h" #include "foundation/PxThread.h" #include <math.h> #if !PX_APPLE_FAMILY && !defined(__CYGWIN__) && !PX_EMSCRIPTEN #include <bits/local_lim.h> // PTHREAD_STACK_MIN #endif #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <sys/syscall.h> #if !PX_APPLE_FAMILY && !PX_EMSCRIPTEN #include <asm/unistd.h> #include <sys/resource.h> #endif #if PX_APPLE_FAMILY #include <sys/types.h> #include <sys/sysctl.h> #include <TargetConditionals.h> #include <pthread.h> #endif #define PxSpinLockPause() asm("nop") namespace physx { namespace { typedef enum { ePxThreadNotStarted, ePxThreadStarted, ePxThreadStopped } PxThreadState; class ThreadImpl { public: PxThreadImpl::ExecuteFn fn; void* arg; volatile int32_t quitNow; volatile int32_t threadStarted; volatile int32_t state; pthread_t thread; pid_t tid; uint32_t affinityMask; const char* name; }; ThreadImpl* getThread(PxThreadImpl* impl) { return reinterpret_cast<ThreadImpl*>(impl); } static void setTid(ThreadImpl& threadImpl) { // query TID // AM: TODO: neither of the below are implemented #if PX_APPLE_FAMILY threadImpl.tid = syscall(SYS_gettid); #elif PX_EMSCRIPTEN threadImpl.tid = pthread_self(); #else threadImpl.tid = syscall(__NR_gettid); #endif // notify/unblock parent thread PxAtomicCompareExchange(&(threadImpl.threadStarted), 1, 0); } void* PxThreadStart(void* arg) { ThreadImpl* impl = getThread(reinterpret_cast<PxThreadImpl*>(arg)); impl->state = ePxThreadStarted; // run setTid in thread's context setTid(*impl); // then run either the passed in function or execute from the derived class (Runnable). if(impl->fn) (*impl->fn)(impl->arg); else if(impl->arg) (reinterpret_cast<PxRunnable*>(impl->arg))->execute(); return 0; } } uint32_t PxThreadImpl::getSize() { return sizeof(ThreadImpl); } PxThreadImpl::Id PxThreadImpl::getId() { return Id(pthread_self()); } PxThreadImpl::PxThreadImpl() { getThread(this)->thread = 0; getThread(this)->tid = 0; getThread(this)->state = ePxThreadNotStarted; getThread(this)->quitNow = 0; getThread(this)->threadStarted = 0; getThread(this)->fn = NULL; getThread(this)->arg = NULL; getThread(this)->affinityMask = 0; getThread(this)->name = "set my name before starting me"; } PxThreadImpl::PxThreadImpl(PxThreadImpl::ExecuteFn fn, void* arg, const char* name) { getThread(this)->thread = 0; getThread(this)->tid = 0; getThread(this)->state = ePxThreadNotStarted; getThread(this)->quitNow = 0; getThread(this)->threadStarted = 0; getThread(this)->fn = fn; getThread(this)->arg = arg; getThread(this)->affinityMask = 0; getThread(this)->name = name; start(0, NULL); } PxThreadImpl::~PxThreadImpl() { if(getThread(this)->state == ePxThreadStarted) kill(); } void PxThreadImpl::start(uint32_t stackSize, PxRunnable* runnable) { if(getThread(this)->state != ePxThreadNotStarted) return; if(stackSize == 0) stackSize = getDefaultStackSize(); #if defined(PTHREAD_STACK_MIN) if(stackSize < PTHREAD_STACK_MIN) { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__, "PxThreadImpl::start(): stack size was set below PTHREAD_STACK_MIN"); stackSize = PTHREAD_STACK_MIN; } #endif if(runnable && !getThread(this)->arg && !getThread(this)->fn) getThread(this)->arg = runnable; pthread_attr_t attr; int status = pthread_attr_init(&attr); PX_ASSERT(!status); PX_UNUSED(status); status = pthread_attr_setstacksize(&attr, stackSize); PX_ASSERT(!status); status = pthread_create(&getThread(this)->thread, &attr, PxThreadStart, this); PX_ASSERT(!status); // wait for thread to startup and write out TID // otherwise TID dependent calls like setAffinity will fail. while(PxAtomicCompareExchange(&(getThread(this)->threadStarted), 1, 1) == 0) yield(); // here we are sure that getThread(this)->state >= ePxThreadStarted status = pthread_attr_destroy(&attr); PX_ASSERT(!status); // apply stored affinity mask if(getThread(this)->affinityMask) setAffinityMask(getThread(this)->affinityMask); if (getThread(this)->name) setName(getThread(this)->name); } void PxThreadImpl::signalQuit() { PxAtomicIncrement(&(getThread(this)->quitNow)); } bool PxThreadImpl::waitForQuit() { if(getThread(this)->state == ePxThreadNotStarted) return false; // works also with a stopped/exited thread if the handle is still valid pthread_join(getThread(this)->thread, NULL); getThread(this)->state = ePxThreadStopped; return true; } bool PxThreadImpl::quitIsSignalled() { return PxAtomicCompareExchange(&(getThread(this)->quitNow), 0, 0) != 0; } #if defined(PX_GCC_FAMILY) __attribute__((noreturn)) #endif void PxThreadImpl::quit() { getThread(this)->state = ePxThreadStopped; pthread_exit(0); } void PxThreadImpl::kill() { if(getThread(this)->state == ePxThreadStarted) pthread_cancel(getThread(this)->thread); getThread(this)->state = ePxThreadStopped; } void PxThreadImpl::sleep(uint32_t ms) { timespec sleepTime; uint32_t remainder = ms % 1000; sleepTime.tv_sec = ms - remainder; sleepTime.tv_nsec = remainder * 1000000L; while(nanosleep(&sleepTime, &sleepTime) == -1) continue; } void PxThreadImpl::yield() { sched_yield(); } void PxThreadImpl::yieldProcessor() { #if (PX_ARM || PX_A64) __asm__ __volatile__("yield"); #else __asm__ __volatile__("pause"); #endif } uint32_t PxThreadImpl::setAffinityMask(uint32_t mask) { // Same as windows impl if mask is zero if(!mask) return 0; getThread(this)->affinityMask = mask; uint64_t prevMask = 0; if(getThread(this)->state == ePxThreadStarted) { #if PX_EMSCRIPTEN // not supported #elif !PX_APPLE_FAMILY // Apple doesn't support syscall with getaffinity and setaffinity int32_t errGet = syscall(__NR_sched_getaffinity, getThread(this)->tid, sizeof(prevMask), &prevMask); if(errGet < 0) return 0; int32_t errSet = syscall(__NR_sched_setaffinity, getThread(this)->tid, sizeof(mask), &mask); if(errSet != 0) return 0; #endif } return uint32_t(prevMask); } void PxThreadImpl::setName(const char* name) { getThread(this)->name = name; if (getThread(this)->state == ePxThreadStarted) { // not implemented because most unix APIs expect setName() // to be called from the thread's context. Example see next comment: // this works only with the current thread and can rename // the main process if used in the wrong context: // prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name) ,0,0,0); PX_UNUSED(name); } } #if !PX_APPLE_FAMILY static PxThreadPriority::Enum convertPriorityFromLinux(uint32_t inPrio, int policy) { PX_COMPILE_TIME_ASSERT(PxThreadPriority::eLOW > PxThreadPriority::eHIGH); PX_COMPILE_TIME_ASSERT(PxThreadPriority::eHIGH == 0); int maxL = sched_get_priority_max(policy); int minL = sched_get_priority_min(policy); int rangeL = maxL - minL; int rangeNv = PxThreadPriority::eLOW - PxThreadPriority::eHIGH; // case for default scheduler policy if(rangeL == 0) return PxThreadPriority::eNORMAL; float floatPrio = (float(maxL - inPrio) * float(rangeNv)) / float(rangeL); return PxThreadPriority::Enum(int(roundf(floatPrio))); } static int convertPriorityToLinux(PxThreadPriority::Enum inPrio, int policy) { int maxL = sched_get_priority_max(policy); int minL = sched_get_priority_min(policy); int rangeL = maxL - minL; int rangeNv = PxThreadPriority::eLOW - PxThreadPriority::eHIGH; // case for default scheduler policy if(rangeL == 0) return 0; float floatPrio = (float(PxThreadPriority::eLOW - inPrio) * float(rangeL)) / float(rangeNv); return minL + int(roundf(floatPrio)); } #endif void PxThreadImpl::setPriority(PxThreadPriority::Enum val) { PX_UNUSED(val); #if !PX_APPLE_FAMILY int policy; sched_param s_param; pthread_getschedparam(getThread(this)->thread, &policy, &s_param); s_param.sched_priority = convertPriorityToLinux(val, policy); pthread_setschedparam(getThread(this)->thread, policy, &s_param); #endif } PxThreadPriority::Enum PxThreadImpl::getPriority(Id pthread) { PX_UNUSED(pthread); #if !PX_APPLE_FAMILY int policy; sched_param s_param; int ret = pthread_getschedparam(pthread_t(pthread), &policy, &s_param); if(ret == 0) return convertPriorityFromLinux(s_param.sched_priority, policy); else return PxThreadPriority::eNORMAL; #else return PxThreadPriority::eNORMAL; #endif } uint32_t PxThreadImpl::getNbPhysicalCores() { #if PX_APPLE_FAMILY int count; size_t size = sizeof(count); return sysctlbyname("hw.physicalcpu", &count, &size, NULL, 0) ? 0 : count; #else // Linux exposes CPU topology using /sys/devices/system/cpu // https://www.kernel.org/doc/Documentation/cputopology.txt if(FILE* f = fopen("/sys/devices/system/cpu/possible", "r")) { int minIndex, maxIndex; int n = fscanf(f, "%d-%d", &minIndex, &maxIndex); fclose(f); if(n == 2) return (maxIndex - minIndex) + 1; else if(n == 1) return minIndex + 1; } // For non-Linux kernels this fallback is possibly the best we can do // but will report logical (hyper-threaded) counts int n = sysconf(_SC_NPROCESSORS_CONF); if(n < 0) return 0; else return n; #endif } PxU32 PxTlsAlloc() { pthread_key_t key; int status = pthread_key_create(&key, NULL); PX_ASSERT(!status); PX_UNUSED(status); return PxU32(key); } void PxTlsFree(PxU32 index) { int status = pthread_key_delete(pthread_key_t(index)); PX_ASSERT(!status); PX_UNUSED(status); } void* PxTlsGet(PxU32 index) { return reinterpret_cast<void*>(pthread_getspecific(pthread_key_t(index))); } size_t PxTlsGetValue(PxU32 index) { return reinterpret_cast<size_t>(pthread_getspecific(pthread_key_t(index))); } PxU32 PxTlsSet(PxU32 index, void* value) { int status = pthread_setspecific(pthread_key_t(index), value); PX_ASSERT(!status); return !status; } PxU32 PxTlsSetValue(PxU32 index, size_t value) { int status = pthread_setspecific(pthread_key_t(index), reinterpret_cast<void*>(value)); PX_ASSERT(!status); return !status; } // DM: On Linux x86-32, without implementation-specific restrictions // the default stack size for a new thread should be 2 megabytes (kernel.org). // NOTE: take care of this value on other architectures! PxU32 PxThreadImpl::getDefaultStackSize() { return 1 << 21; } } // namespace physx
12,042
C++
24.788009
102
0.72189
NVIDIA-Omniverse/PhysX/physx/source/foundation/unix/FdUnixMutex.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/PxAssert.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxMutex.h" #include "foundation/PxAtomic.h" #include "foundation/PxThread.h" #include <pthread.h> namespace physx { #if PX_LINUX #include <sched.h> static int gMutexProtocol = PTHREAD_PRIO_INHERIT; PX_FORCE_INLINE bool isLegalProtocol(const int mutexProtocol) { return ( (PTHREAD_PRIO_NONE == mutexProtocol) || (PTHREAD_PRIO_INHERIT == mutexProtocol) || ((PTHREAD_PRIO_PROTECT == mutexProtocol) && ((sched_getscheduler(0) == SCHED_FIFO) || (sched_getscheduler(0) == SCHED_RR))) ); } bool PxSetMutexProtocol(const int mutexProtocol) { if(isLegalProtocol(mutexProtocol)) { gMutexProtocol = mutexProtocol; return true; } return false; } int PxGetMutexProtocol() { return gMutexProtocol; } #endif //PX_LINUX namespace { struct MutexUnixImpl { pthread_mutex_t lock; PxThread::Id owner; }; MutexUnixImpl* getMutex(PxMutexImpl* impl) { return reinterpret_cast<MutexUnixImpl*>(impl); } } PxMutexImpl::PxMutexImpl() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); #if PX_LINUX pthread_mutexattr_setprotocol(&attr, gMutexProtocol); pthread_mutexattr_setprioceiling(&attr, 0); #endif pthread_mutex_init(&getMutex(this)->lock, &attr); pthread_mutexattr_destroy(&attr); } PxMutexImpl::~PxMutexImpl() { pthread_mutex_destroy(&getMutex(this)->lock); } void PxMutexImpl::lock() { int err = pthread_mutex_lock(&getMutex(this)->lock); PX_ASSERT(!err); PX_UNUSED(err); #if PX_DEBUG getMutex(this)->owner = PxThread::getId(); #endif } bool PxMutexImpl::trylock() { bool success = !pthread_mutex_trylock(&getMutex(this)->lock); #if PX_DEBUG if(success) getMutex(this)->owner = PxThread::getId(); #endif return success; } void PxMutexImpl::unlock() { #if PX_DEBUG if(getMutex(this)->owner != PxThread::getId()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "Mutex must be unlocked only by thread that has already acquired lock"); return; } #endif int err = pthread_mutex_unlock(&getMutex(this)->lock); PX_ASSERT(!err); PX_UNUSED(err); } uint32_t PxMutexImpl::getSize() { return sizeof(MutexUnixImpl); } class ReadWriteLockImpl { public: PxMutex mutex; volatile int readerCounter; }; PxReadWriteLock::PxReadWriteLock() { mImpl = reinterpret_cast<ReadWriteLockImpl*>(PX_ALLOC(sizeof(ReadWriteLockImpl), "ReadWriteLockImpl")); PX_PLACEMENT_NEW(mImpl, ReadWriteLockImpl); mImpl->readerCounter = 0; } PxReadWriteLock::~PxReadWriteLock() { mImpl->~ReadWriteLockImpl(); PX_FREE(mImpl); } void PxReadWriteLock::lockReader(bool takeLock) { if(takeLock) mImpl->mutex.lock(); PxAtomicIncrement(&mImpl->readerCounter); if(takeLock) mImpl->mutex.unlock(); } void PxReadWriteLock::lockWriter() { mImpl->mutex.lock(); // spin lock until no readers while(mImpl->readerCounter); } void PxReadWriteLock::unlockReader() { PxAtomicDecrement(&mImpl->readerCounter); } void PxReadWriteLock::unlockWriter() { mImpl->mutex.unlock(); } } // namespace physx
4,878
C++
23.395
126
0.736367
NVIDIA-Omniverse/PhysX/physx/source/foundation/unix/FdUnixSList.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 "foundation/PxAtomic.h" #include "foundation/PxSList.h" #include "foundation/PxThread.h" #include <pthread.h> #if PX_EMSCRIPTEN #define USE_MUTEX #endif namespace physx { namespace { #if defined(USE_MUTEX) class ScopedMutexLock { pthread_mutex_t& mMutex; public: PX_INLINE ScopedMutexLock(pthread_mutex_t& mutex) : mMutex(mutex) { pthread_mutex_lock(&mMutex); } PX_INLINE ~ScopedMutexLock() { pthread_mutex_unlock(&mMutex); } }; typedef ScopedMutexLock ScopedLock; #else struct ScopedSpinLock { PX_FORCE_INLINE ScopedSpinLock(volatile int32_t& lock) : mLock(lock) { while(__sync_lock_test_and_set(&mLock, 1)) { // spinning without atomics is usually // causing less bus traffic. -> only one // CPU is modifying the cache line. while(lock) PxSpinLockPause(); } } PX_FORCE_INLINE ~ScopedSpinLock() { __sync_lock_release(&mLock); } private: volatile int32_t& mLock; }; typedef ScopedSpinLock ScopedLock; #endif struct SListDetail { PxSListEntry* head; #if defined(USE_MUTEX) pthread_mutex_t lock; #else volatile int32_t lock; #endif }; template <typename T> SListDetail* getDetail(T* impl) { return reinterpret_cast<SListDetail*>(impl); } } PxSListImpl::PxSListImpl() { getDetail(this)->head = NULL; #if defined(USE_MUTEX) pthread_mutex_init(&getDetail(this)->lock, NULL); #else getDetail(this)->lock = 0; // 0 == unlocked #endif } PxSListImpl::~PxSListImpl() { #if defined(USE_MUTEX) pthread_mutex_destroy(&getDetail(this)->lock); #endif } void PxSListImpl::push(PxSListEntry* entry) { ScopedLock lock(getDetail(this)->lock); entry->mNext = getDetail(this)->head; getDetail(this)->head = entry; } PxSListEntry* PxSListImpl::pop() { ScopedLock lock(getDetail(this)->lock); PxSListEntry* result = getDetail(this)->head; if(result != NULL) getDetail(this)->head = result->mNext; return result; } PxSListEntry* PxSListImpl::flush() { ScopedLock lock(getDetail(this)->lock); PxSListEntry* result = getDetail(this)->head; getDetail(this)->head = NULL; return result; } uint32_t PxSListImpl::getSize() { return sizeof(SListDetail); } } // namespace physx
3,873
C++
24.320261
74
0.73638
NVIDIA-Omniverse/PhysX/physx/source/foundation/unix/FdUnixSocket.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxIntrinsics.h" #include "foundation/PxMathIntrinsics.h" #include "foundation/PxSocket.h" #include <sys/types.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/time.h> #include <netdb.h> #include <arpa/inet.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #define INVALID_SOCKET -1 #ifndef SOMAXCONN #define SOMAXCONN 5 #endif namespace physx { const uint32_t PxSocket::DEFAULT_BUFFER_SIZE = 32768; class SocketImpl { public: SocketImpl(bool isBlocking); virtual ~SocketImpl(); bool connect(const char* host, uint16_t port, uint32_t timeout); bool listen(uint16_t port); bool accept(bool block); void disconnect(); void setBlocking(bool blocking); virtual uint32_t write(const uint8_t* data, uint32_t length); virtual bool flush(); uint32_t read(uint8_t* data, uint32_t length); PX_FORCE_INLINE bool isBlocking() const { return mIsBlocking; } PX_FORCE_INLINE bool isConnected() const { return mIsConnected; } PX_FORCE_INLINE const char* getHost() const { return mHost; } PX_FORCE_INLINE uint16_t getPort() const { return mPort; } protected: bool nonBlockingTimeout() const; int32_t mSocket; int32_t mListenSocket; const char* mHost; uint16_t mPort; bool mIsConnected; bool mIsBlocking; bool mListenMode; }; void socketSetBlockingInternal(int32_t socket, bool blocking); SocketImpl::SocketImpl(bool isBlocking) : mSocket(INVALID_SOCKET) , mListenSocket(INVALID_SOCKET) , mHost(NULL) , mPort(0) , mIsConnected(false) , mIsBlocking(isBlocking) , mListenMode(false) { } SocketImpl::~SocketImpl() { } bool SocketImpl::connect(const char* host, uint16_t port, uint32_t timeout) { sockaddr_in socketAddress; intrinsics::memSet(&socketAddress, 0, sizeof(sockaddr_in)); socketAddress.sin_family = AF_INET; socketAddress.sin_port = htons(port); // get host hostent* hp = gethostbyname(host); if(!hp) { in_addr a; a.s_addr = inet_addr(host); hp = gethostbyaddr(reinterpret_cast<const char*>(&a), sizeof(in_addr), AF_INET); if(!hp) return false; } intrinsics::memCopy(&socketAddress.sin_addr, hp->h_addr_list[0], hp->h_length); // connect mSocket = socket(AF_INET, SOCK_STREAM, 0); if(mSocket == INVALID_SOCKET) return false; socketSetBlockingInternal(mSocket, false); int connectRet = ::connect(mSocket, reinterpret_cast<sockaddr*>(&socketAddress), sizeof(socketAddress)); if(connectRet < 0) { if(errno != EINPROGRESS) { disconnect(); return false; } // Setup poll function call to monitor the connect call. // By querying for POLLOUT we're checking if the socket is // ready for writing. pollfd pfd; pfd.fd = mSocket; pfd.events = POLLOUT; const int pollResult = ::poll(&pfd, 1, timeout /*milliseconds*/); const bool pollTimeout = (pollResult == 0); const bool pollError = (pollResult < 0); // an error inside poll happened. Can check error with `errno` variable. if(pollTimeout || pollError) { disconnect(); return false; } else { PX_ASSERT(pollResult == 1); // check that event was precisely POLLOUT and not anything else (e.g., errors, hang-up) bool test = (pfd.revents & POLLOUT) && !(pfd.revents & (~POLLOUT)); if(!test) { disconnect(); return false; } } // check if we are really connected, above code seems to return // true if host is a unix machine even if the connection was // not accepted. char buffer; if(recv(mSocket, &buffer, 0, 0) < 0) { if(errno != EWOULDBLOCK) { disconnect(); return false; } } } socketSetBlockingInternal(mSocket, mIsBlocking); #if PX_APPLE_FAMILY int noSigPipe = 1; setsockopt(mSocket, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, sizeof(int)); #endif mIsConnected = true; mPort = port; mHost = host; return true; } bool SocketImpl::listen(uint16_t port) { mListenSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(mListenSocket == INVALID_SOCKET) return false; // enable address reuse: "Address already in use" error message int yes = 1; if(setsockopt(mListenSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) return false; mListenMode = true; sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; intrinsics::memSet(addr.sin_zero, '\0', sizeof addr.sin_zero); return bind(mListenSocket, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != -1 && ::listen(mListenSocket, SOMAXCONN) != -1; } bool SocketImpl::accept(bool block) { if(mIsConnected || !mListenMode) return false; // set the listen socket to be non-blocking. socketSetBlockingInternal(mListenSocket, block); int32_t clientSocket = ::accept(mListenSocket, 0, 0); if(clientSocket == INVALID_SOCKET) return false; mSocket = clientSocket; mIsConnected = true; socketSetBlockingInternal(mSocket, mIsBlocking); // force the mode to whatever the user set return mIsConnected; } void SocketImpl::disconnect() { if(mListenSocket != INVALID_SOCKET) { close(mListenSocket); mListenSocket = INVALID_SOCKET; } if(mSocket != INVALID_SOCKET) { if(mIsConnected) { socketSetBlockingInternal(mSocket, true); shutdown(mSocket, SHUT_RDWR); } close(mSocket); mSocket = INVALID_SOCKET; } mIsConnected = false; mListenMode = false; mPort = 0; mHost = NULL; } bool SocketImpl::nonBlockingTimeout() const { return !mIsBlocking && errno == EWOULDBLOCK; } void socketSetBlockingInternal(int32_t socket, bool blocking) { int mode = fcntl(socket, F_GETFL, 0); if(!blocking) mode |= O_NONBLOCK; else mode &= ~O_NONBLOCK; fcntl(socket, F_SETFL, mode); } // should be cross-platform from here down void SocketImpl::setBlocking(bool blocking) { if(blocking != mIsBlocking) { mIsBlocking = blocking; if(isConnected()) socketSetBlockingInternal(mSocket, blocking); } } bool SocketImpl::flush() { return true; } uint32_t SocketImpl::write(const uint8_t* data, uint32_t length) { if(length == 0) return 0; int sent = send(mSocket, reinterpret_cast<const char*>(data), int32_t(length), 0); if(sent <= 0 && !nonBlockingTimeout()) disconnect(); return uint32_t(sent > 0 ? sent : 0); } uint32_t SocketImpl::read(uint8_t* data, uint32_t length) { if(length == 0) return 0; int32_t received = recv(mSocket, reinterpret_cast<char*>(data), int32_t(length), 0); if(received <= 0 && !nonBlockingTimeout()) disconnect(); return uint32_t(received > 0 ? received : 0); } class BufferedSocketImpl : public SocketImpl { public: BufferedSocketImpl(bool isBlocking) : SocketImpl(isBlocking), mBufferPos(0) { } virtual ~BufferedSocketImpl() { } bool flush(); uint32_t write(const uint8_t* data, uint32_t length); private: uint32_t mBufferPos; uint8_t mBuffer[PxSocket::DEFAULT_BUFFER_SIZE]; }; bool BufferedSocketImpl::flush() { uint32_t totalBytesWritten = 0; while(totalBytesWritten < mBufferPos && mIsConnected) totalBytesWritten += int32_t(SocketImpl::write(mBuffer + totalBytesWritten, mBufferPos - totalBytesWritten)); bool ret = (totalBytesWritten == mBufferPos); mBufferPos = 0; return ret; } uint32_t BufferedSocketImpl::write(const uint8_t* data, uint32_t length) { uint32_t bytesWritten = 0; while(mBufferPos + length >= PxSocket::DEFAULT_BUFFER_SIZE) { uint32_t currentChunk = PxSocket::DEFAULT_BUFFER_SIZE - mBufferPos; intrinsics::memCopy(mBuffer + mBufferPos, data + bytesWritten, currentChunk); bytesWritten += uint32_t(currentChunk); // for the user, this is consumed even if we fail to shove it down a // non-blocking socket uint32_t sent = SocketImpl::write(mBuffer, PxSocket::DEFAULT_BUFFER_SIZE); mBufferPos = PxSocket::DEFAULT_BUFFER_SIZE - sent; if(sent < PxSocket::DEFAULT_BUFFER_SIZE) // non-blocking or error { if(sent) // we can reasonably hope this is rare intrinsics::memMove(mBuffer, mBuffer + sent, mBufferPos); return bytesWritten; } length -= currentChunk; } if(length > 0) { intrinsics::memCopy(mBuffer + mBufferPos, data + bytesWritten, length); bytesWritten += length; mBufferPos += length; } return bytesWritten; } PxSocket::PxSocket(bool inIsBuffering, bool isBlocking) { if(inIsBuffering) { void* mem = PX_ALLOC(sizeof(BufferedSocketImpl), "BufferedSocketImpl"); mImpl = PX_PLACEMENT_NEW(mem, BufferedSocketImpl)(isBlocking); } else { void* mem = PX_ALLOC(sizeof(SocketImpl), "SocketImpl"); mImpl = PX_PLACEMENT_NEW(mem, SocketImpl)(isBlocking); } } PxSocket::~PxSocket() { mImpl->flush(); mImpl->disconnect(); mImpl->~SocketImpl(); PX_FREE(mImpl); } bool PxSocket::connect(const char* host, uint16_t port, uint32_t timeout) { return mImpl->connect(host, port, timeout); } bool PxSocket::listen(uint16_t port) { return mImpl->listen(port); } bool PxSocket::accept(bool block) { return mImpl->accept(block); } void PxSocket::disconnect() { mImpl->disconnect(); } bool PxSocket::isConnected() const { return mImpl->isConnected(); } const char* PxSocket::getHost() const { return mImpl->getHost(); } uint16_t PxSocket::getPort() const { return mImpl->getPort(); } bool PxSocket::flush() { if(!mImpl->isConnected()) return false; return mImpl->flush(); } uint32_t PxSocket::write(const uint8_t* data, uint32_t length) { if(!mImpl->isConnected()) return 0; return mImpl->write(data, length); } uint32_t PxSocket::read(uint8_t* data, uint32_t length) { if(!mImpl->isConnected()) return 0; return mImpl->read(data, length); } void PxSocket::setBlocking(bool blocking) { mImpl->setBlocking(blocking); } bool PxSocket::isBlocking() const { return mImpl->isBlocking(); } } // namespace physx
11,327
C++
22.6
115
0.712369
NVIDIA-Omniverse/PhysX/physx/source/foundation/windows/FdWindowsFPU.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/PxFPU.h" #include "float.h" #include "foundation/PxIntrinsics.h" #if PX_X64 || PX_ARM || PX_A64 #define _MCW_ALL _MCW_DN | _MCW_EM | _MCW_RC #else #define _MCW_ALL _MCW_DN | _MCW_EM | _MCW_IC | _MCW_RC | _MCW_PC #endif physx::PxFPUGuard::PxFPUGuard() { // default plus FTZ and DAZ #if PX_X64 || PX_ARM || PX_A64 // query current control word state _controlfp_s(mControlWords, 0, 0); // set both x87 and sse units to default + DAZ unsigned int cw; _controlfp_s(&cw, _CW_DEFAULT | _DN_FLUSH, _MCW_ALL); #else // query current control word state __control87_2(0, 0, mControlWords, mControlWords + 1); // set both x87 and sse units to default + DAZ unsigned int x87, sse; __control87_2(_CW_DEFAULT | _DN_FLUSH, _MCW_ALL, &x87, &sse); #endif } physx::PxFPUGuard::~PxFPUGuard() { _clearfp(); #if PX_X64 || PX_ARM || PX_A64 // reset FP state unsigned int cw; _controlfp_s(&cw, *mControlWords, _MCW_ALL); #else // reset FP state unsigned int x87, sse; __control87_2(mControlWords[0], _MCW_ALL, &x87, 0); __control87_2(mControlWords[1], _MCW_ALL, 0, &sse); #endif } void physx::PxEnableFPExceptions() { // clear any pending exceptions _clearfp(); // enable all fp exceptions except inexact and underflow (common, benign) _controlfp_s(NULL, uint32_t(~_MCW_EM) | _EM_INEXACT | _EM_UNDERFLOW, _MCW_EM); } void physx::PxDisableFPExceptions() { _controlfp_s(NULL, _MCW_EM, _MCW_EM); }
3,121
C++
34.078651
79
0.721243
NVIDIA-Omniverse/PhysX/physx/source/foundation/windows/FdWindowsMutex.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/windows/PxWindowsInclude.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxMutex.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxThread.h" namespace physx { namespace { struct MutexWinImpl { CRITICAL_SECTION mLock; PxThread::Id mOwner; }; } static PX_FORCE_INLINE MutexWinImpl* getMutex(PxMutexImpl* impl) { return reinterpret_cast<MutexWinImpl*>(impl); } PxMutexImpl::PxMutexImpl() { InitializeCriticalSection(&getMutex(this)->mLock); getMutex(this)->mOwner = 0; } PxMutexImpl::~PxMutexImpl() { DeleteCriticalSection(&getMutex(this)->mLock); } void PxMutexImpl::lock() { EnterCriticalSection(&getMutex(this)->mLock); #if PX_DEBUG getMutex(this)->mOwner = PxThread::getId(); #endif } bool PxMutexImpl::trylock() { bool success = TryEnterCriticalSection(&getMutex(this)->mLock) != 0; #if PX_DEBUG if(success) getMutex(this)->mOwner = PxThread::getId(); #endif return success; } void PxMutexImpl::unlock() { #if PX_DEBUG // ensure we are already holding the lock if(getMutex(this)->mOwner != PxThread::getId()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Mutex must be unlocked only by thread that has already acquired lock"); return; } #endif LeaveCriticalSection(&getMutex(this)->mLock); } uint32_t PxMutexImpl::getSize() { return sizeof(MutexWinImpl); } class ReadWriteLockImpl { PX_NOCOPY(ReadWriteLockImpl) public: ReadWriteLockImpl() { } PxMutex mutex; volatile LONG readerCount; // handle recursive writer locking }; PxReadWriteLock::PxReadWriteLock() { mImpl = reinterpret_cast<ReadWriteLockImpl*>(PX_ALLOC(sizeof(ReadWriteLockImpl), "ReadWriteLockImpl")); PX_PLACEMENT_NEW(mImpl, ReadWriteLockImpl); mImpl->readerCount = 0; } PxReadWriteLock::~PxReadWriteLock() { mImpl->~ReadWriteLockImpl(); PX_FREE(mImpl); } void PxReadWriteLock::lockReader(bool takeLock) { if(takeLock) mImpl->mutex.lock(); InterlockedIncrement(&mImpl->readerCount); if(takeLock) mImpl->mutex.unlock(); } void PxReadWriteLock::lockWriter() { mImpl->mutex.lock(); // spin lock until no readers while(mImpl->readerCount); } void PxReadWriteLock::unlockReader() { InterlockedDecrement(&mImpl->readerCount); } void PxReadWriteLock::unlockWriter() { mImpl->mutex.unlock(); } } // namespace physx
4,013
C++
24.896774
138
0.751807
NVIDIA-Omniverse/PhysX/physx/source/foundation/windows/FdWindowsAtomic.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/windows/PxWindowsInclude.h" #include "foundation/PxAtomic.h" namespace physx { PxI32 PxAtomicExchange(volatile PxI32* val, PxI32 val2) { return (PxI32)InterlockedExchange((volatile LONG*)val, (LONG)val2); } PxI32 PxAtomicCompareExchange(volatile PxI32* dest, PxI32 exch, PxI32 comp) { return (PxI32)InterlockedCompareExchange((volatile LONG*)dest, exch, comp); } void* PxAtomicCompareExchangePointer(volatile void** dest, void* exch, void* comp) { return InterlockedCompareExchangePointer((volatile PVOID*)dest, exch, comp); } PxI32 PxAtomicIncrement(volatile PxI32* val) { return (PxI32)InterlockedIncrement((volatile LONG*)val); } PxI32 PxAtomicDecrement(volatile PxI32* val) { return (PxI32)InterlockedDecrement((volatile LONG*)val); } PxI32 PxAtomicAdd(volatile PxI32* val, PxI32 delta) { LONG newValue, oldValue; do { oldValue = *val; newValue = oldValue + delta; } while(InterlockedCompareExchange((volatile LONG*)val, newValue, oldValue) != oldValue); return newValue; } PxI32 PxAtomicMax(volatile PxI32* val, PxI32 val2) { // Could do this more efficiently in asm... LONG newValue, oldValue; do { oldValue = *val; newValue = val2 > oldValue ? val2 : oldValue; } while(InterlockedCompareExchange((volatile LONG*)val, newValue, oldValue) != oldValue); return newValue; } } // namespace physx
3,054
C++
32.944444
90
0.759005
NVIDIA-Omniverse/PhysX/physx/source/foundation/windows/FdWindowsTime.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/PxTime.h" #include "foundation/windows/PxWindowsInclude.h" using namespace physx; static int64_t getTimeTicks() { LARGE_INTEGER a; QueryPerformanceCounter(&a); return a.QuadPart; } static double getTickDuration() { LARGE_INTEGER a; QueryPerformanceFrequency(&a); return 1.0f / double(a.QuadPart); } static double sTickDuration = getTickDuration(); static const PxCounterFrequencyToTensOfNanos gCounterFreq = PxTime::getCounterFrequency(); const PxCounterFrequencyToTensOfNanos& PxTime::getBootCounterFrequency() { return gCounterFreq; } PxCounterFrequencyToTensOfNanos PxTime::getCounterFrequency() { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); return PxCounterFrequencyToTensOfNanos(PxTime::sNumTensOfNanoSecondsInASecond, (uint64_t)freq.QuadPart); } uint64_t PxTime::getCurrentCounterValue() { LARGE_INTEGER ticks; QueryPerformanceCounter(&ticks); return (uint64_t)ticks.QuadPart; } PxTime::PxTime() : mTickCount(0) { getElapsedSeconds(); } PxTime::Second PxTime::getElapsedSeconds() { int64_t lastTickCount = mTickCount; mTickCount = getTimeTicks(); return (mTickCount - lastTickCount) * sTickDuration; } PxTime::Second PxTime::peekElapsedSeconds() { return (getTimeTicks() - mTickCount) * sTickDuration; } PxTime::Second PxTime::getLastTime() const { return mTickCount * sTickDuration; }
3,051
C++
31.817204
105
0.773517
NVIDIA-Omniverse/PhysX/physx/source/foundation/windows/FdWindowsThread.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/windows/PxWindowsInclude.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxAssert.h" #include "foundation/PxThread.h" #include "foundation/PxAlloca.h" // an exception for setting the thread name in Microsoft debuggers #define NS_MS_VC_EXCEPTION 0x406D1388 namespace physx { namespace { #if PX_VC #pragma warning(disable : 4061) // enumerator 'identifier' in switch of enum 'enumeration' is not handled #pragma warning(disable : 4191) //'operator/operation' : unsafe conversion from 'type of expression' to 'type required' #endif // struct for naming a thread in the debugger #pragma pack(push, 8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) class ThreadImpl { public: enum State { NotStarted, Started, Stopped }; HANDLE thread; LONG quitNow; // Should be 32bit aligned on SMP systems. State state; DWORD threadID; PxThreadImpl::ExecuteFn fn; void* arg; uint32_t affinityMask; const char* name; }; static PX_FORCE_INLINE ThreadImpl* getThread(PxThreadImpl* impl) { return reinterpret_cast<ThreadImpl*>(impl); } static DWORD WINAPI PxThreadStart(LPVOID arg) { ThreadImpl* impl = getThread((PxThreadImpl*)arg); // run either the passed in function or execute from the derived class (Runnable). if(impl->fn) (*impl->fn)(impl->arg); else if(impl->arg) ((PxRunnable*)impl->arg)->execute(); return 0; } // cache physical thread count static uint32_t gPhysicalCoreCount = 0; } uint32_t PxThreadImpl::getSize() { return sizeof(ThreadImpl); } PxThreadImpl::Id PxThreadImpl::getId() { return static_cast<Id>(GetCurrentThreadId()); } // fwd GetLogicalProcessorInformation() typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); uint32_t PxThreadImpl::getNbPhysicalCores() { if(!gPhysicalCoreCount) { // modified example code from: http://msdn.microsoft.com/en-us/library/ms683194 LPFN_GLPI glpi; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL; DWORD returnLength = 0; DWORD processorCoreCount = 0; DWORD byteOffset = 0; glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); if(NULL == glpi) { // GetLogicalProcessorInformation not supported on OS < XP Service Pack 3 return 0; } DWORD rc = (DWORD)glpi(NULL, &returnLength); PX_ASSERT(rc == FALSE); PX_UNUSED(rc); // first query reports required buffer space if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) { buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)PxAlloca(returnLength); } else { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Error querying buffer size for number of physical processors"); return 0; } // retrieve data rc = (DWORD)glpi(buffer, &returnLength); if(rc != TRUE) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Error querying number of physical processors"); return 0; } ptr = buffer; while(byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { switch(ptr->Relationship) { case RelationProcessorCore: processorCoreCount++; break; default: break; } byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ptr++; } gPhysicalCoreCount = processorCoreCount; } return gPhysicalCoreCount; } PxThreadImpl::PxThreadImpl() { getThread(this)->thread = NULL; getThread(this)->state = ThreadImpl::NotStarted; getThread(this)->quitNow = 0; getThread(this)->fn = NULL; getThread(this)->arg = NULL; getThread(this)->affinityMask = 0; getThread(this)->name = NULL; } PxThreadImpl::PxThreadImpl(ExecuteFn fn, void* arg, const char* name) { getThread(this)->thread = NULL; getThread(this)->state = ThreadImpl::NotStarted; getThread(this)->quitNow = 0; getThread(this)->fn = fn; getThread(this)->arg = arg; getThread(this)->affinityMask = 0; getThread(this)->name = name; start(0, NULL); } PxThreadImpl::~PxThreadImpl() { if(getThread(this)->state == ThreadImpl::Started) kill(); CloseHandle(getThread(this)->thread); } void PxThreadImpl::start(uint32_t stackSize, PxRunnable* runnable) { if(getThread(this)->state != ThreadImpl::NotStarted) return; getThread(this)->state = ThreadImpl::Started; if(runnable && !getThread(this)->arg && !getThread(this)->fn) getThread(this)->arg = runnable; getThread(this)->thread = CreateThread(NULL, stackSize, PxThreadStart, (LPVOID) this, CREATE_SUSPENDED, &getThread(this)->threadID); if(!getThread(this)->thread) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "FdWindowsThread::start: Failed to create thread."); getThread(this)->state = ThreadImpl::NotStarted; return; } // set affinity, set name and resume if(getThread(this)->affinityMask) setAffinityMask(getThread(this)->affinityMask); if (getThread(this)->name) setName(getThread(this)->name); DWORD rc = ResumeThread(getThread(this)->thread); if(rc == DWORD(-1)) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "FdWindowsThread::start: Failed to resume thread."); getThread(this)->state = ThreadImpl::NotStarted; return; } } void PxThreadImpl::signalQuit() { InterlockedIncrement(&(getThread(this)->quitNow)); } bool PxThreadImpl::waitForQuit() { if(getThread(this)->state == ThreadImpl::NotStarted) return false; WaitForSingleObject(getThread(this)->thread, INFINITE); getThread(this)->state = ThreadImpl::Stopped; return true; } bool PxThreadImpl::quitIsSignalled() { return InterlockedCompareExchange(&(getThread(this)->quitNow), 0, 0) != 0; } void PxThreadImpl::quit() { getThread(this)->state = ThreadImpl::Stopped; ExitThread(0); } void PxThreadImpl::kill() { if(getThread(this)->state == ThreadImpl::Started) TerminateThread(getThread(this)->thread, 0); getThread(this)->state = ThreadImpl::Stopped; } void PxThreadImpl::sleep(uint32_t ms) { Sleep(ms); } void PxThreadImpl::yield() { SwitchToThread(); } void PxThreadImpl::yieldProcessor() { YieldProcessor(); } uint32_t PxThreadImpl::setAffinityMask(uint32_t mask) { if(mask) { // store affinity getThread(this)->affinityMask = mask; // if thread already started apply immediately if(getThread(this)->state == ThreadImpl::Started) { uint32_t err = uint32_t(SetThreadAffinityMask(getThread(this)->thread, mask)); return err; } } return 0; } void PxThreadImpl::setName(const char* name) { getThread(this)->name = name; if (getThread(this)->state == ThreadImpl::Started) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name; info.dwThreadID = getThread(this)->threadID; info.dwFlags = 0; // C++ Exceptions are disabled for this project, but SEH is not (and cannot be) // http://stackoverflow.com/questions/943087/what-exactly-will-happen-if-i-disable-c-exceptions-in-a-project __try { RaiseException(NS_MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except (EXCEPTION_EXECUTE_HANDLER) { // this runs if not attached to a debugger (thus not really naming the thread) } } } void PxThreadImpl::setPriority(PxThreadPriority::Enum prio) { BOOL rc = false; switch(prio) { case PxThreadPriority::eHIGH: rc = SetThreadPriority(getThread(this)->thread, THREAD_PRIORITY_HIGHEST); break; case PxThreadPriority::eABOVE_NORMAL: rc = SetThreadPriority(getThread(this)->thread, THREAD_PRIORITY_ABOVE_NORMAL); break; case PxThreadPriority::eNORMAL: rc = SetThreadPriority(getThread(this)->thread, THREAD_PRIORITY_NORMAL); break; case PxThreadPriority::eBELOW_NORMAL: rc = SetThreadPriority(getThread(this)->thread, THREAD_PRIORITY_BELOW_NORMAL); break; case PxThreadPriority::eLOW: rc = SetThreadPriority(getThread(this)->thread, THREAD_PRIORITY_LOWEST); break; default: break; } if(!rc) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "FdWindowsThread::setPriority: Failed to set thread priority."); } } PxThreadPriority::Enum PxThreadImpl::getPriority(Id threadId) { PxThreadPriority::Enum retval = PxThreadPriority::eLOW; int priority = GetThreadPriority((HANDLE)threadId); PX_COMPILE_TIME_ASSERT(THREAD_PRIORITY_HIGHEST > THREAD_PRIORITY_ABOVE_NORMAL); if(priority >= THREAD_PRIORITY_HIGHEST) retval = PxThreadPriority::eHIGH; else if(priority >= THREAD_PRIORITY_ABOVE_NORMAL) retval = PxThreadPriority::eABOVE_NORMAL; else if(priority >= THREAD_PRIORITY_NORMAL) retval = PxThreadPriority::eNORMAL; else if(priority >= THREAD_PRIORITY_BELOW_NORMAL) retval = PxThreadPriority::eBELOW_NORMAL; return retval; } PxU32 PxTlsAlloc() { DWORD rv = ::TlsAlloc(); PX_ASSERT(rv != TLS_OUT_OF_INDEXES); return (PxU32)rv; } void PxTlsFree(PxU32 index) { ::TlsFree(index); } void* PxTlsGet(PxU32 index) { return ::TlsGetValue(index); } size_t PxTlsGetValue(PxU32 index) { return size_t(::TlsGetValue(index)); } PxU32 PxTlsSet(PxU32 index, void* value) { return PxU32(::TlsSetValue(index, value)); } PxU32 PxTlsSetValue(PxU32 index, size_t value) { return PxU32(::TlsSetValue(index, reinterpret_cast<void*>(value))); } PxU32 PxThreadImpl::getDefaultStackSize() { return 1048576; }; } // namespace physx
11,129
C++
25.374408
128
0.729176
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtGjkQueryExt.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 "extensions/PxGjkQueryExt.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxBoxGeometry.h" #include "geometry/PxPlaneGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "foundation/PxAllocator.h" #include "geomutils/PxContactBuffer.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// PxGjkQueryExt::SphereSupport::SphereSupport() : radius(0.0f) { } PxGjkQueryExt::SphereSupport::SphereSupport(PxReal _radius) : radius(_radius) { } PxGjkQueryExt::SphereSupport::SphereSupport(const PxSphereGeometry& geom) : radius(geom.radius) { } PxReal PxGjkQueryExt::SphereSupport::getMargin() const { return radius; } PxVec3 PxGjkQueryExt::SphereSupport::supportLocal(const PxVec3& /*dir*/) const { return PxVec3(0.0f); } /////////////////////////////////////////////////////////////////////////////// PxGjkQueryExt::CapsuleSupport::CapsuleSupport() : radius(0.0f), halfHeight(0.0f) { } PxGjkQueryExt::CapsuleSupport::CapsuleSupport(PxReal _radius, PxReal _halfHeight) : radius(_radius), halfHeight(_halfHeight) { } PxGjkQueryExt::CapsuleSupport::CapsuleSupport(const PxCapsuleGeometry& geom) : radius(geom.radius) { } PxReal PxGjkQueryExt::CapsuleSupport::getMargin() const { return radius; } PxVec3 PxGjkQueryExt::CapsuleSupport::supportLocal(const PxVec3& dir) const { return PxVec3(PxSign2(dir.x) * halfHeight, 0.0f, 0.0f); } /////////////////////////////////////////////////////////////////////////////// PxGjkQueryExt::BoxSupport::BoxSupport() : halfExtents(0.0f), margin(0.0f) { } PxGjkQueryExt::BoxSupport::BoxSupport(const PxVec3& _halfExtents, PxReal _margin) : halfExtents(_halfExtents), margin(_margin) { } PxGjkQueryExt::BoxSupport::BoxSupport(const PxBoxGeometry& box, PxReal _margin) : halfExtents(box.halfExtents), margin(_margin) { } PxReal PxGjkQueryExt::BoxSupport::getMargin() const { return margin; } PxVec3 PxGjkQueryExt::BoxSupport::supportLocal(const PxVec3& dir) const { const PxVec3 d = dir.getNormalized(); return PxVec3(PxSign2(d.x) * halfExtents.x, PxSign2(d.y) * halfExtents.y, PxSign2(d.z) * halfExtents.z); } /////////////////////////////////////////////////////////////////////////////// PxGjkQueryExt::ConvexMeshSupport::ConvexMeshSupport() : convexMesh (NULL), scale (0.0f), scaleRotation (0.0f), margin (0.0f) { } PxGjkQueryExt::ConvexMeshSupport::ConvexMeshSupport(const PxConvexMesh& _convexMesh, const PxVec3& _scale, const PxQuat& _scaleRotation, PxReal _margin) : convexMesh (&_convexMesh), scale (_scale), scaleRotation (_scaleRotation), margin (_margin) { } PxGjkQueryExt::ConvexMeshSupport::ConvexMeshSupport(const PxConvexMeshGeometry& _convexMesh, PxReal _margin) : convexMesh (_convexMesh.convexMesh), scale (_convexMesh.scale.scale), scaleRotation (_convexMesh.scale.rotation), margin (_margin) { } PxReal PxGjkQueryExt::ConvexMeshSupport::getMargin() const { return margin * scale.minElement(); } PxVec3 PxGjkQueryExt::ConvexMeshSupport::supportLocal(const PxVec3& dir) const { if (convexMesh == NULL) return PxVec3(0.0f); PxVec3 d = scaleRotation.rotateInv(scaleRotation.rotate(dir).multiply(PxVec3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z))); const PxVec3* verts = convexMesh->getVertices(); int count = int(convexMesh->getNbVertices()); float maxDot = -FLT_MAX; int index = -1; for (int i = 0; i < count; ++i) { float dot = verts[i].dot(d); if (dot > maxDot) { maxDot = dot; index = i; } } if (index == -1) return PxVec3(0); return scaleRotation.rotateInv(scaleRotation.rotate(verts[index]).multiply(scale)); } /////////////////////////////////////////////////////////////////////////////// PxGjkQueryExt::ConvexGeomSupport::ConvexGeomSupport() : mType(PxGeometryType::eINVALID) { } PxGjkQueryExt::ConvexGeomSupport::ConvexGeomSupport(const PxGeometry& geom, PxReal margin) { mType = PxGeometryType::eINVALID; switch (geom.getType()) { case PxGeometryType::eSPHERE: { mType = PxGeometryType::eSPHERE; const PxSphereGeometry& sphere = static_cast<const PxSphereGeometry&>(geom); PX_PLACEMENT_NEW(&mSupport, SphereSupport(sphere.radius + margin)); break; } case PxGeometryType::eCAPSULE: { mType = PxGeometryType::eCAPSULE; const PxCapsuleGeometry& capsule = static_cast<const PxCapsuleGeometry&>(geom); PX_PLACEMENT_NEW(&mSupport, CapsuleSupport(capsule.radius + margin, capsule.halfHeight)); break; } case PxGeometryType::eBOX: { mType = PxGeometryType::eBOX; PX_PLACEMENT_NEW(&mSupport, BoxSupport(static_cast<const PxBoxGeometry&>(geom), margin)); break; } case PxGeometryType::eCONVEXMESH: { mType = PxGeometryType::eCONVEXMESH; PX_PLACEMENT_NEW(&mSupport, ConvexMeshSupport(static_cast<const PxConvexMeshGeometry&>(geom), margin)); break; } default: break; } } PxGjkQueryExt::ConvexGeomSupport::~ConvexGeomSupport() { if (isValid()) reinterpret_cast<Support&>(mSupport).~Support(); } bool PxGjkQueryExt::ConvexGeomSupport::isValid() const { return mType != PxGeometryType::eINVALID; } PxReal PxGjkQueryExt::ConvexGeomSupport::getMargin() const { return isValid() ? reinterpret_cast<const Support&>(mSupport).getMargin() : 0.0f; } PxVec3 PxGjkQueryExt::ConvexGeomSupport::supportLocal(const PxVec3& dir) const { return isValid() ? reinterpret_cast<const Support&>(mSupport).supportLocal(dir) : PxVec3(0.0f); } /////////////////////////////////////////////////////////////////////////////// bool PxGjkQueryExt::generateContacts(const PxGjkQuery::Support& a, const PxGjkQuery::Support& b, const PxTransform& poseA, const PxTransform& poseB, PxReal contactDistance, PxReal toleranceLength, PxContactBuffer& contactBuffer) { PxVec3 pointA, pointB, separatingAxis; PxReal separation; if (!PxGjkQuery::proximityInfo(a, b, poseA, poseB, contactDistance, toleranceLength, pointA, pointB, separatingAxis, separation)) return false; PxContactPoint contact; contact.point = (pointA + pointB) * 0.5f; // VR: should I make it just pointB? contact.normal = separatingAxis; contact.separation = separation; contactBuffer.contact(contact); return true; }
7,879
C++
30.646586
228
0.706435
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtBroadPhase.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxBounds3.h" #include "foundation/PxErrorCallback.h" #include "foundation/PxFoundation.h" #include "extensions/PxBroadPhaseExt.h" using namespace physx; PxU32 PxBroadPhaseExt::createRegionsFromWorldBounds(PxBounds3* regions, const PxBounds3& globalBounds, PxU32 nbSubdiv, PxU32 upAxis) { PX_CHECK_MSG(globalBounds.isValid(), "PxBroadPhaseExt::createRegionsFromWorldBounds(): invalid bounds provided!"); PX_CHECK_MSG(upAxis<3, "PxBroadPhaseExt::createRegionsFromWorldBounds(): invalid up-axis provided!"); const PxVec3& min = globalBounds.minimum; const PxVec3& max = globalBounds.maximum; const float dx = (max.x - min.x) / float(nbSubdiv); const float dy = (max.y - min.y) / float(nbSubdiv); const float dz = (max.z - min.z) / float(nbSubdiv); PxU32 nbRegions = 0; PxVec3 currentMin, currentMax; for(PxU32 j=0;j<nbSubdiv;j++) { for(PxU32 i=0;i<nbSubdiv;i++) { if(upAxis==0) { currentMin = PxVec3(min.x, min.y + dy * float(i), min.z + dz * float(j)); currentMax = PxVec3(max.x, min.y + dy * float(i+1), min.z + dz * float(j+1)); } else if(upAxis==1) { currentMin = PxVec3(min.x + dx * float(i), min.y, min.z + dz * float(j)); currentMax = PxVec3(min.x + dx * float(i+1), max.y, min.z + dz * float(j+1)); } else if(upAxis==2) { currentMin = PxVec3(min.x + dx * float(i), min.y + dy * float(j), min.z); currentMax = PxVec3(min.x + dx * float(i+1), min.y + dy * float(j+1), max.z); } regions[nbRegions++] = PxBounds3(currentMin, currentMax); } } return nbRegions; }
3,266
C++
43.148648
132
0.717085
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSampling.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "extensions/PxSamplingExt.h" #include "GuSDF.h" #include "foundation/PxQuat.h" #include "foundation/PxHashSet.h" #include "GuDistancePointTriangle.h" #include "extensions/PxRemeshingExt.h" #include "geometry/PxGeometryQuery.h" #include "PxQueryReport.h" #include "foundation/PxHashMap.h" #include "CmRandom.h" #include "GuAABBTreeNode.h" #include "GuAABBTree.h" #include "GuAABBTreeBounds.h" #include "GuWindingNumber.h" #include "foundation/PxMathUtils.h" #include "foundation/PxSort.h" namespace physx { namespace { using namespace Gu; using namespace Cm; static const PxI32 neighborEdges[3][2] = { { 0, 1 }, { 2, 0 }, { 1, 2 } }; struct Int3 { PxI32 x; PxI32 y; PxI32 z; Int3(PxI32 x_, PxI32 y_, PxI32 z_) : x(x_), y(y_), z(z_) {} Int3() : x(0), y(0), z(0) {} }; struct ActiveSample { PxI32 mIndex; PxArray<PxI32> mNearbyTriangles; PxArray<PxReal> mCumulativeTriangleAreas; ActiveSample() : mIndex(-1) {} ActiveSample(PxI32 index, const PxArray<PxI32>& nearbyTriangles, const PxArray<PxReal>& cumulativeTriangleAreas) { mIndex = index; mNearbyTriangles = nearbyTriangles; mCumulativeTriangleAreas = cumulativeTriangleAreas; } }; struct PointWithNormal { PxVec3 mPoint; PxVec3 mNormal; PointWithNormal() {} PointWithNormal(const PxVec3& point, const PxVec3& normal) : mPoint(point), mNormal(normal) { } }; struct IndexWithNormal { PxI32 mIndex; PxVec3 mNormal; IndexWithNormal(PxI32 index, const PxVec3& normal) : mIndex(index), mNormal(normal) { } }; void getBoundsFromPoints(const PxVec3* points, const PxU32 numPoints, PxVec3& outMinExtents, PxVec3& outMaxExtents) { PxVec3 minExtents(FLT_MAX); PxVec3 maxExtents(-FLT_MAX); // calculate face bounds for (PxU32 i = 0; i < numPoints; ++i) { const PxVec3& a = points[i]; minExtents = a.minimum(minExtents); maxExtents = a.maximum(maxExtents); } outMinExtents = minExtents; outMaxExtents = maxExtents; } PX_FORCE_INLINE PxReal triArea(const PxVec3& a, const PxVec3& b, const PxVec3& c) { return 0.5f * (b - a).cross(c - a).magnitude(); } PX_FORCE_INLINE PxReal triArea(const PxU32* tri, const PxVec3* points) { return triArea(points[tri[0]], points[tri[1]], points[tri[2]]); } PX_FORCE_INLINE PxU64 edgeKey(PxI32 a, PxI32 b) { if (a < b) return ((PxU64(a)) << 32) | (PxU64(b)); else return ((PxU64(b)) << 32) | (PxU64(a)); } void buildTriangleAdjacency(const PxU32* tris, PxU32 numTriangles, PxArray<PxI32>& result) { PxU32 l = 4 * numTriangles; //4 elements per triangle - waste one entry per triangle to get a power of 2 which allows for bit shift usage instead of modulo result.clear(); result.resize(l, -1); for (PxU32 i = 3; i < l; i += 4) result[i] = -2; PxHashMap<PxU64, PxU32> edges; for (PxU32 i = 0; i < numTriangles; ++i) { const PxU32* tri = &tris[3 * i]; for (PxU32 j = 0; j < 3; ++j) { const PxU64 edge = edgeKey(tri[neighborEdges[j][0]], tri[neighborEdges[j][1]]); const PxPair<const PxU64, PxU32>* it = edges.find(edge); if (it) { result[4u * i + j] = it->second; result[it->second] = 4u * i + j; } else { PxU32 v = 4u * i + j; edges.insert(edge, v); } } } } void collectTrianglesInSphere(const PxVec3& center, PxReal radius, PxI32 startTri, const PxU32* triangles, const PxVec3* points, const PxArray<PxI32>& adj, PxHashSet<PxI32>& result) { PxArray<PxI32> stack; stack.pushBack(startTri); result.clear(); result.insert(startTri); while (stack.size() > 0) { PxI32 tri = stack.popBack() * 4; for (PxI32 i = 0; i < 3; ++i) { PxI32 n = adj[tri + i] >> 2; if (n >= 0 && !result.contains(n)) { const PxU32* t = &triangles[3 * n]; if (Gu::distancePointTriangleSquared(center, points[t[0]], points[t[1]] - points[t[0]], points[t[2]] - points[t[0]]) < radius * radius) { result.insert(n); stack.pushBack(n); } } } } } void createActiveSample(const PxArray<PxReal>& triangleAreaBuffer, PxI32 sampleIndex, const PxVec3& sample, PxReal radius, PxI32 startTri, const PxU32* triangles, const PxVec3* points, const PxArray<PxI32>& adj, ActiveSample& result) { PxHashSet<PxI32> nearbyTriangles; collectTrianglesInSphere(sample, radius, startTri, triangles, points, adj, nearbyTriangles); result.mNearbyTriangles.clear(); result.mNearbyTriangles.reserve(nearbyTriangles.size()); //for (PxI32 t : nearbyTriangles) for (PxHashSet<PxI32>::Iterator iter = nearbyTriangles.getIterator(); !iter.done(); ++iter) result.mNearbyTriangles.pushBack(*iter); result.mCumulativeTriangleAreas.clear(); result.mCumulativeTriangleAreas.resize(nearbyTriangles.size()); result.mCumulativeTriangleAreas[0] = triangleAreaBuffer[result.mNearbyTriangles[0]]; for (PxU32 i = 1; i < nearbyTriangles.size(); ++i) result.mCumulativeTriangleAreas[i] = result.mCumulativeTriangleAreas[i - 1] + triangleAreaBuffer[result.mNearbyTriangles[i]]; result.mIndex = sampleIndex; } //Returns the index of the element with value <= v PxU32 binarySearch(const PxArray<PxReal>& sorted, PxReal v) { PxU32 low = 0; PxU32 up = PxU32(sorted.size()); while (up - low > 1) { PxU32 middle = (up + low) >> 1; PxReal m = sorted[middle]; if (v <= m) up = middle; else low = middle; } return low; } PxVec3 randomPointOnTriangle(BasicRandom& rnd, const PxU32* tri, const PxVec3* points, PxVec3* barycentricCoordinates = NULL) { while (true) { PxReal a = rnd.rand(0.0f, 1.0f); PxReal b = rnd.rand(0.0f, 1.0f); PxReal sum = a + b; if (sum > 1) continue; PxReal c = 1 - a - b; if (barycentricCoordinates) (*barycentricCoordinates) = PxVec3(a, b, c); return points[tri[0]] * a + points[tri[1]] * b + points[tri[2]] * c; } } bool samplePointInBallOnSurface(BasicRandom& rnd, const PxArray<PxReal>& cumulativeAreas, const PxVec3* points, const PxU32* triangles, const PxArray<PxI32>& nearbyTriangles, const PxVec3& point, PxReal radius, PxVec3& sample, PxI32& triId, PxI32 numAttempts = 30, PxVec3* barycentricCoordinates = NULL) { triId = -1; //Use variable upper bound as described in http://extremelearning.com.au/an-improved-version-of-bridsons-algorithm-n-for-poisson-disc-sampling/ PxReal step = radius / numAttempts; PxReal rUpper = radius + step; PxVec3 fallback; PxReal fallbackDist = FLT_MAX; PxI32 fallbackId = -1; PxVec3 fallbackBary; for (PxI32 i = 0; i < numAttempts; ++i) { PxReal totalArea = cumulativeAreas[cumulativeAreas.size() - 1]; PxReal r = rnd.rand(0.0f, 1.0f) * totalArea; PxI32 id; id = binarySearch(cumulativeAreas, r); triId = nearbyTriangles[id]; sample = randomPointOnTriangle(rnd, &triangles[3 * triId], points, barycentricCoordinates); const PxReal dist2 = (sample - point).magnitudeSquared(); if (dist2 > radius * radius && dist2 < rUpper * rUpper) return true; if (dist2 > radius * radius && dist2 < 4 * radius * radius && dist2 < fallbackDist) { fallbackDist = dist2; fallbackId = triId; fallback = sample; if (barycentricCoordinates) fallbackBary = *barycentricCoordinates; } rUpper += step; } if (fallbackId >= 0) { sample = fallback; triId = fallbackId; if (barycentricCoordinates) *barycentricCoordinates = fallbackBary; return true; } return false; } } class PoissonSamplerShared { private: struct SparseGridNode { PxI32 mPointIndex; PxI32 mExcessStartIndex; PxI32 mExcessEndIndex; SparseGridNode(PxI32 pointIndex_) : mPointIndex(pointIndex_), mExcessStartIndex(0), mExcessEndIndex(-1) { } SparseGridNode() : mPointIndex(-1), mExcessStartIndex(0), mExcessEndIndex(-1) { } }; //Returns true if successful. False if too many cells are required (overflow) bool rebuildSparseGrid(); public: PoissonSamplerShared() : maxNumSamples(0), currentSamplingRadius(0.0f) {} //Returns true if successful. False if too many cells are required (overflow) bool setSamplingRadius(PxReal r); void addSamples(const PxArray<PxVec3>& samples); PxU32 removeSamples(const PxArray<PxVec3>& samples); PxI32 findSample(const PxVec3& p); PxReal minDistanceToOtherSamplesSquared(const PxVec3& p) const; const PxArray<PxVec3>& getSamples() const { return result; } bool addPointToSparseGrid(const PxVec3& p, PxI32 pointIndex); protected: bool postAddPointToSparseGrid(const PxVec3& p, PxI32 pointIndex); bool preAddPointToSparseGrid(const PxVec3& p, PxI32 pointIndex); public: //Input PxI32 numSampleAttemptsAroundPoint; PxVec3 size; PxVec3 min; PxU32 maxNumSamples; //Intermediate data PxReal currentSamplingRadius; Int3 resolution; PxReal cellSize; PxArray<PxU32> occupiedCellBits; PxHashMap<PxI32, SparseGridNode> sparseGrid3D; PxArray<PxI32> excessList; Cm::BasicRandom rnd; bool gridResolutionValid = false; //Output PxArray<PxVec3> result; PX_NOCOPY(PoissonSamplerShared) }; struct PointInVolumeTester { virtual bool pointInVolume(const PxVec3& p) const = 0; virtual ~PointInVolumeTester() {} }; PX_FORCE_INLINE bool pointInSphere(const PxVec3& p, const PxVec3& sphereCenter, PxReal sphereRadius) { return (p - sphereCenter).magnitudeSquared() < sphereRadius * sphereRadius; } struct AlwaysInsideTester : public PointInVolumeTester { AlwaysInsideTester() {} virtual bool pointInVolume(const PxVec3&) const { return true; } virtual ~AlwaysInsideTester() {} }; struct PointInSphereTester : public PointInVolumeTester { PxVec3 mCenter; PxReal mRadius; PointInSphereTester(const PxVec3& center, const PxReal radius) : mCenter(center), mRadius(radius) {} virtual bool pointInVolume(const PxVec3& p) const { return pointInSphere(p, mCenter, mRadius); } virtual ~PointInSphereTester() {} }; struct PointInOBBTester : public PointInVolumeTester { PxVec3 mBoxCenter; PxVec3 mBoxAxisAlignedExtents; PxQuat mBoxOrientation; PointInOBBTester(const PxVec3& boxCenter, const PxVec3& boxAxisAlignedExtents, const PxQuat boxOrientation) : mBoxCenter(boxCenter), mBoxAxisAlignedExtents(boxAxisAlignedExtents), mBoxOrientation(boxOrientation) {} virtual bool pointInVolume(const PxVec3& p) const { PxVec3 localPoint = mBoxOrientation.rotateInv(p - mBoxCenter); return localPoint.x >= -mBoxAxisAlignedExtents.x && localPoint.x <= mBoxAxisAlignedExtents.x && localPoint.y >= -mBoxAxisAlignedExtents.y && localPoint.y <= mBoxAxisAlignedExtents.y && localPoint.z >= -mBoxAxisAlignedExtents.z && localPoint.z <= mBoxAxisAlignedExtents.z; } virtual ~PointInOBBTester() {} }; class TriangleMeshPoissonSampler : public PxTriangleMeshPoissonSampler { public: TriangleMeshPoissonSampler(const PxU32* tris, PxU32 numTris, const PxVec3* pts_, PxU32 numPts, PxReal r, PxI32 numSampleAttemptsAroundPoint_ = 30, PxU32 maxNumSamples_ = 0); virtual void addSamplesInVolume(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples); virtual void addSamplesInSphere(const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples); virtual void addSamplesInBox(const PxBounds3& axisAlignedBox, const PxQuat& boxOrientation, bool createVolumeSamples); virtual const PxArray<PxI32>& getSampleTriangleIds() const { return triangleIds; } virtual const PxArray<PxVec3>& getSampleBarycentrics() const { return barycentricCoordinates; } virtual bool setSamplingRadius(PxReal samplingRadius) { return poissonSamplerShared.setSamplingRadius(samplingRadius); } virtual void addSamples(const PxArray<PxVec3>& samples) { poissonSamplerShared.addSamples(samples); } void createVolumeSamples(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, PxReal randomScale, PxReal r, bool addToSparseGrid = true); virtual PxU32 removeSamples(const PxArray<PxVec3>& samples) { return poissonSamplerShared.removeSamples(samples); } virtual const PxArray<PxVec3>& getSamples() const { return poissonSamplerShared.result; } virtual bool isPointInTriangleMesh(const PxVec3& p); virtual ~TriangleMeshPoissonSampler() { } public: bool pointInMesh(const PxVec3& p); PoissonSamplerShared poissonSamplerShared; //Input const PxVec3* originalPoints; const PxU32* originalTriangles; const PxU32 numOriginalTriangles; PxVec3 max; PxArray<PxVec3> points; PxArray<PxU32> triangles; PxArray<PxU32> triangleMap; PxArray<PxReal> triangleAreaBuffer; PxArray<PxI32> adj; PxArray<Gu::BVHNode> tree; PxHashMap<PxU32, Gu::ClusterApproximation> clusters; //Intermediate data PxArray<ActiveSample> activeSamples; //Output PxArray<PxI32> triangleIds; PxArray<PxVec3> barycentricCoordinates; PX_NOCOPY(TriangleMeshPoissonSampler) }; class ShapePoissonSampler : public PxPoissonSampler { public: ShapePoissonSampler(const PxGeometry& geometry_, const PxTransform& transform_, const PxBounds3& worldBounds_, PxReal r, PxI32 numSampleAttemptsAroundPoint_ = 30, PxU32 maxNumSamples_ = 0); virtual void addSamplesInVolume(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples); virtual void addSamplesInSphere(const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples); virtual void addSamplesInBox(const PxBounds3& axisAlignedBox, const PxQuat& boxOrientation, bool createVolumeSamples); virtual bool setSamplingRadius(PxReal samplingRadius) { return poissonSamplerShared.setSamplingRadius(samplingRadius); } virtual void addSamples(const PxArray<PxVec3>& samples) { poissonSamplerShared.addSamples(samples); } void createVolumeSamples(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, PxReal randomScale, PxReal r, bool addToSparseGrid = true); virtual PxU32 removeSamples(const PxArray<PxVec3>& samples) { return poissonSamplerShared.removeSamples(samples); } virtual const PxArray<PxVec3>& getSamples() const { return poissonSamplerShared.result; } virtual ~ShapePoissonSampler() { } public: PoissonSamplerShared poissonSamplerShared; //Input const PxGeometry& shape; const PxTransform actorGlobalPose; //Intermediate data PxArray<IndexWithNormal> activeSamples; }; bool TriangleMeshPoissonSampler::pointInMesh(const PxVec3& p) { return Gu::computeWindingNumber(tree.begin(), p, clusters, originalTriangles, originalPoints) > 0.5f; } PxPoissonSampler* PxCreateShapeSampler(const PxGeometry& geometry, const PxTransform& transform, const PxBounds3& worldBounds, PxReal r, PxI32 numSampleAttemptsAroundPoint) { return PX_NEW(ShapePoissonSampler)(geometry, transform, worldBounds, r, numSampleAttemptsAroundPoint); } PxTriangleMeshPoissonSampler* PxCreateTriangleMeshSampler(const PxU32* tris, PxU32 numTris, const PxVec3* pts, PxU32 numPts, PxReal r, PxI32 numSampleAttemptsAroundPoint) { return PX_NEW(TriangleMeshPoissonSampler)(tris, numTris, pts, numPts, r, numSampleAttemptsAroundPoint); } PxVec3 computeBarycentricCoordinates(PxVec3 p, const PxVec3& a, PxVec3 b, PxVec3 c) { PxVec4 bary; computeBarycentric(a, b, c, p, bary); return PxVec3(bary.x, bary.y, bary.z); } ShapePoissonSampler::ShapePoissonSampler(const PxGeometry& shape_, const PxTransform& actorGlobalPose_, const PxBounds3& worldBounds_, PxReal r, PxI32 numSampleAttemptsAroundPoint_, PxU32 maxNumSamples_) : shape(shape_), actorGlobalPose(actorGlobalPose_) { poissonSamplerShared.size = worldBounds_.maximum - worldBounds_.minimum; poissonSamplerShared.min = worldBounds_.minimum; poissonSamplerShared.numSampleAttemptsAroundPoint = numSampleAttemptsAroundPoint_; poissonSamplerShared.maxNumSamples = maxNumSamples_; setSamplingRadius(r); } TriangleMeshPoissonSampler::TriangleMeshPoissonSampler(const PxU32* tris, PxU32 numTris, const PxVec3* pts_, PxU32 numPts, PxReal r, PxI32 numSampleAttemptsAroundPoint_, PxU32 maxNumSamples_) : originalPoints(pts_), originalTriangles(tris), numOriginalTriangles(numTris) { poissonSamplerShared.currentSamplingRadius = 0.0f; poissonSamplerShared.numSampleAttemptsAroundPoint = numSampleAttemptsAroundPoint_; poissonSamplerShared.maxNumSamples = maxNumSamples_; getBoundsFromPoints(originalPoints, numPts, poissonSamplerShared.min, max); poissonSamplerShared.size = max - poissonSamplerShared.min; points.assign(originalPoints, originalPoints + numPts); triangles.assign(tris, tris + 3 * numTris); PxRemeshingExt::limitMaxEdgeLength(triangles, points, 2.0f * r, 100, &triangleMap, PxMax(10000u, 4 * numTris)); PxU32 numTriangles = triangles.size() / 3; triangleAreaBuffer.resize(numTriangles); for (PxU32 i = 0; i < numTriangles; ++i) triangleAreaBuffer[i] = triArea(&triangles[3 * i], points.begin()); buildTriangleAdjacency(triangles.begin(), numTriangles, adj); setSamplingRadius(r); } void PoissonSamplerShared::addSamples(const PxArray<PxVec3>& samples) { if (samples.size() > 0) { for (PxU32 i = 0; i < samples.size(); ++i) { result.pushBack(samples[i]); } rebuildSparseGrid(); } } PxI32 PoissonSamplerShared::findSample(const PxVec3& p) { PxI32 x = PxI32((p.x - min.x) / cellSize); PxI32 y = PxI32((p.y - min.y) / cellSize); PxI32 z = PxI32((p.z - min.z) / cellSize); if (x >= resolution.x) x = resolution.x - 1; if (y >= resolution.y) y = resolution.y - 1; if (z >= resolution.z) z = resolution.z - 1; PxReal minDist = FLT_MAX; PxI32 index = -1; for (PxI32 oX = -1; oX <= 1; ++oX) { for (PxI32 oY = -1; oY <= 1; ++oY) { for (PxI32 oZ = -1; oZ <= 1; ++oZ) { const PxI32 xx = x + oX; const PxI32 yy = y + oY; const PxI32 zz = z + oZ; if (xx >= 0 && xx < resolution.x && yy >= 0 && yy < resolution.y && zz >= 0 && zz < resolution.z) { PxI32 cellIndex = xx + resolution.x * yy + (resolution.x * resolution.y) * zz; if ((occupiedCellBits[cellIndex >> 5] & (1u << (cellIndex & 31))) != 0) { const PxPair<const PxI32, SparseGridNode>* it = sparseGrid3D.find(cellIndex); if (it) { const PxReal dist2 = (result[it->second.mPointIndex] - p).magnitudeSquared(); if (dist2 < minDist) { minDist = dist2; index = it->second.mPointIndex; } if (it->second.mExcessStartIndex >= 0) { for (PxI32 i = it->second.mExcessStartIndex; i < it->second.mExcessEndIndex; ++i) { const PxReal dist2_ = (result[excessList[i]] - p).magnitudeSquared(); if (dist2_ < minDist) { minDist = dist2_; index = it->second.mPointIndex; } } } if (minDist == 0.0f) { return index; } } } } } } } return -1; } PxU32 PoissonSamplerShared::removeSamples(const PxArray<PxVec3>& samples) { if (samples.size() > 0) { PxArray<PxI32> samplesToRemove; samplesToRemove.reserve(samples.size()); for (PxU32 i = 0; i < samples.size(); ++i) { PxI32 index = findSample(samples[i]); PX_ASSERT(samples[i] == result[index]); if (index >= 0) samplesToRemove.pushBack(index); } PxSort(samplesToRemove.begin(), samplesToRemove.size()); PxI32 counter = 0; for (PxI32 i = PxI32(samplesToRemove.size()) - 1; i >= 0; --i) { result[samplesToRemove[i]] = result[result.size() - 1 - counter]; ++counter; } result.removeRange(result.size() - counter, counter); rebuildSparseGrid(); return samplesToRemove.size(); } return 0; } bool PoissonSamplerShared::setSamplingRadius(PxReal r) { if (r != currentSamplingRadius) { currentSamplingRadius = r; return rebuildSparseGrid(); } return gridResolutionValid; } bool PoissonSamplerShared::rebuildSparseGrid() { const PxReal dimension = 3.0f; cellSize = (currentSamplingRadius / PxSqrt(dimension)) * 0.9999f; const PxF64 cellsX = PxF64(size.x) / PxF64(cellSize); const PxF64 cellsY = PxF64(size.y) / PxF64(cellSize); const PxF64 cellsZ = PxF64(size.z) / PxF64(cellSize); resolution = Int3(PxMax(1, PxI32(ceil(cellsX))), PxMax(1, PxI32(ceil(cellsY))), PxMax(1, PxI32(ceil(cellsZ)))); const PxF64 numCellsDbl = PxF64(resolution.x) * PxF64(resolution.y) * PxI64(resolution.z); if (numCellsDbl >= (1u << 31) || cellsX >= (1u << 31) || cellsY >= (1u << 31) || cellsZ >= (1u << 31)) { gridResolutionValid = false; PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "Internal grid resolution of sampler too high. Either a smaller mesh or a bigger radius must be used."); return false; } gridResolutionValid = true; PxU32 numCells = PxU32(resolution.x * resolution.y * resolution.z); occupiedCellBits.clear(); occupiedCellBits.resize((numCells + 32 - 1) / 32, 0); sparseGrid3D.clear(); for (PxU32 i = 0; i < result.size(); ++i) preAddPointToSparseGrid(result[i], i); PxI32 cumulativeSum = 0; for (PxHashMap<PxI32, SparseGridNode>::Iterator iter = sparseGrid3D.getIterator(); !iter.done(); ++iter) { if (iter->second.mExcessStartIndex > 0) { PxI32 start = cumulativeSum; cumulativeSum += iter->second.mExcessStartIndex; iter->second.mExcessStartIndex = start; iter->second.mExcessEndIndex = start - 1; } else { iter->second.mExcessStartIndex = -1; } } excessList.resize(cumulativeSum); for (PxU32 i = 0; i < result.size(); ++i) postAddPointToSparseGrid(result[i], i); return true; } bool PoissonSamplerShared::postAddPointToSparseGrid(const PxVec3& p, PxI32 pointIndex) { PxI32 x = PxI32((p.x - min.x) / cellSize); PxI32 y = PxI32((p.y - min.y) / cellSize); PxI32 z = PxI32((p.z - min.z) / cellSize); if (x >= resolution.x) x = resolution.x - 1; if (y >= resolution.y) y = resolution.y - 1; if (z >= resolution.z) z = resolution.z - 1; PxI32 cellIndex = x + resolution.x * y + (resolution.x * resolution.y) * z; SparseGridNode& n = sparseGrid3D[cellIndex]; if (n.mExcessStartIndex < 0) { PX_ASSERT(n.mPointIndex == pointIndex); return true; } if (n.mExcessEndIndex < n.mExcessStartIndex) { PX_ASSERT(n.mPointIndex == pointIndex); n.mExcessEndIndex++; return true; } else { excessList[n.mExcessEndIndex] = pointIndex; n.mExcessEndIndex++; return true; } } bool PoissonSamplerShared::preAddPointToSparseGrid(const PxVec3& p, PxI32 pointIndex) { PxI32 x = PxI32((p.x - min.x) / cellSize); PxI32 y = PxI32((p.y - min.y) / cellSize); PxI32 z = PxI32((p.z - min.z) / cellSize); if (x >= resolution.x) x = resolution.x - 1; if (y >= resolution.y) y = resolution.y - 1; if (z >= resolution.z) z = resolution.z - 1; PxI32 cellIndex = x + resolution.x * y + (resolution.x * resolution.y) * z; if ((occupiedCellBits[cellIndex >> 5] & (1u << (cellIndex & 31))) != 0) { SparseGridNode& n = sparseGrid3D[cellIndex]; n.mExcessStartIndex++; return true; } else { sparseGrid3D.insert(cellIndex, SparseGridNode(pointIndex)); occupiedCellBits[cellIndex >> 5] ^= (1u << (cellIndex & 31)); return true; } } bool PoissonSamplerShared::addPointToSparseGrid(const PxVec3& p, PxI32 pointIndex) { PxI32 x = PxI32((p.x - min.x) / cellSize); PxI32 y = PxI32((p.y - min.y) / cellSize); PxI32 z = PxI32((p.z - min.z) / cellSize); if (x >= resolution.x) x = resolution.x - 1; if (y >= resolution.y) y = resolution.y - 1; if (z >= resolution.z) z = resolution.z - 1; PxI32 cellIndex = x + resolution.x * y + (resolution.x * resolution.y) * z; //if (sparseGrid3D.ContainsKey(cellIndex)) // return false; sparseGrid3D.insert(cellIndex, pointIndex); occupiedCellBits[cellIndex >> 5] ^= (1u << (cellIndex & 31)); return true; } PxReal PoissonSamplerShared::minDistanceToOtherSamplesSquared(const PxVec3& p) const { PxI32 x = PxI32((p.x - min.x) / cellSize); PxI32 y = PxI32((p.y - min.y) / cellSize); PxI32 z = PxI32((p.z - min.z) / cellSize); if (x >= resolution.x) x = resolution.x - 1; if (y >= resolution.y) y = resolution.y - 1; if (z >= resolution.z) z = resolution.z - 1; PxReal minDist = FLT_MAX; for (PxI32 oX = -2; oX <= 2; ++oX) { for (PxI32 oY = -2; oY <= 2; ++oY) { for (PxI32 oZ = -2; oZ <= 2; ++oZ) { const PxI32 xx = x + oX; const PxI32 yy = y + oY; const PxI32 zz = z + oZ; if (xx >= 0 && xx < resolution.x && yy >= 0 && yy < resolution.y && zz >= 0 && zz < resolution.z) { PxI32 cellIndex = xx + resolution.x * yy + (resolution.x * resolution.y) * zz; if ((occupiedCellBits[cellIndex >> 5] & (1u << (cellIndex & 31))) != 0) { const PxPair<const PxI32, SparseGridNode>* it = sparseGrid3D.find(cellIndex); if (it) { const PxReal dist2 = (result[it->second.mPointIndex] - p).magnitudeSquared(); if (dist2 < minDist) minDist = dist2; if (it->second.mExcessStartIndex >= 0) { for (PxI32 i = it->second.mExcessStartIndex; i < it->second.mExcessEndIndex; ++i) { const PxReal dist2_ = (result[excessList[i]] - p).magnitudeSquared(); if (dist2_ < minDist) minDist = dist2_; } } } } } } } } return minDist; } void buildTree(const PxU32* triangles, const PxU32 numTriangles, const PxVec3* points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f) { //Computes a bounding box for every triangle in triangles Gu::AABBTreeBounds boxes; boxes.init(numTriangles); for (PxU32 i = 0; i < numTriangles; ++i) { const PxU32* tri = &triangles[3 * i]; PxBounds3 box = PxBounds3::empty(); box.include(points[tri[0]]); box.include(points[tri[1]]); box.include(points[tri[2]]); box.fattenFast(enlargement); boxes.getBounds()[i] = box; } Gu::buildAABBTree(numTriangles, boxes, tree); } bool TriangleMeshPoissonSampler::isPointInTriangleMesh(const PxVec3& p) { if (tree.size() == 0) { //Lazy initialization buildTree(originalTriangles, numOriginalTriangles, originalPoints, tree); Gu::precomputeClusterInformation(tree.begin(), originalTriangles, numOriginalTriangles, originalPoints, clusters); } return pointInMesh(p); } void TriangleMeshPoissonSampler::addSamplesInBox(const PxBounds3& axisAlignedBox, const PxQuat& boxOrientation, bool createVolumeSamples) { PointInOBBTester pointInOBB(axisAlignedBox.getCenter(), axisAlignedBox.getExtents(), boxOrientation); addSamplesInVolume(pointInOBB, axisAlignedBox.getCenter(), axisAlignedBox.getExtents().magnitude(), createVolumeSamples); } void TriangleMeshPoissonSampler::addSamplesInSphere(const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples) { PointInSphereTester pointInSphere(sphereCenter, sphereRadius); addSamplesInVolume(pointInSphere, sphereCenter, sphereRadius, createVolumeSamples); } //Ideally the sphere center is located on the mesh's surface void TriangleMeshPoissonSampler::addSamplesInVolume(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, bool volumeSamples) { PxArray<PxU32> localActiveSamples; for (PxU32 i = 0; i < activeSamples.size();) { if (activeSamples[i].mIndex >= PxI32(poissonSamplerShared.result.size())) { activeSamples[i] = activeSamples[activeSamples.size() - 1]; activeSamples.remove(activeSamples.size() - 1); continue; } if (pointInSphere(poissonSamplerShared.result[activeSamples[i].mIndex], sphereCenter, sphereRadius)) localActiveSamples.pushBack(i); ++i; } if (localActiveSamples.size() == 0) { const PxReal r = poissonSamplerShared.currentSamplingRadius; //Try to find a seed sample for (PxU32 i = 0; i < triangles.size(); i += 3) { PxVec3 p = (1.0f / 3.0f) * (points[triangles[i]] + points[triangles[i + 1]] + points[triangles[i + 2]]); PxReal triRadius = PxSqrt(PxMax((p - points[triangles[i]]).magnitudeSquared(), PxMax((p - points[triangles[i + 1]]).magnitudeSquared(), (p - points[triangles[i + 2]]).magnitudeSquared()))); PxReal sum = triRadius + sphereRadius; if ((p - sphereCenter).magnitudeSquared() < sum * sum) { bool success = false; for (PxI32 j = 0; j < 30; ++j) { PxVec3 sample = randomPointOnTriangle(poissonSamplerShared.rnd, triangles.begin() + i, points.begin()); if (poissonSamplerShared.minDistanceToOtherSamplesSquared(sample) > r * r) { if (pointInVolume.pointInVolume(sample)) { PxI32 newSampleId = PxI32(poissonSamplerShared.result.size()); PxU32 sampleTriId = i / 3; ActiveSample as; createActiveSample(triangleAreaBuffer, newSampleId, sample, 2 * r, sampleTriId, triangles.begin(), points.begin(), adj, as); localActiveSamples.pushBack(activeSamples.size()); activeSamples.pushBack(as); poissonSamplerShared.result.pushBack(sample); triangleIds.pushBack(triangleMap[sampleTriId]); { const PxU32 triId = triangleMap[sampleTriId]; const PxU32* origTri = &originalTriangles[3 * triId]; barycentricCoordinates.pushBack(computeBarycentricCoordinates(sample, originalPoints[origTri[0]], originalPoints[origTri[1]], originalPoints[origTri[2]])); } poissonSamplerShared.addPointToSparseGrid(sample, newSampleId); success = true; if (poissonSamplerShared.maxNumSamples > 0 && poissonSamplerShared.result.size() >= poissonSamplerShared.maxNumSamples) return; break; } } } if (success) break; } } } //Start poisson sampling while (localActiveSamples.size() > 0) { const PxReal r = poissonSamplerShared.currentSamplingRadius; PxI32 localSampleIndex = poissonSamplerShared.rnd.rand32() % localActiveSamples.size(); PxI32 selectedActiveSample = localActiveSamples[localSampleIndex]; const ActiveSample& s = activeSamples[selectedActiveSample]; bool successDist = false; bool success = false; for (PxI32 i = 0; i < poissonSamplerShared.numSampleAttemptsAroundPoint; ++i) { PxI32 sampleTriId; PxVec3 barycentricCoordinate; PxVec3 sample; if (samplePointInBallOnSurface(poissonSamplerShared.rnd, s.mCumulativeTriangleAreas, points.begin(), triangles.begin(), s.mNearbyTriangles, poissonSamplerShared.result[s.mIndex], r, sample, sampleTriId, 30, &barycentricCoordinate)) { if (poissonSamplerShared.minDistanceToOtherSamplesSquared(sample) > r * r) { successDist = true; if (pointInVolume.pointInVolume(sample)) { PxI32 newSampleId = PxI32(poissonSamplerShared.result.size()); ActiveSample as; createActiveSample(triangleAreaBuffer, newSampleId, sample, 2 * r, sampleTriId, triangles.begin(), points.begin(), adj, as); localActiveSamples.pushBack(activeSamples.size()); activeSamples.pushBack(as); poissonSamplerShared.result.pushBack(sample); triangleIds.pushBack(triangleMap[sampleTriId]); { const PxU32 triId = triangleMap[sampleTriId]; const PxU32* origTri = &originalTriangles[3 * triId]; barycentricCoordinates.pushBack(computeBarycentricCoordinates(sample, originalPoints[origTri[0]], originalPoints[origTri[1]], originalPoints[origTri[2]])); } poissonSamplerShared.addPointToSparseGrid(sample, newSampleId); success = true; if (poissonSamplerShared.maxNumSamples > 0 && poissonSamplerShared.result.size() >= poissonSamplerShared.maxNumSamples) return; break; } } } } if (!successDist) { PxU32 oldId = activeSamples.size() - 1; activeSamples[selectedActiveSample] = activeSamples[activeSamples.size() - 1]; activeSamples.remove(activeSamples.size() - 1); for (PxU32 i = 0; i < localActiveSamples.size(); ++i) { if (localActiveSamples[i] == oldId) { localActiveSamples[i] = selectedActiveSample; break; } } } if (!success) { localActiveSamples[localSampleIndex] = localActiveSamples[localActiveSamples.size() - 1]; localActiveSamples.remove(localActiveSamples.size() - 1); } } if (volumeSamples) { PxReal randomScale = 0.1f; //Relative to particleSpacing PxReal r = (1.0f + 2.0f * randomScale) * 1.001f * poissonSamplerShared.currentSamplingRadius; createVolumeSamples(pointInVolume, sphereCenter, sphereRadius, randomScale, r); } } void TriangleMeshPoissonSampler::createVolumeSamples(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, PxReal randomScale, PxReal r, bool addToSparseGrid) { if (tree.size() == 0) { //Lazy initialization buildTree(originalTriangles, numOriginalTriangles, originalPoints, tree); Gu::precomputeClusterInformation(tree.begin(), originalTriangles, numOriginalTriangles, originalPoints, clusters); } PxVec3 sphereBoxMin = PxVec3(sphereCenter.x - sphereRadius, sphereCenter.y - sphereRadius, sphereCenter.z - sphereRadius) - poissonSamplerShared.min; PxVec3 sphereBoxMax = PxVec3(sphereCenter.x + sphereRadius, sphereCenter.y + sphereRadius, sphereCenter.z + sphereRadius) - poissonSamplerShared.min; Int3 start(PxI32(PxFloor(sphereBoxMin.x / r)), PxI32(PxFloor(sphereBoxMin.y / r)), PxI32(PxFloor(sphereBoxMin.z / r))); Int3 end(PxI32(PxCeil(sphereBoxMax.x / r)), PxI32(PxCeil(sphereBoxMax.y / r)), PxI32(PxCeil(sphereBoxMax.z / r))); for (PxI32 x = start.x; x < end.x; ++x) { for (PxI32 y = start.y; y < end.y; ++y) { for (PxI32 z = start.z; z < end.z; ++z) { PxVec3 p = poissonSamplerShared.min + PxVec3(x * r, y * r, z * r); p += PxVec3(poissonSamplerShared.rnd.randomFloat32(-randomScale, randomScale) * poissonSamplerShared.currentSamplingRadius, poissonSamplerShared.rnd.randomFloat32(-randomScale, randomScale) * poissonSamplerShared.currentSamplingRadius, poissonSamplerShared.rnd.randomFloat32(-randomScale, randomScale) * poissonSamplerShared.currentSamplingRadius); if (pointInVolume.pointInVolume(p)) { if (poissonSamplerShared.minDistanceToOtherSamplesSquared(p) > poissonSamplerShared.currentSamplingRadius * poissonSamplerShared.currentSamplingRadius && pointInMesh(p)) { PxI32 newSampleId = PxI32(poissonSamplerShared.result.size()); poissonSamplerShared.result.pushBack(p); if (addToSparseGrid) poissonSamplerShared.addPointToSparseGrid(p, newSampleId); triangleIds.pushBack(-1); barycentricCoordinates.pushBack(PxVec3(0.0f)); if (poissonSamplerShared.maxNumSamples > 0 && poissonSamplerShared.result.size() >= poissonSamplerShared.maxNumSamples) return; } } } } } } PxU32 PX_FORCE_INLINE raycast(const PxGeometry& geometry, const PxTransform& transform, const PxVec3& rayOrigin, const PxVec3& rayDir, PxReal maxDist, PxHitFlags hitFlags, PxU32 maxHits, PxRaycastHit* rayHits) { return PxGeometryQuery::raycast( rayOrigin, rayDir, geometry, transform, maxDist, hitFlags, maxHits, rayHits); } bool PX_FORCE_INLINE pointInShape(const PxGeometry& geometry, const PxTransform& transform, const PxVec3& p) { //This is a bit a work-around solution: When a raycast starts inside of a shape, it returns the ray origin as hit point PxRaycastHit hit; return PxGeometryQuery::raycast(p, PxVec3(1.0f, 0.0f, 0.0f), geometry, transform, 1.0f, PxHitFlag::ePOSITION, 1, &hit) > 0 && hit.position == p; } bool projectionCallback(PxReal targetDistance, const PxGeometry& geometry, const PxTransform& transform, PxReal boundingBoxDiagonalLength, const PxVec3& p, const PxVec3& n, PointWithNormal& result) { PxRaycastHit hitPos; PxU32 numHitsPos = raycast(geometry, transform, p - boundingBoxDiagonalLength * n, n, 2 * boundingBoxDiagonalLength, PxHitFlag::eMESH_BOTH_SIDES | PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, 1, &hitPos); PxRaycastHit hitNeg; PxU32 numHitsNeg = raycast(geometry, transform, p + boundingBoxDiagonalLength * n, -n, 2 * boundingBoxDiagonalLength, PxHitFlag::eMESH_BOTH_SIDES | PxHitFlag::ePOSITION | PxHitFlag::eNORMAL, 1, &hitNeg); targetDistance *= 0.5f; if (numHitsPos && numHitsNeg) { if (PxAbs((hitPos.position - p).magnitude() - targetDistance) < PxAbs((hitNeg.position - p).magnitude() - targetDistance)) result = PointWithNormal(hitPos.position, hitPos.normal); else result = PointWithNormal(hitNeg.position, hitNeg.normal); return true; } else if (numHitsPos) { result = PointWithNormal(hitPos.position, hitPos.normal); return true; } else if (numHitsNeg) { result = PointWithNormal(hitNeg.position, hitNeg.normal); return true; } return false; } PxVec3 randomDirection(BasicRandom& rnd) { PxVec3 dir; do { dir = PxVec3((rnd.rand(0.0f, 1.0f) - 0.5f), (rnd.rand(0.0f, 1.0f) - 0.5f), (rnd.rand(0.0f, 1.0f) - 0.5f)); } while (dir.magnitudeSquared() < 1e-8f); return dir.getNormalized(); } PxVec3 getPerpendicularVectorNormalized(const PxVec3& dir) { PxReal x = PxAbs(dir.x); PxReal y = PxAbs(dir.y); PxReal z = PxAbs(dir.z); if (x >= y && x >= z) return dir.cross(PxVec3(0, 1, 0)).getNormalized(); else if (y >= x && y >= z) return dir.cross(PxVec3(0, 0, 1)).getNormalized(); else return dir.cross(PxVec3(1, 0, 0)).getNormalized(); } PxVec3 randomPointOnDisc(BasicRandom& rnd, const PxVec3& point, const PxVec3& normal, PxReal radius, PxReal rUpper) { //TODO: Use better random number generator PxReal r = radius + rnd.rand(0.0f, 1.0f) * (rUpper - radius); PxVec3 x = getPerpendicularVectorNormalized(normal); PxVec3 y = normal.cross(x).getNormalized(); PxReal angle = rnd.rand(0.0f, 1.0f) * (2.0f * 3.1415926535898f); return point + x * (r * PxCos(angle)) + y * (r * PxSin(angle)); } bool samplePointInBallOnSurface(BasicRandom& rnd, const PxGeometry& shape, const PxTransform& actorGlobalPose, const PxReal diagonalLength, const PxVec3& point, const PxVec3& normal, PxReal radius, PointWithNormal& sample, PxI32 numAttempts = 30) { for (PxI32 i = 0; i < numAttempts; ++i) { PxVec3 p = randomPointOnDisc(rnd, point, normal, radius, 2 * radius); //Distort the direction of the normal a bit PxVec3 n = normal; do { n.x += 0.5f * (rnd.rand(0.0f, 1.0f) - 0.5f); n.y += 0.5f * (rnd.rand(0.0f, 1.0f) - 0.5f); n.z += 0.5f * (rnd.rand(0.0f, 1.0f) - 0.5f); } while (n.magnitudeSquared() < 1e-8f); n.normalize(); if (projectionCallback(radius, shape, actorGlobalPose, diagonalLength, p, n, sample)) { PxReal d2 = (sample.mPoint - point).magnitudeSquared(); if (d2 >= radius * radius && d2 < 4 * radius * radius) return true; } } return false; } void ShapePoissonSampler::addSamplesInBox(const PxBounds3& axisAlignedBox, const PxQuat& boxOrientation, bool createVolumeSamples) { PointInOBBTester pointInOBB(axisAlignedBox.getCenter(), axisAlignedBox.getExtents(), boxOrientation); addSamplesInVolume(pointInOBB, axisAlignedBox.getCenter(), axisAlignedBox.getExtents().magnitude(), createVolumeSamples); } void ShapePoissonSampler::addSamplesInSphere(const PxVec3& sphereCenter, PxReal sphereRadius, bool createVolumeSamples) { PointInSphereTester pointInSphere(sphereCenter, sphereRadius); addSamplesInVolume(pointInSphere, sphereCenter, sphereRadius, createVolumeSamples); } void ShapePoissonSampler::addSamplesInVolume(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, bool volumeSamples) { PxReal boundingBoxDiagonalLength = poissonSamplerShared.size.magnitude(); PxArray<PxU32> localActiveSamples; for (PxU32 i = 0; i < activeSamples.size();) { if (activeSamples[i].mIndex >= PxI32(poissonSamplerShared.result.size())) { activeSamples[i] = activeSamples[activeSamples.size() - 1]; activeSamples.remove(activeSamples.size() - 1); continue; } if (pointInSphere(poissonSamplerShared.result[activeSamples[i].mIndex], sphereCenter, sphereRadius)) localActiveSamples.pushBack(i); ++i; } if (localActiveSamples.size() == 0) { PxVec3 center = poissonSamplerShared.min + 0.5f * poissonSamplerShared.size;; PointWithNormal sample; PxVec3 arbitrarySeedPointOnSurface; PxVec3 reference = sphereCenter - center; reference.normalizeSafe(); for (PxI32 i = 0; i < 1000; ++i) { PxVec3 dir = /*reference + 0.5f**/randomDirection(poissonSamplerShared.rnd); dir.normalize(); if (projectionCallback(poissonSamplerShared.currentSamplingRadius, shape, actorGlobalPose, boundingBoxDiagonalLength, sphereCenter, dir, sample)) { if (poissonSamplerShared.minDistanceToOtherSamplesSquared(sample.mPoint) > poissonSamplerShared.currentSamplingRadius * poissonSamplerShared.currentSamplingRadius) { if (pointInVolume.pointInVolume(sample.mPoint)) { PxI32 newSampleId = PxI32(poissonSamplerShared.result.size()); localActiveSamples.pushBack(activeSamples.size()); activeSamples.pushBack(IndexWithNormal(newSampleId, sample.mNormal)); poissonSamplerShared.result.pushBack(sample.mPoint); poissonSamplerShared.addPointToSparseGrid(sample.mPoint, newSampleId); if (poissonSamplerShared.maxNumSamples > 0 && poissonSamplerShared.result.size() >= poissonSamplerShared.maxNumSamples) return; break; } } } } } while (localActiveSamples.size() > 0) { PxI32 localSampleIndex = poissonSamplerShared.rnd.rand32() % localActiveSamples.size(); PxI32 selectedActiveSample = localActiveSamples[localSampleIndex]; const IndexWithNormal& s = activeSamples[selectedActiveSample]; bool successDist = false; bool success = false; for (PxI32 i = 0; i < poissonSamplerShared.numSampleAttemptsAroundPoint; ++i) { PointWithNormal sample; if (samplePointInBallOnSurface(poissonSamplerShared.rnd, shape, actorGlobalPose, boundingBoxDiagonalLength, poissonSamplerShared.result[s.mIndex], s.mNormal, poissonSamplerShared.currentSamplingRadius, sample)) { if (poissonSamplerShared.minDistanceToOtherSamplesSquared(sample.mPoint) > poissonSamplerShared.currentSamplingRadius * poissonSamplerShared.currentSamplingRadius) { successDist = true; if (pointInVolume.pointInVolume(sample.mPoint)) { successDist = true; PxI32 newSampleId = PxI32(poissonSamplerShared.result.size()); localActiveSamples.pushBack(activeSamples.size()); activeSamples.pushBack(IndexWithNormal(newSampleId, sample.mNormal)); poissonSamplerShared.result.pushBack(sample.mPoint); poissonSamplerShared.addPointToSparseGrid(sample.mPoint, newSampleId); success = true; if (poissonSamplerShared.maxNumSamples > 0 && poissonSamplerShared.result.size() >= poissonSamplerShared.maxNumSamples) return; break; } } } } if (!successDist) { PxU32 oldId = activeSamples.size() - 1; activeSamples[selectedActiveSample] = activeSamples[activeSamples.size() - 1]; activeSamples.remove(activeSamples.size() - 1); for (PxU32 i = 0; i < localActiveSamples.size(); ++i) { if (localActiveSamples[i] == oldId) { localActiveSamples[i] = selectedActiveSample; break; } } } if (!success) { localActiveSamples[localSampleIndex] = localActiveSamples[localActiveSamples.size() - 1]; localActiveSamples.remove(localActiveSamples.size() - 1); } } if (volumeSamples) { PxReal randomScale = 0.1f; //Relative to particleSpacing PxReal r = (1.0f + 2.0f * randomScale) * 1.001f * poissonSamplerShared.currentSamplingRadius; createVolumeSamples(pointInVolume, sphereCenter, sphereRadius, randomScale, r); } } void ShapePoissonSampler::createVolumeSamples(const PointInVolumeTester& pointInVolume, const PxVec3& sphereCenter, PxReal sphereRadius, PxReal randomScale, PxReal r, bool addToSparseGrid) { PxVec3 sphereBoxMin = PxVec3(sphereCenter.x - sphereRadius, sphereCenter.y - sphereRadius, sphereCenter.z - sphereRadius) - poissonSamplerShared.min; PxVec3 sphereBoxMax = PxVec3(sphereCenter.x + sphereRadius, sphereCenter.y + sphereRadius, sphereCenter.z + sphereRadius) - poissonSamplerShared.min; Int3 start(PxI32(PxFloor(sphereBoxMin.x / r)), PxI32(PxFloor(sphereBoxMin.y / r)), PxI32(PxFloor(sphereBoxMin.z / r))); Int3 end(PxI32(PxCeil(sphereBoxMax.x / r)), PxI32(PxCeil(sphereBoxMax.y / r)), PxI32(PxCeil(sphereBoxMax.z / r))); for (PxI32 x = start.x; x < end.x; ++x) { for (PxI32 y = start.y; y < end.y; ++y) { for (PxI32 z = start.z; z < end.z; ++z) { PxVec3 p = poissonSamplerShared.min + PxVec3(x * r, y * r, z * r); p += PxVec3(poissonSamplerShared.rnd.randomFloat32(-randomScale, randomScale) * poissonSamplerShared.currentSamplingRadius, poissonSamplerShared.rnd.randomFloat32(-randomScale, randomScale) * poissonSamplerShared.currentSamplingRadius, poissonSamplerShared.rnd.randomFloat32(-randomScale, randomScale) * poissonSamplerShared.currentSamplingRadius); if (pointInVolume.pointInVolume(p) && pointInShape(shape, actorGlobalPose, p)) { if (poissonSamplerShared.minDistanceToOtherSamplesSquared(p) > poissonSamplerShared.currentSamplingRadius * poissonSamplerShared.currentSamplingRadius) { PxI32 newSampleId = PxI32(poissonSamplerShared.result.size()); poissonSamplerShared.result.pushBack(p); if (addToSparseGrid) poissonSamplerShared.addPointToSparseGrid(p, newSampleId); if (poissonSamplerShared.maxNumSamples > 0 && poissonSamplerShared.result.size() >= poissonSamplerShared.maxNumSamples) return; } } } } } } //Use for triangle meshes //https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf bool PxSamplingExt::poissonSample(const PxSimpleTriangleMesh& mesh, PxReal r, PxArray<PxVec3>& result, PxReal rVolume, PxArray<PxI32>* triangleIds, PxArray<PxVec3>* barycentricCoordinates, const PxBounds3* axisAlignedBox, const PxQuat* boxOrientation, PxU32 maxNumSamples, PxU32 numSampleAttemptsAroundPoint) { TriangleMeshPoissonSampler sampler(reinterpret_cast<const PxU32*>(mesh.triangles.data), mesh.triangles.count, reinterpret_cast<const PxVec3*>(mesh.points.data), mesh.points.count, r, numSampleAttemptsAroundPoint, maxNumSamples); if (!sampler.poissonSamplerShared.gridResolutionValid) { return false; } PxVec3 center = 0.5f*(sampler.max + sampler.poissonSamplerShared.min); PxReal boundingSphereRadius = 1.001f * (sampler.max - sampler.poissonSamplerShared.min).magnitude() * 0.5f; if (axisAlignedBox == NULL || boxOrientation == NULL) { sampler.addSamplesInSphere(center, boundingSphereRadius, false); if (rVolume > 0.0f) { AlwaysInsideTester tester; sampler.createVolumeSamples(tester, center, boundingSphereRadius, 0.1f, rVolume, false); } } else { sampler.addSamplesInBox(*axisAlignedBox, *boxOrientation, false); if (rVolume > 0.0f) { PointInOBBTester tester(axisAlignedBox->getCenter(), axisAlignedBox->getExtents(), *boxOrientation); sampler.createVolumeSamples(tester, center, boundingSphereRadius, 0.1f, rVolume, false); } } result = sampler.getSamples(); if (triangleIds) *triangleIds = sampler.getSampleTriangleIds(); if (barycentricCoordinates) *barycentricCoordinates = sampler.getSampleBarycentrics(); return true; } bool PxSamplingExt::poissonSample(const PxGeometry& geometry, const PxTransform& transform, const PxBounds3& worldBounds, PxReal r, PxArray<PxVec3>& result, PxReal rVolume, const PxBounds3* axisAlignedBox, const PxQuat* boxOrientation, PxU32 maxNumSamples, PxU32 numSampleAttemptsAroundPoint) { PxVec3 center = worldBounds.getCenter(); ShapePoissonSampler sampler(geometry, transform, worldBounds, r, numSampleAttemptsAroundPoint, maxNumSamples); PxReal boundingSphereRadius = 1.001f * worldBounds.getExtents().magnitude(); if (!sampler.poissonSamplerShared.gridResolutionValid) return false; if (axisAlignedBox == NULL || boxOrientation == NULL) { sampler.addSamplesInSphere(center, worldBounds.getExtents().magnitude() * 1.001f, false); if (rVolume > 0.0f) { AlwaysInsideTester tester; sampler.createVolumeSamples(tester, center, boundingSphereRadius, 0.1f, rVolume, false); } } else { sampler.addSamplesInBox(*axisAlignedBox, *boxOrientation, false); if (rVolume > 0.0f) { PointInOBBTester tester(axisAlignedBox->getCenter(), axisAlignedBox->getExtents(), *boxOrientation); sampler.createVolumeSamples(tester, center, boundingSphereRadius, 0.1f, rVolume, false); } } result = sampler.getSamples(); return true; } }
50,931
C++
33.251513
235
0.700457
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDistanceJoint.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 EXT_DISTANCE_JOINT_H #define EXT_DISTANCE_JOINT_H #include "common/PxTolerancesScale.h" #include "extensions/PxDistanceJoint.h" #include "ExtJoint.h" #include "foundation/PxUserAllocated.h" #include "CmUtils.h" namespace physx { struct PxDistanceJointGeneratedValues; namespace Ext { struct DistanceJointData : public JointData { PxReal minDistance; PxReal maxDistance; PxReal tolerance; PxReal stiffness; PxReal damping; PxDistanceJointFlags jointFlags; }; typedef JointT<PxDistanceJoint, DistanceJointData, PxDistanceJointGeneratedValues> DistanceJointT; class DistanceJoint : public DistanceJointT { public: // PX_SERIALIZATION DistanceJoint(PxBaseFlags baseFlags) : DistanceJointT(baseFlags) {} void resolveReferences(PxDeserializationContext& context); static DistanceJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<DistanceJoint>(address, context); } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION DistanceJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); // PxDistanceJoint virtual PxReal getDistance() const PX_OVERRIDE; virtual void setMinDistance(PxReal distance) PX_OVERRIDE; virtual PxReal getMinDistance() const PX_OVERRIDE; virtual void setMaxDistance(PxReal distance) PX_OVERRIDE; virtual PxReal getMaxDistance() const PX_OVERRIDE; virtual void setTolerance(PxReal tolerance) PX_OVERRIDE; virtual PxReal getTolerance() const PX_OVERRIDE; virtual void setStiffness(PxReal spring) PX_OVERRIDE; virtual PxReal getStiffness() const PX_OVERRIDE; virtual void setDamping(PxReal damping) PX_OVERRIDE; virtual PxReal getDamping() const PX_OVERRIDE; virtual void setDistanceJointFlags(PxDistanceJointFlags flags) PX_OVERRIDE; virtual void setDistanceJointFlag(PxDistanceJointFlag::Enum flag, bool value) PX_OVERRIDE; virtual PxDistanceJointFlags getDistanceJointFlags() const PX_OVERRIDE; //~PxDistanceJoint // PxConstraintConnector virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE; #if PX_SUPPORT_OMNI_PVD virtual void updateOmniPvdProperties() const PX_OVERRIDE; #endif //~PxConstraintConnector }; } // namespace Ext } // namespace physx #endif
4,130
C
42.03125
164
0.765617
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultCpuDispatcher.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 "ExtDefaultCpuDispatcher.h" #include "ExtCpuWorkerThread.h" #include "ExtTaskQueueHelper.h" #include "foundation/PxString.h" using namespace physx; PxDefaultCpuDispatcher* physx::PxDefaultCpuDispatcherCreate(PxU32 numThreads, PxU32* affinityMasks, PxDefaultCpuDispatcherWaitForWorkMode::Enum mode, PxU32 yieldProcessorCount) { return PX_NEW(Ext::DefaultCpuDispatcher)(numThreads, affinityMasks, mode, yieldProcessorCount); } #if !PX_SWITCH void Ext::DefaultCpuDispatcher::getAffinityMasks(PxU32* affinityMasks, PxU32 threadCount) { for(PxU32 i=0; i < threadCount; i++) { affinityMasks[i] = 0; } } #endif Ext::DefaultCpuDispatcher::DefaultCpuDispatcher(PxU32 numThreads, PxU32* affinityMasks, PxDefaultCpuDispatcherWaitForWorkMode::Enum mode, PxU32 yieldProcessorCount) : mQueueEntryPool(EXT_TASK_QUEUE_ENTRY_POOL_SIZE, "QueueEntryPool"), mNumThreads(numThreads), mShuttingDown(false) #if PX_PROFILE ,mRunProfiled(true) #else ,mRunProfiled(false) #endif , mWaitForWorkMode(mode) , mYieldProcessorCount(yieldProcessorCount) { PX_CHECK_MSG((((PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_PROCESSOR == mWaitForWorkMode) && (mYieldProcessorCount > 0)) || (((PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_THREAD == mWaitForWorkMode) || (PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == mWaitForWorkMode)) && (0 == mYieldProcessorCount))), "Illegal yield processor count for chosen execute mode"); PxU32* defaultAffinityMasks = NULL; if(!affinityMasks) { defaultAffinityMasks = PX_ALLOCATE(PxU32, numThreads, "ThreadAffinityMasks"); getAffinityMasks(defaultAffinityMasks, numThreads); affinityMasks = defaultAffinityMasks; } // initialize threads first, then start mWorkerThreads = PX_ALLOCATE(CpuWorkerThread, numThreads, "CpuWorkerThread"); const PxU32 nameLength = 32; mThreadNames = PX_ALLOCATE(PxU8, nameLength * numThreads, "CpuWorkerThreadName"); if (mWorkerThreads) { for(PxU32 i = 0; i < numThreads; ++i) { PX_PLACEMENT_NEW(mWorkerThreads+i, CpuWorkerThread)(); mWorkerThreads[i].initialize(this); } for(PxU32 i = 0; i < numThreads; ++i) { if (mThreadNames) { char* threadName = reinterpret_cast<char*>(mThreadNames + (i*nameLength)); Pxsnprintf(threadName, nameLength, "PxWorker%02d", i); mWorkerThreads[i].setName(threadName); } mWorkerThreads[i].setAffinityMask(affinityMasks[i]); mWorkerThreads[i].start(PxThread::getDefaultStackSize()); } PX_FREE(defaultAffinityMasks); } else { mNumThreads = 0; } } Ext::DefaultCpuDispatcher::~DefaultCpuDispatcher() { for(PxU32 i = 0; i < mNumThreads; ++i) mWorkerThreads[i].signalQuit(); mShuttingDown = true; if(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == mWaitForWorkMode) mWorkReady.set(); for(PxU32 i = 0; i < mNumThreads; ++i) mWorkerThreads[i].waitForQuit(); for(PxU32 i = 0; i < mNumThreads; ++i) mWorkerThreads[i].~CpuWorkerThread(); PX_FREE(mWorkerThreads); PX_FREE(mThreadNames); } void Ext::DefaultCpuDispatcher::release() { PX_DELETE_THIS; } void Ext::DefaultCpuDispatcher::submitTask(PxBaseTask& task) { if(!mNumThreads) { // no worker threads, run directly runTask(task); task.release(); return; } // TODO: Could use TLS to make this more efficient const PxThread::Id currentThread = PxThread::getId(); const PxU32 nbThreads = mNumThreads; for(PxU32 i=0; i<nbThreads; ++i) { if(mWorkerThreads[i].tryAcceptJobToLocalQueue(task, currentThread)) { if(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == mWaitForWorkMode) { return mWorkReady.set(); } else { PX_ASSERT(PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_PROCESSOR == mWaitForWorkMode || PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_THREAD == mWaitForWorkMode); return; } } } SharedQueueEntry* entry = mQueueEntryPool.getEntry(&task); if(entry) { mJobList.push(*entry); if(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == mWaitForWorkMode) mWorkReady.set(); } } PxBaseTask* Ext::DefaultCpuDispatcher::fetchNextTask() { PxBaseTask* task = getJob(); if(!task) task = stealJob(); return task; } PxBaseTask* Ext::DefaultCpuDispatcher::getJob() { return TaskQueueHelper::fetchTask(mJobList, mQueueEntryPool); } PxBaseTask* Ext::DefaultCpuDispatcher::stealJob() { const PxU32 nbThreads = mNumThreads; for(PxU32 i=0; i<nbThreads; ++i) { PxBaseTask* ret = mWorkerThreads[i].giveUpJob(); if(ret) return ret; } return NULL; } void Ext::DefaultCpuDispatcher::resetWakeSignal() { PX_ASSERT(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == mWaitForWorkMode); mWorkReady.reset(); // The code below is necessary to avoid deadlocks on shut down. // A thread usually loops as follows: // while quit is not signaled // 1) reset wake signal // 2) fetch work // 3) if work -> process // 4) else -> wait for wake signal // // If a thread reaches 1) after the thread pool signaled wake up, // the wake up sync gets reset and all other threads which have not // passed 4) already will wait forever. // The code below makes sure that on shutdown, the wake up signal gets // sent again after it was reset // if (mShuttingDown) mWorkReady.set(); }
6,923
C++
30.761468
253
0.744764
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSceneQueryExt.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 "extensions/PxSceneQueryExt.h" #include "geometry/PxGeometryHelpers.h" #include "foundation/PxAllocatorCallback.h" #include "CmUtils.h" #include "foundation/PxAllocator.h" using namespace physx; bool PxSceneQueryExt::raycastAny( const PxScene& scene, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxSceneQueryHit& hit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall, const PxSceneQueryCache* cache) { PxSceneQueryFilterData fdAny = filterData; fdAny.flags |= PxQueryFlag::eANY_HIT; PxRaycastBuffer buf; scene.raycast(origin, unitDir, distance, buf, PxHitFlag::eANY_HIT, fdAny, filterCall, cache); hit = buf.block; return buf.hasBlock; } bool PxSceneQueryExt::raycastSingle(const PxScene& scene, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxSceneQueryFlags outputFlags, PxRaycastHit& hit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall, const PxSceneQueryCache* cache) { PxRaycastBuffer buf; PxQueryFilterData fd1 = filterData; scene.raycast(origin, unitDir, distance, buf, outputFlags, fd1, filterCall, cache); hit = buf.block; return buf.hasBlock; } PxI32 PxSceneQueryExt::raycastMultiple( const PxScene& scene, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxSceneQueryFlags outputFlags, PxRaycastHit* hitBuffer, PxU32 hitBufferSize, bool& blockingHit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall, const PxSceneQueryCache* cache) { PxRaycastBuffer buf(hitBuffer, hitBufferSize); PxQueryFilterData fd1 = filterData; scene.raycast(origin, unitDir, distance, buf, outputFlags, fd1, filterCall, cache); blockingHit = buf.hasBlock; if(blockingHit) { if(buf.nbTouches < hitBufferSize) { hitBuffer[buf.nbTouches] = buf.block; return PxI32(buf.nbTouches+1); } else // overflow, drop the last touch { hitBuffer[hitBufferSize-1] = buf.block; return -1; } } else // no block return PxI32(buf.nbTouches); } bool PxSceneQueryExt::sweepAny( const PxScene& scene, const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSceneQueryFlags queryFlags, PxSceneQueryHit& hit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall, const PxSceneQueryCache* cache, PxReal inflation) { PxSceneQueryFilterData fdAny = filterData; fdAny.flags |= PxQueryFlag::eANY_HIT; PxSweepBuffer buf; scene.sweep(geometry, pose, unitDir, distance, buf, queryFlags|PxHitFlag::eANY_HIT, fdAny, filterCall, cache, inflation); hit = buf.block; return buf.hasBlock; } bool PxSceneQueryExt::sweepSingle( const PxScene& scene, const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSceneQueryFlags outputFlags, PxSweepHit& hit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall, const PxSceneQueryCache* cache, PxReal inflation) { PxSweepBuffer buf; PxQueryFilterData fd1 = filterData; scene.sweep(geometry, pose, unitDir, distance, buf, outputFlags, fd1, filterCall, cache, inflation); hit = buf.block; return buf.hasBlock; } PxI32 PxSceneQueryExt::sweepMultiple( const PxScene& scene, const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSceneQueryFlags outputFlags, PxSweepHit* hitBuffer, PxU32 hitBufferSize, bool& blockingHit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall, const PxSceneQueryCache* cache, PxReal inflation) { PxQueryFilterData fd1 = filterData; PxSweepBuffer buf(hitBuffer, hitBufferSize); scene.sweep(geometry, pose, unitDir, distance, buf, outputFlags, fd1, filterCall, cache, inflation); blockingHit = buf.hasBlock; if(blockingHit) { if(buf.nbTouches < hitBufferSize) { hitBuffer[buf.nbTouches] = buf.block; return PxI32(buf.nbTouches+1); } else // overflow, drop the last touch { hitBuffer[hitBufferSize-1] = buf.block; return -1; } } else // no block return PxI32(buf.nbTouches); } PxI32 PxSceneQueryExt::overlapMultiple( const PxScene& scene, const PxGeometry& geometry, const PxTransform& pose, PxOverlapHit* hitBuffer, PxU32 hitBufferSize, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall) { PxQueryFilterData fd1 = filterData; fd1.flags |= PxQueryFlag::eNO_BLOCK; PxOverlapBuffer buf(hitBuffer, hitBufferSize); scene.overlap(geometry, pose, buf, fd1, filterCall); if(buf.hasBlock) { if(buf.nbTouches < hitBufferSize) { hitBuffer[buf.nbTouches] = buf.block; return PxI32(buf.nbTouches+1); } else // overflow, drop the last touch { hitBuffer[hitBufferSize-1] = buf.block; return -1; } } else // no block return PxI32(buf.nbTouches); } bool PxSceneQueryExt::overlapAny( const PxScene& scene, const PxGeometry& geometry, const PxTransform& pose, PxOverlapHit& hit, const PxSceneQueryFilterData& filterData, PxSceneQueryFilterCallback* filterCall) { PxSceneQueryFilterData fdAny = filterData; fdAny.flags |= (PxQueryFlag::eANY_HIT | PxQueryFlag::eNO_BLOCK); PxOverlapBuffer buf; scene.overlap(geometry, pose, buf, fdAny, filterCall); hit = buf.block; return buf.hasBlock; } namespace { struct Raycast { PxVec3 origin; PxVec3 unitDir; PxReal distance; PxHitFlags hitFlags; PxQueryFilterData filterData; const PxQueryCache* cache; }; struct Sweep { PxGeometryHolder geometry; PxTransform pose; PxVec3 unitDir; PxReal distance; PxHitFlags hitFlags; PxQueryFilterData filterData; const PxQueryCache* cache; PxReal inflation; }; struct Overlap { PxGeometryHolder geometry; PxTransform pose; PxQueryFilterData filterData; const PxQueryCache* cache; }; } template<typename HitType> struct NpOverflowBuffer : PxHitBuffer<HitType> { bool overflow; bool processCalled; PxU32 saveNbTouches; NpOverflowBuffer(HitType* hits, PxU32 count) : PxHitBuffer<HitType>(hits, count), overflow(false), processCalled(false), saveNbTouches(0) { } virtual PxAgain processTouches(const HitType* /*hits*/, PxU32 /*count*/) { if (processCalled) return false; saveNbTouches = this->nbTouches; processCalled = true; return true; } virtual void finalizeQuery() { if (processCalled) { overflow = (this->nbTouches > 0); this->nbTouches = saveNbTouches; } } }; class ExtBatchQuery : public PxBatchQueryExt { PX_NOCOPY(ExtBatchQuery) public: ExtBatchQuery( const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, PxRaycastBuffer* raycastBuffers, Raycast* raycastQueries, const PxU32 maxNbRaycasts, PxRaycastHit* raycastTouches, const PxU32 maxNbRaycastTouches, PxSweepBuffer* sweepBuffers, Sweep* sweepQueries, const PxU32 maxNbSweeps, PxSweepHit* sweepTouches, const PxU32 maxNbSweepTouches, PxOverlapBuffer* overlapBuffers, Overlap* overlapQueries, const PxU32 maxNbOverlaps, PxOverlapHit* overlapTouches, const PxU32 maxNbOverlapTouches); ~ExtBatchQuery() {} virtual void release(); virtual PxRaycastBuffer* raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, const PxU16 maxNbTouches, PxHitFlags hitFlags = PxHitFlags(PxHitFlag::eDEFAULT), const PxQueryFilterData& filterData = PxQueryFilterData(), const PxQueryCache* cache = NULL); virtual PxSweepBuffer* sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, const PxU16 maxNbTouches, PxHitFlags hitFlags = PxHitFlags(PxHitFlag::eDEFAULT), const PxQueryFilterData& filterData = PxQueryFilterData(), const PxQueryCache* cache = NULL, const PxReal inflation = 0.f); virtual PxOverlapBuffer* overlap( const PxGeometry& geometry, const PxTransform& pose, PxU16 maxNbTouches = 0, const PxQueryFilterData& filterData = PxQueryFilterData(), const PxQueryCache* cache = NULL); virtual void execute(); private: template<typename HitType, typename QueryType> struct Query { PxHitBuffer<HitType>* mBuffers; QueryType* mQueries; PxU32 mMaxNbBuffers; HitType* mTouches; PxU32 mMaxNbTouches; PxU32 mBufferTide; Query() : mBuffers(NULL), mQueries(NULL), mMaxNbBuffers(0), mTouches(NULL), mMaxNbTouches(0), mBufferTide(0) { } Query(PxHitBuffer<HitType>* buffers, QueryType* queries, const PxU32 maxNbBuffers, HitType* touches, const PxU32 maxNbTouches) : mBuffers(buffers), mQueries(queries), mMaxNbBuffers(maxNbBuffers), mTouches(touches), mMaxNbTouches(maxNbTouches), mBufferTide(0) { for (PxU32 i = 0; i < mMaxNbBuffers; i++) { mBuffers[i].hasBlock = false; mBuffers[i].nbTouches = 0; } } PxHitBuffer<HitType>* addQuery(const QueryType& query, const PxU32 maxNbTouches) { if ((mBufferTide + 1) > mMaxNbBuffers) { //Ran out of queries. return NULL; } PxHitBuffer<HitType>* buffer = mBuffers + mBufferTide; buffer->touches = NULL; buffer->maxNbTouches = maxNbTouches; buffer->hasBlock = false; buffer->nbTouches = 0xffffffff; mQueries[mBufferTide] = query; mBufferTide++; return buffer; } static void performQuery(const PxScene& scene, const Raycast& query, NpOverflowBuffer<PxRaycastHit>& hitBuffer, PxQueryFilterCallback* qfcb) { scene.raycast( query.origin, query.unitDir, query.distance, hitBuffer, query.hitFlags, query.filterData, qfcb, query.cache); } static void performQuery(const PxScene& scene, const Sweep& query, NpOverflowBuffer<PxSweepHit>& hitBuffer, PxQueryFilterCallback* qfcb) { scene.sweep( query.geometry.any(), query.pose, query.unitDir, query.distance, hitBuffer, query.hitFlags, query.filterData, qfcb, query.cache, query.inflation); } static void performQuery(const PxScene& scene, const Overlap& query, NpOverflowBuffer<PxOverlapHit>& hitBuffer, PxQueryFilterCallback* qfcb) { scene.overlap( query.geometry.any(), query.pose, hitBuffer, query.filterData, qfcb, query.cache); } void execute(const PxScene& scene, PxQueryFilterCallback* qfcb) { PxU32 touchesTide = 0; for (PxU32 i = 0; i < mBufferTide; i++) { PX_ASSERT(0xffffffff == mBuffers[i].nbTouches); PX_ASSERT(0xffffffff != mBuffers[i].maxNbTouches); PX_ASSERT(!mBuffers[i].touches); bool noTouchesRemaining = false; if (mBuffers[i].maxNbTouches > 0) { if (touchesTide >= mMaxNbTouches) { //No resources left. mBuffers[i].maxNbTouches = 0; mBuffers[i].touches = NULL; noTouchesRemaining = true; } else if ((touchesTide + mBuffers[i].maxNbTouches) > mMaxNbTouches) { //Some resources left but not enough to match requested number. //This might be enough but it depends on the number of hits generated by the query. mBuffers[i].maxNbTouches = mMaxNbTouches - touchesTide; mBuffers[i].touches = mTouches + touchesTide; } else { //Enough resources left to match request. mBuffers[i].touches = mTouches + touchesTide; } } bool overflow = false; { PX_ALIGN(16, NpOverflowBuffer<HitType> overflowBuffer)(mBuffers[i].touches, mBuffers[i].maxNbTouches); performQuery(scene, mQueries[i], overflowBuffer, qfcb); overflow = overflowBuffer.overflow || noTouchesRemaining; mBuffers[i].hasBlock = overflowBuffer.hasBlock; mBuffers[i].block = overflowBuffer.block; mBuffers[i].nbTouches = overflowBuffer.nbTouches; } if(overflow) { mBuffers[i].maxNbTouches = 0xffffffff; } touchesTide += mBuffers[i].nbTouches; } mBufferTide = 0; } }; const PxScene& mScene; PxQueryFilterCallback* mQueryFilterCallback; Query<PxRaycastHit, Raycast> mRaycasts; Query<PxSweepHit, Sweep> mSweeps; Query<PxOverlapHit, Overlap> mOverlaps; }; template<typename HitType> class ExtBatchQueryDesc { public: ExtBatchQueryDesc(const PxU32 maxNbResults, const PxU32 maxNbTouches) : mResults(NULL), mMaxNbResults(maxNbResults), mTouches(NULL), mMaxNbTouches(maxNbTouches) { } ExtBatchQueryDesc(PxHitBuffer<HitType>* results, const PxU32 maxNbResults, HitType* touches, PxU32 maxNbTouches) : mResults(results), mMaxNbResults(maxNbResults), mTouches(touches), mMaxNbTouches(maxNbTouches) { } PX_FORCE_INLINE PxHitBuffer<HitType>* getResults() const { return mResults; } PX_FORCE_INLINE PxU32 getNbResults() const { return mMaxNbResults; } PX_FORCE_INLINE HitType* getTouches() const { return mTouches; } PX_FORCE_INLINE PxU32 getNbTouches() const { return mMaxNbTouches; } private: PxHitBuffer<HitType>* mResults; PxU32 mMaxNbResults; HitType* mTouches; PxU32 mMaxNbTouches; }; template <typename HitType, typename QueryType> PxU32 computeByteSize(const ExtBatchQueryDesc<HitType>& queryDesc) { PxU32 byteSize = 0; if (queryDesc.getNbResults() > 0) { byteSize += sizeof(QueryType)*queryDesc.getNbResults(); if (!queryDesc.getResults()) { byteSize += sizeof(PxHitBuffer<HitType>)*queryDesc.getNbResults() + sizeof(HitType)*queryDesc.getNbTouches(); } } return byteSize; } template <typename HitType, typename QueryType> PxU8* parseDesc (PxU8* bufIn, const ExtBatchQueryDesc<HitType>& queryDesc, PxHitBuffer<HitType>*& results, QueryType*& queries, PxU32& maxBufferSize, HitType*& touches, PxU32& maxNbTouches) { PxU8* bufOut = bufIn; results = queryDesc.getResults(); queries = NULL; maxBufferSize = queryDesc.getNbResults(); touches = queryDesc.getTouches(); maxNbTouches = queryDesc.getNbTouches(); if (maxBufferSize > 0) { queries = reinterpret_cast<QueryType*>(bufOut); bufOut += sizeof(QueryType)*maxBufferSize; if (!results) { results = reinterpret_cast<PxHitBuffer<HitType>*>(bufOut); for (PxU32 i = 0; i < maxBufferSize; i++) { PX_PLACEMENT_NEW(results + i, PxHitBuffer<HitType>); } bufOut += sizeof(PxHitBuffer<HitType>)*maxBufferSize; if (maxNbTouches > 0) { touches = reinterpret_cast<HitType*>(bufOut); bufOut += sizeof(HitType)*maxNbTouches; } } } return bufOut; } PxBatchQueryExt* create (const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, const ExtBatchQueryDesc<PxRaycastHit>& raycastDesc, const ExtBatchQueryDesc<PxSweepHit>& sweepDesc, const ExtBatchQueryDesc<PxOverlapHit>& overlapDesc) { const PxU32 byteSize = sizeof(ExtBatchQuery) + computeByteSize<PxRaycastHit, Raycast>(raycastDesc) + computeByteSize<PxSweepHit, Sweep>(sweepDesc) + computeByteSize<PxOverlapHit, Overlap>(overlapDesc); PxAllocatorCallback& allocator = *PxGetAllocatorCallback(); PxU8* buf = reinterpret_cast<PxU8*>(allocator.allocate(byteSize, "NpBatchQueryExt", PX_FL)); PX_CHECK_AND_RETURN_NULL(buf, "PxCreateBatchQueryExt - alllocation failed"); ExtBatchQuery* bq = reinterpret_cast<ExtBatchQuery*>(buf); buf += sizeof(ExtBatchQuery); PxHitBuffer<PxRaycastHit>* raycastBuffers = NULL; Raycast* raycastQueries = NULL; PxU32 maxNbRaycasts = 0; PxRaycastHit* raycastTouches = NULL; PxU32 maxNbRaycastTouches = 0; buf = parseDesc<PxRaycastHit, Raycast>(buf, raycastDesc, raycastBuffers, raycastQueries, maxNbRaycasts, raycastTouches, maxNbRaycastTouches); PxHitBuffer<PxSweepHit>* sweepBuffers = NULL; Sweep* sweepQueries = NULL; PxU32 maxNbSweeps = 0; PxSweepHit* sweepTouches = NULL; PxU32 maxNbSweepTouches = 0; buf = parseDesc<PxSweepHit, Sweep>(buf, sweepDesc, sweepBuffers, sweepQueries, maxNbSweeps, sweepTouches, maxNbSweepTouches); PxHitBuffer<PxOverlapHit>* overlapBuffers = NULL; Overlap* overlapQueries = NULL; PxU32 maxNbOverlaps = 0; PxOverlapHit* overlapTouches = NULL; PxU32 maxNbOverlapTouches = 0; buf = parseDesc<PxOverlapHit, Overlap>(buf, overlapDesc, overlapBuffers, overlapQueries, maxNbOverlaps, overlapTouches, maxNbOverlapTouches); PX_ASSERT((reinterpret_cast<PxU8*>(bq) + byteSize) == buf); PX_PLACEMENT_NEW(bq, ExtBatchQuery)( scene, queryFilterCallback, raycastBuffers, raycastQueries, maxNbRaycasts, raycastTouches, maxNbRaycastTouches, sweepBuffers, sweepQueries, maxNbSweeps, sweepTouches, maxNbSweepTouches, overlapBuffers, overlapQueries, maxNbOverlaps, overlapTouches, maxNbOverlapTouches); return bq; } PxBatchQueryExt* physx::PxCreateBatchQueryExt( const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, const PxU32 maxNbRaycasts, const PxU32 maxNbRaycastTouches, const PxU32 maxNbSweeps, const PxU32 maxNbSweepTouches, const PxU32 maxNbOverlaps, const PxU32 maxNbOverlapTouches) { PX_CHECK_AND_RETURN_NULL(!((0 != maxNbRaycastTouches) && (0 == maxNbRaycasts)), "PxCreateBatchQueryExt - maxNbRaycastTouches is non-zero but maxNbRaycasts is zero"); PX_CHECK_AND_RETURN_NULL(!((0 != maxNbSweepTouches) && (0 == maxNbSweeps)), "PxCreateBatchQueryExt - maxNbSweepTouches is non-zero but maxNbSweeps is zero"); PX_CHECK_AND_RETURN_NULL(!((0 != maxNbOverlapTouches) && (0 == maxNbOverlaps)), "PxCreateBatchQueryExt - maxNbOverlaps is non-zero but maxNbOverlaps is zero"); return create(scene, queryFilterCallback, ExtBatchQueryDesc<PxRaycastHit>(maxNbRaycasts, maxNbRaycastTouches), ExtBatchQueryDesc<PxSweepHit>(maxNbSweeps, maxNbSweepTouches), ExtBatchQueryDesc<PxOverlapHit>(maxNbOverlaps, maxNbOverlapTouches)); } PxBatchQueryExt* physx::PxCreateBatchQueryExt( const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, PxRaycastBuffer* raycastBuffers, const PxU32 maxNbRaycasts, PxRaycastHit* raycastTouches, const PxU32 maxNbRaycastTouches, PxSweepBuffer* sweepBuffers, const PxU32 maxNbSweeps, PxSweepHit* sweepTouches, const PxU32 maxNbSweepTouches, PxOverlapBuffer* overlapBuffers, const PxU32 maxNbOverlaps, PxOverlapHit* overlapTouches, const PxU32 maxNbOverlapTouches) { PX_CHECK_AND_RETURN_NULL(!(!raycastTouches && (maxNbRaycastTouches != 0)), "PxCreateBatchQueryExt - maxNbRaycastTouches > 0 but raycastTouches is NULL"); PX_CHECK_AND_RETURN_NULL(!(!raycastBuffers && (maxNbRaycasts != 0)), "PxCreateBatchQueryExt - maxNbRaycasts > 0 but raycastBuffers is NULL"); PX_CHECK_AND_RETURN_NULL(!(!raycastBuffers && raycastTouches), "PxCreateBatchQueryExt - raycastBuffers is NULL but raycastTouches is non-NULL"); PX_CHECK_AND_RETURN_NULL(!(!sweepTouches && (maxNbSweepTouches != 0)), "PxCreateBatchQueryExt - maxNbSweepTouches > 0 but sweepTouches is NULL"); PX_CHECK_AND_RETURN_NULL(!(!sweepBuffers && (maxNbSweeps != 0)), "PxCreateBatchQueryExt - maxNbSweeps > 0 but sweepBuffers is NULL"); PX_CHECK_AND_RETURN_NULL(!(!sweepBuffers && sweepTouches), "PxCreateBatchQueryExt - sweepBuffers is NULL but sweepTouches is non-NULL"); PX_CHECK_AND_RETURN_NULL(!(!overlapTouches && (maxNbOverlapTouches != 0)), "PxCreateBatchQueryExt - maxNbOverlapTouches > 0 but overlapTouches is NULL"); PX_CHECK_AND_RETURN_NULL(!(!overlapBuffers && (maxNbOverlaps != 0)), "PxCreateBatchQueryExt - maxNbOverlaps > 0 but overlapBuffers is NULL"); PX_CHECK_AND_RETURN_NULL(!(!overlapBuffers && overlapTouches), "PxCreateBatchQueryExt - overlapBuffers is NULL but overlapTouches is non-NULL"); return create(scene, queryFilterCallback, ExtBatchQueryDesc<PxRaycastHit>(raycastBuffers, maxNbRaycasts, raycastTouches, maxNbRaycastTouches), ExtBatchQueryDesc<PxSweepHit>(sweepBuffers, maxNbSweeps, sweepTouches, maxNbSweepTouches), ExtBatchQueryDesc<PxOverlapHit>(overlapBuffers, maxNbOverlaps, overlapTouches, maxNbOverlapTouches)); } ExtBatchQuery::ExtBatchQuery (const PxScene& scene, PxQueryFilterCallback* queryFilterCallback, PxRaycastBuffer* raycastBuffers, Raycast* raycastQueries, const PxU32 maxNbRaycasts, PxRaycastHit* raycastTouches, const PxU32 maxNbRaycastTouches, PxSweepBuffer* sweepBuffers, Sweep* sweepQueries, const PxU32 maxNbSweeps, PxSweepHit* sweepTouches, const PxU32 maxNbSweepTouches, PxOverlapBuffer* overlapBuffers, Overlap* overlapQueries, const PxU32 maxNbOverlaps, PxOverlapHit* overlapTouches, const PxU32 maxNbOverlapTouches) : mScene(scene), mQueryFilterCallback(queryFilterCallback) { typedef Query<PxRaycastHit, Raycast> QueryRaycast; typedef Query<PxSweepHit, Sweep> QuerySweep; typedef Query<PxOverlapHit, Overlap> QueryOverlap; PX_PLACEMENT_NEW(&mRaycasts, QueryRaycast)(raycastBuffers, raycastQueries, maxNbRaycasts, raycastTouches, maxNbRaycastTouches); PX_PLACEMENT_NEW(&mSweeps, QuerySweep)(sweepBuffers, sweepQueries, maxNbSweeps, sweepTouches, maxNbSweepTouches); PX_PLACEMENT_NEW(&mOverlaps, QueryOverlap)(overlapBuffers, overlapQueries, maxNbOverlaps, overlapTouches, maxNbOverlapTouches); } void ExtBatchQuery::release() { PxGetAllocatorCallback()->deallocate(this); } PxRaycastBuffer* ExtBatchQuery::raycast (const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, const PxU16 maxNbTouches, PxHitFlags hitFlags, const PxQueryFilterData& filterData, const PxQueryCache* cache) { const PxQueryFilterData qfd(filterData.data, filterData.flags | PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR); const Raycast raycast = { origin, unitDir, distance, hitFlags, qfd, cache }; PxRaycastBuffer* buffer = mRaycasts.addQuery(raycast, maxNbTouches); PX_CHECK_MSG(buffer, "PxBatchQueryExt::raycast - number of raycast() calls exceeds maxNbRaycasts. query discarded"); return buffer; } PxSweepBuffer* ExtBatchQuery::sweep (const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, const PxU16 maxNbTouches, PxHitFlags hitFlags, const PxQueryFilterData& filterData, const PxQueryCache* cache, const PxReal inflation) { const PxQueryFilterData qfd(filterData.data, filterData.flags | PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR); const Sweep sweep = { geometry, pose, unitDir, distance, hitFlags, qfd, cache, inflation}; PxSweepBuffer* buffer = mSweeps.addQuery(sweep, maxNbTouches); PX_CHECK_MSG(buffer, "PxBatchQueryExt::sweep - number of sweep() calls exceeds maxNbSweeps. query discarded"); return buffer; } PxOverlapBuffer* ExtBatchQuery::overlap (const PxGeometry& geometry, const PxTransform& pose, PxU16 maxNbTouches, const PxQueryFilterData& filterData, const PxQueryCache* cache) { const PxQueryFilterData qfd(filterData.data, filterData.flags | PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR); const Overlap overlap = { geometry, pose, qfd, cache}; PxOverlapBuffer* buffer = mOverlaps.addQuery(overlap, maxNbTouches); PX_CHECK_MSG(buffer, "PxBatchQueryExt::overlap - number of overlap() calls exceeds maxNbOverlaps. query discarded"); return buffer; } void ExtBatchQuery::execute() { mRaycasts.execute(mScene, mQueryFilterCallback); mSweeps.execute(mScene, mQueryFilterCallback); mOverlaps.execute(mScene, mQueryFilterCallback); }
24,701
C++
34.440459
152
0.751265
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCustomSceneQuerySystem.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 "extensions/PxCustomSceneQuerySystem.h" #include "extensions/PxShapeExt.h" #include "foundation/PxAlloca.h" #include "foundation/PxHashMap.h" #include "foundation/PxUserAllocated.h" #include "geometry/PxBVH.h" #include "GuActorShapeMap.h" #include "ExtSqQuery.h" #include "SqFactory.h" #include "PxRigidActor.h" #include "PxPruningStructure.h" using namespace physx; using namespace Sq; using namespace Gu; // PT: this customized version uses: // - a modified version of Sq::PrunerManager, named Sq::ExtPrunerManager, located in ExtSqManager.cpp // - a modified version of Sq::SceneQueries, named Sq::ExtSceneQueries, located in ExtSqQuery.cpp // // Sq::PrunerManager and Sq::SceneQueries live in the SceneQuery lib, and are used by PhysX internally // to implement the regular SQ system. // // Sq::ExtPrunerManager and Sq::ExtSceneQueries live in the Extensions lib, and are not used by the // regular PhysX SQ system. They are examples of how the default code can be customized. // static CompanionPrunerType getCompanionType(PxDynamicTreeSecondaryPruner::Enum type) { switch(type) { case PxDynamicTreeSecondaryPruner::eNONE: return COMPANION_PRUNER_NONE; case PxDynamicTreeSecondaryPruner::eBUCKET: return COMPANION_PRUNER_BUCKET; case PxDynamicTreeSecondaryPruner::eINCREMENTAL: return COMPANION_PRUNER_INCREMENTAL; case PxDynamicTreeSecondaryPruner::eBVH: return COMPANION_PRUNER_AABB_TREE; case PxDynamicTreeSecondaryPruner::eLAST: return COMPANION_PRUNER_NONE; } return COMPANION_PRUNER_NONE; } static BVHBuildStrategy getBuildStrategy(PxBVHBuildStrategy::Enum bs) { switch(bs) { case PxBVHBuildStrategy::eFAST: return BVH_SPLATTER_POINTS; case PxBVHBuildStrategy::eDEFAULT: return BVH_SPLATTER_POINTS_SPLIT_GEOM_CENTER; case PxBVHBuildStrategy::eSAH: return BVH_SAH; case PxBVHBuildStrategy::eLAST: return BVH_SPLATTER_POINTS; } return BVH_SPLATTER_POINTS; } static Pruner* create(PxPruningStructureType::Enum type, PxU64 contextID, PxDynamicTreeSecondaryPruner::Enum secondaryType, PxBVHBuildStrategy::Enum buildStrategy, PxU32 nbObjectsPerNode) { // if(0) // return createIncrementalPruner(contextID); const CompanionPrunerType cpType = getCompanionType(secondaryType); const BVHBuildStrategy bs = getBuildStrategy(buildStrategy); Pruner* pruner = NULL; switch(type) { case PxPruningStructureType::eNONE: { pruner = createBucketPruner(contextID); break; } case PxPruningStructureType::eDYNAMIC_AABB_TREE: { pruner = createAABBPruner(contextID, true, cpType, bs, nbObjectsPerNode); break; } case PxPruningStructureType::eSTATIC_AABB_TREE: { pruner = createAABBPruner(contextID, false, cpType, bs, nbObjectsPerNode); break; } case PxPruningStructureType::eLAST: break; } return pruner; } #define EXT_PRUNER_EPSILON 0.005f // PT: in this external implementation we'll use Px pointers instead of Np pointers in the payload. static PX_FORCE_INLINE void setPayload(PrunerPayload& pp, const PxShape* shape, const PxRigidActor* actor) { pp.data[0] = size_t(shape); pp.data[1] = size_t(actor); } static PX_FORCE_INLINE PxShape* getShapeFromPayload(const PrunerPayload& payload) { return reinterpret_cast<PxShape*>(payload.data[0]); } static PX_FORCE_INLINE PxRigidActor* getActorFromPayload(const PrunerPayload& payload) { return reinterpret_cast<PxRigidActor*>(payload.data[1]); } static PX_FORCE_INLINE bool isDynamicActor(const PxRigidActor& actor) { const PxType actorType = actor.getConcreteType(); return actorType != PxConcreteType::eRIGID_STATIC; } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE ActorShapeData createActorShapeData(PrunerHandle h, PrunerCompoundId id) { return (ActorShapeData(id) << 32) | ActorShapeData(h); } static PX_FORCE_INLINE PrunerHandle getPrunerHandle(ActorShapeData data) { return PrunerHandle(data); } static PX_FORCE_INLINE PrunerCompoundId getCompoundID(ActorShapeData data) { return PrunerCompoundId(data >> 32); } /////////////////////////////////////////////////////////////////////////////// namespace { class ExtSqAdapter : public ExtQueryAdapter { PX_NOCOPY(ExtSqAdapter) public: ExtSqAdapter(const PxCustomSceneQuerySystemAdapter& adapter) : mUserAdapter(adapter)/*, mFilterData(NULL)*/ {} virtual ~ExtSqAdapter() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter // ExtQueryAdapter virtual PrunerHandle findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const; virtual void getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const; virtual void getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const; virtual bool processPruner(PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const; //~ExtQueryAdapter const PxCustomSceneQuerySystemAdapter& mUserAdapter; ActorShapeMap mDatabase; const PxQueryFilterData* mFilterData; }; } const PxGeometry& ExtSqAdapter::getGeometry(const PrunerPayload& payload) const { PxShape* shape = getShapeFromPayload(payload); return shape->getGeometry(); } PrunerHandle ExtSqAdapter::findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const { const PxU32 actorIndex = cache.actor->getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); const ActorShapeData actorShapeData = mDatabase.find(actorIndex, cache.actor, cache.shape); compoundId = getCompoundID(actorShapeData); prunerIndex = mUserAdapter.getPrunerIndex(*cache.actor, *cache.shape); return getPrunerHandle(actorShapeData); } void ExtSqAdapter::getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const { PxShape* shape = getShapeFromPayload(payload); filterData = shape->getQueryFilterData(); } void ExtSqAdapter::getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const { actorShape.actor = getActorFromPayload(payload); actorShape.shape = getShapeFromPayload(payload); } bool ExtSqAdapter::processPruner(PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const { return mUserAdapter.processPruner(prunerIndex, context, filterData, filterCall); } /////////////////////////////////////////////////////////////////////////////// namespace { class CustomPxSQ : public PxCustomSceneQuerySystem, public PxUserAllocated { public: CustomPxSQ(const PxCustomSceneQuerySystemAdapter& adapter, ExtPVDCapture* pvd, PxU64 contextID, PxSceneQueryUpdateMode::Enum mode, bool usesTreeOfPruners) : mExtAdapter (adapter), mQueries (pvd, contextID, EXT_PRUNER_EPSILON, mExtAdapter, usesTreeOfPruners), mUpdateMode (mode), mRefCount (1) {} virtual ~CustomPxSQ() {} virtual void release(); virtual void acquireReference(); virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) { SQ().preallocate(prunerIndex, nbShapes); } virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure); virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape); virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform); virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& pxbvh, const PxTransform* transforms); virtual void removeSQCompound(PxSQCompoundHandle compoundHandle); virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform); virtual void flushUpdates() { SQ().flushUpdates(); } virtual void flushMemory() { SQ().flushMemory(); } virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const { SQ().visualize(prunerIndex, out); } virtual void shiftOrigin(const PxVec3& shift) { SQ().shiftOrigin(shift); } virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex); virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle); virtual void finalizeUpdates(); virtual void setDynamicTreeRebuildRateHint(PxU32 dynTreeRebuildRateHint) { SQ().setDynamicTreeRebuildRateHint(dynTreeRebuildRateHint); } virtual PxU32 getDynamicTreeRebuildRateHint() const { return SQ().getDynamicTreeRebuildRateHint(); } virtual void forceRebuildDynamicTree(PxU32 prunerIndex) { SQ().forceRebuildDynamicTree(prunerIndex); } virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const { return mUpdateMode; } virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum mode) { mUpdateMode = mode; } virtual PxU32 getStaticTimestamp() const { return SQ().getStaticTimestamp(); } virtual void merge(const PxPruningStructure& pxps); virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const; virtual bool overlap(const PxGeometry& geometry, const PxTransform& transform, PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const; virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices); virtual PxU32 addPruner(PxPruningStructureType::Enum primaryType, PxDynamicTreeSecondaryPruner::Enum secondaryType, PxU32 preallocated); virtual PxU32 startCustomBuildstep(); virtual void customBuildstep(PxU32 index); virtual void finishCustomBuildstep(); PX_FORCE_INLINE ExtPrunerManager& SQ() { return mQueries.mSQManager; } PX_FORCE_INLINE const ExtPrunerManager& SQ() const { return mQueries.mSQManager; } ExtSqAdapter mExtAdapter; ExtSceneQueries mQueries; PxSceneQueryUpdateMode::Enum mUpdateMode; PxU32 mRefCount; }; } /////////////////////////////////////////////////////////////////////////////// void addExternalSQ(PxSceneQuerySystem* added); void removeExternalSQ(PxSceneQuerySystem* removed); void CustomPxSQ::release() { mRefCount--; if(!mRefCount) { removeExternalSQ(this); PX_DELETE_THIS; } } void CustomPxSQ::acquireReference() { mRefCount++; } void CustomPxSQ::addSQShape(const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure) { PrunerPayload payload; setPayload(payload, &shape, &actor); const bool isDynamic = isDynamicActor(actor); const PxU32 prunerIndex = mExtAdapter.mUserAdapter.getPrunerIndex(actor, shape); const PrunerCompoundId cid = compoundHandle ? PrunerCompoundId(*compoundHandle) : INVALID_COMPOUND_ID; const PrunerHandle shapeHandle = SQ().addPrunerShape(payload, prunerIndex, isDynamic, cid, bounds, transform, hasPruningStructure); const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); mExtAdapter.mDatabase.add(actorIndex, &actor, &shape, createActorShapeData(shapeHandle, cid)); } namespace { struct DatabaseCleaner : PrunerPayloadRemovalCallback { DatabaseCleaner(ExtSqAdapter& adapter) : mAdapter(adapter){} virtual void invoke(PxU32 nbRemoved, const PrunerPayload* removed) { PxU32 actorIndex = 0xffffffff; const PxRigidActor* cachedActor = NULL; while(nbRemoved--) { const PrunerPayload& payload = *removed++; const PxRigidActor* actor = getActorFromPayload(payload); if(actor!=cachedActor) { actorIndex = actor->getInternalActorIndex(); cachedActor = actor; } PX_ASSERT(actorIndex!=0xffffffff); bool status = mAdapter.mDatabase.remove(actorIndex, actor, getShapeFromPayload(payload), NULL); PX_ASSERT(status); PX_UNUSED(status); } } ExtSqAdapter& mAdapter; PX_NOCOPY(DatabaseCleaner) }; } void CustomPxSQ::removeSQShape(const PxRigidActor& actor, const PxShape& shape) { const bool isDynamic = isDynamicActor(actor); const PxU32 prunerIndex = mExtAdapter.mUserAdapter.getPrunerIndex(actor, shape); const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); ActorShapeData actorShapeData; mExtAdapter.mDatabase.remove(actorIndex, &actor, &shape, &actorShapeData); const PrunerHandle shapeHandle = getPrunerHandle(actorShapeData); const PrunerCompoundId compoundId = getCompoundID(actorShapeData); SQ().removePrunerShape(prunerIndex, isDynamic, compoundId, shapeHandle, NULL); } void CustomPxSQ::updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) { const bool isDynamic = isDynamicActor(actor); const PxU32 prunerIndex = mExtAdapter.mUserAdapter.getPrunerIndex(actor, shape); const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); const ActorShapeData actorShapeData = mExtAdapter.mDatabase.find(actorIndex, &actor, &shape); const PrunerHandle shapeHandle = getPrunerHandle(actorShapeData); const PrunerCompoundId cid = getCompoundID(actorShapeData); SQ().markForUpdate(prunerIndex, isDynamic, cid, shapeHandle, transform); } PxSQCompoundHandle CustomPxSQ::addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms) { const PxU32 numSqShapes = bvh.getNbBounds(); PX_ALLOCA(payloads, PrunerPayload, numSqShapes); for(PxU32 i=0; i<numSqShapes; i++) setPayload(payloads[i], shapes[i], &actor); const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); PX_ALLOCA(shapeHandles, PrunerHandle, numSqShapes); SQ().addCompoundShape(bvh, actorIndex, actor.getGlobalPose(), shapeHandles, payloads, transforms, isDynamicActor(actor)); for(PxU32 i=0; i<numSqShapes; i++) { // PT: TODO: actorIndex is now redundant! mExtAdapter.mDatabase.add(actorIndex, &actor, shapes[i], createActorShapeData(shapeHandles[i], actorIndex)); } return PxSQCompoundHandle(actorIndex); } void CustomPxSQ::removeSQCompound(PxSQCompoundHandle compoundHandle) { DatabaseCleaner cleaner(mExtAdapter); SQ().removeCompoundActor(PrunerCompoundId(compoundHandle), &cleaner); } void CustomPxSQ::updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) { SQ().updateCompoundActor(PrunerCompoundId(compoundHandle), compoundTransform); } PxSQBuildStepHandle CustomPxSQ::prepareSceneQueryBuildStep(PxU32 prunerIndex) { return SQ().prepareSceneQueriesUpdate(prunerIndex); } void CustomPxSQ::sceneQueryBuildStep(PxSQBuildStepHandle handle) { SQ().sceneQueryBuildStep(handle); } void CustomPxSQ::finalizeUpdates() { switch(mUpdateMode) { case PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED: SQ().afterSync(true, true); break; case PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED: SQ().afterSync(true, false); break; case PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED: SQ().afterSync(false, false); break; } } void CustomPxSQ::merge(const PxPruningStructure& /*pxps*/) { PX_ASSERT(!"Not supported by this custom SQ system"); // PT: PxPruningStructure only knows about the regular static/dynamic pruners, so it is not // compatible with this custom version. } bool CustomPxSQ::raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { return mQueries._raycast(origin, unitDir, distance, hitCall, hitFlags, filterData, filterCall, cache, flags); } bool CustomPxSQ::sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const { return mQueries._sweep(geometry, pose, unitDir, distance, hitCall, hitFlags, filterData, filterCall, cache, inflation, flags); } bool CustomPxSQ::overlap( const PxGeometry& geometry, const PxTransform& transform, PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { return mQueries._overlap( geometry, transform, hitCall, filterData, filterCall, cache, flags); } PxSQPrunerHandle CustomPxSQ::getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const { const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); const ActorShapeData actorShapeData = mExtAdapter.mDatabase.find(actorIndex, &actor, &shape); prunerIndex = mExtAdapter.mUserAdapter.getPrunerIndex(actor, shape); return PxSQPrunerHandle(getPrunerHandle(actorShapeData)); } void CustomPxSQ::sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) { SQ().sync(prunerIndex, handles, indices, bounds, transforms, count, ignoredIndices); } PxU32 CustomPxSQ::addPruner(PxPruningStructureType::Enum primaryType, PxDynamicTreeSecondaryPruner::Enum secondaryType, PxU32 preallocated) { Pruner* pruner = create(primaryType, mQueries.getContextId(), secondaryType, PxBVHBuildStrategy::eFAST, 4); return mQueries.mSQManager.addPruner(pruner, preallocated); } PxU32 CustomPxSQ::startCustomBuildstep() { return SQ().startCustomBuildstep(); } void CustomPxSQ::customBuildstep(PxU32 index) { SQ().customBuildstep(index); } void CustomPxSQ::finishCustomBuildstep() { SQ().finishCustomBuildstep(); } /////////////////////////////////////////////////////////////////////////////// PxCustomSceneQuerySystem* physx::PxCreateCustomSceneQuerySystem(PxSceneQueryUpdateMode::Enum sceneQueryUpdateMode, PxU64 contextID, const PxCustomSceneQuerySystemAdapter& adapter, bool usesTreeOfPruners) { ExtPVDCapture* pvd = NULL; CustomPxSQ* pxsq = PX_NEW(CustomPxSQ)(adapter, pvd, contextID, sceneQueryUpdateMode, usesTreeOfPruners); addExternalSQ(pxsq); return pxsq; } ///////////////////////////////////////////////////////////////////////////////
21,442
C++
40.880859
203
0.743821
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRigidActorExt.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 "extensions/PxRigidActorExt.h" #include "foundation/PxFPU.h" #include "foundation/PxAllocator.h" #include "foundation/PxInlineArray.h" #include "geometry/PxGeometryQuery.h" #include "cooking/PxBVHDesc.h" #include "cooking/PxCooking.h" using namespace physx; PxBounds3* PxRigidActorExt::getRigidActorShapeLocalBoundsList(const PxRigidActor& actor, PxU32& numBounds) { const PxU32 numShapes = actor.getNbShapes(); if(numShapes == 0) return NULL; PxInlineArray<PxShape*, 64> shapes("PxShape*"); shapes.resize(numShapes); actor.getShapes(shapes.begin(), shapes.size()); PxU32 numSqShapes = 0; for(PxU32 i=0; i<numShapes; i++) { if(shapes[i]->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE) numSqShapes++; } PxBounds3* bounds = PX_ALLOCATE(PxBounds3, numSqShapes, "PxBounds3"); numSqShapes = 0; { PX_SIMD_GUARD // PT: external guard because we use PxGeometryQueryFlag::Enum(0) below for(PxU32 i=0; i<numShapes; i++) { if(shapes[i]->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE) PxGeometryQuery::computeGeomBounds(bounds[numSqShapes++], shapes[i]->getGeometry(), shapes[i]->getLocalPose(), 0.0f, 1.0f, PxGeometryQueryFlag::Enum(0)); } } numBounds = numSqShapes; return bounds; } PxBVH* PxRigidActorExt::createBVHFromActor(PxPhysics& physics, const PxRigidActor& actor) { PxU32 nbBounds = 0; PxBounds3* bounds = PxRigidActorExt::getRigidActorShapeLocalBoundsList(actor, nbBounds); PxBVHDesc bvhDesc; bvhDesc.bounds.count = nbBounds; bvhDesc.bounds.data = bounds; bvhDesc.bounds.stride = sizeof(PxBounds3); PxBVH* bvh = PxCreateBVH(bvhDesc, physics.getPhysicsInsertionCallback()); PX_FREE(bounds); return bvh; }
3,372
C++
36.477777
157
0.753559
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtTriangleMeshExt.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/PxMeshQuery.h" #include "geometry/PxGeometryQuery.h" #include "geometry/PxTriangleMeshGeometry.h" #include "geometry/PxHeightFieldGeometry.h" #include "geometry/PxHeightField.h" #include "geometry/PxTriangleMesh.h" #include "extensions/PxTriangleMeshExt.h" #include "GuSDF.h" #include "GuTriangleMesh.h" #include "foundation/PxAllocator.h" using namespace physx; PxMeshOverlapUtil::PxMeshOverlapUtil() : mResultsMemory(mResults), mNbResults(0), mMaxNbResults(256) { } PxMeshOverlapUtil::~PxMeshOverlapUtil() { if(mResultsMemory != mResults) PX_FREE(mResultsMemory); } PxU32 PxMeshOverlapUtil::findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose) { bool overflow; PxU32 nbTouchedTris = PxMeshQuery::findOverlapTriangleMesh(geom, geomPose, meshGeom, meshPose, mResultsMemory, mMaxNbResults, 0, overflow); if(overflow) { const PxU32 maxNbTris = meshGeom.triangleMesh->getNbTriangles(); if(!maxNbTris) { mNbResults = 0; return 0; } if(mMaxNbResults<maxNbTris) { if(mResultsMemory != mResults) PX_FREE(mResultsMemory); mResultsMemory = PX_ALLOCATE(PxU32, maxNbTris, "PxMeshOverlapUtil::findOverlap"); mMaxNbResults = maxNbTris; } nbTouchedTris = PxMeshQuery::findOverlapTriangleMesh(geom, geomPose, meshGeom, meshPose, mResultsMemory, mMaxNbResults, 0, overflow); PX_ASSERT(nbTouchedTris); PX_ASSERT(!overflow); } mNbResults = nbTouchedTris; return nbTouchedTris; } PxU32 PxMeshOverlapUtil::findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose) { bool overflow = true; PxU32 nbTouchedTris = PxMeshQuery::findOverlapHeightField(geom, geomPose, hfGeom, hfPose, mResultsMemory, mMaxNbResults, 0, overflow); if(overflow) { const PxU32 maxNbTris = hfGeom.heightField->getNbRows()*hfGeom.heightField->getNbColumns()*2; if(!maxNbTris) { mNbResults = 0; return 0; } if(mMaxNbResults<maxNbTris) { if(mResultsMemory != mResults) PX_FREE(mResultsMemory); mResultsMemory = PX_ALLOCATE(PxU32, maxNbTris, "PxMeshOverlapUtil::findOverlap"); mMaxNbResults = maxNbTris; } nbTouchedTris = PxMeshQuery::findOverlapHeightField(geom, geomPose, hfGeom, hfPose, mResultsMemory, mMaxNbResults, 0, overflow); PX_ASSERT(nbTouchedTris); PX_ASSERT(!overflow); } mNbResults = nbTouchedTris; return nbTouchedTris; } namespace { template<typename MeshGeometry> bool computeMeshPenetrationT(PxVec3& direction, PxReal& depth, const PxGeometry& geom, const PxTransform& geomPose, const MeshGeometry& meshGeom, const PxTransform& meshPose, PxU32 maxIter, PxU32* nbIterOut) { PxU32 nbIter = 0; PxTransform pose = geomPose; for (; nbIter < maxIter; nbIter++) { PxVec3 currentDir; PxF32 currentDepth; if (!PxGeometryQuery::computePenetration(currentDir, currentDepth, geom, pose, meshGeom, meshPose)) break; pose.p += currentDir * currentDepth; } if(nbIterOut) *nbIterOut = nbIter; PxVec3 diff = pose.p - geomPose.p; depth = diff.magnitude(); if (depth>0) direction = diff / depth; return nbIter!=0; } } bool physx::PxComputeTriangleMeshPenetration(PxVec3& direction, PxReal& depth, const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose, PxU32 maxIter, PxU32* nbIter) { return computeMeshPenetrationT(direction, depth, geom, geomPose, meshGeom, meshPose, maxIter, nbIter); } bool physx::PxComputeHeightFieldPenetration(PxVec3& direction, PxReal& depth, const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& meshPose, PxU32 maxIter, PxU32* nbIter) { return computeMeshPenetrationT(direction, depth, geom, geomPose, hfGeom, meshPose, maxIter, nbIter); } bool physx::PxExtractIsosurfaceFromSDF(const PxTriangleMesh& triangleMesh, PxArray<PxVec3>& isosurfaceVertices, PxArray<PxU32>& isosurfaceTriangleIndices) { PxU32 dimX, dimY, dimZ; triangleMesh.getSDFDimensions(dimX, dimY, dimZ); if (dimX == 0 || dimY == 0 || dimZ == 0) return false; const Gu::TriangleMesh* guTriangleMesh = static_cast<const Gu::TriangleMesh*>(&triangleMesh); const Gu::SDF& sdf = guTriangleMesh->getSdfDataFast(); extractIsosurfaceFromSDF(sdf, isosurfaceVertices, isosurfaceTriangleIndices); return true; }
6,322
C++
32.278947
158
0.737583
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtPvd.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. // suppress LNK4221 #include "foundation/PxPreprocessor.h" PX_DUMMY_SYMBOL #if PX_SUPPORT_PVD #include "ExtPvd.h" #include "PxExtensionMetaDataObjects.h" #include "ExtD6Joint.h" #include "ExtFixedJoint.h" #include "ExtSphericalJoint.h" #include "ExtDistanceJoint.h" #include "ExtRevoluteJoint.h" #include "ExtPrismaticJoint.h" #include "ExtJointMetaDataExtensions.h" #include "PvdMetaDataPropertyVisitor.h" #include "PvdMetaDataDefineProperties.h" namespace physx { namespace Ext { using namespace physx::Vd; template<typename TObjType, typename TOperator> inline void visitPvdInstanceProperties( TOperator inOperator ) { PxClassInfoTraits<TObjType>().Info.visitInstanceProperties( makePvdPropertyFilter( inOperator ), 0 ); } template<typename TObjType, typename TOperator> inline void visitPvdProperties( TOperator inOperator ) { PvdPropertyFilter<TOperator> theFilter( makePvdPropertyFilter( inOperator ) ); PxU32 thePropCount = PxClassInfoTraits<TObjType>().Info.visitBaseProperties( theFilter ); PxClassInfoTraits<TObjType>().Info.visitInstanceProperties( theFilter, thePropCount ); } Pvd::PvdNameSpace::PvdNameSpace(physx::pvdsdk::PvdDataStream& conn, const char* /*name*/) : mConnection(conn) { } Pvd::PvdNameSpace::~PvdNameSpace() { } void Pvd::releasePvdInstance(physx::pvdsdk::PvdDataStream& pvdConnection, const PxConstraint& c, const PxJoint& joint) { if(!pvdConnection.isConnected()) return; //remove from scene and from any attached actors. PxRigidActor* actor0, *actor1; c.getActors( actor0, actor1 ); PxScene* scene = c.getScene(); if(scene) pvdConnection.removeObjectRef( scene, "Joints", &joint ); if ( actor0 && actor0->getScene() ) pvdConnection.removeObjectRef( actor0, "Joints", &joint ); if ( actor1 && actor1->getScene()) pvdConnection.removeObjectRef( actor1, "Joints", &joint ); pvdConnection.destroyInstance(&joint); } template<typename TObjType> void registerProperties( PvdDataStream& inStream ) { inStream.createClass<TObjType>(); PvdPropertyDefinitionHelper& theHelper( inStream.getPropertyDefinitionHelper() ); PvdClassInfoDefine theDefinitionObj( theHelper, getPvdNamespacedNameForType<TObjType>() ); visitPvdInstanceProperties<TObjType>( theDefinitionObj ); } template<typename TObjType, typename TValueStructType> void registerPropertiesAndValueStruct( PvdDataStream& inStream ) { inStream.createClass<TObjType>(); inStream.deriveClass<PxJoint,TObjType>(); PvdPropertyDefinitionHelper& theHelper( inStream.getPropertyDefinitionHelper() ); { PvdClassInfoDefine theDefinitionObj( theHelper, getPvdNamespacedNameForType<TObjType>() ); visitPvdInstanceProperties<TObjType>( theDefinitionObj ); } { PvdClassInfoValueStructDefine theDefinitionObj( theHelper ); visitPvdProperties<TObjType>( theDefinitionObj ); theHelper.addPropertyMessage<TObjType,TValueStructType>(); } } void Pvd::sendClassDescriptions(physx::pvdsdk::PvdDataStream& inStream) { if (inStream.isClassExist<PxJoint>()) return; { //PxJoint registerProperties<PxJoint>( inStream ); inStream.createProperty<PxJoint,ObjectRef>( "Parent", "parents" ); registerPropertiesAndValueStruct<PxDistanceJoint,PxDistanceJointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxContactJoint, PxContactJointGeneratedValues>(inStream); registerPropertiesAndValueStruct<PxFixedJoint,PxFixedJointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxPrismaticJoint,PxPrismaticJointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxSphericalJoint,PxSphericalJointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxRevoluteJoint,PxRevoluteJointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxD6Joint,PxD6JointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxGearJoint,PxGearJointGeneratedValues>( inStream); registerPropertiesAndValueStruct<PxRackAndPinionJoint,PxRackAndPinionJointGeneratedValues>( inStream); } } void Pvd::setActors( physx::pvdsdk::PvdDataStream& inStream, const PxJoint& inJoint, const PxConstraint& c, const PxActor* newActor0, const PxActor* newActor1 ) { PxRigidActor* actor0, *actor1; c.getActors( actor0, actor1 ); if ( actor0 ) inStream.removeObjectRef( actor0, "Joints", &inJoint ); if ( actor1 ) inStream.removeObjectRef( actor1, "Joints", &inJoint ); if ( newActor0 && newActor0->getScene()) inStream.pushBackObjectRef( newActor0, "Joints", &inJoint ); if ( newActor1 && newActor1->getScene()) inStream.pushBackObjectRef( newActor1, "Joints", &inJoint ); inStream.setPropertyValue( &inJoint, "Actors.actor0", reinterpret_cast<const void*>(newActor0) ); inStream.setPropertyValue( &inJoint, "Actors.actor1", reinterpret_cast<const void*>(newActor1) ); const void* parent = newActor0 ? newActor0 : newActor1; inStream.setPropertyValue( &inJoint, "Parent", parent ); if((newActor0 && !newActor0->getScene()) || (newActor1 && !newActor1->getScene())) { inStream.removeObjectRef( c.getScene(), "Joints", &inJoint ); } } } } #endif // PX_SUPPORT_PVD
6,837
C++
40.192771
161
0.771098
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRackAndPinionJoint.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 "ExtRackAndPinionJoint.h" #include "ExtConstraintHelper.h" #include "extensions/PxRevoluteJoint.h" #include "extensions/PxPrismaticJoint.h" #include "PxArticulationJointReducedCoordinate.h" //#include <stdio.h> #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; PX_IMPLEMENT_OUTPUT_ERROR RackAndPinionJoint::RackAndPinionJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : RackAndPinionJointT(PxJointConcreteType::eRACK_AND_PINION, actor0, localFrame0, actor1, localFrame1, "RackAndPinionJointData") { RackAndPinionJointData* data = static_cast<RackAndPinionJointData*>(mData); data->hingeJoint = NULL; data->prismaticJoint = NULL; data->ratio = 1.0f; data->px = 0.0f; data->vangle = 0.0f; resetError(); } void RackAndPinionJoint::setRatio(float ratio) { RackAndPinionJointData* data = reinterpret_cast<RackAndPinionJointData*>(mData); data->ratio = ratio; resetError(); markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRackAndPinionJoint, ratio, static_cast<PxRackAndPinionJoint&>(*this), ratio) } float RackAndPinionJoint::getRatio() const { RackAndPinionJointData* data = reinterpret_cast<RackAndPinionJointData*>(mData); return data->ratio; } bool RackAndPinionJoint::setData(PxU32 nbRackTeeth, PxU32 nbPinionTeeth, float rackLength) { if(!nbRackTeeth) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setData: nbRackTeeth cannot be zero."); if(!nbPinionTeeth) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setData: nbPinionTeeth cannot be zero."); if(rackLength<=0.0f) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setData: rackLength must be positive."); RackAndPinionJointData* data = reinterpret_cast<RackAndPinionJointData*>(mData); data->ratio = (PxTwoPi*nbRackTeeth)/(rackLength*nbPinionTeeth); resetError(); markDirty(); return true; } bool RackAndPinionJoint::setJoints(const PxBase* hinge, const PxBase* prismatic) { RackAndPinionJointData* data = static_cast<RackAndPinionJointData*>(mData); if(hinge) { const PxType type0 = hinge->getConcreteType(); if(type0 == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* joint0 = static_cast<const PxArticulationJointReducedCoordinate*>(hinge); const PxArticulationJointType::Enum artiJointType0 = joint0->getJointType(); if(artiJointType0 != PxArticulationJointType::eREVOLUTE && artiJointType0 != PxArticulationJointType::eREVOLUTE_UNWRAPPED) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setJoints: passed joint must be a revolute joint."); } else { if(type0 != PxJointConcreteType::eREVOLUTE && type0 != PxJointConcreteType::eD6) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setJoints: passed hinge joint must be either a revolute joint or a D6 joint."); } } if(prismatic) { const PxType type1 = prismatic->getConcreteType(); if(type1 == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* joint1 = static_cast<const PxArticulationJointReducedCoordinate*>(prismatic); const PxArticulationJointType::Enum artiJointType1 = joint1->getJointType(); if(artiJointType1 != PxArticulationJointType::ePRISMATIC) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setJoints: passed joint must be a prismatic joint."); } else { if(type1 != PxJointConcreteType::ePRISMATIC && type1 != PxJointConcreteType::eD6) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRackAndPinionJoint::setJoints: passed prismatic joint must be either a prismatic joint or a D6 joint."); } } data->hingeJoint = hinge; data->prismaticJoint = prismatic; resetError(); markDirty(); #if PX_SUPPORT_OMNI_PVD const PxBase* joints[] = { hinge, prismatic }; PxU32 jointCount = sizeof(joints) / sizeof(joints[0]); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxRackAndPinionJoint, joints, static_cast<PxRackAndPinionJoint&>(*this), joints, jointCount) #endif return true; } void RackAndPinionJoint::getJoints(const PxBase*& hinge, const PxBase*& prismatic) const { const RackAndPinionJointData* data = static_cast<const RackAndPinionJointData*>(mData); hinge = data->hingeJoint; prismatic = data->prismaticJoint; } static float angleDiff(float angle0, float angle1) { const float diff = fmodf( angle1 - angle0 + PxPi, PxTwoPi) - PxPi; return diff < -PxPi ? diff + PxTwoPi : diff; } void RackAndPinionJoint::updateError() { RackAndPinionJointData* data = static_cast<RackAndPinionJointData*>(mData); if(!data->hingeJoint || !data->prismaticJoint) return; PxRigidActor* rackActor0; PxRigidActor* rackActor1; getActors(rackActor0, rackActor1); float Angle0 = 0.0f; float Sign0 = 0.0f; { PxRigidActor* hingeActor0; PxRigidActor* hingeActor1; const PxType type = data->hingeJoint->getConcreteType(); if(type == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* artiHingeJoint = static_cast<const PxArticulationJointReducedCoordinate*>(data->hingeJoint); hingeActor0 = &artiHingeJoint->getParentArticulationLink(); hingeActor1 = &artiHingeJoint->getChildArticulationLink(); Angle0 = artiHingeJoint->getJointPosition(PxArticulationAxis::eTWIST); } else { const PxJoint* hingeJoint = static_cast<const PxJoint*>(data->hingeJoint); hingeJoint->getActors(hingeActor0, hingeActor1); if(type == PxJointConcreteType::eREVOLUTE) Angle0 = static_cast<const PxRevoluteJoint*>(hingeJoint)->getAngle(); else if (type == PxJointConcreteType::eD6) Angle0 = static_cast<const PxD6Joint*>(hingeJoint)->getTwistAngle(); } if(rackActor0 == hingeActor0 || rackActor1 == hingeActor0) Sign0 = -1.0f; else if (rackActor0 == hingeActor1 || rackActor1 == hingeActor1) Sign0 = 1.0f; else PX_ASSERT(0); } if(!mInitDone) { mInitDone = true; mPersistentAngle0 = Angle0; } const float travelThisFrame0 = angleDiff(Angle0, mPersistentAngle0); mVirtualAngle0 += travelThisFrame0; // printf("mVirtualAngle0: %f\n", mVirtualAngle0); mPersistentAngle0 = Angle0; float px = 0.0f; float Sign1 = 0.0f; { PxRigidActor* prismaticActor0; PxRigidActor* prismaticActor1; const PxType type = data->prismaticJoint->getConcreteType(); if(type == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* artiPrismaticJoint = static_cast<const PxArticulationJointReducedCoordinate*>(data->prismaticJoint); prismaticActor0 = &artiPrismaticJoint->getParentArticulationLink(); prismaticActor1 = &artiPrismaticJoint->getChildArticulationLink(); px = artiPrismaticJoint->getJointPosition(PxArticulationAxis::eX); } else { const PxJoint* prismaticJoint = static_cast<const PxJoint*>(data->prismaticJoint); prismaticJoint->getActors(prismaticActor0, prismaticActor1); if(type==PxJointConcreteType::ePRISMATIC) px = static_cast<const PxPrismaticJoint*>(prismaticJoint)->getPosition(); else if(type==PxJointConcreteType::eD6) px = prismaticJoint->getRelativeTransform().p.x; } if(rackActor0 == prismaticActor0 || rackActor1 == prismaticActor0) Sign1 = -1.0f; else if(rackActor0 == prismaticActor1 || rackActor1 == prismaticActor1) Sign1 = 1.0f; else PX_ASSERT(0); } // printf("px: %f\n", px); data->px = Sign1*px; data->vangle = Sign0*mVirtualAngle0; markDirty(); } void RackAndPinionJoint::resetError() { mVirtualAngle0 = 0.0f; mPersistentAngle0 = 0.0f; mInitDone = false; } static void RackAndPinionJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) { const RackAndPinionJointData& data = *reinterpret_cast<const RackAndPinionJointData*>(constantBlock); // Visualize joint frames PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); viz.visualizeJointFrames(cA2w, cB2w); } if(0) { const RackAndPinionJointData& data = *reinterpret_cast<const RackAndPinionJointData*>(constantBlock); if(0) { PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); const PxVec3 gearAxis0 = cA2w.q.getBasisVector0(); const PxVec3 rackPrismaticAxis = cB2w.q.getBasisVector0(); viz.visualizeLine(cA2w.p, cA2w.p + gearAxis0, 0xff0000ff); viz.visualizeLine(cB2w.p, cB2w.p + rackPrismaticAxis, 0xff0000ff); } } } //TAG:solverprepshader static PxU32 RackAndPinionJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const RackAndPinionJointData& data = *reinterpret_cast<const RackAndPinionJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); cA2wOut = cB2w.p; cB2wOut = cB2w.p; const PxVec3 gearAxis = cA2w.q.getBasisVector0(); const PxVec3 rackPrismaticAxis = cB2w.q.getBasisVector0(); // PT: this optional bit of code tries to fix the ratio for cases where the "same" rack is moved e.g. above or below a gear. // In that case the rack would move in one direction or another depending on its position compared to the gear, and to avoid // having to use a negative ratio in one of these cases this code tries to compute the proper sign and handle both cases the // same way from the user's perspective. This created unexpected issues in ill-defined cases where e.g. the gear and the rack // completely overlap, and we end up with a +0 or -0 for "dp" in the code below. So now this code disables itself in these // cases but it would probably be better to disable it entirely. We don't do it though since it could break existing scenes. // We might want to revisit these decisions at some point. float Coeff = 1.0f; const float epsilon = 0.001f; const PxVec3 delta = cB2w.p - cA2w.p; if(delta.magnitudeSquared()>epsilon*epsilon) { const PxVec3 velocity = gearAxis.cross(delta); if(velocity.magnitudeSquared()>epsilon*epsilon) { const float dp = velocity.dot(rackPrismaticAxis); Coeff = fabsf(dp)>epsilon ? PxSign(dp) : 1.0f; } } Px1DConstraint& con = constraints[0]; con.linear0 = PxVec3(0.0f); con.linear1 = rackPrismaticAxis * data.ratio*Coeff; con.angular0 = gearAxis; con.angular1 = PxVec3(0.0f); con.geometricError = -Coeff*data.px*data.ratio - data.vangle; con.minImpulse = -PX_MAX_F32; con.maxImpulse = PX_MAX_F32; con.velocityTarget = 0.f; con.forInternalUse = 0.f; con.solveHint = 0; con.flags = Px1DConstraintFlag::eOUTPUT_FORCE|Px1DConstraintFlag::eANGULAR_CONSTRAINT; con.mods.bounce.restitution = 0.0f; con.mods.bounce.velocityThreshold = 0.0f; return 1; } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gRackAndPinionJointShaders = { RackAndPinionJointSolverPrep, RackAndPinionJointVisualize, PxConstraintFlag::eALWAYS_UPDATE }; PxConstraintSolverPrep RackAndPinionJoint::getPrep() const { return gRackAndPinionJointShaders.solverPrep; } PxRackAndPinionJoint* physx::PxRackAndPinionJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxRackAndPinionJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxRackAndPinionJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxRackAndPinionJointCreate: at least one actor must be dynamic"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxRackAndPinionJointCreate: actors must be different"); return createJointT<RackAndPinionJoint, RackAndPinionJointData>(physics, actor0, localFrame0, actor1, localFrame1, gRackAndPinionJointShaders); } // PX_SERIALIZATION void RackAndPinionJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gRackAndPinionJointShaders); RackAndPinionJointData* data = static_cast<RackAndPinionJointData*>(mData); context.translatePxBase(data->hingeJoint); context.translatePxBase(data->prismaticJoint); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD template<> void physx::Ext::omniPvdInitJoint<RackAndPinionJoint>(RackAndPinionJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxRackAndPinionJoint& j = static_cast<PxRackAndPinionJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRackAndPinionJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eRACK_AND_PINION); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRackAndPinionJoint, ratio, j, joint.getRatio()) OMNI_PVD_WRITE_SCOPE_END } #endif
15,195
C++
37.568528
184
0.760777
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtD6JointCreate.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/PxD6JointCreate.h" #include "extensions/PxD6Joint.h" #include "extensions/PxFixedJoint.h" #include "extensions/PxRevoluteJoint.h" #include "extensions/PxSphericalJoint.h" #include "extensions/PxPrismaticJoint.h" #include "extensions/PxDistanceJoint.h" #include "PxPhysics.h" using namespace physx; static const PxVec3 gX(1.0f, 0.0f, 0.0f); PxJoint* physx::PxD6JointCreate_Fixed(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, bool useD6) { const PxTransform jointFrame0(localPos0); const PxTransform jointFrame1(localPos1); if(useD6) // PT: by default all D6 axes are locked, i.e. it is a fixed joint. return PxD6JointCreate(physics, actor0, jointFrame0, actor1, jointFrame1); else return PxFixedJointCreate(physics, actor0, jointFrame0, actor1, jointFrame1); } PxJoint* physx::PxD6JointCreate_Distance(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, float maxDist, bool useD6) { const PxTransform localFrame0(localPos0); const PxTransform localFrame1(localPos1); if(useD6) { PxD6Joint* j = PxD6JointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eX, PxD6Motion::eLIMITED); j->setMotion(PxD6Axis::eY, PxD6Motion::eLIMITED); j->setMotion(PxD6Axis::eZ, PxD6Motion::eLIMITED); j->setDistanceLimit(PxJointLinearLimit(maxDist)); return j; } else { PxDistanceJoint* j = PxDistanceJointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setDistanceJointFlag(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED, true); j->setMaxDistance(maxDist); return j; } } PxJoint* physx::PxD6JointCreate_Prismatic(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float minLimit, float maxLimit, bool useD6) { const PxQuat q = PxShortestRotation(gX, axis); const PxTransform localFrame0(localPos0, q); const PxTransform localFrame1(localPos1, q); const PxJointLinearLimitPair limit(PxTolerancesScale(), minLimit, maxLimit); if(useD6) { PxD6Joint* j = PxD6JointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setMotion(PxD6Axis::eX, PxD6Motion::eFREE); if(minLimit==maxLimit) j->setMotion(PxD6Axis::eX, PxD6Motion::eLOCKED); else if(minLimit>maxLimit) j->setMotion(PxD6Axis::eX, PxD6Motion::eFREE); else// if(minLimit<maxLimit) { j->setMotion(PxD6Axis::eX, PxD6Motion::eLIMITED); j->setLinearLimit(PxD6Axis::eX, limit); } return j; } else { PxPrismaticJoint* j = PxPrismaticJointCreate(physics, actor0, localFrame0, actor1, localFrame1); if(minLimit<maxLimit) { j->setPrismaticJointFlag(PxPrismaticJointFlag::eLIMIT_ENABLED, true); j->setLimit(limit); } return j; } } PxJoint* physx::PxD6JointCreate_Revolute(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float minLimit, float maxLimit, bool useD6) { const PxQuat q = PxShortestRotation(gX, axis); const PxTransform localFrame0(localPos0, q); const PxTransform localFrame1(localPos1, q); const PxJointAngularLimitPair limit(minLimit, maxLimit); if(useD6) { PxD6Joint* j = PxD6JointCreate(physics, actor0, localFrame0, actor1, localFrame1); if(minLimit==maxLimit) j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eLOCKED); else if(minLimit>maxLimit) j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); else// if(minLimit<maxLimit) { j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eLIMITED); j->setTwistLimit(limit); } return j; } else { PxRevoluteJoint* j = PxRevoluteJointCreate(physics, actor0, localFrame0, actor1, localFrame1); if(minLimit<maxLimit) { j->setRevoluteJointFlag(PxRevoluteJointFlag::eLIMIT_ENABLED, true); j->setLimit(limit); } return j; } } PxJoint* physx::PxD6JointCreate_Spherical(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float limit1, float limit2, bool useD6) { const PxQuat q = PxShortestRotation(gX, axis); const PxTransform localFrame0(localPos0, q); const PxTransform localFrame1(localPos1, q); const PxJointLimitCone limit(limit1, limit2); if(useD6) { PxD6Joint* j = PxD6JointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); if(limit1>0.0f && limit2>0.0f) { j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eLIMITED); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eLIMITED); j->setSwingLimit(limit); } else { j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); } return j; } else { PxSphericalJoint* j = PxSphericalJointCreate(physics, actor0, localFrame0, actor1, localFrame1); if(limit1>0.0f && limit2>0.0f) { j->setSphericalJointFlag(PxSphericalJointFlag::eLIMIT_ENABLED, true); j->setLimitCone(limit); } return j; } } PxJoint* physx::PxD6JointCreate_GenericCone(float& apiroty, float& apirotz, PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, float minLimit1, float maxLimit1, float minLimit2, float maxLimit2, bool useD6) { const float DesiredMinSwingY = minLimit1; const float DesiredMaxSwingY = maxLimit1; const float DesiredMinSwingZ = minLimit2; const float DesiredMaxSwingZ = maxLimit2; const float APIMaxY = (DesiredMaxSwingY - DesiredMinSwingY)*0.5f; const float APIMaxZ = (DesiredMaxSwingZ - DesiredMinSwingZ)*0.5f; const float APIRotY = (DesiredMaxSwingY + DesiredMinSwingY)*0.5f; const float APIRotZ = (DesiredMaxSwingZ + DesiredMinSwingZ)*0.5f; apiroty = APIRotY; apirotz = APIRotZ; const PxQuat RotY = PxGetRotYQuat(APIRotY); const PxQuat RotZ = PxGetRotZQuat(APIRotZ); const PxQuat Rot = RotY * RotZ; const PxTransform localFrame0(localPos0, Rot); const PxTransform localFrame1(localPos1); const PxJointLimitCone limit(APIMaxY, APIMaxZ); if(useD6) { PxD6Joint* j = PxD6JointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eLIMITED); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eLIMITED); j->setSwingLimit(limit); return j; } else { PxSphericalJoint* j = PxSphericalJointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setSphericalJointFlag(PxSphericalJointFlag::eLIMIT_ENABLED, true); j->setLimitCone(limit); return j; } } PxJoint* physx::PxD6JointCreate_Pyramid(PxPhysics& physics, PxRigidActor* actor0, const PxVec3& localPos0, PxRigidActor* actor1, const PxVec3& localPos1, const PxVec3& axis, float minLimit1, float maxLimit1, float minLimit2, float maxLimit2) { const PxQuat q = PxShortestRotation(gX, axis); const PxTransform localFrame0(localPos0, q); const PxTransform localFrame1(localPos1, q); const PxJointLimitPyramid limit(minLimit1, maxLimit1, minLimit2, maxLimit2); PxD6Joint* j = PxD6JointCreate(physics, actor0, localFrame0, actor1, localFrame1); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); if(limit.isValid()) { j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eLIMITED); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eLIMITED); j->setPyramidSwingLimit(limit); } else { j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); } return j; }
9,426
C++
36.557769
269
0.756525
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRaycastCCD.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 "geometry/PxSphereGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "geometry/PxConvexMesh.h" #include "extensions/PxShapeExt.h" #include "extensions/PxRaycastCCD.h" #include "PxScene.h" #include "PxRigidDynamic.h" #include "foundation/PxArray.h" using namespace physx; namespace physx { class RaycastCCDManagerInternal { PX_NOCOPY(RaycastCCDManagerInternal) public: RaycastCCDManagerInternal(PxScene* scene) : mScene(scene) {} ~RaycastCCDManagerInternal(){} bool registerRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape); bool unregisterRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape); void doRaycastCCD(bool doDynamicDynamicCCD); struct CCDObject { PX_FORCE_INLINE CCDObject(PxRigidDynamic* actor, PxShape* shape, const PxVec3& witness) : mActor(actor), mShape(shape), mWitness(witness) {} PxRigidDynamic* mActor; PxShape* mShape; PxVec3 mWitness; }; private: PxScene* mScene; physx::PxArray<CCDObject> mObjects; }; } static PxVec3 getShapeCenter(PxShape* shape, const PxTransform& pose) { PxVec3 offset(0.0f); const PxGeometry& geom = shape->getGeometry(); if(geom.getType()==PxGeometryType::eCONVEXMESH) { const PxConvexMeshGeometry& geometry = static_cast<const PxConvexMeshGeometry&>(geom); PxReal mass; PxMat33 localInertia; PxVec3 localCenterOfMass; geometry.convexMesh->getMassInformation(mass, localInertia, localCenterOfMass); offset += localCenterOfMass; } return pose.transform(offset); } static PX_FORCE_INLINE PxVec3 getShapeCenter(PxRigidActor* actor, PxShape* shape) { const PxTransform pose = PxShapeExt::getGlobalPose(*shape, *actor); return getShapeCenter(shape, pose); } static PxReal computeInternalRadius(PxRigidActor* actor, PxShape* shape, const PxVec3& dir) { const PxBounds3 bounds = PxShapeExt::getWorldBounds(*shape, *actor); const PxReal diagonal = (bounds.maximum - bounds.minimum).magnitude(); const PxReal offsetFromOrigin = diagonal * 2.0f; PxTransform pose = PxShapeExt::getGlobalPose(*shape, *actor); PxReal internalRadius = 0.0f; const PxReal length = offsetFromOrigin*2.0f; const PxGeometry& geom = shape->getGeometry(); switch(geom.getType()) { case PxGeometryType::eSPHERE: { const PxSphereGeometry& geometry = static_cast<const PxSphereGeometry&>(geom); internalRadius = geometry.radius; } break; case PxGeometryType::eBOX: case PxGeometryType::eCAPSULE: { pose.p = PxVec3(0.0f); const PxVec3 virtualOrigin = pose.p + dir * offsetFromOrigin; PxRaycastHit hit; PxU32 nbHits = PxGeometryQuery::raycast(virtualOrigin, -dir, shape->getGeometry(), pose, length, PxHitFlags(0), 1, &hit); PX_UNUSED(nbHits); PX_ASSERT(nbHits); internalRadius = offsetFromOrigin - hit.distance; } break; case PxGeometryType::eCONVEXMESH: { PxVec3 shapeCenter = getShapeCenter(shape, pose); shapeCenter -= pose.p; pose.p = PxVec3(0.0f); const PxVec3 virtualOrigin = shapeCenter + dir * offsetFromOrigin; PxRaycastHit hit; PxU32 nbHits = PxGeometryQuery::raycast(virtualOrigin, -dir, shape->getGeometry(), pose, length, PxHitFlags(0), 1, &hit); PX_UNUSED(nbHits); PX_ASSERT(nbHits); internalRadius = offsetFromOrigin - hit.distance; } break; default: break; } return internalRadius; } class CCDRaycastFilterCallback : public PxQueryFilterCallback { public: CCDRaycastFilterCallback(PxRigidActor* actor, PxShape* shape) : mActor(actor), mShape(shape){} PxRigidActor* mActor; PxShape* mShape; virtual PxQueryHitType::Enum preFilter(const PxFilterData&, const PxShape* shape, const PxRigidActor* actor, PxHitFlags&) { if(mActor==actor && mShape==shape) return PxQueryHitType::eNONE; return PxQueryHitType::eBLOCK; } virtual PxQueryHitType::Enum postFilter(const PxFilterData&, const PxQueryHit&, const PxShape*, const PxRigidActor*) { return PxQueryHitType::eNONE; } }; static bool CCDRaycast(PxScene* scene, PxRigidActor* actor, PxShape* shape, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxRaycastHit& hit, bool dyna_dyna) { const PxQueryFlags qf(dyna_dyna ? PxQueryFlags(PxQueryFlag::eSTATIC|PxQueryFlag::eDYNAMIC|PxQueryFlag::ePREFILTER) : PxQueryFlags(PxQueryFlag::eSTATIC)); const PxQueryFilterData filterData(PxFilterData(), qf); CCDRaycastFilterCallback CB(actor, shape); PxRaycastBuffer buf1; scene->raycast(origin, unitDir, distance, buf1, PxHitFlags(0), filterData, &CB); hit = buf1.block; return buf1.hasBlock; } static PxRigidDynamic* canDoCCD(PxRigidActor& actor, PxShape* /*shape*/) { if(actor.getConcreteType()!=PxConcreteType::eRIGID_DYNAMIC) return NULL; // PT: no need to do it for statics PxRigidDynamic* dyna = static_cast<PxRigidDynamic*>(&actor); const PxU32 nbShapes = dyna->getNbShapes(); if(nbShapes!=1) return NULL; // PT: only works with simple actors for now if(dyna->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC) return NULL; // PT: no need to do it for kinematics return dyna; } static bool doRaycastCCD(PxScene* scene, const RaycastCCDManagerInternal::CCDObject& object, PxTransform& newPose, PxVec3& newShapeCenter, bool dyna_dyna) { PxRigidDynamic* dyna = canDoCCD(*object.mActor, object.mShape); if(!dyna) return true; bool updateCCDWitness = true; const PxVec3 offset = newPose.p - newShapeCenter; const PxVec3& origin = object.mWitness; const PxVec3& dest = newShapeCenter; PxVec3 dir = dest - origin; const PxReal length = dir.magnitude(); if(length!=0.0f) { dir /= length; const PxReal internalRadius = computeInternalRadius(object.mActor, object.mShape, dir); PxRaycastHit hit; if(internalRadius!=0.0f && CCDRaycast(scene, object.mActor, object.mShape, origin, dir, length, hit, dyna_dyna)) { updateCCDWitness = false; const PxReal radiusLimit = internalRadius * 0.75f; if(hit.distance>radiusLimit) { newShapeCenter = origin + dir * (hit.distance - radiusLimit); } else { if(hit.actor->getConcreteType()==PxConcreteType::eRIGID_DYNAMIC) return true; newShapeCenter = origin; } newPose.p = offset + newShapeCenter; const PxTransform shapeLocalPose = object.mShape->getLocalPose(); const PxTransform inverseShapeLocalPose = shapeLocalPose.getInverse(); const PxTransform newGlobalPose = newPose * inverseShapeLocalPose; dyna->setGlobalPose(newGlobalPose); } } return updateCCDWitness; } bool RaycastCCDManagerInternal::registerRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape) { if(!actor || !shape) return false; mObjects.pushBack(CCDObject(actor, shape, getShapeCenter(actor, shape))); return true; } bool RaycastCCDManagerInternal::unregisterRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape) { if(!actor || !shape) return false; const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { if(mObjects[i].mActor==actor && mObjects[i].mShape==shape) { mObjects[i] = mObjects[nbObjects-1]; mObjects.popBack(); return true; } } return false; } void RaycastCCDManagerInternal::doRaycastCCD(bool doDynamicDynamicCCD) { const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { CCDObject& object = mObjects[i]; if(object.mActor->isSleeping()) continue; PxTransform newPose = PxShapeExt::getGlobalPose(*object.mShape, *object.mActor); PxVec3 newShapeCenter = getShapeCenter(object.mShape, newPose); if(::doRaycastCCD(mScene, object, newPose, newShapeCenter, doDynamicDynamicCCD)) object.mWitness = newShapeCenter; } } RaycastCCDManager::RaycastCCDManager(PxScene* scene) { mImpl = new RaycastCCDManagerInternal(scene); } RaycastCCDManager::~RaycastCCDManager() { delete mImpl; } bool RaycastCCDManager::registerRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape) { return mImpl->registerRaycastCCDObject(actor, shape); } bool RaycastCCDManager::unregisterRaycastCCDObject(PxRigidDynamic* actor, PxShape* shape) { return mImpl->unregisterRaycastCCDObject(actor, shape); } void RaycastCCDManager::doRaycastCCD(bool doDynamicDynamicCCD) { mImpl->doRaycastCCD(doDynamicDynamicCCD); }
9,900
C++
29.940625
178
0.751212
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtD6Joint.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/PxRenderBuffer.h" #include "ExtD6Joint.h" #include "ExtConstraintHelper.h" #include "CmConeLimitHelper.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; D6Joint::D6Joint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : D6JointT (PxJointConcreteType::eD6, actor0, localFrame0, actor1, localFrame1, "D6JointData"), mRecomputeMotion(true) { D6JointData* data = static_cast<D6JointData*>(mData); for(PxU32 i=0;i<6;i++) data->motion[i] = PxD6Motion::eLOCKED; data->twistLimit = PxJointAngularLimitPair(-PxPi/2, PxPi/2); data->swingLimit = PxJointLimitCone(PxPi/2, PxPi/2); data->pyramidSwingLimit = PxJointLimitPyramid(-PxPi/2, PxPi/2, -PxPi/2, PxPi/2); data->distanceLimit = PxJointLinearLimit(PX_MAX_F32); data->distanceMinDist = 1e-6f*scale.length; data->linearLimitX = PxJointLinearLimitPair(scale); data->linearLimitY = PxJointLinearLimitPair(scale); data->linearLimitZ = PxJointLinearLimitPair(scale); for(PxU32 i=0;i<PxD6Drive::eCOUNT;i++) data->drive[i] = PxD6JointDrive(); data->drivePosition = PxTransform(PxIdentity); data->driveLinearVelocity = PxVec3(0.0f); data->driveAngularVelocity = PxVec3(0.0f); data->mUseDistanceLimit = false; data->mUseNewLinearLimits = false; data->mUseConeLimit = false; data->mUsePyramidLimits = false; } PxD6Motion::Enum D6Joint::getMotion(PxD6Axis::Enum index) const { return data().motion[index]; } void D6Joint::setMotion(PxD6Axis::Enum index, PxD6Motion::Enum t) { data().motion[index] = t; mRecomputeMotion = true; markDirty(); #if PX_SUPPORT_OMNI_PVD PxD6Motion::Enum motions[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) motions[i] = getMotion(PxD6Axis::Enum(i)); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, motions, static_cast<PxD6Joint&>(*this), motions, PxD6Axis::eCOUNT) #endif } PxReal D6Joint::getTwistAngle() const { return getTwistAngle_Internal(); } PxReal D6Joint::getSwingYAngle() const { return getSwingYAngle_Internal(); } PxReal D6Joint::getSwingZAngle() const { return getSwingZAngle_Internal(); } PxD6JointDrive D6Joint::getDrive(PxD6Drive::Enum index) const { return data().drive[index]; } void D6Joint::setDrive(PxD6Drive::Enum index, const PxD6JointDrive& d) { PX_CHECK_AND_RETURN(d.isValid(), "PxD6Joint::setDrive: drive is invalid"); data().drive[index] = d; mRecomputeMotion = true; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); PxReal forceLimit[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) forceLimit[i] = getDrive(PxD6Drive::Enum(i)).forceLimit; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveForceLimit, j, forceLimit, PxD6Axis::eCOUNT) PxD6JointDriveFlags flags[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) flags[i] = getDrive(PxD6Drive::Enum(i)).flags; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveFlags, j, flags, PxD6Axis::eCOUNT) PxReal stiffness[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) stiffness[i] = getDrive(PxD6Drive::Enum(i)).stiffness; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveStiffness, j, stiffness, PxD6Axis::eCOUNT) PxReal damping[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) damping[i] = getDrive(PxD6Drive::Enum(i)).damping; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveDamping, j, damping, PxD6Axis::eCOUNT) OMNI_PVD_WRITE_SCOPE_END #endif } void D6Joint::setDistanceLimit(const PxJointLinearLimit& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setDistanceLimit: limit invalid"); data().distanceLimit = l; data().mUseDistanceLimit = true; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, distanceLimitValue, j, l.value) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, distanceLimitRestitution, j, l.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, distanceLimitBounceThreshold, j, l.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, distanceLimitStiffness, j, l.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, distanceLimitDamping, j, l.damping) OMNI_PVD_WRITE_SCOPE_END #endif } PxJointLinearLimit D6Joint::getDistanceLimit() const { return data().distanceLimit; } void D6Joint::setLinearLimit(PxD6Axis::Enum axis, const PxJointLinearLimitPair& limit) { PX_CHECK_AND_RETURN(axis>=PxD6Axis::eX && axis<=PxD6Axis::eZ, "PxD6Joint::setLinearLimit: invalid axis value"); PX_CHECK_AND_RETURN(limit.isValid(), "PxD6Joint::setLinearLimit: limit invalid"); D6JointData& d = data(); if(axis==PxD6Axis::eX) d.linearLimitX = limit; else if(axis==PxD6Axis::eY) d.linearLimitY = limit; else if(axis==PxD6Axis::eZ) d.linearLimitZ = limit; else return; d.mUseNewLinearLimits = true; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); const PxU32 valueCount = 3; PxReal values[valueCount]; for (PxU32 i = 0; i < valueCount; ++i) values[i] = getLinearLimit(PxD6Axis::Enum(i)).lower; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, linearLimitLower, j, values, valueCount) for (PxU32 i = 0; i < valueCount; ++i) values[i] = getLinearLimit(PxD6Axis::Enum(i)).upper; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, linearLimitUpper, j, values, valueCount) for (PxU32 i = 0; i < valueCount; ++i) values[i] = getLinearLimit(PxD6Axis::Enum(i)).restitution; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, linearLimitRestitution, j, values, valueCount) for (PxU32 i = 0; i < valueCount; ++i) values[i] = getLinearLimit(PxD6Axis::Enum(i)).bounceThreshold; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, linearLimitBounceThreshold, j, values, valueCount) for (PxU32 i = 0; i < valueCount; ++i) values[i] = getLinearLimit(PxD6Axis::Enum(i)).stiffness; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, linearLimitStiffness, j, values, valueCount) for (PxU32 i = 0; i < valueCount; ++i) values[i] = getLinearLimit(PxD6Axis::Enum(i)).damping; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, linearLimitDamping, j, values, valueCount) OMNI_PVD_WRITE_SCOPE_END #endif } PxJointLinearLimitPair D6Joint::getLinearLimit(PxD6Axis::Enum axis) const { PX_CHECK_AND_RETURN_VAL(axis>=PxD6Axis::eX && axis<=PxD6Axis::eZ, "PxD6Joint::getLinearLimit: invalid axis value", PxJointLinearLimitPair(PxTolerancesScale(), 0.0f, 0.0f)); const D6JointData& d = data(); if(axis==PxD6Axis::eX) return d.linearLimitX; else if(axis==PxD6Axis::eY) return d.linearLimitY; else if(axis==PxD6Axis::eZ) return d.linearLimitZ; return PxJointLinearLimitPair(PxTolerancesScale(), 0.0f, 0.0f); } PxJointAngularLimitPair D6Joint::getTwistLimit() const { return data().twistLimit; } void D6Joint::setTwistLimit(const PxJointAngularLimitPair& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setTwistLimit: limit invalid"); // PT: the tangent version is not compatible with the double-cover feature, since the potential limit extent in that case is 4*PI. // i.e. we'd potentially take the tangent of something equal to PI/2. So the tangent stuff makes the limits less accurate, and it // also reduces the available angular range for the joint. All that for questionable performance gains. PX_CHECK_AND_RETURN(l.lower>-PxTwoPi && l.upper<PxTwoPi , "PxD6Joint::twist limit must be strictly between -2*PI and 2*PI"); data().twistLimit = l; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistLimitLower, j, l.lower) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistLimitUpper, j, l.upper) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistLimitRestitution, j, l.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistLimitBounceThreshold, j, l.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistLimitStiffness, j, l.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistLimitDamping, j, l.damping) OMNI_PVD_WRITE_SCOPE_END #endif } PxJointLimitPyramid D6Joint::getPyramidSwingLimit() const { return data().pyramidSwingLimit; } void D6Joint::setPyramidSwingLimit(const PxJointLimitPyramid& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setPyramidSwingLimit: limit invalid"); data().pyramidSwingLimit = l; data().mUsePyramidLimits = true; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitYAngleMin, j, l.yAngleMin) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitYAngleMax, j, l.yAngleMax) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitZAngleMin, j, l.zAngleMin) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitZAngleMax, j, l.zAngleMax) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitRestitution, j, l.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitBounceThreshold, j, l.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitStiffness, j, l.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, pyramidSwingLimitDamping, j, l.damping) OMNI_PVD_WRITE_SCOPE_END #endif } PxJointLimitCone D6Joint::getSwingLimit() const { return data().swingLimit; } void D6Joint::setSwingLimit(const PxJointLimitCone& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setSwingLimit: limit invalid"); data().swingLimit = l; data().mUseConeLimit = true; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingLimitYAngle, j, l.yAngle) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingLimitZAngle, j, l.zAngle) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingLimitRestitution, j, l.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingLimitBounceThreshold, j, l.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingLimitStiffness, j, l.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingLimitDamping, j, l.damping) OMNI_PVD_WRITE_SCOPE_END #endif } PxTransform D6Joint::getDrivePosition() const { return data().drivePosition; } void D6Joint::setDrivePosition(const PxTransform& pose, bool autowake) { PX_CHECK_AND_RETURN(pose.isSane(), "PxD6Joint::setDrivePosition: pose invalid"); data().drivePosition = pose.getNormalized(); if(autowake) wakeUpActors(); markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, drivePosition, static_cast<PxD6Joint&>(*this), pose) } void D6Joint::getDriveVelocity(PxVec3& linear, PxVec3& angular) const { linear = data().driveLinearVelocity; angular = data().driveAngularVelocity; } void D6Joint::setDriveVelocity(const PxVec3& linear, const PxVec3& angular, bool autowake) { PX_CHECK_AND_RETURN(linear.isFinite() && angular.isFinite(), "PxD6Joint::setDriveVelocity: velocity invalid"); data().driveLinearVelocity = linear; data().driveAngularVelocity = angular; if(autowake) wakeUpActors(); markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveLinVelocity, j, linear) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveAngVelocity, j, angular) OMNI_PVD_WRITE_SCOPE_END #endif } void* D6Joint::prepareData() { D6JointData& d = data(); if(mRecomputeMotion) { mRecomputeMotion = false; d.driving = 0; d.limited = 0; d.locked = 0; for(PxU32 i=0;i<PxD6Axis::eCOUNT;i++) { if(d.motion[i] == PxD6Motion::eLIMITED) d.limited |= 1<<i; else if(d.motion[i] == PxD6Motion::eLOCKED) d.locked |= 1<<i; } // a linear direction isn't driven if it's locked if(active(PxD6Drive::eX) && d.motion[PxD6Axis::eX]!=PxD6Motion::eLOCKED) d.driving |= 1<< PxD6Drive::eX; if(active(PxD6Drive::eY) && d.motion[PxD6Axis::eY]!=PxD6Motion::eLOCKED) d.driving |= 1<< PxD6Drive::eY; if(active(PxD6Drive::eZ) && d.motion[PxD6Axis::eZ]!=PxD6Motion::eLOCKED) d.driving |= 1<< PxD6Drive::eZ; // SLERP drive requires all angular dofs unlocked, and inhibits swing/twist const bool swing1Locked = d.motion[PxD6Axis::eSWING1] == PxD6Motion::eLOCKED; const bool swing2Locked = d.motion[PxD6Axis::eSWING2] == PxD6Motion::eLOCKED; const bool twistLocked = d.motion[PxD6Axis::eTWIST] == PxD6Motion::eLOCKED; if(active(PxD6Drive::eSLERP) && !swing1Locked && !swing2Locked && !twistLocked) d.driving |= 1<<PxD6Drive::eSLERP; else { if(active(PxD6Drive::eTWIST) && !twistLocked) d.driving |= 1<<PxD6Drive::eTWIST; if(active(PxD6Drive::eSWING) && (!swing1Locked || !swing2Locked)) d.driving |= 1<< PxD6Drive::eSWING; } } this->D6JointT::prepareData(); return mData; } static PX_FORCE_INLINE PxReal computePhi(const PxQuat& q) { PxQuat twist = q; twist.normalize(); PxReal angle = twist.getAngle(); if(twist.x<0.0f) angle = -angle; return angle; } static void visualizeAngularLimit(PxConstraintVisualizer& viz, const PxTransform& t, float swingLimitYZ) { viz.visualizeAngularLimit(t, -swingLimitYZ, swingLimitYZ); } static void visualizeDoubleCone(PxConstraintVisualizer& viz, const PxTransform& t, float swingLimitYZ) { viz.visualizeDoubleCone(t, swingLimitYZ); } static void visualizeCone(PxConstraintVisualizer& viz, const D6JointData& data, const PxTransform& cA2w) { viz.visualizeLimitCone(cA2w, PxTan(data.swingLimit.zAngle / 4), PxTan(data.swingLimit.yAngle / 4)); } static void visualizeLine(PxConstraintVisualizer& viz, const PxVec3& origin, const PxVec3& axis, const PxJointLinearLimitPair& limit) { const PxVec3 p0 = origin + axis * limit.lower; const PxVec3 p1 = origin + axis * limit.upper; viz.visualizeLine(p0, p1, PxU32(PxDebugColor::eARGB_YELLOW)); } static void visualizeQuad(PxConstraintVisualizer& viz, const PxVec3& origin, const PxVec3& axis0, const PxJointLinearLimitPair& limit0, const PxVec3& axis1, const PxJointLinearLimitPair& limit1) { const PxU32 color = PxU32(PxDebugColor::eARGB_YELLOW); const PxVec3 l0 = axis0 * limit0.lower; const PxVec3 u0 = axis0 * limit0.upper; const PxVec3 l1 = axis1 * limit1.lower; const PxVec3 u1 = axis1 * limit1.upper; const PxVec3 p0 = origin + l0 + l1; const PxVec3 p1 = origin + u0 + l1; const PxVec3 p2 = origin + u0 + u1; const PxVec3 p3 = origin + l0 + u1; viz.visualizeLine(p0, p1, color); viz.visualizeLine(p1, p2, color); viz.visualizeLine(p2, p3, color); viz.visualizeLine(p3, p0, color); } static void visualizeBox(PxConstraintVisualizer& viz, const PxVec3& origin, const PxVec3& axis0, const PxJointLinearLimitPair& limit0, const PxVec3& axis1, const PxJointLinearLimitPair& limit1, const PxVec3& axis2, const PxJointLinearLimitPair& limit2) { const PxU32 color = PxU32(PxDebugColor::eARGB_YELLOW); const PxVec3 l0 = axis0 * limit0.lower; const PxVec3 u0 = axis0 * limit0.upper; const PxVec3 l1 = axis1 * limit1.lower; const PxVec3 u1 = axis1 * limit1.upper; const PxVec3 l2 = axis2 * limit2.lower; const PxVec3 u2 = axis2 * limit2.upper; const PxVec3 p0 = origin + l0 + l1 + l2; const PxVec3 p1 = origin + u0 + l1 + l2; const PxVec3 p2 = origin + u0 + u1 + l2; const PxVec3 p3 = origin + l0 + u1 + l2; const PxVec3 p0b = origin + l0 + l1 + u2; const PxVec3 p1b = origin + u0 + l1 + u2; const PxVec3 p2b = origin + u0 + u1 + u2; const PxVec3 p3b = origin + l0 + u1 + u2; viz.visualizeLine(p0, p1, color); viz.visualizeLine(p1, p2, color); viz.visualizeLine(p2, p3, color); viz.visualizeLine(p3, p0, color); viz.visualizeLine(p0b, p1b, color); viz.visualizeLine(p1b, p2b, color); viz.visualizeLine(p2b, p3b, color); viz.visualizeLine(p3b, p0b, color); viz.visualizeLine(p0, p0b, color); viz.visualizeLine(p1, p1b, color); viz.visualizeLine(p2, p2b, color); viz.visualizeLine(p3, p3b, color); } static float computeLimitedDistance(const D6JointData& data, const PxTransform& cB2cA, const PxMat33& cA2w_m, PxVec3& _limitDir) { PxVec3 limitDir(0.0f); for(PxU32 i = 0; i<3; i++) { if(data.limited & (1 << (PxD6Axis::eX + i))) limitDir += cA2w_m[i] * cB2cA.p[i]; } _limitDir = limitDir; return limitDir.magnitude(); } static void drawPyramid(PxConstraintVisualizer& viz, const D6JointData& data, const PxTransform& cA2w, const PxQuat& /*swing*/, bool /*useY*/, bool /*useZ*/) { struct Local { static void drawArc(PxConstraintVisualizer& _viz, const PxTransform& _cA2w, float ymin, float ymax, float zmin, float zmax, PxU32 color) { // PT: we use 32 segments for the cone case, so that's 32/4 segments per arc in the pyramid case const PxU32 nb = 32/4; PxVec3 prev(0.0f); for(PxU32 i=0;i<nb;i++) { const float coeff = float(i)/float(nb-1); const float y = coeff*ymax + (1.0f-coeff)*ymin; const float z = coeff*zmax + (1.0f-coeff)*zmin; const float r = 1.0f; PxMat33 my; PxSetRotZ(my, z); PxMat33 mz; PxSetRotY(mz, y); const PxVec3 p0 = (my*mz).transform(PxVec3(r, 0.0f, 0.0f)); const PxVec3 p0w = _cA2w.transform(p0); _viz.visualizeLine(_cA2w.p, p0w, color); if(i) _viz.visualizeLine(prev, p0w, color); prev = p0w; } } }; const PxJointLimitPyramid& l = data.pyramidSwingLimit; const PxU32 color = PxU32(PxDebugColor::eARGB_YELLOW); Local::drawArc(viz, cA2w, l.yAngleMin, l.yAngleMin, l.zAngleMin, l.zAngleMax, color); Local::drawArc(viz, cA2w, l.yAngleMax, l.yAngleMax, l.zAngleMin, l.zAngleMax, color); Local::drawArc(viz, cA2w, l.yAngleMin, l.yAngleMax, l.zAngleMin, l.zAngleMin, color); Local::drawArc(viz, cA2w, l.yAngleMin, l.yAngleMax, l.zAngleMax, l.zAngleMax, color); } static void D6JointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { const PxU32 SWING1_FLAG = 1<<PxD6Axis::eSWING1, SWING2_FLAG = 1<<PxD6Axis::eSWING2, TWIST_FLAG = 1<<PxD6Axis::eTWIST; const PxU32 ANGULAR_MASK = SWING1_FLAG | SWING2_FLAG | TWIST_FLAG; const PxU32 LINEAR_MASK = 1<<PxD6Axis::eX | 1<<PxD6Axis::eY | 1<<PxD6Axis::eZ; PX_UNUSED(ANGULAR_MASK); PX_UNUSED(LINEAR_MASK); const D6JointData& data = *reinterpret_cast<const D6JointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) viz.visualizeJointFrames(cA2w, cB2w); if(flags & PxConstraintVisualizationFlag::eLIMITS) { const PxTransform cB2cA = cA2w.transformInv(cB2w); const PxMat33Padded cA2w_m(cA2w.q); const PxMat33Padded cB2w_m(cB2w.q); if(data.mUseNewLinearLimits) { switch(data.limited) { case 1<<PxD6Axis::eX: visualizeLine(viz, cA2w.p, cA2w_m.column0, data.linearLimitX); break; case 1<<PxD6Axis::eY: visualizeLine(viz, cA2w.p, cA2w_m.column1, data.linearLimitY); break; case 1<<PxD6Axis::eZ: visualizeLine(viz, cA2w.p, cA2w_m.column2, data.linearLimitZ); break; case 1<<PxD6Axis::eX|1<<PxD6Axis::eY: visualizeQuad(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cA2w_m.column1, data.linearLimitY); break; case 1<<PxD6Axis::eX|1<<PxD6Axis::eZ: visualizeQuad(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cA2w_m.column2, data.linearLimitZ); break; case 1<<PxD6Axis::eY|1<<PxD6Axis::eZ: visualizeQuad(viz, cA2w.p, cA2w_m.column1, data.linearLimitY, cA2w_m.column2, data.linearLimitZ); break; case 1<<PxD6Axis::eX|1<<PxD6Axis::eY|1<<PxD6Axis::eZ: visualizeBox(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cA2w_m.column1, data.linearLimitY, cA2w_m.column2, data.linearLimitZ); break; } } if(data.mUseDistanceLimit) // PT: old linear/distance limit { PxVec3 limitDir; const float distance = computeLimitedDistance(data, cB2cA, cA2w_m, limitDir); // visualise only if some of the axis is limited if(distance > data.distanceMinDist) { PxU32 color = 0x00ff00; if(distance>data.distanceLimit.value) color = 0xff0000; viz.visualizeLine(cA2w.p, cB2w.p, color); } } PxQuat swing, twist; PxSeparateSwingTwist(cB2cA.q, swing, twist); if(data.limited&TWIST_FLAG) viz.visualizeAngularLimit(cA2w, data.twistLimit.lower, data.twistLimit.upper); const bool swing1Limited = (data.limited & SWING1_FLAG)!=0, swing2Limited = (data.limited & SWING2_FLAG)!=0; if(swing1Limited && swing2Limited) { if(data.mUseConeLimit) visualizeCone(viz, data, cA2w); if(data.mUsePyramidLimits) drawPyramid(viz, data, cA2w, swing, true, true); } else if(swing1Limited ^ swing2Limited) { const PxTransform yToX(PxVec3(0.0f), PxQuat(-PxPi/2.0f, PxVec3(0.0f, 0.0f, 1.0f))); const PxTransform zToX(PxVec3(0.0f), PxQuat(PxPi/2.0f, PxVec3(0.0f, 1.0f, 0.0f))); if(swing1Limited) { if(data.locked & SWING2_FLAG) { if(data.mUsePyramidLimits) drawPyramid(viz, data, cA2w, swing, true, false); else // PT:: tag: scalar transform*transform visualizeAngularLimit(viz, cA2w * yToX, data.swingLimit.yAngle); // PT: swing Y limited, swing Z locked } else if(!data.mUsePyramidLimits) // PT:: tag: scalar transform*transform visualizeDoubleCone(viz, cA2w * zToX, data.swingLimit.yAngle); // PT: swing Y limited, swing Z free } else { if(data.locked & SWING1_FLAG) { if(data.mUsePyramidLimits) drawPyramid(viz, data, cA2w, swing, false, true); else // PT:: tag: scalar transform*transform visualizeAngularLimit(viz, cA2w * zToX, data.swingLimit.zAngle); // PT: swing Z limited, swing Y locked } else if(!data.mUsePyramidLimits) // PT:: tag: scalar transform*transform visualizeDoubleCone(viz, cA2w * yToX, data.swingLimit.zAngle); // PT: swing Z limited, swing Y free } } } } static PX_FORCE_INLINE void setupSingleSwingLimit(joint::ConstraintHelper& ch, const D6JointData& data, const PxVec3& axis, float swingYZ, float swingW, float swingLimitYZ) { ch.anglePair(computeSwingAngle(swingYZ, swingW), -swingLimitYZ, swingLimitYZ, axis, data.swingLimit); } static PX_FORCE_INLINE void setupDualConeSwingLimits(joint::ConstraintHelper& ch, const D6JointData& data, const PxVec3& axis, float sin, float swingLimitYZ) { ch.anglePair(PxAsin(sin), -swingLimitYZ, swingLimitYZ, axis.getNormalized(), data.swingLimit); } static void setupConeSwingLimits(joint::ConstraintHelper& ch, const D6JointData& data, const PxQuat& swing, const PxTransform& cA2w) { PxVec3 axis; PxReal error; const Cm::ConeLimitHelperTanLess coneHelper(data.swingLimit.yAngle, data.swingLimit.zAngle); coneHelper.getLimit(swing, axis, error); ch.angularLimit(cA2w.rotate(axis), error, data.swingLimit); } static void setupPyramidSwingLimits(joint::ConstraintHelper& ch, const D6JointData& data, const PxQuat& swing, const PxTransform& cA2w, bool useY, bool useZ) { const PxQuat q = cA2w.q * swing; const PxJointLimitPyramid& l = data.pyramidSwingLimit; if(useY) ch.anglePair(computeSwingAngle(swing.y, swing.w), l.yAngleMin, l.yAngleMax, q.getBasisVector1(), l); if(useZ) ch.anglePair(computeSwingAngle(swing.z, swing.w), l.zAngleMin, l.zAngleMax, q.getBasisVector2(), l); } static void setupLinearLimit(joint::ConstraintHelper& ch, const PxJointLinearLimitPair& limit, const float origin, const PxVec3& axis) { ch.linearLimit(axis, origin, limit.upper, limit); ch.linearLimit(-axis, -origin, -limit.lower, limit); } //TAG:solverprepshader static PxU32 D6JointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool useExtendedLimits, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const D6JointData& data = *reinterpret_cast<const D6JointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); const PxU32 SWING1_FLAG = 1<<PxD6Axis::eSWING1; const PxU32 SWING2_FLAG = 1<<PxD6Axis::eSWING2; const PxU32 TWIST_FLAG = 1<<PxD6Axis::eTWIST; const PxU32 ANGULAR_MASK = SWING1_FLAG | SWING2_FLAG | TWIST_FLAG; const PxU32 LINEAR_MASK = 1<<PxD6Axis::eX | 1<<PxD6Axis::eY | 1<<PxD6Axis::eZ; const PxD6JointDrive* drives = data.drive; PxU32 locked = data.locked; const PxU32 limited = data.limited; const PxU32 driving = data.driving; // PT: it is a mistake to use the neighborhood operator since it // prevents us from using the quat's double-cover feature. if(!useExtendedLimits) joint::applyNeighborhoodOperator(cA2w, cB2w); const PxTransform cB2cA = cA2w.transformInv(cB2w); PX_ASSERT(data.c2b[0].isValid()); PX_ASSERT(data.c2b[1].isValid()); PX_ASSERT(cA2w.isValid()); PX_ASSERT(cB2w.isValid()); PX_ASSERT(cB2cA.isValid()); const PxMat33Padded cA2w_m(cA2w.q); const PxMat33Padded cB2w_m(cB2w.q); // handy for swing computation const PxVec3& bX = cB2w_m.column0; const PxVec3& aY = cA2w_m.column1; const PxVec3& aZ = cA2w_m.column2; if(driving & ((1<<PxD6Drive::eX)|(1<<PxD6Drive::eY)|(1<<PxD6Drive::eZ))) { // TODO: make drive unilateral if we are outside the limit const PxVec3 posErr = data.drivePosition.p - cB2cA.p; for(PxU32 i=0; i<3; i++) { // -driveVelocity because velTarget is child (body1) - parent (body0) and Jacobian is 1 for body0 and -1 for parent if(driving & (1<<(PxD6Drive::eX+i))) ch.linear(cA2w_m[i], -data.driveLinearVelocity[i], posErr[i], drives[PxD6Drive::eX+i]); } } if(driving & ((1<<PxD6Drive::eSLERP)|(1<<PxD6Drive::eSWING)|(1<<PxD6Drive::eTWIST))) { const PxQuat d2cA_q = cB2cA.q.dot(data.drivePosition.q)>0.0f ? data.drivePosition.q : -data.drivePosition.q; const PxVec3& v = data.driveAngularVelocity; const PxQuat delta = d2cA_q.getConjugate() * cB2cA.q; if(driving & (1<<PxD6Drive::eSLERP)) { const PxVec3 velTarget = -cA2w.rotate(data.driveAngularVelocity); PxVec3 axis[3] = { PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 1.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f) }; if(drives[PxD6Drive::eSLERP].stiffness!=0.0f) joint::computeJacobianAxes(axis, cA2w.q * d2cA_q, cB2w.q); // converges faster if there is only velocity drive for(PxU32 i=0; i<3; i++) ch.angular(axis[i], axis[i].dot(velTarget), -delta.getImaginaryPart()[i], drives[PxD6Drive::eSLERP], PxConstraintSolveHint::eSLERP_SPRING); } else { if(driving & (1<<PxD6Drive::eTWIST)) ch.angular(cA2w_m.column0, v.x, -2.0f * delta.x, drives[PxD6Drive::eTWIST]); if(driving & (1<<PxD6Drive::eSWING)) { const PxVec3 err = delta.getBasisVector0(); if(!(locked & SWING1_FLAG)) ch.angular(aY, v.y, err.z, drives[PxD6Drive::eSWING]); if(!(locked & SWING2_FLAG)) ch.angular(aZ, v.z, -err.y, drives[PxD6Drive::eSWING]); } } } if(limited & ANGULAR_MASK) { PxQuat swing, twist; PxSeparateSwingTwist(cB2cA.q, swing, twist); // swing limits: if just one is limited: if the other is free, we support // (-pi/2, +pi/2) limit, using tan of the half-angle as the error measure parameter. // If the other is locked, we support (-pi, +pi) limits using the tan of the quarter-angle // Notation: th == PxTanHalf, tq = tanQuarter if(limited & SWING1_FLAG && limited & SWING2_FLAG) { if(data.mUseConeLimit) setupConeSwingLimits(ch, data, swing, cA2w); // PT: no else here by design, we want to allow creating both the cone & the pyramid at the same time, // which can be useful to make the cone more robust against large velocities. if(data.mUsePyramidLimits) setupPyramidSwingLimits(ch, data, swing, cA2w, true, true); } else { if(limited & SWING1_FLAG) { if(locked & SWING2_FLAG) { if(data.mUsePyramidLimits) setupPyramidSwingLimits(ch, data, swing, cA2w, true, false); else setupSingleSwingLimit(ch, data, aY, swing.y, swing.w, data.swingLimit.yAngle); // PT: swing Y limited, swing Z locked } else { if(!data.mUsePyramidLimits) setupDualConeSwingLimits(ch, data, aZ.cross(bX), -aZ.dot(bX), data.swingLimit.yAngle); // PT: swing Y limited, swing Z free else PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "D6JointSolverPrep: invalid joint setup. Double pyramid mode not supported."); } } if(limited & SWING2_FLAG) { if(locked & SWING1_FLAG) { if(data.mUsePyramidLimits) setupPyramidSwingLimits(ch, data, swing, cA2w, false, true); else setupSingleSwingLimit(ch, data, aZ, swing.z, swing.w, data.swingLimit.zAngle); // PT: swing Z limited, swing Y locked } else if(!data.mUsePyramidLimits) setupDualConeSwingLimits(ch, data, -aY.cross(bX), aY.dot(bX), data.swingLimit.zAngle); // PT: swing Z limited, swing Y free else PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "D6JointSolverPrep: invalid joint setup. Double pyramid mode not supported."); } } if(limited & TWIST_FLAG) ch.anglePair(computePhi(twist), data.twistLimit.lower, data.twistLimit.upper, cB2w_m.column0, data.twistLimit); } if(limited & LINEAR_MASK) { if(data.mUseDistanceLimit) // PT: old linear/distance limit { PxVec3 limitDir; const float distance = computeLimitedDistance(data, cB2cA, cA2w_m, limitDir); if(distance > data.distanceMinDist) ch.linearLimit(limitDir * (1.0f/distance), distance, data.distanceLimit.value, data.distanceLimit); } if(data.mUseNewLinearLimits) // PT: new asymmetric linear limits { const PxVec3& bOriginInA = cB2cA.p; // PT: TODO: we check that the DOFs are not "locked" to be consistent with the prismatic joint, but it // doesn't look like this case is possible, since it would be caught by the "isValid" check when setting // the limits. And in fact the "distance" linear limit above doesn't do this check. if((limited & (1<<PxD6Axis::eX)) && data.linearLimitX.lower <= data.linearLimitX.upper) setupLinearLimit(ch, data.linearLimitX, bOriginInA.x, cA2w_m.column0); if((limited & (1<<PxD6Axis::eY)) && data.linearLimitY.lower <= data.linearLimitY.upper) setupLinearLimit(ch, data.linearLimitY, bOriginInA.y, cA2w_m.column1); if((limited & (1<<PxD6Axis::eZ)) && data.linearLimitZ.lower <= data.linearLimitZ.upper) setupLinearLimit(ch, data.linearLimitZ, bOriginInA.z, cA2w_m.column2); } } // we handle specially the case of just one swing dof locked const PxU32 angularLocked = locked & ANGULAR_MASK; if(angularLocked == SWING1_FLAG) { ch.angularHard(bX.cross(aZ), -bX.dot(aZ)); locked &= ~SWING1_FLAG; } else if(angularLocked == SWING2_FLAG) { locked &= ~SWING2_FLAG; ch.angularHard(bX.cross(aY), -bX.dot(aY)); } // PT: TODO: cA2w_m has already been computed above, no need to recompute it within prepareLockedAxes PxVec3 ra, rb; ch.prepareLockedAxes(cA2w.q, cB2w.q, cB2cA.p, locked&7, locked>>3, ra, rb); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; /*cA2wOut = cA2w.p; cB2wOut = cB2w.p;*/ // PT: TODO: check the number cannot be too high now return ch.getCount(); } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gD6JointShaders = { D6JointSolverPrep, D6JointVisualize, /*PxConstraintFlag::Enum(0)*/PxConstraintFlag::eGPU_COMPATIBLE }; PxConstraintSolverPrep D6Joint::getPrep() const { return gD6JointShaders.solverPrep; } PxD6Joint* physx::PxD6JointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxD6JointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxD6JointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxD6JointCreate: actors must be different"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxD6JointCreate: at least one actor must be dynamic"); return createJointT<D6Joint, D6JointData>(physics, actor0, localFrame0, actor1, localFrame1, gD6JointShaders); } // PX_SERIALIZATION void D6Joint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gD6JointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD void D6Joint::updateOmniPvdProperties() const { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistAngle, j, getTwistAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingYAngle, j, getSwingYAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingZAngle, j, getSwingZAngle()) OMNI_PVD_WRITE_SCOPE_END } template<> void physx::Ext::omniPvdInitJoint<D6Joint>(D6Joint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxD6Joint& j = static_cast<const PxD6Joint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eD6); PxD6Motion::Enum motions[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) motions[i] = joint.getMotion(PxD6Axis::Enum(i)); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, motions, j, motions, PxD6Axis::eCOUNT) PxReal forceLimit[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) forceLimit[i] = joint.getDrive(PxD6Drive::Enum(i)).forceLimit; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveForceLimit, j, forceLimit, PxD6Axis::eCOUNT) PxD6JointDriveFlags flags[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) { flags[i] = joint.getDrive(PxD6Drive::Enum(i)).flags; } OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveFlags, j, flags, PxD6Axis::eCOUNT) PxReal stiffness[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) { stiffness[i] = joint.getDrive(PxD6Drive::Enum(i)).stiffness; } OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveStiffness, j, stiffness, PxD6Axis::eCOUNT) PxReal damping[PxD6Axis::eCOUNT]; for (PxU32 i = 0; i < PxD6Axis::eCOUNT; ++i) { damping[i] = joint.getDrive(PxD6Drive::Enum(i)).damping; } OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveDamping, j, damping, PxD6Axis::eCOUNT) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, drivePosition, j, joint.getDrivePosition()) PxVec3 driveLinVel, driveAngVel; joint.getDriveVelocity(driveLinVel, driveAngVel); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveLinVelocity, j, driveLinVel) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, driveAngVelocity, j, driveAngVel) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, twistAngle, j, joint.getTwistAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingYAngle, j, joint.getSwingYAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxD6Joint, swingZAngle, j, joint.getSwingZAngle()) OMNI_PVD_WRITE_SCOPE_END } #endif
39,185
C++
37.79802
173
0.728544
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqManager.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 EXT_SQ_MANAGER_H #define EXT_SQ_MANAGER_H #include "common/PxPhysXCommonConfig.h" #include "foundation/PxBitMap.h" #include "foundation/PxArray.h" #include "SqPruner.h" #include "SqManager.h" #include "foundation/PxHashSet.h" namespace physx { namespace Sq { class CompoundPruner; } } #include "foundation/PxMutex.h" namespace physx { class PxRenderOutput; class PxBVH; class PxSceneLimits; namespace Gu { class BVH; } namespace Sq { // PT: this is a customized version of physx::Sq::PrunerManager that supports more than 2 hardcoded pruners. // It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners. class ExtPrunerManager : public PxUserAllocated { public: ExtPrunerManager(PxU64 contextID, float inflation, const Adapter& adapter, bool usesTreeOfPruners); ~ExtPrunerManager(); PxU32 addPruner(Gu::Pruner* pruner, PxU32 preallocated); Gu::PrunerHandle addPrunerShape(const Gu::PrunerPayload& payload, PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, const PxBounds3& bounds, const PxTransform& transform, bool hasPruningStructure=false); void addCompoundShape(const PxBVH& bvh, PrunerCompoundId compoundId, const PxTransform& compoundTransform, Gu::PrunerHandle* prunerHandle, const Gu::PrunerPayload* payloads, const PxTransform* transforms, bool isDynamic); void markForUpdate(PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, Gu::PrunerHandle shapeHandle, const PxTransform& transform); void removePrunerShape(PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, Gu::PrunerHandle shapeHandle, Gu::PrunerPayloadRemovalCallback* removalCallback); PX_FORCE_INLINE PxU32 getNbPruners() const { return mPrunerExt.size(); } PX_FORCE_INLINE const Gu::Pruner* getPruner(PxU32 index) const { return mPrunerExt[index]->mPruner; } PX_FORCE_INLINE Gu::Pruner* getPruner(PxU32 index) { return mPrunerExt[index]->mPruner; } PX_FORCE_INLINE const CompoundPruner* getCompoundPruner() const { return mCompoundPrunerExt.mPruner; } PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; } void preallocate(PxU32 prunerIndex, PxU32 nbShapes); void setDynamicTreeRebuildRateHint(PxU32 dynTreeRebuildRateHint); PX_FORCE_INLINE PxU32 getDynamicTreeRebuildRateHint() const { return mRebuildRateHint; } void flushUpdates(); void forceRebuildDynamicTree(PxU32 prunerIndex); void updateCompoundActor(PrunerCompoundId compoundId, const PxTransform& compoundTransform); void removeCompoundActor(PrunerCompoundId compoundId, Gu::PrunerPayloadRemovalCallback* removalCallback); void* prepareSceneQueriesUpdate(PxU32 prunerIndex); void sceneQueryBuildStep(void* handle); void sync(PxU32 prunerIndex, const Gu::PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices); void afterSync(bool buildStep, bool commit); void shiftOrigin(const PxVec3& shift); void visualize(PxU32 prunerIndex, PxRenderOutput& out) const; void flushMemory(); PX_FORCE_INLINE PxU32 getStaticTimestamp() const { return mStaticTimestamp; } PX_FORCE_INLINE const Adapter& getAdapter() const { return mAdapter; } PX_FORCE_INLINE const Gu::BVH* getTreeOfPruners() const { return mTreeOfPruners; } PxU32 startCustomBuildstep(); void customBuildstep(PxU32 index); void finishCustomBuildstep(); void createTreeOfPruners(); private: const Adapter& mAdapter; PxArray<PrunerExt*> mPrunerExt; CompoundPrunerExt mCompoundPrunerExt; Gu::BVH* mTreeOfPruners; const PxU64 mContextID; PxU32 mStaticTimestamp; PxU32 mRebuildRateHint; const float mInflation; // SQ_PRUNER_EPSILON PxMutex mSQLock; // to make sure only one query updates the dirty pruner structure if multiple queries run in parallel volatile bool mPrunerNeedsUpdating; volatile bool mTimestampNeedsUpdating; const bool mUsesTreeOfPruners; void flushShapes(); PX_FORCE_INLINE void invalidateStaticTimestamp() { mStaticTimestamp++; } PX_NOCOPY(ExtPrunerManager) }; } } #endif
6,262
C
43.735714
233
0.724529
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtPrismaticJoint.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 "ExtPrismaticJoint.h" #include "ExtConstraintHelper.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; PrismaticJoint::PrismaticJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : PrismaticJointT(PxJointConcreteType::ePRISMATIC, actor0, localFrame0, actor1, localFrame1, "PrismaticJointData") { PrismaticJointData* data = static_cast<PrismaticJointData*>(mData); data->limit = PxJointLinearLimitPair(scale); data->jointFlags = PxPrismaticJointFlags(); } PxPrismaticJointFlags PrismaticJoint::getPrismaticJointFlags(void) const { return data().jointFlags; } void PrismaticJoint::setPrismaticJointFlags(PxPrismaticJointFlags flags) { data().jointFlags = flags; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, jointFlags, static_cast<PxPrismaticJoint&>(*this), flags) } void PrismaticJoint::setPrismaticJointFlag(PxPrismaticJointFlag::Enum flag, bool value) { if(value) data().jointFlags |= flag; else data().jointFlags &= ~flag; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, jointFlags, static_cast<PxPrismaticJoint&>(*this), getPrismaticJointFlags()) } PxJointLinearLimitPair PrismaticJoint::getLimit() const { return data().limit; } void PrismaticJoint::setLimit(const PxJointLinearLimitPair& limit) { PX_CHECK_AND_RETURN(limit.isValid(), "PxPrismaticJoint::setLimit: invalid parameter"); data().limit = limit; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxPrismaticJoint& j = static_cast<PxPrismaticJoint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitLower, j, limit.lower) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitUpper, j, limit.upper) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitRestitution, j, limit.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitBounceThreshold, j, limit.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitStiffness, j, limit.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitDamping, j, limit.damping) OMNI_PVD_WRITE_SCOPE_END #endif } static void PrismaticJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { const PrismaticJointData& data = *reinterpret_cast<const PrismaticJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) viz.visualizeJointFrames(cA2w, cB2w); if((flags & PxConstraintVisualizationFlag::eLIMITS) && (data.jointFlags & PxPrismaticJointFlag::eLIMIT_ENABLED)) { viz.visualizeLinearLimit(cA2w, cB2w, data.limit.lower); viz.visualizeLinearLimit(cA2w, cB2w, data.limit.upper); } } //TAG:solverprepshader static PxU32 PrismaticJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const PrismaticJointData& data = *reinterpret_cast<const PrismaticJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); joint::applyNeighborhoodOperator(cA2w, cB2w); const bool limitEnabled = data.jointFlags & PxPrismaticJointFlag::eLIMIT_ENABLED; const PxJointLinearLimitPair& limit = data.limit; const bool limitIsLocked = limitEnabled && limit.lower >= limit.upper; const PxVec3 bOriginInA = cA2w.transformInv(cB2w.p); PxVec3 ra, rb, axis; ch.prepareLockedAxes(cA2w.q, cB2w.q, bOriginInA, limitIsLocked ? 7ul : 6ul, 7ul, ra, rb, &axis); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; if(limitEnabled && !limitIsLocked) { const PxReal ordinate = bOriginInA.x; ch.linearLimit(axis, ordinate, limit.upper, limit); ch.linearLimit(-axis, -ordinate, -limit.lower, limit); } return ch.getCount(); } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gPrismaticJointShaders = { PrismaticJointSolverPrep, PrismaticJointVisualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep PrismaticJoint::getPrep() const { return gPrismaticJointShaders.solverPrep; } PxPrismaticJoint* physx::PxPrismaticJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxPrismaticJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxPrismaticJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxPrismaticJointCreate: at least one actor must be dynamic"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxPrismaticJointCreate: actors must be different"); return createJointT<PrismaticJoint, PrismaticJointData>(physics, actor0, localFrame0, actor1, localFrame1, gPrismaticJointShaders); } // PX_SERIALIZATION void PrismaticJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gPrismaticJointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD void PrismaticJoint::updateOmniPvdProperties() const { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxPrismaticJoint& j = static_cast<const PxPrismaticJoint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, position, j, getPosition()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, velocity, j, getVelocity()) OMNI_PVD_WRITE_SCOPE_END } template<> void physx::Ext::omniPvdInitJoint<PrismaticJoint>(PrismaticJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxPrismaticJoint& j = static_cast<PxPrismaticJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::ePRISMATIC); PxJointLinearLimitPair limit = joint.getLimit(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitLower, j, limit.lower) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitUpper, j, limit.upper) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitRestitution, j, limit.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitBounceThreshold, j, limit.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitStiffness, j, limit.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, limitDamping, j, limit.damping) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, position, j, joint.getPosition()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxPrismaticJoint, velocity, j, joint.getVelocity()) OMNI_PVD_WRITE_SCOPE_END } #endif
9,429
C++
43.904762
175
0.778768
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtConstraintHelper.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 EXT_CONSTRAINT_HELPER_H #define EXT_CONSTRAINT_HELPER_H #include "foundation/PxAssert.h" #include "foundation/PxTransform.h" #include "foundation/PxMat33.h" #include "foundation/PxSIMDHelpers.h" #include "extensions/PxD6Joint.h" #include "ExtJointData.h" #include "foundation/PxVecMath.h" namespace physx { namespace Ext { namespace joint { PX_FORCE_INLINE void applyNeighborhoodOperator(const PxTransform32& cA2w, PxTransform32& cB2w) { if(cA2w.q.dot(cB2w.q)<0.0f) // minimum dist quat (equiv to flipping cB2bB.q, which we don't use anywhere) cB2w.q = -cB2w.q; } PX_INLINE void computeJointFrames(PxTransform32& cA2w, PxTransform32& cB2w, const JointData& data, const PxTransform& bA2w, const PxTransform& bB2w) { PX_ASSERT(bA2w.isValid() && bB2w.isValid()); aos::transformMultiply<false, true>(cA2w, bA2w, data.c2b[0]); aos::transformMultiply<false, true>(cB2w, bB2w, data.c2b[1]); PX_ASSERT(cA2w.isValid() && cB2w.isValid()); } PX_INLINE void computeJacobianAxes(PxVec3 row[3], const PxQuat& qa, const PxQuat& qb) { // Compute jacobian matrix for (qa* qb) [[* means conjugate in this expr]] // d/dt (qa* qb) = 1/2 L(qa*) R(qb) (omega_b - omega_a) // result is L(qa*) R(qb), where L(q) and R(q) are left/right q multiply matrix const PxReal wa = qa.w, wb = qb.w; const PxVec3 va(qa.x,qa.y,qa.z), vb(qb.x,qb.y,qb.z); const PxVec3 c = vb*wa + va*wb; const PxReal d0 = wa*wb; const PxReal d1 = va.dot(vb); const PxReal d = d0 - d1; row[0] = (va * vb.x + vb * va.x + PxVec3(d, c.z, -c.y)) * 0.5f; row[1] = (va * vb.y + vb * va.y + PxVec3(-c.z, d, c.x)) * 0.5f; row[2] = (va * vb.z + vb * va.z + PxVec3(c.y, -c.x, d)) * 0.5f; if((d0 + d1) != 0.0f) // check if relative rotation is 180 degrees which can lead to singular matrix return; else { row[0].x += PX_EPS_F32; row[1].y += PX_EPS_F32; row[2].z += PX_EPS_F32; } } PX_FORCE_INLINE Px1DConstraint* _linear(const PxVec3& axis, const PxVec3& ra, const PxVec3& rb, PxReal posErr, PxConstraintSolveHint::Enum hint, Px1DConstraint* c) { c->solveHint = PxU16(hint); c->linear0 = axis; c->angular0 = ra.cross(axis); c->linear1 = axis; c->angular1 = rb.cross(axis); c->geometricError = posErr; PX_ASSERT(c->linear0.isFinite()); PX_ASSERT(c->linear1.isFinite()); PX_ASSERT(c->angular0.isFinite()); PX_ASSERT(c->angular1.isFinite()); return c; } PX_FORCE_INLINE Px1DConstraint* _angular(const PxVec3& axis, PxReal posErr, PxConstraintSolveHint::Enum hint, Px1DConstraint* c) { c->solveHint = PxU16(hint); c->linear0 = PxVec3(0.0f); c->angular0 = axis; c->linear1 = PxVec3(0.0f); c->angular1 = axis; c->geometricError = posErr; c->flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; return c; } class ConstraintHelper { Px1DConstraint* mConstraints; Px1DConstraint* mCurrent; PX_ALIGN(16, PxVec3p mRa); PX_ALIGN(16, PxVec3p mRb); PX_ALIGN(16, PxVec3p mCA2w); PX_ALIGN(16, PxVec3p mCB2w); public: ConstraintHelper(Px1DConstraint* c, const PxVec3& ra, const PxVec3& rb) : mConstraints(c), mCurrent(c), mRa(ra), mRb(rb) {} /*PX_NOINLINE*/ ConstraintHelper(Px1DConstraint* c, PxConstraintInvMassScale& invMassScale, PxTransform32& cA2w, PxTransform32& cB2w, PxVec3p& body0WorldOffset, const JointData& data, const PxTransform& bA2w, const PxTransform& bB2w) : mConstraints(c), mCurrent(c) { using namespace aos; V4StoreA(V4LoadA(&data.invMassScale.linear0), &invMassScale.linear0); //invMassScale = data.invMassScale; computeJointFrames(cA2w, cB2w, data, bA2w, bB2w); if(1) { const Vec4V cB2wV = V4LoadA(&cB2w.p.x); const Vec4V raV = V4Sub(cB2wV, V4LoadU(&bA2w.p.x)); // const PxVec3 ra = cB2w.p - bA2w.p; V4StoreU(raV, &body0WorldOffset.x); // body0WorldOffset = ra; V4StoreA(raV, &mRa.x); // mRa = ra; V4StoreA(V4Sub(cB2wV, V4LoadU(&bB2w.p.x)), &mRb.x); // mRb = cB2w.p - bB2w.p; V4StoreA(V4LoadA(&cA2w.p.x), &mCA2w.x); // mCA2w = cA2w.p; V4StoreA(cB2wV, &mCB2w.x); // mCB2w = cB2w.p; } else { const PxVec3 ra = cB2w.p - bA2w.p; body0WorldOffset = ra; mRa = ra; mRb = cB2w.p - bB2w.p; mCA2w = cA2w.p; mCB2w = cB2w.p; } } PX_FORCE_INLINE const PxVec3& getRa() const { return mRa; } PX_FORCE_INLINE const PxVec3& getRb() const { return mRb; } // hard linear & angular PX_FORCE_INLINE void linearHard(const PxVec3& axis, PxReal posErr) { Px1DConstraint* c = linear(axis, posErr, PxConstraintSolveHint::eEQUALITY); c->flags |= Px1DConstraintFlag::eOUTPUT_FORCE; } PX_FORCE_INLINE void angularHard(const PxVec3& axis, PxReal posErr) { Px1DConstraint* c = angular(axis, posErr, PxConstraintSolveHint::eEQUALITY); c->flags |= Px1DConstraintFlag::eOUTPUT_FORCE; } // limited linear & angular PX_FORCE_INLINE void linearLimit(const PxVec3& axis, PxReal ordinate, PxReal limitValue, const PxJointLimitParameters& limit) { if(!limit.isSoft() || ordinate > limitValue) addLimit(linear(axis, limitValue - ordinate, PxConstraintSolveHint::eNONE), limit); } PX_FORCE_INLINE void angularLimit(const PxVec3& axis, PxReal ordinate, PxReal limitValue, const PxJointLimitParameters& limit) { if(!limit.isSoft() || ordinate > limitValue) addLimit(angular(axis, limitValue - ordinate, PxConstraintSolveHint::eNONE), limit); } PX_FORCE_INLINE void angularLimit(const PxVec3& axis, PxReal error, const PxJointLimitParameters& limit) { addLimit(angular(axis, error, PxConstraintSolveHint::eNONE), limit); } PX_FORCE_INLINE void anglePair(PxReal angle, PxReal lower, PxReal upper, const PxVec3& axis, const PxJointLimitParameters& limit) { PX_ASSERT(lower<upper); const bool softLimit = limit.isSoft(); if(!softLimit || angle < lower) angularLimit(-axis, -(lower - angle), limit); if(!softLimit || angle > upper) angularLimit(axis, (upper - angle), limit); } // driven linear & angular PX_FORCE_INLINE void linear(const PxVec3& axis, PxReal velTarget, PxReal error, const PxD6JointDrive& drive) { addDrive(linear(axis, error, PxConstraintSolveHint::eNONE), velTarget, drive); } PX_FORCE_INLINE void angular(const PxVec3& axis, PxReal velTarget, PxReal error, const PxD6JointDrive& drive, PxConstraintSolveHint::Enum hint = PxConstraintSolveHint::eNONE) { addDrive(angular(axis, error, hint), velTarget, drive); } PX_FORCE_INLINE PxU32 getCount() const { return PxU32(mCurrent - mConstraints); } void prepareLockedAxes(const PxQuat& qA, const PxQuat& qB, const PxVec3& cB2cAp, PxU32 lin, PxU32 ang, PxVec3& raOut, PxVec3& rbOut, PxVec3* axis=NULL) { Px1DConstraint* current = mCurrent; PxVec3 errorVector(0.0f); PxVec3 ra = mRa; PxVec3 rb = mRb; if(lin) { const PxMat33Padded axes(qA); if(axis) *axis = axes.column0; if(lin&1) errorVector -= axes.column0 * cB2cAp.x; if(lin&2) errorVector -= axes.column1 * cB2cAp.y; if(lin&4) errorVector -= axes.column2 * cB2cAp.z; ra += errorVector; if(lin&1) _linear(axes.column0, ra, rb, -cB2cAp.x, PxConstraintSolveHint::eEQUALITY, current++); if(lin&2) _linear(axes.column1, ra, rb, -cB2cAp.y, PxConstraintSolveHint::eEQUALITY, current++); if(lin&4) _linear(axes.column2, ra, rb, -cB2cAp.z, PxConstraintSolveHint::eEQUALITY, current++); } if (ang) { const PxQuat qB2qA = qA.getConjugate() * qB; PxVec3 row[3]; computeJacobianAxes(row, qA, qB); if (ang & 1) _angular(row[0], -qB2qA.x, PxConstraintSolveHint::eEQUALITY, current++); if (ang & 2) _angular(row[1], -qB2qA.y, PxConstraintSolveHint::eEQUALITY, current++); if (ang & 4) _angular(row[2], -qB2qA.z, PxConstraintSolveHint::eEQUALITY, current++); } raOut = ra; rbOut = rb; for(Px1DConstraint* front = mCurrent; front < current; front++) front->flags |= Px1DConstraintFlag::eOUTPUT_FORCE; mCurrent = current; } PX_FORCE_INLINE Px1DConstraint* getConstraintRow() { return mCurrent++; } private: PX_FORCE_INLINE Px1DConstraint* linear(const PxVec3& axis, PxReal posErr, PxConstraintSolveHint::Enum hint) { return _linear(axis, mRa, mRb, posErr, hint, mCurrent++); } PX_FORCE_INLINE Px1DConstraint* angular(const PxVec3& axis, PxReal posErr, PxConstraintSolveHint::Enum hint) { return _angular(axis, posErr, hint, mCurrent++); } void addLimit(Px1DConstraint* c, const PxJointLimitParameters& limit) { PxU16 flags = PxU16(c->flags | Px1DConstraintFlag::eOUTPUT_FORCE); if(limit.isSoft()) { flags |= Px1DConstraintFlag::eSPRING; c->mods.spring.stiffness = limit.stiffness; c->mods.spring.damping = limit.damping; } else { c->solveHint = PxConstraintSolveHint::eINEQUALITY; c->mods.bounce.restitution = limit.restitution; c->mods.bounce.velocityThreshold = limit.bounceThreshold; if(c->geometricError>0.0f) flags |= Px1DConstraintFlag::eKEEPBIAS; if(limit.restitution>0.0f) flags |= Px1DConstraintFlag::eRESTITUTION; } c->flags = flags; c->minImpulse = 0.0f; } void addDrive(Px1DConstraint* c, PxReal velTarget, const PxD6JointDrive& drive) { c->velocityTarget = velTarget; PxU16 flags = PxU16(c->flags | Px1DConstraintFlag::eSPRING | Px1DConstraintFlag::eHAS_DRIVE_LIMIT); if(drive.flags & PxD6JointDriveFlag::eACCELERATION) flags |= Px1DConstraintFlag::eACCELERATION_SPRING; c->flags = flags; c->mods.spring.stiffness = drive.stiffness; c->mods.spring.damping = drive.damping; c->minImpulse = -drive.forceLimit; c->maxImpulse = drive.forceLimit; PX_ASSERT(c->linear0.isFinite()); PX_ASSERT(c->angular0.isFinite()); } }; } } // namespace } #endif
11,712
C
33.551622
177
0.676571
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultCpuDispatcher.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 EXT_DEFAULT_CPU_DISPATCHER_H #define EXT_DEFAULT_CPU_DISPATCHER_H #include "common/PxProfileZone.h" #include "task/PxTask.h" #include "extensions/PxDefaultCpuDispatcher.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxSync.h" #include "foundation/PxSList.h" #include "ExtSharedQueueEntryPool.h" namespace physx { namespace Ext { class CpuWorkerThread; #if PX_VC #pragma warning(push) #pragma warning(disable:4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif // Because of the SList member I assume class DefaultCpuDispatcher : public PxDefaultCpuDispatcher, public PxUserAllocated { friend class TaskQueueHelper; PX_NOCOPY(DefaultCpuDispatcher) private: ~DefaultCpuDispatcher(); public: DefaultCpuDispatcher(PxU32 numThreads, PxU32* affinityMasks, PxDefaultCpuDispatcherWaitForWorkMode::Enum mode = PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK, PxU32 yieldProcessorCount = 0); // PxCpuDispatcher virtual void submitTask(PxBaseTask& task) PX_OVERRIDE; virtual PxU32 getWorkerCount() const PX_OVERRIDE { return mNumThreads; } //~PxCpuDispatcher // PxDefaultCpuDispatcher virtual void release() PX_OVERRIDE; virtual void setRunProfiled(bool runProfiled) PX_OVERRIDE { mRunProfiled = runProfiled; } virtual bool getRunProfiled() const PX_OVERRIDE { return mRunProfiled; } //~PxDefaultCpuDispatcher PxBaseTask* getJob(); PxBaseTask* stealJob(); PxBaseTask* fetchNextTask(); PX_FORCE_INLINE void runTask(PxBaseTask& task) { if(mRunProfiled) { PX_PROFILE_ZONE(task.getName(), task.getContextId()); task.run(); } else task.run(); } void waitForWork() { PX_ASSERT(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == mWaitForWorkMode); mWorkReady.wait(); } void resetWakeSignal(); static void getAffinityMasks(PxU32* affinityMasks, PxU32 threadCount); PX_FORCE_INLINE PxDefaultCpuDispatcherWaitForWorkMode::Enum getWaitForWorkMode() const { return mWaitForWorkMode; } PX_FORCE_INLINE PxU32 getYieldProcessorCount() const { return mYieldProcessorCount; } protected: CpuWorkerThread* mWorkerThreads; SharedQueueEntryPool<> mQueueEntryPool; PxSList mJobList; PxSync mWorkReady; PxU8* mThreadNames; PxU32 mNumThreads; bool mShuttingDown; bool mRunProfiled; const PxDefaultCpuDispatcherWaitForWorkMode::Enum mWaitForWorkMode; const PxU32 mYieldProcessorCount; }; #if PX_VC #pragma warning(pop) #endif } // namespace Ext } #endif
4,717
C
39.672413
216
0.687301
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtContactJoint.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 "ExtContactJoint.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; ContactJoint::ContactJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : ContactJointT(PxJointConcreteType::eCONTACT, actor0, localFrame0, actor1, localFrame1, "ContactJointData") { PX_UNUSED(scale); ContactJointData* data = static_cast<ContactJointData*>(mData); data->contact = PxVec3(0.f); data->normal = PxVec3(0.f); data->penetration = 0.f; data->restitution = 0.f; data->bounceThreshold = 0.f; } PxVec3 ContactJoint::getContact() const { return data().contact; } void ContactJoint::setContact(const PxVec3& contact) { PX_CHECK_AND_RETURN(contact.isFinite(), "PxContactJoint::setContact: invalid parameter"); data().contact = contact; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, point, static_cast<PxContactJoint&>(*this), getContact()) } PxVec3 ContactJoint::getContactNormal() const { return data().normal; } void ContactJoint::setContactNormal(const PxVec3& normal) { PX_CHECK_AND_RETURN(normal.isFinite(), "PxContactJoint::setContactNormal: invalid parameter"); data().normal = normal; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, normal, static_cast<PxContactJoint&>(*this), getContactNormal()) } PxReal ContactJoint::getPenetration() const { return data().penetration; } void ContactJoint::setPenetration(PxReal penetration) { PX_CHECK_AND_RETURN(PxIsFinite(penetration), "ContactJoint::setPenetration: invalid parameter"); data().penetration = penetration; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, penetration, static_cast<PxContactJoint&>(*this), getPenetration()) } PxReal ContactJoint::getRestitution() const { return data().restitution; } void ContactJoint::setRestitution(const PxReal restitution) { PX_CHECK_AND_RETURN(PxIsFinite(restitution) && restitution >= 0.f && restitution <= 1.f, "ContactJoint::setRestitution: invalid parameter"); data().restitution = restitution; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, restitution, static_cast<PxContactJoint&>(*this), getRestitution()) } PxReal ContactJoint::getBounceThreshold() const { return data().bounceThreshold; } void ContactJoint::setBounceThreshold(const PxReal bounceThreshold) { PX_CHECK_AND_RETURN(PxIsFinite(bounceThreshold) && bounceThreshold > 0.f, "ContactJoint::setBounceThreshold: invalid parameter"); data().bounceThreshold = bounceThreshold; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, bounceThreshold, static_cast<PxContactJoint&>(*this), getBounceThreshold()) } void ContactJoint::computeJacobians(PxJacobianRow* jacobian) const { const PxVec3 cp = data().contact; const PxVec3 normal = data().normal; PxRigidActor* actor0, *actor1; this->getActors(actor0, actor1); PxVec3 raXn(0.f), rbXn(0.f); if (actor0 && actor0->is<PxRigidBody>()) { PxRigidBody* dyn = actor0->is<PxRigidBody>(); PxTransform cmassPose = dyn->getGlobalPose() * dyn->getCMassLocalPose(); raXn = (cp - cmassPose.p).cross(normal); } if (actor1 && actor1->is<PxRigidBody>()) { PxRigidBody* dyn = actor1->is<PxRigidBody>(); PxTransform cmassPose = dyn->getGlobalPose() * dyn->getCMassLocalPose(); rbXn = (cp - cmassPose.p).cross(normal); } jacobian->linear0 = normal; jacobian->angular0 = raXn; jacobian->linear1 = -normal; jacobian->angular1 = -rbXn; } PxU32 ContactJoint::getNbJacobianRows() const { return 1; } static void ContactJointVisualize(PxConstraintVisualizer& /*viz*/, const void* /*constantBlock*/, const PxTransform& /*body0Transform*/, const PxTransform& /*body1Transform*/, PxU32 /*flags*/) { //TODO } //TAG:solverprepshader static PxU32 ContactJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& /*invMassScale*/, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const ContactJointData& data = *reinterpret_cast<const ContactJointData*>(constantBlock); const PxVec3& contact = data.contact; const PxVec3& normal = data.normal; cA2wOut = contact; cB2wOut = contact; const PxVec3 ra = contact - bA2w.p; const PxVec3 rb = contact - bB2w.p; body0WorldOffset = PxVec3(0.f); Px1DConstraint& con = constraints[0]; con.linear0 = normal; con.linear1 = normal; con.angular0 = ra.cross(normal); con.angular1 = rb.cross(normal); con.geometricError = data.penetration; con.minImpulse = 0.f; con.maxImpulse = PX_MAX_F32; con.velocityTarget = 0.f; con.forInternalUse = 0.f; con.solveHint = 0; con.flags = Px1DConstraintFlag::eOUTPUT_FORCE; con.mods.bounce.restitution = data.restitution; con.mods.bounce.velocityThreshold = data.bounceThreshold; return 1; } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gContactJointShaders = { ContactJointSolverPrep, ContactJointVisualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep ContactJoint::getPrep() const { return gContactJointShaders.solverPrep; } PxContactJoint* physx::PxContactJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxContactJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxContactJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxContactJointCreate: actors must be different"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxContactJointCreate: at least one actor must be dynamic"); return createJointT<ContactJoint, ContactJointData>(physics, actor0, localFrame0, actor1, localFrame1, gContactJointShaders); } // PX_SERIALIZATION void ContactJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gContactJointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD template<> void physx::Ext::omniPvdInitJoint<ContactJoint>(ContactJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxContactJoint& j = static_cast<PxContactJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eCONTACT); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, point, j, joint.getContact()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, normal, j, joint.getContactNormal()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, penetration, j, joint.getPenetration()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, restitution, j, joint.getRestitution()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxContactJoint, bounceThreshold, j, joint.getBounceThreshold()) OMNI_PVD_WRITE_SCOPE_END } #endif
8,998
C++
35.28629
192
0.757279
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRigidBodyExt.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 "geometry/PxSphereGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxPlaneGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "geometry/PxTriangleMeshGeometry.h" #include "geometry/PxHeightFieldGeometry.h" #include "geometry/PxGeometryHelpers.h" #include "geometry/PxConvexMesh.h" #include "geometry/PxTriangleMesh.h" #include "extensions/PxRigidBodyExt.h" #include "extensions/PxShapeExt.h" #include "extensions/PxMassProperties.h" #include "PxShape.h" #include "PxScene.h" #include "PxRigidDynamic.h" #include "PxRigidStatic.h" #include "ExtInertiaTensor.h" #include "foundation/PxAllocator.h" #include "foundation/PxSIMDHelpers.h" #include "CmUtils.h" using namespace physx; using namespace Cm; static bool computeMassAndDiagInertia(Ext::InertiaTensorComputer& inertiaComp, PxVec3& diagTensor, PxQuat& orient, PxReal& massOut, PxVec3& coM, bool lockCOM, const PxRigidBody& body, const char* errorStr) { // The inertia tensor and center of mass is relative to the actor at this point. Transform to the // body frame directly if CoM is specified, else use computed center of mass if (lockCOM) { inertiaComp.translate(-coM); // base the tensor on user's desired center of mass. } else { //get center of mass - has to be done BEFORE centering. coM = inertiaComp.getCenterOfMass(); //the computed result now needs to be centered around the computed center of mass: inertiaComp.center(); } // The inertia matrix is now based on the body's center of mass desc.massLocalPose.p massOut = inertiaComp.getMass(); diagTensor = PxDiagonalize(inertiaComp.getInertia(), orient); if ((diagTensor.x > 0.0f) && (diagTensor.y > 0.0f) && (diagTensor.z > 0.0f)) return true; else { PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL, "%s: inertia tensor has negative components (ill-conditioned input expected). Approximation for inertia tensor will be used instead.", errorStr); // keep center of mass but use the AABB as a crude approximation for the inertia tensor PxBounds3 bounds = body.getWorldBounds(); const PxTransform pose = body.getGlobalPose(); bounds = PxBounds3::transformFast(pose.getInverse(), bounds); Ext::InertiaTensorComputer it(false); it.setBox(bounds.getExtents()); it.scaleDensity(massOut / it.getMass()); const PxMat33 inertia = it.getInertia(); diagTensor = PxVec3(inertia.column0.x, inertia.column1.y, inertia.column2.z); orient = PxQuat(PxIdentity); return true; } } static bool computeMassAndInertia(Ext::InertiaTensorComputer& inertiaComp, bool multipleMassOrDensity, PxRigidBody& body, const PxReal* densities, const PxReal* masses, PxU32 densityOrMassCount, bool includeNonSimShapes) { PX_ASSERT(!densities || !masses); PX_ASSERT((densities || masses) && (densityOrMassCount > 0)); PxInlineArray<PxShape*, 16> shapes("PxShape*"); shapes.resize(body.getNbShapes()); body.getShapes(shapes.begin(), shapes.size()); PxU32 validShapeIndex = 0; PxReal currentMassOrDensity; const PxReal* massOrDensityArray; if (densities) { massOrDensityArray = densities; currentMassOrDensity = densities[0]; } else { massOrDensityArray = masses; currentMassOrDensity = masses[0]; } if (!PxIsFinite(currentMassOrDensity)) return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeMassAndInertia: Provided mass or density has no valid value"); for(PxU32 i=0; i < shapes.size(); i++) { if ((!(shapes[i]->getFlags() & PxShapeFlag::eSIMULATION_SHAPE)) && (!includeNonSimShapes)) continue; if (multipleMassOrDensity) { if (validShapeIndex < densityOrMassCount) { currentMassOrDensity = massOrDensityArray[validShapeIndex]; if (!PxIsFinite(currentMassOrDensity)) return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeMassAndInertia: Provided mass or density has no valid value"); } else return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeMassAndInertia: Not enough mass/density values provided for all (simulation) shapes"); } Ext::InertiaTensorComputer it(false); const PxGeometry& geom = shapes[i]->getGeometry(); switch(geom.getType()) { case PxGeometryType::eSPHERE : { const PxSphereGeometry& g = static_cast<const PxSphereGeometry&>(geom); PxTransform temp(shapes[i]->getLocalPose()); it.setSphere(g.radius, &temp); } break; case PxGeometryType::eBOX : { const PxBoxGeometry& g = static_cast<const PxBoxGeometry&>(geom); PxTransform temp(shapes[i]->getLocalPose()); it.setBox(g.halfExtents, &temp); } break; case PxGeometryType::eCAPSULE : { const PxCapsuleGeometry& g = static_cast<const PxCapsuleGeometry&>(geom); PxTransform temp(shapes[i]->getLocalPose()); it.setCapsule(0, g.radius, g.halfHeight, &temp); } break; case PxGeometryType::eCONVEXMESH : { const PxConvexMeshGeometry& g = static_cast<const PxConvexMeshGeometry&>(geom); PxConvexMesh& convMesh = *g.convexMesh; PxReal convMass; PxMat33 convInertia; PxVec3 convCoM; convMesh.getMassInformation(convMass, convInertia, convCoM); if (!g.scale.isIdentity()) { //scale the mass properties convMass *= (g.scale.scale.x * g.scale.scale.y * g.scale.scale.z); convCoM = g.scale.transform(convCoM); convInertia = PxMassProperties::scaleInertia(convInertia, g.scale.rotation, g.scale.scale); } it = Ext::InertiaTensorComputer(convInertia, convCoM, convMass); it.transform(shapes[i]->getLocalPose()); } break; case PxGeometryType::eCUSTOM: { PxMassProperties mp(shapes[i]->getGeometry()); it = Ext::InertiaTensorComputer(mp.inertiaTensor, mp.centerOfMass, mp.mass); it.transform(shapes[i]->getLocalPose()); } break; case PxGeometryType::eTRIANGLEMESH: { const PxTriangleMeshGeometry& g = static_cast<const PxTriangleMeshGeometry&>(geom); PxReal mass; PxMat33 inertia; PxVec3 centerOfMass; g.triangleMesh->getMassInformation(mass, inertia, centerOfMass); if (!g.scale.isIdentity()) { //scale the mass properties mass *= (g.scale.scale.x * g.scale.scale.y * g.scale.scale.z); centerOfMass = g.scale.transform(centerOfMass); inertia = PxMassProperties::scaleInertia(inertia, g.scale.rotation, g.scale.scale); } it = Ext::InertiaTensorComputer(inertia, centerOfMass, mass); it.transform(shapes[i]->getLocalPose()); } break; default: { return PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeMassAndInertia: Dynamic actor with illegal collision shapes"); } } if (densities) it.scaleDensity(currentMassOrDensity); else if (multipleMassOrDensity) // mass per shape -> need to scale density per shape it.scaleDensity(currentMassOrDensity / it.getMass()); inertiaComp.add(it); validShapeIndex++; } if (validShapeIndex && masses && (!multipleMassOrDensity)) // at least one simulation shape and single mass for all shapes -> scale density at the end inertiaComp.scaleDensity(currentMassOrDensity / inertiaComp.getMass()); return true; } static bool updateMassAndInertia(bool multipleMassOrDensity, PxRigidBody& body, const PxReal* densities, PxU32 densityCount, const PxVec3* massLocalPose, bool includeNonSimShapes) { bool success; // default values in case there were no shapes PxReal massOut = 1.0f; PxVec3 diagTensor(1.0f); PxQuat orient(PxIdentity); bool lockCom = massLocalPose != NULL; PxVec3 com = lockCom ? *massLocalPose : PxVec3(0); const char* errorStr = "PxRigidBodyExt::updateMassAndInertia"; if (densities && densityCount) { Ext::InertiaTensorComputer inertiaComp(true); if(computeMassAndInertia(inertiaComp, multipleMassOrDensity, body, densities, NULL, densityCount, includeNonSimShapes)) { if(inertiaComp.getMass()!=0 && computeMassAndDiagInertia(inertiaComp, diagTensor, orient, massOut, com, lockCom, body, errorStr)) success = true; else success = false; // body with no shapes provided or computeMassAndDiagInertia() failed } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: Mass and inertia computation failed, setting mass to 1 and inertia to (1,1,1)", errorStr); success = false; } } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: No density specified, setting mass to 1 and inertia to (1,1,1)", errorStr); success = false; } PX_ASSERT(orient.isFinite()); PX_ASSERT(diagTensor.isFinite()); PX_ASSERT(PxIsFinite(massOut)); body.setMass(massOut); body.setMassSpaceInertiaTensor(diagTensor); body.setCMassLocalPose(PxTransform(com, orient)); return success; } bool PxRigidBodyExt::updateMassAndInertia(PxRigidBody& body, const PxReal* densities, PxU32 densityCount, const PxVec3* massLocalPose, bool includeNonSimShapes) { return ::updateMassAndInertia(true, body, densities, densityCount, massLocalPose, includeNonSimShapes); } bool PxRigidBodyExt::updateMassAndInertia(PxRigidBody& body, PxReal density, const PxVec3* massLocalPose, bool includeNonSimShapes) { return ::updateMassAndInertia(false, body, &density, 1, massLocalPose, includeNonSimShapes); } static bool setMassAndUpdateInertia(bool multipleMassOrDensity, PxRigidBody& body, const PxReal* masses, PxU32 massCount, const PxVec3* massLocalPose, bool includeNonSimShapes) { bool success; // default values in case there were no shapes PxReal massOut = 1.0f; PxVec3 diagTensor(1.0f); PxQuat orient(PxIdentity); bool lockCom = massLocalPose != NULL; PxVec3 com = lockCom ? *massLocalPose : PxVec3(0); const char* errorStr = "PxRigidBodyExt::setMassAndUpdateInertia"; if(masses && massCount) { Ext::InertiaTensorComputer inertiaComp(true); if(computeMassAndInertia(inertiaComp, multipleMassOrDensity, body, NULL, masses, massCount, includeNonSimShapes)) { success = true; if (inertiaComp.getMass()!=0 && !computeMassAndDiagInertia(inertiaComp, diagTensor, orient, massOut, com, lockCom, body, errorStr)) success = false; // computeMassAndDiagInertia() failed (mass zero?) if (massCount == 1) massOut = masses[0]; // to cover special case where body has no simulation shape } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: Mass and inertia computation failed, setting mass to 1 and inertia to (1,1,1)", errorStr); success = false; } } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "%s: No mass specified, setting mass to 1 and inertia to (1,1,1)", errorStr); success = false; } PX_ASSERT(orient.isFinite()); PX_ASSERT(diagTensor.isFinite()); body.setMass(massOut); body.setMassSpaceInertiaTensor(diagTensor); body.setCMassLocalPose(PxTransform(com, orient)); return success; } bool PxRigidBodyExt::setMassAndUpdateInertia(PxRigidBody& body, const PxReal* masses, PxU32 massCount, const PxVec3* massLocalPose, bool includeNonSimShapes) { return ::setMassAndUpdateInertia(true, body, masses, massCount, massLocalPose, includeNonSimShapes); } bool PxRigidBodyExt::setMassAndUpdateInertia(PxRigidBody& body, PxReal mass, const PxVec3* massLocalPose, bool includeNonSimShapes) { return ::setMassAndUpdateInertia(false, body, &mass, 1, massLocalPose, includeNonSimShapes); } PxMassProperties PxRigidBodyExt::computeMassPropertiesFromShapes(const PxShape* const* shapes, PxU32 shapeCount) { PxInlineArray<PxMassProperties, 16> massProps; massProps.reserve(shapeCount); PxInlineArray<PxTransform, 16> localTransforms; localTransforms.reserve(shapeCount); for(PxU32 shapeIdx=0; shapeIdx < shapeCount; shapeIdx++) { const PxShape* shape = shapes[shapeIdx]; PxMassProperties mp(shape->getGeometry()); massProps.pushBack(mp); localTransforms.pushBack(shape->getLocalPose()); } return PxMassProperties::sum(massProps.begin(), localTransforms.begin(), shapeCount); } PX_INLINE void addForceAtPosInternal(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode, bool wakeup) { if(mode == PxForceMode::eACCELERATION || mode == PxForceMode::eVELOCITY_CHANGE) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBodyExt::addForce methods do not support eACCELERATION or eVELOCITY_CHANGE modes"); return; } const PxTransform globalPose = body.getGlobalPose(); const PxVec3 centerOfMass = globalPose.transform(body.getCMassLocalPose().p); const PxVec3 torque = (pos - centerOfMass).cross(force); body.addForce(force, mode, wakeup); body.addTorque(torque, mode, wakeup); } void PxRigidBodyExt::addForceAtPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode, bool wakeup) { addForceAtPosInternal(body, force, pos, mode, wakeup); } void PxRigidBodyExt::addForceAtLocalPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode, bool wakeup) { //transform pos to world space const PxVec3 globalForcePos = body.getGlobalPose().transform(pos); addForceAtPosInternal(body, force, globalForcePos, mode, wakeup); } void PxRigidBodyExt::addLocalForceAtPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode, bool wakeup) { const PxVec3 globalForce = body.getGlobalPose().rotate(force); addForceAtPosInternal(body, globalForce, pos, mode, wakeup); } void PxRigidBodyExt::addLocalForceAtLocalPos(PxRigidBody& body, const PxVec3& force, const PxVec3& pos, PxForceMode::Enum mode, bool wakeup) { const PxTransform globalPose = body.getGlobalPose(); const PxVec3 globalForcePos = globalPose.transform(pos); const PxVec3 globalForce = globalPose.rotate(force); addForceAtPosInternal(body, globalForce, globalForcePos, mode, wakeup); } PX_INLINE PxVec3 getVelocityAtPosInternal(const PxRigidBody& body, const PxVec3& point) { PxVec3 velocity = body.getLinearVelocity(); velocity += body.getAngularVelocity().cross(point); return velocity; } PxVec3 PxRigidBodyExt::getVelocityAtPos(const PxRigidBody& body, const PxVec3& point) { const PxTransform globalPose = body.getGlobalPose(); const PxVec3 centerOfMass = globalPose.transform(body.getCMassLocalPose().p); const PxVec3 rpoint = point - centerOfMass; return getVelocityAtPosInternal(body, rpoint); } PxVec3 PxRigidBodyExt::getLocalVelocityAtLocalPos(const PxRigidBody& body, const PxVec3& point) { const PxTransform globalPose = body.getGlobalPose(); const PxVec3 centerOfMass = globalPose.transform(body.getCMassLocalPose().p); const PxVec3 rpoint = globalPose.transform(point) - centerOfMass; return getVelocityAtPosInternal(body, rpoint); } PxVec3 PxRigidBodyExt::getVelocityAtOffset(const PxRigidBody& body, const PxVec3& point) { const PxTransform globalPose = body.getGlobalPose(); const PxVec3 centerOfMass = globalPose.rotate(body.getCMassLocalPose().p); const PxVec3 rpoint = point - centerOfMass; return getVelocityAtPosInternal(body, rpoint); } void PxRigidBodyExt::computeVelocityDeltaFromImpulse(const PxRigidBody& body, const PxTransform& globalPose, const PxVec3& point, const PxVec3& impulse, const PxReal invMassScale, const PxReal invInertiaScale, PxVec3& linearVelocityChange, PxVec3& angularVelocityChange) { const PxVec3 centerOfMass = globalPose.transform(body.getCMassLocalPose().p); const PxReal invMass = body.getInvMass() * invMassScale; const PxVec3 invInertiaMS = body.getMassSpaceInvInertiaTensor() * invInertiaScale; PxMat33 invInertia; transformInertiaTensor(invInertiaMS, PxMat33Padded(globalPose.q), invInertia); linearVelocityChange = impulse * invMass; const PxVec3 rXI = (point - centerOfMass).cross(impulse); angularVelocityChange = invInertia * rXI; } void PxRigidBodyExt::computeLinearAngularImpulse(const PxRigidBody& body, const PxTransform& globalPose, const PxVec3& point, const PxVec3& impulse, const PxReal invMassScale, const PxReal invInertiaScale, PxVec3& linearImpulse, PxVec3& angularImpulse) { const PxVec3 centerOfMass = globalPose.transform(body.getCMassLocalPose().p); linearImpulse = impulse * invMassScale; angularImpulse = (point - centerOfMass).cross(impulse) * invInertiaScale; } void PxRigidBodyExt::computeVelocityDeltaFromImpulse(const PxRigidBody& body, const PxVec3& impulsiveForce, const PxVec3& impulsiveTorque, PxVec3& deltaLinearVelocity, PxVec3& deltaAngularVelocity) { { const PxF32 recipMass = body.getInvMass(); deltaLinearVelocity = impulsiveForce*recipMass; } { const PxTransform globalPose = body.getGlobalPose(); const PxTransform cmLocalPose = body.getCMassLocalPose(); // PT:: tag: scalar transform*transform const PxTransform body2World = globalPose*cmLocalPose; const PxMat33Padded M(body2World.q); const PxVec3 recipInertiaBodySpace = body.getMassSpaceInvInertiaTensor(); PxMat33 recipInertiaWorldSpace; const float axx = recipInertiaBodySpace.x*M(0,0), axy = recipInertiaBodySpace.x*M(1,0), axz = recipInertiaBodySpace.x*M(2,0); const float byx = recipInertiaBodySpace.y*M(0,1), byy = recipInertiaBodySpace.y*M(1,1), byz = recipInertiaBodySpace.y*M(2,1); const float czx = recipInertiaBodySpace.z*M(0,2), czy = recipInertiaBodySpace.z*M(1,2), czz = recipInertiaBodySpace.z*M(2,2); recipInertiaWorldSpace(0,0) = axx*M(0,0) + byx*M(0,1) + czx*M(0,2); recipInertiaWorldSpace(1,1) = axy*M(1,0) + byy*M(1,1) + czy*M(1,2); recipInertiaWorldSpace(2,2) = axz*M(2,0) + byz*M(2,1) + czz*M(2,2); recipInertiaWorldSpace(0,1) = recipInertiaWorldSpace(1,0) = axx*M(1,0) + byx*M(1,1) + czx*M(1,2); recipInertiaWorldSpace(0,2) = recipInertiaWorldSpace(2,0) = axx*M(2,0) + byx*M(2,1) + czx*M(2,2); recipInertiaWorldSpace(1,2) = recipInertiaWorldSpace(2,1) = axy*M(2,0) + byy*M(2,1) + czy*M(2,2); deltaAngularVelocity = recipInertiaWorldSpace*(impulsiveTorque); } } //================================================================================= // Single closest hit compound sweep bool PxRigidBodyExt::linearSweepSingle( PxRigidBody& body, PxScene& scene, const PxVec3& unitDir, const PxReal distance, PxHitFlags outputFlags, PxSweepHit& closestHit, PxU32& shapeIndex, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation) { shapeIndex = 0xFFFFffff; PxReal closestDist = distance; PxU32 nbShapes = body.getNbShapes(); for(PxU32 i=0; i < nbShapes; i++) { PxShape* shape = NULL; body.getShapes(&shape, 1, i); PX_ASSERT(shape != NULL); PxTransform pose = PxShapeExt::getGlobalPose(*shape, body); PxQueryFilterData fd; fd.flags = filterData.flags; PxU32 or4 = (filterData.data.word0 | filterData.data.word1 | filterData.data.word2 | filterData.data.word3); fd.data = or4 ? filterData.data : shape->getQueryFilterData(); PxSweepBuffer subHit; // touching hits are not allowed to be returned from the filters scene.sweep(shape->getGeometry(), pose, unitDir, distance, subHit, outputFlags, fd, filterCall, cache, inflation); if (subHit.hasBlock && subHit.block.distance < closestDist) { closestDist = subHit.block.distance; closestHit = subHit.block; shapeIndex = i; } } return (shapeIndex != 0xFFFFffff); } //================================================================================= // Multiple hits compound sweep // AP: we might be able to improve the return results API but no time for it in 3.3 PxU32 PxRigidBodyExt::linearSweepMultiple( PxRigidBody& body, PxScene& scene, const PxVec3& unitDir, const PxReal distance, PxHitFlags outputFlags, PxSweepHit* hitBuffer, PxU32* hitShapeIndices, PxU32 hitBufferSize, PxSweepHit& block, PxI32& blockingHitShapeIndex, bool& overflow, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation) { overflow = false; blockingHitShapeIndex = -1; for (PxU32 i = 0; i < hitBufferSize; i++) hitShapeIndices[i] = 0xFFFFffff; PxI32 sumNbResults = 0; PxU32 nbShapes = body.getNbShapes(); PxF32 shrunkMaxDistance = distance; for(PxU32 i=0; i < nbShapes; i++) { PxShape* shape = NULL; body.getShapes(&shape, 1, i); PX_ASSERT(shape != NULL); PxTransform pose = PxShapeExt::getGlobalPose(*shape, body); PxQueryFilterData fd; fd.flags = filterData.flags; PxU32 or4 = (filterData.data.word0 | filterData.data.word1 | filterData.data.word2 | filterData.data.word3); fd.data = or4 ? filterData.data : shape->getQueryFilterData(); PxU32 bufSizeLeft = hitBufferSize-sumNbResults; PxSweepHit extraHit; PxSweepBuffer buffer(bufSizeLeft == 0 ? &extraHit : hitBuffer+sumNbResults, bufSizeLeft == 0 ? 1 : hitBufferSize-sumNbResults); scene.sweep(shape->getGeometry(), pose, unitDir, shrunkMaxDistance, buffer, outputFlags, fd, filterCall, cache, inflation); // Check and abort on overflow. Assume overflow if result count is bufSize. PxU32 nbNewResults = buffer.getNbTouches(); overflow |= (nbNewResults >= bufSizeLeft); if (bufSizeLeft == 0) // this is for when we used the extraHit buffer nbNewResults = 0; // set hitShapeIndices for each new non-blocking hit for (PxU32 j = 0; j < nbNewResults; j++) if (sumNbResults + PxU32(j) < hitBufferSize) hitShapeIndices[sumNbResults+j] = i; if (buffer.hasBlock) // there's a blocking hit in the most recent sweepMultiple results { // overwrite the return result blocking hit with the new blocking hit if under if (blockingHitShapeIndex == -1 || buffer.block.distance < block.distance) { blockingHitShapeIndex = PxI32(i); block = buffer.block; } // Remove all the old touching hits below the new maxDist // sumNbResults is not updated yet at this point // and represents the count accumulated so far excluding the very last query PxI32 nbNewResultsSigned = PxI32(nbNewResults); // need a signed version, see nbNewResultsSigned-- below for (PxI32 j = sumNbResults-1; j >= 0; j--) // iterate over "old" hits (up to shapeIndex-1) if (buffer.block.distance < hitBuffer[j].distance) { // overwrite with last "new" hit PxI32 sourceIndex = PxI32(sumNbResults)+nbNewResultsSigned-1; PX_ASSERT(sourceIndex >= j); hitBuffer[j] = hitBuffer[sourceIndex]; hitShapeIndices[j] = hitShapeIndices[sourceIndex]; nbNewResultsSigned--; // can get negative, that means we are shifting the last results array } sumNbResults += nbNewResultsSigned; } else // if there was no new blocking hit we don't need to do anything special, simply append all results to touch array sumNbResults += nbNewResults; PX_ASSERT(sumNbResults >= 0 && sumNbResults <= PxI32(hitBufferSize)); } return PxU32(sumNbResults); }
24,451
C++
37.689873
220
0.741401
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtPvd.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 EXT_PVD_H #define EXT_PVD_H #if PX_SUPPORT_PVD #include "extensions/PxJoint.h" #include "foundation/PxUserAllocated.h" #include "PxPvdDataStream.h" #include "PvdTypeNames.h" #include "PxPvdObjectModelBaseTypes.h" #if PX_LINUX && PX_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-identifier" #endif #include "PxExtensionMetaDataObjects.h" #if PX_LINUX && PX_CLANG #pragma clang diagnostic pop #endif namespace physx { class PxJoint; class PxD6Joint; class PxDistanceJoint; class PxFixedJoint; class PxPrismaticJoint; class PxRevoluteJoint; class PxSphericalJoint; class PxContactJoint; class PxGearJoint; class PxRackAndPinionJoint; } #define JOINT_GROUP 3 namespace physx { namespace pvdsdk { #define DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP( type ) DEFINE_PVD_TYPE_NAME_MAP( physx::type, "physx3", #type ) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFixedJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFixedJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxDistanceJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxDistanceJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxContactJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxContactJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPrismaticJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPrismaticJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRevoluteJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRevoluteJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSphericalJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSphericalJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxD6Joint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxD6JointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxGearJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxGearJointGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRackAndPinionJoint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRackAndPinionJointGeneratedValues) #undef DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP } //pvdsdk } // physx namespace physx { namespace Ext { using namespace physx::pvdsdk; class Pvd: public physx::PxUserAllocated { Pvd& operator=(const Pvd&); public: class PvdNameSpace { public: PvdNameSpace(PvdDataStream& conn, const char* name); ~PvdNameSpace(); private: PvdNameSpace& operator=(const PvdNameSpace&); PvdDataStream& mConnection; }; static void setActors( PvdDataStream& PvdDataStream, const PxJoint& inJoint, const PxConstraint& c, const PxActor* newActor0, const PxActor* newActor1 ); template<typename TObjType> static void createInstance( PvdDataStream& inStream, const PxConstraint& c, const TObjType& inSource ) { inStream.createInstance( &inSource ); inStream.pushBackObjectRef( c.getScene(), "Joints", &inSource ); class ConstraintUpdateCmd : public PvdDataStream::PvdCommand { ConstraintUpdateCmd &operator=(const ConstraintUpdateCmd&) { PX_ASSERT(0); return *this; } //PX_NOCOPY doesn't work for local classes public: const PxConstraint& mConstraint; const PxJoint& mJoint; PxRigidActor* actor0, *actor1; ConstraintUpdateCmd(const PxConstraint& constraint, const PxJoint& joint):PvdDataStream::PvdCommand(), mConstraint(constraint), mJoint(joint) { mConstraint.getActors( actor0, actor1 ); } //Assigned is needed for copying ConstraintUpdateCmd(const ConstraintUpdateCmd& cmd) :PvdDataStream::PvdCommand(), mConstraint(cmd.mConstraint), mJoint(cmd.mJoint) { } virtual bool canRun(PvdInstanceDataStream &inStream_ ) { PX_ASSERT(inStream_.isInstanceValid(&mJoint)); //When run this command, the constraint maybe buffer removed return ((actor0 == NULL) || inStream_.isInstanceValid(actor0)) && ((actor1 == NULL) || inStream_.isInstanceValid(actor1)); } virtual void run( PvdInstanceDataStream &inStream_ ) { //When run this command, the constraint maybe buffer removed if(!inStream_.isInstanceValid(&mJoint)) return; PxRigidActor* actor0_, *actor1_; mConstraint.getActors( actor0_, actor1_ ); if ( actor0_ && (inStream_.isInstanceValid(actor0_)) ) inStream_.pushBackObjectRef( actor0_, "Joints", &mJoint ); if ( actor1_ && (inStream_.isInstanceValid(actor1_)) ) inStream_.pushBackObjectRef( actor1_, "Joints", &mJoint ); const void* parent = actor0_ ? actor0_ : actor1_; inStream_.setPropertyValue( &mJoint, "Parent", parent ); } }; ConstraintUpdateCmd* cmd = PX_PLACEMENT_NEW(inStream.allocateMemForCmd(sizeof(ConstraintUpdateCmd)), ConstraintUpdateCmd)(c, inSource); if(cmd->canRun( inStream )) cmd->run( inStream ); else inStream.pushPvdCommand( *cmd ); } template<typename jointtype, typename structValue> static void updatePvdProperties(PvdDataStream& pvdConnection, const jointtype& joint) { structValue theValueStruct( &joint ); pvdConnection.setPropertyMessage( &joint, theValueStruct ); } template<typename jointtype> static void simUpdate(PvdDataStream& /*pvdConnection*/, const jointtype& /*joint*/) {} template<typename jointtype> static void createPvdInstance(PvdDataStream& pvdConnection, const PxConstraint& c, const jointtype& joint) { createInstance<jointtype>( pvdConnection, c, joint ); } static void releasePvdInstance(PvdDataStream& pvdConnection, const PxConstraint& c, const PxJoint& joint); static void sendClassDescriptions(PvdDataStream& pvdConnection); }; } // ext } // physx #endif // PX_SUPPORT_PVD #endif // EXT_PVD_H
7,347
C
35.019608
145
0.75051
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtParticleExt.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 "extensions/PxParticleExt.h" #include "foundation/PxUserAllocated.h" #include "PxScene.h" #include "PxPhysics.h" #include "PxRigidBody.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" namespace physx { namespace ExtGpu { void PxDmaDataToDevice(PxCudaContextManager* cudaContextManager, PxParticleBuffer* particleBuffer, const PxParticleBufferDesc& desc) { #if PX_SUPPORT_GPU_PHYSX cudaContextManager->acquireContext(); PxVec4* posInvMass = particleBuffer->getPositionInvMasses(); PxVec4* velocities = particleBuffer->getVelocities(); PxU32* phases = particleBuffer->getPhases(); PxParticleVolume* volumes = particleBuffer->getParticleVolumes(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); //KS - TODO - use an event to wait for this cudaContext->memcpyHtoDAsync(CUdeviceptr(posInvMass), desc.positions, desc.numActiveParticles * sizeof(PxVec4), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(velocities), desc.velocities, desc.numActiveParticles * sizeof(PxVec4), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(phases), desc.phases, desc.numActiveParticles * sizeof(PxU32), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(volumes), desc.volumes, desc.numVolumes * sizeof(PxParticleVolume), 0); particleBuffer->setNbActiveParticles(desc.numActiveParticles); particleBuffer->setNbParticleVolumes(desc.numVolumes); cudaContext->streamSynchronize(0); cudaContextManager->releaseContext(); #else PX_UNUSED(cudaContextManager); PX_UNUSED(particleBuffer); PX_UNUSED(desc); #endif } PxParticleBuffer* PxCreateAndPopulateParticleBuffer(const PxParticleBufferDesc& desc, PxCudaContextManager* cudaContextManager) { PxParticleBuffer* particleBuffer = PxGetPhysics().createParticleBuffer(desc.maxParticles, desc.maxVolumes, cudaContextManager); PxDmaDataToDevice(cudaContextManager, particleBuffer, desc); return particleBuffer; } PxParticleAndDiffuseBuffer* PxCreateAndPopulateParticleAndDiffuseBuffer(const PxParticleAndDiffuseBufferDesc& desc, PxCudaContextManager* cudaContextManager) { PxParticleAndDiffuseBuffer* particleBuffer = PxGetPhysics().createParticleAndDiffuseBuffer(desc.maxParticles, desc.maxVolumes, desc.maxDiffuseParticles, cudaContextManager); PxDmaDataToDevice(cudaContextManager, particleBuffer, desc); particleBuffer->setMaxActiveDiffuseParticles(desc.maxActiveDiffuseParticles); return particleBuffer; } PxParticleClothBuffer* PxCreateAndPopulateParticleClothBuffer(const PxParticleBufferDesc& desc, const PxParticleClothDesc& clothDesc, PxPartitionedParticleCloth& output, PxCudaContextManager* cudaContextManager) { #if PX_SUPPORT_GPU_PHYSX cudaContextManager->acquireContext(); PxParticleClothBuffer* clothBuffer = PxGetPhysics().createParticleClothBuffer(desc.maxParticles, desc.maxVolumes, clothDesc.nbCloths, clothDesc.nbTriangles, clothDesc.nbSprings, cudaContextManager); PxVec4* posInvMass = clothBuffer->getPositionInvMasses(); PxVec4* velocities = clothBuffer->getVelocities(); PxU32* phases = clothBuffer->getPhases(); PxParticleVolume* volumes = clothBuffer->getParticleVolumes(); PxU32* triangles = clothBuffer->getTriangles(); PxVec4* restPositions = clothBuffer->getRestPositions(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); cudaContext->memcpyHtoDAsync(CUdeviceptr(posInvMass), desc.positions, desc.numActiveParticles * sizeof(PxVec4), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(velocities), desc.velocities, desc.numActiveParticles * sizeof(PxVec4), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(phases), desc.phases, desc.numActiveParticles * sizeof(PxU32), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(volumes), desc.volumes, desc.numVolumes * sizeof(PxParticleVolume), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(triangles), clothDesc.triangles, clothDesc.nbTriangles * sizeof(PxU32) * 3, 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(restPositions), clothDesc.restPositions, desc.numActiveParticles * sizeof(PxVec4), 0); clothBuffer->setNbActiveParticles(desc.numActiveParticles); clothBuffer->setNbParticleVolumes(desc.numVolumes); clothBuffer->setNbTriangles(clothDesc.nbTriangles); clothBuffer->setCloths(output); cudaContext->streamSynchronize(0); cudaContextManager->releaseContext(); return clothBuffer; #else PX_UNUSED(desc); PX_UNUSED(clothDesc); PX_UNUSED(output); PX_UNUSED(cudaContextManager); return NULL; #endif } PxParticleRigidBuffer* PxCreateAndPopulateParticleRigidBuffer(const PxParticleBufferDesc& desc, const PxParticleRigidDesc& rigidDesc, PxCudaContextManager* cudaContextManager) { #if PX_SUPPORT_GPU_PHYSX cudaContextManager->acquireContext(); PxParticleRigidBuffer* rigidBuffer = PxGetPhysics().createParticleRigidBuffer(desc.maxParticles, desc.maxVolumes, rigidDesc.maxRigids, cudaContextManager); PxVec4* posInvMassd = rigidBuffer->getPositionInvMasses(); PxVec4* velocitiesd = rigidBuffer->getVelocities(); PxU32* phasesd = rigidBuffer->getPhases(); PxParticleVolume* volumesd = rigidBuffer->getParticleVolumes(); PxU32* rigidOffsetsd = rigidBuffer->getRigidOffsets(); PxReal* rigidCoefficientsd = rigidBuffer->getRigidCoefficients(); PxVec4* rigidTranslationsd = rigidBuffer->getRigidTranslations(); PxVec4* rigidRotationsd = rigidBuffer->getRigidRotations(); PxVec4* rigidLocalPositionsd = rigidBuffer->getRigidLocalPositions(); PxVec4* rigidLocalNormalsd = rigidBuffer->getRigidLocalNormals(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); const PxU32 numRigids = rigidDesc.numActiveRigids; const PxU32 numActiveParticles = desc.numActiveParticles; cudaContext->memcpyHtoDAsync(CUdeviceptr(posInvMassd), desc.positions, numActiveParticles * sizeof(PxVec4), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(velocitiesd), desc.velocities, numActiveParticles * sizeof(PxVec4), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(phasesd), desc.phases, numActiveParticles * sizeof(PxU32), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(volumesd), desc.volumes, desc.numVolumes * sizeof(PxParticleVolume), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(rigidOffsetsd), rigidDesc.rigidOffsets, sizeof(PxU32) * (numRigids + 1), 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(rigidCoefficientsd), rigidDesc.rigidCoefficients, sizeof(PxReal) * numRigids, 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(rigidTranslationsd), rigidDesc.rigidTranslations, sizeof(PxVec4) * numRigids, 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(rigidRotationsd), rigidDesc.rigidRotations, sizeof(PxQuat) * numRigids, 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(rigidLocalPositionsd), rigidDesc.rigidLocalPositions, sizeof(PxVec4) * desc.numActiveParticles, 0); cudaContext->memcpyHtoDAsync(CUdeviceptr(rigidLocalNormalsd), rigidDesc.rigidLocalNormals, sizeof(PxVec4) * desc.numActiveParticles, 0); rigidBuffer->setNbActiveParticles(numActiveParticles); rigidBuffer->setNbRigids(numRigids); rigidBuffer->setNbParticleVolumes(desc.numVolumes); cudaContext->streamSynchronize(0); cudaContextManager->releaseContext(); return rigidBuffer; #else PX_UNUSED(desc); PX_UNUSED(rigidDesc); PX_UNUSED(cudaContextManager); return NULL; #endif } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PxParticleAttachmentBuffer::PxParticleAttachmentBuffer(PxParticleBuffer& particleBuffer, PxParticleSystem& particleSystem) : mParticleBuffer(particleBuffer), mDeviceAttachments(NULL), mDeviceFilters(NULL), mNumDeviceAttachments(0), mNumDeviceFilters(0), mCudaContextManager(particleSystem.getCudaContextManager()), mParticleSystem(particleSystem), mDirty(false) { } PxParticleAttachmentBuffer::~PxParticleAttachmentBuffer() { #if PX_SUPPORT_GPU_PHYSX mCudaContextManager->acquireContext(); PxCudaContext* cudaContext = mCudaContextManager->getCudaContext(); if (mDeviceAttachments) cudaContext->memFree((CUdeviceptr)mDeviceAttachments); if (mDeviceFilters) cudaContext->memFree((CUdeviceptr)mDeviceFilters); mDeviceAttachments = NULL; mDeviceFilters = NULL; mCudaContextManager->releaseContext(); #endif } void PxParticleAttachmentBuffer::copyToDevice(CUstream stream) { #if PX_SUPPORT_GPU_PHYSX mCudaContextManager->acquireContext(); PxCudaContext* cudaContext = mCudaContextManager->getCudaContext(); if (mAttachments.size() > mNumDeviceAttachments) { if (mDeviceAttachments) cudaContext->memFree((CUdeviceptr)mDeviceAttachments); cudaContext->memAlloc((CUdeviceptr*)&mDeviceAttachments, sizeof(PxParticleRigidAttachment)*mAttachments.size()); mNumDeviceAttachments = mAttachments.size(); } if (mFilters.size() > mNumDeviceFilters) { if (mDeviceFilters) cudaContext->memFree((CUdeviceptr)mDeviceFilters); cudaContext->memAlloc((CUdeviceptr*)&mDeviceFilters, sizeof(PxParticleRigidFilterPair)*mFilters.size()); mNumDeviceFilters = mFilters.size(); } if (mAttachments.size()) cudaContext->memcpyHtoDAsync((CUdeviceptr)mDeviceAttachments, mAttachments.begin(), sizeof(PxParticleRigidAttachment)*mAttachments.size(), stream); if (mFilters.size()) cudaContext->memcpyHtoDAsync((CUdeviceptr)mDeviceFilters, mFilters.begin(), sizeof(PxParticleRigidFilterPair)*mFilters.size(), stream); mParticleBuffer.setRigidAttachments(mDeviceAttachments, mAttachments.size()); mParticleBuffer.setRigidFilters(mDeviceFilters, mFilters.size()); mDirty = true; for (PxU32 i = 0; i < mNewReferencedBodies.size(); ++i) { if (mReferencedBodies[mNewReferencedBodies[i]] > 0) mParticleSystem.addRigidAttachment(mNewReferencedBodies[i]); } for (PxU32 i = 0; i < mDestroyedRefrencedBodies.size(); ++i) { if (mReferencedBodies[mDestroyedRefrencedBodies[i]] == 0) mParticleSystem.removeRigidAttachment(mDestroyedRefrencedBodies[i]); } mNewReferencedBodies.resize(0); mDestroyedRefrencedBodies.resize(0); mCudaContextManager->releaseContext(); #else PX_UNUSED(stream); #endif } void PxParticleAttachmentBuffer::addRigidAttachment(PxRigidActor* rigidActor, const PxU32 particleID, const PxVec3& localPose, PxConeLimitedConstraint* coneLimit) { PX_CHECK_AND_RETURN(coneLimit == NULL || coneLimit->isValid(), "PxParticleAttachmentBuffer::addRigidAttachment: PxConeLimitedConstraint needs to be valid if specified."); PX_ASSERT(particleID < mParticleBuffer.getNbActiveParticles()); PxParticleRigidAttachment attachment(PxConeLimitedConstraint(), PxVec4(0.0f)); if (rigidActor == NULL) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxParticleAttachmentBuffer::addRigidAttachment: rigidActor cannot be NULL."); return; } if (coneLimit) { attachment.mConeLimitParams.axisAngle = PxVec4(coneLimit->mAxis, coneLimit->mAngle); attachment.mConeLimitParams.lowHighLimits = PxVec4(coneLimit->mLowLimit, coneLimit->mHighLimit, 0.f, 0.f); } if (rigidActor->getType() == PxActorType::eRIGID_STATIC) { // attachments to rigid static work in global space attachment.mLocalPose0 = PxVec4(static_cast<PxRigidBody*>(rigidActor)->getGlobalPose().transform(localPose), 0.0f); attachment.mID0 = PxNodeIndex().getInd(); } else { // others use body space. PxRigidBody* rigid = static_cast<PxRigidBody*>(rigidActor); PxTransform body2Actor = rigid->getCMassLocalPose(); attachment.mLocalPose0 = PxVec4(body2Actor.transformInv(localPose), 0.f); attachment.mID0 = rigid->getInternalIslandNodeIndex().getInd(); } attachment.mID1 = particleID; //Insert in order... PxU32 l = 0, r = PxU32(mAttachments.size()); while (l < r) //If difference is just 1, we've found an item... { PxU32 index = (l + r) / 2; if (attachment < mAttachments[index]) r = index; else if (attachment > mAttachments[index]) l = index + 1; else l = r = index; //This is a match so insert before l } mAttachments.insert(); for (PxU32 i = mAttachments.size()-1; i > l; --i) { mAttachments[i] = mAttachments[i - 1]; } mAttachments[l] = attachment; mDirty = true; if (rigidActor) { PxU32& refCount = mReferencedBodies[rigidActor]; if (refCount == 0) mNewReferencedBodies.pushBack(rigidActor); refCount++; } } bool PxParticleAttachmentBuffer::removeRigidAttachment(PxRigidActor* rigidActor, const PxU32 particleID) { PX_ASSERT(particleID < mParticleBuffer.getNbActiveParticles()); if (rigidActor == NULL) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxParticleAttachmentBuffer::removeRigidAttachment: rigidActor cannot be NULL."); return false; } if (rigidActor) { PxU32& refCount = mReferencedBodies[rigidActor]; refCount--; if (refCount == 0) mDestroyedRefrencedBodies.pushBack(rigidActor); } PxParticleRigidFilterPair attachment; attachment.mID0 = rigidActor->getType() != PxActorType::eRIGID_STATIC ? static_cast<PxRigidBody*>(rigidActor)->getInternalIslandNodeIndex().getInd() : PxNodeIndex().getInd(); attachment.mID1 = particleID; PxU32 l = 0, r = PxU32(mAttachments.size()); while (l < r) //If difference is just 1, we've found an item... { PxU32 index = (l + r) / 2; if (attachment < mAttachments[index]) r = index; else if (attachment > mAttachments[index]) l = index + 1; else l = r = index; //This is a match so insert before l } if (mAttachments[l] == attachment) { mDirty = true; //Remove mAttachments.remove(l); return true; } return false; } void PxParticleAttachmentBuffer::addRigidFilter(PxRigidActor* rigidActor, const PxU32 particleID) { PX_ASSERT(particleID < mParticleBuffer.getNbActiveParticles()); PxParticleRigidFilterPair attachment; attachment.mID0 = rigidActor->getType() != PxActorType::eRIGID_STATIC ? static_cast<PxRigidBody*>(rigidActor)->getInternalIslandNodeIndex().getInd() : PxNodeIndex().getInd(); attachment.mID1 = particleID; //Insert in order... PxU32 l = 0, r = PxU32(mFilters.size()); while (l < r) //If difference is just 1, we've found an item... { PxU32 index = (l + r) / 2; if (attachment < mFilters[index]) r = index; else if (attachment > mFilters[index]) l = index + 1; else l = r = index; //This is a match so insert before l } mFilters.insert(); for (PxU32 i = mFilters.size() - 1; i > l; --i) { mFilters[i] = mFilters[i - 1]; } mFilters[l] = attachment; mDirty = true; } bool PxParticleAttachmentBuffer::removeRigidFilter(PxRigidActor* rigidActor, const PxU32 particleID) { PX_ASSERT(particleID < mParticleBuffer.getNbActiveParticles()); PxParticleRigidFilterPair attachment; attachment.mID0 = rigidActor->getType() != PxActorType::eRIGID_STATIC ? static_cast<PxRigidBody*>(rigidActor)->getInternalIslandNodeIndex().getInd() : PxNodeIndex().getInd(); attachment.mID1 = particleID; PxU32 l = 0, r = PxU32(mFilters.size()); while (l < r) //If difference is just 1, we've found an item... { PxU32 index = (l + r) / 2; if (attachment < mFilters[index]) r = index; else if (attachment > mFilters[index]) l = index + 1; else l = r = index; //This is a match so insert before l } if (mFilters[l] == attachment) { mDirty = true; //Remove mFilters.remove(l); return true; } return false; } PxParticleAttachmentBuffer* PxCreateParticleAttachmentBuffer(PxParticleBuffer& buffer, PxParticleSystem& particleSystem) { return PX_NEW(PxParticleAttachmentBuffer)(buffer, particleSystem); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ParticleClothBuffersImpl : public PxParticleClothBufferHelper, public PxUserAllocated { ParticleClothBuffersImpl(const PxU32 maxCloths, const PxU32 maxTriangles, const PxU32 maxSprings, const PxU32 maxParticles, PxCudaContextManager* cudaContextManager) : mCudaContextManager(cudaContextManager) { mMaxParticles = maxParticles; mClothDesc.nbParticles = 0; mMaxTriangles = maxTriangles; mClothDesc.nbTriangles = 0; mMaxSprings = maxSprings; mClothDesc.nbSprings = 0; mMaxCloths = maxCloths; mClothDesc.nbCloths = 0; #if PX_SUPPORT_GPU_PHYSX mClothDesc.restPositions = mCudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); mClothDesc.triangles = mCudaContextManager->allocPinnedHostBuffer<PxU32>(maxTriangles * 3); mClothDesc.springs = mCudaContextManager->allocPinnedHostBuffer<PxParticleSpring>(maxSprings); mClothDesc.cloths = mCudaContextManager->allocPinnedHostBuffer<PxParticleCloth>(maxCloths); #endif } void release() { #if PX_SUPPORT_GPU_PHYSX mCudaContextManager->freePinnedHostBuffer(mClothDesc.cloths); mCudaContextManager->freePinnedHostBuffer(mClothDesc.restPositions); mCudaContextManager->freePinnedHostBuffer(mClothDesc.triangles); mCudaContextManager->freePinnedHostBuffer(mClothDesc.springs); #endif PX_DELETE_THIS; } PxU32 getMaxCloths() const { return mMaxCloths; } PxU32 getNumCloths() const { return mClothDesc.nbCloths; } PxU32 getMaxSprings() const { return mMaxSprings; } PxU32 getNumSprings() const { return mClothDesc.nbSprings; } PxU32 getMaxTriangles() const { return mMaxTriangles; } PxU32 getNumTriangles() const { return mClothDesc.nbTriangles; } PxU32 getMaxParticles() const { return mMaxParticles; } PxU32 getNumParticles() const { return mClothDesc.nbParticles; } void addCloth(const PxParticleCloth& particleCloth, const PxU32* triangles, const PxU32 numTriangles, const PxParticleSpring* springs, const PxU32 numSprings, const PxVec4* restPositions, const PxU32 numParticles) { if (mClothDesc.nbCloths + 1 > mMaxCloths) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxParticleClothBufferHelper::addCloth: exceeding maximal number of cloths that can be added."); return; } if (mClothDesc.nbSprings + numSprings > mMaxSprings) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxParticleClothBufferHelper::addCloth: exceeding maximal number of springs that can be added."); return; } if (mClothDesc.nbTriangles + numTriangles > mMaxTriangles) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxParticleClothBufferHelper::addCloth: exceeding maximal number of triangles that can be added."); return; } if (mClothDesc.nbParticles + numParticles > mMaxParticles) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxParticleClothBufferHelper::addCloth: exceeding maximal number of particles that can be added."); return; } mClothDesc.cloths[mClothDesc.nbCloths] = particleCloth; mClothDesc.nbCloths += 1; for (PxU32 i = 0; i < numSprings; ++i) { PxParticleSpring& dst = mClothDesc.springs[mClothDesc.nbSprings + i]; dst = springs[i]; dst.ind0 += mClothDesc.nbParticles; dst.ind1 += mClothDesc.nbParticles; } mClothDesc.nbSprings += numSprings; for (PxU32 i = 0; i < numTriangles*3; ++i) { PxU32& dst = mClothDesc.triangles[mClothDesc.nbTriangles*3 + i]; dst = triangles[i] + mClothDesc.nbParticles; } mClothDesc.nbTriangles += numTriangles; PxMemCopy(mClothDesc.restPositions + mClothDesc.nbParticles, restPositions, sizeof(PxVec4)*numParticles); mClothDesc.nbParticles += numParticles; } void addCloth(const PxReal blendScale, const PxReal restVolume, const PxReal pressure, const PxU32* triangles, const PxU32 numTriangles, const PxParticleSpring* springs, const PxU32 numSprings, const PxVec4* restPositions, const PxU32 numParticles) { PX_UNUSED(blendScale); PxParticleCloth particleCloth; //particleCloth.clothBlendScale = blendScale; particleCloth.restVolume = restVolume; particleCloth.pressure = pressure; particleCloth.startVertexIndex = mClothDesc.nbParticles; particleCloth.numVertices = numParticles; particleCloth.startTriangleIndex = mClothDesc.nbTriangles * 3; particleCloth.numTriangles = numTriangles; addCloth(particleCloth, triangles, numTriangles, springs, numSprings, restPositions, numParticles); } PxParticleClothDesc& getParticleClothDesc() { return mClothDesc; } PxU32 mMaxCloths; PxU32 mMaxSprings; PxU32 mMaxTriangles; PxU32 mMaxParticles; PxParticleClothDesc mClothDesc; PxCudaContextManager* mCudaContextManager; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ParticleVolumeBuffersImpl : public PxParticleVolumeBufferHelper, public PxUserAllocated { ParticleVolumeBuffersImpl(PxU32 maxVolumes, PxU32 maxTriangles, PxCudaContextManager* cudaContextManager) { mMaxVolumes = maxVolumes; mNumVolumes = 0; mMaxTriangles = maxTriangles; mNumTriangles = 0; mParticleVolumeMeshes = reinterpret_cast<PxParticleVolumeMesh*>(PX_ALLOC(sizeof(PxParticleVolumeMesh) * maxVolumes, "ParticleVolumeBuffersImpl::mParticleVolumeMeshes")); mTriangles = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * maxTriangles * 3, "ParticleVolumeBuffersImpl::mTriangles")); #if PX_SUPPORT_GPU_PHYSX mParticleVolumes = cudaContextManager->allocPinnedHostBuffer<PxParticleVolume>(maxVolumes); mCudaContextManager = cudaContextManager; #else PX_UNUSED(cudaContextManager); #endif } void release() { #if PX_SUPPORT_GPU_PHYSX mCudaContextManager->freePinnedHostBuffer(mParticleVolumes); #endif PX_FREE(mParticleVolumeMeshes); PX_FREE(mTriangles); PX_DELETE_THIS; } virtual PxU32 getMaxVolumes() const { return mMaxVolumes; } virtual PxU32 getNumVolumes() const { return mNumVolumes; } virtual PxU32 getMaxTriangles() const { return mMaxTriangles; } virtual PxU32 getNumTriangles() const { return mNumTriangles; } virtual PxParticleVolume* getParticleVolumes() { return mParticleVolumes; } virtual PxParticleVolumeMesh* getParticleVolumeMeshes() { return mParticleVolumeMeshes; } virtual PxU32* getTriangles() { return mTriangles; } virtual void addVolume(const PxParticleVolume& volume, const PxParticleVolumeMesh& volumeMesh, const PxU32* triangles, const PxU32 numTriangles) { if (mNumVolumes < mMaxVolumes && mNumTriangles + numTriangles <= mMaxTriangles) { PX_ASSERT(volumeMesh.startIndex == mNumTriangles); mParticleVolumes[mNumVolumes] = volume; mParticleVolumeMeshes[mNumVolumes] = volumeMesh; mNumVolumes++; for (PxU32 i = 0; i < numTriangles*3; ++i) { mTriangles[mNumTriangles*3 + i] = triangles[i] + volumeMesh.startIndex; } mNumTriangles += numTriangles; } } virtual void addVolume(const PxU32 particleOffset, const PxU32 numParticles, const PxU32* triangles, const PxU32 numTriangles) { if (mNumVolumes < mMaxVolumes && mNumTriangles + numTriangles <= mMaxTriangles) { PxParticleVolume particleVolume; particleVolume.bound.setEmpty(); particleVolume.particleIndicesOffset = particleOffset; particleVolume.numParticles = numParticles; PxParticleVolumeMesh particleVolumeMesh; particleVolumeMesh.startIndex = mNumTriangles; particleVolumeMesh.count = numTriangles; mParticleVolumes[mNumVolumes] = particleVolume; mParticleVolumeMeshes[mNumVolumes] = particleVolumeMesh; mNumVolumes++; for (PxU32 i = 0; i < numTriangles*3; ++i) { mTriangles[mNumTriangles*3 + i] = triangles[i] + particleOffset; } mNumTriangles += numTriangles; } } PxU32 mMaxVolumes; PxU32 mNumVolumes; PxU32 mMaxTriangles; PxU32 mNumTriangles; PxParticleVolume* mParticleVolumes; PxParticleVolumeMesh* mParticleVolumeMeshes; PxU32* mTriangles; PxCudaContextManager* mCudaContextManager; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ParticleRigidBuffersImpl : public PxParticleRigidBufferHelper, public PxUserAllocated { ParticleRigidBuffersImpl(PxU32 maxRigids, PxU32 maxParticles, PxCudaContextManager* cudaContextManager) : mCudaContextManager(cudaContextManager) { mRigidDesc.maxRigids = maxRigids; mRigidDesc.numActiveRigids = 0; mMaxParticles = maxParticles; mNumParticles = 0; #if PX_SUPPORT_GPU_PHYSX mCudaContextManager->allocPinnedHostBuffer<PxU32>(mRigidDesc.rigidOffsets, maxRigids + 1); mCudaContextManager->allocPinnedHostBuffer<PxReal>(mRigidDesc.rigidCoefficients, maxRigids); mCudaContextManager->allocPinnedHostBuffer<PxVec4>(mRigidDesc.rigidTranslations, maxRigids); mCudaContextManager->allocPinnedHostBuffer<PxQuat>(mRigidDesc.rigidRotations, maxRigids); mCudaContextManager->allocPinnedHostBuffer<PxVec4>(mRigidDesc.rigidLocalPositions, maxParticles); mCudaContextManager->allocPinnedHostBuffer<PxVec4>(mRigidDesc.rigidLocalNormals, maxParticles); #endif } void release() { #if PX_SUPPORT_GPU_PHYSX mCudaContextManager->freePinnedHostBuffer(mRigidDesc.rigidOffsets); mCudaContextManager->freePinnedHostBuffer(mRigidDesc.rigidCoefficients); mCudaContextManager->freePinnedHostBuffer(mRigidDesc.rigidTranslations); mCudaContextManager->freePinnedHostBuffer(mRigidDesc.rigidRotations); mCudaContextManager->freePinnedHostBuffer(mRigidDesc.rigidLocalPositions); mCudaContextManager->freePinnedHostBuffer(mRigidDesc.rigidLocalNormals); #endif PX_DELETE_THIS; } virtual PxU32 getMaxRigids() const { return mRigidDesc.maxRigids; } virtual PxU32 getNumRigids() const { return mRigidDesc.numActiveRigids; } virtual PxU32 getMaxParticles() const { return mMaxParticles; } virtual PxU32 getNumParticles() const { return mNumParticles; } void addRigid(const PxVec3& translation, const PxQuat& rotation, const PxReal coefficient, const PxVec4* localPositions, const PxVec4* localNormals, PxU32 numParticles) { PX_ASSERT(numParticles > 0); const PxU32 numRigids = mRigidDesc.numActiveRigids; if (numParticles > 0 && numRigids < mRigidDesc.maxRigids && mNumParticles + numParticles <= mMaxParticles) { mRigidDesc.rigidOffsets[numRigids] = mNumParticles; mRigidDesc.rigidOffsets[numRigids + 1] = mNumParticles + numParticles; mRigidDesc.rigidTranslations[numRigids] = PxVec4(translation, 0.0f); mRigidDesc.rigidRotations[numRigids] = rotation; mRigidDesc.rigidCoefficients[numRigids] = coefficient; PxMemCopy(mRigidDesc.rigidLocalPositions + mNumParticles, localPositions, numParticles * sizeof(PxVec4)); PxMemCopy(mRigidDesc.rigidLocalNormals + mNumParticles, localNormals, numParticles * sizeof(PxVec4)); mRigidDesc.numActiveRigids += 1; mNumParticles += numParticles; } } PxParticleRigidDesc& getParticleRigidDesc() { return mRigidDesc; } PxU32 mMaxParticles; PxU32 mNumParticles; PxParticleRigidDesc mRigidDesc; PxCudaContextManager* mCudaContextManager; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PxParticleVolumeBufferHelper* PxCreateParticleVolumeBufferHelper(PxU32 maxVolumes, PxU32 maxTriangles, PxCudaContextManager* cudaContextManager) { PxParticleVolumeBufferHelper* ret = NULL; #if PX_SUPPORT_GPU_PHYSX ret = PX_NEW(ParticleVolumeBuffersImpl)(maxVolumes, maxTriangles, cudaContextManager); #else PX_UNUSED(maxVolumes); PX_UNUSED(maxTriangles); PX_UNUSED(cudaContextManager); #endif return ret; } PxParticleClothBufferHelper* PxCreateParticleClothBufferHelper(const PxU32 maxCloths, const PxU32 maxTriangles, const PxU32 maxSprings, const PxU32 maxParticles, PxCudaContextManager* cudaContextManager) { PxParticleClothBufferHelper* ret = NULL; #if PX_SUPPORT_GPU_PHYSX ret = PX_NEW(ParticleClothBuffersImpl)(maxCloths, maxTriangles, maxSprings, maxParticles, cudaContextManager); #else PX_UNUSED(maxCloths); PX_UNUSED(maxTriangles); PX_UNUSED(maxSprings); PX_UNUSED(maxParticles); PX_UNUSED(cudaContextManager); #endif return ret; } PxParticleRigidBufferHelper* PxCreateParticleRigidBufferHelper(const PxU32 maxRigids, const PxU32 maxParticles, PxCudaContextManager* cudaContextManager) { PxParticleRigidBufferHelper* ret = NULL; #if PX_SUPPORT_GPU_PHYSX ret = PX_NEW(ParticleRigidBuffersImpl)(maxRigids, maxParticles, cudaContextManager); #else PX_UNUSED(maxRigids); PX_UNUSED(maxParticles); PX_UNUSED(cudaContextManager); #endif return ret; } } //namespace ExtGpu } //namespace physx
29,866
C++
35.378806
211
0.762004
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSimpleFactory.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 "foundation/PxQuat.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxBoxGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "geometry/PxPlaneGeometry.h" #include "extensions/PxRigidBodyExt.h" #include "extensions/PxSimpleFactory.h" #include "PxPhysics.h" #include "PxScene.h" #include "PxRigidStatic.h" #include "PxRigidStatic.h" #include "PxRigidDynamic.h" #include "PxShape.h" #include "foundation/PxUtilities.h" #include "foundation/PxInlineArray.h" using namespace physx; static bool isDynamicGeometry(PxGeometryType::Enum type) { return type == PxGeometryType::eBOX || type == PxGeometryType::eSPHERE || type == PxGeometryType::eCAPSULE || type == PxGeometryType::eCONVEXMESH; } namespace physx { PxRigidDynamic* PxCreateDynamic(PxPhysics& sdk, const PxTransform& transform, PxShape& shape, PxReal density) { PX_CHECK_AND_RETURN_NULL(transform.isValid(), "PxCreateDynamic: transform is not valid."); PxRigidDynamic* actor = sdk.createRigidDynamic(transform); if(actor) { if(!actor->attachShape(shape)) { actor->release(); return NULL; } if(!PxRigidBodyExt::updateMassAndInertia(*actor, density)) { actor->release(); return NULL; } } return actor; } PxRigidDynamic* PxCreateDynamic(PxPhysics& sdk, const PxTransform& transform, const PxGeometry& geometry, PxMaterial& material, PxReal density, const PxTransform& shapeOffset) { PX_CHECK_AND_RETURN_NULL(transform.isValid(), "PxCreateDynamic: transform is not valid."); PX_CHECK_AND_RETURN_NULL(shapeOffset.isValid(), "PxCreateDynamic: shapeOffset is not valid."); if(!isDynamicGeometry(geometry.getType()) || density <= 0.0f) return NULL; PxShape* shape = sdk.createShape(geometry, material, true); if(!shape) return NULL; shape->setLocalPose(shapeOffset); PxRigidDynamic* body = shape ? PxCreateDynamic(sdk, transform, *shape, density) : NULL; shape->release(); return body; } PxRigidDynamic* PxCreateKinematic(PxPhysics& sdk, const PxTransform& transform, PxShape& shape, PxReal density) { PX_CHECK_AND_RETURN_NULL(transform.isValid(), "PxCreateKinematic: transform is not valid."); bool isDynGeom = isDynamicGeometry(shape.getGeometry().getType()); if(isDynGeom && density <= 0.0f) return NULL; PxRigidDynamic* actor = sdk.createRigidDynamic(transform); if(actor) { actor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); if(!isDynGeom) shape.setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); actor->attachShape(shape); if(isDynGeom) PxRigidBodyExt::updateMassAndInertia(*actor, density); else { actor->setMass(1.f); actor->setMassSpaceInertiaTensor(PxVec3(1.f,1.f,1.f)); } } return actor; } PxRigidDynamic* PxCreateKinematic(PxPhysics& sdk, const PxTransform& transform, const PxGeometry& geometry, PxMaterial& material, PxReal density, const PxTransform& shapeOffset) { PX_CHECK_AND_RETURN_NULL(transform.isValid(), "PxCreateKinematic: transform is not valid."); PX_CHECK_AND_RETURN_NULL(shapeOffset.isValid(), "PxCreateKinematic: shapeOffset is not valid."); bool isDynGeom = isDynamicGeometry(geometry.getType()); if(isDynGeom && density <= 0.0f) return NULL; PxShape* shape = sdk.createShape(geometry, material, true); if(!shape) return NULL; shape->setLocalPose(shapeOffset); PxRigidDynamic* body = PxCreateKinematic(sdk, transform, *shape, density); shape->release(); return body; } PxRigidStatic* PxCreateStatic(PxPhysics& sdk, const PxTransform& transform, PxShape& shape) { PX_CHECK_AND_RETURN_NULL(transform.isValid(), "PxCreateStatic: transform is not valid."); PxRigidStatic* s = sdk.createRigidStatic(transform); if(s) s->attachShape(shape); return s; } PxRigidStatic* PxCreateStatic(PxPhysics& sdk, const PxTransform& transform, const PxGeometry& geometry, PxMaterial& material, const PxTransform& shapeOffset) { PX_CHECK_AND_RETURN_NULL(transform.isValid(), "PxCreateStatic: transform is not valid."); PX_CHECK_AND_RETURN_NULL(shapeOffset.isValid(), "PxCreateStatic: shapeOffset is not valid."); PxShape* shape = sdk.createShape(geometry, material, true); if(!shape) return NULL; shape->setLocalPose(shapeOffset); PxRigidStatic* s = PxCreateStatic(sdk, transform, *shape); shape->release(); return s; } PxRigidStatic* PxCreatePlane(PxPhysics& sdk, const PxPlane& plane, PxMaterial& material) { PX_CHECK_AND_RETURN_NULL(plane.n.isFinite(), "PxCreatePlane: plane normal is not valid."); if (!plane.n.isNormalized()) return NULL; return PxCreateStatic(sdk, PxTransformFromPlaneEquation(plane), PxPlaneGeometry(), material); } PxShape* PxCloneShape(PxPhysics& physics, const PxShape& from, bool isExclusive) { PxInlineArray<PxMaterial*, 64> materials; PxU16 materialCount = from.getNbMaterials(); materials.resize(materialCount); from.getMaterials(materials.begin(), materialCount); PxShape* to = physics.createShape(from.getGeometry(), materials.begin(), materialCount, isExclusive, from.getFlags()); to->setLocalPose(from.getLocalPose()); to->setContactOffset(from.getContactOffset()); to->setRestOffset(from.getRestOffset()); to->setSimulationFilterData(from.getSimulationFilterData()); to->setQueryFilterData(from.getQueryFilterData()); to->setTorsionalPatchRadius(from.getTorsionalPatchRadius()); to->setMinTorsionalPatchRadius(from.getMinTorsionalPatchRadius()); return to; } static void copyStaticProperties(PxPhysics& physics, PxRigidActor& to, const PxRigidActor& from) { PxInlineArray<PxShape*, 64> shapes; shapes.resize(from.getNbShapes()); PxU32 shapeCount = from.getNbShapes(); from.getShapes(shapes.begin(), shapeCount); for(PxU32 i = 0; i < shapeCount; i++) { PxShape* s = shapes[i]; if(!s->isExclusive()) to.attachShape(*s); else { PxShape* newShape = physx::PxCloneShape(physics, *s, true); to.attachShape(*newShape); newShape->release(); } } to.setActorFlags(from.getActorFlags()); to.setOwnerClient(from.getOwnerClient()); to.setDominanceGroup(from.getDominanceGroup()); } PxRigidStatic* PxCloneStatic(PxPhysics& physicsSDK, const PxTransform& transform, const PxRigidActor& from) { PxRigidStatic* to = physicsSDK.createRigidStatic(transform); if(!to) return NULL; copyStaticProperties(physicsSDK, *to, from); return to; } PxRigidDynamic* PxCloneDynamic(PxPhysics& physicsSDK, const PxTransform& transform, const PxRigidDynamic& from) { PxRigidDynamic* to = physicsSDK.createRigidDynamic(transform); if(!to) return NULL; copyStaticProperties(physicsSDK, *to, from); to->setRigidBodyFlags(from.getRigidBodyFlags()); to->setMass(from.getMass()); to->setMassSpaceInertiaTensor(from.getMassSpaceInertiaTensor()); to->setCMassLocalPose(from.getCMassLocalPose()); to->setLinearVelocity(from.getLinearVelocity()); to->setAngularVelocity(from.getAngularVelocity()); to->setLinearDamping(from.getLinearDamping()); to->setAngularDamping(from.getAngularDamping()); PxU32 posIters, velIters; from.getSolverIterationCounts(posIters, velIters); to->setSolverIterationCounts(posIters, velIters); to->setMaxLinearVelocity(from.getMaxLinearVelocity()); to->setMaxAngularVelocity(from.getMaxAngularVelocity()); to->setMaxDepenetrationVelocity(from.getMaxDepenetrationVelocity()); to->setSleepThreshold(from.getSleepThreshold()); to->setStabilizationThreshold(from.getStabilizationThreshold()); to->setMinCCDAdvanceCoefficient(from.getMinCCDAdvanceCoefficient()); to->setContactReportThreshold(from.getContactReportThreshold()); to->setMaxContactImpulse(from.getMaxContactImpulse()); PxTransform target; if (from.getKinematicTarget(target)) to->setKinematicTarget(target); to->setRigidDynamicLockFlags(from.getRigidDynamicLockFlags()); return to; } static PxTransform scalePosition(const PxTransform& t, PxReal scale) { return PxTransform(t.p*scale, t.q); } void PxScaleRigidActor(PxRigidActor& actor, PxReal scale, bool scaleMassProps) { PX_CHECK_AND_RETURN(scale > 0, "PxScaleRigidActor requires that the scale parameter is greater than zero"); PxInlineArray<PxShape*, 64> shapes; shapes.resize(actor.getNbShapes()); actor.getShapes(shapes.begin(), shapes.size()); for(PxU32 i=0;i<shapes.size();i++) { shapes[i]->setLocalPose(scalePosition(shapes[i]->getLocalPose(), scale)); PxGeometryHolder h(shapes[i]->getGeometry()); switch(h.getType()) { case PxGeometryType::eSPHERE: h.sphere().radius *= scale; break; case PxGeometryType::ePLANE: break; case PxGeometryType::eCAPSULE: h.capsule().halfHeight *= scale; h.capsule().radius *= scale; break; case PxGeometryType::eBOX: h.box().halfExtents *= scale; break; case PxGeometryType::eCONVEXMESH: h.convexMesh().scale.scale *= scale; break; case PxGeometryType::eTRIANGLEMESH: h.triangleMesh().scale.scale *= scale; break; case PxGeometryType::eHEIGHTFIELD: h.heightField().heightScale *= scale; h.heightField().rowScale *= scale; h.heightField().columnScale *= scale; break; default: PX_ASSERT(0); } shapes[i]->setGeometry(h.any()); } if(!scaleMassProps) return; PxRigidDynamic* dynamic = (&actor)->is<PxRigidDynamic>(); if(!dynamic) return; PxReal scale3 = scale*scale*scale; dynamic->setMass(dynamic->getMass()*scale3); dynamic->setMassSpaceInertiaTensor(dynamic->getMassSpaceInertiaTensor()*scale3*scale*scale); dynamic->setCMassLocalPose(scalePosition(dynamic->getCMassLocalPose(), scale)); } }
11,482
C++
29.703208
119
0.73637
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtParticleClothCooker.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 "extensions/PxParticleClothCooker.h" #include "foundation/PxArray.h" #include "foundation/PxSort.h" #include "foundation/PxHashMap.h" #include "foundation/PxHashSet.h" #include "GuInternal.h" namespace physx { namespace ExtGpu { namespace { struct Edge { Edge(PxU32 v0, PxU32 v1, PxU32 triangle0, PxU32 triangle1, bool isLongest0, bool isLongest1) { a = PxMin(v0, v1); b = PxMax(v0, v1); triangleA = triangle0; triangleB = triangle1; longestA = isLongest0; longestB = isLongest1; PX_ASSERT_WITH_MESSAGE(a != b, "PxCreateInflatableFromMesh encountered a degenerate edge inside a triangle."); } PxU32 a, b; PxU32 triangleA, triangleB; bool longestA, longestB; //true if it is the longest edge of triangle bool operator<(const Edge& other) const { if(a == other.a) return b < other.b; return a < other.a; } bool operator==(const Edge& other) const { if(a == other.a) return b == other.b; return false; } }; class EdgeHash { public: uint32_t operator()(const Edge& e) const { return PxComputeHash(e.a) ^ PxComputeHash(e.b); } bool equal(const Edge& e0, const Edge& e1) const { return e0.a == e1.a && e0.b == e1.b; } }; class EdgeSet : public PxHashSet<Edge, EdgeHash> { public: typedef PxHashSet<Edge, EdgeHash> Base; typedef Base::Iterator Iterator; void insert(const Edge& newEdge) { PX_ASSERT(newEdge.a < newEdge.b); bool exists; Edge* edge = mBase.create(newEdge, exists); if (!exists) { PX_PLACEMENT_NEW(edge, Edge)(newEdge); } else { PX_ASSERT_WITH_MESSAGE(edge->triangleB == 0xffffffff, "Edge with more than 2 triangles found in PxCreateInflatableFromMesh"); edge->triangleB = newEdge.triangleA; //Add triangle info from duplicate to Unique edge edge->longestB = newEdge.longestA; } } }; template<typename T> void partialSum(T* begin, T* end, T* dest) { *dest = *begin; dest++; begin++; while(begin!=end) { *dest = dest[-1] + *begin; dest++; begin++; } } /* outAdjacencies is a list of adjacent vertices in outAdjacencies outAdjacencyIndices is a list of indices to quickly find adjacent vertices in outAdjacencies. all the adjacent vertices to vertex V are stored in outAdjacencies starting at outAdjacencyIndices[V] and ending at outAdjacencyIndices[V+1] so the first vertex is outAdjacencies[outAdjacencyIndices[V]], and the last one is outAdjacencies[outAdjacencyIndices[V+1]-1] */ void gatherAdjacencies(PxArray<PxU32>& outAdjacencyIndices, PxArray<PxU32>& outAdjacencies, PxU32 vertexCount, PxArray<Edge> const& inUniqueEdges, bool ignoreDiagonals = false ) { PX_ASSERT(outAdjacencyIndices.size() == 0); PX_ASSERT(outAdjacencies.size() == 0); outAdjacencyIndices.resize(vertexCount+1, 0); //calculate valency for(PxU32 i = 0; i < inUniqueEdges.size(); i++) { const Edge& edge = inUniqueEdges[i]; if(ignoreDiagonals && edge.longestA && edge.longestB) continue; outAdjacencyIndices[edge.a]++; outAdjacencyIndices[edge.b]++; } partialSum(outAdjacencyIndices.begin(), outAdjacencyIndices.end(), outAdjacencyIndices.begin()); outAdjacencyIndices.back() = outAdjacencyIndices[vertexCount-1]; outAdjacencies.resize(outAdjacencyIndices.back(),0xffffffff); for(PxU32 i = 0; i < inUniqueEdges.size(); i++) { const Edge& edge = inUniqueEdges[i]; if(ignoreDiagonals && edge.longestA && edge.longestB) continue; outAdjacencyIndices[edge.a]--; outAdjacencies[outAdjacencyIndices[edge.a]]=edge.b; outAdjacencyIndices[edge.b]--; outAdjacencies[outAdjacencyIndices[edge.b]] = edge.a; } } template <typename T, typename A> A MaxArg(T const& vA, T const& vB, A const& aA, A const& aB) { if(vA > vB) return aA; return aB; } PxU32 GetOppositeVertex(PxU32* inTriangleIndices, PxU32 triangleIndex, PxU32 a, PxU32 b) { for(int i = 0; i<3; i++) { if(inTriangleIndices[triangleIndex+i] != a && inTriangleIndices[triangleIndex + i] !=b) return inTriangleIndices[triangleIndex + i]; } PX_ASSERT_WITH_MESSAGE(0, "Degenerate Triangle found in PxCreateInflatableFromMesh"); return 0; } Edge GetAlternateDiagonal(Edge const& edge, PxU32* inTriangleIndices) { PxU32 vA = GetOppositeVertex(inTriangleIndices, edge.triangleA, edge.a, edge.b); PxU32 vB = GetOppositeVertex(inTriangleIndices, edge.triangleB, edge.a, edge.b); bool longestA = true; bool longestB = true; PxU32 tA = 0xffffffff; PxU32 tB = 0xffffffff; return Edge(vA, vB, tA, tB, longestA, longestB); } } //namespace class PxParticleClothCookerImpl : public PxParticleClothCooker, public PxUserAllocated { public: PxParticleClothCookerImpl(PxU32 vertexCount, physx::PxVec4* inVertices, PxU32 triangleIndexCount, PxU32* inTriangleIndices, PxU32 constraintTypeFlags, PxVec3 verticalDirection, PxReal bendingConstraintMaxAngle) : mVertexCount(vertexCount), mVertices(inVertices), mTriangleIndexCount(triangleIndexCount), mTriangleIndices(inTriangleIndices), mConstraintTypeFlags(constraintTypeFlags), mVerticalDirection(verticalDirection), mBendingConstraintMaxAngle(bendingConstraintMaxAngle) { } virtual void release() { PX_DELETE_THIS; } /** \brief generate the constraint and triangle per vertex information. */ virtual void cookConstraints(const PxParticleClothConstraint* constraints, const PxU32 numConstraints); virtual PxU32* getTriangleIndices() { return mTriangleIndexBuffer.begin(); } virtual PxU32 getTriangleIndicesCount() { return mTriangleIndexBuffer.size(); } virtual PxParticleClothConstraint* getConstraints() { return mConstraintBuffer.begin(); } virtual PxU32 getConstraintCount() { return mConstraintBuffer.size(); } /** \brief Computes the volume of a closed mesh and the contraintScale. Expects vertices in local space - 'close' to origin. */ virtual void calculateMeshVolume(); virtual float getMeshVolume() {return mMeshVolume;} private: PxArray<PxU32> mTriangleIndexBuffer; PxArray<PxParticleClothConstraint> mConstraintBuffer; PxU32 mVertexCount; physx::PxVec4* mVertices; //we don't own this PxU32 mTriangleIndexCount; PxU32* mTriangleIndices; //we don't own this PxU32 mConstraintTypeFlags; PxVec3 mVerticalDirection; float mBendingConstraintMaxAngle; float mMeshVolume; void addTriangle(PxArray<PxU32>& trianglesPerVertex, PxU32 triangleIndex) { for(int j = 0; j < 3; j++) { PxU32 vertexIndex = mTriangleIndices[triangleIndex + j]; mTriangleIndexBuffer.pushBack(vertexIndex); trianglesPerVertex[vertexIndex]++; } } }; void PxParticleClothCookerImpl::cookConstraints(const PxParticleClothConstraint* constraints, const PxU32 numConstraints) { EdgeSet edgeSet; edgeSet.reserve(mTriangleIndexCount); PxArray<PxU32> trianglesPerVertex; trianglesPerVertex.resize(mVertexCount, 0); mTriangleIndexBuffer.clear(); mTriangleIndexBuffer.reserve(mTriangleIndexCount); mConstraintBuffer.clear(); mConstraintBuffer.reserve(mVertexCount*12); //Add all edges to Edges for(PxU32 i = 0; i<mTriangleIndexCount; i+=3) { //Get vertex indices PxU32 v0 = mTriangleIndices[i + 0]; PxU32 v1 = mTriangleIndices[i + 1]; PxU32 v2 = mTriangleIndices[i + 2]; //Get vertex points PxVec3 p0 = mVertices[v0].getXYZ(); PxVec3 p1 = mVertices[v1].getXYZ(); PxVec3 p2 = mVertices[v2].getXYZ(); //check which edge is the longest float len0 = (p0 - p1).magnitude(); float len1 = (p1 - p2).magnitude(); float len2 = (p2 - p0).magnitude(); int longest = MaxArg(len0, PxMax(len1,len2), 0, MaxArg(len1, len2, 1, 2)); //Store edges edgeSet.insert(Edge(v0, v1, i, 0xffffffff, longest == 0, false)); edgeSet.insert(Edge(v1, v2, i, 0xffffffff, longest == 1, false)); edgeSet.insert(Edge(v2, v0, i, 0xffffffff, longest == 2, false)); //Add triangle to mTriangleIndexBuffer and increment trianglesPerVertex values addTriangle(trianglesPerVertex,i); } if (constraints) { //skip constraints cooking if provided by user mConstraintBuffer.assign(constraints, constraints + numConstraints); return; } trianglesPerVertex.clear(); trianglesPerVertex.shrink(); PxArray<Edge> uniqueEdges; uniqueEdges.reserve(mTriangleIndexCount); //over allocate to avoid resizes for (EdgeSet::Iterator iter = edgeSet.getIterator(); !iter.done(); ++iter) { const Edge& e = *iter; uniqueEdges.pushBack(e); } //Maximum angle before it is a horizontal constraint const float cosAngle45 = cosf(45.0f / 360.0f * PxTwoPi); //Add all horizontal, vertical and shearing constraints PxU32 constraintCount = uniqueEdges.size(); //we are going to push back more edges, but we don't need to process them for(PxU32 i = 0; i < constraintCount; i++) { const Edge& edge = uniqueEdges[i]; PxParticleClothConstraint c; c.particleIndexA = edge.a; c.particleIndexB = edge.b; //Get vertices's PxVec3 vA = mVertices[c.particleIndexA].getXYZ(); PxVec3 vB = mVertices[c.particleIndexB].getXYZ(); //Calculate rest length c.length = (vA - vB).magnitude(); if(edge.longestA && edge.longestB && (mConstraintTypeFlags & PxParticleClothConstraint::eTYPE_DIAGONAL_CONSTRAINT)) { //Shearing constraint c.constraintType = c.eTYPE_DIAGONAL_CONSTRAINT; //add constraint mConstraintBuffer.pushBack(c); //We only have one of the quad diagonals in a triangle mesh, get the other one here const Edge alternateEdge = GetAlternateDiagonal(edge, mTriangleIndices); c.particleIndexA = alternateEdge.a; c.particleIndexB = alternateEdge.b; //Get vertices's PxVec3 vA2 = mVertices[c.particleIndexA].getXYZ(); PxVec3 vB2 = mVertices[c.particleIndexB].getXYZ(); //Calculate rest length c.length = (vA2 - vB2).magnitude(); //add constraint mConstraintBuffer.pushBack(c); if (mConstraintTypeFlags & PxParticleClothConstraint::eTYPE_DIAGONAL_BENDING_CONSTRAINT) { if (!edgeSet.contains(alternateEdge)) { edgeSet.insert(alternateEdge); uniqueEdges.pushBack(alternateEdge); //Add edge for bending constraint step } } } else { //horizontal/vertical constraint PxVec3 dir = (vA - vB) / c.length; if(mVerticalDirection.dot(dir)> cosAngle45) c.constraintType = c.eTYPE_VERTICAL_CONSTRAINT; else c.constraintType = c.eTYPE_HORIZONTAL_CONSTRAINT; if(mConstraintTypeFlags & c.constraintType) { //add constraint mConstraintBuffer.pushBack(c); } } } if(!(mConstraintTypeFlags & PxParticleClothConstraint::eTYPE_BENDING_CONSTRAINT)) return; //Get adjacency information needed for the bending constraints PxArray<PxU32> adjacencyIndices; PxArray<PxU32> adjacencies; gatherAdjacencies(adjacencyIndices, adjacencies, mVertexCount, uniqueEdges, !(mConstraintTypeFlags & PxParticleClothConstraint::eTYPE_DIAGONAL_BENDING_CONSTRAINT)); //Maximum angle we consider to be parallel for the bending constraints const float maxCosAngle = PxCos(mBendingConstraintMaxAngle); for(PxU32 i = 0; i<mVertexCount; i++) { //For each vertex, find all adjacent vertex pairs, and add bending constraints for pairs that form roughly a straight line PxVec3 center = mVertices[i].getXYZ(); for(PxU32 adjA = adjacencyIndices[i]; PxI32(adjA) < PxI32(adjacencyIndices[i+1])-1; adjA++) { PxVec3 a = mVertices[adjacencies[adjA]].getXYZ(); PxVec3 dir1 = (a-center).getNormalized(); float bestCosAngle = -1.0f; PxU32 bestAdjB = 0xffffffff; //Choose the most parallel adjB for(PxU32 adjB = adjA+1; adjB < adjacencyIndices[i + 1]; adjB++) { PxVec3 b = mVertices[adjacencies[adjB]].getXYZ(); PxVec3 dir2 = (b - center).getNormalized(); float cosAngleAbs = PxAbs(dir1.dot(dir2)); if(cosAngleAbs > bestCosAngle) { bestCosAngle = cosAngleAbs; bestAdjB = adjB; } } //Check if the lines a-center and center-b are roughly parallel if(bestCosAngle > maxCosAngle) { //Add bending constraint PxParticleClothConstraint c; c.particleIndexA = adjacencies[adjA]; c.particleIndexB = adjacencies[bestAdjB]; PX_ASSERT(c.particleIndexA != c.particleIndexB); //Get vertices's PxVec3 vA = mVertices[c.particleIndexA].getXYZ(); PxVec3 vB = mVertices[c.particleIndexB].getXYZ(); //Calculate rest length c.length = (vA - vB).magnitude(); c.constraintType = c.eTYPE_BENDING_CONSTRAINT; //add constraint mConstraintBuffer.pushBack(c); } } } } void PxParticleClothCookerImpl::calculateMeshVolume() { // the physx api takes volume*6 now. mMeshVolume = Gu::computeTriangleMeshVolume(mVertices, mTriangleIndices, mTriangleIndexCount / 3) * 6.0f; } } // namespace ExtGpu ExtGpu::PxParticleClothCooker* PxCreateParticleClothCooker(PxU32 vertexCount, PxVec4* inVertices, PxU32 triangleIndexCount, PxU32* inTriangleIndices, PxU32 constraintTypeFlags, PxVec3 verticalDirection, PxReal bendingConstraintMaxAngle) { return PX_NEW(ExtGpu::PxParticleClothCookerImpl)(vertexCount, inVertices, triangleIndexCount, inTriangleIndices, constraintTypeFlags, verticalDirection, bendingConstraintMaxAngle); } } // namespace physx
14,643
C++
30.492473
165
0.7381
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultErrorCallback.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/PxAssert.h" #include "foundation/PxString.h" #include "foundation/PxThread.h" #include "extensions/PxDefaultErrorCallback.h" #include <stdio.h> using namespace physx; PxDefaultErrorCallback::PxDefaultErrorCallback() { } PxDefaultErrorCallback::~PxDefaultErrorCallback() { } void PxDefaultErrorCallback::reportError(PxErrorCode::Enum e, const char* message, const char* file, int line) { const char* errorCode = NULL; switch (e) { case PxErrorCode::eNO_ERROR: errorCode = "no error"; break; case PxErrorCode::eINVALID_PARAMETER: errorCode = "invalid parameter"; break; case PxErrorCode::eINVALID_OPERATION: errorCode = "invalid operation"; break; case PxErrorCode::eOUT_OF_MEMORY: errorCode = "out of memory"; break; case PxErrorCode::eDEBUG_INFO: errorCode = "info"; break; case PxErrorCode::eDEBUG_WARNING: errorCode = "warning"; break; case PxErrorCode::ePERF_WARNING: errorCode = "performance warning"; break; case PxErrorCode::eABORT: errorCode = "abort"; break; case PxErrorCode::eINTERNAL_ERROR: errorCode = "internal error"; break; case PxErrorCode::eMASK_ALL: errorCode = "unknown error"; break; } PX_ASSERT(errorCode); if(errorCode) { char buffer[1024]; sprintf(buffer, "%s (%d) : %s : %s\n", file, line, errorCode, message); PxPrintString(buffer); // in debug builds halt execution for abort codes PX_ASSERT(e != PxErrorCode::eABORT); // in release builds we also want to halt execution // and make sure that the error message is flushed while (e == PxErrorCode::eABORT) { PxPrintString(buffer); PxThread::sleep(1000); } } }
3,353
C++
30.942857
110
0.739338
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRevoluteJoint.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 EXT_REVOLUTE_JOINT_H #define EXT_REVOLUTE_JOINT_H #include "extensions/PxRevoluteJoint.h" #include "ExtJoint.h" #include "foundation/PxIntrinsics.h" #include "CmUtils.h" namespace physx { struct PxRevoluteJointGeneratedValues; namespace Ext { struct RevoluteJointData : public JointData { PxReal driveVelocity; PxReal driveForceLimit; PxReal driveGearRatio; PxJointAngularLimitPair limit; PxRevoluteJointFlags jointFlags; // private: // PT: must be public for a benchmark RevoluteJointData(const PxJointAngularLimitPair& pair) : limit(pair) {} }; typedef JointT<PxRevoluteJoint, RevoluteJointData, PxRevoluteJointGeneratedValues> RevoluteJointT; class RevoluteJoint : public RevoluteJointT { public: // PX_SERIALIZATION RevoluteJoint(PxBaseFlags baseFlags) : RevoluteJointT(baseFlags) {} void resolveReferences(PxDeserializationContext& context); static RevoluteJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<RevoluteJoint>(address, context); } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION RevoluteJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); // PxRevoluteJoint virtual PxReal getAngle() const PX_OVERRIDE; virtual PxReal getVelocity() const PX_OVERRIDE; virtual void setLimit(const PxJointAngularLimitPair& limit) PX_OVERRIDE; virtual PxJointAngularLimitPair getLimit() const PX_OVERRIDE; virtual void setDriveVelocity(PxReal velocity, bool autowake = true) PX_OVERRIDE; virtual PxReal getDriveVelocity() const PX_OVERRIDE; virtual void setDriveForceLimit(PxReal forceLimit) PX_OVERRIDE; virtual PxReal getDriveForceLimit() const PX_OVERRIDE; virtual void setDriveGearRatio(PxReal gearRatio) PX_OVERRIDE; virtual PxReal getDriveGearRatio() const PX_OVERRIDE; virtual void setRevoluteJointFlags(PxRevoluteJointFlags flags) PX_OVERRIDE; virtual void setRevoluteJointFlag(PxRevoluteJointFlag::Enum flag, bool value) PX_OVERRIDE; virtual PxRevoluteJointFlags getRevoluteJointFlags() const PX_OVERRIDE; //~PxRevoluteJoint // PxConstraintConnector virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE; #if PX_SUPPORT_OMNI_PVD virtual void updateOmniPvdProperties() const PX_OVERRIDE; #endif //~PxConstraintConnector }; } // namespace Ext } // namespace physx #endif
4,240
C
42.27551
169
0.767689
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtExtensions.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/PxIO.h" #include "common/PxMetaData.h" #include "common/PxSerializer.h" #include "extensions/PxExtensionsAPI.h" #include "extensions/PxRepXSerializer.h" #include "ExtDistanceJoint.h" #include "ExtD6Joint.h" #include "ExtFixedJoint.h" #include "ExtPrismaticJoint.h" #include "ExtRevoluteJoint.h" #include "ExtSphericalJoint.h" #include "ExtSerialization.h" #include "SnRepXCoreSerializer.h" #include "SnJointRepXSerializer.h" #include "PxExtensionMetaDataObjects.h" #if PX_SUPPORT_PVD #include "ExtPvd.h" #include "PxPvdDataStream.h" #include "PxPvdClient.h" #include "PsPvd.h" #endif #if PX_SUPPORT_OMNI_PVD # include "omnipvd/PxOmniPvd.h" # include "omnipvd/OmniPvdPxExtensionsSampler.h" #endif using namespace physx; using namespace physx::pvdsdk; #if PX_SUPPORT_PVD struct JointConnectionHandler : public PvdClient { JointConnectionHandler() : mPvd(NULL),mConnected(false){} PvdDataStream* getDataStream() { return NULL; } void onPvdConnected() { PvdDataStream* stream = PvdDataStream::create(mPvd); if(stream) { mConnected = true; Ext::Pvd::sendClassDescriptions(*stream); stream->release(); } } bool isConnected() const { return mConnected; } void onPvdDisconnected() { mConnected = false; } void flush() { } PsPvd* mPvd; bool mConnected; }; static JointConnectionHandler gPvdHandler; #endif bool PxInitExtensions(PxPhysics& physics, PxPvd* pvd) { PX_ASSERT(&physics.getFoundation() == &PxGetFoundation()); PX_UNUSED(physics); PX_UNUSED(pvd); PxIncFoundationRefCount(); #if PX_SUPPORT_PVD if(pvd) { gPvdHandler.mPvd = static_cast<PsPvd*>(pvd); gPvdHandler.mPvd->addClient(&gPvdHandler); } #endif #if PX_SUPPORT_OMNI_PVD if (physics.getOmniPvd() && physics.getOmniPvd()->getWriter()) { if (OmniPvdPxExtensionsSampler::createInstance()) { OmniPvdPxExtensionsSampler::getInstance()->setOmniPvdInstance(physics.getOmniPvd()); OmniPvdPxExtensionsSampler::getInstance()->registerClasses(); } } #endif return true; } static PxArray<PxSceneQuerySystem*>* gExternalSQ = NULL; void addExternalSQ(PxSceneQuerySystem* added) { if(!gExternalSQ) gExternalSQ = new PxArray<PxSceneQuerySystem*>; gExternalSQ->pushBack(added); } void removeExternalSQ(PxSceneQuerySystem* removed) { if(gExternalSQ) { const PxU32 nb = gExternalSQ->size(); for(PxU32 i=0;i<nb;i++) { PxSceneQuerySystem* sq = (*gExternalSQ)[i]; if(sq==removed) { gExternalSQ->replaceWithLast(i); return; } } } } static void releaseExternalSQ() { if(gExternalSQ) { PxArray<PxSceneQuerySystem*>* copy = gExternalSQ; gExternalSQ = NULL; const PxU32 nb = copy->size(); for(PxU32 i=0;i<nb;i++) { PxSceneQuerySystem* sq = (*copy)[i]; sq->release(); } PX_DELETE(copy); } } void PxCloseExtensions(void) { releaseExternalSQ(); PxDecFoundationRefCount(); #if PX_SUPPORT_PVD if(gPvdHandler.mConnected) { PX_ASSERT(gPvdHandler.mPvd); gPvdHandler.mPvd->removeClient(&gPvdHandler); gPvdHandler.mPvd = NULL; } #endif #if PX_SUPPORT_OMNI_PVD if (OmniPvdPxExtensionsSampler::getInstance()) { OmniPvdPxExtensionsSampler::destroyInstance(); } #endif } void Ext::RegisterExtensionsSerializers(PxSerializationRegistry& sr) { //for repx serialization sr.registerRepXSerializer(PxConcreteType::eMATERIAL, PX_NEW_REPX_SERIALIZER( PxMaterialRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eSHAPE, PX_NEW_REPX_SERIALIZER( PxShapeRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH33, PX_NEW_REPX_SERIALIZER( PxBVH33TriangleMeshRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH34, PX_NEW_REPX_SERIALIZER( PxBVH34TriangleMeshRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eHEIGHTFIELD, PX_NEW_REPX_SERIALIZER( PxHeightFieldRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eCONVEX_MESH, PX_NEW_REPX_SERIALIZER( PxConvexMeshRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eRIGID_STATIC, PX_NEW_REPX_SERIALIZER( PxRigidStaticRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eRIGID_DYNAMIC, PX_NEW_REPX_SERIALIZER( PxRigidDynamicRepXSerializer )); sr.registerRepXSerializer(PxConcreteType::eARTICULATION_REDUCED_COORDINATE, PX_NEW_REPX_SERIALIZER( PxArticulationReducedCoordinateRepXSerializer)); sr.registerRepXSerializer(PxConcreteType::eAGGREGATE, PX_NEW_REPX_SERIALIZER( PxAggregateRepXSerializer )); sr.registerRepXSerializer(PxJointConcreteType::eFIXED, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxFixedJoint> )); sr.registerRepXSerializer(PxJointConcreteType::eDISTANCE, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxDistanceJoint> )); sr.registerRepXSerializer(PxJointConcreteType::eD6, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxD6Joint> )); sr.registerRepXSerializer(PxJointConcreteType::ePRISMATIC, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxPrismaticJoint> )); sr.registerRepXSerializer(PxJointConcreteType::eREVOLUTE, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxRevoluteJoint> )); sr.registerRepXSerializer(PxJointConcreteType::eSPHERICAL, PX_NEW_REPX_SERIALIZER( PxJointRepXSerializer<PxSphericalJoint> )); //for binary serialization sr.registerSerializer(PxJointConcreteType::eFIXED, PX_NEW_SERIALIZER_ADAPTER( FixedJoint )); sr.registerSerializer(PxJointConcreteType::eDISTANCE, PX_NEW_SERIALIZER_ADAPTER( DistanceJoint )); sr.registerSerializer(PxJointConcreteType::eD6, PX_NEW_SERIALIZER_ADAPTER( D6Joint) ); sr.registerSerializer(PxJointConcreteType::ePRISMATIC, PX_NEW_SERIALIZER_ADAPTER( PrismaticJoint )); sr.registerSerializer(PxJointConcreteType::eREVOLUTE, PX_NEW_SERIALIZER_ADAPTER( RevoluteJoint )); sr.registerSerializer(PxJointConcreteType::eSPHERICAL, PX_NEW_SERIALIZER_ADAPTER( SphericalJoint )); } void Ext::UnregisterExtensionsSerializers(PxSerializationRegistry& sr) { PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eFIXED)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eDISTANCE)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eD6 )); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::ePRISMATIC)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eREVOLUTE)); PX_DELETE_SERIALIZER_ADAPTER(sr.unregisterSerializer(PxJointConcreteType::eSPHERICAL)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eMATERIAL)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eSHAPE)); // PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eTRIANGLE_MESH)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH33)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eTRIANGLE_MESH_BVH34)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eHEIGHTFIELD)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eCONVEX_MESH)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eRIGID_STATIC)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eRIGID_DYNAMIC)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eARTICULATION_REDUCED_COORDINATE)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxConcreteType::eAGGREGATE)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eFIXED)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eDISTANCE)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eD6)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::ePRISMATIC)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eREVOLUTE)); PX_DELETE_REPX_SERIALIZER(sr.unregisterRepXSerializer(PxJointConcreteType::eSPHERICAL)); }
9,731
C++
37.015625
149
0.781215
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSoftBodyExt.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 "extensions/PxSoftBodyExt.h" #include "extensions/PxTetMakerExt.h" #include "GuTetrahedronMesh.h" #include "cooking/PxCooking.h" #include "PxPhysics.h" #include "extensions/PxRemeshingExt.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" using namespace physx; using namespace Cm; //Computes the volume of the simulation mesh defined as the sum of the volumes of all tetrahedra static PxReal computeSimulationMeshVolume(PxSoftBody& sb, PxVec4* simPositions) { const PxU32 numTetsGM = sb.getSimulationMesh()->getNbTetrahedrons(); const PxU32* tetPtr32 = reinterpret_cast<const PxU32*>(sb.getSimulationMesh()->getTetrahedrons()); const PxU16* tetPtr16 = reinterpret_cast<const PxU16*>(sb.getSimulationMesh()->getTetrahedrons()); const bool sixteenBit = sb.getSimulationMesh()->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; PxReal volume = 0; for (PxU32 i = 0; i < numTetsGM; ++i) { PxVec4& x0 = simPositions[sixteenBit ? tetPtr16[4 * i] : tetPtr32[4 * i]]; PxVec4& x1 = simPositions[sixteenBit ? tetPtr16[4 * i + 1] : tetPtr32[4 * i + 1]]; PxVec4& x2 = simPositions[sixteenBit ? tetPtr16[4 * i + 2] : tetPtr32[4 * i + 2]]; PxVec4& x3 = simPositions[sixteenBit ? tetPtr16[4 * i + 3] : tetPtr32[4 * i + 3]]; const PxVec3 u1 = x1.getXYZ() - x0.getXYZ(); const PxVec3 u2 = x2.getXYZ() - x0.getXYZ(); const PxVec3 u3 = x3.getXYZ() - x0.getXYZ(); PxMat33 Q = PxMat33(u1, u2, u3); const PxReal det = Q.getDeterminant(); volume += det; } volume /= 6.0f; return volume; } //Recomputes the volume associated with a vertex. Every tetrahedron distributes a quarter of its volume to //each vertex it is connected to. Finally the volume stored for every vertex is inverted. static void updateNodeInverseVolumes(PxSoftBody& sb, PxVec4* simPositions) { const PxU32 numVertsGM = sb.getSimulationMesh()->getNbVertices(); const PxU32 numTetsGM = sb.getSimulationMesh()->getNbTetrahedrons(); const PxU32* tetPtr32 = reinterpret_cast<const PxU32*>(sb.getSimulationMesh()->getTetrahedrons()); const PxU16* tetPtr16 = reinterpret_cast<const PxU16*>(sb.getSimulationMesh()->getTetrahedrons()); const bool sixteenBit = sb.getSimulationMesh()->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; for (PxU32 i = 0; i < numVertsGM; ++i) simPositions[i].w = 0.0f; for (PxU32 i = 0; i < numTetsGM; ++i) { PxVec4& x0 = simPositions[sixteenBit ? tetPtr16[4 * i] : tetPtr32[4 * i]]; PxVec4& x1 = simPositions[sixteenBit ? tetPtr16[4 * i + 1] : tetPtr32[4 * i + 1]]; PxVec4& x2 = simPositions[sixteenBit ? tetPtr16[4 * i + 2] : tetPtr32[4 * i + 2]]; PxVec4& x3 = simPositions[sixteenBit ? tetPtr16[4 * i + 3] : tetPtr32[4 * i + 3]]; const PxVec3 u1 = x1.getXYZ() - x0.getXYZ(); const PxVec3 u2 = x2.getXYZ() - x0.getXYZ(); const PxVec3 u3 = x3.getXYZ() - x0.getXYZ(); PxMat33 Q = PxMat33(u1, u2, u3); //det should be positive const PxReal det = Q.getDeterminant(); if (det <= 1.e-9f) PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "updateNodeInverseVolumes(): tetrahedron is degenerate or inverted"); //Distribute one quarter of the volume to each vertex the tetrahedron is connected to const PxReal volume = det / 6.0f; x0.w += 0.25f * volume; x1.w += 0.25f * volume; x2.w += 0.25f * volume; x3.w += 0.25f * volume; } //Invert the volumes stored per vertex and copy it to the velocity buffer for (PxU32 i = 0; i < numVertsGM; ++i) { if (simPositions[i].w > 0) { simPositions[i].w = 1.0f / simPositions[i].w; } } } void PxSoftBodyExt::updateMass(PxSoftBody& sb, const PxReal density, const PxReal maxInvMassRatio, PxVec4* simPositionsPinned) { //Inverse volumes are recomputed to ensure that multiple subsequent calls of this method lead to correct results updateNodeInverseVolumes(sb, simPositionsPinned); const PxU32 numVertsGM = sb.getSimulationMesh()->getNbVertices(); PxReal minInvMass = PX_MAX_F32, maxInvMass = 0.f; for (PxU32 i = 0; i < numVertsGM; ++i) { const PxVec4& vert = simPositionsPinned[i]; PxReal invMass = vert.w; invMass = invMass / (density); minInvMass = invMass > 0.f ? PxMin(invMass, minInvMass) : minInvMass; maxInvMass = PxMax(invMass, maxInvMass); simPositionsPinned[i] = PxVec4(vert.x, vert.y, vert.z, invMass); } if (minInvMass != PX_MAX_F32) { const PxReal ratio = maxInvMass / minInvMass; if (ratio > maxInvMassRatio) { //Clamp the upper limit... maxInvMass = minInvMass * maxInvMassRatio; for (PxU32 i = 0; i < numVertsGM; ++i) { PxVec4& posInvMass = simPositionsPinned[i]; posInvMass.w = PxMin(posInvMass.w, maxInvMass); } } } } void PxSoftBodyExt::setMass(PxSoftBody& sb, const PxReal mass, const PxReal maxInvMassRatio, PxVec4* simPositionsPinned) { //Compute the density such that density times volume is equal to the desired mass updateMass(sb, mass / computeSimulationMeshVolume(sb, simPositionsPinned), maxInvMassRatio, simPositionsPinned); } void PxSoftBodyExt::transform(PxSoftBody& sb, const PxTransform& transform, const PxReal scale, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned) { const PxU32 numVertsGM = sb.getSimulationMesh()->getNbVertices(); const PxU32 numVerts = sb.getCollisionMesh()->getNbVertices(); for (PxU32 i = 0; i < numVertsGM; ++i) { const PxVec4 tpInvMass = simPositionsPinned[i]; const PxReal invMass = tpInvMass.w; PxVec3 vert = PxVec3(tpInvMass.x * scale, tpInvMass.y * scale, tpInvMass.z * scale); //Transform the vertex position and keep the inverse mass vert = transform.transform(vert); simPositionsPinned[i] = PxVec4(vert.x, vert.y, vert.z, invMass); PxVec4 vel = simVelocitiesPinned[i]; PxVec3 v = PxVec3(vel.x * scale, vel.y * scale, vel.z * scale); //Velocities are translation invariant, therefore only the direction needs to get adjusted. //The inverse mass is stored as well to optimize memory access on the GPU v = transform.rotate(v); simVelocitiesPinned[i] = PxVec4(v.x, v.y, v.z, invMass); } for (PxU32 i = 0; i < numVerts; ++i) { restPositionsPinned[i] = PxVec4(restPositionsPinned[i].x*scale, restPositionsPinned[i].y*scale, restPositionsPinned[i].z*scale, 1.f); const PxVec4 tpInvMass = collPositionsPinned[i]; PxVec3 vert = PxVec3(tpInvMass.x * scale, tpInvMass.y * scale, tpInvMass.z * scale); vert = transform.transform(vert); collPositionsPinned[i] = PxVec4(vert.x, vert.y, vert.z, tpInvMass.w); } PxMat33* tetraRestPosesGM = static_cast<Gu::SoftBodyAuxData*>(sb.getSoftBodyAuxData())->getGridModelRestPosesFast(); // reinterpret_cast<PxMat33*>(simMeshData->softBodyAuxData.getGridModelRestPosesFast()); const PxU32 nbTetraGM = sb.getSimulationMesh()->getNbTetrahedrons(); const PxReal invScale = 1.0f / scale; for (PxU32 i = 0; i < nbTetraGM; ++i) { PxMat33& m = tetraRestPosesGM[i]; //Scale the rest pose m.column0 = m.column0 * invScale; m.column1 = m.column1 * invScale; m.column2 = m.column2 * invScale; //The rest pose is translation invariant, it only needs be rotated PxVec3 row0 = transform.rotateInv(PxVec3(m.column0.x, m.column1.x, m.column2.x)); PxVec3 row1 = transform.rotateInv(PxVec3(m.column0.y, m.column1.y, m.column2.y)); PxVec3 row2 = transform.rotateInv(PxVec3(m.column0.z, m.column1.z, m.column2.z)); m.column0 = PxVec3(row0.x, row1.x, row2.x); m.column1 = PxVec3(row0.y, row1.y, row2.y); m.column2 = PxVec3(row0.z, row1.z, row2.z); } PxMat33* tetraRestPoses = static_cast<Gu::SoftBodyAuxData*>(sb.getSoftBodyAuxData())->getRestPosesFast(); // reinterpret_cast<PxMat33*>(simMeshData->softBodyAuxData.getGridModelRestPosesFast()); const PxU32 nbTetra = sb.getCollisionMesh()->getNbTetrahedrons(); for (PxU32 i = 0; i < nbTetra; ++i) { PxMat33& m = tetraRestPoses[i]; //Scale the rest pose m.column0 = m.column0 * invScale; m.column1 = m.column1 * invScale; m.column2 = m.column2 * invScale; //The rest pose is translation invariant, it only needs be rotated PxVec3 row0 = transform.rotateInv(PxVec3(m.column0.x, m.column1.x, m.column2.x)); PxVec3 row1 = transform.rotateInv(PxVec3(m.column0.y, m.column1.y, m.column2.y)); PxVec3 row2 = transform.rotateInv(PxVec3(m.column0.z, m.column1.z, m.column2.z)); m.column0 = PxVec3(row0.x, row1.x, row2.x); m.column1 = PxVec3(row0.y, row1.y, row2.y); m.column2 = PxVec3(row0.z, row1.z, row2.z); } } void PxSoftBodyExt::updateEmbeddedCollisionMesh(PxSoftBody& sb, PxVec4* simPositionsPinned, PxVec4* collPositionsPinned) { Gu::SoftBodyAuxData* softBodyAuxData = static_cast<Gu::SoftBodyAuxData*>(sb.getSoftBodyAuxData()); const PxU32* remapTable = softBodyAuxData->mVertsRemapInGridModel; PxReal* barycentricCoordinates = softBodyAuxData->mVertsBarycentricInGridModel; PxTetrahedronMesh* simMesh = sb.getSimulationMesh(); const void* tets = simMesh->getTetrahedrons(); const PxU32* tets32 = static_cast<const PxU32*>(tets); const PxU16* tets16 = static_cast<const PxU16*>(tets); bool sixteenBit = simMesh->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES; const PxU32 numVerts = sb.getCollisionMesh()->getNbVertices(); for (PxU32 i = 0; i < numVerts; ++i) { //The tetrahedra are ordered differently on the GPU, therefore the index must be taken from the remap table const PxU32 tetrahedronIdx = remapTable[i]; const PxVec4 p0 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx] : tets32[4 * tetrahedronIdx]]; const PxVec4 p1 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx + 1] : tets32[4 * tetrahedronIdx + 1]]; const PxVec4 p2 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx + 2] : tets32[4 * tetrahedronIdx + 2]]; const PxVec4 p3 = simPositionsPinned[sixteenBit ? tets16[4 * tetrahedronIdx + 3] : tets32[4 * tetrahedronIdx + 3]]; const PxReal* barycentric = &barycentricCoordinates[4*i]; //Compute the embedded position as a weigted sum of vertices from the simulation mesh //This ensures that all tranformations and scale changes applied to the simulation mesh get transferred //to the collision mesh collPositionsPinned[i] = p0 * barycentric[0] + p1 * barycentric[1] + p2 * barycentric[2] + p3 * barycentric[3]; collPositionsPinned[i].w = 1.0f; } } void PxSoftBodyExt::commit(PxSoftBody& sb, PxSoftBodyDataFlags flags, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned, CUstream stream) { copyToDevice(sb, flags, simPositionsPinned, simVelocitiesPinned, collPositionsPinned, restPositionsPinned, stream); } void PxSoftBodyExt::copyToDevice(PxSoftBody& sb, PxSoftBodyDataFlags flags, PxVec4* simPositionsPinned, PxVec4* simVelocitiesPinned, PxVec4* collPositionsPinned, PxVec4* restPositionsPinned, CUstream stream) { //Updating the collision mesh's vertices ensures that simulation mesh and collision mesh are //represented in the same coordinate system and the same scale updateEmbeddedCollisionMesh(sb, simPositionsPinned, collPositionsPinned); #if PX_SUPPORT_GPU_PHYSX PxScopedCudaLock _lock(*sb.getCudaContextManager()); PxCudaContext* ctx = sb.getCudaContextManager()->getCudaContext(); if (flags & PxSoftBodyDataFlag::ePOSITION_INVMASS && collPositionsPinned) ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getPositionInvMassBufferD()), collPositionsPinned, sb.getCollisionMesh()->getNbVertices() * sizeof(PxVec4), stream); if (flags & PxSoftBodyDataFlag::eREST_POSITION_INVMASS && restPositionsPinned) ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getRestPositionBufferD()), restPositionsPinned, sb.getCollisionMesh()->getNbVertices() * sizeof(PxVec4), stream); if (flags & PxSoftBodyDataFlag::eSIM_POSITION_INVMASS && simPositionsPinned) ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getSimPositionInvMassBufferD()), simPositionsPinned, sb.getSimulationMesh()->getNbVertices() * sizeof(PxVec4), stream); if (flags & PxSoftBodyDataFlag::eSIM_VELOCITY && simVelocitiesPinned) ctx->memcpyHtoDAsync(reinterpret_cast<CUdeviceptr>(sb.getSimVelocityBufferD()), simVelocitiesPinned, sb.getSimulationMesh()->getNbVertices() * sizeof(PxVec4), stream); // we need to synchronize if the stream is the default argument. if (stream == 0) { ctx->streamSynchronize(stream); } #else PX_UNUSED(restPositionsPinned); PX_UNUSED(simVelocitiesPinned); PX_UNUSED(stream); #endif sb.markDirty(flags); } PxSoftBodyMesh* PxSoftBodyExt::createSoftBodyMesh(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, PxU32 numVoxelsAlongLongestAABBAxis, PxInsertionCallback& insertionCallback, const bool validate) { //Compute collision mesh physx::PxArray<physx::PxVec3> collisionMeshVertices; physx::PxArray<physx::PxU32> collisionMeshIndices; if (!PxTetMaker::createConformingTetrahedronMesh(surfaceMesh, collisionMeshVertices, collisionMeshIndices, validate)) return NULL; PxTetrahedronMeshDesc meshDesc(collisionMeshVertices, collisionMeshIndices); //Compute simulation mesh physx::PxArray<physx::PxI32> vertexToTet; vertexToTet.resize(meshDesc.points.count); physx::PxArray<physx::PxVec3> simulationMeshVertices; physx::PxArray<physx::PxU32> simulationMeshIndices; PxTetMaker::createVoxelTetrahedronMesh(meshDesc, numVoxelsAlongLongestAABBAxis, simulationMeshVertices, simulationMeshIndices, vertexToTet.begin()); PxTetrahedronMeshDesc simMeshDesc(simulationMeshVertices, simulationMeshIndices); PxSoftBodySimulationDataDesc simDesc(vertexToTet); physx::PxSoftBodyMesh* softBodyMesh = PxCreateSoftBodyMesh(params, simMeshDesc, meshDesc, simDesc, insertionCallback); return softBodyMesh; } PxSoftBodyMesh* PxSoftBodyExt::createSoftBodyMeshNoVoxels(const PxCookingParams& params, const PxSimpleTriangleMesh& surfaceMesh, PxInsertionCallback& insertionCallback, PxReal maxWeightRatioInTet, const bool validate) { PxCookingParams p = params; p.maxWeightRatioInTet = maxWeightRatioInTet; physx::PxArray<physx::PxVec3> collisionMeshVertices; physx::PxArray<physx::PxU32> collisionMeshIndices; if (!PxTetMaker::createConformingTetrahedronMesh(surfaceMesh, collisionMeshVertices, collisionMeshIndices, validate)) return NULL; PxTetrahedronMeshDesc meshDesc(collisionMeshVertices, collisionMeshIndices); PxSoftBodySimulationDataDesc simDesc; physx::PxSoftBodyMesh* softBodyMesh = PxCreateSoftBodyMesh(p, meshDesc, meshDesc, simDesc, insertionCallback); return softBodyMesh; } PxSoftBody* PxSoftBodyExt::createSoftBodyFromMesh(PxSoftBodyMesh* softBodyMesh, const PxTransform& transform, const PxFEMSoftBodyMaterial& material, PxCudaContextManager& cudaContextManager, PxReal density, PxU32 solverIterationCount, const PxFEMParameters& femParams, PxReal scale) { PxSoftBody* softBody = PxGetPhysics().createSoftBody(cudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxFEMSoftBodyMaterial* materialPointer = const_cast<PxFEMSoftBodyMaterial*>(&material); PxShape* shape = PxGetPhysics().createShape(geometry, &materialPointer, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, &cudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); softBody->setSolverIterationCounts(solverIterationCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); #if PX_SUPPORT_GPU_PHYSX PxCudaContextManager* mgr = &cudaContextManager; PX_PINNED_HOST_FREE(mgr, simPositionInvMassPinned); PX_PINNED_HOST_FREE(mgr, simVelocityPinned); PX_PINNED_HOST_FREE(mgr, collPositionInvMassPinned); PX_PINNED_HOST_FREE(mgr, restPositionPinned) #endif } return softBody; } PxSoftBody* PxSoftBodyExt::createSoftBodyBox(const PxTransform& transform, const PxVec3& boxDimensions, const PxFEMSoftBodyMaterial& material, PxCudaContextManager& cudaContextManager, PxReal maxEdgeLength, PxReal density, PxU32 solverIterationCount, const PxFEMParameters& femParams, PxU32 numVoxelsAlongLongestAABBAxis, PxReal scale) { PxArray<PxVec3> triVerts; triVerts.reserve(8); triVerts.pushBack(PxVec3(0.5f, -0.5f, -0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(0.5f, -0.5f, 0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(-0.5f, -0.5f, 0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(-0.5f, -0.5f, -0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(0.5f, 0.5f, -0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(0.5f, 0.5f, 0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(-0.5f, 0.5f, 0.5f).multiply(boxDimensions)); triVerts.pushBack(PxVec3(-0.5f, 0.5f, -0.5f).multiply(boxDimensions)); PxArray<PxU32> triIndices; triIndices.reserve(12 * 3); triIndices.pushBack(1); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(6); triIndices.pushBack(5); triIndices.pushBack(4); triIndices.pushBack(5); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(6); triIndices.pushBack(2); triIndices.pushBack(2); triIndices.pushBack(6); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(1); triIndices.pushBack(3); triIndices.pushBack(4); triIndices.pushBack(7); triIndices.pushBack(5); triIndices.pushBack(0); triIndices.pushBack(4); triIndices.pushBack(1); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(2); triIndices.pushBack(7); triIndices.pushBack(4); triIndices.pushBack(0); triIndices.pushBack(7); if (maxEdgeLength > 0.0f) PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 3); PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); PxTolerancesScale tolerancesScale; PxCookingParams params(tolerancesScale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; params.midphaseDesc = PxMeshMidPhase::eBVH34; PxSoftBodyMesh* softBodyMesh = createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, PxGetPhysics().getPhysicsInsertionCallback()); return createSoftBodyFromMesh(softBodyMesh, transform, material, cudaContextManager, density, solverIterationCount, femParams, scale); } void PxSoftBodyExt::allocateAndInitializeHostMirror(PxSoftBody& softBody, PxCudaContextManager* cudaContextManager, PxVec4*& simPositionInvMassPinned, PxVec4*& simVelocityPinned, PxVec4*& collPositionInvMassPinned, PxVec4*& restPositionPinned) { PX_ASSERT(softBody.getCollisionMesh() != NULL); PX_ASSERT(softBody.getSimulationMesh() != NULL); PxU32 nbCollVerts = softBody.getCollisionMesh()->getNbVertices(); PxU32 nbSimVerts = softBody.getSimulationMesh()->getNbVertices(); #if PX_SUPPORT_GPU_PHYSX simPositionInvMassPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbSimVerts); simVelocityPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbSimVerts); collPositionInvMassPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbCollVerts); restPositionPinned = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, nbCollVerts); #else PX_UNUSED(cudaContextManager); #endif // write positionInvMass into CPU part. const PxVec3* positions = softBody.getCollisionMesh()->getVertices(); for (PxU32 i = 0; i < nbCollVerts; ++i) { PxVec3 vert = positions[i]; collPositionInvMassPinned[i] = PxVec4(vert, 1.f); restPositionPinned[i] = PxVec4(vert, 1.f); } // write sim mesh part. PxSoftBodyAuxData* s = softBody.getSoftBodyAuxData(); PxReal* invMassGM = s->getGridModelInvMass(); const PxVec3* simPositions = softBody.getSimulationMesh()->getVertices(); for (PxU32 i = 0; i < nbSimVerts; ++i) { PxReal invMass = invMassGM ? invMassGM[i] : 1.f; simPositionInvMassPinned[i] = PxVec4(simPositions[i], invMass); simVelocityPinned[i] = PxVec4(0.f, 0.f, 0.f, invMass); } } struct InternalSoftBodyState { PxVec4* mVertices; PxArray<PxReal> mInvMasses; const PxU32* mTetrahedra; PxArray<PxMat33> mInvRestPose; PxArray<PxVec3> mPrevPos; InternalSoftBodyState(const PxVec4* verticesOriginal, PxVec4* verticesDeformed, PxU32 nbVertices, const PxU32* tetrahedra, PxU32 nbTetraheda, const bool* vertexIsFixed) : mVertices(verticesDeformed), mTetrahedra(tetrahedra) { PxReal density = 1.0f; mInvMasses.resize(nbVertices, 0.0f); mInvRestPose.resize(nbTetraheda, PxMat33(PxZero)); for (PxU32 i = 0; i < nbTetraheda; i++) { const PxU32* t = &mTetrahedra[4 * i]; const PxVec3 a = verticesOriginal[t[0]].getXYZ(); PxMat33 ir(verticesOriginal[t[1]].getXYZ() - a, verticesOriginal[t[2]].getXYZ() - a, verticesOriginal[t[3]].getXYZ() - a); PxReal volume = ir.getDeterminant() / 6.0f; if (volume > 1e-8f) mInvRestPose[i] = ir.getInverse(); PxReal m = 0.25f * volume * density; mInvMasses[t[0]] += m; mInvMasses[t[1]] += m; mInvMasses[t[2]] += m; mInvMasses[t[3]] += m; } for (PxU32 i = 0; i < nbVertices; i++) { bool fixed = vertexIsFixed ? vertexIsFixed[i] : verticesOriginal[i].w == 0.0f; if (mInvMasses[i] != 0.0f && !fixed) mInvMasses[i] = 1.0f / mInvMasses[i]; else mInvMasses[i] = 0.0f; } mPrevPos.resize(nbVertices); for (PxU32 i = 0; i < mPrevPos.size(); ++i) mPrevPos[i] = mVertices[i].getXYZ(); } void applyDelta() { for (PxU32 i = 0; i < mPrevPos.size(); ++i) { PxVec3 delta = mVertices[i].getXYZ() - mPrevPos[i]; mPrevPos[i] = mVertices[i].getXYZ(); mVertices[i] += PxVec4(0.99f * delta, 0.0f); } } PX_FORCE_INLINE void applyToElem(PxU32 elemNr, PxReal C, PxReal compliance, const PxVec3& g1, const PxVec3& g2, const PxVec3& g3, const PxVec4& invMasses) { if (C == 0.0f) return; const PxVec3 g0 = -g1 - g2 - g3; const PxU32* t = &mTetrahedra[4 * elemNr]; const PxReal w = g0.magnitudeSquared() * invMasses.x + g1.magnitudeSquared() * invMasses.y + g2.magnitudeSquared() * invMasses.z + g3.magnitudeSquared() * invMasses.w; if (w == 0.0f) return; const PxReal alpha = compliance; const PxReal dlambda = -C / (w + alpha); if (invMasses.x != 0.0f) mVertices[t[0]] += PxVec4(g0 * dlambda * invMasses.x, 0.0f); if (invMasses.y != 0.0f) mVertices[t[1]] += PxVec4(g1 * dlambda * invMasses.y, 0.0f); if (invMasses.z != 0.0f) mVertices[t[2]] += PxVec4(g2 * dlambda * invMasses.z, 0.0f); if (invMasses.w != 0.0f) mVertices[t[3]] += PxVec4(g3 * dlambda * invMasses.w, 0.0f); } void solveElem(PxU32 elemNr) { const PxMat33& ir = mInvRestPose[elemNr]; if (ir == PxMat33(PxZero)) return; const PxU32* tet = &mTetrahedra[4 * elemNr]; PxVec4 invMasses(mInvMasses[tet[0]], mInvMasses[tet[1]], mInvMasses[tet[2]], mInvMasses[tet[3]]); PxMat33 P; P.column0 = mVertices[tet[1]].getXYZ() - mVertices[tet[0]].getXYZ(); P.column1 = mVertices[tet[2]].getXYZ() - mVertices[tet[0]].getXYZ(); P.column2 = mVertices[tet[3]].getXYZ() - mVertices[tet[0]].getXYZ(); PxMat33 F = P * ir; PxVec3 g1 = F.column0 * 2.0f * ir.column0.x + F.column1 * 2.0f * ir.column1.x + F.column2 * 2.0f * ir.column2.x; PxVec3 g2 = F.column0 * 2.0f * ir.column0.y + F.column1 * 2.0f * ir.column1.y + F.column2 * 2.0f * ir.column2.y; PxVec3 g3 = F.column0 * 2.0f * ir.column0.z + F.column1 * 2.0f * ir.column1.z + F.column2 * 2.0f * ir.column2.z; PxReal C = F.column0.magnitudeSquared() + F.column1.magnitudeSquared() + F.column2.magnitudeSquared() - 3.0f; applyToElem(elemNr, C, 0.0f, g1, g2, g3, invMasses); P.column0 = mVertices[tet[1]].getXYZ() - mVertices[tet[0]].getXYZ(); P.column1 = mVertices[tet[2]].getXYZ() - mVertices[tet[0]].getXYZ(); P.column2 = mVertices[tet[3]].getXYZ() - mVertices[tet[0]].getXYZ(); F = P * ir; PxMat33& dF = P; //Re-use memory, possible since P is not used anymore afterwards dF.column0 = F.column1.cross(F.column2); dF.column1 = F.column2.cross(F.column0); dF.column2 = F.column0.cross(F.column1); g1 = dF.column0 * ir.column0.x + dF.column1 * ir.column1.x + dF.column2 * ir.column2.x; g2 = dF.column0 * ir.column0.y + dF.column1 * ir.column1.y + dF.column2 * ir.column2.y; g3 = dF.column0 * ir.column0.z + dF.column1 * ir.column1.z + dF.column2 * ir.column2.z; C = F.getDeterminant() - 1.0f; applyToElem(elemNr, C, 0.0f, g1, g2, g3, invMasses); } }; void PxSoftBodyExt::relaxSoftBodyMesh(const PxVec4* verticesOriginal, PxVec4* verticesDeformed, PxU32 nbVertices, const PxU32* tetrahedra, PxU32 nbTetraheda, const bool* vertexIsFixed, PxU32 numIterations) { InternalSoftBodyState state(verticesOriginal, verticesDeformed, nbVertices, tetrahedra, nbTetraheda, vertexIsFixed); for (PxU32 iter = 0; iter < numIterations; ++iter) { state.applyDelta(); for (PxU32 i = 0; i < nbTetraheda; ++i) state.solveElem(i); } return; }
27,653
C++
42.895238
243
0.74397
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultSimulationFilterShader.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 "extensions/PxDefaultSimulationFilterShader.h" #include "PxRigidActor.h" #include "PxShape.h" #include "PxSoftBody.h" #include "foundation/PxIntrinsics.h" #include "foundation/PxAllocator.h" #include "foundation/PxInlineArray.h" using namespace physx; namespace { #define GROUP_SIZE 32 struct PxCollisionBitMap { PX_INLINE PxCollisionBitMap() : enable(true) {} bool operator()() const { return enable; } bool& operator= (const bool &v) { enable = v; return enable; } private: bool enable; }; PxCollisionBitMap gCollisionTable[GROUP_SIZE][GROUP_SIZE]; PxFilterOp::Enum gFilterOps[3] = { PxFilterOp::PX_FILTEROP_AND, PxFilterOp::PX_FILTEROP_AND, PxFilterOp::PX_FILTEROP_AND }; PxGroupsMask gFilterConstants[2]; bool gFilterBool = false; static void gAND(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(mask0.bits0 & mask1.bits0); results.bits1 = PxU16(mask0.bits1 & mask1.bits1); results.bits2 = PxU16(mask0.bits2 & mask1.bits2); results.bits3 = PxU16(mask0.bits3 & mask1.bits3); } static void gOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(mask0.bits0 | mask1.bits0); results.bits1 = PxU16(mask0.bits1 | mask1.bits1); results.bits2 = PxU16(mask0.bits2 | mask1.bits2); results.bits3 = PxU16(mask0.bits3 | mask1.bits3); } static void gXOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(mask0.bits0 ^ mask1.bits0); results.bits1 = PxU16(mask0.bits1 ^ mask1.bits1); results.bits2 = PxU16(mask0.bits2 ^ mask1.bits2); results.bits3 = PxU16(mask0.bits3 ^ mask1.bits3); } static void gNAND(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(~(mask0.bits0 & mask1.bits0)); results.bits1 = PxU16(~(mask0.bits1 & mask1.bits1)); results.bits2 = PxU16(~(mask0.bits2 & mask1.bits2)); results.bits3 = PxU16(~(mask0.bits3 & mask1.bits3)); } static void gNOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(~(mask0.bits0 | mask1.bits0)); results.bits1 = PxU16(~(mask0.bits1 | mask1.bits1)); results.bits2 = PxU16(~(mask0.bits2 | mask1.bits2)); results.bits3 = PxU16(~(mask0.bits3 | mask1.bits3)); } static void gNXOR(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(~(mask0.bits0 ^ mask1.bits0)); results.bits1 = PxU16(~(mask0.bits1 ^ mask1.bits1)); results.bits2 = PxU16(~(mask0.bits2 ^ mask1.bits2)); results.bits3 = PxU16(~(mask0.bits3 ^ mask1.bits3)); } static void gSWAP_AND(PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1) { results.bits0 = PxU16(mask0.bits0 & mask1.bits2); results.bits1 = PxU16(mask0.bits1 & mask1.bits3); results.bits2 = PxU16(mask0.bits2 & mask1.bits0); results.bits3 = PxU16(mask0.bits3 & mask1.bits1); } typedef void (*FilterFunction) (PxGroupsMask& results, const PxGroupsMask& mask0, const PxGroupsMask& mask1); FilterFunction const gTable[] = { gAND, gOR, gXOR, gNAND, gNOR, gNXOR, gSWAP_AND }; static PxFilterData convert(const PxGroupsMask& mask) { PxFilterData fd; fd.word2 = PxU32(mask.bits0 | (mask.bits1 << 16)); fd.word3 = PxU32(mask.bits2 | (mask.bits3 << 16)); return fd; } static PxGroupsMask convert(const PxFilterData& fd) { PxGroupsMask mask; mask.bits0 = PxU16((fd.word2 & 0xffff)); mask.bits1 = PxU16((fd.word2 >> 16)); mask.bits2 = PxU16((fd.word3 & 0xffff)); mask.bits3 = PxU16((fd.word3 >> 16)); return mask; } static bool getFilterData(const PxActor& actor, PxFilterData& fd) { PxActorType::Enum aType = actor.getType(); switch (aType) { case PxActorType::eRIGID_DYNAMIC: case PxActorType::eRIGID_STATIC: case PxActorType::eARTICULATION_LINK: { const PxRigidActor& rActor = static_cast<const PxRigidActor&>(actor); PX_CHECK_AND_RETURN_VAL(rActor.getNbShapes() >= 1,"There must be a shape in actor", false); PxShape* shape = NULL; rActor.getShapes(&shape, 1); fd = shape->getSimulationFilterData(); } break; default: break; } return true; } PX_FORCE_INLINE static void adjustFilterData(bool groupsMask, const PxFilterData& src, PxFilterData& dst) { if (groupsMask) { dst.word2 = src.word2; dst.word3 = src.word3; } else dst.word0 = src.word0; } template<bool TGroupsMask> static void setFilterData(PxActor& actor, const PxFilterData& fd) { PxActorType::Enum aType = actor.getType(); switch (aType) { case PxActorType::eRIGID_DYNAMIC: case PxActorType::eRIGID_STATIC: case PxActorType::eARTICULATION_LINK: { const PxRigidActor& rActor = static_cast<const PxRigidActor&>(actor); PxShape* shape; for(PxU32 i=0; i < rActor.getNbShapes(); i++) { rActor.getShapes(&shape, 1, i); // retrieve current group mask PxFilterData resultFd = shape->getSimulationFilterData(); adjustFilterData(TGroupsMask, fd, resultFd); // set new filter data shape->setSimulationFilterData(resultFd); } } break; case PxActorType::eSOFTBODY: { PxSoftBody& sActor = static_cast<PxSoftBody&>(actor); PxShape* shape = sActor.getShape(); // retrieve current group mask PxFilterData resultFd = shape->getSimulationFilterData(); adjustFilterData(TGroupsMask, fd, resultFd); // set new filter data shape->setSimulationFilterData(resultFd); } break; break; default: break; } } } PxFilterFlags physx::PxDefaultSimulationFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); // let triggers through if(PxFilterObjectIsTrigger(attributes0) || PxFilterObjectIsTrigger(attributes1)) { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; return PxFilterFlags(); } // Collision Group if (!gCollisionTable[filterData0.word0][filterData1.word0]()) { return PxFilterFlag::eSUPPRESS; } // Filter function PxGroupsMask g0 = convert(filterData0); PxGroupsMask g1 = convert(filterData1); PxGroupsMask g0k0; gTable[gFilterOps[0]](g0k0, g0, gFilterConstants[0]); PxGroupsMask g1k1; gTable[gFilterOps[1]](g1k1, g1, gFilterConstants[1]); PxGroupsMask final; gTable[gFilterOps[2]](final, g0k0, g1k1); bool r = final.bits0 || final.bits1 || final.bits2 || final.bits3; if (r != gFilterBool) { return PxFilterFlag::eSUPPRESS; } pairFlags = PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlags(); } bool physx::PxGetGroupCollisionFlag(const PxU16 group1, const PxU16 group2) { PX_CHECK_AND_RETURN_NULL(group1 < 32 && group2 < 32, "Group must be less than 32"); return gCollisionTable[group1][group2](); } void physx::PxSetGroupCollisionFlag(const PxU16 group1, const PxU16 group2, const bool enable) { PX_CHECK_AND_RETURN(group1 < 32 && group2 < 32, "Group must be less than 32"); gCollisionTable[group1][group2] = enable; gCollisionTable[group2][group1] = enable; } PxU16 physx::PxGetGroup(const PxActor& actor) { PxFilterData fd; getFilterData(actor, fd); return PxU16(fd.word0); } void physx::PxSetGroup(PxActor& actor, const PxU16 collisionGroup) { PX_CHECK_AND_RETURN(collisionGroup < 32,"Collision group must be less than 32"); PxFilterData fd(collisionGroup, 0, 0, 0); setFilterData<false>(actor, fd); } void physx::PxGetFilterOps(PxFilterOp::Enum& op0, PxFilterOp::Enum& op1, PxFilterOp::Enum& op2) { op0 = gFilterOps[0]; op1 = gFilterOps[1]; op2 = gFilterOps[2]; } void physx::PxSetFilterOps(const PxFilterOp::Enum& op0, const PxFilterOp::Enum& op1, const PxFilterOp::Enum& op2) { gFilterOps[0] = op0; gFilterOps[1] = op1; gFilterOps[2] = op2; } bool physx::PxGetFilterBool() { return gFilterBool; } void physx::PxSetFilterBool(const bool enable) { gFilterBool = enable; } void physx::PxGetFilterConstants(PxGroupsMask& c0, PxGroupsMask& c1) { c0 = gFilterConstants[0]; c1 = gFilterConstants[1]; } void physx::PxSetFilterConstants(const PxGroupsMask& c0, const PxGroupsMask& c1) { gFilterConstants[0] = c0; gFilterConstants[1] = c1; } PxGroupsMask physx::PxGetGroupsMask(const PxActor& actor) { PxFilterData fd; if (getFilterData(actor, fd)) return convert(fd); else return PxGroupsMask(); } void physx::PxSetGroupsMask(PxActor& actor, const PxGroupsMask& mask) { PxFilterData fd = convert(mask); setFilterData<true>(actor, fd); }
10,357
C++
28.679083
124
0.722989
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtGearJoint.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 "ExtGearJoint.h" #include "ExtConstraintHelper.h" #include "extensions/PxRevoluteJoint.h" #include "PxArticulationJointReducedCoordinate.h" #include "omnipvd/ExtOmniPvdSetData.h" //#include <stdio.h> using namespace physx; using namespace Ext; PX_IMPLEMENT_OUTPUT_ERROR GearJoint::GearJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : GearJointT(PxJointConcreteType::eGEAR, actor0, localFrame0, actor1, localFrame1, "GearJointData") { GearJointData* data = static_cast<GearJointData*>(mData); data->hingeJoint0 = NULL; data->hingeJoint1 = NULL; data->gearRatio = 0.0f; data->error = 0.0f; resetError(); } bool GearJoint::setHinges(const PxBase* hinge0, const PxBase* hinge1) { GearJointData* data = static_cast<GearJointData*>(mData); if(hinge0) { const PxType type0 = hinge0->getConcreteType(); if(type0 == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* joint0 = static_cast<const PxArticulationJointReducedCoordinate*>(hinge0); const PxArticulationJointType::Enum artiJointType = joint0->getJointType(); if(artiJointType != PxArticulationJointType::eREVOLUTE && artiJointType != PxArticulationJointType::eREVOLUTE_UNWRAPPED) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint."); } else { if(type0 != PxJointConcreteType::eREVOLUTE && type0 != PxJointConcreteType::eD6) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint or a D6 joint."); } } if(hinge1) { const PxType type1 = hinge1->getConcreteType(); if(type1 == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* joint1 = static_cast<const PxArticulationJointReducedCoordinate*>(hinge1); const PxArticulationJointType::Enum artiJointType = joint1->getJointType(); if(artiJointType != PxArticulationJointType::eREVOLUTE && artiJointType != PxArticulationJointType::eREVOLUTE_UNWRAPPED) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint."); } else { if(type1 != PxJointConcreteType::eREVOLUTE && type1 != PxJointConcreteType::eD6) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxGearJoint::setHinges: passed joint must be either a revolute joint or a D6 joint."); } } data->hingeJoint0 = hinge0; data->hingeJoint1 = hinge1; resetError(); markDirty(); #if PX_SUPPORT_OMNI_PVD const PxBase* joints[] ={ hinge0, hinge1 }; const PxU32 hingeCount = sizeof(joints) / sizeof(joints[0]); OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, hinges, static_cast<PxGearJoint&>(*this), joints, hingeCount) #endif return true; } void GearJoint::getHinges(const PxBase*& hinge0, const PxBase*& hinge1) const { const GearJointData* data = static_cast<const GearJointData*>(mData); hinge0 = data->hingeJoint0; hinge1 = data->hingeJoint1; } void GearJoint::setGearRatio(float ratio) { GearJointData* data = static_cast<GearJointData*>(mData); data->gearRatio = ratio; resetError(); markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, ratio, static_cast<PxGearJoint&>(*this), ratio) } float GearJoint::getGearRatio() const { const GearJointData* data = static_cast<const GearJointData*>(mData); return data->gearRatio; } static float angleDiff(float angle0, float angle1) { const float diff = fmodf(angle1 - angle0 + PxPi, PxTwoPi) - PxPi; return diff < -PxPi ? diff + PxTwoPi : diff; } static void getAngleAndSign(float& angle, float& sign, const PxBase* dataHingeJoint, PxRigidActor* gearActor0, PxRigidActor* gearActor1) { PxRigidActor* hingeActor0; PxRigidActor* hingeActor1; const PxType type = dataHingeJoint->getConcreteType(); if(type == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { const PxArticulationJointReducedCoordinate* artiHingeJoint = static_cast<const PxArticulationJointReducedCoordinate*>(dataHingeJoint); hingeActor0 = &artiHingeJoint->getParentArticulationLink(); hingeActor1 = &artiHingeJoint->getChildArticulationLink(); angle = artiHingeJoint->getJointPosition(PxArticulationAxis::eTWIST); } else { const PxJoint* hingeJoint = static_cast<const PxJoint*>(dataHingeJoint); hingeJoint->getActors(hingeActor0, hingeActor1); if(type == PxJointConcreteType::eREVOLUTE) angle = static_cast<const PxRevoluteJoint*>(hingeJoint)->getAngle(); else if(type == PxJointConcreteType::eD6) angle = static_cast<const PxD6Joint*>(hingeJoint)->getTwistAngle(); } if(gearActor0 == hingeActor0 || gearActor1 == hingeActor0) sign = -1.0f; else if(gearActor0 == hingeActor1 || gearActor1 == hingeActor1) sign = 1.0f; else PX_ASSERT(0); } void GearJoint::updateError() { GearJointData* data = static_cast<GearJointData*>(mData); if(!data->hingeJoint0 || !data->hingeJoint1) return; PxRigidActor* gearActor0; PxRigidActor* gearActor1; getActors(gearActor0, gearActor1); float Angle0 = 0.0f; float Sign0 = 0.0f; getAngleAndSign(Angle0, Sign0, data->hingeJoint0, gearActor0, gearActor1); float Angle1 = 0.0f; float Sign1 = 0.0f; getAngleAndSign(Angle1, Sign1, data->hingeJoint1, gearActor0, gearActor1); Angle1 = -Angle1; if(!mInitDone) { mInitDone = true; mPersistentAngle0 = Angle0; mPersistentAngle1 = Angle1; } const float travelThisFrame0 = angleDiff(Angle0, mPersistentAngle0); const float travelThisFrame1 = angleDiff(Angle1, mPersistentAngle1); mVirtualAngle0 += travelThisFrame0; mVirtualAngle1 += travelThisFrame1; // printf("travelThisFrame0: %f\n", travelThisFrame0); // printf("travelThisFrame1: %f\n", travelThisFrame1); // printf("ratio: %f\n", travelThisFrame1/travelThisFrame0); mPersistentAngle0 = Angle0; mPersistentAngle1 = Angle1; const float error = Sign0*mVirtualAngle0*data->gearRatio - Sign1*mVirtualAngle1; // printf("error: %f\n", error); data->error = error; markDirty(); } void GearJoint::resetError() { mVirtualAngle0 = mVirtualAngle1 = 0.0f; mPersistentAngle0 = mPersistentAngle1 = 0.0f; mInitDone = false; } static const bool gVizJointFrames = true; static const bool gVizGearAxes = false; static void GearJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) { const GearJointData& data = *reinterpret_cast<const GearJointData*>(constantBlock); // Visualize joint frames PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(gVizJointFrames) viz.visualizeJointFrames(cA2w, cB2w); if(gVizGearAxes) { const PxVec3 gearAxis0 = cA2w.rotate(PxVec3(1.0f, 0.0f, 0.0f)).getNormalized(); const PxVec3 gearAxis1 = cB2w.rotate(PxVec3(1.0f, 0.0f, 0.0f)).getNormalized(); viz.visualizeLine(body0Transform.p+gearAxis0, body0Transform.p, 0xff0000ff); viz.visualizeLine(body1Transform.p+gearAxis1, body1Transform.p, 0xff0000ff); } } } //TAG:solverprepshader static PxU32 GearJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const GearJointData& data = *reinterpret_cast<const GearJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); cA2wOut = cB2w.p; cB2wOut = cB2w.p; const PxVec3 gearAxis0 = cA2w.q.getBasisVector0(); const PxVec3 gearAxis1 = cB2w.q.getBasisVector0(); Px1DConstraint& con = constraints[0]; con.linear0 = PxVec3(0.0f); con.linear1 = PxVec3(0.0f); con.angular0 = gearAxis0*data.gearRatio; con.angular1 = -gearAxis1; con.geometricError = -data.error; con.minImpulse = -PX_MAX_F32; con.maxImpulse = PX_MAX_F32; con.velocityTarget = 0.f; con.forInternalUse = 0.f; con.solveHint = 0; con.flags = Px1DConstraintFlag::eOUTPUT_FORCE|Px1DConstraintFlag::eANGULAR_CONSTRAINT; con.mods.bounce.restitution = 0.0f; con.mods.bounce.velocityThreshold = 0.0f; return 1; } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gGearJointShaders = { GearJointSolverPrep, GearJointVisualize, PxConstraintFlag::eALWAYS_UPDATE }; PxConstraintSolverPrep GearJoint::getPrep() const { return gGearJointShaders.solverPrep; } PxGearJoint* physx::PxGearJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxGearJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxGearJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxGearJointCreate: at least one actor must be dynamic"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxGearJointCreate: actors must be different"); return createJointT<GearJoint, GearJointData>(physics, actor0, localFrame0, actor1, localFrame1, gGearJointShaders); } // PX_SERIALIZATION void GearJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gGearJointShaders); GearJointData* data = static_cast<GearJointData*>(mData); context.translatePxBase(data->hingeJoint0); context.translatePxBase(data->hingeJoint1); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD template<> void physx::Ext::omniPvdInitJoint<GearJoint>(GearJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxGearJoint& j = static_cast<PxGearJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eGEAR); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxGearJoint, ratio, j , joint.getGearRatio()) OMNI_PVD_WRITE_SCOPE_END } #endif
12,129
C++
35.869301
169
0.756534
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtPxStringTable.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/PxAllocatorCallback.h" #include "foundation/PxString.h" #include "foundation/PxUserAllocated.h" #include "extensions/PxStringTableExt.h" #include "PxProfileAllocatorWrapper.h" //tools for using a custom allocator namespace physx { using namespace physx::profile; class PxStringTableImpl : public PxStringTable, public PxUserAllocated { typedef PxProfileHashMap<const char*, PxU32> THashMapType; PxProfileAllocatorWrapper mWrapper; THashMapType mHashMap; public: PxStringTableImpl( PxAllocatorCallback& inAllocator ) : mWrapper ( inAllocator ) , mHashMap ( mWrapper ) { } virtual ~PxStringTableImpl() { for ( THashMapType::Iterator iter = mHashMap.getIterator(); iter.done() == false; ++iter ) PX_PROFILE_DELETE( mWrapper, const_cast<char*>( iter->first ) ); mHashMap.clear(); } virtual const char* allocateStr( const char* inSrc ) { if ( inSrc == NULL ) inSrc = ""; const THashMapType::Entry* existing( mHashMap.find( inSrc ) ); if ( existing == NULL ) { size_t len( strlen( inSrc ) ); len += 1; char* newMem = reinterpret_cast<char*>(mWrapper.getAllocator().allocate( len, "PxStringTableImpl: const char*", PX_FL)); physx::Pxstrlcpy( newMem, len, inSrc ); mHashMap.insert( newMem, 1 ); return newMem; } else { ++const_cast<THashMapType::Entry*>(existing)->second; return existing->first; } } /** * Release the string table and all the strings associated with it. */ virtual void release() { PX_PROFILE_DELETE( mWrapper.getAllocator(), this ); } }; PxStringTable& PxStringTableExt::createStringTable( PxAllocatorCallback& inAllocator ) { return *PX_PROFILE_NEW( inAllocator, PxStringTableImpl )( inAllocator ); } }
3,477
C++
34.85567
124
0.727064
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDistanceJoint.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 "ExtDistanceJoint.h" #include "ExtConstraintHelper.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; DistanceJoint::DistanceJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : DistanceJointT(PxJointConcreteType::eDISTANCE, actor0, localFrame0, actor1, localFrame1, "DistanceJointData") { DistanceJointData* data = static_cast<DistanceJointData*>(mData); data->stiffness = 0.0f; data->damping = 0.0f; data->minDistance = 0.0f; data->maxDistance = 0.0f; data->tolerance = 0.025f * scale.length; data->jointFlags = PxDistanceJointFlag::eMAX_DISTANCE_ENABLED; } PxReal DistanceJoint::getDistance() const { return getRelativeTransform().p.magnitude(); } void DistanceJoint::setMinDistance(PxReal distance) { PX_CHECK_AND_RETURN(PxIsFinite(distance) && distance>=0.0f, "PxDistanceJoint::setMinDistance: invalid parameter"); data().minDistance = distance; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, minDistance, static_cast<PxDistanceJoint&>(*this), distance) } PxReal DistanceJoint::getMinDistance() const { return data().minDistance; } void DistanceJoint::setMaxDistance(PxReal distance) { PX_CHECK_AND_RETURN(PxIsFinite(distance) && distance>=0.0f, "PxDistanceJoint::setMaxDistance: invalid parameter"); data().maxDistance = distance; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, maxDistance, static_cast<PxDistanceJoint&>(*this), distance) } PxReal DistanceJoint::getMaxDistance() const { return data().maxDistance; } void DistanceJoint::setTolerance(PxReal tolerance) { PX_CHECK_AND_RETURN(PxIsFinite(tolerance), "PxDistanceJoint::setTolerance: invalid parameter"); data().tolerance = tolerance; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, tolerance, static_cast<PxDistanceJoint&>(*this), tolerance) } PxReal DistanceJoint::getTolerance() const { return data().tolerance; } void DistanceJoint::setStiffness(PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness), "PxDistanceJoint::setStiffness: invalid parameter"); data().stiffness = stiffness; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, stiffness, static_cast<PxDistanceJoint&>(*this), stiffness) } PxReal DistanceJoint::getStiffness() const { return data().stiffness; } void DistanceJoint::setDamping(PxReal damping) { PX_CHECK_AND_RETURN(PxIsFinite(damping), "PxDistanceJoint::setDamping: invalid parameter"); data().damping = damping; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, damping, static_cast<PxDistanceJoint&>(*this), damping) } PxReal DistanceJoint::getDamping() const { return data().damping; } PxDistanceJointFlags DistanceJoint::getDistanceJointFlags(void) const { return data().jointFlags; } void DistanceJoint::setDistanceJointFlags(PxDistanceJointFlags flags) { data().jointFlags = flags; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, jointFlags, static_cast<PxDistanceJoint&>(*this), flags) } void DistanceJoint::setDistanceJointFlag(PxDistanceJointFlag::Enum flag, bool value) { if(value) data().jointFlags |= flag; else data().jointFlags &= ~flag; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, jointFlags, static_cast<PxDistanceJoint&>(*this), getDistanceJointFlags()) } static void DistanceJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { const DistanceJointData& data = *reinterpret_cast<const DistanceJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) viz.visualizeJointFrames(cA2w, cB2w); // PT: we consider the following is part of the joint's "limits" since that's the only available flag we have if(flags & PxConstraintVisualizationFlag::eLIMITS) { const bool enforceMax = (data.jointFlags & PxDistanceJointFlag::eMAX_DISTANCE_ENABLED); const bool enforceMin = (data.jointFlags & PxDistanceJointFlag::eMIN_DISTANCE_ENABLED); if(!enforceMin && !enforceMax) return; PxVec3 dir = cB2w.p - cA2w.p; const float currentDist = dir.normalize(); PxU32 color = 0x00ff00; if(enforceMax && currentDist>data.maxDistance) color = 0xff0000; if(enforceMin && currentDist<data.minDistance) color = 0x0000ff; viz.visualizeLine(cA2w.p, cB2w.p, color); } } static PX_FORCE_INLINE void setupConstraint(Px1DConstraint& c, const PxVec3& direction, const PxVec3& angular0, const PxVec3& angular1, const DistanceJointData& data) { // constraint is breakable, so we need to output forces c.flags = Px1DConstraintFlag::eOUTPUT_FORCE; c.linear0 = direction; c.angular0 = angular0; c.linear1 = direction; c.angular1 = angular1; if(data.jointFlags & PxDistanceJointFlag::eSPRING_ENABLED) { c.flags |= Px1DConstraintFlag::eSPRING; c.mods.spring.stiffness= data.stiffness; c.mods.spring.damping = data.damping; } } static PX_FORCE_INLINE PxU32 setupMinConstraint(Px1DConstraint& c, const PxVec3& direction, const PxVec3& angular0, const PxVec3& angular1, const DistanceJointData& data, float distance) { setupConstraint(c, direction, angular0, angular1, data); c.geometricError = distance - data.minDistance + data.tolerance; c.minImpulse = 0.0f; if(distance>=data.minDistance) c.flags |= Px1DConstraintFlag::eKEEPBIAS; return 1; } static PX_FORCE_INLINE PxU32 setupMaxConstraint(Px1DConstraint& c, const PxVec3& direction, const PxVec3& angular0, const PxVec3& angular1, const DistanceJointData& data, float distance) { setupConstraint(c, direction, angular0, angular1, data); c.geometricError = distance - data.maxDistance - data.tolerance; c.maxImpulse = 0.0f; if(distance<=data.maxDistance) c.flags |= Px1DConstraintFlag::eKEEPBIAS; return 1; } //TAG:solverprepshader static PxU32 DistanceJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const DistanceJointData& data = *reinterpret_cast<const DistanceJointData*>(constantBlock); const bool enforceMax = (data.jointFlags & PxDistanceJointFlag::eMAX_DISTANCE_ENABLED) && data.maxDistance>=0.0f; const bool enforceMin = (data.jointFlags & PxDistanceJointFlag::eMIN_DISTANCE_ENABLED) && data.minDistance>=0.0f; if(!enforceMax && !enforceMin) return 0; PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); cA2wOut = cB2w.p; cB2wOut = cB2w.p; PxVec3 direction = cA2w.p - cB2w.p; const PxReal distance = direction.normalize(); #define EPS_REAL 1.192092896e-07F if(distance < EPS_REAL) direction = PxVec3(1.0f, 0.0f, 0.0f); Px1DConstraint* c = constraints; const PxVec3 angular0 = ch.getRa().cross(direction); const PxVec3 angular1 = ch.getRb().cross(direction); if(enforceMin && !enforceMax) return setupMinConstraint(*c, direction, angular0, angular1, data, distance); else if(enforceMax && !enforceMin) return setupMaxConstraint(*c, direction, angular0, angular1, data, distance); else { if(data.minDistance == data.maxDistance) { setupConstraint(*c, direction, angular0, angular1, data); //add tolerance so we don't have contact-style jitter problem. const PxReal error = distance - data.maxDistance; c->geometricError = error > data.tolerance ? error - data.tolerance : error < -data.tolerance ? error + data.tolerance : 0.0f; return 1; } // since we dont know the current rigid velocity, we need to insert row for both limits PxU32 nb = setupMinConstraint(*c, direction, angular0, angular1, data, distance); if(nb) c++; nb += setupMaxConstraint(*c, direction, angular0, angular1, data, distance); return nb; } } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gDistanceJointShaders = { DistanceJointSolverPrep, DistanceJointVisualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep DistanceJoint::getPrep() const { return gDistanceJointShaders.solverPrep; } PxDistanceJoint* physx::PxDistanceJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxDistanceJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxDistanceJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxDistanceJointCreate: actors must be different"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxD6JointCreate: at least one actor must be dynamic"); return createJointT<DistanceJoint, DistanceJointData>(physics, actor0, localFrame0, actor1, localFrame1, gDistanceJointShaders); } // PX_SERIALIZATION void DistanceJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gDistanceJointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD void DistanceJoint::updateOmniPvdProperties() const { const PxDistanceJoint& j = static_cast<const PxDistanceJoint&>(*this); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, distance, j, getDistance()) } template<> void physx::Ext::omniPvdInitJoint<DistanceJoint>(DistanceJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxDistanceJoint& j = static_cast<PxDistanceJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eDISTANCE); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, minDistance, j, joint.getMinDistance()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, maxDistance, j, joint.getMaxDistance()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, tolerance, j, joint.getTolerance()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, stiffness, j, joint.getStiffness()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, damping, j, joint.getDamping()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, jointFlags, j, joint.getDistanceJointFlags()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxDistanceJoint, distance, j, joint.getDistance()) OMNI_PVD_WRITE_SCOPE_END } #endif
12,711
C++
37.289157
186
0.761466
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtContactJoint.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 EXT_CONTACT_JOINT_H #define EXT_CONTACT_JOINT_H #include "common/PxTolerancesScale.h" #include "extensions/PxContactJoint.h" #include "ExtJoint.h" #include "foundation/PxUserAllocated.h" #include "CmUtils.h" namespace physx { struct PxContactJointGeneratedValues; namespace Ext { struct ContactJointData : public JointData { PxVec3 contact; PxVec3 normal; PxReal penetration; PxReal restitution; PxReal bounceThreshold; }; typedef JointT<PxContactJoint, ContactJointData, PxContactJointGeneratedValues> ContactJointT; class ContactJoint : public ContactJointT { public: // PX_SERIALIZATION ContactJoint(PxBaseFlags baseFlags) : ContactJointT(baseFlags) {} void resolveReferences(PxDeserializationContext& context); static ContactJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<ContactJoint>(address, context); } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ContactJoint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); // PxContactJoint virtual PxVec3 getContact() const PX_OVERRIDE; virtual void setContact(const PxVec3& contact) PX_OVERRIDE; virtual PxVec3 getContactNormal() const PX_OVERRIDE; virtual void setContactNormal(const PxVec3& normal) PX_OVERRIDE; virtual PxReal getPenetration() const PX_OVERRIDE; virtual void setPenetration(const PxReal penetration) PX_OVERRIDE; virtual PxReal getRestitution() const PX_OVERRIDE; virtual void setRestitution(const PxReal resititution) PX_OVERRIDE; virtual PxReal getBounceThreshold() const PX_OVERRIDE; virtual void setBounceThreshold(const PxReal bounceThreshold) PX_OVERRIDE; virtual void computeJacobians(PxJacobianRow* jacobian) const PX_OVERRIDE; virtual PxU32 getNbJacobianRows() const PX_OVERRIDE; //~PxContactJoint // PxConstraintConnector virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE; //~PxConstraintConnector }; } // namespace Ext } // namespace physx #endif
3,862
C
42.897727
163
0.767478
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSmoothNormals.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 "extensions/PxSmoothNormals.h" #include "foundation/PxMathUtils.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" using namespace physx; static PxReal computeAngle(const PxVec3* verts, const PxU32* refs, PxU32 vref) { PxU32 e0=0,e2=0; if(vref==refs[0]) { e0 = 2; e2 = 1; } else if(vref==refs[1]) { e0 = 2; e2 = 0; } else if(vref==refs[2]) { e0 = 0; e2 = 1; } else { PX_ASSERT(0); } const PxVec3 edge0 = verts[refs[e0]] - verts[vref]; const PxVec3 edge1 = verts[refs[e2]] - verts[vref]; return PxComputeAngle(edge0, edge1); } bool PxBuildSmoothNormals(PxU32 nbTris, PxU32 nbVerts, const PxVec3* verts, const PxU32* dFaces, const PxU16* wFaces, PxVec3* normals, bool flip) { if(!verts || !normals || !nbTris || !nbVerts) return false; // Get correct destination buffers // - if available, write directly to user-provided buffers // - else get some ram and keep track of it PxVec3* FNormals = PX_ALLOCATE(PxVec3, nbTris, "PxVec3"); if(!FNormals) return false; // Compute face normals const PxU32 c = PxU32(flip!=0); for(PxU32 i=0; i<nbTris; i++) { // compute indices outside of array index to workaround // SNC bug which was generating incorrect addresses const PxU32 i0 = i*3+0; const PxU32 i1 = i*3+1+c; const PxU32 i2 = i*3+2-c; const PxU32 Ref0 = dFaces ? dFaces[i0] : wFaces ? wFaces[i0] : 0; const PxU32 Ref1 = dFaces ? dFaces[i1] : wFaces ? wFaces[i1] : 1; const PxU32 Ref2 = dFaces ? dFaces[i2] : wFaces ? wFaces[i2] : 2; FNormals[i] = (verts[Ref2]-verts[Ref0]).cross(verts[Ref1] - verts[Ref0]); PX_ASSERT(!FNormals[i].isZero()); FNormals[i].normalize(); } // Compute vertex normals PxMemSet(normals, 0, nbVerts*sizeof(PxVec3)); // TTP 3751 PxVec3* TmpNormals = PX_ALLOCATE(PxVec3, nbVerts, "PxVec3"); PxMemSet(TmpNormals, 0, nbVerts*sizeof(PxVec3)); for(PxU32 i=0;i<nbTris;i++) { PxU32 Ref[3]; Ref[0] = dFaces ? dFaces[i*3+0] : wFaces ? wFaces[i*3+0] : 0; Ref[1] = dFaces ? dFaces[i*3+1] : wFaces ? wFaces[i*3+1] : 1; Ref[2] = dFaces ? dFaces[i*3+2] : wFaces ? wFaces[i*3+2] : 2; for(PxU32 j=0;j<3;j++) { if(TmpNormals[Ref[j]].isZero()) TmpNormals[Ref[j]] = FNormals[i]; } } //~TTP 3751 for(PxU32 i=0;i<nbTris;i++) { PxU32 Ref[3]; Ref[0] = dFaces ? dFaces[i*3+0] : wFaces ? wFaces[i*3+0] : 0; Ref[1] = dFaces ? dFaces[i*3+1] : wFaces ? wFaces[i*3+1] : 1; Ref[2] = dFaces ? dFaces[i*3+2] : wFaces ? wFaces[i*3+2] : 2; normals[Ref[0]] += FNormals[i] * computeAngle(verts, Ref, Ref[0]); normals[Ref[1]] += FNormals[i] * computeAngle(verts, Ref, Ref[1]); normals[Ref[2]] += FNormals[i] * computeAngle(verts, Ref, Ref[2]); } // Normalize vertex normals for(PxU32 i=0;i<nbVerts;i++) { if(normals[i].isZero()) normals[i] = TmpNormals[i]; // PX_ASSERT(!normals[i].isZero()); normals[i].normalize(); } PX_FREE(TmpNormals); // TTP 3751 PX_FREE(FNormals); return true; }
4,681
C++
31.513889
145
0.687246
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtTetrahedronMeshExt.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 "extensions/PxTetrahedronMeshExt.h" #include "foundation/PxMathUtils.h" #include "foundation/PxHashMap.h" #include "GuTetrahedronMesh.h" #include "GuBox.h" #include "GuBV4.h" #include "GuBV4_Common.h" #include "GuDistancePointTetrahedron.h" #include "GuAABBTreeNode.h" #include "GuAABBTree.h" #include "GuAABBTreeBounds.h" #include "GuAABBTreeQuery.h" namespace physx { struct TetrahedronFinderCallback { PxVec3 mQueryPoint; PxI32 mTetId; PxVec4 mBary; const PxVec3* mVertices; const PxU32* mTets; PxReal mTolerance = 1e-6f; TetrahedronFinderCallback(const PxVec3& queryPoint, const PxVec3* vertices, const PxU32* tets, const PxReal tolerance = 1e-6f) : mQueryPoint(queryPoint), mTetId(-1), mVertices(vertices), mTets(tets), mTolerance(tolerance) {} PX_FORCE_INLINE bool testPrimitive(const PxU32 primitiveStartId, const PxU32 numPrimitives) { for (PxU32 i = 0; i < numPrimitives; ++i) { const PxU32* tet = &mTets[4 * (primitiveStartId + i)]; computeBarycentric(mVertices[tet[0]], mVertices[tet[1]], mVertices[tet[2]], mVertices[tet[3]], mQueryPoint, mBary); if (mBary.x >= -mTolerance && mBary.x <= 1 + mTolerance && mBary.y >= -mTolerance && mBary.y <= 1 + mTolerance && mBary.z >= -mTolerance && mBary.z <= 1 + mTolerance && mBary.w >= -mTolerance && mBary.w <= 1 + mTolerance) { mTetId = PxI32(primitiveStartId + i); return true; } } return false; } PX_FORCE_INLINE bool testBox(const float boxMinX, const float boxMinY, const float boxMinZ, const float boxMaxX, const float boxMaxY, const float boxMaxZ) { return mQueryPoint.x >= boxMinX && mQueryPoint.y >= boxMinY && mQueryPoint.z >= boxMinZ && mQueryPoint.x <= boxMaxX && mQueryPoint.y <= boxMaxY && mQueryPoint.z <= boxMaxZ; } }; struct ClosestTetrahedronFinderCallback { PxVec3 mQueryPoint; PxI32 mTetId; PxVec4 mBary; PxReal mDist = 1.84467e+19f; // sqrtf(FLT_MAX) const PxVec3* mVertices; const PxU32* mTets; PxReal mTolerance = 1e-6f; ClosestTetrahedronFinderCallback(const PxVec3& queryPoint, const PxVec3* vertices, const PxU32* tets) : mQueryPoint(queryPoint), mTetId(-1), mVertices(vertices), mTets(tets) {} PX_FORCE_INLINE bool testPrimitive(const PxU32 primitiveStartId, const PxU32 numPrimitives) { for (PxU32 i = 0; i < numPrimitives; ++i) { PxVec4 bary; const PxU32* tet = &mTets[4 * (primitiveStartId + i)]; computeBarycentric(mVertices[tet[0]], mVertices[tet[1]], mVertices[tet[2]], mVertices[tet[3]], mQueryPoint, bary); if (bary.x >= -mTolerance && bary.x <= 1 + mTolerance && bary.y >= -mTolerance && bary.y <= 1 + mTolerance && bary.z >= -mTolerance && bary.z <= 1 + mTolerance && bary.w >= -mTolerance && bary.w <= 1 + mTolerance) { mTetId = PxI32(primitiveStartId + i); mBary = bary; mDist = 0; return true; } PxVec3 closest = Gu::closestPtPointTetrahedron(mQueryPoint, mVertices[tet[0]], mVertices[tet[1]], mVertices[tet[2]], mVertices[tet[3]]); PxReal distSq = (closest - mQueryPoint).magnitudeSquared(); if (distSq < mDist * mDist) { mTetId = PxI32(primitiveStartId + i); mBary = bary; mDist = PxSqrt(distSq); } } return false; } PX_FORCE_INLINE bool testBox(const float boxMinX, const float boxMinY, const float boxMinZ, const float boxMaxX, const float boxMaxY, const float boxMaxZ) { if (mQueryPoint.x >= boxMinX && mQueryPoint.y >= boxMinY && mQueryPoint.z >= boxMinZ && mQueryPoint.x <= boxMaxX && mQueryPoint.y <= boxMaxY && mQueryPoint.z <= boxMaxZ) return true; PxVec3 closest = mQueryPoint; closest.x = PxClamp(closest.x, boxMinX, boxMaxX); closest.y = PxClamp(closest.y, boxMinY, boxMaxY); closest.z = PxClamp(closest.z, boxMinZ, boxMaxZ); PxReal distSq = (closest - mQueryPoint).magnitudeSquared(); return distSq < mDist * mDist; } }; template<typename T, PxU32 i> int process(PxU32* stack, PxU32& stackSize, const Gu::BVDataSwizzledNQ* node, T& callback) { if (callback.testBox(node->mMinX[i], node->mMinY[i], node->mMinZ[i], node->mMaxX[i], node->mMaxY[i], node->mMaxZ[i])) { if (node->isLeaf(i)) { PxU32 primitiveIndex = node->getPrimitive(i); const PxU32 numPrimitives = Gu::getNbPrimitives(primitiveIndex); if(callback.testPrimitive(primitiveIndex, numPrimitives)) //Returns true if the query should be terminated immediately return 1; } else stack[stackSize++] = node->getChildData(i); } return 0; } template<typename T> void traverseBVH(const Gu::BV4Tree& tree, T& callback) { const Gu::BVDataPackedNQ* root = static_cast<const Gu::BVDataPackedNQ*>(tree.mNodes); PxU32 stack[GU_BV4_STACK_SIZE]; PxU32 stackSize = 0; stack[stackSize++] = tree.mInitData; while (stackSize > 0) { const PxU32 childData = stack[--stackSize]; const Gu::BVDataSwizzledNQ* node = reinterpret_cast<const Gu::BVDataSwizzledNQ*>(root + Gu::getChildOffset(childData)); const PxU32 nodeType = Gu::getChildType(childData); if (nodeType > 1) if (process<T, 3>(stack, stackSize, node, callback)) return; if (nodeType > 0) if (process<T, 2>(stack, stackSize, node, callback)) return; if (process<T, 1>(stack, stackSize, node, callback)) return; if (process<T, 0>(stack, stackSize, node, callback)) return; } } PxI32 PxTetrahedronMeshExt::findTetrahedronContainingPoint(const PxTetrahedronMesh* mesh, const PxVec3& point, PxVec4& bary, PxReal tolerance) { TetrahedronFinderCallback callback(point, mesh->getVertices(), static_cast<const PxU32*>(mesh->getTetrahedrons()), tolerance); traverseBVH(static_cast<const Gu::BVTetrahedronMesh*>(mesh)->getBV4Tree(), callback); bary = callback.mBary; return callback.mTetId; } PxI32 PxTetrahedronMeshExt::findTetrahedronClosestToPoint(const PxTetrahedronMesh* mesh, const PxVec3& point, PxVec4& bary) { ClosestTetrahedronFinderCallback callback(point, mesh->getVertices(), static_cast<const PxU32*>(mesh->getTetrahedrons())); const Gu::BV4Tree& tree = static_cast<const Gu::BVTetrahedronMesh*>(mesh)->getBV4Tree(); if (tree.mNbNodes) traverseBVH(tree, callback); else callback.testPrimitive(0, mesh->getNbTetrahedrons()); bary = callback.mBary; return callback.mTetId; } class ClosestDistanceToTetmeshTraversalController { private: PxReal mClosestDistanceSquared; const PxU32* mTetrahedra; const PxVec3* mPoints; const Gu::BVHNode* mNodes; PxVec3 mQueryPoint; PxVec3 mClosestPoint; PxI32 mClosestTetId; public: PX_FORCE_INLINE ClosestDistanceToTetmeshTraversalController() {} PX_FORCE_INLINE ClosestDistanceToTetmeshTraversalController(const PxU32* tetrahedra, const PxVec3* points, Gu::BVHNode* nodes) : mTetrahedra(tetrahedra), mPoints(points), mNodes(nodes), mQueryPoint(0.0f), mClosestPoint(0.0f), mClosestTetId(-1) { initialize(tetrahedra, points, nodes); } void initialize(const PxU32* tetrahedra, const PxVec3* points, Gu::BVHNode* nodes) { mTetrahedra = tetrahedra; mPoints = points; mNodes = nodes; mQueryPoint = PxVec3(0.0f); mClosestPoint = PxVec3(0.0f); mClosestTetId = -1; mClosestDistanceSquared = PX_MAX_F32; } PX_FORCE_INLINE void setQueryPoint(const PxVec3& queryPoint) { this->mQueryPoint = queryPoint; mClosestDistanceSquared = FLT_MAX; mClosestPoint = PxVec3(0.0f); mClosestTetId = -1; } PX_FORCE_INLINE const PxVec3& getClosestPoint() const { return mClosestPoint; } PX_FORCE_INLINE PxReal distancePointBoxSquared(const PxBounds3& box, const PxVec3& point) { PxVec3 closestPt = box.minimum.maximum(box.maximum.minimum(point)); return (closestPt - point).magnitudeSquared(); } PX_FORCE_INLINE Gu::TraversalControl::Enum analyze(const Gu::BVHNode& node, PxI32) { if (distancePointBoxSquared(node.mBV, mQueryPoint) >= mClosestDistanceSquared) return Gu::TraversalControl::eDontGoDeeper; if (node.isLeaf()) { const PxI32 j = node.getPrimitiveIndex(); const PxU32* tet = &mTetrahedra[4 * j]; PxVec4 bary; computeBarycentric(mPoints[tet[0]], mPoints[tet[1]], mPoints[tet[2]], mPoints[tet[3]], mQueryPoint, bary); const PxReal tolerance = 0.0f; if (bary.x >= -tolerance && bary.x <= 1 + tolerance && bary.y >= -tolerance && bary.y <= 1 + tolerance && bary.z >= -tolerance && bary.z <= 1 + tolerance && bary.w >= -tolerance && bary.w <= 1 + tolerance) { mClosestDistanceSquared = 0; mClosestTetId = j; mClosestPoint = mQueryPoint; return Gu::TraversalControl::eAbort; } PxVec3 closest = Gu::closestPtPointTetrahedron(mQueryPoint, mPoints[tet[0]], mPoints[tet[1]], mPoints[tet[2]], mPoints[tet[3]]); PxReal d2 = (closest - mQueryPoint).magnitudeSquared(); if (d2 < mClosestDistanceSquared) { mClosestDistanceSquared = d2; mClosestTetId = j; mClosestPoint = closest; } return Gu::TraversalControl::eDontGoDeeper; } const Gu::BVHNode& nodePos = mNodes[node.getPosIndex()]; const PxReal distSquaredPos = distancePointBoxSquared(nodePos.mBV, mQueryPoint); const Gu::BVHNode& nodeNeg = mNodes[node.getNegIndex()]; const PxReal distSquaredNeg = distancePointBoxSquared(nodeNeg.mBV, mQueryPoint); if (distSquaredPos < distSquaredNeg) { if (distSquaredPos < mClosestDistanceSquared) return Gu::TraversalControl::eGoDeeper; } else { if (distSquaredNeg < mClosestDistanceSquared) return Gu::TraversalControl::eGoDeeperNegFirst; } return Gu::TraversalControl::eDontGoDeeper; } PxI32 getClosestTetId() const { return mClosestTetId; } void setClosestStart(const PxReal closestDistanceSquared, PxI32 closestTetrahedron, const PxVec3& closestPoint) { mClosestDistanceSquared = closestDistanceSquared; mClosestTetId = closestTetrahedron; mClosestPoint = closestPoint; } private: PX_NOCOPY(ClosestDistanceToTetmeshTraversalController) }; static void buildTree(const PxU32* tetrahedra, const PxU32 numTetrahedra, const PxVec3* points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f) { //Computes a bounding box for every triangle in triangles Gu::AABBTreeBounds boxes; boxes.init(numTetrahedra); for (PxU32 i = 0; i < numTetrahedra; ++i) { const PxU32* tri = &tetrahedra[4 * i]; PxBounds3 box = PxBounds3::empty(); box.include(points[tri[0]]); box.include(points[tri[1]]); box.include(points[tri[2]]); box.include(points[tri[3]]); box.fattenFast(enlargement); boxes.getBounds()[i] = box; } Gu::buildAABBTree(numTetrahedra, boxes, tree); } void PxTetrahedronMeshExt::createPointsToTetrahedronMap(const PxArray<PxVec3>& tetMeshVertices, const PxArray<PxU32>& tetMeshIndices, const PxArray<PxVec3>& pointsToEmbed, PxArray<PxVec4>& barycentricCoordinates, PxArray<PxU32>& tetLinks) { PxArray<Gu::BVHNode> tree; buildTree(tetMeshIndices.begin(), tetMeshIndices.size() / 4, tetMeshVertices.begin(), tree); ClosestDistanceToTetmeshTraversalController cd(tetMeshIndices.begin(), tetMeshVertices.begin(), tree.begin()); barycentricCoordinates.resize(pointsToEmbed.size()); tetLinks.resize(pointsToEmbed.size()); for (PxU32 i = 0; i < pointsToEmbed.size(); ++i) { cd.setQueryPoint(pointsToEmbed[i]); Gu::traverseBVH(tree.begin(), cd); const PxU32* tet = &tetMeshIndices[4 * cd.getClosestTetId()]; PxVec4 bary; computeBarycentric(tetMeshVertices[tet[0]], tetMeshVertices[tet[1]], tetMeshVertices[tet[2]], tetMeshVertices[tet[3]], cd.getClosestPoint(), bary); barycentricCoordinates[i] = bary; tetLinks[i] = cd.getClosestTetId(); } } struct SortedTriangle { public: PxU32 A; PxU32 B; PxU32 C; PxI32 TetIndex; bool Flipped; PX_FORCE_INLINE SortedTriangle(PxU32 a, PxU32 b, PxU32 c, PxI32 tetIndex = -1) { A = a; B = b; C = c; Flipped = false; TetIndex = tetIndex; if (A > B) { PxSwap(A, B); Flipped = !Flipped; } if (B > C) { PxSwap(B, C); Flipped = !Flipped; } if (A > B) { PxSwap(A, B); Flipped = !Flipped; } } }; struct TriangleHash { PX_FORCE_INLINE std::size_t operator()(const SortedTriangle& k) const { return k.A ^ k.B ^ k.C; } PX_FORCE_INLINE bool equal(const SortedTriangle& first, const SortedTriangle& second) const { return first.A == second.A && first.B == second.B && first.C == second.C; } }; static const PxU32 tetFaces[4][3] = { {0, 2, 1}, {0, 1, 3}, {0, 3, 2}, {1, 2, 3} }; void PxTetrahedronMeshExt::extractTetMeshSurface(const void* tetrahedra, PxU32 numTetrahedra, bool sixteenBitIndices, PxArray<PxU32>& surfaceTriangles, PxArray<PxU32>* surfaceTriangleToTet, bool flipTriangleOrientation) { PxHashMap<SortedTriangle, PxU32, TriangleHash> tris; const PxU32* tets32 = reinterpret_cast<const PxU32*>(tetrahedra); const PxU16* tets16 = reinterpret_cast<const PxU16*>(tetrahedra); PxU32 l = 4 * numTetrahedra; for (PxU32 i = 0; i < l; i += 4) { for (PxU32 j = 0; j < 4; ++j) { SortedTriangle tri(sixteenBitIndices ? tets16[i + tetFaces[j][0]] : tets32[i + tetFaces[j][0]], sixteenBitIndices ? tets16[i + tetFaces[j][1]] : tets32[i + tetFaces[j][1]], sixteenBitIndices ? tets16[i + tetFaces[j][2]] : tets32[i + tetFaces[j][2]], i); if (const PxPair<const SortedTriangle, PxU32>* ptr = tris.find(tri)) tris[tri] = ptr->second + 1; else tris.insert(tri, 1); } } surfaceTriangles.clear(); if (surfaceTriangleToTet) surfaceTriangleToTet->clear(); for (PxHashMap<SortedTriangle, PxU32, TriangleHash>::Iterator iter = tris.getIterator(); !iter.done(); ++iter) { if (iter->second == 1) { surfaceTriangles.pushBack(iter->first.A); if (iter->first.Flipped != flipTriangleOrientation) { surfaceTriangles.pushBack(iter->first.C); surfaceTriangles.pushBack(iter->first.B); } else { surfaceTriangles.pushBack(iter->first.B); surfaceTriangles.pushBack(iter->first.C); } if (surfaceTriangleToTet) surfaceTriangleToTet->pushBack(iter->first.TetIndex); } } } void PxTetrahedronMeshExt::extractTetMeshSurface(const PxTetrahedronMesh* mesh, PxArray<PxU32>& surfaceTriangles, PxArray<PxU32>* surfaceTriangleToTet, bool flipTriangleOrientation) { extractTetMeshSurface(mesh->getTetrahedrons(), mesh->getNbTetrahedrons(), mesh->getTetrahedronMeshFlags() & PxTetrahedronMeshFlag::e16_BIT_INDICES, surfaceTriangles, surfaceTriangleToTet, flipTriangleOrientation); } }
16,167
C++
35.089286
220
0.705326
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtTetMakerExt.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 "tet/ExtDelaunayBoundaryInserter.h" #include "extensions/PxTetMakerExt.h" #include "cooking/PxTetrahedronMeshDesc.h" #include "geometry/PxTriangleMesh.h" #include "tet/ExtMeshSimplificator.h" #include "tet/ExtRemesher.h" #include "tet/ExtOctreeTetrahedralizer.h" #include "tet/ExtVoxelTetrahedralizer.h" #include "foundation/PxMat33.h" #include <stdio.h> using namespace physx; PX_FORCE_INLINE PxReal computeTetrahedronVolume(const PxVec3& x0, const PxVec3& x1, const PxVec3& x2, const PxVec3& x3) { const PxVec3 u1 = x1 - x0; const PxVec3 u2 = x2 - x0; const PxVec3 u3 = x3 - x0; PxMat33 edgeMatrix = PxMat33(u1, u2, u3); const PxReal det = edgeMatrix.getDeterminant(); const PxReal volume = det / 6.0f; return volume; } //Remove tets with small volume void removeSmallVolumeTetrahedra(PxArray<::physx::PxVec3>& vertices, PxArray<PxU32>& indices, PxReal volumeThreshold = 1e-8f) { uint32_t indexer = 0; for (uint32_t i = 0; i < indices.size(); i += 4) { for (uint32_t j = 0; j < 4; ++j) { indices[indexer + j] = indices[i + j]; } if (computeTetrahedronVolume(vertices[indices[i]], vertices[indices[i + 1]], vertices[indices[i + 2]], vertices[indices[i + 3]]) >= volumeThreshold) { indexer += 4; } } if (indexer < indices.size()) { indices.removeRange(indexer, indices.size() - indexer); } } //Removes vertices not referenced by any tetrahedron and maps the tet's indices to match the compacted vertex list void removeUnusedVertices(PxArray<::physx::PxVec3>& vertices, PxArray<PxU32>& tets, PxU32 numPointsToKeepAtBeginning = 0) { PxArray<PxI32> compressorMap; compressorMap.resize(vertices.size()); for (PxU32 i = 0; i < numPointsToKeepAtBeginning; ++i) compressorMap[i] = 0; for (PxU32 i = numPointsToKeepAtBeginning; i < compressorMap.size(); ++i) compressorMap[i] = -1; for (PxU32 i = 0; i < tets.size(); i += 4) { const PxU32* tet = &tets[i]; if (tet[0] == 0xFFFFFFFFu) continue; compressorMap[tet[0]] = 0; compressorMap[tet[1]] = 0; compressorMap[tet[2]] = 0; compressorMap[tet[3]] = 0; } PxU32 indexer = 0; for (PxU32 i = 0; i < compressorMap.size(); ++i) { if (compressorMap[i] >= 0) { compressorMap[i] = indexer; vertices[indexer] = vertices[i]; indexer++; } } for (PxU32 i = 0; i < tets.size(); i += 4) { PxU32* tet = &tets[i]; if (tet[0] == 0xFFFFFFFFu) continue; tet[0] = compressorMap[tet[0]]; tet[1] = compressorMap[tet[1]]; tet[2] = compressorMap[tet[2]]; tet[3] = compressorMap[tet[3]]; } if (indexer < vertices.size()) vertices.removeRange(indexer, vertices.size() - indexer); } PX_FORCE_INLINE PxU64 buildKey(PxI32 a, PxI32 b) { if (a < b) return ((PxU64(a)) << 32) | (PxU64(b)); else return ((PxU64(b)) << 32) | (PxU64(a)); } static const PxI32 neighborEdgeList[3][2] = { { 0, 1 }, { 0, 2 }, { 1, 2 } }; static void buildTriangleNeighborhood(const PxI32* tris, PxU32 numTris, PxArray<PxI32>& result) { PxU32 l = 4 * numTris; //Waste one element in neighborhood info but allow bit shift access instead result.clear(); result.resize(l, -1); PxHashMap<PxU64, PxI32> faces; for (PxU32 i = 0; i < numTris; ++i) { const PxI32* tri = &tris[3 * i]; if (tris[0] < 0) continue; for (PxI32 j = 0; j < 3; ++j) { PxU64 key = buildKey(tri[neighborEdgeList[j][0]], tri[neighborEdgeList[j][1]]); if (const PxPair<const PxU64, PxI32>* ptr = faces.find(key)) { if (ptr->second < 0) { //PX_ASSERT(false); //Invalid tetmesh since a face is shared by more than 2 tetrahedra continue; } result[4 * i + j] = ptr->second; result[ptr->second] = 4 * i + j; faces[key] = -1; } else faces.insert(key, 4 * i + j); } } } void PxTetMaker::detectTriangleIslands(const PxI32* triangles, PxU32 numTriangles, PxArray<PxU32>& islandIndexPerTriangle) { //Detect islands PxArray<PxI32> neighborhood; buildTriangleNeighborhood(triangles, numTriangles, neighborhood); const PxU32 noIslandAssignedMarker = 0xFFFFFFFF; islandIndexPerTriangle.resize(numTriangles, noIslandAssignedMarker); PxU32 start = 0; PxI32 color = -1; PxArray<PxI32> stack; while (true) { stack.clear(); while (start < islandIndexPerTriangle.size()) { if (islandIndexPerTriangle[start] == noIslandAssignedMarker) { stack.pushBack(start); ++color; islandIndexPerTriangle[start] = color; break; } ++start; } if (start == islandIndexPerTriangle.size()) break; while (stack.size() > 0) { PxI32 id = stack.popBack(); for (PxI32 i = 0; i < 3; ++i) { PxI32 a = neighborhood[4 * id + i]; PxI32 tetId = a >> 2; if (tetId >= 0 && islandIndexPerTriangle[tetId] == noIslandAssignedMarker) { stack.pushBack(tetId); islandIndexPerTriangle[tetId] = color; } } } } } PxU32 PxTetMaker::findLargestIslandId(const PxU32* islandIndexPerTriangle, PxU32 numTriangles) { PxU32 numIslands = 0; for (PxU32 i = 0; i < numTriangles; ++i) numIslands = PxMax(numIslands, islandIndexPerTriangle[i]); ++numIslands; PxArray<PxU32> numEntriesPerColor; numEntriesPerColor.resize(numIslands, 0); for (PxU32 i = 0; i < numTriangles; ++i) numEntriesPerColor[islandIndexPerTriangle[i]] += 1; PxU32 colorWithHighestTetCount = 0; for (PxU32 i = 1; i < numEntriesPerColor.size(); ++i) if (numEntriesPerColor[i] > numEntriesPerColor[colorWithHighestTetCount]) colorWithHighestTetCount = i; return colorWithHighestTetCount; } bool PxTetMaker::createConformingTetrahedronMesh(const PxSimpleTriangleMesh& triangleMesh, physx::PxArray<physx::PxVec3>& outVertices, physx::PxArray<physx::PxU32>& outTetIndices, const bool validate, PxReal volumeThreshold) { if (validate) { PxTriangleMeshAnalysisResults result = PxTetMaker::validateTriangleMesh(triangleMesh); if (result & PxTriangleMeshAnalysisResult::eMESH_IS_INVALID) { PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "createConformingTetrahedronMesh(): Input triangle mesh is not suited to create a tetmesh due to deficiencies. Please call PxTetMaker::validateTriangleMesh(triangleMesh) for more details."); return false; } } Ext::generateTetmesh(triangleMesh.points, triangleMesh.triangles, triangleMesh.flags & PxMeshFlag::e16_BIT_INDICES, outVertices, outTetIndices); if (volumeThreshold > 0.0f) removeSmallVolumeTetrahedra(outVertices, outTetIndices, volumeThreshold); PxU32 numRemoveAtEnd = Ext::removeDisconnectedIslands(reinterpret_cast<PxI32*>(outTetIndices.begin()), outTetIndices.size() / 4); if (numRemoveAtEnd > 0) outTetIndices.removeRange(outTetIndices.size() - 4 * numRemoveAtEnd, 4 * numRemoveAtEnd); removeUnusedVertices(outVertices, outTetIndices, triangleMesh.points.count); return true; } bool PxTetMaker::createVoxelTetrahedronMesh(const PxTetrahedronMeshDesc& tetMesh, const PxU32 numVoxelsAlongLongestBoundingBoxAxis, physx::PxArray<physx::PxVec3>& outVertices, physx::PxArray<physx::PxU32>& outTetIndices, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel) { //numTetsPerVoxel has only two valid values. if (numTetsPerVoxel != 5 && numTetsPerVoxel != 6) numTetsPerVoxel = 5; Ext::generateVoxelTetmesh(tetMesh.points, tetMesh.tetrahedrons, numVoxelsAlongLongestBoundingBoxAxis, outVertices, outTetIndices, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel); return true; } bool PxTetMaker::createVoxelTetrahedronMeshFromEdgeLength(const PxTetrahedronMeshDesc& tetMesh, const PxReal voxelEdgeLength, physx::PxArray<physx::PxVec3>& outVertices, physx::PxArray<physx::PxU32>& outTetIndices, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel) { //numTetsPerVoxel has only two valid values. if (numTetsPerVoxel != 5 && numTetsPerVoxel != 6) numTetsPerVoxel = 5; Ext::generateVoxelTetmesh(tetMesh.points, tetMesh.tetrahedrons, voxelEdgeLength, outVertices, outTetIndices, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel); return true; } PxTriangleMeshAnalysisResults PxTetMaker::validateTriangleMesh(const PxSimpleTriangleMesh& triangleMesh, const PxReal minVolumeThreshold, const PxReal minTriangleAngleRadians) { return Ext::validateTriangleMesh(triangleMesh.points, triangleMesh.triangles, triangleMesh.flags & PxMeshFlag::e16_BIT_INDICES, minVolumeThreshold, minTriangleAngleRadians); } PxTetrahedronMeshAnalysisResults PxTetMaker::validateTetrahedronMesh(const PxBoundedData& points, const PxBoundedData& tetrahedra, const PxReal minTetVolumeThreshold) { return Ext::validateTetrahedronMesh(points, tetrahedra, false, minTetVolumeThreshold); } void PxTetMaker::simplifyTriangleMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices, int targetTriangleCount, PxF32 maximalEdgeLength, PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxArray<PxU32> *vertexMap, PxReal edgeLengthCostWeight, PxReal flatnessDetectionThreshold, bool projectSimplifiedPointsOnInputMeshSurface, PxArray<PxU32>* outputVertexToInputTriangle, bool removeDisconnectedPatches) { Ext::MeshSimplificator ms; PxArray<PxU32> indexMapToFullTriangleSet; if (removeDisconnectedPatches) { PxU32 numTriangles = inputIndices.size() / 3; PxArray<PxU32> islandIndexPerTriangle; PxTetMaker::detectTriangleIslands(reinterpret_cast<const PxI32*>(inputIndices.begin()), numTriangles, islandIndexPerTriangle); PxU32 biggestIslandIndex = PxTetMaker::findLargestIslandId(islandIndexPerTriangle.begin(), islandIndexPerTriangle.size()); PxArray<PxU32> connectedTriangleSet; for (PxU32 i = 0; i < numTriangles; ++i) { if (islandIndexPerTriangle[i] == biggestIslandIndex) { for (PxU32 j = 0; j < 3; ++j) connectedTriangleSet.pushBack(inputIndices[3 * i + j]); indexMapToFullTriangleSet.pushBack(i); } } ms.init(inputVertices, connectedTriangleSet, edgeLengthCostWeight, flatnessDetectionThreshold, projectSimplifiedPointsOnInputMeshSurface); ms.decimateBySize(targetTriangleCount, maximalEdgeLength); ms.readBack(outputVertices, outputIndices, vertexMap, outputVertexToInputTriangle); } else { ms.init(inputVertices, inputIndices, edgeLengthCostWeight, flatnessDetectionThreshold, projectSimplifiedPointsOnInputMeshSurface); ms.decimateBySize(targetTriangleCount, maximalEdgeLength); ms.readBack(outputVertices, outputIndices, vertexMap, outputVertexToInputTriangle); } if (removeDisconnectedPatches && projectSimplifiedPointsOnInputMeshSurface && outputVertexToInputTriangle) { for (PxU32 i = 0; i < outputVertexToInputTriangle->size(); ++i) (*outputVertexToInputTriangle)[i] = indexMapToFullTriangleSet[(*outputVertexToInputTriangle)[i]]; } } void PxTetMaker::remeshTriangleMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices, PxU32 gridResolution, PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxArray<PxU32> *vertexMap) { Ext::Remesher rm; rm.remesh(inputVertices, inputIndices, gridResolution, vertexMap); rm.readBack(outputVertices, outputIndices); } void PxTetMaker::remeshTriangleMesh(const PxVec3* inputVertices, PxU32 nbVertices, const PxU32* inputIndices, PxU32 nbIndices, PxU32 gridResolution, PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxArray<PxU32> *vertexMap) { Ext::Remesher rm; rm.remesh(inputVertices, nbVertices, inputIndices, nbIndices, gridResolution, vertexMap); rm.readBack(outputVertices, outputIndices); } void PxTetMaker::createTreeBasedTetrahedralMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices, bool useTreeNodes, PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxReal volumeThreshold) { Ext::OctreeTetrahedralizer ot; ot.createTetMesh(inputVertices, inputIndices, useTreeNodes); ot.readBack(outputVertices, outputIndices); if (volumeThreshold > 0.0f) removeSmallVolumeTetrahedra(outputVertices, outputIndices, volumeThreshold); PxU32 numRemoveAtEnd = Ext::removeDisconnectedIslands(reinterpret_cast<PxI32*>(outputIndices.begin()), outputIndices.size() / 4); if (numRemoveAtEnd > 0) outputIndices.removeRange(outputIndices.size() - 4 * numRemoveAtEnd, 4 * numRemoveAtEnd); removeUnusedVertices(outputVertices, outputIndices, inputVertices.size()); } void PxTetMaker::createRelaxedVoxelTetrahedralMesh(const PxArray<PxVec3>& inputVertices, const PxArray<PxU32>&inputIndices, PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputIndices, PxI32 resolution, PxI32 numRelaxationIters, PxF32 relMinTetVolume) { Ext::VoxelTetrahedralizer vt; vt.createTetMesh(inputVertices, inputIndices, resolution, numRelaxationIters, relMinTetVolume); vt.readBack(outputVertices, outputIndices); }
14,404
C++
36.415584
250
0.752152
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRevoluteJoint.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 "ExtRevoluteJoint.h" #include "ExtConstraintHelper.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; RevoluteJoint::RevoluteJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : RevoluteJointT(PxJointConcreteType::eREVOLUTE, actor0, localFrame0, actor1, localFrame1, "RevoluteJointData") { RevoluteJointData* data = static_cast<RevoluteJointData*>(mData); data->driveForceLimit = PX_MAX_F32; data->driveVelocity = 0.0f; data->driveGearRatio = 1.0f; data->limit = PxJointAngularLimitPair(-PxPi/2, PxPi/2); data->jointFlags = PxRevoluteJointFlags(); } PxReal RevoluteJoint::getAngle() const { return getTwistAngle_Internal(); } PxReal RevoluteJoint::getVelocity() const { return getRelativeAngularVelocity().magnitude(); } PxJointAngularLimitPair RevoluteJoint::getLimit() const { return data().limit; } void RevoluteJoint::setLimit(const PxJointAngularLimitPair& limit) { PX_CHECK_AND_RETURN(limit.isValid(), "PxRevoluteJoint::setLimit: limit invalid"); PX_CHECK_AND_RETURN(limit.lower>-PxTwoPi && limit.upper<PxTwoPi , "PxRevoluteJoint::twist limit must be strictly between -2*PI and 2*PI"); data().limit = limit; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxRevoluteJoint& j = static_cast<PxRevoluteJoint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitLower, j, limit.lower) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitUpper, j, limit.upper) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitRestitution, j, limit.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitBounceThreshold, j, limit.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitStiffness, j, limit.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitDamping, j, limit.damping) OMNI_PVD_WRITE_SCOPE_END #endif } PxReal RevoluteJoint::getDriveVelocity() const { return data().driveVelocity; } void RevoluteJoint::setDriveVelocity(PxReal velocity, bool autowake) { PX_CHECK_AND_RETURN(PxIsFinite(velocity), "PxRevoluteJoint::setDriveVelocity: invalid parameter"); data().driveVelocity = velocity; if(autowake) wakeUpActors(); markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveVelocity, static_cast<PxRevoluteJoint&>(*this), velocity) } PxReal RevoluteJoint::getDriveForceLimit() const { return data().driveForceLimit; } void RevoluteJoint::setDriveForceLimit(PxReal forceLimit) { PX_CHECK_AND_RETURN(PxIsFinite(forceLimit), "PxRevoluteJoint::setDriveForceLimit: invalid parameter"); data().driveForceLimit = forceLimit; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveForceLimit, static_cast<PxRevoluteJoint&>(*this), forceLimit) } PxReal RevoluteJoint::getDriveGearRatio() const { return data().driveGearRatio; } void RevoluteJoint::setDriveGearRatio(PxReal gearRatio) { PX_CHECK_AND_RETURN(PxIsFinite(gearRatio) && gearRatio>0, "PxRevoluteJoint::setDriveGearRatio: invalid parameter"); data().driveGearRatio = gearRatio; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveGearRatio, static_cast<PxRevoluteJoint&>(*this), gearRatio) } PxRevoluteJointFlags RevoluteJoint::getRevoluteJointFlags(void) const { return data().jointFlags; } void RevoluteJoint::setRevoluteJointFlags(PxRevoluteJointFlags flags) { data().jointFlags = flags; OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, jointFlags, static_cast<PxRevoluteJoint&>(*this), flags) } void RevoluteJoint::setRevoluteJointFlag(PxRevoluteJointFlag::Enum flag, bool value) { if(value) data().jointFlags |= flag; else data().jointFlags &= ~flag; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, jointFlags, static_cast<PxRevoluteJoint&>(*this), getRevoluteJointFlags()) } static PxQuat computeTwist(const PxTransform& cA2w, const PxTransform& cB2w) { // PT: following code is the same as this part of the "getAngle" function: // const PxQuat q = getRelativeTransform().q; // PxQuat swing, twist; // PxSeparateSwingTwist(q, swing, twist); // But it's done a little bit more efficiently since we don't need the swing quat. // PT: rotation part of "const PxTransform cB2cA = cA2w.transformInv(cB2w);" const PxQuat cB2cAq = cA2w.q.getConjugate() * cB2w.q; // PT: twist part of "PxSeparateSwingTwist(cB2cAq,swing,twist)" (more or less) return PxQuat(cB2cAq.x, 0.0f, 0.0f, cB2cAq.w); } // PT: this version is similar to the "getAngle" function, but the twist is computed slightly differently. static PX_FORCE_INLINE PxReal computePhi(const PxTransform& cA2w, const PxTransform& cB2w) { PxQuat twist = computeTwist(cA2w, cB2w); twist.normalize(); PxReal angle = twist.getAngle(); if(twist.x<0.0f) angle = -angle; return angle; } static void RevoluteJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { const RevoluteJointData& data = *reinterpret_cast<const RevoluteJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) viz.visualizeJointFrames(cA2w, cB2w); if((data.jointFlags & PxRevoluteJointFlag::eLIMIT_ENABLED) && (flags & PxConstraintVisualizationFlag::eLIMITS)) viz.visualizeAngularLimit(cA2w, data.limit.lower, data.limit.upper); } //TAG:solverprepshader static PxU32 RevoluteJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool useExtendedLimits, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const RevoluteJointData& data = *reinterpret_cast<const RevoluteJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); const PxJointAngularLimitPair& limit = data.limit; const bool limitEnabled = data.jointFlags & PxRevoluteJointFlag::eLIMIT_ENABLED; const bool limitIsLocked = limitEnabled && limit.lower >= limit.upper; // PT: it is a mistake to use the neighborhood operator since it // prevents us from using the quat's double-cover feature. if(!useExtendedLimits) joint::applyNeighborhoodOperator(cA2w, cB2w); PxVec3 ra, rb, axis; ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, PxU32(limitIsLocked ? 7 : 6), ra, rb, &axis); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; if(limitIsLocked) return ch.getCount(); if(data.jointFlags & PxRevoluteJointFlag::eDRIVE_ENABLED) { Px1DConstraint* c = ch.getConstraintRow(); c->solveHint = PxConstraintSolveHint::eNONE; c->linear0 = PxVec3(0.0f); c->angular0 = -axis; c->linear1 = PxVec3(0.0f); c->angular1 = -axis * data.driveGearRatio; c->velocityTarget = data.driveVelocity; c->minImpulse = -data.driveForceLimit; c->maxImpulse = data.driveForceLimit; c->flags |= Px1DConstraintFlag::eANGULAR_CONSTRAINT; if(data.jointFlags & PxRevoluteJointFlag::eDRIVE_FREESPIN) { if(data.driveVelocity > 0.0f) c->minImpulse = 0.0f; if(data.driveVelocity < 0.0f) c->maxImpulse = 0.0f; } c->flags |= Px1DConstraintFlag::eHAS_DRIVE_LIMIT; } if(limitEnabled) { const PxReal phi = computePhi(cA2w, cB2w); ch.anglePair(phi, data.limit.lower, data.limit.upper, axis, limit); } return ch.getCount(); } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gRevoluteJointShaders = { RevoluteJointSolverPrep, RevoluteJointVisualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep RevoluteJoint::getPrep() const { return gRevoluteJointShaders.solverPrep; } // PT: for tests / benchmarks PxConstraintSolverPrep getRevoluteJointPrep() { return gRevoluteJointShaders.solverPrep; } PxRevoluteJoint* physx::PxRevoluteJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxRevoluteJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxRevoluteJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxRevoluteJointCreate: actors must be different"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxRevoluteJointCreate: at least one actor must be dynamic"); return createJointT<RevoluteJoint, RevoluteJointData>(physics, actor0, localFrame0, actor1, localFrame1, gRevoluteJointShaders); } // PX_SERIALIZATION void RevoluteJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gRevoluteJointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD void RevoluteJoint::updateOmniPvdProperties() const { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxRevoluteJoint& j = static_cast<const PxRevoluteJoint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, angle, j, getAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, velocity, j, getVelocity()) OMNI_PVD_WRITE_SCOPE_END } template<> void physx::Ext::omniPvdInitJoint<RevoluteJoint>(RevoluteJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxRevoluteJoint& j = static_cast<PxRevoluteJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eREVOLUTE); PxJointAngularLimitPair limit = joint.getLimit(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitLower, j, limit.lower) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitUpper, j, limit.upper) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitRestitution, j, limit.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitBounceThreshold, j, limit.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitStiffness, j, limit.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, limitDamping, j, limit.damping) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveVelocity, j, joint.getDriveVelocity()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveForceLimit, j, joint.getDriveForceLimit()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, driveGearRatio, j, joint.getDriveGearRatio()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, jointFlags, j, joint.getRevoluteJointFlags()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, angle, j, joint.getAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRevoluteJoint, velocity, j, joint.getVelocity()) OMNI_PVD_WRITE_SCOPE_END } #endif
13,481
C++
40.103658
175
0.768563
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSharedQueueEntryPool.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 EXT_SHARED_QUEUE_ENTRY_POOL_H #define EXT_SHARED_QUEUE_ENTRY_POOL_H #include "foundation/PxAllocator.h" #include "foundation/PxArray.h" #include "foundation/PxSList.h" namespace physx { namespace Ext { class SharedQueueEntry : public PxSListEntry { public: SharedQueueEntry(void* objectRef) : mObjectRef(objectRef), mPooledEntry(false) {} SharedQueueEntry() : mObjectRef(NULL), mPooledEntry(true) {} public: void* mObjectRef; bool mPooledEntry; // True if the entry was preallocated in a pool }; #if PX_VC #pragma warning(push) #pragma warning(disable:4324) // Padding was added at the end of a structure because of a __declspec(align) value. #endif // Because of the SList member I assume*/ template<class Alloc = typename PxAllocatorTraits<SharedQueueEntry>::Type > class SharedQueueEntryPool : private Alloc { public: SharedQueueEntryPool(PxU32 poolSize, const Alloc& alloc = Alloc("SharedQueueEntryPool")); ~SharedQueueEntryPool(); SharedQueueEntry* getEntry(void* objectRef); void putEntry(SharedQueueEntry& entry); private: SharedQueueEntry* mTaskEntryPool; PxSList mTaskEntryPtrPool; }; #if PX_VC #pragma warning(pop) #endif template <class Alloc> SharedQueueEntryPool<Alloc>::SharedQueueEntryPool(PxU32 poolSize, const Alloc& alloc) : Alloc(alloc) { PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc("SharedQueueEntryPool"); mTaskEntryPool = poolSize ? reinterpret_cast<SharedQueueEntry*>(alignedAlloc.allocate(sizeof(SharedQueueEntry) * poolSize, PX_FL)) : NULL; if (mTaskEntryPool) { for(PxU32 i=0; i < poolSize; i++) { PX_ASSERT((size_t(&mTaskEntryPool[i]) & (PX_SLIST_ALIGNMENT-1)) == 0); // The SList entry must be aligned according to PX_SLIST_ALIGNMENT PX_PLACEMENT_NEW(&mTaskEntryPool[i], SharedQueueEntry)(); PX_ASSERT(mTaskEntryPool[i].mPooledEntry == true); mTaskEntryPtrPool.push(mTaskEntryPool[i]); } } } template <class Alloc> SharedQueueEntryPool<Alloc>::~SharedQueueEntryPool() { if (mTaskEntryPool) { PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc("SharedQueueEntryPool"); alignedAlloc.deallocate(mTaskEntryPool); } } template <class Alloc> SharedQueueEntry* SharedQueueEntryPool<Alloc>::getEntry(void* objectRef) { SharedQueueEntry* e = static_cast<SharedQueueEntry*>(mTaskEntryPtrPool.pop()); if (e) { PX_ASSERT(e->mPooledEntry == true); e->mObjectRef = objectRef; return e; } else { PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc; e = reinterpret_cast<SharedQueueEntry*>(alignedAlloc.allocate(sizeof(SharedQueueEntry), PX_FL)); if (e) { PX_PLACEMENT_NEW(e, SharedQueueEntry)(objectRef); PX_ASSERT(e->mPooledEntry == false); } return e; } } template <class Alloc> void SharedQueueEntryPool<Alloc>::putEntry(SharedQueueEntry& entry) { if (entry.mPooledEntry) { entry.mObjectRef = NULL; mTaskEntryPtrPool.push(entry); } else { PxAlignedAllocator<PX_SLIST_ALIGNMENT, Alloc> alignedAlloc; alignedAlloc.deallocate(&entry); } } } // namespace Ext } // namespace physx #endif
4,780
C
30.453947
141
0.748954
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqQuery.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 EXT_SQ_QUERY_H #define EXT_SQ_QUERY_H #include "foundation/PxSimpleTypes.h" #include "geometry/PxGeometryQueryFlags.h" #include "ExtSqManager.h" #include "PxQueryReport.h" #include "GuCachedFuncs.h" namespace physx { class PxGeometry; struct PxQueryFilterData; struct PxFilterData; class PxQueryFilterCallback; namespace Sq { struct ExtMultiQueryInput; class ExtPVDCapture { public: ExtPVDCapture() {} virtual ~ExtPVDCapture() {} virtual bool transmitSceneQueries() = 0; virtual void raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) = 0; virtual void sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits) = 0; virtual void overlap(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData) = 0; }; // SceneQueries-level adapter. Augments the PrunerManager-level adapter with functions needed to perform queries. class ExtQueryAdapter : public Adapter { public: ExtQueryAdapter() {} virtual ~ExtQueryAdapter() {} // PT: TODO: decouple from PxQueryCache? virtual Gu::PrunerHandle findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const = 0; // PT: TODO: return reference? but this version is at least consistent with getActorShape virtual void getFilterData(const Gu::PrunerPayload& payload, PxFilterData& filterData) const = 0; virtual void getActorShape(const Gu::PrunerPayload& payload, PxActorShape& actorShape) const = 0; // PT: new for this customized version: a function to perform per-pruner filtering virtual bool processPruner(PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const = 0; }; } // PT: this is a customized version of physx::Sq::SceneQueries that supports more than 2 hardcoded pruners. // It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners. class ExtSceneQueries { PX_NOCOPY(ExtSceneQueries) public: ExtSceneQueries(Sq::ExtPVDCapture* pvd, PxU64 contextID, float inflation, const Sq::ExtQueryAdapter& adapter, bool usesTreeOfPruners); ~ExtSceneQueries(); PX_FORCE_INLINE Sq::ExtPrunerManager& getPrunerManagerFast() { return mSQManager; } PX_FORCE_INLINE const Sq::ExtPrunerManager& getPrunerManagerFast() const { return mSQManager; } template<typename QueryHit> bool multiQuery( const Sq::ExtMultiQueryInput& in, PxHitCallback<QueryHit>& hits, PxHitFlags hitFlags, const PxQueryCache*, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const; bool _raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, // Ray data PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; bool _sweep( const PxGeometry& geometry, const PxTransform& pose, // GeomObject data const PxVec3& unitDir, const PxReal distance, // Ray data PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const; bool _overlap( const PxGeometry& geometry, const PxTransform& transform, // GeomObject data PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; PX_FORCE_INLINE PxU64 getContextId() const { return mSQManager.getContextId(); } Sq::ExtPrunerManager mSQManager; public: Gu::CachedFuncs mCachedFuncs; Sq::ExtPVDCapture* mPVD; }; #if PX_SUPPORT_EXTERN_TEMPLATE //explicit template instantiation declaration extern template bool ExtSceneQueries::multiQuery<PxRaycastHit>(const Sq::ExtMultiQueryInput&, PxHitCallback<PxRaycastHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; extern template bool ExtSceneQueries::multiQuery<PxOverlapHit>(const Sq::ExtMultiQueryInput&, PxHitCallback<PxOverlapHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; extern template bool ExtSceneQueries::multiQuery<PxSweepHit>(const Sq::ExtMultiQueryInput&, PxHitCallback<PxSweepHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; #endif } #endif
6,787
C
46.468531
212
0.741565
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtFixedJoint.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 "ExtFixedJoint.h" #include "ExtConstraintHelper.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; FixedJoint::FixedJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : FixedJointT(PxJointConcreteType::eFIXED, actor0, localFrame0, actor1, localFrame1, "FixedJointData") { // FixedJointData* data = static_cast<FixedJointData*>(mData); } static void FixedJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) { const FixedJointData& data = *reinterpret_cast<const FixedJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); viz.visualizeJointFrames(cA2w, cB2w); } } //TAG:solverprepshader static PxU32 FixedJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const FixedJointData& data = *reinterpret_cast<const FixedJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); joint::applyNeighborhoodOperator(cA2w, cB2w); PxVec3 ra, rb; ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, 7, ra, rb); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; return ch.getCount(); } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gFixedJointShaders = { FixedJointSolverPrep, FixedJointVisualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep FixedJoint::getPrep() const { return gFixedJointShaders.solverPrep; } PxFixedJoint* physx::PxFixedJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxFixedJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxFixedJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxFixedJointCreate: at least one actor must be dynamic"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxFixedJointCreate: actors must be different"); return createJointT<FixedJoint, FixedJointData>(physics, actor0, localFrame0, actor1, localFrame1, gFixedJointShaders); } // PX_SERIALIZATION void FixedJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gFixedJointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD template<> void physx::Ext::omniPvdInitJoint<FixedJoint>(FixedJoint& joint) { PxFixedJoint& j = static_cast<PxFixedJoint&>(joint); OMNI_PVD_CREATE(OMNI_PVD_CONTEXT_HANDLE, PxFixedJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eFIXED); } #endif
5,026
C++
42.713043
170
0.764823
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtDefaultStreams.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/PxAssert.h" #include "foundation/PxAllocatorCallback.h" #include "foundation/PxMemory.h" #include "foundation/PxBitUtils.h" #include "extensions/PxDefaultStreams.h" #include "SnFile.h" #include "foundation/PxUtilities.h" #include <errno.h> using namespace physx; PxDefaultMemoryOutputStream::PxDefaultMemoryOutputStream(PxAllocatorCallback &allocator) : mAllocator (allocator) , mData (NULL) , mSize (0) , mCapacity (0) { } PxDefaultMemoryOutputStream::~PxDefaultMemoryOutputStream() { if(mData) mAllocator.deallocate(mData); } PxU32 PxDefaultMemoryOutputStream::write(const void* src, PxU32 size) { PxU32 expectedSize = mSize + size; if(expectedSize > mCapacity) { mCapacity = PxMax(PxNextPowerOfTwo(expectedSize), 4096u); PxU8* newData = reinterpret_cast<PxU8*>(mAllocator.allocate(mCapacity,"PxDefaultMemoryOutputStream",__FILE__,__LINE__)); PX_ASSERT(newData!=NULL); PxMemCopy(newData, mData, mSize); if(mData) mAllocator.deallocate(mData); mData = newData; } PxMemCopy(mData+mSize, src, size); mSize += size; return size; } /////////////////////////////////////////////////////////////////////////////// PxDefaultMemoryInputData::PxDefaultMemoryInputData(PxU8* data, PxU32 length) : mSize (length), mData (data), mPos (0) { } PxU32 PxDefaultMemoryInputData::read(void* dest, PxU32 count) { PxU32 length = PxMin<PxU32>(count, mSize-mPos); PxMemCopy(dest, mData+mPos, length); mPos += length; return length; } PxU32 PxDefaultMemoryInputData::getLength() const { return mSize; } void PxDefaultMemoryInputData::seek(PxU32 offset) { mPos = PxMin<PxU32>(mSize, offset); } PxU32 PxDefaultMemoryInputData::tell() const { return mPos; } PxDefaultFileOutputStream::PxDefaultFileOutputStream(const char* filename) { mFile = NULL; sn::fopen_s(&mFile, filename, "wb"); // PT: when this fails, check that: // - the path is correct // - the file does not already exist. If it does, check that it is not write protected. if(NULL == mFile) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Unable to open file %s, errno 0x%x\n",filename,errno); } PX_ASSERT(mFile); } PxDefaultFileOutputStream::~PxDefaultFileOutputStream() { if(mFile) fclose(mFile); mFile = NULL; } PxU32 PxDefaultFileOutputStream::write(const void* src, PxU32 count) { return mFile ? PxU32(fwrite(src, 1, count, mFile)) : 0; } bool PxDefaultFileOutputStream::isValid() { return mFile != NULL; } /////////////////////////////////////////////////////////////////////////////// PxDefaultFileInputData::PxDefaultFileInputData(const char* filename) { mFile = NULL; sn::fopen_s(&mFile, filename, "rb"); if(mFile) { fseek(mFile, 0, SEEK_END); mLength = PxU32(ftell(mFile)); fseek(mFile, 0, SEEK_SET); } else { mLength = 0; } } PxDefaultFileInputData::~PxDefaultFileInputData() { if(mFile) fclose(mFile); } PxU32 PxDefaultFileInputData::read(void* dest, PxU32 count) { PX_ASSERT(mFile); const size_t size = fread(dest, 1, count, mFile); // there should be no assert here since by spec of PxInputStream we can read fewer bytes than expected return PxU32(size); } PxU32 PxDefaultFileInputData::getLength() const { return mLength; } void PxDefaultFileInputData::seek(PxU32 pos) { fseek(mFile, long(pos), SEEK_SET); } PxU32 PxDefaultFileInputData::tell() const { return PxU32(ftell(mFile)); } bool PxDefaultFileInputData::isValid() const { return mFile != NULL; }
5,195
C++
25.783505
122
0.719346
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSceneQuerySystem.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 "extensions/PxSceneQuerySystemExt.h" #include "extensions/PxShapeExt.h" #include "foundation/PxAlloca.h" #include "foundation/PxHashMap.h" #include "foundation/PxUserAllocated.h" #include "geometry/PxBVH.h" #include "GuActorShapeMap.h" #include "SqQuery.h" #include "SqFactory.h" #include "PxRigidActor.h" #include "PxPruningStructure.h" #include "PxSceneDesc.h" // PT: for PxSceneLimits TODO: remove // PT: this file re-implements a scene-queries system for PxScene inside PxExtensions. All SQ-related calls from the PxScene API // will be re-routed to this class. This version re-uses the same internal code as PhysX (most notably from SqQuery.h) so there is // little differences between the internal PhysX version and this one except minor implementation details like what we store in the // PrunerPayload. The whole API is available, it uses the same number of "pruners" for the queries, etc. This is a good working // starting point for users who want to start tinkering with the system without starting from scratch. using namespace physx; using namespace Sq; using namespace Gu; #define EXT_PRUNER_EPSILON 0.005f // PT: in this external implementation we'll use Px pointers instead of Np pointers in the payload. static PX_FORCE_INLINE void setPayload(PrunerPayload& pp, const PxShape* shape, const PxRigidActor* actor) { pp.data[0] = size_t(shape); pp.data[1] = size_t(actor); } static PX_FORCE_INLINE PxShape* getShapeFromPayload(const PrunerPayload& payload) { return reinterpret_cast<PxShape*>(payload.data[0]); } static PX_FORCE_INLINE PxRigidActor* getActorFromPayload(const PrunerPayload& payload) { return reinterpret_cast<PxRigidActor*>(payload.data[1]); } static PX_FORCE_INLINE bool isDynamicActor(const PxRigidActor& actor) { const PxType actorType = actor.getConcreteType(); return actorType != PxConcreteType::eRIGID_STATIC; } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE ActorShapeData createActorShapeData(PrunerData data, PrunerCompoundId id) { return (ActorShapeData(id) << 32) | ActorShapeData(data); } static PX_FORCE_INLINE PrunerData getPrunerData(ActorShapeData data) { return PrunerData(data); } static PX_FORCE_INLINE PrunerCompoundId getCompoundID(ActorShapeData data) { return PrunerCompoundId(data >> 32); } /////////////////////////////////////////////////////////////////////////////// namespace { class ExtSqAdapter : public QueryAdapter { public: ExtSqAdapter() {} virtual ~ExtSqAdapter() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter // QueryAdapter virtual PrunerHandle findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const; virtual void getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const; virtual void getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const; //~QueryAdapter ActorShapeMap mDatabase; }; } const PxGeometry& ExtSqAdapter::getGeometry(const PrunerPayload& payload) const { PxShape* shape = getShapeFromPayload(payload); return shape->getGeometry(); } PrunerHandle ExtSqAdapter::findPrunerHandle(const PxQueryCache& cache, PrunerCompoundId& compoundId, PxU32& prunerIndex) const { const PxU32 actorIndex = cache.actor->getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); const ActorShapeData actorShapeData = mDatabase.find(actorIndex, cache.actor, cache.shape); const PrunerData prunerData = getPrunerData(actorShapeData); compoundId = getCompoundID(actorShapeData); prunerIndex = getPrunerIndex(prunerData); return getPrunerHandle(prunerData); } void ExtSqAdapter::getFilterData(const PrunerPayload& payload, PxFilterData& filterData) const { PxShape* shape = getShapeFromPayload(payload); filterData = shape->getQueryFilterData(); } void ExtSqAdapter::getActorShape(const PrunerPayload& payload, PxActorShape& actorShape) const { actorShape.actor = getActorFromPayload(payload); actorShape.shape = getShapeFromPayload(payload); } /////////////////////////////////////////////////////////////////////////////// namespace { class ExternalPxSQ : public PxSceneQuerySystem, public PxUserAllocated { public: ExternalPxSQ(PVDCapture* pvd, PxU64 contextID, Pruner* staticPruner, Pruner* dynamicPruner, PxU32 dynamicTreeRebuildRateHint, PxSceneQueryUpdateMode::Enum mode, const PxSceneLimits& limits) : mQueries (pvd, contextID, staticPruner, dynamicPruner, dynamicTreeRebuildRateHint, EXT_PRUNER_EPSILON, limits, mExtAdapter), mUpdateMode (mode), mRefCount (1) {} virtual ~ExternalPxSQ() {} virtual void release(); virtual void acquireReference(); virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) { SQ().preallocate(prunerIndex, nbShapes); } virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure); virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape); virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform); virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& pxbvh, const PxTransform* transforms); virtual void removeSQCompound(PxSQCompoundHandle compoundHandle); virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform); virtual void flushUpdates() { SQ().flushUpdates(); } virtual void flushMemory() { SQ().flushMemory(); } virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const { SQ().visualize(prunerIndex, out); } virtual void shiftOrigin(const PxVec3& shift) { SQ().shiftOrigin(shift); } virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex); virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle); virtual void finalizeUpdates(); virtual void setDynamicTreeRebuildRateHint(PxU32 dynTreeRebuildRateHint) { SQ().setDynamicTreeRebuildRateHint(dynTreeRebuildRateHint); } virtual PxU32 getDynamicTreeRebuildRateHint() const { return SQ().getDynamicTreeRebuildRateHint(); } virtual void forceRebuildDynamicTree(PxU32 prunerIndex) { SQ().forceRebuildDynamicTree(prunerIndex); } virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const { return mUpdateMode; } virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum mode) { mUpdateMode = mode; } virtual PxU32 getStaticTimestamp() const { return SQ().getStaticTimestamp(); } virtual void merge(const PxPruningStructure& pxps); virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const; virtual bool overlap(const PxGeometry& geometry, const PxTransform& transform, PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const; virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices); PX_FORCE_INLINE PrunerManager& SQ() { return mQueries.mSQManager; } PX_FORCE_INLINE const PrunerManager& SQ() const { return mQueries.mSQManager; } ExtSqAdapter mExtAdapter; SceneQueries mQueries; PxSceneQueryUpdateMode::Enum mUpdateMode; PxU32 mRefCount; }; } /////////////////////////////////////////////////////////////////////////////// void addExternalSQ(PxSceneQuerySystem* added); void removeExternalSQ(PxSceneQuerySystem* removed); void ExternalPxSQ::release() { mRefCount--; if(!mRefCount) { removeExternalSQ(this); PX_DELETE_THIS; } } void ExternalPxSQ::acquireReference() { mRefCount++; } void ExternalPxSQ::addSQShape(const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds, const PxTransform& transform, const PxSQCompoundHandle* compoundHandle, bool hasPruningStructure) { PrunerPayload payload; setPayload(payload, &shape, &actor); const PrunerCompoundId cid = compoundHandle ? PrunerCompoundId(*compoundHandle) : INVALID_COMPOUND_ID; const PrunerData prunerData = SQ().addPrunerShape(payload, isDynamicActor(actor), cid, bounds, transform, hasPruningStructure); const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); mExtAdapter.mDatabase.add(actorIndex, &actor, &shape, createActorShapeData(prunerData, cid)); } namespace { struct DatabaseCleaner : PrunerPayloadRemovalCallback { DatabaseCleaner(ExtSqAdapter& adapter) : mAdapter(adapter){} virtual void invoke(PxU32 nbRemoved, const PrunerPayload* removed) { PxU32 actorIndex = 0xffffffff; const PxRigidActor* cachedActor = NULL; while(nbRemoved--) { const PrunerPayload& payload = *removed++; const PxRigidActor* actor = getActorFromPayload(payload); if(actor!=cachedActor) { actorIndex = actor->getInternalActorIndex(); cachedActor = actor; } PX_ASSERT(actorIndex!=0xffffffff); bool status = mAdapter.mDatabase.remove(actorIndex, actor, getShapeFromPayload(payload), NULL); PX_ASSERT(status); PX_UNUSED(status); } } ExtSqAdapter& mAdapter; PX_NOCOPY(DatabaseCleaner) }; } void ExternalPxSQ::removeSQShape(const PxRigidActor& actor, const PxShape& shape) { const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); ActorShapeData actorShapeData; mExtAdapter.mDatabase.remove(actorIndex, &actor, &shape, &actorShapeData); const PrunerData data = getPrunerData(actorShapeData); const PrunerCompoundId compoundId = getCompoundID(actorShapeData); SQ().removePrunerShape(compoundId, data, NULL); } void ExternalPxSQ::updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) { const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); const ActorShapeData actorShapeData = mExtAdapter.mDatabase.find(actorIndex, &actor, &shape); const PrunerData shapeHandle = getPrunerData(actorShapeData); const PrunerCompoundId cid = getCompoundID(actorShapeData); SQ().markForUpdate(cid, shapeHandle, transform); } PxSQCompoundHandle ExternalPxSQ::addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms) { const PxU32 numSqShapes = bvh.getNbBounds(); PX_ALLOCA(payloads, PrunerPayload, numSqShapes); for(PxU32 i=0; i<numSqShapes; i++) setPayload(payloads[i], shapes[i], &actor); const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); PX_ALLOCA(shapeHandles, PrunerData, numSqShapes); SQ().addCompoundShape(bvh, actorIndex, actor.getGlobalPose(), shapeHandles, payloads, transforms, isDynamicActor(actor)); for(PxU32 i=0; i<numSqShapes; i++) { // PT: TODO: actorIndex is now redundant! mExtAdapter.mDatabase.add(actorIndex, &actor, shapes[i], createActorShapeData(shapeHandles[i], actorIndex)); } return PxSQCompoundHandle(actorIndex); } void ExternalPxSQ::removeSQCompound(PxSQCompoundHandle compoundHandle) { DatabaseCleaner cleaner(mExtAdapter); SQ().removeCompoundActor(PrunerCompoundId(compoundHandle), &cleaner); } void ExternalPxSQ::updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) { SQ().updateCompoundActor(PrunerCompoundId(compoundHandle), compoundTransform); } PxSQBuildStepHandle ExternalPxSQ::prepareSceneQueryBuildStep(PxU32 prunerIndex) { return SQ().prepareSceneQueriesUpdate(PruningIndex::Enum(prunerIndex)); } void ExternalPxSQ::sceneQueryBuildStep(PxSQBuildStepHandle handle) { SQ().sceneQueryBuildStep(handle); } void ExternalPxSQ::finalizeUpdates() { switch(mUpdateMode) { case PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED: SQ().afterSync(true, true); break; case PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED: SQ().afterSync(true, false); break; case PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED: SQ().afterSync(false, false); break; } } void ExternalPxSQ::merge(const PxPruningStructure& pxps) { Pruner* staticPruner = SQ().getPruner(PruningIndex::eSTATIC); if(staticPruner) staticPruner->merge(pxps.getStaticMergeData()); Pruner* dynamicPruner = SQ().getPruner(PruningIndex::eDYNAMIC); if(dynamicPruner) dynamicPruner->merge(pxps.getDynamicMergeData()); } bool ExternalPxSQ::raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxRaycastCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { return mQueries._raycast(origin, unitDir, distance, hitCall, hitFlags, filterData, filterCall, cache, flags); } bool ExternalPxSQ::sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxSweepCallback& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const { return mQueries._sweep(geometry, pose, unitDir, distance, hitCall, hitFlags, filterData, filterCall, cache, inflation, flags); } bool ExternalPxSQ::overlap( const PxGeometry& geometry, const PxTransform& transform, PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { return mQueries._overlap( geometry, transform, hitCall, filterData, filterCall, cache, flags); } PxSQPrunerHandle ExternalPxSQ::getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const { const PxU32 actorIndex = actor.getInternalActorIndex(); PX_ASSERT(actorIndex!=0xffffffff); const ActorShapeData actorShapeData = mExtAdapter.mDatabase.find(actorIndex, &actor, &shape); const PrunerData prunerData = getPrunerData(actorShapeData); prunerIndex = getPrunerIndex(prunerData); return PxSQPrunerHandle(getPrunerHandle(prunerData)); } void ExternalPxSQ::sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) { PX_ASSERT(prunerIndex==PruningIndex::eDYNAMIC); if(prunerIndex==PruningIndex::eDYNAMIC) SQ().sync(handles, indices, bounds, transforms, count, ignoredIndices); } /////////////////////////////////////////////////////////////////////////////// static CompanionPrunerType getCompanionType(PxDynamicTreeSecondaryPruner::Enum type) { switch(type) { case PxDynamicTreeSecondaryPruner::eNONE: return COMPANION_PRUNER_NONE; case PxDynamicTreeSecondaryPruner::eBUCKET: return COMPANION_PRUNER_BUCKET; case PxDynamicTreeSecondaryPruner::eINCREMENTAL: return COMPANION_PRUNER_INCREMENTAL; case PxDynamicTreeSecondaryPruner::eBVH: return COMPANION_PRUNER_AABB_TREE; case PxDynamicTreeSecondaryPruner::eLAST: return COMPANION_PRUNER_NONE; } return COMPANION_PRUNER_NONE; } static BVHBuildStrategy getBuildStrategy(PxBVHBuildStrategy::Enum bs) { switch(bs) { case PxBVHBuildStrategy::eFAST: return BVH_SPLATTER_POINTS; case PxBVHBuildStrategy::eDEFAULT: return BVH_SPLATTER_POINTS_SPLIT_GEOM_CENTER; case PxBVHBuildStrategy::eSAH: return BVH_SAH; case PxBVHBuildStrategy::eLAST: return BVH_SPLATTER_POINTS; } return BVH_SPLATTER_POINTS; } static Pruner* create(PxPruningStructureType::Enum type, PxU64 contextID, PxDynamicTreeSecondaryPruner::Enum secondaryType, PxBVHBuildStrategy::Enum buildStrategy, PxU32 nbObjectsPerNode) { // if(0) // return createIncrementalPruner(contextID); const CompanionPrunerType cpType = getCompanionType(secondaryType); const BVHBuildStrategy bs = getBuildStrategy(buildStrategy); Pruner* pruner = NULL; switch(type) { case PxPruningStructureType::eNONE: { pruner = createBucketPruner(contextID); break; } case PxPruningStructureType::eDYNAMIC_AABB_TREE: { pruner = createAABBPruner(contextID, true, cpType, bs, nbObjectsPerNode); break; } case PxPruningStructureType::eSTATIC_AABB_TREE: { pruner = createAABBPruner(contextID, false, cpType, bs, nbObjectsPerNode); break; } case PxPruningStructureType::eLAST: break; } return pruner; } PxSceneQuerySystem* physx::PxCreateExternalSceneQuerySystem(const PxSceneQueryDesc& desc, PxU64 contextID) { PVDCapture* pvd = NULL; Pruner* staticPruner = create(desc.staticStructure, contextID, desc.dynamicTreeSecondaryPruner, desc.staticBVHBuildStrategy, desc.staticNbObjectsPerNode); Pruner* dynamicPruner = create(desc.dynamicStructure, contextID, desc.dynamicTreeSecondaryPruner, desc.dynamicBVHBuildStrategy, desc.dynamicNbObjectsPerNode); ExternalPxSQ* pxsq = PX_NEW(ExternalPxSQ)(pvd, contextID, staticPruner, dynamicPruner, desc.dynamicTreeRebuildRateHint, desc.sceneQueryUpdateMode, PxSceneLimits()); addExternalSQ(pxsq); return pxsq; }
20,079
C++
41.723404
201
0.744459
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtJoint.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 EXT_JOINT_H #define EXT_JOINT_H #include "PxPhysics.h" #include "extensions/PxConstraintExt.h" #include "PxRigidStatic.h" #include "PxRigidDynamic.h" #include "PxArticulationLink.h" #include "PxArticulationReducedCoordinate.h" #include "PxScene.h" #include "foundation/PxAllocator.h" #include "foundation/PxMathUtils.h" #include "CmUtils.h" #include "ExtJointData.h" #if PX_SUPPORT_PVD #include "pvd/PxPvdSceneClient.h" #include "ExtPvd.h" #include "PxPvdClient.h" #endif #include "omnipvd/ExtOmniPvdSetData.h" namespace physx { // PX_SERIALIZATION class PxDeserializationContext; PxConstraint* resolveConstraintPtr(PxDeserializationContext& v, PxConstraint* old, PxConstraintConnector* connector, PxConstraintShaderTable& shaders); // ~PX_SERIALIZATION namespace Ext { PX_FORCE_INLINE float computeSwingAngle(float swingYZ, float swingW) { return 4.0f * PxAtan2(swingYZ, 1.0f + swingW); // tan (t/2) = sin(t)/(1+cos t), so this is the quarter angle } template<class JointType, class DataType> PX_FORCE_INLINE JointType* createJointT(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1, const PxConstraintShaderTable& shaders) { JointType* j; PX_NEW_SERIALIZED(j, JointType)(physics.getTolerancesScale(), actor0, localFrame0, actor1, localFrame1); if(!physics.createConstraint(actor0, actor1, *j, shaders, sizeof(DataType))) PX_DELETE(j); #if PX_SUPPORT_OMNI_PVD if (j) { omniPvdInitJoint(*j); } #endif return j; } // PX_SERIALIZATION template<class JointType> PX_FORCE_INLINE JointType* createJointObject(PxU8*& address, PxDeserializationContext& context) { JointType* obj = PX_PLACEMENT_NEW(address, JointType(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(JointType); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION template <class Base, class DataClass, class ValueStruct> class JointT : public Base, public PxConstraintConnector, public PxUserAllocated { public: // PX_SERIALIZATION JointT(PxBaseFlags baseFlags) : Base(baseFlags) {} void exportExtraData(PxSerializationContext& stream) { if(mData) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mData, sizeof(DataClass)); } stream.writeName(mName); } void importExtraData(PxDeserializationContext& context) { if(mData) mData = context.readExtraData<DataClass, PX_SERIAL_ALIGN>(); context.readName(mName); } virtual void preExportDataReset(){} virtual void requiresObjects(PxProcessPxBaseCallback& c) { c.process(*mPxConstraint); { PxRigidActor* a0 = NULL; PxRigidActor* a1 = NULL; mPxConstraint->getActors(a0,a1); if (a0) { c.process(*a0); } if (a1) { c.process(*a1); } } } //~PX_SERIALIZATION #if PX_SUPPORT_PVD // PxConstraintConnector virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream& pvdConnection, const PxConstraint* c, PxPvdUpdateType::Enum updateType) const PX_OVERRIDE { if(updateType == PxPvdUpdateType::UPDATE_SIM_PROPERTIES) { Ext::Pvd::simUpdate<Base>(pvdConnection, *this); return true; } else if(updateType == PxPvdUpdateType::UPDATE_ALL_PROPERTIES) { Ext::Pvd::updatePvdProperties<Base, ValueStruct>(pvdConnection, *this); return true; } else if(updateType == PxPvdUpdateType::CREATE_INSTANCE) { Ext::Pvd::createPvdInstance<Base>(pvdConnection, *c, *this); return true; } else if(updateType == PxPvdUpdateType::RELEASE_INSTANCE) { Ext::Pvd::releasePvdInstance(pvdConnection, *c, *this); return true; } return false; } #else virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream&, const PxConstraint*, PxPvdUpdateType::Enum) const PX_OVERRIDE { return false; } #endif // PxConstraintConnector virtual void updateOmniPvdProperties() const PX_OVERRIDE { } // PxJoint virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) PX_OVERRIDE { //TODO SDK-DEV //You can get the debugger stream from the NpScene //Ext::Pvd::setActors( stream, this, mPxConstraint, actor0, actor1 ); PX_CHECK_AND_RETURN(actor0 != actor1, "PxJoint::setActors: actors must be different"); PX_CHECK_AND_RETURN((actor0 && !actor0->is<PxRigidStatic>()) || (actor1 && !actor1->is<PxRigidStatic>()), "PxJoint::setActors: at least one actor must be non-static"); #if PX_SUPPORT_PVD PxScene* scene = getScene(); if(scene) { //if pvd not connect data stream is NULL physx::pvdsdk::PvdDataStream* conn = scene->getScenePvdClient()->getClientInternal()->getDataStream(); if( conn != NULL ) Ext::Pvd::setActors( *conn, *this, *mPxConstraint, actor0, actor1 ); } #endif mPxConstraint->setActors(actor0, actor1); mData->c2b[0] = getCom(actor0).transformInv(mLocalPose[0]); mData->c2b[1] = getCom(actor1).transformInv(mLocalPose[1]); mPxConstraint->markDirty(); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0, static_cast<PxJoint&>(*this), actor0) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1, static_cast<PxJoint&>(*this), actor1) OMNI_PVD_WRITE_SCOPE_END } // PxJoint virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const PX_OVERRIDE { if(mPxConstraint) mPxConstraint->getActors(actor0,actor1); else { actor0 = NULL; actor1 = NULL; } } // this is the local pose relative to the actor, and we store internally the local // pose relative to the body // PxJoint virtual void setLocalPose(PxJointActorIndex::Enum actor, const PxTransform& pose) PX_OVERRIDE { PX_CHECK_AND_RETURN(pose.isSane(), "PxJoint::setLocalPose: transform is invalid"); const PxTransform p = pose.getNormalized(); mLocalPose[actor] = p; mData->c2b[actor] = getCom(actor).transformInv(p); mPxConstraint->markDirty(); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0LocalPose, static_cast<PxJoint&>(*this), mLocalPose[0]) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1LocalPose, static_cast<PxJoint&>(*this), mLocalPose[1]) OMNI_PVD_WRITE_SCOPE_END } // PxJoint virtual PxTransform getLocalPose(PxJointActorIndex::Enum actor) const PX_OVERRIDE { return mLocalPose[actor]; } static PxTransform getGlobalPose(const PxRigidActor* actor) { if(!actor) return PxTransform(PxIdentity); return actor->getGlobalPose(); } static void getActorVelocity(const PxRigidActor* actor, PxVec3& linear, PxVec3& angular) { if(!actor || actor->is<PxRigidStatic>()) { linear = angular = PxVec3(0.0f); return; } linear = static_cast<const PxRigidBody*>(actor)->getLinearVelocity(); angular = static_cast<const PxRigidBody*>(actor)->getAngularVelocity(); } // PxJoint virtual PxTransform getRelativeTransform() const PX_OVERRIDE { PxRigidActor* actor0, * actor1; mPxConstraint->getActors(actor0, actor1); const PxTransform t0 = getGlobalPose(actor0) * mLocalPose[0]; const PxTransform t1 = getGlobalPose(actor1) * mLocalPose[1]; return t0.transformInv(t1); } // PxJoint virtual PxVec3 getRelativeLinearVelocity() const PX_OVERRIDE { PxRigidActor* actor0, * actor1; PxVec3 l0, a0, l1, a1; mPxConstraint->getActors(actor0, actor1); PxTransform t0 = getCom(actor0), t1 = getCom(actor1); getActorVelocity(actor0, l0, a0); getActorVelocity(actor1, l1, a1); PxVec3 p0 = t0.q.rotate(mLocalPose[0].p), p1 = t1.q.rotate(mLocalPose[1].p); return t0.transformInv(l1 - a1.cross(p1) - l0 + a0.cross(p0)); } // PxJoint virtual PxVec3 getRelativeAngularVelocity() const PX_OVERRIDE { PxRigidActor* actor0, * actor1; PxVec3 l0, a0, l1, a1; mPxConstraint->getActors(actor0, actor1); PxTransform t0 = getCom(actor0); getActorVelocity(actor0, l0, a0); getActorVelocity(actor1, l1, a1); return t0.transformInv(a1 - a0); } // PxJoint virtual void setBreakForce(PxReal force, PxReal torque) PX_OVERRIDE { PX_CHECK_AND_RETURN(PxIsFinite(force) && PxIsFinite(torque), "PxJoint::setBreakForce: invalid float"); mPxConstraint->setBreakForce(force,torque); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakForce, static_cast<PxJoint&>(*this), force) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakTorque, static_cast<PxJoint&>(*this), torque) OMNI_PVD_WRITE_SCOPE_END } // PxJoint virtual void getBreakForce(PxReal& force, PxReal& torque) const PX_OVERRIDE { mPxConstraint->getBreakForce(force,torque); } // PxJoint virtual void setConstraintFlags(PxConstraintFlags flags) PX_OVERRIDE { mPxConstraint->setFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, constraintFlags, static_cast<PxJoint&>(*this), flags) } // PxJoint virtual void setConstraintFlag(PxConstraintFlag::Enum flag, bool value) PX_OVERRIDE { mPxConstraint->setFlag(flag, value); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, constraintFlags, static_cast<PxJoint&>(*this), getConstraintFlags()) } // PxJoint virtual PxConstraintFlags getConstraintFlags() const PX_OVERRIDE { return mPxConstraint->getFlags(); } // PxJoint virtual void setInvMassScale0(PxReal invMassScale) PX_OVERRIDE { PX_CHECK_AND_RETURN(PxIsFinite(invMassScale) && invMassScale>=0, "PxJoint::setInvMassScale0: scale must be non-negative"); mData->invMassScale.linear0 = invMassScale; mPxConstraint->markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale0, static_cast<PxJoint&>(*this), invMassScale) } // PxJoint virtual PxReal getInvMassScale0() const PX_OVERRIDE { return mData->invMassScale.linear0; } // PxJoint virtual void setInvInertiaScale0(PxReal invInertiaScale) PX_OVERRIDE { PX_CHECK_AND_RETURN(PxIsFinite(invInertiaScale) && invInertiaScale>=0, "PxJoint::setInvInertiaScale0: scale must be non-negative"); mData->invMassScale.angular0 = invInertiaScale; mPxConstraint->markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale0, static_cast<PxJoint&>(*this), invInertiaScale) } // PxJoint virtual PxReal getInvInertiaScale0() const PX_OVERRIDE { return mData->invMassScale.angular0; } // PxJoint virtual void setInvMassScale1(PxReal invMassScale) PX_OVERRIDE { PX_CHECK_AND_RETURN(PxIsFinite(invMassScale) && invMassScale>=0, "PxJoint::setInvMassScale1: scale must be non-negative"); mData->invMassScale.linear1 = invMassScale; mPxConstraint->markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale1, static_cast<PxJoint&>(*this), invMassScale) } // PxJoint virtual PxReal getInvMassScale1() const PX_OVERRIDE { return mData->invMassScale.linear1; } // PxJoint virtual void setInvInertiaScale1(PxReal invInertiaScale) PX_OVERRIDE { PX_CHECK_AND_RETURN(PxIsFinite(invInertiaScale) && invInertiaScale>=0, "PxJoint::setInvInertiaScale: scale must be non-negative"); mData->invMassScale.angular1 = invInertiaScale; mPxConstraint->markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale1, static_cast<PxJoint&>(*this), invInertiaScale) } // PxJoint virtual PxReal getInvInertiaScale1() const PX_OVERRIDE { return mData->invMassScale.angular1; } // PxJoint virtual PxConstraint* getConstraint() const PX_OVERRIDE { return mPxConstraint; } // PxJoint virtual void setName(const char* name) PX_OVERRIDE { mName = name; #if PX_SUPPORT_OMNI_PVD const char* n = name ? name : ""; PxU32 nLen = PxU32(strlen(n)) + 1; OMNI_PVD_SET_ARRAY(OMNI_PVD_CONTEXT_HANDLE, PxJoint, name, static_cast<PxJoint&>(*this), n, nLen) #endif } // PxJoint virtual const char* getName() const PX_OVERRIDE { return mName; } // PxJoint virtual void release() PX_OVERRIDE { mPxConstraint->release(); } // PxJoint virtual PxScene* getScene() const PX_OVERRIDE { return mPxConstraint ? mPxConstraint->getScene() : NULL; } // PxConstraintConnector virtual void onComShift(PxU32 actor) PX_OVERRIDE { mData->c2b[actor] = getCom(actor).transformInv(mLocalPose[actor]); markDirty(); } // PxConstraintConnector virtual void onOriginShift(const PxVec3& shift) PX_OVERRIDE { PxRigidActor* a[2]; mPxConstraint->getActors(a[0], a[1]); if (!a[0]) { mLocalPose[0].p -= shift; mData->c2b[0].p -= shift; markDirty(); } else if (!a[1]) { mLocalPose[1].p -= shift; mData->c2b[1].p -= shift; markDirty(); } } // PxConstraintConnector virtual void* prepareData() PX_OVERRIDE { return mData; } // PxConstraintConnector virtual void* getExternalReference(PxU32& typeID) PX_OVERRIDE { typeID = PxConstraintExtIDs::eJOINT; return static_cast<PxJoint*>( this ); } // PxConstraintConnector virtual PxBase* getSerializable() PX_OVERRIDE { return this; } // PxConstraintConnector virtual void onConstraintRelease() PX_OVERRIDE { PX_FREE(mData); PX_DELETE_THIS; } // PxConstraintConnector virtual const void* getConstantBlock() const PX_OVERRIDE { return mData; } virtual void connectToConstraint(PxConstraint* c) PX_OVERRIDE { mPxConstraint = c; } private: PxTransform getCom(PxU32 index) const { PxRigidActor* a[2]; mPxConstraint->getActors(a[0],a[1]); return getCom(a[index]); } PxTransform getCom(PxRigidActor* actor) const { if (!actor) return PxTransform(PxIdentity); else if (actor->getType() == PxActorType::eRIGID_DYNAMIC || actor->getType() == PxActorType::eARTICULATION_LINK) return static_cast<PxRigidBody*>(actor)->getCMassLocalPose(); else { PX_ASSERT(actor->getType() == PxActorType::eRIGID_STATIC); return static_cast<PxRigidStatic*>(actor)->getGlobalPose().getInverse(); } } protected: JointT(PxType concreteType, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1, const char* name) : Base (concreteType, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mName (NULL), mPxConstraint (NULL) { PX_UNUSED(name); Base::userData = NULL; const PxU32 size = sizeof(DataClass); JointData* data = reinterpret_cast<JointData*>(PX_ALLOC(size, name)); PxMarkSerializedMemory(data, size); mLocalPose[0] = localFrame0.getNormalized(); mLocalPose[1] = localFrame1.getNormalized(); data->c2b[0] = getCom(actor0).transformInv(mLocalPose[0]); data->c2b[1] = getCom(actor1).transformInv(mLocalPose[1]); data->invMassScale.linear0 = 1.0f; data->invMassScale.angular0 = 1.0f; data->invMassScale.linear1 = 1.0f; data->invMassScale.angular1 = 1.0f; mData = data; } virtual ~JointT() { if(Base::getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(mData); OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxJoint, static_cast<Base&>(*this)) } PX_FORCE_INLINE DataClass& data() const { return *static_cast<DataClass*>(mData); } PX_FORCE_INLINE void markDirty() { mPxConstraint->markDirty(); } void wakeUpActors() { PxRigidActor* a[2]; mPxConstraint->getActors(a[0], a[1]); for(PxU32 i = 0; i < 2; i++) { if(a[i] && a[i]->getScene()) { if(a[i]->getType() == PxActorType::eRIGID_DYNAMIC) { PxRigidDynamic* rd = static_cast<PxRigidDynamic*>(a[i]); if(!(rd->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC)) { const PxScene* scene = rd->getScene(); const PxReal wakeCounterResetValue = scene->getWakeCounterResetValue(); const PxReal wakeCounter = rd->getWakeCounter(); if(wakeCounter < wakeCounterResetValue) { rd->wakeUp(); } } } else if(a[i]->getType() == PxActorType::eARTICULATION_LINK) { PxArticulationLink* link = reinterpret_cast<PxArticulationLink*>(a[i]); PxArticulationReducedCoordinate& articulation = link->getArticulation(); const PxReal wakeCounter = articulation.getWakeCounter(); const PxScene* scene = link->getScene(); const PxReal wakeCounterResetValue = scene->getWakeCounterResetValue(); if(wakeCounter < wakeCounterResetValue) { articulation.wakeUp(); } } } } } PX_FORCE_INLINE PxQuat getTwistOrSwing(bool needTwist) const { const PxQuat q = getRelativeTransform().q; // PT: TODO: we don't need to compute both quats here PxQuat swing, twist; PxSeparateSwingTwist(q, swing, twist); return needTwist ? twist : swing; } PxReal getTwistAngle_Internal() const { const PxQuat twist = getTwistOrSwing(true); // PT: the angle-axis formulation creates the quat like this: // // const float a = angleRadians * 0.5f; // const float s = PxSin(a); // w = PxCos(a); // x = unitAxis.x * s; // y = unitAxis.y * s; // z = unitAxis.z * s; // // With the twist axis = (1;0;0) this gives: // // w = PxCos(angleRadians * 0.5f); // x = PxSin(angleRadians * 0.5f); // y = 0.0f; // z = 0.0f; // // Thus the quat's "getAngle" function returns: // // angle = PxAcos(w) * 2.0f; // // PxAcos will return an angle between 0 and PI in radians, so "getAngle" will return an angle between 0 and PI*2. PxReal angle = twist.getAngle(); if(twist.x<0.0f) angle = -angle; return angle; } PxReal getSwingYAngle_Internal() const { PxQuat swing = getTwistOrSwing(false); if(swing.w < 0.0f) // choose the shortest rotation swing = -swing; const PxReal angle = computeSwingAngle(swing.y, swing.w); PX_ASSERT(angle>-PxPi && angle<=PxPi); // since |y| < w+1, the atan magnitude is < PI/4 return angle; } PxReal getSwingZAngle_Internal() const { PxQuat swing = getTwistOrSwing(false); if(swing.w < 0.0f) // choose the shortest rotation swing = -swing; const PxReal angle = computeSwingAngle(swing.z, swing.w); PX_ASSERT(angle>-PxPi && angle <= PxPi); // since |y| < w+1, the atan magnitude is < PI/4 return angle; } const char* mName; PxTransform mLocalPose[2]; PxConstraint* mPxConstraint; JointData* mData; }; #if PX_SUPPORT_OMNI_PVD void omniPvdSetBaseJointParams(PxJoint& joint, PxJointConcreteType::Enum cType); template<typename JointType> void omniPvdInitJoint(JointType& joint); #endif } // namespace Ext } #endif
20,603
C
28.267045
208
0.697229
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtGearJoint.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 EXT_GEAR_JOINT_H #define EXT_GEAR_JOINT_H #include "extensions/PxGearJoint.h" #include "ExtJoint.h" #include "CmUtils.h" namespace physx { struct PxGearJointGeneratedValues; namespace Ext { struct GearJointData : public JointData { const PxBase* hingeJoint0; //either PxJoint or PxArticulationJointReducedCoordinate const PxBase* hingeJoint1; //either PxJoint or PxArticulationJointReducedCoordinate float gearRatio; float error; }; typedef JointT<PxGearJoint, GearJointData, PxGearJointGeneratedValues> GearJointT; class GearJoint : public GearJointT { public: // PX_SERIALIZATION GearJoint(PxBaseFlags baseFlags) : GearJointT(baseFlags) {} void resolveReferences(PxDeserializationContext& context); static GearJoint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<GearJoint>(address, context); } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION GearJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); // PxGearJoint virtual bool setHinges(const PxBase* hinge0, const PxBase* hinge1) PX_OVERRIDE; virtual void getHinges(const PxBase*& hinge0, const PxBase*& hinge1) const PX_OVERRIDE; virtual void setGearRatio(float ratio) PX_OVERRIDE; virtual float getGearRatio() const PX_OVERRIDE; //~PxGearJoint // PxConstraintConnector virtual void* prepareData() PX_OVERRIDE { updateError(); return mData; } virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE; //~PxConstraintConnector private: float mVirtualAngle0; float mVirtualAngle1; float mPersistentAngle0; float mPersistentAngle1; bool mInitDone; void updateError(); void resetError(); }; } // namespace Ext } #endif
3,654
C
39.164835
164
0.74439
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtD6Joint.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 EXT_D6_JOINT_H #define EXT_D6_JOINT_H #include "extensions/PxD6Joint.h" #include "ExtJoint.h" namespace physx { struct PxD6JointGeneratedValues; namespace Ext { struct D6JointData : public JointData { PxD6Motion::Enum motion[6]; PxJointLinearLimit distanceLimit; PxJointLinearLimitPair linearLimitX; PxJointLinearLimitPair linearLimitY; PxJointLinearLimitPair linearLimitZ; PxJointAngularLimitPair twistLimit; PxJointLimitCone swingLimit; PxJointLimitPyramid pyramidSwingLimit; PxD6JointDrive drive[PxD6Drive::eCOUNT]; PxTransform drivePosition; PxVec3 driveLinearVelocity; PxVec3 driveAngularVelocity; // derived quantities PxU32 locked; // bitmap of locked DOFs PxU32 limited; // bitmap of limited DOFs PxU32 driving; // bitmap of active drives (implies driven DOFs not locked) PxReal distanceMinDist; // distance limit minimum distance to get a good direction // PT: the PxD6Motion values are now shared for both kind of linear limits, so we need // an extra bool to know which one(s) should be actually used. bool mUseDistanceLimit; bool mUseNewLinearLimits; // PT: the swing limits can now be a cone or a pyramid, so we need // an extra bool to know which one(s) should be actually used. bool mUseConeLimit; bool mUsePyramidLimits; private: D6JointData(const PxJointLinearLimit& distance, const PxJointLinearLimitPair& linearX, const PxJointLinearLimitPair& linearY, const PxJointLinearLimitPair& linearZ, const PxJointAngularLimitPair& twist, const PxJointLimitCone& swing, const PxJointLimitPyramid& pyramid) : distanceLimit (distance), linearLimitX (linearX), linearLimitY (linearY), linearLimitZ (linearZ), twistLimit (twist), swingLimit (swing), pyramidSwingLimit (pyramid), mUseDistanceLimit (false), mUseNewLinearLimits (false), mUseConeLimit (false), mUsePyramidLimits (false) {} }; typedef JointT<PxD6Joint, D6JointData, PxD6JointGeneratedValues> D6JointT; class D6Joint : public D6JointT { public: // PX_SERIALIZATION D6Joint(PxBaseFlags baseFlags) : D6JointT(baseFlags) {} void resolveReferences(PxDeserializationContext& context); static D6Joint* createObject(PxU8*& address, PxDeserializationContext& context) { return createJointObject<D6Joint>(address, context); } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION D6Joint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1); // PxD6Joint virtual void setMotion(PxD6Axis::Enum index, PxD6Motion::Enum t) PX_OVERRIDE; virtual PxD6Motion::Enum getMotion(PxD6Axis::Enum index) const PX_OVERRIDE; virtual PxReal getTwistAngle() const PX_OVERRIDE; virtual PxReal getSwingYAngle() const PX_OVERRIDE; virtual PxReal getSwingZAngle() const PX_OVERRIDE; virtual void setDistanceLimit(const PxJointLinearLimit& l) PX_OVERRIDE; virtual PxJointLinearLimit getDistanceLimit() const PX_OVERRIDE; virtual void setLinearLimit(PxD6Axis::Enum axis, const PxJointLinearLimitPair& limit) PX_OVERRIDE; virtual PxJointLinearLimitPair getLinearLimit(PxD6Axis::Enum axis) const PX_OVERRIDE; virtual void setTwistLimit(const PxJointAngularLimitPair& l) PX_OVERRIDE; virtual PxJointAngularLimitPair getTwistLimit() const PX_OVERRIDE; virtual void setSwingLimit(const PxJointLimitCone& l) PX_OVERRIDE; virtual PxJointLimitCone getSwingLimit() const PX_OVERRIDE; virtual void setPyramidSwingLimit(const PxJointLimitPyramid& limit) PX_OVERRIDE; virtual PxJointLimitPyramid getPyramidSwingLimit() const PX_OVERRIDE; virtual void setDrive(PxD6Drive::Enum index, const PxD6JointDrive& d) PX_OVERRIDE; virtual PxD6JointDrive getDrive(PxD6Drive::Enum index) const PX_OVERRIDE; virtual void setDrivePosition(const PxTransform& pose, bool autowake = true) PX_OVERRIDE; virtual PxTransform getDrivePosition() const PX_OVERRIDE; virtual void setDriveVelocity(const PxVec3& linear, const PxVec3& angular, bool autowake = true) PX_OVERRIDE; virtual void getDriveVelocity(PxVec3& linear, PxVec3& angular) const PX_OVERRIDE; //~PxD6Joint // PxConstraintConnector virtual PxConstraintSolverPrep getPrep() const PX_OVERRIDE; virtual void* prepareData() PX_OVERRIDE; #if PX_SUPPORT_OMNI_PVD virtual void updateOmniPvdProperties() const PX_OVERRIDE; #endif //~PxConstraintConnector private: bool active(const PxD6Drive::Enum index) const { const PxD6JointDrive& d = data().drive[index]; return d.stiffness!=0 || d.damping != 0; } bool mRecomputeMotion; bool mPadding[3]; // PT: padding from prev bool }; } // namespace Ext } // namespace physx #endif
6,579
C
40.645569
158
0.755586
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtMetaData.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/PxIO.h" #include "common/PxMetaData.h" #include "extensions/PxJoint.h" #include "ExtJoint.h" #include "ExtD6Joint.h" #include "ExtFixedJoint.h" #include "ExtSphericalJoint.h" #include "ExtDistanceJoint.h" #include "ExtContactJoint.h" #include "ExtRevoluteJoint.h" #include "ExtPrismaticJoint.h" #include "serialization/SnSerializationRegistry.h" #include "serialization/Binary/SnSerializationContext.h" using namespace physx; using namespace Cm; using namespace Ext; /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_JointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, JointData) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, JointData, PxTransform32, c2b, 0) PX_DEF_BIN_METADATA_ITEM(stream, JointData, PxConstraintInvMassScale, invMassScale, 0) } static void getBinaryMetaData_PxD6JointDrive(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxD6JointDriveFlags, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, PxD6JointDrive) PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxReal, stiffness, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxReal, damping, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxReal, forceLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxD6JointDrive, PxD6JointDriveFlags, flags, 0) } static void getBinaryMetaData_PxJointLimitParameters(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxJointLimitParameters) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, restitution, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, bounceThreshold, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, stiffness, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitParameters, PxReal, damping, 0) } static void getBinaryMetaData_PxJointLinearLimit(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxJointLinearLimit) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLinearLimit, PxJointLimitParameters) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLinearLimit, PxReal, value, 0) } static void getBinaryMetaData_PxJointLinearLimitPair(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxJointLinearLimitPair) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLinearLimitPair, PxJointLimitParameters) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLinearLimitPair, PxReal, upper, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLinearLimitPair, PxReal, lower, 0) } static void getBinaryMetaData_PxJointAngularLimitPair(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxJointAngularLimitPair) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointAngularLimitPair, PxJointLimitParameters) PX_DEF_BIN_METADATA_ITEM(stream, PxJointAngularLimitPair, PxReal, upper, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointAngularLimitPair, PxReal, lower, 0) } static void getBinaryMetaData_PxJointLimitCone(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxJointLimitCone) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLimitCone, PxJointLimitParameters) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitCone, PxReal, yAngle, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitCone, PxReal, zAngle, 0) } static void getBinaryMetaData_PxJointLimitPyramid(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxJointLimitPyramid) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJointLimitPyramid, PxJointLimitParameters) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, yAngleMin, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, yAngleMax, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, zAngleMin, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxJointLimitPyramid, PxReal, zAngleMax, 0) } void PxJoint::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxJoint, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, PxJoint, void, userData, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_RevoluteJointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxRevoluteJointFlags, PxU16) PX_DEF_BIN_METADATA_CLASS(stream, RevoluteJointData) PX_DEF_BIN_METADATA_BASE_CLASS(stream, RevoluteJointData, JointData) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxReal, driveVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxReal, driveForceLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxReal, driveGearRatio, 0) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxJointAngularLimitPair,limit, 0) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxRevoluteJointFlags, jointFlags, 0) #ifdef EXPLICIT_PADDING_METADATA PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING) #endif } void RevoluteJoint::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_RevoluteJointData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, RevoluteJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, RevoluteJoint, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, RevoluteJoint, PxConstraintConnector) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJoint, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, RevoluteJoint, PxTransform, mLocalPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, RevoluteJoint, JointData, mData, PxMetaDataFlag::ePTR) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, RevoluteJoint, RevoluteJointData, mData, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, RevoluteJoint, mName, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_SphericalJointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxSphericalJointFlags, PxU16) PX_DEF_BIN_METADATA_CLASS(stream, SphericalJointData) PX_DEF_BIN_METADATA_BASE_CLASS(stream, SphericalJointData, JointData) PX_DEF_BIN_METADATA_ITEM(stream, SphericalJointData, PxJointLimitCone, limit, 0) PX_DEF_BIN_METADATA_ITEM(stream, SphericalJointData, PxSphericalJointFlags, jointFlags, 0) #ifdef EXPLICIT_PADDING_METADATA PX_DEF_BIN_METADATA_ITEM(stream, SphericalJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING) #endif } void SphericalJoint::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_SphericalJointData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, SphericalJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, SphericalJoint, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, SphericalJoint, PxConstraintConnector) PX_DEF_BIN_METADATA_ITEM(stream, SphericalJoint, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, SphericalJoint, PxTransform, mLocalPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, SphericalJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, SphericalJoint, JointData, mData, PxMetaDataFlag::ePTR) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, SphericalJoint, SphericalJointData, mData, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, SphericalJoint, mName, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_DistanceJointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxDistanceJointFlags, PxU16) PX_DEF_BIN_METADATA_CLASS(stream, DistanceJointData) PX_DEF_BIN_METADATA_BASE_CLASS(stream, DistanceJointData, JointData) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, minDistance, 0) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, maxDistance, 0) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, tolerance, 0) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, stiffness, 0) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxReal, damping, 0) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxDistanceJointFlags, jointFlags, 0) #ifdef EXPLICIT_PADDING_METADATA PX_DEF_BIN_METADATA_ITEM(stream, DistanceJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING) #endif } void DistanceJoint::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_DistanceJointData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, DistanceJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, DistanceJoint, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, DistanceJoint, PxConstraintConnector) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJoint, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, DistanceJoint, PxTransform, mLocalPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, DistanceJoint, JointData, mData, PxMetaDataFlag::ePTR) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, DistanceJoint, DistanceJointData, mData, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, DistanceJoint, mName, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_D6JointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxD6Motion::Enum, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, D6JointData) PX_DEF_BIN_METADATA_BASE_CLASS(stream, D6JointData, JointData) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6JointData, PxD6Motion::Enum, motion, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimit, distanceLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimitPair, linearLimitX, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimitPair, linearLimitY, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLinearLimitPair, linearLimitZ, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointAngularLimitPair, twistLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLimitCone, swingLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxJointLimitPyramid, pyramidSwingLimit, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6JointData, PxD6JointDrive, drive, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxTransform, drivePosition, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxVec3, driveLinearVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxVec3, driveAngularVelocity, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxU32, locked, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxU32, limited, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxU32, driving, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, PxReal, distanceMinDist, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUseDistanceLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUseNewLinearLimits, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUseConeLimit, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6JointData, bool, mUsePyramidLimits, 0) } void D6Joint::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_D6JointData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, D6Joint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, D6Joint, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, D6Joint, PxConstraintConnector) PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6Joint, PxTransform, mLocalPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, JointData, mData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, D6Joint, bool, mRecomputeMotion, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, D6Joint, bool, mPadding, PxMetaDataFlag::ePADDING) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, D6Joint, D6JointData, mData, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, D6Joint, mName, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PrismaticJointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxPrismaticJointFlags, PxU16) PX_DEF_BIN_METADATA_CLASS(stream, PrismaticJointData) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PrismaticJointData, JointData) PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJointData, PxJointLinearLimitPair, limit, 0) PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJointData, PxPrismaticJointFlags, jointFlags, 0) #ifdef EXPLICIT_PADDING_METADATA PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJointData, PxU16, paddingFromFlags, PxMetaDataFlag::ePADDING) #endif } void PrismaticJoint::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_PrismaticJointData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, PrismaticJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PrismaticJoint, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PrismaticJoint, PxConstraintConnector) PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJoint, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, PrismaticJoint, PxTransform, mLocalPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, PrismaticJoint, JointData, mData, PxMetaDataFlag::ePTR) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, PrismaticJoint, PrismaticJointData, mData, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, PrismaticJoint, mName, 0) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_FixedJointData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, FixedJointData) PX_DEF_BIN_METADATA_BASE_CLASS(stream, FixedJointData, JointData) } void FixedJoint::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_FixedJointData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, FixedJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, FixedJoint, PxJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, FixedJoint, PxConstraintConnector) PX_DEF_BIN_METADATA_ITEM(stream, FixedJoint, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, FixedJoint, PxTransform, mLocalPose, 0) PX_DEF_BIN_METADATA_ITEM(stream, FixedJoint, PxConstraint, mPxConstraint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, FixedJoint, JointData, mData, PxMetaDataFlag::ePTR) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, FixedJoint, FixedJointData, mData, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, FixedJoint, mName, 0) } void getBinaryMetaData_SerializationContext(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxSerialObjectId, PxU64) PX_DEF_BIN_METADATA_TYPEDEF(stream, SerialObjectIndex, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, Sn::ManifestEntry) PX_DEF_BIN_METADATA_ITEM(stream, Sn::ManifestEntry, PxU32, offset, 0) PX_DEF_BIN_METADATA_ITEM(stream, Sn::ManifestEntry, PxType, type, 0) PX_DEF_BIN_METADATA_CLASS(stream, Sn::ImportReference) PX_DEF_BIN_METADATA_ITEM(stream, Sn::ImportReference, PxSerialObjectId, id, 0) PX_DEF_BIN_METADATA_ITEM(stream, Sn::ImportReference, PxType, type, 0) PX_DEF_BIN_METADATA_CLASS(stream, Sn::ExportReference) PX_DEF_BIN_METADATA_ITEM(stream, Sn::ExportReference, PxSerialObjectId, id, 0) PX_DEF_BIN_METADATA_ITEM(stream, Sn::ExportReference, SerialObjectIndex, objIndex, 0) PX_DEF_BIN_METADATA_CLASS(stream, Sn::InternalReferencePtr) PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferencePtr, void, reference, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferencePtr, SerialObjectIndex, objIndex, 0) PX_DEF_BIN_METADATA_CLASS(stream, Sn::InternalReferenceHandle16) PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferenceHandle16, PxU16, reference, PxMetaDataFlag::eHANDLE) PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferenceHandle16, PxU16, pad, PxMetaDataFlag::ePADDING) PX_DEF_BIN_METADATA_ITEM(stream, Sn::InternalReferenceHandle16, SerialObjectIndex, objIndex, 0) } namespace physx { namespace Ext { void GetExtensionsBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream,PxConstraintConnector) getBinaryMetaData_JointData(stream); getBinaryMetaData_PxD6JointDrive(stream); getBinaryMetaData_PxJointLimitParameters(stream); getBinaryMetaData_PxJointLimitCone(stream); getBinaryMetaData_PxJointLimitPyramid(stream); getBinaryMetaData_PxJointLinearLimit(stream); getBinaryMetaData_PxJointLinearLimitPair(stream); getBinaryMetaData_PxJointAngularLimitPair(stream); PxJoint::getBinaryMetaData(stream); RevoluteJoint::getBinaryMetaData(stream); SphericalJoint::getBinaryMetaData(stream); DistanceJoint::getBinaryMetaData(stream); D6Joint::getBinaryMetaData(stream); PrismaticJoint::getBinaryMetaData(stream); FixedJoint::getBinaryMetaData(stream); getBinaryMetaData_SerializationContext(stream); } } } ///////////////////////////////////////////////////////////////////////////////
19,509
C++
44.584112
121
0.737352
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSphericalJoint.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 "ExtSphericalJoint.h" #include "ExtConstraintHelper.h" #include "CmConeLimitHelper.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; SphericalJoint::SphericalJoint(const PxTolerancesScale& /*scale*/, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : SphericalJointT(PxJointConcreteType::eSPHERICAL, actor0, localFrame0, actor1, localFrame1, "SphericalJointData") { SphericalJointData* data = static_cast<SphericalJointData*>(mData); data->limit = PxJointLimitCone(PxPi/2, PxPi/2); data->jointFlags = PxSphericalJointFlags(); } void SphericalJoint::setLimitCone(const PxJointLimitCone &limit) { PX_CHECK_AND_RETURN(limit.isValid(), "PxSphericalJoint::setLimit: invalid parameter"); data().limit = limit; markDirty(); #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxSphericalJoint& j = static_cast<PxSphericalJoint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitYAngle, j, limit.yAngle) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitZAngle, j, limit.zAngle) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitRestitution, j, limit.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitBounceThreshold, j, limit.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitStiffness, j, limit.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitDamping, j, limit.damping) OMNI_PVD_WRITE_SCOPE_END #endif } PxJointLimitCone SphericalJoint::getLimitCone() const { return data().limit; } PxSphericalJointFlags SphericalJoint::getSphericalJointFlags(void) const { return data().jointFlags; } void SphericalJoint::setSphericalJointFlags(PxSphericalJointFlags flags) { data().jointFlags = flags; OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, jointFlags, static_cast<PxSphericalJoint&>(*this), flags) } void SphericalJoint::setSphericalJointFlag(PxSphericalJointFlag::Enum flag, bool value) { if(value) data().jointFlags |= flag; else data().jointFlags &= ~flag; markDirty(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, jointFlags, static_cast<PxSphericalJoint&>(*this), getSphericalJointFlags()) } PxReal SphericalJoint::getSwingYAngle() const { return getSwingYAngle_Internal(); } PxReal SphericalJoint::getSwingZAngle() const { return getSwingZAngle_Internal(); } static void SphericalJointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { const SphericalJointData& data = *reinterpret_cast<const SphericalJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) viz.visualizeJointFrames(cA2w, cB2w); if((flags & PxConstraintVisualizationFlag::eLIMITS) && (data.jointFlags & PxSphericalJointFlag::eLIMIT_ENABLED)) { joint::applyNeighborhoodOperator(cA2w, cB2w); const PxTransform cB2cA = cA2w.transformInv(cB2w); PxQuat swing, twist; PxSeparateSwingTwist(cB2cA.q, swing, twist); viz.visualizeLimitCone(cA2w, PxTan(data.limit.zAngle/4), PxTan(data.limit.yAngle/4)); } } //TAG:solverprepshader static PxU32 SphericalJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const SphericalJointData& data = *reinterpret_cast<const SphericalJointData*>(constantBlock); PxTransform32 cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); joint::applyNeighborhoodOperator(cA2w, cB2w); if(data.jointFlags & PxSphericalJointFlag::eLIMIT_ENABLED) { PxQuat swing, twist; PxSeparateSwingTwist(cA2w.q.getConjugate() * cB2w.q, swing, twist); PX_ASSERT(PxAbs(swing.x)<1e-6f); PxVec3 axis; PxReal error; const Cm::ConeLimitHelperTanLess coneHelper(data.limit.yAngle, data.limit.zAngle); coneHelper.getLimit(swing, axis, error); ch.angularLimit(cA2w.rotate(axis), error, data.limit); } PxVec3 ra, rb; ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, 0, ra, rb); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; return ch.getCount(); } /////////////////////////////////////////////////////////////////////////////// static PxConstraintShaderTable gSphericalJointShaders = { SphericalJointSolverPrep, SphericalJointVisualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep SphericalJoint::getPrep() const { return gSphericalJointShaders.solverPrep; } PxSphericalJoint* physx::PxSphericalJointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxSphericalJointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxSphericalJointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxSphericalJointCreate: actors must be different"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxSphericalJointCreate: at least one actor must be dynamic"); return createJointT<SphericalJoint, SphericalJointData>(physics, actor0, localFrame0, actor1, localFrame1, gSphericalJointShaders); } // PX_SERIALIZATION void SphericalJoint::resolveReferences(PxDeserializationContext& context) { mPxConstraint = resolveConstraintPtr(context, mPxConstraint, this, gSphericalJointShaders); } //~PX_SERIALIZATION #if PX_SUPPORT_OMNI_PVD void SphericalJoint::updateOmniPvdProperties() const { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) const PxSphericalJoint& j = static_cast<const PxSphericalJoint&>(*this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingYAngle, j, getSwingYAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingZAngle, j, getSwingZAngle()) OMNI_PVD_WRITE_SCOPE_END } template<> void physx::Ext::omniPvdInitJoint<SphericalJoint>(SphericalJoint& joint) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxSphericalJoint& j = static_cast<PxSphericalJoint&>(joint); OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, j); omniPvdSetBaseJointParams(static_cast<PxJoint&>(joint), PxJointConcreteType::eSPHERICAL); PxJointLimitCone limit = joint.getLimitCone(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitYAngle, j, limit.yAngle) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitZAngle, j, limit.zAngle) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitRestitution, j, limit.restitution) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitBounceThreshold, j, limit.bounceThreshold) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitStiffness, j, limit.stiffness) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, limitDamping, j, limit.damping) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, jointFlags, j, joint.getSphericalJointFlags()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingYAngle, j, joint.getSwingYAngle()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxSphericalJoint, swingZAngle, j, joint.getSwingZAngle()) OMNI_PVD_WRITE_SCOPE_END } #endif
9,876
C++
42.70354
176
0.777845
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtRemeshingExt.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 "extensions/PxRemeshingExt.h" #include "foundation/PxHashMap.h" namespace physx { void assignTriangle(PxArray<PxU32>& triangles, PxU32 triIndex, PxU32 a, PxU32 b, PxU32 c) { triangles[3 * triIndex] = a; triangles[3 * triIndex + 1] = b; triangles[3 * triIndex + 2] = c; } void addTriangle(PxArray<PxU32>& triangles, PxU32 a, PxU32 b, PxU32 c) { triangles.pushBack(a); triangles.pushBack(b); triangles.pushBack(c); } void subdivideTriangle(int i, int ab, int bc, int ac, PxArray<PxU32>& triangles, PxArray<PxVec3>& points) { PxU32 tri[3] = { triangles[3 * i],triangles[3 * i + 1],triangles[3 * i + 2] }; if (ab >= 0 && bc >= 0 && ac >= 0) { addTriangle(triangles, tri[0], ab, ac); addTriangle(triangles, tri[1], bc, ab); addTriangle(triangles, tri[2], ac, bc); assignTriangle(triangles, i, ab, bc, ac); } else if (ac >= 0 && ab >= 0) { float dB = (points[ac] - points[tri[1]]).magnitudeSquared(); float dC = (points[ab] - points[tri[2]]).magnitudeSquared(); if (dB < dC) { addTriangle(triangles, tri[1], tri[2], ac); addTriangle(triangles, tri[1], ac, ab); } else { addTriangle(triangles, tri[1], tri[2], ab); addTriangle(triangles, tri[2], ac, ab); } assignTriangle(triangles, i, tri[0], ab, ac); } else if (ab >= 0 && bc >= 0) { float dA = (points[bc] - points[tri[0]]).magnitudeSquared(); float dC = (points[ab] - points[tri[2]]).magnitudeSquared(); if (dC < dA) { addTriangle(triangles, tri[2], tri[0], ab); addTriangle(triangles, tri[2], ab, bc); } else { addTriangle(triangles, tri[2], tri[0], bc); addTriangle(triangles, tri[0], ab, bc); } assignTriangle(triangles, i, tri[1], bc, ab); } else if (bc >= 0 && ac >= 0) { float dA = (points[bc] - points[tri[0]]).magnitudeSquared(); float dB = (points[ac] - points[tri[1]]).magnitudeSquared(); if (dA < dB) { addTriangle(triangles, tri[0], tri[1], bc); addTriangle(triangles, tri[0], bc, ac); } else { addTriangle(triangles, tri[0], tri[1], ac); addTriangle(triangles, tri[1], bc, ac); } assignTriangle(triangles, i, tri[2], ac, bc); } else if (ab >= 0) { addTriangle(triangles, tri[1], tri[2], ab); assignTriangle(triangles, i, tri[2], tri[0], ab); } else if (bc >= 0) { addTriangle(triangles, tri[2], tri[0], bc); assignTriangle(triangles, i, tri[0], tri[1], bc); } else if (ac >= 0) { addTriangle(triangles, tri[1], tri[2], ac); assignTriangle(triangles, i, tri[0], tri[1], ac); } } PX_FORCE_INLINE PxU64 key(PxU32 a, PxU32 b) { if (a < b) return ((PxU64(a)) << 32) | (PxU64(b)); else return ((PxU64(b)) << 32) | (PxU64(a)); } void checkEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, PxI32>& edges, PxArray<PxVec3>& points, PxReal maxEdgeLength) { if ((points[a] - points[b]).magnitudeSquared() < maxEdgeLength * maxEdgeLength) return; PxU64 k = key(a, b); if (edges.find(k)) return; edges.insert(k, points.size()); points.pushBack(0.5f * (points[a] + points[b])); } PX_FORCE_INLINE PxI32 getEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, PxI32>& edges) { if (const PxPair<const PxU64, PxI32>* ptr = edges.find(key(a, b))) return ptr->second; return -1; } struct Info { PxI32 StartIndex; PxI32 Count; Info(PxI32 startIndex, PxI32 count) { StartIndex = startIndex; Count = count; } }; void checkEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, Info>& edges, PxArray<PxVec3>& points, PxReal maxEdgeLength) { if (a > b) PxSwap(a, b); PxReal l = (points[a] - points[b]).magnitudeSquared(); if (l < maxEdgeLength * maxEdgeLength) return; l = PxSqrt(l); PxU32 numSubdivisions = (PxU32)(l / maxEdgeLength); if (numSubdivisions <= 1) return; PxU64 k = key(a, b); if (edges.find(k)) return; edges.insert(k, Info(points.size(), numSubdivisions - 1)); for (PxU32 i = 1; i < numSubdivisions; ++i) { PxReal p = (PxReal)i / numSubdivisions; points.pushBack((1 - p) * points[a] + p * points[b]); } } PX_FORCE_INLINE Info getEdge(PxU32 a, PxU32 b, PxHashMap<PxU64, Info>& edges) { const PxPair<const PxU64, Info>* value = edges.find(key(a, b)); if (value) return value->second; return Info(-1, -1); } PX_FORCE_INLINE void addPoints(PxArray<PxU32>& polygon, const Info& ab, bool reverse) { if (reverse) { for (PxI32 i = ab.Count - 1; i >= 0; --i) polygon.pushBack(ab.StartIndex + i); } else { for (PxI32 i = 0; i < ab.Count; ++i) polygon.pushBack(ab.StartIndex + i); } } PX_FORCE_INLINE PxReal angle(const PxVec3& l, const PxVec3& r) { PxReal d = l.dot(r) / PxSqrt(l.magnitudeSquared() * r.magnitudeSquared()); if (d <= -1) return PxPi; if (d >= 1) return 0.0f; return PxAcos(d); } PX_FORCE_INLINE PxReal evaluateCost(const PxArray<PxVec3>& vertices, PxU32 a, PxU32 b, PxU32 c) { const PxVec3& aa = vertices[a]; const PxVec3& bb = vertices[b]; const PxVec3& cc = vertices[c]; PxReal a1 = angle(bb - aa, cc - aa); PxReal a2 = angle(aa - bb, cc - bb); PxReal a3 = angle(aa - cc, bb - cc); return PxMax(a1, PxMax(a2, a3)); //return (aa - bb).magnitude() + (aa - cc).magnitude() + (bb - cc).magnitude(); } void triangulateConvex(PxU32 originalTriangleIndexTimes3, PxArray<PxU32>& polygon, const PxArray<PxVec3>& vertices, PxArray<PxU32>& triangles, PxArray<PxI32>& offsets) { offsets.forceSize_Unsafe(0); offsets.reserve(polygon.size()); for (PxU32 i = 0; i < polygon.size(); ++i) offsets.pushBack(1); PxI32 start = 0; PxU32 count = polygon.size(); PxU32 triCounter = 0; while (count > 2) { PxReal minCost = FLT_MAX; PxI32 best = -1; PxI32 i = start; for (PxU32 j = 0; j < count; ++j) { PxU32 a = polygon[i]; PX_ASSERT(offsets[i] >= 0); PxI32 n = (i + offsets[i]) % polygon.size(); PX_ASSERT(offsets[n] >= 0); PxU32 b = polygon[n]; PxU32 nn = (n + offsets[n]) % polygon.size(); PX_ASSERT(offsets[nn] >= 0); PxU32 c = polygon[nn]; PxReal cost = evaluateCost(vertices, a, b, c); if (cost < minCost) { minCost = cost; best = i; } i = n; } { PxU32 a = polygon[best]; PxI32 n = (best + offsets[best]) % polygon.size(); PxU32 b = polygon[n]; PxU32 nn = (n + offsets[n]) % polygon.size(); PxU32 c = polygon[nn]; if (n == start) start += offsets[n]; offsets[best] += offsets[n]; offsets[n] = -1; PX_ASSERT(offsets[(best + offsets[best]) % polygon.size()] >= 0); if (triCounter == 0) { triangles[originalTriangleIndexTimes3 + 0] = a; triangles[originalTriangleIndexTimes3 + 1] = b; triangles[originalTriangleIndexTimes3 + 2] = c; } else { triangles.pushBack(a); triangles.pushBack(b); triangles.pushBack(c); } ++triCounter; } --count; } } bool limitMaxEdgeLengthAdaptive(PxArray<PxU32>& triangles, PxArray<PxVec3>& points, PxReal maxEdgeLength, PxArray<PxU32>* triangleMap = NULL) { PxHashMap<PxU64, Info> edges; bool split = false; //Analyze edges for (PxU32 i = 0; i < triangles.size(); i += 3) { const PxU32* t = &triangles[i]; checkEdge(t[0], t[1], edges, points, maxEdgeLength); checkEdge(t[1], t[2], edges, points, maxEdgeLength); checkEdge(t[0], t[2], edges, points, maxEdgeLength); } PxArray<PxI32> offsets; PxArray<PxU32> polygon; //Subdivide triangles if required PxU32 size = triangles.size(); for (PxU32 i = 0; i < size; i += 3) { const PxU32* t = &triangles[i]; Info ab = getEdge(t[0], t[1], edges); Info bc = getEdge(t[1], t[2], edges); Info ac = getEdge(t[0], t[2], edges); if (ab.StartIndex >= 0 || bc.StartIndex >= 0 || ac.StartIndex >= 0) { polygon.forceSize_Unsafe(0); polygon.pushBack(t[0]); addPoints(polygon, ab, t[0] > t[1]); polygon.pushBack(t[1]); addPoints(polygon, bc, t[1] > t[2]); polygon.pushBack(t[2]); addPoints(polygon, ac, t[2] > t[0]); PxU32 s = triangles.size(); triangulateConvex(i, polygon, points, triangles, offsets); split = true; if (triangleMap != NULL) { for (PxU32 j = s; j < triangles.size(); ++j) triangleMap->pushBack((*triangleMap)[i]); } } /*else { result.pushBack(t[0]); result.pushBack(t[1]); result.pushBack(t[2]); if (triangleMap != NULL) triangleMap->pushBack((*triangleMap)[i]); }*/ } return split; } bool PxRemeshingExt::reduceSliverTriangles(PxArray<PxU32>& triangles, PxArray<PxVec3>& points, PxReal maxEdgeLength, PxU32 maxIterations, PxArray<PxU32>* triangleMap, PxU32 triangleCountThreshold) { bool split = limitMaxEdgeLengthAdaptive(triangles, points, maxEdgeLength, triangleMap); if (!split) return false; for (PxU32 i = 1; i < maxIterations; ++i) { split = limitMaxEdgeLengthAdaptive(triangles, points, maxEdgeLength, triangleMap); if (!split) break; if (triangles.size() >= triangleCountThreshold) break; } return true; } bool PxRemeshingExt::limitMaxEdgeLength(PxArray<PxU32>& triangles, PxArray<PxVec3>& points, PxReal maxEdgeLength, PxU32 maxIterations, PxArray<PxU32>* triangleMap, PxU32 triangleCountThreshold) { if (triangleMap) { triangleMap->clear(); triangleMap->reserve(triangles.size() / 3); for (PxU32 i = 0; i < triangles.size() / 3; ++i) triangleMap->pushBack(i); } PxU32 numIndices = triangles.size(); PxHashMap<PxU64, PxI32> edges; bool success = true; for (PxU32 k = 0; k < maxIterations && success; ++k) { success = false; edges.clear(); //Analyze edges for (PxU32 i = 0; i < triangles.size(); i += 3) { checkEdge(triangles[i], triangles[i + 1], edges, points, maxEdgeLength); checkEdge(triangles[i + 1], triangles[i + 2], edges, points, maxEdgeLength); checkEdge(triangles[i], triangles[i + 2], edges, points, maxEdgeLength); } //Subdivide triangles if required PxU32 size = triangles.size(); for (PxU32 i = 0; i < size; i += 3) { PxI32 ab = getEdge(triangles[i], triangles[i + 1], edges); PxI32 bc = getEdge(triangles[i + 1], triangles[i + 2], edges); PxI32 ac = getEdge(triangles[i], triangles[i + 2], edges); if (ab >= 0 || bc >= 0 || ac >= 0) { PxU32 s = triangles.size(); subdivideTriangle(i / 3, ab, bc, ac, triangles, points); success = true; if (triangleMap) { for (PxU32 j = s / 3; j < triangles.size() / 3; ++j) triangleMap->pushBack((*triangleMap)[i / 3]); } } } if (triangles.size() >= triangleCountThreshold) break; } return numIndices != triangles.size(); } }
12,387
C++
27.283105
197
0.631307
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCollection.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/PxBase.h" #include "geometry/PxConvexMesh.h" #include "geometry/PxTriangleMesh.h" #include "geometry/PxHeightField.h" #include "extensions/PxJoint.h" #include "extensions/PxConstraintExt.h" #include "extensions/PxCollectionExt.h" #include "PxShape.h" #include "PxMaterial.h" #include "PxArticulationReducedCoordinate.h" #include "PxAggregate.h" #include "PxPhysics.h" #include "PxScene.h" #include "PxPruningStructure.h" #include "foundation/PxArray.h" using namespace physx; void PxCollectionExt::releaseObjects(PxCollection& collection, bool releaseExclusiveShapes) { PxArray<PxBase*> releasableObjects; for (PxU32 i = 0; i < collection.getNbObjects(); ++i) { PxBase* s = &collection.getObject(i); // pruning structure must be released before its actors if(s->is<PxPruningStructure>()) { if(!releasableObjects.empty()) { PxBase* first = releasableObjects[0]; releasableObjects.pushBack(first); releasableObjects[0] = s; } } else { if (s->isReleasable() && (releaseExclusiveShapes || !s->is<PxShape>() || !s->is<PxShape>()->isExclusive())) releasableObjects.pushBack(s); } } for (PxU32 i = 0; i < releasableObjects.size(); ++i) releasableObjects[i]->release(); while (collection.getNbObjects() > 0) collection.remove(collection.getObject(0)); } void PxCollectionExt::remove(PxCollection& collection, PxType concreteType, PxCollection* to) { PxArray<PxBase*> removeObjects; for (PxU32 i = 0; i < collection.getNbObjects(); i++) { PxBase& object = collection.getObject(i); if(concreteType == object.getConcreteType()) { if(to) to->add(object); removeObjects.pushBack(&object); } } for (PxU32 i = 0; i < removeObjects.size(); ++i) collection.remove(*removeObjects[i]); } PxCollection* PxCollectionExt::createCollection(PxPhysics& physics) { PxCollection* collection = PxCreateCollection(); if (!collection) return NULL; // Collect convexes { PxArray<PxConvexMesh*> objects(physics.getNbConvexMeshes()); const PxU32 nb = physics.getConvexMeshes(objects.begin(), objects.size()); PX_ASSERT(nb == objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } // Collect triangle meshes { PxArray<PxTriangleMesh*> objects(physics.getNbTriangleMeshes()); const PxU32 nb = physics.getTriangleMeshes(objects.begin(), objects.size()); PX_ASSERT(nb == objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } // Collect heightfields { PxArray<PxHeightField*> objects(physics.getNbHeightFields()); const PxU32 nb = physics.getHeightFields(objects.begin(), objects.size()); PX_ASSERT(nb == objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } // Collect materials { PxArray<PxMaterial*> objects(physics.getNbMaterials()); const PxU32 nb = physics.getMaterials(objects.begin(), objects.size()); PX_ASSERT(nb == objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } // Collect shapes { PxArray<PxShape*> objects(physics.getNbShapes()); const PxU32 nb = physics.getShapes(objects.begin(), objects.size()); PX_ASSERT(nb == objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } return collection; } PxCollection* PxCollectionExt::createCollection(PxScene& scene) { PxCollection* collection = PxCreateCollection(); if (!collection) return NULL; // Collect actors { PxActorTypeFlags selectionFlags = PxActorTypeFlag::eRIGID_STATIC | PxActorTypeFlag::eRIGID_DYNAMIC; PxArray<PxActor*> objects(scene.getNbActors(selectionFlags)); const PxU32 nb = scene.getActors(selectionFlags, objects.begin(), objects.size()); PX_ASSERT(nb==objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } // Collect constraints { PxArray<PxConstraint*> objects(scene.getNbConstraints()); const PxU32 nb = scene.getConstraints(objects.begin(), objects.size()); PX_ASSERT(nb==objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) { PxU32 typeId; PxJoint* joint = reinterpret_cast<PxJoint*>(objects[i]->getExternalReference(typeId)); if(typeId == PxConstraintExtIDs::eJOINT) collection->add(*joint); } } // Collect articulations { PxArray<PxArticulationReducedCoordinate*> objects(scene.getNbArticulations()); const PxU32 nb = scene.getArticulations(objects.begin(), objects.size()); PX_ASSERT(nb==objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } // Collect aggregates { PxArray<PxAggregate*> objects(scene.getNbAggregates()); const PxU32 nb = scene.getAggregates(objects.begin(), objects.size()); PX_ASSERT(nb==objects.size()); PX_UNUSED(nb); for(PxU32 i=0;i<objects.size();i++) collection->add(*objects[i]); } return collection; }
6,731
C++
27.892704
110
0.713861
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqQuery.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 "ExtSqQuery.h" using namespace physx; using namespace Sq; #include "common/PxProfileZone.h" #include "foundation/PxFPU.h" #include "GuBounds.h" #include "GuIntersectionRayBox.h" #include "GuIntersectionRay.h" #include "GuBVH.h" #include "geometry/PxGeometryQuery.h" #include "geometry/PxSphereGeometry.h" #include "geometry/PxBoxGeometry.h" #include "geometry/PxCapsuleGeometry.h" #include "geometry/PxConvexMeshGeometry.h" #include "geometry/PxTriangleMeshGeometry.h" //#include "geometry/PxBVH.h" #include "PxQueryFiltering.h" #include "PxRigidActor.h" using namespace physx; using namespace Sq; using namespace Gu; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// // PT: this is a customized version of physx::Sq::SceneQueries that supports more than 2 hardcoded pruners. // It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners. // See #MODIFIED tag for what changed in this file compared to the initial code in SqQuery.cpp static PX_FORCE_INLINE void copy(PxRaycastHit* PX_RESTRICT dest, const PxRaycastHit* PX_RESTRICT src) { dest->faceIndex = src->faceIndex; dest->flags = src->flags; dest->position = src->position; dest->normal = src->normal; dest->distance = src->distance; dest->u = src->u; dest->v = src->v; dest->actor = src->actor; dest->shape = src->shape; } static PX_FORCE_INLINE void copy(PxSweepHit* PX_RESTRICT dest, const PxSweepHit* PX_RESTRICT src) { dest->faceIndex = src->faceIndex; dest->flags = src->flags; dest->position = src->position; dest->normal = src->normal; dest->distance = src->distance; dest->actor = src->actor; dest->shape = src->shape; } static PX_FORCE_INLINE void copy(PxOverlapHit* PX_RESTRICT dest, const PxOverlapHit* PX_RESTRICT src) { dest->faceIndex = src->faceIndex; dest->actor = src->actor; dest->shape = src->shape; } // these partial template specializations are used to generalize the query code to be reused for all permutations of // hit type=(raycast, overlap, sweep) x query type=(ANY, SINGLE, MULTIPLE) template <typename HitType> struct HitTypeSupport { enum { IsRaycast = 0, IsSweep = 0, IsOverlap = 0 }; }; template <> struct HitTypeSupport<PxRaycastHit> { enum { IsRaycast = 1, IsSweep = 0, IsOverlap = 0 }; static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit& hit) { return static_cast<const PxRaycastHit&>(hit).distance; } }; template <> struct HitTypeSupport<PxSweepHit> { enum { IsRaycast = 0, IsSweep = 1, IsOverlap = 0 }; static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit& hit) { return static_cast<const PxSweepHit&>(hit).distance; } }; template <> struct HitTypeSupport<PxOverlapHit> { enum { IsRaycast = 0, IsSweep = 0, IsOverlap = 1 }; static PX_FORCE_INLINE PxReal getDistance(const PxQueryHit&) { return -1.0f; } }; #define HITDIST(hit) HitTypeSupport<HitType>::getDistance(hit) template<typename HitType> static PxU32 clipHitsToNewMaxDist(HitType* ppuHits, PxU32 count, PxReal newMaxDist) { PxU32 i=0; while(i!=count) { if(HITDIST(ppuHits[i]) > newMaxDist) ppuHits[i] = ppuHits[--count]; else i++; } return count; } namespace physx { namespace Sq { struct ExtMultiQueryInput { const PxVec3* rayOrigin; // only valid for raycasts const PxVec3* unitDir; // only valid for raycasts and sweeps PxReal maxDistance; // only valid for raycasts and sweeps const PxGeometry* geometry; // only valid for overlaps and sweeps const PxTransform* pose; // only valid for overlaps and sweeps PxReal inflation; // only valid for sweeps // Raycast constructor ExtMultiQueryInput(const PxVec3& aRayOrigin, const PxVec3& aUnitDir, PxReal aMaxDist) { rayOrigin = &aRayOrigin; unitDir = &aUnitDir; maxDistance = aMaxDist; geometry = NULL; pose = NULL; inflation = 0.0f; } // Overlap constructor ExtMultiQueryInput(const PxGeometry* aGeometry, const PxTransform* aPose) { geometry = aGeometry; pose = aPose; inflation = 0.0f; rayOrigin = unitDir = NULL; } // Sweep constructor ExtMultiQueryInput( const PxGeometry* aGeometry, const PxTransform* aPose, const PxVec3& aUnitDir, const PxReal aMaxDist, const PxReal aInflation) { rayOrigin = NULL; maxDistance = aMaxDist; unitDir = &aUnitDir; geometry = aGeometry; pose = aPose; inflation = aInflation; } PX_FORCE_INLINE const PxVec3& getDir() const { PX_ASSERT(unitDir); return *unitDir; } PX_FORCE_INLINE const PxVec3& getOrigin() const { PX_ASSERT(rayOrigin); return *rayOrigin; } }; } } // performs a single geometry query for any HitType (PxSweepHit, PxOverlapHit, PxRaycastHit) template<typename HitType> struct ExtGeomQueryAny { static PX_FORCE_INLINE PxU32 geomHit( const CachedFuncs& funcs, const ExtMultiQueryInput& input, const Gu::ShapeData* sd, const PxGeometry& sceneGeom, const PxTransform& pose, PxHitFlags hitFlags, PxU32 maxHits, HitType* hits, const PxReal shrunkMaxDistance, const PxBounds3* precomputedBounds, PxQueryThreadContext* context) { using namespace Gu; const PxGeometry& geom0 = *input.geometry; const PxTransform& pose0 = *input.pose; const PxGeometry& geom1 = sceneGeom; const PxTransform& pose1 = pose; // Handle raycasts if(HitTypeSupport<HitType>::IsRaycast) { // the test for mesh AABB is archived in //sw/physx/dev/apokrovsky/graveyard/sqMeshAABBTest.cpp // TODO: investigate performance impact (see US12801) PX_CHECK_AND_RETURN_VAL(input.getDir().isFinite(), "PxScene::raycast(): rayDir is not valid.", 0); PX_CHECK_AND_RETURN_VAL(input.getOrigin().isFinite(), "PxScene::raycast(): rayOrigin is not valid.", 0); PX_CHECK_AND_RETURN_VAL(pose1.isValid(), "PxScene::raycast(): pose is not valid.", 0); PX_CHECK_AND_RETURN_VAL(shrunkMaxDistance >= 0.0f, "PxScene::raycast(): maxDist is negative.", 0); PX_CHECK_AND_RETURN_VAL(PxIsFinite(shrunkMaxDistance), "PxScene::raycast(): maxDist is not valid.", 0); PX_CHECK_AND_RETURN_VAL(PxAbs(input.getDir().magnitudeSquared()-1)<1e-4f, "PxScene::raycast(): ray direction must be unit vector.", 0); // PT: TODO: investigate perf difference const RaycastFunc func = funcs.mCachedRaycastFuncs[geom1.getType()]; return func(geom1, pose1, input.getOrigin(), input.getDir(), shrunkMaxDistance, hitFlags, maxHits, reinterpret_cast<PxGeomRaycastHit*>(hits), sizeof(PxRaycastHit), context); } // Handle sweeps else if(HitTypeSupport<HitType>::IsSweep) { PX_ASSERT(precomputedBounds != NULL); PX_ASSERT(sd != NULL); // b0 = query shape bounds // b1 = scene shape bounds // AP: Here we clip the sweep to bounds with sum of extents. This is needed for GJK stability. // because sweep is equivalent to a raycast vs a scene shape with inflated bounds. // This also may (or may not) provide an optimization for meshes because top level of rtree has multiple boxes // and there is no bounds test for the whole mesh elsewhere PxBounds3 b0 = *precomputedBounds, b1; // compute the scene geometry bounds // PT: TODO: avoid recomputing the bounds here Gu::computeBounds(b1, sceneGeom, pose, 0.0f, 1.0f); const PxVec3 combExt = (b0.getExtents() + b1.getExtents())*1.01f; PxF32 tnear, tfar; if(!intersectRayAABB2(-combExt, combExt, b0.getCenter() - b1.getCenter(), input.getDir(), shrunkMaxDistance, tnear, tfar)) // returns (tnear<tfar) if(tnear>tfar) // this second test is needed because shrunkMaxDistance can be 0 for 0 length sweep return 0; PX_ASSERT(input.getDir().isNormalized()); // tfar is now the t where the ray exits the AABB. input.getDir() is normalized const PxVec3& unitDir = input.getDir(); PxSweepHit& sweepHit = reinterpret_cast<PxSweepHit&>(hits[0]); // if we don't start inside the AABB box, offset the start pos, because of precision issues with large maxDist const bool offsetPos = (tnear > GU_RAY_SURFACE_OFFSET); const PxReal offset = offsetPos ? (tnear - GU_RAY_SURFACE_OFFSET) : 0.0f; const PxVec3 offsetVec(offsetPos ? (unitDir*offset) : PxVec3(0.0f)); // we move the geometry we sweep against, so that we avoid the Gu::Capsule/Box recomputation const PxTransform pose1Offset(pose1.p - offsetVec, pose1.q); const PxReal distance = PxMin(tfar, shrunkMaxDistance) - offset; const PxReal inflation = input.inflation; PX_CHECK_AND_RETURN_VAL(pose0.isValid(), "PxScene::sweep(): pose0 is not valid.", 0); PX_CHECK_AND_RETURN_VAL(pose1Offset.isValid(), "PxScene::sweep(): pose1 is not valid.", 0); PX_CHECK_AND_RETURN_VAL(unitDir.isFinite(), "PxScene::sweep(): unitDir is not valid.", 0); PX_CHECK_AND_RETURN_VAL(PxIsFinite(distance), "PxScene::sweep(): distance is not valid.", 0); PX_CHECK_AND_RETURN_VAL((distance >= 0.0f && !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP)) || distance > 0.0f, "PxScene::sweep(): sweep distance must be >=0 or >0 with eASSUME_NO_INITIAL_OVERLAP.", 0); PxU32 retVal = 0; const GeomSweepFuncs& sf = funcs.mCachedSweepFuncs; switch(geom0.getType()) { case PxGeometryType::eSPHERE: { const PxSphereGeometry& sphereGeom = static_cast<const PxSphereGeometry&>(geom0); const PxCapsuleGeometry capsuleGeom(sphereGeom.radius, 0.0f); const Capsule worldCapsule(pose0.p, pose0.p, sphereGeom.radius); // AP: precompute? const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP; const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom1.getType()] : sf.capsuleMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, capsuleGeom, pose0, worldCapsule, unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; case PxGeometryType::eCAPSULE: { const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP; const SweepCapsuleFunc func = precise ? sf.preciseCapsuleMap[geom1.getType()] : sf.capsuleMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, static_cast<const PxCapsuleGeometry&>(geom0), pose0, sd->getGuCapsule(), unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; case PxGeometryType::eBOX: { const bool precise = hitFlags & PxHitFlag::ePRECISE_SWEEP; const SweepBoxFunc func = precise ? sf.preciseBoxMap[geom1.getType()] : sf.boxMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, static_cast<const PxBoxGeometry&>(geom0), pose0, sd->getGuBox(), unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; case PxGeometryType::eCONVEXMESH: { const PxConvexMeshGeometry& convexGeom = static_cast<const PxConvexMeshGeometry&>(geom0); const SweepConvexFunc func = sf.convexMap[geom1.getType()]; retVal = PxU32(func(geom1, pose1Offset, convexGeom, pose0, unitDir, distance, sweepHit, hitFlags, inflation, context)); } break; default: outputError<physx::PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxScene::sweep(): first geometry object parameter must be sphere, capsule, box or convex geometry."); break; } if (retVal) { // we need to offset the distance back sweepHit.distance += offset; // we need to offset the hit position back as we moved the geometry we sweep against sweepHit.position += offsetVec; } return retVal; } // Handle overlaps else if(HitTypeSupport<HitType>::IsOverlap) { const GeomOverlapTable* overlapFuncs = funcs.mCachedOverlapFuncs; return PxU32(Gu::overlap(geom0, pose0, geom1, pose1, overlapFuncs, context)); } else { PX_ALWAYS_ASSERT_MESSAGE("Unexpected template expansion in GeomQueryAny::geomHit"); return 0; } } }; /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE bool applyFilterEquation(const ExtQueryAdapter& adapter, const PrunerPayload& payload, const PxFilterData& queryFd) { // if the filterData field is non-zero, and the bitwise-AND value of filterData AND the shape's // queryFilterData is zero, the shape is skipped. if(queryFd.word0 | queryFd.word1 | queryFd.word2 | queryFd.word3) { // PT: TODO: revisit this, there's an obvious LHS here otherwise // We could maybe make this more flexible and let the user do the filtering // const PxFilterData& objFd = adapter.getFilterData(payload); PxFilterData objFd; adapter.getFilterData(payload, objFd); const PxU32 keep = (queryFd.word0 & objFd.word0) | (queryFd.word1 & objFd.word1) | (queryFd.word2 & objFd.word2) | (queryFd.word3 & objFd.word3); if(!keep) return false; } return true; } static PX_FORCE_INLINE bool applyAllPreFiltersSQ( const ExtQueryAdapter& adapter, const PrunerPayload& payload, const PxActorShape& as, PxQueryHitType::Enum& shapeHitType, const PxQueryFlags& inFilterFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, PxHitFlags& queryFlags/*, PxU32 maxNbTouches*/) { // #MODIFIED // PT: we have to do the static / dynamic filtering here now, because we're operating on N pruners // and we don't know which one(s) are "static", which ones are "dynamic", and which ones are a mix of both. const bool doStatics = filterData.flags & PxQueryFlag::eSTATIC; const bool doDynamic = filterData.flags & PxQueryFlag::eDYNAMIC; const PxType actorType = as.actor->getConcreteType(); const bool isStatic = (actorType == PxConcreteType::eRIGID_STATIC); if(isStatic && !doStatics) return false; if(!isStatic && !doDynamic) return false; //~#MODIFIED if(!(filterData.flags & PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR) && !applyFilterEquation(adapter, payload, filterData.data)) return false; if((inFilterFlags & PxQueryFlag::ePREFILTER) && (filterCall)) { PxHitFlags outQueryFlags = queryFlags; if(filterCall) shapeHitType = filterCall->preFilter(filterData.data, as.shape, as.actor, outQueryFlags); // AP: at this point the callback might return eTOUCH but the touch buffer can be empty, the hit will be discarded //PX_CHECK_MSG(hitType == PxQueryHitType::eTOUCH ? maxNbTouches > 0 : true, // "SceneQuery: preFilter returned eTOUCH but empty touch buffer was provided, hit discarded."); queryFlags = (queryFlags & ~PxHitFlag::eMODIFIABLE_FLAGS) | (outQueryFlags & PxHitFlag::eMODIFIABLE_FLAGS); if(shapeHitType == PxQueryHitType::eNONE) return false; } // test passed, continue to return as; return true; } static PX_NOINLINE void computeCompoundShapeTransform(PxTransform* PX_RESTRICT transform, const PxTransform* PX_RESTRICT compoundPose, const PxTransform* PX_RESTRICT transforms, PxU32 primIndex) { // PT:: tag: scalar transform*transform *transform = (*compoundPose) * transforms[primIndex]; } // struct to access protected data members in the public PxHitCallback API template<typename HitType> struct ExtMultiQueryCallback : public PrunerRaycastCallback, public PrunerOverlapCallback, public CompoundPrunerRaycastCallback, public CompoundPrunerOverlapCallback { const ExtSceneQueries& mScene; const ExtMultiQueryInput& mInput; PxHitCallback<HitType>& mHitCall; const PxHitFlags mHitFlags; const PxQueryFilterData& mFilterData; PxQueryFilterCallback* mFilterCall; PxReal mShrunkDistance; const PxHitFlags mMeshAnyHitFlags; bool mReportTouchesAgain; bool mFarBlockFound; // this is to prevent repeated searches for far block const bool mNoBlock; const bool mAnyHit; // The reason we need these bounds is because we need to know combined(inflated shape) bounds to clip the sweep path // to be tolerable by GJK precision issues. This test is done for (queryShape vs touchedShapes) // So it makes sense to cache the bounds for sweep query shape, otherwise we'd have to recompute them every time // Currently only used for sweeps. const PxBounds3* mQueryShapeBounds; const ShapeData* mShapeData; PxTransform mCompoundShapeTransform; ExtMultiQueryCallback( const ExtSceneQueries& scene, const ExtMultiQueryInput& input, bool anyHit, PxHitCallback<HitType>& hitCall, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, PxReal shrunkDistance) : mScene (scene), mInput (input), mHitCall (hitCall), mHitFlags (hitFlags), mFilterData (filterData), mFilterCall (filterCall), mShrunkDistance (shrunkDistance), mMeshAnyHitFlags ((hitFlags.isSet(PxHitFlag::eMESH_ANY) || anyHit) ? PxHitFlag::eMESH_ANY : PxHitFlag::Enum(0)), mReportTouchesAgain (true), mFarBlockFound (filterData.flags & PxQueryFlag::eNO_BLOCK), mNoBlock (filterData.flags & PxQueryFlag::eNO_BLOCK), mAnyHit (anyHit), mQueryShapeBounds (NULL), mShapeData (NULL) { } bool processTouchHit(const HitType& hit, PxReal& aDist) #if PX_WINDOWS_FAMILY PX_RESTRICT #endif { // -------------------------- handle eTOUCH hits --------------------------------- // for qType=multiple, store the hit. For other qTypes ignore it. // <= is important for initially overlapping sweeps #if PX_CHECKED if(mHitCall.maxNbTouches == 0 && !mFilterData.flags.isSet(PxQueryFlag::eRESERVED)) // issue a warning if eTOUCH was returned by the prefilter, we have 0 touch buffer and not a batch query // not doing for BQ because the touches buffer can be overflown and thats ok by spec // eRESERVED to avoid a warning from nested callback (closest blocking hit recursive search) outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "User filter returned PxQueryHitType::eTOUCH but the touches buffer was empty. Hit was discarded."); #endif if(mHitCall.maxNbTouches && mReportTouchesAgain && HITDIST(hit) <= mShrunkDistance) { // Buffer full: need to find the closest blocking hit, clip touch hits and flush the buffer if(mHitCall.nbTouches == mHitCall.maxNbTouches) { // issue a second nested query just looking for the closest blocking hit // could do better perf-wise by saving traversal state (start looking for blocking from this point) // but this is not a perf critical case because users can provide a bigger buffer // that covers non-degenerate cases // far block search doesn't apply to overlaps because overlaps don't work with blocking hits if(HitTypeSupport<HitType>::IsOverlap == 0) { // AP: the use of eRESERVED is a bit tricky, see other comments containing #LABEL1 PxQueryFilterData fd1 = mFilterData; fd1.flags |= PxQueryFlag::eRESERVED; PxHitBuffer<HitType> buf1; // create a temp callback buffer for a single blocking hit if(!mFarBlockFound && mHitCall.maxNbTouches > 0 && mScene.ExtSceneQueries::multiQuery<HitType>(mInput, buf1, mHitFlags, NULL, fd1, mFilterCall)) { mHitCall.block = buf1.block; mHitCall.hasBlock = true; mHitCall.nbTouches = clipHitsToNewMaxDist<HitType>(mHitCall.touches, mHitCall.nbTouches, HITDIST(buf1.block)); mShrunkDistance = HITDIST(buf1.block); aDist = mShrunkDistance; } mFarBlockFound = true; } if(mHitCall.nbTouches == mHitCall.maxNbTouches) { mReportTouchesAgain = mHitCall.processTouches(mHitCall.touches, mHitCall.nbTouches); if(!mReportTouchesAgain) return false; // optimization - buffer is full else mHitCall.nbTouches = 0; // reset nbTouches so we can continue accumulating again } } //if(hitCall.nbTouches < hitCall.maxNbTouches) // can be true if maxNbTouches is 0 mHitCall.touches[mHitCall.nbTouches++] = hit; } // if(hitCall.maxNbTouches && reportTouchesAgain && HITDIST(hit) <= shrunkDistance) return true; } template<const bool isCached> // is this call coming as a callback from the pruner or a single item cached callback? bool _invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) #if PX_WINDOWS_FAMILY PX_RESTRICT #endif { PX_ASSERT(payloads); const PrunerPayload& payload = payloads[primIndex]; const ExtQueryAdapter& adapter = static_cast<const ExtQueryAdapter&>(mScene.mSQManager.getAdapter()); PxActorShape actorShape; adapter.getActorShape(payload, actorShape); const PxQueryFlags filterFlags = mFilterData.flags; // for no filter callback, default to eTOUCH for MULTIPLE, eBLOCK otherwise // also always treat as eBLOCK if currently tested shape is cached // Using eRESERVED flag as a special condition to default to eTOUCH hits while only looking for a single blocking hit // from a nested query (see other comments containing #LABEL1) PxQueryHitType::Enum shapeHitType = ((mHitCall.maxNbTouches || (mFilterData.flags & PxQueryFlag::eRESERVED)) && !isCached) ? PxQueryHitType::eTOUCH : PxQueryHitType::eBLOCK; // apply pre-filter PxHitFlags filteredHitFlags = mHitFlags; if(!isCached) // don't run filters on single item cache { if(!applyAllPreFiltersSQ(adapter, payload, actorShape, shapeHitType/*in&out*/, filterFlags, mFilterData, mFilterCall, filteredHitFlags/*, mHitCall.maxNbTouches*/)) return true; // skip this shape from reporting if prefilter said to do so // if(shapeHitType == PxQueryHitType::eNONE) // return true; } const PxGeometry& shapeGeom = adapter.getGeometry(payload); PX_ASSERT(transforms); const PxTransform* shapeTransform; if(!compoundPose) { shapeTransform = transforms + primIndex; } else { computeCompoundShapeTransform(&mCompoundShapeTransform, compoundPose, transforms, primIndex); shapeTransform = &mCompoundShapeTransform; } const PxU32 tempCount = 1; HitType tempBuf[tempCount]; // Here we decide whether to use the user provided buffer in place or a local stack buffer // see if we have more room left in the callback results buffer than in the parent stack buffer // if so get subHits in-place in the hit buffer instead of the parent stack buffer // nbTouches is the number of accumulated touch hits so far // maxNbTouches is the size of the user buffer PxU32 maxSubHits1; HitType* subHits1; if(mHitCall.nbTouches >= mHitCall.maxNbTouches) // if there's no room left in the user buffer, use a stack buffer { // tried using 64 here - causes check stack code to get generated on xbox, perhaps because of guard page // need this buffer in case the input buffer is full but we still want to correctly merge results from later hits maxSubHits1 = tempCount; subHits1 = reinterpret_cast<HitType*>(tempBuf); } else { maxSubHits1 = mHitCall.maxNbTouches - mHitCall.nbTouches; // how much room is left in the user buffer subHits1 = mHitCall.touches + mHitCall.nbTouches; // pointer to the first free hit in the user buffer } // call the geometry specific intersection template const PxU32 nbSubHits = ExtGeomQueryAny<HitType>::geomHit( mScene.mCachedFuncs, mInput, mShapeData, shapeGeom, *shapeTransform, filteredHitFlags | mMeshAnyHitFlags, maxSubHits1, subHits1, mShrunkDistance, mQueryShapeBounds, &mHitCall); // ------------------------- iterate over geometry subhits ----------------------------------- for (PxU32 iSubHit = 0; iSubHit < nbSubHits; iSubHit++) { HitType& hit = subHits1[iSubHit]; hit.actor = actorShape.actor; hit.shape = actorShape.shape; // some additional processing only for sweep hits with initial overlap if(HitTypeSupport<HitType>::IsSweep && HITDIST(hit) == 0.0f && !(filteredHitFlags & PxHitFlag::eMTD)) // PT: necessary as some leaf routines are called with reversed params, thus writing +unitDir there. // AP: apparently still necessary to also do in Gu because Gu can be used standalone (without SQ) reinterpret_cast<PxSweepHit&>(hit).normal = -mInput.getDir(); // start out with hitType for this cached shape set to a pre-filtered hit type PxQueryHitType::Enum hitType = shapeHitType; // run the post-filter if specified in filterFlags and filterCall is non-NULL if(!isCached && mFilterCall && (filterFlags & PxQueryFlag::ePOSTFILTER)) { //if(mFilterCall) hitType = mFilterCall->postFilter(mFilterData.data, hit, hit.shape, hit.actor); } // early out on any hit if eANY_HIT was specified, regardless of hit type if(mAnyHit && hitType != PxQueryHitType::eNONE) { // block or touch qualifies for qType=ANY type hit => return it as blocking according to spec. Ignore eNONE. //mHitCall.block = hit; copy(&mHitCall.block, &hit); mHitCall.hasBlock = true; return false; // found a hit for ANY qType, can early exit now } if(mNoBlock && hitType==PxQueryHitType::eBLOCK) hitType = PxQueryHitType::eTOUCH; PX_WARN_ONCE_IF(HitTypeSupport<HitType>::IsOverlap && hitType == PxQueryHitType::eBLOCK, "eBLOCK returned from user filter for overlap() query. This may cause undesired behavior. " "Consider using PxQueryFlag::eNO_BLOCK for overlap queries."); if(hitType == PxQueryHitType::eTOUCH) { if(!processTouchHit(hit, aDist)) return false; } // if(hitType == PxQueryHitType::eTOUCH) else if(hitType == PxQueryHitType::eBLOCK) { // -------------------------- handle eBLOCK hits ---------------------------------- // only eBLOCK qualifies as a closest hit candidate => compare against best distance and store // <= is needed for eTOUCH hits to be recorded correctly vs same eBLOCK distance for overlaps if(HITDIST(hit) <= mShrunkDistance) { if(HitTypeSupport<HitType>::IsOverlap == 0) { mShrunkDistance = HITDIST(hit); aDist = mShrunkDistance; } //mHitCall.block = hit; copy(&mHitCall.block, &hit); mHitCall.hasBlock = true; } } // if(hitType == eBLOCK) else { PX_ASSERT(hitType == PxQueryHitType::eNONE); } } // for iSubHit return true; } virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) { return _invoke<false>(aDist, primIndex, payloads, transforms, NULL); } virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms) { float unused = 0.0f; return _invoke<false>(unused, primIndex, payloads, transforms, NULL); } virtual bool invoke(PxReal& aDist, PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) { return _invoke<false>(aDist, primIndex, payloads, transforms, compoundPose); } virtual bool invoke(PxU32 primIndex, const PrunerPayload* payloads, const PxTransform* transforms, const PxTransform* compoundPose) { float unused = 0.0f; return _invoke<false>(unused, primIndex, payloads, transforms, compoundPose); } private: ExtMultiQueryCallback<HitType>& operator=(const ExtMultiQueryCallback<HitType>&); }; //======================================================================================================================== #if PX_SUPPORT_PVD template<typename HitType> struct ExtCapturePvdOnReturn : public PxHitCallback<HitType> { // copy the arguments of multiQuery into a struct, this is strictly for PVD recording const ExtSceneQueries* mSQ; const ExtMultiQueryInput& mInput; const PxQueryFilterData& mFilterData; PxArray<HitType> mAllHits; PxHitCallback<HitType>& mParentCallback; ExtCapturePvdOnReturn( const ExtSceneQueries* sq, const ExtMultiQueryInput& input, const PxQueryFilterData& filterData, PxHitCallback<HitType>& parentCallback) : PxHitCallback<HitType> (parentCallback.touches, parentCallback.maxNbTouches), mSQ (sq), mInput (input), mFilterData (filterData), mParentCallback (parentCallback) {} virtual PxAgain processTouches(const HitType* hits, PxU32 nbHits) { const PxAgain again = mParentCallback.processTouches(hits, nbHits); for(PxU32 i=0; i<nbHits; i++) mAllHits.pushBack(hits[i]); return again; } ~ExtCapturePvdOnReturn() { ExtPVDCapture* pvd = mSQ->mPVD; if(!pvd || !pvd->transmitSceneQueries()) return; if(mParentCallback.nbTouches) { for(PxU32 i = 0; i < mParentCallback.nbTouches; i++) mAllHits.pushBack(mParentCallback.touches[i]); } if(mParentCallback.hasBlock) mAllHits.pushBack(mParentCallback.block); // PT: TODO: why do we need reinterpret_casts below? if(HitTypeSupport<HitType>::IsRaycast) pvd->raycast(mInput.getOrigin(), mInput.getDir(), mInput.maxDistance, reinterpret_cast<PxRaycastHit*>(mAllHits.begin()), mAllHits.size(), mFilterData, this->maxNbTouches!=0); else if(HitTypeSupport<HitType>::IsOverlap) pvd->overlap(*mInput.geometry, *mInput.pose, reinterpret_cast<PxOverlapHit*>(mAllHits.begin()), mAllHits.size(), mFilterData); else if(HitTypeSupport<HitType>::IsSweep) pvd->sweep (*mInput.geometry, *mInput.pose, mInput.getDir(), mInput.maxDistance, reinterpret_cast<PxSweepHit*>(mAllHits.begin()), mAllHits.size(), mFilterData, this->maxNbTouches!=0); } private: ExtCapturePvdOnReturn<HitType>& operator=(const ExtCapturePvdOnReturn<HitType>&); }; #endif // PX_SUPPORT_PVD //======================================================================================================================== template<typename HitType> struct ExtIssueCallbacksOnReturn { PxHitCallback<HitType>& hits; bool again; // query was stopped by previous processTouches. This means that nbTouches is still non-zero // but we don't need to issue processTouches again PX_FORCE_INLINE ExtIssueCallbacksOnReturn(PxHitCallback<HitType>& aHits) : hits(aHits) { again = true; } ~ExtIssueCallbacksOnReturn() { if(again) // only issue processTouches if query wasn't stopped // this is because nbTouches doesn't get reset to 0 in this case (according to spec) // and the touches in touches array were already processed by the callback { if(hits.hasBlock && hits.nbTouches) hits.nbTouches = clipHitsToNewMaxDist<HitType>(hits.touches, hits.nbTouches, HITDIST(hits.block)); if(hits.nbTouches) { bool again_ = hits.processTouches(hits.touches, hits.nbTouches); if(again_) hits.nbTouches = 0; } } hits.finalizeQuery(); } private: ExtIssueCallbacksOnReturn<HitType>& operator=(const ExtIssueCallbacksOnReturn<HitType>&); }; #undef HITDIST //======================================================================================================================== template<typename HitType> static bool doQueryVsCached(const PrunerHandle handle, PxU32 prunerIndex, const PrunerCompoundId cachedCompoundId, const ExtPrunerManager& manager, ExtMultiQueryCallback<HitType>& pcb, const ExtMultiQueryInput& input); static PX_FORCE_INLINE PxCompoundPrunerQueryFlags convertFlags(PxQueryFlags inFlags) { PxCompoundPrunerQueryFlags outFlags(0); if(inFlags.isSet(PxQueryFlag::eSTATIC)) outFlags.raise(PxCompoundPrunerQueryFlag::eSTATIC); if(inFlags.isSet(PxQueryFlag::eDYNAMIC)) outFlags.raise(PxCompoundPrunerQueryFlag::eDYNAMIC); return outFlags; } // #MODIFIED static PX_FORCE_INLINE bool prunerFilter(const ExtQueryAdapter& adapter, PxU32 prunerIndex, const PxQueryThreadContext* context, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) { // PT: the internal PhysX code can skip an entire pruner by just testing one query flag, since there is a direct // mapping between the static/dynamic flags and the static/dynamic pruners. This is not the case here anymore, // so instead we call a user-provided callback to validate processing each pruner. return adapter.processPruner(prunerIndex, context, filterData, filterCall); } //~#MODIFIED // PT: the following local callbacks are for the "tree of pruners" template<typename HitType> struct LocalBaseCallback { LocalBaseCallback(ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) : mPCB (pcb), mSQManager (manager), mAdapter (adapter), mHits (hits), mFilterData (filterData), mFilterCall (filterCall) {} ExtMultiQueryCallback<HitType>& mPCB; const Sq::ExtPrunerManager& mSQManager; const ExtQueryAdapter& mAdapter; PxHitCallback<HitType>& mHits; const PxQueryFilterData& mFilterData; PxQueryFilterCallback* mFilterCall; PX_FORCE_INLINE const Pruner* filtering(PxU32 prunerIndex) { if(!prunerFilter(mAdapter, prunerIndex, &mHits, mFilterData, mFilterCall)) return NULL; return mSQManager.getPruner(prunerIndex); } PX_NOCOPY(LocalBaseCallback) }; template<typename HitType> struct LocalRaycastCallback : LocalBaseCallback<HitType>, PxBVH::RaycastCallback { LocalRaycastCallback(const ExtMultiQueryInput& input, ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) : LocalBaseCallback<HitType>(pcb, manager, adapter, hits, filterData, filterCall), mInput(input) {} virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) { const Pruner* pruner = LocalBaseCallback<HitType>::filtering(boundsIndex); if(!pruner) return true; return pruner->raycast(mInput.getOrigin(), mInput.getDir(), distance, this->mPCB); } const ExtMultiQueryInput& mInput; PX_NOCOPY(LocalRaycastCallback) }; template<typename HitType> struct LocalOverlapCallback : LocalBaseCallback<HitType>, PxBVH::OverlapCallback { LocalOverlapCallback(const ShapeData& shapeData, ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) : LocalBaseCallback<HitType>(pcb, manager, adapter, hits, filterData, filterCall), mShapeData(shapeData) {} virtual bool reportHit(PxU32 boundsIndex) { const Pruner* pruner = LocalBaseCallback<HitType>::filtering(boundsIndex); if(!pruner) return true; return pruner->overlap(mShapeData, this->mPCB); } const ShapeData& mShapeData; PX_NOCOPY(LocalOverlapCallback) }; template<typename HitType> struct LocalSweepCallback : LocalBaseCallback<HitType>, PxBVH::RaycastCallback { LocalSweepCallback(const ShapeData& shapeData, const PxVec3& dir, ExtMultiQueryCallback<HitType>& pcb, const Sq::ExtPrunerManager& manager, const ExtQueryAdapter& adapter, PxHitCallback<HitType>& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) : LocalBaseCallback<HitType>(pcb, manager, adapter, hits, filterData, filterCall), mShapeData(shapeData), mDir(dir) {} virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) { const Pruner* pruner = LocalBaseCallback<HitType>::filtering(boundsIndex); if(!pruner) return true; return pruner->sweep(mShapeData, mDir, distance, this->mPCB); } const ShapeData& mShapeData; const PxVec3& mDir; PX_NOCOPY(LocalSweepCallback) }; // PT: TODO: revisit error messages without breaking UTs template<typename HitType> bool ExtSceneQueries::multiQuery( const ExtMultiQueryInput& input, PxHitCallback<HitType>& hits, PxHitFlags hitFlags, const PxQueryCache* cache, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall) const { const bool anyHit = (filterData.flags & PxQueryFlag::eANY_HIT) == PxQueryFlag::eANY_HIT; if(HitTypeSupport<HitType>::IsRaycast == 0) { PX_CHECK_AND_RETURN_VAL(input.pose != NULL, "NpSceneQueries::overlap/sweep pose is NULL.", 0); PX_CHECK_AND_RETURN_VAL(input.pose->isValid(), "NpSceneQueries::overlap/sweep pose is not valid.", 0); } else { PX_CHECK_AND_RETURN_VAL(input.getOrigin().isFinite(), "NpSceneQueries::raycast pose is not valid.", 0); } if(HitTypeSupport<HitType>::IsOverlap == 0) { PX_CHECK_AND_RETURN_VAL(input.getDir().isFinite(), "NpSceneQueries multiQuery input check: unitDir is not valid.", 0); PX_CHECK_AND_RETURN_VAL(input.getDir().isNormalized(), "NpSceneQueries multiQuery input check: direction must be normalized", 0); } if(HitTypeSupport<HitType>::IsRaycast) { PX_CHECK_AND_RETURN_VAL(input.maxDistance > 0.0f, "NpSceneQueries::multiQuery input check: distance cannot be negative or zero", 0); } if(HitTypeSupport<HitType>::IsOverlap && !anyHit) { PX_CHECK_AND_RETURN_VAL(hits.maxNbTouches > 0, "PxScene::overlap() calls without eANY_HIT flag require a touch hit buffer for return results.", 0); } if(HitTypeSupport<HitType>::IsSweep) { PX_CHECK_AND_RETURN_VAL(input.maxDistance >= 0.0f, "NpSceneQueries multiQuery input check: distance cannot be negative", 0); PX_CHECK_AND_RETURN_VAL(input.maxDistance != 0.0f || !(hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP), "NpSceneQueries multiQuery input check: zero-length sweep only valid without the PxHitFlag::eASSUME_NO_INITIAL_OVERLAP flag", 0); } PX_CHECK_MSG(!cache || (cache && cache->shape && cache->actor), "Raycast cache specified but shape or actor pointer is NULL!"); PrunerCompoundId cachedCompoundId = INVALID_COMPOUND_ID; // PT: this is similar to the code in the SqRefFinder so we could share that code maybe. But here we later retrieve the payload from the PrunerData, // i.e. we basically go back to the same pointers we started from. I suppose it's to make sure they get properly invalidated when an object is deleted etc, // but we could still probably find a more efficient way to do that here. Isn't it exactly why we had the Signature class initially? // // how can this work anyway? if the actor has been deleted the lookup won't work either => doc says it's up to users to manage that.... const ExtQueryAdapter& adapter = static_cast<const ExtQueryAdapter&>(mSQManager.getAdapter()); PxU32 prunerIndex = 0xffffffff; const PrunerHandle cacheData = cache ? adapter.findPrunerHandle(*cache, cachedCompoundId, prunerIndex) : INVALID_PRUNERHANDLE; // this function is logically const for the SDK user, as flushUpdates() will not have an API-visible effect on this object // internally however, flushUpdates() changes the states of the Pruners in mSQManager // because here is the only place we need this, const_cast instead of making SQM mutable const_cast<ExtSceneQueries*>(this)->mSQManager.flushUpdates(); #if PX_SUPPORT_PVD ExtCapturePvdOnReturn<HitType> pvdCapture(this, input, filterData, hits); #endif ExtIssueCallbacksOnReturn<HitType> cbr(hits); // destructor will execute callbacks on return from this function hits.hasBlock = false; hits.nbTouches = 0; PxReal shrunkDistance = HitTypeSupport<HitType>::IsOverlap ? PX_MAX_REAL : input.maxDistance; // can be progressively shrunk as we go over the list of shapes if(HitTypeSupport<HitType>::IsSweep) shrunkDistance = PxMin(shrunkDistance, PX_MAX_SWEEP_DISTANCE); ExtMultiQueryCallback<HitType> pcb(*this, input, anyHit, hits, hitFlags, filterData, filterCall, shrunkDistance); if(cacheData!=INVALID_PRUNERHANDLE && hits.maxNbTouches == 0) // don't use cache for queries that can return touch hits { if(!doQueryVsCached(cacheData, prunerIndex, cachedCompoundId, mSQManager, pcb, input)) return hits.hasAnyHits(); } const PxU32 nbPruners = mSQManager.getNbPruners(); const CompoundPruner* compoundPruner = mSQManager.getCompoundPruner(); const PxCompoundPrunerQueryFlags compoundPrunerQueryFlags = convertFlags(filterData.flags); const BVH* treeOfPruners = mSQManager.getTreeOfPruners(); if(HitTypeSupport<HitType>::IsRaycast) { // #MODIFIED bool again = true; if(treeOfPruners) { LocalRaycastCallback<HitType> prunerRaycastCB(input, pcb, mSQManager, adapter, hits, filterData, filterCall); again = treeOfPruners->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, prunerRaycastCB, PxGeometryQueryFlag::Enum(0)); if(!again) { cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } else { for(PxU32 i=0;i<nbPruners;i++) { if(prunerFilter(adapter, i, &hits, filterData, filterCall)) { const Pruner* pruner = mSQManager.getPruner(i); again = pruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb); if(!again) { cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } } } //~#MODIFIED if(again && compoundPruner) again = compoundPruner->raycast(input.getOrigin(), input.getDir(), pcb.mShrunkDistance, pcb, compoundPrunerQueryFlags); cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } else if(HitTypeSupport<HitType>::IsOverlap) { PX_ASSERT(input.geometry); const ShapeData sd(*input.geometry, *input.pose, input.inflation); pcb.mShapeData = &sd; // #MODIFIED bool again = true; if(treeOfPruners) { LocalOverlapCallback<HitType> prunerOverlapCB(sd, pcb, mSQManager, adapter, hits, filterData, filterCall); again = treeOfPruners->overlap(*input.geometry, *input.pose, prunerOverlapCB, PxGeometryQueryFlag::Enum(0)); if(!again) { cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } else { for(PxU32 i=0;i<nbPruners;i++) { if(prunerFilter(adapter, i, &hits, filterData, filterCall)) { const Pruner* pruner = mSQManager.getPruner(i); again = pruner->overlap(sd, pcb); if(!again) { cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } } } //~#MODIFIED if(again && compoundPruner) again = compoundPruner->overlap(sd, pcb, compoundPrunerQueryFlags); cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } else { PX_ASSERT(HitTypeSupport<HitType>::IsSweep); PX_ASSERT(input.geometry); const ShapeData sd(*input.geometry, *input.pose, input.inflation); pcb.mQueryShapeBounds = &sd.getPrunerInflatedWorldAABB(); pcb.mShapeData = &sd; // #MODIFIED bool again = true; if(treeOfPruners) { LocalSweepCallback<HitType> prunerSweepCB(sd, input.getDir(), pcb, mSQManager, adapter, hits, filterData, filterCall); again = treeOfPruners->sweep(*input.geometry, *input.pose, input.getDir(), pcb.mShrunkDistance, prunerSweepCB, PxGeometryQueryFlag::Enum(0)); if(!again) { cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } else { for(PxU32 i=0;i<nbPruners;i++) { if(prunerFilter(adapter, i, &hits, filterData, filterCall)) { const Pruner* pruner = mSQManager.getPruner(i); again = pruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb); if(!again) { cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } } } //~#MODIFIED if(again && compoundPruner) again = compoundPruner->sweep(sd, input.getDir(), pcb.mShrunkDistance, pcb, compoundPrunerQueryFlags); cbr.again = again; // update the status to avoid duplicate processTouches() return hits.hasAnyHits(); } } //explicit template instantiation template bool ExtSceneQueries::multiQuery<PxRaycastHit>(const ExtMultiQueryInput&, PxHitCallback<PxRaycastHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; template bool ExtSceneQueries::multiQuery<PxOverlapHit>(const ExtMultiQueryInput&, PxHitCallback<PxOverlapHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; template bool ExtSceneQueries::multiQuery<PxSweepHit>(const ExtMultiQueryInput&, PxHitCallback<PxSweepHit>&, PxHitFlags, const PxQueryCache*, const PxQueryFilterData&, PxQueryFilterCallback*) const; /////////////////////////////////////////////////////////////////////////////// bool ExtSceneQueries::_raycast( const PxVec3& origin, const PxVec3& unitDir, const PxReal distance, PxHitCallback<PxRaycastHit>& hits, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { PX_PROFILE_ZONE("SceneQuery.raycast", getContextId()); PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD) ExtMultiQueryInput input(origin, unitDir, distance); return multiQuery<PxRaycastHit>(input, hits, hitFlags, cache, filterData, filterCall); } ////////////////////////////////////////////////////////////////////////// bool ExtSceneQueries::_overlap( const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hits, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const { PX_PROFILE_ZONE("SceneQuery.overlap", getContextId()); PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD) ExtMultiQueryInput input(&geometry, &pose); return multiQuery<PxOverlapHit>(input, hits, PxHitFlags(), cache, filterData, filterCall); } /////////////////////////////////////////////////////////////////////////////// bool ExtSceneQueries::_sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance, PxHitCallback<PxSweepHit>& hits, PxHitFlags hitFlags, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, const PxReal inflation, PxGeometryQueryFlags flags) const { PX_PROFILE_ZONE("SceneQuery.sweep", getContextId()); PX_SIMD_GUARD_CNDT(flags & PxGeometryQueryFlag::eSIMD_GUARD) #if PX_CHECKED if(!PxGeometryQuery::isValid(geometry)) return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Provided geometry is not valid"); #endif if((hitFlags & PxHitFlag::ePRECISE_SWEEP) && (hitFlags & PxHitFlag::eMTD)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " Precise sweep doesn't support MTD. Perform MTD with default sweep"); hitFlags &= ~PxHitFlag::ePRECISE_SWEEP; } if((hitFlags & PxHitFlag::eASSUME_NO_INITIAL_OVERLAP) && (hitFlags & PxHitFlag::eMTD)) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " eMTD cannot be used in conjunction with eASSUME_NO_INITIAL_OVERLAP. eASSUME_NO_INITIAL_OVERLAP will be ignored"); hitFlags &= ~PxHitFlag::eASSUME_NO_INITIAL_OVERLAP; } PxReal realInflation = inflation; if((hitFlags & PxHitFlag::ePRECISE_SWEEP)&& inflation > 0.f) { realInflation = 0.f; outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, " Precise sweep doesn't support inflation, inflation will be overwritten to be zero"); } ExtMultiQueryInput input(&geometry, &pose, unitDir, distance, realInflation); return multiQuery<PxSweepHit>(input, hits, hitFlags, cache, filterData, filterCall); } /////////////////////////////////////////////////////////////////////////////// template<typename HitType> static bool doQueryVsCached(const PrunerHandle handle, PxU32 prunerIndex, const PrunerCompoundId cachedCompoundId, const ExtPrunerManager& manager, ExtMultiQueryCallback<HitType>& pcb, const ExtMultiQueryInput& input) { // this block is only executed for single shape cache const PrunerPayload* payloads; const PxTransform* compoundPosePtr; PxTransform* transform; PxTransform compoundPose; if(cachedCompoundId == INVALID_COMPOUND_ID) { const Pruner* pruner = manager.getPruner(PruningIndex::Enum(prunerIndex)); PX_ASSERT(pruner); PrunerPayloadData ppd; const PrunerPayload& cachedPayload = pruner->getPayloadData(handle, &ppd); payloads = &cachedPayload; compoundPosePtr = NULL; transform = ppd.mTransform; } else { const CompoundPruner* pruner = manager.getCompoundPruner(); PX_ASSERT(pruner); PrunerPayloadData ppd; const PrunerPayload& cachedPayload = pruner->getPayloadData(handle, cachedCompoundId, &ppd); compoundPose = pruner->getTransform(cachedCompoundId); payloads = &cachedPayload; compoundPosePtr = &compoundPose; transform = ppd.mTransform; } PxReal dummyDist; bool againAfterCache; if(HitTypeSupport<HitType>::IsSweep) { // AP: for sweeps we cache the bounds because we need to know them for the test to clip the sweep to bounds // otherwise GJK becomes unstable. The bounds can be used multiple times so this is an optimization. const ShapeData sd(*input.geometry, *input.pose, input.inflation); pcb.mQueryShapeBounds = &sd.getPrunerInflatedWorldAABB(); pcb.mShapeData = &sd; // againAfterCache = pcb.invoke(dummyDist, 0); againAfterCache = pcb.template _invoke<true>(dummyDist, 0, payloads, transform, compoundPosePtr); pcb.mQueryShapeBounds = NULL; pcb.mShapeData = NULL; } else // againAfterCache = pcb.invoke(dummyDist, 0); againAfterCache = pcb.template _invoke<true>(dummyDist, 0, payloads, transform, compoundPosePtr); return againAfterCache; } /////////////////////////////////////////////////////////////////////////////// ExtSceneQueries::ExtSceneQueries(ExtPVDCapture* pvd, PxU64 contextID, float inflation, const ExtQueryAdapter& adapter, bool usesTreeOfPruners) : mSQManager (contextID, inflation, adapter, usesTreeOfPruners), mPVD (pvd) { } ExtSceneQueries::~ExtSceneQueries() { }
50,766
C++
40.04042
276
0.723713
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCustomGeometryExt.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 "extensions/PxCustomGeometryExt.h" #include <geometry/PxGeometryHelpers.h> #include <geometry/PxGeometryQuery.h> #include <geometry/PxMeshQuery.h> #include <geometry/PxTriangle.h> #include <geometry/PxTriangleMesh.h> #include <geometry/PxTriangleMeshGeometry.h> #include <geomutils/PxContactBuffer.h> #include <common/PxRenderOutput.h> #include <extensions/PxGjkQueryExt.h> #include <extensions/PxMassProperties.h> #include <PxImmediateMode.h> #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; #if PX_SUPPORT_OMNI_PVD using namespace Ext; #endif static const PxU32 gCollisionShapeColor = PxU32(PxDebugColor::eARGB_MAGENTA); /////////////////////////////////////////////////////////////////////////////// static const PxU32 MAX_TRIANGLES = 512; static const PxU32 MAX_TRIANGLE_CONTACTS = 6; const PxReal FACE_CONTACT_THRESHOLD = 0.99999f; struct TrimeshContactFilter { PxU32 triCount; PxU32 triIndices[MAX_TRIANGLES]; PxU32 triAdjacencies[MAX_TRIANGLES][3]; PxU32 triContactCounts[MAX_TRIANGLES][2]; PxContactPoint triContacts[MAX_TRIANGLES][MAX_TRIANGLE_CONTACTS]; TrimeshContactFilter() : triCount(0) {} void addTriangleContacts(const PxContactPoint* points, PxU32 count, const PxU32 triIndex, const PxVec3 triVerts[3], const PxU32 triAdjacency[3]) { if (triCount == MAX_TRIANGLES) return; triIndices[triCount] = triIndex; PxU32& faceContactCount = triContactCounts[triCount][0]; PxU32& edgeContactCount = triContactCounts[triCount][1]; faceContactCount = edgeContactCount = 0; for (PxU32 i = 0; i < 3; ++i) triAdjacencies[triCount][i] = triAdjacency[i]; PxVec3 triNormal = (triVerts[1] - triVerts[0]).cross(triVerts[2] - triVerts[0]).getNormalized(); for (PxU32 i = 0; i < count; ++i) { const PxContactPoint& point = points[i]; bool faceContact = fabsf(point.normal.dot(triNormal)) > FACE_CONTACT_THRESHOLD; if (faceContactCount + edgeContactCount < MAX_TRIANGLE_CONTACTS) { if (faceContact) triContacts[triCount][faceContactCount++] = point; else triContacts[triCount][MAX_TRIANGLE_CONTACTS - 1 - edgeContactCount++] = point; } } ++triCount; } void writeToBuffer(PxContactBuffer& buffer) { for (PxU32 i = 0; i < triCount; ++i) { if (triContactCounts[i][1] > 0) { for (PxU32 j = 0; j < triCount; ++j) { if (triIndices[j] == triAdjacencies[i][0] || triIndices[j] == triAdjacencies[i][1] || triIndices[j] == triAdjacencies[i][2]) { if (triContactCounts[j][0] > 0) { triContactCounts[i][1] = 0; break; } } } } for (PxU32 j = 0; j < triContactCounts[i][0]; ++j) buffer.contact(triContacts[i][j]); for (PxU32 j = 0; j < triContactCounts[i][1]; ++j) buffer.contact(triContacts[i][MAX_TRIANGLE_CONTACTS - 1 - j]); } } PX_NOCOPY(TrimeshContactFilter) }; /////////////////////////////////////////////////////////////////////////////// struct TriangleSupport : PxGjkQuery::Support { PxVec3 v0, v1, v2; PxReal margin; TriangleSupport(const PxVec3& _v0, const PxVec3& _v1, const PxVec3& _v2, PxReal _margin) : v0(_v0), v1(_v1), v2(_v2), margin(_margin) {} virtual PxReal getMargin() const { return margin; } virtual PxVec3 supportLocal(const PxVec3& dir) const { float d0 = dir.dot(v0), d1 = dir.dot(v1), d2 = dir.dot(v2); return (d0 > d1 && d0 > d2) ? v0 : (d1 > d2) ? v1 : v2; } }; /////////////////////////////////////////////////////////////////////////////// static void drawArc(const PxVec3& center, const PxVec3& radius, const PxVec3& axis, PxReal angle, PxReal error, PxRenderOutput& out) { int sides = int(ceilf(angle / (2 * acosf(1.0f - error)))); float step = angle / sides; out << PxRenderOutput::LINESTRIP; for (int i = 0; i <= sides; ++i) out << center + PxQuat(step * i, axis).rotate(radius); } static void drawCircle(const PxVec3& center, const PxVec3& radius, const PxVec3& axis, PxReal error, PxRenderOutput& out) { drawArc(center, radius, axis, PxTwoPi, error, out); } static void drawQuarterCircle(const PxVec3& center, const PxVec3& radius, const PxVec3& axis, PxReal error, PxRenderOutput& out) { drawArc(center, radius, axis, PxPiDivTwo, error, out); } static void drawLine(const PxVec3& s, const PxVec3& e, PxRenderOutput& out) { out << PxRenderOutput::LINES << s << e; } /////////////////////////////////////////////////////////////////////////////// PxBounds3 PxCustomGeometryExt::BaseConvexCallbacks::getLocalBounds(const PxGeometry&) const { const PxVec3 min(supportLocal(PxVec3(-1, 0, 0)).x, supportLocal(PxVec3(0, -1, 0)).y, supportLocal(PxVec3(0, 0, -1)).z); const PxVec3 max(supportLocal(PxVec3(1, 0, 0)).x, supportLocal(PxVec3(0, 1, 0)).y, supportLocal(PxVec3(0, 0, 1)).z); PxBounds3 bounds(min, max); bounds.fattenSafe(getMargin()); return bounds; } bool PxCustomGeometryExt::BaseConvexCallbacks::generateContacts(const PxGeometry& geom0, const PxGeometry& geom1, const PxTransform& pose0, const PxTransform& pose1, const PxReal contactDistance, const PxReal meshContactMargin, const PxReal toleranceLength, PxContactBuffer& contactBuffer) const { struct ContactRecorder : immediate::PxContactRecorder { PxContactBuffer* contactBuffer; ContactRecorder(PxContactBuffer& _contactBuffer) : contactBuffer(&_contactBuffer) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { for (PxU32 i = 0; i < nbContacts; ++i) contactBuffer->contact(contactPoints[i]); return true; } } contactRecorder(contactBuffer); PxCache contactCache; struct ContactCacheAllocator : PxCacheAllocator { PxU8 buffer[1024]; ContactCacheAllocator() { PxMemSet(buffer, 0, sizeof(buffer)); } virtual PxU8* allocateCacheData(const PxU32 /*byteSize*/) { return reinterpret_cast<PxU8*>(size_t(buffer + 0xf) & ~0xf); } } contactCacheAllocator; const PxTransform identityPose(PxIdentity); switch (geom1.getType()) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1); if (PxGjkQueryExt::generateContacts(*this, geomSupport, pose0, pose1, contactDistance, toleranceLength, contactBuffer)) { PxGeometryHolder substituteGeom; PxTransform preTransform; if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0)) { contactBuffer.count--; const PxGeometry* pGeom0 = &substituteGeom.any(); const PxGeometry* pGeom1 = &geom1; // PT:: tag: scalar transform*transform PxTransform pose = pose0.transform(preTransform); immediate::PxGenerateContacts(&pGeom0, &pGeom1, &pose, &pose1, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); } } break; } case PxGeometryType::ePLANE: { const PxPlane plane = PxPlane(1.0f, 0.0f, 0.0f, 0.0f).transform(pose1); const PxPlane localPlane = plane.inverseTransform(pose0); const PxVec3 point = supportLocal(-localPlane.n) - localPlane.n * margin; const float dist = localPlane.distance(point); if (dist < contactDistance) { const PxVec3 n = localPlane.n; const PxVec3 p = point - n * dist * 0.5f; PxContactPoint contact; contact.point = pose0.transform(p); contact.normal = pose0.rotate(n); contact.separation = dist; contactBuffer.contact(contact); PxGeometryHolder substituteGeom; PxTransform preTransform; if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0)) { contactBuffer.count--; const PxGeometry* pGeom0 = &substituteGeom.any(); const PxGeometry* pGeom1 = &geom1; // PT:: tag: scalar transform*transform PxTransform pose = pose0.transform(preTransform); immediate::PxGenerateContacts(&pGeom0, &pGeom1, &pose, &pose1, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); } } break; } case PxGeometryType::eTRIANGLEMESH: case PxGeometryType::eHEIGHTFIELD: { // As a triangle has no thickness, we need to choose some collision margin - the distance // considered a touching contact. I set it as 1% of the custom shape minimum dimension. PxReal meshMargin = getLocalBounds(geom0).getDimensions().minElement() * 0.01f; TrimeshContactFilter contactFilter; bool hasAdjacency = (geom1.getType() != PxGeometryType::eTRIANGLEMESH || (static_cast<const PxTriangleMeshGeometry&>(geom1).triangleMesh->getTriangleMeshFlags() & PxTriangleMeshFlag::eADJACENCY_INFO)); PxBoxGeometry boxGeom(getLocalBounds(geom0).getExtents() + PxVec3(contactDistance + meshMargin)); PxU32 triangles[MAX_TRIANGLES]; bool overflow = false; PxU32 triangleCount = (geom1.getType() == PxGeometryType::eTRIANGLEMESH) ? PxMeshQuery::findOverlapTriangleMesh(boxGeom, pose0, static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow) : PxMeshQuery::findOverlapHeightField(boxGeom, pose0, static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow); if (overflow) PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "PxCustomGeometryExt::BaseConvexCallbacks::generateContacts() Too many triangles.\n"); for (PxU32 i = 0; i < triangleCount; ++i) { PxTriangle tri; PxU32 adjacent[3]; if (geom1.getType() == PxGeometryType::eTRIANGLEMESH) PxMeshQuery::getTriangle(static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles[i], tri, NULL, hasAdjacency ? adjacent : NULL); else PxMeshQuery::getTriangle(static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles[i], tri, NULL, adjacent); TriangleSupport triSupport(tri.verts[0], tri.verts[1], tri.verts[2], meshMargin); if (PxGjkQueryExt::generateContacts(*this, triSupport, pose0, identityPose, contactDistance, toleranceLength, contactBuffer)) { contactBuffer.contacts[contactBuffer.count - 1].internalFaceIndex1 = triangles[i]; PxGeometryHolder substituteGeom; PxTransform preTransform; if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0)) { contactBuffer.count--; const PxGeometry& geom = substituteGeom.any(); // PT:: tag: scalar transform*transform PxTransform pose = pose0.transform(preTransform); PxGeometryQuery::generateTriangleContacts(geom, pose, tri.verts, triangles[i], contactDistance, meshMargin, toleranceLength, contactBuffer); } } if (hasAdjacency) { contactFilter.addTriangleContacts(contactBuffer.contacts, contactBuffer.count, triangles[i], tri.verts, adjacent); contactBuffer.count = 0; } } if (hasAdjacency) contactFilter.writeToBuffer(contactBuffer); break; } case PxGeometryType::eCUSTOM: { const PxCustomGeometry& customGeom1 = static_cast<const PxCustomGeometry&>(geom1); if (customGeom1.getCustomType() == CylinderCallbacks::TYPE() || customGeom1.getCustomType() == ConeCallbacks::TYPE()) // It's a CustomConvex { BaseConvexCallbacks* custom1 = static_cast<BaseConvexCallbacks*>(customGeom1.callbacks); if (PxGjkQueryExt::generateContacts(*this, *custom1, pose0, pose1, contactDistance, toleranceLength, contactBuffer)) { PxGeometryHolder substituteGeom; PxTransform preTransform; if (useSubstituteGeometry(substituteGeom, preTransform, contactBuffer.contacts[contactBuffer.count - 1], pose0)) { contactBuffer.count--; PxU32 oldCount = contactBuffer.count; const PxGeometry* pGeom0 = &substituteGeom.any(); const PxGeometry* pGeom1 = &geom1; // PT:: tag: scalar transform*transform PxTransform pose = pose0.transform(preTransform); immediate::PxGenerateContacts(&pGeom1, &pGeom0, &pose1, &pose, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); for (int i = oldCount; i < int(contactBuffer.count); ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; } } } else { const PxGeometry* pGeom0 = &geom0; const PxGeometry* pGeom1 = &geom1; immediate::PxGenerateContacts(&pGeom1, &pGeom0, &pose1, &pose0, &contactCache, 1, contactRecorder, contactDistance, meshContactMargin, toleranceLength, contactCacheAllocator); for (int i = 0; i < int(contactBuffer.count); ++i) contactBuffer.contacts[i].normal = -contactBuffer.contacts[i].normal; } break; } default: break; } return contactBuffer.count > 0; } PxU32 PxCustomGeometryExt::BaseConvexCallbacks::raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose, PxReal maxDist, PxHitFlags /*hitFlags*/, PxU32 /*maxHits*/, PxGeomRaycastHit* rayHits, PxU32 /*stride*/, PxRaycastThreadContext*) const { // When FLT_MAX is used as maxDist, it works bad with GJK algorithm. // Here I compute the maximum needed distance (wiseDist) as the diagonal // of the bounding box of both the geometry and the ray origin. PxBounds3 bounds = PxBounds3::transformFast(pose, getLocalBounds(geom)); bounds.include(origin); PxReal wiseDist = PxMin(maxDist, bounds.getDimensions().magnitude()); PxReal t; PxVec3 n, p; if (PxGjkQuery::raycast(*this, pose, origin, unitDir, wiseDist, t, n, p)) { PxGeomRaycastHit& hit = *rayHits; hit.distance = t; hit.position = p; hit.normal = n; return 1; } return 0; } bool PxCustomGeometryExt::BaseConvexCallbacks::overlap(const PxGeometry& /*geom0*/, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { switch (geom1.getType()) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1); if (PxGjkQuery::overlap(*this, geomSupport, pose0, pose1)) return true; break; } default: break; } return false; } bool PxCustomGeometryExt::BaseConvexCallbacks::sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry& geom0, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags /*hitFlags*/, const PxReal inflation, PxSweepThreadContext*) const { PxBounds3 bounds0 = PxBounds3::transformFast(pose0, getLocalBounds(geom0)); switch (geom1.getType()) { case PxGeometryType::eSPHERE: case PxGeometryType::eCAPSULE: case PxGeometryType::eBOX: case PxGeometryType::eCONVEXMESH: { // See comment in BaseConvexCallbacks::raycast PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom1, pose1, 0, inflation); bounds.include(bounds0); PxReal wiseDist = PxMin(maxDist, bounds.getDimensions().magnitude()); PxGjkQueryExt::ConvexGeomSupport geomSupport(geom1, inflation); PxReal t; PxVec3 n, p; if (PxGjkQuery::sweep(*this, geomSupport, pose0, pose1, unitDir, wiseDist, t, n, p)) { sweepHit.distance = t; sweepHit.position = p; sweepHit.normal = n; sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL; return true; } break; } // sweep against triangle meshes and height fields for CCD support case PxGeometryType::eTRIANGLEMESH: case PxGeometryType::eHEIGHTFIELD: { PxReal radius = getLocalBounds(geom0).getExtents().magnitude(); PxGeometryHolder sweepGeom = PxSphereGeometry(radius + inflation); PxTransform sweepGeomPose = pose0; if (maxDist > FLT_EPSILON) { sweepGeom = PxCapsuleGeometry(radius + inflation, maxDist * 0.5f); sweepGeomPose = PxTransform(pose0.p - unitDir * maxDist * 0.5f, PxShortestRotation(PxVec3(1, 0, 0), unitDir)); } PxU32 triangles[MAX_TRIANGLES]; bool overflow = false; PxU32 triangleCount = (geom1.getType() == PxGeometryType::eTRIANGLEMESH) ? PxMeshQuery::findOverlapTriangleMesh(sweepGeom.any(), sweepGeomPose, static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow) : PxMeshQuery::findOverlapHeightField(sweepGeom.any(), sweepGeomPose, static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles, MAX_TRIANGLES, 0, overflow); if(overflow) PxGetFoundation().error(PxErrorCode::eDEBUG_INFO, PX_FL, "PxCustomGeometryExt::BaseConvexCallbacks::sweep() Too many triangles.\n"); sweepHit.distance = PX_MAX_F32; const PxTransform identityPose(PxIdentity); for (PxU32 i = 0; i < triangleCount; ++i) { PxTriangle tri; if (geom1.getType() == PxGeometryType::eTRIANGLEMESH) PxMeshQuery::getTriangle(static_cast<const PxTriangleMeshGeometry&>(geom1), pose1, triangles[i], tri); else PxMeshQuery::getTriangle(static_cast<const PxHeightFieldGeometry&>(geom1), pose1, triangles[i], tri); TriangleSupport triSupport(tri.verts[0], tri.verts[1], tri.verts[2], inflation); PxBounds3 bounds = bounds0; for (PxU32 j = 0; j < 3; ++j) bounds.include(tri.verts[j]); bounds.fattenFast(inflation); // See comment in BaseConvexCallbacks::raycast PxReal wiseDist = PxMin(maxDist, bounds.getDimensions().magnitude()); PxReal t; PxVec3 n, p; if (PxGjkQuery::sweep(*this, triSupport, pose0, identityPose, unitDir, wiseDist, t, n, p)) { if (sweepHit.distance > t) { sweepHit.faceIndex = triangles[i]; sweepHit.distance = t; sweepHit.position = p; sweepHit.normal = n; sweepHit.flags = PxHitFlag::ePOSITION | PxHitFlag::eNORMAL | PxHitFlag::eFACE_INDEX; } } } if (sweepHit.distance < PX_MAX_F32) return true; break; } default: break; } return false; } bool PxCustomGeometryExt::BaseConvexCallbacks::usePersistentContactManifold(const PxGeometry& /*geometry*/, PxReal& breakingThreshold) const { // Even if we don't use persistent manifold, we still need to set proper breakingThreshold // because the other geometry still can force the PCM usage. FLT_EPSILON ensures that // the contacts will be discarded and recomputed every frame if actor moves. breakingThreshold = FLT_EPSILON; return false; } void PxCustomGeometryExt::BaseConvexCallbacks::setMargin(float m) { margin = m; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtBaseConvexCallbacks, margin, *this, margin); #endif } /////////////////////////////////////////////////////////////////////////////// IMPLEMENT_CUSTOM_GEOMETRY_TYPE(PxCustomGeometryExt::CylinderCallbacks) PxCustomGeometryExt::CylinderCallbacks::CylinderCallbacks(float _height, float _radius, int _axis, float _margin) : BaseConvexCallbacks(_margin), height(_height), radius(_radius), axis(_axis) { #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, *this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtBaseConvexCallbacks, margin, *static_cast<BaseConvexCallbacks*>(this), margin); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, height, *this, height); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, radius, *this, radius); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, axis, *this, axis); OMNI_PVD_WRITE_SCOPE_END #endif } void PxCustomGeometryExt::CylinderCallbacks::setHeight(float h) { height = h; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, height, *this, height); #endif } void PxCustomGeometryExt::CylinderCallbacks::setRadius(float r) { radius = r; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, radius, *this, radius); #endif } void PxCustomGeometryExt::CylinderCallbacks::setAxis(int a) { axis = a; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtCylinderCallbacks, axis, *this, axis); #endif } void PxCustomGeometryExt::CylinderCallbacks::visualize(const PxGeometry&, PxRenderOutput& out, const PxTransform& transform, const PxBounds3&) const { const float ERR = 0.001f; out << gCollisionShapeColor; out << transform; int axis1 = (axis + 1) % 3; int axis2 = (axis + 2) % 3; PxVec3 zr(PxZero), rd(PxZero), ax(PxZero), ax1(PxZero), ax2(PxZero), r0(PxZero), r1(PxZero); ax[axis] = ax1[axis1] = ax2[axis2] = 1.0f; r0[axis1] = r1[axis2] = radius; rd[axis1] = radius; rd[axis] = -(height * 0.5f + margin); drawCircle(zr, rd, ax, ERR, out); rd[axis] = (height * 0.5f + margin); drawCircle(zr, rd, ax, ERR, out); rd[axis1] = radius + margin; rd[axis] = -(height * 0.5f); drawCircle(zr, rd, ax, ERR, out); rd[axis] = (height * 0.5f); drawCircle(zr, rd, ax, ERR, out); drawLine(-ax * height * 0.5f + ax1 * (radius + margin), ax * height * 0.5f + ax1 * (radius + margin), out); drawLine(-ax * height * 0.5f - ax1 * (radius + margin), ax * height * 0.5f - ax1 * (radius + margin), out); drawLine(-ax * height * 0.5f + ax2 * (radius + margin), ax * height * 0.5f + ax2 * (radius + margin), out); drawLine(-ax * height * 0.5f - ax2 * (radius + margin), ax * height * 0.5f - ax2 * (radius + margin), out); drawQuarterCircle(-ax * height * 0.5f + ax1 * radius, -ax * margin, -ax2, ERR, out); drawQuarterCircle(-ax * height * 0.5f - ax1 * radius, -ax * margin, ax2, ERR, out); drawQuarterCircle(-ax * height * 0.5f + ax2 * radius, -ax * margin, ax1, ERR, out); drawQuarterCircle(-ax * height * 0.5f - ax2 * radius, -ax * margin, -ax1, ERR, out); drawQuarterCircle(ax * height * 0.5f + ax1 * radius, ax * margin, ax2, ERR, out); drawQuarterCircle(ax * height * 0.5f - ax1 * radius, ax * margin, -ax2, ERR, out); drawQuarterCircle(ax * height * 0.5f + ax2 * radius, ax * margin, -ax1, ERR, out); drawQuarterCircle(ax * height * 0.5f - ax2 * radius, ax * margin, ax1, ERR, out); } PxVec3 PxCustomGeometryExt::CylinderCallbacks::supportLocal(const PxVec3& dir) const { float halfHeight = height * 0.5f; PxVec3 d = dir.getNormalized(); switch (axis) { case 0: // X { if (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0); return PxVec3(PxSign2(d.x) * halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius; } case 1: // Y { if (PxSign2(d.x) == 0 && PxSign2(d.y) != 0 && PxSign2(d.z) == 0) return PxVec3(0, PxSign2(d.y) * halfHeight, 0); return PxVec3(0, PxSign2(d.y) * halfHeight, 0) + PxVec3(d.x, 0, d.z).getNormalized() * radius; } case 2: // Z { if (PxSign2(d.x) == 0 && PxSign2(d.y) == 0 && PxSign2(d.z) != 0) return PxVec3(0, 0, PxSign2(d.z) * halfHeight); return PxVec3(0, 0, PxSign2(d.z) * halfHeight) + PxVec3(d.x, d.y, 0).getNormalized() * radius; } } return PxVec3(0); } void PxCustomGeometryExt::CylinderCallbacks::computeMassProperties(const PxGeometry& /*geometry*/, PxMassProperties& massProperties) const { if (margin == 0) { PxMassProperties& mass = massProperties; float R = radius, H = height; mass.mass = PxPi * R * R * H; mass.inertiaTensor = PxMat33(PxZero); mass.centerOfMass = PxVec3(PxZero); float I0 = mass.mass * R * R / 2.0f; float I1 = mass.mass * (3 * R * R + H * H) / 12.0f; mass.inertiaTensor[axis][axis] = I0; mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1; } else { const int SLICE_COUNT = 32; PxMassProperties sliceMasses[SLICE_COUNT]; PxTransform slicePoses[SLICE_COUNT]; float sliceHeight = height / SLICE_COUNT; for (int i = 0; i < SLICE_COUNT; ++i) { float t = -height * 0.5f + i * sliceHeight + sliceHeight * 0.5f; float R = getRadiusAtHeight(t), H = sliceHeight; PxMassProperties mass; mass.mass = PxPi * R * R * H; mass.inertiaTensor = PxMat33(PxZero); mass.centerOfMass = PxVec3(PxZero); float I0 = mass.mass * R * R / 2.0f; float I1 = mass.mass * (3 * R * R + H * H) / 12.0f; mass.inertiaTensor[axis][axis] = I0; mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1; mass.centerOfMass[axis] = t; sliceMasses[i] = mass; slicePoses[i] = PxTransform(PxIdentity); } massProperties = PxMassProperties::sum(sliceMasses, slicePoses, SLICE_COUNT); } } bool PxCustomGeometryExt::CylinderCallbacks::useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const { // here I check if we contact with the cylender bases or the lateral surface // where more than 1 contact point can be generated. PxVec3 locN = pose0.rotateInv(p.normal); float nAng = acosf(PxClamp(-locN[axis], -1.0f, 1.0f)); float epsAng = PxPi / 36.0f; // 5 degrees if (nAng < epsAng || nAng > PxPi - epsAng) { // if we contact with the bases // make the substitute geometry a box and rotate it so one of // the corners matches the contact point PxVec3 halfSize; halfSize[axis] = height * 0.5f + margin; halfSize[(axis + 1) % 3] = halfSize[(axis + 2) % 3] = radius / sqrtf(2.0f); geom = PxBoxGeometry(halfSize); PxVec3 axisDir(PxZero); axisDir[axis] = 1.0f; PxVec3 locP = pose0.transformInv(p.point); float s1 = locP[(axis + 1) % 3], s2 = locP[(axis + 2) % 3]; float ang = ((s1 * s1) + (s2 * s2) > 1e-3f) ? atan2f(s2, s1) : 0; preTransform = PxTransform(PxQuat(ang + PxPi * 0.25f, axisDir)); return true; } else if (nAng > PxPiDivTwo - epsAng && nAng < PxPiDivTwo + epsAng) { // if it's the lateral surface // make the substitute geometry a capsule and rotate it so it aligns // with the cylinder surface geom = PxCapsuleGeometry(radius + margin, height * 0.5f); switch (axis) { case 0: preTransform = PxTransform(PxIdentity); break; case 1: preTransform = PxTransform(PxQuat(PxPi * 0.5f, PxVec3(0, 0, 1))); break; case 2: preTransform = PxTransform(PxQuat(PxPi * 0.5f, PxVec3(0, 1, 0))); break; } return true; } return false; } float PxCustomGeometryExt::CylinderCallbacks::getRadiusAtHeight(float h) const { if (h >= -height * 0.5f && h <= height * 0.5f) return radius + margin; if (h < -height * 0.5f) { float a = -h - height * 0.5f; return radius + sqrtf(margin * margin - a * a); } if (h > height * 0.5f) { float a = h - height * 0.5f; return radius + sqrtf(margin * margin - a * a); } PX_ASSERT(0); return 0; } /////////////////////////////////////////////////////////////////////////////// IMPLEMENT_CUSTOM_GEOMETRY_TYPE(PxCustomGeometryExt::ConeCallbacks) PxCustomGeometryExt::ConeCallbacks::ConeCallbacks(float _height, float _radius, int _axis, float _margin) : BaseConvexCallbacks(_margin), height(_height), radius(_radius), axis(_axis) { #if PX_SUPPORT_OMNI_PVD OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_CREATE_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, *this); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtBaseConvexCallbacks, margin, *static_cast<BaseConvexCallbacks*>(this), margin); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, height, *this, height); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, radius, *this, radius); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, axis, *this, axis); OMNI_PVD_WRITE_SCOPE_END #endif } void PxCustomGeometryExt::ConeCallbacks::setHeight(float h) { height = h; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, height, *this, height); #endif } void PxCustomGeometryExt::ConeCallbacks::setRadius(float r) { radius = r; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, radius, *this, radius); #endif } void PxCustomGeometryExt::ConeCallbacks::setAxis(int a) { axis = a; #if PX_SUPPORT_OMNI_PVD OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxCustomGeometryExtConeCallbacks, axis, *this, axis); #endif } void PxCustomGeometryExt::ConeCallbacks::visualize(const PxGeometry&, PxRenderOutput& out, const PxTransform& transform, const PxBounds3&) const { const float ERR = 0.001f; out << gCollisionShapeColor; out << transform; int axis1 = (axis + 1) % 3; int axis2 = (axis + 2) % 3; PxVec3 zr(PxZero), rd(PxZero), ax(PxZero), ax1(PxZero), ax2(PxZero), r0(PxZero), r1(PxZero); ax[axis] = ax1[axis1] = ax2[axis2] = 1.0f; r0[axis1] = r1[axis2] = radius; float ang = atan2f(radius, height); float aSin = sinf(ang); rd[axis1] = radius; rd[axis] = -(height * 0.5f + margin); drawCircle(zr, rd, ax, ERR, out); rd[axis] = -(height * 0.5f) + margin * aSin; rd[axis1] = getRadiusAtHeight(rd[axis]); drawCircle(zr, rd, ax, ERR, out); rd[axis] = height * 0.5f + margin * aSin; rd[axis1] = getRadiusAtHeight(rd[axis]); drawCircle(zr, rd, ax, ERR, out); float h0 = -height * 0.5f + margin * aSin, h1 = height * 0.5f + margin * aSin; float s0 = getRadiusAtHeight(h0), s1 = getRadiusAtHeight(h1); drawLine(ax * h0 + ax1 * s0, ax * h1 + ax1 * s1, out); drawLine(ax * h0 - ax1 * s0, ax * h1 - ax1 * s1, out); drawLine(ax * h0 + ax2 * s0, ax * h1 + ax2 * s1, out); drawLine(ax * h0 - ax2 * s0, ax * h1 - ax2 * s1, out); drawArc(-ax * height * 0.5f + ax1 * radius, -ax * margin, -ax2, PxPiDivTwo + ang, ERR, out); drawArc(-ax * height * 0.5f - ax1 * radius, -ax * margin, ax2, PxPiDivTwo + ang, ERR, out); drawArc(-ax * height * 0.5f + ax2 * radius, -ax * margin, ax1, PxPiDivTwo + ang, ERR, out); drawArc(-ax * height * 0.5f - ax2 * radius, -ax * margin, -ax1, PxPiDivTwo + ang, ERR, out); drawArc(ax * height * 0.5f, ax * margin, ax2, PxPiDivTwo - ang, ERR, out); drawArc(ax * height * 0.5f, ax * margin, -ax2, PxPiDivTwo - ang, ERR, out); drawArc(ax * height * 0.5f, ax * margin, -ax1, PxPiDivTwo - ang, ERR, out); drawArc(ax * height * 0.5f, ax * margin, ax1, PxPiDivTwo - ang, ERR, out); } PxVec3 PxCustomGeometryExt::ConeCallbacks::supportLocal(const PxVec3& dir) const { float halfHeight = height * 0.5f; float cosAlph = radius / sqrtf(height * height + radius * radius); PxVec3 d = dir.getNormalized(); switch (axis) { case 0: // X { if (d.x > cosAlph || (PxSign2(d.x) != 0 && PxSign2(d.y) == 0 && PxSign2(d.z) == 0)) return PxVec3(PxSign2(d.x) * halfHeight, 0, 0); return PxVec3(-halfHeight, 0, 0) + PxVec3(0, d.y, d.z).getNormalized() * radius; } case 1: // Y { if (d.y > cosAlph || (PxSign2(d.y) != 0 && PxSign2(d.x) == 0 && PxSign2(d.z) == 0)) return PxVec3(0, PxSign2(d.y) * halfHeight, 0); return PxVec3(0, -halfHeight, 0) + PxVec3(d.x, 0, d.z).getNormalized() * radius; } case 2: // Z { if (d.z > cosAlph || (PxSign2(d.z) != 0 && PxSign2(d.x) == 0 && PxSign2(d.y) == 0)) return PxVec3(0, 0, PxSign2(d.z) * halfHeight); return PxVec3(0, 0, -halfHeight) + PxVec3(d.x, d.y, 0).getNormalized() * radius; } } return PxVec3(0); } void PxCustomGeometryExt::ConeCallbacks::computeMassProperties(const PxGeometry& /*geometry*/, PxMassProperties& massProperties) const { if (margin == 0) { PxMassProperties& mass = massProperties; float H = height, R = radius; mass.mass = PxPi * R * R * H / 3.0f; mass.inertiaTensor = PxMat33(PxZero); mass.centerOfMass = PxVec3(PxZero); float I0 = mass.mass * R * R * 3.0f / 10.0f; float I1 = mass.mass * (R * R * 3.0f / 20.0f + H * H * 3.0f / 80.0f); mass.inertiaTensor[axis][axis] = I0; mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1; mass.centerOfMass[axis] = -H / 4.0f; mass.inertiaTensor = PxMassProperties::translateInertia(mass.inertiaTensor, mass.mass, mass.centerOfMass); } else { const int SLICE_COUNT = 32; PxMassProperties sliceMasses[SLICE_COUNT]; PxTransform slicePoses[SLICE_COUNT]; float sliceHeight = height / SLICE_COUNT; for (int i = 0; i < SLICE_COUNT; ++i) { float t = -height * 0.5f + i * sliceHeight + sliceHeight * 0.5f; float R = getRadiusAtHeight(t), H = sliceHeight; PxMassProperties mass; mass.mass = PxPi * R * R * H; mass.inertiaTensor = PxMat33(PxZero); mass.centerOfMass = PxVec3(PxZero); float I0 = mass.mass * R * R / 2.0f; float I1 = mass.mass * (3 * R * R + H * H) / 12.0f; mass.inertiaTensor[axis][axis] = I0; mass.inertiaTensor[(axis + 1) % 3][(axis + 1) % 3] = mass.inertiaTensor[(axis + 2) % 3][(axis + 2) % 3] = I1; mass.centerOfMass[axis] = t; sliceMasses[i] = mass; slicePoses[i] = PxTransform(PxIdentity); } massProperties = PxMassProperties::sum(sliceMasses, slicePoses, SLICE_COUNT); massProperties.inertiaTensor = PxMassProperties::translateInertia(massProperties.inertiaTensor, massProperties.mass, massProperties.centerOfMass); } } bool PxCustomGeometryExt::ConeCallbacks::useSubstituteGeometry(PxGeometryHolder& geom, PxTransform& preTransform, const PxContactPoint& p, const PxTransform& pose0) const { // here I check if we contact with the cone base or the lateral surface // where more than 1 contact point can be generated. PxVec3 locN = pose0.rotateInv(p.normal); float nAng = acosf(PxClamp(-locN[axis], -1.0f, 1.0f)); float epsAng = PxPi / 36.0f; // 5 degrees float coneAng = atan2f(radius, height); if (nAng > PxPi - epsAng) { // if we contact with the base // make the substitute geometry a box and rotate it so one of // the corners matches the contact point PxVec3 halfSize; halfSize[axis] = height * 0.5f + margin; halfSize[(axis + 1) % 3] = halfSize[(axis + 2) % 3] = radius / sqrtf(2.0f); geom = PxBoxGeometry(halfSize); PxVec3 axisDir(PxZero); axisDir[axis] = 1.0f; PxVec3 locP = pose0.transformInv(p.point); float s1 = locP[(axis + 1) % 3], s2 = locP[(axis + 2) % 3]; float ang = ((s1 * s1) + (s2 * s2) > 1e-3f) ? atan2f(s2, s1) : 0; preTransform = PxTransform(PxQuat(ang + PxPi * 0.25f, axisDir)); return true; } else if (nAng > PxPiDivTwo - coneAng - epsAng && nAng < PxPiDivTwo - coneAng + epsAng) { // if it's the lateral surface // make the substitute geometry a capsule and rotate it so it aligns // with the cone surface geom = PxCapsuleGeometry(radius * 0.25f + margin, sqrtf(height * height + radius * radius) * 0.5f); switch (axis) { case 0: { PxVec3 capC = (PxVec3(height * 0.5f, 0, 0) + PxVec3(-height * 0.5f, radius, 0)) * 0.5f - PxVec3(radius, height, 0).getNormalized() * radius * 0.25f; preTransform = PxTransform(capC, PxQuat(-coneAng, PxVec3(0, 0, 1))); break; } case 1: { PxVec3 capC = (PxVec3(0, height * 0.5f, 0) + PxVec3(0, -height * 0.5f, radius)) * 0.5f - PxVec3(0, radius, height).getNormalized() * radius * 0.25f; preTransform = PxTransform(capC, PxQuat(-coneAng, PxVec3(1, 0, 0)) * PxQuat(PxPiDivTwo, PxVec3(0, 0, 1))); break; } case 2: { PxVec3 capC = (PxVec3(0, 0, height * 0.5f) + PxVec3(radius, 0, -height * 0.5f)) * 0.5f - PxVec3(height, 0, radius).getNormalized() * radius * 0.25f; preTransform = PxTransform(capC, PxQuat(-coneAng, PxVec3(0, 1, 0)) * PxQuat(PxPiDivTwo, PxVec3(0, 1, 0))); break; } } PxVec3 axisDir(PxZero); axisDir[axis] = 1.0f; float n1 = -locN[(axis + 1) % 3], n2 = -locN[(axis + 2) % 3]; float ang = atan2f(n2, n1); // PT:: tag: scalar transform*transform preTransform = PxTransform(PxQuat(ang, axisDir)) * preTransform; return true; } return false; } float PxCustomGeometryExt::ConeCallbacks::getRadiusAtHeight(float h) const { float angle = atan2f(radius, height); float aSin = sinf(angle); float aCos = cosf(angle); if (h >= -height * 0.5f + margin * aSin && h <= height * 0.5f + margin * aSin) return radius * (height * 0.5f - h) / height + margin / aCos; if (h < -height * 0.5f + margin * aSin) { float a = -h - height * 0.5f; return radius + sqrtf(margin * margin - a * a); } if (h > height * 0.5f + margin * aSin) { float a = h - height * 0.5f; return sqrtf(margin * margin - a * a); } PX_ASSERT(0); return 0; }
37,760
C++
37.142424
203
0.693459
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtJoint.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 "ExtJoint.h" #include "omnipvd/ExtOmniPvdSetData.h" using namespace physx; using namespace Ext; // PX_SERIALIZATION PxConstraint* physx::resolveConstraintPtr(PxDeserializationContext& v, PxConstraint* old, PxConstraintConnector* connector, PxConstraintShaderTable &shaders) { v.translatePxBase(old); PxConstraint* new_nx = static_cast<PxConstraint*>(old); new_nx->setConstraintFunctions(*connector, shaders); return new_nx; } //~PX_SERIALIZATION static void normalToTangents(const PxVec3& n, PxVec3& t1, PxVec3& t2) { const PxReal m_sqrt1_2 = PxReal(0.7071067811865475244008443621048490); if(fabsf(n.z) > m_sqrt1_2) { const PxReal a = n.y*n.y + n.z*n.z; const PxReal k = PxReal(1.0)/PxSqrt(a); t1 = PxVec3(0,-n.z*k,n.y*k); t2 = PxVec3(a*k,-n.x*t1.z,n.x*t1.y); } else { const PxReal a = n.x*n.x + n.y*n.y; const PxReal k = PxReal(1.0)/PxSqrt(a); t1 = PxVec3(-n.y*k,n.x*k,0); t2 = PxVec3(-n.z*t1.y,n.z*t1.x,a*k); } t1.normalize(); t2.normalize(); } void PxSetJointGlobalFrame(PxJoint& joint, const PxVec3* wsAnchor, const PxVec3* axisIn) { PxRigidActor* actors[2]; joint.getActors(actors[0], actors[1]); PxTransform localPose[2]; for(PxU32 i=0; i<2; i++) localPose[i] = PxTransform(PxIdentity); // 1) global anchor if(wsAnchor) { //transform anchorPoint to local space for(PxU32 i=0; i<2; i++) localPose[i].p = actors[i] ? actors[i]->getGlobalPose().transformInv(*wsAnchor) : *wsAnchor; } // 2) global axis if(axisIn) { PxVec3 localAxis[2], localNormal[2]; //find 2 orthogonal vectors. //gotta do this in world space, if we choose them //separately in local space they won't match up in worldspace. PxVec3 axisw = *axisIn; axisw.normalize(); PxVec3 normalw, binormalw; ::normalToTangents(axisw, binormalw, normalw); //because axis is supposed to be the Z axis of a frame with the other two being X and Y, we need to negate //Y to make the frame right handed. Note that the above call makes a right handed frame if we pass X --> Y,Z, so //it need not be changed. for(PxU32 i=0; i<2; i++) { if(actors[i]) { const PxTransform& m = actors[i]->getGlobalPose(); PxMat33 mM(m.q); localAxis[i] = mM.transformTranspose(axisw); localNormal[i] = mM.transformTranspose(normalw); } else { localAxis[i] = axisw; localNormal[i] = normalw; } PxMat33 rot(localAxis[i], localNormal[i], localAxis[i].cross(localNormal[i])); localPose[i].q = PxQuat(rot); localPose[i].q.normalize(); } } for(PxU32 i=0; i<2; i++) joint.setLocalPose(static_cast<PxJointActorIndex::Enum>( i ), localPose[i]); } #if PX_SUPPORT_OMNI_PVD void physx::Ext::omniPvdSetBaseJointParams(PxJoint& joint, PxJointConcreteType::Enum cType) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) PxJoint& j = static_cast<PxJoint&>(joint); PxRigidActor* actors[2]; j.getActors(actors[0], actors[1]); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0, j, actors[0]) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1, j, actors[1]) PxTransform actor0LocalPose = j.getLocalPose(PxJointActorIndex::eACTOR0); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor0LocalPose, j, actor0LocalPose) PxTransform actor1LocalPose = j.getLocalPose(PxJointActorIndex::eACTOR1); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, actor1LocalPose, j, actor1LocalPose) PxReal breakForce, breakTorque; j.getBreakForce(breakForce, breakTorque); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakForce, j, breakForce) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, breakTorque, j, breakTorque) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, constraintFlags, j, j.getConstraintFlags()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale0, j, j.getInvMassScale0()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale0, j, j.getInvInertiaScale0()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invMassScale1, j, j.getInvMassScale1()) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, invInertiaScale1, j, j.getInvInertiaScale1()) const char* name = j.getName() ? j.getName() : ""; PxU32 nameLen = PxU32(strlen(name)) + 1; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, name, j, name, nameLen) const char* typeName = j.getConcreteTypeName(); PxU32 typeNameLen = PxU32(strlen(typeName)) + 1; OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, concreteTypeName, j, typeName, typeNameLen) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxJoint, type, j, cType) OMNI_PVD_WRITE_SCOPE_END } #endif
6,667
C++
40.416149
157
0.736013
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtCpuWorkerThread.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 "task/PxTask.h" #include "ExtCpuWorkerThread.h" #include "ExtDefaultCpuDispatcher.h" #include "ExtTaskQueueHelper.h" #include "foundation/PxFPU.h" using namespace physx; Ext::CpuWorkerThread::CpuWorkerThread() : mQueueEntryPool(EXT_TASK_QUEUE_ENTRY_POOL_SIZE), mThreadId(0) { } Ext::CpuWorkerThread::~CpuWorkerThread() { } void Ext::CpuWorkerThread::initialize(DefaultCpuDispatcher* ownerDispatcher) { mOwner = ownerDispatcher; } bool Ext::CpuWorkerThread::tryAcceptJobToLocalQueue(PxBaseTask& task, PxThread::Id taskSubmitionThread) { if(taskSubmitionThread == mThreadId) { SharedQueueEntry* entry = mQueueEntryPool.getEntry(&task); if (entry) { mLocalJobList.push(*entry); return true; } else return false; } return false; } PxBaseTask* Ext::CpuWorkerThread::giveUpJob() { return TaskQueueHelper::fetchTask(mLocalJobList, mQueueEntryPool); } void Ext::CpuWorkerThread::execute() { mThreadId = getId(); const PxDefaultCpuDispatcherWaitForWorkMode::Enum ownerWaitForWorkMode = mOwner->getWaitForWorkMode(); while(!quitIsSignalled()) { if(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == ownerWaitForWorkMode) mOwner->resetWakeSignal(); PxBaseTask* task = TaskQueueHelper::fetchTask(mLocalJobList, mQueueEntryPool); if(!task) task = mOwner->fetchNextTask(); if(task) { mOwner->runTask(*task); task->release(); } else if(PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_THREAD == ownerWaitForWorkMode) { PxThread::yield(); } else if(PxDefaultCpuDispatcherWaitForWorkMode::eYIELD_PROCESSOR == ownerWaitForWorkMode) { const PxU32 pauseCounter = mOwner->getYieldProcessorCount(); for(PxU32 j = 0; j < pauseCounter; j++) PxThread::yieldProcesor(); } else { PX_ASSERT(PxDefaultCpuDispatcherWaitForWorkMode::eWAIT_FOR_WORK == ownerWaitForWorkMode); mOwner->waitForWork(); } } quit(); }
3,602
C++
30.605263
103
0.752915
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtSqManager.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 "ExtSqManager.h" #define SQ_DEBUG_VIZ_STATIC_COLOR PxU32(PxDebugColor::eARGB_BLUE) #define SQ_DEBUG_VIZ_DYNAMIC_COLOR PxU32(PxDebugColor::eARGB_RED) #define SQ_DEBUG_VIZ_STATIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKBLUE) #define SQ_DEBUG_VIZ_DYNAMIC_COLOR2 PxU32(PxDebugColor::eARGB_DARKRED) #define SQ_DEBUG_VIZ_COMPOUND_COLOR PxU32(PxDebugColor::eARGB_MAGENTA) #include "GuBounds.h" using namespace physx; using namespace Sq; using namespace Gu; /////////////////////////////////////////////////////////////////////////////// #include "SqFactory.h" #include "common/PxProfileZone.h" #include "common/PxRenderBuffer.h" #include "GuBVH.h" #include "foundation/PxAlloca.h" // PT: this is a customized version of physx::Sq::PrunerManager that supports more than 2 hardcoded pruners. // It might not be possible to support the whole PxSceneQuerySystem API with an arbitrary number of pruners. ExtPrunerManager::ExtPrunerManager(PxU64 contextID, float inflation, const Adapter& adapter, bool usesTreeOfPruners) : mAdapter (adapter), mTreeOfPruners (NULL), mContextID (contextID), mStaticTimestamp (0), mRebuildRateHint (100), mInflation (inflation), mPrunerNeedsUpdating (false), mTimestampNeedsUpdating (false), mUsesTreeOfPruners (usesTreeOfPruners) { mCompoundPrunerExt.mPruner = createCompoundPruner(contextID); } ExtPrunerManager::~ExtPrunerManager() { PX_DELETE(mTreeOfPruners); const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; PX_DELETE(pe); } } PxU32 ExtPrunerManager::addPruner(Pruner* pruner, PxU32 preallocated) { const PxU32 index = mPrunerExt.size(); PrunerExt* pe = PX_NEW(PrunerExt); pe->init(pruner); if(preallocated) pe->preallocate(preallocated); mPrunerExt.pushBack(pe); return index; } void ExtPrunerManager::preallocate(PxU32 prunerIndex, PxU32 nbShapes) { const bool preallocateCompoundPruner = prunerIndex==0xffffffff; if(preallocateCompoundPruner) { mCompoundPrunerExt.preallocate(nbShapes); } else { if(prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return; } mPrunerExt[prunerIndex]->preallocate(nbShapes); } } void ExtPrunerManager::flushMemory() { const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; pe->flushMemory(); } mCompoundPrunerExt.flushMemory(); } PrunerHandle ExtPrunerManager::addPrunerShape(const PrunerPayload& payload, PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, const PxBounds3& bounds, const PxTransform& transform, bool hasPruningStructure) { if(compoundId==INVALID_COMPOUND_ID && prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return INVALID_PRUNERHANDLE; } mPrunerNeedsUpdating = true; if(!dynamic) invalidateStaticTimestamp(); PrunerHandle handle; if(compoundId == INVALID_COMPOUND_ID) { PX_ASSERT(prunerIndex<mPrunerExt.size()); PX_ASSERT(mPrunerExt[prunerIndex]->pruner()); mPrunerExt[prunerIndex]->pruner()->addObjects(&handle, &bounds, &payload, &transform, 1, hasPruningStructure); //mPrunerExt[prunerIndex].growDirtyList(handle); } else { PX_ASSERT(mCompoundPrunerExt.pruner()); mCompoundPrunerExt.pruner()->addObject(compoundId, handle, bounds, payload, transform); } return handle; } void ExtPrunerManager::removePrunerShape(PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, PrunerHandle shapeHandle, PrunerPayloadRemovalCallback* removalCallback) { if(compoundId==INVALID_COMPOUND_ID && prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return; } mPrunerNeedsUpdating = true; if(!dynamic) invalidateStaticTimestamp(); if(compoundId == INVALID_COMPOUND_ID) { PX_ASSERT(prunerIndex<mPrunerExt.size()); PX_ASSERT(mPrunerExt[prunerIndex]->pruner()); mPrunerExt[prunerIndex]->removeFromDirtyList(shapeHandle); mPrunerExt[prunerIndex]->pruner()->removeObjects(&shapeHandle, 1, removalCallback); } else { mCompoundPrunerExt.removeFromDirtyList(compoundId, shapeHandle); mCompoundPrunerExt.pruner()->removeObject(compoundId, shapeHandle, removalCallback); } } void ExtPrunerManager::markForUpdate(PxU32 prunerIndex, bool dynamic, PrunerCompoundId compoundId, PrunerHandle shapeHandle, const PxTransform& transform) { if(compoundId==INVALID_COMPOUND_ID && prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return; } mPrunerNeedsUpdating = true; if(!dynamic) invalidateStaticTimestamp(); if(compoundId == INVALID_COMPOUND_ID) { PX_ASSERT(prunerIndex<mPrunerExt.size()); PX_ASSERT(mPrunerExt[prunerIndex]->pruner()); // PT: TODO: at this point do we still need a dirty list? we could just update the bounds directly? mPrunerExt[prunerIndex]->addToDirtyList(shapeHandle, dynamic, transform); } else mCompoundPrunerExt.addToDirtyList(compoundId, shapeHandle, transform); } void ExtPrunerManager::setDynamicTreeRebuildRateHint(PxU32 rebuildRateHint) { mRebuildRateHint = rebuildRateHint; // PT: we are still using the same rebuild hint for all pruners here, which may or may // not make sense. We could also have a different build rate for each pruner. const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; Pruner* pruner = pe->pruner(); if(pruner && pruner->isDynamic()) static_cast<DynamicPruner*>(pruner)->setRebuildRateHint(rebuildRateHint); } } void ExtPrunerManager::afterSync(bool buildStep, bool commit) { PX_PROFILE_ZONE("Sim.sceneQueryBuildStep", mContextID); if(!buildStep && !commit) { mPrunerNeedsUpdating = true; return; } // flush user modified objects flushShapes(); // PT: TODO: with N pruners this part would be worth multi-threading const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; Pruner* pruner = pe->pruner(); if(pruner) { if(pruner->isDynamic()) static_cast<DynamicPruner*>(pruner)->buildStep(true); if(commit) pruner->commit(); } } if(commit) { if(mUsesTreeOfPruners) createTreeOfPruners(); } mPrunerNeedsUpdating = !commit; } void ExtPrunerManager::flushShapes() { PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID); // must already have acquired writer lock here const float inflation = 1.0f + mInflation; bool mustInvalidateStaticTimestamp = false; const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; if(pe->processDirtyList(i, mAdapter, inflation)) mustInvalidateStaticTimestamp = true; } if(mustInvalidateStaticTimestamp) invalidateStaticTimestamp(); mCompoundPrunerExt.flushShapes(mAdapter, inflation); } void ExtPrunerManager::flushUpdates() { PX_PROFILE_ZONE("SceneQuery.flushUpdates", mContextID); if(mPrunerNeedsUpdating) { // no need to take lock if manual sq update is enabled // as flushUpdates will only be called from NpScene::flushQueryUpdates() mSQLock.lock(); if(mPrunerNeedsUpdating) { flushShapes(); const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; if(pe->pruner()) pe->pruner()->commit(); } if(mUsesTreeOfPruners) createTreeOfPruners(); PxMemoryBarrier(); mPrunerNeedsUpdating = false; } mSQLock.unlock(); } } void ExtPrunerManager::forceRebuildDynamicTree(PxU32 prunerIndex) { // PT: beware here when called from the PxScene, the prunerIndex may not match PX_PROFILE_ZONE("SceneQuery.forceDynamicTreeRebuild", mContextID); if(prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return; } PxMutex::ScopedLock lock(mSQLock); PrunerExt* pe = mPrunerExt[prunerIndex]; Pruner* pruner = pe->pruner(); if(pruner && pruner->isDynamic()) { static_cast<DynamicPruner*>(pruner)->purge(); static_cast<DynamicPruner*>(pruner)->commit(); } } void* ExtPrunerManager::prepareSceneQueriesUpdate(PxU32 prunerIndex) { // PT: beware here when called from the PxScene, the prunerIndex may not match if(prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return NULL; } PX_ASSERT(mPrunerExt[prunerIndex]->pruner()); bool retVal = false; Pruner* pruner = mPrunerExt[prunerIndex]->pruner(); if(pruner && pruner->isDynamic()) retVal = static_cast<DynamicPruner*>(pruner)->prepareBuild(); return retVal ? pruner : NULL; } void ExtPrunerManager::sceneQueryBuildStep(void* handle) { PX_PROFILE_ZONE("SceneQuery.sceneQueryBuildStep", mContextID); Pruner* pruner = reinterpret_cast<Pruner*>(handle); if(pruner && pruner->isDynamic()) { const bool buildFinished = static_cast<DynamicPruner*>(pruner)->buildStep(false); if(buildFinished) mPrunerNeedsUpdating = true; } } void ExtPrunerManager::visualize(PxU32 prunerIndex, PxRenderOutput& out) const { // PT: beware here when called from the PxScene, the prunerIndex may not match // This is quite awkward and should be improved. // PT: problem here is that this function will be called by the regular PhysX scene when plugged to its PxSceneDesc, // and the calling code only understands the regular PhysX pruners. const bool visualizeCompoundPruner = prunerIndex==0xffffffff; if(visualizeCompoundPruner) { const CompoundPruner* cp = mCompoundPrunerExt.pruner(); if(cp) cp->visualizeEx(out, SQ_DEBUG_VIZ_COMPOUND_COLOR, true, true); } else { if(prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return; } PrunerExt* pe = mPrunerExt[prunerIndex]; Pruner* pruner = pe->pruner(); if(pruner) { // PT: TODO: this doesn't really work: the static color was for static shapes but they // could still be stored in a dynamic pruner. So this code doesn't use a color scheme // consistent with what we use in the default code. if(pruner->isDynamic()) { //if(visDynamic) pruner->visualize(out, SQ_DEBUG_VIZ_DYNAMIC_COLOR, SQ_DEBUG_VIZ_DYNAMIC_COLOR2); } else { //if(visStatic) pruner->visualize(out, SQ_DEBUG_VIZ_STATIC_COLOR, SQ_DEBUG_VIZ_STATIC_COLOR2); } } } } void ExtPrunerManager::shiftOrigin(const PxVec3& shift) { const PxU32 nb = mPrunerExt.size(); for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; Pruner* pruner = pe->pruner(); if(pruner) pruner->shiftOrigin(shift); } mCompoundPrunerExt.pruner()->shiftOrigin(shift); } void ExtPrunerManager::addCompoundShape(const PxBVH& pxbvh, PrunerCompoundId compoundId, const PxTransform& compoundTransform, PrunerHandle* prunerHandle, const PrunerPayload* payloads, const PxTransform* transforms, bool isDynamic) { const Gu::BVH& bvh = static_cast<const Gu::BVH&>(pxbvh); PX_ASSERT(mCompoundPrunerExt.mPruner); mCompoundPrunerExt.mPruner->addCompound(prunerHandle, bvh, compoundId, compoundTransform, isDynamic, payloads, transforms); if(!isDynamic) invalidateStaticTimestamp(); } void ExtPrunerManager::updateCompoundActor(PrunerCompoundId compoundId, const PxTransform& compoundTransform) { PX_ASSERT(mCompoundPrunerExt.mPruner); const bool isDynamic = mCompoundPrunerExt.mPruner->updateCompound(compoundId, compoundTransform); if(!isDynamic) invalidateStaticTimestamp(); } void ExtPrunerManager::removeCompoundActor(PrunerCompoundId compoundId, PrunerPayloadRemovalCallback* removalCallback) { PX_ASSERT(mCompoundPrunerExt.mPruner); const bool isDynamic = mCompoundPrunerExt.mPruner->removeCompound(compoundId, removalCallback); if(!isDynamic) invalidateStaticTimestamp(); } void ExtPrunerManager::sync(PxU32 prunerIndex, const PrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) { if(!count) return; if(prunerIndex>=mPrunerExt.size()) { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "Invalid pruner index"); return; } Pruner* pruner = getPruner(prunerIndex); if(!pruner) return; PxU32 startIndex = 0; PxU32 numIndices = count; // if shape sim map is not empty, parse the indices and skip update for the dirty one if(ignoredIndices.count()) { // PT: I think this codepath was used with SCB / buffered changes, but it's not needed anymore numIndices = 0; for(PxU32 i=0; i<count; i++) { // if(ignoredIndices.test(boundsIndices[i])) if(ignoredIndices.boundedTest(boundsIndices[i])) { pruner->updateObjects(handles + startIndex, numIndices, mInflation, boundsIndices + startIndex, bounds, transforms); numIndices = 0; startIndex = i + 1; } else numIndices++; } // PT: we fallback to the next line on purpose - no "else" } pruner->updateObjects(handles + startIndex, numIndices, mInflation, boundsIndices + startIndex, bounds, transforms); } PxU32 ExtPrunerManager::startCustomBuildstep() { PX_PROFILE_ZONE("SceneQuery.startCustomBuildstep", mContextID); // flush user modified objects //flushShapes(); { PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID); // PT: only flush the compound pruner synchronously // must already have acquired writer lock here const float inflation = 1.0f + mInflation; mCompoundPrunerExt.flushShapes(mAdapter, inflation); } mTimestampNeedsUpdating = false; return mPrunerExt.size(); } void ExtPrunerManager::customBuildstep(PxU32 index) { PX_PROFILE_ZONE("SceneQuery.customBuildstep", mContextID); PX_ASSERT(index<mPrunerExt.size()); PrunerExt* pe = mPrunerExt[index]; Pruner* pruner = pe->pruner(); //void ExtPrunerManager::flushShapes() { PX_PROFILE_ZONE("SceneQuery.flushShapes", mContextID); // must already have acquired writer lock here const float inflation = 1.0f + mInflation; if(pe->processDirtyList(index, mAdapter, inflation)) mTimestampNeedsUpdating = true; } if(pruner) { if(pruner->isDynamic()) static_cast<DynamicPruner*>(pruner)->buildStep(true); // PT: "true" because that parameter was made for PxSceneQuerySystem::sceneQueryBuildStep(), not us pruner->commit(); } } void ExtPrunerManager::finishCustomBuildstep() { PX_PROFILE_ZONE("SceneQuery.finishCustomBuildstep", mContextID); if(mUsesTreeOfPruners) createTreeOfPruners(); mPrunerNeedsUpdating = false; if(mTimestampNeedsUpdating) invalidateStaticTimestamp(); } void ExtPrunerManager::createTreeOfPruners() { PX_PROFILE_ZONE("SceneQuery.createTreeOfPruners", mContextID); PX_DELETE(mTreeOfPruners); mTreeOfPruners = PX_NEW(BVH)(NULL); const PxU32 nb = mPrunerExt.size(); PxBounds3* prunerBounds = reinterpret_cast<PxBounds3*>(PxAlloca(sizeof(PxBounds3)*(nb+1))); PxU32 nbBounds = 0; for(PxU32 i=0;i<nb;i++) { PrunerExt* pe = mPrunerExt[i]; Pruner* pruner = pe->pruner(); if(pruner) pruner->getGlobalBounds(prunerBounds[nbBounds++]); } mTreeOfPruners->init(nbBounds, NULL, prunerBounds, sizeof(PxBounds3), BVH_SPLATTER_POINTS, 1, 0.01f); }
16,920
C++
28.224525
232
0.741253
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/ExtInertiaTensor.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 EXT_INERTIA_TENSOR_H #define EXT_INERTIA_TENSOR_H #include "foundation/PxMat33.h" #include "foundation/PxMathUtils.h" namespace physx { namespace Ext { class InertiaTensorComputer { public: InertiaTensorComputer(bool initTozero = true); InertiaTensorComputer(const PxMat33& inertia, const PxVec3& com, PxReal mass); ~InertiaTensorComputer(); PX_INLINE void zero(); //sets to zero mass PX_INLINE void setDiagonal(PxReal mass, const PxVec3& diagonal); //sets as a diagonal tensor PX_INLINE void rotate(const PxMat33& rot); //rotates the mass void translate(const PxVec3& t); //translates the mass PX_INLINE void transform(const PxTransform& transform); //transforms the mass PX_INLINE void scaleDensity(PxReal densityScale); //scales by a density factor PX_INLINE void add(const InertiaTensorComputer& it); //adds a mass PX_INLINE void center(); //recenters inertia around center of mass void setBox(const PxVec3& halfWidths); //sets as an axis aligned box PX_INLINE void setBox(const PxVec3& halfWidths, const PxTransform* pose); //sets as an oriented box void setSphere(PxReal radius); PX_INLINE void setSphere(PxReal radius, const PxTransform* pose); void setCylinder(int dir, PxReal r, PxReal l); PX_INLINE void setCylinder(int dir, PxReal r, PxReal l, const PxTransform* pose); void setCapsule(int dir, PxReal r, PxReal l); PX_INLINE void setCapsule(int dir, PxReal r, PxReal l, const PxTransform* pose); void setEllipsoid(PxReal rx, PxReal ry, PxReal rz); PX_INLINE void setEllipsoid(PxReal rx, PxReal ry, PxReal rz, const PxTransform* pose); PX_INLINE PxVec3 getCenterOfMass() const { return mG; } PX_INLINE PxReal getMass() const { return mMass; } PX_INLINE PxMat33 getInertia() const { return mI; } private: PxMat33 mI; PxVec3 mG; PxReal mMass; }; //-------------------------------------------------------------- // // Helper routines // //-------------------------------------------------------------- // Special version allowing 2D quads PX_INLINE PxReal volume(const PxVec3& extents) { PxReal v = 1.0f; if(extents.x != 0.0f) v*=extents.x; if(extents.y != 0.0f) v*=extents.y; if(extents.z != 0.0f) v*=extents.z; return v; } // Sphere PX_INLINE PxReal computeSphereRatio(PxReal radius) { return (4.0f/3.0f) * PxPi * radius * radius * radius; } PxReal computeSphereMass(PxReal radius, PxReal density) { return density * computeSphereRatio(radius); } PxReal computeSphereDensity(PxReal radius, PxReal mass) { return mass / computeSphereRatio(radius); } // Box PX_INLINE PxReal computeBoxRatio(const PxVec3& extents) { return volume(extents); } PxReal computeBoxMass(const PxVec3& extents, PxReal density) { return density * computeBoxRatio(extents); } PxReal computeBoxDensity(const PxVec3& extents, PxReal mass) { return mass / computeBoxRatio(extents); } // Ellipsoid PX_INLINE PxReal computeEllipsoidRatio(const PxVec3& extents) { return (4.0f/3.0f) * PxPi * volume(extents); } PxReal computeEllipsoidMass(const PxVec3& extents, PxReal density) { return density * computeEllipsoidRatio(extents); } PxReal computeEllipsoidDensity(const PxVec3& extents, PxReal mass) { return mass / computeEllipsoidRatio(extents); } // Cylinder PX_INLINE PxReal computeCylinderRatio(PxReal r, PxReal l) { return PxPi * r * r * (2.0f*l); } PxReal computeCylinderMass(PxReal r, PxReal l, PxReal density) { return density * computeCylinderRatio(r, l); } PxReal computeCylinderDensity(PxReal r, PxReal l, PxReal mass) { return mass / computeCylinderRatio(r, l); } // Capsule PX_INLINE PxReal computeCapsuleRatio(PxReal r, PxReal l) { return computeSphereRatio(r) + computeCylinderRatio(r, l);} PxReal computeCapsuleMass(PxReal r, PxReal l, PxReal density) { return density * computeCapsuleRatio(r, l); } PxReal computeCapsuleDensity(PxReal r, PxReal l, PxReal mass) { return mass / computeCapsuleRatio(r, l); } // Cone PX_INLINE PxReal computeConeRatio(PxReal r, PxReal l) { return PxPi * r * r * PxAbs(l)/3.0f; } PxReal computeConeMass(PxReal r, PxReal l, PxReal density) { return density * computeConeRatio(r, l); } PxReal computeConeDensity(PxReal r, PxReal l, PxReal mass) { return mass / computeConeRatio(r, l); } void computeBoxInertiaTensor(PxVec3& inertia, PxReal mass, PxReal xlength, PxReal ylength, PxReal zlength); void computeSphereInertiaTensor(PxVec3& inertia, PxReal mass, PxReal radius, bool hollow); bool jacobiTransform(PxI32 n, PxF64 a[], PxF64 w[]); bool diagonalizeInertiaTensor(const PxMat33& denseInertia, PxVec3& diagonalInertia, PxMat33& rotation); } // namespace Ext void Ext::computeBoxInertiaTensor(PxVec3& inertia, PxReal mass, PxReal xlength, PxReal ylength, PxReal zlength) { //to model a hollow block, one would have to multiply coeff by up to two. const PxReal coeff = mass/12; inertia.x = coeff * (ylength*ylength + zlength*zlength); inertia.y = coeff * (xlength*xlength + zlength*zlength); inertia.z = coeff * (xlength*xlength + ylength*ylength); PX_ASSERT(inertia.x != 0.0f); PX_ASSERT(inertia.y != 0.0f); PX_ASSERT(inertia.z != 0.0f); PX_ASSERT(inertia.isFinite()); } void Ext::computeSphereInertiaTensor(PxVec3& inertia, PxReal mass, PxReal radius, bool hollow) { inertia.x = mass * radius * radius; if (hollow) inertia.x *= PxReal(2 / 3.0); else inertia.x *= PxReal(2 / 5.0); inertia.z = inertia.y = inertia.x; PX_ASSERT(inertia.isFinite()); } //-------------------------------------------------------------- // // InertiaTensorComputer implementation // //-------------------------------------------------------------- Ext::InertiaTensorComputer::InertiaTensorComputer(bool initTozero) { if (initTozero) zero(); } Ext::InertiaTensorComputer::InertiaTensorComputer(const PxMat33& inertia, const PxVec3& com, PxReal mass) : mI(inertia), mG(com), mMass(mass) { } Ext::InertiaTensorComputer::~InertiaTensorComputer() { } PX_INLINE void Ext::InertiaTensorComputer::zero() { mMass = 0.0f; mI = PxMat33(PxZero); mG = PxVec3(0); } PX_INLINE void Ext::InertiaTensorComputer::setDiagonal(PxReal mass, const PxVec3& diag) { mMass = mass; mI = PxMat33::createDiagonal(diag); mG = PxVec3(0); PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite()); PX_ASSERT(PxIsFinite(mMass)); } void Ext::InertiaTensorComputer::setBox(const PxVec3& halfWidths) { // Setup inertia tensor for a cube with unit density const PxReal mass = 8.0f * computeBoxRatio(halfWidths); const PxReal s =(1.0f/3.0f) * mass; const PxReal x = halfWidths.x*halfWidths.x; const PxReal y = halfWidths.y*halfWidths.y; const PxReal z = halfWidths.z*halfWidths.z; setDiagonal(mass, PxVec3(y+z, z+x, x+y) * s); } PX_INLINE void Ext::InertiaTensorComputer::rotate(const PxMat33& rot) { //well known inertia tensor rotation expression is: RIR' -- this could be optimized due to symmetry, see code to do that in Body::updateGlobalInverseInertia mI = rot * mI * rot.getTranspose(); PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite()); //com also needs to be rotated mG = rot * mG; PX_ASSERT(mG.isFinite()); } void Ext::InertiaTensorComputer::translate(const PxVec3& t) { if (!t.isZero()) //its common for this to be zero { PxMat33 t1, t2; t1.column0 = PxVec3(0, mG.z, -mG.y); t1.column1 = PxVec3(-mG.z, 0, mG.x); t1.column2 = PxVec3(mG.y, -mG.x, 0); PxVec3 sum = mG + t; if (sum.isZero()) { mI += (t1 * t1)*mMass; } else { t2.column0 = PxVec3(0, sum.z, -sum.y); t2.column1 = PxVec3(-sum.z, 0, sum.x); t2.column2 = PxVec3(sum.y, -sum.x, 0); mI += (t1 * t1 - t2 * t2)*mMass; } //move center of mass mG += t; PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite()); PX_ASSERT(mG.isFinite()); } } PX_INLINE void Ext::InertiaTensorComputer::transform(const PxTransform& transform) { rotate(PxMat33(transform.q)); translate(transform.p); } PX_INLINE void Ext::InertiaTensorComputer::setBox(const PxVec3& halfWidths, const PxTransform* pose) { setBox(halfWidths); if (pose) transform(*pose); } PX_INLINE void Ext::InertiaTensorComputer::scaleDensity(PxReal densityScale) { mI *= densityScale; mMass *= densityScale; PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite()); PX_ASSERT(PxIsFinite(mMass)); } PX_INLINE void Ext::InertiaTensorComputer::add(const InertiaTensorComputer& it) { const PxReal TotalMass = mMass + it.mMass; mG = (mG * mMass + it.mG * it.mMass) / TotalMass; mMass = TotalMass; mI += it.mI; PX_ASSERT(mI.column0.isFinite() && mI.column1.isFinite() && mI.column2.isFinite()); PX_ASSERT(mG.isFinite()); PX_ASSERT(PxIsFinite(mMass)); } PX_INLINE void Ext::InertiaTensorComputer::center() { PxVec3 center = -mG; translate(center); } void Ext::InertiaTensorComputer::setSphere(PxReal radius) { // Compute mass of the sphere const PxReal m = computeSphereRatio(radius); // Compute moment of inertia const PxReal s = m * radius * radius * (2.0f/5.0f); setDiagonal(m,PxVec3(s,s,s)); } PX_INLINE void Ext::InertiaTensorComputer::setSphere(PxReal radius, const PxTransform* pose) { setSphere(radius); if (pose) transform(*pose); } void Ext::InertiaTensorComputer::setCylinder(int dir, PxReal r, PxReal l) { // Compute mass of cylinder const PxReal m = computeCylinderRatio(r, l); const PxReal i1 = r*r*m/2.0f; const PxReal i2 = (3.0f*r*r+4.0f*l*l)*m/12.0f; switch(dir) { case 0: setDiagonal(m,PxVec3(i1,i2,i2)); break; case 1: setDiagonal(m,PxVec3(i2,i1,i2)); break; default: setDiagonal(m,PxVec3(i2,i2,i1)); break; } } PX_INLINE void Ext::InertiaTensorComputer::setCylinder(int dir, PxReal r, PxReal l, const PxTransform* pose) { setCylinder(dir, r, l); if (pose) transform(*pose); } void Ext::InertiaTensorComputer::setCapsule(int dir, PxReal r, PxReal l) { // Compute mass of capsule const PxReal m = computeCapsuleRatio(r, l); const PxReal t = PxPi * r * r; const PxReal i1 = t * ((r*r*r * 8.0f/15.0f) + (l*r*r)); const PxReal i2 = t * ((r*r*r * 8.0f/15.0f) + (l*r*r * 3.0f/2.0f) + (l*l*r * 4.0f/3.0f) + (l*l*l * 2.0f/3.0f)); switch(dir) { case 0: setDiagonal(m,PxVec3(i1,i2,i2)); break; case 1: setDiagonal(m,PxVec3(i2,i1,i2)); break; default: setDiagonal(m,PxVec3(i2,i2,i1)); break; } } PX_INLINE void Ext::InertiaTensorComputer::setCapsule(int dir, PxReal r, PxReal l, const PxTransform* pose) { setCapsule(dir, r, l); if (pose) transform(*pose); } void Ext::InertiaTensorComputer::setEllipsoid(PxReal rx, PxReal ry, PxReal rz) { // Compute mass of ellipsoid const PxReal m = computeEllipsoidRatio(PxVec3(rx, ry, rz)); // Compute moment of inertia const PxReal s = m * (2.0f/5.0f); // Setup inertia tensor for an ellipsoid centered at the origin setDiagonal(m,PxVec3(ry*rz,rz*rx,rx*ry)*s); } PX_INLINE void Ext::InertiaTensorComputer::setEllipsoid(PxReal rx, PxReal ry, PxReal rz, const PxTransform* pose) { setEllipsoid(rx,ry,rz); if (pose) transform(*pose); } } #endif
12,953
C
33.360743
157
0.692658
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetUnionFind.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtTetUnionFind.h" namespace physx { namespace Ext { //------------------------------------------------------------------------------------ void UnionFind::init(PxI32 numSets) { mEntries.resize(numSets); for (PxI32 i = 0; i < numSets; i++) { Entry &e = mEntries[i]; e.parent = i; e.rank = 0; e.setNr = i; } } //------------------------------------------------------------------------------------ PxI32 UnionFind::find(PxI32 x) { if (mEntries[x].parent != x) mEntries[x].parent = find(mEntries[x].parent); return mEntries[x].parent; } //------------------------------------------------------------------------------------ void UnionFind::makeSet(PxI32 x, PxI32 y) { PxI32 xroot = find(x); PxI32 yroot = find(y); if (xroot == yroot) return; if (mEntries[xroot].rank < mEntries[yroot].rank) mEntries[xroot].parent = yroot; else if (mEntries[xroot].rank > mEntries[yroot].rank) mEntries[yroot].parent = xroot; else { mEntries[yroot].parent = xroot; mEntries[xroot].rank++; } } //------------------------------------------------------------------------------------ PxI32 UnionFind::computeSetNrs() { PxArray<PxI32> oldToNew(mEntries.size(), -1); PxI32 numSets = 0; for (PxU32 i = 0; i < mEntries.size(); i++) { PxI32 nr = find(i); if (oldToNew[nr] < 0) oldToNew[nr] = numSets++; mEntries[i].setNr = oldToNew[nr]; } return numSets; } //------------------------------------------------------------------------------------ PxI32 UnionFind::getSetNr(PxI32 x) { return mEntries[x].setNr; } } }
3,162
C++
33.380434
87
0.609108
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtQuadric.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_QUADRIC_H #define EXT_QUADRIC_H #include "foundation/PxVec3.h" // MM: used in ExtMeshSimplificator // see paper Garland and Heckbert: "Surface Simplification Using Quadric Error Metrics" namespace physx { namespace Ext { class Quadric { public: PX_FORCE_INLINE void zero() { a00 = 0.0f; a01 = 0.0f; a02 = 0.0f; a03 = 0.0f; a11 = 0.0f; a12 = 0.0f; a13 = 0.0f; a22 = 0.0f; a23 = 0.0f; a33 = 0.0f; } PX_FORCE_INLINE void setFromPlane(const PxVec3& v0, const PxVec3& v1, const PxVec3& v2) { PxVec3 n = (v1 - v0).cross(v2 - v0); n.normalize(); float d = -n.dot(v0); a00 = n.x * n.x; a01 = n.x * n.y; a02 = n.x * n.z; a03 = n.x * d; a11 = n.y * n.y; a12 = n.y * n.z; a13 = n.y * d; a22 = n.z * n.z; a23 = n.z * d; a33 = d * d; } PX_FORCE_INLINE Quadric operator +(const Quadric& q) const { Quadric sum; sum.a00 = a00 + q.a00; sum.a01 = a01 + q.a01; sum.a02 = a02 + q.a02; sum.a03 = a03 + q.a03; sum.a11 = a11 + q.a11; sum.a12 = a12 + q.a12; sum.a13 = a13 + q.a13; sum.a22 = a22 + q.a22; sum.a23 = a23 + q.a23; sum.a33 = a33 + q.a33; return sum; } void operator +=(const Quadric& q) { a00 += q.a00; a01 += q.a01; a02 += q.a02; a03 += q.a03; a11 += q.a11; a12 += q.a12; a13 += q.a13; a22 += q.a22; a23 += q.a23; a33 += q.a33; } PxF32 outerProduct(const PxVec3& v) { return a00 * v.x * v.x + 2.0f * a01 * v.x * v.y + 2.0f * a02 * v.x * v.z + 2.0f * a03 * v.x + a11 * v.y * v.y + 2.0f * a12 * v.y * v.z + 2.0f * a13 * v.y + a22 * v.z * v.z + 2.0f * a23 * v.z + a33; } private: PxF32 a00, a01, a02, a03; PxF32 a11, a12, a13; PxF32 a22, a23; PxF32 a33; }; } } #endif
3,331
C
34.446808
97
0.637646
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtFastWindingNumber.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtFastWindingNumber.h" #include "foundation/PxSort.h" #include "foundation/PxMath.h" #include "ExtUtilities.h" //The following paper explains all the techniques used in this file //http://www.dgp.toronto.edu/projects/fast-winding-numbers/fast-winding-numbers-for-soups-and-clouds-siggraph-2018-barill-et-al.pdf namespace physx { namespace Ext { PxF64 computeWindingNumber(const PxArray<Gu::BVHNode>& tree, const PxVec3d& q, PxF64 beta, const PxHashMap<PxU32, ClusterApproximationF64>& clusters, const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points) { return Gu::computeWindingNumber<PxF64, PxVec3d>(tree.begin(), q, beta, clusters, reinterpret_cast<const PxU32*>(triangles.begin()), points.begin()); } void precomputeClusterInformation(PxArray<Gu::BVHNode>& tree, const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points, PxHashMap<PxU32, ClusterApproximationF64>& result, PxI32 rootNodeIndex) { Gu::precomputeClusterInformation<PxF64, PxVec3d>(tree.begin(), reinterpret_cast<const PxU32*>(triangles.begin()), triangles.size(), points.begin(), result, rootNodeIndex); } } }
2,691
C++
48.851851
173
0.770346
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayTetrahedralizer.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_DELAUNAY_TETRAHEDRALIZER_H #define EXT_DELAUNAY_TETRAHEDRALIZER_H #include "foundation/PxArray.h" #include "foundation/PxVec3.h" #include "foundation/PxHashSet.h" #include "GuTetrahedron.h" #include "ExtVec3.h" namespace physx { namespace Ext { using Edge = PxPair<PxI32, PxI32>; using Tetrahedron = Gu::TetrahedronT<PxI32>; using Tetrahedron16 = Gu::TetrahedronT<PxI16>; void buildNeighborhood(const PxArray<Tetrahedron>& tets, PxArray<PxI32>& result); void buildNeighborhood(const PxI32* tets, PxU32 numTets, PxArray<PxI32>& result); PX_FORCE_INLINE PxF64 tetVolume(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d) { return (-1.0 / 6.0) * (a - d).dot((b - d).cross(c - d)); } PX_FORCE_INLINE PxF64 tetVolume(const Tetrahedron& tet, const PxArray<PxVec3d>& points) { return tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); } //Returns the intersection (set operation) of two sorted lists PX_FORCE_INLINE void intersectionOfSortedLists(const PxArray<PxI32>& sorted1, const PxArray<PxI32>& sorted2, PxArray<PxI32>& result) { PxU32 a = 0; PxU32 b = 0; result.clear(); while (a < sorted1.size() && b < sorted2.size()) { if (sorted1[a] == sorted2[b]) { result.pushBack(sorted1[a]); ++a; ++b; } else if (sorted1[a] > sorted2[b]) ++b; else ++a; } } PX_FORCE_INLINE bool intersectionOfSortedListsContainsElements(const PxArray<PxI32>& sorted1, const PxArray<PxI32>& sorted2) { PxU32 a = 0; PxU32 b = 0; while (a < sorted1.size() && b < sorted2.size()) { if (sorted1[a] == sorted2[b]) return true; else if (sorted1[a] > sorted2[b]) ++b; else ++a; } return false; } class BaseTetAnalyzer { public: virtual PxF64 quality(const PxArray<PxI32> tetIndices) const = 0; virtual PxF64 quality(const PxArray<Tetrahedron> tetrahedraToCheck) const = 0; virtual bool improved(PxF64 previousQuality, PxF64 newQuality) const = 0; virtual ~BaseTetAnalyzer() {} }; class MinimizeMaxAmipsEnergy : public BaseTetAnalyzer { const PxArray<PxVec3d>& points; const PxArray<Tetrahedron>& tetrahedra; public: MinimizeMaxAmipsEnergy(const PxArray<PxVec3d>& points_, const PxArray<Tetrahedron>& tetrahedra_) : points(points_), tetrahedra(tetrahedra_) {} PxF64 quality(const PxArray<PxI32> tetIndices) const; PxF64 quality(const PxArray<Tetrahedron> tetrahedraToCheck) const; bool improved(PxF64 previousQuality, PxF64 newQuality) const; virtual ~MinimizeMaxAmipsEnergy() {} private: PX_NOCOPY(MinimizeMaxAmipsEnergy) }; class MaximizeMinTetVolume : public BaseTetAnalyzer { const PxArray<PxVec3d>& points; const PxArray<Tetrahedron>& tetrahedra; public: MaximizeMinTetVolume(const PxArray<PxVec3d>& points_, const PxArray<Tetrahedron>& tetrahedra_) : points(points_), tetrahedra(tetrahedra_) {} PxF64 quality(const PxArray<PxI32> tetIndices) const; PxF64 quality(const PxArray<Tetrahedron> tetrahedraToCheck) const; bool improved(PxF64 previousQuality, PxF64 newQuality) const; virtual ~MaximizeMinTetVolume() {} private: PX_NOCOPY(MaximizeMinTetVolume) }; //Helper class to extract surface triangles from a tetmesh struct SortedTriangle { public: PxI32 A; PxI32 B; PxI32 C; bool Flipped; PX_FORCE_INLINE SortedTriangle(PxI32 a, PxI32 b, PxI32 c) { A = a; B = b; C = c; Flipped = false; if (A > B) { PxSwap(A, B); Flipped = !Flipped; } if (B > C) { PxSwap(B, C); Flipped = !Flipped; } if (A > B) { PxSwap(A, B); Flipped = !Flipped; } } }; struct TriangleHash { PX_FORCE_INLINE std::size_t operator()(const SortedTriangle& k) const { return k.A ^ k.B ^ k.C; } PX_FORCE_INLINE bool equal(const SortedTriangle& first, const SortedTriangle& second) const { return first.A == second.A && first.B == second.B && first.C == second.C; } }; struct RecoverEdgeMemoryCache { PxArray<PxI32> facesStart; PxHashSet<PxI32> tetsDoneStart; PxArray<PxI32> resultStart; PxArray<PxI32> facesEnd; PxHashSet<PxI32> tetsDoneEnd; PxArray<PxI32> resultEnd; }; class StackMemory { public: void clear() { faces.forceSize_Unsafe(0); hashSet.clear(); } PxArray<PxI32> faces; PxHashSet<PxI32> hashSet; }; //Incremental delaunay tetrahedralizer class DelaunayTetrahedralizer { public: //The bounds specified must contain all points that will get inserted by calling insertPoints. DelaunayTetrahedralizer(const PxVec3d& min, const PxVec3d& max); DelaunayTetrahedralizer(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets); void initialize(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets); //Inserts a bunch of new points into the tetrahedralization and keeps the delaunay condition satisfied. The new result will //get stored in the tetrahedra array. Points to insert must already be present in inPoints, the indices of the points to insert //can be controlled with start and end index (end index is exclusive, start index is inclusive) void insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end, PxArray<Tetrahedron>& tetrahedra); bool insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end); void exportTetrahedra(PxArray<Tetrahedron>& tetrahedra); bool canCollapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove, PxF64 volumeChangeThreshold = 0.1, BaseTetAnalyzer* tetAnalyzer = NULL); bool canCollapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB, PxF64& qualityAfterCollapse, PxF64 volumeChangeThreshold = 0.1, BaseTetAnalyzer* tetAnalyzer = NULL); void collapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove); void collapseEdge(PxI32 edgeVertexAToKeep, PxI32 edgeVertexBToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB); void collectTetsConnectedToVertex(PxI32 vertexIndex, PxArray<PxI32>& tetIds); void collectTetsConnectedToVertex(PxArray<PxI32>& faces, PxHashSet<PxI32>& tetsDone, PxI32 vertexIndex, PxArray<PxI32>& tetIds); void collectTetsConnectedToEdge(PxI32 edgeStart, PxI32 edgeEnd, PxArray<PxI32>& tetIds); PX_FORCE_INLINE const PxVec3d& point(PxI32 index) const { return centeredNormalizedPoints[index]; } PX_FORCE_INLINE PxU32 numPoints() const { return centeredNormalizedPoints.size(); } PX_FORCE_INLINE PxArray<PxVec3d>& points() { return centeredNormalizedPoints; } PX_FORCE_INLINE const PxArray<PxVec3d>& points() const { return centeredNormalizedPoints; } PxU32 addPoint(const PxVec3d& p) { centeredNormalizedPoints.pushBack(p); vertexToTet.pushBack(-1); return centeredNormalizedPoints.size() - 1; } PX_FORCE_INLINE const Tetrahedron& tetrahedron(PxI32 index) const { return result[index]; } PX_FORCE_INLINE PxU32 numTetrahedra() const { return result.size(); } PX_FORCE_INLINE PxArray<Tetrahedron>& tetrahedra() { return result; } PX_FORCE_INLINE const PxArray<Tetrahedron>& tetrahedra() const { return result; } void copyInternalPointsTo(PxArray<PxVec3d>& points) { points = centeredNormalizedPoints; } bool optimizeByFlipping(PxArray<PxI32>& affectedFaces, const BaseTetAnalyzer& qualityAnalyzer); void insertPointIntoEdge(PxI32 newPointIndex, PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& affectedTets, BaseTetAnalyzer* qualityAnalyzer = NULL); bool removeEdgeByFlip(PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& tetIndices, BaseTetAnalyzer* qualityAnalyzer = NULL); void addLockedEdges(const PxArray<Gu::IndexedTriangleT<PxI32>>& triangles); void addLockedTriangles(const PxArray<Gu::IndexedTriangleT<PxI32>>& triangles); void clearLockedEdges() { lockedEdges.clear(); } void clearLockedTriangles() { lockedTriangles.clear(); } bool recoverEdgeByFlip(PxI32 eStart, PxI32 eEnd, RecoverEdgeMemoryCache& cache); void generateTetmeshEnforcingEdges(const PxArray<PxVec3d>& trianglePoints, const PxArray<Gu::IndexedTriangleT<PxI32>>& triangles, PxArray<PxArray<PxI32>>& allEdges, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets); private: PxArray<PxVec3d> centeredNormalizedPoints; PxArray<PxI32> neighbors; PxArray<PxI32> unusedTets; PxArray<PxI32> vertexToTet; PxArray<Tetrahedron> result; PxI32 numAdditionalPointsAtBeginning = 4; PxHashSet<SortedTriangle, TriangleHash> lockedTriangles; PxHashSet<PxU64> lockedEdges; StackMemory stackMemory; PX_NOCOPY(DelaunayTetrahedralizer) }; struct EdgeWithLength { PxI32 A; PxI32 B; PxF64 Length; EdgeWithLength(PxI32 a_, PxI32 b_, PxF64 length_) { A = a_; B = b_; Length = length_; } }; PX_FORCE_INLINE bool operator <(const EdgeWithLength& lhs, const EdgeWithLength& rhs) { return lhs.Length < rhs.Length; } struct SplitEdge { PxI32 A; PxI32 B; PxF64 Q; PxF64 L; bool InteriorEdge; SplitEdge(PxI32 a, PxI32 b, PxF64 q, PxF64 l, bool interiorEdge) { A = a; B = b; Q = q; L = l; InteriorEdge = interiorEdge; } }; PX_FORCE_INLINE bool operator >(const SplitEdge& lhs, const SplitEdge& rhs) { if (lhs.Q == rhs.Q) return lhs.L > rhs.L; return lhs.Q > rhs.Q; } bool optimizeByCollapsing(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints, BaseTetAnalyzer* qualityAnalyzer = NULL); bool optimizeBySwapping(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, const PxArray<PxArray<PxI32>>& pointToOriginalTriangle, BaseTetAnalyzer* qualityAnalyzer); bool optimizeBySplitting(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, const PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 maxPointsToInsert = -1, bool sortByQuality = false, BaseTetAnalyzer* qualityAnalyzer = NULL, PxF64 qualityThreshold = 10); //Modified tetmesh quality improvement implementation of the method described in https://cs.nyu.edu/~yixinhu/tetwild.pdf Section 3.2 Mesh Improvement void optimize(DelaunayTetrahedralizer& del, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints, PxArray<PxVec3d>& optimizedPoints, PxArray<Tetrahedron>& optimizedTets, PxI32 numPasses = 10); } } #endif
11,905
C
31.798898
166
0.742041
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetSplitting.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_TET_SPLITTING_H #define EXT_TET_SPLITTING_H #include "ExtVec3.h" #include "foundation/PxArray.h" #include "foundation/PxHashMap.h" #include "GuTetrahedron.h" namespace physx { namespace Ext { using Edge = PxPair<PxI32, PxI32>; using Tetrahedron = Gu::TetrahedronT<PxI32>; //Splits all edges specified in edgesToSplit. The tets are modified in place. The poitns referenced by index in the key-value pari in //edgesToSplit must already pe present in the points array. This functions guarantees that the tetmesh will remain watertight. PX_C_EXPORT void PX_CALL_CONV split(PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points, const PxHashMap<PxU64, PxI32>& edgesToSplit); } } #endif
2,272
C
44.459999
142
0.769366
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtOctreeTetrahedralizer.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtOctreeTetrahedralizer.h" #include "foundation/PxSort.h" #include "foundation/PxQuat.h" #include "CmRandom.h" namespace physx { namespace Ext { // ------------------------------------------------------------------------------------- static const PxI32 childRelPos[8][3] = { {0,0,0}, {1,0,0},{0,1,0},{1,1,0}, {0,0,1}, {1,0,1},{0,1,1},{1,1,1} }; static const PxI32 cubeCorners[8][3] = { {0,0,0}, {1,0,0},{1,1,0},{0,1,0}, {0,0,1}, {1,0,1},{1,1,1},{0,1,1} }; //static const PxI32 cubeEdges[12][2] = { {0,1}, {1,2},{2,3},{3,0}, {0,4},{1,5},{2,6},{3,7},{4,5},{5,6},{6,7},{7,4} }; static const PxI32 tetFaces[4][3] = { {2,1,0}, {0,1,3}, {1,2,3}, {2,0,3} }; static const PxI32 cubeTets[6][4] = { {0,1,2,5}, {0,4,5,2}, {2,4,5,6}, {4,7,6,3}, {2,6,3,4}, {0,2,3,4} }; static const PxI32 cubeTetNeighbors[6][4] = { {-1,-1,-1,1}, {-1,5,2,0}, {1,4,-1,-1}, {-1,-1,-1,4}, {-1,2,3,5}, {-1,1,4,-1} }; // ------------------------------------------------------------------------------------- OctreeTetrahedralizer::OctreeTetrahedralizer() { clear(); } // ------------------------------------------------------------------------------------- void OctreeTetrahedralizer::clearTets() { tetVerts.clear(); tetIds.clear(); firstFreeTet = -1; currentTetMark = 0; tetMarks.clear(); tetNeighbors.clear(); renderVerts.clear(); renderTriIds.clear(); firstABBVert = 0; } // ------------------------------------------------------------------------------------- void OctreeTetrahedralizer::clear() { surfaceVerts.clear(); surfaceTriIds.clear(); tetIds.clear(); tetNeighbors.clear(); cells.clear(); clearTets(); prevClip = -1.0f; prevScale = -1.0f; } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::createTree() { Bounds3 bounds; bounds.setEmpty(); for (PxI32 i = 0; i < PxI32(surfaceVerts.size()); i++) { const PxVec3& v = surfaceVerts[i]; bounds.include(PxVec3d(PxF64(v.x), PxF64(v.y), PxF64(v.z))); } bounds.expand(0.01); PxVec3d dims = bounds.getDimensions(); PxF64 size = PxMax(dims.x, PxMax(dims.y, dims.z)); // create root cells.resize(1); cells.front().init(); cells.front().orig = bounds.minimum; cells.front().size = size; cells.front().depth = 0; // insert vertices PxI32 numVerts = PxI32(surfaceVerts.size()); for (PxI32 i = 0; i < numVerts; i++) { treeInsertVert(0, i); } } // ------------------------------------------------------------------------------------- PxI32 OctreeTetrahedralizer::Cell::getChildNr(const PxVec3d& p) { if (firstChild < 0) return -1; PxI32 nr = 0; if (p.x > orig.x + 0.5 * size) nr |= 1; if (p.y > orig.y + 0.5 * size) nr |= 2; if (p.z > orig.z + 0.5 * size) nr |= 4; return firstChild + nr; } // ------------------------------------------------------------------------------------- void OctreeTetrahedralizer::treeInsertVert(PxI32 cellNr, PxI32 vertNr) { // inner node if (cells[cellNr].firstChild >= 0) { treeInsertVert(cells[cellNr].getChildNr(surfaceVerts[vertNr]), vertNr); return; } // add vertsOfCell.add(cellNr, vertNr); cells[cellNr].numVerts++; if (cells[cellNr].numVerts <= maxVertsPerCell || cells[cellNr].depth >= maxTreeDepth) return; // split PxI32 firstChild = cells.size(); cells[cellNr].firstChild = firstChild; cells.resize(cells.size() + 8); for (PxI32 i = 0; i < 8; i++) { Cell& child = cells[firstChild + i]; child.init(); child.depth = cells[cellNr].depth + 1; child.size = cells[cellNr].size * 0.5; child.orig = cells[cellNr].orig + PxVec3d( childRelPos[i][0] * child.size, childRelPos[i][1] * child.size, childRelPos[i][2] * child.size); } PxI32 iterator, id; vertsOfCell.initIteration(cellNr, iterator); while (vertsOfCell.iterate(id, iterator)) treeInsertVert(cells[cellNr].getChildNr(surfaceVerts[id]), id); vertsOfCell.removeAll(cellNr); cells[cellNr].numVerts = 0; } // ----------------------------------------------------------------------------------- static PxVec3d jitter(const PxVec3d& p, Cm::RandomR250& random) { PxF64 eps = 0.001; return PxVec3d( p.x - eps + 2.0 * eps * PxF64(random.rand(0.0f, 1.0f)), p.y - eps + 2.0 * eps * PxF64(random.rand(0.0f, 1.0f)), p.z - eps + 2.0 * eps * PxF64(random.rand(0.0f, 1.0f))); } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::createTetVerts(bool includeOctreeNodes) { tetVerts.clear(); insideTester.init(surfaceVerts.begin(), PxI32(surfaceVerts.size()), surfaceTriIds.begin(), PxI32(surfaceTriIds.size()) / 3); for (PxI32 i = 0; i < PxI32(surfaceVerts.size()); i++) { const PxVec3& v = surfaceVerts[i]; tetVerts.pushBack(PxVec3d(PxF64(v.x), PxF64(v.y), PxF64(v.z))); } if (includeOctreeNodes) { PxArray<PxVec3d> treeVerts; for (PxI32 i = 0; i < PxI32(cells.size()); i++) { PxF64 s = cells[i].size; for (PxI32 j = 0; j < 8; j++) { PxVec3d p = cells[i].orig + PxVec3d( s * cubeCorners[j][0], s * cubeCorners[j][1], s * cubeCorners[j][2]); treeVerts.pushBack(p); } } // remove duplicates PxF64 eps = 1e-8; struct Ref { PxF64 d; PxI32 vertNr; bool operator < (const Ref& r) const { return d < r.d; } }; PxI32 numTreeVerts = PxI32(treeVerts.size()); PxArray<Ref> refs(numTreeVerts); for (PxI32 i = 0; i < numTreeVerts; i++) { PxVec3d& p = treeVerts[i]; refs[i].d = p.x + 0.3 * p.y + 0.1 * p.z; refs[i].vertNr = i; } PxSort(refs.begin(), refs.size()); PxArray<bool> duplicate(numTreeVerts, false); PxI32 nr = 0; Cm::RandomR250 random(0); while (nr < numTreeVerts) { Ref& r = refs[nr]; nr++; if (duplicate[r.vertNr]) continue; PxVec3d& p = treeVerts[r.vertNr]; PxVec3d v = jitter(p, random); if (insideTester.isInside(PxVec3(PxReal(v.x), PxReal(v.y), PxReal(v.z)))) tetVerts.pushBack(jitter(p, random)); PxI32 i = nr; while (i < numTreeVerts && fabs(refs[i].d - r.d) < eps) { PxVec3d& q = treeVerts[refs[i].vertNr]; if ((p - q).magnitude() < eps) duplicate[refs[i].vertNr] = true; i++; } } } } // ----------------------------------------------------------------------------------- PxVec3d OctreeTetrahedralizer::getTetCenter(PxI32 tetNr) const { return (tetVerts[tetIds[4 * tetNr]] + tetVerts[tetIds[4 * tetNr + 1]] + tetVerts[tetIds[4 * tetNr + 2]] + tetVerts[tetIds[4 * tetNr + 3]]) * 0.25; } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::treeInsertTet(PxI32 tetNr) { PxVec3d center = getTetCenter(tetNr); PxI32 cellNr = 0; while (cellNr >= 0) { Cell& c = cells[cellNr]; if (c.closestTetNr < 0) c.closestTetNr = tetNr; else { PxVec3d cellCenter = c.orig + PxVec3d(c.size, c.size, c.size) * 0.5; PxVec3d closest = getTetCenter(c.closestTetNr); if ((cellCenter - center).magnitudeSquared() < (cellCenter - closest).magnitudeSquared()) c.closestTetNr = tetNr; } cellNr = cells[cellNr].getChildNr(center); } } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::treeRemoveTet(PxI32 tetNr) { PxVec3d center = getTetCenter(tetNr); PxI32 cellNr = 0; while (cellNr >= 0) { Cell& c = cells[cellNr]; if (c.closestTetNr == tetNr) c.closestTetNr = -1; cellNr = cells[cellNr].getChildNr(center); } } void resizeFast(PxArray<PxI32>& arr, PxU32 newSize, PxI32 value = 0) { if (newSize < arr.size()) arr.removeRange(newSize, arr.size() - newSize); else { while (arr.size() < newSize) arr.pushBack(value); } } // ----------------------------------------------------------------------------------- PxI32 OctreeTetrahedralizer::getNewTetNr() { PxI32 newTetNr; if (firstFreeTet >= 0) { // take from free list newTetNr = firstFreeTet; firstFreeTet = tetIds[4 * firstFreeTet]; } else { // append newTetNr = PxI32(tetIds.size()) / 4; resizeFast(tetIds, tetIds.size() + 4); resizeFast(tetMarks, newTetNr + 1, 0); resizeFast(tetNeighbors, tetIds.size(), -1); } return newTetNr; } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::removeTetNr(PxI32 tetNr) { // add to free list tetIds[4 * tetNr] = firstFreeTet; tetIds[4 * tetNr + 1] = -1; tetIds[4 * tetNr + 2] = -1; tetIds[4 * tetNr + 3] = -1; firstFreeTet = tetNr; } // ----------------------------------------------------------------------------------- bool OctreeTetrahedralizer::findSurroundingTet(const PxVec3d& p, PxI32 startTetNr, PxI32& tetNr) { currentTetMark++; tetNr = startTetNr; bool found = false; while (!found) { if (tetNr < 0 || tetMarks[tetNr] == currentTetMark) // circular, something went wrong break; tetMarks[tetNr] = currentTetMark; PxVec3d c = getTetCenter(tetNr); PxI32* ids = &tetIds[4 * tetNr]; PxF64 minT = DBL_MAX; PxI32 minFaceNr = -1; for (PxI32 i = 0; i < 4; i++) { const PxVec3d& p0 = tetVerts[ids[tetFaces[i][0]]]; const PxVec3d& p1 = tetVerts[ids[tetFaces[i][1]]]; const PxVec3d& p2 = tetVerts[ids[tetFaces[i][2]]]; PxVec3d n = (p1 - p0).cross(p2 - p0); n = n.getNormalized(); PxF64 hp = (p - p0).dot(n); PxF64 hc = (c - p0).dot(n); PxF64 t = hp - hc; if (t == 0.0) continue; t = -hc / t; // time when c -> p hits the face if (t >= 0.0 && t < minT) { // in front and new min minT = t; minFaceNr = i; } } if (minT >= 1.0) found = true; else tetNr = tetNeighbors[4 * tetNr + minFaceNr]; } return found; } // ----------------------------------------------------------------------------------- bool OctreeTetrahedralizer::findSurroundingTet(const PxVec3d& p, PxI32& tetNr) { PxI32 startTet = 0; PxI32 cellNr = 0; while (cellNr >= 0) { if (cells[cellNr].closestTetNr >= 0) startTet = cells[cellNr].closestTetNr; cellNr = cells[cellNr].getChildNr(p); } return findSurroundingTet(p, startTet, tetNr); } // ----------------------------------------------------------------------------------- static PxVec3d getCircumCenter(PxVec3d& p0, PxVec3d& p1, PxVec3d& p2, PxVec3d& p3) { PxVec3d b = p1 - p0; PxVec3d c = p2 - p0; PxVec3d d = p3 - p0; PxF64 det = 2.0 * (b.x*(c.y*d.z - c.z*d.y) - b.y*(c.x*d.z - c.z*d.x) + b.z*(c.x*d.y - c.y*d.x)); if (det == 0.0) return p0; else { PxVec3d v = c.cross(d)*b.dot(b) + d.cross(b)*c.dot(c) + b.cross(c)*d.dot(d); v /= det; return p0 + v; } } // ----------------------------------------------------------------------------------- bool OctreeTetrahedralizer::meshInsertTetVert(PxI32 vertNr) { const PxVec3d& p = tetVerts[vertNr]; PxI32 surroundingTetNr; if (!findSurroundingTet(p, surroundingTetNr)) return false; // find violating tets violatingTets.clear(); stack.clear(); currentTetMark++; stack.pushBack(surroundingTetNr); while (!stack.empty()) { PxI32 tetNr = stack.back(); stack.popBack(); if (tetMarks[tetNr] == currentTetMark) continue; tetMarks[tetNr] = currentTetMark; violatingTets.pushBack(tetNr); for (PxI32 i = 0; i < 4; i++) { PxI32 n = tetNeighbors[4 * tetNr + i]; if (n < 0 || tetMarks[n] == currentTetMark) continue; // Delaunay condition test PxI32* ids = &tetIds[4 * n]; PxVec3d c = getCircumCenter(tetVerts[ids[0]], tetVerts[ids[1]], tetVerts[ids[2]], tetVerts[ids[3]]); PxF64 r2 = (tetVerts[ids[0]] - c).magnitudeSquared(); if ((p - c).magnitudeSquared() < r2) stack.pushBack(n); } } // remove old tets, create new ones edges.clear(); Edge e; for (PxI32 i = 0; i < PxI32(violatingTets.size()); i++) { PxI32 tetNr = violatingTets[i]; // copy information before we delete it PxI32 ids[4], ns[4]; for (PxI32 j = 0; j < 4; j++) { ids[j] = tetIds[4 * tetNr + j]; ns[j] = tetNeighbors[4 * tetNr + j]; } // delete the tetrahedron treeRemoveTet(tetNr); removeTetNr(tetNr); // visit neighbors for (PxI32 j = 0; j < 4; j++) { PxI32 n = ns[j]; if (n < 0 || tetMarks[n] != currentTetMark) { // no neighbor or neighbor is not-violating -> we are facing the border // create new tetrahedron PxI32 newTetNr = getNewTetNr(); PxI32 id0 = ids[tetFaces[j][2]]; PxI32 id1 = ids[tetFaces[j][1]]; PxI32 id2 = ids[tetFaces[j][0]]; tetIds[4 * newTetNr] = id0; tetIds[4 * newTetNr + 1] = id1; tetIds[4 * newTetNr + 2] = id2; tetIds[4 * newTetNr + 3] = vertNr; treeInsertTet(newTetNr); tetNeighbors[4 * newTetNr] = n; if (n >= 0) { for (PxI32 k = 0; k < 4; k++) { if (tetNeighbors[4 * n + k] == tetNr) tetNeighbors[4 * n + k] = newTetNr; } } // will set the neighbors among the new tetrahedra later tetNeighbors[4 * newTetNr + 1] = -1; tetNeighbors[4 * newTetNr + 2] = -1; tetNeighbors[4 * newTetNr + 3] = -1; e.init(id0, id1, newTetNr, 1); edges.pushBack(e); e.init(id1, id2, newTetNr, 2); edges.pushBack(e); e.init(id2, id0, newTetNr, 3); edges.pushBack(e); } } // next neighbor } // next violating tetrahedron // fix neighbors PxSort(edges.begin(), edges.size()); PxI32 nr = 0; while (nr < PxI32(edges.size())) { Edge& e0 = edges[nr]; nr++; if (nr < PxI32(edges.size()) && edges[nr] == e0) { Edge& e1 = edges[nr]; tetNeighbors[4 * e0.tetNr + e0.faceNr] = e1.tetNr; tetNeighbors[4 * e1.tetNr + e1.faceNr] = e0.tetNr; nr++; } } return true; } // ----------------------------------------------------------------------------------- static PxF64 tetQuality(const PxVec3d& p0, const PxVec3d& p1, const PxVec3d& p2, const PxVec3d& p3) { PxVec3d d0 = p1 - p0; PxVec3d d1 = p2 - p0; PxVec3d d2 = p3 - p0; PxVec3d d3 = p2 - p1; PxVec3d d4 = p3 - p2; PxVec3d d5 = p1 - p3; PxF64 s0 = d0.magnitudeSquared(); PxF64 s1 = d1.magnitudeSquared(); PxF64 s2 = d2.magnitudeSquared(); PxF64 s3 = d3.magnitudeSquared(); PxF64 s4 = d4.magnitudeSquared(); PxF64 s5 = d5.magnitudeSquared(); PxF64 ms = (s0 + s1 + s2 + s3 + s4 + s5) / 6.0; PxF64 rms = sqrt(ms); static const PxF64 s = 12.0 / sqrt(2.0); PxF64 vol = d0.dot(d1.cross(d2)) / 6.0; return s * vol / (rms * rms * rms); // 1.0 for regular tetrahedron } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::pruneTets() { insideTester.init(surfaceVerts.begin(), PxI32(surfaceVerts.size()), surfaceTriIds.begin(), PxI32(surfaceTriIds.size()) / 3); static PxF64 minQuality = 0.01; PxI32 numTets = tetIds.size() / 4; PxI32 num = 0; for (PxI32 i = 0; i < numTets; i++) { bool remove = false; PxI32* ids = &tetIds[4 * i]; for (PxI32 j = 0; j < 4; j++) { if (ids[j] >= firstABBVert) remove = true; } if (ids[0] < 0 || ids[1] < 0 || ids[2] < 0 || ids[3] < 0) remove = true; if (!remove) { PxVec3d c = getTetCenter(i); if (!insideTester.isInside(PxVec3(PxReal(c.x), PxReal(c.y), PxReal(c.z)))) remove = true; if (tetQuality(tetVerts[ids[0]], tetVerts[ids[1]], tetVerts[ids[2]], tetVerts[ids[3]]) < minQuality) continue; } if (remove) continue; for (PxI32 j = 0; j < 4; j++) tetIds[4 * num + j] = ids[j]; num++; } tetIds.resize(4 * num); } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::createTetMesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds, bool includeOctreeNodes, PxI32 _maxVertsPerCell, PxI32 _maxTreeDepth) { this->surfaceVerts = verts; surfaceTriIds.resize(triIds.size()); for (PxU32 i = 0; i < triIds.size(); i++) this->surfaceTriIds[i] = triIds[i]; this->maxVertsPerCell = _maxVertsPerCell; this->maxTreeDepth = _maxTreeDepth; createTree(); clearTets(); if (cells.empty()) return; createTetVerts(includeOctreeNodes); if (tetVerts.empty()) return; for (PxI32 i = 0; i < PxI32(cells.size()); i++) cells[i].closestTetNr = -1; // create aabb tets Bounds3 bounds; bounds.setEmpty(); for (PxI32 i = 0; i < PxI32(tetVerts.size()); i++) bounds.include(tetVerts[i]); bounds.expand(bounds.getDimensions().magnitude() * 0.1); firstABBVert = PxI32(tetVerts.size()); PxVec3d dims = bounds.getDimensions(); for (PxI32 i = 0; i < 8; i++) { tetVerts.pushBack(bounds.minimum + PxVec3d( cubeCorners[i][0] * dims.x, cubeCorners[i][1] * dims.y, cubeCorners[i][2] * dims.z)); } for (PxI32 i = 0; i < 6; i++) { for (PxI32 j = 0; j < 4; j++) { tetIds.pushBack(firstABBVert + cubeTets[i][j]); tetNeighbors.pushBack(cubeTetNeighbors[i][j]); } treeInsertTet(i); } tetMarks.resize(6, 0); for (PxI32 i = 0; i < firstABBVert; i++) { meshInsertTetVert(i); } pruneTets(); renderTriIds.clear(); renderVerts.clear(); } // ----------------------------------------------------------------------------------- void OctreeTetrahedralizer::readBack(PxArray<PxVec3> &outputTetVerts, PxArray<PxU32> &outputTetIds) { outputTetVerts.resize(tetVerts.size()); for (PxU32 i = 0; i < tetVerts.size(); i++) { PxVec3d &v = tetVerts[i]; outputTetVerts[i] = PxVec3(PxReal(v.x), PxReal(v.y), PxReal(v.z)); } outputTetIds.resize(tetIds.size()); for (PxU32 i = 0; i < tetIds.size(); i++) outputTetIds[i] = PxU32(tetIds[i]); } } }
20,051
C++
26.356071
120
0.536632
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtVec3.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_VEC3_H #define EXT_VEC3_H #include "foundation/PxMath.h" #include "foundation/PxVec3.h" namespace physx { namespace Ext { // --------------------------------------------------------------------------------- struct Bounds3 { Bounds3() {} Bounds3(const PxVec3d &min, const PxVec3d &max) : minimum(min), maximum(max) {} void setEmpty() { minimum = PxVec3d(PX_MAX_F64, PX_MAX_F64, PX_MAX_F64); maximum = PxVec3d(-PX_MAX_F64, -PX_MAX_F64, -PX_MAX_F64); } PxVec3d getDimensions() const { return maximum - minimum; } void include(const PxVec3d &p) { minimum = minimum.minimum(p); maximum = maximum.maximum(p); } void include(const Bounds3 &b) { minimum = minimum.minimum(b.minimum); maximum = maximum.maximum(b.maximum); } void expand(double d) { minimum -= PxVec3d(d, d, d); maximum += PxVec3d(d, d, d); } PxVec3d minimum, maximum; }; } } #endif
2,507
C
34.323943
86
0.694456
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayTetrahedralizer.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtDelaunayTetrahedralizer.h" #include "foundation/PxSort.h" #include "foundation/PxHashMap.h" #include "ExtUtilities.h" namespace physx { namespace Ext { using Triangle = Gu::IndexedTriangleT<PxI32>; //http://tizian.cs.uni-bonn.de/publications/BaudsonKlein.pdf Page 44 static const PxI32 neighborFaces[4][3] = { { 0, 1, 2 }, { 0, 3, 1 }, { 0, 2, 3 }, { 1, 3, 2 } }; static const PxI32 tetTip[4] = { 3, 2, 1, 0 }; struct Plane { PxVec3d normal; PxF64 planeD; PX_FORCE_INLINE Plane(const PxVec3d& n, PxF64 d) : normal(n), planeD(d) { } PX_FORCE_INLINE Plane(const PxVec3d& n, const PxVec3d& pointOnPlane) : normal(n) { planeD = -pointOnPlane.dot(normal); } PX_FORCE_INLINE Plane(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c) { normal = (b - a).cross(c - a); PxF64 norm = normal.magnitude(); normal /= norm; planeD = -a.dot(normal); } PX_FORCE_INLINE PxF64 signedDistance(const PxVec3d& p) { return normal.dot(p) + planeD; } PX_FORCE_INLINE PxF64 unsignedDistance(const PxVec3d& p) { return PxAbs(signedDistance(p)); } }; DelaunayTetrahedralizer::DelaunayTetrahedralizer(const PxVec3d& min, const PxVec3d& max) { for(PxI32 i = 0; i < 4; ++i) neighbors.pushBack(-1); PxF64 radius = 1.1 * 0.5 * (max - min).magnitude(); PxF64 scaledRadius = 6 * radius; centeredNormalizedPoints.pushBack(PxVec3d(-scaledRadius, -scaledRadius, -scaledRadius)); centeredNormalizedPoints.pushBack(PxVec3d(scaledRadius, scaledRadius, -scaledRadius)); centeredNormalizedPoints.pushBack(PxVec3d(-scaledRadius, scaledRadius, scaledRadius)); centeredNormalizedPoints.pushBack(PxVec3d(scaledRadius, -scaledRadius, scaledRadius)); numAdditionalPointsAtBeginning = 4; result.pushBack(Tetrahedron(0, 1, 2, 3)); for (PxI32 i = 0; i < 4; ++i) vertexToTet.pushBack(0); } void buildNeighborhood(const PxI32* tets, PxU32 numTets, PxArray<PxI32>& result) { PxU32 l = 4 * numTets; result.clear(); result.resize(l, -1); PxHashMap<SortedTriangle, PxI32, TriangleHash> faces; for (PxU32 i = 0; i < numTets; ++i) { const PxI32* tet = &tets[4 * i]; if (tet[0] < 0) continue; for (PxI32 j = 0; j < 4; ++j) { SortedTriangle tri(tet[neighborFaces[j][0]], tet[neighborFaces[j][1]], tet[neighborFaces[j][2]]); if (const PxPair<const SortedTriangle, PxI32>* ptr = faces.find(tri)) { if (ptr->second < 0) { //PX_ASSERT(false); //Invalid tetmesh since a face is shared by more than 2 tetrahedra continue; } result[4 * i + j] = ptr->second; result[ptr->second] = 4 * i + j; faces[tri] = -1; } else faces.insert(tri, 4 * i + j); } } } void buildNeighborhood(const PxArray<Tetrahedron>& tets, PxArray<PxI32>& result) { buildNeighborhood(reinterpret_cast<const PxI32*>(tets.begin()), tets.size(), result); } bool shareFace(const Tetrahedron& t1, const Tetrahedron& t2) { PxI32 counter = 0; if (t1.contains(t2[0])) ++counter; if (t1.contains(t2[1])) ++counter; if (t1.contains(t2[2])) ++counter; if (t1.contains(t2[3])) ++counter; if (counter == 4) PX_ASSERT(false); return counter == 3; } //Keep for debugging & verification void validateNeighborhood(const PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors) { PxI32 borderCounter = 0; for (PxU32 i = 0; i < neighbors.size(); ++i) if (neighbors[i] == -1) ++borderCounter; //if (borderCounter != 4) // throw new Exception(); PxArray<PxI32> n; buildNeighborhood(tets, n); for (PxU32 i = 0; i < n.size(); ++i) { if (n[i] < 0) continue; if (n[i] != neighbors[i]) PX_ASSERT(false); } for (PxU32 i = 0; i < neighbors.size(); ++i) { if (neighbors[i] < 0) continue; Tetrahedron tet1 = tets[i >> 2]; Tetrahedron tet2 = tets[neighbors[i] >> 2]; if (!shareFace(tet1, tet2)) PX_ASSERT(false); PxI32 face1 = i & 3; SortedTriangle tri1(tet1[neighborFaces[face1][0]], tet1[neighborFaces[face1][1]], tet1[neighborFaces[face1][2]]); PxI32 face2 = neighbors[i] & 3; SortedTriangle tri2(tet2[neighborFaces[face2][0]], tet2[neighborFaces[face2][1]], tet2[neighborFaces[face2][2]]); if (tri1.A != tri2.A || tri1.B != tri2.B || tri1.C != tri2.C) PX_ASSERT(false); } } void buildVertexToTet(const PxArray<Tetrahedron>& tets, PxI32 numPoints, PxArray<PxI32>& result) { result.clear(); result.resize(numPoints, -1); for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; result[tet[0]] = i; result[tet[1]] = i; result[tet[2]] = i; result[tet[3]] = i; } } DelaunayTetrahedralizer::DelaunayTetrahedralizer(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets) { initialize(points, tets); } void DelaunayTetrahedralizer::initialize(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets) { clearLockedEdges(); clearLockedTriangles(); centeredNormalizedPoints = points; result = tets; numAdditionalPointsAtBeginning = 0; buildNeighborhood(tets, neighbors); buildVertexToTet(tets, points.size(), vertexToTet); for (PxU32 i = 0; i < tets.size(); ++i) if (tets[i][0] < 0) unusedTets.pushBack(i); } PX_FORCE_INLINE PxF64 inSphere(const PxVec3d& pa, const PxVec3d& pb, const PxVec3d& pc, const PxVec3d& pd, const PxVec3d& candidiate) { PxF64 aex = pa.x - candidiate.x; PxF64 bex = pb.x - candidiate.x; PxF64 cex = pc.x - candidiate.x; PxF64 dex = pd.x - candidiate.x; PxF64 aey = pa.y - candidiate.y; PxF64 bey = pb.y - candidiate.y; PxF64 cey = pc.y - candidiate.y; PxF64 dey = pd.y - candidiate.y; PxF64 aez = pa.z - candidiate.z; PxF64 bez = pb.z - candidiate.z; PxF64 cez = pc.z - candidiate.z; PxF64 dez = pd.z - candidiate.z; PxF64 ab = aex * bey - bex * aey; PxF64 bc = bex * cey - cex * bey; PxF64 cd = cex * dey - dex * cey; PxF64 da = dex * aey - aex * dey; PxF64 ac = aex * cey - cex * aey; PxF64 bd = bex * dey - dex * bey; PxF64 abc = aez * bc - bez * ac + cez * ab; PxF64 bcd = bez * cd - cez * bd + dez * bc; PxF64 cda = cez * da + dez * ac + aez * cd; PxF64 dab = dez * ab + aez * bd + bez * da; PxF64 alift = aex * aex + aey * aey + aez * aez; PxF64 blift = bex * bex + bey * bey + bez * bez; PxF64 clift = cex * cex + cey * cey + cez * cez; PxF64 dlift = dex * dex + dey * dey + dez * dez; return (dlift * abc - clift * dab) + (blift * cda - alift * bcd); } PX_FORCE_INLINE bool isDelaunay(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& neighbors, PxI32 faceId) { PxI32 neighborPointer = neighbors[faceId]; if (neighborPointer < 0) return true; //Border faces are always delaunay PxI32 tet1Id = faceId >> 2; PxI32 tet2Id = neighborPointer >> 2; const PxI32* localTriangle1 = neighborFaces[faceId & 3]; PxI32 localTip1 = tetTip[faceId & 3]; PxI32 localTip2 = tetTip[neighborPointer & 3]; Tetrahedron tet1 = tets[tet1Id]; Tetrahedron tet2 = tets[tet2Id]; return inSphere(points[tet1[localTriangle1[0]]], points[tet1[localTriangle1[1]]], points[tet1[localTriangle1[2]]], points[tet1[localTip1]], points[tet2[localTip2]]) > 0; } PX_FORCE_INLINE PxI32 storeNewTet(PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, const Tetrahedron& tet, PxArray<PxI32>& unusedTets) { if (unusedTets.size() == 0) { PxU32 tetId = tets.size(); tets.pushBack(tet); for (PxI32 i = 0; i < 4; ++i) neighbors.pushBack(-1); return tetId; } else { PxI32 tetId = unusedTets[unusedTets.size() - 1]; unusedTets.remove(unusedTets.size() - 1); tets[tetId] = tet; return tetId; } } PX_FORCE_INLINE PxI32 localFaceId(PxI32 localA, PxI32 localB, PxI32 localC) { PxI32 result = localA + localB + localC - 3; PX_ASSERT(result >= 0 || result <= 3); return result; } PX_FORCE_INLINE PxI32 localFaceId(const Tetrahedron& tet, PxI32 globalA, PxI32 globalB, PxI32 globalC) { PxI32 result = localFaceId(tet.indexOf(globalA), tet.indexOf(globalB), tet.indexOf(globalC)); return result; } PX_FORCE_INLINE void setFaceNeighbor(PxArray<PxI32>& neighbors, PxI32 tetId, PxI32 faceId, PxI32 newNeighborTet, PxI32 newNeighborFace) { neighbors[4 * tetId + faceId] = 4 * newNeighborTet + newNeighborFace; neighbors[4 * newNeighborTet + newNeighborFace] = 4 * tetId + faceId; } PX_FORCE_INLINE void setFaceNeighbor(PxArray<PxI32>& neighbors, PxI32 tetId, PxI32 faceId, PxI32 newNeighbor) { neighbors[4 * tetId + faceId] = newNeighbor; if (newNeighbor >= 0) neighbors[newNeighbor] = 4 * tetId + faceId; } PX_FORCE_INLINE void setFaceNeighbor(PxArray<PxI32>& affectedFaces, PxArray<PxI32>& neighbors, PxI32 tetId, PxI32 faceId, PxI32 newNeighbor) { setFaceNeighbor(neighbors, tetId, faceId, newNeighbor); affectedFaces.pushBack(newNeighbor); } void flip1to4(PxI32 pointToInsert, PxI32 tetId, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces) { const Tetrahedron origTet = tets[tetId]; Tetrahedron tet(origTet[0], origTet[1], origTet[2], pointToInsert); tets[tetId] = tet; Tetrahedron tet2(origTet[0], origTet[3], origTet[1], pointToInsert); Tetrahedron tet3(origTet[0], origTet[2], origTet[3], pointToInsert); Tetrahedron tet4(origTet[1], origTet[3], origTet[2], pointToInsert); PxI32 tet2Id = storeNewTet(tets, neighbors, tet2, unusedTets); PxI32 tet3Id = storeNewTet(tets, neighbors, tet3, unusedTets); PxI32 tet4Id = storeNewTet(tets, neighbors, tet4, unusedTets); PxI32 n1 = neighbors[4 * tetId + localFaceId(origTet, origTet[0], origTet[1], origTet[2])]; PxI32 n2 = neighbors[4 * tetId + localFaceId(origTet, origTet[0], origTet[1], origTet[3])]; PxI32 n3 = neighbors[4 * tetId + localFaceId(origTet, origTet[0], origTet[2], origTet[3])]; PxI32 n4 = neighbors[4 * tetId + localFaceId(origTet, origTet[1], origTet[2], origTet[3])]; setFaceNeighbor(affectedFaces, neighbors, tetId, localFaceId(tet, origTet[0], origTet[1], origTet[2]), n1); setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, origTet[0], origTet[1], origTet[3]), n2); setFaceNeighbor(affectedFaces, neighbors, tet3Id, localFaceId(tet3, origTet[0], origTet[2], origTet[3]), n3); setFaceNeighbor(affectedFaces, neighbors, tet4Id, localFaceId(tet4, origTet[1], origTet[2], origTet[3]), n4); setFaceNeighbor(neighbors, tetId, localFaceId(tet, pointToInsert, origTet[0], origTet[1]), tet2Id, localFaceId(tet2, pointToInsert, origTet[0], origTet[1])); setFaceNeighbor(neighbors, tetId, localFaceId(tet, pointToInsert, origTet[0], origTet[2]), tet3Id, localFaceId(tet3, pointToInsert, origTet[0], origTet[2])); setFaceNeighbor(neighbors, tetId, localFaceId(tet, pointToInsert, origTet[1], origTet[2]), tet4Id, localFaceId(tet4, pointToInsert, origTet[1], origTet[2])); setFaceNeighbor(neighbors, tet2Id, localFaceId(tet2, pointToInsert, origTet[0], origTet[3]), tet3Id, localFaceId(tet3, pointToInsert, origTet[0], origTet[3])); setFaceNeighbor(neighbors, tet2Id, localFaceId(tet2, pointToInsert, origTet[1], origTet[3]), tet4Id, localFaceId(tet4, pointToInsert, origTet[1], origTet[3])); setFaceNeighbor(neighbors, tet3Id, localFaceId(tet3, pointToInsert, origTet[2], origTet[3]), tet4Id, localFaceId(tet4, pointToInsert, origTet[2], origTet[3])); vertexToTet[tet[0]] = tetId; vertexToTet[tet[1]] = tetId; vertexToTet[tet[2]] = tetId; vertexToTet[tet[3]] = tetId; vertexToTet[tet2[0]] = tet2Id; vertexToTet[tet2[1]] = tet2Id; vertexToTet[tet2[2]] = tet2Id; vertexToTet[tet2[3]] = tet2Id; vertexToTet[tet3[0]] = tet3Id; vertexToTet[tet3[1]] = tet3Id; vertexToTet[tet3[2]] = tet3Id; vertexToTet[tet3[3]] = tet3Id; vertexToTet[tet4[0]] = tet4Id; vertexToTet[tet4[1]] = tet4Id; vertexToTet[tet4[2]] = tet4Id; vertexToTet[tet4[3]] = tet4Id; } bool flip2to3(PxI32 tet1Id, PxI32 tet2Id, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces, PxI32 tip1, PxI32 tip2, const Triangle& tri) { // 2->3 flip Tetrahedron tet1(tip2, tip1, tri[0], tri[1]); Tetrahedron tet2(tip2, tip1, tri[1], tri[2]); Tetrahedron tet3(tip2, tip1, tri[2], tri[0]); PxI32 n1 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[0], tri[1], tip1)]; PxI32 n2 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[0], tri[1], tip2)]; if (n1 >= 0 && (n1 >> 2) == (n2 >> 2)) { if (Tetrahedron::identical(tet1, tets[n1 >> 2])) return false; } PxI32 n3 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[1], tri[2], tip1)]; PxI32 n4 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[1], tri[2], tip2)]; if (n3 >= 0 && (n3 >> 2) == (n4 >> 2)) { if (Tetrahedron::identical(tet2, tets[n3 >> 2])) return false; } PxI32 n5 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[2], tri[0], tip1)]; PxI32 n6 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[2], tri[0], tip2)]; if (n5 >= 0 && (n5 >> 2) == (n6 >> 2)) { if (Tetrahedron::identical(tet3, tets[n5 >> 2])) return false; } PxI32 tet3Id = storeNewTet(tets, neighbors, tet3, unusedTets); setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, tri[0], tri[1], tip1), n1); setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, tri[0], tri[1], tip2), n2); setFaceNeighbor(neighbors, tet1Id, localFaceId(tet1, tri[0], tip1, tip2), tet3Id, localFaceId(tet3, tri[0], tip1, tip2)); //Interior face setFaceNeighbor(neighbors, tet1Id, localFaceId(tet1, tri[1], tip1, tip2), tet2Id, localFaceId(tet2, tri[1], tip1, tip2)); //Interior face setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, tri[1], tri[2], tip1), n3); setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, tri[1], tri[2], tip2), n4); setFaceNeighbor(neighbors, tet2Id, localFaceId(tet2, tri[2], tip1, tip2), tet3Id, localFaceId(tet3, tri[2], tip1, tip2)); //Interior face setFaceNeighbor(affectedFaces, neighbors, tet3Id, localFaceId(tet3, tri[2], tri[0], tip1), n5); setFaceNeighbor(affectedFaces, neighbors, tet3Id, localFaceId(tet3, tri[2], tri[0], tip2), n6); tets[tet1Id] = tet1; tets[tet2Id] = tet2; vertexToTet[tet1[0]] = tet1Id; vertexToTet[tet1[1]] = tet1Id; vertexToTet[tet1[2]] = tet1Id; vertexToTet[tet1[3]] = tet1Id; vertexToTet[tet2[0]] = tet2Id; vertexToTet[tet2[1]] = tet2Id; vertexToTet[tet2[2]] = tet2Id; vertexToTet[tet2[3]] = tet2Id; vertexToTet[tet3[0]] = tet3Id; vertexToTet[tet3[1]] = tet3Id; vertexToTet[tet3[2]] = tet3Id; vertexToTet[tet3[3]] = tet3Id; return true; } bool flip3to2(PxI32 tet1Id, PxI32 tet2Id, PxI32 tet3Id, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces, PxI32 tip1, PxI32 tip2, PxI32 reflexEdgeA, PxI32 reflexEdgeB, PxI32 nonReflexTrianglePoint) { // 3->2 flip Tetrahedron tet1(tip1, tip2, reflexEdgeA, nonReflexTrianglePoint); Tetrahedron tet2(tip2, tip1, reflexEdgeB, nonReflexTrianglePoint); PxI32 n1 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], reflexEdgeA, tip1, nonReflexTrianglePoint)]; PxI32 n2 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], reflexEdgeA, tip2, nonReflexTrianglePoint)]; PxI32 n3 = neighbors[4 * tet3Id + localFaceId(tets[tet3Id], reflexEdgeA, tip1, tip2)]; if (n1 >= 0 && n2 >= 0 && (n1 >> 2) == (n2 >> 2) && Tetrahedron::identical(tet1, tets[n1 >> 2])) return false; if (n1 >= 0 && n3 >= 0 && (n1 >> 2) == (n3 >> 2) && Tetrahedron::identical(tet1, tets[n1 >> 2])) return false; if (n2 >= 0 && n3 >= 0 && (n2 >> 2) == (n3 >> 2) && Tetrahedron::identical(tet1, tets[n2 >> 2])) return false; PxI32 n4 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], reflexEdgeB, tip1, nonReflexTrianglePoint)]; PxI32 n5 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], reflexEdgeB, tip2, nonReflexTrianglePoint)]; PxI32 n6 = neighbors[4 * tet3Id + localFaceId(tets[tet3Id], reflexEdgeB, tip1, tip2)]; if (n4 >= 0 && n5 >= 0 && (n4 >> 2) == (n5 >> 2) && Tetrahedron::identical(tet2, tets[n4 >> 2])) return false; if (n4 >= 0 && n6 >= 0 && (n4 >> 2) == (n6 >> 2) && Tetrahedron::identical(tet2, tets[n4 >> 2])) return false; if (n5 >= 0 && n6 >= 0 && (n5 >> 2) == (n6 >> 2) && Tetrahedron::identical(tet2, tets[n5 >> 2])) return false; setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, reflexEdgeA, tip1, nonReflexTrianglePoint), n1); setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, reflexEdgeA, tip2, nonReflexTrianglePoint), n2); setFaceNeighbor(affectedFaces, neighbors, tet1Id, localFaceId(tet1, reflexEdgeA, tip1, tip2), n3); setFaceNeighbor(neighbors, tet1Id, localFaceId(tet1, nonReflexTrianglePoint, tip1, tip2), tet2Id, localFaceId(tet2, nonReflexTrianglePoint, tip1, tip2)); //Interior face // Marker (*) setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, reflexEdgeB, tip1, nonReflexTrianglePoint), n4); setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, reflexEdgeB, tip2, nonReflexTrianglePoint), n5); setFaceNeighbor(affectedFaces, neighbors, tet2Id, localFaceId(tet2, reflexEdgeB, tip1, tip2), n6); tets[tet1Id] = tet1; tets[tet2Id] = tet2; tets[tet3Id] = Tetrahedron(-1, -1, -1, -1); for (PxI32 i = 0; i < 4; ++i) neighbors[4 * tet3Id + i] = -2; unusedTets.pushBack(tet3Id); vertexToTet[tet1[0]] = tet1Id; vertexToTet[tet1[1]] = tet1Id; vertexToTet[tet1[2]] = tet1Id; vertexToTet[tet1[3]] = tet1Id; vertexToTet[tet2[0]] = tet2Id; vertexToTet[tet2[1]] = tet2Id; vertexToTet[tet2[2]] = tet2Id; vertexToTet[tet2[3]] = tet2Id; return true; } PX_FORCE_INLINE PxF64 orient3D(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d) { return (a - d).dot((b - d).cross(c - d)); } PX_FORCE_INLINE bool edgeIsLocked(const PxHashSet<PxU64>& lockedEdges, int edgeA, int edgeB) { return lockedEdges.contains(key(edgeA, edgeB)); } PX_FORCE_INLINE bool faceIsLocked(const PxHashSet<SortedTriangle, TriangleHash>& lockedTriangles, int triA, int triB, int triC) { return lockedTriangles.contains(SortedTriangle(triA, triB, triC)); } void flip(const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxI32 faceId, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces, const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges) { PxI32 neighborPointer = neighbors[faceId]; if (neighborPointer < 0) return; PxI32 tet1Id = faceId >> 2; const PxI32* localTriangle1 = neighborFaces[faceId & 3]; Tetrahedron tet1 = tets[tet1Id]; Triangle tri(tet1[localTriangle1[0]], tet1[localTriangle1[1]], tet1[localTriangle1[2]]); PxI32 localTip1 = tetTip[faceId & 3]; PxI32 localTip2 = tetTip[neighborPointer & 3]; PxI32 tip1 = tet1[localTip1]; PxI32 tet2Id = neighborPointer >> 2; Tetrahedron tet2 = tets[tet2Id]; PxI32 tip2 = tet2[localTip2]; PX_ASSERT(tet2.contains(tri[0]) && tet2.contains(tri[1]) && tet2.contains(tri[2])); PxI32 face1 = -1; PxI32 face2 = -1; PxI32 numReflexEdges = 0; PxI32 reflexEdgeA = -1; PxI32 reflexEdgeB = -1; PxI32 nonReflexTrianglePoint = -1; PxF64 ab = orient3D(points[tri[0]], points[tri[1]], points[tip1], points[tip2]); if (ab < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[0], localTriangle1[1], localTip1); reflexEdgeA = tri[0]; reflexEdgeB = tri[1]; nonReflexTrianglePoint = tri[2]; face2 = localFaceId(tet2, tri[0], tri[1], tip2); } PxF64 bc = orient3D(points[tri[1]], points[tri[2]], points[tip1], points[tip2]); if (bc < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[1], localTriangle1[2], localTip1); reflexEdgeA = tri[1]; reflexEdgeB = tri[2]; nonReflexTrianglePoint = tri[0]; face2 = localFaceId(tet2, tri[1], tri[2], tip2); } PxF64 ca = orient3D(points[tri[2]], points[tri[0]], points[tip1], points[tip2]); if (ca < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[2], localTriangle1[0], localTip1); reflexEdgeA = tri[2]; reflexEdgeB = tri[0]; nonReflexTrianglePoint = tri[1]; face2 = localFaceId(tet2, tri[2], tri[0], tip2); } if (numReflexEdges == 0) { if (!faceIsLocked(lockedFaces, tri[0], tri[1], tri[2])) flip2to3(tet1Id, tet2Id, neighbors, vertexToTet, tets, unusedTets, affectedFaces, tip1, tip2, tri); } else if (numReflexEdges == 1) { PxI32 candidate1 = neighbors[4 * tet1Id + face1] >> 2; PxI32 candidate2 = neighbors[4 * tet2Id + face2] >> 2; if (candidate1 == candidate2 && candidate1 >= 0) { if (!edgeIsLocked(lockedEdges, reflexEdgeA, reflexEdgeB) && !faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint) && !faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip1) && !faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip2)) flip3to2(tet1Id, tet2Id, candidate1, neighbors, vertexToTet, tets, unusedTets, affectedFaces, tip1, tip2, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint); } } else if (numReflexEdges == 2) { //Cannot do anything } else if (numReflexEdges == 3) { //Something is wrong if we end up here - maybe there are degenerate tetrahedra or issues due to numerical rounding } } void flip(PxArray<PxI32>& faces, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces, const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges) { while (faces.size() > 0) { PxI32 faceId = faces.popBack(); if (faceId < 0) continue; if (isDelaunay(points, tets, neighbors, faceId)) continue; affectedFaces.clear(); flip(points, tets, neighbors, vertexToTet, faceId, unusedTets, affectedFaces, lockedFaces, lockedEdges); for (PxU32 j = 0; j < affectedFaces.size(); ++j) if (faces.find(affectedFaces[j]) == faces.end()) faces.pushBack(affectedFaces[j]); } } void insertAndFlip(PxI32 pointToInsert, PxI32 tetId, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, PxArray<PxI32>& affectedFaces, const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges) { flip1to4(pointToInsert, tetId, neighbors, vertexToTet, tets, unusedTets, affectedFaces); PxArray<PxI32> stack; for (PxU32 j = 0; j < affectedFaces.size(); ++j) if (stack.find(affectedFaces[j]) == stack.end()) stack.pushBack(affectedFaces[j]); flip(stack, neighbors, vertexToTet, points, tets, unusedTets, affectedFaces, lockedFaces, lockedEdges); } PxI32 searchAll(const PxVec3d& p, const PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points) { for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; PxI32 j = 0; for (; j < 4; j++) { Plane plane(points[tet[neighborFaces[j][0]]], points[tet[neighborFaces[j][1]]], points[tet[neighborFaces[j][2]]]); PxF64 distP = plane.signedDistance(p); if (distP < 0) break; } if (j == 4) return i; } return -1; } bool runDelaunay(const PxArray<PxVec3d>& points, PxI32 start, PxI32 end, PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<PxI32>& unusedTets, const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges) { PxI32 tetId = 0; PxArray<PxI32> affectedFaces; for (PxI32 i = start; i < end; ++i) { const PxVec3d p = points[i]; if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z)) continue; if (tetId < 0 || unusedTets.find(tetId) != unusedTets.end()) tetId = 0; while (unusedTets.find(tetId) != unusedTets.end()) ++tetId; PxU32 counter = 0; bool tetLocated = false; while (!tetLocated) { const Tetrahedron& tet = tets[tetId]; const PxVec3d center = (points[tet[0]] + points[tet[1]] + points[tet[2]] + points[tet[3]]) * 0.25; PxF64 minDist = DBL_MAX; PxI32 minFaceNr = -1; for (PxI32 j = 0; j < 4; j++) { Plane plane(points[tet[neighborFaces[j][0]]], points[tet[neighborFaces[j][1]]], points[tet[neighborFaces[j][2]]]); PxF64 distP = plane.signedDistance(p); PxF64 distCenter = plane.signedDistance(center); PxF64 delta = distP - distCenter; if (delta == 0.0) continue; delta = -distCenter / delta; if (delta >= 0.0 && delta < minDist) { minDist = delta; minFaceNr = j; } } if (minDist >= 1.0) tetLocated = true; else { tetId = neighbors[4 * tetId + minFaceNr] >> 2; if (tetId < 0) { tetId = searchAll(p, tets, points); tetLocated = true; } } ++counter; if (counter > tets.size()) { tetId = searchAll(p, tets, points); if (tetId < 0) return false; tetLocated = true; } } insertAndFlip(i, tetId, neighbors, vertexToTet, points, tets, unusedTets, affectedFaces, lockedFaces, lockedEdges); } return true; } bool DelaunayTetrahedralizer::insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end) { for (PxI32 i = start; i < end; ++i) { centeredNormalizedPoints.pushBack(inPoints[i]); vertexToTet.pushBack(-1); } if (!runDelaunay(centeredNormalizedPoints, start + numAdditionalPointsAtBeginning, end + numAdditionalPointsAtBeginning, result, neighbors, vertexToTet, unusedTets, lockedTriangles, lockedEdges)) return false; return true; } void DelaunayTetrahedralizer::exportTetrahedra(PxArray<Tetrahedron>& tetrahedra) { tetrahedra.clear(); for (PxU32 i = 0; i < result.size(); ++i) { const Tetrahedron& tet = result[i]; if (tet[0] >= numAdditionalPointsAtBeginning && tet[1] >= numAdditionalPointsAtBeginning && tet[2] >= numAdditionalPointsAtBeginning && tet[3] >= numAdditionalPointsAtBeginning) tetrahedra.pushBack(Tetrahedron(tet[0] - numAdditionalPointsAtBeginning, tet[1] - numAdditionalPointsAtBeginning, tet[2] - numAdditionalPointsAtBeginning, tet[3] - numAdditionalPointsAtBeginning)); } } void DelaunayTetrahedralizer::insertPoints(const PxArray<PxVec3d>& inPoints, PxI32 start, PxI32 end, PxArray<Tetrahedron>& tetrahedra) { insertPoints(inPoints, start, end); exportTetrahedra(tetrahedra); } //Code below this line is for tetmesh manipulation and not directly required to generate a Delaunay tetrahedron mesh. It is used to impmrove the quality of a tetrahedral mesh. //https://cs.nyu.edu/~panozzo/papers/SLIM-2016.pdf PxF64 evaluateAmipsEnergyPow3(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d) { PxF64 x1 = a.x + d.x - 2.0 * b.x; PxF64 x2 = a.x + b.x + d.x - 3.0 * c.x; PxF64 y1 = a.y + d.y - 2.0 * b.y; PxF64 y2 = a.y + b.y + d.y - 3.0 * c.y; PxF64 z1 = a.z + d.z - 2.0 * b.z; PxF64 z2 = a.z + b.z + d.z - 3.0 * c.z; PxF64 f = (1.0 / (PxSqrt(3.0) * PxSqrt(6.0))) * ((a.x - d.x) * (y1 * z2 - y2 * z1) - (a.y - d.y) * (z2 * x1 - x2 * z1) + (a.z - d.z) * (y2 * x1 - y1 * x2)); if (f >= 0) return 0.25 * DBL_MAX; PxF64 g = a.x * (b.x + c.x + d.x - 3.0 * a.x) + a.y * (b.y + c.y + d.y - 3.0 * a.y) + a.z * (b.z + c.z + d.z - 3.0 * a.z) + b.x * (a.x + c.x + d.x - 3.0 * b.x) + b.y * (a.y + c.y + d.y - 3.0 * b.y) + b.z * (a.z + c.z + d.z - 3.0 * b.z) + c.x * x2 + c.y * y2 + c.z * z2 + d.x * (a.x + b.x + c.x - 3.0 * d.x) + d.y * (a.y + b.y + c.y - 3.0 * d.y) + d.z * (a.z + b.z + c.z - 3.0 * d.z); return -0.125 * (g * g * g) / (f * f); //return -0.5 * PxPow(f * f, -1.0 / 3.0) * g; } PX_FORCE_INLINE PxF64 pow(const PxF64 a, const PxF64 b) { return PxF64(PxPow(PxF32(a), PxF32(b))); } PX_FORCE_INLINE PxF64 evaluateAmipsEnergy(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d) { return pow(evaluateAmipsEnergyPow3(a, b, c, d), 1.0 / 3.0); } PxF64 maxEnergyPow3(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets) { PxF64 maxEnergy = 0; for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; PxF64 e = evaluateAmipsEnergyPow3(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); if (e > maxEnergy) maxEnergy = e; } return maxEnergy; } PX_FORCE_INLINE PxF64 maxEnergy(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets) { return pow(maxEnergyPow3(points, tets), 1.0 / 3.0); } PxF64 maxEnergyPow3(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& tetIds) { PxF64 maxEnergy = 0; for (PxU32 i = 0; i < tetIds.size(); ++i) { const Tetrahedron& tet = tets[tetIds[i]]; if (tet[0] < 0) continue; PxF64 e = evaluateAmipsEnergyPow3(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); if (e > maxEnergy) maxEnergy = e; } return maxEnergy; } PxF64 minAbsTetVolume(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets) { PxF64 minVol = DBL_MAX; for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; PxF64 vol = PxAbs(tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]])); if (vol < minVol) minVol = vol; } return minVol; } PxF64 minTetVolume(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets) { PxF64 minVol = DBL_MAX; for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; PxF64 vol = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); if (vol < minVol) minVol = vol; } return minVol; } PxF64 minTetVolume(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& indices) { PxF64 minVol = DBL_MAX; for (PxU32 i = 0; i < indices.size(); ++i) { const Tetrahedron& tet = tets[indices[i]]; if (tet[0] < 0) continue; PxF64 vol = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); if (vol < minVol) minVol = vol; } return minVol; } PxF64 MinimizeMaxAmipsEnergy::quality(const PxArray<PxI32> tetIndices) const { return maxEnergyPow3(points, tetrahedra, tetIndices); } PxF64 MinimizeMaxAmipsEnergy::quality(const PxArray<Tetrahedron> tetrahedraToCheck) const { return maxEnergyPow3(points, tetrahedraToCheck); } bool MinimizeMaxAmipsEnergy::improved(PxF64 previousQuality, PxF64 newQuality) const { return newQuality < previousQuality; //Minimize quality for Amips energy } PxF64 MaximizeMinTetVolume::quality(const PxArray<PxI32> tetIndices) const { return minTetVolume(points, tetrahedra, tetIndices); } PxF64 MaximizeMinTetVolume::quality(const PxArray<Tetrahedron> tetrahedraToCheck) const { return minTetVolume(points, tetrahedraToCheck); } bool MaximizeMinTetVolume::improved(PxF64 previousQuality, PxF64 newQuality) const { return newQuality > previousQuality; //Maximize quality for min volume } void fixVertexToTet(PxArray<PxI32>& vertexToTet, const PxArray<PxI32>& newTetIds, const PxArray<Tetrahedron>& tets) { for (PxU32 i = 0; i < newTetIds.size(); ++i) { PxI32 id = newTetIds[i]; const Tetrahedron& tet = tets[id]; if (tet[0] < 0) continue; while (PxU32(tet[0]) >= vertexToTet.size()) vertexToTet.pushBack(-1); while (PxU32(tet[1]) >= vertexToTet.size()) vertexToTet.pushBack(-1); while (PxU32(tet[2]) >= vertexToTet.size()) vertexToTet.pushBack(-1); while (PxU32(tet[3]) >= vertexToTet.size()) vertexToTet.pushBack(-1); vertexToTet[tet[0]] = id; vertexToTet[tet[1]] = id; vertexToTet[tet[2]] = id; vertexToTet[tet[3]] = id; } } void fixNeighborhoodLocally(const PxArray<PxI32>& removedTets, const PxArray<PxI32>& tetIndices, const PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighborhood, PxArray<PxI32>* affectedFaces = NULL) { for (PxU32 k = 0; k < removedTets.size(); ++k) { PxI32 i = removedTets[k]; for (PxI32 j = 0; j < 4; ++j) { PxI32 faceId = 4 * i + j; neighborhood[faceId] = -1; if (affectedFaces != NULL && affectedFaces->find(faceId) == affectedFaces->end()) affectedFaces->pushBack(faceId); } } PxHashMap<SortedTriangle, PxI32, TriangleHash> faces; for(PxU32 k = 0; k< tetIndices.size(); ++k) { PxI32 i = tetIndices[k]; if (i < 0) continue; const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; for (PxI32 j = 0; j < 4; ++j) { SortedTriangle tri(tet[neighborFaces[j][0]], tet[neighborFaces[j][1]], tet[neighborFaces[j][2]]); if (const PxPair<const SortedTriangle, PxI32>* ptr = faces.find(tri)) { neighborhood[4 * i + j] = ptr->second; neighborhood[ptr->second] = 4 * i + j; } else faces.insert(tri, 4 * i + j); } } //validateNeighborhood(tets, neighborhood); } void collectTetsConnectedToVertex(PxArray<PxI32>& faces, PxHashSet<PxI32>& tetsDone, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& tetNeighbors, const PxArray<PxI32>& vertexToTet, PxI32 vertexIndex, PxArray<PxI32>& tetIds, PxI32 secondVertexId = -1, PxI32 thirdVertexId = -1) { tetIds.clear(); int tetIndex = vertexToTet[vertexIndex]; if (tetIndex < 0) return; //Free floating point if ((secondVertexId < 0 || tets[tetIndex].contains(secondVertexId)) && (thirdVertexId < 0 || tets[tetIndex].contains(thirdVertexId))) tetIds.pushBack(tetIndex); faces.clear(); tetsDone.clear(); for (int i = 0; i < 4; ++i) { if (tetNeighbors[4 * tetIndex + i] >= 0) faces.pushBack(4 * tetIndex + i); } tetsDone.insert(tetIndex); while (faces.size() > 0) { PxI32 faceId = faces.popBack(); int tetId = tetNeighbors[faceId] >> 2; if (tetId < 0 || tetIds.find(tetId) != tetIds.end()) continue; const Tetrahedron& tet = tets[tetId]; int id = tet.indexOf(vertexIndex); if (id >= 0) { if ((secondVertexId < 0 || tets[tetId].contains(secondVertexId)) && (thirdVertexId < 0 || tets[tetId].contains(thirdVertexId))) tetIds.pushBack(tetId); const PxI32* f = neighborFaces[id]; for (int i = 0; i < 3; ++i) { int candidate = 4 * tetId + f[i]; if (tetsDone.insert(tetNeighbors[candidate] >> 2)) { int otherTetId = tetNeighbors[candidate] >> 2; if (otherTetId >= 0 && tets[otherTetId].contains(vertexIndex)) faces.pushBack(candidate); } } } } } void DelaunayTetrahedralizer::collectTetsConnectedToVertex(PxI32 vertexIndex, PxArray<PxI32>& tetIds) { stackMemory.clear(); physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, vertexIndex, tetIds, -1, -1); } void DelaunayTetrahedralizer::collectTetsConnectedToVertex(PxArray<PxI32>& faces, PxHashSet<PxI32>& tetsDone, PxI32 vertexIndex, PxArray<PxI32>& tetIds) { faces.clear(); tetsDone.clear(); physx::Ext::collectTetsConnectedToVertex(faces, tetsDone, result, neighbors, vertexToTet, vertexIndex, tetIds); } void DelaunayTetrahedralizer::collectTetsConnectedToEdge(PxI32 edgeStart, PxI32 edgeEnd, PxArray<PxI32>& tetIds) { if (edgeStart < edgeEnd) PxSwap(edgeStart, edgeEnd); stackMemory.clear(); physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeStart, tetIds, edgeEnd); } PX_FORCE_INLINE bool containsDuplicates(PxI32 a, PxI32 b, PxI32 c, PxI32 d) { return a == b || a == c || a == d || b == c || b == d || c == d; } //Returns true if the volume of a tet would become negative if a vertex it contains would get replaced by another one bool tetFlipped(const Tetrahedron& tet, PxI32 vertexToReplace, PxI32 replacement, const PxArray<PxVec3d>& points, PxF64 volumeChangeThreshold = 0.1) { PxF64 volumeBefore = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); PxI32 a = tet[0] == vertexToReplace ? replacement : tet[0]; PxI32 b = tet[1] == vertexToReplace ? replacement : tet[1]; PxI32 c = tet[2] == vertexToReplace ? replacement : tet[2]; PxI32 d = tet[3] == vertexToReplace ? replacement : tet[3]; if (containsDuplicates(a, b, c, d)) return false; PxF64 volume = tetVolume(points[a], points[b], points[c], points[d]); if (volume < 0) return true; if (PxAbs(volume / volumeBefore) < volumeChangeThreshold) return true; return false; } PX_FORCE_INLINE Tetrahedron getTet(const Tetrahedron& tet, PxI32 vertexToReplace, PxI32 replacement) { return Tetrahedron(tet[0] == vertexToReplace ? replacement : tet[0], tet[1] == vertexToReplace ? replacement : tet[1], tet[2] == vertexToReplace ? replacement : tet[2], tet[3] == vertexToReplace ? replacement : tet[3]); } PX_FORCE_INLINE bool containsDuplicates(const Tetrahedron& tet) { return tet[0] == tet[1] || tet[0] == tet[2] || tet[0] == tet[3] || tet[1] == tet[2] || tet[1] == tet[3] || tet[2] == tet[3]; } //Returns true if a tetmesh's edge, defined by vertex indices keep and remove, can be collapsed without leading to an invalid tetmesh topology bool canCollapseEdge(PxI32 keep, PxI32 remove, const PxArray<PxVec3d>& points, const PxArray<PxI32>& tetsConnectedToKeepVertex, const PxArray<PxI32>& tetsConnectedToRemoveVertex, const PxArray<Tetrahedron>& allTet, PxF64& qualityAfterCollapse, PxF64 volumeChangeThreshold = 0.1, BaseTetAnalyzer* tetAnalyzer = NULL) { const PxArray<PxI32>& tets = tetsConnectedToRemoveVertex; //If a tet would get a negative volume due to the edge collapse, then this edge is not collapsible for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = allTet[tets[i]]; if (tet[0] < 0) return false; if (tetFlipped(tet, remove, keep, points, volumeChangeThreshold)) return false; } PxHashMap<SortedTriangle, PxI32, TriangleHash> triangles; PxHashSet<PxI32> candidates; for (PxU32 i = 0; i < tets.size(); ++i) candidates.insert(tets[i]); const PxArray<PxI32>& tets2 = tetsConnectedToKeepVertex; for (PxU32 i = 0; i < tets2.size(); ++i) if (allTet[tets2[i]][0] >= 0) candidates.insert(tets2[i]); PxArray<PxI32> affectedTets; affectedTets.reserve(candidates.size()); PxArray<Tetrahedron> remainingTets; remainingTets.reserve(candidates.size()); //If a tet-face would get referenced by more than 2 tetrahedra due to the edge collapse, then this edge is not collapsible for (PxHashSet<PxI32>::Iterator iter = candidates.getIterator(); !iter.done(); ++iter) { PxI32 tetRef = *iter; affectedTets.pushBack(tetRef); Tetrahedron tet = getTet(allTet[tetRef], remove, keep); if (containsDuplicates(tet)) continue; remainingTets.pushBack(tet); for (PxU32 j = 0; j < 4; ++j) { SortedTriangle tri(tet[neighborFaces[j][0]], tet[neighborFaces[j][1]], tet[neighborFaces[j][2]]); if (const PxPair<const SortedTriangle, PxI32>* ptr = triangles.find(tri)) triangles[tri] = ptr->second + 1; else triangles.insert(tri, 1); } } for (PxHashMap<SortedTriangle, PxI32, TriangleHash>::Iterator iter = triangles.getIterator(); !iter.done(); ++iter) if (iter->second > 2) return false; if (tetAnalyzer == NULL) return true; qualityAfterCollapse = tetAnalyzer->quality(remainingTets); return tetAnalyzer->improved(tetAnalyzer->quality(affectedTets), qualityAfterCollapse); } bool DelaunayTetrahedralizer::canCollapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove, PxF64 volumeChangeThreshold, BaseTetAnalyzer* tetAnalyzer) { PxF64 qualityAfterCollapse; PxArray<PxI32> tetsA, tetsB; stackMemory.clear(); physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToKeep, tetsA); stackMemory.clear(); physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToRemove, tetsB); return canCollapseEdge(edgeVertexToKeep, edgeVertexToRemove, tetsA, tetsB, qualityAfterCollapse, volumeChangeThreshold, tetAnalyzer); } bool DelaunayTetrahedralizer::canCollapseEdge(PxI32 edgeVertexAToKeep, PxI32 edgeVertexBToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB, PxF64& qualityAfterCollapse, PxF64 volumeChangeThreshold, BaseTetAnalyzer* tetAnalyzer) { return physx::Ext::canCollapseEdge(edgeVertexAToKeep, edgeVertexBToRemove, centeredNormalizedPoints, tetsConnectedToA, //physx::Ext::collectTetsConnectedToVertex(result, neighbors, vertexToTet, edgeVertexAToKeep), tetsConnectedToB, //physx::Ext::collectTetsConnectedToVertex(result, neighbors, vertexToTet, edgeVertexBToRemove), result, qualityAfterCollapse, volumeChangeThreshold, tetAnalyzer); } void collapseEdge(PxI32 keep, PxI32 remove, const PxArray<PxI32>& tetsConnectedToKeepVertex, const PxArray<PxI32>& tetsConnectedToRemoveVertex, PxArray<Tetrahedron>& allTets, PxArray<PxI32>& neighborhood, PxArray<PxI32>& vertexToTet, PxArray<PxI32>& unusedTets, PxArray<PxI32>& changedTets) { PxArray<PxI32> removedTets; changedTets.clear(); const PxArray<PxI32>& tets = tetsConnectedToRemoveVertex; for (PxI32 i = tets.size() - 1; i >= 0; --i) { PxI32 tetId = tets[i]; Tetrahedron tet = allTets[tetId]; tet.replace(remove, keep); if (containsDuplicates(tet)) { for (PxU32 j = 0; j < 4; ++j) { if (vertexToTet[tet[j]] == tetId) vertexToTet[tet[j]] = -1; tet[j] = -1; } removedTets.pushBack(tetId); unusedTets.pushBack(tetId); } else { changedTets.pushBack(tetId); } allTets[tetId] = tet; } for (PxU32 i = 0; i < tetsConnectedToKeepVertex.size(); ++i) { PxI32 id = tetsConnectedToKeepVertex[i]; if (removedTets.find(id) == removedTets.end()) changedTets.pushBack(id); } for (PxU32 i = 0; i < removedTets.size(); ++i) { PxI32 id = removedTets[i]; for (PxI32 j = 0; j < 4; ++j) { PxI32 n = neighborhood[4 * id + j]; if (n >= 0) neighborhood[n] = -1; } } fixNeighborhoodLocally(removedTets, changedTets, allTets, neighborhood); fixVertexToTet(vertexToTet, changedTets, allTets); vertexToTet[remove] = -1; } void DelaunayTetrahedralizer::collapseEdge(PxI32 edgeVertexToKeep, PxI32 edgeVertexToRemove) { PxArray<PxI32> changedTets; PxArray<PxI32> keepTetIds; PxArray<PxI32> removeTetIds; stackMemory.clear(); physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToKeep, keepTetIds); stackMemory.clear(); physx::Ext::collectTetsConnectedToVertex(stackMemory.faces, stackMemory.hashSet, result, neighbors, vertexToTet, edgeVertexToRemove, removeTetIds); physx::Ext::collapseEdge(edgeVertexToKeep, edgeVertexToRemove, keepTetIds, removeTetIds, result, neighbors, vertexToTet, unusedTets, changedTets); } void DelaunayTetrahedralizer::collapseEdge(PxI32 edgeVertexAToKeep, PxI32 edgeVertexBToRemove, const PxArray<PxI32>& tetsConnectedToA, const PxArray<PxI32>& tetsConnectedToB) { PxArray<PxI32> changedTets; physx::Ext::collapseEdge(edgeVertexAToKeep, edgeVertexBToRemove, tetsConnectedToA, tetsConnectedToB, result, neighbors, vertexToTet, unusedTets, changedTets); } bool buildRing(const PxArray<Edge>& edges, PxArray<PxI32>& result) { result.reserve(edges.size() + 1); const Edge& first = edges[0]; result.pushBack(first.first); result.pushBack(first.second); PxU32 currentEdge = 0; PxI32 connector = first.second; for (PxU32 j = 1; j < edges.size(); ++j) { for (PxU32 i = 1; i < edges.size(); ++i) { if (i == currentEdge) continue; const Edge& e = edges[i]; if (e.first == connector) { currentEdge = i; result.pushBack(e.second); connector = e.second; } else if (e.second == connector) { currentEdge = i; result.pushBack(e.first); connector = e.first; } if (connector == result[0]) { result.remove(result.size() - 1); if (result.size() != edges.size()) { result.clear(); return false; //Multiple segments - unexpected input } return true; //Cyclic } } } result.clear(); return false; } void addRange(PxHashSet<PxI32>& set, const PxArray<PxI32>& list) { for (PxU32 i = 0; i < list.size(); ++i) set.insert(list[i]); } static Edge createEdge(PxI32 x, PxI32 y, bool swap) { if (swap) return Edge(y, x); else return Edge(x, y); } Edge getOtherEdge(const Tetrahedron& tet, PxI32 x, PxI32 y) { x = tet.indexOf(x); y = tet.indexOf(y); bool swap = x > y; if (swap) PxSwap(x, y); if (x == 0 && y == 1) return createEdge(tet[2], tet[3], swap); if (x == 0 && y == 2) return createEdge(tet[3], tet[1], swap); if (x == 0 && y == 3) return createEdge(tet[1], tet[2], swap); if (x == 1 && y == 2) return createEdge(tet[0], tet[3], swap); if (x == 1 && y == 3) return createEdge(tet[2], tet[0], swap); if (x == 2 && y == 3) return createEdge(tet[0], tet[1], swap); return Edge(-1, -1); } bool removeEdgeByFlip(PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& faces, PxHashSet<PxI32>& hashset, PxArray<PxI32>& tetIndices, PxArray<Tetrahedron>& tets, PxArray<PxVec3d>& pts, PxArray<PxI32>& unusedTets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, BaseTetAnalyzer* qualityAnalyzer = NULL) { //validateNeighborhood(tets, neighbors); PxArray<Edge> ringEdges; ringEdges.reserve(tetIndices.size()); for (PxU32 i = 0; i < tetIndices.size(); ++i) ringEdges.pushBack(getOtherEdge(tets[tetIndices[i]], edgeA, edgeB)); PxArray<PxI32> ring; buildRing(ringEdges, ring); if (ring.size() == 0) return false; PxArray<PxI32> ringCopy(ring); const PxVec3d& a = pts[edgeA]; const PxVec3d& b = pts[edgeB]; PxArray<Tetrahedron> newTets; newTets.reserve(ring.size() * 2); PxArray<Triangle> newFaces; while (ring.size() >= 3) { PxF64 shortestDist = DBL_MAX; PxI32 id = -1; for (PxI32 i = 0; i < PxI32(ring.size()); ++i) { const PxVec3d& s = pts[ring[(i - 1 + ring.size()) % ring.size()]]; const PxVec3d& middle = pts[ring[i]]; const PxVec3d& e = pts[ring[(i + 1) % ring.size()]]; const PxF64 d = (s - e).magnitudeSquared(); if (d < shortestDist) { const PxF64 vol1 = tetVolume(s, middle, e, b); const PxF64 vol2 = tetVolume(a, s, middle, e); if (vol1 > 0 && vol2 > 0) { shortestDist = d; id = i; } } } if (id < 0) return false; { const PxI32& s = ring[(id - 1 + ring.size()) % ring.size()]; const PxI32& middle = ring[id]; const PxI32& e = ring[(id + 1) % ring.size()]; newTets.pushBack(Tetrahedron(s, middle, e, edgeB)); newTets.pushBack(Tetrahedron(edgeA, s, middle, e)); newFaces.pushBack(Triangle(s, middle, e)); if (ring.size() > 3) { newFaces.pushBack(Triangle(s, e, edgeA)); newFaces.pushBack(Triangle(s, e, edgeB)); } } ring.remove(id); } //Analyze and decide if operation should be done if (qualityAnalyzer != NULL && !qualityAnalyzer->improved(qualityAnalyzer->quality(tetIndices), qualityAnalyzer->quality(newTets))) return false; PxArray<PxI32> newTetIds; for (PxU32 i = 0; i < tetIndices.size(); ++i) { for (PxI32 j = 0; j < 4; ++j) { PxI32 id = 4 * tetIndices[i] + j; PxI32 neighborTet = neighbors[id] >> 2; if (neighborTet >= 0 && tetIndices.find(neighborTet) == tetIndices.end() && newTetIds.find(neighborTet) == newTetIds.end()) newTetIds.pushBack(neighborTet); } } PxHashSet<PxI32> set; PxArray<PxI32> tetIds; collectTetsConnectedToVertex(faces, hashset, tets, neighbors, vertexToTet, edgeA, tetIds); addRange(set, tetIds); faces.forceSize_Unsafe(0); hashset.clear(); tetIds.forceSize_Unsafe(0); collectTetsConnectedToVertex(faces, hashset, tets, neighbors, vertexToTet, edgeB, tetIds); addRange(set, tetIds); for (PxU32 i = 0; i < ringCopy.size(); ++i) { faces.forceSize_Unsafe(0); hashset.clear(); tetIds.forceSize_Unsafe(0); collectTetsConnectedToVertex(faces, hashset, tets, neighbors, vertexToTet, ringCopy[i], tetIds); addRange(set, tetIds); } for (PxHashSet<PxI32>::Iterator iter = set.getIterator(); !iter.done(); ++iter) { PxI32 i = *iter; const Tetrahedron& neighborTet = tets[i]; for (PxU32 j = 0; j < newFaces.size(); ++j) if (neighborTet.containsFace(newFaces[j])) return false; for (PxU32 j = 0; j < newTets.size(); ++j) { const Tetrahedron& t = newTets[j]; if (Tetrahedron::identical(t, neighborTet)) return false; } } for (PxU32 i = 0; i < tetIndices.size(); ++i) { tets[tetIndices[i]] = Tetrahedron(-1, -1, -1, -1); unusedTets.pushBack(tetIndices[i]); } PxU32 l = newTetIds.size(); for (PxU32 i = 0; i < newTets.size(); ++i) newTetIds.pushBack(storeNewTet(tets, neighbors, newTets[i], unusedTets)); fixNeighborhoodLocally(tetIndices, newTetIds, tets, neighbors); tetIndices.clear(); for (PxU32 i = l; i < newTetIds.size(); ++i) tetIndices.pushBack(newTetIds[i]); fixVertexToTet(vertexToTet, tetIndices, tets); return true; } bool DelaunayTetrahedralizer::removeEdgeByFlip(PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& tetIndices, BaseTetAnalyzer* qualityAnalyzer) { stackMemory.clear(); return physx::Ext::removeEdgeByFlip(edgeA, edgeB, stackMemory.faces, stackMemory.hashSet, tetIndices, result, centeredNormalizedPoints, unusedTets, neighbors, vertexToTet, qualityAnalyzer); } void DelaunayTetrahedralizer::addLockedEdges(const PxArray<Triangle>& triangles) { for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& t = triangles[i]; lockedEdges.insert(key(t[0] + numAdditionalPointsAtBeginning, t[1] + numAdditionalPointsAtBeginning)); lockedEdges.insert(key(t[0] + numAdditionalPointsAtBeginning, t[2] + numAdditionalPointsAtBeginning)); lockedEdges.insert(key(t[1] + numAdditionalPointsAtBeginning, t[2] + numAdditionalPointsAtBeginning)); } } void DelaunayTetrahedralizer::addLockedTriangles(const PxArray<Triangle>& triangles) { for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; lockedTriangles.insert(SortedTriangle(tri[0] + numAdditionalPointsAtBeginning, tri[1] + numAdditionalPointsAtBeginning, tri[2] + numAdditionalPointsAtBeginning)); } } void previewFlip3to2(PxI32 tip1, PxI32 tip2, PxI32 reflexEdgeA, PxI32 reflexEdgeB, PxI32 nonReflexTrianglePoint, Tetrahedron& tet1, Tetrahedron& tet2) { // 3->2 flip tet1 = Tetrahedron(tip1, tip2, reflexEdgeA, nonReflexTrianglePoint); tet2 = Tetrahedron(tip2, tip1, reflexEdgeB, nonReflexTrianglePoint); } bool previewFlip2to3(PxI32 tet1Id, PxI32 tet2Id, const PxArray<PxI32>& neighbors, const PxArray<Tetrahedron>& tets, PxI32 tip1, PxI32 tip2, Triangle tri, Tetrahedron& tet1, Tetrahedron& tet2, Tetrahedron& tet3) { // 2->3 flip tet1 = Tetrahedron(tip2, tip1, tri[0], tri[1]); tet2 = Tetrahedron(tip2, tip1, tri[1], tri[2]); tet3 = Tetrahedron(tip2, tip1, tri[2], tri[0]); PxI32 n1 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[0], tri[1], tip1)]; PxI32 n2 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[0], tri[1], tip2)]; if (n1 >= 0 && (n1 >> 2) == (n2 >> 2)) { if (Tetrahedron::identical(tet1, tets[n1 >> 2])) return false; } PxI32 n3 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[1], tri[2], tip1)]; PxI32 n4 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[1], tri[2], tip2)]; if (n3 >= 0 && (n3 >> 2) == (n4 >> 2)) { if (Tetrahedron::identical(tet2, tets[n3 >> 2])) return false; } PxI32 n5 = neighbors[4 * tet1Id + localFaceId(tets[tet1Id], tri[2], tri[0], tip1)]; PxI32 n6 = neighbors[4 * tet2Id + localFaceId(tets[tet2Id], tri[2], tri[0], tip2)]; if (n5 >= 0 && (n5 >> 2) == (n6 >> 2)) { if (Tetrahedron::identical(tet3, tets[n5 >> 2])) return false; } return true; } bool previewFlip(const PxArray<PxVec3d>& points, const PxArray<Tetrahedron>& tets, const PxArray<PxI32>& neighbors, PxI32 faceId, PxArray<Tetrahedron>& newTets, PxArray<PxI32>& removedTets, const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges) { newTets.clear(); removedTets.clear(); PxI32 neighborPointer = neighbors[faceId]; if (neighborPointer < 0) return false; PxI32 tet1Id = faceId >> 2; const PxI32* localTriangle1 = neighborFaces[faceId & 3]; Tetrahedron tet1 = tets[tet1Id]; Triangle tri(tet1[localTriangle1[0]], tet1[localTriangle1[1]], tet1[localTriangle1[2]]); PxI32 localTip1 = tetTip[faceId & 3]; PxI32 localTip2 = tetTip[neighborPointer & 3]; PxI32 tip1 = tet1[localTip1]; PxI32 tet2Id = neighborPointer >> 2; Tetrahedron tet2 = tets[tet2Id]; PxI32 tip2 = tet2[localTip2]; if (!tet2.contains(tri[0]) || !tet2.contains(tri[1]) || !tet2.contains(tri[2])) { return false; } PxI32 face1 = -1; PxI32 face2 = -1; PxI32 numReflexEdges = 0; PxI32 reflexEdgeA = -1; PxI32 reflexEdgeB = -1; PxI32 nonReflexTrianglePoint = -1; PxF64 ab = orient3D(points[tri[0]], points[tri[1]], points[tip1], points[tip2]); if (ab < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[0], localTriangle1[1], localTip1); reflexEdgeA = tri[0]; reflexEdgeB = tri[1]; nonReflexTrianglePoint = tri[2]; face2 = localFaceId(tet2, tri[0], tri[1], tip2); } PxF64 bc = orient3D(points[tri[1]], points[tri[2]], points[tip1], points[tip2]); if (bc < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[1], localTriangle1[2], localTip1); reflexEdgeA = tri[1]; reflexEdgeB = tri[2]; nonReflexTrianglePoint = tri[0]; face2 = localFaceId(tet2, tri[1], tri[2], tip2); } PxF64 ca = orient3D(points[tri[2]], points[tri[0]], points[tip1], points[tip2]); if (ca < 0) { ++numReflexEdges; face1 = localFaceId(localTriangle1[2], localTriangle1[0], localTip1); reflexEdgeA = tri[2]; reflexEdgeB = tri[0]; nonReflexTrianglePoint = tri[1]; face2 = localFaceId(tet2, tri[2], tri[0], tip2); } if (numReflexEdges == 0) { if (!faceIsLocked(lockedFaces, tri[0], tri[1], tri[2])) { Tetrahedron tet3; if (previewFlip2to3(tet1Id, tet2Id, neighbors, tets, tip1, tip2, tri, tet1, tet2, tet3)) { newTets.pushBack(tet1); newTets.pushBack(tet2); newTets.pushBack(tet3); removedTets.pushBack(tet1Id); removedTets.pushBack(tet2Id); return true; } else return true; } } else if (numReflexEdges == 1) { PxI32 candidate1 = neighbors[4 * tet1Id + face1] >> 2; PxI32 candidate2 = neighbors[4 * tet2Id + face2] >> 2; if (candidate1 == candidate2 && candidate1 >= 0) { if (!edgeIsLocked(lockedEdges, reflexEdgeA, reflexEdgeB) && !faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint) && !faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip1) && !faceIsLocked(lockedFaces, reflexEdgeA, reflexEdgeB, tip2)) { previewFlip3to2(tip1, tip2, reflexEdgeA, reflexEdgeB, nonReflexTrianglePoint, tet1, tet2); newTets.pushBack(tet1); newTets.pushBack(tet2); removedTets.pushBack(tet1Id); removedTets.pushBack(tet2Id); removedTets.pushBack(candidate1); return true;; } } } else if (numReflexEdges == 2) { //Cannot do anything } else if (numReflexEdges == 3) { } return true; } void collectCommonFaces(const PxArray<PxI32>& a, const PxArray<PxI32>& b, const PxArray<PxI32>& neighbors, PxArray<PxI32>& result) { result.clear(); for (PxU32 i = 0; i < a.size(); ++i) { PxI32 tetId = a[i]; for (int j = 0; j < 4; ++j) { int id = 4 * tetId + j; if (b.find(neighbors[id] >> 2) != b.end()) { if (result.find(id) == result.end()) result.pushBack(id); } } } } void previewFlip2to3(PxI32 tip1, PxI32 tip2, const Triangle& tri, Tetrahedron& tet1, Tetrahedron& tet2, Tetrahedron& tet3) { // 2->3 flip tet1 = Tetrahedron(tip2, tip1, tri[0], tri[1]); tet2 = Tetrahedron(tip2, tip1, tri[1], tri[2]); tet3 = Tetrahedron(tip2, tip1, tri[2], tri[0]); } bool DelaunayTetrahedralizer::recoverEdgeByFlip(PxI32 eStart, PxI32 eEnd, RecoverEdgeMemoryCache& cache) { PxArray<PxI32>& tetsStart = cache.resultStart; PxArray<PxI32>& tetsEnd = cache.resultEnd; collectTetsConnectedToVertex(cache.facesStart, cache.tetsDoneStart, eStart, tetsStart); collectTetsConnectedToVertex(cache.facesEnd, cache.tetsDoneEnd, eEnd, tetsEnd); for (PxU32 i = 0; i < tetsEnd.size(); ++i) { const Tetrahedron& tet = result[tetsEnd[i]]; if (tet.contains(eStart)) return true; } PxArray<PxI32> commonFaces; collectCommonFaces(tetsStart, tetsEnd, neighbors, commonFaces); if (commonFaces.size() > 0) { for (PxU32 i = 0; i < commonFaces.size(); ++i) { PxI32 faceId = commonFaces[i]; PxI32 tetId = faceId >> 2; const Tetrahedron& tet = result[tetId]; const PxI32* local = neighborFaces[faceId & 3]; Triangle tri(tet[local[0]], tet[local[1]], tet[local[2]]); if (tri.contains(eStart) || tri.contains(eEnd)) continue; int n = neighbors[faceId]; int tetId2 = n >> 2; int tip1 = tet[tetTip[faceId & 3]]; int tip2 = result[tetId2][tetTip[n & 3]]; Tetrahedron tet1, tet2, tet3; previewFlip2to3(tip1, tip2, tri, tet1, tet2, tet3); if (tetVolume(tet1, centeredNormalizedPoints) > 0 && tetVolume(tet2, centeredNormalizedPoints) > 0 && tetVolume(tet3, centeredNormalizedPoints) > 0) { PxArray<PxI32> affectedFaces; if (flip2to3(tetId, tetId2, neighbors, vertexToTet, result, unusedTets, affectedFaces, tip1, tip2, tri)) return true; } } } return false; } void insert(PxArray<int>& list, int a, int b, int id) { for (PxI32 i = 0; i < PxI32(list.size()); ++i) if (list[i] == a || list[i] == b) { list.pushBack(-1); for (PxI32 j = list.size() - 2; j > i; --j) { list[j + 1] = list[j]; } list[i + 1] = id; return; } PX_ASSERT(false); } void DelaunayTetrahedralizer::generateTetmeshEnforcingEdges(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles, PxArray<PxArray<PxI32>>& allEdges, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets) { clearLockedEdges(); clearLockedTriangles(); addLockedEdges(triangles); addLockedTriangles(triangles); points.resize(trianglePoints.size()); for (PxU32 i = 0; i < trianglePoints.size(); ++i) points[i] = trianglePoints[i]; insertPoints(points, 0, points.size()); allEdges.clear(); allEdges.reserve(lockedEdges.size()); PxHashMap<PxU64, PxU32> edgeToIndex; PxArray<PxI32> list; for (PxHashSet<PxU64>::Iterator iter = lockedEdges.getIterator(); !iter.done(); ++iter) { edgeToIndex.insert(*iter, allEdges.size()); list.forceSize_Unsafe(0); list.pushBack(PxI32((*iter) >> 32)); list.pushBack(PxI32((*iter))); allEdges.pushBack(list); } pointToOriginalTriangle.clear(); for (PxU32 i = 0; i < points.size(); ++i) pointToOriginalTriangle.pushBack(PxArray<PxI32>()); for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; pointToOriginalTriangle[tri[0]].pushBack(i); pointToOriginalTriangle[tri[1]].pushBack(i); pointToOriginalTriangle[tri[2]].pushBack(i); } for (PxU32 i = 0;i < points.size(); ++i) { PxArray<PxI32>& tempList = pointToOriginalTriangle[i]; PxSort(tempList.begin(), tempList.size()); } PxArray<PxI32> intersection; RecoverEdgeMemoryCache cache; while (true) { PxArray<PxU64> copy; copy.reserve(lockedEdges.size()); for (PxHashSet<PxU64>::Iterator e = lockedEdges.getIterator(); !e.done(); ++e) copy.pushBack(*e); PxI32 missing = 0; for (PxU32 k = 0; k < copy.size(); ++k) { PxU64 e = copy[k]; PxI32 a = PxI32(e >> 32); PxI32 b = PxI32(e); if (!recoverEdgeByFlip(a, b, cache)) { PxU32 id = centeredNormalizedPoints.size(); PxU32 i = edgeToIndex[e]; if (allEdges[i].size() < 10) { PxVec3d p = (centeredNormalizedPoints[a] + centeredNormalizedPoints[b]) * 0.5; points.pushBack(p); insertPoints(points, points.size() - 1, points.size()); intersection.forceSize_Unsafe(0); intersectionOfSortedLists(pointToOriginalTriangle[a - numAdditionalPointsAtBeginning], pointToOriginalTriangle[b - numAdditionalPointsAtBeginning], intersection); pointToOriginalTriangle.pushBack(intersection); insert(allEdges[i], a, b, id); edgeToIndex.insert(key(a, id), i); edgeToIndex.insert(key(b, id), i); edgeToIndex.erase(e); lockedEdges.erase(e); lockedEdges.insert(key(a, id)); lockedEdges.insert(key(b, id)); ++missing; } } } if (missing == 0) break; } for (PxU32 i = 0; i < allEdges.size(); ++i) { PxArray<PxI32>& tempList = allEdges[i]; for (PxU32 j = 0; j < tempList.size(); ++j) tempList[j] -= numAdditionalPointsAtBeginning; } exportTetrahedra(finalTets); } PxI32 optimizeByFlipping(PxArray<PxI32>& faces, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tets, PxArray<PxI32>& unusedTets, const BaseTetAnalyzer& qualityAnalyzer, PxArray<PxI32>& affectedFaces, const PxHashSet<SortedTriangle, TriangleHash>& lockedFaces, const PxHashSet<PxU64>& lockedEdges) { PxI32 counter = 0; while (faces.size() > 0) { PxI32 faceId = faces.popBack(); if (faceId < 0) continue; PxArray<Tetrahedron> newTets; PxArray<PxI32> removedTets; if (!previewFlip(points, tets, neighbors, faceId, newTets, removedTets, lockedFaces, lockedEdges)) continue; if (!qualityAnalyzer.improved(qualityAnalyzer.quality(removedTets), qualityAnalyzer.quality(newTets))) continue; affectedFaces.clear(); flip(points, tets, neighbors, vertexToTet, faceId, unusedTets, affectedFaces, lockedFaces, lockedEdges); for (PxU32 j = 0; j < affectedFaces.size(); ++j) if (faces.find(affectedFaces[j]) == faces.end()) faces.pushBack(affectedFaces[j]); ++counter; } return counter; } bool DelaunayTetrahedralizer::optimizeByFlipping(PxArray<PxI32>& affectedFaces, const BaseTetAnalyzer& qualityAnalyzer) { PxArray<PxI32> stack; for (PxU32 i = 0; i < affectedFaces.size(); ++i) stack.pushBack(affectedFaces[i]); PxI32 counter = physx::Ext::optimizeByFlipping(stack, neighbors, vertexToTet, centeredNormalizedPoints, result, unusedTets, qualityAnalyzer, affectedFaces, lockedTriangles, lockedEdges); return counter > 0; } void insertPointIntoEdge(PxI32 newPointIndex, PxI32 edgeA, PxI32 edgeB, PxArray<Tetrahedron>& tets, PxArray<PxI32>& neighbors, PxArray<PxI32>& vertexToTet, PxArray<PxI32>& unusedTets, PxArray<PxI32>* affectedFaces, PxArray<PxI32>& affectedTets) { PxU32 l = affectedTets.size(); if (l == 0) return; PxArray<PxI32> removedTets; for (PxU32 i = 0; i < affectedTets.size(); ++i) removedTets.pushBack(affectedTets[i]); PxArray<PxI32> newTets; for (PxU32 i = 0; i < affectedTets.size(); ++i) newTets.pushBack(affectedTets[i]); for (PxU32 i = 0; i < l; ++i) { for (PxI32 j = 0; j < 4; ++j) { PxI32 id = 4 * affectedTets[i] + j; PxI32 neighborTet = neighbors[id] >> 2; if (neighborTet >= 0 && affectedTets.find(neighborTet) == affectedTets.end()) affectedTets.pushBack(neighborTet); } } PxU32 l2 = affectedTets.size(); for (PxU32 i = 0; i < l; ++i) { PxI32 id = affectedTets[i]; const Tetrahedron& tet = tets[id]; Edge oppositeEdge = getOtherEdge(tet, edgeA, edgeB); tets[id] = Tetrahedron(oppositeEdge.first, oppositeEdge.second, edgeA, newPointIndex); PxI32 j = storeNewTet(tets, neighbors, Tetrahedron(oppositeEdge.first, oppositeEdge.second, newPointIndex, edgeB), unusedTets); affectedTets.pushBack(j); newTets.pushBack(j); } fixNeighborhoodLocally(removedTets, affectedTets, tets, neighbors, affectedFaces); fixVertexToTet(vertexToTet, newTets, tets); affectedTets.removeRange(l, l2 - l); } void DelaunayTetrahedralizer::insertPointIntoEdge(PxI32 newPointIndex, PxI32 edgeA, PxI32 edgeB, PxArray<PxI32>& affectedTets, BaseTetAnalyzer* qualityAnalyzer) { PxArray<PxI32> affectedFaces; physx::Ext::insertPointIntoEdge(newPointIndex, edgeA, edgeB, result, neighbors, vertexToTet, unusedTets, &affectedFaces, affectedTets); if (qualityAnalyzer != NULL) optimizeByFlipping(affectedFaces, *qualityAnalyzer); } bool containsAll(const PxArray<PxI32>& list, const PxArray<PxI32>& itemsToBePresentInList) { for (PxU32 i = 0; i < itemsToBePresentInList.size(); ++i) if (list.find(itemsToBePresentInList[i]) == list.end()) return false; return true; } bool optimizeByCollapsing(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints, BaseTetAnalyzer* qualityAnalyzer) { PxI32 l = PxI32(pointToOriginalTriangle.size()); bool success = false; PxArray<PxI32> tetsA; PxArray<PxI32> tetsB; for (PxU32 i = 0; i < edges.size(); ++i) { const EdgeWithLength& e = edges[i]; tetsA.forceSize_Unsafe(0); del.collectTetsConnectedToVertex(e.A, tetsA); if (tetsA.empty()) continue; bool edgeExists = false; for (PxU32 j = 0; j < tetsA.size(); ++j) { const Tetrahedron& tet = del.tetrahedron(tetsA[j]); if (tet.contains(e.B)) { edgeExists = true; break; } } if (!edgeExists) continue; tetsB.forceSize_Unsafe(0); del.collectTetsConnectedToVertex(e.B, tetsB); if (tetsB.empty()) continue; PxF64 firstQuality = 0, secondQuality = 0; bool firstOptionValid = e.B >= numFixPoints && (e.B >= l || (e.A < l && containsAll(pointToOriginalTriangle[e.A], pointToOriginalTriangle[e.B]))) && del.canCollapseEdge(e.A, e.B, tetsA, tetsB, firstQuality, 0, qualityAnalyzer); bool secondOptionValid = e.A >= numFixPoints && (e.A >= l || (e.B < l && containsAll(pointToOriginalTriangle[e.B], pointToOriginalTriangle[e.A]))) && del.canCollapseEdge(e.B, e.A, tetsB, tetsA, secondQuality, 0, qualityAnalyzer); if (qualityAnalyzer != NULL && firstOptionValid && secondOptionValid) { if (qualityAnalyzer->improved(firstQuality, secondQuality)) firstOptionValid = false; else secondOptionValid = false; } if (firstOptionValid) { if (e.B >= numFixPoints) { del.collapseEdge(e.A, e.B, tetsA, tetsB); if (e.B < l) pointToOriginalTriangle[e.B].clear(); success = true; } } else if (secondOptionValid) { if (e.A >= numFixPoints) { del.collapseEdge(e.B, e.A, tetsB, tetsA); if (e.A < l) pointToOriginalTriangle[e.A].clear(); success = true; } } } return success; } bool optimizeBySwapping(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, const PxArray<PxArray<PxI32>>& pointToOriginalTriangle, BaseTetAnalyzer* qualityAnalyzer) { PxI32 l = PxI32(pointToOriginalTriangle.size()); bool success = false; PxArray<PxI32> tetIds; for (PxU32 i = 0; i < edges.size(); ++i) { const EdgeWithLength& e = edges[i]; const bool isInteriorEdge = e.A >= l || e.B >= l || !intersectionOfSortedListsContainsElements(pointToOriginalTriangle[e.A], pointToOriginalTriangle[e.B]); if (isInteriorEdge) { tetIds.forceSize_Unsafe(0); del.collectTetsConnectedToEdge(e.A, e.B, tetIds); if (tetIds.size() <= 2) continue; //This would mean we have a surface edge if (del.removeEdgeByFlip(e.A, e.B, tetIds, qualityAnalyzer)) success = true; } } return success; } void patternSearchOptimize(PxI32 pointToModify, PxF64 step, PxArray<PxVec3d>& points, BaseTetAnalyzer& score, const PxArray<PxI32>& tetrahedra, PxF64 minStep) { const PxVec3d dir[] = { PxVec3d(1.0, 0.0, 0.0), PxVec3d(-1.0, 0.0, 0.0), PxVec3d(0.0, 1.0, 0.0), PxVec3d(0.0, -1.0, 0.0), PxVec3d(0.0, 0.0, 1.0), PxVec3d(0.0, 0.0, -1.0), }; const PxI32 oppositeDir[] = { 1, 0, 3, 2, 5, 4 }; PxF64 currentScore = score.quality(tetrahedra); // score(); PxVec3d p = points[pointToModify]; PxI32 skip = -1; PxI32 maxIter = 100; PxI32 iter = 0; while (step > minStep && iter < maxIter) { PxF64 best = currentScore; PxI32 id = -1; for (PxI32 i = 0; i < 6; ++i) { if (i == skip) continue; //That point was the best before current iteration - it cannot be the best anymore points[pointToModify] = p + dir[i] * step; PxF64 s = score.quality(tetrahedra); // score(); if (score.improved(best, s)) { best = s; id = i; } } if (id >= 0) { p = p + dir[id] * step; points[pointToModify] = p; currentScore = best; skip = oppositeDir[id]; } else { points[pointToModify] = p; step = step * 0.5; skip = -1; } ++iter; } } bool optimizeBySplitting(DelaunayTetrahedralizer& del, const PxArray<EdgeWithLength>& edges, const PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 maxPointsToInsert, bool sortByQuality, BaseTetAnalyzer* qualityAnalyzer, PxF64 qualityThreshold) { const PxF64 qualityThresholdPow3 = qualityThreshold * qualityThreshold * qualityThreshold; PxArray<PxF64> tetQualityBuffer; tetQualityBuffer.resize(del.numTetrahedra()); for (PxU32 i = 0; i < del.numTetrahedra(); ++i) { const Tetrahedron& tet = del.tetrahedron(i); if (tet[0] >= 0) tetQualityBuffer[i] = evaluateAmipsEnergyPow3(del.point(tet[0]), del.point(tet[1]), del.point(tet[2]), del.point(tet[3])); } PxI32 l = PxI32(pointToOriginalTriangle.size()); PxArray<SplitEdge> edgesToSplit; PxArray<PxI32> tetIds; for (PxI32 i = edges.size() - 1; i >= 0; --i) { const EdgeWithLength& e = edges[i]; const bool isInteriorEdge = e.A >= l || e.B >= l || !intersectionOfSortedListsContainsElements(pointToOriginalTriangle[e.A], pointToOriginalTriangle[e.B]); if (isInteriorEdge) { tetIds.forceSize_Unsafe(0); del.collectTetsConnectedToEdge(e.A, e.B, tetIds); if (tetIds.size() <= 2) continue; //This would mean we got a surface edge... PxF64 max = 0; for (PxU32 j = 0; j < tetIds.size(); ++j) { if (tetQualityBuffer[tetIds[j]] > max) max = tetQualityBuffer[tetIds[j]]; } if (max > qualityThresholdPow3) edgesToSplit.pushBack(SplitEdge(e.A, e.B, max, (del.point(e.A) - del.point(e.B)).magnitudeSquared(), isInteriorEdge)); } } if (sortByQuality) { PxSort(edgesToSplit.begin(), edgesToSplit.size(), PxGreater<SplitEdge>()); } PxI32 counter = 0; PxArray<PxI32> tetsConnectedToEdge; PxArray<PxI32> tetsConnectedToVertex; for (PxU32 i = 0; i < edgesToSplit.size(); ++i) { const SplitEdge& e = edgesToSplit[i]; if (i > 0 && edgesToSplit[i - 1].Q == e.Q) continue; if (counter == maxPointsToInsert) break; PxU32 id = del.addPoint((del.point(e.A) + del.point(e.B)) * 0.5); tetsConnectedToEdge.forceSize_Unsafe(0); del.collectTetsConnectedToEdge(e.A, e.B, tetsConnectedToEdge); del.insertPointIntoEdge(id, e.A, e.B, tetsConnectedToEdge, qualityAnalyzer); if (e.InteriorEdge && qualityAnalyzer) { tetsConnectedToVertex.forceSize_Unsafe(0); del.collectTetsConnectedToVertex(id, tetsConnectedToVertex); patternSearchOptimize(id, e.L, del.points(), *qualityAnalyzer, tetsConnectedToVertex, 0.01 * e.L); } ++counter; } return edgesToSplit.size() > 0; } void updateEdges(PxArray<EdgeWithLength>& edges, PxHashSet<PxU64>& tetEdges, const PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points) { edges.clear(); tetEdges.clear(); for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; tetEdges.insert(key(tet[0], tet[1])); tetEdges.insert(key(tet[0], tet[2])); tetEdges.insert(key(tet[0], tet[3])); tetEdges.insert(key(tet[1], tet[2])); tetEdges.insert(key(tet[1], tet[3])); tetEdges.insert(key(tet[2], tet[3])); } for (PxHashSet<PxU64>::Iterator iter = tetEdges.getIterator(); !iter.done(); ++iter) { PxU64 e = *iter; PxI32 a = PxI32(e >> 32); PxI32 b = PxI32(e); edges.pushBack(EdgeWithLength(a, b, (points[a] - points[b]).magnitudeSquared())); } PxSort(edges.begin(), edges.size(), PxLess<EdgeWithLength>()); } void optimize(DelaunayTetrahedralizer& del, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32 numFixPoints, PxArray<PxVec3d>& optimizedPoints, PxArray<Tetrahedron>& optimizedTets, PxI32 numPasses) { PxHashSet<PxU64> tetEdges; PxArray<EdgeWithLength> edges; updateEdges(edges, tetEdges, del.tetrahedra(), del.points()); MinimizeMaxAmipsEnergy qualityAnalyzer(del.points(), del.tetrahedra()); //MaximizeMinTetVolume qualityAnalyzer(del.points(), del.tetrahedra()); optimizedTets = PxArray<Tetrahedron>(del.tetrahedra()); optimizedPoints = PxArray<PxVec3d>(del.points()); PxF64 minVolBefore = minAbsTetVolume(del.points(), del.tetrahedra()); PxF64 maxEnergyBefore = maxEnergy(del.points(), del.tetrahedra()); PxI32 numPointsToInsertPerPass = PxMax(20, PxI32(0.05 * del.numPoints())); for (PxI32 j = 0; j < numPasses; ++j) { //(1) Splitting updateEdges(edges, tetEdges, del.tetrahedra(), del.points()); optimizeBySplitting(del, edges, pointToOriginalTriangle, numPointsToInsertPerPass, true, &qualityAnalyzer); //(3) Swapping updateEdges(edges, tetEdges, del.tetrahedra(), del.points()); optimizeBySwapping(del, edges, pointToOriginalTriangle, &qualityAnalyzer); //(2) Collapsing updateEdges(edges, tetEdges, del.tetrahedra(), del.points()); optimizeByCollapsing(del, edges, pointToOriginalTriangle, numFixPoints, &qualityAnalyzer); //(4) Smoothing //Note done here - seems not to improve the quality that much PxF64 energy = maxEnergy(del.points(), del.tetrahedra()); PxF64 minVol = minAbsTetVolume(del.points(), del.tetrahedra()); if (energy / minVol >= maxEnergyBefore / minVolBefore/*minVol <= minVolBefore*/) { del.initialize(optimizedPoints, optimizedTets); bool swapped = true, collapsed = true; PxI32 maxReductionLoops = 30; PxI32 counter = 0; while (swapped || collapsed) { //(3) Swapping updateEdges(edges, tetEdges, del.tetrahedra(), del.points()); swapped = optimizeBySwapping(del, edges, pointToOriginalTriangle, &qualityAnalyzer); //(2) Collapsing updateEdges(edges, tetEdges, del.tetrahedra(), del.points()); collapsed = optimizeByCollapsing(del, edges, pointToOriginalTriangle, numFixPoints, &qualityAnalyzer); if (counter >= maxReductionLoops) break; ++counter; } optimizedTets = PxArray<Tetrahedron>(del.tetrahedra()); optimizedPoints = PxArray<PxVec3d>(del.points()); return; } optimizedTets = PxArray<Tetrahedron>(del.tetrahedra()); optimizedPoints = PxArray<PxVec3d>(del.points()); minVolBefore = minVol; maxEnergyBefore = energy; } } } }
76,979
C++
34.295736
231
0.674327
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtTetSplitting.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtTetSplitting.h" #include "ExtUtilities.h" #include "foundation/PxBasicTemplates.h" namespace physx { namespace Ext { //Last four bits are used //Last bit set stands for A //Second last bit stands for B //Third last bit stands for C //Fourth last bit stands for D typedef PxU32 TetCorner; typedef PxU32 TetEdge; static const TetCorner None = 0x00000000; static const TetCorner A = 0x00000001; static const TetCorner B = 0x00000002; static const TetCorner C = 0x00000004; static const TetCorner D = 0x00000008; static const TetEdge AB = 0x00000003; static const TetEdge AC = 0x00000005; static const TetEdge AD = 0x00000009; static const TetEdge BC = 0x00000006; static const TetEdge BD = 0x0000000A; static const TetEdge CD = 0x0000000C; static const TetCorner tetCorners[4] = { A, B, C, D }; //Specifies which edges of a tetrahedron should get a point inserted (=split) struct TetSubdivisionInfo { //If an index has value -1 then this means that this edge won't get split PxI32 ab; PxI32 ac; PxI32 ad; PxI32 bc; PxI32 bd; PxI32 cd; Tetrahedron tet; PxI32 id; PX_FORCE_INLINE TetSubdivisionInfo() : ab(-1), ac(-1), ad(-1), bc(-1), bd(-1), cd(-1), tet(Tetrahedron(-1, -1, -1, -1)), id(-1) {} PX_FORCE_INLINE TetSubdivisionInfo(Tetrahedron tet_, PxI32 aBPointInsertIndex, PxI32 aCPointInsertIndex, PxI32 aDPointInsertIndex, PxI32 bCPointInsertIndex, PxI32 bDPointInsertIndex, PxI32 cDPointInsertIndex, PxI32 id_ = -1) : ab(aBPointInsertIndex), ac(aCPointInsertIndex), ad(aDPointInsertIndex), bc(bCPointInsertIndex), bd(bDPointInsertIndex), cd(cDPointInsertIndex), tet(tet_), id(id_) { } PX_FORCE_INLINE void swapInternal(TetCorner corner1, TetCorner corner2, TetCorner& cornerToProcess) { if (cornerToProcess == corner1) cornerToProcess = corner2; else if (cornerToProcess == corner2) cornerToProcess = corner1; } //Helper method for sorting template<typename T> void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } //Helper method for sorting bool swap(TetCorner corner1, TetCorner corner2, TetCorner& additionalCornerToProcess1, TetCorner& additionalCornerToProcess2) { swapInternal(corner1, corner2, additionalCornerToProcess1); swapInternal(corner1, corner2, additionalCornerToProcess2); return swap(corner1, corner2); } //Helper method for sorting bool swap(TetCorner corner1, TetCorner corner2, TetCorner& additionalCornerToProcess) { swapInternal(corner1, corner2, additionalCornerToProcess); return swap(corner1, corner2); } //Helper method for sorting bool swap(TetCorner corner1, TetCorner corner2) { if (corner1 == corner2) return false; if (corner1 > corner2) { TetCorner tmp = corner1; corner1 = corner2; corner2 = tmp; } if (corner1 == A && corner2 == B) { PxSwap(ad, bd); PxSwap(ac, bc); PxSwap(tet[0], tet[1]); } else if (corner1 == A && corner2 == C) { PxSwap(ad, cd); PxSwap(ab, bc); PxSwap(tet[0], tet[2]); } else if (corner1 == A && corner2 == D) { PxSwap(ac, cd); PxSwap(ab, bd); PxSwap(tet[0], tet[3]); } else if (corner1 == B && corner2 == C) { PxSwap(ac, ab); PxSwap(cd, bd); PxSwap(tet[1], tet[2]); } else if (corner1 == B && corner2 == D) { PxSwap(ab, ad); PxSwap(bc, cd); PxSwap(tet[1], tet[3]); } else if (corner1 == C && corner2 == D) { PxSwap(ac, ad); PxSwap(bc, bd); PxSwap(tet[2], tet[3]); } return true; } //Allows to sort the information such that edges of neighboring tets have the same orientation PxI32 sort() { PxI32 counter = 0; if (tet[0] > tet[1]) { swap(A, B); ++counter; } if (tet[0] > tet[2]) { swap(A, C); ++counter; } if (tet[0] > tet[3]) { swap(A, D); ++counter; } if (tet[1] > tet[2]) { swap(B, C); ++counter; } if (tet[1] > tet[3]) { swap(B, D); ++counter; } if (tet[2] > tet[3]) { swap(C, D); ++counter; } return counter; } }; //Returns true if the edge is adjacent to the specified corner PX_FORCE_INLINE bool edgeContainsCorner(TetEdge edge, TetCorner corner) { return (edge & corner) != 0; } //Returns the common point of two edges, will be None if there is no common point PX_FORCE_INLINE TetCorner getCommonPoint(TetEdge edge1, TetEdge edge2) { return edge1 & edge2; } //Extracts the global indices from a tet given a local edge Edge getTetEdge(const Tetrahedron& tet, TetEdge edge) { switch (edge) { case AB: return Edge(tet[0], tet[1]); case AC: return Edge(tet[0], tet[2]); case AD: return Edge(tet[0], tet[3]); case BC: return Edge(tet[1], tet[2]); case BD: return Edge(tet[1], tet[3]); case CD: return Edge(tet[2], tet[3]); } return Edge(-1, -1); } TetCorner getStart(TetEdge e) { switch (e) { case AB: return A; case AC: return A; case AD: return A; case BC: return B; case BD: return B; case CD: return C; } return None; } TetCorner getEnd(TetEdge e) { switch (e) { case AB: return B; case AC: return C; case AD: return D; case BC: return C; case BD: return D; case CD: return D; } return None; } PX_FORCE_INLINE TetEdge getOppositeEdge(TetEdge edge) { return 0x0000000F ^ edge; } //Finds the index of the first instance of value in list PxI32 getIndexOfFirstValue(PxI32 list[4], PxI32 value = 0, PxI32 startAt = 0) { for (PxI32 i = startAt; i < 4; ++i) if (list[i] == value) return i; PX_ASSERT(false); // we should never reach this line return 0; } //Counts how many times every corner is referenced by the specified set of edges - useful for corner classification void getCornerAccessCounter(TetEdge edges[6], PxI32 edgesLength, PxI32 cornerAccessCounter[4]) { for (PxI32 i = 0; i < 4; ++i) cornerAccessCounter[i] = 0; for (PxI32 j = 0; j < edgesLength; ++j) { switch (edges[j]) { case AB: ++cornerAccessCounter[0]; ++cornerAccessCounter[1]; break; case AC: ++cornerAccessCounter[0]; ++cornerAccessCounter[2]; break; case AD: ++cornerAccessCounter[0]; ++cornerAccessCounter[3]; break; case BC: ++cornerAccessCounter[1]; ++cornerAccessCounter[2]; break; case BD: ++cornerAccessCounter[1]; ++cornerAccessCounter[3]; break; case CD: ++cornerAccessCounter[2]; ++cornerAccessCounter[3]; break; } } } //Returns the tet's edge that does not contain corner1 and neither corner2 Edge getRemainingEdge(const Tetrahedron& tet, PxI32 corner1, PxI32 corner2) { PxI32 indexer = 0; Edge result(-1, -1); for (PxU32 i = 0; i < 4; ++i) { if (tet[i] != corner1 && tet[i] != corner2) { if (indexer == 0) result.first = tet[i]; else if (indexer == 1) result.second = tet[i]; ++indexer; } } return result; } PX_FORCE_INLINE TetCorner getOtherCorner(TetEdge edge, TetCorner corner) { return edge ^ corner; } PX_FORCE_INLINE Tetrahedron flip(bool doFlip, Tetrahedron t) { if (doFlip) PxSwap(t[2], t[3]); return t; } //Splits all tets according to the specification in tetSubdivisionInfos. The resulting mesh will be watertight if the tetSubdivisionInfos are specified such //that all tets sharing and edge will get the same point inserted on their corresponding edge void split(PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points, const PxArray<TetSubdivisionInfo>& tetSubdivisionInfos) { PxU32 originalNumTets = tets.size(); for (PxU32 i = 0; i < originalNumTets; ++i) { TetSubdivisionInfo info = tetSubdivisionInfos[i]; PxI32 counter = info.sort(); TetEdge splitEdges[6]; PxI32 splitEdgesLength = 0; TetEdge nonSplitEdges[6]; PxI32 nonSplitEdgesLength = 0; PxI32 insertionIndices[6]; PxI32 insertionIndicesLength = 0; if (info.ab >= 0) { splitEdges[splitEdgesLength++] = AB; insertionIndices[insertionIndicesLength++] = info.ab; } else nonSplitEdges[nonSplitEdgesLength++] = AB; if (info.ac >= 0) { splitEdges[splitEdgesLength++] = AC; insertionIndices[insertionIndicesLength++] = info.ac; } else nonSplitEdges[nonSplitEdgesLength++] = AC; if (info.ad >= 0) { splitEdges[splitEdgesLength++] = AD; insertionIndices[insertionIndicesLength++] = info.ad; } else nonSplitEdges[nonSplitEdgesLength++] = AD; if (info.bc >= 0) { splitEdges[splitEdgesLength++] = BC; insertionIndices[insertionIndicesLength++] = info.bc; } else nonSplitEdges[nonSplitEdgesLength++] = BC; if (info.bd >= 0) { splitEdges[splitEdgesLength++] = BD; insertionIndices[insertionIndicesLength++] = info.bd; } else nonSplitEdges[nonSplitEdgesLength++] = BD; if (info.cd >= 0) { splitEdges[splitEdgesLength++] = CD; insertionIndices[insertionIndicesLength++] = info.cd; } else nonSplitEdges[nonSplitEdgesLength++] = CD; //Depending on how many tet edges get a point inserted, a different topology results. //The created topology will make sure all neighboring tet faces will be tessellated identically to keep the mesh watertight switch (splitEdgesLength) { case 0: //Nothing to do here break; case 1: { PxI32 pointIndex = insertionIndices[0]; Edge splitEdge = getTetEdge(info.tet, splitEdges[0]); Edge oppositeEdge = getTetEdge(info.tet, getOppositeEdge(splitEdges[0])); tets[i] = Tetrahedron(oppositeEdge.first, oppositeEdge.second, splitEdge.first, pointIndex); tets.pushBack(Tetrahedron(oppositeEdge.first, oppositeEdge.second, pointIndex, splitEdge.second)); break; } case 2: { TetCorner corner = getCommonPoint(splitEdges[0], splitEdges[1]); if (corner != None) { //edges have a common point //Rearrange such that common corner is a and first edge is from a to b while second edge is from a to c TetCorner p1 = getOtherCorner(splitEdges[0], corner); TetCorner p2 = getOtherCorner(splitEdges[1], corner); if (info.swap(corner, A, p1, p2)) ++counter; if (info.swap(p1, B, p2)) ++counter; if (info.swap(p2, C)) ++counter; if (info.tet[1] > info.tet[2]) { if (info.swap(B, C)) ++counter; } const bool f = counter % 2 == 1; tets[i] = flip(f, Tetrahedron(info.tet[0], info.tet[3], info.ab, info.ac)); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.tet[1], info.ab, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.tet[2], info.tet[1], info.ac))); } else { //Edges don't have a common point (opposite edges) TetEdge edge1 = splitEdges[0]; //TetEdge edge2 = splitEdges[1]; //Permute the tetrahedron such that edge1 becomes the edge AB if (info.swap(getStart(edge1), A)) ++counter; if (info.swap(getEnd(edge1), B)) ++counter; if (info.tet[0] > info.tet[1]) { if (info.swap(A, B)) ++counter; } if (info.tet[2] > info.tet[3]) { if (info.swap(C, D)) ++counter; } const bool f = counter % 2 == 1; tets[i] = flip(f, Tetrahedron(info.tet[0], info.ab, info.tet[2], info.cd)); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.ab, info.cd, info.tet[2]))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ab, info.cd, info.tet[3]))); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.ab, info.tet[3], info.cd))); } break; } case 3: { //There are three sub cases called a, b and c TetCorner commonPoint01 = getCommonPoint(splitEdges[0], splitEdges[1]); TetCorner commonPoint02 = getCommonPoint(splitEdges[0], splitEdges[2]); TetCorner commonPoint12 = getCommonPoint(splitEdges[1], splitEdges[2]); if (commonPoint01 == None || commonPoint02 == None || commonPoint12 == None) { //The three edges form a non closed strip //The strip's end points are connected by a tet edge - map this edge such that it becomes edge AB //Then sort AB PxI32 cnt[4]; getCornerAccessCounter(splitEdges, splitEdgesLength, cnt); PxI32 index = getIndexOfFirstValue(cnt, 1); TetCorner refStart = tetCorners[index]; TetCorner refEnd = tetCorners[getIndexOfFirstValue(cnt, 1, index + 1)]; TetCorner cornerToMapOntoC = None; if (edgeContainsCorner(splitEdges[0], refEnd)) { cornerToMapOntoC = getOtherCorner(splitEdges[0], refEnd); } else if (edgeContainsCorner(splitEdges[1], refEnd)) { cornerToMapOntoC = getOtherCorner(splitEdges[1], refEnd); } else if (edgeContainsCorner(splitEdges[2], refEnd)) { cornerToMapOntoC = getOtherCorner(splitEdges[2], refEnd); } if (info.swap(refStart, A, refEnd, cornerToMapOntoC)) ++counter; if (info.swap(refEnd, B, cornerToMapOntoC)) ++counter; if (info.swap(cornerToMapOntoC, C)) ++counter; if (info.tet[0] > info.tet[1]) { if (info.swap(A, B)) ++counter; if (info.swap(C, D)) ++counter; } const bool f = counter % 2 == 1; tets[i] = flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bc, info.ad)); if (info.tet[0] > info.tet[2]) { tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.cd, info.ad, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.ad, info.bc))); } else { tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.cd, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bc, info.cd))); } if (info.tet[1] > info.tet[3]) { tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.bc, info.ad, info.cd))); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.tet[1], info.ad, info.bc))); } else { tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.tet[3], info.cd, info.ad))); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.bc, info.ad, info.cd))); } } else if (edgeContainsCorner(splitEdges[2], commonPoint01)) { //All three edges share one common point //Permute tetrahedron such that the common tip point is a if (info.swap(commonPoint01, A)) ++counter; //Sort the remaining values if (info.tet[1] > info.tet[2]) { if (info.swap(B, C)) ++counter; } if (info.tet[2] > info.tet[3]) { if (info.swap(C, D)) ++counter; } if (info.tet[1] > info.tet[2]) { if (info.swap(B, C)) ++counter; } const bool f = counter % 2 == 1; tets[i] = flip(f, Tetrahedron(info.tet[0], info.ab, info.ac, info.ad)); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.ab, info.ad, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.tet[1], info.ad, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.tet[2], info.ad, info.tet[3]))); } else { //Edges form a triangle //Rearrange such that point opposite of triangle loop is point d //Triangle loop is a, b and c, make sure they're sorted if (!(commonPoint01 == A || commonPoint02 == A || commonPoint12 == A)) { if (info.swap(A, D)) ++counter; } else if (!(commonPoint01 == B || commonPoint02 == B || commonPoint12 == B)) { if (info.swap(B, D)) ++counter; } else if (!(commonPoint01 == C || commonPoint02 == C || commonPoint12 == C)) { if (info.swap(C, D)) ++counter; } else if (!(commonPoint01 == D || commonPoint02 == D || commonPoint12 == D)) { if (info.swap(D, D)) ++counter; } //Sort a,b and c if (info.tet[0] > info.tet[1]) if (info.swap(A, B)) ++counter; if (info.tet[1] > info.tet[2]) if (info.swap(B, C)) ++counter; if (info.tet[0] > info.tet[1]) if (info.swap(A, B)) ++counter; const bool f = counter % 2 == 1; tets[i] = flip(f, Tetrahedron(info.tet[3], info.ab, info.ac, info.bc)); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ab, info.ac, info.tet[0]))); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ab, info.bc, info.tet[1]))); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ac, info.bc, info.tet[2]))); } break; } case 4: { TetCorner commonPoint = getCommonPoint(nonSplitEdges[0], nonSplitEdges[1]); if (commonPoint != None) { //Three edges form a triangle and the two edges that are not split share a common point TetCorner p1 = getOtherCorner(nonSplitEdges[0], commonPoint); TetCorner p2 = getOtherCorner(nonSplitEdges[1], commonPoint); if (info.swap(commonPoint, A, p1, p2)) ++counter; if (info.swap(p1, B, p2)) ++counter; if (info.swap(p2, C)) ++counter; if (info.tet[1] > info.tet[2]) if (info.swap(B, C)) ++counter; const bool f = counter % 2 == 0; //Tip tets[i] = flip(f, Tetrahedron(info.tet[3], info.ad, info.bd, info.cd)); //Center tets.pushBack(flip(f, Tetrahedron(info.bd, info.ad, info.bc, info.cd))); if (info.tet[0] < info.tet[1] && info.tet[0] < info.tet[2]) { tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bd, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.bc, info.cd))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bc, info.bd, info.ad))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bc, info.ad, info.cd))); } else if (info.tet[0] > info.tet[1] && info.tet[0] < info.tet[2]) { tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[2], info.bc, info.cd))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bc, info.ad, info.cd))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.ad, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.bc, info.bd, info.ad))); } else { tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.ad, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[1], info.bc, info.bd, info.ad))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.tet[0], info.ad, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.bc, info.ad, info.cd))); } } else { //All four edges form a loop TetEdge edge1 = nonSplitEdges[0]; //Permute the tetrahedron such that edge1 becomes the edge AB TetCorner end = getEnd(edge1); if (info.swap(getStart(edge1), A, end)) ++counter; if (info.swap(end, B)) ++counter; //Sort if (info.tet[0] > info.tet[1]) if (info.swap(A, B)) ++counter; if (info.tet[2] > info.tet[3]) if (info.swap(C, D)) ++counter; const bool f = counter % 2 == 1; tets[i] = flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bc, info.bd)); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.tet[3], info.ad, info.bd))); PxF64 dist1 = (points[info.ad] - points[info.bc]).magnitudeSquared(); PxF64 dist2 = (points[info.ac] - points[info.bd]).magnitudeSquared(); if (dist1 < dist2) { //Diagonal from AD to BC tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bc, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bd, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.ad, info.ac, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.ad, info.bc, info.bd))); } else { //Diagonal from AC to BD tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bd, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ac, info.bd, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.bc, info.bd, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[2], info.bd, info.ad, info.ac))); } } break; } case 5: { //There is only one edge that does not get split //First create 2 small tetrahedra in every corner that is not an end point of the unsplit edge TetEdge nonSplitEdge; if (info.ab < 0) nonSplitEdge = AB; else if (info.ac < 0) nonSplitEdge = AC; else if (info.ad < 0) nonSplitEdge = AD; else if (info.bc < 0) nonSplitEdge = BC; else if (info.bd < 0) nonSplitEdge = BD; else //if (info.CDPointInsertIndex < 0) nonSplitEdge = CD; TetCorner end = getEnd(nonSplitEdge); if (info.swap(getStart(nonSplitEdge), A, end)) ++counter; if (info.swap(end, B)) ++counter; if (info.tet[0] > info.tet[1]) if (info.swap(A, B)) ++counter; if (info.tet[2] > info.tet[3]) if (info.swap(C, D)) ++counter; const bool f = counter % 2 == 1; //Two corner tets at corner C and corner D tets[i] = flip(f, Tetrahedron(info.tet[2], info.ac, info.bc, info.cd)); tets.pushBack(flip(f, Tetrahedron(info.tet[3], info.ad, info.cd, info.bd))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.tet[1], info.bc, info.bd))); //There are two possible diagonals -> take the shorter PxF64 dist1 = (points[info.ac] - points[info.bd]).magnitudeSquared(); PxF64 dist2 = (points[info.ad] - points[info.bc]).magnitudeSquared(); if (dist1 < dist2) { //Diagonal from AC to BD tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ad, info.bd, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ac, info.bd, info.bc))); //Tip pyramid tets.pushBack(flip(f, Tetrahedron(info.cd, info.bc, info.bd, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.cd, info.bd, info.ad, info.ac))); } else { //Diagonal from AD to BC tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.ac, info.ad, info.bc))); tets.pushBack(flip(f, Tetrahedron(info.tet[0], info.bd, info.bc, info.ad))); //Tip pyramid tets.pushBack(flip(f, Tetrahedron(info.cd, info.bc, info.ad, info.ac))); tets.pushBack(flip(f, Tetrahedron(info.cd, info.bd, info.ad, info.bc))); } break; } case 6: { //First create a small tetrahedron in every corner const bool f = counter % 2 == 1; if (f) info.swap(A, B); tets[i] = Tetrahedron(info.tet[0], info.ab, info.ac, info.ad); tets.pushBack(Tetrahedron(info.tet[1], info.ab, info.bd, info.bc)); tets.pushBack(Tetrahedron(info.tet[2], info.ac, info.bc, info.cd)); tets.pushBack(Tetrahedron(info.tet[3], info.ad, info.cd, info.bd)); //Now fill the remaining octahedron in the middle //An octahedron can be constructed using 4 tetrahedra //There are three diagonal candidates -> pick the shortest diagonal PxF64 dist1 = (points[info.ab] - points[info.cd]).magnitudeSquared(); PxF64 dist2 = (points[info.ac] - points[info.bd]).magnitudeSquared(); PxF64 dist3 = (points[info.ad] - points[info.bc]).magnitudeSquared(); if (dist1 <= dist2 && dist1 <= dist3) { tets.pushBack(Tetrahedron(info.ab, info.cd, info.ad, info.bd)); tets.pushBack(Tetrahedron(info.ab, info.cd, info.bd, info.bc)); tets.pushBack(Tetrahedron(info.ab, info.cd, info.bc, info.ac)); tets.pushBack(Tetrahedron(info.ab, info.cd, info.ac, info.ad)); } else if (dist2 <= dist1 && dist2 <= dist3) { tets.pushBack(Tetrahedron(info.ac, info.bd, info.cd, info.ad)); tets.pushBack(Tetrahedron(info.ac, info.bd, info.ad, info.ab)); tets.pushBack(Tetrahedron(info.ac, info.bd, info.ab, info.bc)); tets.pushBack(Tetrahedron(info.ac, info.bd, info.bc, info.cd)); } else { tets.pushBack(Tetrahedron(info.ad, info.bc, info.bd, info.ab)); tets.pushBack(Tetrahedron(info.ad, info.bc, info.cd, info.bd)); tets.pushBack(Tetrahedron(info.ad, info.bc, info.ac, info.cd)); tets.pushBack(Tetrahedron(info.ad, info.bc, info.ab, info.ac)); } break; } } } } void split(PxArray<Tetrahedron>& tets, const PxArray<PxVec3d>& points, const PxHashMap<PxU64, PxI32>& edgesToSplit) { PxArray<TetSubdivisionInfo> subdivisionInfos; subdivisionInfos.resize(tets.size()); for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; TetSubdivisionInfo info(tet, -1, -1, -1, -1, -1, -1, i); if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[0], tet[1]))) info.ab = ptr->second; if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[0], tet[2]))) info.ac = ptr->second; if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[0], tet[3]))) info.ad = ptr->second; if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[1], tet[2]))) info.bc = ptr->second; if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[1], tet[3]))) info.bd = ptr->second; if (const PxPair<const PxU64, PxI32>* ptr = edgesToSplit.find(key(tet[2], tet[3]))) info.cd = ptr->second; subdivisionInfos[i] = info; } split(tets, points, subdivisionInfos); } } }
26,502
C++
31.922981
165
0.639046
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMarchingCubesTable.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_MARCHING_CUBES_TABLE_H #define EXT_MARCHING_CUBES_TABLE_H namespace physx { namespace Ext { // point numbering // 7-----------6 // /| /| // / | / | // / | / | // 4-----------5 | // | | | | // | 3-------|---2 // | / | / // | / | / // |/ |/ // 0-----------1 // edge numbering // *-----6-----* // /| /| // 7 | 5 | // / 11 / 10 // *-----4-----* | // | | | | // | *-----2-|---* // 8 / 9 / // | 3 | 1 // |/ |/ // *-----0-----* // z // | y // | / // |/ // 0---- x int marchingCubeCorners[8][3] = { {0,0,0}, {1,0,0},{1,1,0},{0,1,0}, {0,0,1}, {1,0,1},{1,1,1},{0,1,1} }; int marchingCubeEdges[12][2] = { {0,1},{1,2},{2,3},{3,0},{4,5},{5,6},{6,7},{7,4},{0,4},{1,5},{2,6},{3,7} }; int firstMarchingCubesId[257] = { 0, 0, 3, 6, 12, 15, 21, 27, 36, 39, 45, 51, 60, 66, 75, 84, 90, 93, 99, 105, 114, 120, 129, 138, 150, 156, 165, 174, 186, 195, 207, 219, 228, 231, 237, 243, 252, 258, 267, 276, 288, 294, 303, 312, 324, 333, 345, 357, 366, 372, 381, 390, 396, 405, 417, 429, 438, 447, 459, 471, 480, 492, 507, 522, 528, 531, 537, 543, 552, 558, 567, 576, 588, 594, 603, 612, 624, 633, 645, 657, 666, 672, 681, 690, 702, 711, 723, 735, 750, 759, 771, 783, 798, 810, 825, 840, 852, 858, 867, 876, 888, 897, 909, 915, 924, 933, 945, 957, 972, 984, 999, 1008, 1014, 1023, 1035, 1047, 1056, 1068, 1083, 1092, 1098, 1110, 1125, 1140, 1152, 1167, 1173, 1185, 1188, 1191, 1197, 1203, 1212, 1218, 1227, 1236, 1248, 1254, 1263, 1272, 1284, 1293, 1305, 1317, 1326, 1332, 1341, 1350, 1362, 1371, 1383, 1395, 1410, 1419, 1425, 1437, 1446, 1458, 1467, 1482, 1488, 1494, 1503, 1512, 1524, 1533, 1545, 1557, 1572, 1581, 1593, 1605, 1620, 1632, 1647, 1662, 1674, 1683, 1695, 1707, 1716, 1728, 1743, 1758, 1770, 1782, 1791, 1806, 1812, 1827, 1839, 1845, 1848, 1854, 1863, 1872, 1884, 1893, 1905, 1917, 1932, 1941, 1953, 1965, 1980, 1986, 1995, 2004, 2010, 2019, 2031, 2043, 2058, 2070, 2085, 2100, 2106, 2118, 2127, 2142, 2154, 2163, 2169, 2181, 2184, 2193, 2205, 2217, 2232, 2244, 2259, 2268, 2280, 2292, 2307, 2322, 2328, 2337, 2349, 2355, 2358, 2364, 2373, 2382, 2388, 2397, 2409, 2415, 2418, 2427, 2433, 2445, 2448, 2454, 2457, 2460, 2460 }; int marchingCubesIds[2460] = { 0, 8, 3, 0, 1, 9, 1, 8, 3, 9, 8, 1, 1, 2, 10, 0, 8, 3, 1, 2, 10, 9, 2, 10, 0, 2, 9, 2, 8, 3, 2, 10, 8, 10, 9, 8, 3, 11, 2, 0, 11, 2, 8, 11, 0, 1, 9, 0, 2, 3, 11, 1, 11, 2, 1, 9, 11, 9, 8, 11, 3, 10, 1, 11, 10, 3, 0, 10, 1, 0, 8, 10, 8, 11, 10, 3, 9, 0, 3, 11, 9, 11, 10, 9, 9, 8, 10, 10, 8, 11, 4, 7, 8, 4, 3, 0, 7, 3, 4, 0, 1, 9, 8, 4, 7, 4, 1, 9, 4, 7, 1, 7, 3, 1, 1, 2, 10, 8, 4, 7, 3, 4, 7, 3, 0, 4, 1, 2, 10, 9, 2, 10, 9, 0, 2, 8, 4, 7, 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, 8, 4, 7, 3, 11, 2, 11, 4, 7, 11, 2, 4, 2, 0, 4, 9, 0, 1, 8, 4, 7, 2, 3, 11, 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, 3, 10, 1, 3, 11, 10, 7, 8, 4, 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, 4, 7, 11, 4, 11, 9, 9, 11, 10, 9, 5, 4, 9, 5, 4, 0, 8, 3, 0, 5, 4, 1, 5, 0, 8, 5, 4, 8, 3, 5, 3, 1, 5, 1, 2, 10, 9, 5, 4, 3, 0, 8, 1, 2, 10, 4, 9, 5, 5, 2, 10, 5, 4, 2, 4, 0, 2, 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, 9, 5, 4, 2, 3, 11, 0, 11, 2, 0, 8, 11, 4, 9, 5, 0, 5, 4, 0, 1, 5, 2, 3, 11, 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, 10, 3, 11, 10, 1, 3, 9, 5, 4, 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, 5, 4, 8, 5, 8, 10, 10, 8, 11, 9, 7, 8, 5, 7, 9, 9, 3, 0, 9, 5, 3, 5, 7, 3, 0, 7, 8, 0, 1, 7, 1, 5, 7, 1, 5, 3, 3, 5, 7, 9, 7, 8, 9, 5, 7, 10, 1, 2, 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, 2, 10, 5, 2, 5, 3, 3, 5, 7, 7, 9, 5, 7, 8, 9, 3, 11, 2, 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, 11, 2, 1, 11, 1, 7, 7, 1, 5, 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, 11, 10, 5, 7, 11, 5, 10, 6, 5, 0, 8, 3, 5, 10, 6, 9, 0, 1, 5, 10, 6, 1, 8, 3, 1, 9, 8, 5, 10, 6, 1, 6, 5, 2, 6, 1, 1, 6, 5, 1, 2, 6, 3, 0, 8, 9, 6, 5, 9, 0, 6, 0, 2, 6, 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, 2, 3, 11, 10, 6, 5, 11, 0, 8, 11, 2, 0, 10, 6, 5, 0, 1, 9, 2, 3, 11, 5, 10, 6, 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, 6, 3, 11, 6, 5, 3, 5, 1, 3, 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, 6, 5, 9, 6, 9, 11, 11, 9, 8, 5, 10, 6, 4, 7, 8, 4, 3, 0, 4, 7, 3, 6, 5, 10, 1, 9, 0, 5, 10, 6, 8, 4, 7, 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, 6, 1, 2, 6, 5, 1, 4, 7, 8, 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, 3, 11, 2, 7, 8, 4, 10, 6, 5, 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, 10, 4, 9, 6, 4, 10, 4, 10, 6, 4, 9, 10, 0, 8, 3, 10, 0, 1, 10, 6, 0, 6, 4, 0, 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, 1, 4, 9, 1, 2, 4, 2, 6, 4, 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, 0, 2, 4, 4, 2, 6, 8, 3, 2, 8, 2, 4, 4, 2, 6, 10, 4, 9, 10, 6, 4, 11, 2, 3, 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, 3, 11, 6, 3, 6, 0, 0, 6, 4, 6, 4, 8, 11, 6, 8, 7, 10, 6, 7, 8, 10, 8, 9, 10, 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, 10, 6, 7, 10, 7, 1, 1, 7, 3, 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, 7, 8, 0, 7, 0, 6, 6, 0, 2, 7, 3, 2, 6, 7, 2, 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, 0, 9, 1, 11, 6, 7, 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, 7, 11, 6, 7, 6, 11, 3, 0, 8, 11, 7, 6, 0, 1, 9, 11, 7, 6, 8, 1, 9, 8, 3, 1, 11, 7, 6, 10, 1, 2, 6, 11, 7, 1, 2, 10, 3, 0, 8, 6, 11, 7, 2, 9, 0, 2, 10, 9, 6, 11, 7, 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, 7, 2, 3, 6, 2, 7, 7, 0, 8, 7, 6, 0, 6, 2, 0, 2, 7, 6, 2, 3, 7, 0, 1, 9, 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, 10, 7, 6, 10, 1, 7, 1, 3, 7, 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, 7, 6, 10, 7, 10, 8, 8, 10, 9, 6, 8, 4, 11, 8, 6, 3, 6, 11, 3, 0, 6, 0, 4, 6, 8, 6, 11, 8, 4, 6, 9, 0, 1, 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, 6, 8, 4, 6, 11, 8, 2, 10, 1, 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, 8, 2, 3, 8, 4, 2, 4, 6, 2, 0, 4, 2, 4, 6, 2, 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, 1, 9, 4, 1, 4, 2, 2, 4, 6, 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, 10, 1, 0, 10, 0, 6, 6, 0, 4, 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, 10, 9, 4, 6, 10, 4, 4, 9, 5, 7, 6, 11, 0, 8, 3, 4, 9, 5, 11, 7, 6, 5, 0, 1, 5, 4, 0, 7, 6, 11, 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, 9, 5, 4, 10, 1, 2, 7, 6, 11, 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, 7, 2, 3, 7, 6, 2, 5, 4, 9, 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, 6, 9, 5, 6, 11, 9, 11, 8, 9, 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, 6, 11, 3, 6, 3, 5, 5, 3, 1, 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, 9, 5, 6, 9, 6, 0, 0, 6, 2, 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, 1, 5, 6, 2, 1, 6, 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, 0, 3, 8, 5, 6, 10, 10, 5, 6, 11, 5, 10, 7, 5, 11, 11, 5, 10, 11, 7, 5, 8, 3, 0, 5, 11, 7, 5, 10, 11, 1, 9, 0, 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, 11, 1, 2, 11, 7, 1, 7, 5, 1, 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, 2, 5, 10, 2, 3, 5, 3, 7, 5, 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, 1, 3, 5, 3, 7, 5, 0, 8, 7, 0, 7, 1, 1, 7, 5, 9, 0, 3, 9, 3, 5, 5, 3, 7, 9, 8, 7, 5, 9, 7, 5, 8, 4, 5, 10, 8, 10, 11, 8, 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, 9, 4, 5, 2, 11, 3, 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, 5, 10, 2, 5, 2, 4, 4, 2, 0, 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, 8, 4, 5, 8, 5, 3, 3, 5, 1, 0, 4, 5, 1, 0, 5, 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, 9, 4, 5, 4, 11, 7, 4, 9, 11, 9, 10, 11, 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, 11, 7, 4, 11, 4, 2, 2, 4, 0, 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, 1, 10, 2, 8, 7, 4, 4, 9, 1, 4, 1, 7, 7, 1, 3, 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, 4, 0, 3, 7, 4, 3, 4, 8, 7, 9, 10, 8, 10, 11, 8, 3, 0, 9, 3, 9, 11, 11, 9, 10, 0, 1, 10, 0, 10, 8, 8, 10, 11, 3, 1, 10, 11, 3, 10, 1, 2, 11, 1, 11, 9, 9, 11, 8, 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, 0, 2, 11, 8, 0, 11, 3, 2, 11, 2, 3, 8, 2, 8, 10, 10, 8, 9, 9, 10, 2, 0, 9, 2, 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, 1, 10, 2, 1, 3, 8, 9, 1, 8, 0, 9, 1, 0, 3, 8 }; } } #endif
11,988
C
67.508571
121
0.436937
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtVoxelTetrahedralizer.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 EXT_VOXEL_TETRAHEDRALIZER_H #define EXT_VOXEL_TETRAHEDRALIZER_H #include "ExtMultiList.h" #include "ExtBVH.h" #include "foundation/PxVec3.h" #include "foundation/PxBounds3.h" namespace physx { namespace Ext { // ------------------------------------------------------------------------------ class VoxelTetrahedralizer { public: VoxelTetrahedralizer(); void clear(); void createTetMesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds, PxI32 resolution, PxI32 numRelaxationIters = 5, PxF32 relMinTetVolume = 0.05f); void readBack(PxArray<PxVec3>& tetVertices, PxArray<PxU32>& tetIndices); private: void voxelize(PxU32 resolution); void createTets(bool subdivBorder, PxU32 numTetsPerVoxel); void buildBVH(); void createUniqueTetVertices(); void findTargetPositions(PxF32 surfaceDist); void conserveVolume(PxF32 relMinVolume); void relax(PxI32 numIters, PxF32 relMinVolume); // input mesh PxArray<PxVec3> surfaceVerts; PxArray<PxI32> surfaceTriIds; PxBounds3 surfaceBounds; // voxel grid struct Voxel { void init(PxI32 _xi, PxI32 _yi, PxI32 _zi) { xi = _xi; yi = _yi; zi = _zi; for (PxI32 i = 0; i < 6; i++) neighbors[i] = -1; for (PxI32 i = 0; i < 8; i++) ids[i] = -1; parent = -1; inner = false; } bool isAt(PxI32 _xi, PxI32 _yi, PxI32 _zi) { return xi == _xi && yi == _yi && zi == _zi; } PxI32 xi, yi, zi; PxI32 neighbors[6]; PxI32 parent; PxI32 ids[8]; bool inner; }; PxVec3 gridOrigin; PxF32 gridSpacing; PxArray<Voxel> voxels; BVHDesc bvh; // tet mesh PxArray<PxVec3> tetVerts; PxArray<PxVec3> origTetVerts; PxArray<PxI32> tetIds; // relaxation PxArray<bool> isSurfaceVert; PxArray<PxVec3> targetVertPos; PxArray<PxI32> queryTris; PxArray<PxI32> edgeIds; }; } } #endif
3,601
C
29.786325
83
0.691752
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtInsideTester.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 EXT_INSIDE_TESTER_H #define EXT_INSIDE_TESTER_H // MM: tester whether a point is inside a triangle mesh // all faces are projected onto the 3 canonical planes and hashed // for fast ray mesh intersections #include "foundation/PxVec3.h" #include "foundation/PxArray.h" #include "foundation/PxQuat.h" #include "CmRandom.h" namespace physx { namespace Ext { // ---------------------------------------------------------- class InsideTester { public: void init(const PxVec3 *vertices, PxI32 numVertices, const PxI32 *triIndices, PxI32 numTris); bool isInside(const PxVec3& pos); private: PxArray<PxVec3> mVertices; PxArray<PxI32> mIndices; struct Grid2d { void init(PxI32 dim0, const PxArray<PxVec3> &vertices, const PxArray<PxI32> &indices); PxI32 numInside(const PxVec3&pos, const PxArray<PxVec3> &vertices, const PxArray<PxI32> &indices); PxI32 dim0; PxVec3 orig; PxI32 num1, num2; float spacing; PxArray<PxI32> first; PxArray<PxI32> tris; PxArray<int> next; Cm::RandomR250 rnd = Cm::RandomR250(0); }; Grid2d mGrids[3]; }; } } #endif
2,826
C
35.714285
102
0.724699
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMeshSimplificator.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_MESH_SIMPLIFICATOR_H #define EXT_MESH_SIMPLIFICATOR_H #include "foundation/PxBounds3.h" #include "foundation/PxArray.h" #include "geometry/PxSimpleTriangleMesh.h" #include "ExtQuadric.h" #include "ExtRandomAccessHeap.h" #include "GuSDF.h" // ------------------------------------------------------------------------------ // MM: implementation of paper Garland and Heckbert: "Surface Simplification Using Quadric Error Metrics" namespace physx { namespace Ext { struct PxVec3Ex { PxVec3 p; PxU32 i = 0xFFFFFFFF; explicit PxVec3Ex() : p(0.0f), i(0xFFFFFFFF) { } explicit PxVec3Ex(PxVec3 point, PxU32 sourceTriangleIndex = 0xFFFFFFFF) : p(point), i(sourceTriangleIndex) { } }; class MeshSimplificator { public: MeshSimplificator(); void init(const PxSimpleTriangleMesh& inputMesh, PxReal edgeLengthCostWeight_ = 1e-1f, PxReal flatnessDetectionThreshold_ = 1e-2f, bool projectSimplifiedPointsOnInputMeshSurface = false); void init(const PxArray<PxVec3> &vertices, const PxArray<PxU32> &triIds, PxReal edgeLengthCostWeight_ = 1e-1f, PxReal flatnessDetectionThreshold_ = 1e-2f, bool projectSimplifiedPointsOnInputMeshSurface = false); void decimateByRatio(PxF32 relativeOutputMeshSize = 0.5f, PxF32 maximalEdgeLength = 0.0f); void decimateBySize(PxI32 targetTriangleCount, PxF32 maximalEdgeLength = 0.0f); void readBack(PxArray<PxVec3>& vertices, PxArray<PxU32>& triIds, PxArray<PxU32> *vertexMap = NULL, PxArray<PxU32> *outputVertexToInputTriangle = NULL); ~MeshSimplificator(); private: PxArray<PxVec3Ex> vertices; PxArray<PxI32> triIds; PxArray<PxVec3> scaledOriginalVertices; PxArray<PxU32> originalTriIds; Gu::PxPointOntoTriangleMeshProjector* projector; void init(); bool step(PxF32 maximalEdgeLength); bool getAdjTris(PxI32 triNr, PxI32 vertNr, PxI32& valence, bool& open, PxArray<PxI32>* tris) const; bool getAdjTris(PxI32 triNr, PxI32 vertNr, PxArray<PxI32>& tris) const; void replaceNeighbor(PxI32 triNr, PxI32 oldNeighbor, PxI32 newNeighbor); PxI32 getEdgeId(PxI32 triNr, PxI32 edgeNr); bool collapseEdge(PxI32 triNr, PxI32 edgeNr); PxVec3Ex evalEdgeCost(PxI32 triNr, PxI32 edgeNr, PxReal& costt); PxVec3Ex projectPoint(const PxVec3& p); void findTriNeighbors(); void transformPointsToUnitBox(PxArray<PxVec3Ex>& points); void transformPointsToOriginalPosition(PxArray<PxVec3>& points); PxI32 numMeshTris; PxArray<Quadric> quadrics; PxArray<PxI32> vertMarks; PxArray<PxI32> adjTris; PxI32 currentVertMark; PxArray<PxI32> triNeighbors; //Scale input points into 0...1 unit-box PxReal scaling; PxVec3 origin; PxReal edgeLengthCostWeight; PxReal flatnessDetectionThreshold; PxArray<PxI32> simplificationMap; struct HeapElem { HeapElem() : triNr(0), edgeNr(0), cost(0.0f) {} HeapElem(PxI32 triNr_, PxI32 edgeNr_, float cost_) : triNr(triNr_), edgeNr(edgeNr_), cost(cost_) {} PxI32 triNr, edgeNr; float cost; PX_FORCE_INLINE bool operator < (const HeapElem& e) const { return cost < e.cost; } }; RandomAccessHeap<HeapElem> heap; }; } } #endif
4,756
C
33.977941
214
0.730866
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMeshSimplificator.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtMeshSimplificator.h" #include "foundation/PxSort.h" namespace physx { namespace Ext { // ------------------------------------------------------------------------------------- MeshSimplificator::MeshSimplificator() { currentVertMark = 0; numMeshTris = 0; } // ------------------------------------------------------------------------------------- void MeshSimplificator::findTriNeighbors() { PxI32 numTris = PxI32(triIds.size()) / 3; triNeighbors.clear(); triNeighbors.resize(3 * numTris, -1); struct Edge { PX_FORCE_INLINE void init(PxI32 _id0, PxI32 _id1, PxI32 _triNr, PxI32 _edgeNr) { this->id0 = PxMin(_id0, _id1); this->id1 = PxMax(_id0, _id1); this->triNr = _triNr; this->edgeNr = _edgeNr; } PX_FORCE_INLINE bool operator < (const Edge& e) const { return (id0 < e.id0 || (id0 == e.id0 && id1 < e.id1)); } PX_FORCE_INLINE bool operator == (const Edge& e) const { return id0 == e.id0 && id1 == e.id1; } PxI32 id0, id1, triNr, edgeNr; }; PxArray<Edge> edges(PxI32(triIds.size())); for (PxI32 i = 0; i < numTris; i++) { for (PxI32 j = 0; j < 3; j++) { PxI32 id0 = triIds[3 * i + j]; PxI32 id1 = triIds[3 * i + (j + 1) % 3]; edges[3 * i + j].init(id0, id1, i, j); } } PxSort(edges.begin(), edges.size()); PxI32 nr = 0; while (nr < PxI32(edges.size())) { Edge& e0 = edges[nr]; nr++; while (nr < PxI32(edges.size()) && edges[nr] == e0) { Edge& e1 = edges[nr]; triNeighbors[3 * e0.triNr + e0.edgeNr] = e1.triNr; triNeighbors[3 * e1.triNr + e1.edgeNr] = e0.triNr; nr++; } } } // ------------------------------------------------------------------------------------- bool MeshSimplificator::getAdjTris(PxI32 triNr, PxI32 vertNr, PxI32& valence, bool& open, PxArray<PxI32>* tris) const { open = false; if (tris) tris->clear(); PxI32 cnt = 0; valence = 0; PxI32 nr = triNr; // counter clock do { if (tris) tris->pushBack(nr); valence++; if (triIds[3 * nr] == vertNr) nr = triNeighbors[3 * nr + 2]; else if (triIds[3 * nr + 1] == vertNr) nr = triNeighbors[3 * nr]; else nr = triNeighbors[3 * nr + 1]; cnt++; } while (nr >= 0 && nr != triNr && cnt < 100); if (cnt >= 100) { valence = 0; return false; } cnt = 0; if (nr < 0) { // open: search clockwise too open = true; nr = triNr; do { if (nr != triNr) { if (tris) tris->pushBack(nr); valence++; } if (triIds[3 * nr] == vertNr) nr = triNeighbors[3 * nr]; else if (triIds[3 * nr + 1] == vertNr) nr = triNeighbors[3 * nr + 1]; else nr = triNeighbors[3 * nr + 2]; cnt++; } while (nr >= 0 && nr != triNr && cnt < 100); valence++; // num tris + 1 if open if (cnt > 100) { valence = 0; return false; } } return true; } // ------------------------------------------------------------------------------------- bool MeshSimplificator::getAdjTris(PxI32 triNr, PxI32 vertNr, PxArray<PxI32>& tris) const { PxI32 valence; bool open; return getAdjTris(triNr, vertNr, valence, open, &tris); } // ------------------------------------------------------------------------------------- void MeshSimplificator::replaceNeighbor(PxI32 triNr, PxI32 oldNeighbor, PxI32 newNeighbor) { if (triNr < 0) return; for (PxI32 i = 0; i < 3; i++) { if (triNeighbors[3 * triNr + i] == oldNeighbor) triNeighbors[3 * triNr + i] = newNeighbor; } } // ------------------------------------------------------------------------------------- PxI32 MeshSimplificator::getEdgeId(PxI32 triNr, PxI32 edgeNr) { PxI32 n = triNeighbors[3 * triNr + edgeNr]; if (n < 0 || triNr < n) return 3 * triNr + edgeNr; else { for (PxI32 i = 0; i < 3; i++) { if (triNeighbors[3 * n + i] == triNr) return 3 * n + i; } } return 0; } inline PxVec3Ex MeshSimplificator::projectPoint(const PxVec3& p) { PxU32 triangleId; PxVec3 pos = projector->projectPoint(p, triangleId); return PxVec3Ex(pos, triangleId); } // ------------------------------------------------------------------------------------- PxVec3Ex MeshSimplificator::evalEdgeCost(PxI32 triNr, PxI32 edgeNr, PxReal &cost) { const PxI32 numSteps = 10; cost = -1.0f; PxI32 id0 = triIds[3 * triNr + edgeNr]; PxI32 id1 = triIds[3 * triNr + (edgeNr + 1) % 3]; PxReal minCost = FLT_MAX; PxReal maxCost = -FLT_MAX; Quadric q; q = quadrics[id0] + quadrics[id1]; PxVec3Ex pos; PxReal edgeLength = (vertices[id0].p - vertices[id1].p).magnitude(); for (PxI32 i = 0; i <= numSteps; i++) { float r = 1.0f / numSteps * i; pos.p = vertices[id0].p * (1.0f - r) + vertices[id1].p * r; if (projector) pos = projectPoint(pos.p); float c = q.outerProduct(pos.p); c += edgeLengthCostWeight * edgeLength; if (cost < 0.0f || c < cost) { cost = c; } if (cost > maxCost) maxCost = cost; if (cost < minCost) minCost = cost; } if (maxCost - minCost < flatnessDetectionThreshold) { float r = 0.5f; pos.p = vertices[id0].p * (1.0f - r) + vertices[id1].p * r; if (projector) pos = projectPoint(pos.p); cost = q.outerProduct(pos.p) + edgeLengthCostWeight * edgeLength; } return pos; } // ------------------------------------------------------------------------------------- bool MeshSimplificator::collapseEdge(PxI32 triNr, PxI32 edgeNr) { if (triIds[3 * triNr] == triIds[3 * triNr + 1]) // the triangle deleted return false; PxI32 id0 = triIds[3 * triNr + edgeNr]; PxI32 id1 = triIds[3 * triNr + (edgeNr + 1) % 3]; PxI32 id2 = triIds[3 * triNr + (edgeNr + 2) % 3]; PxI32 id3 = -1; PxI32 n = triNeighbors[3 * triNr + edgeNr]; PxI32 nEdgeNr = 0; if (n >= 0) { if (triNeighbors[3 * n] == triNr) nEdgeNr = 0; else if (triNeighbors[3 * n + 1] == triNr) nEdgeNr = 1; else if (triNeighbors[3 * n + 2] == triNr) nEdgeNr = 2; id3 = triIds[3 * n + (nEdgeNr + 2) % 3]; } // not legal if there exists id != id0,id1 with (id0,id) and (id1,id) edges // but (id,id0,id1) is not a triangle bool OK = getAdjTris(triNr, id0, adjTris); currentVertMark++; for (PxI32 i = 0; i < PxI32(adjTris.size()); i++) { PxI32 adj = adjTris[i]; for (PxI32 j = 0; j < 3; j++) vertMarks[triIds[3 * adj + j]] = currentVertMark; } OK = OK && getAdjTris(triNr, id1, adjTris); if (!OK) return false; for (PxI32 i = 0; i < PxI32(adjTris.size()); i++) { PxI32 adj = adjTris[i]; for (PxI32 j = 0; j < 3; j++) { PxI32 id = triIds[3 * adj + j]; if (vertMarks[id] == currentVertMark && id != id0 && id != id1 && id != id2 && id != id3) return false; } } // new center pos PxReal cost; PxVec3Ex newPos = evalEdgeCost(triNr, edgeNr, cost); //PxVec3 newPos = vertices[id0] * (1.0f - ratio) + vertices[id1] * ratio; // any triangle flips? for (PxI32 side = 0; side < 2; side++) { getAdjTris(triNr, side == 0 ? id0 : id1, adjTris); PxI32 other = side == 0 ? id1 : id0; for (PxU32 i = 0; i < adjTris.size(); i++) { PxI32 adj = adjTris[i]; PxVec3 p[3], q[3]; bool deleted = false; for (PxI32 j = 0; j < 3; j++) { PxI32 id = triIds[3 * adj + j]; if (id == other) deleted = true; p[j] = vertices[id].p; q[j] = (id == id0 || id == id1) ? newPos.p : p[j]; } if (!deleted) { PxVec3 n0 = (p[1] - p[0]).cross(p[2] - p[0]); PxVec3 n1 = (q[1] - q[0]).cross(q[2] - q[0]); if (n0.dot(n1) <= 0.0f) return false; } } } // remove adjacent edges from heap for (PxI32 side = 0; side < 2; side++) { PxI32 id = side == 0 ? id0 : id1; getAdjTris(triNr, id, adjTris); for (PxU32 i = 0; i < adjTris.size(); i++) { PxI32 adj = adjTris[i]; for (PxI32 j = 0; j < 3; j++) { PxI32 adj0 = triIds[3 * adj + j]; PxI32 adj1 = triIds[3 * adj + (j + 1) % 3]; if (adj0 == id0 || adj0 == id1 || adj1 == id0 || adj1 == id1) { PxI32 edgeId = getEdgeId(adj, j); heap.remove(edgeId); } } } } // move vertex if (id0 > id1) { int id = id0; id0 = id1; id1 = id; } vertices[id0] = newPos; quadrics[id0] += quadrics[id1]; // collapse edge getAdjTris(triNr, id1, adjTris); for (PxU32 i = 0; i < adjTris.size(); i++) { PxI32 adj = adjTris[i]; for (PxI32 j = 0; j < 3; j++) { PxI32& id = triIds[3 * adj + j]; if (id == id1) id = id0; } } simplificationMap[id1] = id0; // mark triangles as deleted (duplicate indices, can still be rendered) triIds[3 * triNr + 2] = triIds[3 * triNr + 1] = triIds[3 * triNr]; numMeshTris--; if (n >= 0) { triIds[3 * n + 2] = triIds[3 * n + 1] = triIds[3 * n]; numMeshTris--; } // update neighbors PxI32 right = triNeighbors[3 * triNr + (edgeNr + 1) % 3]; PxI32 left = triNeighbors[3 * triNr + (edgeNr + 2) % 3]; replaceNeighbor(right, triNr, left); replaceNeighbor(left, triNr, right); PxI32 startTriNr = PxMax(right, left); if (n >= 0) { right = triNeighbors[3 * n + (nEdgeNr + 1) % 3]; left = triNeighbors[3 * n + (nEdgeNr + 2) % 3]; replaceNeighbor(right, n, left); replaceNeighbor(left, n, right); startTriNr = PxMax(startTriNr, PxMax(right, left)); } // add new edges to heap if (startTriNr >= 0) { getAdjTris(startTriNr, id0, adjTris); for (PxU32 i = 0; i < adjTris.size(); i++) { PxI32 adj = adjTris[i]; for (PxI32 j = 0; j < 3; j++) { PxI32 adj0 = triIds[3 * adj + j]; PxI32 adj1 = triIds[3 * adj + (j + 1) % 3]; if (adj0 == id0 || adj1 == id0) { evalEdgeCost(adj, j, cost); PxI32 id = getEdgeId(adj, j); heap.insert(HeapElem(adj, j, cost), id); } } } } return true; } #if PX_LINUX #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmisleading-indentation" #endif void minMax(const PxArray<PxVec3Ex>& points, PxVec3& min, PxVec3& max) { min = PxVec3(FLT_MAX, FLT_MAX, FLT_MAX); max = PxVec3(-FLT_MAX, -FLT_MAX, -FLT_MAX); for (PxU32 i = 0; i < points.size(); ++i) { const PxVec3& p = points[i].p; if (p.x > max.x) max.x = p.x; if (p.y > max.y) max.y = p.y; if (p.z > max.z) max.z = p.z; if (p.x < min.x) min.x = p.x; if (p.y < min.y) min.y = p.y; if (p.z < min.z) min.z = p.z; } } #if PX_LINUX #pragma GCC diagnostic pop #endif void MeshSimplificator::transformPointsToUnitBox(PxArray<PxVec3Ex>& points) { PxVec3 min, max; minMax(points, min, max); origin = min; PxVec3 size = max - min; scaling = 1.0f / PxMax(PxMax(1e-6f, size.x), PxMax(size.y, size.z)); for (PxU32 i = 0; i < points.size(); ++i) points[i].p = (points[i].p - min) * scaling; } void MeshSimplificator::transformPointsToOriginalPosition(PxArray<PxVec3>& points) { PxReal s = 1.0f / scaling; for (PxU32 i = 0; i < points.size(); ++i) points[i] = points[i] * s + origin; } // ------------------------------------------------------------------------------------- void MeshSimplificator::init(const PxSimpleTriangleMesh& inputMesh, PxReal edgeLengthCostWeight_, PxReal flatnessDetectionThreshold_, bool projectSimplifiedPointsOnInputMeshSurface) { edgeLengthCostWeight = edgeLengthCostWeight_; flatnessDetectionThreshold = flatnessDetectionThreshold_; vertices.resize(inputMesh.points.count); for (PxU32 i = 0; i < inputMesh.points.count; i++) vertices[i] = PxVec3Ex(inputMesh.points.at<PxVec3>(i)); transformPointsToUnitBox(vertices); PxI32 numIndices = 3 * inputMesh.triangles.count; triIds.resize(numIndices); if (inputMesh.flags & PxMeshFlag::e16_BIT_INDICES) { for (PxI32 i = 0; i < numIndices; i++) triIds[i] = PxI32(inputMesh.triangles.at<PxU16>(i)); } else { for (PxI32 i = 0; i < numIndices; i++) triIds[i] = PxI32(inputMesh.triangles.at<PxU32>(i)); } for (PxU32 i = 0; i < triIds.size(); i++) vertices[triIds[i]].i = i / 3; if (projectSimplifiedPointsOnInputMeshSurface) { originalTriIds.resize(triIds.size()); for (PxU32 i = 0; i < triIds.size(); ++i) originalTriIds[i] = triIds[i]; scaledOriginalVertices.resize(inputMesh.points.count); for (PxU32 i = 0; i < inputMesh.points.count; i++) scaledOriginalVertices[i] = vertices[i].p; projector = Gu::PxCreatePointOntoTriangleMeshProjector(scaledOriginalVertices.begin(), originalTriIds.begin(), inputMesh.triangles.count); } else projector = NULL; init(); } // ------------------------------------------------------------------------------------- void MeshSimplificator::init(const PxArray<PxVec3> &inputVertices, const PxArray<PxU32> &inputTriIds, PxReal edgeLengthCostWeight_, PxReal flatnessDetectionThreshold_, bool projectSimplifiedPointsOnInputMeshSurface) { edgeLengthCostWeight = edgeLengthCostWeight_; flatnessDetectionThreshold = flatnessDetectionThreshold_; vertices.resize(inputVertices.size()); for (PxU32 i = 0; i < inputVertices.size(); i++) vertices[i] = PxVec3Ex(inputVertices[i]); for (PxU32 i = 0; i < inputTriIds.size(); i++) vertices[inputTriIds[i]].i = i / 3; transformPointsToUnitBox(vertices); triIds.resize(inputTriIds.size()); for (PxU32 i = 0; i < inputTriIds.size(); i++) triIds[i] = PxI32(inputTriIds[i]); if (projectSimplifiedPointsOnInputMeshSurface) { scaledOriginalVertices.resize(inputVertices.size()); for (PxU32 i = 0; i < inputVertices.size(); i++) scaledOriginalVertices[i] = vertices[i].p; projector = Gu::PxCreatePointOntoTriangleMeshProjector(scaledOriginalVertices.begin(), inputTriIds.begin(), inputTriIds.size() / 3); } else projector = NULL; init(); } MeshSimplificator::~MeshSimplificator() { if (projector) { PX_RELEASE(projector) } } // ------------------------------------------------------------------------------------- void MeshSimplificator::init() { vertMarks.clear(); vertMarks.resize(vertices.size(), 0); currentVertMark = 0; findTriNeighbors(); // init vertex quadrics quadrics.resize(vertices.size()); for (PxU32 i = 0; i < vertices.size(); i++) quadrics[i].zero(); Quadric q; PxI32 numTris = PxI32(triIds.size()) / 3; for (PxI32 i = 0; i < numTris; i++) { PxI32 id0 = triIds[3 * i]; PxI32 id1 = triIds[3 * i + 1]; PxI32 id2 = triIds[3 * i + 2]; q.setFromPlane(vertices[id0].p, vertices[id1].p, vertices[id2].p); quadrics[id0] += q; quadrics[id1] += q; quadrics[id2] += q; } // init heap heap.clear(); for (PxI32 i = 0; i < numTris; i++) { for (PxI32 j = 0; j < 3; j++) { PxI32 n = triNeighbors[3 * i + j]; if (n < 0 || i < n) { PxReal cost; evalEdgeCost(i, j, cost); heap.insert(HeapElem(i, j, cost), getEdgeId(i, j)); } } } numMeshTris = numTris; // init simplification map simplificationMap.resize(vertices.size()); for (PxI32 i = 0; i < PxI32(vertices.size()); i++) simplificationMap[i] = i; // each vertex is a root } // ------------------------------------------------------------------------------------- bool MeshSimplificator::step(PxF32 maximalEdgeLength) { int heapMinSize = 20; if (heap.size() < heapMinSize) return false; while (heap.size() > heapMinSize) { HeapElem e = heap.deleteMin(); PxI32 id0 = triIds[3 * e.triNr + e.edgeNr]; PxI32 id1 = triIds[3 * e.triNr + (e.edgeNr + 1) % 3]; PxF32 length = (vertices[id0].p - vertices[id1].p).magnitude(); if (maximalEdgeLength == 0.0f || length < maximalEdgeLength) { collapseEdge(e.triNr, e.edgeNr); return true; } } return false; } // ------------------------------------------------------------------------------------- void MeshSimplificator::decimateByRatio(PxF32 relativeOutputMeshSize, PxF32 maximalEdgeLength) { relativeOutputMeshSize = PxClamp(relativeOutputMeshSize, 0.1f, 0.99f); PxI32 numSteps = PxI32(PxFloor(PxF32(heap.size()) * (1.0f - relativeOutputMeshSize))); for (PxI32 i = 0; i < numSteps; i++) { if (!step(maximalEdgeLength)) break; } } // ------------------------------------------------------------------------------------- void MeshSimplificator::decimateBySize(PxI32 targetTriangleCount, PxF32 maximalEdgeLength) { while (numMeshTris > targetTriangleCount) { if (!step(maximalEdgeLength)) break; } } // ------------------------------------------------------------------------------------- void MeshSimplificator::readBack(PxArray<PxVec3>& outVertices, PxArray<PxU32>& outTriIds, PxArray<PxU32> *vertexMap, PxArray<PxU32> *outputVertexToInputTriangle) { outVertices.clear(); outTriIds.clear(); PxArray<PxI32> idMap(vertices.size(), -1); PxI32 numTris = PxI32(triIds.size()) / 3; for (PxI32 i = 0; i < numTris; i++) { if (triIds[3 * i] == triIds[3 * i + 1]) // deleted continue; for (PxI32 j = 0; j < 3; j++) { PxI32 id = triIds[3 * i + j]; if (idMap[id] < 0) { idMap[id] = outVertices.size(); outVertices.pushBack(vertices[id].p); if(outputVertexToInputTriangle && projector) outputVertexToInputTriangle->pushBack(vertices[id].i); } outTriIds.pushBack(PxU32(idMap[id])); } } transformPointsToOriginalPosition(outVertices); if (vertexMap) { for (PxU32 i = 0; i < simplificationMap.size(); ++i) { PxI32 id = i; while (id != simplificationMap[id]) { id = simplificationMap[id]; } const PxI32 finalLink = id; id = i; simplificationMap[i] = finalLink; while (id != simplificationMap[id]) { PxI32 oldId = id; id = simplificationMap[id]; simplificationMap[oldId] = finalLink; } } vertexMap->resize(vertices.size()); for (PxU32 i = 0; i < simplificationMap.size(); ++i) { PxI32 mapped = idMap[simplificationMap[i]]; (*vertexMap)[i] = mapped; } } } } }
20,191
C++
26.472109
163
0.551483
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtRemesher.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_REMESHER_H #define EXT_REMESHER_H #include "foundation/PxBounds3.h" #include "foundation/PxArray.h" namespace physx { namespace Ext { // ------------------------------------------------------------------------------ class Remesher { public: Remesher() {} ~Remesher() {} void remesh(const PxVec3* verts, PxU32 nbVertices, const PxU32* triIds, PxU32 nbTriangleIndices, PxU32 resolution = 100, PxArray<PxU32> *vertexMap = nullptr); void remesh(const PxArray<PxVec3>& verts, const PxArray<PxU32>& triIds, PxU32 resolution = 100, PxArray<PxU32> *vertexMap = nullptr); void clear(); void readBack(PxArray<PxVec3>& vertices, PxArray<PxU32>& triIds); private: PxArray<PxVec3> vertices; PxArray<PxI32> triIds; void addCell(PxI32 xi, PxI32 yi, PxI32 zi); PxI32 getCellNr(PxI32 xi, PxI32 yi, PxI32 zi) const; bool cellExists(PxI32 xi, PxI32 yi, PxI32 zi) const; void removeDuplicateVertices(); void pruneInternalSurfaces(); void computeNormals(); void findTriNeighbors(); void project(const PxVec3* inputVerts, const PxU32* inputTriIds, PxU32 nbTriangleIndices, float searchDist, float surfaceDist); void createVertexMap(const PxVec3* verts, PxU32 nbVertices, const PxVec3 &gridOrigin, PxF32 &gridSpacing, PxArray<PxU32> &vertexMap); // ------------------------------------------------------------------------------------- struct Cell { void init(PxI32 _xi, PxI32 _yi, PxI32 _zi) { this->xi = _xi; this->yi = _yi; this->zi = _zi; this->next = -1; } PxI32 xi, yi, zi; PxI32 next; }; PxArray<Cell> cells; PxArray<PxI32> firstCell; PxArray<PxVec3> normals; PxArray<PxI32> triNeighbors; PxArray<PxI32> cellOfVertex; PxArray<PxBounds3> bvhBounds; PxArray<PxI32> bvhTris; }; } } #endif
3,394
C
34
161
0.69122
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtMultiList.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 EXT_MULTI_LIST_H #define EXT_MULTI_LIST_H // MM: Multiple linked lists in a common array with a free list #include "foundation/PxArray.h" namespace physx { namespace Ext { //----------------------------------------------------------------------------- template <class T> class MultiList { public: MultiList(PxI32 maxId = 0) { firstFree = -1; if (maxId > 0) first.reserve(maxId + 1); } void reserve(int maxId) { first.reserve(maxId + 1); } void clear(); PxI32 add(PxI32 id, const T &item); bool addUnique(PxI32 id, const T &item); bool exists(PxI32 id, const T &item) const; void remove(PxI32 id, const T &item); void removeAll(PxI32 id); PxI32 size(PxI32 id) const; PxI32 getPairNr(PxI32 id, const T &item) const; void replace(PxI32 id, const T &before, const T &after); void getItems(PxI32 id) const; mutable PxArray<T> queryItems; void initIteration(PxI32 id, PxI32& iterator); bool iterate(T& item, PxI32& iterator); void getPointers(PxI32 id); mutable PxArray<T*> queryPointers; private: PxArray<PxI32> first; PxArray<T> items; PxArray<PxI32> next; PxI32 firstFree; }; //----------------------------------------------------------------------------- template <class T> void MultiList<T>::clear() { first.clear(); next.clear(); items.clear(); queryItems.clear(); queryPointers.clear(); firstFree = -1; } //----------------------------------------------------------------------------- template <class T> PxI32 MultiList<T>::add(PxI32 id, const T &item) { if (id >= PxI32(first.size())) first.resize(id + 1, -1); PxI32 pos = firstFree; if (pos >= 0) firstFree = next[firstFree]; else { pos = PxI32(items.size()); items.resize(items.size() + 1); next.resize(items.size() + 1); } next[pos] = first[id]; first[id] = pos; items[pos] = item; return pos; } //----------------------------------------------------------------------------- template <class T> bool MultiList<T>::addUnique(PxI32 id, const T &item) { if (exists(id, item)) return false; add(id, item); return true; } //----------------------------------------------------------------------------- template <class T> bool MultiList<T>::exists(PxI32 id, const T &item) const { return getPairNr(id, item) >= 0; } //----------------------------------------------------------------------------- template <class T> PxI32 MultiList<T>::size(PxI32 id) const { if (id >= PxI32(first.size())) return 0; PxI32 num = 0; PxI32 nr = first[id]; while (nr >= 0) { num++; nr = next[nr]; } return num; } //----------------------------------------------------------------------------- template <class T> PxI32 MultiList<T>::getPairNr(PxI32 id, const T &item) const { if (id < 0 || id >= PxI32(first.size())) return -1; PxI32 nr = first[id]; while (nr >= 0) { if (items[nr] == item) return nr; nr = next[nr]; } return -1; } //----------------------------------------------------------------------------- template <class T> void MultiList<T>::remove(PxI32 id, const T &itemNr) { PxI32 nr = first[id]; PxI32 prev = -1; while (nr >= 0 && items[nr] != itemNr) { prev = nr; nr = next[nr]; } if (nr < 0) return; if (prev >= 0) next[prev] = next[nr]; else first[id] = next[nr]; next[nr] = firstFree; firstFree = nr; } //----------------------------------------------------------------------------- template <class T> void MultiList<T>::replace(PxI32 id, const T &before, const T &after) { PxI32 nr = first[id]; while (nr >= 0) { if (items[nr] == before) items[nr] = after; nr = next[nr]; } } //----------------------------------------------------------------------------- template <class T> void MultiList<T>::removeAll(PxI32 id) { if (id >= PxI32(first.size())) return; PxI32 nr = first[id]; if (nr < 0) return; PxI32 prev = -1; while (nr >= 0) { prev = nr; nr = next[nr]; } next[prev] = firstFree; firstFree = first[id]; first[id] = -1; } //----------------------------------------------------------------------------- template <class T> void MultiList<T>::getItems(PxI32 id) const { queryItems.clear(); if (id >= PxI32(first.size())) return; PxI32 nr = first[id]; while (nr >= 0) { queryItems.push_back(items[nr]); nr = next[nr]; } } //----------------------------------------------------------------------------- template <class T> void MultiList<T>::initIteration(PxI32 id, PxI32& iterator) { if (id >= PxI32(first.size())) iterator = -1; else iterator = first[id]; } //----------------------------------------------------------------------------- template <class T> bool MultiList<T>::iterate(T& item, PxI32& iterator) { if (iterator >= 0) { item = items[iterator]; iterator = next[iterator]; return true; } return false; } //----------------------------------------------------------------------------- template <class T> void MultiList<T>::getPointers(PxI32 id) { queryPointers.clear(); if (id >= PxI32(first.size())) return; PxI32 nr = first[id]; while (nr >= 0) { queryPointers.push_back(&items[nr]); nr = next[nr]; } } } } #endif
7,212
C
25.039711
81
0.529257
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtDelaunayBoundaryInserter.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtDelaunayBoundaryInserter.h" #include "ExtTetSplitting.h" #include "ExtFastWindingNumber.h" #include "ExtTetUnionFind.h" #include "ExtVec3.h" #include "foundation/PxSort.h" #include "foundation/PxBasicTemplates.h" #include "CmRandom.h" #include "tet/ExtUtilities.h" #include "GuAABBTree.h" #include "GuAABBTreeQuery.h" #include "GuIntersectionTriangleTriangle.h" #include "GuIntersectionTetrahedronBox.h" #include "foundation/PxMathUtils.h" #include "GuInternal.h" #include "common/GuMeshAnalysis.h" #include <stdio.h> #define PI 3.141592653589793238462643383 namespace physx { namespace Ext { using namespace Gu; template<typename T> bool contains(const PxArray<T>& list, const T& value) { for (PxU32 i = 0; i < list.size(); ++i) if (list[i] == value) return true; return false; } //Returns a value proportional to the signed volume of the tetrahedron specified by the points a, b, c and d //Usualy only the result's sign is used in algorithms checking for intersections etc. PX_FORCE_INLINE PxF64 orient3D(const PxVec3d& a, const PxVec3d& b, const PxVec3d& c, const PxVec3d& d) { return (a - d).dot((b - d).cross(c - d)); } PX_FORCE_INLINE PxF64 sign(const PxF64 value) { if (value == 0) return 0.0; if (value > 0) return 1.0; return -1.0; } PX_FORCE_INLINE PxF64 signedDistancePointPlane(const PxVec3d& point, const PxVec3d& normal, PxF64 planeD) { return point.dot(normal) + planeD; } PX_FORCE_INLINE bool lineSegmentIntersectsTriangle(const PxVec3d& segmentStart, const PxVec3d& segmentEnd, const PxVec3d& triA, const PxVec3d& triB, const PxVec3d& triC, PxVec3d& intersectionPoint) { PxVec3d n = (triB - triA).cross(triC - triA); PxF64 l2 = n.magnitudeSquared(); if (l2 < 1e-12) return false; //const PxF64 s = orient3D(segmentStart, triA, triB, triC); //const PxF64 e = orient3D(segmentEnd, triA, triB, triC); PxF64 planeD = -n.dot(triA); PxF64 s = signedDistancePointPlane(segmentStart, n, planeD); PxF64 e = signedDistancePointPlane(segmentEnd, n, planeD); if (s == 0 || e == 0) return false; if (/*s == 0 || e == 0 ||*/ sign(s) != sign(e)) { const PxF64 ab = orient3D(segmentStart, segmentEnd, triA, triB); const PxF64 bc = orient3D(segmentStart, segmentEnd, triB, triC); const PxF64 ca = orient3D(segmentStart, segmentEnd, triC, triA); const bool signAB = ab > 0; const bool signBC = bc > 0; const bool signCA = ca > 0; if ((ab == 0 && signBC == signCA) || (bc == 0 && signAB == signCA) || (ca == 0 && signAB == signBC) || (signAB == signBC && signAB == signCA)) { s = PxAbs(s); e = PxAbs(e); intersectionPoint = (segmentEnd * s + segmentStart * e) / (s + e); return true; } return false; } else return false; } //Helper class that controls the BVH traversal when checking if a specified edge intersects a triangle mesh with a BVH build around it //Edges intersecting the triangle mesh are scheduled to get split at the point where they intersect the mesh's surface class IntersectionFixingTraversalController { private: const PxArray<Triangle>& triangles; PxArray<PxVec3d>& points; PxHashMap<PxU64, PxI32>& edgesToSplit; PxArray<PxArray<PxI32>>& pointToOriginalTriangle; PxU64 edge; PxI32 a; PxI32 b; //PxF32 minX, minY, minZ, maxX, maxY, maxZ; PxBounds3 box; bool repeat = false; public: PX_FORCE_INLINE IntersectionFixingTraversalController(const PxArray<Triangle>& triangles_, PxArray<PxVec3d>& points_, PxHashMap<PxU64, PxI32>& edgesToSplit_, PxArray<PxArray<PxI32>>& pointToOriginalTriangle_) : triangles(triangles_), points(points_), edgesToSplit(edgesToSplit_), pointToOriginalTriangle(pointToOriginalTriangle_) { } bool shouldRepeat() const { return repeat; } void resetRepeat() { repeat = false; } PX_FORCE_INLINE void update(PxU64 e) { edge = e; a = PxI32(e >> 32); b = PxI32(e); const PxVec3d& pA = points[a]; const PxVec3d& pB = points[b]; box = PxBounds3(PxVec3(PxF32(PxMin(pA.x, pB.x)), PxF32(PxMin(pA.y, pB.y)), PxF32(PxMin(pA.z, pB.z))), PxVec3(PxF32(PxMax(pA.x, pB.x)), PxF32(PxMax(pA.y, pB.y)), PxF32(PxMax(pA.z, pB.z)))); } PX_FORCE_INLINE TraversalControl::Enum analyze(const BVHNode& node, PxI32) { if (node.isLeaf()) { PxI32 j = node.getPrimitiveIndex(); if (!contains(pointToOriginalTriangle[a], PxI32(j)) && !contains(pointToOriginalTriangle[b], PxI32(j))) { const Triangle& tri = triangles[j]; const PxVec3d& triA = points[tri[0]]; const PxVec3d& triB = points[tri[1]]; const PxVec3d& triC = points[tri[2]]; PxVec3d intersectionPoint; if (lineSegmentIntersectsTriangle(points[a], points[b], triA, triB, triC, intersectionPoint)) { if (edgesToSplit.find(edge) == NULL) { edgesToSplit.insert(edge, PxI32(points.size())); points.pushBack(intersectionPoint); PxArray<PxI32> arr; arr.pushBack(j); pointToOriginalTriangle.pushBack(arr); } else { repeat = true; } } } return TraversalControl::eDontGoDeeper; } if (node.mBV.intersects(box)) return TraversalControl::eGoDeeper; return TraversalControl::eDontGoDeeper; } private: PX_NOCOPY(IntersectionFixingTraversalController) }; #if PX_LINUX #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmisleading-indentation" #endif void minMax(const PxArray<PxVec3d>& points, PxVec3d& min, PxVec3d& max) { min = PxVec3d(DBL_MAX, DBL_MAX, DBL_MAX); max = PxVec3d(-DBL_MAX, -DBL_MAX, -DBL_MAX); for (PxU32 i = 0; i < points.size(); ++i) { const PxVec3d& p = points[i]; if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z)) continue; if (p.x > max.x) max.x = p.x; if (p.y > max.y) max.y = p.y; if (p.z > max.z) max.z = p.z; if (p.x < min.x) min.x = p.x; if (p.y < min.y) min.y = p.y; if (p.z < min.z) min.z = p.z; } } #if PX_LINUX #pragma GCC diagnostic pop #endif //Creates a delaunay tetrahedralization out of the specified points void generateDelaunay3D(const PxArray<PxVec3d>& points, PxArray<Tetrahedron>& tetrahedra) { PxVec3d min, max; minMax(points, min, max); DelaunayTetrahedralizer delaunay(min, max); delaunay.insertPoints(points, 0, points.size(), tetrahedra); } PX_FORCE_INLINE PxF64 determinant(const PxVec3d& col1, const PxVec3d& col2, const PxVec3d& col3) { return col1.dot(col2.cross(col3)); } //Simple but slow implementation of winding numbers to determine if a point is inside a mesh or not //https://igl.ethz.ch/projects/winding-number/robust-inside-outside-segmentation-using-generalized-winding-numbers-siggraph-2013-jacobson-et-al.pdf PxF64 windingNumber(const PxArray<PxVec3d>& points, const PxArray<Triangle>& triangles, const PxVec3d& p) { PxF64 sum = 0; for (PxU32 i = 0; i < triangles.size(); i++) { const Triangle& tri = triangles[i]; const PxVec3d a = points[tri[0]] - p; const PxVec3d b = points[tri[1]] - p; const PxVec3d c = points[tri[2]] - p; PxF64 la = a.magnitude(), lb = b.magnitude(), lc = c.magnitude(); PxF64 omega = atan2(determinant(a, b, c), (la * lb * lc + a.dot(b) * lc + b.dot(c) * la + c.dot(a) * lb)); sum += omega; } sum *= 2; sum /= (4 * PI); return sum; } //Helper class to record the subdivision history of an edge struct SubdivisionEdge { PxI32 Start; PxI32 End; PxI32 ChildA; PxI32 ChildB; PX_FORCE_INLINE SubdivisionEdge(PxI32 start, PxI32 end, PxI32 childA = -1, PxI32 childB = -1) : Start(start), End(end), ChildA(childA), ChildB(childB) { } PX_FORCE_INLINE bool HasChildren() const { return ChildA >= 0; } }; //A memory friendly implementation to compute a full batch of winding numbers for every specified query point in testPoints void multiWindingNumberMemoryFriendly(const PxArray<PxVec3d>& meshPoints, const PxArray<Triangle>& meshTriangles, const PxArray<PxVec3d>& testPoints, PxArray<PxF64>& result) { PxU32 l = testPoints.size(); result.resize(l); for (PxU32 i = 0; i < l; ++i) result[i] = 0.0; for (PxU32 i = 0; i < meshTriangles.size(); i++) { const Triangle& tri = meshTriangles[i]; const PxVec3d aa = meshPoints[tri[0]]; const PxVec3d bb = meshPoints[tri[1]]; const PxVec3d cc = meshPoints[tri[2]]; for (PxU32 j = 0; j < l; ++j) { const PxVec3d p = testPoints[j]; PxVec3d a = aa; PxVec3d b = bb; PxVec3d c = cc; a.x -= p.x; a.y -= p.y; a.z -= p.z; b.x -= p.x; b.y -= p.y; b.z -= p.z; c.x -= p.x; c.y -= p.y; c.z -= p.z; const PxF64 la = sqrt(a.x * a.x + a.y * a.y + a.z * a.z), lb = sqrt(b.x * b.x + b.y * b.y + b.z * b.z), lc = sqrt(c.x * c.x + c.y * c.y + c.z * c.z); const PxF64 y = a.x * b.y * c.z - a.x * b.z * c.y - a.y * b.x * c.z + a.y * b.z * c.x + a.z * b.x * c.y - a.z * b.y * c.x; const PxF64 x = (la * lb * lc + (a.x * b.x + a.y * b.y + a.z * b.z) * lc + (b.x * c.x + b.y * c.y + b.z * c.z) * la + (c.x * a.x + c.y * a.y + c.z * a.z) * lb); const PxF64 omega = atan2(y, x); result[j] += omega; } } PxF64 scaling = 2.0 / (4 * PI); for (PxU32 i = 0; i < l; ++i) result[i] *= scaling; } //Generates a tetmesh matching the surface of the specified triangle mesh exactly - might insert additional points on the //triangle mesh's surface. I also provides access about the location of newly created points. void generateTetmesh(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles, PxArray<SubdivisionEdge>& allEdges, PxI32& numOriginalEdges, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxI32& numPointsBelongingToMultipleTriangles, PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets) { points.resize(trianglePoints.size()); for (PxU32 i = 0; i < trianglePoints.size(); ++i) points[i] = trianglePoints[i]; PxVec3d min, max; minMax(points, min, max); PxHashSet<PxU64> edges; for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; edges.insert(key(tri[0], tri[1])); edges.insert(key(tri[1], tri[2])); edges.insert(key(tri[0], tri[2])); } numOriginalEdges = PxI32(edges.size()); allEdges.clear(); for (PxHashSet<PxU64>::Iterator iter = edges.getIterator(); !iter.done(); ++iter) { allEdges.pushBack(SubdivisionEdge(PxI32((*iter) >> 32), PxI32(*iter))); } pointToOriginalTriangle.clear(); for (PxU32 i = 0; i < points.size(); ++i) pointToOriginalTriangle.pushBack(PxArray<PxI32>()); for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; pointToOriginalTriangle[tri[0]].pushBack(i); pointToOriginalTriangle[tri[1]].pushBack(i); pointToOriginalTriangle[tri[2]].pushBack(i); } for (PxU32 i = 0; i < points.size(); ++i) { PxArray<PxI32>& list = pointToOriginalTriangle[i]; PxSort(list.begin(), list.size()); } PxArray<Tetrahedron> tets; DelaunayTetrahedralizer del(min, max); PxU32 prevCount = 0; bool success = true; PxHashSet<PxU64> tetEdges; PxArray<PxI32> intersection; //Subdivide edges and insert new points ond edges into delaunay tetrahedralization until //all required edges are present in the tetrahedralization while (success) { success = false; del.insertPoints(points, prevCount, points.size(), tets); prevCount = points.size(); tetEdges.clear(); for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; tetEdges.insert(key(tet[0], tet[1])); tetEdges.insert(key(tet[0], tet[2])); tetEdges.insert(key(tet[0], tet[3])); tetEdges.insert(key(tet[1], tet[2])); tetEdges.insert(key(tet[1], tet[3])); tetEdges.insert(key(tet[2], tet[3])); } PxU32 l = allEdges.size(); for (PxU32 i = 0; i < l; ++i) { SubdivisionEdge e = allEdges[i]; //Copy the edge here because we modify the list below and the reference could get invalid if the list resizes internally if (e.HasChildren()) continue; const PxU64 k = key(e.Start, e.End); if (!tetEdges.contains(k)) { allEdges.pushBack(SubdivisionEdge(e.Start, PxI32(points.size()))); allEdges.pushBack(SubdivisionEdge(PxI32(points.size()), e.End)); e.ChildA = PxI32(allEdges.size()) - 2; e.ChildB = PxI32(allEdges.size()) - 1; allEdges[i] = e; //Write the modified edge back since we did not capture a reference but made a copy points.pushBack((points[e.Start] + points[e.End]) * 0.5); intersection.clear(); intersectionOfSortedLists(pointToOriginalTriangle[e.Start], pointToOriginalTriangle[e.End], intersection); pointToOriginalTriangle.pushBack(intersection); success = true; } } } for (PxU32 i = 0; i < tets.size(); ++i) { Tetrahedron& tet = tets[i]; if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0) PxSwap(tet[0], tet[1]); } PxHashMap<PxU64, PxI32> edgesToSplit; numPointsBelongingToMultipleTriangles = PxI32(points.size()); //Split all tetrahedron edges that penetrate the triangle mesh's surface PxArray<BVHNode> tree; buildTree(triangles, points, tree); IntersectionFixingTraversalController controller(triangles, points, edgesToSplit, pointToOriginalTriangle); for (PxHashSet<PxU64>::Iterator iter = tetEdges.getIterator(); !iter.done(); ++iter) { const PxU64 edge = *iter; controller.update(edge); traverseBVH(tree.begin(), controller); } split(tets, points, edgesToSplit); //Remove all tetrahedra that are outside of the triangle mesh PxHashMap<PxU32, ClusterApproximationF64> clusters; precomputeClusterInformation(tree, triangles, points, clusters); PxArray<PxF64> windingNumbers; windingNumbers.resize(tets.size()); PxF64 sign = 1; PxF64 windingNumberSum = 0; for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; PxVec3d q = (points[tet[0]] + points[tet[1]] + points[tet[2]] + points[tet[3]]) * 0.25; PxF64 windingNumber = computeWindingNumber(tree, q, 2.0, clusters, triangles, points); windingNumbers[i] = windingNumber; windingNumberSum += windingNumber; } if (windingNumberSum < 0.0) sign = -1; //Array<PxVec3d> tetCenters; //tetCenters.resize(tets.size()); //for (PxU32 i = 0; i < tets.size(); ++i) //{ // const Tetrahedron& tet = tets[i]; // tetCenters[i] = (points[tet.A] + points[tet.B] + points[tet.c] + points[tet.D]) * 0.25; //} //multiWindingNumberMemoryFriendly(points, triangles, tetCenters, windingNumbers); finalTets.clear(); for (PxU32 i = 0; i < windingNumbers.size(); ++i) if (sign * windingNumbers[i] > 0.5) finalTets.pushBack(tets[i]); for (PxU32 i = 0; i < finalTets.size(); ++i) { Tetrahedron& tet = finalTets[i]; if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0) PxSwap(tet[0], tet[1]); } } void generateTetmesh(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles, PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets) { PxArray<SubdivisionEdge> allEdges; PxI32 numOriginalEdges; PxArray<PxArray<PxI32>> pointToOriginalTriangle; PxI32 numPointsBelongingToMultipleTriangles; generateTetmesh(trianglePoints, triangles, allEdges, numOriginalEdges, pointToOriginalTriangle, numPointsBelongingToMultipleTriangles, points, finalTets); } static const PxI32 tetFaces[4][3] = { {0, 1, 2}, {0, 3, 1}, {0, 2, 3}, {1, 3, 2} }; void extractTetmeshSurface(const PxArray<PxI32>& tets, PxArray<PxI32>& triangles) { PxHashMap<SortedTriangle, PxI32, TriangleHash> tris; for (PxU32 i = 0; i < tets.size(); i += 4) { for (PxU32 j = 0; j < 4; ++j) { SortedTriangle tri(tets[i + tetFaces[j][0]], tets[i + tetFaces[j][1]], tets[i + tetFaces[j][2]]); if (const PxPair<const SortedTriangle, PxI32>* ptr = tris.find(tri)) tris[tri] = ptr->second + 1; else tris.insert(tri, 1); } } triangles.clear(); for (PxHashMap<SortedTriangle, PxI32, TriangleHash>::Iterator iter = tris.getIterator(); !iter.done(); ++iter) { if (iter->second == 1) { triangles.pushBack(iter->first.A); if (iter->first.Flipped) { triangles.pushBack(iter->first.C); triangles.pushBack(iter->first.B); } else { triangles.pushBack(iter->first.B); triangles.pushBack(iter->first.C); } } } } struct TriangleWithTetLink { PxI32 triA; PxI32 triB; PxI32 triC; PxI32 tetId; TriangleWithTetLink(PxI32 triA_, PxI32 triB_, PxI32 triC_, PxI32 tetId_) : triA(triA_), triB(triB_), triC(triC_), tetId(tetId_) {} }; void extractTetmeshSurfaceWithTetLink(const PxArray<Tetrahedron>& tets, PxArray<TriangleWithTetLink>& surface) { PxHashMap<SortedTriangle, PxI32, TriangleHash> tris; for (PxU32 i = 0; i < tets.size(); ++i) { if (tets[i][0] < 0) continue; for (PxU32 j = 0; j < 4; ++j) { SortedTriangle tri(tets[i][tetFaces[j][0]], tets[i][tetFaces[j][1]], tets[i][tetFaces[j][2]]); if (tris.find(tri)) tris[tri] = -1; else tris.insert(tri, i); } } surface.clear(); for (PxHashMap<SortedTriangle, PxI32, TriangleHash>::Iterator iter = tris.getIterator(); !iter.done(); ++iter) { if (iter->second >= 0) surface.pushBack(TriangleWithTetLink(iter->first.A, iter->first.B, iter->first.C, iter->second)); } } //Removes vertices not referenced by any tetrahedron and maps the tet's indices to match the compacted vertex list void removeUnusedVertices(PxArray<PxVec3d>& vertices, PxArray<Tetrahedron>& tets, PxU32 numPointsToKeepAtBeginning = 0) { PxArray<PxI32> compressorMap; compressorMap.resize(vertices.size()); for (PxU32 i = 0; i < numPointsToKeepAtBeginning; ++i) compressorMap[i] = 0; for (PxU32 i = numPointsToKeepAtBeginning; i < compressorMap.size(); ++i) compressorMap[i] = -1; for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; compressorMap[tet[0]] = 0; compressorMap[tet[1]] = 0; compressorMap[tet[2]] = 0; compressorMap[tet[3]] = 0; } PxU32 indexer = 0; for (PxU32 i = 0; i < compressorMap.size(); ++i) { if (compressorMap[i] >= 0) { compressorMap[i] = indexer; vertices[indexer] = vertices[i]; indexer++; } } for (PxU32 i = 0; i < tets.size(); ++i) { Tetrahedron& tet = tets[i]; if (tet[0] < 0) continue; tet[0] = compressorMap[tet[0]]; tet[1] = compressorMap[tet[1]]; tet[2] = compressorMap[tet[2]]; tet[3] = compressorMap[tet[3]]; } if (indexer < vertices.size()) vertices.removeRange(indexer, vertices.size() - indexer); } PxF64 tetQuality(const PxVec3d& p0, const PxVec3d& p1, const PxVec3d& p2, const PxVec3d& p3) { const PxVec3d d0 = p1 - p0; const PxVec3d d1 = p2 - p0; const PxVec3d d2 = p3 - p0; const PxVec3d d3 = p2 - p1; const PxVec3d d4 = p3 - p2; const PxVec3d d5 = p1 - p3; PxF64 s0 = d0.magnitudeSquared(); PxF64 s1 = d1.magnitudeSquared(); PxF64 s2 = d2.magnitudeSquared(); PxF64 s3 = d3.magnitudeSquared(); PxF64 s4 = d4.magnitudeSquared(); PxF64 s5 = d5.magnitudeSquared(); PxF64 ms = (1.0 / 6.0) * (s0 + s1 + s2 + s3 + s4 + s5); PxF64 rms = PxSqrt(ms); PxF64 s = 12.0 / PxSqrt(2.0); PxF64 vol = PxAbs((1.0 / 6.0) * d0.dot(d1.cross(d2))); return s * vol / (rms * rms * rms); // Ideal tet has quality 1 } //The face must be one of the 4 faces from the tetrahedron, otherwise the result will be incorrect PX_FORCE_INLINE PxI32 getTetCornerOppositeToFace(const Tetrahedron& tet, PxI32 faceA, PxI32 faceB, PxI32 faceC) { return tet[0] + tet[1] + tet[2] + tet[3] - faceA - faceB - faceC; } void improveTetmesh(PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets, PxI32 numPointsBelongingToMultipleTriangles, PxArray<PxArray<PxI32>>& pointToOriginalTriangle, PxArray<PxArray<PxI32>>& edges, PxI32 numOriginalPoints) { DelaunayTetrahedralizer del(points, finalTets); bool success = true; //Collapse edges as long as we find collapsible edges //Only collaps edges such that the input triangle mesh's edges are preserved while (success) { success = false; PxArray<PxI32> adjTets; // Try to remove points that are on the interior of an original face for (PxU32 i = numPointsBelongingToMultipleTriangles; i < points.size(); ++i) { PxI32 tri = pointToOriginalTriangle[i][0]; adjTets.forceSize_Unsafe(0); del.collectTetsConnectedToVertex(i, adjTets); for (PxU32 j = 0; j < adjTets.size(); ++j) { const Tetrahedron& tet = del.tetrahedron(adjTets[j]); if (tet[0] < 0) continue; for (PxI32 k = 0; k < 4; ++k) { PxI32 id = tet[k]; if (id != PxI32(i) && contains(pointToOriginalTriangle[id], tri)) { if (del.canCollapseEdge(id, i)) { del.collapseEdge(id, i); break; } } } } } // Try to remove points that are on the edge between two original faces for (PxU32 i = 0; i < edges.size(); ++i) { PxArray<PxI32>& edge = edges[i]; if (edge.size() == 2) continue; for (PxU32 j = edge.size() - 1; j >= 1; --j) { const PxI32 remove = edge[j - 1]; const PxI32 keep = edge[j]; if (remove >= numOriginalPoints && del.canCollapseEdge(keep, remove)) { del.collapseEdge(keep, remove); success = true; edge.remove(j - 1); } } for (PxU32 j = 1; j < edge.size(); ++j) { const PxI32 keep = edge[j - 1]; const PxI32 remove = edge[j]; if (remove >= numOriginalPoints && del.canCollapseEdge(keep, remove)) { del.collapseEdge(keep, remove); success = true; edge.remove(j); --j; } } } } optimize(del, pointToOriginalTriangle, numOriginalPoints, points, finalTets, 10); //Remove sliver tets on surface success = true; while (success) { success = false; PxArray<TriangleWithTetLink> surface; extractTetmeshSurfaceWithTetLink(finalTets, surface); for (PxU32 i = 0; i < surface.size(); ++i) { const TriangleWithTetLink& link = surface[i]; const Tetrahedron& tet = finalTets[link.tetId]; if (tet[0] < 0) continue; PxI32 other = getTetCornerOppositeToFace(tet, link.triA, link.triB, link.triC); const PxVec3d& a = points[link.triA]; const PxVec3d& b = points[link.triB]; const PxVec3d& c = points[link.triC]; PxVec3d n = (b - a).cross(c - a); //n.normalize(); PxF64 planeD = -(n.dot(a)); PxF64 dist = PxAbs(signedDistancePointPlane(points[other], n, planeD)); if (dist < 1e-4 * n.magnitude()) { finalTets[link.tetId] = Tetrahedron(-1, -1, -1, -1); success = true; } } } PxU32 indexer = 0; for (PxU32 i = 0; i < finalTets.size(); ++i) { const Tetrahedron& tet = finalTets[i]; if (tet[0] >= 0) finalTets[indexer++] = tet; } if (indexer < finalTets.size()) finalTets.removeRange(indexer, finalTets.size() - indexer); removeUnusedVertices(points, finalTets, numOriginalPoints); for (PxU32 i = 0; i < finalTets.size(); ++i) { Tetrahedron& tet = finalTets[i]; if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0) PxSwap(tet[0], tet[1]); } } PxU32 removeDisconnectedIslands(PxI32* finalTets, PxU32 numTets) { //Detect islands PxArray<PxI32> neighborhood; buildNeighborhood(finalTets, numTets, neighborhood); PxArray<PxI32> tetColors; tetColors.resize(numTets, -1); PxU32 start = 0; PxI32 color = -1; PxArray<PxI32> stack; while (true) { stack.clear(); while (start < tetColors.size()) { if (tetColors[start] < 0) { stack.pushBack(start); ++color; tetColors[start] = color; break; } ++start; } if (start == tetColors.size()) break; while (stack.size() > 0) { PxI32 id = stack.popBack(); for (PxI32 i = 0; i < 4; ++i) { PxI32 a = neighborhood[4 * id + i]; PxI32 tetId = a >> 2; if (tetId >= 0 && tetColors[tetId] == -1) { stack.pushBack(tetId); tetColors[tetId] = color; } } } } if (color > 0) { //Found more than one island: Count number of tets per color PxArray<PxU32> numTetsPerColor; numTetsPerColor.resize(color + 1, 0); for (PxU32 i = 0; i < tetColors.size(); ++i) numTetsPerColor[tetColors[i]] += 1; PxI32 colorWithHighestTetCount = 0; for (PxU32 i = 1; i < numTetsPerColor.size(); ++i) if (numTetsPerColor[i] > numTetsPerColor[colorWithHighestTetCount]) colorWithHighestTetCount = i; PxU32 indexer = 0; for (PxU32 i = 0; i < numTets; ++i) { for (PxU32 j = 0; j < 4; ++j) finalTets[4 * indexer + j] = finalTets[4 * i + j]; if (tetColors[i] == colorWithHighestTetCount) ++indexer; } //if (indexer < finalTets.size()) // finalTets.removeRange(indexer, finalTets.size() - indexer); return numTets - indexer; } return 0; } void removeDisconnectedIslands(PxArray<Tetrahedron>& finalTets) { PxU32 numRemoveAtEnd = removeDisconnectedIslands(reinterpret_cast<PxI32*>(finalTets.begin()), finalTets.size()); if (numRemoveAtEnd > 0) finalTets.removeRange(finalTets.size() - numRemoveAtEnd, numRemoveAtEnd); } //Generates a tetmesh matching the surface of the specified triangle mesh exactly - might insert additional points on the //triangle mesh's surface. It will try to remove as many points inserted during construction as possible by applying an //edge collapse post processing step. void generateTetsWithCollapse(const PxArray<PxVec3d>& trianglePoints, const PxArray<Triangle>& triangles, PxArray<PxVec3d>& points, PxArray<Tetrahedron>& finalTets) { const PxI32 numOriginalPoints = PxI32(trianglePoints.size()); PxArray<PxArray<PxI32>> pointToOriginalTriangle; PxI32 numPointsBelongingToMultipleTriangles; PxArray<PxArray<PxI32>> edges; PxVec3d min, max; minMax(trianglePoints, min, max); DelaunayTetrahedralizer del(min, max); PxArray<Tetrahedron> tets; del.generateTetmeshEnforcingEdges(trianglePoints, triangles, edges, pointToOriginalTriangle, points, tets); PxHashSet<PxU64> tetEdges; numPointsBelongingToMultipleTriangles = points.size(); PxHashMap<PxU64, PxI32> edgesToSplit; IntersectionFixingTraversalController controller(triangles, points, edgesToSplit, pointToOriginalTriangle); PxArray<BVHNode> tree; buildTree(triangles, points, tree); PxI32 counter = 0; do { controller.resetRepeat(); tetEdges.clear(); for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; tetEdges.insert(key(tet[0], tet[1])); tetEdges.insert(key(tet[0], tet[2])); tetEdges.insert(key(tet[0], tet[3])); tetEdges.insert(key(tet[1], tet[2])); tetEdges.insert(key(tet[1], tet[3])); tetEdges.insert(key(tet[2], tet[3])); } edgesToSplit.clear(); for (PxHashSet<PxU64>::Iterator iter = tetEdges.getIterator(); !iter.done(); ++iter) { const PxU64 edge = *iter; controller.update(edge); traverseBVH(tree.begin(), controller); } split(tets, points, /*remaining*/edgesToSplit); ++counter; if (counter >= 2) break; } while (controller.shouldRepeat()); //Remove all tetrahedra that are outside of the triangle mesh PxHashMap<PxU32, ClusterApproximationF64> clusters; precomputeClusterInformation(tree, triangles, points, clusters); PxArray<PxF64> windingNumbers; windingNumbers.resize(tets.size()); PxF64 sign = 1; PxF64 windingNumberSum = 0; for (PxU32 i = 0; i < tets.size(); ++i) { const Tetrahedron& tet = tets[i]; PxVec3d q = (points[tet[0]] + points[tet[1]] + points[tet[2]] + points[tet[3]]) * 0.25; PxF64 windingNumber = computeWindingNumber(tree, q, 2.0, clusters, triangles, points); windingNumbers[i] = windingNumber; windingNumberSum += windingNumber; } if (windingNumberSum < 0.0) sign = -1; finalTets.clear(); for (PxU32 i = 0; i < windingNumbers.size(); ++i) if (sign * windingNumbers[i] > 0.5) finalTets.pushBack(tets[i]); for (PxU32 i = 0; i < finalTets.size(); ++i) { Tetrahedron& tet = finalTets[i]; if (tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]) < 0) PxSwap(tet[0], tet[1]); } improveTetmesh(points, finalTets, numPointsBelongingToMultipleTriangles, pointToOriginalTriangle, edges, numOriginalPoints); } bool convexTetmesh(PxArray<PxVec3d>& points, const PxArray<Triangle>& tris, PxArray<Tetrahedron>& tets) { PxVec3d centroid = PxVec3d(0.0, 0.0, 0.0); PxI32 counter = 0; for (PxU32 i = 0; i < points.size(); ++i) { const PxVec3d& p = points[i]; if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z)) continue; centroid += p; ++counter; } centroid /= counter; PxF64 volSign = 0; PxU32 centerIndex = points.size(); points.pushBack(centroid); tets.clear(); tets.reserve(tris.size()); for (PxU32 i = 0; i < tris.size(); ++i) { const Triangle& tri = tris[i]; Tetrahedron tet = Tetrahedron(centerIndex, tri[0], tri[1], tri[2]); const PxF64 vol = tetVolume(points[tet[0]], points[tet[1]], points[tet[2]], points[tet[3]]); if (vol < 0) PxSwap(tet[2], tet[3]); tets.pushBack(tet); if (volSign == 0) { volSign = vol > 0 ? 1 : -1; } else if (volSign * vol < 0) { points.remove(points.size() - 1); tets.clear(); return false; } } return true; } void convert(const PxArray<PxF32>& points, PxArray<PxVec3d>& result) { result.resize(points.size() / 3); for (PxU32 i = 0; i < result.size(); ++i) result[i] = PxVec3d(PxF64(points[3 * i]), PxF64(points[3 * i + 1]), PxF64(points[3 * i + 2])); } void convert(const PxArray<PxVec3d>& points, PxArray<PxF32>& result) { result.resize(3 * points.size()); for (PxU32 i = 0; i < points.size(); ++i) { const PxVec3d& p = points[i]; result[3 * i] = PxF32(p.x); result[3 * i + 1] = PxF32(p.y); result[3 * i + 2] = PxF32(p.z); } } void convert(const PxArray<PxVec3d>& points, PxArray<PxVec3>& result) { result.resize(points.size()); for (PxU32 i = 0; i < points.size(); ++i) { const PxVec3d& p = points[i]; result[i] = PxVec3(PxF32(p.x), PxF32(p.y), PxF32(p.z)); } } void convert(const PxBoundedData& points, PxArray<PxVec3d>& result) { result.resize(points.count); for (PxU32 i = 0; i < points.count; ++i) { const PxVec3& p = points.at<PxVec3>(i); result[i] = PxVec3d(PxF64(p.x), PxF64(p.y), PxF64(p.z)); } } void convert(const PxArray<PxI32>& indices, PxArray<Triangle>& result) { //static cast possible? result.resize(indices.size() / 3); for (PxU32 i = 0; i < result.size(); ++i) result[i] = Triangle(indices[3 * i], indices[3 * i + 1], indices[3 * i + 2]); } void convert(const PxBoundedData& indices, bool has16bitIndices, PxArray<Triangle>& result) { result.resize(indices.count); if (has16bitIndices) { for (PxU32 i = 0; i < indices.count; ++i) { const Triangle16& tri = indices.at<Triangle16>(i); result[i] = Triangle(tri[0], tri[1], tri[2]); } } else { for (PxU32 i = 0; i < indices.count; ++i) result[i] = indices.at<Triangle>(i); } } void convert(const PxArray<Tetrahedron>& tetrahedra, PxArray<PxU32>& result) { //static cast possible? result.resize(4 * tetrahedra.size()); for (PxU32 i = 0; i < tetrahedra.size(); ++i) { const Tetrahedron& t = tetrahedra[i]; result[4 * i] = t[0]; result[4 * i + 1] = t[1]; result[4 * i + 2] = t[2]; result[4 * i + 3] = t[3]; } } //Keep for debugging & verification void writeTets(const char* path, const PxArray<PxVec3>& tetPoints, const PxArray<PxU32>& tets) { FILE *fp; fp = fopen(path, "w+"); fprintf(fp, "# Tetrahedral mesh generated using\n\n"); fprintf(fp, "# %d vertices\n", tetPoints.size()); for (PxU32 i = 0; i < tetPoints.size(); ++i) { fprintf(fp, "v %f %f %f\n", PxF64(tetPoints[i].x), PxF64(tetPoints[i].y), PxF64(tetPoints[i].z)); } fprintf(fp, "\n"); fprintf(fp, "# %d tetrahedra\n", (tets.size() / 4)); for (PxU32 i = 0; i < tets.size(); i += 4) { fprintf(fp, "t %d %d %d %d\n", tets[i], tets[i + 1], tets[i + 2], tets[i + 3]); } fclose(fp); } //Keep for debugging & verification void writeOFF(const char* path, const PxArray<PxF32>& vertices, const PxArray<PxI32>& tris) { FILE *fp; fp = fopen(path, "w+"); fprintf(fp, "OFF\n"); fprintf(fp, "%d %d 0\n", vertices.size() / 3, tris.size() / 3); for (PxU32 i = 0; i < vertices.size(); i += 3) { fprintf(fp, "%f %f %f\n", PxF64(vertices[i]), PxF64(vertices[i + 1]), PxF64(vertices[i + 2])); } for (PxU32 i = 0; i < tris.size(); i += 3) { fprintf(fp, "3 %d %d %d\n", tris[i], tris[i + 1], tris[i + 2]); } fclose(fp); } //Keep for debugging & verification void writeSTL(const char* path, const PxArray<PxVec3>& vertices, const PxArray<PxI32>& tris) { FILE *fp; fp = fopen(path, "w+"); fprintf(fp, "solid mesh\n"); for (PxU32 i = 0; i < tris.size(); i += 3) { const PxI32* tri = &tris[i]; const PxVec3& a = vertices[tri[0]]; const PxVec3& b = vertices[tri[1]]; const PxVec3& c = vertices[tri[2]]; PxVec3 n = (b - a).cross(c - a); n.normalize(); fprintf(fp, "facet normal %f %f %f\n", PxF64(n.x), PxF64(n.y), PxF64(n.z)); fprintf(fp, "%s", "outer loop\n"); fprintf(fp, " vertex %f %f %f\n", PxF64(a.x), PxF64(a.y), PxF64(a.z)); fprintf(fp, " vertex %f %f %f\n", PxF64(b.x), PxF64(b.y), PxF64(b.z)); fprintf(fp, " vertex %f %f %f\n", PxF64(c.x), PxF64(c.y), PxF64(c.z)); fprintf(fp, "%s", "endloop\n"); fprintf(fp, "%s", "endfacet\n"); } fprintf(fp, "endsolid mesh\n"); fclose(fp); } void generateTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTriangles, const bool has16bitIndices, PxArray<PxVec3>& tetPoints, PxArray<PxU32>& finalTets) { //writeOFF("c:\\tmp\\debug.off", trianglePoints, triangles); PxArray<PxVec3d> points; convert(inputPoints, points); PxArray<Triangle> tris; convert(inputTriangles, has16bitIndices, tris); //PxTriangleMeshAnalysisResults result = validateTriangleMesh(inputPoints, inputTriangles, has16bitIndices); //PX_ASSERT(!(result & PxTriangleMeshAnalysisResult::eMESH_IS_INVALID)); PxArray<PxI32> map; MeshAnalyzer::mapDuplicatePoints<PxVec3d, PxF64>(points.begin(), points.size(), map); for (PxI32 i = 0; i < PxI32(points.size()); ++i) { if(map[i] != i) points[i] = PxVec3d(PxF64(NAN), PxF64(NAN), PxF64(NAN)); } for (PxU32 i = 0; i < tris.size(); ++i) { Triangle& t = tris[i]; for (PxU32 j = 0; j < 3; ++j) t[j] = map[t[j]]; if (t[0] == t[1] || t[1] == t[2] || t[0] == t[2]) { tris[i] = tris[tris.size() - 1]; tris.remove(tris.size() - 1); --i; } } PxArray<PxVec3d> tetPts; PxArray<Tetrahedron> tets; //if (makeTriOrientationConsistent(tris)) { if (convexTetmesh(points, tris, tets)) { tetPts.clear(); tetPts.reserve(tris.size()); for (PxU32 i = 0/*l*/; i < map.size(); ++i) { tetPts.pushBack(points[map[i]]); } for (PxU32 i = map.size(); i < points.size(); ++i) { tetPts.pushBack(points[i]); } } else { //Transform points such that the are located inside the unit cube PxVec3d min, max; minMax(points, min, max); PxVec3d size = max - min; PxF64 scaling = 1.0 / PxMax(size.x, PxMax(size.y, size.z)); //Add some noise to avoid geometric degeneracies Cm::RandomR250 r(0); PxF64 randomMagnitude = 1e-6; for (PxU32 i = 0; i < points.size(); ++i) { PxVec3d& p = points[i]; p = (p - min) * scaling; p.x += PxF64(r.rand(-0.5f, 0.5f)) * randomMagnitude; p.y += PxF64(r.rand(-0.5f, 0.5f)) * randomMagnitude; p.z += PxF64(r.rand(-0.5f, 0.5f)) * randomMagnitude; } generateTetsWithCollapse(points, tris, tetPts, tets); //Scale back to original size scaling = 1.0 / scaling; //for (PxU32 i = 0; i < l; ++i) // tetPts[i] = PxVec3d(trianglePoints[3 * i], trianglePoints[3 * i + 1], trianglePoints[3 * i + 2]); for (PxU32 i = 0; i < map.size(); ++i) { tetPts[i] = tetPts[map[i]]; } for (PxU32 i = 0; i < tetPts.size(); ++i) { tetPts[i] = tetPts[i] * scaling + min; } } } convert(tetPts, tetPoints); convert(tets, finalTets); //writeTets("c:\\tmp\\bottle.tet", tetPoints, finalTets); } PX_FORCE_INLINE PxF32 tetVolume(const PxVec3& a, const PxVec3& b, const PxVec3& c, const PxVec3& d) { return (-1.0f / 6.0f) * (a - d).dot((b - d).cross(c - d)); } void pointMasses(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxF32 density, PxArray<PxF32>& mass) { mass.resize(tetVerts.size()); for (PxU32 i = 0; i < mass.size(); ++i) mass[i] = 0.0f; //const PxVec3* verts = (PxVec3*)&tetVerts[0]; for (PxU32 i = 0; i < tets.size(); i += 4) { PxF32 weightDiv4 = density * 0.25f * PxAbs(tetVolume(tetVerts[tets[i]], tetVerts[tets[i + 1]], tetVerts[tets[i + 2]], tetVerts[tets[i + 3]])); mass[tets[i]] += weightDiv4; mass[tets[i + 1]] += weightDiv4; mass[tets[i + 2]] += weightDiv4; mass[tets[i + 3]] += weightDiv4; } } void restPoses(const PxArray<PxVec3>& tetVerts, const PxArray<PxU32>& tets, PxArray<PxMat33>& restPoses) { restPoses.resize(tets.size() / 4); //const PxVec3* verts = (PxVec3*)&tetVerts[0]; for (PxU32 i = 0; i < tets.size(); i += 4) { const PxVec3 u1 = tetVerts[tets[i + 1]] - tetVerts[tets[i]]; const PxVec3 u2 = tetVerts[tets[i + 2]] - tetVerts[tets[i]]; const PxVec3 u3 = tetVerts[tets[i + 3]] - tetVerts[tets[i]]; const PxMat33 m = PxMat33(u1, u2, u3); const PxMat33 rest = m.getInverse(); restPoses[i / 4] = rest; } } void tetFibers(const PxArray<PxVec3>& /*tetVerts*/, const PxArray<PxU32>& tets, PxArray<PxVec3>& tetFibers) { //Just use dummy data for the moment. Could solve a heat equation on the tetmesh to get better fibers but the boundary conditions of the heat quations need to be known tetFibers.resize(tets.size() / 4); for (PxU32 i = 0; i < tets.size(); i += 4) { tetFibers[i / 4] = PxVec3(1.0f, 0.f, 0.f); } } void minMax(const PxBoundedData& points, PxVec3& min, PxVec3& max) { min = PxVec3(PX_MAX_F32); max = PxVec3(-PX_MAX_F32); for (PxU32 i = 0; i < points.count; ++i) { const PxVec3& p = points.at<PxVec3>(i); if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z)) continue; max = max.maximum(p); min = min.minimum(p); } } const PxI32 xNegFace[4] = { 0, 1, 2, 3 }; const PxI32 xPosFace[4] = { 4, 5, 6, 7 }; const PxI32 yNegFace[4] = { 0, 1, 4, 5 }; const PxI32 yPosFace[4] = { 2, 3, 6, 7 }; const PxI32 zNegFace[4] = { 0, 2, 4, 6 }; const PxI32 zPosFace[4] = { 1, 3, 5, 7 }; const PxI32 offsetsX[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; const PxI32 offsetsY[8] = { 0, 0, 1, 1, 0, 0, 1, 1 }; const PxI32 offsetsZ[8] = { 0, 1, 0, 1, 0, 1, 0, 1 }; const PxI32 tets6PerVoxel[24] = { 0,1,6,2, 0,1,4,6, 1,4,6,5, 1,2,3,6, 1,3,7,6, 1,5,6,7 }; const PxU32 tets5PerVoxel[] = { 0, 6, 3, 5, 0, 1, 5, 3, 6, 7, 3, 5, 4, 5, 6, 0, 2, 3, 0, 6, 1, 7, 4, 2, 1, 0, 2, 4, 7, 6, 4, 2, 5, 4, 1, 7, 3, 2, 7, 1 }; struct VoxelNodes { PxI32 c[8]; // XYZ PxI32 c000() { return c[0]; } PxI32 c001() { return c[1]; } PxI32 c010() { return c[2]; } PxI32 c011() { return c[3]; } PxI32 c100() { return c[4]; } PxI32 c101() { return c[5]; } PxI32 c110() { return c[6]; } PxI32 c111() { return c[7]; } VoxelNodes(PxI32& nodeIndexer) { for (PxI32 i = 0; i < 8; ++i) c[i] = nodeIndexer++; } }; static const PxI32 neighborFacesAscending[4][3] = { { 0, 1, 2 }, { 0, 1, 3 }, { 0, 2, 3 }, { 1, 2, 3 } }; struct Vox { PxU32 mLocationX, mLocationY, mLocationZ; PxArray<PxI32> mTets; PxArray<PxArray<PxI32>> mClusters; PxArray<VoxelNodes> mNodes; PxU32 mBaseTetIndex; PxU32 mNumEmittedTets; Vox(PxU32 locationX, PxU32 locationY, PxU32 locationZ) : mLocationX(locationX), mLocationY(locationY), mLocationZ(locationZ), mBaseTetIndex(0), mNumEmittedTets(0) { } void operator=(const Vox &v) { mLocationX = v.mLocationX; mLocationY = v.mLocationY; mLocationZ = v.mLocationZ; mTets = v.mTets; mClusters = v.mClusters; mNodes = v.mNodes; mBaseTetIndex = v.mBaseTetIndex; mNumEmittedTets = v.mNumEmittedTets; } void initNodes(PxI32& nodeIndexer) { for (PxU32 i = 0; i < mClusters.size(); ++i) mNodes.pushBack(VoxelNodes(nodeIndexer)); } void buildLocalTetAdjacency(const PxBoundedData& tetrahedra, const PxArray<PxI32>& indices, PxArray<PxI32>& result) { PxU32 l = 4 * indices.size(); result.clear(); result.resize(l, -1); PxHashMap<PxU64, PxI32> faces(indices.size()); for (PxU32 i = 0; i < indices.size(); ++i) { Tetrahedron tet = tetrahedra.at<Tetrahedron>(indices[i]); if (tet[0] < 0) continue; tet.sort(); for (PxI32 j = 0; j < 4; ++j) { const PxU64 tri = ((PxU64(tet[neighborFacesAscending[j][0]])) << 42) | ((PxU64(tet[neighborFacesAscending[j][1]])) << 21) | ((PxU64(tet[neighborFacesAscending[j][2]]))); if (const PxPair<const PxU64, PxI32>* ptr = faces.find(tri)) { result[4 * i + j] = ptr->second; result[ptr->second] = 4 * i + j; faces.erase(tri); //Keep memory low } else faces.insert(tri, 4 * i + j); } } } void computeClusters(const PxBoundedData& tetrahedra) { PxArray<PxI32> adj; buildLocalTetAdjacency(tetrahedra, mTets, adj); PxArray<bool> done; done.resize(mTets.size(), false); PxU32 start = 0; PxArray<PxI32> stack; while (true) { stack.clear(); while (start < done.size()) { if (!done[start]) { stack.pushBack(start); done[start] = true; PxArray<PxI32> c; c.pushBack(mTets[start]); mClusters.pushBack(c); break; } ++start; } if (start == done.size()) break; while (stack.size() > 0) { PxI32 id = stack.popBack(); for (PxI32 i = 0; i < 4; ++i) { PxI32 a = adj[4 * id + i]; PxI32 tetId = a >> 2; if (tetId >= 0 && !done[tetId]) { stack.pushBack(tetId); done[tetId] = true; mClusters[mClusters.size() - 1].pushBack(mTets[tetId]); } } } } #if PX_DEBUG if (mClusters.size() > 1) { PxI32 abc = 0; ++abc; } #endif for (PxU32 i = 0; i < mClusters.size(); ++i) PxSort(mClusters[i].begin(), mClusters[i].size()); } void embed(PxArray<PxReal>& embeddingError, PxI32 id, const PxVec3& p, const PxU32 startIndex, const PxU32 endIndex, const Tetrahedron* voxelTets, const PxArray<PxVec3>& voxelPoints, PxI32* embeddings) { //PxVec4 best(1000, 1000, 1000, 1000); PxReal bestError = embeddingError[id]; PxI32 bestIndex = -1; for (PxU32 i = startIndex; i < endIndex; ++i) { const Tetrahedron& candidate = voxelTets[i]; PxVec4 bary; computeBarycentric(voxelPoints[candidate[0]], voxelPoints[candidate[1]], voxelPoints[candidate[2]], voxelPoints[candidate[3]], p, bary); const PxReal eps = 0; if ((bary.x >= -eps && bary.x <= 1.f + eps) && (bary.y >= -eps && bary.y <= 1.f + eps) && (bary.z >= -eps && bary.z <= 1.f + eps) && (bary.w >= -eps && bary.w <= 1.f + eps)) { embeddings[id] = i; embeddingError[id] = 0; return; } else { PxReal error = 0; PxReal min = PxMin(PxMin(bary.x, bary.y), PxMin(bary.z, bary.w)); if (min < 0) error = -min; PxReal max = PxMax(PxMax(bary.x, bary.y), PxMax(bary.z, bary.w)); if (max > 1) { PxReal e = max - 1; if (e > error) error = e; } if (error < bestError) { //best = bary; bestError = error; bestIndex = i; } } } if (bestIndex >= 0) { embeddings[id] = bestIndex; embeddingError[id] = bestError; } } bool embed(const PxU32 anchorNodeIndex, const PxBoundedData& colTets, PxI32 numTetsPerVoxel, PxArray<PxReal>& embeddingError, PxI32 id, const PxVec3& p, const Tetrahedron* voxelTets, const PxArray<PxVec3>& voxelPoints, PxI32* embeddings) { if (mClusters.size() > 1) { for (PxU32 i = 0; i < mClusters.size(); ++i) { const PxArray<PxI32>& c = mClusters[i]; for (PxU32 j = 0; j < c.size(); ++j) { const Tetrahedron& candidate = colTets.at<Tetrahedron>(c[j]); if (candidate.contains(anchorNodeIndex)) { embed(embeddingError, id, p, mBaseTetIndex + i * numTetsPerVoxel, mBaseTetIndex + (i + 1) * numTetsPerVoxel, voxelTets, voxelPoints, embeddings); return true; } } } return false; } embed(embeddingError, id, p, mBaseTetIndex, mBaseTetIndex + numTetsPerVoxel, voxelTets, voxelPoints, embeddings); return true; } void embed(const PxBoundedData& colPoints, const PxBoundedData& colTets, PxI32 numTetsPerVoxel, PxArray<PxReal>& embeddingError, PxI32 id, const PxVec3& p, const Tetrahedron* voxelTets, const PxArray<PxVec3>& voxelPoints, PxI32* embeddings) { PxReal bestError = embeddingError[id]; PxI32 bestIndex = 0; if (mClusters.size() > 1) { for (PxU32 i = 0; i < mClusters.size(); ++i) { const PxArray<PxI32>& c = mClusters[i]; for (PxU32 j = 0; j < c.size(); ++j) { const Tetrahedron& candidate = colTets.at<Tetrahedron>(c[j]); PxVec4 bary; computeBarycentric(colPoints.at< PxVec3>(candidate[0]), colPoints.at<PxVec3>(candidate[1]), colPoints.at<PxVec3>(candidate[2]), colPoints.at<PxVec3>(candidate[3]), p, bary); const PxReal eps = 0; if ((bary.x >= -eps && bary.x <= 1.f + eps) && (bary.y >= -eps && bary.y <= 1.f + eps) && (bary.z >= -eps && bary.z <= 1.f + eps) && (bary.w >= -eps && bary.w <= 1.f + eps)) { embed(embeddingError, id, p, mBaseTetIndex + i * numTetsPerVoxel, mBaseTetIndex + (i + 1) * numTetsPerVoxel, voxelTets, voxelPoints, embeddings); return; } else { PxReal error = 0; PxReal min = PxMin(PxMin(bary.x, bary.y), PxMin(bary.z, bary.w)); if (min < 0) error = -min; PxReal max = PxMax(PxMax(bary.x, bary.y), PxMax(bary.z, bary.w)); if (max > 1) { PxReal e = max - 1; if (e > error) error = e; } if (error < bestError) { //best = bary; bestError = error; bestIndex = i; } } } } } if (bestIndex >= 0) { embed(embeddingError, id, p, mBaseTetIndex + bestIndex * numTetsPerVoxel, mBaseTetIndex + (bestIndex + 1) * numTetsPerVoxel, voxelTets, voxelPoints, embeddings); } } void emitTets(PxArray<PxU32>& voxelTets, PxArray<PxVec3>& voxelPoints, PxI32* embeddings,/* UnionFind uf,*/ const PxVec3& voxelBlockMin, const PxVec3& voxelSize, const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxArray<PxReal>& embeddingError, const PxI32& numTetsPerVoxel) { for (PxU32 i = 0; i < mNodes.size(); ++i) { const VoxelNodes& n = mNodes[i]; for (PxI32 j = 0; j < 8; ++j) { PxI32 id = n.c[j]; voxelPoints[id] = PxVec3(voxelBlockMin.x + (mLocationX + offsetsX[j]) * voxelSize.x, voxelBlockMin.y + (mLocationY + offsetsY[j]) * voxelSize.y, voxelBlockMin.z + (mLocationZ + offsetsZ[j]) * voxelSize.z); } //Emit 5 or 6 tets if (numTetsPerVoxel == 5) { PxI32 flip = (mLocationX + mLocationY + mLocationZ) % 2; PxI32 offset = flip * 20; for (PxI32 j = 0; j < 20; j += 4) { PxI32 a = n.c[tets5PerVoxel[j + 0 + offset]]; PxI32 b = n.c[tets5PerVoxel[j + 1 + offset]]; PxI32 c = n.c[tets5PerVoxel[j + 2 + offset]]; PxI32 d = n.c[tets5PerVoxel[j + 3 + offset]]; //Tetrahedron tet(a, b, c, d); //voxelTets.pushBack(tet); voxelTets.pushBack(a); voxelTets.pushBack(b); voxelTets.pushBack(c); voxelTets.pushBack(d); } } else { for (PxI32 j = 0; j < 24; j += 4) { PxI32 a = n.c[tets6PerVoxel[j + 0]]; PxI32 b = n.c[tets6PerVoxel[j + 1]]; PxI32 c = n.c[tets6PerVoxel[j + 2]]; PxI32 d = n.c[tets6PerVoxel[j + 3]]; //Tetrahedron tet(a, b, c, d); //voxelTets.pushBack(tet); voxelTets.pushBack(a); voxelTets.pushBack(b); voxelTets.pushBack(c); voxelTets.pushBack(d); } } if (embeddings) { PxVec3 min(voxelBlockMin.x + (mLocationX + 0) * voxelSize.x, voxelBlockMin.y + (mLocationY + 0) * voxelSize.y, voxelBlockMin.z + (mLocationZ + 0) * voxelSize.z); PxVec3 max(voxelBlockMin.x + (mLocationX + 1) * voxelSize.x, voxelBlockMin.y + (mLocationY + 1) * voxelSize.y, voxelBlockMin.z + (mLocationZ + 1) * voxelSize.z); PxBounds3 box(min, max); box.fattenFast(1e-5f); //Embedding const PxArray<PxI32>& cluster = mClusters[i]; Tetrahedron* voxelTetPtr = reinterpret_cast<Tetrahedron*>(voxelTets.begin()); for (PxU32 j = 0; j < cluster.size(); ++j) { const Tetrahedron& tet = inputTets.at<Tetrahedron>(cluster[j]); const PxU32 end = voxelTets.size() / 4; const PxU32 start = end - numTetsPerVoxel; for (PxU32 k = 0; k < 4; ++k) if (embeddingError[tet[k]] > 0 && box.contains(inputPoints.at<PxVec3>(tet[k]))) embed(embeddingError, tet[k], inputPoints.at<PxVec3>(tet[k]), start, end, voxelTetPtr, voxelPoints, embeddings); } } } } void mapNodes(UnionFind& uf) { for (PxU32 i = 0; i < mNodes.size(); ++i) { VoxelNodes& n = mNodes[i]; for (PxI32 j = 0; j < 8; ++j) n.c[j] = uf.getSetNr(n.c[j]); mNodes[i] = n; } } }; struct Int3 { PxU32 x; PxU32 y; PxU32 z; }; #if PX_LINUX #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmisleading-indentation" #endif void getVoxelRange(const PxBoundedData& points, Tetrahedron tet, const PxVec3& voxelBlockMin, const PxVec3& voxelSize, PxU32 numVoxelsX, PxU32 numVoxelsY, PxU32 numVoxelsZ, Int3& min, Int3& max, PxBounds3& box, PxReal enlarge) { PxVec3 mi = points.at<PxVec3>(tet[0]); PxVec3 ma = mi; for (PxI32 i = 1; i < 4; ++i) { const PxVec3& p = points.at<PxVec3>(tet[i]); if (p.x < mi.x) mi.x = p.x; if (p.y < mi.y) mi.y = p.y; if (p.z < mi.z) mi.z = p.z; if (p.x > ma.x) ma.x = p.x; if (p.y > ma.y) ma.y = p.y; if (p.z > ma.z) ma.z = p.z; } mi.x -= enlarge; mi.y -= enlarge; mi.z -= enlarge; ma.x += enlarge; ma.y += enlarge; ma.z += enlarge; box.minimum = mi; box.maximum = ma; min.x = PxU32((mi.x - voxelBlockMin.x) / voxelSize.x); min.y = PxU32((mi.y - voxelBlockMin.y) / voxelSize.y); min.z = PxU32((mi.z - voxelBlockMin.z) / voxelSize.z); max.x = PxU32((ma.x - voxelBlockMin.x) / voxelSize.x); max.y = PxU32((ma.y - voxelBlockMin.y) / voxelSize.y); max.z = PxU32((ma.z - voxelBlockMin.z) / voxelSize.z); min.x = PxMax(0u, min.x); min.y = PxMax(0u, min.y); min.z = PxMax(0u, min.z); max.x = PxMin(numVoxelsX - 1, max.x); max.y = PxMin(numVoxelsY - 1, max.y); max.z = PxMin(numVoxelsZ - 1, max.z); } #if PX_LINUX #pragma GCC diagnostic pop #endif PX_FORCE_INLINE void connect(const VoxelNodes& voxelNodesA, const PxI32* faceVoxelA, const VoxelNodes& voxelNodesB, const PxI32* faceVoxelB, UnionFind& uf) { for (PxI32 i = 0; i < 4; ++i) uf.makeSet(voxelNodesA.c[faceVoxelA[i]], voxelNodesB.c[faceVoxelB[i]]); } PX_FORCE_INLINE bool intersectionOfSortedListsNotEmpty(const PxArray<PxI32>& sorted1, const PxArray<PxI32>& sorted2) { PxU32 a = 0; PxU32 b = 0; while (a < sorted1.size() && b < sorted2.size()) { if (sorted1[a] == sorted2[b]) return true; else if (sorted1[a] > sorted2[b]) ++b; else ++a; } return false; } void connect(const Vox& voxelA, const PxI32* faceVoxelA, const Vox& voxelB, const PxI32* faceVoxelB, UnionFind& uf) { for (PxU32 i = 0; i < voxelA.mClusters.size(); ++i) { const PxArray<PxI32>& clusterA = voxelA.mClusters[i]; for (PxU32 j = 0; j < voxelB.mClusters.size(); ++j) { const PxArray<PxI32>& clusterB = voxelB.mClusters[j]; if (intersectionOfSortedListsNotEmpty(clusterA, clusterB)) connect(voxelA.mNodes[i], faceVoxelA, voxelB.mNodes[j], faceVoxelB, uf); } } } PX_FORCE_INLINE PxU32 cell(PxU32 x, PxU32 y, PxU32 z, PxU32 numX, PxU32 numXtimesNumY) { return x + y * numX + z * numXtimesNumY; } Int3 getCell(const PxVec3& p, const PxVec3& voxelBlockMin, const PxVec3& voxelSize, const PxU32 numVoxelsX, const PxU32 numVoxelsY, const PxU32 numVoxelsZ) { Int3 cell; PxVec3 c = p - voxelBlockMin; cell.x = PxU32(c.x / voxelSize.x); cell.y = PxU32(c.y / voxelSize.y); cell.z = PxU32(c.z / voxelSize.z); if (cell.x >= numVoxelsX) cell.x = numVoxelsX - 1; if (cell.y >= numVoxelsY) cell.y = numVoxelsY - 1; if (cell.z >= numVoxelsZ) cell.z = numVoxelsZ - 1; return cell; } PX_FORCE_INLINE PxReal aabbDistanceSquaredToPoint(const PxVec3& min, const PxVec3& max, const PxVec3& p) { PxReal sqDist = 0.0f; if (p.x < min.x) sqDist += (min.x - p.x) * (min.x - p.x); if (p.x > max.x) sqDist += (p.x - max.x) * (p.x - max.x); if (p.y < min.y) sqDist += (min.y - p.y) * (min.y - p.y); if (p.y > max.y) sqDist += (p.y - max.y) * (p.y - max.y); if (p.z < min.z) sqDist += (min.z - p.z) * (min.z - p.z); if (p.z > max.z) sqDist += (p.z - max.z) * (p.z - max.z); return sqDist; } PxI32 getVoxelId(PxArray<PxI32> voxelIds, const PxVec3& p, const PxVec3& voxelBlockMin, const PxVec3& voxelSize, const PxU32 numVoxelsX, const PxU32 numVoxelsY, const PxU32 numVoxelsZ) { PxVec3 pt = p - voxelBlockMin; PxU32 ix = PxU32(PxMax(0.0f, pt.x / voxelSize.x)); PxU32 iy = PxU32(PxMax(0.0f, pt.y / voxelSize.y)); PxU32 iz = PxU32(PxMax(0.0f, pt.z / voxelSize.z)); if (ix >= numVoxelsX) ix = numVoxelsX - 1; if (iy >= numVoxelsY) iy = numVoxelsY - 1; if (iz >= numVoxelsZ) iz = numVoxelsZ - 1; PxU32 id = cell(ix, iy, iz, numVoxelsX, numVoxelsX * numVoxelsY); if (voxelIds[id] >= 0) return voxelIds[id]; const PxI32 numOffsets = 6; const PxI32 offsets[numOffsets][3] = { {-1, 0, 0}, {+1, 0, 0}, {0, -1, 0}, {0, +1, 0}, {0, 0, -1}, {0, 0, +1} }; PxReal minDist = FLT_MAX; for (PxU32 i = 0; i < numOffsets; ++i) { const PxI32* o = offsets[i]; PxI32 newX = ix + o[0]; PxI32 newY = iy + o[1]; PxI32 newZ = iz + o[2]; if (newX >= 0 && newX < PxI32(numVoxelsX) && newY >= 0 && newY < PxI32(numVoxelsY) && newZ >= 0 && newZ < PxI32(numVoxelsZ)) { PxU32 candidate = cell(newX, newY, newZ, numVoxelsX, numVoxelsX * numVoxelsY); if (voxelIds[candidate] >= 0) { PxVec3 min(voxelBlockMin.x + newX * voxelSize.x, voxelBlockMin.y + newY * voxelSize.y, voxelBlockMin.z + newZ * voxelSize.z); PxVec3 max = min + voxelSize; PxReal d = aabbDistanceSquaredToPoint(min, max, p); if (d < minDist) { id = candidate; minDist = d; } } } } PxI32 result = voxelIds[id]; if (result < 0) { //Search the closest voxel over all voxels minDist = FLT_MAX; for (PxU32 newX = 0; newX < numVoxelsX; ++newX) for (PxU32 newY = 0; newY < numVoxelsY; ++newY) for (PxU32 newZ = 0; newZ < numVoxelsZ; ++newZ) { PxU32 candidate = cell(newX, newY, newZ, numVoxelsX, numVoxelsX * numVoxelsY); if (voxelIds[candidate] >= 0) { PxVec3 min(voxelBlockMin.x + newX * voxelSize.x, voxelBlockMin.y + newY * voxelSize.y, voxelBlockMin.z + newZ * voxelSize.z); PxVec3 max = min + voxelSize; PxReal d = aabbDistanceSquaredToPoint(min, max, p); if (d < minDist) { id = candidate; minDist = d; } } } } result = voxelIds[id]; if (result < 0) return 0; return result; } void generateVoxelTetmesh(const PxBoundedData& inputPointsOrig, const PxBoundedData& inputTets, PxU32 numVoxelsX, PxU32 numVoxelsY, PxU32 numVoxelsZ, PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel) { if (inputTets.count == 0) return; //No input, so there is no basis for creating an output PxU32 xy = numVoxelsX * numVoxelsY; PxVec3 origMin, origMax; minMax(inputPointsOrig, origMin, origMax); PxVec3 size = origMax - origMin; PxReal scaling = 1.0f / PxMax(size.x, PxMax(size.y, size.z)); PxArray<PxVec3> scaledPoints; scaledPoints.resize(inputPointsOrig.count); for (PxU32 i = 0; i < inputPointsOrig.count; ++i) { PxVec3 p = inputPointsOrig.at<PxVec3>(i); scaledPoints[i] = (p - origMin) * scaling; } PxBoundedData inputPoints; inputPoints.count = inputPointsOrig.count; inputPoints.stride = sizeof(PxVec3); inputPoints.data = scaledPoints.begin(); PxVec3 voxelBlockMin, voxelBlockMax; minMax(inputPoints, voxelBlockMin, voxelBlockMax); PxVec3 voxelBlockSize = voxelBlockMax - voxelBlockMin; PxVec3 voxelSize(voxelBlockSize.x / numVoxelsX, voxelBlockSize.y / numVoxelsY, voxelBlockSize.z / numVoxelsZ); PxArray<PxI32> voxelIds; voxelIds.resize(numVoxelsX * numVoxelsY * numVoxelsZ, -1); PxArray<Vox> voxels; for(PxU32 i=0;i< inputTets.count;++i) { Int3 min, max; const Tetrahedron& tet = inputTets.at<Tetrahedron>(i); PxBounds3 tetBox; getVoxelRange(inputPoints, tet, voxelBlockMin, voxelSize, numVoxelsX, numVoxelsY, numVoxelsZ, min, max, tetBox, 1.e-4f); //bool success = false; for (PxU32 x = min.x; x <= max.x; ++x) { for (PxU32 y = min.y; y <= max.y; ++y) { for (PxU32 z = min.z; z <= max.z; ++z) { PxBounds3 box(PxVec3(voxelBlockMin.x + x * voxelSize.x, voxelBlockMin.y + y * voxelSize.y, voxelBlockMin.z + z * voxelSize.z), PxVec3(voxelBlockMin.x + (x + 1) * voxelSize.x, voxelBlockMin.y + (y + 1) * voxelSize.y, voxelBlockMin.z + (z + 1) * voxelSize.z)); if (intersectTetrahedronBox(inputPoints.at<PxVec3>(tet[0]), inputPoints.at<PxVec3>(tet[1]), inputPoints.at<PxVec3>(tet[2]), inputPoints.at<PxVec3>(tet[3]), box)) { //success = true; PxI32 voxelId = voxelIds[cell(x, y, z, numVoxelsX, xy)]; if (voxelId < 0) { voxelId = voxels.size(); voxelIds[cell(x, y, z, numVoxelsX, xy)] = voxelId; voxels.pushBack(Vox(x, y, z)); } Vox& v = voxels[voxelId]; v.mTets.pushBack(i); } } } } /*if (!success) { PxI32 abc = 0; ++abc; }*/ } PxI32 nodeIndexer = 0; for(PxU32 i=0;i<voxels.size();++i) { voxels[i].computeClusters(inputTets); } for (PxU32 i = 0; i < voxels.size(); ++i) { voxels[i].initNodes(nodeIndexer); } UnionFind uf(nodeIndexer); for (PxU32 i = 0; i < voxels.size(); ++i) { Vox& v = voxels[i]; if (v.mLocationX > 0 && voxelIds[cell(v.mLocationX - 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)] >= 0) connect(voxels[voxelIds[cell(v.mLocationX - 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)]], xPosFace, v, xNegFace, uf); if (v.mLocationX < numVoxelsX - 1 && voxelIds[cell(v.mLocationX + 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)] >= 0) connect(v, xPosFace, voxels[voxelIds[cell(v.mLocationX + 1, v.mLocationY, v.mLocationZ, numVoxelsX, xy)]], xNegFace, uf); if (v.mLocationY > 0 && voxelIds[cell(v.mLocationX, v.mLocationY - 1, v.mLocationZ, numVoxelsX, xy)] >= 0) connect(voxels[voxelIds[cell(v.mLocationX, v.mLocationY - 1, v.mLocationZ, numVoxelsX, xy)]], yPosFace, v, yNegFace, uf); if (v.mLocationY < numVoxelsY - 1 && voxelIds[cell(v.mLocationX, v.mLocationY + 1, v.mLocationZ, numVoxelsX, xy)] >= 0) connect(v, yPosFace, voxels[voxelIds[cell(v.mLocationX, v.mLocationY + 1, v.mLocationZ, numVoxelsX, xy)]], yNegFace, uf); if (v.mLocationZ > 0 && voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ - 1, numVoxelsX, xy)] >= 0) connect(voxels[voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ - 1, numVoxelsX, xy)]], zPosFace, v, zNegFace, uf); if (v.mLocationZ < numVoxelsZ - 1 && voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ + 1, numVoxelsX, xy)] >= 0) connect(v, zPosFace, voxels[voxelIds[cell(v.mLocationX, v.mLocationY, v.mLocationZ + 1, numVoxelsX, xy)]], zNegFace, uf); } PxI32 numVertices = uf.computeSetNrs(); for (PxU32 i = 0; i < voxels.size(); ++i) { voxels[i].mapNodes(uf); } //const PxU32 numTetsPerVoxel = 5; voxelPoints.resize(numVertices); //intputPointToOutputTetIndex.resize(numInputPoints); voxelTets.clear(); PxArray<PxReal> embeddingError; embeddingError.resize(inputPoints.count, 1000); for (PxU32 i = 0; i < voxels.size(); ++i) { Vox& v = voxels[i]; v.mBaseTetIndex = voxelTets.size() / 4; v.emitTets(voxelTets, voxelPoints, intputPointToOutputTetIndex, voxelBlockMin, voxelSize, inputPoints, inputTets, embeddingError, numTetsPerVoxel); v.mNumEmittedTets = voxelTets.size() / 4 - v.mBaseTetIndex; } #if PX_DEBUG PxArray<bool> pointUsed; pointUsed.resize(inputPoints.count, false); for (PxU32 i = 0; i < inputTets.count; ++i) { const Tetrahedron& tet = inputTets.at<Tetrahedron>(i); for (PxU32 j = 0; j < 4; ++j) pointUsed[tet[j]] = true; } #endif Tetrahedron* voxelTetPtr = reinterpret_cast<Tetrahedron*>(voxelTets.begin()); for (PxU32 i = 0; i < embeddingError.size(); ++i) { if (embeddingError[i] == 1000) { const PxVec3& p = inputPoints.at<PxVec3>(i); PxI32 voxelId = getVoxelId(voxelIds, p, voxelBlockMin, voxelSize, numVoxelsX, numVoxelsY, numVoxelsZ); PX_ASSERT(voxelId >= 0); Vox& vox = voxels[voxelId]; if (anchorNodeIndices && anchorNodeIndices[i] < inputPoints.count) { if (!vox.embed(anchorNodeIndices[i], inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex)) { PxVec3 pt = inputPoints.at<PxVec3>(anchorNodeIndices[i]); voxelId = getVoxelId(voxelIds, pt, voxelBlockMin, voxelSize, numVoxelsX, numVoxelsY, numVoxelsZ); PX_ASSERT(voxelId >= 0); Vox& v = voxels[voxelId]; if (!v.embed(anchorNodeIndices[i], inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex)) v.embed(inputPoints, inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex); } } else vox.embed(inputPoints, inputTets, numTetsPerVoxel, embeddingError, i, p, voxelTetPtr, voxelPoints, intputPointToOutputTetIndex); } } //Scale back to original size scaling = 1.0f / scaling; for(PxU32 i=0;i<voxelPoints.size();++i) voxelPoints[i] = voxelPoints[i] * scaling + origMin; } void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxReal voxelEdgeLength, PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel) { PxVec3 min, max; minMax(inputPoints, min, max); PxVec3 blockSize = max - min; PxU32 numCellsX = PxMax(1u, PxU32(blockSize.x / voxelEdgeLength + 0.5f)); PxU32 numCellsY = PxMax(1u, PxU32(blockSize.y / voxelEdgeLength + 0.5f)); PxU32 numCellsZ = PxMax(1u, PxU32(blockSize.z / voxelEdgeLength + 0.5f)); generateVoxelTetmesh(inputPoints, inputTets, numCellsX, numCellsY, numCellsZ, voxelPoints, voxelTets, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel); } void generateVoxelTetmesh(const PxBoundedData& inputPoints, const PxBoundedData& inputTets, PxU32 numVoxelsAlongLongestBoundingBoxAxis, PxArray<PxVec3>& voxelPoints, PxArray<PxU32>& voxelTets, PxI32* intputPointToOutputTetIndex, const PxU32* anchorNodeIndices, PxU32 numTetsPerVoxel) { PxVec3 min, max; minMax(inputPoints, min, max); PxVec3 size = max - min; PxReal voxelEdgeLength = PxMax(size.x, PxMax(size.y, size.z)) / numVoxelsAlongLongestBoundingBoxAxis; generateVoxelTetmesh(inputPoints, inputTets, voxelEdgeLength, voxelPoints, voxelTets, intputPointToOutputTetIndex, anchorNodeIndices, numTetsPerVoxel); } static PxReal computeMeshVolume(const PxArray<PxVec3>& points, const PxArray<Triangle>& triangles) { PxVec3 center(0, 0, 0); for (PxU32 i = 0; i < points.size(); ++i) { center += points[i]; } center /= PxReal(points.size()); PxReal volume = 0; for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; volume += tetVolume(points[tri[0]], points[tri[1]], points[tri[2]], center); } return PxAbs(volume); } static PxTriangleMeshAnalysisResults validateConnectivity(const PxArray<Triangle>& triangles) { PxArray<bool> flip; PxHashMap<PxU64, PxI32> edges; PxArray<PxArray<PxU32>> connectedTriangleGroups; if (!MeshAnalyzer::buildConsistentTriangleOrientationMap(triangles.begin(), triangles.size(), flip, edges, connectedTriangleGroups)) return PxTriangleMeshAnalysisResult::Enum::eEDGE_SHARED_BY_MORE_THAN_TWO_TRIANGLES; PxTriangleMeshAnalysisResults result = PxTriangleMeshAnalysisResult::eVALID; for (PxHashMap<PxU64, PxI32>::Iterator iter = edges.getIterator(); !iter.done(); ++iter) if (iter->second >= 0) { result = result | PxTriangleMeshAnalysisResult::eOPEN_BOUNDARIES; break; } for (PxU32 i = 0; i < flip.size(); ++i) { if (flip[i]) { return result | PxTriangleMeshAnalysisResult::Enum::eINCONSISTENT_TRIANGLE_ORIENTATION; } } return result; } static bool trianglesIntersect(const Triangle& tri1, const Triangle& tri2, const PxArray<PxVec3>& points) { int counter = 0; if (tri1.contains(tri2[0])) ++counter; if (tri1.contains(tri2[1])) ++counter; if (tri1.contains(tri2[2])) ++counter; if (counter > 0) return false; //Triangles share at leat one point return Gu::trianglesIntersect(points[tri1[0]], points[tri1[1]], points[tri1[2]], points[tri2[0]], points[tri2[1]], points[tri2[2]]); } static PxBounds3 triBounds(const PxArray<PxVec3>& points, const Triangle& tri, PxReal enlargement) { PxBounds3 box = PxBounds3::empty(); box.include(points[tri[0]]); box.include(points[tri[1]]); box.include(points[tri[2]]); box.fattenFast(enlargement); return box; } static bool meshContainsSelfIntersections(const PxArray<PxVec3>& points, const PxArray<Triangle>& triangles) { PxReal enlargement = 1e-6f; AABBTreeBounds boxes; boxes.init(triangles.size()); for (PxU32 i = 0; i < triangles.size(); ++i) { boxes.getBounds()[i] = triBounds(points, triangles[i], enlargement); } PxArray<Gu::BVHNode> tree; Gu::buildAABBTree(triangles.size(), boxes, tree); PxArray<PxI32> candidateTriangleIndices; IntersectionCollectingTraversalController tc(candidateTriangleIndices); for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; PxBounds3 box = triBounds(points, tri, enlargement); tc.reset(box); traverseBVH(tree, tc); for (PxU32 j = 0; j < candidateTriangleIndices.size(); ++j) { Triangle tri2 = triangles[j]; if (trianglesIntersect(tri, tri2, points)) return true; } } return false; } static PxReal maxDotProduct(const PxVec3& a, const PxVec3& b, const PxVec3& c) { const PxVec3 ab = b - a; const PxVec3 ac = c - a; const PxVec3 bc = c - b; PxReal maxDot = ab.dot(ac) / PxSqrt(ab.magnitudeSquared() * ac.magnitudeSquared()); PxReal dot = ac.dot(bc) / PxSqrt(ac.magnitudeSquared() * bc.magnitudeSquared()); if (dot > maxDot) maxDot = dot; dot = -ab.dot(bc) / PxSqrt(ab.magnitudeSquared() * bc.magnitudeSquared()); if (dot > maxDot) maxDot = dot; return maxDot; } static PxReal minimumAngle(const PxArray<PxVec3>& points, const PxArray<Triangle>& triangles) { PxReal maxDot = -1; for (PxU32 i = 0; i < triangles.size(); ++i) { const Triangle& tri = triangles[i]; PxReal dot = maxDotProduct(points[tri[0]], points[tri[1]], points[tri[2]]); if (dot > maxDot) maxDot = dot; } if (maxDot > 1) maxDot = 1; return PxAcos(maxDot); //Converts to the minimal angle } PxTetrahedronMeshAnalysisResults validateTetrahedronMesh(const PxBoundedData& points, const PxBoundedData& tetrahedra, const bool has16BitIndices, const PxReal minTetVolumeThreshold) { PxTetrahedronMeshAnalysisResults result = PxTetrahedronMeshAnalysisResult::eVALID; PxArray<Tetrahedron> tets; tets.reserve(tetrahedra.count); for (PxU32 i = 0; i < tetrahedra.count; ++i) { Tetrahedron t; if (has16BitIndices) { Tetrahedron16 t16 = tetrahedra.at<Tetrahedron16>(i); t = Tetrahedron(t16[0], t16[1], t16[2], t16[3]); } else t = tetrahedra.at<Tetrahedron>(i); tets.pushBack(t); } for (PxU32 i = 0; i < tetrahedra.count; ++i) { const Tetrahedron& tetInd = tets[i]; const PxReal volume = computeTetrahedronVolume(points.at<PxVec3>(tetInd.v[0]), points.at<PxVec3>(tetInd.v[1]), points.at<PxVec3>(tetInd.v[2]), points.at<PxVec3>(tetInd.v[3])); if (volume <= minTetVolumeThreshold) { result |= PxTetrahedronMeshAnalysisResult::eDEGENERATE_TETRAHEDRON; break; } } if (result & PxTetrahedronMeshAnalysisResult::eDEGENERATE_TETRAHEDRON) result |= PxTetrahedronMeshAnalysisResult::eMESH_IS_INVALID; return result; } PxTriangleMeshAnalysisResults validateTriangleMesh(const PxBoundedData& points, const PxBoundedData& triangles, const bool has16BitIndices, const PxReal minVolumeThreshold, const PxReal minTriangleAngleRadians) { PxVec3 min, max; minMax(points, min, max); PxVec3 size = max - min; PxReal scaling = 1.0f / PxMax(PxMax(size.x, size.y), PxMax(1e-6f, size.z)); PxArray<PxVec3> normalizedPoints; normalizedPoints.reserve(points.count); PxTriangleMeshAnalysisResults result = PxTriangleMeshAnalysisResult::eVALID; if (has16BitIndices && points.count > PX_MAX_U16) result |= PxTriangleMeshAnalysisResult::eREQUIRES_32BIT_INDEX_BUFFER; for (PxU32 i = 0; i < points.count; ++i) { const PxVec3& p = points.at<PxVec3>(i); if (!PxIsFinite(p.x) || !PxIsFinite(p.y) || !PxIsFinite(p.z)) { result |= PxTriangleMeshAnalysisResult::eCONTAINS_INVALID_POINTS; normalizedPoints.pushBack(p); continue; } normalizedPoints.pushBack((p - min) * scaling); } PxArray<PxI32> map; MeshAnalyzer::mapDuplicatePoints<PxVec3, PxF32>(normalizedPoints.begin(), normalizedPoints.size(), map); PxArray<Triangle> mappedTriangles; mappedTriangles.reserve(triangles.count); for (PxU32 i = 0; i < triangles.count; ++i) { Triangle t; if (has16BitIndices) { Triangle16 t16 = triangles.at<Triangle16>(i); t = Triangle(t16[0], t16[1], t16[2]); } else t = triangles.at<Triangle>(i); for (PxU32 j = 0; j < 3; ++j) { PxI32 id = t[j]; if (id < 0 || id >= PxI32(points.count)) { return PxTriangleMeshAnalysisResult::eTRIANGLE_INDEX_OUT_OF_RANGE | PxTriangleMeshAnalysisResult::eMESH_IS_INVALID; } } mappedTriangles.pushBack(t); } for (PxU32 i = 0; i < map.size(); ++i) if (map[i] != PxI32(i)) { result = result | PxTriangleMeshAnalysisResult::eCONTAINS_DUPLICATE_POINTS; break; } if(minimumAngle(normalizedPoints, mappedTriangles) < minTriangleAngleRadians) result = result | PxTriangleMeshAnalysisResult::eCONTAINS_ACUTE_ANGLED_TRIANGLES; PxReal volume = computeMeshVolume(normalizedPoints, mappedTriangles); if (volume < minVolumeThreshold) result = result | PxTriangleMeshAnalysisResult::eZERO_VOLUME; result = result | validateConnectivity(mappedTriangles); if(meshContainsSelfIntersections(normalizedPoints, mappedTriangles)) result = result | PxTriangleMeshAnalysisResult::eSELF_INTERSECTIONS; if (result & PxTriangleMeshAnalysisResult::eZERO_VOLUME) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID; if (result & PxTriangleMeshAnalysisResult::eOPEN_BOUNDARIES) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC; if (result & PxTriangleMeshAnalysisResult::eSELF_INTERSECTIONS) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC; if (result & PxTriangleMeshAnalysisResult::eINCONSISTENT_TRIANGLE_ORIENTATION) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID; if (result & PxTriangleMeshAnalysisResult::eCONTAINS_ACUTE_ANGLED_TRIANGLES) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC; if (result & PxTriangleMeshAnalysisResult::eEDGE_SHARED_BY_MORE_THAN_TWO_TRIANGLES) result |= PxTriangleMeshAnalysisResult::eMESH_IS_PROBLEMATIC; if (result & PxTriangleMeshAnalysisResult::eCONTAINS_INVALID_POINTS) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID; if (result & PxTriangleMeshAnalysisResult::eREQUIRES_32BIT_INDEX_BUFFER) result |= PxTriangleMeshAnalysisResult::eMESH_IS_INVALID; return result; } //Consistent triangle orientation } }
74,608
C++
30.533812
242
0.642491
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtRandomAccessHeap.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_RANDOM_ACCESS_HEAP_H #define EXT_RANDOM_ACCESS_HEAP_H #include "foundation/PxArray.h" // MM: heap which allows the modification of the priorities of entries stored anywhere in the tree // for this, every entry gets an id via which it can be accessed // used in ExtMeshSimplificator to sort edges w.r.t. their error metric // ------------------------------------------------------------------------------ namespace physx { namespace Ext { template <class T> class RandomAccessHeap { public: RandomAccessHeap() { heap.resize(1); // dummy such that root is at 1 for faster parent child computation ids.resize(1); nextId = 0; } void resizeFast(PxArray<PxI32>& arr, PxU32 newSize, PxI32 value = 0) { if (newSize < arr.size()) arr.removeRange(newSize, arr.size() - newSize); else { while (arr.size() < newSize) arr.pushBack(value); } } PxI32 insert(T elem, PxI32 id = -1) // id for ability to alter the entry later or to identify duplicates { if (id < 0) { id = nextId; nextId++; } else if (id >= nextId) nextId = id + 1; if (id >= 0 && id < PxI32(posOfId.size()) && posOfId[id] >= 0) return id; // already in heap heap.pushBack(elem); ids.pushBack(id); if (id >= PxI32(posOfId.size())) resizeFast(posOfId, id + 1, -1); posOfId[id] = heap.size() - 1; percolate(PxI32(heap.size()) - 1); return id; } bool remove(PxI32 id) { PxI32 i = posOfId[id]; if (i < 0) return false; posOfId[id] = -1; T prev = heap[i]; heap[i] = heap.back(); heap.popBack(); ids[i] = ids.back(); ids.popBack(); if (i < PxI32(heap.size())) { posOfId[ids[i]] = i; if (heap.size() > 1) { if (heap[i] < prev) percolate(i); else siftDown(i); } } return true; } T deleteMin() { T min(-1, -1, 0.0f); if (heap.size() > 1) { min = heap[1]; posOfId[ids[1]] = -1; heap[1] = heap.back(); heap.popBack(); ids[1] = ids.back(); ids.popBack(); posOfId[ids[1]] = 1; siftDown(1); } return min; } void makeHeap(const PxArray<T> &elems) // O(n) instead of inserting one after the other O(n log n) { heap.resize(elems.size() + 1); ids.resize(elems.size() + 1); posOfId.resize(elems.size()); for (PxU32 i = 0; i < elems.size(); i++) { heap[i + 1] = elems[i]; ids[i + 1] = i; posOfId[ids[i + 1]] = i + 1; } PxI32 n = (heap.size() - 1) >> 1; for (PxI32 i = n; i >= 1; i--) siftDown(i); } void clear() { heap.capacity() == 0 ? heap.resize(1) : heap.forceSize_Unsafe(1); ids.capacity() == 0 ? ids.resize(1) : ids.forceSize_Unsafe(1); posOfId.forceSize_Unsafe(0); nextId = 0; } PX_FORCE_INLINE PxI32 size() { return heap.size() - 1; } PX_FORCE_INLINE bool empty() { return heap.size() <= 1; } private: void siftDown(PxI32 i) { PxI32 n = PxI32(heap.size()) - 1; PxI32 k = i; PxI32 j; do { j = k; if (2 * j < n && heap[2 * j] < heap[k]) k = 2 * j; if (2 * j < n && heap[2 * j + 1] < heap[k]) k = 2 * j + 1; T temp = heap[j]; heap[j] = heap[k]; heap[k] = temp; PxI32 id = ids[j]; ids[j] = ids[k]; ids[k] = id; posOfId[ids[j]] = j; posOfId[ids[k]] = k; } while (j != k); } void percolate(PxI32 i) { PxI32 k = i; PxI32 j; do { j = k; if (j > 1 && !(heap[j >> 1] < heap[k])) k = j >> 1; T temp = heap[j]; heap[j] = heap[k]; heap[k] = temp; PxI32 id = ids[j]; ids[j] = ids[k]; ids[k] = id; posOfId[ids[j]] = j; posOfId[ids[k]] = k; } while (j != k); } PxArray<T> heap; PxArray<PxI32> ids; PxArray<PxI32> posOfId; PxI32 nextId; }; } } #endif
5,482
C
24.03653
108
0.582087
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtFastWindingNumber.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_FAST_WINDING_NUMBER_H #define EXT_FAST_WINDING_NUMBER_H #include "ExtVec3.h" #include "GuWindingNumberT.h" namespace physx { namespace Ext { using Triangle = Gu::IndexedTriangleT<PxI32>; using Triangle16 = Gu::IndexedTriangleT<PxI16>; typedef Gu::ClusterApproximationT<PxF64, PxVec3d> ClusterApproximationF64; typedef Gu::SecondOrderClusterApproximationT<PxF64, PxVec3d> SecondOrderClusterApproximationF64; PxF64 computeWindingNumber(const PxArray<Gu::BVHNode>& tree, const PxVec3d& q, PxF64 beta, const PxHashMap<PxU32, ClusterApproximationF64>& clusters, const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points); void precomputeClusterInformation(PxArray<Gu::BVHNode>& tree, const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points, PxHashMap<PxU32, ClusterApproximationF64>& result, PxI32 rootNodeIndex = 0); } } #endif
2,439
C
44.185184
150
0.777368
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtUtilities.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #ifndef EXT_TET_CPU_BVH_H #define EXT_TET_CPU_BVH_H #include "foundation/PxArray.h" #include "foundation/PxBounds3.h" #include "GuBVH.h" #include "GuAABBTree.h" #include "GuAABBTreeNode.h" #include "GuAABBTreeBounds.h" #include "GuAABBTreeQuery.h" #include "GuTriangle.h" #include "ExtVec3.h" namespace physx { namespace Ext { using Triangle = Gu::IndexedTriangleT<PxI32>; //Creates an unique 64bit bit key out of two 32bit values, the key is order independent, useful as hash key for edges //Use this functions to compute the edge keys used in the edgesToSplit parameter of the split function below. PX_FORCE_INLINE PxU64 key(PxI32 a, PxI32 b) { if (a < b) return ((PxU64(a)) << 32) | (PxU64(b)); else return ((PxU64(b)) << 32) | (PxU64(a)); } void buildTree(const PxU32* triangles, const PxU32 numTriangles, const PxVec3d* points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f); //Builds a BVH from a set of triangles PX_FORCE_INLINE void buildTree(const PxArray<Triangle>& triangles, const PxArray<PxVec3d>& points, PxArray<Gu::BVHNode>& tree, PxF32 enlargement = 1e-4f) { buildTree(reinterpret_cast<const PxU32*>(triangles.begin()), triangles.size(), points.begin(), tree, enlargement); } template<typename T> void traverseBVH(const PxArray<Gu::BVHNode>& nodes, T& traversalController, PxI32 rootNodeIndex = 0) { traverseBVH(nodes.begin(), traversalController, rootNodeIndex); } class IntersectionCollectingTraversalController { PxBounds3 box; PxArray<PxI32>& candidateTriangleIndices; public: IntersectionCollectingTraversalController(PxArray<PxI32>& candidateTriangleIndices_) : box(PxBounds3::empty()), candidateTriangleIndices(candidateTriangleIndices_) { } IntersectionCollectingTraversalController(const PxBounds3& box_, PxArray<PxI32>& candidateTriangleIndices_) : box(box_), candidateTriangleIndices(candidateTriangleIndices_) { } void reset(const PxBounds3& box_) { box = box_; candidateTriangleIndices.clear(); } Gu::TraversalControl::Enum analyze(const Gu::BVHNode& node, PxI32) { if (node.isLeaf()) { candidateTriangleIndices.pushBack(node.getPrimitiveIndex()); return Gu::TraversalControl::eDontGoDeeper; } if (node.mBV.intersects(box)) return Gu::TraversalControl::eGoDeeper; return Gu::TraversalControl::eDontGoDeeper; } private: PX_NOCOPY(IntersectionCollectingTraversalController) }; } } #endif
4,002
C
35.390909
154
0.750875
NVIDIA-Omniverse/PhysX/physx/source/physxextensions/src/tet/ExtRemesher.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "ExtRemesher.h" #include "ExtBVH.h" #include "ExtMarchingCubesTable.h" #include "foundation/PxSort.h" #include "GuIntersectionTriangleBox.h" #include "GuBox.h" namespace physx { namespace Ext { // ------------------------------------------------------------------------------------- void Remesher::clear() { cells.clear(); vertices.clear(); normals.clear(); triIds.clear(); triNeighbors.clear(); } #define HASH_SIZE 170111 // ------------------------------------------------------------------------------------- PX_FORCE_INLINE static PxU32 hash(PxI32 xi, PxI32 yi, PxI32 zi) { PxU32 h = (xi * 92837111) ^ (yi * 689287499) ^ (zi * 283923481); return h % HASH_SIZE; } // ------------------------------------------------------------------------------------- void Remesher::addCell(PxI32 xi, PxI32 yi, PxI32 zi) { Cell c; c.init(xi, yi, zi); PxU32 h = hash(xi, yi, zi); c.next = firstCell[h]; firstCell[h] = PxI32(cells.size()); cells.pushBack(c); } // ------------------------------------------------------------------------------------- PxI32 Remesher::getCellNr(PxI32 xi, PxI32 yi, PxI32 zi) const { PxU32 h = hash(xi, yi, zi); PxI32 nr = firstCell[h]; while (nr >= 0) { const Cell& c = cells[nr]; if (c.xi == xi && c.yi == yi && c.zi == zi) return nr; nr = c.next; } return -1; } // ------------------------------------------------------------------------------------- PX_FORCE_INLINE bool Remesher::cellExists(PxI32 xi, PxI32 yi, PxI32 zi) const { return getCellNr(xi, yi, zi) >= 0; } // ------------------------------------------------------------------------------------- void Remesher::remesh(const PxArray<PxVec3>& inputVerts, const PxArray<PxU32>& inputTriIds, PxU32 resolution, PxArray<PxU32> *vertexMap) { remesh(inputVerts.begin(), inputVerts.size(), inputTriIds.begin(), inputTriIds.size(), resolution, vertexMap); } void Remesher::remesh(const PxVec3* inputVerts, PxU32 nbVertices, const PxU32* inputTriIds, PxU32 nbTriangleIndices, PxU32 resolution, PxArray<PxU32> *vertexMap) { clear(); PxBounds3 meshBounds; meshBounds.setEmpty(); for (PxU32 i = 0; i < nbVertices; i++) meshBounds.include(inputVerts[i]); PxVec3 dims = meshBounds.getDimensions(); float spacing = PxMax(dims.x, PxMax(dims.y, dims.z)) / resolution; meshBounds.fattenFast(3.0f * spacing); PxU32 numTris = nbTriangleIndices / 3; PxBounds3 triBounds, cellBounds; Gu::BoxPadded box; box.rot = PxMat33(PxIdentity); firstCell.clear(); firstCell.resize(HASH_SIZE, -1); // create sparse overlapping cells for (PxU32 i = 0; i < numTris; i++) { const PxVec3& p0 = inputVerts[inputTriIds[3 * i]]; const PxVec3& p1 = inputVerts[inputTriIds[3 * i + 1]]; const PxVec3& p2 = inputVerts[inputTriIds[3 * i + 2]]; triBounds.setEmpty(); triBounds.include(p0); triBounds.include(p1); triBounds.include(p2); PxI32 x0 = PxI32(PxFloor((triBounds.minimum.x - meshBounds.minimum.x) / spacing)); PxI32 y0 = PxI32(PxFloor((triBounds.minimum.y - meshBounds.minimum.y) / spacing)); PxI32 z0 = PxI32(PxFloor((triBounds.minimum.z - meshBounds.minimum.z) / spacing)); PxI32 x1 = PxI32(PxFloor((triBounds.maximum.x - meshBounds.minimum.x) / spacing)) + 1; PxI32 y1 = PxI32(PxFloor((triBounds.maximum.y - meshBounds.minimum.y) / spacing)) + 1; PxI32 z1 = PxI32(PxFloor((triBounds.maximum.z - meshBounds.minimum.z) / spacing)) + 1; for (PxI32 xi = x0; xi <= x1; xi++) { for (PxI32 yi = y0; yi <= y1; yi++) { for (PxI32 zi = z0; zi <= z1; zi++) { cellBounds.minimum.x = meshBounds.minimum.x + xi * spacing; cellBounds.minimum.y = meshBounds.minimum.y + yi * spacing; cellBounds.minimum.z = meshBounds.minimum.z + zi * spacing; cellBounds.maximum = cellBounds.minimum + PxVec3(spacing, spacing, spacing); cellBounds.fattenFast(1e-5f); box.center = cellBounds.getCenter(); box.extents = cellBounds.getExtents(); if (!Gu::intersectTriangleBox(box, p0, p1, p2)) continue; if (!cellExists(xi, yi, zi)) addCell(xi, yi, zi); } } } } // using marching cubes to create boundaries vertices.clear(); cellOfVertex.clear(); triIds.clear(); PxI32 edgeVertId[12]; PxVec3 cornerPos[8]; int cornerVoxelNr[8]; for (PxI32 i = 0; i < PxI32(cells.size()); i++) { Cell& c = cells[i]; // we need to handle a 2 x 2 x 2 block of cells to cover the boundary for (PxI32 dx = 0; dx < 2; dx++) { for (PxI32 dy = 0; dy < 2; dy++) { for (PxI32 dz = 0; dz < 2; dz++) { PxI32 xi = c.xi + dx; PxI32 yi = c.yi + dy; PxI32 zi = c.zi + dz; // are we responsible for this cell? PxI32 maxCellNr = i; for (PxI32 rx = xi - 1; rx <= xi; rx++) for (PxI32 ry = yi - 1; ry <= yi; ry++) for (PxI32 rz = zi - 1; rz <= zi; rz++) maxCellNr = PxMax(maxCellNr, getCellNr(rx, ry, rz)); if (maxCellNr != i) continue; PxI32 code = 0; for (PxI32 j = 0; j < 8; j++) { PxI32 mx = xi - 1 + marchingCubeCorners[j][0]; PxI32 my = yi - 1 + marchingCubeCorners[j][1]; PxI32 mz = zi - 1 + marchingCubeCorners[j][2]; cornerVoxelNr[j] = getCellNr(mx, my, mz); if (cornerVoxelNr[j] >= 0) code |= (1 << j); cornerPos[j].x = meshBounds.minimum.x + (mx + 0.5f) * spacing; cornerPos[j].y = meshBounds.minimum.y + (my + 0.5f) * spacing; cornerPos[j].z = meshBounds.minimum.z + (mz + 0.5f) * spacing; } PxI32 first = firstMarchingCubesId[code]; PxI32 num = (firstMarchingCubesId[code + 1] - first); // create vertices and tris for (PxI32 j = 0; j < 12; j++) edgeVertId[j] = -1; for (PxI32 j = num - 1; j >= 0; j--) { PxI32 edgeId = marchingCubesIds[first + j]; if (edgeVertId[edgeId] < 0) { PxI32 id0 = marchingCubeEdges[edgeId][0]; PxI32 id1 = marchingCubeEdges[edgeId][1]; PxVec3& p0 = cornerPos[id0]; PxVec3& p1 = cornerPos[id1]; edgeVertId[edgeId] = vertices.size(); vertices.pushBack((p0 + p1) * 0.5f); cellOfVertex.pushBack(PxMax(cornerVoxelNr[id0], cornerVoxelNr[id1])); } triIds.pushBack(edgeVertId[edgeId]); } } } } } removeDuplicateVertices(); pruneInternalSurfaces(); project(inputVerts, inputTriIds, nbTriangleIndices, 2.0f * spacing, 0.1f * spacing); if (vertexMap) createVertexMap(inputVerts, nbVertices, meshBounds.minimum, spacing, *vertexMap); computeNormals(); } // ------------------------------------------------------------------------------------- void Remesher::removeDuplicateVertices() { PxF32 eps = 1e-5f; struct Ref { PxF32 d; PxI32 id; bool operator < (const Ref& r) const { return d < r.d; } }; PxI32 numVerts = PxI32(vertices.size()); PxArray<Ref> refs(numVerts); for (PxI32 i = 0; i < numVerts; i++) { PxVec3& p = vertices[i]; refs[i].d = p.x + 0.3f * p.y + 0.1f * p.z; refs[i].id = i; } PxSort(refs.begin(), refs.size()); PxArray<PxI32> idMap(vertices.size(), -1); PxArray<PxVec3> oldVerts = vertices; PxArray<PxI32> oldCellOfVertex = cellOfVertex; vertices.clear(); cellOfVertex.clear(); PxI32 nr = 0; while (nr < numVerts) { Ref& r = refs[nr]; nr++; if (idMap[r.id] >= 0) continue; idMap[r.id] = vertices.size(); vertices.pushBack(oldVerts[r.id]); cellOfVertex.pushBack(oldCellOfVertex[r.id]); PxI32 i = nr; while (i < numVerts && fabsf(refs[i].d - r.d) < eps) { PxI32 id = refs[i].id; if ((oldVerts[r.id] - oldVerts[id]).magnitudeSquared() < eps * eps) idMap[id] = idMap[r.id]; i++; } } for (PxI32 i = 0; i < PxI32(triIds.size()); i++) triIds[i] = idMap[triIds[i]]; } // ------------------------------------------------------------------------------------- void Remesher::findTriNeighbors() { PxI32 numTris = PxI32(triIds.size()) / 3; triNeighbors.clear(); triNeighbors.resize(3 * numTris, -1); struct Edge { void init(PxI32 _id0, PxI32 _id1, PxI32 _triNr, PxI32 _edgeNr) { this->id0 = PxMin(_id0, _id1); this->id1 = PxMax(_id0, _id1); this->triNr = _triNr; this->edgeNr = _edgeNr; } bool operator < (const Edge& e) const { if (id0 < e.id0) return true; if (id0 > e.id0) return false; return id1 < e.id1; } bool operator == (const Edge& e) const { return id0 == e.id0 && id1 == e.id1; } PxI32 id0, id1, triNr, edgeNr; }; PxArray<Edge> edges(triIds.size()); for (PxI32 i = 0; i < numTris; i++) { for (PxI32 j = 0; j < 3; j++) { PxI32 id0 = triIds[3 * i + j]; PxI32 id1 = triIds[3 * i + (j + 1) % 3]; edges[3 * i + j].init(id0, id1, i, j); } } PxSort(edges.begin(), edges.size()); PxI32 nr = 0; while (nr < PxI32(edges.size())) { Edge& e0 = edges[nr]; nr++; while (nr < PxI32(edges.size()) && edges[nr] == e0) { Edge& e1 = edges[nr]; triNeighbors[3 * e0.triNr + e0.edgeNr] = e1.triNr; triNeighbors[3 * e1.triNr + e1.edgeNr] = e0.triNr; nr++; } } } // ------------------------------------------------------------------------------------- void Remesher::pruneInternalSurfaces() { // flood islands, if the enclosed volume is negative remove it findTriNeighbors(); PxI32 numTris = PxI32(triIds.size()) / 3; PxArray<PxI32> oldTriIds = triIds; triIds.clear(); PxArray<bool> visited(numTris, false); PxArray<PxI32> stack; for (PxI32 i = 0; i < numTris; i++) { if (visited[i]) continue; stack.clear(); stack.pushBack(i); PxI32 islandStart = PxI32(triIds.size()); float vol = 0.0f; while (!stack.empty()) { PxI32 triNr = stack.back(); stack.popBack(); if (visited[triNr]) continue; visited[triNr] = true; for (PxI32 j = 0; j < 3; j++) triIds.pushBack(oldTriIds[3 * triNr + j]); const PxVec3& p0 = vertices[oldTriIds[3 * triNr]]; const PxVec3& p1 = vertices[oldTriIds[3 * triNr + 1]]; const PxVec3& p2 = vertices[oldTriIds[3 * triNr + 2]]; vol += p0.cross(p1).dot(p2); for (PxI32 j = 0; j < 3; j++) { PxI32 n = triNeighbors[3 * triNr + j]; if (n >= 0 && !visited[n]) stack.pushBack(n); } } if (vol <= 0.0f) triIds.resize(islandStart); } // remove unreferenced vertices PxArray<PxI32> idMap(vertices.size(), -1); PxArray<PxVec3> oldVerts = vertices; PxArray<PxI32> oldCellOfVertex = cellOfVertex; vertices.clear(); cellOfVertex.clear(); for (int i = 0; i < PxI32(triIds.size()); i++) { PxI32 id = triIds[i]; if (idMap[id] < 0) { idMap[id] = vertices.size(); vertices.pushBack(oldVerts[id]); cellOfVertex.pushBack(oldCellOfVertex[id]); } triIds[i] = idMap[id]; } } // ----------------------------------------------------------------------------------- static void getClosestPointOnTriangle(const PxVec3& pos, const PxVec3& p0, const PxVec3& p1, const PxVec3& p2, PxVec3& closest, PxVec3& bary) { PxVec3 e0 = p1 - p0; PxVec3 e1 = p2 - p0; PxVec3 tmp = p0 - pos; float a = e0.dot(e0); float b = e0.dot(e1); float c = e1.dot(e1); float d = e0.dot(tmp); float e = e1.dot(tmp); PxVec3 coords, clampedCoords; coords.x = b * e - c * d; // s * det coords.y = b * d - a * e; // t * det coords.z = a * c - b * b; // det clampedCoords = PxVec3(PxZero); if (coords.x <= 0.0f) { if (c != 0.0f) clampedCoords.y = -e / c; } else if (coords.y <= 0.0f) { if (a != 0.0f) clampedCoords.x = -d / a; } else if (coords.x + coords.y > coords.z) { float denominator = a + c - b - b; float numerator = c + e - b - d; if (denominator != 0.0f) { clampedCoords.x = numerator / denominator; clampedCoords.y = 1.0f - clampedCoords.x; } } else { // all inside if (coords.z != 0.0f) { clampedCoords.x = coords.x / coords.z; clampedCoords.y = coords.y / coords.z; } } bary.y = PxMin(PxMax(clampedCoords.x, 0.0f), 1.0f); bary.z = PxMin(PxMax(clampedCoords.y, 0.0f), 1.0f); bary.x = 1.0f - bary.y - bary.z; closest = p0 * bary.x + p1 * bary.y + p2 * bary.z; } // ------------------------------------------------------------------------------------- void Remesher::project(const PxVec3* inputVerts, const PxU32* inputTriIds, PxU32 nbTriangleIndices, float searchDist, float surfaceDist) { // build a bvh for the input mesh PxI32 numInputTris = PxI32(nbTriangleIndices) / 3; if (numInputTris == 0) return; bvhBounds.resize(numInputTris); bvhTris.clear(); for (PxI32 i = 0; i < numInputTris; i++) { PxBounds3& b = bvhBounds[i]; b.setEmpty(); b.include(inputVerts[inputTriIds[3 * i]]); b.include(inputVerts[inputTriIds[3 * i + 1]]); b.include(inputVerts[inputTriIds[3 * i + 2]]); } BVHDesc bvh; BVHBuilder::build(bvh, &bvhBounds[0], bvhBounds.size()); // project vertices to closest point on surface PxBounds3 pb; for (PxU32 i = 0; i < vertices.size(); i++) { PxVec3& p = vertices[i]; pb.setEmpty(); pb.include(p); pb.fattenFast(searchDist); bvh.query(pb, bvhTris); float minDist2 = PX_MAX_F32; PxVec3 closest(PxZero); for (PxU32 j = 0; j < bvhTris.size(); j++) { PxI32 triNr = bvhTris[j]; const PxVec3& p0 = inputVerts[inputTriIds[3 * triNr]]; const PxVec3& p1 = inputVerts[inputTriIds[3 * triNr + 1]]; const PxVec3& p2 = inputVerts[inputTriIds[3 * triNr + 2]]; PxVec3 c, bary; getClosestPointOnTriangle(p, p0, p1, p2, c, bary); float dist2 = (c - p).magnitudeSquared(); if (dist2 < minDist2) { minDist2 = dist2; closest = c; } } if (minDist2 < PX_MAX_F32) { PxVec3 n = p - closest; n.normalize(); p = closest + n * surfaceDist; } } } static const int cellNeighbors[6][3] = { { -1,0,0 }, {1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} }; // ------------------------------------------------------------------------------------- void Remesher::createVertexMap(const PxVec3* inputVerts, PxU32 nbVertices, const PxVec3 &gridOrigin, PxF32 &gridSpacing, PxArray<PxU32> &vertexMap) { PxArray<PxI32> vertexOfCell(cells.size(), -1); PxArray<PxI32 > front[2]; PxI32 frontNr = 0; // compute inverse links for (PxI32 i = 0; i < PxI32(vertices.size()); i++) { PxI32 cellNr = cellOfVertex[i]; if (cellNr >= 0) { if (vertexOfCell[cellNr] < 0) { vertexOfCell[cellNr] = i; front[frontNr].pushBack(cellNr); } } } // propagate cell->vertex links through the voxel mesh while (!front[frontNr].empty()) { front[1 - frontNr].clear(); for (PxI32 i = 0; i < PxI32(front[frontNr].size()); i++) { int cellNr = front[frontNr][i]; Cell& c = cells[cellNr]; for (PxI32 j = 0; j < 6; j++) { PxI32 n = getCellNr(c.xi + cellNeighbors[j][0], c.yi + cellNeighbors[j][1], c.zi + cellNeighbors[j][2]); if (n >= 0 && vertexOfCell[n] < 0) { vertexOfCell[n] = vertexOfCell[cellNr]; front[1 - frontNr].pushBack(n); } } } frontNr = 1 - frontNr; } // create the map vertexMap.clear(); vertexMap.resize(nbVertices, 0); for (PxU32 i = 0; i < nbVertices; i++) { const PxVec3& p = inputVerts[i]; PxI32 xi = PxI32(PxFloor((p.x - gridOrigin.x) / gridSpacing)); PxI32 yi = PxI32(PxFloor((p.y - gridOrigin.y) / gridSpacing)); PxI32 zi = PxI32(PxFloor((p.z - gridOrigin.z) / gridSpacing)); PxI32 cellNr = getCellNr(xi, yi, zi); vertexMap[i] = cellNr >= 0 ? vertexOfCell[cellNr] : 0; } } // ------------------------------------------------------------------------------------- void Remesher::computeNormals() { normals.clear(); normals.resize(vertices.size(), PxVec3(PxZero)); for (PxI32 i = 0; i < PxI32(triIds.size()); i += 3) { PxI32* ids = &triIds[i]; PxVec3& p0 = vertices[ids[0]]; PxVec3& p1 = vertices[ids[1]]; PxVec3& p2 = vertices[ids[2]]; PxVec3 n = (p1 - p0).cross(p2 - p0); normals[ids[0]] += n; normals[ids[1]] += n; normals[ids[2]] += n; } for (PxI32 i = 0; i < PxI32(normals.size()); i++) normals[i].normalize(); } // ------------------------------------------------------------------------------------- void Remesher::readBack(PxArray<PxVec3>& outputVertices, PxArray<PxU32>& outputTriIds) { outputVertices = vertices; outputTriIds.resize(triIds.size()); for (PxU32 i = 0; i < triIds.size(); i++) outputTriIds[i] = PxU32(triIds[i]); } } }
18,791
C++
27.472727
163
0.552232