file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorSim.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 "ScActorSim.h" #include "ScActorCore.h" #include "ScElementSim.h" #include "ScScene.h" #include "ScInteraction.h" using namespace physx; using namespace Sc; static const PxFilterObjectType::Enum gFilterType[PxActorType::eACTOR_COUNT] = { PxFilterObjectType::eRIGID_STATIC, // PxActorType::eRIGID_STATIC PxFilterObjectType::eRIGID_DYNAMIC, // PxActorType::eRIGID_DYNAMIC PxFilterObjectType::eARTICULATION, // PxActorType::eARTICULATION_LINK PxFilterObjectType::eSOFTBODY, // PxActorType::eSOFTBODY PxFilterObjectType::eFEMCLOTH, // PxActorType::eFEMCLOTH PxFilterObjectType::ePARTICLESYSTEM, // PxActorType::ePBD_PARTICLESYSTEM PxFilterObjectType::ePARTICLESYSTEM, // PxActorType::eFLIP_PARTICLESYSTEM PxFilterObjectType::ePARTICLESYSTEM, // PxActorType::eMPM_PARTICLESYSTEM PxFilterObjectType::eHAIRSYSTEM, // PxActorType::eHAIRSYSTEM }; static const PxU32 gFilterFlagEx[PxActorType::eACTOR_COUNT] = { PxFilterObjectFlagEx::eRIGID_STATIC, // PxActorType::eRIGID_STATIC PxFilterObjectFlagEx::eRIGID_DYNAMIC, // PxActorType::eRIGID_DYNAMIC PxFilterObjectFlagEx::eRIGID_DYNAMIC, // PxActorType::eARTICULATION_LINK PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::eSOFTBODY, // PxActorType::eSOFTBODY PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::eFEMCLOTH, // PxActorType::eFEMCLOTH PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::ePARTICLESYSTEM, // PxActorType::ePBD_PARTICLESYSTEM PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::ePARTICLESYSTEM, // PxActorType::eFLIP_PARTICLESYSTEM PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::ePARTICLESYSTEM, // PxActorType::eMPM_PARTICLESYSTEM PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::eHAIRSYSTEM, // PxActorType::eHAIRSYSTEM }; // PT: if this breaks, you need to update the above table PX_COMPILE_TIME_ASSERT(PxActorType::eACTOR_COUNT==9); // PT: make sure that the highest flag fits into 16bit PX_COMPILE_TIME_ASSERT(PxFilterObjectFlagEx::eLAST<=0xffff); Sc::ActorSim::ActorSim(Scene& scene, ActorCore& core) : mScene (scene), mCore (core), mActiveListIndex (SC_NOT_IN_SCENE_INDEX), mActiveCompoundListIndex(SC_NOT_IN_SCENE_INDEX), mNodeIndex (PX_INVALID_NODE), mInternalFlags (0) { core.setSim(this); mId = scene.getActorIDTracker().createID(); { PX_ASSERT(gFilterType[PxActorType::eRIGID_STATIC] == PxFilterObjectType::eRIGID_STATIC); PX_ASSERT(gFilterType[PxActorType::eRIGID_DYNAMIC] == PxFilterObjectType::eRIGID_DYNAMIC); PX_ASSERT(gFilterType[PxActorType::eARTICULATION_LINK] == PxFilterObjectType::eARTICULATION); PX_ASSERT(gFilterType[PxActorType::eSOFTBODY] == PxFilterObjectType::eSOFTBODY); PX_ASSERT(gFilterType[PxActorType::eFEMCLOTH] == PxFilterObjectType::eFEMCLOTH); PX_ASSERT(gFilterType[PxActorType::ePBD_PARTICLESYSTEM] == PxFilterObjectType::ePARTICLESYSTEM); PX_ASSERT(gFilterType[PxActorType::eFLIP_PARTICLESYSTEM] == PxFilterObjectType::ePARTICLESYSTEM); PX_ASSERT(gFilterType[PxActorType::eMPM_PARTICLESYSTEM] == PxFilterObjectType::ePARTICLESYSTEM); PX_ASSERT(gFilterType[PxActorType::eHAIRSYSTEM] == PxFilterObjectType::eHAIRSYSTEM); const PxActorType::Enum actorType = getActorType(); PxFilterObjectAttributes filterAttr = 0; setFilterObjectAttributeType(filterAttr, gFilterType[actorType]); filterAttr |= gFilterFlagEx[actorType]; mFilterFlags = PxTo16(filterAttr); } } Sc::ActorSim::~ActorSim() { mInteractions.releaseMem(*this); mScene.getActorIDTracker().releaseID(mId); } void Sc::ActorSim::registerInteractionInActor(Interaction* interaction) { const PxU32 id = mInteractions.size(); mInteractions.pushBack(interaction, *this); interaction->setActorId(this, id); } void Sc::ActorSim::unregisterInteractionFromActor(Interaction* interaction) { const PxU32 i = interaction->getActorId(this); PX_ASSERT(i < mInteractions.size()); mInteractions.replaceWithLast(i); if (i<mInteractions.size()) mInteractions[i]->setActorId(this, i); } void Sc::ActorSim::reallocInteractions(Sc::Interaction**& mem, PxU32& capacity, PxU32 size, PxU32 requiredMinCapacity) { Interaction** newMem; PxU32 newCapacity; if(requiredMinCapacity==0) { newCapacity = 0; newMem = 0; } else if(requiredMinCapacity<=INLINE_INTERACTION_CAPACITY) { newCapacity = INLINE_INTERACTION_CAPACITY; newMem = mInlineInteractionMem; } else { newCapacity = PxNextPowerOfTwo(requiredMinCapacity-1); newMem = reinterpret_cast<Interaction**>(mScene.allocatePointerBlock(newCapacity)); } PX_ASSERT(newCapacity >= requiredMinCapacity && requiredMinCapacity>=size); if(mem) { PxMemCopy(newMem, mem, size*sizeof(Interaction*)); if(mem!=mInlineInteractionMem) mScene.deallocatePointerBlock(reinterpret_cast<void**>(mem), capacity); } capacity = newCapacity; mem = newMem; } void Sc::ActorSim::setActorsInteractionsDirty(InteractionDirtyFlag::Enum flag, const ActorSim* other, PxU8 interactionFlag) { PxU32 size = getActorInteractionCount(); Interaction** interactions = getActorInteractions(); while(size--) { Interaction* interaction = *interactions++; if((!other || other == &interaction->getActorSim0() || other == &interaction->getActorSim1()) && (interaction->readInteractionFlag(interactionFlag))) interaction->setDirty(flag); } }
7,003
C++
39.72093
151
0.772383
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeSim.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 SC_HAIRSYSTEM_SHAPE_SIM_H #define SC_HAIRSYSTEM_SHAPE_SIM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXConfig.h" #include "ScElementSim.h" #include "ScShapeSimBase.h" namespace physx { namespace Sc { class HairSystemSim; class HairSystemShapeCore; /** A collision detection primitive for the hair system. */ class HairSystemShapeSim : public ShapeSimBase { HairSystemShapeSim& operator=(const HairSystemShapeSim &); public: HairSystemShapeSim(HairSystemSim& hairSystem, const HairSystemShapeCore* core); virtual ~HairSystemShapeSim(); // ElementSim implementation virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const; // ~ElementSim HairSystemSim& getBodySim() const; void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; void createLowLevelVolume(); void destroyLowLevelVolume(); }; } // namespace Sc } #endif #endif
2,600
C
33.68
102
0.750769
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimStats.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 "ScSimStats.h" #include "PxvSimStats.h" #include "PxsHeapMemoryAllocator.h" using namespace physx; Sc::SimStats::SimStats() { numBroadPhaseAdds = numBroadPhaseRemoves = 0; gpuMemSizeParticles = 0; gpuMemSizeSoftBodies = 0; clear(); } void Sc::SimStats::clear() { #if PX_ENABLE_SIM_STATS PxMemZero(const_cast<void*>(reinterpret_cast<volatile void*>(&numTriggerPairs)), sizeof(TriggerPairCounts)); numBroadPhaseAddsPending = numBroadPhaseRemovesPending = 0; #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif } void Sc::SimStats::simStart() { #if PX_ENABLE_SIM_STATS // pending broadphase adds/removes are now the current ones numBroadPhaseAdds = numBroadPhaseAddsPending; numBroadPhaseRemoves = numBroadPhaseRemovesPending; clear(); #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif } void Sc::SimStats::readOut(PxSimulationStatistics& s, const PxvSimStats& simStats) const { #if PX_ENABLE_SIM_STATS s = PxSimulationStatistics(); // clear stats for(PxU32 i=0; i < PxGeometryType::eCONVEXMESH+1; i++) { for(PxU32 j=0; j < PxGeometryType::eGEOMETRY_COUNT; j++) { s.nbTriggerPairs[i][j] += PxU32(numTriggerPairs[i][j]); if (i != j) s.nbTriggerPairs[j][i] += PxU32(numTriggerPairs[i][j]); } } s.nbBroadPhaseAdds = numBroadPhaseAdds; s.nbBroadPhaseRemoves = numBroadPhaseRemoves; for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++) { s.nbDiscreteContactPairs[i][i] = simStats.mNbDiscreteContactPairs[i][i]; s.nbModifiedContactPairs[i][i] = simStats.mNbModifiedContactPairs[i][i]; s.nbCCDPairs[i][i] = simStats.mNbCCDPairs[i][i]; for(PxU32 j=i+1; j < PxGeometryType::eGEOMETRY_COUNT; j++) { PxU32 c = simStats.mNbDiscreteContactPairs[i][j]; s.nbDiscreteContactPairs[i][j] = c; s.nbDiscreteContactPairs[j][i] = c; c = simStats.mNbModifiedContactPairs[i][j]; s.nbModifiedContactPairs[i][j] = c; s.nbModifiedContactPairs[j][i] = c; c = simStats.mNbCCDPairs[i][j]; s.nbCCDPairs[i][j] = c; s.nbCCDPairs[j][i] = c; } #if PX_DEBUG for(PxU32 j=0; j < i; j++) { // PxvSimStats should only use one half of the matrix PX_ASSERT(simStats.mNbDiscreteContactPairs[i][j] == 0); PX_ASSERT(simStats.mNbModifiedContactPairs[i][j] == 0); PX_ASSERT(simStats.mNbCCDPairs[i][j] == 0); } #endif } s.nbDiscreteContactPairsTotal = simStats.mNbDiscreteContactPairsTotal; s.nbDiscreteContactPairsWithCacheHits = simStats.mNbDiscreteContactPairsWithCacheHits; s.nbDiscreteContactPairsWithContacts = simStats.mNbDiscreteContactPairsWithContacts; s.nbActiveConstraints = simStats.mNbActiveConstraints; s.nbActiveDynamicBodies = simStats.mNbActiveDynamicBodies; s.nbActiveKinematicBodies = simStats.mNbActiveKinematicBodies; s.nbAxisSolverConstraints = simStats.mNbAxisSolverConstraints; s.peakConstraintMemory = simStats.mPeakConstraintBlockAllocations * 16 * 1024; s.compressedContactSize = simStats.mTotalCompressedContactSize; s.requiredContactConstraintMemory = simStats.mTotalConstraintSize; s.nbNewPairs = simStats.mNbNewPairs; s.nbLostPairs = simStats.mNbLostPairs; s.nbNewTouches = simStats.mNbNewTouches; s.nbLostTouches = simStats.mNbLostTouches; s.nbPartitions = simStats.mNbPartitions; s.gpuMemParticles = gpuMemSizeParticles; s.gpuMemSoftBodies = gpuMemSizeSoftBodies; #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS PX_UNUSED(s); PX_UNUSED(simStats); #endif }
5,106
C++
34.465278
109
0.75754
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementInteractionMarker.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 SC_ELEMENT_INTERACTION_MARKER_H #define SC_ELEMENT_INTERACTION_MARKER_H #include "ScElementSimInteraction.h" #include "ScNPhaseCore.h" namespace physx { namespace Sc { class ElementInteractionMarker : public ElementSimInteraction { public: PX_INLINE ElementInteractionMarker(ElementSim& element0, ElementSim& element1, bool createParallel/* = false*/); ~ElementInteractionMarker(); }; } // namespace Sc PX_INLINE Sc::ElementInteractionMarker::ElementInteractionMarker(ElementSim& element0, ElementSim& element1, bool createParallel) : ElementSimInteraction(element0, element1, InteractionType::eMARKER, InteractionFlag::eRB_ELEMENT|InteractionFlag::eFILTERABLE) { if(!createParallel) { // PT: no call to onActivate() here, interaction markers are always inactive registerInActors(); Scene& scene = getScene(); scene.registerInteraction(this, false); } } } #endif
2,602
C
39.046153
131
0.76864
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintInteraction.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 SC_CONSTRAINT_INTERACTION_H #define SC_CONSTRAINT_INTERACTION_H #include "ScInteraction.h" namespace physx { namespace Sc { class ConstraintSim; class RigidSim; class ConstraintInteraction : public Interaction { public: ConstraintInteraction(ConstraintSim* shader, RigidSim& r0, RigidSim& r1); ~ConstraintInteraction(); bool onActivate(void* data); bool onDeactivate(); void updateState(); void destroy(); // disables the interaction and unregisters from the system. Does NOT delete the object. This is used on destruction but also when a constraint breaks. PX_FORCE_INLINE ConstraintSim* getConstraint() { return mConstraint; } PX_FORCE_INLINE PxU32 getEdgeIndex() const { return mEdgeIndex; } private: ConstraintSim* mConstraint; PxU32 mEdgeIndex; }; } // namespace Sc } #endif
2,578
C
38.075757
176
0.745927
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSqBoundsManager.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 "GuPrunerTypedef.h" #include "ScSqBoundsManager.h" #include "ScBodySim.h" #include "ScShapeSim.h" #include "ScSqBoundsSync.h" #include "common/PxProfileZone.h" using namespace physx; using namespace Sc; #define INVALID_REF ScPrunerHandle(Gu::INVALID_PRUNERHANDLE) SqBoundsManager0::SqBoundsManager0() : mShapes ("SqBoundsManager::mShapes"), mRefs ("SqBoundsManager::mRefs"), mBoundsIndices ("SqBoundsManager::mBoundsIndices"), mRefless ("SqBoundsManager::mRefless") { } void SqBoundsManager0::addSyncShape(ShapeSimBase& shape) { PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE); PX_ASSERT(!shape.getBodySim()->usingSqKinematicTarget()); PX_ASSERT(!shape.getBodySim()->isFrozen()); const PxU32 id = mShapes.size(); PX_ASSERT(id == mRefs.size()); PX_ASSERT(id == mBoundsIndices.size()); shape.setSqBoundsId(id); // PT: mShapes / mRefs / mBoundsIndices are "parallel arrays". These arrays are persistent. // mRefless is temporary/transient data to help populate mRefs each frame. // mRefs / mBoundsIndices will be ultimately passed to updateObjects, whose API dictates the layout here. // mShapes is not actually used for the sync, it's only here to be able to call setSqBoundsId in removeShape. mShapes.pushBack(static_cast<Sc::ShapeSim*>(&shape)); mRefs.pushBack(INVALID_REF); mBoundsIndices.pushBack(shape.getElementID()); mRefless.pushBack(static_cast<Sc::ShapeSim*>(&shape)); } void SqBoundsManager0::removeSyncShape(ShapeSimBase& shape) { const PxU32 id = shape.getSqBoundsId(); PX_ASSERT(id!=PX_INVALID_U32); shape.setSqBoundsId(PX_INVALID_U32); mShapes[id] = mShapes.back(); mBoundsIndices[id] = mBoundsIndices.back(); mRefs[id] = mRefs.back(); if(id+1 != mShapes.size()) mShapes[id]->setSqBoundsId(id); mShapes.popBack(); mRefs.popBack(); mBoundsIndices.popBack(); } void SqBoundsManager0::syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices) { PX_PROFILE_ZONE("Sim.sceneQuerySyncBounds", contextID); PX_UNUSED(contextID); #if PX_DEBUG for(PxU32 i=0;i<mShapes.size();i++) { const ShapeSimBase& shape = *mShapes[i]; PX_UNUSED(shape); PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE); PX_ASSERT(!shape.getBodySim()->usingSqKinematicTarget()); PX_ASSERT(!shape.getBodySim()->isFrozen()); } #endif ShapeSimBase*const * shapes = mRefless.begin(); for(PxU32 i=0, size = mRefless.size();i<size;i++) { const PxU32 id = shapes[i]->getSqBoundsId(); // PT: // // If id == PX_INVALID_U32, the shape has been removed and not re-added. Nothing to do in this case, we just ignore it. // This case didn't previously exist since mRefless only contained valid (added) shapes. But now we left removed shapes in the // structure, and these have an id == PX_INVALID_U32. // // Now if the id is valid but mRefs[id] == PX_INVALID_U32, this is a regular shape that has been added and not processed yet. // So we process it. // // Finally, if both id and mRefs[id] are not PX_INVALID_U32, this is a shape that has been added, removed, and re-added. The // array contains the same shape twice and we only need to process it once. if(id!=PX_INVALID_U32) { if(mRefs[id] == INVALID_REF) { PxU32 prunerIndex = 0xffffffff; mRefs[id] = finder.find(static_cast<PxRigidBody*>(shapes[i]->getBodySim()->getPxActor()), shapes[i]->getPxShape(), prunerIndex); PX_ASSERT(prunerIndex==1); } } } mRefless.clear(); sync.sync(1, mRefs.begin(), mBoundsIndices.begin(), bounds, transforms, mShapes.size(), ignoredIndices); } // PT: we need to change the code so that the shape is added to the proper array during syncBounds, not during addSyncShape, // because the pruner index is not known in addSyncShape. We could perhaps call the ref-finder directly in addSyncShape, but // it would impose an order on the calls (the shape would need to be added to the pruners before addSyncShape is called. There's // no such requirement with the initial code). // // Instead we do this: // - in addSyncShape we just add the shape to a "waiting room", that's all. // - adding the shape to the proper array is delayed until syncBounds. That way the prunerIndex will be available. Also we could // then take advantage of batching, since all shapes are processed/added at the same time. // - the only catch is that we need to ensure the previous edge-cases are still properly handled, i.e. when a shape is added then // removed before sync is called, etc. // SqBoundsManagerEx::SqBoundsManagerEx() : mWaitingRoom ("SqBoundsManagerEx::mWaitingRoom"), mPrunerSyncData (NULL), mPrunerSyncDataSize (0) { } SqBoundsManagerEx::~SqBoundsManagerEx() { const PxU32 nbToGo = mPrunerSyncDataSize; for(PxU32 i=0;i<nbToGo;i++) { PrunerSyncData* psd = mPrunerSyncData[i]; PX_DELETE(psd); } PX_FREE(mPrunerSyncData); } void SqBoundsManagerEx::resize(PxU32 index) { PxU32 size = mPrunerSyncDataSize ? mPrunerSyncDataSize*2 : 64; const PxU32 minSize = index+1; if(minSize>size) size = minSize*2; PrunerSyncData** items = PX_ALLOCATE(PrunerSyncData*, size, "PrunerSyncData"); if(mPrunerSyncData) PxMemCopy(items, mPrunerSyncData, mPrunerSyncDataSize*sizeof(PrunerSyncData*)); PxMemZero(items+mPrunerSyncDataSize, (size-mPrunerSyncDataSize)*sizeof(PrunerSyncData*)); PX_FREE(mPrunerSyncData); mPrunerSyncData = items; mPrunerSyncDataSize = size; } void SqBoundsManagerEx::addSyncShape(ShapeSimBase& shape) { PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE); PX_ASSERT(!shape.getBodySim()->usingSqKinematicTarget()); PX_ASSERT(!shape.getBodySim()->isFrozen()); PX_ASSERT(shape.getSqBoundsId()==PX_INVALID_U32); PX_ASSERT(shape.getSqPrunerIndex()==PX_INVALID_U32); const PxU32 id = mWaitingRoom.size(); mWaitingRoom.pushBack(&shape); shape.setSqBoundsId(id); shape.setSqPrunerIndex(PX_INVALID_U32); } void SqBoundsManagerEx::removeSyncShape(ShapeSimBase& shape) { const PxU32 id = shape.getSqBoundsId(); const PxU32 prunerIndex = shape.getSqPrunerIndex(); PX_ASSERT(id!=PX_INVALID_U32); shape.setSqBoundsId(PX_INVALID_U32); shape.setSqPrunerIndex(PX_INVALID_U32); if(prunerIndex==PX_INVALID_U32) { // PT: this shape is still in the waiting room PX_ASSERT(mWaitingRoom[id]==&shape); mWaitingRoom[id] = mWaitingRoom.back(); if(id+1 != mWaitingRoom.size()) mWaitingRoom[id]->setSqBoundsId(id); mWaitingRoom.popBack(); } else { // PT: this shape is active PX_ASSERT(prunerIndex<mPrunerSyncDataSize); PrunerSyncData* psd = mPrunerSyncData[prunerIndex]; PX_ASSERT(psd); PX_ASSERT(psd->mShapes[id]==&shape); psd->mShapes[id] = psd->mShapes.back(); psd->mBoundsIndices[id] = psd->mBoundsIndices.back(); psd->mRefs[id] = psd->mRefs.back(); if(id+1 != psd->mShapes.size()) psd->mShapes[id]->setSqBoundsId(id); psd->mShapes.popBack(); psd->mBoundsIndices.popBack(); psd->mRefs.popBack(); if(!psd->mShapes.size()) { PX_DELETE(psd); mPrunerSyncData[prunerIndex] = NULL; } } } void SqBoundsManagerEx::syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices) { PX_PROFILE_ZONE("Sim.sceneQuerySyncBounds", contextID); PX_UNUSED(contextID); /* #if PX_DEBUG for(PxU32 i=0;i<mShapeData.size();i++) { const ShapeSQData& shape = mShapeData[i]; PX_UNUSED(shape); PX_ASSERT(shape.mSim->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE); PX_ASSERT(!shape.mSim->getBodySim()->usingSqKinematicTarget()); PX_ASSERT(!shape.mSim->getBodySim()->isFrozen()); } #endif */ const PxU32 nbToGo = mWaitingRoom.size(); if(nbToGo) { for(PxU32 i=0;i<nbToGo;i++) { ShapeSimBase* sim = mWaitingRoom[i]; PX_ASSERT(i==sim->getSqBoundsId()); PX_ASSERT(PX_INVALID_U32==sim->getSqPrunerIndex()); PxU32 prunerIndex = 0xffffffff; const ScPrunerHandle prunerHandle = finder.find(static_cast<PxRigidBody*>(sim->getBodySim()->getPxActor()), sim->getPxShape(), prunerIndex); PX_ASSERT(prunerIndex!=0xffffffff); if(prunerIndex>=mPrunerSyncDataSize) resize(prunerIndex); PrunerSyncData* psd = mPrunerSyncData[prunerIndex]; if(!psd) { psd = PX_NEW(PrunerSyncData); mPrunerSyncData[prunerIndex] = psd; } PxArray<ShapeSimBase*>& shapes = psd->mShapes; PxArray<ScPrunerHandle>& refs = psd->mRefs; PxArray<PxU32>& boundsIndices = psd->mBoundsIndices; const PxU32 id = shapes.size(); PX_ASSERT(id == refs.size()); PX_ASSERT(id == boundsIndices.size()); sim->setSqBoundsId(id); sim->setSqPrunerIndex(prunerIndex); // PT: mShapes / mRefs / mBoundsIndices are "parallel arrays". These arrays are persistent. // mRefless is temporary/transient data to help populate mRefs each frame. // mRefs / mBoundsIndices will be ultimately passed to updateObjects, whose API dictates the layout here. // mShapes is not actually used for the sync, it's only here to be able to call setSqBoundsId in removeShape. shapes.pushBack(sim); refs.pushBack(prunerHandle); boundsIndices.pushBack(sim->getElementID()); } mWaitingRoom.clear(); // PT: TODO: optimize wasted memory here } // PT: TODO: optimize this { const PxU32 nb = mPrunerSyncDataSize; for(PxU32 i=0;i<nb;i++) { PrunerSyncData* psd = mPrunerSyncData[i]; if(psd) sync.sync(i, psd->mRefs.begin(), psd->mBoundsIndices.begin(), bounds, transforms, psd->mRefs.size(), ignoredIndices); } } }
11,245
C++
33.078788
182
0.728946
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScPhysics.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/PxTolerancesScale.h" #include "ScPhysics.h" #include "ScScene.h" #include "PxvGlobals.h" using namespace physx; Sc::Physics* Sc::Physics::mInstance = NULL; const PxReal Sc::Physics::sWakeCounterOnCreation = 20.0f*0.02f; namespace physx { namespace Sc { OffsetTable gOffsetTable; } } Sc::Physics::Physics(const PxTolerancesScale& scale, const PxvOffsetTable& pxvOffsetTable) : mScale(scale) { mInstance = this; PxvInit(pxvOffsetTable); } Sc::Physics::~Physics() { PxvTerm(); mInstance = NULL; }
2,225
C++
36.099999
106
0.758202
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothShapeSim.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 PX_PHYSICS_FEMCLOTH_SHAPE_SIM #define PX_PHYSICS_FEMCLOTH_SHAPE_SIM #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXConfig.h" #include "ScElementSim.h" #include "ScShapeSimBase.h" namespace physx { namespace Sc { class FEMClothSim; class FEMClothShapeSim : public ShapeSimBase { PxTransform initialTransform; PxReal initialScale; FEMClothShapeSim& operator=(const FEMClothShapeSim &); public: FEMClothShapeSim(FEMClothSim& FEMCloth); virtual ~FEMClothShapeSim(); PX_FORCE_INLINE void setInitialTransform(const PxTransform& transform, PxReal scale) { initialTransform = transform; initialScale = scale; //The base class constructor ensures that getElementID() points to a valid entry in the bounds array getScene().getBoundsArray().setBounds(getWorldBounds(), getElementID()); } void attachShapeCore(const ShapeCore* core); // ElementSim implementation virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const; // ~ElementSim PxBounds3 getWorldBounds() const; //PX_FORCE_INLINE FEMClothSim& getBodySim() const { return static_cast<FEMClothSim&>(getActor()); } FEMClothSim& getBodySim() const; void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; void createLowLevelVolume(); void destroyLowLevelVolume(); }; } // namespace Sc } #endif #endif
3,042
C
34.8
105
0.750164
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSim.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 SC_SHAPE_SIM_H #define SC_SHAPE_SIM_H #include "ScShapeSimBase.h" namespace physx { /** Simulation object corresponding to a shape core object. This object is created when a ShapeCore object is added to the simulation, and destroyed when it is removed */ namespace Sc { class RigidSim; class ShapeCore; class ShapeSim : public ShapeSimBase { PX_NOCOPY(ShapeSim) public: ShapeSim(RigidSim&, ShapeCore& core); ~ShapeSim(); }; } // namespace Sc } #endif
2,186
C
36.067796
87
0.754803
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodySim.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 SC_SOFTBODY_SIM_H #define SC_SOFTBODY_SIM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxUserAllocated.h" #include "DySoftBody.h" #include "ScSoftBodyCore.h" #include "ScSoftBodyShapeSim.h" namespace physx { namespace Sc { class Scene; class SoftBodySim : public ActorSim { PX_NOCOPY(SoftBodySim) public: SoftBodySim(SoftBodyCore& core, Scene& scene); ~SoftBodySim(); PX_INLINE Dy::SoftBody* getLowLevelSoftBody() const { return mLLSoftBody; } PX_INLINE SoftBodyCore& getCore() const { return static_cast<SoftBodyCore&>(mCore); } virtual PxActor* getPxActor() const { return getCore().getPxActor(); } void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; bool isSleeping() const; bool isActive() const { return !isSleeping(); } void setActive(bool active, bool asPartOfCreation=false); void enableSelfCollision(); void disableSelfCollision(); void onSetWakeCounter(); void attachShapeCore(ShapeCore* core); void attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState); PxTetrahedronMesh* getSimulationMesh(); PxSoftBodyAuxData* getSoftBodyAuxData(); PxTetrahedronMesh* getCollisionMesh(); PxU32 getGpuSoftBodyIndex() const; SoftBodyShapeSim& getShapeSim() { return mShapeSim; } private: Dy::SoftBody* mLLSoftBody; SoftBodyShapeSim mShapeSim; PxU32 mIslandNodeIndex; // PT: as far as I can tell these are never actually called // void activate(); // void deactivate(); }; } // namespace Sc } #endif #endif
3,340
C
33.443299
106
0.716766
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodyShapeSim.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 SC_SOFTBODY_SHAPE_SIM_H #define SC_SOFTBODY_SHAPE_SIM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxPhysXConfig.h" #include "ScElementSim.h" #include "ScShapeSimBase.h" namespace physx { namespace Sc { class SoftBodySim; /** A collision detection primitive for soft body. */ class SoftBodyShapeSim : public ShapeSimBase { PxTransform initialTransform; PxReal initialScale; SoftBodyShapeSim& operator=(const SoftBodyShapeSim &); public: SoftBodyShapeSim(SoftBodySim& softbody); virtual ~SoftBodyShapeSim(); PX_FORCE_INLINE void setInitialTransform(const PxTransform& transform, PxReal scale) { initialTransform = transform; initialScale = scale; //The base class constructor ensures that getElementID() points to a valid entry in the bounds array getScene().getBoundsArray().setBounds(getWorldBounds(), getElementID()); } void attachShapeCore(const ShapeCore* core); // ElementSim implementation virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const; // ~ElementSim PxBounds3 getWorldBounds() const; //PX_FORCE_INLINE SoftBodySim& getBodySim() const { return static_cast<SoftBodySim&>(getActor()); } SoftBodySim& getBodySim() const; void updateBounds(); void updateBoundsInAABBMgr(); PxBounds3 getBounds() const; void createLowLevelVolume(); void destroyLowLevelVolume(); }; } // namespace Sc } #endif #endif
3,097
C
34.609195
105
0.74556
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSensorSim.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 SC_ARTICULATION_SENSOR_SIM_H #define SC_ARTICULATION_SENSOR_SIM_H #include "foundation/PxUserAllocated.h" #include "PxArticulationReducedCoordinate.h" #include "DyFeatherstoneArticulation.h" namespace physx { namespace Sc { class Scene; class ArticulationSensorCore; class ArticulationCore; class ArticulationSim; class ArticulationSensorSim : public PxUserAllocated { PX_NOCOPY(ArticulationSensorSim) public: ArticulationSensorSim(Sc::ArticulationSensorCore& core, Sc::Scene& scene); ~ArticulationSensorSim(); const PxSpatialForce& getForces() const; void setRelativePose(const PxTransform& relativePose); void setFlag(PxU16 flag); PX_FORCE_INLINE Sc::Scene& getScene() { return mScene; } PX_FORCE_INLINE const Sc::Scene& getScene() const { return mScene; } PX_FORCE_INLINE void setLowLevelIndex(const PxU32 llIndex) { mLLIndex = llIndex;} PX_FORCE_INLINE PxU32 getLowLevelIndex() const { return mLLIndex; } PX_FORCE_INLINE Sc::ArticulationSensorCore& getCore() { return mCore; } PX_FORCE_INLINE const Sc::ArticulationSensorCore& getCore() const { return mCore; } PX_FORCE_INLINE Dy::ArticulationSensor& getLLSensor() { return mLLSensor; } Sc::Scene& mScene; Sc::ArticulationSensorCore& mCore; Sc::ArticulationSim* mArticulationSim; Dy::ArticulationSensor mLLSensor; PxU32 mLLIndex; }; } } #endif //SC_ARTICULATION_SENSOR_SIM_H
3,096
C
34.597701
84
0.764535
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScInteraction.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 SC_INTERACTION_H #define SC_INTERACTION_H #include "foundation/Px.h" #include "ScInteractionFlags.h" #include "ScActorSim.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" namespace physx { #define PX_INVALID_INTERACTION_ACTOR_ID 0xffffffff #define PX_INVALID_INTERACTION_SCENE_ID 0xffffffff namespace Sc { struct InteractionType { enum Enum { eOVERLAP = 0, // corresponds to ShapeInteraction eTRIGGER, // corresponds to TriggerInteraction eMARKER, // corresponds to ElementInteractionMarker eTRACKED_IN_SCENE_COUNT, // not a real type, interactions above this limit are tracked in the scene eCONSTRAINTSHADER, // corresponds to ConstraintInteraction eARTICULATION, // corresponds to ArticulationJointSim eINVALID }; }; // Interactions are used for connecting actors into activation groups. An interaction always connects exactly two actors. // An interaction is implicitly active if at least one of the two actors it connects is active. // PT: we need PxUserAllocated only for ArticulationJointSim, which for some reason doesn't follow the same design as the others. // The others are allocated from pools in NphaseCore. class Interaction : public PxUserAllocated { PX_NOCOPY(Interaction) Interaction(ActorSim& actor0, ActorSim& actor1, InteractionType::Enum interactionType, PxU8 flags); ~Interaction() { PX_ASSERT(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)); } public: // Interactions automatically register themselves in the actors here PX_FORCE_INLINE void registerInActors(); // Interactions automatically unregister themselves from the actors here PX_FORCE_INLINE void unregisterFromActors(); PX_FORCE_INLINE ActorSim& getActorSim0() const { return mActor0; } PX_FORCE_INLINE ActorSim& getActorSim1() const { return mActor1; } PX_FORCE_INLINE Scene& getScene() const { return mActor0.getScene(); } PX_FORCE_INLINE InteractionType::Enum getType() const { return InteractionType::Enum(mInteractionType); } PX_FORCE_INLINE PxU8 readInteractionFlag(PxU8 flag) const { return PxU8(mInteractionFlags & flag); } PX_FORCE_INLINE void raiseInteractionFlag(InteractionFlag::Enum flag) { mInteractionFlags |= flag; } PX_FORCE_INLINE void clearInteractionFlag(InteractionFlag::Enum flag) { mInteractionFlags &= ~flag; } /** \brief Mark the interaction as dirty. This will put the interaction into a list that is processed once per simulation step. @see InteractionDirtyFlag */ PX_FORCE_INLINE void setDirty(PxU32 dirtyFlags); /** \brief Clear all flags that mark the interaction as dirty and optionally remove the interaction from the list of dirty interactions. @see InteractionDirtyFlag */ /*PX_FORCE_INLINE*/ void setClean(bool removeFromList); PX_FORCE_INLINE PxIntBool needsRefiltering() const { return (getDirtyFlags() & InteractionDirtyFlag::eFILTER_STATE); } PX_FORCE_INLINE PxIntBool isElementInteraction() const; PX_FORCE_INLINE void setInteractionId(PxU32 id) { mSceneId = id; } PX_FORCE_INLINE PxU32 getInteractionId() const { return mSceneId; } PX_FORCE_INLINE bool isRegistered() const { return mSceneId != PX_INVALID_INTERACTION_SCENE_ID; } PX_FORCE_INLINE void setActorId(ActorSim* actor, PxU32 id); PX_FORCE_INLINE PxU32 getActorId(const ActorSim* actor) const; PX_FORCE_INLINE PxU8 getDirtyFlags() const { return mDirtyFlags; } private: void addToDirtyList(); void removeFromDirtyList(); ActorSim& mActor0; ActorSim& mActor1; // PT: TODO: merge the 6bits of the 3 PxU8s in the top bits of the 3 PxU32s PxU32 mSceneId; // PT: TODO: merge this with mInteractionType // PT: TODO: are those IDs even worth caching? Since the number of interactions per actor is (or should be) small, // we could just do a linear search and save memory here... PxU32 mActorId0; // PT: id of this interaction within mActor0's mInteractions array PxU32 mActorId1; // PT: id of this interaction within mActor1's mInteractions array protected: const PxU8 mInteractionType; // PT: stored on a byte to save space, should be InteractionType enum, 5/6 bits needed here PxU8 mInteractionFlags; // PT: 6 bits needed here, see InteractionFlag enum PxU8 mDirtyFlags; // PT: 6 bits needed here, see InteractionDirtyFlag enum PxU8 mPadding8; }; } // namespace Sc ////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void Sc::Interaction::registerInActors() { mActor0.registerInteractionInActor(this); mActor1.registerInteractionInActor(this); } PX_FORCE_INLINE void Sc::Interaction::unregisterFromActors() { mActor0.unregisterInteractionFromActor(this); mActor1.unregisterInteractionFromActor(this); } PX_FORCE_INLINE void Sc::Interaction::setActorId(ActorSim* actor, PxU32 id) { PX_ASSERT(id != PX_INVALID_INTERACTION_ACTOR_ID); PX_ASSERT(&mActor0 == actor || &mActor1 == actor); if(&mActor0 == actor) mActorId0 = id; else mActorId1 = id; } PX_FORCE_INLINE PxU32 Sc::Interaction::getActorId(const ActorSim* actor) const { PX_ASSERT(&mActor0 == actor || &mActor1 == actor); return &mActor0 == actor ? mActorId0 : mActorId1; } PX_FORCE_INLINE PxIntBool Sc::Interaction::isElementInteraction() const { const PxIntBool res = readInteractionFlag(InteractionFlag::eRB_ELEMENT); PX_ASSERT( (res && ((getType() == InteractionType::eOVERLAP) || (getType() == InteractionType::eTRIGGER) || (getType() == InteractionType::eMARKER))) || (!res && ((getType() == InteractionType::eCONSTRAINTSHADER) || (getType() == InteractionType::eARTICULATION)))); return res; } PX_FORCE_INLINE void Sc::Interaction::setDirty(PxU32 dirtyFlags) { PX_ASSERT(getType() != InteractionType::eARTICULATION); mDirtyFlags |= PxTo8(dirtyFlags); if(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)) { addToDirtyList(); raiseInteractionFlag(InteractionFlag::eIN_DIRTY_LIST); } } //PX_FORCE_INLINE void Sc::Interaction::setClean(bool removeFromList) //{ // if (readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)) // { // if (removeFromList) // if we process all dirty interactions anyway, then we can just clear the list at the end and save the work here. // removeFromDirtyList(); // clearInteractionFlag(InteractionFlag::eIN_DIRTY_LIST); // } // // mDirtyFlags = 0; //} } #endif
8,185
C
38.167464
139
0.732071
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScInteraction.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/Px.h" #include "ScInteraction.h" #include "ScNPhaseCore.h" using namespace physx; Sc::Interaction::Interaction(ActorSim& actor0, ActorSim& actor1, InteractionType::Enum type, PxU8 flags) : mActor0 (actor0), mActor1 (actor1), mSceneId (PX_INVALID_INTERACTION_SCENE_ID), mActorId0 (PX_INVALID_INTERACTION_ACTOR_ID), mActorId1 (PX_INVALID_INTERACTION_ACTOR_ID), mInteractionType (PxTo8(type)), mInteractionFlags (flags), mDirtyFlags (0) { PX_ASSERT_WITH_MESSAGE(&actor0.getScene() == &actor1.getScene(),"Cannot create an interaction between actors belonging to different scenes."); PX_ASSERT(PxU32(type)<256); // PT: type is now stored on a byte } void Sc::Interaction::addToDirtyList() { getActorSim0().getScene().getNPhaseCore()->addToDirtyInteractionList(this); } void Sc::Interaction::removeFromDirtyList() { getActorSim0().getScene().getNPhaseCore()->removeFromDirtyInteractionList(this); } void Sc::Interaction::setClean(bool removeFromList) { if (readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)) { if (removeFromList) // if we process all dirty interactions anyway, then we can just clear the list at the end and save the work here. removeFromDirtyList(); clearInteractionFlag(InteractionFlag::eIN_DIRTY_LIST); } mDirtyFlags = 0; }
3,010
C++
41.40845
143
0.757807
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScStaticSim.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 SC_STATIC_SIM_H #define SC_STATIC_SIM_H #include "ScRigidSim.h" #include "ScStaticCore.h" namespace physx { namespace Sc { class StaticSim : public RigidSim { //--------------------------------------------------------------------------------- // Construction, destruction & initialization //--------------------------------------------------------------------------------- public: StaticSim(Scene& scene, StaticCore& core) : RigidSim(scene, core) {} ~StaticSim() { getStaticCore().setSim(NULL); } PX_FORCE_INLINE StaticCore& getStaticCore() const { return static_cast<StaticCore&>(getRigidCore()); } }; } // namespace Sc } #endif
2,396
C
41.803571
115
0.687813
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScContactStream.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 SC_CONTACT_STREAM_H #define SC_CONTACT_STREAM_H #include "foundation/Px.h" #include "PxSimulationEventCallback.h" #include "ScObjectIDTracker.h" #include "ScRigidSim.h" #include "ScStaticSim.h" #include "ScBodySim.h" namespace physx { class PxShape; namespace Sc { class ActorPair; // Internal counterpart of PxContactPair struct ContactShapePair { public: PxShape* shapes[2]; const PxU8* contactPatches; const PxU8* contactPoints; const PxReal* contactForces; PxU32 requiredBufferSize; PxU8 contactCount; PxU8 patchCount; PxU16 constraintStreamSize; PxU16 flags; PxU16 events; PxU32 shapeID[2]; //26 (or 38 on 64bit) }; PX_COMPILE_TIME_ASSERT(sizeof(ContactShapePair) == sizeof(PxContactPair)); struct ContactStreamManagerFlag { enum Enum { /** \brief Need to test stream for shapes that were removed from the actor/scene Usually this is the case when a shape gets removed from the scene, however, other operations that remove the broadphase volume of a pair object have to be considered as well since the shape might get removed later after such an operation. The scenarios to consider are: \li shape gets removed (this includes raising PxActorFlag::eDISABLE_SIMULATION) \li shape switches to eSCENE_QUERY_SHAPE only \li shape switches to eTRIGGER_SHAPE \li resetFiltering() \li actor gets removed from an aggregate */ eTEST_FOR_REMOVED_SHAPES = (1<<0), /** \brief Invalid stream memory not allocated */ eINVALID_STREAM = (1<<1), /** \brief Incomplete stream will be reported */ eINCOMPLETE_STREAM = (1<<2), /** \brief The stream contains extra data with PxContactPairVelocity items where the post solver velocity needs to get written to. Only valid for discrete collision (in CCD the post response velocity is available immediately). */ eNEEDS_POST_SOLVER_VELOCITY = (1<<3), /** \brief Marker for the next available free flag */ eNEXT_FREE_FLAG = (1<<4) }; }; struct ContactStreamHeader { PxU16 contactPass; // marker for extra data to know when a new collison pass started (discrete collision -> CCD pass 1 -> CCD pass 2 -> ...) PxU16 pad; // to keep the stream 4byte aligned }; /** \brief Contact report logic and data management. The internal contact report stream has the following format: ContactStreamHeader | PxContactPairIndex0 | (PxContactPairPose0, PxContactPairVelocity0) | ... | PxContactPairIndexN | (PxContactPairPoseN, PxContactPairVelocityN) | (unused memory up to maxExtraDataSize ) | PxContactPair0 | ... | PxContactPairM | (unsued pairs up to maxPairCount) */ class ContactStreamManager { public: PX_FORCE_INLINE ContactStreamManager() : maxPairCount(0), flags_and_maxExtraDataBlocks(0) {} PX_FORCE_INLINE ~ContactStreamManager() {} PX_FORCE_INLINE void reset(); PX_FORCE_INLINE PxU16 getFlags() const; PX_FORCE_INLINE void raiseFlags(PxU16 flags); PX_FORCE_INLINE void clearFlags(PxU16 flags); PX_FORCE_INLINE PxU32 getMaxExtraDataSize() const; PX_FORCE_INLINE void setMaxExtraDataSize(PxU32 size); // size in bytes (will translate into blocks internally) PX_FORCE_INLINE Sc::ContactShapePair* getShapePairs(PxU8* contactReportPairData) const; PX_FORCE_INLINE static void convertDeletedShapesInContactStream(ContactShapePair*, PxU32 pairCount, const ObjectIDTracker&); PX_FORCE_INLINE static PxU32 computeExtraDataBlockCount(PxU32 extraDataSize); PX_FORCE_INLINE static PxU32 computeExtraDataBlockSize(PxU32 extraDataSize); PX_FORCE_INLINE static PxU16 computeContactReportExtraDataSize(PxU32 extraDataFlags, bool addHeader); PX_FORCE_INLINE static void fillInContactReportExtraData(PxContactPairVelocity*, PxU32 index, const ActorSim&, bool isCCDPass); PX_FORCE_INLINE static void fillInContactReportExtraData(PxContactPairPose*, PxU32 index, const ActorSim&, bool isCCDPass, const bool useCurrentTransform); PX_FORCE_INLINE void fillInContactReportExtraData(PxU8* stream, PxU32 extraDataFlags, const ActorSim&, const ActorSim&, PxU32 ccdPass, const bool useCurrentTransform, PxU32 pairIndex, PxU32 sizeOffset); PX_FORCE_INLINE void setContactReportPostSolverVelocity(PxU8* stream, const ActorSim&, const ActorSim&); PxU32 bufferIndex; // marks the start of the shape pair stream of the actor pair (byte offset with respect to global contact buffer stream) PxU16 maxPairCount; // used to reserve the same amount of memory as in the last frame (as an initial guess) PxU16 currentPairCount; // number of shape pairs stored in the buffer PxU16 extraDataSize; // size of the extra data section in the stream private: PxU16 flags_and_maxExtraDataBlocks; // used to reserve the same amount of memory as in the last frame (as an initial guess) public: static const PxU32 sExtraDataBlockSizePow2 = 4; // extra data gets allocated as a multiple of 2^sExtraDataBlockSizePow2 to keep memory low of this struct. static const PxU32 sFlagMask = (ContactStreamManagerFlag::eNEXT_FREE_FLAG - 1); static const PxU32 sMaxExtraDataShift = 4; // shift necessary to extract the maximum number of blocks allocated for extra data PX_COMPILE_TIME_ASSERT(ContactStreamManagerFlag::eNEXT_FREE_FLAG == (1 << sMaxExtraDataShift)); }; } // namespace Sc PX_FORCE_INLINE void Sc::ContactStreamManager::reset() { currentPairCount = 0; extraDataSize = 0; flags_and_maxExtraDataBlocks &= ~sFlagMask; } PX_FORCE_INLINE PxU16 Sc::ContactStreamManager::getFlags() const { return (flags_and_maxExtraDataBlocks & sFlagMask); } PX_FORCE_INLINE void Sc::ContactStreamManager::raiseFlags(PxU16 flags) { PX_ASSERT(flags < ContactStreamManagerFlag::eNEXT_FREE_FLAG); flags_and_maxExtraDataBlocks |= flags; } PX_FORCE_INLINE void Sc::ContactStreamManager::clearFlags(PxU16 flags) { PX_ASSERT(flags < ContactStreamManagerFlag::eNEXT_FREE_FLAG); PxU16 tmpFlags = getFlags(); tmpFlags &= ~flags; flags_and_maxExtraDataBlocks &= ~sFlagMask; raiseFlags(tmpFlags); } PX_FORCE_INLINE PxU32 Sc::ContactStreamManager::getMaxExtraDataSize() const { return PxU32((flags_and_maxExtraDataBlocks >> sMaxExtraDataShift) << sExtraDataBlockSizePow2); } PX_FORCE_INLINE void Sc::ContactStreamManager::setMaxExtraDataSize(PxU32 size) { PxU32 nbBlocks = computeExtraDataBlockCount(size); flags_and_maxExtraDataBlocks = PxTo16((flags_and_maxExtraDataBlocks & sFlagMask) | (nbBlocks << sMaxExtraDataShift)); } PX_FORCE_INLINE Sc::ContactShapePair* Sc::ContactStreamManager::getShapePairs(PxU8* contactReportPairData) const { return reinterpret_cast<Sc::ContactShapePair*>(contactReportPairData + getMaxExtraDataSize()); } PX_FORCE_INLINE void Sc::ContactStreamManager::convertDeletedShapesInContactStream(ContactShapePair* shapePairs, PxU32 pairCount, const ObjectIDTracker& tracker) { for(PxU32 i=0; i < pairCount; i++) { ContactShapePair& csp = shapePairs[i]; PxU32 shape0ID = csp.shapeID[0]; PxU32 shape1ID = csp.shapeID[1]; PxU16 flags = csp.flags; PX_COMPILE_TIME_ASSERT(sizeof(flags) == sizeof((reinterpret_cast<ContactShapePair*>(0))->flags)); if (tracker.isDeletedID(shape0ID)) flags |= PxContactPairFlag::eREMOVED_SHAPE_0; if (tracker.isDeletedID(shape1ID)) flags |= PxContactPairFlag::eREMOVED_SHAPE_1; csp.flags = flags; } } PX_FORCE_INLINE PxU32 Sc::ContactStreamManager::computeExtraDataBlockCount(PxU32 extraDataSize_) { PxU32 nbBlocks; if (extraDataSize_ & ((1 << sExtraDataBlockSizePow2) - 1)) // not a multiple of block size -> need one block more nbBlocks = (extraDataSize_ >> sExtraDataBlockSizePow2) + 1; else nbBlocks = (extraDataSize_ >> sExtraDataBlockSizePow2); return nbBlocks; } PX_FORCE_INLINE PxU32 Sc::ContactStreamManager::computeExtraDataBlockSize(PxU32 extraDataSize_) { return (computeExtraDataBlockCount(extraDataSize_) << sExtraDataBlockSizePow2); } PX_FORCE_INLINE PxU16 Sc::ContactStreamManager::computeContactReportExtraDataSize(PxU32 extraDataFlags, bool addHeader) { PX_ASSERT(extraDataFlags); PxU16 extraDataSize_ = sizeof(PxContactPairIndex); if (extraDataFlags & PxPairFlag::ePRE_SOLVER_VELOCITY) extraDataSize_ += sizeof(PxContactPairVelocity); if (extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY) extraDataSize_ += sizeof(PxContactPairVelocity); if (extraDataFlags & PxPairFlag::eCONTACT_EVENT_POSE) extraDataSize_ += sizeof(PxContactPairPose); if (addHeader) extraDataSize_ += sizeof(ContactStreamHeader); return extraDataSize_; } PX_FORCE_INLINE void Sc::ContactStreamManager::fillInContactReportExtraData(PxContactPairVelocity* cpVel, PxU32 index, const ActorSim& rs, bool isCCDPass) { if (rs.getActorType() != PxActorType::eRIGID_STATIC) { const BodySim& bs = static_cast<const BodySim&>(rs); if ((!isCCDPass) || (cpVel->type == PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY)) { const BodyCore& bc = bs.getBodyCore(); cpVel->linearVelocity[index] = bc.getLinearVelocity(); cpVel->angularVelocity[index] = bc.getAngularVelocity(); } else { PX_ASSERT(cpVel->type == PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY); const Cm::SpatialVector& vel = bs.getLowLevelBody().getPreSolverVelocities(); cpVel->linearVelocity[index] = vel.linear; cpVel->angularVelocity[index] = vel.angular; } } else { cpVel->linearVelocity[index] = PxVec3(0.0f); cpVel->angularVelocity[index] = PxVec3(0.0f); } } PX_FORCE_INLINE void Sc::ContactStreamManager::fillInContactReportExtraData(PxContactPairPose* cpPose, PxU32 index, const ActorSim& rs, bool isCCDPass, const bool useCurrentTransform) { if(rs.getActorType() != PxActorType::eRIGID_STATIC) { const BodySim& bs = static_cast<const BodySim&>(rs); const BodyCore& bc = bs.getBodyCore(); const PxTransform& src = (!isCCDPass && useCurrentTransform) ? bc.getBody2World() : bs.getLowLevelBody().getLastCCDTransform(); // PT:: tag: scalar transform*transform cpPose->globalPose[index] = src * bc.getBody2Actor().getInverse(); } else { const StaticSim& ss = static_cast<const StaticSim&>(rs); const StaticCore& sc = ss.getStaticCore(); cpPose->globalPose[index] = sc.getActor2World(); } } PX_FORCE_INLINE void Sc::ContactStreamManager::fillInContactReportExtraData(PxU8* stream, PxU32 extraDataFlags, const ActorSim& rs0, const ActorSim& rs1, PxU32 ccdPass, const bool useCurrentTransform, PxU32 pairIndex, PxU32 sizeOffset) { ContactStreamHeader* strHeader = reinterpret_cast<ContactStreamHeader*>(stream); strHeader->contactPass = PxTo16(ccdPass); stream += sizeOffset; PxU8* edStream = stream; bool isCCDPass = (ccdPass != 0); { PxContactPairIndex* cpIndex = reinterpret_cast<PxContactPairIndex*>(edStream); cpIndex->type = PxContactPairExtraDataType::eCONTACT_PAIR_INDEX; cpIndex->index = PxTo16(pairIndex); edStream += sizeof(PxContactPairIndex); PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream))); } // Important: make sure this one is the first after the PxContactPairIndex item for discrete contacts as it needs to get filled in before the reports get sent // (post solver velocity is not available when it gets created) if (extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY) { PxContactPairVelocity* cpVel = reinterpret_cast<PxContactPairVelocity*>(edStream); cpVel->type = PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY; edStream += sizeof(PxContactPairVelocity); if (!isCCDPass) raiseFlags(ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY); // don't know the post solver velocity yet else { ContactStreamManager::fillInContactReportExtraData(cpVel, 0, rs0, true); ContactStreamManager::fillInContactReportExtraData(cpVel, 1, rs1, true); } PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream))); } if (extraDataFlags & PxPairFlag::ePRE_SOLVER_VELOCITY) { PxContactPairVelocity* cpVel = reinterpret_cast<PxContactPairVelocity*>(edStream); cpVel->type = PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY; ContactStreamManager::fillInContactReportExtraData(cpVel, 0, rs0, isCCDPass); ContactStreamManager::fillInContactReportExtraData(cpVel, 1, rs1, isCCDPass); edStream += sizeof(PxContactPairVelocity); PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream))); } if (extraDataFlags & PxPairFlag::eCONTACT_EVENT_POSE) { PxContactPairPose* cpPose = reinterpret_cast<PxContactPairPose*>(edStream); cpPose->type = PxContactPairExtraDataType::eCONTACT_EVENT_POSE; ContactStreamManager::fillInContactReportExtraData(cpPose, 0, rs0, isCCDPass, useCurrentTransform); ContactStreamManager::fillInContactReportExtraData(cpPose, 1, rs1, isCCDPass, useCurrentTransform); edStream += sizeof(PxContactPairPose); PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream))); } extraDataSize = PxTo16(sizeOffset + PxU32(edStream - stream)); } PX_FORCE_INLINE void Sc::ContactStreamManager::setContactReportPostSolverVelocity(PxU8* stream, const ActorSim& rs0, const ActorSim& rs1) { PX_ASSERT(extraDataSize > (sizeof(ContactStreamHeader) + sizeof(PxContactPairIndex))); PxContactPairVelocity* cpVel = reinterpret_cast<PxContactPairVelocity*>(stream + sizeof(ContactStreamHeader) + sizeof(PxContactPairIndex)); PX_ASSERT(cpVel->type == PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY); fillInContactReportExtraData(cpVel, 0, rs0, false); fillInContactReportExtraData(cpVel, 1, rs1, false); clearFlags(ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY); } } #endif
15,260
C
36.962686
208
0.759174
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScNPhaseCore.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 SC_NPHASE_CORE_H #define SC_NPHASE_CORE_H #include "foundation/PxHash.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "foundation/PxMutex.h" #include "foundation/PxAtomic.h" #include "PxPhysXConfig.h" #include "foundation/PxPool.h" #include "PxSimulationEventCallback.h" #include "ScTriggerPairs.h" #include "ScScene.h" #include "ScContactReportBuffer.h" namespace physx { namespace Bp { struct AABBOverlap; struct BroadPhasePair; } namespace Sc { class ActorSim; class ElementSim; class ShapeSimBase; class Interaction; class ElementSimInteraction; class ElementInteractionMarker; class TriggerInteraction; class ShapeInteraction; class ActorPair; class ActorPairReport; class ActorPairContactReportData; struct ContactShapePair; class NPhaseContext; class ContactStreamManager; struct FilterPair; class FilterPairManager; class ActorSim; class TriggerContactTask; struct PairReleaseFlag { enum Enum { eRUN_LOST_TOUCH_LOGIC = (1 << 0), // run the lost-touch-logic for a pair that gets removed. eWAKE_ON_LOST_TOUCH = (1 << 1) // a pair that lost touch should check whether the actors should get woken up }; }; /* NPhaseCore encapsulates the near phase processing to allow multiple implementations(eg threading and non threaded). The broadphase inserts shape pairs into the NPhaseCore, which are then processed into contact point streams. Pairs can then be processed into AxisConstraints by the GroupSolveCore. */ struct BodyPairKey { PX_FORCE_INLINE BodyPairKey(PxU32 sim0, PxU32 sim1) : mSim0(sim0), mSim1(sim1) {} const PxU32 mSim0; const PxU32 mSim1; PX_FORCE_INLINE bool operator == (const BodyPairKey& pair) const { return mSim0 == pair.mSim0 && mSim1 == pair.mSim1; } }; PX_INLINE PxU32 PxComputeHash(const BodyPairKey& key) { const PxU32 add0 = key.mSim0; const PxU32 add1 = key.mSim1; const PxU32 base = PxU32((add0 & 0xFFFF) | (add1 << 16)); return physx::PxComputeHash(base); } struct ElementSimKey { PxU32 mID0; PxU32 mID1; ElementSimKey() : mID0(0xffffffff), mID1(0xffffffff) {} ElementSimKey(PxU32 id0, PxU32 id1) { if(id0 > id1) PxSwap(id0, id1); mID0 = id0; mID1 = id1; } PX_FORCE_INLINE bool operator == (const ElementSimKey& pair) const { return mID0 == pair.mID0 && mID1 == pair.mID1; } }; PX_INLINE PxU32 PxComputeHash(const ElementSimKey& key) { const PxU64 base = PxU64(key.mID0) | (PxU64(key.mID1) << 32); return physx::PxComputeHash(base); } class ContactReportAllocationManager { PxU8* mBuffer; PxU32 mBufferSize; PxU32 mCurrentBufferIndex; PxU32 mCurrentOffset; ContactReportBuffer& mReportBuffer; PxMutex& mMutex; const PxU32 mBuferBlockSize; PX_NOCOPY(ContactReportAllocationManager) public: ContactReportAllocationManager(ContactReportBuffer& buffer, PxMutex& mutex, const PxU32 bufferBlockSize = 16384) : mBuffer(NULL), mBufferSize(0), mCurrentBufferIndex(0), mCurrentOffset(0), mReportBuffer(buffer), mMutex(mutex), mBuferBlockSize(bufferBlockSize) { } PxU8* allocate(PxU32 size, PxU32& index, PxU32 alignment = 16u) { //(1) fix up offsets... const PxU32 pad = ((mCurrentBufferIndex + alignment - 1)&~(alignment - 1)) - mCurrentBufferIndex; PxU32 currOffset = mCurrentOffset + pad; if ((currOffset + size) > mBufferSize) { const PxU32 allocSize = PxMax(size, mBuferBlockSize); mMutex.lock(); mBuffer = mReportBuffer.allocateNotThreadSafe(allocSize, mCurrentBufferIndex, alignment); mCurrentOffset = currOffset = 0; mBufferSize = allocSize; mMutex.unlock(); } PxU8* ret = mBuffer + currOffset; index = mCurrentBufferIndex + currOffset; mCurrentOffset = currOffset + size; return ret; } }; class TriggerProcessingContext { public: TriggerProcessingContext() : mTmpTriggerProcessingBlock(NULL) , mTmpTriggerPairCount(0) { } bool initialize(TriggerInteraction**, PxU32 pairCount, PxcScratchAllocator&); void deinitialize(PxcScratchAllocator&); PX_FORCE_INLINE TriggerInteraction* const* getTriggerInteractions() const { return reinterpret_cast<TriggerInteraction**>(mTmpTriggerProcessingBlock); } PX_FORCE_INLINE PxU32 getTriggerInteractionCount() const { return mTmpTriggerPairCount; } PX_FORCE_INLINE TriggerContactTask* getTriggerContactTasks() { const PxU32 offset = mTmpTriggerPairCount * sizeof(TriggerInteraction*); return reinterpret_cast<TriggerContactTask*>(mTmpTriggerProcessingBlock + offset); } PX_FORCE_INLINE PxMutex& getTriggerWriteBackLock() { return mTriggerWriteBackLock; } private: PxU8* mTmpTriggerProcessingBlock; // temporary memory block to process trigger pairs in parallel // (see comment in Sc::Scene::postIslandGen too) PxU32 mTmpTriggerPairCount; PxMutex mTriggerWriteBackLock; }; class NPhaseCore : public PxUserAllocated { PX_NOCOPY(NPhaseCore) public: NPhaseCore(Scene& scene, const PxSceneDesc& desc); ~NPhaseCore(); ElementSimInteraction* findInteraction(const ElementSim* element0, const ElementSim* element1); void onTriggerOverlapCreated(const Bp::AABBOverlap* PX_RESTRICT pairs, PxU32 pairCount); void runOverlapFilters( PxU32 nbToProcess, const Bp::AABBOverlap* PX_RESTRICT pairs, FilterInfo* PX_RESTRICT filterInfo, PxU32& nbToKeep, PxU32& nbToSuppress, PxU32* PX_RESTRICT keepMap); void onOverlapRemoved(ElementSim* volume0, ElementSim* volume1, PxU32 ccdPass, void* elemSim, PxsContactManagerOutputIterator& outputs); void onVolumeRemoved(ElementSim* volume, PxU32 flags, PxsContactManagerOutputIterator& outputs); void managerNewTouch(Sc::ShapeInteraction& interaction); PxU32 getDefaultContactReportStreamBufferSize() const; void fireCustomFilteringCallbacks(PxsContactManagerOutputIterator& outputs); void addToDirtyInteractionList(Interaction* interaction); void removeFromDirtyInteractionList(Interaction* interaction); void updateDirtyInteractions(PxsContactManagerOutputIterator& outputs); /** \brief Allocate buffers for trigger overlap test. See comment in Sc::Scene::postIslandGen for why this is split up into multiple parts. \param[in] continuation The task to run after trigger processing. \return The concluding trigger processing task if there is work to do, else NULL. */ PxBaseTask* prepareForTriggerInteractionProcessing(PxBaseTask* continuation); // Perform trigger overlap tests. void processTriggerInteractions(PxBaseTask& continuation); // Deactivate trigger interactions if possible, free buffers from overlap tests and clean up. // See comment in Sc::Scene::postIslandGen for why this is split up into multiple parts. void concludeTriggerInteractionProcessing(PxBaseTask* continuation); // Check candidates for persistent touch contact events and create those events if necessary. void processPersistentContactEvents(PxsContactManagerOutputIterator& outputs); PX_FORCE_INLINE void addToContactReportActorPairSet(ActorPairReport* pair) { mContactReportActorPairSet.pushBack(pair); } void clearContactReportActorPairs(bool shrinkToZero); PX_FORCE_INLINE PxU32 getNbContactReportActorPairs() const { return mContactReportActorPairSet.size(); } PX_FORCE_INLINE ActorPairReport* const* getContactReportActorPairs() const { return mContactReportActorPairSet.begin(); } void addToPersistentContactEventPairs(ShapeInteraction*); void addToPersistentContactEventPairsDelayed(ShapeInteraction*); void removeFromPersistentContactEventPairs(ShapeInteraction*); PX_FORCE_INLINE PxU32 getCurrentPersistentContactEventPairCount() const { return mNextFramePersistentContactEventPairIndex; } PX_FORCE_INLINE ShapeInteraction* const* getCurrentPersistentContactEventPairs() const { return mPersistentContactEventPairList.begin(); } PX_FORCE_INLINE PxU32 getAllPersistentContactEventPairCount() const { return mPersistentContactEventPairList.size(); } PX_FORCE_INLINE ShapeInteraction* const* getAllPersistentContactEventPairs() const { return mPersistentContactEventPairList.begin(); } PX_FORCE_INLINE void preparePersistentContactEventListForNextFrame(); void addToForceThresholdContactEventPairs(ShapeInteraction*); void removeFromForceThresholdContactEventPairs(ShapeInteraction*); PX_FORCE_INLINE PxU32 getForceThresholdContactEventPairCount() const { return mForceThresholdContactEventPairList.size(); } PX_FORCE_INLINE ShapeInteraction* const* getForceThresholdContactEventPairs() const { return mForceThresholdContactEventPairList.begin(); } PX_FORCE_INLINE PxU8* getContactReportPairData(const PxU32& bufferIndex) const { return mContactReportBuffer.getData(bufferIndex); } PxU8* reserveContactReportPairData(PxU32 pairCount, PxU32 extraDataSize, PxU32& bufferIndex, ContactReportAllocationManager* alloc = NULL); PxU8* resizeContactReportPairData(PxU32 pairCount, PxU32 extraDataSize, Sc::ContactStreamManager& csm); PX_FORCE_INLINE void clearContactReportStream() { mContactReportBuffer.reset(); } // Do not free memory at all PX_FORCE_INLINE void freeContactReportStreamMemory() { mContactReportBuffer.flush(); } ActorPairContactReportData* createActorPairContactReportData(); void releaseActorPairContactReportData(ActorPairContactReportData* data); void registerInteraction(ElementSimInteraction* interaction); void unregisterInteraction(ElementSimInteraction* interaction); ElementSimInteraction* createRbElementInteraction(const FilterInfo& fInfo, ShapeSimBase& s0, ShapeSimBase& s1, PxsContactManager* contactManager, Sc::ShapeInteraction* shapeInteraction, Sc::ElementInteractionMarker* interactionMarker, bool isTriggerPair); void lockReports() { mReportAllocLock.lock(); } void unlockReports() { mReportAllocLock.unlock(); } private: void callPairLost(const ShapeSimBase& s0, const ShapeSimBase& s1, bool objVolumeRemoved); ElementSimInteraction* createTriggerElementInteraction(ShapeSimBase& s0, ShapeSimBase& s1); // removedElement: points to the removed element (that is, the BP volume wrapper), if a pair gets removed or loses touch due to a removed element. // NULL if not triggered by a removed element. // void releaseElementPair(ElementSimInteraction* pair, PxU32 flags, ElementSim* removedElement, PxU32 ccdPass, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs); void lostTouchReports(ShapeInteraction* pair, PxU32 flags, ElementSim* removedElement, PxU32 ccdPass, PxsContactManagerOutputIterator& outputs); ShapeInteraction* createShapeInteraction(ShapeSimBase& s0, ShapeSimBase& s1, PxPairFlags pairFlags, PxsContactManager* contactManager, Sc::ShapeInteraction* shapeInteraction); TriggerInteraction* createTriggerInteraction(ShapeSimBase& s0, ShapeSimBase& s1, PxPairFlags triggerFlags); ElementInteractionMarker* createElementInteractionMarker(ElementSim& e0, ElementSim& e1, ElementInteractionMarker* marker); //------------- Filtering ------------- ElementSimInteraction* refilterInteraction(ElementSimInteraction* pair, const FilterInfo* filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs); //------------------------------------- ElementSimInteraction* convert(ElementSimInteraction* pair, InteractionType::Enum type, FilterInfo& filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs); ActorPair* findActorPair(ShapeSimBase* s0, ShapeSimBase* s1, PxIntBool isReportPair); PX_FORCE_INLINE void destroyActorPairReport(ActorPairReport&); // Pooling Scene& mOwnerScene; PxArray<ActorPairReport*> mContactReportActorPairSet; PxArray<ShapeInteraction*> mPersistentContactEventPairList; // Pairs which request events which do not get triggered by the sdk and thus need to be tested actively every frame. // May also contain force threshold event pairs (see mForceThresholdContactEventPairList) // This list is split in two, the elements in front are for the current frame, the elements at the // back will get added next frame. PxU32 mNextFramePersistentContactEventPairIndex; // start index of the pairs which need to get added to the persistent list for next frame PxArray<ShapeInteraction*> mForceThresholdContactEventPairList; // Pairs which request force threshold contact events. A pair is only in this list if it does have contact. // Note: If a pair additionally requests PxPairFlag::eNOTIFY_TOUCH_PERSISTS events, then it // goes into mPersistentContactEventPairList instead. This allows to share the list index. // data layout: // ContactActorPair0_ExtraData, ContactShapePair0_0, ContactShapePair0_1, ... ContactShapePair0_N, // ContactActorPair1_ExtraData, ContactShapePair1_0, ... // ContactReportBuffer mContactReportBuffer; // Shape pair information for contact reports PxCoalescedHashSet<Interaction*> mDirtyInteractions; // Pools PxPool<ActorPair> mActorPairPool; PxPool<ActorPairReport> mActorPairReportPool; PxPool<ShapeInteraction> mShapeInteractionPool; PxPool<TriggerInteraction> mTriggerInteractionPool; PxPool<ActorPairContactReportData> mActorPairContactReportDataPool; PxPool<ElementInteractionMarker> mInteractionMarkerPool; Cm::DelegateTask<Sc::NPhaseCore, &Sc::NPhaseCore::concludeTriggerInteractionProcessing> mConcludeTriggerInteractionProcessingTask; TriggerProcessingContext mTriggerProcessingContext; PxHashMap<BodyPairKey, ActorPair*> mActorPairMap; PxHashMap<ElementSimKey, ElementSimInteraction*> mElementSimMap; PxMutex mBufferAllocLock; PxMutex mReportAllocLock; friend class Sc::Scene; friend class Sc::ShapeInteraction; }; struct FilteringContext { PX_NOCOPY(FilteringContext) public: FilteringContext(const Sc::Scene& scene) : mFilterShader (scene.getFilterShaderFast()), mFilterShaderData (scene.getFilterShaderDataFast()), mFilterShaderDataSize (scene.getFilterShaderDataSizeFast()), mFilterCallback (scene.getFilterCallbackFast()), mKineKineFilteringMode (scene.getKineKineFilteringMode()), mStaticKineFilteringMode(scene.getStaticKineFilteringMode()) { } PxSimulationFilterShader mFilterShader; const void* mFilterShaderData; PxU32 mFilterShaderDataSize; PxSimulationFilterCallback* mFilterCallback; const PxPairFilteringMode::Enum mKineKineFilteringMode; const PxPairFilteringMode::Enum mStaticKineFilteringMode; }; } // namespace Sc PX_FORCE_INLINE void Sc::NPhaseCore::preparePersistentContactEventListForNextFrame() { // reports have been processed -> "activate" next frame candidates for persistent contact events mNextFramePersistentContactEventPairIndex = mPersistentContactEventPairList.size(); } } #endif
16,717
C
39.1875
188
0.77155
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeInteraction.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 "ScShapeInteraction.h" #if PX_SUPPORT_GPU_PHYSX #include "ScParticleSystemSim.h" #endif using namespace physx; Sc::ShapeInteraction::ShapeInteraction(ShapeSimBase& s1, ShapeSimBase& s2, PxPairFlags pairFlags, PxsContactManager* contactManager) : ElementSimInteraction (s1, s2, InteractionType::eOVERLAP, InteractionFlag::eRB_ELEMENT|InteractionFlag::eFILTERABLE), mActorPair (NULL), mManager (NULL), mContactReportStamp (PX_INVALID_U32), mReportPairIndex (INVALID_REPORT_PAIR_ID), mEdgeIndex (IG_INVALID_EDGE), mReportStreamIndex (0) { mFlags = 0; // The PxPairFlags get stored in the SipFlag, make sure any changes get noticed PX_COMPILE_TIME_ASSERT(PxPairFlag::eSOLVE_CONTACT == (1<<0)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eMODIFY_CONTACTS == (1<<1)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_FOUND == (1<<2)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_PERSISTS == (1<<3)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_LOST == (1<<4)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_CCD == (1<<5)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND == (1<<6)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS == (1<<7)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST == (1<<8)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_CONTACT_POINTS == (1<<9)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eDETECT_DISCRETE_CONTACT == (1<<10)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eDETECT_CCD_CONTACT == (1<<11)); PX_COMPILE_TIME_ASSERT(PxPairFlag::ePRE_SOLVER_VELOCITY == (1<<12)); PX_COMPILE_TIME_ASSERT(PxPairFlag::ePOST_SOLVER_VELOCITY == (1<<13)); PX_COMPILE_TIME_ASSERT(PxPairFlag::eCONTACT_EVENT_POSE == (1<<14)); PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eSOLVE_CONTACT) == PxPairFlag::eSOLVE_CONTACT); PX_COMPILE_TIME_ASSERT((PxPairFlag::eSOLVE_CONTACT | PAIR_FLAGS_MASK) == PAIR_FLAGS_MASK); PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eCONTACT_EVENT_POSE) == PxPairFlag::eCONTACT_EVENT_POSE); PX_COMPILE_TIME_ASSERT((PxPairFlag::eCONTACT_EVENT_POSE | PAIR_FLAGS_MASK) == PAIR_FLAGS_MASK); setPairFlags(pairFlags); //Add a fresh edge to the island manager. Scene& scene = getScene(); //Sc::BodySim* bs0 = getShape0().getBodySim(); //Sc::BodySim* bs1 = getShape1().getBodySim(); Sc::ActorSim& bs0 = getShape0().getActor(); Sc::ActorSim& bs1 = getShape1().getActor(); updateFlags(scene, bs0, bs1, pairFlags); if(contactManager == NULL) { PxNodeIndex indexA, indexB; //if(bs0) // the first shape always belongs to a dynamic body (we assert for this above) { indexA = bs0.getNodeIndex(); bs0.registerCountedInteraction(); } if(!bs1.isStaticRigid()) { indexB = bs1.getNodeIndex(); bs1.registerCountedInteraction(); } IG::SimpleIslandManager* simpleIslandManager = scene.getSimpleIslandManager(); const PxActorType::Enum actorTypeLargest = PxMax(bs0.getActorType(), bs1.getActorType()); IG::Edge::EdgeType type = IG::Edge::eCONTACT_MANAGER; #if PX_SUPPORT_GPU_PHYSX if (actorTypeLargest == PxActorType::eSOFTBODY) type = IG::Edge::eSOFT_BODY_CONTACT; if (actorTypeLargest == PxActorType::eFEMCLOTH) type = IG::Edge::eFEM_CLOTH_CONTACT; else if (isParticleSystem(actorTypeLargest)) type = IG::Edge::ePARTICLE_SYSTEM_CONTACT; else if (actorTypeLargest == PxActorType::eHAIRSYSTEM) type = IG::Edge::eHAIR_SYSTEM_CONTACT; #endif mEdgeIndex = simpleIslandManager->addContactManager(NULL, indexA, indexB, this, type); { const bool active = onActivate(contactManager); registerInActors(); scene.registerInteraction(this, active); } //If it is a soft body or particle overlap, treat it as a contact for now (we can hook up touch found/lost events later maybe) if (actorTypeLargest > PxActorType::eARTICULATION_LINK) simpleIslandManager->setEdgeConnected(mEdgeIndex, type); } else { onActivate(contactManager); } } Sc::ShapeInteraction::~ShapeInteraction() { Sc::ActorSim* body0 = &getShape0().getActor(); Sc::ActorSim* body1 = &getShape1().getActor(); body0->unregisterCountedInteraction(); if (body1) body1->unregisterCountedInteraction(); if(mManager) destroyManager(); if(mEdgeIndex != IG_INVALID_EDGE) { Scene& scene = getScene(); scene.getSimpleIslandManager()->removeConnection(mEdgeIndex); mEdgeIndex = IG_INVALID_EDGE; scene.unregisterInteraction(this); } // This will remove the interaction from the actors list, which will prevent // update calls to this actor because of Body::wakeUp below. unregisterFromActors(); if(mReportPairIndex != INVALID_REPORT_PAIR_ID) removeFromReportPairList(); } void Sc::ShapeInteraction::clearIslandGenData() { if(mEdgeIndex != IG_INVALID_EDGE) { Scene& scene = getScene(); scene.getSimpleIslandManager()->removeConnection(mEdgeIndex); mEdgeIndex = IG_INVALID_EDGE; } } PX_FORCE_INLINE void Sc::ShapeInteraction::processReportPairOnActivate() { PX_ASSERT(isReportPair()); PX_ASSERT(mReportPairIndex == INVALID_REPORT_PAIR_ID); if(readFlag(WAS_IN_PERSISTENT_EVENT_LIST)) { getScene().getNPhaseCore()->addToPersistentContactEventPairs(this); mFlags &= ~WAS_IN_PERSISTENT_EVENT_LIST; } } PX_FORCE_INLINE void Sc::ShapeInteraction::processReportPairOnDeactivate() { PX_ASSERT(isReportPair()); PX_ASSERT(mReportPairIndex != INVALID_REPORT_PAIR_ID); PX_COMPILE_TIME_ASSERT(IS_IN_PERSISTENT_EVENT_LIST == (WAS_IN_PERSISTENT_EVENT_LIST >> 1)); PX_ASSERT(!(readFlag(WAS_IN_PERSISTENT_EVENT_LIST))); const PxU32 wasInPersList = (mFlags & IS_IN_PERSISTENT_EVENT_LIST) << 1; mFlags |= wasInPersList; removeFromReportPairList(); } void Sc::ShapeInteraction::setContactReportPostSolverVelocity(ContactStreamManager& cs) { Scene& scene = getScene(); NPhaseCore* npcore = scene.getNPhaseCore(); PxU8* stream = npcore->getContactReportPairData(cs.bufferIndex); ActorPairReport& apr = getActorPairReport(); cs.setContactReportPostSolverVelocity(stream, apr.getActorA(), apr.getActorB()); } void Sc::ShapeInteraction::resetManagerCachedState() const { if(mManager) { Sc::Scene& scene = getScene(); PxvNphaseImplementationContext* nphaseImplementationContext = scene.getLowLevelContext()->getNphaseImplementationContext(); PX_ASSERT(nphaseImplementationContext); mManager->resetCachedState(); nphaseImplementationContext->refreshContactManager(mManager); } } /* This method can be called from various stages in the pipeline, some of which operate before the actor has advanced its pose and some after it has advanced its pose. Discrete touch found events operate before the pose has been updated. This is because we are using the found event to active the bodies before solve so that we can just solve the activated bodies. Lost touch events occur after the pose has been updated. */ void Sc::ShapeInteraction::processUserNotificationSync() { PX_ASSERT(hasTouch()); if(mManager) PxPrefetchLine(mManager); // make sure shape A and shape B are the same way round as the actors (in compounds they may be swapped) // TODO: make "unswapped" a SIP flag and set it in updateState() if(!mActorPair) return; NPhaseCore* npcore = getScene().getNPhaseCore(); ActorPairReport& aPairReport = getActorPairReport(); if(!aPairReport.isInContactReportActorPairSet()) { aPairReport.setInContactReportActorPairSet(); npcore->addToContactReportActorPairSet(&aPairReport); aPairReport.incRefCount(); } aPairReport.createContactStreamManager(*npcore); } void Sc::ShapeInteraction::processUserNotificationAsync(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform, PxsContactManagerOutputIterator& outputs, ContactReportAllocationManager* alloc) { contactEvent = (!ccdPass) ? contactEvent : (contactEvent | PxPairFlag::eNOTIFY_TOUCH_CCD); if(!mActorPair) return; ActorPairReport& aPairReport = getActorPairReport(); Scene& scene = getScene(); NPhaseCore* npcore = scene.getNPhaseCore(); ContactStreamManager& cs = aPairReport.createContactStreamManager(*npcore); // Prepare user notification const PxU32 timeStamp = scene.getTimeStamp(); const PxU32 shapePairTimeStamp = scene.getReportShapePairTimeStamp(); const PxU32 pairFlags = getPairFlags(); PX_ASSERT(pairFlags & contactEvent); const PxU32 extraDataFlags = pairFlags & CONTACT_REPORT_EXTRA_DATA; PxU8* stream = NULL; ContactShapePair* pairStream = NULL; const bool unswapped = &aPairReport.getActorA() == &getShape0().getActor(); const Sc::ShapeSimBase& shapeA = unswapped ? getShape0() : getShape1(); const Sc::ShapeSimBase& shapeB = unswapped ? getShape1() : getShape0(); if(aPairReport.streamResetStamp(timeStamp)) { PX_ASSERT(mContactReportStamp != shapePairTimeStamp); // actor pair and shape pair timestamps must both be out of sync in this case PxU16 maxCount; if(cs.maxPairCount != 0) maxCount = cs.maxPairCount; // use value from previous report else { // TODO: Use some kind of heuristic maxCount = 2; cs.maxPairCount = maxCount; } PxU32 maxExtraDataSize; if(!extraDataFlags || touchLost) { maxExtraDataSize = 0; cs.setMaxExtraDataSize(maxExtraDataSize); } else { PxU32 currentMaxExtraDataSize = cs.getMaxExtraDataSize(); maxExtraDataSize = ContactStreamManager::computeContactReportExtraDataSize(extraDataFlags, true); PX_ASSERT(maxExtraDataSize > 0); if(maxExtraDataSize <= currentMaxExtraDataSize) maxExtraDataSize = currentMaxExtraDataSize; // use value from previous report else cs.setMaxExtraDataSize(maxExtraDataSize); } stream = npcore->reserveContactReportPairData(maxCount, maxExtraDataSize, cs.bufferIndex, alloc); if(!maxExtraDataSize) // this is the usual case, so set it first for branch prediction cs.reset(); else if(stream) { cs.reset(); PX_ASSERT(extraDataFlags); PX_ASSERT(!touchLost); cs.fillInContactReportExtraData(stream, extraDataFlags, aPairReport.getActorA(), aPairReport.getActorB(), ccdPass, useCurrentTransform, 0, sizeof(ContactStreamHeader)); if((extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY) && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT)) scene.setPostSolverVelocityNeeded(); } } else { const PxU32 currentPairCount = cs.currentPairCount; if(currentPairCount != 0) { PxU8* tmpStreamPtr = npcore->getContactReportPairData(cs.bufferIndex); if(!extraDataFlags) stream = tmpStreamPtr; // this is the usual case, so set it first for branch prediction else { if(!touchLost) { // - the first few shape pair events might not request extra data // - the events so far were due to touch lost // - multiple reports due to CCD multiple passes // Hence, the extra data has to be created/extended now. // const PxU16 oldExtraDataSize = cs.extraDataSize; PxI32 lastContactPass; if(oldExtraDataSize) { ContactStreamHeader* strHeader = reinterpret_cast<ContactStreamHeader*>(tmpStreamPtr); lastContactPass = strHeader->contactPass; } else lastContactPass = -1; if(PxI32(ccdPass) > lastContactPass) // do not send extra data mulitple times for the same contact pass { const PxU16 extraDataSize = PxU16(oldExtraDataSize + ContactStreamManager::computeContactReportExtraDataSize(extraDataFlags, (oldExtraDataSize == 0))); PxU8* strPtr; if (extraDataSize <= cs.getMaxExtraDataSize()) strPtr = tmpStreamPtr; else strPtr = npcore->resizeContactReportPairData(currentPairCount < cs.maxPairCount ? cs.maxPairCount : PxU32(cs.maxPairCount+1), extraDataSize, cs); // the check for max pair count is there to avoid another potential allocation further below if(strPtr) { stream = strPtr; PxU32 sizeOffset; if(oldExtraDataSize) sizeOffset = oldExtraDataSize; else sizeOffset = sizeof(ContactStreamHeader); cs.fillInContactReportExtraData(strPtr, extraDataFlags, aPairReport.getActorA(), aPairReport.getActorB(), ccdPass, useCurrentTransform, currentPairCount, sizeOffset); if((extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY) && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT)) scene.setPostSolverVelocityNeeded(); } else { stream = tmpStreamPtr; cs.raiseFlags(ContactStreamManagerFlag::eINCOMPLETE_STREAM); } } else stream = tmpStreamPtr; } else stream = tmpStreamPtr; } } } if(stream) pairStream = cs.getShapePairs(stream); else { cs.raiseFlags(ContactStreamManagerFlag::eINVALID_STREAM); return; } ContactShapePair* cp; if(mContactReportStamp != shapePairTimeStamp) { // this shape pair is not in the contact notification stream yet if(cs.currentPairCount < cs.maxPairCount) cp = pairStream + cs.currentPairCount; else { const PxU32 newSize = PxU32(cs.currentPairCount + (cs.currentPairCount >> 1) + 1); stream = npcore->resizeContactReportPairData(newSize, cs.getMaxExtraDataSize(), cs); if(stream) { pairStream = cs.getShapePairs(stream); cp = pairStream + cs.currentPairCount; } else { cs.raiseFlags(ContactStreamManagerFlag::eINCOMPLETE_STREAM); return; } } //!!! why is alignment important here? Looks almost like some refactor nonsense PX_ASSERT(0==(reinterpret_cast<uintptr_t>(stream) & 0x0f)); // check 16Byte alignment mReportStreamIndex = cs.currentPairCount; cp->shapes[0] = shapeA.getPxShape(); cp->shapes[1] = shapeB.getPxShape(); cp->contactPatches = NULL; cp->contactPoints = NULL; cp->contactForces = NULL; cp->contactCount = 0; cp->patchCount = 0; cp->constraintStreamSize = 0; cp->requiredBufferSize = 0; cp->flags = infoFlags; PX_ASSERT(contactEvent <= 0xffff); cp->events = PxU16(contactEvent); cp->shapeID[0] = shapeA.getElementID(); cp->shapeID[1] = shapeB.getElementID(); cs.currentPairCount++; mContactReportStamp = shapePairTimeStamp; } else { // this shape pair is in the contact notification stream already but there is a second event (can happen with force threshold reports, for example). PX_ASSERT(mReportStreamIndex < cs.currentPairCount); cp = &pairStream[mReportStreamIndex]; cp->events |= contactEvent; if(touchLost && cp->events & PxPairFlag::eNOTIFY_TOUCH_PERSISTS) cp->events &= PxU16(~PxPairFlag::eNOTIFY_TOUCH_PERSISTS); cp->flags |= infoFlags; } if((getPairFlags() & PxPairFlag::eNOTIFY_CONTACT_POINTS) && mManager && (!cp->contactPatches) && !(contactEvent & PxU32(PxPairFlag::eNOTIFY_TOUCH_LOST | PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST))) { const PxcNpWorkUnit& workUnit = mManager->getWorkUnit(); PxsContactManagerOutput* output = NULL; if(workUnit.mNpIndex & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK) output = &getScene().getLowLevelContext()->getNphaseImplementationContext()->getNewContactManagerOutput(workUnit.mNpIndex); else output = &outputs.getContactManager(workUnit.mNpIndex); const PxsCCDContactHeader* ccdContactData = reinterpret_cast<const PxsCCDContactHeader*>(workUnit.ccdContacts); const bool isCCDPass = (ccdPass != 0); if((output->nbPatches && !isCCDPass) || (ccdContactData && (!ccdContactData->isFromPreviousPass) && isCCDPass)) { const PxU8* contactPatchData; const PxU8* contactPointData; PxU32 cDataSize; PxU32 alignedContactDataSize; const PxReal* impulses; PxU32 nbPoints = output->nbContacts; PxU32 contactPatchCount = output->nbPatches; if(!isCCDPass) { PX_ASSERT(0==(reinterpret_cast<const uintptr_t>(output->contactPatches) & 0x0f)); // check 16Byte alignment contactPatchData = output->contactPatches; contactPointData = output->contactPoints; cDataSize = sizeof(PxContactPatch)*output->nbPatches + sizeof(PxContact)*output->nbContacts; alignedContactDataSize = (cDataSize + 0xf) & 0xfffffff0; impulses = output->contactForces; } else { PX_ASSERT(0==(reinterpret_cast<const uintptr_t>(ccdContactData) & 0x0f)); // check 16Byte alignment contactPatchData = reinterpret_cast<const PxU8*>(ccdContactData) + sizeof(PxsCCDContactHeader); contactPointData = contactPatchData + sizeof(PxContactPatch); cDataSize = ccdContactData->contactStreamSize - sizeof(PxsCCDContactHeader); PxU32 tmpAlignedSize = (ccdContactData->contactStreamSize + 0xf) & 0xfffffff0; alignedContactDataSize = tmpAlignedSize - sizeof(PxsCCDContactHeader); impulses = reinterpret_cast<const PxReal*>(contactPatchData + alignedContactDataSize); nbPoints = 1; contactPatchCount = 1; } infoFlags = cp->flags; infoFlags |= unswapped ? 0 : PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED; //PX_ASSERT(0==(reinterpret_cast<const uintptr_t>(impulses) & 0x0f)); const PxU32 impulseSize = impulses ? (nbPoints * sizeof(PxReal)) : 0; if(impulseSize) infoFlags |= PxContactPairFlag::eINTERNAL_HAS_IMPULSES; cp->contactPatches = contactPatchData; cp->contactPoints = contactPointData; cp->contactCount = PxTo8(nbPoints); cp->patchCount = PxTo8(contactPatchCount); cp->constraintStreamSize = PxTo16(cDataSize); cp->requiredBufferSize = alignedContactDataSize + impulseSize; cp->contactForces = impulses; cp->flags = infoFlags; } } } void Sc::ShapeInteraction::processUserNotification(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform, PxsContactManagerOutputIterator& outputs) { processUserNotificationSync(); processUserNotificationAsync(contactEvent, infoFlags, touchLost, ccdPass, useCurrentTransform, outputs); } PxU32 Sc::ShapeInteraction::getContactPointData(const void*& contactPatches, const void*& contactPoints, PxU32& contactDataSize, PxU32& contactPointCount, PxU32& numPatches, const PxReal*& impulses, PxU32 startOffset, PxsContactManagerOutputIterator& outputs) { // Process LL generated contacts if(mManager != NULL) { const PxcNpWorkUnit& workUnit = mManager->getWorkUnit(); PxsContactManagerOutput* output = NULL; if(workUnit.mNpIndex & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK) output = &getScene().getLowLevelContext()->getNphaseImplementationContext()->getNewContactManagerOutput(workUnit.mNpIndex); else output = &outputs.getContactManager(workUnit.mNpIndex); /*const void* dcdContactPatches; const void* dcdContactPoints; PxU32 dcdContactPatchCount; const PxReal* dcdImpulses; const PxsCCDContactHeader* ccdContactStream; PxU32 dcdContactCount = mManager->getContactPointData(dcdContactPatches, dcdContactPoints, dcdContactPatchCount, dcdImpulses, ccdContactStream); PX_ASSERT(((dcdContactCount == 0) && (!ccdContactStream)) || ((dcdContactCount > 0) && hasTouch()) || (ccdContactStream && hasCCDTouch()));*/ const PxsCCDContactHeader* ccdContactStream = reinterpret_cast<const PxsCCDContactHeader*>(workUnit.ccdContacts); PxU32 idx = 0; if(output) // preventive measure for omnicrash OM-109664 { if(output->nbContacts) { if(startOffset == 0) { contactPatches = output->contactPatches; contactPoints = output->contactPoints; contactDataSize = sizeof(PxContactPatch) * output->nbPatches + sizeof(PxContact) * output->nbContacts; contactPointCount = output->nbContacts; numPatches = output->nbPatches; impulses = output->contactForces; if(!ccdContactStream) return startOffset; else return (startOffset + 1); } idx++; } while(ccdContactStream) { if(startOffset == idx) { const PxU8* stream = reinterpret_cast<const PxU8*>(ccdContactStream); PxU16 streamSize = ccdContactStream->contactStreamSize; contactPatches = stream + sizeof(PxsCCDContactHeader); contactPoints = stream + sizeof(PxsCCDContactHeader) + sizeof(PxContactPatch); contactDataSize = streamSize - sizeof(PxsCCDContactHeader); contactPointCount = 1; numPatches = 1; impulses = reinterpret_cast<const PxReal*>(stream + ((streamSize + 0xf) & 0xfffffff0)); if(!ccdContactStream->nextStream) return startOffset; else return (startOffset + 1); } idx++; ccdContactStream = ccdContactStream->nextStream; } } } else { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PxsContactManagerOutput output is null!\n"); } contactPatches = NULL; contactPoints = NULL; contactDataSize = 0; contactPointCount = 0; numPatches = 0; impulses = NULL; return startOffset; } // Note that LL will not send end touch events for managers that are destroyed while having contact void Sc::ShapeInteraction::managerNewTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs) { if(readFlag(HAS_TOUCH)) return; // Do not count the touch twice (for instance when recreating a manager with touch) // We have contact this frame setHasTouch(); if(adjustCounters) adjustCountersOnNewTouch(); if(!isReportPair()) return; else { PX_ASSERT(hasTouch()); PX_ASSERT(!readFlag(IS_IN_PERSISTENT_EVENT_LIST)); PX_ASSERT(!readFlag(IS_IN_FORCE_THRESHOLD_EVENT_LIST)); const PxU32 pairFlags = getPairFlags(); if(pairFlags & PxPairFlag::eNOTIFY_TOUCH_FOUND) { PxU16 infoFlag = 0; if(mActorPair->getTouchCount() == 1) // this code assumes that the actor pair touch count does get incremented beforehand infoFlag = PxContactPairFlag::eACTOR_PAIR_HAS_FIRST_TOUCH; processUserNotification(PxPairFlag::eNOTIFY_TOUCH_FOUND, infoFlag, false, ccdPass, true, outputs); } if(pairFlags & PxPairFlag::eNOTIFY_TOUCH_PERSISTS) { getScene().getNPhaseCore()->addToPersistentContactEventPairsDelayed(this); // to make sure that from now on, the pairs are tested for persistent contact events } else if(pairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS) { // new touch -> need to start checking for force threshold events // Note: this code assumes that it runs before the pairs get tested for force threshold exceeded getScene().getNPhaseCore()->addToForceThresholdContactEventPairs(this); } } } bool Sc::ShapeInteraction::managerLostTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs) { if(!readFlag(HAS_TOUCH)) return false; // We do not have LL contacts this frame and also we lost LL contact this frame if(!isReportPair()) { setHasNoTouch(); } else { PX_ASSERT(hasTouch()); sendLostTouchReport(false, ccdPass, outputs); if(readFlag(IS_IN_CONTACT_EVENT_LIST)) { // don't need to worry about persistent/force-threshold contact events until next new touch if(readFlag(IS_IN_FORCE_THRESHOLD_EVENT_LIST)) { getScene().getNPhaseCore()->removeFromForceThresholdContactEventPairs(this); } else { PX_ASSERT(readFlag(IS_IN_PERSISTENT_EVENT_LIST)); getScene().getNPhaseCore()->removeFromPersistentContactEventPairs(this); } clearFlag(FORCE_THRESHOLD_EXCEEDED_FLAGS); } setHasNoTouch(); } ActorSim& body0 = getShape0().getActor(); ActorSim& body1 = getShape1().getActor(); if(adjustCounters) adjustCountersOnLostTouch(); if(body1.isStaticRigid()) { body0.internalWakeUp(); return false; } return true; } PX_FORCE_INLINE void Sc::ShapeInteraction::updateFlags(const Sc::Scene& scene, const Sc::ActorSim& bs0, const Sc::ActorSim& bs1, const PxU32 pairFlags) { // the first shape always belongs to a dynamic body/ a soft body bool enabled = true; if (bs0.isDynamicRigid()) { const Sc::BodySim& body0 = static_cast<const Sc::BodySim&>(bs0); enabled = !body0.isKinematic(); } if (bs1.isDynamicRigid()) { const Sc::BodySim& body1 = static_cast<const Sc::BodySim&>(bs1); enabled |= !body1.isKinematic(); } // Check if collision response is disabled enabled = enabled && (pairFlags & PxPairFlag::eSOLVE_CONTACT); setFlag(CONTACTS_RESPONSE_DISABLED, !enabled); // Check if contact points needed setFlag(CONTACTS_COLLECT_POINTS, ( (pairFlags & PxPairFlag::eNOTIFY_CONTACT_POINTS) || (pairFlags & PxPairFlag::eMODIFY_CONTACTS) || scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT) || scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL) || scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_ERROR) || scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_FORCE)) ); } PX_INLINE PxReal ScGetRestOffset(const Sc::ShapeSimBase& shapeSim) { #if PX_SUPPORT_GPU_PHYSX if (shapeSim.getActor().isParticleSystem()) return static_cast<Sc::ParticleSystemSim&>(shapeSim.getActor()).getCore().getRestOffset(); #endif return shapeSim.getRestOffset(); } void Sc::ShapeInteraction::updateState(const PxU8 externalDirtyFlags) { const PxU32 oldContactState = getManagerContactState(); const PxU8 dirtyFlags = PxU8(getDirtyFlags() | externalDirtyFlags); const PxU32 pairFlags = getPairFlags(); Scene& scene = getScene(); IG::SimpleIslandManager* islandManager = scene.getSimpleIslandManager(); if(dirtyFlags & (InteractionDirtyFlag::eFILTER_STATE | InteractionDirtyFlag::eVISUALIZATION)) { Sc::ActorSim& bs0 = getShape0().getActor(); Sc::ActorSim& bs1 = getShape1().getActor(); PxIntBool wasDisabled = readFlag(CONTACTS_RESPONSE_DISABLED); updateFlags(scene, bs0, bs1, pairFlags); PxIntBool isDisabled = readFlag(CONTACTS_RESPONSE_DISABLED); if(!wasDisabled && isDisabled) { islandManager->setEdgeDisconnected(mEdgeIndex); } else if(wasDisabled && !isDisabled) { if(readFlag(ShapeInteraction::HAS_TOUCH)) islandManager->setEdgeConnected(mEdgeIndex, IG::Edge::eCONTACT_MANAGER); } } const PxU32 newContactState = getManagerContactState(); const bool recreateManager = (oldContactState != newContactState); // No use in updating manager properties if the manager is going to be re-created or does not exist yet if((!recreateManager) && (mManager != 0)) { ShapeSimBase& shapeSim0 = getShape0(); ShapeSimBase& shapeSim1 = getShape1(); // Update dominance if(dirtyFlags & InteractionDirtyFlag::eDOMINANCE) { Sc::ActorSim& bs0 = shapeSim0.getActor(); Sc::ActorSim& bs1 = shapeSim1.getActor(); // Static actors are in dominance group zero and must remain there const PxDominanceGroup dom0 = bs0.getActorCore().getDominanceGroup(); const PxDominanceGroup dom1 = !bs1.isStaticRigid() ? bs1.getActorCore().getDominanceGroup() : PxDominanceGroup(0); const PxDominanceGroupPair cdom = getScene().getDominanceGroupPair(dom0, dom1); mManager->setDominance0(cdom.dominance0); mManager->setDominance1(cdom.dominance1); } if (dirtyFlags & InteractionDirtyFlag::eBODY_KINEMATIC) { //Kinematic flags changed - clear flag for kinematic on the pair Sc::ActorSim& bs1 = shapeSim1.getActor(); if (bs1.isDynamicRigid()) { if (static_cast<BodySim&>(bs1).isKinematic()) mManager->getWorkUnit().flags |= PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR; else mManager->getWorkUnit().flags &= (~PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR); } } // Update skin width if(dirtyFlags & InteractionDirtyFlag::eREST_OFFSET) mManager->setRestDistance(ScGetRestOffset(shapeSim0) + ScGetRestOffset(shapeSim1)); //we may want to only write these if they have changed, the set code is a bit painful for the integration flags because of bit unpacking + packing. mManager->setCCD((getPairFlags() & PxPairFlag::eDETECT_CCD_CONTACT) != 0); if(dirtyFlags) resetManagerCachedState(); // this flushes changes through to the GPU } else if (readInteractionFlag(InteractionFlag::eIS_ACTIVE)) // only re-create the manager if the pair is active { PX_ASSERT(mManager); // if the pair is active, there has to be a manager if (dirtyFlags & InteractionDirtyFlag::eBODY_KINEMATIC) { //Kinematic->dynamic transition const IG::IslandSim& islandSim = getScene().getSimpleIslandManager()->getSpeculativeIslandSim(); // //check whether active in the speculative sim! const ActorSim& bodySim0 = getShape0().getActor(); const ActorSim& bodySim1 = getShape1().getActor(); if (!islandSim.getNode(bodySim0.getNodeIndex()).isActiveOrActivating() && (bodySim1.isStaticRigid() || !islandSim.getNode(bodySim1.getNodeIndex()).isActiveOrActivating())) { onDeactivate(); scene.notifyInteractionDeactivated(this); } else { //Else we are allowed to be active, so recreate if (mEdgeIndex != IG_INVALID_EDGE) islandManager->clearEdgeRigidCM(mEdgeIndex); destroyManager(); createManager(NULL); } } else { PX_ASSERT(activeManagerAllowed()); // A) This is a newly created pair // // B) The contact notification or processing state has changed. // All existing managers need to be deleted and recreated with the correct flag set // These flags can only be set at creation in LL //KS - added this code here because it is no longer done in destroyManager() - a side-effect of the parallelization of the interaction management code if (mEdgeIndex != IG_INVALID_EDGE) islandManager->clearEdgeRigidCM(mEdgeIndex); destroyManager(); createManager(NULL); } } } bool Sc::ShapeInteraction::onActivate(void* contactManager) { if(isReportPair()) { // for pairs that go through a second island pass, there is the possibility that they get put to sleep again after the second pass. // So we do not want to check for re-insertion into the persistent report pair list yet. processReportPairOnActivate(); } if(updateManager(contactManager)) { raiseInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } else return false; } bool Sc::ShapeInteraction::onDeactivate() { PX_ASSERT(!getShape0().getActor().isStaticRigid() || !getShape1().getActor().isStaticRigid()); const ActorSim& bodySim0 = getShape0().getActor(); const ActorSim& bodySim1 = getShape1().getActor(); PX_ASSERT( (bodySim0.isStaticRigid() && !bodySim1.isStaticRigid() && !bodySim1.isActive()) || (bodySim1.isStaticRigid() && !bodySim0.isStaticRigid() && !bodySim0.isActive()) || ((!bodySim0.isStaticRigid() && !bodySim1.isStaticRigid() && (!bodySim0.isActive() || !bodySim1.isActive()))) ); if((!bodySim0.isActive()) && (bodySim1.isStaticRigid() || !bodySim1.isActive())) { if(mReportPairIndex != INVALID_REPORT_PAIR_ID) processReportPairOnDeactivate(); PX_ASSERT((mManager->getTouchStatus() > 0) == (hasTouch() > 0)); Scene& scene = getScene(); IG::SimpleIslandManager* islandManager = scene.getSimpleIslandManager(); if(mManager) { if((!readFlag(TOUCH_KNOWN)) && mManager->touchStatusKnown() && (!mManager->getTouchStatus())) { // for pairs that are inserted asleep, we do not know the touch state. If they run through narrowphase and a touch is found, // then a managerNewTouch() call will inform this object about the found touch. However, if narrowphase detects that there // is no touch, this object will not be informed about it. The low level manager will always know though. Now, before destroying // the pair manager, we need to record "does not have touch" state if available. raiseFlag(HAS_NO_TOUCH); } destroyManager(); if(mEdgeIndex != IG_INVALID_EDGE) islandManager->clearEdgeRigidCM(mEdgeIndex); } islandManager->deactivateEdge(mEdgeIndex); // // We distinguish two scenarios here: // // A) island generation deactivates objects: // -> the deactivated body was active // -> narrowphase ran on this pair // -> the touch status is known // -> touch: the objects of the pair are in the same island // -> no touch: the objects of the pair are in different islands // // As a consequence, the edge state is not changed. The assumption is that anything that could break the touch status // from here on will have to mark the edges connected (for example if the object gets moved). // // B) user deactivates objects: // -> the touch status might not be known (for example, the pose gets integrated after the solver which might cause a change // in touch status. If the object gets put to sleep after that, we have to be conservative and mark the edge connected. // other example: an active object gets moved by the user and then deactivated). // clearInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } else { return false; } } void Sc::ShapeInteraction::createManager(void* contactManager) { //PX_PROFILE_ZONE("ShapeInteraction.createManager", 0); Sc::Scene& scene = getScene(); const PxU32 pairFlags = getPairFlags(); const int disableCCDContact = !(pairFlags & PxPairFlag::eDETECT_CCD_CONTACT); PxsContactManager* manager = scene.getLowLevelContext()->createContactManager(reinterpret_cast<PxsContactManager*>(contactManager), !disableCCDContact); PxcNpWorkUnit& mNpUnit = manager->getWorkUnit(); // Check if contact generation callback has been ordered on the pair int contactChangeable = 0; if(pairFlags & PxPairFlag::eMODIFY_CONTACTS) contactChangeable = 1; ShapeSimBase& shapeSim0 = getShape0(); ShapeSimBase& shapeSim1 = getShape1(); const PxActorType::Enum type0 = shapeSim0.getActor().getActorType(); const PxActorType::Enum type1 = shapeSim1.getActor().getActorType(); const int disableResponse = readFlag(CONTACTS_RESPONSE_DISABLED) ? 1 : 0; const int disableDiscreteContact = !(pairFlags & PxPairFlag::eDETECT_DISCRETE_CONTACT); const int reportContactInfo = readFlag(CONTACTS_COLLECT_POINTS); const int hasForceThreshold = !disableResponse && (pairFlags & CONTACT_FORCE_THRESHOLD_PAIRS); int touching; if(readFlag(TOUCH_KNOWN)) touching = readFlag(HAS_TOUCH) ? 1 : -1; else touching = 0; // Static actors are in dominance group zero and must remain there Sc::ActorSim& bs0 = shapeSim0.getActor(); Sc::ActorSim& bs1 = shapeSim1.getActor(); const PxDominanceGroup dom0 = bs0.getActorCore().getDominanceGroup(); const PxDominanceGroup dom1 = bs1.isStaticRigid() ? PxDominanceGroup(0) : bs1.getActorCore().getDominanceGroup(); const bool kinematicActor = bs1.isDynamicRigid() ? static_cast<BodySim&>(bs1).isKinematic() : false; const PxDominanceGroupPair cdom = scene.getDominanceGroupPair(dom0, dom1); /*const PxI32 hasArticulations= (type0 == PxActorType::eARTICULATION_LINK) | (type1 == PxActorType::eARTICULATION_LINK)<<1; const PxI32 hasDynamics = (type0 != PxActorType::eRIGID_STATIC) | (type1 != PxActorType::eRIGID_STATIC)<<1;*/ const PxsShapeCore* shapeCore0 = &shapeSim0.getCore().getCore(); const PxsShapeCore* shapeCore1 = &shapeSim1.getCore().getCore(); //Initialize the manager.... manager->mRigidBody0 = bs0.isDynamicRigid() ? &static_cast<BodySim&>(bs0).getLowLevelBody() : NULL; manager->mRigidBody1 = bs1.isDynamicRigid() ? &static_cast<BodySim&>(bs1).getLowLevelBody() : NULL; manager->mShapeInteraction = this; mNpUnit.shapeCore0 = shapeCore0; mNpUnit.shapeCore1 = shapeCore1; PX_ASSERT(shapeCore0->getTransform().isValid() && shapeCore1->getTransform().isValid()); mNpUnit.rigidCore0 = !bs0.isNonRigid() ? &static_cast<ShapeSim&>(shapeSim0).getPxsRigidCore() : NULL; mNpUnit.rigidCore1 = !bs1.isNonRigid() ? &static_cast<ShapeSim&>(shapeSim1).getPxsRigidCore() : NULL; mNpUnit.restDistance = ScGetRestOffset(shapeSim0) + ScGetRestOffset(shapeSim1); mNpUnit.dominance0 = cdom.dominance0; mNpUnit.dominance1 = cdom.dominance1; mNpUnit.geomType0 = PxU8(shapeCore0->mGeometry.getType()); mNpUnit.geomType1 = PxU8(shapeCore1->mGeometry.getType()); mNpUnit.mTransformCache0 = shapeSim0.getTransformCacheID(); mNpUnit.mTransformCache1 = shapeSim1.getTransformCacheID(); mNpUnit.mTorsionalPatchRadius = PxMax(shapeSim0.getTorsionalPatchRadius(),shapeSim1.getTorsionalPatchRadius()); mNpUnit.mMinTorsionalPatchRadius = PxMax(shapeSim0.getMinTorsionalPatchRadius(), shapeSim1.getMinTorsionalPatchRadius()); const PxReal slop0 = manager->mRigidBody0 ? manager->mRigidBody0->getCore().offsetSlop : 0.0f; const PxReal slop1 = manager->mRigidBody1 ? manager->mRigidBody1->getCore().offsetSlop : 0.0f; mNpUnit.mOffsetSlop = PxMax(slop0, slop1); PxU16 wuflags = 0; if(type0 == PxActorType::eARTICULATION_LINK) wuflags |= PxcNpWorkUnitFlag::eARTICULATION_BODY0; if(type1 == PxActorType::eARTICULATION_LINK) wuflags |= PxcNpWorkUnitFlag::eARTICULATION_BODY1; if(type0 == PxActorType::eRIGID_DYNAMIC) wuflags |= PxcNpWorkUnitFlag::eDYNAMIC_BODY0; if(type1 == PxActorType::eRIGID_DYNAMIC) wuflags |= PxcNpWorkUnitFlag::eDYNAMIC_BODY1; #if PX_SUPPORT_GPU_PHYSX if (type0 == PxActorType::eSOFTBODY) wuflags |= PxcNpWorkUnitFlag::eSOFT_BODY; if (type1 == PxActorType::eSOFTBODY) wuflags |= PxcNpWorkUnitFlag::eSOFT_BODY; #endif if(!disableResponse && !contactChangeable) wuflags |= PxcNpWorkUnitFlag::eOUTPUT_CONSTRAINTS; if(!disableDiscreteContact) wuflags |= PxcNpWorkUnitFlag::eDETECT_DISCRETE_CONTACT; if(kinematicActor) wuflags |= PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR; if(disableResponse) wuflags |= PxcNpWorkUnitFlag::eDISABLE_RESPONSE; if(!disableCCDContact) wuflags |= PxcNpWorkUnitFlag::eDETECT_CCD_CONTACTS; // this is just the user req: contact reports can also be generated by body thresholding if(reportContactInfo || contactChangeable) wuflags |= PxcNpWorkUnitFlag::eOUTPUT_CONTACTS; if(hasForceThreshold) wuflags |= PxcNpWorkUnitFlag::eFORCE_THRESHOLD; if(contactChangeable) wuflags |= PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT; mNpUnit.flags = wuflags; manager->mFlags = PxU32(contactChangeable ? PxsContactManager::PXS_CM_CHANGEABLE : 0) | PxU32(disableCCDContact ? 0 : PxsContactManager::PXS_CM_CCD_LINEAR); //manager->mUserData = this; mNpUnit.mNpIndex = 0xFFffFFff; mManager = manager; PxU8 statusFlags = 0; if(touching > 0) statusFlags |= PxcNpWorkUnitStatusFlag::eHAS_TOUCH; else if (touching < 0) statusFlags |= PxcNpWorkUnitStatusFlag::eHAS_NO_TOUCH; mNpUnit.statusFlags = statusFlags; //KS - do not register the CMs here if contactManager isn't null. This implies this is a newly-found pair so we'll do that addition outside in parallel if(contactManager == NULL) { scene.getSimpleIslandManager()->setEdgeRigidCM(mEdgeIndex, mManager); PxvNphaseImplementationContext* nphaseImplementationContext = scene.getLowLevelContext()->getNphaseImplementationContext(); PX_ASSERT(nphaseImplementationContext); nphaseImplementationContext->registerContactManager(mManager, this, touching, 0); } } void Sc::ShapeInteraction::onShapeChangeWhileSleeping(bool shapeOfDynamicChanged) { // if an operation that can break touch status occurs, all deactivated pairs need to set the sleep island edge // to connected to make sure that potentially joined islands get detected once parts of the island wake up. // Active interactions can be ignored because the edges of those will be marked connected on deactivation. if(!mManager) { Scene& scene = getScene(); //soft body/dynamic before static ActorSim& body0 = getShape0().getActor(); if(shapeOfDynamicChanged && !readFlag(TOUCH_KNOWN)) { // conservative approach: if a pair was added asleep, and a body/shape gets moved, we want to check next frame // whether the other body should get woken up. The motivation behind this is to get a similar behavior as in // the case where the objects fell asleep rather than have been added asleep (in that case the object will be // woken up with one frame delay). ActorSim& body1 = getShape1().getActor(); if(body1.isDynamicRigid() && !readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) // the first shape always belongs to a dynamic body, hence no need to test body0 scene.addToLostTouchList(body0, body1); // note: this will cause duplicate entries if the pair loses AABB overlap the next frame } } }
41,588
C++
35.771883
217
0.735982
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeCore.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 SC_HAIRSYSTEM_SHAPECORE_H #define SC_HAIRSYSTEM_SHAPECORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxUserAllocated.h" #include "DyHairSystemCore.h" #include "ScShapeCore.h" #include "PxShape.h" namespace physx { class PxCudaContextManager; namespace Sc { class HairSystemShapeCore : public Sc::ShapeCore { public: // PX_SERIALIZATION HairSystemShapeCore(const PxEMPTY); //~PX_SERIALIZATION HairSystemShapeCore(); ~HairSystemShapeCore(); PX_FORCE_INLINE const Dy::HairSystemCore& getLLCore() const { return mLLCore; } PX_FORCE_INLINE Dy::HairSystemCore& getLLCore() { return mLLCore; } void createBuffers(PxCudaContextManager* cudaContextManager); void releaseBuffers(); PxU64& getGpuMemStat() { return mGpuMemStat; } private: Dy::HairSystemCore mLLCore; PxU64 mGpuMemStat; PxCudaContextManager* mCudaContextManager; }; } // namespace Sc } // namespace physx #endif #endif
2,561
C
34.583333
82
0.755955
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScTriggerInteraction.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 "ScTriggerInteraction.h" #include "ScBodySim.h" #include "ScNPhaseCore.h" using namespace physx; using namespace Sc; TriggerInteraction::TriggerInteraction( ShapeSimBase& tShape, ShapeSimBase& oShape) : ElementSimInteraction(tShape, oShape, InteractionType::eTRIGGER, InteractionFlag::eRB_ELEMENT | InteractionFlag::eFILTERABLE), mLastFrameHadContacts(false) { mFlags = PROCESS_THIS_FRAME; // The PxPairFlags eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST get stored and mixed up with internal flags. Make sure any breaking change gets noticed. PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_FOUND < PxPairFlag::eNOTIFY_TOUCH_LOST); PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eNOTIFY_TOUCH_FOUND) == PxPairFlag::eNOTIFY_TOUCH_FOUND); PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eNOTIFY_TOUCH_LOST) == PxPairFlag::eNOTIFY_TOUCH_LOST); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_FOUND < 0xffff); PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_LOST < 0xffff); PX_COMPILE_TIME_ASSERT(LAST < 0xffff); { const bool active = onActivate(NULL); registerInActors(); getScene().registerInteraction(this, active); } PX_ASSERT(getTriggerShape().getFlags() & PxShapeFlag::eTRIGGER_SHAPE); mTriggerCache.state = Gu::TRIGGER_DISJOINT; } TriggerInteraction::~TriggerInteraction() { getScene().unregisterInteraction(this); unregisterFromActors(); } static bool isOneActorActive(TriggerInteraction* trigger) { const ActorSim& actorSim0 = trigger->getTriggerShape().getActor(); if(actorSim0.isActive() && actorSim0.isDynamicRigid()) { const BodySim* bodySim0 = static_cast<const BodySim*>(&actorSim0); PX_UNUSED(bodySim0); PX_ASSERT(!bodySim0->isKinematic() || bodySim0->readInternalFlag(BodySim::BF_KINEMATIC_MOVED) || bodySim0->readInternalFlag(BodySim::InternalFlags(BodySim::BF_KINEMATIC_SETTLING | BodySim::BF_KINEMATIC_SETTLING_2))); return true; } const ActorSim& actorSim1 = trigger->getOtherShape().getActor(); if(actorSim1.isActive() && actorSim1.isDynamicRigid()) { const BodySim* bodySim1 = static_cast<const BodySim*>(&actorSim1); PX_UNUSED(bodySim1); PX_ASSERT(!bodySim1->isKinematic() || bodySim1->readInternalFlag(BodySim::BF_KINEMATIC_MOVED) || bodySim1->readInternalFlag(BodySim::InternalFlags(BodySim::BF_KINEMATIC_SETTLING | BodySim::BF_KINEMATIC_SETTLING_2))); return true; } return false; } // // Some general information about triggers and sleeping // // The goal is to avoid running overlap tests if both objects are sleeping. // This is an optimization for eNOTIFY_TOUCH_LOST events since the overlap state // can not change if both objects are sleeping. eNOTIFY_TOUCH_FOUND should be sent nonetheless. // For this to work the following assumptions are made: // - On creation or if the pose of an actor is set, the pair will always be checked. // - If the scenario above does not apply, then a trigger pair can only be deactivated, if both actors are sleeping. // - If an overlapping actor is activated/deactivated, the trigger interaction gets notified // bool TriggerInteraction::onActivate(void*) { // IMPORTANT: this method can get called concurrently from multiple threads -> make sure shared resources // are protected (note: there are none at the moment but it might change) if(!(readFlag(PROCESS_THIS_FRAME))) { if(isOneActorActive(this)) { raiseInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } else return false; } else { raiseInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; // newly created trigger pairs should always test for overlap, no matter the sleep state } } bool TriggerInteraction::onDeactivate() { if(!readFlag(PROCESS_THIS_FRAME)) { if(!isOneActorActive(this)) { clearInteractionFlag(InteractionFlag::eIS_ACTIVE); return true; } else return false; } else return false; }
5,608
C++
39.352518
151
0.754458
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSimBase.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 "ScShapeSimBase.h" #include "ScSqBoundsManager.h" #include "ScTriggerInteraction.h" #include "ScSimulationController.h" #include "CmTransformUtils.h" #include "ScShapeInteraction.h" using namespace physx; using namespace Sc; // PT: keep local functions in cpp, no need to pollute the header. Don't force conversions to bool if not necessary. static PX_FORCE_INLINE PxU32 hasTriggerFlags(PxShapeFlags flags) { return PxU32(flags) & PxU32(PxShapeFlag::eTRIGGER_SHAPE); } void resetElementID(Scene& scene, ShapeSimBase& shapeSim) { PX_ASSERT(!shapeSim.isInBroadPhase()); // scene.getDirtyShapeSimMap().reset(shapeSim.getElementID()); scene.getDirtyShapeSimMap().boundedReset(shapeSim.getElementID()); if (shapeSim.getSqBoundsId() != PX_INVALID_U32) shapeSim.destroySqBounds(); } PX_INLINE Bp::FilterGroup::Enum getBPGroup(const ShapeSimBase& shapeSim) { const BodySim* bs = shapeSim.getBodySim(); const RigidSim& rbSim = shapeSim.getRbSim(); bool isKinematic = bs ? bs->isKinematic() : false; if (isKinematic && bs->hasForcedKinematicNotif()) isKinematic = false; return Bp::getFilterGroup(rbSim.getActorType() == PxActorType::eRIGID_STATIC, rbSim.getActorID(), isKinematic); } static void setElementInteractionsDirty(Sc::ElementSim& elementSim, InteractionDirtyFlag::Enum flag, PxU8 interactionFlag) { ElementSim::ElementInteractionIterator iter = elementSim.getElemInteractions(); ElementSimInteraction* interaction = iter.getNext(); while(interaction) { if(interaction->readInteractionFlag(interactionFlag)) interaction->setDirty(flag); interaction = iter.getNext(); } } void ShapeSimBase::onFilterDataChange() { setElementInteractionsDirty(*this, InteractionDirtyFlag::eFILTER_STATE, InteractionFlag::eFILTERABLE); } void ShapeSimBase::onResetFiltering() { if (isInBroadPhase()) reinsertBroadPhase(); } void ShapeSimBase::onMaterialChange() { setElementInteractionsDirty(*this, InteractionDirtyFlag::eMATERIAL, InteractionFlag::eRB_ELEMENT); } void ShapeSimBase::onRestOffsetChange() { setElementInteractionsDirty(*this, InteractionDirtyFlag::eREST_OFFSET, InteractionFlag::eRB_ELEMENT); } void ShapeSimBase::onContactOffsetChange() { if (isInBroadPhase()) getScene().getAABBManager()->setContactDistance(getElementID(), getCore().getContactOffset()); } void ShapeSimBase::removeFromBroadPhase(bool wakeOnLostTouch) { if (isInBroadPhase()) internalRemoveFromBroadPhase(wakeOnLostTouch); } void ShapeSimBase::reinsertBroadPhase() { bool wasPendingInsert = false; if (isInBroadPhase()) { wasPendingInsert = internalRemoveFromBroadPhase(); } // internalAddToBroadPhase(); Scene& scene = getScene(); // Scene::removeShape { //unregisterShapeFromNphase(shape.getCore()); // PT: "getID" is const but the addShape call used LLShape, which uses elementID, so.... scene.getSimulationController()->removeShape(getElementID()); scene.unregisterShapeFromNphase(getCore(), getElementID()); } // Call ShapeSim dtor { resetElementID(scene, *this); } // Call ElementSim dtor - only required if this shape was not pending insert (otherwise the elementID is fine to keep) if (!wasPendingInsert) { { releaseID(); } // Call ElementSim ctor { initID(); } } // Call ShapeSim ctor { initSubsystemsDependingOnElementID(); } // Scene::addShape { scene.getSimulationController()->addShape(&getLLShapeSim(), getElementID()); // PT: TODO: anything else needed here? scene.registerShapeInNphase(&getRbSim().getRigidCore(), getCore(), getElementID()); } } PX_FORCE_INLINE void ShapeSimBase::internalAddToBroadPhase() { PX_ASSERT(!isInBroadPhase()); addToAABBMgr(getCore().getContactOffset(), getBPGroup(*this), (getCore().getCore().mShapeFlags & PxShapeFlag::eTRIGGER_SHAPE) ? Bp::ElementType::eTRIGGER : Bp::ElementType::eSHAPE); } PX_FORCE_INLINE bool ShapeSimBase::internalRemoveFromBroadPhase(bool wakeOnLostTouch) { PX_ASSERT(isInBroadPhase()); bool res = removeFromAABBMgr(); Scene& scene = getScene(); PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs(); scene.getNPhaseCore()->onVolumeRemoved(this, wakeOnLostTouch ? PxU32(PairReleaseFlag::eWAKE_ON_LOST_TOUCH) : 0, outputs); return res; } void ShapeSimBase::initSubsystemsDependingOnElementID() { Scene& scScene = getScene(); Bp::BoundsArray& boundsArray = scScene.getBoundsArray(); const PxU32 index = getElementID(); PX_ALIGN(16, PxTransform absPos); getAbsPoseAligned(&absPos); PxsTransformCache& cache = scScene.getLowLevelContext()->getTransformCache(); cache.initEntry(index); cache.setTransformCache(absPos, 0, index); boundsArray.updateBounds(absPos, getCore().getGeometryUnion().getGeometry(), index); { PX_PROFILE_ZONE("API.simAddShapeToBroadPhase", scScene.getContextId()); if (isBroadPhase(getCore().getFlags())) internalAddToBroadPhase(); else scScene.getAABBManager()->reserveSpaceForBounds(index); scScene.updateContactDistance(index, getContactOffset()); } // if(scScene.getDirtyShapeSimMap().size() <= index) // scScene.getDirtyShapeSimMap().resize(PxMax(index+1, (scScene.getDirtyShapeSimMap().size()+1) * 2u)); RigidSim& owner = getRbSim(); if (owner.isDynamicRigid() && static_cast<BodySim&>(owner).isActive()) createSqBounds(); // Init LL shape { mLLShape.mElementIndex_GPU = index; mLLShape.mShapeCore = const_cast<PxsShapeCore*>(&getCore().getCore()); if (owner.getActorType() == PxActorType::eRIGID_STATIC) { mLLShape.mBodySimIndex_GPU = PxNodeIndex(PX_INVALID_NODE); } else { BodySim& bodySim = static_cast<BodySim&>(getActor()); mLLShape.mBodySimIndex_GPU = bodySim.getNodeIndex(); //mLLShape.mLocalBound = computeBounds(mCore.getGeometry(), PxTransform(PxIdentity)); } } } void ShapeSimBase::getAbsPoseAligned(PxTransform* PX_RESTRICT globalPose) const { // PT: TODO: simplify dynamic case when shape2Actor = idt const PxsShapeCore& shapeCore = getCore().getCore(); const PxTransform& shape2Actor = shapeCore.getTransform(); const PxTransform* actor2World = NULL; if (getActor().getActorType() == PxActorType::eRIGID_STATIC) { PxsRigidCore& core = static_cast<StaticSim&>(getActor()).getStaticCore().getCore(); if (shapeCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eIDT_TRANSFORM)) { PX_ASSERT(shape2Actor.p.isZero() && shape2Actor.q.isIdentity()); *globalPose = core.body2World; return; } actor2World = &core.body2World; } else { PxsBodyCore& core = static_cast<BodySim&>(getActor()).getBodyCore().getCore(); if (!core.hasIdtBody2Actor()) { Cm::getDynamicGlobalPoseAligned(core.body2World, shape2Actor, core.getBody2Actor(), *globalPose); return; } actor2World = &core.body2World; } Cm::getStaticGlobalPoseAligned(*actor2World, shape2Actor, *globalPose); } void ShapeSimBase::onFlagChange(PxShapeFlags oldFlags) { const PxShapeFlags newFlags = getCore().getFlags(); const bool oldBp = isBroadPhase(oldFlags) != 0; const bool newBp = isBroadPhase(newFlags) != 0; // Change of collision shape flags requires removal/add to broadphase if (oldBp != newBp) { if (!oldBp && newBp) { // A.B. if a trigger was removed and inserted within the same frame we need to reinsert if (hasTriggerFlags(newFlags) && getScene().getAABBManager()->isMarkedForRemove(getElementID())) reinsertBroadPhase(); else internalAddToBroadPhase(); } else internalRemoveFromBroadPhase(); } else { const bool wasTrigger = hasTriggerFlags(oldFlags) != 0; const bool isTrigger = hasTriggerFlags(newFlags) != 0; if (wasTrigger != isTrigger) reinsertBroadPhase(); // re-insertion is necessary because trigger pairs get killed } const PxShapeFlags hadSq = oldFlags & PxShapeFlag::eSCENE_QUERY_SHAPE; const PxShapeFlags hasSq = newFlags & PxShapeFlag::eSCENE_QUERY_SHAPE; if (hasSq && !hadSq) { BodySim* body = getBodySim(); if (body && body->isActive()) createSqBounds(); } else if (hadSq && !hasSq) destroySqBounds(); getScene().getSimulationController()->reinsertShape(&getLLShapeSim(), getElementID()); } BodySim* ShapeSimBase::getBodySim() const { ActorSim& a = getActor(); return a.isDynamicRigid() ? static_cast<BodySim*>(&a) : NULL; } PxsRigidCore& ShapeSimBase::getPxsRigidCore() const { ActorSim& a = getActor(); return a.isDynamicRigid() ? static_cast<BodySim&>(a).getBodyCore().getCore() : static_cast<StaticSim&>(a).getStaticCore().getCore(); } void ShapeSimBase::updateCached(PxU32 transformCacheFlags, PxBitMapPinned* shapeChangedMap) { PX_ALIGN(16, PxTransform absPose); getAbsPoseAligned(&absPose); Scene& scene = getScene(); const PxU32 index = getElementID(); scene.getLowLevelContext()->getTransformCache().setTransformCache(absPose, transformCacheFlags, index); scene.getBoundsArray().updateBounds(absPose, getCore().getGeometryUnion().getGeometry(), index); if (shapeChangedMap && isInBroadPhase()) shapeChangedMap->growAndSet(index); } void ShapeSimBase::updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray) { const PxU32 index = getElementID(); PxsCachedTransform& ct = transformCache.getTransformCache(index); PxPrefetchLine(&ct); getAbsPoseAligned(&ct.transform); ct.flags = 0; PxBounds3& b = boundsArray.begin()[index]; Gu::computeBounds(b, getCore().getGeometryUnion().getGeometry(), ct.transform, 0.0f, 1.0f); } void ShapeSimBase::updateBPGroup() { if (isInBroadPhase()) { Sc::Scene& scene = getScene(); scene.getAABBManager()->setBPGroup(getElementID(), getBPGroup(*this)); reinsertBroadPhase(); // internalRemoveFromBroadPhase(); // internalAddToBroadPhase(); } } void ShapeSimBase::markBoundsForUpdate() { Scene& scene = getScene(); if (isInBroadPhase()) scene.getDirtyShapeSimMap().growAndSet(getElementID()); } static PX_FORCE_INLINE void updateInteraction(Scene& scene, Interaction* i, const bool isDynamic, const bool isAsleep) { if (i->getType() == InteractionType::eOVERLAP) { ShapeInteraction* si = static_cast<ShapeInteraction*>(i); si->resetManagerCachedState(); if (isAsleep) si->onShapeChangeWhileSleeping(isDynamic); } else if (i->getType() == InteractionType::eTRIGGER) (static_cast<TriggerInteraction*>(i))->forceProcessingThisFrame(scene); // trigger pairs need to be checked next frame } void ShapeSimBase::onVolumeOrTransformChange() { Scene& scene = getScene(); BodySim* body = getBodySim(); const bool isDynamic = (body != NULL); const bool isAsleep = body ? !body->isActive() : true; ElementSim::ElementInteractionIterator iter = getElemInteractions(); ElementSimInteraction* i = iter.getNext(); while (i) { updateInteraction(scene, i, isDynamic, isAsleep); i = iter.getNext(); } markBoundsForUpdate(); getScene().getSimulationController()->reinsertShape(&getLLShapeSim(), getElementID()); } void notifyActorInteractionsOfTransformChange(ActorSim& actor) { bool isDynamic; bool isAsleep; if (actor.isDynamicRigid()) { isDynamic = true; isAsleep = !static_cast<BodySim&>(actor).isActive(); } else { isDynamic = false; isAsleep = true; } Scene& scene = actor.getScene(); PxU32 nbInteractions = actor.getActorInteractionCount(); Interaction** interactions = actor.getActorInteractions(); while (nbInteractions--) updateInteraction(scene, *interactions++, isDynamic, isAsleep); } void ShapeSimBase::createSqBounds() { if (mSqBoundsId != PX_INVALID_U32) return; BodySim* bodySim = getBodySim(); PX_ASSERT(bodySim); if (bodySim->usingSqKinematicTarget() || bodySim->isFrozen() || !bodySim->isActive() || bodySim->readInternalFlag(BodySim::BF_IS_COMPOUND_RIGID)) return; if (getCore().getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE) getScene().getSqBoundsManager().addSyncShape(*this); } void ShapeSimBase::destroySqBounds() { if (mSqBoundsId != PX_INVALID_U32) getScene().getSqBoundsManager().removeSyncShape(*this); }
13,518
C++
29.109131
182
0.745155
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothShapeSim.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 "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScFEMClothShapeSim.h" #include "ScNPhaseCore.h" #include "ScScene.h" #include "ScFEMClothSim.h" #include "PxsContext.h" #include "BpAABBManager.h" #include "ScSqBoundsManager.h" #include "geometry/PxTetrahedronMesh.h" #include "geometry/PxTriangleMesh.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::FEMClothShapeSim::FEMClothShapeSim(FEMClothSim& FEMCloth) : ShapeSimBase(FEMCloth, NULL), initialTransform(PxVec3(0, 0, 0)), initialScale(1.0f) { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::FEMClothShapeSim::~FEMClothShapeSim() { if (isInBroadPhase()) destroyLowLevelVolume(); PX_ASSERT(!isInBroadPhase()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::FEMClothShapeSim::attachShapeCore(const Sc::ShapeCore* shapeCore) { setCore(shapeCore); createLowLevelVolume(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::FEMClothShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const { filterAttr = 0; setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eFEMCLOTH); filterData = getBodySim().getCore().getSimulationFilterData(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::FEMClothShapeSim::updateBounds() { Scene& scene = getScene(); PxBounds3 worldBounds = getWorldBounds(); worldBounds.fattenSafe(getContactOffset()); // fatten for fast moving colliders scene.getBoundsArray().setBounds(worldBounds, getElementID()); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); } void Sc::FEMClothShapeSim::updateBoundsInAABBMgr() { Scene& scene = getScene(); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); scene.getAABBManager()->setGPUStateChanged(); } PxBounds3 Sc::FEMClothShapeSim::getBounds() const { PxBounds3 bounds = getScene().getBoundsArray().getBounds(getElementID()); return bounds; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::FEMClothShapeSim::createLowLevelVolume() { PX_ASSERT(getWorldBounds().isFinite()); const PxU32 index = getElementID(); getScene().getBoundsArray().setBounds(getWorldBounds(), index); { const PxU32 group = Bp::FilterGroup::eDYNAMICS_BASE + getActor().getActorID(); const PxU32 type = Bp::FilterType::FEMCLOTH; addToAABBMgr(getCore().getContactOffset(), Bp::FilterGroup::Enum((group << BP_FILTERING_TYPE_SHIFT_BIT) | type), Bp::ElementType::eSHAPE); } // PT: TODO: what's the difference between "getContactOffset()" and "getCore().getContactOffset()" above? getScene().updateContactDistance(index, getContactOffset()); PxsTransformCache& cache = getScene().getLowLevelContext()->getTransformCache(); cache.initEntry(index); PxTransform idt(PxIdentity); cache.setTransformCache(idt, 0, index); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::FEMClothShapeSim::destroyLowLevelVolume() { if (!isInBroadPhase()) return; Sc::Scene& scene = getScene(); PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs(); scene.getNPhaseCore()->onVolumeRemoved(this, 0, outputs); removeFromAABBMgr(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PxBounds3 Sc::FEMClothShapeSim::getWorldBounds() const { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(getCore().getGeometry()); PxTriangleMesh* triMesh = triGeom.triangleMesh; // PT: are you sure you want to go through the Px API here? PxBounds3 bounds = triMesh->getLocalBounds(); bounds.minimum *= initialScale; bounds.maximum *= initialScale; bounds = PxBounds3::transformFast(initialTransform, bounds); return bounds; } Sc::FEMClothSim& Sc::FEMClothShapeSim::getBodySim() const { return static_cast<FEMClothSim&>(getActor()); } #endif //PX_SUPPORT_GPU_PHYSX
6,702
C++
38.898809
199
0.582811
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorCore.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 "ScActorCore.h" #include "ScActorSim.h" #include "ScShapeCore.h" #include "ScShapeSim.h" #include "ScBodySim.h" using namespace physx; Sc::ActorCore::ActorCore(PxActorType::Enum actorType, PxU8 actorFlags, PxClientID owner, PxDominanceGroup dominanceGroup) : mSim (NULL), mAggregateIDOwnerClient ((PxU32(owner)<<24)|0x00ffffff), mActorFlags (actorFlags), mActorType (PxU8(actorType)), mDominanceGroup (dominanceGroup) { PX_ASSERT((actorType & 0xff) == actorType); } Sc::ActorCore::~ActorCore() { } void Sc::ActorCore::setActorFlags(PxActorFlags af) { const PxActorFlags old = mActorFlags; if(af!=old) { mActorFlags = af; if(mSim) mSim->postActorFlagChange(old, af); } } void Sc::ActorCore::setDominanceGroup(PxDominanceGroup g) { PX_ASSERT(g<128); mDominanceGroup = g; if(mSim) { //force all related interactions to refresh, so they fetch new dominance values. mSim->setActorsInteractionsDirty(InteractionDirtyFlag::eDOMINANCE, NULL, InteractionFlag::eRB_ELEMENT); } } void Sc::ActorCore::reinsertShapes() { PX_ASSERT(mSim); if(!mSim) return; PxU32 nbElems = mSim->getNbElements(); ElementSim** elems = mSim->getElements(); while (nbElems--) { ShapeSim* current = static_cast<ShapeSim*>(*elems++); current->reinsertBroadPhase(); } }
3,002
C++
33.125
123
0.746502
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationCore.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 "ScArticulationCore.h" #include "ScPhysics.h" #include "ScBodyCore.h" #include "ScBodySim.h" #include "ScArticulationSim.h" using namespace physx; Sc::ArticulationCore::ArticulationCore() : mSim(NULL) { const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); mCore.solverIterationCounts = 1<<8 | 4; mCore.sleepThreshold = 5e-5f * scale.speed * scale.speed; mCore.freezeThreshold = 5e-6f * scale.speed * scale.speed; mCore.wakeCounter = Physics::sWakeCounterOnCreation; mCore.gpuRemapIndex = 0xffffffff; mCore.maxLinearVelocity = 1e+6f; mCore.maxAngularVelocity = 1e+6f; } Sc::ArticulationCore::~ArticulationCore() { } //-------------------------------------------------------------- // // ArticulationCore interface implementation // //-------------------------------------------------------------- void Sc::ArticulationCore::setWakeCounter(const PxReal v) { mCore.wakeCounter = v; if (mSim) { mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_WAKECOUNTER); } #ifdef _DEBUG if(mSim) mSim->debugCheckWakeCounterOfLinks(v); #endif } void Sc::ArticulationCore::setMaxLinearVelocity(const PxReal v) { mCore.maxLinearVelocity = v; if (mSim) { mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITY_LIMITS); } } void Sc::ArticulationCore::setMaxAngularVelocity(const PxReal v) { mCore.maxAngularVelocity = v; if (mSim) { mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITY_LIMITS); } } bool Sc::ArticulationCore::isSleeping() const { return mSim ? mSim->isSleeping() : (mCore.wakeCounter == 0.0f); } void Sc::ArticulationCore::wakeUp(PxReal wakeCounter) { mCore.wakeCounter = wakeCounter; if (mSim) { Dy::FeatherstoneArticulation* arti = static_cast<Dy::FeatherstoneArticulation*>(mSim->getLowLevelArticulation()); arti->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_WAKECOUNTER); } #ifdef _DEBUG if(mSim) mSim->debugCheckSleepStateOfLinks(false); #endif } void Sc::ArticulationCore::putToSleep() { mCore.wakeCounter = 0.0f; if (mSim) { Dy::FeatherstoneArticulation* arti = static_cast<Dy::FeatherstoneArticulation*>(mSim->getLowLevelArticulation()); arti->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_WAKECOUNTER); } #ifdef _DEBUG if(mSim) mSim->debugCheckSleepStateOfLinks(true); #endif } void Sc::ArticulationCore::setArticulationFlags(PxArticulationFlags flags) { mCore.flags = flags; if(mSim) { mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_USER_FLAGS); const bool isFixedBaseLink = flags & PxArticulationFlag::eFIX_BASE; mSim->setFixedBaseLink(isFixedBaseLink); } } PxU32 Sc::ArticulationCore::getDofs() const { return mSim ? mSim->getDofs() : 0xFFFFFFFFu; } PxArticulationCache* Sc::ArticulationCore::createCache() const { return mSim ? mSim->createCache() : NULL; } PxU32 Sc::ArticulationCore::getCacheDataSize() const { return mSim ? mSim->getCacheDataSize() : 0xFFFFFFFFu; } void Sc::ArticulationCore::zeroCache(PxArticulationCache& cache) const { if(mSim) mSim->zeroCache(cache); } bool Sc::ArticulationCore::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag) const { if(mSim) return mSim->applyCache(cache, flag); return false; } void Sc::ArticulationCore::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const { if(mSim) mSim->copyInternalStateToCache(cache, flag, isGpuSimEnabled); } void Sc::ArticulationCore::packJointData(const PxReal* maximum, PxReal* reduced) const { if(mSim) mSim->packJointData(maximum, reduced); } void Sc::ArticulationCore::unpackJointData(const PxReal* reduced, PxReal* maximum) const { if(mSim) mSim->unpackJointData(reduced, maximum); } void Sc::ArticulationCore::commonInit() const { if(mSim) mSim->commonInit(); } void Sc::ArticulationCore::computeGeneralizedGravityForce(PxArticulationCache& cache) const { if(mSim) mSim->computeGeneralizedGravityForce(cache); } void Sc::ArticulationCore::computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const { if(mSim) mSim->computeCoriolisAndCentrifugalForce(cache); } void Sc::ArticulationCore::computeGeneralizedExternalForce(PxArticulationCache& cache) const { if(mSim) mSim->computeGeneralizedExternalForce(cache); } void Sc::ArticulationCore::computeJointAcceleration(PxArticulationCache& cache) const { if(mSim) mSim->computeJointAcceleration(cache); } void Sc::ArticulationCore::computeJointForce(PxArticulationCache& cache) const { if(mSim) mSim->computeJointForce(cache); } void Sc::ArticulationCore::computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const { if(mSim) mSim->computeDenseJacobian(cache, nRows, nCols); } void Sc::ArticulationCore::computeCoefficientMatrix(PxArticulationCache& cache) const { if(mSim) mSim->computeCoefficientMatrix(cache); } bool Sc::ArticulationCore::computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter) const { return mSim ? mSim->computeLambda(cache, initialState, jointTorque, gravity, maxIter) : false; } void Sc::ArticulationCore::computeGeneralizedMassMatrix(PxArticulationCache& cache) const { if(mSim) mSim->computeGeneralizedMassMatrix(cache); } PxU32 Sc::ArticulationCore::getCoefficientMatrixSize() const { return mSim ? mSim->getCoefficientMatrixSize() : 0xFFFFFFFFu; } PxSpatialVelocity Sc::ArticulationCore::getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const { return mSim ? mSim->getLinkAcceleration(linkId, isGpuSimEnabled) : PxSpatialVelocity(); } PxU32 Sc::ArticulationCore::getGpuArticulationIndex() const { return mSim ? mCore.gpuRemapIndex : 0xffffffff; } void Sc::ArticulationCore::updateKinematic(PxArticulationKinematicFlags flags) { PX_ASSERT(mSim); if (mSim) mSim->updateKinematic(flags); } PxNodeIndex Sc::ArticulationCore::getIslandNodeIndex() const { return mSim ? mSim->getIslandNodeIndex() : PxNodeIndex(PX_INVALID_NODE); } void Sc::ArticulationCore::setGlobalPose() { if(mSim) mSim->setGlobalPose(); }
7,894
C++
26.604895
185
0.756651
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationTendonSim.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 "ScArticulationTendonSim.h" #include "ScArticulationTendonCore.h" #include "ScArticulationAttachmentCore.h" #include "ScArticulationTendonJointCore.h" #include "ScArticulationJointCore.h" #include "ScScene.h" #include "DyArticulationTendon.h" #include "ScArticulationSim.h" using namespace physx; Sc::ArticulationSpatialTendonSim::ArticulationSpatialTendonSim(ArticulationSpatialTendonCore& tendon, Scene& scene) : mTendonCore(tendon), mScene(scene) { mTendonCore.setSim(this); mLLTendon.mStiffness = tendon.mStiffness; mLLTendon.mDamping = tendon.mDamping; mLLTendon.mOffset = tendon.mOffset; mLLTendon.mLimitStiffness = tendon.mLimitStiffness; } Sc::ArticulationSpatialTendonSim::~ArticulationSpatialTendonSim() { mTendonCore.setSim(NULL); } void Sc::ArticulationSpatialTendonSim::setStiffness(const PxReal stiffness) { mLLTendon.mStiffness = stiffness; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON); } PxReal Sc::ArticulationSpatialTendonSim::getStiffness() const { return mLLTendon.mStiffness; } void Sc::ArticulationSpatialTendonSim::setDamping(const PxReal damping) { mLLTendon.mDamping = damping; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON); } PxReal Sc::ArticulationSpatialTendonSim::getDamping() const { return mLLTendon.mDamping; } void Sc::ArticulationSpatialTendonSim::setLimitStiffness(const PxReal stiffness) { mLLTendon.mLimitStiffness = stiffness; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } PxReal Sc::ArticulationSpatialTendonSim::getLimitStiffness() const { return mLLTendon.mLimitStiffness; } void Sc::ArticulationSpatialTendonSim::setOffset(const PxReal offset) { mLLTendon.mOffset = offset; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON); } PxReal Sc::ArticulationSpatialTendonSim::getOffset() const { return mLLTendon.mOffset; } void Sc::ArticulationSpatialTendonSim::setAttachmentCoefficient(ArticulationAttachmentCore& core, const PxReal coefficient) { const PxU32 index = core.mAttachmentIndex; Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index); attachment.coefficient = coefficient; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT); } void Sc::ArticulationSpatialTendonSim::setAttachmentRelativeOffset(ArticulationAttachmentCore& core, const PxVec3& offset) { const PxU32 index = core.mAttachmentIndex; Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index); attachment.relativeOffset = offset; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT); } void Sc::ArticulationSpatialTendonSim::setAttachmentLimits(ArticulationAttachmentCore& core, const PxReal lowLimit, const PxReal highLimit) { const PxU32 index = core.mAttachmentIndex; Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index); attachment.lowLimit = lowLimit; attachment.highLimit = highLimit; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT); } void Sc::ArticulationSpatialTendonSim::setAttachmentRestLength(ArticulationAttachmentCore& core, const PxReal restLength) { const PxU32 index = core.mAttachmentIndex; Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index); attachment.restLength = restLength; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT); } void Sc::ArticulationSpatialTendonSim::addAttachment(ArticulationAttachmentCore& core) { const PxU32 index = mLLTendon.getNewID(); Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index); attachment.relativeOffset = core.mRelativeOffset; attachment.linkInd = PxU16(core.mLLLinkIndex); attachment.lowLimit = core.mLowLimit; attachment.highLimit = core.mHighLimit; attachment.coefficient = core.mCoefficient; attachment.myInd = index; attachment.children = 0; attachment.childCount = 0; attachment.restLength = core.mRestLength; core.mAttachmentIndex = index; core.mTendonSim = this; if (core.mParent) { const PxU32 parentIndex = core.mParent->mAttachmentIndex; attachment.parent = parentIndex; mLLTendon.getAttachment(parentIndex).children |= Dy::ArticulationAttachmentBitField(1) << index; mLLTendon.getAttachment(parentIndex).childCount++; } else { attachment.parent = DY_ARTICULATION_ATTACHMENT_NONE; } } void Sc::ArticulationSpatialTendonSim::removeAttachment(ArticulationAttachmentCore& core) { const PxU32 index = core.mAttachmentIndex; Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index); PX_ASSERT(attachment.childCount == 0); if (attachment.parent != DY_ARTICULATION_ATTACHMENT_NONE) { Dy::ArticulationAttachment& parent = mLLTendon.getAttachment(attachment.parent); parent.children &= ~(Dy::ArticulationAttachmentBitField(1) << index); parent.childCount--; } mLLTendon.freeID(index); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::ArticulationFixedTendonSim::ArticulationFixedTendonSim(ArticulationFixedTendonCore& tendon, Scene& scene) : mTendonCore(tendon), mScene(scene) { mTendonCore.setSim(this); mLLTendon.mStiffness = tendon.mStiffness; mLLTendon.mDamping = tendon.mDamping; mLLTendon.mOffset = tendon.mOffset; mLLTendon.mLimitStiffness = tendon.mLimitStiffness; mLLTendon.mLowLimit = tendon.mLowLimit; mLLTendon.mHighLimit = tendon.mHighLimit; mLLTendon.mRestLength = tendon.mRestLength; } Sc::ArticulationFixedTendonSim::~ArticulationFixedTendonSim() { mTendonCore.setSim(NULL); } void Sc::ArticulationFixedTendonSim::setStiffness(const PxReal stiffness) { mLLTendon.mStiffness = stiffness; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } PxReal Sc::ArticulationFixedTendonSim::getStiffness() const { return mLLTendon.mStiffness; } void Sc::ArticulationFixedTendonSim::setDamping(const PxReal damping) { mLLTendon.mDamping = damping; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } PxReal Sc::ArticulationFixedTendonSim::getDamping() const { return mLLTendon.mDamping; } void Sc::ArticulationFixedTendonSim::setLimitStiffness(const PxReal stiffness) { mLLTendon.mLimitStiffness = stiffness; Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation()); llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } PxReal Sc::ArticulationFixedTendonSim::getLimitStiffness() const { return mLLTendon.mLimitStiffness; } void Sc::ArticulationFixedTendonSim::setOffset(const PxReal offset) { mLLTendon.mOffset = offset; mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } PxReal Sc::ArticulationFixedTendonSim::getOffset() const { return mLLTendon.mOffset; } void Sc::ArticulationFixedTendonSim::setSpringRestLength(const PxReal restLength) { mLLTendon.mRestLength = restLength; mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } PxReal Sc::ArticulationFixedTendonSim::getSpringRestLength() const { return mLLTendon.mRestLength; } void Sc::ArticulationFixedTendonSim::setLimitRange(const PxReal lowLimit, const PxReal highLimit) { mLLTendon.mLowLimit = lowLimit; mLLTendon.mHighLimit = highLimit; mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON); } void Sc::ArticulationFixedTendonSim::getLimitRange(PxReal& lowLimit, PxReal& highLimit) const { lowLimit = mLLTendon.mLowLimit; highLimit = mLLTendon.mHighLimit; } void Sc::ArticulationFixedTendonSim::addTendonJoint(ArticulationTendonJointCore& tendonJointCore) { const PxU32 jointIndex = mLLTendon.getNewID(); Dy::ArticulationTendonJoint& tendonJoint = mLLTendon.getTendonJoint(jointIndex); tendonJoint.axis = PxU16(tendonJointCore.axis); tendonJoint.coefficient = tendonJointCore.coefficient; tendonJoint.recipCoefficient = tendonJointCore.recipCoefficient; tendonJoint.linkInd = PxU16(tendonJointCore.mLLLinkIndex); tendonJoint.children = 0; tendonJoint.childCount = 0; tendonJointCore.mLLTendonJointIndex = jointIndex; //tendonJointCore.mLLTendonJoint = &tendonJoint; tendonJointCore.mTendonSim = this; if (tendonJointCore.mParent) { const PxU32 parentIndex = tendonJointCore.mParent->mLLTendonJointIndex; tendonJoint.parent = parentIndex; mLLTendon.getTendonJoint(parentIndex).children |= Dy::ArticulationAttachmentBitField(1) << jointIndex; mLLTendon.getTendonJoint(parentIndex).childCount++; } else { tendonJoint.parent = DY_ARTICULATION_ATTACHMENT_NONE; } } void Sc::ArticulationFixedTendonSim::removeTendonJoint(ArticulationTendonJointCore& core) { const PxU32 index = core.mLLTendonJointIndex; Dy::ArticulationTendonJoint& tendonJoint = mLLTendon.getTendonJoint(index); PX_ASSERT(tendonJoint.childCount == 0); if (tendonJoint.parent != DY_ARTICULATION_ATTACHMENT_NONE) { Dy::ArticulationTendonJoint& parent = mLLTendon.getTendonJoint(tendonJoint.parent); parent.children &= ~(Dy::ArticulationAttachmentBitField(1) << index); parent.childCount--; } mLLTendon.freeID(index); } void Sc::ArticulationFixedTendonSim::setTendonJointCoefficient(ArticulationTendonJointCore& core, const PxArticulationAxis::Enum axis, const float coefficient, const float recipCoefficient) { const PxU32 index = core.mLLTendonJointIndex; Dy::ArticulationTendonJoint& tendonJoint = mLLTendon.getTendonJoint(index); tendonJoint.axis = PxU16(axis); tendonJoint.coefficient = coefficient; tendonJoint.recipCoefficient = recipCoefficient; mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON_JOINT); }
12,802
C++
33.23262
189
0.79761
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeSim.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 "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScHairSystemShapeSim.h" #include "ScNPhaseCore.h" #include "ScHairSystemSim.h" #include "PxsContext.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::HairSystemShapeSim::HairSystemShapeSim(HairSystemSim& hairSystemSim, const HairSystemShapeCore* core) : ShapeSimBase(hairSystemSim, core) { createLowLevelVolume(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::HairSystemShapeSim::~HairSystemShapeSim() { if (isInBroadPhase()) destroyLowLevelVolume(); PX_ASSERT(!isInBroadPhase()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::HairSystemShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const { filterAttr = 0; setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eHAIRSYSTEM); filterData = getBodySim().getCore().getShapeCore().getSimulationFilterData(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::HairSystemShapeSim::updateBounds() { Scene& scene = getScene(); PxBounds3 worldBounds = PxBounds3(PxVec3(0.f), PxVec3(0.f)); const PxReal contactOffset = getBodySim().getCore().getContactOffset(); worldBounds.fattenSafe(contactOffset); // fatten for fast moving colliders scene.getBoundsArray().setBounds(worldBounds, getElementID()); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::HairSystemShapeSim::updateBoundsInAABBMgr() { //we are updating the bound in GPU so we just need to set the actor handle in CPU to make sure //the GPU BP will process the vertices Scene& scene = getScene(); scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID()); scene.getAABBManager()->setGPUStateChanged(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PxBounds3 Sc::HairSystemShapeSim::getBounds() const { PxBounds3 bounds = getScene().getBoundsArray().getBounds(getElementID()); return bounds; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::HairSystemShapeSim::createLowLevelVolume() { // PX_ASSERT(getWorldBounds().isFinite()); const PxU32 index = getElementID(); getScene().getBoundsArray().setBounds(PxBounds3(PxVec3(0.f), PxVec3(0.f)), index); { const PxU32 group = Bp::FilterGroup::eDYNAMICS_BASE + getActor().getActorID(); const PxU32 type = Bp::FilterType::HAIRSYSTEM; addToAABBMgr(getCore().getContactOffset(), Bp::FilterGroup::Enum((group << BP_FILTERING_TYPE_SHIFT_BIT) | type), Bp::ElementType::eSHAPE); } // PT: TODO: what's the difference between "getContactOffset()" and "getCore().getContactOffset()" above? getScene().updateContactDistance(index, getContactOffset()); PxsTransformCache& cache = getScene().getLowLevelContext()->getTransformCache(); cache.initEntry(index); PxTransform idt(PxIdentity); cache.setTransformCache(idt, 0, index); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Sc::HairSystemShapeSim::destroyLowLevelVolume() { if (!isInBroadPhase()) return; Sc::Scene& scene = getScene(); PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs(); scene.getNPhaseCore()->onVolumeRemoved(this, 0, outputs); removeFromAABBMgr(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Sc::HairSystemSim& Sc::HairSystemShapeSim::getBodySim() const { return static_cast<HairSystemSim&>(getActor()); } #endif // PX_SUPPORT_GPU_PHYSX
6,453
C++
43.510345
199
0.552146
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScTriggerPairs.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 SC_TRIGGER_PAIRS_H #define SC_TRIGGER_PAIRS_H #include "foundation/PxArray.h" #include "PxFiltering.h" #include "PxClient.h" #include "PxSimulationEventCallback.h" namespace physx { class PxShape; namespace Sc { struct TriggerPairFlag { enum Enum { eTEST_FOR_REMOVED_SHAPES = PxTriggerPairFlag::eNEXT_FREE // for cases where the pair got deleted because one of the shape volumes got removed from broadphase. // This covers scenarios like volume re-insertion into broadphase as well since the shape might get removed // after such an operation. The scenarios to consider are: // // - shape gets removed (this includes raising PxActorFlag::eDISABLE_SIMULATION) // - shape switches to eSCENE_QUERY_SHAPE only // - shape switches to eSIMULATION_SHAPE // - resetFiltering() // - actor gets removed from an aggregate }; }; PX_COMPILE_TIME_ASSERT((1 << (8*sizeof(PxTriggerPairFlags::InternalType))) > TriggerPairFlag::eTEST_FOR_REMOVED_SHAPES); struct TriggerPairExtraData { PX_INLINE TriggerPairExtraData() : shape0ID(0xffffffff), shape1ID(0xffffffff), client0ID(0xff), client1ID(0xff) { } PX_INLINE TriggerPairExtraData(PxU32 s0ID, PxU32 s1ID, PxClientID cl0ID, PxClientID cl1ID) : shape0ID(s0ID), shape1ID(s1ID), client0ID(cl0ID), client1ID(cl1ID) { } PxU32 shape0ID; PxU32 shape1ID; PxClientID client0ID; PxClientID client1ID; }; typedef PxArray<TriggerPairExtraData> TriggerBufferExtraData; typedef PxArray<PxTriggerPair> TriggerBufferAPI; } // namespace Sc } #endif
3,419
C
35.382978
161
0.717754
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFiltering.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 "ScFiltering.h" #include "ScShapeInteraction.h" #include "ScTriggerInteraction.h" #include "ScConstraintCore.h" #include "ScArticulationSim.h" using namespace physx; using namespace Sc; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE PxU64 getPairID(const ShapeSimBase& s0, const ShapeSimBase& s1) { PxU64 id0 = PxU64(s0.getElementID()); PxU64 id1 = PxU64(s1.getElementID()); if(id1<id0) PxSwap(id0, id1); const PxU64 pairID = (id0<<32)|id1; return pairID; } /////////////////////////////////////////////////////////////////////////////// template<const bool supportTriggers> static PxFilterObjectAttributes getFilterObjectAttributes(const ShapeSimBase& shape) { const ActorSim& actorSim = shape.getActor(); PxFilterObjectAttributes filterAttr = actorSim.getFilterAttributes(); if(supportTriggers && (shape.getCore().getFlags() & PxShapeFlag::eTRIGGER_SHAPE)) filterAttr |= PxFilterObjectFlag::eTRIGGER; #if PX_DEBUG BodySim* b = shape.getBodySim(); if(b) { if(!b->isArticulationLink()) { if(b->isKinematic()) PX_ASSERT(filterAttr & PxFilterObjectFlag::eKINEMATIC); PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eRIGID_DYNAMIC); } else { PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eARTICULATION); } } else { #if PX_SUPPORT_GPU_PHYSX // For softbody and particle system, the bodySim is set to null if(actorSim.isSoftBody()) { PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eSOFTBODY); } else if(actorSim.isParticleSystem()) { PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::ePARTICLESYSTEM); } else if(actorSim.isFEMCloth()) { PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eFEMCLOTH); } else if(actorSim.isHairSystem()) { PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eHAIRSYSTEM); } else #endif { PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eRIGID_STATIC); } } #endif return filterAttr; } /////////////////////////////////////////////////////////////////////////////// // PT: checks that the kill & suppress flags are not both set, disable kill flag if they are. static PX_INLINE void checkFilterFlags(PxFilterFlags& filterFlags) { if((filterFlags & (PxFilterFlag::eKILL | PxFilterFlag::eSUPPRESS)) == (PxFilterFlag::eKILL | PxFilterFlag::eSUPPRESS)) { #if PX_CHECKED outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: eKILL and eSUPPRESS must not be set simultaneously. eSUPPRESS will be used."); #endif filterFlags.clear(PxFilterFlag::eKILL); } } /////////////////////////////////////////////////////////////////////////////// static PX_INLINE PxPairFlags checkRbPairFlags( const ShapeSimBase& s0, const ShapeSimBase& s1, bool isKinePair, PxPairFlags pairFlags, PxFilterFlags filterFlags, bool isNonRigid) { if(filterFlags & (PxFilterFlag::eSUPPRESS | PxFilterFlag::eKILL)) return pairFlags; if(isKinePair && (pairFlags & PxPairFlag::eSOLVE_CONTACT)) { #if PX_CHECKED outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: Resolving contacts between two kinematic objects is invalid. Contacts will not get resolved."); #endif pairFlags.clear(PxPairFlag::eSOLVE_CONTACT); } if(isNonRigid && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT)) pairFlags.clear(PxPairFlag::eDETECT_CCD_CONTACT); #if PX_CHECKED // we want to avoid to run contact generation for pairs that should not get resolved or have no contact/trigger reports if (!(PxU32(pairFlags) & (PxPairFlag::eSOLVE_CONTACT | ShapeInteraction::CONTACT_REPORT_EVENTS))) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: Pair with no contact/trigger reports detected, nor is PxPairFlag::eSOLVE_CONTACT set. It is recommended to suppress/kill such pairs for performance reasons."); else if(!(pairFlags & (PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eDETECT_CCD_CONTACT))) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: Pair did not request either eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT. It is recommended to suppress/kill such pairs for performance reasons."); if(((s0.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)!=0 || (s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)!=0) && (pairFlags & PxPairFlag::eTRIGGER_DEFAULT) && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT)) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: CCD isn't supported on Triggers yet"); #else PX_UNUSED(s0); PX_UNUSED(s1); #endif return pairFlags; } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE bool createFilterInfo(FilterInfo& filterInfo, const PxFilterFlags filterFlags) { filterInfo = FilterInfo(filterFlags); return true; } static void filterRbCollisionPairSecondStage(FilterInfo& filterInfo, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1, bool isKinePair, const PxFilterObjectAttributes fa0, const PxFilterObjectAttributes fa1, bool runCallbacks, bool isNonRigid) { // Run filter shader const PxFilterData& fd0 = s0.getCore().getSimulationFilterData(); const PxFilterData& fd1 = s1.getCore().getSimulationFilterData(); filterInfo.filterFlags = context.mFilterShader(fa0, fd0, fa1, fd1, filterInfo.pairFlags, context.mFilterShaderData, context.mFilterShaderDataSize); if(filterInfo.filterFlags & PxFilterFlag::eCALLBACK) { if(context.mFilterCallback) { if(!runCallbacks) { return; } else { // If a FilterPair is provided, then we use it, else we create a new one // (A FilterPair is provided in the case for a pairLost()-pairFound() sequence after refiltering) struct Local { static PX_FORCE_INLINE PxShape* fetchActorAndShape(const ShapeSimBase& sim, const PxFilterObjectAttributes fa, PxActor*& a) { a = sim.getActor().getPxActor(); #if PX_SUPPORT_GPU_PHYSX if(PxGetFilterObjectType(fa)==PxFilterObjectType::ePARTICLESYSTEM) return NULL; // Particle system does not have a valid shape so set it to null #endif PX_UNUSED(fa); return sim.getPxShape(); } }; PxActor* a0, *a1; PxShape* shape0 = Local::fetchActorAndShape(s0, fa0, a0); PxShape* shape1 = Local::fetchActorAndShape(s1, fa1, a1); filterInfo.filterFlags = context.mFilterCallback->pairFound(getPairID(s0, s1), fa0, fd0, a0, shape0, fa1, fd1, a1, shape1, filterInfo.pairFlags); filterInfo.hasPairID = true; } } else { filterInfo.filterFlags.clear(PxFilterFlag::eNOTIFY); outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: eCALLBACK set but no filter callback defined."); } } checkFilterFlags(filterInfo.filterFlags); const bool hasNotify = (filterInfo.filterFlags & PxFilterFlag::eNOTIFY) == PxFilterFlag::eNOTIFY; const bool hasKill = filterInfo.filterFlags & PxFilterFlag::eKILL; { if(filterInfo.hasPairID && (hasKill || !hasNotify)) { if(hasKill && hasNotify) context.mFilterCallback->pairLost(getPairID(s0, s1), fa0, fd0, fa1, fd1, false); if(!hasNotify) { // No notification, hence we don't need to treat it as a filter callback pair anymore. // Make sure that eCALLBACK gets removed as well filterInfo.filterFlags.clear(PxFilterFlag::eNOTIFY); } filterInfo.hasPairID = false; } } // Sanity checks PX_ASSERT((!hasKill) || (hasKill && (!filterInfo.hasPairID))); PX_ASSERT((!hasNotify) || (hasNotify && filterInfo.hasPairID)); if(runCallbacks || (!(filterInfo.filterFlags & PxFilterFlag::eCALLBACK))) filterInfo.pairFlags = checkRbPairFlags(s0, s1, isKinePair, filterInfo.pairFlags, filterInfo.filterFlags, isNonRigid); } static bool filterArticulationLinks(const BodySim* bs0, const BodySim* bs1) { //It's the same articulation, so we can filter based on flags... const ArticulationSim* articulationSim0 = bs0->getArticulation(); const ArticulationSim* articulationSim1 = bs1->getArticulation(); if(articulationSim0 == articulationSim1) { if(articulationSim0->getCore().getArticulationFlags() & PxArticulationFlag::eDISABLE_SELF_COLLISION) return true; //check to see if one link is the parent of the other link, if so disable collision const PxU32 linkId0 = bs0->getNodeIndex().articulationLinkId(); const PxU32 linkId1 = bs1->getNodeIndex().articulationLinkId(); if(linkId1 < linkId0) return articulationSim0->getLink(linkId0).parent == linkId1; else return articulationSim1->getLink(linkId1).parent == linkId0; } return false; } static PX_FORCE_INLINE bool filterJointedBodies(const ActorSim& rbActor0, const ActorSim& rbActor1) { // If the bodies of the shape pair are connected by a joint, we need to check whether this connection disables the collision. // Note: As an optimization, the dynamic bodies have a flag which specifies whether they have any constraints at all. That works // because a constraint has at least one dynamic body and an interaction is tracked by both objects. // PT: the BF_HAS_CONSTRAINTS flag is only raised on dynamic actors in the BodySim class, but it's not raised on static actors. // Thus the only reliable way to use the flag (without casting to BodySim etc) is when both actors don't have the flag set, in // which case we're sure we're not dealing with a jointed pair. if(!rbActor0.readInternalFlag(ActorSim::BF_HAS_CONSTRAINTS) && !rbActor1.readInternalFlag(ActorSim::BF_HAS_CONSTRAINTS)) return false; ConstraintCore* core = rbActor0.getScene().findConstraintCore(&rbActor0, &rbActor1); return core ? !(core->getFlags() & PxConstraintFlag::eCOLLISION_ENABLED) : false; } static PX_FORCE_INLINE bool hasForceNotifEnabled(const BodySim* bs, PxRigidBodyFlag::Enum flag) { if(!bs) return false; const PxsRigidCore& core = bs->getBodyCore().getCore(); return core.mFlags.isSet(flag); } static PX_FORCE_INLINE bool validateSuppress(const BodySim* b0, const BodySim* b1, PxRigidBodyFlag::Enum flag) { if(hasForceNotifEnabled(b0, flag)) return false; if(hasForceNotifEnabled(b1, flag)) return false; return true; } static PX_FORCE_INLINE bool filterKinematics(const BodySim* b0, const BodySim* b1, bool kine0, bool kine1, PxPairFilteringMode::Enum kineKineFilteringMode, PxPairFilteringMode::Enum staticKineFilteringMode) { const bool kinematicPair = kine0 | kine1; if(kinematicPair) { if(staticKineFilteringMode != PxPairFilteringMode::eKEEP) { if(!b0 || !b1) return validateSuppress(b0, b1, PxRigidBodyFlag::eFORCE_STATIC_KINE_NOTIFICATIONS); } if(kineKineFilteringMode != PxPairFilteringMode::eKEEP) { if(kine0 && kine1) return validateSuppress(b0, b1, PxRigidBodyFlag::eFORCE_KINE_KINE_NOTIFICATIONS); } } return false; } template<const bool runAllTests> static bool filterRbCollisionPairShared( FilterInfo& filterInfo, bool& isNonRigid, bool& isKinePair, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1, const PxFilterObjectAttributes filterAttr0, const PxFilterObjectAttributes filterAttr1) { const bool kine0 = PxFilterObjectIsKinematic(filterAttr0); const bool kine1 = PxFilterObjectIsKinematic(filterAttr1); const ActorSim& rbActor0 = s0.getActor(); const BodySim* bs0 = NULL; if(filterAttr0 & PxFilterObjectFlagEx::eRIGID_DYNAMIC) bs0 = static_cast<const BodySim*>(&rbActor0); else if(filterAttr0 & PxFilterObjectFlagEx::eNON_RIGID) isNonRigid = true; const ActorSim& rbActor1 = s1.getActor(); const BodySim* bs1 = NULL; if(filterAttr1 & PxFilterObjectFlagEx::eRIGID_DYNAMIC) bs1 = static_cast<const BodySim*>(&rbActor1); else if(filterAttr1 & PxFilterObjectFlagEx::eNON_RIGID) isNonRigid = true; if(!isNonRigid && filterKinematics(bs0, bs1, kine0, kine1, context.mKineKineFilteringMode, context.mStaticKineFilteringMode)) return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS); if(filterJointedBodies(rbActor0, rbActor1)) return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS); const PxFilterObjectType::Enum filterType0 = PxGetFilterObjectType(filterAttr0); const PxFilterObjectType::Enum filterType1 = PxGetFilterObjectType(filterAttr1); // PT: For unknown reasons the filtering code was not the same for triggers/refiltered pairs and for regular "shape sim" pairs // out of the BP. The tests on "runAllTests" below capture that. I did not change what the code // was doing, although it might very well be wrong - we might want to run all these tests in both codepaths. if(runAllTests) { #if PX_SUPPORT_GPU_PHYSX if(filterType0==PxFilterObjectType::ePARTICLESYSTEM && filterType1==PxFilterObjectType::ePARTICLESYSTEM) return createFilterInfo(filterInfo, PxFilterFlag::eKILL); if(filterType0==PxFilterObjectType::eHAIRSYSTEM && filterType1==PxFilterObjectType::eHAIRSYSTEM ) return createFilterInfo(filterInfo, PxFilterFlag::eKILL); #endif } const bool link0 = filterType0==PxFilterObjectType::eARTICULATION; const bool link1 = filterType1==PxFilterObjectType::eARTICULATION; if(runAllTests) { if(link0 ^ link1) { if(link0) { const PxU8 fixedBaseLink = bs0->getLowLevelBody().mCore->fixedBaseLink; const bool isStaticOrKinematic = (filterType1 == PxFilterObjectType::eRIGID_STATIC) || kine1; if(fixedBaseLink && isStaticOrKinematic) return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS); } if(link1) { const PxU8 fixedBaseLink = bs1->getLowLevelBody().mCore->fixedBaseLink; const bool isStaticOrKinematic = (filterType0 == PxFilterObjectType::eRIGID_STATIC) || kine0; if(fixedBaseLink && isStaticOrKinematic) return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS); } } } if(link0 && link1) { if(runAllTests) { const PxU8 fixedBaseLink0 = bs0->getLowLevelBody().mCore->fixedBaseLink; const PxU8 fixedBaseLink1 = bs1->getLowLevelBody().mCore->fixedBaseLink; if(fixedBaseLink0 && fixedBaseLink1) return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS); } if(filterArticulationLinks(bs0, bs1)) return createFilterInfo(filterInfo, PxFilterFlag::eKILL); } isKinePair = kine0 && kine1; return false; } static void filterRbCollisionPair(FilterInfo& filterInfo, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1, bool& isTriggerPair, bool runCallbacks) { const PxFilterObjectAttributes filterAttr0 = getFilterObjectAttributes<true>(s0); const PxFilterObjectAttributes filterAttr1 = getFilterObjectAttributes<true>(s1); const bool trigger0 = PxFilterObjectIsTrigger(filterAttr0); const bool trigger1 = PxFilterObjectIsTrigger(filterAttr1); isTriggerPair = trigger0 || trigger1; bool isNonRigid = false; bool isKinePair = false; if(isTriggerPair) { if(trigger0 && trigger1) // trigger-trigger pairs are not supported { createFilterInfo(filterInfo, PxFilterFlag::eKILL); return; } // PT: I think we need to do this here to properly handle kinematic triggers. const bool kine0 = PxFilterObjectIsKinematic(filterAttr0); const bool kine1 = PxFilterObjectIsKinematic(filterAttr1); isKinePair = kine0 && kine1; } else { if(filterRbCollisionPairShared<false>(filterInfo, isNonRigid, isKinePair, context, s0, s1, filterAttr0, filterAttr1)) return; } filterRbCollisionPairSecondStage(filterInfo, context, s0, s1, isKinePair, filterAttr0, filterAttr1, runCallbacks, isNonRigid); } static PX_FORCE_INLINE void filterRbCollisionPairAllTests(FilterInfo& filterInfo, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1) { PX_ASSERT(!(s0.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)); PX_ASSERT(!(s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)); const PxFilterObjectAttributes filterAttr0 = getFilterObjectAttributes<false>(s0); const PxFilterObjectAttributes filterAttr1 = getFilterObjectAttributes<false>(s1); bool isNonRigid = false; bool isKinePair = false; if(filterRbCollisionPairShared<true>(filterInfo, isNonRigid, isKinePair, context, s0, s1, filterAttr0, filterAttr1)) return; filterRbCollisionPairSecondStage(filterInfo, context, s0, s1, isKinePair, filterAttr0, filterAttr1, true, isNonRigid); } static PX_FORCE_INLINE bool testElementSimPointers(const ElementSim* e0, const ElementSim* e1) { PX_ASSERT(e0); PX_ASSERT(e1); // PT: a bit of defensive coding added for OM-74224. In theory this should not be needed, as the broadphase is not // supposed to return null pointers here. But there seems to be an issue somewhere, most probably in the GPU BP kernels, // and this is an attempt at preventing a crash. We could/should remove this eventually. if(!e0 || !e1) return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "NPhaseCore::runOverlapFilters: found null elements!"); return true; } static PX_FORCE_INLINE bool testShapeSimCorePointers(const ShapeSimBase* s0, const ShapeSimBase* s1) { bool isValid0 = s0->isPxsCoreValid(); bool isValid1 = s1->isPxsCoreValid(); PX_ASSERT(isValid0); PX_ASSERT(isValid1); // GW: further defensive coding added for OM-111249 // This is only a temporary / immediate solution to mitigate crashes // Still need to root-cause what is causing null pointers here if(!isValid0 || !isValid1) return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "NPhaseCore::runOverlapFilters: found null PxsShapeCore pointers!"); return true; } // PT: called from OverlapFilterTask void NPhaseCore::runOverlapFilters( PxU32 nbToProcess, const Bp::AABBOverlap* PX_RESTRICT pairs, FilterInfo* PX_RESTRICT filterInfo, PxU32& nbToKeep_, PxU32& nbToSuppress_, PxU32* PX_RESTRICT keepMap ) { PxU32 nbToKeep = 0; PxU32 nbToSuppress = 0; const FilteringContext context(mOwnerScene); for(PxU32 i=0; i<nbToProcess; i++) { const Bp::AABBOverlap& pair = pairs[i]; const ElementSim* e0 = reinterpret_cast<const ElementSim*>(pair.mUserData0); const ElementSim* e1 = reinterpret_cast<const ElementSim*>(pair.mUserData1); if(!testElementSimPointers(e0, e1)) continue; PX_ASSERT(!findInteraction(e0, e1)); const ShapeSimBase* s0 = static_cast<const ShapeSimBase*>(e0); const ShapeSimBase* s1 = static_cast<const ShapeSimBase*>(e1); if(!testShapeSimCorePointers(s0, s1)) continue; PX_ASSERT(&s0->getActor() != &s1->getActor()); // No actor internal interactions filterInfo[i].filterFlags = PxFilterFlags(0); filterInfo[i].pairFlags = PxPairFlags(0); filterInfo[i].hasPairID = false; filterRbCollisionPairAllTests(filterInfo[i], context, *s0, *s1); const PxFilterFlags filterFlags = filterInfo[i].filterFlags; if(!(filterFlags & PxFilterFlag::eKILL)) { if(!(filterFlags & PxFilterFlag::eSUPPRESS)) nbToKeep++; else nbToSuppress++; keepMap[i / 32] |= (1 << (i & 31)); } } nbToKeep_ = nbToKeep; nbToSuppress_ = nbToSuppress; } ElementSimInteraction* NPhaseCore::createTriggerElementInteraction(ShapeSimBase& s0, ShapeSimBase& s1) { PX_ASSERT((s0.getFlags() & PxShapeFlag::eTRIGGER_SHAPE) || (s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)); const FilteringContext context(mOwnerScene); bool isTriggerPair; FilterInfo filterInfo; filterRbCollisionPair(filterInfo, context, s0, s1, isTriggerPair, false); PX_ASSERT(isTriggerPair); if(filterInfo.filterFlags & PxFilterFlag::eKILL) { PX_ASSERT(!filterInfo.hasPairID); // No filter callback pair info for killed pairs return NULL; } return createRbElementInteraction(filterInfo, s0, s1, NULL, NULL, NULL, isTriggerPair); } void NPhaseCore::onTriggerOverlapCreated(const Bp::AABBOverlap* PX_RESTRICT pairs, PxU32 pairCount) { for(PxU32 i=0; i<pairCount; i++) { ElementSim* volume0 = reinterpret_cast<ElementSim*>(pairs[i].mUserData0); ElementSim* volume1 = reinterpret_cast<ElementSim*>(pairs[i].mUserData1); if(!testElementSimPointers(volume0, volume1)) continue; PX_ASSERT(!findInteraction(volume0, volume1)); ShapeSimBase* shapeHi = static_cast<ShapeSimBase*>(volume1); ShapeSimBase* shapeLo = static_cast<ShapeSimBase*>(volume0); // No actor internal interactions PX_ASSERT(&shapeHi->getActor() != &shapeLo->getActor()); // PT: this case is only for triggers these days PX_ASSERT((shapeLo->getFlags() & PxShapeFlag::eTRIGGER_SHAPE) || (shapeHi->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)); createTriggerElementInteraction(*shapeHi, *shapeLo); } } void NPhaseCore::callPairLost(const ShapeSimBase& s0, const ShapeSimBase& s1, bool objVolumeRemoved) { const PxFilterObjectAttributes fa0 = getFilterObjectAttributes<true>(s0); const PxFilterObjectAttributes fa1 = getFilterObjectAttributes<true>(s1); const PxFilterData& fd0 = s0.getCore().getSimulationFilterData(); const PxFilterData& fd1 = s1.getCore().getSimulationFilterData(); mOwnerScene.getFilterCallbackFast()->pairLost(getPairID(s0, s1), fa0, fd0, fa1, fd1, objVolumeRemoved); } ElementSimInteraction* NPhaseCore::refilterInteraction(ElementSimInteraction* pair, const FilterInfo* filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs) { const InteractionType::Enum oldType = pair->getType(); switch (oldType) { case InteractionType::eTRIGGER: case InteractionType::eMARKER: case InteractionType::eOVERLAP: { ShapeSimBase& s0 = static_cast<ShapeSimBase&>(pair->getElement0()); ShapeSimBase& s1 = static_cast<ShapeSimBase&>(pair->getElement1()); FilterInfo finfo; if(filterInfo) { // The filter changes are provided by an outside source (the user filter callback) finfo = *filterInfo; PX_ASSERT(finfo.hasPairID); if((finfo.filterFlags & PxFilterFlag::eKILL) && ((finfo.filterFlags & PxFilterFlag::eNOTIFY) == PxFilterFlag::eNOTIFY) ) { callPairLost(s0, s1, false); finfo.hasPairID = false; } ActorSim& bs0 = s0.getActor(); ActorSim& bs1 = s1.getActor(); const bool isKinePair = PxFilterObjectIsKinematic(bs0.getFilterAttributes()) && PxFilterObjectIsKinematic(bs1.getFilterAttributes()); finfo.pairFlags = checkRbPairFlags(s0, s1, isKinePair, finfo.pairFlags, finfo.filterFlags, s0.getActor().isNonRigid() || s1.getActor().isNonRigid()); } else { if(pair->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR)) callPairLost(s0, s1, false); const FilteringContext context(mOwnerScene); bool isTriggerPair; filterRbCollisionPair(finfo, context, s0, s1, isTriggerPair, true); PX_UNUSED(isTriggerPair); } if(pair->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR) && ((finfo.filterFlags & PxFilterFlag::eNOTIFY) != PxFilterFlag::eNOTIFY) ) { // The pair was a filter callback pair but not any longer pair->clearInteractionFlag(InteractionFlag::eIS_FILTER_PAIR); finfo.hasPairID = false; } struct Local { static InteractionType::Enum getRbElementInteractionType(const ShapeSimBase* primitive0, const ShapeSimBase* primitive1, PxFilterFlags filterFlag) { if(filterFlag & PxFilterFlag::eKILL) return InteractionType::eINVALID; if(filterFlag & PxFilterFlag::eSUPPRESS) return InteractionType::eMARKER; if(primitive0->getFlags() & PxShapeFlag::eTRIGGER_SHAPE || primitive1->getFlags() & PxShapeFlag::eTRIGGER_SHAPE) return InteractionType::eTRIGGER; PX_ASSERT( (primitive0->getGeometryType() != PxGeometryType::eTRIANGLEMESH) || (primitive1->getGeometryType() != PxGeometryType::eTRIANGLEMESH)); return InteractionType::eOVERLAP; } }; const InteractionType::Enum newType = Local::getRbElementInteractionType(&s0, &s1, finfo.filterFlags); if(pair->getType() != newType) //Only convert interaction type if the type has changed { return convert(pair, newType, finfo, removeFromDirtyList, outputs); } else { //The pair flags might have changed, we need to forward the new ones if(oldType == InteractionType::eOVERLAP) { ShapeInteraction* si = static_cast<ShapeInteraction*>(pair); const PxU32 newPairFlags = finfo.pairFlags; const PxU32 oldPairFlags = si->getPairFlags(); PX_ASSERT((newPairFlags & ShapeInteraction::PAIR_FLAGS_MASK) == newPairFlags); PX_ASSERT((oldPairFlags & ShapeInteraction::PAIR_FLAGS_MASK) == oldPairFlags); if(newPairFlags != oldPairFlags) { if(!(oldPairFlags & ShapeInteraction::CONTACT_REPORT_EVENTS) && (newPairFlags & ShapeInteraction::CONTACT_REPORT_EVENTS) && (si->getActorPair() == NULL || !si->getActorPair()->isReportPair())) { // for this actor pair there was no shape pair that requested contact reports but now there is one // -> all the existing shape pairs need to get re-adjusted to point to an ActorPairReport instance instead. ActorPair* actorPair = findActorPair(&s0, &s1, PxIntTrue); if (si->getActorPair() == NULL) { actorPair->incRefCount(); si->setActorPair(*actorPair); } } if(si->readFlag(ShapeInteraction::IN_PERSISTENT_EVENT_LIST) && (!(newPairFlags & PxPairFlag::eNOTIFY_TOUCH_PERSISTS))) { // the new report pair flags don't require persistent checks anymore -> remove from persistent list // Note: The pair might get added to the force threshold list later if(si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST)) removeFromPersistentContactEventPairs(si); else si->clearFlag(ShapeInteraction::WAS_IN_PERSISTENT_EVENT_LIST); } if(newPairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS) { PX_ASSERT((si->mReportPairIndex == INVALID_REPORT_PAIR_ID) || (!si->readFlag(ShapeInteraction::WAS_IN_PERSISTENT_EVENT_LIST))); if(si->mReportPairIndex == INVALID_REPORT_PAIR_ID && si->readInteractionFlag(InteractionFlag::eIS_ACTIVE)) { PX_ASSERT(!si->readFlag(ShapeInteraction::WAS_IN_PERSISTENT_EVENT_LIST)); // sanity check: an active pair should never have this flag set if(si->hasTouch()) addToForceThresholdContactEventPairs(si); } } else if((oldPairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS)) { // no force threshold events needed any longer -> clear flags si->clearFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_FLAGS); if(si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST)) removeFromForceThresholdContactEventPairs(si); } } si->setPairFlags(finfo.pairFlags); } else if(oldType == InteractionType::eTRIGGER) static_cast<TriggerInteraction*>(pair)->setTriggerFlags(finfo.pairFlags); return pair; } } case InteractionType::eCONSTRAINTSHADER: case InteractionType::eARTICULATION: case InteractionType::eTRACKED_IN_SCENE_COUNT: case InteractionType::eINVALID: PX_ASSERT(0); break; } return NULL; } void NPhaseCore::fireCustomFilteringCallbacks(PxsContactManagerOutputIterator& outputs) { PX_PROFILE_ZONE("Sim.fireCustomFilteringCallbacks", mOwnerScene.getContextId()); PxSimulationFilterCallback* callback = mOwnerScene.getFilterCallbackFast(); if(callback) { // Ask user for pair filter status changes PxU64 pairID; PxFilterFlags filterFlags; PxPairFlags pairFlags; while(callback->statusChange(pairID, pairFlags, filterFlags)) { const PxU32 id0 = PxU32(pairID); const PxU32 id1 = PxU32(pairID>>32); const PxHashMap<ElementSimKey, ElementSimInteraction*>::Entry* pair = mElementSimMap.find(ElementSimKey(id0, id1)); ElementSimInteraction* ei = pair ? pair->second : NULL; PX_ASSERT(ei); // Check if the user tries to update a pair even though he deleted it earlier in the same frame checkFilterFlags(filterFlags); PX_ASSERT(ei->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR)); FilterInfo finfo; finfo.filterFlags = filterFlags; finfo.pairFlags = pairFlags; finfo.hasPairID = true; ElementSimInteraction* refInt = refilterInteraction(ei, &finfo, true, outputs); // this gets called at the end of the simulation -> there should be no dirty interactions around PX_ASSERT(!refInt->readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)); PX_ASSERT(!refInt->getDirtyFlags()); if((refInt == ei) && (refInt->getType() == InteractionType::eOVERLAP)) // No interaction conversion happened, the pairFlags were just updated static_cast<ShapeInteraction*>(refInt)->updateState(InteractionDirtyFlag::eFILTER_STATE); } } }
30,403
C++
36.81592
224
0.725652
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScRigidSim.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 "ScScene.h" #include "ScRigidSim.h" #include "ScShapeSim.h" #include "PxsSimulationController.h" using namespace physx; using namespace Sc; /* PT: The BP group ID comes from a Cm::IDPool, and ActorSim is the only class releasing the ID. The rigid tracker ID comes from a Cm::IDPool internal to an ObjectIDTracker, and ActorSim is the only class using it. Thus we should: - promote the BP group ID stuff to a "tracker" object - use the BP group ID as a rigid ID */ RigidSim::RigidSim(Scene& scene, RigidCore& core) : ActorSim(scene, core) { } RigidSim::~RigidSim() { } void notifyActorInteractionsOfTransformChange(ActorSim& actor); void RigidSim::notifyShapesOfTransformChange() { PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); sim->markBoundsForUpdate(); } notifyActorInteractionsOfTransformChange(*this); } void RigidSim::setBodyNodeIndex(const PxNodeIndex nodeIndex) { PxU32 nbElems = getNbElements(); ElementSim** elems = getElements(); while (nbElems--) { ShapeSim* sim = static_cast<ShapeSim*>(*elems++); getScene().getSimulationController()->updateShape(sim->getLLShapeSim(), nodeIndex); } }
2,935
C++
34.373494
90
0.752981
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeCore.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 "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "foundation/PxErrorCallback.h" #include "ScHairSystemShapeCore.h" #include "ScHairSystemShapeSim.h" #include "ScPhysics.h" #include "PxvGlobals.h" #include "PxPhysXGpu.h" using namespace physx; using namespace Sc; namespace physx { namespace Sc { HairSystemShapeCore::HairSystemShapeCore() : ShapeCore(PxEmpty) , mGpuMemStat(0) { mSimulationFilterData = PxFilterData(); mCore = PxsShapeCore(); const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale(); mCore.setTransform(PxTransform(PxIdentity)); mCore.mContactOffset = 0.0f; mCore.mRestOffset = 0.0f; mCore.mShapeFlags = 0; mCore.mMinTorsionalPatchRadius = 0.f; mCore.mTorsionalRadius = 0.f; mLLCore.mSleepThreshold = 5e-5f * scale.speed * scale.speed; mLLCore.mWakeCounter = Physics::sWakeCounterOnCreation; } // PX_SERIALIZATION HairSystemShapeCore::HairSystemShapeCore(const PxEMPTY) : ShapeCore(PxEmpty) { } HairSystemShapeCore::~HairSystemShapeCore() { releaseBuffers(); } void HairSystemShapeCore::createBuffers(PxCudaContextManager* cudaContextManager) { mCudaContextManager = cudaContextManager; // nothing else to do at the moment } void HairSystemShapeCore::releaseBuffers() { // nothing to do at the moment } } // namespace Sc } // namespace physx #endif // PX_SUPPORT_GPU_PHYSX
2,931
C++
30.191489
81
0.769362
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScStaticCore.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 "ScStaticCore.h" #include "ScStaticSim.h" #include "PxRigidStatic.h" using namespace physx; Sc::StaticSim* Sc::StaticCore::getSim() const { return static_cast<StaticSim*>(Sc::ActorCore::getSim()); } void Sc::StaticCore::setActor2World(const PxTransform& actor2World) { mCore.body2World = actor2World; StaticSim* sim = getSim(); if(sim) sim->notifyShapesOfTransformChange(); }
2,094
C++
41.755101
74
0.761223
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScBroadphase.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 SC_BROADPHASE_H #define SC_BROADPHASE_H #include "PxvConfig.h" #include "foundation/PxArray.h" // PT: this class captures parts of the Sc::Scene that deals with broadphase matters. namespace physx { class PxBroadPhaseCallback; namespace Bp { class AABBManagerBase; } namespace Sc { class ObjectIDTracker; class BroadphaseManager { public: BroadphaseManager(); ~BroadphaseManager(); PX_FORCE_INLINE void setBroadPhaseCallback(PxBroadPhaseCallback* callback) { mBroadPhaseCallback = callback; } PX_FORCE_INLINE PxBroadPhaseCallback* getBroadPhaseCallback() const { return mBroadPhaseCallback; } void prepareOutOfBoundsCallbacks(Bp::AABBManagerBase* aabbManager); bool fireOutOfBoundsCallbacks(Bp::AABBManagerBase* aabbManager, const ObjectIDTracker& tracker); void flush(Bp::AABBManagerBase* aabbManager); PxBroadPhaseCallback* mBroadPhaseCallback; PxArray<PxU32> mOutOfBoundsIDs; }; } } #endif
2,711
C
36.666666
117
0.751383
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScFEMClothCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_SCP_FEMCLOTH_CORE #define PX_PHYSICS_SCP_FEMCLOTH_CORE #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxFEMCloth.h" #endif #include "PxFEMParameter.h" #include "../../lowleveldynamics/include/DyFEMClothCore.h" #include "foundation/PxAssert.h" #include "ScActorCore.h" #include "ScShapeCore.h" #include "PxFiltering.h" #include "ScRigidCore.h" //KS - required for ShapeChangeNotifyFlags. Ideally, we should move that to a separate shared file #include "PxConeLimitedConstraint.h" namespace physx { namespace Sc { class FEMClothSim; class FEMClothCore : public ActorCore { // PX_SERIALIZATION public: FEMClothCore(const PxEMPTY) : ActorCore(PxEmpty) {} //static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION FEMClothCore(); ~FEMClothCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PxFEMParameters getParameter() const; void setParameter(const PxFEMParameters& paramters); void addRigidFilter(Sc::BodyCore* core, PxU32 vertId); void removeRigidFilter(Sc::BodyCore* core, PxU32 vertId); PxU32 addRigidAttachment(Sc::BodyCore* core, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeRigidAttachment(Sc::BodyCore* core, PxU32 handle); void addTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx); void removeTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx); PxU32 addTriRigidAttachment(Sc::BodyCore* core, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeTriRigidAttachment(Sc::BodyCore* core, PxU32 handle); void addClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, PxU32 triIdx); void removeClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx0, PxU32 triIdx); PxU32 addClothAttachment(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric); void removeClothAttachment(Sc::FEMClothCore* otherCore, PxU32 handle); #if 0 // disabled until future use. void setDrag(const PxReal v) { mCore.drag = v; } PxReal getDrag() const { return mCore.drag; } void setLift(const PxReal v) { mCore.lift = v; } PxReal getLift() const { return mCore.lift; } void setWind(const PxVec3& wind) { mCore.wind = wind; } PxVec3 getWind() const { return mCore.wind; } void setAirDensity(const float airDensity) { mCore.airDensity = airDensity; } PxReal getAirDensity() const { return mCore.airDensity; } void setBendingActivationAngle(const PxReal angle) { mCore.mBendingActivationAngle = angle; } PxReal getBendingActivationAngle() const { return mCore.mBendingActivationAngle; } #endif void setBendingScales(const PxReal* const bendingScales, PxU32 nbElements); const PxReal* getBendingScales() const; PxU32 getNbBendingScales() const { return mCore.mBendingScales.size(); } void setMaxVelocity(const float maxVelocity) { mCore.maxVelocity = maxVelocity; } PxReal getMaxVelocity() const { return mCore.maxVelocity; } void setMaxDepenetrationVelocity(const float maxDepenetrationVelocity) { mCore.maxDepenetrationVelocity = maxDepenetrationVelocity; } PxReal getMaxDepenetrationVelocity() const { return mCore.maxDepenetrationVelocity; } void setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency) { mCore.nbCollisionPairUpdatesPerTimestep = frequency; } PxU32 getNbCollisionPairUpdatesPerTimestep() const { return mCore.nbCollisionPairUpdatesPerTimestep; } void setNbCollisionSubsteps(const PxU32 frequency) { mCore.nbCollisionSubsteps = frequency; } PxU32 getNbCollisionSubsteps() const { return mCore.nbCollisionSubsteps; } PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxActor* getPxActor() const; void attachShapeCore(ShapeCore* shapeCore); PxReal getWakeCounter() const; void setWakeCounter(const PxReal v); void setWakeCounterInternal(const PxReal v); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: FEMClothSim* getSim() const; PX_FORCE_INLINE const Dy::FEMClothCore& getCore() const { return mCore; } PX_FORCE_INLINE Dy::FEMClothCore& getCore() { return mCore; } static PX_FORCE_INLINE FEMClothCore& getFEMClothCore(FEMClothCore& core) { size_t offset = PX_OFFSET_OF_RT(FEMClothCore, mCore); return *reinterpret_cast<FEMClothCore*>(reinterpret_cast<PxU8*>(&core) - offset); } void setSimulationFilterData(const PxFilterData& data); PxFilterData getSimulationFilterData() const; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFEMClothFlags getFlags() const { return mCore.mFlags; } void setFlags(PxFEMClothFlags flags); #endif PX_FORCE_INLINE PxU64& getGpuMemStat() { return mGpuMemStat; } void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags); private: Dy::FEMClothCore mCore; PxFilterData mFilterData; PxU64 mGpuMemStat; }; } // namespace Sc } #endif #endif
7,376
C
41.396551
141
0.697939
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationAttachmentCore.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 SC_ATTACHMENT_CORE_H #define SC_ATTACHMENT_CORE_H #include "foundation/PxVec3.h" namespace physx { namespace Sc { class ArticulationAttachmentCore { public: // PX_SERIALIZATION ArticulationAttachmentCore(const PxEMPTY) : mTendonSim(NULL) {} void preExportDataReset() { } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationAttachmentCore() : mLowLimit(PX_MAX_F32), mHighLimit(-PX_MAX_F32), mRestLength(0.f) { } PxVec3 mRelativeOffset; //relative offset to the link(in link space) ArticulationAttachmentCore* mParent; PxReal mLowLimit; PxReal mHighLimit; PxReal mRestLength; PxReal mCoefficient; PxU32 mLLLinkIndex; PxU32 mAttachmentIndex; Sc::ArticulationSpatialTendonSim* mTendonSim; }; }//namespace Sc }//namespace physx #endif
2,600
C
36.695652
97
0.738462
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScScene.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 SC_SCENE_H #define SC_SCENE_H #include "PxPhysXConfig.h" #include "PxScene.h" #include "PxSimulationEventCallback.h" #include "foundation/PxPool.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "CmTask.h" #include "CmFlushPool.h" #include "CmPreallocatingPool.h" #include "foundation/PxBitMap.h" #include "ScIterators.h" #include "PxsMaterialManager.h" #include "PxvManager.h" #include "ScStaticCore.h" #include "ScBodyCore.h" #include "PxAggregate.h" #include "PxsContext.h" #include "PxsIslandSim.h" #include "GuPrunerTypedef.h" #include "DyContext.h" #include "ScFiltering.h" #include "ScBroadphase.h" #include "ScInteraction.h" #define PX_MAX_DOMINANCE_GROUP 32 class OverlapFilterTask; namespace physx { class NpShape; struct PxTriggerPair; class PxsSimulationController; class PxsSimulationControllerCallback; class PxsMemoryManager; struct PxConeLimitedConstraint; #if PX_SUPPORT_GPU_PHYSX class PxsKernelWranglerManager; class PxsHeapMemoryAllocatorManager; #endif namespace IG { class SimpleIslandManager; class NodeIndex; typedef PxU32 EdgeIndex; } class PxsCCDContext; namespace Cm { class IDPool; } namespace Bp { class AABBManagerBase; class BroadPhase; class BoundsArray; } namespace Dy { class FeatherstoneArticulation; class Context; #if PX_SUPPORT_GPU_PHYSX class SoftBody; class FEMCloth; class ParticleSystem; class HairSystem; #endif } namespace Sc { class ActorSim; class ElementSim; class ShapeCore; class RigidCore; class ConstraintCore; class ArticulationCore; class ArticulationJointCore; class ArticulationSpatialTendonCore; class ArticulationFixedTendonCore; class ArticulationSensorCore; class LLArticulationPool; class LLArticulationRCPool; class LLSoftBodyPool; class LLFEMClothPool; class LLParticleSystemPool; class LLHairSystemPool; class BodyCore; class SoftBodyCore; class FEMClothCore; class ParticleSystemCore; class HairSystemCore; class NPhaseCore; class ConstraintInteraction; class ElementSimInteraction; class BodySim; class ShapeSim; class RigidSim; class StaticSim; class ConstraintSim; struct TriggerPairExtraData; class ObjectIDTracker; class ActorPairReport; class ContactStreamManager; class SqBoundsManager; class ShapeInteraction; class ElementInteractionMarker; class ArticulationSim; class SoftBodySim; class FEMClothSim; class ParticleSystemSim; class HairSystemSim; class SimStats; struct SimStateData; struct BatchInsertionState { BodySim* bodySim; StaticSim*staticSim; ShapeSim* shapeSim; ptrdiff_t staticActorOffset; ptrdiff_t staticShapeTableOffset; ptrdiff_t dynamicActorOffset; ptrdiff_t dynamicShapeTableOffset; ptrdiff_t shapeOffset; }; struct BatchRemoveState { PxInlineArray<ShapeSim*, 64> bufferedShapes; PxInlineArray<const ShapeCore*, 64> removedShapes; }; struct SceneInternalFlag { enum Enum { eSCENE_SIP_STATES_DIRTY_DOMINANCE = (1<<1), eSCENE_SIP_STATES_DIRTY_VISUALIZATION = (1<<2), eSCENE_DEFAULT = 0 }; }; struct SimulationStage { enum Enum { eCOMPLETE, eCOLLIDE, eFETCHCOLLIDE, eADVANCE, eFETCHRESULT }; }; struct SqBoundsSync; struct SqRefFinder; struct ParticleOrSoftBodyRigidInteraction { IG::EdgeIndex mIndex; PxU32 mCount; ParticleOrSoftBodyRigidInteraction() : mCount(0) {} }; class Scene : public PxUserAllocated { struct SimpleBodyPair { ActorSim* body1; ActorSim* body2; PxU32 body1ID; PxU32 body2ID; }; PX_NOCOPY(Scene) public: Scene(const PxSceneDesc& desc, PxU64 contextID); ~Scene() {} //use release() plz. void preAllocate(PxU32 nbStatics, PxU32 nbBodies, PxU32 nbStaticShapes, PxU32 nbDynamicShapes); void release(); PX_FORCE_INLINE PxsSimulationController* getSimulationController() { return mSimulationController; } PX_FORCE_INLINE const PxsSimulationController* getSimulationController() const { return mSimulationController; } PX_FORCE_INLINE Bp::AABBManagerBase* getAABBManager() { return mAABBManager; } PX_FORCE_INLINE const Bp::AABBManagerBase* getAABBManager() const { return mAABBManager; } PX_FORCE_INLINE PxArray<BodySim*>& getCcdBodies() { return mCcdBodies; } PX_FORCE_INLINE IG::SimpleIslandManager* getSimpleIslandManager() { return mSimpleIslandManager; } PX_FORCE_INLINE const IG::SimpleIslandManager* getSimpleIslandManager() const { return mSimpleIslandManager; } PX_FORCE_INLINE SimulationStage::Enum getSimulationStage() const { return mSimulationStage; } PX_FORCE_INLINE void setSimulationStage(SimulationStage::Enum stage) { mSimulationStage = stage; } PX_FORCE_INLINE PxPool<SimStateData>* getSimStateDataPool() { return mSimStateDataPool; } PX_FORCE_INLINE PxBitMap& getDirtyShapeSimMap() { return mDirtyShapeSimMap; } PX_FORCE_INLINE void setGravity(const PxVec3& g) { mGravity = g; } PX_FORCE_INLINE const PxVec3& getGravity() const { return mGravity; } PX_FORCE_INLINE void setElapsedTime(PxReal t) { mDt = t; mOneOverDt = t > 0.0f ? 1.0f/t : 0.0f; } PX_FORCE_INLINE PxReal getOneOverDt() const { return mOneOverDt; } // PX_FORCE_INLINE PxReal getDt() const { return mDt; } PX_FORCE_INLINE void setLimits(const PxSceneLimits& limits) { mLimits = limits; } PX_FORCE_INLINE const PxSceneLimits& getLimits() const { return mLimits; } PX_FORCE_INLINE void setBatchRemove(BatchRemoveState* bs) { mBatchRemoveState = bs; } PX_FORCE_INLINE BatchRemoveState* getBatchRemove() const { return mBatchRemoveState; } PX_FORCE_INLINE void setMaxArticulationLinks(const PxU32 maxLinks) { mMaxNbArticulationLinks = maxLinks; } PX_FORCE_INLINE PxU32 getMaxArticulationLinks() const { return mMaxNbArticulationLinks; } // mDynamicsContext wrappers PX_FORCE_INLINE Dy::Context* getDynamicsContext() { return mDynamicsContext; } PX_FORCE_INLINE const Dy::Context* getDynamicsContext() const { return mDynamicsContext; } PX_FORCE_INLINE void setBounceThresholdVelocity(PxReal t) { mDynamicsContext->setBounceThreshold(-t); } PX_FORCE_INLINE PxReal getBounceThresholdVelocity() const { return -mDynamicsContext->getBounceThreshold(); } PX_FORCE_INLINE PxSolverType::Enum getSolverType() const { return mDynamicsContext->getSolverType(); } PX_FORCE_INLINE void setFrictionType(PxFrictionType::Enum model) { mDynamicsContext->setFrictionType(model); } PX_FORCE_INLINE PxFrictionType::Enum getFrictionType() const { return mDynamicsContext->getFrictionType(); } PX_FORCE_INLINE void setSolverBatchSize(PxU32 solverBatchSize) { mDynamicsContext->setSolverBatchSize(solverBatchSize); } PX_FORCE_INLINE PxU32 getSolverBatchSize() const { return mDynamicsContext->getSolverBatchSize(); } PX_FORCE_INLINE void setSolverArticBatchSize(PxU32 solverBatchSize) { mDynamicsContext->setSolverArticBatchSize(solverBatchSize); } PX_FORCE_INLINE PxU32 getSolverArticBatchSize() const { return mDynamicsContext->getSolverArticBatchSize(); } PX_FORCE_INLINE void setCCDMaxSeparation(PxReal separation) { mDynamicsContext->setCCDSeparationThreshold(separation); } PX_FORCE_INLINE PxReal getCCDMaxSeparation() const { return mDynamicsContext->getCCDSeparationThreshold(); } PX_FORCE_INLINE void setMaxBiasCoefficient(PxReal coeff) { mDynamicsContext->setMaxBiasCoefficient(coeff); } PX_FORCE_INLINE PxReal getMaxBiasCoefficient() const { return mDynamicsContext->getMaxBiasCoefficient(); } PX_FORCE_INLINE void setFrictionOffsetThreshold(PxReal t) { mDynamicsContext->setFrictionOffsetThreshold(t); } PX_FORCE_INLINE PxReal getFrictionOffsetThreshold() const { return mDynamicsContext->getFrictionOffsetThreshold(); } PX_FORCE_INLINE void setFrictionCorrelationDistance(PxReal t) { mDynamicsContext->setCorrelationDistance(t); } PX_FORCE_INLINE PxReal getFrictionCorrelationDistance() const { return mDynamicsContext->getCorrelationDistance(); } PX_FORCE_INLINE PxReal getLengthScale() const { return mDynamicsContext->getLengthScale(); } PX_FORCE_INLINE void setDynamicsDirty() { mDynamicsContext->setStateDirty(true); } //~mDynamicsContext wrappers // mLLContext wrappers PX_FORCE_INLINE PxsContext* getLowLevelContext() { return mLLContext; } PX_FORCE_INLINE const PxsContext* getLowLevelContext() const { return mLLContext; } PX_FORCE_INLINE Cm::FlushPool* getFlushPool() { return &mLLContext->getTaskPool(); } PX_FORCE_INLINE void setPCM(bool enabled) { mLLContext->setPCM(enabled); } PX_FORCE_INLINE void setContactCache(bool enabled) { mLLContext->setContactCache(enabled); } PX_FORCE_INLINE void setContactModifyCallback(PxContactModifyCallback* callback) { mLLContext->setContactModifyCallback(callback); } PX_FORCE_INLINE PxContactModifyCallback* getContactModifyCallback() const { return mLLContext->getContactModifyCallback(); } PX_FORCE_INLINE void setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value) { mVisualizationParameterChanged = true; mLLContext->setVisualizationParameter(param, value); } PX_FORCE_INLINE PxReal getVisualizationParameter(PxVisualizationParameter::Enum param) const { return mLLContext->getVisualizationParameter(param); } PX_FORCE_INLINE void setVisualizationCullingBox(const PxBounds3& box) { mLLContext->setVisualizationCullingBox(box); } PX_FORCE_INLINE const PxBounds3& getVisualizationCullingBox() const { return mLLContext->getVisualizationCullingBox(); } PX_FORCE_INLINE PxReal getVisualizationScale() const { return mLLContext->getRenderScale(); } PX_FORCE_INLINE PxRenderBuffer& getRenderBuffer() { return mLLContext->getRenderBuffer(); } PX_FORCE_INLINE void setNbContactDataBlocks(PxU32 blockCount) { mLLContext->getNpMemBlockPool().setBlockCount(blockCount); } PX_FORCE_INLINE PxU32 getNbContactDataBlocksUsed() const { return mLLContext->getNpMemBlockPool().getUsedBlockCount(); } PX_FORCE_INLINE PxU32 getMaxNbContactDataBlocksUsed() const { return mLLContext->getNpMemBlockPool().getMaxUsedBlockCount(); } PX_FORCE_INLINE PxU32 getMaxNbConstraintDataBlocksUsed() const { return mLLContext->getNpMemBlockPool().getPeakConstraintBlockCount(); } PX_FORCE_INLINE void setScratchBlock(void* addr, PxU32 size) { mLLContext->setScratchBlock(addr, size); } //~mLLContext wrappers PX_FORCE_INLINE void setFlags(PxSceneFlags flags) { mPublicFlags = flags; } PX_FORCE_INLINE PxSceneFlags getFlags() const { return mPublicFlags; } PX_FORCE_INLINE bool readInternalFlag(SceneInternalFlag::Enum flag) const { return (mInternalFlags & flag) != 0; } void addStatic(StaticCore&, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* uninflatedBounds); void removeStatic(StaticCore&, PxInlineArray<const ShapeCore*,64>& removedShapes, bool wakeOnLostTouch); void addBody(BodyCore&, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* uninflatedBounds, bool compound); void removeBody(BodyCore&, PxInlineArray<const ShapeCore*,64>& removedShapes, bool wakeOnLostTouch); // Batch insertion API. // the bounds generated here are the uninflated bounds for the shapes, *if* they are trigger or sim shapes. // It's up to the caller to ensure the bounds array is big enough. // Some care is required in handling these since sim and SQ tweak the bounds in slightly different ways. void startBatchInsertion(BatchInsertionState&); void addStatic(PxActor* actor, BatchInsertionState&, PxBounds3* outBounds); void addBody(PxActor* actor, BatchInsertionState&, PxBounds3* outBounds, bool compound); void finishBatchInsertion(BatchInsertionState&); void addConstraint(ConstraintCore&, RigidCore*, RigidCore*); void removeConstraint(ConstraintCore&); void addArticulation(ArticulationCore&, BodyCore& root); void removeArticulation(ArticulationCore&); void addArticulationJoint(ArticulationJointCore&, BodyCore& parent, BodyCore& child); void removeArticulationJoint(ArticulationJointCore&); void addArticulationTendon(ArticulationSpatialTendonCore&); void removeArticulationTendon(ArticulationSpatialTendonCore&); void addArticulationTendon(ArticulationFixedTendonCore&); void removeArticulationTendon(ArticulationFixedTendonCore&); void addArticulationSensor(ArticulationSensorCore&); void removeArticulationSensor(ArticulationSensorCore&); void addArticulationSimControl(ArticulationCore& core); void removeArticulationSimControl(ArticulationCore& core); void updateBodySim(BodySim& sim); PX_FORCE_INLINE PxU32 getNbArticulations() const { return mArticulations.size(); } PX_FORCE_INLINE ArticulationCore* const* getArticulations() { return mArticulations.getEntries(); } PX_FORCE_INLINE PxU32 getNbConstraints() const { return mConstraints.size(); } PX_FORCE_INLINE ConstraintCore*const* getConstraints() const { return mConstraints.getEntries(); } PX_FORCE_INLINE ConstraintCore*const* getConstraints() { return mConstraints.getEntries(); } void initContactsIterator(ContactIterator&, PxsContactManagerOutputIterator&); void setSimulationEventCallback(PxSimulationEventCallback* callback); PxSimulationEventCallback* getSimulationEventCallback() const; void setCCDContactModifyCallback(PxCCDContactModifyCallback* callback); PxCCDContactModifyCallback* getCCDContactModifyCallback() const; void setCCDMaxPasses(PxU32 ccdMaxPasses); PxU32 getCCDMaxPasses() const; void setCCDThreshold(PxReal t); PxReal getCCDThreshold() const; // Broad-phase management void finishBroadPhase(PxBaseTask* continuation); void finishBroadPhaseStage2(PxU32 ccdPass); void preallocateContactManagers(PxBaseTask* continuation); void islandInsertion(PxBaseTask* continuation); void registerContactManagers(PxBaseTask* continuation); void registerInteractions(PxBaseTask* continuation); void registerSceneInteractions(PxBaseTask* continuation); void secondPassNarrowPhase(PxBaseTask* continuation); void setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance); PxDominanceGroupPair getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const; // Run void simulate(PxReal timeStep, PxBaseTask* continuation); void advance(PxReal timeStep, PxBaseTask* continuation); void collide(PxReal timeStep, PxBaseTask* continuation); void endSimulation(); void flush(bool sendPendingReports); void fireBrokenConstraintCallbacks(); void fireTriggerCallbacks(); void fireQueuedContactCallbacks(); void fireOnAdvanceCallback(); const PxArray<PxContactPairHeader>& getQueuedContactPairHeaders(); void postCallbacksPreSync(); void postCallbacksPreSyncKinematics(); void postReportsCleanup(); void fireCallbacksPostSync(); void syncSceneQueryBounds(SqBoundsSync& sync, SqRefFinder& finder); PxU32 getDefaultContactReportStreamBufferSize() const; void visualizeStartStep(); // PX_ENABLE_SIM_STATS void getStats(PxSimulationStatistics& stats) const; PX_FORCE_INLINE SimStats& getStatsInternal() { return *mStats; } // PX_ENABLE_SIM_STATS void buildActiveActors(); void buildActiveAndFrozenActors(); PxActor** getActiveActors(PxU32& nbActorsOut); void setActiveActors(PxActor** actors, PxU32 nbActors); PxActor** getFrozenActors(PxU32& nbActorsOut); void finalizeContactStreamAndCreateHeader(PxContactPairHeader& header, const ActorPairReport& aPair, ContactStreamManager& cs, PxU32 removedShapeTestMask); PxTaskManager* getTaskManagerPtr() const { return mTaskManager; } PxCudaContextManager* getCudaContextManager() const { return mCudaContextManager; } void shiftOrigin(const PxVec3& shift); PX_FORCE_INLINE bool isCollisionPhaseActive() const { return mIsCollisionPhaseActive; } PX_FORCE_INLINE void setCollisionPhaseToActive() { PX_ASSERT(!mIsCollisionPhaseActive); mIsCollisionPhaseActive = true; } PX_FORCE_INLINE void setCollisionPhaseToInactive() { PX_ASSERT(mIsCollisionPhaseActive); mIsCollisionPhaseActive = false; } void addShape_(RigidSim&, ShapeCore&); void removeShape_(ShapeSim&, bool wakeOnLostTouch); void registerShapeInNphase(RigidCore* rigidCore, const ShapeCore& shapeCore, const PxU32 transformCacheID); void unregisterShapeFromNphase(const ShapeCore& shapeCore, const PxU32 transformCacheID); void notifyNphaseOnUpdateShapeMaterial(const ShapeCore& shapeCore); // Get an array of the active actors. PX_FORCE_INLINE BodyCore*const* getActiveBodiesArray() const { return mActiveBodies.begin(); } PX_FORCE_INLINE PxU32 getNumActiveBodies() const { return mActiveBodies.size(); } PX_FORCE_INLINE BodyCore*const* getActiveCompoundBodiesArray() const { return mActiveCompoundBodies.begin(); } PX_FORCE_INLINE PxU32 getNumActiveCompoundBodies() const { return mActiveCompoundBodies.size(); } PX_FORCE_INLINE PxU32 getNbInteractions(InteractionType::Enum type) const { return mInteractions[type].size(); } PX_FORCE_INLINE PxU32 getNbActiveInteractions(InteractionType::Enum type) const { return mActiveInteractionCount[type]; } // Get all interactions of a certain type PX_FORCE_INLINE ElementSimInteraction** getInteractions(InteractionType::Enum type) { return mInteractions[type].begin(); } PX_FORCE_INLINE ElementSimInteraction** getActiveInteractions(InteractionType::Enum type) { return mInteractions[type].begin(); } void registerInteraction(ElementSimInteraction* interaction, bool active); void unregisterInteraction(ElementSimInteraction* interaction); void notifyInteractionActivated(Interaction* interaction); void notifyInteractionDeactivated(Interaction* interaction); // for pool management of interaction arrays, a major cause of dynamic allocation void** allocatePointerBlock(PxU32 size); void deallocatePointerBlock(void**, PxU32 size); private: // Get the number of active one-way dominator actors PX_FORCE_INLINE PxU32 getActiveKinematicBodiesCount() const { return mActiveKinematicBodyCount; } // Get an iterator to the active one-way dominator actors PX_FORCE_INLINE BodyCore*const* getActiveKinematicBodies() const { return mActiveBodies.begin(); } // Get the number of active non-kinematic actors PX_FORCE_INLINE PxU32 getActiveDynamicBodiesCount() const { return mActiveBodies.size() - mActiveKinematicBodyCount; } // Get the active non-kinematic actors PX_FORCE_INLINE BodyCore*const* getActiveDynamicBodies() const { return mActiveBodies.begin() + mActiveKinematicBodyCount; } void swapInteractionArrayIndices(PxU32 id1, PxU32 id2, InteractionType::Enum type); public: void addDirtyArticulationSim(ArticulationSim* artiSim); void removeDirtyArticulationSim(ArticulationSim* artiSim); void addToActiveList(ActorSim& actor); void removeFromActiveList(ActorSim& actor); void removeFromActiveCompoundBodyList(BodySim& actor); void swapInActiveBodyList(BodySim& body); // call when an active body gets switched from dynamic to kinematic or vice versa void addActiveBreakableConstraint(ConstraintSim*, ConstraintInteraction*); void removeActiveBreakableConstraint(ConstraintSim*); //the Actor should register its top level shapes with these. void removeBody(BodySim&); //lists of actors woken up or put to sleep last simulate void onBodyWakeUp(BodySim* body); void onBodySleep(BodySim* body); PX_FORCE_INLINE bool isValid() const { return (mLLContext != NULL); } void addToLostTouchList(ActorSim& body1, ActorSim& body2); PxU32 createAggregate(void* userData, PxU32 maxNumShapes, PxAggregateFilterHint filterHint); void deleteAggregate(PxU32 id); Dy::FeatherstoneArticulation* createLLArticulation(ArticulationSim* sim); void destroyLLArticulation(Dy::FeatherstoneArticulation&); PX_FORCE_INLINE PxPool<ConstraintInteraction>* getConstraintInteractionPool() const { return mConstraintInteractionPool; } public: PX_FORCE_INLINE const PxsMaterialManager& getMaterialManager() const { return mMaterialManager; } PX_FORCE_INLINE PxsMaterialManager& getMaterialManager() { return mMaterialManager; } PX_FORCE_INLINE const BroadphaseManager& getBroadphaseManager() const { return mBroadphaseManager; } PX_FORCE_INLINE BroadphaseManager& getBroadphaseManager() { return mBroadphaseManager; } PX_FORCE_INLINE bool fireOutOfBoundsCallbacks() { return mBroadphaseManager.fireOutOfBoundsCallbacks(mAABBManager, *mElementIDPool); } // Collision filtering void setFilterShaderData(const void* data, PxU32 dataSize); PX_FORCE_INLINE const void* getFilterShaderDataFast() const { return mFilterShaderData; } PX_FORCE_INLINE PxU32 getFilterShaderDataSizeFast() const { return mFilterShaderDataSize; } PX_FORCE_INLINE PxSimulationFilterShader getFilterShaderFast() const { return mFilterShader; } PX_FORCE_INLINE PxSimulationFilterCallback* getFilterCallbackFast() const { return mFilterCallback; } PX_FORCE_INLINE PxPairFilteringMode::Enum getKineKineFilteringMode() const { return mKineKineFilteringMode; } PX_FORCE_INLINE PxPairFilteringMode::Enum getStaticKineFilteringMode() const { return mStaticKineFilteringMode; } PX_FORCE_INLINE PxU32 getTimeStamp() const { return mTimeStamp; } PX_FORCE_INLINE PxU32 getReportShapePairTimeStamp() const { return mReportShapePairTimeStamp; } PX_FORCE_INLINE NPhaseCore* getNPhaseCore() const { return mNPhaseCore; } void checkConstraintBreakage(); PX_FORCE_INLINE PxArray<TriggerPairExtraData>& getTriggerBufferExtraData() { return *mTriggerBufferExtraData; } PX_FORCE_INLINE PxArray<PxTriggerPair>& getTriggerBufferAPI() { return mTriggerBufferAPI; } void reserveTriggerReportBufferSpace(const PxU32 pairCount, PxTriggerPair*& triggerPairBuffer, TriggerPairExtraData*& triggerPairExtraBuffer); PX_FORCE_INLINE ObjectIDTracker& getActorIDTracker() { return *mActorIDTracker; } PX_FORCE_INLINE void markReleasedBodyIDForLostTouch(PxU32 id) { mLostTouchPairsDeletedBodyIDs.growAndSet(id); } void resizeReleasedBodyIDMaps(PxU32 maxActors, PxU32 numActors); PX_FORCE_INLINE StaticSim& getStaticAnchor() { return *mStaticAnchor; } PX_FORCE_INLINE Bp::BoundsArray& getBoundsArray() const { return *mBoundsArray; } PX_FORCE_INLINE void updateContactDistance(PxU32 idx, PxReal distance) { (*mContactDistance)[idx] = distance; mHasContactDistanceChanged = true; } PX_FORCE_INLINE SqBoundsManager& getSqBoundsManager() const { return *mSqBoundsManager; } PX_FORCE_INLINE BodyCore* const* getSleepBodiesArray(PxU32& count) { count = mSleepBodies.size(); return mSleepBodies.getEntries(); } PX_FORCE_INLINE PxTaskManager& getTaskManager() const { PX_ASSERT(mTaskManager); return *mTaskManager; } PX_FORCE_INLINE void setPostSolverVelocityNeeded() { mContactReportsNeedPostSolverVelocity = true; } PX_FORCE_INLINE ObjectIDTracker& getConstraintIDTracker() { return *mConstraintIDTracker; } PX_FORCE_INLINE ObjectIDTracker& getElementIDPool() { return *mElementIDPool; } PX_FORCE_INLINE PxBitMap& getVelocityModifyMap() { return mVelocityModifyMap; } void* allocateConstraintBlock(PxU32 size); void deallocateConstraintBlock(void* addr, PxU32 size); void stepSetupCollide(PxBaseTask* continuation);//This is very important to guarantee thread safty in the collide PX_FORCE_INLINE void addToPosePreviewList(BodySim& b) { PX_ASSERT(!mPosePreviewBodies.contains(&b)); mPosePreviewBodies.insert(&b); } PX_FORCE_INLINE void removeFromPosePreviewList(BodySim& b) { PX_ASSERT(mPosePreviewBodies.contains(&b)); mPosePreviewBodies.erase(&b); } #if PX_DEBUG PX_FORCE_INLINE bool isInPosePreviewList(BodySim& b) const { return mPosePreviewBodies.contains(&b); } #endif PX_FORCE_INLINE void setSpeculativeCCDRigidBody(PxU32 index) { mSpeculativeCCDRigidBodyBitMap.growAndSet(index); } PX_FORCE_INLINE void resetSpeculativeCCDRigidBody(PxU32 index) { if(index < mSpeculativeCCDRigidBodyBitMap.size()) mSpeculativeCCDRigidBodyBitMap.reset(index); } PX_FORCE_INLINE void setSpeculativeCCDArticulationLink(PxU32 index) { mSpeculativeCDDArticulationBitMap.growAndSet(index); } PX_FORCE_INLINE void resetSpeculativeCCDArticulationLink(PxU32 index) { if(index < mSpeculativeCDDArticulationBitMap.size()) mSpeculativeCDDArticulationBitMap.reset(index); } PX_FORCE_INLINE PxU64 getContextId() const { return mContextId; } PX_FORCE_INLINE bool isUsingGpuDynamicsOrBp() const { return mUseGpuBp || mUseGpuDynamics; } PX_FORCE_INLINE bool isUsingGpuDynamicsAndBp() const { return mUseGpuBp && mUseGpuDynamics; } PX_FORCE_INLINE bool isUsingGpuDynamics() const { return mUseGpuDynamics; } PX_FORCE_INLINE bool isUsingGpuBp() const { return mUseGpuBp; } PX_FORCE_INLINE void setDirectGPUAPIInitialized() { mIsDirectGPUAPIInitialized = true; } PX_FORCE_INLINE bool isDirectGPUAPIInitialized() const { return mIsDirectGPUAPIInitialized; } // statistics counters increase/decrease PX_FORCE_INLINE void increaseNumKinematicsCounter() { mNbRigidKinematic++; } PX_FORCE_INLINE void decreaseNumKinematicsCounter() { mNbRigidKinematic--; } PX_FORCE_INLINE void increaseNumDynamicsCounter() { mNbRigidDynamics++; } PX_FORCE_INLINE void decreaseNumDynamicsCounter() { mNbRigidDynamics--; } ConstraintCore* findConstraintCore(const ActorSim* sim0, const ActorSim* sim1); //internal private methods: private: void activateEdgesInternal(const IG::EdgeIndex* activatingEdges, const PxU32 nbActivatingEdges); void releaseConstraints(bool endOfScene); PX_INLINE void clearBrokenConstraintBuffer() { mBrokenConstraints.clear(); } ///////////////////////////////////////////////////////////// void collideStep(PxBaseTask* continuation); void advanceStep(PxBaseTask* continuation); // subroutines of collideStep/solveStep: void kinematicsSetup(PxBaseTask* continuation); void stepSetupSolve(PxBaseTask* continuation); //void stepSetupSimulate(); void processNarrowPhaseTouchEvents(); void processNarrowPhaseTouchEventsStage2(PxBaseTask*); void setEdgesConnected(PxBaseTask*); void processNarrowPhaseLostTouchEvents(PxBaseTask*); void processNarrowPhaseLostTouchEventsIslands(PxBaseTask*); void processLostTouchPairs(); void integrateKinematicPose(); void updateKinematicCached(PxBaseTask* task); void beforeSolver(PxBaseTask* continuation); void checkForceThresholdContactEvents(PxU32 ccdPass); private: void putObjectsToSleep(); void wakeObjectsUp(); void collectPostSolverVelocitiesBeforeCCD(); void clearSleepWakeBodies(void); PX_INLINE void cleanUpSleepBodies(); PX_INLINE void cleanUpWokenBodies(); PX_INLINE void cleanUpSleepOrWokenBodies(PxCoalescedHashSet<BodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker); private: // Material manager PX_ALIGN(16, PxsMaterialManager mMaterialManager); BroadphaseManager mBroadphaseManager; PxU64 mContextId; PxArray<BodyCore*> mActiveBodies; // Sorted: kinematic before dynamic PxU32 mActiveKinematicBodyCount; // Number of active kinematics. This is also the index in mActiveBodies where the active dynamic bodies start. PxU32 mActiveDynamicBodyCount; // Number of active dynamics. This is also the index in mActiveBodies where the active soft bodies start. PxArray<BodyCore*> mActiveCompoundBodies; BodyCore** mActiveKinematicsCopy; PxU32 mActiveKinematicsCopyCapacity; // PT: this array used for: // - debug visualization // - processing trigger interactions // - updating dirty interactions PxArray<ElementSimInteraction*> mInteractions[InteractionType::eTRACKED_IN_SCENE_COUNT]; PxU32 mActiveInteractionCount[InteractionType::eTRACKED_IN_SCENE_COUNT]; // Interactions with id < activeInteractionCount are active template <typename T, PxU32 size> struct Block { PxU8 mem[sizeof(T)*size]; Block() {} // get around VS warning C4345, otherwise useless }; typedef Block<void*, 8> PointerBlock8; typedef Block<void*, 16> PointerBlock16; typedef Block<void*, 32> PointerBlock32; PxPool<PointerBlock8> mPointerBlock8Pool; PxPool<PointerBlock16> mPointerBlock16Pool; PxPool<PointerBlock32> mPointerBlock32Pool; PxsContext* mLLContext; Bp::AABBManagerBase* mAABBManager; PxsCCDContext* mCCDContext; PxI32 mNumFastMovingShapes; PxU32 mCCDPass; IG::SimpleIslandManager* mSimpleIslandManager; Dy::Context* mDynamicsContext; PxsMemoryManager* mMemoryManager; #if PX_SUPPORT_GPU_PHYSX PxsKernelWranglerManager* mGpuWranglerManagers; PxsHeapMemoryAllocatorManager* mHeapMemoryAllocationManager; #endif PxsSimulationController* mSimulationController; PxsSimulationControllerCallback* mSimulationControllerCallback; PxSceneLimits mLimits; PxVec3 mGravity; //!< Gravity vector PxArray<PxContactPairHeader> mQueuedContactPairHeaders; //time: //constants set with setTiming(): PxReal mDt; //delta time for current step. PxReal mOneOverDt; //inverse of dt. //stepping / counters: PxU32 mTimeStamp; //Counts number of steps. PxU32 mReportShapePairTimeStamp; //Timestamp for refreshing the shape pair report structure. Updated before delayed shape/actor deletion and before CCD passes. //containers: // Those ones contain shape ptrs from Actor, i.e. compound level, not subparts PxCoalescedHashSet<ConstraintCore*> mConstraints; Bp::BoundsArray* mBoundsArray; PxFloatArrayPinned* mContactDistance; bool mHasContactDistanceChanged; SqBoundsManager* mSqBoundsManager; PxArray<BodySim*> mCcdBodies; PxArray<PxTriggerPair> mTriggerBufferAPI; PxArray<TriggerPairExtraData>* mTriggerBufferExtraData; PxCoalescedHashSet<ArticulationCore*> mArticulations; PxCoalescedHashSet<ArticulationSim*> mDirtyArticulationSims; PxArray<ConstraintCore*> mBrokenConstraints; PxCoalescedHashSet<ConstraintSim*> mActiveBreakableConstraints; // pools for joint buffers // Fixed joint is 92 bytes, D6 is 364 bytes right now. So these three pools cover all the internal cases typedef Block<PxU8, 128> MemBlock128; typedef Block<PxU8, 256> MemBlock256; typedef Block<PxU8, 384> MemBlock384; PxPool2<MemBlock128, 8192> mMemBlock128Pool; PxPool2<MemBlock256, 8192> mMemBlock256Pool; PxPool2<MemBlock384, 8192> mMemBlock384Pool; // broad phase data: NPhaseCore* mNPhaseCore; // Collision filtering void* mFilterShaderData; PxU32 mFilterShaderDataSize; PxU32 mFilterShaderDataCapacity; PxSimulationFilterShader mFilterShader; PxSimulationFilterCallback* mFilterCallback; const PxPairFilteringMode::Enum mKineKineFilteringMode; const PxPairFilteringMode::Enum mStaticKineFilteringMode; PxCoalescedHashSet<BodyCore*> mSleepBodies; PxCoalescedHashSet<BodyCore*> mWokeBodies; bool mWokeBodyListValid; bool mSleepBodyListValid; const bool mEnableStabilization; PxArray<PxActor*> mActiveActors; PxArray<PxActor*> mFrozenActors; PxArray<const PxRigidBody*> mClientPosePreviewBodies; // buffer for bodies that requested early report of the integrated pose (eENABLE_POSE_INTEGRATION_PREVIEW). // This buffer gets exposed to users. Is officially accessible from PxSimulationEventCallback::onAdvance() // until the next simulate()/advance(). PxArray<PxTransform> mClientPosePreviewBuffer; // buffer of newly integrated poses for the bodies that requested a preview. This buffer gets exposed // to users. PxSimulationEventCallback* mSimulationEventCallback; SimStats* mStats; PxU32 mInternalFlags; // PT: combination of ::SceneInternalFlag, looks like only 2 bits are needed PxSceneFlags mPublicFlags; // Copy of PxSceneDesc::flags, of type PxSceneFlag // PT: TODO: unify names, "tracker" or "pool"? ObjectIDTracker* mConstraintIDTracker; // PT: provides Sc::ContraintSim::mLowLevelConstraint::index ObjectIDTracker* mActorIDTracker; // PT: provides Sc::ActorSim::mId ObjectIDTracker* mElementIDPool; // PT: provides Sc::ElementSim::mElementID StaticCore mAnchorCore; StaticSim* mStaticAnchor; Cm::PreallocatingPool<ShapeSim>* mShapeSimPool; Cm::PreallocatingPool<StaticSim>* mStaticSimPool; Cm::PreallocatingPool<BodySim>* mBodySimPool; PxPool<ConstraintSim>* mConstraintSimPool; LLArticulationRCPool* mLLArticulationRCPool; PxHashMap<PxPair<const ActorSim*, const ActorSim*>, ConstraintCore*> mConstraintMap; PxPool<ConstraintInteraction>* mConstraintInteractionPool; PxPool<SimStateData>* mSimStateDataPool; BatchRemoveState* mBatchRemoveState; PxArray<SimpleBodyPair> mLostTouchPairs; PxBitMap mLostTouchPairsDeletedBodyIDs; // Need to know which bodies have been deleted when processing the lost touch pair list. // Can't use the existing rigid object ID tracker class since this map needs to be cleared at // another point in time. PxBitMap mVelocityModifyMap; PxArray<PxvContactManagerTouchEvent> mTouchFoundEvents; PxArray<PxvContactManagerTouchEvent> mTouchLostEvents; PxBitMap mDirtyShapeSimMap; PxU32 mDominanceBitMatrix[PX_MAX_DOMINANCE_GROUP]; bool mVisualizationParameterChanged; PxU32 mMaxNbArticulationLinks; // statics: PxU32 mNbRigidStatics; PxU32 mNbRigidDynamics; PxU32 mNbRigidKinematic; PxU32 mNbGeometries[PxGeometryType::eGEOMETRY_COUNT]; //IG::Node::eTYPE_COUNT PxU32 mNumDeactivatingNodes[IG::Node::eTYPE_COUNT]; // task decomposition void broadPhase(PxBaseTask* continuation); void broadPhaseFirstPass(PxBaseTask* continuation); void broadPhaseSecondPass(PxBaseTask* continuation); void updateBroadPhase(PxBaseTask* continuation); void preIntegrate(PxBaseTask* continuation); void postBroadPhase(PxBaseTask* continuation); void postBroadPhaseContinuation(PxBaseTask* continuation); void preRigidBodyNarrowPhase(PxBaseTask* continuation); void postBroadPhaseStage2(PxBaseTask* continuation); void postBroadPhaseStage3(PxBaseTask* continuation); void updateBoundsAndShapes(PxBaseTask* continuation); void rigidBodyNarrowPhase(PxBaseTask* continuation); void unblockNarrowPhase(PxBaseTask* continuation); void islandGen(PxBaseTask* continuation); void processLostSolverPatches(PxBaseTask* continuation); void processFoundSolverPatches(PxBaseTask* continuation); void postIslandGen(PxBaseTask* continuation); void solver(PxBaseTask* continuation); void updateBodies(PxBaseTask* continuation); void updateShapes(PxBaseTask* continuation); void updateSimulationController(PxBaseTask* continuation); void updateDynamics(PxBaseTask* continuation); void processLostContacts(PxBaseTask*); void processLostContacts2(PxBaseTask*); void processLostContacts3(PxBaseTask*); void destroyManagers(PxBaseTask*); void lostTouchReports(PxBaseTask*); void unregisterInteractions(PxBaseTask*); void postThirdPassIslandGen(PxBaseTask*); void postSolver(PxBaseTask* continuation); void constraintProjection(PxBaseTask* continuation); void afterIntegration(PxBaseTask* continuation); // performs sleep check, for instance void postCCDPass(PxBaseTask* continuation); void ccdBroadPhaseAABB(PxBaseTask* continuation); void ccdBroadPhase(PxBaseTask* continuation); void updateCCDMultiPass(PxBaseTask* continuation); void updateCCDSinglePass(PxBaseTask* continuation); void updateCCDSinglePassStage2(PxBaseTask* continuation); void updateCCDSinglePassStage3(PxBaseTask* continuation); void finalizationPhase(PxBaseTask* continuation); void postNarrowPhase(PxBaseTask* continuation); void addShapes(NpShape*const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& sim, PxBounds3* outBounds); void removeShapes(RigidSim& , PxInlineArray<ShapeSim*, 64>& , PxInlineArray<const ShapeCore*, 64>&, bool wakeOnLostTouch); private: void addShapes(NpShape*const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& sim, ShapeSim*& prefetchedShapeSim, PxBounds3* outBounds); void updateContactDistances(PxBaseTask* continuation); void updateDirtyShapes(PxBaseTask* continuation); Cm::DelegateTask<Scene, &Scene::secondPassNarrowPhase> mSecondPassNarrowPhase; Cm::DelegateFanoutTask<Scene, &Scene::postNarrowPhase> mPostNarrowPhase; Cm::DelegateFanoutTask<Scene, &Scene::finalizationPhase> mFinalizationPhase; Cm::DelegateTask<Scene, &Scene::updateCCDMultiPass> mUpdateCCDMultiPass; //multi-pass ccd stuff PxArray<Cm::DelegateTask<Scene, &Scene::updateCCDSinglePass> > mUpdateCCDSinglePass; PxArray<Cm::DelegateTask<Scene, &Scene::updateCCDSinglePassStage2> > mUpdateCCDSinglePass2; PxArray<Cm::DelegateTask<Scene, &Scene::updateCCDSinglePassStage3> > mUpdateCCDSinglePass3; PxArray<Cm::DelegateTask<Scene, &Scene::ccdBroadPhaseAABB> > mCCDBroadPhaseAABB; PxArray<Cm::DelegateTask<Scene, &Scene::ccdBroadPhase> > mCCDBroadPhase; PxArray<Cm::DelegateTask<Scene, &Scene::postCCDPass> > mPostCCDPass; Cm::DelegateTask<Scene, &Scene::afterIntegration> mAfterIntegration; Cm::DelegateTask<Scene, &Scene::postSolver> mPostSolver; Cm::DelegateTask<Scene, &Scene::solver> mSolver; Cm::DelegateTask<Scene, &Scene::updateBodies> mUpdateBodies; Cm::DelegateTask<Scene, &Scene::updateShapes> mUpdateShapes; Cm::DelegateTask<Scene, &Scene::updateSimulationController> mUpdateSimulationController; Cm::DelegateTask<Scene, &Scene::updateDynamics> mUpdateDynamics; Cm::DelegateTask<Scene, &Scene::processLostContacts> mProcessLostContactsTask; Cm::DelegateTask<Scene, &Scene::processLostContacts2> mProcessLostContactsTask2; Cm::DelegateTask<Scene, &Scene::processLostContacts3> mProcessLostContactsTask3; Cm::DelegateTask<Scene, &Scene::destroyManagers> mDestroyManagersTask; Cm::DelegateTask<Scene, &Scene::lostTouchReports> mLostTouchReportsTask; Cm::DelegateTask<Scene, &Scene::unregisterInteractions> mUnregisterInteractionsTask; Cm::DelegateTask<Scene, &Scene::processNarrowPhaseLostTouchEventsIslands> mProcessNarrowPhaseLostTouchTasks; Cm::DelegateTask<Scene, &Scene::processNarrowPhaseLostTouchEvents> mProcessNPLostTouchEvents; Cm::DelegateTask<Scene, &Scene::postThirdPassIslandGen> mPostThirdPassIslandGenTask; Cm::DelegateTask<Scene, &Scene::postIslandGen> mPostIslandGen; Cm::DelegateTask<Scene, &Scene::islandGen> mIslandGen; Cm::DelegateTask<Scene, &Scene::preRigidBodyNarrowPhase> mPreRigidBodyNarrowPhase; Cm::DelegateTask<Scene, &Scene::setEdgesConnected> mSetEdgesConnectedTask; Cm::DelegateTask<Scene, &Scene::processLostSolverPatches> mProcessLostPatchesTask; Cm::DelegateTask<Scene, &Scene::processFoundSolverPatches> mProcessFoundPatchesTask; Cm::DelegateFanoutTask<Scene, &Scene::updateBoundsAndShapes> mUpdateBoundAndShapeTask; Cm::DelegateTask<Scene, &Scene::rigidBodyNarrowPhase> mRigidBodyNarrowPhase; Cm::DelegateTask<Scene, &Scene::unblockNarrowPhase> mRigidBodyNPhaseUnlock; Cm::DelegateTask<Scene, &Scene::postBroadPhase> mPostBroadPhase; Cm::DelegateTask<Scene, &Scene::postBroadPhaseContinuation> mPostBroadPhaseCont; Cm::DelegateTask<Scene, &Scene::postBroadPhaseStage2> mPostBroadPhase2; Cm::DelegateFanoutTask<Scene, &Scene::postBroadPhaseStage3> mPostBroadPhase3; Cm::DelegateTask<Scene, &Scene::preallocateContactManagers> mPreallocateContactManagers; Cm::DelegateTask<Scene, &Scene::islandInsertion> mIslandInsertion; Cm::DelegateTask<Scene, &Scene::registerContactManagers> mRegisterContactManagers; Cm::DelegateTask<Scene, &Scene::registerInteractions> mRegisterInteractions; Cm::DelegateTask<Scene, &Scene::registerSceneInteractions> mRegisterSceneInteractions; Cm::DelegateTask<Scene, &Scene::broadPhase> mBroadPhase; Cm::DelegateTask<Scene, &Scene::advanceStep> mAdvanceStep; Cm::DelegateTask<Scene, &Scene::collideStep> mCollideStep; Cm::DelegateTask<Scene, &Scene::broadPhaseFirstPass> mBpFirstPass; Cm::DelegateTask<Scene, &Scene::broadPhaseSecondPass> mBpSecondPass; Cm::DelegateTask<Scene, &Scene::updateBroadPhase> mBpUpdate; Cm::DelegateTask<Scene, &Scene::preIntegrate> mPreIntegrate; Cm::FlushPool mTaskPool; PxTaskManager* mTaskManager; PxCudaContextManager* mCudaContextManager; bool mContactReportsNeedPostSolverVelocity; bool mUseGpuDynamics; bool mUseGpuBp; bool mCCDBp; SimulationStage::Enum mSimulationStage; PxCoalescedHashSet<const BodySim*> mPosePreviewBodies; // list of bodies that requested early report of the integrated pose (eENABLE_POSE_INTEGRATION_PREVIEW). PxArray<PxsContactManager*> mPreallocatedContactManagers; PxArray<ShapeInteraction*> mPreallocatedShapeInteractions; PxArray<ElementInteractionMarker*> mPreallocatedInteractionMarkers; OverlapFilterTask* mOverlapFilterTaskHead; // PT: tmp data passed from finishBroadPhase to preallocateContactManagers PxArray<FilterInfo> mFilterInfo; // PT: tmp data passed from finishBroadPhase to preallocateContactManagers PxBitMap mSpeculativeCCDRigidBodyBitMap; PxBitMap mSpeculativeCDDArticulationBitMap; bool mIsCollisionPhaseActive; // Set to true as long as collision phase is active (used as an indicator that it is OK to read object pose, // velocity etc. compared to the solver phase where these properties might get written to). bool mIsDirectGPUAPIInitialized; public: // For OmniPVD. To notify NpScene that actor's sleeping state has changed. typedef void(*SleepingStateChangedCallback)(PxRigidDynamic&, bool); SleepingStateChangedCallback mOnSleepingStateChanged; // PT: moved all the GPU-related code & data here in an attempt to clearly separate the CPU/GPU bits #if PX_SUPPORT_GPU_PHYSX public: void gpu_addToActiveList(ActorSim& actorSim, ActorCore* appendedActorCore); void gpu_removeFromActiveList(ActorSim& actorSim, PxU32 removedActiveIndex); void gpu_clearSleepWakeBodies(); void gpu_buildActiveActors(); void gpu_buildActiveAndFrozenActors(); void gpu_setSimulationEventCallback(PxSimulationEventCallback* callback); PxU32 gpu_cleanUpSleepAndWokenBodies(); void gpu_fireOnSleepCallback(PxActor** actors); void gpu_fireOnWakeCallback(PxActor** actors); void gpu_updateBounds(); void gpu_releasePools(); void gpu_release(); void addSoftBody(SoftBodyCore&); void removeSoftBody(SoftBodyCore&); void addFEMCloth(FEMClothCore&); void removeFEMCloth(FEMClothCore&); void addParticleSystem(ParticleSystemCore&); void removeParticleSystem(ParticleSystemCore&); void addHairSystem(HairSystemCore&); void removeHairSystem(HairSystemCore&); PX_FORCE_INLINE PxU32 getNbSoftBodies() const { return mSoftBodies.size(); } PX_FORCE_INLINE SoftBodyCore* const* getSoftBodies() { return mSoftBodies.getEntries(); } PX_FORCE_INLINE PxU32 getNbFEMCloths() const { return mFEMCloths.size(); } PX_FORCE_INLINE FEMClothCore* const* getFEMCloths() { return mFEMCloths.getEntries(); } PX_FORCE_INLINE PxU32 getNbParticleSystems() const { return mParticleSystems.size(); } PX_FORCE_INLINE ParticleSystemCore* const* getParticleSystems() { return mParticleSystems.getEntries(); } PX_FORCE_INLINE PxU32 getNbHairSystems() const { return mHairSystems.size(); } PX_FORCE_INLINE HairSystemCore* const* getHairSystems() { return mHairSystems.getEntries(); } PX_FORCE_INLINE SoftBodyCore*const* getActiveSoftBodiesArray() const { return mActiveSoftBodies.begin(); } PX_FORCE_INLINE PxU32 getNumActiveSoftBodies() const { return mActiveSoftBodies.size(); } PX_FORCE_INLINE FEMClothCore*const* getActiveFEMClothsArray() const { return mActiveFEMCloths.begin(); } PX_FORCE_INLINE PxU32 getNumActiveFEMCloths() const { return mActiveFEMCloths.size(); } PX_FORCE_INLINE HairSystemCore*const* getActiveHairSystemsArray() const { return mActiveHairSystems.begin(); } PX_FORCE_INLINE PxU32 getNumActiveHairSystems() const { return mActiveHairSystems.size(); } // PT: redundant? // Get the active soft body actors PX_FORCE_INLINE SoftBodyCore*const* getActiveSoftBodies() const { return mActiveSoftBodies.begin(); } PX_FORCE_INLINE SoftBodyCore*const* getSleepSoftBodiesArray(PxU32& count) { count = mSleepSoftBodies.size(); return mSleepSoftBodies.getEntries(); } // PT: redundant? // Get the active FEM-cloth actors PX_FORCE_INLINE FEMClothCore*const* getActiveFEMCloths() const { return mActiveFEMCloths.begin(); } PX_FORCE_INLINE const PxsFEMMaterialManager& getFEMMaterialManager() const { return mFEMMaterialManager; } PX_FORCE_INLINE PxsFEMMaterialManager& getFEMMaterialManager() { return mFEMMaterialManager; } PX_FORCE_INLINE const PxsFEMClothMaterialManager& getFEMClothMaterialManager() const { return mFEMClothMaterialManager; } PX_FORCE_INLINE PxsFEMClothMaterialManager& getFEMClothMaterialManager() { return mFEMClothMaterialManager; } PX_FORCE_INLINE const PxsPBDMaterialManager& getPBDMaterialManager() const { return mPBDMaterialManager; } PX_FORCE_INLINE PxsPBDMaterialManager& getPBDMaterialManager() { return mPBDMaterialManager; } PX_FORCE_INLINE const PxsFLIPMaterialManager& getFLIPMaterialManager() const { return mFLIPMaterialManager; } PX_FORCE_INLINE PxsFLIPMaterialManager& getFLIPMaterialManager() { return mFLIPMaterialManager; } PX_FORCE_INLINE const PxsMPMMaterialManager& getMPMMaterialManager() const { return mMPMMaterialManager; } PX_FORCE_INLINE PxsMPMMaterialManager& getMPMMaterialManager() { return mMPMMaterialManager; } Dy::SoftBody* createLLSoftBody(SoftBodySim* sim); void destroyLLSoftBody(Dy::SoftBody& softBody); Dy::FEMCloth* createLLFEMCloth(FEMClothSim* sim); void destroyLLFEMCloth(Dy::FEMCloth& femCloth); Dy::ParticleSystem* createLLParticleSystem(ParticleSystemSim* sim); void destroyLLParticleSystem(Dy::ParticleSystem& softBody); Dy::HairSystem* createLLHairSystem(HairSystemSim* sim); void destroyLLHairSystem(Dy::HairSystem& hairSystem); // PT: TODO: why inline these ones? PX_INLINE void cleanUpSleepSoftBodies(); PX_INLINE void cleanUpWokenSoftBodies(); PX_INLINE void cleanUpSleepOrWokenSoftBodies(PxCoalescedHashSet<SoftBodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker); PX_INLINE void cleanUpSleepHairSystems(); PX_INLINE void cleanUpWokenHairSystems(); PX_INLINE void cleanUpSleepOrWokenHairSystems(PxCoalescedHashSet<HairSystemCore*>& bodyList, PxU32 removeFlag, bool& validMarker); void addSoftBodySimControl(SoftBodyCore& core); void removeSoftBodySimControl(SoftBodyCore& core); void addFEMClothSimControl(FEMClothCore& core); void removeFEMClothSimControl(FEMClothCore& core); void addParticleSystemSimControl(ParticleSystemCore& core); void removeParticleSystemSimControl(ParticleSystemCore& core); void addHairSystemSimControl(HairSystemCore& core); void removeHairSystemSimControl(HairSystemCore& core); void addParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId); void removeParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId); PxU32 addParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric); void removeParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 handle); void addRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 vertId); void removeRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 vertId); PxU32 addRigidAttachment(BodyCore* core, SoftBodySim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeRigidAttachment(BodyCore* core, SoftBodySim& sim, PxU32 handle); void addTetRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 tetIdx); void removeTetRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 tetIdx); PxU32 addTetRigidAttachment(BodyCore* core, SoftBodySim& sim, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void addSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1); void removeSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1); void addSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); void removeSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); PxU32 addSoftBodyAttachment(SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, SoftBodySim& sim, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset); void removeSoftBodyAttachment(SoftBodyCore& core, SoftBodySim& sim, PxU32 handle); void addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx); void removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx); void addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx); void removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx); PxU32 addClothAttachment(FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, SoftBodySim& sim, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset); void removeClothAttachment(FEMClothCore& core, SoftBodySim& sim, PxU32 handle); void addRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 vertId); void removeRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 vertId); PxU32 addRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 handle); void addClothFilter(FEMClothCore& core0, PxU32 triIdx0, Sc::FEMClothSim& sim1, PxU32 triIdx1); void removeClothFilter(FEMClothCore& core, PxU32 triIdx0, FEMClothSim& sim1, PxU32 triIdx1); PxU32 addTriClothAttachment(FEMClothCore& core0, PxU32 triIdx0, const PxVec4& barycentric0, Sc::FEMClothSim& sim1, PxU32 triIdx1, const PxVec4& barycentric1); void removeTriClothAttachment(FEMClothCore& core, FEMClothSim& sim1, PxU32 handle); void addTriRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 triIdx); void removeTriRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 triIdx); PxU32 addTriRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeTriRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 handle); void addRigidAttachment(BodyCore* core, ParticleSystemSim& sim); void removeRigidAttachment(BodyCore* core, ParticleSystemSim& sim); void addAttachment(const BodySim& bodySim, const HairSystemSim& hairSim); void addAttachment(const SoftBodySim& sbSim, const HairSystemSim& hairSim); void removeAttachment(const BodySim& bodySim, const HairSystemSim& hairSim); void removeAttachment(const SoftBodySim& sbSim, const HairSystemSim& hairSim); PxActor** getActiveSoftBodyActors(PxU32& nbActorsOut); void setActiveSoftBodyActors(PxActor** actors, PxU32 nbActors); //PxActor** getActiveFEMClothActors(PxU32& nbActorsOut); //void setActiveFEMClothActors(PxActor** actors, PxU32 nbActors); PX_ALIGN(16, PxsFEMMaterialManager mFEMMaterialManager); PX_ALIGN(16, PxsFEMClothMaterialManager mFEMClothMaterialManager); PX_ALIGN(16, PxsPBDMaterialManager mPBDMaterialManager); PX_ALIGN(16, PxsFLIPMaterialManager mFLIPMaterialManager); PX_ALIGN(16, PxsMPMMaterialManager mMPMMaterialManager); PxArray<SoftBodyCore*> mActiveSoftBodies; PxArray<FEMClothCore*> mActiveFEMCloths; PxArray<ParticleSystemCore*> mActiveParticleSystems; PxArray<HairSystemCore*> mActiveHairSystems; PxCoalescedHashSet<SoftBodyCore*> mSoftBodies; PxCoalescedHashSet<FEMClothCore*> mFEMCloths; PxCoalescedHashSet<ParticleSystemCore*> mParticleSystems; PxCoalescedHashSet<HairSystemCore*> mHairSystems; PxCoalescedHashSet<SoftBodyCore*> mSleepSoftBodies; PxCoalescedHashSet<SoftBodyCore*> mWokeSoftBodies; PxCoalescedHashSet<HairSystemCore*> mSleepHairSystems; PxCoalescedHashSet<HairSystemCore*> mWokeHairSystems; PxArray<PxActor*> mActiveSoftBodyActors; PxArray<PxActor*> mActiveFEMClothActors; PxArray<PxActor*> mActiveHairSystemActors; LLSoftBodyPool* mLLSoftBodyPool; LLFEMClothPool* mLLFEMClothPool; LLParticleSystemPool* mLLParticleSystemPool; LLHairSystemPool* mLLHairSystemPool; PxHashMap<PxPair<PxU32, PxU32>, ParticleOrSoftBodyRigidInteraction> mParticleOrSoftBodyRigidInteractionMap; bool mWokeSoftBodyListValid; bool mSleepSoftBodyListValid; bool mWokeHairSystemListValid; bool mSleepHairSystemListValid; #endif }; bool activateInteraction(Interaction* interaction, void* data); void activateInteractions(Sc::ActorSim& actorSim); void deactivateInteractions(Sc::ActorSim& actorSim); } // namespace Sc } #endif
59,428
C
48.441764
232
0.728024
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationCore.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 SC_ARTICULATION_CORE_H #define SC_ARTICULATION_CORE_H #include "ScActorCore.h" #include "DyFeatherstoneArticulation.h" namespace physx { class PxNodeIndex; namespace Sc { class ArticulationSim; class ArticulationCore { //--------------------------------------------------------------------------------- // Construction, destruction & initialization //--------------------------------------------------------------------------------- // PX_SERIALIZATION public: ArticulationCore(const PxEMPTY) : mSim(NULL), mCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationCore(); ~ArticulationCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PX_FORCE_INLINE PxReal getSleepThreshold() const { return mCore.sleepThreshold; } PX_FORCE_INLINE void setSleepThreshold(const PxReal v) { mCore.sleepThreshold = v; } PX_FORCE_INLINE PxReal getFreezeThreshold() const { return mCore.freezeThreshold; } PX_FORCE_INLINE void setFreezeThreshold(const PxReal v) { mCore.freezeThreshold = v; } PX_FORCE_INLINE PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } PX_FORCE_INLINE void setSolverIterationCounts(PxU16 c) { mCore.solverIterationCounts = c; } PX_FORCE_INLINE PxReal getWakeCounter() const { return mCore.wakeCounter; } PX_FORCE_INLINE void setWakeCounterInternal(const PxReal v) { mCore.wakeCounter = v; } void setWakeCounter(const PxReal v); PX_FORCE_INLINE PxReal getMaxLinearVelocity() const { return mCore.maxLinearVelocity; } void setMaxLinearVelocity(const PxReal max); PX_FORCE_INLINE PxReal getMaxAngularVelocity() const { return mCore.maxAngularVelocity; } void setMaxAngularVelocity(const PxReal max); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); //--------------------------------------------------------------------------------- // external reduced coordinate API //--------------------------------------------------------------------------------- void setArticulationFlags(PxArticulationFlags flags); PxArticulationFlags getArticulationFlags() const { return mCore.flags; } PxU32 getDofs() const; PxArticulationCache* createCache() const; PxU32 getCacheDataSize() const; void zeroCache(PxArticulationCache& cache) const; bool applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag)const; void copyInternalStateToCache (PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const; void packJointData(const PxReal* maximum, PxReal* reduced) const; void unpackJointData(const PxReal* reduced, PxReal* maximum) const; void commonInit() const; void computeGeneralizedGravityForce(PxArticulationCache& cache) const; void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const; void computeGeneralizedExternalForce(PxArticulationCache& cache) const; void computeJointAcceleration(PxArticulationCache& cache) const; void computeJointForce(PxArticulationCache& cache) const; void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const; void computeCoefficientMatrix(PxArticulationCache& cache) const; bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter) const; void computeGeneralizedMassMatrix(PxArticulationCache& cache) const; PxU32 getCoefficientMatrixSize() const; PxSpatialVelocity getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const; PxU32 getGpuArticulationIndex() const; void updateKinematic(PxArticulationKinematicFlags flags); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: PX_FORCE_INLINE void setSim(ArticulationSim* sim) { PX_ASSERT((sim==0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ArticulationSim* getSim() const { return mSim; } PX_FORCE_INLINE Dy::ArticulationCore& getCore() { return mCore; } static PX_FORCE_INLINE ArticulationCore& getArticulationCore(ArticulationCore& core) { const size_t offset = PX_OFFSET_OF(ArticulationCore, mCore); return *reinterpret_cast<ArticulationCore*>(reinterpret_cast<PxU8*>(&core) - offset); } PxNodeIndex getIslandNodeIndex() const; void setGlobalPose(); private: ArticulationSim* mSim; Dy::ArticulationCore mCore; }; } // namespace Sc } #endif
6,973
C
41.012048
176
0.637746
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScActorCore.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 SC_ACTOR_CORE_H #define SC_ACTOR_CORE_H #include "common/PxMetaData.h" #include "PxActor.h" namespace physx { namespace Sc { class ActorSim; class ActorCore { public: // PX_SERIALIZATION ActorCore(const PxEMPTY) : mSim(NULL), mActorFlags(PxEmpty) { } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ActorCore(PxActorType::Enum actorType, PxU8 actorFlags, PxClientID owner, PxDominanceGroup dominanceGroup); ~ActorCore(); PX_FORCE_INLINE ActorSim* getSim() const { return mSim; } PX_FORCE_INLINE void setSim(ActorSim* sim) { PX_ASSERT((sim==NULL) ^ (mSim==NULL)); mSim = sim; } PX_FORCE_INLINE PxActorFlags getActorFlags() const { return mActorFlags; } void setActorFlags(PxActorFlags af); PX_FORCE_INLINE PxDominanceGroup getDominanceGroup() const { return PxDominanceGroup(mDominanceGroup); } void setDominanceGroup(PxDominanceGroup g); PX_FORCE_INLINE void setOwnerClient(PxClientID inId) { const PxU32 aggid = mAggregateIDOwnerClient & 0x00ffffff; mAggregateIDOwnerClient = (PxU32(inId)<<24) | aggid; } PX_FORCE_INLINE PxClientID getOwnerClient() const { return mAggregateIDOwnerClient>>24; } PX_FORCE_INLINE PxActorType::Enum getActorCoreType() const { return PxActorType::Enum(mActorType); } void reinsertShapes(); PX_FORCE_INLINE void setAggregateID(PxU32 id) { PX_ASSERT(id==0xffffffff || id<(1<<24)); const PxU32 ownerClient = mAggregateIDOwnerClient & 0xff000000; mAggregateIDOwnerClient = (id & 0x00ffffff) | ownerClient; } PX_FORCE_INLINE PxU32 getAggregateID() const { const PxU32 id = mAggregateIDOwnerClient & 0x00ffffff; return id == 0x00ffffff ? PX_INVALID_U32 : id; } private: ActorSim* mSim; // PxU32 mAggregateIDOwnerClient; // PxClientID (8bit) | aggregate ID (24bit) // PT: TODO: the remaining members could be packed into just a 16bit mask PxActorFlags mActorFlags; // PxActor's flags (PxU8) => only 4 bits used PxU8 mActorType; // Actor type (8 bits, but 3 would be enough) PxU8 mDominanceGroup; // Dominance group (8 bits, but 5 would be enough because "must be < 32") }; #if PX_P64_FAMILY PX_COMPILE_TIME_ASSERT(sizeof(Sc::ActorCore)==16); #else PX_COMPILE_TIME_ASSERT(sizeof(Sc::ActorCore)==12); #endif } // namespace Sc } ////////////////////////////////////////////////////////////////////////// #endif
4,467
C
37.517241
118
0.666443
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScPhysics.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 SC_PHYSICS_H #define SC_PHYSICS_H #include "PxPhysics.h" #include "PxScene.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxBasicTemplates.h" #include "PxActor.h" namespace physx { class PxMaterial; class PxTolerancesScale; struct PxvOffsetTable; #if PX_SUPPORT_GPU_PHYSX class PxPhysXGpu; #endif namespace Sc { class Scene; class StaticCore; class RigidCore; class BodyCore; class ArticulationCore; class ArticulationJointCore; class ConstraintCore; class ShapeCore; struct OffsetTable { PX_FORCE_INLINE OffsetTable() {} PX_FORCE_INLINE PxShape* convertScShape2Px(ShapeCore* sc) const { return PxPointerOffset<PxShape*>(sc, scShape2Px); } PX_FORCE_INLINE const PxShape* convertScShape2Px(const ShapeCore* sc) const { return PxPointerOffset<const PxShape*>(sc, scShape2Px); } PX_FORCE_INLINE PxConstraint* convertScConstraint2Px(ConstraintCore* sc) const { return PxPointerOffset<PxConstraint*>(sc, scConstraint2Px); } PX_FORCE_INLINE const PxConstraint* convertScConstraint2Px(const ConstraintCore* sc) const { return PxPointerOffset<const PxConstraint*>(sc, scConstraint2Px); } PX_FORCE_INLINE PxArticulationReducedCoordinate* convertScArticulation2Px(ArticulationCore* sc) const { return PxPointerOffset<PxArticulationReducedCoordinate*>(sc, scArticulationRC2Px); } PX_FORCE_INLINE const PxArticulationReducedCoordinate* convertScArticulation2Px(const ArticulationCore* sc) const { return PxPointerOffset<const PxArticulationReducedCoordinate*>(sc, scArticulationRC2Px); } PX_FORCE_INLINE PxArticulationJointReducedCoordinate* convertScArticulationJoint2Px(ArticulationJointCore* sc) const { return PxPointerOffset<PxArticulationJointReducedCoordinate*>(sc, scArticulationJointRC2Px); } PX_FORCE_INLINE const PxArticulationJointReducedCoordinate* convertScArticulationJoint2Px(const ArticulationJointCore* sc) const { return PxPointerOffset<const PxArticulationJointReducedCoordinate*>(sc, scArticulationJointRC2Px); } ptrdiff_t scRigidStatic2PxActor; ptrdiff_t scRigidDynamic2PxActor; ptrdiff_t scArticulationLink2PxActor; ptrdiff_t scSoftBody2PxActor; ptrdiff_t scPBDParticleSystem2PxActor; ptrdiff_t scFLIPParticleSystem2PxActor; ptrdiff_t scMPMParticleSystem2PxActor; ptrdiff_t scHairSystem2PxActor; ptrdiff_t scShape2Px; ptrdiff_t scArticulationRC2Px; ptrdiff_t scArticulationJointRC2Px; ptrdiff_t scConstraint2Px; ptrdiff_t scCore2PxActor[PxActorType::eACTOR_COUNT]; }; extern OffsetTable gOffsetTable; class Physics : public PxUserAllocated { public: PX_FORCE_INLINE static Physics& getInstance() { return *mInstance; } Physics(const PxTolerancesScale&, const PxvOffsetTable& pxvOffsetTable); ~Physics(); PX_FORCE_INLINE const PxTolerancesScale& getTolerancesScale() const { return mScale; } private: PxTolerancesScale mScale; static Physics* mInstance; public: static const PxReal sWakeCounterOnCreation; }; } // namespace Sc } #endif
4,800
C
35.930769
167
0.770417
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScRigidCore.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 SC_RIGID_CORE_H #define SC_RIGID_CORE_H #include "ScActorCore.h" #include "ScPhysics.h" #include "PxvDynamics.h" #include "PxShape.h" namespace physx { namespace Sc { class RigidSim; class ShapeCore; struct ShapeChangeNotifyFlag { enum Enum { eGEOMETRY = 1<<0, eMATERIAL = 1<<1, eSHAPE2BODY = 1<<2, eFILTERDATA = 1<<3, eCONTACTOFFSET = 1<<4, eRESTOFFSET = 1<<5, eRESET_FILTERING = 1<<6 }; }; typedef PxFlags<ShapeChangeNotifyFlag::Enum, PxU32> ShapeChangeNotifyFlags; PX_FLAGS_OPERATORS(ShapeChangeNotifyFlag::Enum,PxU32) class RigidCore : public ActorCore { public: PX_FORCE_INLINE PxActor* getPxActor() const { return PxPointerOffset<PxActor*>(const_cast<RigidCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); } void addShapeToScene(ShapeCore& shape); void removeShapeFromScene(ShapeCore& shape, bool wakeOnLostTouch); void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags); void onShapeFlagsChange(ShapeCore& shape, PxShapeFlags oldShapeFlags); void unregisterShapeFromNphase(ShapeCore& shapeCore); void registerShapeInNphase(ShapeCore& shapeCore); RigidSim* getSim() const; PxU32 getRigidID() const; static void getBinaryMetaData(PxOutputStream& stream); protected: RigidCore(const PxEMPTY) : ActorCore(PxEmpty) {} RigidCore(PxActorType::Enum type); ~RigidCore(); }; } // namespace Sc } #endif
3,198
C
34.153846
121
0.73546
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationTendonCore.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_SCP_ARTICULATION_TENDON_CORE #define PX_PHYSICS_SCP_ARTICULATION_TENDON_CORE #include "DyArticulationTendon.h" namespace physx { namespace Sc { class ArticulationSpatialTendonSim; class ArticulationFixedTendonSim; class ArticulationTendonCore { public: // PX_SERIALIZATION ArticulationTendonCore(const PxEMPTY) {} void preExportDataReset() { } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationTendonCore() : mStiffness(0.f), mDamping(0.f), mOffset(0.f), mLimitStiffness(0.f) { } PxReal mStiffness; PxReal mDamping; PxReal mOffset; PxReal mLimitStiffness; }; class ArticulationSpatialTendonCore : public ArticulationTendonCore { public: // PX_SERIALIZATION ArticulationSpatialTendonCore(const PxEMPTY) : ArticulationTendonCore(PxEmpty), mSim(NULL) {} void preExportDataReset() { } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationSpatialTendonCore() : ArticulationTendonCore() { mSim = NULL; } ~ArticulationSpatialTendonCore() {} void setStiffness(const PxReal stiffness); PxReal getStiffness() const; void setDamping(const PxReal damping); PxReal getDamping() const; void setLimitStiffness(const PxReal stiffness); PxReal getLimitStiffness() const; void setOffset(const PxReal offset); PxReal getOffset() const; PX_FORCE_INLINE void setSim(ArticulationSpatialTendonSim* sim) { PX_ASSERT((sim == 0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ArticulationSpatialTendonSim* getSim() const { return mSim; } ArticulationSpatialTendonSim* mSim; }; class ArticulationFixedTendonCore : public ArticulationTendonCore { public: // PX_SERIALIZATION ArticulationFixedTendonCore(const PxEMPTY) : ArticulationTendonCore(PxEmpty), mSim(NULL) {} void preExportDataReset() {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationFixedTendonCore() : ArticulationTendonCore(), mLowLimit(PX_MAX_F32), mHighLimit(-PX_MAX_F32), mRestLength(0.f) { mSim = NULL; } ~ArticulationFixedTendonCore() {} void setStiffness(const PxReal stiffness); PxReal getStiffness() const; void setDamping(const PxReal damping); PxReal getDamping() const; void setLimitStiffness(const PxReal stiffness); PxReal getLimitStiffness() const; void setOffset(const PxReal offset); PxReal getOffset() const; void setSpringRestLength(const PxReal restLength); PxReal getSpringRestLength() const; void setLimitRange(const PxReal lowLimit, const PxReal highLimit); void getLimitRange(PxReal& lowLimit, PxReal& highLimit) const; PX_FORCE_INLINE void setSim(ArticulationFixedTendonSim* sim) { PX_ASSERT((sim == 0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ArticulationFixedTendonSim* getSim() const { return mSim; } PxReal mLowLimit; PxReal mHighLimit; PxReal mRestLength; ArticulationFixedTendonSim* mSim; }; }//namespace Sc } //namespace physx #endif
4,963
C
31.874172
124
0.717913
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScSqBoundsSync.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 SC_SQ_BOUNDS_SYNC_H #define SC_SQ_BOUNDS_SYNC_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxBitMap.h" #include "PxSceneQuerySystem.h" namespace physx { class PxBounds3; class PxRigidBody; class PxShape; typedef PxSQPrunerHandle ScPrunerHandle; namespace Sc { // PT: TODO: revisit the need for a virtual interface struct SqRefFinder { virtual ScPrunerHandle find(const PxRigidBody* body, const PxShape* shape, PxU32& prunerIndex) = 0; virtual ~SqRefFinder() {} }; // PT: TODO: revisit the need for a virtual interface struct SqBoundsSync { virtual void sync(PxU32 prunerIndex, const ScPrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0; virtual ~SqBoundsSync() {} }; } } #endif
2,536
C
37.439393
205
0.76183
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScShapeCore.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 SC_SHAPE_CORE_H #define SC_SHAPE_CORE_H #include "foundation/PxUtilities.h" #include "PxvGeometry.h" #include "PxFiltering.h" #include "PxShape.h" namespace physx { class PxShape; class PxsSimulationController; namespace Sc { class ShapeSim; class ShapeCore { public: // PX_SERIALIZATION ShapeCore(const PxEMPTY); void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void resolveMaterialReference(PxU32 materialTableIndex, PxU16 materialIndex); //~PX_SERIALIZATION ShapeCore(const PxGeometry& geometry, PxShapeFlags shapeFlags, const PxU16* materialIndices, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum softOrClothFlags = PxShapeCoreFlag::Enum(0)); ~ShapeCore(); PX_FORCE_INLINE PxGeometryType::Enum getGeometryType() const { return mCore.mGeometry.getType(); } PxShape* getPxShape(); const PxShape* getPxShape() const; PX_FORCE_INLINE const GeometryUnion& getGeometryUnion() const { return mCore.mGeometry; } PX_FORCE_INLINE const PxGeometry& getGeometry() const { return mCore.mGeometry.getGeometry(); } void setGeometry(const PxGeometry& geom); PxU16 getNbMaterialIndices() const; const PxU16* getMaterialIndices() const; void setMaterialIndices(const PxU16* materialIndices, PxU16 materialIndexCount); PX_FORCE_INLINE const PxTransform& getShape2Actor() const { return mCore.getTransform(); } PX_FORCE_INLINE void setShape2Actor(const PxTransform& s2b) { mCore.setTransform(s2b); } PX_FORCE_INLINE const PxFilterData& getSimulationFilterData() const { return mSimulationFilterData; } PX_FORCE_INLINE void setSimulationFilterData(const PxFilterData& data) { mSimulationFilterData = data; } PX_FORCE_INLINE PxReal getContactOffset() const { return mCore.mContactOffset; } void setContactOffset(PxReal offset); PX_FORCE_INLINE PxReal getRestOffset() const { return mCore.mRestOffset; } PX_FORCE_INLINE void setRestOffset(PxReal offset) { mCore.mRestOffset = offset; } PX_FORCE_INLINE PxReal getDensityForFluid() const { return mCore.getDensityForFluid(); } PX_FORCE_INLINE void setDensityForFluid(PxReal densityForFluid) { mCore.setDensityForFluid(densityForFluid); } PX_FORCE_INLINE PxReal getTorsionalPatchRadius() const { return mCore.mTorsionalRadius; } PX_FORCE_INLINE void setTorsionalPatchRadius(PxReal tpr) { mCore.mTorsionalRadius = tpr; } PX_FORCE_INLINE PxReal getMinTorsionalPatchRadius() const {return mCore.mMinTorsionalPatchRadius; } PX_FORCE_INLINE void setMinTorsionalPatchRadius(PxReal radius) { mCore.mMinTorsionalPatchRadius = radius; } PX_FORCE_INLINE PxShapeFlags getFlags() const { return PxShapeFlags(mCore.mShapeFlags); } PX_FORCE_INLINE void setFlags(PxShapeFlags f) { mCore.mShapeFlags = f; } PX_FORCE_INLINE const PxsShapeCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF(ShapeCore, mCore); } static PX_FORCE_INLINE ShapeCore& getCore(PxsShapeCore& core) { return *reinterpret_cast<ShapeCore*>(reinterpret_cast<PxU8*>(&core) - getCoreOffset()); } PX_FORCE_INLINE ShapeSim* getExclusiveSim() const { return mExclusiveSim; } PX_FORCE_INLINE void setExclusiveSim(ShapeSim* sim) { if (!sim || mCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eIS_EXCLUSIVE)) { mExclusiveSim = sim; } } PxU32 getInternalShapeIndex(PxsSimulationController& simulationController) const; #if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux protected: #endif PxFilterData mSimulationFilterData; // Simulation filter data PxsShapeCore PX_ALIGN(16, mCore); ShapeSim* mExclusiveSim; //only set if shape is exclusive #if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux public: #endif const char* mName; // PT: moved here from NpShape to fill padding bytes }; } // namespace Sc } #endif
6,269
C
43.785714
119
0.707609
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationJointCore.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 SC_ARTICULATION_JOINT_CORE_H #define SC_ARTICULATION_JOINT_CORE_H #include "foundation/PxTransform.h" #include "common/PxMetaData.h" #include "DyVArticulation.h" namespace physx { namespace Sc { class BodyCore; class ArticulationJointSim; class ArticulationCore; class ArticulationJointDesc { public: BodyCore* parent; BodyCore* child; PxTransform parentPose; PxTransform childPose; }; class ArticulationJointCore { public: // PX_SERIALIZATION ArticulationJointCore(const PxEMPTY) : mCore(PxEmpty), mSim(NULL) {} void preExportDataReset() { mCore.jointDirtyFlag = Dy::ArticulationJointCoreDirtyFlag::eALL; } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationJointCore(const PxTransform& parentFrame, const PxTransform& childFrame); ~ArticulationJointCore(); //Those methods are not allowed while the articulation are in the scene PX_FORCE_INLINE const PxTransform& getParentPose() const { return mCore.parentPose; } void setParentPose(const PxTransform&); PX_FORCE_INLINE const PxTransform& getChildPose() const { return mCore.childPose; } void setChildPose(const PxTransform&); //Those functions doesn't change the articulation configuration so the application is allowed to change those value in run-time PX_FORCE_INLINE PxArticulationLimit getLimit(PxArticulationAxis::Enum axis) const { return mCore.limits[axis]; } void setLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit); PX_FORCE_INLINE PxArticulationDrive getDrive(PxArticulationAxis::Enum axis) const { return mCore.drives[axis]; } void setDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive); void setTargetP(PxArticulationAxis::Enum axis, PxReal targetP); PX_FORCE_INLINE PxReal getTargetP(PxArticulationAxis::Enum axis) const { return mCore.targetP[axis]; } void setTargetV(PxArticulationAxis::Enum axis, PxReal targetV); PX_FORCE_INLINE PxReal getTargetV(PxArticulationAxis::Enum axis) const { return mCore.targetV[axis]; } void setArmature(PxArticulationAxis::Enum axis, PxReal armature); PX_FORCE_INLINE PxReal getArmature(PxArticulationAxis::Enum axis) const { return mCore.armature[axis]; } void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos); PxReal getJointPosition(PxArticulationAxis::Enum axis) const; void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel); PxReal getJointVelocity(PxArticulationAxis::Enum axis) const; // PT: TODO: don't we need to set ArticulationJointCoreDirtyFlag::eMOTION here? PX_FORCE_INLINE void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { mCore.motion[axis] = PxU8(motion); } PX_FORCE_INLINE PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const { return PxArticulationMotion::Enum(mCore.motion[axis]); } PX_FORCE_INLINE void setJointType(PxArticulationJointType::Enum type) { mCore.initJointType(type); } PX_FORCE_INLINE PxArticulationJointType::Enum getJointType() const { return PxArticulationJointType::Enum(mCore.jointType); } PX_FORCE_INLINE void setFrictionCoefficient(const PxReal coefficient) { mCore.initFrictionCoefficient(coefficient); } PX_FORCE_INLINE PxReal getFrictionCoefficient() const { return mCore.frictionCoefficient; } PX_FORCE_INLINE void setMaxJointVelocity(const PxReal maxJointV) { mCore.initMaxJointVelocity(maxJointV); } PX_FORCE_INLINE PxReal getMaxJointVelocity() const { return mCore.maxJointVelocity; } PX_FORCE_INLINE ArticulationJointSim* getSim() const { return mSim; } PX_FORCE_INLINE void setSim(ArticulationJointSim* sim) { PX_ASSERT((sim==0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE Dy::ArticulationJointCore& getCore() { return mCore; } PX_FORCE_INLINE void setArticulation(ArticulationCore* articulation) { mArticulation = articulation; } PX_FORCE_INLINE const ArticulationCore* getArticulation() const { return mArticulation; } PX_FORCE_INLINE void setRoot(PxArticulationJointReducedCoordinate* base) { mRootType = base; } PX_FORCE_INLINE PxArticulationJointReducedCoordinate* getRoot() const { return mRootType; } PX_FORCE_INLINE void setLLIndex(const PxU32 llLinkIndex) { mLLLinkIndex = llLinkIndex; } private: void setSimDirty(); PX_FORCE_INLINE void setDirty(Dy::ArticulationJointCoreDirtyFlag::Enum dirtyFlag) { mCore.jointDirtyFlag |= dirtyFlag; setSimDirty(); } Dy::ArticulationJointCore mCore; ArticulationJointSim* mSim; ArticulationCore* mArticulation; PxArticulationJointReducedCoordinate* mRootType; PxU32 mLLLinkIndex; #if PX_P64_FAMILY PxU32 pad; #endif }; } // namespace Sc } #endif
6,991
C
47.220689
158
0.710914
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationSensor.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 SC_ARTICULATION_SENSOR_CORE #define SC_ARTICULATION_SENSOR_CORE #include "foundation/PxVec3.h" #include "foundation/PxTransform.h" namespace physx { namespace Sc { class ArticulationCore; class ArticulationSensorSim; class ArticulationSensorCore { public: // PX_SERIALIZATION ArticulationSensorCore(const PxEMPTY) :mSim(NULL) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationSensorCore(){} PX_FORCE_INLINE void setSim(ArticulationSensorSim* sim) { PX_ASSERT((sim == 0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ArticulationSensorSim* getSim() const { return mSim; } ArticulationSensorSim* mSim; PxTransform mRelativePose; PxU16 mFlags; }; }//namespace Sc }//namespace physx #endif //SC_ARTICULATION_SENSOR_CORE
2,553
C
34.472222
75
0.744222
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScStaticCore.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 SC_STATIC_CORE_H #define SC_STATIC_CORE_H #include "ScRigidCore.h" #include "PxvDynamics.h" namespace physx { namespace Sc { class StaticSim; class StaticCore : public RigidCore { public: StaticCore(const PxTransform& actor2World): RigidCore(PxActorType::eRIGID_STATIC) { mCore.body2World = actor2World; mCore.mFlags = PxRigidBodyFlags(); } PX_FORCE_INLINE const PxTransform& getActor2World() const { return mCore.body2World; } void setActor2World(const PxTransform& actor2World); PX_FORCE_INLINE PxsRigidCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(StaticCore, mCore);} StaticCore(const PxEMPTY) : RigidCore(PxEmpty), mCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); StaticSim* getSim() const; PX_FORCE_INLINE void onOriginShift(const PxVec3& shift) { mCore.body2World.p -= shift; } private: PxsRigidCore mCore; }; } // namespace Sc } #endif
2,784
C
37.680555
96
0.727371
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScBodyCore.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 SC_BODY_CORE_H #define SC_BODY_CORE_H #include "foundation/PxTransform.h" #include "ScRigidCore.h" #include "PxRigidDynamic.h" #include "PxvDynamics.h" #include "PxvConfig.h" namespace physx { namespace Sc { class BodySim; class BodyCore : public RigidCore { public: // PX_SERIALIZATION BodyCore(const PxEMPTY) : RigidCore(PxEmpty), mCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); void restoreDynamicData(); //~PX_SERIALIZATION BodyCore(PxActorType::Enum type, const PxTransform& bodyPose); ~BodyCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PX_FORCE_INLINE const PxTransform& getBody2World() const { return mCore.body2World; } void setBody2World(const PxTransform& p); void setCMassLocalPose(const PxTransform& body2Actor); PX_FORCE_INLINE const PxVec3& getLinearVelocity() const { return mCore.linearVelocity; } void setLinearVelocity(const PxVec3& v, bool skipBodySimUpdate=false); PX_FORCE_INLINE const PxVec3& getAngularVelocity() const { return mCore.angularVelocity; } void setAngularVelocity(const PxVec3& v, bool skipBodySimUpdate=false); PX_FORCE_INLINE PxReal getCfmScale() const { return mCore.cfmScale; } void setCfmScale(PxReal d); PX_FORCE_INLINE void updateVelocities(const PxVec3& linearVelModPerStep, const PxVec3& angularVelModPerStep) { mCore.linearVelocity += linearVelModPerStep; mCore.angularVelocity += angularVelModPerStep; } PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return mCore.getBody2Actor(); } void setBody2Actor(const PxTransform& p); void addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc); void setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc); void clearSpatialAcceleration(bool force, bool torque); void addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta); void clearSpatialVelocity(bool force, bool torque); PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; } PX_FORCE_INLINE void setMaxPenetrationBias(PxReal p) { mCore.maxPenBias = p; } PxReal getInverseMass() const; void setInverseMass(PxReal m); const PxVec3& getInverseInertia() const; void setInverseInertia(const PxVec3& i); PxReal getLinearDamping() const; void setLinearDamping(PxReal d); PxReal getAngularDamping() const; void setAngularDamping(PxReal d); PX_FORCE_INLINE PxRigidBodyFlags getFlags() const { return mCore.mFlags; } void setFlags(PxRigidBodyFlags f); PX_FORCE_INLINE PxRigidDynamicLockFlags getRigidDynamicLockFlags() const { return mCore.lockFlags; } PX_FORCE_INLINE void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) { mCore.lockFlags = flags; } PX_FORCE_INLINE PxReal getSleepThreshold() const { return mCore.sleepThreshold; } void setSleepThreshold(PxReal t); PX_FORCE_INLINE PxReal getFreezeThreshold() const { return mCore.freezeThreshold; } void setFreezeThreshold(PxReal t); PX_FORCE_INLINE PxReal getMaxContactImpulse() const { return mCore.maxContactImpulse; } void setMaxContactImpulse(PxReal m); PX_FORCE_INLINE PxReal getOffsetSlop() const { return mCore.offsetSlop; } void setOffsetSlop(PxReal slop); PxNodeIndex getInternalIslandNodeIndex() const; PX_FORCE_INLINE PxReal getWakeCounter() const { return mCore.wakeCounter; } void setWakeCounter(PxReal wakeCounter, bool forceWakeUp=false); bool isSleeping() const; PX_FORCE_INLINE void wakeUp(PxReal wakeCounter) { setWakeCounter(wakeCounter, true); } void putToSleep(); PxReal getMaxAngVelSq() const; void setMaxAngVelSq(PxReal v); PxReal getMaxLinVelSq() const; void setMaxLinVelSq(PxReal v); PX_FORCE_INLINE PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } void setSolverIterationCounts(PxU16 c); bool getKinematicTarget(PxTransform& p) const; bool getHasValidKinematicTarget() const; void setKinematicTarget(const PxTransform& p, PxReal wakeCounter); void invalidateKinematicTarget(); PX_FORCE_INLINE PxReal getContactReportThreshold() const { return mCore.contactReportThreshold; } void setContactReportThreshold(PxReal t) { mCore.contactReportThreshold = t; } void onOriginShift(const PxVec3& shift); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- PX_FORCE_INLINE void setLinearVelocityInternal(const PxVec3& v) { mCore.linearVelocity = v; } PX_FORCE_INLINE void setAngularVelocityInternal(const PxVec3& v) { mCore.angularVelocity = v; } PX_FORCE_INLINE void setWakeCounterFromSim(PxReal c) { mCore.wakeCounter = c; } BodySim* getSim() const; PX_FORCE_INLINE PxsBodyCore& getCore() { return mCore; } PX_FORCE_INLINE const PxsBodyCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(BodyCore, mCore); } PX_FORCE_INLINE PxReal getCCDAdvanceCoefficient() const { return mCore.ccdAdvanceCoefficient; } PX_FORCE_INLINE void setCCDAdvanceCoefficient(PxReal c) { mCore.ccdAdvanceCoefficient = c; } void onRemoveKinematicFromScene(); PxIntBool isFrozen() const; static PX_FORCE_INLINE BodyCore& getCore(PxsBodyCore& core) { return *reinterpret_cast<BodyCore*>(reinterpret_cast<PxU8*>(&core) - getCoreOffset()); } void setFixedBaseLink(bool value); private: PX_ALIGN_PREFIX(16) PxsBodyCore mCore PX_ALIGN_SUFFIX(16); }; } // namespace Sc } #endif
7,887
C
41.637838
113
0.684037
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScSoftBodyCore.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 SC_SOFT_BODY_CORE_H #define SC_SOFT_BODY_CORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxSoftBody.h" #include "DySoftBodyCore.h" #include "foundation/PxAssert.h" #include "ScActorCore.h" #include "ScShapeCore.h" #include "PxFiltering.h" #include "ScRigidCore.h" //KS - needed for ShapeChangeNotifyFlags. Move to a shared header namespace physx { namespace Sc { class SoftBodySim; class BodyCore; class FEMClothCore; class ParticleSystemCore; class SoftBodyCore : public ActorCore { // PX_SERIALIZATION public: SoftBodyCore(const PxEMPTY) : ActorCore(PxEmpty){} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION SoftBodyCore(); ~SoftBodyCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- void setMaterial(const PxU16 handle); void clearMaterials(); PxFEMParameters getParameter() const; void setParameter(const PxFEMParameters paramters); PxReal getSleepThreshold() const; void setSleepThreshold(const PxReal v); PxReal getFreezeThreshold() const; void setFreezeThreshold(const PxReal v); PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxReal getWakeCounter() const; void setWakeCounter(const PxReal v); void setWakeCounterInternal(const PxReal v); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); PxActor* getPxActor() const; void attachShapeCore(ShapeCore* shapeCore); void attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState); void addParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId); void removeParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId); PxU32 addParticleAttachment(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric); void removeParticleAttachment(Sc::ParticleSystemCore* core, PxU32 handle); void addRigidFilter(Sc::BodyCore* core, PxU32 vertId); void removeRigidFilter(Sc::BodyCore* core, PxU32 vertId); PxU32 addRigidAttachment(Sc::BodyCore* core, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void removeRigidAttachment(Sc::BodyCore* core, PxU32 handle); void addTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx); void removeTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx); PxU32 addTetRigidAttachment(Sc::BodyCore* core, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); void addSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1); void removeSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1); void addSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); void removeSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); PxU32 addSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset); void removeSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 handle); void addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx); void removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx); void addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx); void removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx); PxU32 addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset); void removeClothAttachment(Sc::FEMClothCore& core, PxU32 handle); PxU32 getGpuSoftBodyIndex() const; void setKinematicTargets(const PxVec4* positions, PxSoftBodyFlags flags); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: SoftBodySim* getSim() const; PX_FORCE_INLINE const Dy::SoftBodyCore& getCore() const { return mCore; } PX_FORCE_INLINE Dy::SoftBodyCore& getCore() { return mCore; } void setSimulationFilterData(const PxFilterData& data); PxFilterData getSimulationFilterData() const; PxSoftBodyFlags getFlags() const { return mCore.mFlags; } void setFlags(PxSoftBodyFlags flags); PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; } PX_FORCE_INLINE void setMaxPenetrationBias(PxReal p) { mCore.maxPenBias = p; } PX_FORCE_INLINE PxU64& getGpuMemStat() { return mGpuMemStat; } void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags); private: Dy::SoftBodyCore mCore; PxFilterData mFilterData; PxU64 mGpuMemStat; }; } // namespace Sc } #endif #endif
7,290
C
41.389535
151
0.697257
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScIterators.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 SC_ITERATORS_H #define SC_ITERATORS_H #include "foundation/PxVec3.h" #include "PxContact.h" namespace physx { class PxShape; class PxsContactManagerOutputIterator; namespace Sc { class ShapeSimBase; class ElementSimInteraction; class ActorSim; struct Contact { Contact() : normal(0.0f) , point(0.0f) , separation(0.0f) , normalForce(0.0f) {} PxVec3 normal; PxVec3 point; PxShape* shape0; PxShape* shape1; PxReal separation; PxReal normalForce; PxU32 faceIndex0; // these are the external indices PxU32 faceIndex1; bool normalForceAvailable; }; class ContactIterator { public: class Pair { public: Pair() : mIter(NULL, NULL, NULL, 0, 0) {} Pair(const void*& contactPatches, const void*& contactPoints, const PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches, ShapeSimBase& shape0, ShapeSimBase& shape1, ActorSim* actor0, ActorSim* actor1); Contact* getNextContact(); PxActor* getActor0() { return mActor0; } PxActor* getActor1() { return mActor1; } private: PxU32 mIndex; PxU32 mNumContacts; PxContactStreamIterator mIter; const PxReal* mForces; Contact mCurrentContact; PxActor* mActor0; PxActor* mActor1; }; ContactIterator() {} explicit ContactIterator(ElementSimInteraction** first, ElementSimInteraction** last, PxsContactManagerOutputIterator& outputs): mCurrent(first), mLast(last), mOffset(0), mOutputs(&outputs) { if ((!first) || (!last) || (first == last)) { mCurrent = NULL; mLast = NULL; } } Pair* getNextPair(); private: ElementSimInteraction** mCurrent; ElementSimInteraction** mLast; Pair mCurrentPair; PxU32 mOffset; PxsContactManagerOutputIterator* mOutputs; private: }; } // namespace Sc } #endif
3,590
C
30.5
239
0.716713
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScParticleSystemCore.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 SC_PARTICLESYSTEM_CORE_H #define SC_PARTICLESYSTEM_CORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxParticleSystem.h" #include "foundation/PxAssert.h" #include "ScActorCore.h" #include "ScShapeCore.h" #include "PxFiltering.h" #include "DyParticleSystem.h" #include "ScParticleSystemShapeCore.h" namespace physx { namespace Sc { class ParticleSystemSim; class BodyCore; class ParticleSystemCore : public ActorCore { // PX_SERIALIZATION public: ParticleSystemCore(const PxEMPTY) : ActorCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ParticleSystemCore(PxActorType::Enum actorType); ~ParticleSystemCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- PxReal getSleepThreshold() const; void setSleepThreshold(const PxReal v); PxReal getRestOffset() const; void setRestOffset(const PxReal v); PxReal getContactOffset() const; void setContactOffset(const PxReal v); PxReal getParticleContactOffset() const; void setParticleContactOffset(const PxReal v); PxReal getSolidRestOffset() const; void setSolidRestOffset(const PxReal v); PxReal getFluidRestOffset() const; void setFluidRestOffset(const PxReal v); PxReal getMaxDepenetrationVelocity() const; void setMaxDepenetrationVelocity(const PxReal v); PxReal getMaxVelocity() const; void setMaxVelocity(const PxReal v); PxParticleSystemCallback* getParticleSystemCallback() const; void setParticleSystemCallback(PxParticleSystemCallback* callback); PxReal getFluidBoundaryDensityScale() const; void setFluidBoundaryDensityScale(const PxReal v); PxU32 getGridSizeX() const; void setGridSizeX(const PxU32 v); PxU32 getGridSizeY() const; void setGridSizeY(const PxU32 v); PxU32 getGridSizeZ() const; void setGridSizeZ(const PxU32 v); PxU16 getSolverIterationCounts() const { return mShapeCore.getLLCore().solverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxReal getWakeCounter() const; void setWakeCounter(const PxReal v); void setWakeCounterInternal(const PxReal v); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); PxActor* getPxActor() const; // TOFIX void enableCCD(const bool enable); PxParticleFlags getFlags() const { return mShapeCore.getLLCore().mFlags; } //void setFlags(PxParticleFlags flags) { mShapeCore.getLLCore().mFlags = flags; } void setFlags(PxParticleFlags flags); void setWind(const PxVec3& wind) {mShapeCore.getLLCore().mWind = wind;} PxVec3 getWind() const { return mShapeCore.getLLCore().mWind; } void setSolverType(const PxParticleSolverType::Enum solverType) { mShapeCore.getLLCore().solverType = solverType; } PxParticleSolverType::Enum getSolverType() const { return mShapeCore.getLLCore().solverType; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxSparseGridParams getSparseGridParams() const { return mShapeCore.getLLCore().sparseGridParams; } void setSparseGridParams(const PxSparseGridParams& params) { mShapeCore.getLLCore().sparseGridParams = params; } PxFLIPParams getFLIPParams() const { return mShapeCore.getLLCore().flipParams; } void setFLIPParams(const PxFLIPParams& params) { mShapeCore.getLLCore().flipParams = params; } PxMPMParams getMPMParams() const { return mShapeCore.getLLCore().mpmParams; } void setMPMParams(const PxMPMParams& params) { mShapeCore.getLLCore().mpmParams = params; } #endif void addRigidAttachment(Sc::BodyCore* core); void removeRigidAttachment(Sc::BodyCore* core); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: ParticleSystemSim* getSim() const; PX_FORCE_INLINE const ParticleSystemShapeCore& getShapeCore() const { return mShapeCore; } PX_FORCE_INLINE ParticleSystemShapeCore& getShapeCore() { return mShapeCore; } void setDirty(const bool dirty); private: //ParticleSystemSim* mSim; ParticleSystemShapeCore mShapeCore; }; } // namespace Sc } #endif #endif
6,305
C
36.987952
123
0.686439
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScConstraintCore.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 SC_CONSTRAINT_CORE_H #define SC_CONSTRAINT_CORE_H #include "PxConstraint.h" namespace physx { namespace Sc { class ConstraintSim; class RigidCore; class ConstraintCore { public: // PX_SERIALIZATION ConstraintCore(const PxEMPTY) : mFlags(PxEmpty), mConnector(NULL), mSim(NULL) {} PX_FORCE_INLINE void setConstraintFunctions(PxConstraintConnector& n, const PxConstraintShaderTable& shaders) { mConnector = &n; mSolverPrep = shaders.solverPrep; mVisualize = shaders.visualize; } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ConstraintCore(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize); ~ConstraintCore() {} void setBodies(RigidCore* r0v, RigidCore* r1v); PxConstraint* getPxConstraint(); const PxConstraint* getPxConstraint() const; PX_FORCE_INLINE PxConstraintConnector* getPxConnector() const { return mConnector; } PX_FORCE_INLINE PxConstraintFlags getFlags() const { return mFlags; } void setFlags(PxConstraintFlags flags); void getForce(PxVec3& force, PxVec3& torque) const; void setBreakForce(PxReal linear, PxReal angular); PX_FORCE_INLINE void getBreakForce(PxReal& linear, PxReal& angular) const { linear = mLinearBreakForce; angular = mAngularBreakForce; } void setMinResponseThreshold(PxReal threshold); PX_FORCE_INLINE PxReal getMinResponseThreshold() const { return mMinResponseThreshold; } void breakApart(); PX_FORCE_INLINE PxConstraintVisualize getVisualize() const { return mVisualize; } PX_FORCE_INLINE PxConstraintSolverPrep getSolverPrep() const { return mSolverPrep; } PX_FORCE_INLINE PxU32 getConstantBlockSize() const { return mDataSize; } PX_FORCE_INLINE void setSim(ConstraintSim* sim) { PX_ASSERT((sim==0) ^ (mSim == 0)); mSim = sim; } PX_FORCE_INLINE ConstraintSim* getSim() const { return mSim; } PX_FORCE_INLINE bool isDirty() const { return mIsDirty ? true : false; } PX_FORCE_INLINE void setDirty() { mIsDirty = 1; } PX_FORCE_INLINE void clearDirty() { mIsDirty = 0; } private: PxConstraintFlags mFlags; //In order to support O(1) insert/remove mIsDirty really wants to be an index into NpScene's dirty joint array PxU8 mIsDirty; PxU8 mPadding; PxVec3 mAppliedForce; PxVec3 mAppliedTorque; PxConstraintConnector* mConnector; PxConstraintSolverPrep mSolverPrep; PxConstraintVisualize mVisualize; PxU32 mDataSize; PxReal mLinearBreakForce; PxReal mAngularBreakForce; PxReal mMinResponseThreshold; ConstraintSim* mSim; }; } // namespace Sc } #endif
4,717
C
38.316666
116
0.690269
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationTendonJointCore.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 SC_TENDON_JOINT_CORE_H #define SC_TENDON_JOINT_CORE_H #include "foundation/PxVec3.h" #include "solver/PxSolverDefs.h" namespace physx { namespace Sc { class ArticulationFixedTendonSim; class ArticulationTendonJointCore { public: // PX_SERIALIZATION ArticulationTendonJointCore(const PxEMPTY) : mTendonSim(NULL) {} void preExportDataReset() { } static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION ArticulationTendonJointCore() { coefficient = PX_MAX_F32; recipCoefficient = PX_MAX_F32; } PX_FORCE_INLINE PxArticulationAxis::Enum getAxis() { return axis; } PX_FORCE_INLINE void getCoefficient(PxArticulationAxis::Enum& axis_, PxReal& coefficient_, PxReal& recipCoefficient_) const { axis_ = axis; coefficient_ = coefficient; recipCoefficient_ = recipCoefficient; } void setCoefficient(PxArticulationAxis::Enum axis_, const PxReal coefficient_, const PxReal recipCoefficient_); PxArticulationAxis::Enum axis; PxReal coefficient; PxReal recipCoefficient; PxU32 mLLLinkIndex; ArticulationTendonJointCore* mParent; PxU32 mLLTendonJointIndex; Sc::ArticulationFixedTendonSim* mTendonSim; }; }//namespace Sc }//namespace physx #endif
3,001
C
34.317647
126
0.743419
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScHairSystemCore.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 SC_HAIR_SYSTEM_CORE_H #define SC_HAIR_SYSTEM_CORE_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "ScActorCore.h" #include "ScHairSystemShapeCore.h" #include "DyHairSystem.h" namespace physx { namespace Sc { class HairSystemSim; class BodySim; class SoftBodySim; class HairSystemCore : public ActorCore { // PX_SERIALIZATION public: HairSystemCore(const PxEMPTY) : ActorCore(PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION HairSystemCore(); ~HairSystemCore(); //--------------------------------------------------------------------------------- // External API //--------------------------------------------------------------------------------- void setMaterial(const PxU16 handle); void clearMaterials(); PxReal getContactOffset() const; void setContactOffset(PxReal v); PxReal getSleepThreshold() const { return mShapeCore.getLLCore().mSleepThreshold; } void setSleepThreshold(const PxReal v); PxU16 getSolverIterationCounts() const { return mShapeCore.getLLCore().mSolverIterationCounts; } void setSolverIterationCounts(PxU16 c); PxReal getWakeCounter() const { return mShapeCore.getLLCore().mWakeCounter; } void setWakeCounter(const PxReal v); bool isSleeping() const; void wakeUp(PxReal wakeCounter); void putToSleep(); PxActor* getPxActor() const; void addAttachment(const BodySim& bodySim); void removeAttachment(const BodySim& bodySim); void addAttachment(const SoftBodySim& sbSim); void removeAttachment(const SoftBodySim& sbSim); //--------------------------------------------------------------------------------- // Internal API //--------------------------------------------------------------------------------- public: HairSystemSim* getSim() const; PX_FORCE_INLINE const HairSystemShapeCore& getShapeCore() const { return mShapeCore; } PX_FORCE_INLINE HairSystemShapeCore& getShapeCore() { return mShapeCore; } PxHairSystemFlags getFlags() const { return PxHairSystemFlags(mShapeCore.getLLCore().mParams.mFlags); } void setFlags(PxHairSystemFlags flags); private: HairSystemShapeCore mShapeCore; }; } // namespace Sc } // namespace physx #endif #endif
3,762
C
34.838095
104
0.702818
NVIDIA-Omniverse/PhysX/physx/source/fastxml/src/PsFastXml.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/PxMemory.h" #include "foundation/PxFoundationConfig.h" #include "foundation/PxAllocator.h" #include "PsFastXml.h" #include <stdio.h> #include <string.h> #include <new> #include <ctype.h> using namespace physx; namespace { #define MIN_CLOSE_COUNT 2 #define DEFAULT_READ_BUFFER_SIZE (16 * 1024) #define NUM_ENTITY 5 struct Entity { const char* str; unsigned int strLength; char chr; }; static const Entity entity[NUM_ENTITY] = { { "&lt;", 4, '<' }, { "&amp;", 5, '&' }, { "&gt;", 4, '>' }, { "&quot;", 6, '\"' }, { "&apos;", 6, '\'' } }; class MyFastXml : public physx::shdfnd::FastXml { public: enum CharType { CT_DATA, CT_EOF, CT_SOFT, CT_END_OF_ELEMENT, // either a forward slash or a greater than symbol CT_END_OF_LINE }; MyFastXml(Callback* c) { mStreamFromMemory = true; mCallback = c; memset(mTypes, CT_DATA, sizeof(mTypes)); mTypes[0] = CT_EOF; mTypes[uint8_t(' ')] = mTypes[uint8_t('\t')] = CT_SOFT; mTypes[uint8_t('/')] = mTypes[uint8_t('>')] = mTypes[uint8_t('?')] = CT_END_OF_ELEMENT; mTypes[uint8_t('\n')] = mTypes[uint8_t('\r')] = CT_END_OF_LINE; mError = 0; mStackIndex = 0; mFileBuf = NULL; mReadBufferEnd = NULL; mReadBuffer = NULL; mReadBufferSize = DEFAULT_READ_BUFFER_SIZE; mOpenCount = 0; mLastReadLoc = 0; for(uint32_t i = 0; i < (MAX_STACK + 1); i++) { mStack[i] = NULL; mStackAllocated[i] = false; } } char* processClose(char c, const char* element, char* scan, int32_t argc, const char** argv, FastXml::Callback* iface, bool& isError) { AttributePairs attr(argc, argv); if(c == '/' || c == '?') { char* slash = const_cast<char*>(static_cast<const char*>(strchr(element, c))); if(slash) *slash = 0; if(c == '?' && strcmp(element, "xml") == 0) { isError = true; if(!iface->processXmlDeclaration(attr, 0, mLineNo)) return NULL; } else { if(!iface->processElement(element, 0, attr, mLineNo)) { isError = true; mError = "User aborted the parsing process"; return NULL; } pushElement(element); const char* close = popElement(); if(!iface->processClose(close, mStackIndex, isError)) { return NULL; } } if(!slash) ++scan; } else { scan = skipNextData(scan); char* data = scan; // this is the data portion of the element, only copies memory if we encounter line feeds char* dest_data = 0; while(*scan && *scan != '<') { if(getCharType(scan) == CT_END_OF_LINE) { if(*scan == '\r') mLineNo++; dest_data = scan; *dest_data++ = ' '; // replace the linefeed with a space... scan = skipNextData(scan); while(*scan && *scan != '<') { if(getCharType(scan) == CT_END_OF_LINE) { if(*scan == '\r') mLineNo++; *dest_data++ = ' '; // replace the linefeed with a space... scan = skipNextData(scan); } else { *dest_data++ = *scan++; } } break; } else if('&' == *scan) { dest_data = scan; while(*scan && *scan != '<') { if('&' == *scan) { if(*(scan + 1) && *(scan + 1) == '#' && *(scan + 2)) { if(*(scan + 2) == 'x') { // Hexadecimal. if(!*(scan + 3)) break; char* q = scan + 3; q = strchr(q, ';'); if(!q || !*q) PX_ASSERT(0); --q; char ch = char(*q > '9' ? (tolower(*q) - 'a' + 10) : *q - '0'); if(*(--q) != tolower('x')) ch |= char(*q > '9' ? (tolower(*q) - 'a' + 10) : *q - '0') << 4; *dest_data++ = ch; } else { // Decimal. if(!*(scan + 2)) break; const char* q = scan + 2; q = strchr(q, ';'); if(!q || !*q) PX_ASSERT(0); --q; char ch = *q - '0'; if(*(--q) != '#') ch |= (*q - '0') * 10; *dest_data++ = ch; } char* start = scan; char* end = strchr(start, ';'); if(end) { *end = 0; scan = end + 1; } continue; } for(int i = 0; i < NUM_ENTITY; ++i) { if(strncmp(entity[i].str, scan, entity[i].strLength) == 0) { *dest_data++ = entity[i].chr; scan += entity[i].strLength; break; } } } else { *dest_data++ = *scan++; } } break; } else ++scan; } if(*scan == '<') { if(scan[1] != '/') { PX_ASSERT(mOpenCount > 0); mOpenCount--; } if(dest_data) { *dest_data = 0; } else { *scan = 0; } scan++; // skip it.. if(*data == 0) data = 0; if(!iface->processElement(element, data, attr, mLineNo)) { isError = true; mError = "User aborted the parsing process"; return NULL; } pushElement(element); // check for the comment use case... if(scan[0] == '!' && scan[1] == '-' && scan[2] == '-') { scan += 3; while(*scan && *scan == ' ') ++scan; char* comment = scan; char* comment_end = strstr(scan, "-->"); if(comment_end) { *comment_end = 0; scan = comment_end + 3; if(!iface->processComment(comment)) { isError = true; mError = "User aborted the parsing process"; return NULL; } } } else if(*scan == '/') { scan = processClose(scan, iface, isError); if(scan == NULL) { return NULL; } } } else { isError = true; mError = "Data portion of an element wasn't terminated properly"; return NULL; } } if(mOpenCount < MIN_CLOSE_COUNT) { scan = readData(scan); } return scan; } char* processClose(char* scan, FastXml::Callback* iface, bool& isError) { const char* start = popElement(), *close = start; if(scan[1] != '>') { scan++; close = scan; while(*scan && *scan != '>') scan++; *scan = 0; } if(0 != strcmp(start, close)) { isError = true; mError = "Open and closing tags do not match"; return 0; } if(!iface->processClose(close, mStackIndex, isError)) { // we need to set the read pointer! uint32_t offset = uint32_t(mReadBufferEnd - scan) - 1; uint32_t readLoc = mLastReadLoc - offset; mFileBuf->seek(readLoc); return NULL; } ++scan; return scan; } virtual bool processXml(physx::PxInputData& fileBuf, bool streamFromMemory) { releaseMemory(); mFileBuf = &fileBuf; mStreamFromMemory = streamFromMemory; return processXml(mCallback); } // if we have finished processing the data we had pending.. char* readData(char* scan) { for(uint32_t i = 0; i < (mStackIndex + 1); i++) { if(!mStackAllocated[i]) { const char* text = mStack[i]; if(text) { uint32_t tlen = uint32_t(strlen(text)); mStack[i] = static_cast<const char*>(mCallback->allocate(tlen + 1)); PxMemCopy(const_cast<void*>(static_cast<const void*>(mStack[i])), text, tlen + 1); mStackAllocated[i] = true; } } } if(!mStreamFromMemory) { if(scan == NULL) { uint32_t seekLoc = mFileBuf->tell(); mReadBufferSize = (mFileBuf->getLength() - seekLoc); } else { return scan; } } if(mReadBuffer == NULL) { mReadBuffer = static_cast<char*>(mCallback->allocate(mReadBufferSize + 1)); } uint32_t offset = 0; uint32_t readLen = mReadBufferSize; if(scan) { offset = uint32_t(scan - mReadBuffer); uint32_t copyLen = mReadBufferSize - offset; if(copyLen) { PX_ASSERT(scan >= mReadBuffer); memmove(mReadBuffer, scan, copyLen); mReadBuffer[copyLen] = 0; readLen = mReadBufferSize - copyLen; } offset = copyLen; } uint32_t readCount = mFileBuf->read(&mReadBuffer[offset], readLen); while(readCount > 0) { mReadBuffer[readCount + offset] = 0; // end of string terminator... mReadBufferEnd = &mReadBuffer[readCount + offset]; const char* scan_ = &mReadBuffer[offset]; while(*scan_) { if(*scan_ == '<' && scan_[1] != '/') { mOpenCount++; } scan_++; } if(mOpenCount < MIN_CLOSE_COUNT) { uint32_t oldSize = uint32_t(mReadBufferEnd - mReadBuffer); mReadBufferSize = mReadBufferSize * 2; char* oldReadBuffer = mReadBuffer; mReadBuffer = static_cast<char*>(mCallback->allocate(mReadBufferSize + 1)); PxMemCopy(mReadBuffer, oldReadBuffer, oldSize); mCallback->deallocate(oldReadBuffer); offset = oldSize; uint32_t readSize = mReadBufferSize - oldSize; readCount = mFileBuf->read(&mReadBuffer[offset], readSize); if(readCount == 0) break; } else { break; } } mLastReadLoc = mFileBuf->tell(); return mReadBuffer; } bool processXml(FastXml::Callback* iface) { bool ret = true; const int MAX_ATTRIBUTE = 2048; // can't imagine having more than 2,048 attributes in a single element right? mLineNo = 1; char* element, *scan = readData(0); while(*scan) { scan = skipNextData(scan); if(*scan == 0) break; if(*scan == '<') { if(scan[1] != '/') { PX_ASSERT(mOpenCount > 0); mOpenCount--; } scan++; if(*scan == '?') // Allow xml declarations { scan++; } else if(scan[0] == '!' && scan[1] == '-' && scan[2] == '-') { scan += 3; while(*scan && *scan == ' ') scan++; char* comment = scan, *comment_end = strstr(scan, "-->"); if(comment_end) { *comment_end = 0; scan = comment_end + 3; if(!iface->processComment(comment)) { mError = "User aborted the parsing process"; return false; } } continue; } else if(scan[0] == '!') // Allow doctype { scan++; // DOCTYPE syntax differs from usual XML so we parse it here // Read DOCTYPE const char* tag = "DOCTYPE"; if(!strstr(scan, tag)) { mError = "Invalid DOCTYPE"; return false; } scan += strlen(tag); // Skip whites while(CT_SOFT == getCharType(scan)) ++scan; // Read rootElement const char* rootElement = scan; while(CT_DATA == getCharType(scan)) ++scan; char* endRootElement = scan; // TODO: read remaining fields (fpi, uri, etc.) while(CT_END_OF_ELEMENT != getCharType(scan++)) ; *endRootElement = 0; if(!iface->processDoctype(rootElement, 0, 0, 0)) { mError = "User aborted the parsing process"; return false; } continue; // Restart loop } } if(*scan == '/') { bool isError = false; scan = processClose(scan, iface, isError); if(!scan) { if(isError) { mError = "User aborted the parsing process"; } return !isError; } } else { if(*scan == '?') scan++; element = scan; int32_t argc = 0; const char* argv[MAX_ATTRIBUTE]; bool close; scan = nextSoftOrClose(scan, close); if(close) { char c = *(scan - 1); if(c != '?' && c != '/') { c = '>'; } *scan++ = 0; bool isError = false; scan = processClose(c, element, scan, argc, argv, iface, isError); if(!scan) { if(isError) { mError = "User aborted the parsing process"; } return !isError; } } else { if(*scan == 0) { return ret; } *scan = 0; // place a zero byte to indicate the end of the element name... scan++; while(*scan) { scan = skipNextData(scan); // advance past any soft seperators (tab or space) if(getCharType(scan) == CT_END_OF_ELEMENT) { char c = *scan++; if('?' == c) { if('>' != *scan) //?> { PX_ASSERT(0); return false; } scan++; } bool isError = false; scan = processClose(c, element, scan, argc, argv, iface, isError); if(!scan) { if(isError) { mError = "User aborted the parsing process"; } return !isError; } break; } else { if(argc >= MAX_ATTRIBUTE) { mError = "encountered too many attributes"; return false; } argv[argc] = scan; scan = nextSep(scan); // scan up to a space, or an equal if(*scan) { if(*scan != '=') { *scan = 0; scan++; while(*scan && *scan != '=') scan++; if(*scan == '=') scan++; } else { *scan = 0; scan++; } if(*scan) // if not eof... { scan = skipNextData(scan); if(*scan == '"') { scan++; argc++; argv[argc] = scan; argc++; while(*scan && *scan != 34) scan++; if(*scan == '"') { *scan = 0; scan++; } else { mError = "Failed to find closing quote for attribute"; return false; } } else { // mError = "Expected quote to begin attribute"; // return false; // PH: let's try to have a more graceful fallback argc--; while(*scan != '/' && *scan != '>' && *scan != 0) scan++; } } } // if( *scan ) } // if ( mTypes[*scan] } // if( close ) } // if( *scan == '/' } // while( *scan ) } if(mStackIndex) { mError = "Invalid file format"; return false; } return ret; } const char* getError(int32_t& lineno) { const char* ret = mError; lineno = mLineNo; mError = 0; return ret; } virtual void release(void) { Callback* c = mCallback; // get the user allocator interface MyFastXml* f = this; // cast the this pointer f->~MyFastXml(); // explicitely invoke the destructor for this class c->deallocate(f); // now free up the memory associated with it. } private: virtual ~MyFastXml(void) { releaseMemory(); } PX_INLINE void releaseMemory(void) { mFileBuf = NULL; mCallback->deallocate(mReadBuffer); mReadBuffer = NULL; mStackIndex = 0; mReadBufferEnd = NULL; mOpenCount = 0; mLastReadLoc = 0; mError = NULL; for(uint32_t i = 0; i < (mStackIndex + 1); i++) { if(mStackAllocated[i]) { mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[i]))); mStackAllocated[i] = false; } mStack[i] = NULL; } } PX_INLINE CharType getCharType(char* scan) const { return mTypes[uint8_t(*scan)]; } PX_INLINE char* nextSoftOrClose(char* scan, bool& close) { while(*scan && getCharType(scan) != CT_SOFT && *scan != '>') scan++; close = *scan == '>'; return scan; } PX_INLINE char* nextSep(char* scan) { while(*scan && getCharType(scan) != CT_SOFT && *scan != '=') scan++; return scan; } PX_INLINE char* skipNextData(char* scan) { // while we have data, and we encounter soft seperators or line feeds... while(*scan && (getCharType(scan) == CT_SOFT || getCharType(scan) == CT_END_OF_LINE)) { if(*scan == '\n') mLineNo++; scan++; } return scan; } void pushElement(const char* element) { PX_ASSERT(mStackIndex < uint32_t(MAX_STACK)); if(mStackIndex < uint32_t(MAX_STACK)) { if(mStackAllocated[mStackIndex]) { mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[mStackIndex]))); mStackAllocated[mStackIndex] = false; } mStack[mStackIndex++] = element; } } const char* popElement(void) { PX_ASSERT(mStackIndex > 0); if(mStackAllocated[mStackIndex]) { mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[mStackIndex]))); mStackAllocated[mStackIndex] = false; } mStack[mStackIndex] = NULL; return mStackIndex ? mStack[--mStackIndex] : NULL; } static const int MAX_STACK = 2048; CharType mTypes[256]; physx::PxInputData* mFileBuf; char* mReadBuffer; char* mReadBufferEnd; uint32_t mOpenCount; uint32_t mReadBufferSize; uint32_t mLastReadLoc; int32_t mLineNo; const char* mError; uint32_t mStackIndex; const char* mStack[MAX_STACK + 1]; bool mStreamFromMemory; bool mStackAllocated[MAX_STACK + 1]; Callback* mCallback; }; } namespace physx { namespace shdfnd { FastXml* createFastXml(FastXml::Callback* iface) { MyFastXml* m = static_cast<MyFastXml*>(iface->allocate(sizeof(MyFastXml))); if(m) { PX_PLACEMENT_NEW(m, MyFastXml(iface)); } return static_cast<FastXml*>(m); } } }
18,519
C++
21.073897
111
0.550138
NVIDIA-Omniverse/PhysX/physx/source/fastxml/include/PsFastXml.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 PSFASTXML_PSFASTXML_H #define PSFASTXML_PSFASTXML_H #include "foundation/PxSimpleTypes.h" // defines basic data types; modify for your platform as needed. #include "foundation/PxIO.h" #include "foundation/PxAssert.h" #include "foundation/PxAllocator.h" namespace physx { namespace shdfnd { class FastXml { PX_NOCOPY(FastXml) public: class AttributePairs { int argc; const char** argv; public: AttributePairs() : argc(0), argv(NULL) { } AttributePairs(int c, const char** v) : argc(c), argv(v) { } PX_INLINE int getNbAttr() const { return argc / 2; } const char* getKey(uint32_t index) const { PX_ASSERT((index * 2) < uint32_t(argc)); return argv[index * 2]; } const char* getValue(uint32_t index) const { PX_ASSERT((index * 2 + 1) < uint32_t(argc)); return argv[index * 2 + 1]; } const char* get(const char* attr) const { int32_t count = argc / 2; for(int32_t i = 0; i < count; ++i) { const char* key = argv[i * 2], *value = argv[i * 2 + 1]; if(strcmp(key, attr) == 0) return value; } return NULL; } }; /*** * Callbacks to the user with the contents of the XML file properly digested. */ class Callback { public: virtual ~Callback() { } virtual bool processComment(const char* comment) = 0; // encountered a comment in the XML // 'element' is the name of the element that is being closed. // depth is the recursion depth of this element. // Return true to continue processing the XML file. // Return false to stop processing the XML file; leaves the read pointer of the stream right after this close // tag. // The bool 'isError' indicates whether processing was stopped due to an error, or intentionally canceled early. virtual bool processClose(const char* element, uint32_t depth, bool& isError) = 0; // process the 'close' // indicator for a previously // encountered element // return true to continue processing the XML document, false to skip. virtual bool processElement(const char* elementName, // name of the element const char* elementData, // element data, null if none const AttributePairs& attr, // attributes int32_t lineno) = 0; // line number in the source XML file // process the XML declaration header virtual bool processXmlDeclaration(const AttributePairs&, // attributes const char* /*elementData*/, int32_t /*lineno*/) { return true; } virtual bool processDoctype(const char* /*rootElement*/, // Root element tag const char* /*type*/, // SYSTEM or PUBLIC const char* /*fpi*/, // Formal Public Identifier const char* /*uri*/) // Path to schema file { return true; } virtual void* allocate(uint32_t size) { return PxGetBroadcastAllocator()->allocate(size, "FastXml", PX_FL); } virtual void deallocate(void* ptr) { PxGetBroadcastAllocator()->deallocate(ptr); } }; virtual bool processXml(PxInputData& buff, bool streamFromMemory = false) = 0; virtual const char* getError(int32_t& lineno) = 0; // report the reason for a parsing error, and the line number // where it occurred. FastXml() { } virtual void release(void) = 0; protected: virtual ~FastXml() { } }; FastXml* createFastXml(FastXml::Callback* iface); } // shdfnd } // physx #endif // PSFASTXML_PSFASTXML_H
5,249
C
30.437126
114
0.674414
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMSoftBodyMaterial.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 "NpFEMSoftBodyMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX using namespace physx; using namespace Cm; NpFEMSoftBodyMaterial::NpFEMSoftBodyMaterial(const PxsFEMSoftBodyMaterialCore& desc) : PxFEMSoftBodyMaterial(PxConcreteType::eSOFTBODY_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpFEMSoftBodyMaterial::~NpFEMSoftBodyMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpFEMSoftBodyMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. NpPhysics::getInstance().addMaterial(this); } void NpFEMSoftBodyMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseFEMMaterialToPool(*this); } else this->~NpFEMSoftBodyMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpFEMSoftBodyMaterial* NpFEMSoftBodyMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpFEMSoftBodyMaterial* obj = PX_PLACEMENT_NEW(address, NpFEMSoftBodyMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpFEMSoftBodyMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpFEMSoftBodyMaterial::release() { RefCountable_decRefCount(*this); } void NpFEMSoftBodyMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpFEMSoftBodyMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpFEMSoftBodyMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setYoungsModulus(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "NpFEMSoftBodyMaterial::setYoungsModulus: invalid float"); mMaterial.youngs = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getYoungsModulus() const { return mMaterial.youngs; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setPoissons(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x < 0.5f, "PxMaterial::setPoissons: invalid float"); mMaterial.poissons = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getPoissons() const { return mMaterial.poissons; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDynamicFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMaterial::setDynamicFriction: invalid float"); mMaterial.dynamicFriction = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDynamicFriction() const { return mMaterial.dynamicFriction; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDampingScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x<= 1.f, "PxMaterial::setDampingScale: invalid float, must be in [0.0, 1.0] range."); mMaterial.dampingScale = toUniformU16(x); updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDampingScale() const { return toUniformReal(mMaterial.dampingScale); } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setMaterialModel(PxFEMSoftBodyMaterialModel::Enum model) { mMaterial.materialModel = PxU16(model); updateMaterial(); } PxFEMSoftBodyMaterialModel::Enum NpFEMSoftBodyMaterial::getMaterialModel() const { return PxFEMSoftBodyMaterialModel::Enum(mMaterial.materialModel); } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDeformThreshold(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformThreshold: invalid float"); mMaterial.deformThreshold = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDeformThreshold() const { return mMaterial.deformThreshold; } ///////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDeformLowLimitRatio(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformLowLimitRatio: invalid float"); mMaterial.deformLowLimitRatio = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDeformLowLimitRatio() const { return mMaterial.deformLowLimitRatio; } ///////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::setDeformHighLimitRatio(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformLowLimitRatio: invalid float"); mMaterial.deformHighLimitRatio = x; updateMaterial(); } PxReal NpFEMSoftBodyMaterial::getDeformHighLimitRatio() const { return mMaterial.deformHighLimitRatio; } /////////////////////////////////////////////////////////////////////////////// #endif
7,394
C++
28.939271
118
0.692183
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMPMMaterial.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 NP_MPM_MATERIAL_H #define NP_MPM_MATERIAL_H #include "common/PxSerialFramework.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" #include "CmRefCountable.h" #include "PxsMPMMaterialCore.h" #include "PxMPMMaterial.h" namespace physx { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION // Compared to other objects, materials are special since they belong to the SDK and not to scenes // (similar to meshes). That's why the NpMPMMaterial does have direct access to the core material instead // of having a buffered interface for it. Scenes will have copies of the SDK material table and there // the materials will be buffered. class NpMPMMaterial : public PxMPMMaterial, public PxUserAllocated { public: // PX_SERIALIZATION NpMPMMaterial(PxBaseFlags baseFlags) : PxMPMMaterial(baseFlags), mMaterial(PxEmpty) {} virtual void resolveReferences(PxDeserializationContext& context); static NpMPMMaterial* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&) {} //~PX_SERIALIZATION NpMPMMaterial(const PxsMPMMaterialCore& desc); virtual ~NpMPMMaterial(); // PxBase virtual void release() PX_OVERRIDE; //~PxBase // PxRefCounted virtual void acquireReference() PX_OVERRIDE; virtual PxU32 getReferenceCount() const PX_OVERRIDE; virtual void onRefCountZero() PX_OVERRIDE; //~PxRefCounted // PxParticleMaterial virtual void setFriction(PxReal friction) PX_OVERRIDE; virtual PxReal getFriction() const PX_OVERRIDE; virtual void setDamping(PxReal damping) PX_OVERRIDE; virtual PxReal getDamping() const PX_OVERRIDE; virtual void setAdhesion(PxReal adhesion) PX_OVERRIDE; virtual PxReal getAdhesion() const PX_OVERRIDE; virtual void setGravityScale(PxReal scale) PX_OVERRIDE; virtual PxReal getGravityScale() const PX_OVERRIDE; virtual void setAdhesionRadiusScale(PxReal scale) PX_OVERRIDE; virtual PxReal getAdhesionRadiusScale() const PX_OVERRIDE; //~PxParticleMaterial // PxMPMMaterial virtual void setStretchAndShearDamping(PxReal stretchAndShearDamping) PX_OVERRIDE; virtual PxReal getStretchAndShearDamping() const PX_OVERRIDE; virtual void setRotationalDamping(PxReal rotationalDamping) PX_OVERRIDE; virtual PxReal getRotationalDamping() const PX_OVERRIDE; virtual void setDensity(PxReal) PX_OVERRIDE; virtual PxReal getDensity() const PX_OVERRIDE; virtual void setMaterialModel(PxMPMMaterialModel::Enum) PX_OVERRIDE; virtual PxMPMMaterialModel::Enum getMaterialModel() const PX_OVERRIDE; virtual void setCuttingFlags(PxMPMCuttingFlags cuttingFlags) PX_OVERRIDE; virtual PxMPMCuttingFlags getCuttingFlags() const PX_OVERRIDE; virtual void setSandFrictionAngle(PxReal sandFrictionAngle) PX_OVERRIDE; virtual PxReal getSandFrictionAngle() const PX_OVERRIDE; virtual void setYieldStress(PxReal yieldStress) PX_OVERRIDE; virtual PxReal getYieldStress() const PX_OVERRIDE; virtual void setIsPlastic(bool) PX_OVERRIDE; virtual bool getIsPlastic() const PX_OVERRIDE; virtual void setYoungsModulus(PxReal) PX_OVERRIDE; virtual PxReal getYoungsModulus() const PX_OVERRIDE; virtual void setPoissons(PxReal) PX_OVERRIDE; virtual PxReal getPoissons() const PX_OVERRIDE; virtual void setHardening(PxReal) PX_OVERRIDE; virtual PxReal getHardening() const PX_OVERRIDE; virtual void setCriticalCompression(PxReal) PX_OVERRIDE; virtual PxReal getCriticalCompression() const PX_OVERRIDE; virtual void setCriticalStretch(PxReal) PX_OVERRIDE; virtual PxReal getCriticalStretch() const PX_OVERRIDE; virtual void setTensileDamageSensitivity(PxReal) PX_OVERRIDE; virtual PxReal getTensileDamageSensitivity() const PX_OVERRIDE; virtual void setCompressiveDamageSensitivity(PxReal) PX_OVERRIDE; virtual PxReal getCompressiveDamageSensitivity() const PX_OVERRIDE; virtual void setAttractiveForceResidual(PxReal) PX_OVERRIDE; virtual PxReal getAttractiveForceResidual() const PX_OVERRIDE; //~PxMPMMaterial PX_FORCE_INLINE static void getMaterialIndices(NpMPMMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount); private: PX_INLINE void updateMaterial(); // PX_SERIALIZATION public: //~PX_SERIALIZATION PxsMPMMaterialCore mMaterial; }; PX_FORCE_INLINE void NpMPMMaterial::getMaterialIndices(NpMPMMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount) { for (PxU32 i = 0; i < materialCount; i++) materialIndices[i] = static_cast<NpMPMMaterial*>(materials[i])->mMaterial.mMaterialIndex; } #endif } #endif
6,754
C
45.909722
132
0.758513
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidStatic.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 NP_RIGID_STATIC_H #define NP_RIGID_STATIC_H #include "common/PxMetaData.h" #include "PxRigidStatic.h" #include "NpRigidActorTemplate.h" #include "ScStaticCore.h" namespace physx { typedef NpRigidActorTemplate<PxRigidStatic> NpRigidStaticT; class NpRigidStatic : public NpRigidStaticT { public: // PX_SERIALIZATION NpRigidStatic(PxBaseFlags baseFlags) : NpRigidStaticT(baseFlags), mCore(PxEmpty) {} void preExportDataReset() { NpRigidStaticT::preExportDataReset(); } virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpRigidStatic* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpRigidStatic(const PxTransform& pose); virtual ~NpRigidStatic(); // PxActor virtual void release() PX_OVERRIDE; virtual PxActorType::Enum getType() const PX_OVERRIDE { return PxActorType::eRIGID_STATIC; } //~PxActor // PxRigidActor virtual void setGlobalPose(const PxTransform& pose, bool wake) PX_OVERRIDE; virtual PxTransform getGlobalPose() const PX_OVERRIDE; //~PxRigidActor // PT: I think these come from NpRigidActorTemplate // PT: TODO: drop them eventually, they all re-route to NpActor now virtual void switchToNoSim() PX_OVERRIDE; virtual void switchFromNoSim() PX_OVERRIDE; #if PX_CHECKED bool checkConstraintValidity() const; #endif PX_FORCE_INLINE const Sc::StaticCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::StaticCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpRigidStatic, mCore); } static PX_FORCE_INLINE size_t getNpShapeManagerOffset() { return PX_OFFSET_OF_RT(NpRigidStatic, mShapeManager); } #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif private: Sc::StaticCore mCore; }; } #endif
3,761
C
38.1875
117
0.744483
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidActorTemplateInternal.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 NP_RIGID_ACTOR_TEMPLATE_INTERNAL_H #define NP_RIGID_ACTOR_TEMPLATE_INTERNAL_H // PT: TODO: what is not internal about NpRigidActorTemplate.h ? Just merge the two files namespace physx { template<class APIClass, class T> static PX_FORCE_INLINE void removeRigidActorT(T& rigidActor) { NpScene* s = rigidActor.getNpScene(); NP_WRITE_CHECK(s); //Remove constraints (if any constraint is attached to the actor). rigidActor.NpRigidActorTemplate<APIClass>::removeConstraints(rigidActor); //Remove from aggregate (if it is in an aggregate). rigidActor.NpActorTemplate<APIClass>::removeFromAggregate(rigidActor); //Remove from scene (if it is in a scene). PxSceneQuerySystem* sqManager = NULL; if(s) { sqManager = &s->getSQAPI(); const bool noSim = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION); s->scRemoveActor(rigidActor, true, noSim); } //Remove associated shapes. rigidActor.NpRigidActorTemplate<APIClass>::removeShapes(sqManager); } template<class APIClass, class T> static PX_FORCE_INLINE bool releaseRigidActorT(T& rigidActor) { NpScene* s = rigidActor.getNpScene(); NP_WRITE_CHECK(s); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(s, "PxActor::release() not allowed while simulation is running. Call will be ignored.", false) const bool noSim = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION); if(s && noSim) { // need to do it here because the Np-shape buffer will not be valid anymore after the removal below // and unlike simulation objects, there is no shape buffer in the simulation controller rigidActor.getShapeManager().clearShapesOnRelease(*s, rigidActor); } NpPhysics::getInstance().notifyDeletionListenersUserRelease(&rigidActor, rigidActor.userData); //Remove constraints, aggregates, scene, shapes. removeRigidActorT<APIClass, T>(rigidActor); if (s) { s->removeFromRigidActorList(rigidActor); } return true; } } #endif
3,642
C
36.947916
145
0.763591
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterialManager.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 NP_MATERIALMANAGER #define NP_MATERIALMANAGER #include "foundation/PxMemory.h" #include "CmIDPool.h" namespace physx { template<class Material> class NpMaterialManager { public: NpMaterialManager() { const PxU32 matCount = 128; mMaterials = reinterpret_cast<Material**>(PX_ALLOC(sizeof(Material*) * matCount, "NpMaterialManager::initialise")); mMaxMaterials = matCount; PxMemZero(mMaterials, sizeof(Material*)*mMaxMaterials); } ~NpMaterialManager() {} void releaseMaterials() { for(PxU32 i=0; i<mMaxMaterials; ++i) { if(mMaterials[i]) { const PxU32 handle(mMaterials[i]->mMaterial.mMaterialIndex); mHandleManager.freeID(handle); mMaterials[i]->release(); mMaterials[i] = NULL; } } PX_FREE(mMaterials); } bool setMaterial(Material& mat) { const PxU32 poolID = mHandleManager.getNewID(); if (poolID >= MATERIAL_INVALID_HANDLE) return false; const PxU16 materialIndex = PxTo16(poolID); if(materialIndex >= mMaxMaterials) resize(); mMaterials[materialIndex] = &mat; mat.mMaterial.mMaterialIndex = materialIndex; return true; } void updateMaterial(Material& mat) { mMaterials[mat.mMaterial.mMaterialIndex] = &mat; } PX_FORCE_INLINE PxU32 getNumMaterials() const { return mHandleManager.getNumUsedID(); } void removeMaterial(Material& mat) { const PxU16 handle = mat.mMaterial.mMaterialIndex; if(handle != MATERIAL_INVALID_HANDLE) { mMaterials[handle] = NULL; mHandleManager.freeID(PxU32(handle)); } } PX_FORCE_INLINE Material* getMaterial(const PxU32 index) const { PX_ASSERT(index < mMaxMaterials); return mMaterials[index]; } PX_FORCE_INLINE PxU32 getMaxSize() const { return mMaxMaterials; } PX_FORCE_INLINE Material** getMaterials() const { return mMaterials; } private: void resize() { const PxU32 numMaterials = mMaxMaterials; mMaxMaterials = PxMin(mMaxMaterials*2, PxU32(MATERIAL_INVALID_HANDLE)); Material** mat = reinterpret_cast<Material**>(PX_ALLOC(sizeof(Material*)*mMaxMaterials, "NpMaterialManager::resize")); PxMemZero(mat, sizeof(Material*)*mMaxMaterials); for(PxU32 i=0; i<numMaterials; ++i) mat[i] = mMaterials[i]; PX_FREE(mMaterials); mMaterials = mat; } Cm::IDPool mHandleManager; Material** mMaterials; PxU32 mMaxMaterials; }; template<class Material> class NpMaterialManagerIterator { public: NpMaterialManagerIterator(const NpMaterialManager<Material>& manager) : mManager(manager), mIndex(0) { } bool getNextMaterial(Material*& np) { const PxU32 maxSize = mManager.getMaxSize(); PxU32 index = mIndex; while(index < maxSize && mManager.getMaterial(index)==NULL) index++; np = NULL; if(index < maxSize) np = mManager.getMaterial(index++); mIndex = index; return np!=NULL; } private: NpMaterialManagerIterator& operator=(const NpMaterialManagerIterator&); const NpMaterialManager<Material>& mManager; PxU32 mIndex; }; } #endif
4,764
C
27.195266
122
0.717464
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterial.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 "NpMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; using namespace Cm; NpMaterial::NpMaterial(const PxsMaterialCore& desc) : PxMaterial(PxConcreteType::eMATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpMaterial::~NpMaterial() { OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, static_cast<PxMaterial &>(*this)) NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. NpPhysics::getInstance().addMaterial(this); } void NpMaterial::onRefCountZero() { void* ud = userData; if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) NpFactory::getInstance().releaseMaterialToPool(*this); else this->~NpMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpMaterial* NpMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpMaterial* obj = PX_PLACEMENT_NEW(address, NpMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpMaterial::release() { RefCountable_decRefCount(*this); } void NpMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setDynamicFriction(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setDynamicFriction: invalid float"); mMaterial.dynamicFriction = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, dynamicFriction, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getDynamicFriction() const { return mMaterial.dynamicFriction; } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setStaticFriction(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setStaticFriction: invalid float"); mMaterial.staticFriction = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, staticFriction, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getStaticFriction() const { return mMaterial.staticFriction; } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setRestitution(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setRestitution: invalid float"); PX_CHECK_MSG(((mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT || x >= 0.0f) && (x <= 1.0f)), "PxMaterial::setRestitution: Restitution value has to be in [0,1]!"); if ((!(mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x < 0.0f) || (x > 1.0f)) { PxClamp(x, 0.0f, 1.0f); PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMaterial::setRestitution: Invalid value %f was clamped to [0,1]!", PxF64(x)); } mMaterial.restitution = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitution, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getRestitution() const { return mMaterial.restitution; } ///////////////////////////////////////////////////////////////////////////////// void NpMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x) && x >= 0.f, "PxMaterial::setDamping: invalid float. Must be >= 0"); PX_CHECK_MSG((((mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x >= 0.f) || x == 0.f), "PxMaterial::setDamping: Damping value has to be in [0,INF] and PxMaterialFlag::eCOMPLIANT_CONTACT should be raised!"); if ((!(mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x != 0.0f)) { x = 0.f; PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMaterial::setDamping: Attempting to set a non-zero damping coefficient without raising PxMaterialFlag::eCOMPLIANT_CONTACT first!"); } mMaterial.damping = x; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, damping, static_cast<PxMaterial &>(*this), x) } PxReal NpMaterial::getDamping() const { return mMaterial.damping; } ///////////////////////////////////////////////////////////////////////////////// void NpMaterial::setFlag(PxMaterialFlag::Enum flag, bool value) { if (value) mMaterial.flags |= flag; else mMaterial.flags &= ~PxMaterialFlags(flag); updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, static_cast<PxMaterial &>(*this), mMaterial.flags) } void NpMaterial::setFlags(PxMaterialFlags inFlags) { mMaterial.flags = inFlags; updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, static_cast<PxMaterial &>(*this), mMaterial.flags) } PxMaterialFlags NpMaterial::getFlags() const { return mMaterial.flags; } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setFrictionCombineMode(PxCombineMode::Enum x) { mMaterial.setFrictionCombineMode(x); updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, frictionCombineMode, static_cast<PxMaterial &>(*this), x) } PxCombineMode::Enum NpMaterial::getFrictionCombineMode() const { return mMaterial.getFrictionCombineMode(); } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::setRestitutionCombineMode(PxCombineMode::Enum x) { mMaterial.setRestitutionCombineMode(x); updateMaterial(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitutionCombineMode, static_cast<PxMaterial &>(*this), x) } PxCombineMode::Enum NpMaterial::getRestitutionCombineMode() const { return mMaterial.getRestitutionCombineMode(); } ///////////////////////////////////////////////////////////////////////////////
8,101
C++
34.073593
217
0.695346
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMCloth.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NP_FEMCLOTH #define PX_PHYSICS_NP_FEMCLOTH #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxFEMCloth.h" #endif #include "ScFEMClothCore.h" #include "NpActorTemplate.h" namespace physx { class NpShape; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION class NpFEMCloth : public NpActorTemplate<PxFEMCloth> { public: NpFEMCloth(PxCudaContextManager& cudaContextManager); NpFEMCloth(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager); virtual ~NpFEMCloth() {} void exportData(PxSerializationContext& /*context*/) const {} //external API virtual PxActorType::Enum getType() const { return PxActorType::eFEMCLOTH; } virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const; virtual void setFEMClothFlag(PxFEMClothFlag::Enum flag, bool val); virtual void setFEMClothFlags(PxFEMClothFlags flags); virtual PxFEMClothFlags getFEMClothFlag() const; #if 0 // disabled until future use. virtual void setDrag(const PxReal drag); virtual PxReal getDrag() const; virtual void setLift(const PxReal lift); virtual PxReal getLift() const; virtual void setWind(const PxVec3& wind); virtual PxVec3 getWind() const; virtual void setAirDensity(const PxReal wind); virtual PxReal getAirDensity() const; virtual void setBendingActivationAngle(const PxReal angle); virtual PxReal getBendingActivationAngle() const; #endif virtual void setParameter(const PxFEMParameters& paramters); virtual PxFEMParameters getParameter() const; virtual void setBendingScales(const PxReal* const bendingScale, PxU32 nbElements); virtual const PxReal* getBendingScales() const; virtual PxU32 getNbBendingScales() const; virtual void setMaxVelocity(const PxReal v); virtual PxReal getMaxVelocity() const; virtual void setMaxDepenetrationVelocity(const PxReal v); virtual PxReal getMaxDepenetrationVelocity() const; virtual void setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency); virtual PxU32 getNbCollisionPairUpdatesPerTimestep() const; virtual void setNbCollisionSubsteps(const PxU32 frequency); virtual PxU32 getNbCollisionSubsteps() const; virtual PxVec4* getPositionInvMassBufferD(); virtual PxVec4* getVelocityBufferD(); virtual PxVec4* getRestPositionBufferD(); virtual void markDirty(PxFEMClothDataFlags flags); virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle); virtual void addTriRigidFilter(PxRigidActor* actor, PxU32 triangleId); virtual void removeTriRigidFilter(PxRigidActor* actor, PxU32 triangleId); virtual PxU32 addTriRigidAttachment(PxRigidActor* actor, PxU32 triangleId, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void removeTriRigidAttachment(PxRigidActor* actor, PxU32 handle); virtual void addClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx); virtual void removeClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx); virtual PxU32 addClothAttachment(PxFEMCloth* otherCloth, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric); virtual void removeClothAttachment(PxFEMCloth* otherCloth, PxU32 handle); virtual PxCudaContextManager* getCudaContextManager() const; virtual void setCudaContextManager(PxCudaContextManager*); virtual void setSolverIterationCounts(PxU32 minPositionIters); virtual void getSolverIterationCounts(PxU32& minPositionIters) const; virtual PxShape* getShape(); virtual bool attachShape(PxShape& shape); virtual void detachShape(); virtual void release(); PX_FORCE_INLINE const Sc::FEMClothCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::FEMClothCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpFEMCloth, mCore); } virtual bool isSleeping() const; // Debug name void setName(const char*); const char* getName() const; void updateMaterials(); private: NpShape* mShape; Sc::FEMClothCore mCore; PxCudaContextManager* mCudaContextManager; }; #endif } #endif #endif
6,406
C
37.830303
175
0.753512
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationLink.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 NP_ARTICULATION_LINK_H #define NP_ARTICULATION_LINK_H #include "NpRigidBodyTemplate.h" #include "PxArticulationLink.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif namespace physx { class NpArticulationLink; class NpArticulationJointReducedCoordinate; class PxConstraintVisualizer; typedef NpRigidBodyTemplate<PxArticulationLink> NpArticulationLinkT; class NpArticulationLinkArray : public PxInlineArray<NpArticulationLink*, 4> //!!!AL TODO: check if default of 4 elements makes sense { public: // PX_SERIALIZATION NpArticulationLinkArray(const PxEMPTY) : PxInlineArray<NpArticulationLink*, 4> (PxEmpty) {} static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpArticulationLinkArray() : PxInlineArray<NpArticulationLink*, 4>("articulationLinkArray") {} }; class NpArticulationLink : public NpArticulationLinkT { public: // PX_SERIALIZATION NpArticulationLink(PxBaseFlags baseFlags) : NpArticulationLinkT(baseFlags), mChildLinks(PxEmpty) {} void preExportDataReset() { NpArticulationLinkT::preExportDataReset(); } virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); virtual bool isSubordinate() const { return true; } static NpArticulationLink* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION virtual ~NpArticulationLink(); //--------------------------------------------------------------------------------- // PxArticulationLink implementation //--------------------------------------------------------------------------------- virtual void release(); virtual PxActorType::Enum getType() const { return PxActorType::eARTICULATION_LINK; } // Pose virtual void setGlobalPose(const PxTransform& /*pose*/, bool /*wake*/) { /*return false; */} virtual PxTransform getGlobalPose() const; virtual bool attachShape(PxShape& shape); virtual void detachShape(PxShape& shape, bool wakeOnLostTouch = true); virtual PxArticulationReducedCoordinate& getArticulation() const; virtual PxArticulationJointReducedCoordinate* getInboundJoint() const; virtual PxU32 getInboundJointDof() const; virtual PxU32 getNbChildren() const; virtual PxU32 getChildren(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getLinkIndex() const; virtual void setCMassLocalPose(const PxTransform& pose); virtual void addForce(const PxVec3& force, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true); virtual void addTorque(const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true); virtual void setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE); virtual void clearForce(PxForceMode::Enum mode = PxForceMode::eFORCE); virtual void clearTorque(PxForceMode::Enum mode = PxForceMode::eFORCE); virtual void setCfmScale(const PxReal cfmScale); virtual PxReal getCfmScale() const; //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpArticulationLink(const PxTransform& bodyPose, PxArticulationReducedCoordinate& root, NpArticulationLink* parent); void releaseInternal(); PX_INLINE PxArticulationReducedCoordinate& getRoot() { return *mRoot; } PX_INLINE NpArticulationLink* getParent() { return mParent; } PX_INLINE const NpArticulationLink* getParent() const { return mParent; } PX_INLINE void setInboundJoint(PxArticulationJointReducedCoordinate& joint) { mInboundJoint = &joint; } void setGlobalPoseInternal(const PxTransform& pose, bool autowake); void setLLIndex(const PxU32 index) { mLLIndex = index; } void setInboundJointDof(const PxU32 index); static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpArticulationLink, mCore); } private: PX_INLINE void addToChildList(NpArticulationLink& link) { mChildLinks.pushBack(&link); } PX_INLINE void removeFromChildList(NpArticulationLink& link) { PX_ASSERT(mChildLinks.find(&link) != mChildLinks.end()); mChildLinks.findAndReplaceWithLast(&link); } public: PX_INLINE NpArticulationLink* const* getChildren() { return mChildLinks.empty() ? NULL : &mChildLinks.front(); } void setFixedBaseLink(bool value); #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; void visualizeJoint(PxConstraintVisualizer& jointViz) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif private: PxArticulationReducedCoordinate* mRoot; //!!!AL TODO: Revisit: Could probably be avoided if registration and deregistration in root is handled differently PxArticulationJointReducedCoordinate* mInboundJoint; NpArticulationLink* mParent; //!!!AL TODO: Revisit: Some memory waste but makes things faster NpArticulationLinkArray mChildLinks; PxU32 mLLIndex; PxU32 mInboundJointDof; }; } #endif
7,266
C
46.496732
170
0.715662
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneQueryCollector.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 NP_PVD_SCENEQUERYCOLLECTOR_H #define NP_PVD_SCENEQUERYCOLLECTOR_H #include "geometry/PxGeometryHelpers.h" #include "PxFiltering.h" #include "PxQueryReport.h" #include "PxQueryFiltering.h" #include "foundation/PxArray.h" #include "foundation/PxMutex.h" #if PX_SUPPORT_PVD namespace physx { namespace Vd { class PvdSceneClient; struct QueryID { enum Enum { QUERY_RAYCAST_ANY_OBJECT, QUERY_RAYCAST_CLOSEST_OBJECT, QUERY_RAYCAST_ALL_OBJECTS, QUERY_OVERLAP_SPHERE_ALL_OBJECTS, QUERY_OVERLAP_AABB_ALL_OBJECTS, QUERY_OVERLAP_OBB_ALL_OBJECTS, QUERY_OVERLAP_CAPSULE_ALL_OBJECTS, QUERY_OVERLAP_CONVEX_ALL_OBJECTS, QUERY_LINEAR_OBB_SWEEP_CLOSEST_OBJECT, QUERY_LINEAR_CAPSULE_SWEEP_CLOSEST_OBJECT, QUERY_LINEAR_CONVEX_SWEEP_CLOSEST_OBJECT }; }; struct PvdReference { PX_FORCE_INLINE PvdReference() {} PX_FORCE_INLINE PvdReference(const char* arrayName, PxU32 baseIndex, PxU32 count) : mArrayName(arrayName), mBaseIndex(baseIndex), mCount(count) {} const char* mArrayName; PxU32 mBaseIndex; PxU32 mCount; }; struct PvdRaycast { PxU32 mType; PxFilterData mFilterData; PxU32 mFilterFlags; PxVec3 mOrigin; PxVec3 mUnitDir; PxReal mDistance; PvdReference mHits; }; struct PvdOverlap { PxU32 mType; PxFilterData mFilterData; PxU32 mFilterFlags; PxTransform mPose; PvdReference mGeometries; PvdReference mHits; }; struct PvdSweep { PxU32 mType; PxU32 mFilterFlags; PxVec3 mUnitDir; PxReal mDistance; PvdReference mGeometries; PvdReference mPoses; PvdReference mFilterData; PvdReference mHits; }; struct PvdSqHit { const void* mShape; const void* mActor; PxU32 mFaceIndex; PxU32 mFlags; PxVec3 mImpact; PxVec3 mNormal; PxF32 mDistance; PxF32 mU; PxF32 mV; PvdSqHit() { setDefaults(0xFFFFffff, NULL, NULL); } explicit PvdSqHit(const PxOverlapHit& hit) { setDefaults(hit.faceIndex, hit.shape, hit.actor); } explicit PvdSqHit(const PxRaycastHit& hit) { setDefaults(hit.faceIndex, hit.shape, hit.actor); mImpact = hit.position; mNormal = hit.normal; mDistance = hit.distance; mFlags = hit.flags; mU = hit.u; mV = hit.v; } explicit PvdSqHit(const PxSweepHit& hit) { setDefaults(hit.faceIndex, hit.shape, hit.actor); mImpact = hit.position; mNormal = hit.normal; mDistance = hit.distance; mFlags = hit.flags; } private: void setDefaults(PxU32 faceIndex, const void* shape, const void* actor) { mShape = shape; mActor = actor; mFaceIndex = faceIndex; mFlags = 0; mImpact = mNormal = PxVec3(0.0f); mDistance = mU = mV = 0.0f; } }; template <class T> class NamedArray : public PxArray<T> { public: NamedArray(const char* names[2]) { mNames[0] = names[0]; mNames[1] = names[1]; } const char* mNames[2]; }; class PvdSceneQueryCollector { PX_NOCOPY(PvdSceneQueryCollector) public: PvdSceneQueryCollector(Vd::PvdSceneClient* pvd, bool isBatched); ~PvdSceneQueryCollector() {} void clear() { PxMutex::ScopedLock lock(mMutex); mAccumulatedRaycastQueries.clear(); mAccumulatedOverlapQueries.clear(); mAccumulatedSweepQueries.clear(); mPvdSqHits.clear(); mPoses.clear(); mFilterData.clear(); } void clearGeometryArrays() { mGeometries0.clear(); mGeometries1.clear(); } void release(); void raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits); void sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData, bool multipleHits); void overlapMultiple(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& filterData); PX_FORCE_INLINE PxMutex& getLock() { return mMutex; } template <class T> PX_FORCE_INLINE const char* getArrayName(const NamedArray<T>& namedArray) const { return namedArray.mNames[mIsBatched]; } PX_FORCE_INLINE const NamedArray<PxGeometryHolder>& getGeometries(PxU32 index) const { return index ? mGeometries1 : mGeometries0; } PX_FORCE_INLINE NamedArray<PxGeometryHolder>& getGeometries(PxU32 index) { return index ? mGeometries1 : mGeometries0; } PX_FORCE_INLINE const NamedArray<PxGeometryHolder>& getCurrentFrameGeometries() const { return getGeometries(mInUse); } PX_FORCE_INLINE const NamedArray<PxGeometryHolder>& getPrevFrameGeometries() const { return getGeometries(mInUse ^ 1); } void prepareNextFrameGeometries() { mInUse ^= 1; getGeometries(mInUse).clear(); } NamedArray<PvdRaycast> mAccumulatedRaycastQueries; NamedArray<PvdSweep> mAccumulatedSweepQueries; NamedArray<PvdOverlap> mAccumulatedOverlapQueries; NamedArray<PvdSqHit> mPvdSqHits; NamedArray<PxTransform> mPoses; NamedArray<PxFilterData> mFilterData; private: Vd::PvdSceneClient* mPVD; PxMutex mMutex; NamedArray<PxGeometryHolder>mGeometries0; NamedArray<PxGeometryHolder>mGeometries1; PxU32 mInUse; const bool mIsBatched; }; } } #endif // PX_SUPPORT_PVD #endif // NP_PVD_SCENEQUERYCOLLECTOR_H
6,912
C
27.684647
199
0.741753
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneQueryCollector.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 "NpPvdSceneQueryCollector.h" #include "NpPvdSceneClient.h" #if PX_SUPPORT_PVD using namespace physx; using namespace Vd; static const char* gName_PvdRaycast[2] = { "SceneQueries.Raycasts", "BatchedQueries.Raycasts" }; static const char* gName_PvdSweep[2] = { "SceneQueries.Sweeps", "BatchedQueries.Sweeps" }; static const char* gName_PvdOverlap[2] = { "SceneQueries.Overlaps", "BatchedQueries.Overlaps" }; static const char* gName_PvdSqHit[2] = { "SceneQueries.Hits", "BatchedQueries.Hits" }; static const char* gName_PxTransform[2] = { "SceneQueries.PoseList", "BatchedQueries.PoseList" }; static const char* gName_PxFilterData[2] = { "SceneQueries.FilterDataList", "BatchedQueries.FilterDataList" }; static const char* gName_PxGeometryHolder[2] = { "SceneQueries.GeometryList", "BatchedQueries.GeometryList" }; PvdSceneQueryCollector::PvdSceneQueryCollector(Vd::PvdSceneClient* pvd, bool isBatched) : mAccumulatedRaycastQueries (gName_PvdRaycast), mAccumulatedSweepQueries (gName_PvdSweep), mAccumulatedOverlapQueries (gName_PvdOverlap), mPvdSqHits (gName_PvdSqHit), mPoses (gName_PxTransform), mFilterData (gName_PxFilterData), mPVD (pvd), mGeometries0 (gName_PxGeometryHolder), mGeometries1 (gName_PxGeometryHolder), mInUse (0), mIsBatched (isBatched) { } void PvdSceneQueryCollector::release() { physx::pvdsdk::PvdDataStream* stream = mPVD->getDataStream(); if(stream && stream->isConnected()) { const PxArray<PxGeometryHolder>& geoms = getPrevFrameGeometries(); for(PxU32 k=0; k<geoms.size(); ++k) stream->destroyInstance(&geoms[k]); clearGeometryArrays(); } } template<class SDKHitType, class PvdHitType> static void accumulate(PvdHitType& query, PxArray<PvdHitType>& accumulated, const char* arrayName, PxArray<PvdSqHit>& dst, const SDKHitType* src, PxU32 nb, const PxQueryFilterData& fd) { query.mFilterFlags = fd.flags; query.mHits = PvdReference(arrayName, dst.size(), nb); PX_ASSERT(PxU32(-1) != nb); for(PxU32 i=0; i<nb; i++) dst.pushBack(PvdSqHit(src[i])); accumulated.pushBack(query); } static PX_FORCE_INLINE void clampNbHits(PxU32& hitsNum, const PxQueryFilterData& fd, bool multipleHits) { if((fd.flags & PxQueryFlag::eANY_HIT) || !multipleHits) hitsNum = hitsNum > 0 ? 1u : 0; } template<class Type> static void pushBackT(PxArray<Type>& array, const Type& item, PvdReference& ref, const char* arrayName) { ref = PvdReference(arrayName, array.size(), 1); array.pushBack(item); } void PvdSceneQueryCollector::raycast(const PxVec3& origin, const PxVec3& unitDir, PxReal distance, const PxRaycastHit* hit, PxU32 hitsNum, const PxQueryFilterData& fd, bool multipleHits) { PxMutex::ScopedLock lock(mMutex); PvdRaycast raycastQuery; raycastQuery.mOrigin = origin; raycastQuery.mUnitDir = unitDir; raycastQuery.mDistance = distance; raycastQuery.mFilterData = fd.data; if(fd.flags & PxQueryFlag::eANY_HIT) raycastQuery.mType = QueryID::QUERY_RAYCAST_ANY_OBJECT; else if(multipleHits) raycastQuery.mType = QueryID::QUERY_RAYCAST_ALL_OBJECTS; else raycastQuery.mType = QueryID::QUERY_RAYCAST_CLOSEST_OBJECT; clampNbHits(hitsNum, fd, multipleHits); accumulate(raycastQuery, mAccumulatedRaycastQueries, getArrayName(mPvdSqHits), mPvdSqHits, hit, hitsNum, fd); } void PvdSceneQueryCollector::sweep(const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, PxReal distance, const PxSweepHit* hit, PxU32 hitsNum, const PxQueryFilterData& fd, bool multipleHits) { PxMutex::ScopedLock lock(mMutex); PvdSweep sweepQuery; pushBackT(getGeometries(mInUse), PxGeometryHolder(geometry), sweepQuery.mGeometries, getArrayName(getGeometries(mInUse))); // PT: TODO: optimize this. We memcopy once to the stack, then again to the array.... pushBackT(mPoses, pose, sweepQuery.mPoses, getArrayName(mPoses)); pushBackT(mFilterData, fd.data, sweepQuery.mFilterData, getArrayName(mFilterData)); const PxGeometryType::Enum type = geometry.getType(); // PT: TODO: QueryID::QUERY_LINEAR_xxx_SWEEP_ALL_OBJECTS are never used! if(type==PxGeometryType::eBOX) sweepQuery.mType = QueryID::QUERY_LINEAR_OBB_SWEEP_CLOSEST_OBJECT; else if(type==PxGeometryType::eSPHERE || type==PxGeometryType::eCAPSULE) sweepQuery.mType = QueryID::QUERY_LINEAR_CAPSULE_SWEEP_CLOSEST_OBJECT; else if(type==PxGeometryType::eCONVEXMESH) sweepQuery.mType = QueryID::QUERY_LINEAR_CONVEX_SWEEP_CLOSEST_OBJECT; else PX_ASSERT(0); sweepQuery.mUnitDir = unitDir; sweepQuery.mDistance = distance; clampNbHits(hitsNum, fd, multipleHits); accumulate(sweepQuery, mAccumulatedSweepQueries, getArrayName(mPvdSqHits), mPvdSqHits, hit, hitsNum, fd); } void PvdSceneQueryCollector::overlapMultiple(const PxGeometry& geometry, const PxTransform& pose, const PxOverlapHit* hit, PxU32 hitsNum, const PxQueryFilterData& fd) { PxMutex::ScopedLock lock(mMutex); PvdOverlap overlapQuery; pushBackT(getGeometries(mInUse), PxGeometryHolder(geometry), overlapQuery.mGeometries, getArrayName(getGeometries(mInUse))); // PT: TODO: optimize this. We memcopy once to the stack, then again to the array.... const PxGeometryType::Enum type = geometry.getType(); if(type==PxGeometryType::eBOX) overlapQuery.mType = pose.q.isIdentity() ? QueryID::QUERY_OVERLAP_AABB_ALL_OBJECTS : QueryID::QUERY_OVERLAP_OBB_ALL_OBJECTS; else if(type==PxGeometryType::eSPHERE) overlapQuery.mType = QueryID::QUERY_OVERLAP_SPHERE_ALL_OBJECTS; else if(type==PxGeometryType::eCAPSULE) overlapQuery.mType = QueryID::QUERY_OVERLAP_CAPSULE_ALL_OBJECTS; else if(type==PxGeometryType::eCONVEXMESH) overlapQuery.mType = QueryID::QUERY_OVERLAP_CONVEX_ALL_OBJECTS; else PX_ASSERT(0); overlapQuery.mPose = pose; overlapQuery.mFilterData = fd.data; accumulate(overlapQuery, mAccumulatedOverlapQueries, getArrayName(mPvdSqHits), mPvdSqHits, hit, hitsNum, fd); } #endif
7,595
C++
48.324675
213
0.7605
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdMetaDataBindingData.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 PVD_META_DATA_BINDING_DATA_H #define PVD_META_DATA_BINDING_DATA_H #if PX_SUPPORT_PVD #include "foundation/PxSimpleTypes.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "foundation/PxArray.h" namespace physx { namespace Vd { typedef PxHashSet<const PxRigidActor*> OwnerActorsValueType; typedef PxHashMap<const PxShape*, OwnerActorsValueType*> OwnerActorsMap; struct PvdMetaDataBindingData : public PxUserAllocated { PxArray<PxU8> mTempU8Array; PxArray<PxActor*> mActors; PxArray<PxArticulationReducedCoordinate*> mArticulations; PxArray<PxArticulationLink*> mArticulationLinks; PxHashSet<PxActor*> mSleepingActors; OwnerActorsMap mOwnerActorsMap; PvdMetaDataBindingData() : mTempU8Array("TempU8Array") , mActors("PxActor") , mArticulations("Articulations") , mArticulationLinks("ArticulationLinks") , mSleepingActors("SleepingActors") { } template <typename TDataType> TDataType* allocateTemp(PxU32 numItems) { mTempU8Array.resize(numItems * sizeof(TDataType)); if(numItems) return reinterpret_cast<TDataType*>(mTempU8Array.begin()); else return NULL; } DataRef<const PxU8> tempToRef() { return DataRef<const PxU8>(mTempU8Array.begin(), mTempU8Array.size()); } }; } } #endif // PX_SUPPORT_PVD #endif
2,978
C
34.464285
74
0.770316
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationTendon.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 "NpArticulationTendon.h" #include "NpArticulationLink.h" #include "NpArticulationReducedCoordinate.h" #include "ScArticulationTendonSim.h" #include "CmUtils.h" using namespace physx; // PX_SERIALIZATION void NpArticulationAttachment::requiresObjects(PxProcessPxBaseCallback& c) { // Collect articulation links const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) c.process(*mChildren[i]); } void NpArticulationAttachment::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mChildren, stream); } void NpArticulationAttachment::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mChildren, context); } void NpArticulationAttachment::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mLink); context.translatePxBase(mParent); const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) { NpArticulationAttachment*& attachment = mChildren[i]; context.translatePxBase(attachment); } context.translatePxBase(mTendon); mCore.mParent = mParent ? &static_cast<NpArticulationAttachment*>(mParent)->mCore : NULL; } NpArticulationAttachment* NpArticulationAttachment::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationAttachment* obj = PX_PLACEMENT_NEW(address, NpArticulationAttachment(PxBaseFlags(0))); address += sizeof(NpArticulationAttachment); obj->importExtraData(context); obj->resolveReferences(context); return obj; } // ~PX_SERIALIZATION NpArticulationAttachment::NpArticulationAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link): PxArticulationAttachment(PxConcreteType::eARTICULATION_ATTACHMENT, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_ATTACHMENT), mLink(link), mParent(parent) { NpArticulationAttachment* npParent = static_cast<NpArticulationAttachment*>(parent); mCore.mRelativeOffset = link->getCMassLocalPose().transform(relativeOffset); mCore.mParent = npParent ? &npParent->getCore() : NULL; mCore.mLowLimit = PX_MAX_F32; mCore.mHighLimit = -PX_MAX_F32; mCore.mRestLength = 0.f; mCore.mCoefficient = coefficient; mCore.mTendonSim = NULL; mCore.mAttachmentIndex = 0xffffffff; } NpArticulationAttachment::~NpArticulationAttachment() { } void NpArticulationAttachment::setRestLength(const PxReal restLength) { PX_CHECK_AND_RETURN(PxIsFinite(restLength), "PxArticulationAttachment::setRestLength(): restLength must have valid value."); PX_CHECK_AND_RETURN(isLeaf(), "PxArticulationAttachment::setRestLength(): Setting rest length on a non-leaf attachment has no effect."); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setRestLength(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mRestLength = restLength; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentRestLength(mCore, restLength); } PxReal NpArticulationAttachment::getRestLength() const { return mCore.mRestLength; } void NpArticulationAttachment::setLimitParameters(const PxArticulationTendonLimit& parameter) { PX_CHECK_AND_RETURN(PxIsFinite(parameter.lowLimit) && PxIsFinite(parameter.highLimit) && (parameter.lowLimit <= parameter.highLimit), "NpArticulationAttachment::setLimitParameters(): lowLimit and highLimit must have valid values and lowLimit must be less than highLimit!"); PX_CHECK_AND_RETURN(isLeaf(), "PxArticulationAttachment::setLimitParameters(): Setting limits on a non-leaf attachment has no effect."); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setLimitParameters(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mLowLimit = parameter.lowLimit; mCore.mHighLimit = parameter.highLimit; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentLimits(mCore, parameter.lowLimit, parameter.highLimit); } PxArticulationTendonLimit NpArticulationAttachment::getLimitParameters()const { PxArticulationTendonLimit parameter; parameter.lowLimit = mCore.mLowLimit; parameter.highLimit = mCore.mHighLimit; return parameter; } void NpArticulationAttachment::setRelativeOffset(const PxVec3& offset) { NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setRelativeOffset(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mRelativeOffset = offset; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentRelativeOffset(mCore, offset); } PxVec3 NpArticulationAttachment::getRelativeOffset() const { return mCore.mRelativeOffset; } void NpArticulationAttachment::setCoefficient(const PxReal coefficient) { PX_CHECK_AND_RETURN(PxIsFinite(coefficient), "PxArticulationAttachment::setCoefficient :: Error: NaN or Inf joint coefficient provided!"); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::setCoefficient(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.mCoefficient = coefficient; if (mCore.mTendonSim) mCore.mTendonSim->setAttachmentCoefficient(mCore, coefficient); } PxReal NpArticulationAttachment::getCoefficient() const { return mCore.mCoefficient; } PxArticulationSpatialTendon* NpArticulationAttachment::getTendon() const { return mTendon; } void NpArticulationAttachment::release() { if (mTendon->getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationAttachment::release() not allowed while the articulation is in the scene. Call will be ignored."); return; } PX_CHECK_AND_RETURN(getNumChildren() == 0, "PxArticulationAttachment:release() can only release leaf attachments, i.e. attachments with zero children."); NpArticulationAttachmentArray& attachments = mTendon->getAttachments(); NpArticulationAttachment* npParentAttachment = static_cast<NpArticulationAttachment*>(mParent); //remove this attachment from the parent if (npParentAttachment) npParentAttachment->removeChild(this); attachments.back()->mHandle = mHandle; attachments.replaceWithLast(mHandle); this->~NpArticulationAttachment(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } void NpArticulationAttachment::removeChild(NpArticulationAttachment* child) { const PxU32 size = mChildren.size(); PxU32 index = 0; for (PxU32 i = 0; i < size; ++i) { NpArticulationAttachment* otherChild = mChildren[i]; if (otherChild == child) { index = i; break; } } const PxU32 lastIndex = size - 1; mChildren[index] = mChildren[lastIndex]; mChildren.forceSize_Unsafe(lastIndex); } // PX_SERIALIZATION void NpArticulationSpatialTendon::requiresObjects(PxProcessPxBaseCallback& c) { const PxU32 nbAttachments = mAttachments.size(); for (PxU32 i = 0; i < nbAttachments; i++) c.process(*mAttachments[i]); } void NpArticulationSpatialTendon::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mAttachments, stream); } void NpArticulationSpatialTendon::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mAttachments, context); } void NpArticulationSpatialTendon::resolveReferences(PxDeserializationContext& context) { const PxU32 nbAttachments = mAttachments.size(); for (PxU32 i = 0; i < nbAttachments; i++) { NpArticulationAttachment*& attachment = mAttachments[i]; context.translatePxBase(attachment); } context.translatePxBase(mArticulation); } NpArticulationSpatialTendon* NpArticulationSpatialTendon::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationSpatialTendon* obj = PX_PLACEMENT_NEW(address, NpArticulationSpatialTendon(PxBaseFlags(0))); address += sizeof(NpArticulationSpatialTendon); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationSpatialTendon::NpArticulationSpatialTendon(NpArticulationReducedCoordinate* articulation) : PxArticulationSpatialTendon(PxConcreteType::eARTICULATION_SPATIAL_TENDON, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_SPATIAL_TENDON), mArticulation(articulation) { mLLIndex = 0xffffffff; mHandle = 0xffffffff; } NpArticulationSpatialTendon::~NpArticulationSpatialTendon() { for (PxU32 i = 0; i < mAttachments.size(); ++i) { if (mAttachments[i]) { mAttachments[i]->~NpArticulationAttachment(); if(mAttachments[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE(mAttachments[i]); } } } PxArticulationAttachment* NpArticulationSpatialTendon::createAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::createAttachment() not allowed while the articulation is in the scene. Call will be ignored."); return NULL; } PX_CHECK_AND_RETURN_NULL(link, "PxArticulationSpatialTendon::createAttachment: Null pointer link provided. Need valid link."); PX_CHECK_AND_RETURN_NULL(&link->getArticulation() == getArticulation(), "PxArticulationSpatialTendon::createAttachment: Link from another articulation provided. Need valid link from same articulation."); #if PX_CHECKED if(parent) PX_CHECK_AND_RETURN_NULL(parent->getTendon() == this, "PxArticulationSpatialTendon::createAttachment: Parent attachment from another tendon provided. Need valid parent from same tendon."); #endif void* npAttachmentMem = PX_ALLOC(sizeof(NpArticulationAttachment), "NpArticulationAttachment"); PxMarkSerializedMemory(npAttachmentMem, sizeof(NpArticulationAttachment)); NpArticulationAttachment* npAttachment = PX_PLACEMENT_NEW(npAttachmentMem, NpArticulationAttachment)(parent, coefficient, relativeOffset, link); if (npAttachment) { npAttachment->setTendon(this); NpArticulationAttachment* parentAttachment = static_cast<NpArticulationAttachment*>(parent); ArticulationAttachmentHandle handle = mAttachments.size(); npAttachment->mHandle = handle; mAttachments.pushBack(npAttachment); if (parentAttachment) { parentAttachment->mChildren.pushBack(npAttachment); npAttachment->mParent = parent; } else { npAttachment->mParent = NULL; } } return npAttachment; } PxU32 NpArticulationSpatialTendon::getAttachments(PxArticulationAttachment** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(mArticulation->getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mAttachments.begin(), mAttachments.size()); } void NpArticulationSpatialTendon::setStiffness(const PxReal stiffness) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >= 0.0f, "PxArticulationTendon::setStiffness: spring coefficient must be >= 0!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxArticulationTendon::setStiffness() not allowed while simulation is running. Call will be ignored.") if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getStiffness(); } void NpArticulationSpatialTendon::setDamping(const PxReal damping) { PX_CHECK_AND_RETURN(PxIsFinite(damping) && damping >= 0.0f, "PxArticulationTendon::setDamping: damping coefficient must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setDamping(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setDamping(damping); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getDamping() const { NP_READ_CHECK(getNpScene()); return mCore.getDamping(); } void NpArticulationSpatialTendon::setLimitStiffness(const PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >= 0.0f, "PxArticulationTendon::setLimitStiffness: stiffness must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setLimitStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimitStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getLimitStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getLimitStiffness(); } void NpArticulationSpatialTendon::setOffset(const PxReal offset, bool autowake) { PX_CHECK_AND_RETURN(PxIsFinite(offset), "PxArticulationTendon::setOffset(): invalid value provided!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::setOffset(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); if (autowake && getNpScene()) mArticulation->autoWakeInternal(); mCore.setOffset(offset); UPDATE_PVD_PROPERTY } PxReal NpArticulationSpatialTendon::getOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getOffset(); } PxArticulationReducedCoordinate* physx::NpArticulationSpatialTendon::getArticulation() const { return mArticulation; } void NpArticulationSpatialTendon::release() { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSpatialTendon::release() not allowed while the articulation is in a scene. Call will be ignored."); return; } PxArray<NpArticulationSpatialTendon*>& spatialTendons = mArticulation->getSpatialTendons(); spatialTendons.back()->setHandle(mHandle); spatialTendons.replaceWithLast(mHandle); this->~NpArticulationSpatialTendon(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } NpArticulationAttachment* NpArticulationSpatialTendon::getAttachment(const PxU32 index) { return mAttachments[index]; } PxU32 NpArticulationSpatialTendon::getNbAttachments() const { return mAttachments.size(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PX_SERIALIZATION void NpArticulationTendonJoint::requiresObjects(PxProcessPxBaseCallback& c) { // Collect articulation links const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) c.process(*mChildren[i]); } void NpArticulationTendonJoint::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mChildren, stream); } void NpArticulationTendonJoint::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mChildren, context); } void NpArticulationTendonJoint::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mLink); context.translatePxBase(mParent); const PxU32 nbChildren = mChildren.size(); for (PxU32 i = 0; i < nbChildren; i++) { NpArticulationTendonJoint*& tendonJoint = mChildren[i]; context.translatePxBase(tendonJoint); } context.translatePxBase(mTendon); mCore.mParent = mParent ? &static_cast<NpArticulationTendonJoint*>(mParent)->mCore : NULL; } NpArticulationTendonJoint* NpArticulationTendonJoint::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationTendonJoint* obj = PX_PLACEMENT_NEW(address, NpArticulationTendonJoint(PxBaseFlags(0))); address += sizeof(NpArticulationTendonJoint); obj->importExtraData(context); obj->resolveReferences(context); return obj; } // ~PX_SERIALIZATION NpArticulationTendonJoint::NpArticulationTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) : PxArticulationTendonJoint(PxConcreteType::eARTICULATION_TENDON_JOINT, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_TENDON_JOINT) { NpArticulationTendonJoint* npParent = static_cast<NpArticulationTendonJoint*>(parent); mCore.mParent = parent ? &npParent->getCore() : NULL; mCore.mLLTendonJointIndex = 0xffffffff; mCore.coefficient = coefficient; mCore.recipCoefficient = recipCoefficient; mCore.axis = axis; mCore.mTendonSim = NULL; mLink = link; mParent = parent; mTendon = NULL; mHandle = 0xffffffff; } PxArticulationFixedTendon* physx::NpArticulationTendonJoint::getTendon() const { return mTendon; } void NpArticulationTendonJoint::setCoefficient(const PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient) { PX_CHECK_AND_RETURN(PxIsFinite(coefficient), "PxArticulationTendonJoint::setCoefficient :: Error: NaN or Inf joint coefficient provided!"); PX_CHECK_AND_RETURN(PxIsFinite(recipCoefficient), "PxArticulationTendonJoint::setCoefficient :: Error: NaN or Inf joint recipCoefficient provided!"); NpScene* npScene = mTendon ? mTendon->getNpScene() : NULL; if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationTendonJoint::setCoefficient(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } mCore.coefficient = coefficient; mCore.recipCoefficient = recipCoefficient; if (mCore.mTendonSim) { mCore.mTendonSim->setTendonJointCoefficient(mCore, axis, coefficient, recipCoefficient); } } void NpArticulationTendonJoint::getCoefficient(PxArticulationAxis::Enum& axis, PxReal& coefficient, PxReal& recipCoefficient) const { mCore.getCoefficient(axis, coefficient, recipCoefficient); } void NpArticulationTendonJoint::release() { if (mTendon->getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationTendonJoint::release() not allowed while the articulation is in the scene. Call will be ignored."); return; } PX_CHECK_AND_RETURN(getNumChildren() == 0, "PxArticulationTendonJoint::release() can only release leaf tendon joints, i.e. joints with zero children."); NpArticulationTendonJointArray& tendonJoints = mTendon->getTendonJoints(); //remove this joint from the parent NpArticulationTendonJoint* npParentJoint = static_cast<NpArticulationTendonJoint*>(mParent); if (npParentJoint) npParentJoint->removeChild(this); tendonJoints.back()->mHandle = mHandle; tendonJoints.replaceWithLast(mHandle); this->~NpArticulationTendonJoint(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } // PX_SERIALIZATION void NpArticulationFixedTendon::requiresObjects(PxProcessPxBaseCallback& c) { const PxU32 nbTendonJoints = mTendonJoints.size(); for (PxU32 i = 0; i < nbTendonJoints; i++) c.process(*mTendonJoints[i]); } void NpArticulationFixedTendon::exportExtraData(PxSerializationContext& stream) { Cm::exportInlineArray(mTendonJoints, stream); } void NpArticulationFixedTendon::importExtraData(PxDeserializationContext& context) { Cm::importInlineArray(mTendonJoints, context); } void NpArticulationFixedTendon::resolveReferences(PxDeserializationContext& context) { const PxU32 nbTendonJoints = mTendonJoints.size(); for (PxU32 i = 0; i < nbTendonJoints; i++) { NpArticulationTendonJoint*& tendonJoint = mTendonJoints[i]; context.translatePxBase(tendonJoint); } context.translatePxBase(mArticulation); } NpArticulationFixedTendon* NpArticulationFixedTendon::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationFixedTendon* obj = PX_PLACEMENT_NEW(address, NpArticulationFixedTendon(PxBaseFlags(0))); address += sizeof(NpArticulationFixedTendon); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationFixedTendon::NpArticulationFixedTendon(NpArticulationReducedCoordinate* articulation) : PxArticulationFixedTendon(PxConcreteType::eARTICULATION_FIXED_TENDON, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_FIXED_TENDON), mArticulation(articulation) { mLLIndex = 0xffffffff; mHandle = 0xffffffff; } NpArticulationFixedTendon::~NpArticulationFixedTendon() { for (PxU32 i = 0; i < mTendonJoints.size(); ++i) { if (mTendonJoints[i]) { mTendonJoints[i]->~NpArticulationTendonJoint(); if (mTendonJoints[i]->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { PX_FREE(mTendonJoints[i]); } } } } void NpArticulationFixedTendon::release() { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::release() not allowed while the articulation is in a scene. Call will be ignored."); return; } PxArray<NpArticulationFixedTendon*>& fixedTendons = mArticulation->getFixedTendons(); fixedTendons.back()->setHandle(mHandle); fixedTendons.replaceWithLast(mHandle); this->~NpArticulationFixedTendon(); if (mBaseFlags & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } PxArticulationTendonJoint* NpArticulationFixedTendon::createTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) { if(getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::createTendonJoint() not allowed while the articulation is in the scene. Call will be ignored."); return NULL; } PX_CHECK_AND_RETURN_NULL(link, "PxArticulationFixedTendon::createTendonJoint: Null pointer link provided. Need valid link."); PX_CHECK_AND_RETURN_NULL(&link->getArticulation() == getArticulation(), "PxArticulationFixedTendon::createTendonJoint: Link from another articulation provided. Need valid link from same articulation."); #if PX_CHECKED if (parent) { PX_CHECK_AND_RETURN_NULL(parent->getTendon() == this, "PxArticulationFixedTendon::createTendonJoint: Parent tendon joint from another tendon provided. Need valid parent from same tendon."); PX_CHECK_AND_RETURN_NULL(parent->getLink() != link, "PxArticulationFixedTendon::createTendonJoint :: Error: Parent link and child link are the same link!"); PX_CHECK_AND_RETURN_NULL(parent->getLink()== (&link->getInboundJoint()->getParentArticulationLink()), "PxArticulationFixedTendon::createTendonJoint :: Error: Link referenced by parent tendon joint must be the parent of the child link!"); } #endif void* npTendonJointtMem = PX_ALLOC(sizeof(NpArticulationTendonJoint), "NpArticulationTendonJoint"); PxMarkSerializedMemory(npTendonJointtMem, sizeof(NpArticulationTendonJoint)); NpArticulationTendonJoint* npTendonJoint = PX_PLACEMENT_NEW(npTendonJointtMem, NpArticulationTendonJoint)(parent, axis, coefficient, recipCoefficient, link); if (npTendonJoint) { NpArticulationTendonJoint* parentTendonJoint = static_cast<NpArticulationTendonJoint*>(parent); npTendonJoint->setTendon(this); if (parentTendonJoint) { parentTendonJoint->mChildren.pushBack(npTendonJoint); npTendonJoint->mParent = parent; } else { npTendonJoint->mParent = NULL; } npTendonJoint->mHandle = mTendonJoints.size(); mTendonJoints.pushBack(npTendonJoint); } return npTendonJoint; } PxU32 NpArticulationFixedTendon::getTendonJoints(PxArticulationTendonJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(mArticulation->getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mTendonJoints.begin(), mTendonJoints.size()); } void NpArticulationFixedTendon::setStiffness(const PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >= 0.0f, "PxArticulationTendon::setStiffness: spring coefficient must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getStiffness(); } void NpArticulationFixedTendon::setDamping(const PxReal damping) { PX_CHECK_AND_RETURN(PxIsFinite(damping) && damping >= 0.0f, "PxArticulationTendon::setDamping: damping coefficient must be >= 0!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setDamping(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setDamping(damping); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getDamping() const { NP_READ_CHECK(getNpScene()); return mCore.getDamping(); } void NpArticulationFixedTendon::setLimitStiffness(const PxReal stiffness) { PX_CHECK_AND_RETURN(PxIsFinite(stiffness) && stiffness >=0.f , "PxArticulationTendon::setLimitStiffness: stiffness must have valid value!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setLimitStiffness(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimitStiffness(stiffness); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getLimitStiffness() const { NP_READ_CHECK(getNpScene()); return mCore.getLimitStiffness(); } void NpArticulationFixedTendon::setRestLength(const PxReal restLength) { PX_CHECK_AND_RETURN(PxIsFinite(restLength) , "PxArticulationTendon::setRestLength: restLength must have valid value!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setRestLength(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setSpringRestLength(restLength); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getRestLength() const { NP_READ_CHECK(getNpScene()); return mCore.getSpringRestLength(); } void NpArticulationFixedTendon::setLimitParameters(const PxArticulationTendonLimit& parameter) { PX_CHECK_AND_RETURN(PxIsFinite(parameter.lowLimit) && PxIsFinite(parameter.highLimit) && (parameter.lowLimit <= parameter.highLimit), "PxArticulationFixedTendon::setLimitParameters: lowLimit and highLimit must have valid values and lowLimit must be less than highLimit!"); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setLimitParameters(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimitRange(parameter.lowLimit, parameter.highLimit); UPDATE_PVD_PROPERTY } PxArticulationTendonLimit NpArticulationFixedTendon::getLimitParameters() const { NP_READ_CHECK(getNpScene()); PxArticulationTendonLimit parameter; mCore.getLimitRange(parameter.lowLimit, parameter.highLimit); return parameter; } NpArticulationTendonJoint* NpArticulationFixedTendon::getTendonJoint(const PxU32 index) { return mTendonJoints[index]; } PxU32 NpArticulationFixedTendon::getNbTendonJoints() const { return mTendonJoints.size(); } void NpArticulationFixedTendon::setOffset(const PxReal offset, bool autowake) { PX_CHECK_AND_RETURN(PxIsFinite(offset), "PxArticulationTendon::setOffset(): invalid value provided!"); PX_ASSERT(!isAPIWriteForbidden()); if (getNpScene() && (getNpScene()->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && getNpScene()->isDirectGPUAPIInitialized()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationFixedTendon::setOffset(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); } if (autowake && getNpScene()) mArticulation->autoWakeInternal(); mCore.setOffset(offset); UPDATE_PVD_PROPERTY } PxReal NpArticulationFixedTendon::getOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getOffset(); } PxArticulationReducedCoordinate* physx::NpArticulationFixedTendon::getArticulation() const { return mArticulation; } void NpArticulationTendonJoint::removeChild(NpArticulationTendonJoint* child) { for(PxU32 i = 0; i < mChildren.size(); ++i) { if(mChildren[i] == child) { mChildren.replaceWithLast(i); break; } } }
32,073
C++
34.717149
273
0.775356
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpCheck.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 NP_CHECK_H #define NP_CHECK_H #include "foundation/PxSimpleTypes.h" namespace physx { class NpScene; // RAII wrapper around the PxScene::startRead() method, note that this // object does not acquire any scene locks, it is an error checking only mechanism class NpReadCheck { public: NpReadCheck(const NpScene* scene, const char* functionName); ~NpReadCheck(); private: const NpScene* mScene; const char* mName; PxU32 mErrorCount; }; // RAII wrapper around the PxScene::startWrite() method, note that this // object does not acquire any scene locks, it is an error checking only mechanism class NpWriteCheck { public: NpWriteCheck(NpScene* scene, const char* functionName, bool allowReentry=true); ~NpWriteCheck(); private: NpScene* mScene; const char* mName; bool mAllowReentry; PxU32 mErrorCount; }; #if (PX_DEBUG || PX_CHECKED) // Creates a scoped read check object that detects whether appropriate scene locks // have been acquired and checks if reads/writes overlap, this macro should typically // be placed at the beginning of any const API methods that are not multi-thread safe, // the error conditions checked can be summarized as: // 1. PxSceneFlag::eREQUIRE_RW_LOCK was specified but PxScene::lockRead() was not yet called // 2. Other threads were already writing, or began writing during the object lifetime #define NP_READ_CHECK(npScenePtr) NpReadCheck npReadCheck(static_cast<const NpScene*>(npScenePtr), __FUNCTION__); // Creates a scoped write check object that detects whether appropriate scene locks // have been acquired and checks if reads/writes overlap, this macro should typically // be placed at the beginning of any non-const API methods that are not multi-thread safe. // By default re-entrant write calls by the same thread are allowed, the error conditions // checked can be summarized as: // 1. PxSceneFlag::eREQUIRE_RW_LOCK was specified but PxScene::lockWrite() was not yet called // 2. Other threads were already reading, or began reading during the object lifetime // 3. Other threads were already writing, or began writing during the object lifetime #define NP_WRITE_CHECK(npScenePtr) NpWriteCheck npWriteCheck(npScenePtr, __FUNCTION__); // Creates a scoped write check object that disallows re-entrant writes, this is used by // the NpScene::simulate method to detect when callbacks make write calls to the API #define NP_WRITE_CHECK_NOREENTRY(npScenePtr) NpWriteCheck npWriteCheck(npScenePtr, __FUNCTION__, false); #else #define NP_READ_CHECK(npScenePtr) #define NP_WRITE_CHECK(npScenePtr) #define NP_WRITE_CHECK_NOREENTRY(npScenePtr) #endif /* PT: suggested ordering for Np-level checks & macros: PX_PROFILE_ZONE(...); NP_WRITE_CHECK(...); PX_CHECK_AND_RETURN_XXX(...); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(...); PX_SIMD_GUARD; Current rationale: - profile zone first to include the cost of the checks in the profiling results. - NP_WRITE_CHECK before PX_CHECK macros. I tried both and the DLL size is smaller with NP_WRITE_CHECK macros first. - PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL after PX_CHECK_AND_RETURN macros, because contrary to the others these macros don't vanish in Release builds. So we want to group together NP_WRITE_CHECK and PX_CHECK_AND_RETURN macros (the ones that do vanish). That way we can eventually skip them with a runtime flag. - PX_SIMD_GUARD last. No need to take the guard before the PX_CHECK_SCENE_API are done, it would only generate more guard dtor code when the macro eary exits. */ } #endif
5,267
C
41.829268
120
0.762104
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationJointReducedCoordinate.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 NP_ARTICULATION_JOINT_RC_H #define NP_ARTICULATION_JOINT_RC_H #include "PxArticulationJointReducedCoordinate.h" #include "ScArticulationJointCore.h" #include "NpArticulationLink.h" #include "NpBase.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif namespace physx { class NpScene; class NpArticulationLink; class NpArticulationJointReducedCoordinate : public PxArticulationJointReducedCoordinate, public NpBase { public: // PX_SERIALIZATION NpArticulationJointReducedCoordinate(PxBaseFlags baseFlags) : PxArticulationJointReducedCoordinate(baseFlags), NpBase(PxEmpty), mCore(PxEmpty) {} void preExportDataReset() { mCore.preExportDataReset(); } virtual void resolveReferences(PxDeserializationContext& context); static NpArticulationJointReducedCoordinate* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&) {} virtual bool isSubordinate() const { return true; } //~PX_SERIALIZATION NpArticulationJointReducedCoordinate(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame); virtual ~NpArticulationJointReducedCoordinate(); //--------------------------------------------------------------------------------- // PxArticulationJoint implementation //--------------------------------------------------------------------------------- virtual void setJointType(PxArticulationJointType::Enum jointType); virtual PxArticulationJointType::Enum getJointType() const; virtual void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion); virtual PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const; virtual void setFrictionCoefficient(const PxReal coefficient); virtual PxReal getFrictionCoefficient() const; virtual void setMaxJointVelocity(const PxReal maxJointV); virtual PxReal getMaxJointVelocity() const; virtual void setLimitParams(PxArticulationAxis::Enum axis, const PxArticulationLimit& pair); virtual PxArticulationLimit getLimitParams(PxArticulationAxis::Enum axis) const; virtual void setDriveParams(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive); virtual PxArticulationDrive getDriveParams(PxArticulationAxis::Enum axis) const; virtual void setDriveTarget(PxArticulationAxis::Enum axis, const PxReal target, bool autowake = true); virtual PxReal getDriveTarget(PxArticulationAxis::Enum axis) const; virtual void setDriveVelocity(PxArticulationAxis::Enum axis, const PxReal targetVel, bool autowake = true); virtual PxReal getDriveVelocity(PxArticulationAxis::Enum axis) const; virtual void setArmature(PxArticulationAxis::Enum axis, const PxReal armature); virtual PxReal getArmature(PxArticulationAxis::Enum axis) const; virtual void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos); virtual PxReal getJointPosition(PxArticulationAxis::Enum axis) const; virtual void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel); virtual PxReal getJointVelocity(PxArticulationAxis::Enum axis) const; void release(); PX_FORCE_INLINE Sc::ArticulationJointCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpArticulationJointReducedCoordinate, mCore); } PX_INLINE void scSetParentPose(const PxTransform& v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setParentPose(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetChildPose(const PxTransform& v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setChildPose(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetJointType(PxArticulationJointType::Enum v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setJointType(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetFrictionCoefficient(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setFrictionCoefficient(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetMaxJointVelocity(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMaxJointVelocity(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& pair) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setLimit(axis, pair); UPDATE_PVD_PROPERTY } PX_INLINE void scSetDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setDrive(axis, drive); UPDATE_PVD_PROPERTY } PX_INLINE void scSetDriveTarget(PxArticulationAxis::Enum axis, PxReal targetP) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setTargetP(axis, targetP); UPDATE_PVD_PROPERTY } PX_INLINE void scSetDriveVelocity(PxArticulationAxis::Enum axis, PxReal targetP) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setTargetV(axis, targetP); UPDATE_PVD_PROPERTY } PX_INLINE void scSetArmature(PxArticulationAxis::Enum axis, PxReal armature) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setArmature(axis, armature); UPDATE_PVD_PROPERTY } PX_INLINE void scSetMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMotion(axis, motion); UPDATE_PVD_PROPERTY } PX_INLINE void scSetJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setJointPosition(axis, jointPos); UPDATE_PVD_PROPERTY } PX_INLINE void scSetJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setJointVelocity(axis, jointVel); UPDATE_PVD_PROPERTY } virtual PxArticulationLink& getParentArticulationLink() const { return *mParent; } virtual PxArticulationLink& getChildArticulationLink() const { return *mChild; } virtual PxTransform getParentPose() const; virtual void setParentPose(const PxTransform& t); virtual PxTransform getChildPose() const; virtual void setChildPose(const PxTransform& t); PX_INLINE const NpArticulationLink& getParent() const { return *mParent; } PX_INLINE NpArticulationLink& getParent() { return *mParent; } PX_INLINE const NpArticulationLink& getChild() const { return *mChild; } PX_INLINE NpArticulationLink& getChild() { return *mChild; } Sc::ArticulationJointCore mCore; NpArticulationLink* mParent; NpArticulationLink* mChild; #if PX_CHECKED private: bool isValidMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion); #endif }; } #endif
8,893
C
38.353982
168
0.727988
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPvdSceneClient.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 NP_SCENE_PVD_CLIENT_H #define NP_SCENE_PVD_CLIENT_H #include "PxPhysXConfig.h" #if PX_SUPPORT_PVD #include "foundation/PxStrideIterator.h" #include "pvd/PxPvdTransport.h" #include "pvd/PxPvdSceneClient.h" #include "PvdMetaDataPvdBinding.h" #include "foundation/PxBitMap.h" #include "PxPvdClient.h" #include "PxPvdUserRenderer.h" #include "PsPvd.h" #include "PxsMaterialCore.h" #include "PxsFEMSoftBodyMaterialCore.h" #include "PxsFEMClothMaterialCore.h" #include "PxsPBDMaterialCore.h" #include "PxsFLIPMaterialCore.h" #include "PxsMPMMaterialCore.h" namespace physx { class PxActor; class PxArticulationLink; class PxRenderBuffer; class NpConstraint; class NpShape; class NpAggregate; class NpRigidStatic; class NpRigidDynamic; class NpArticulationLink; class NpArticulationJointReducedCoordinate; class NpArticulationReducedCoordinate; class NpArticulationSpatialTendon; class NpArticulationFixedTendon; class NpArticulationSensor; class NpActor; class NpScene; #if PX_SUPPORT_GPU_PHYSX class NpSoftBody; class NpFEMCloth; class NpPBDParticleSystem; class NpFLIPParticleSystem; class NpMPMParticleSystem; class NpHairSystem; #endif namespace Sc { class ConstraintCore; } namespace Vd { class PvdSceneClient : public PxPvdSceneClient, public PvdClient, public PvdVisualizer { PX_NOCOPY(PvdSceneClient) public: PvdSceneClient(NpScene& scene); virtual ~PvdSceneClient(); // PxPvdSceneClient virtual void setScenePvdFlag(PxPvdSceneFlag::Enum flag, bool value); virtual void setScenePvdFlags(PxPvdSceneFlags flags) { mFlags = flags; } virtual PxPvdSceneFlags getScenePvdFlags() const { return mFlags; } virtual void updateCamera(const char* name, const PxVec3& origin, const PxVec3& up, const PxVec3& target); virtual void drawPoints(const PxDebugPoint* points, PxU32 count); virtual void drawLines(const PxDebugLine* lines, PxU32 count); virtual void drawTriangles(const PxDebugTriangle* triangles, PxU32 count); virtual void drawText(const PxDebugText& text); virtual PvdClient* getClientInternal() { return this; } //~PxPvdSceneClient // pvdClient virtual PvdDataStream* getDataStream() { return mPvdDataStream; } virtual bool isConnected() const { return mIsConnected; } virtual void onPvdConnected(); virtual void onPvdDisconnected(); virtual void flush() {} //~pvdClient PX_FORCE_INLINE bool checkPvdDebugFlag() const { return mIsConnected && (mPvd->getInstrumentationFlags() & PxPvdInstrumentationFlag::eDEBUG); } PX_FORCE_INLINE PxPvdSceneFlags getScenePvdFlagsFast() const { return mFlags; } PX_FORCE_INLINE void setPsPvd(PsPvd* pvd) { mPvd = pvd; } void frameStart(PxReal simulateElapsedTime); void frameEnd(); void updatePvdProperties(); void releasePvdInstance(); void createPvdInstance (const PxActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void updatePvdProperties(const PxActor* actor); void releasePvdInstance (const PxActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void createPvdInstance (const NpActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void updatePvdProperties(const NpActor* actor); void releasePvdInstance (const NpActor* actor); // temporary for deformables and particle systems - sschirm: deformables and particles are gone... void createPvdInstance (const NpRigidDynamic* body); void createPvdInstance (const NpArticulationLink* body); void updatePvdProperties (const NpRigidDynamic* body); void updatePvdProperties (const NpArticulationLink* body); void releasePvdInstance (const NpRigidDynamic* body); void releasePvdInstance (const NpArticulationLink* body); void updateBodyPvdProperties(const NpActor* body); void updateKinematicTarget (const NpActor* body, const PxTransform& p); void createPvdInstance (const NpRigidStatic* rigidStatic); void updatePvdProperties (const NpRigidStatic* rigidStatic); void releasePvdInstance (const NpRigidStatic* rigidStatic); void createPvdInstance (const NpConstraint* constraint); void updatePvdProperties(const NpConstraint* constraint); void releasePvdInstance (const NpConstraint* constraint); void createPvdInstance (const NpArticulationReducedCoordinate* articulation); void updatePvdProperties(const NpArticulationReducedCoordinate* articulation); void releasePvdInstance (const NpArticulationReducedCoordinate* articulation); void createPvdInstance (const NpArticulationJointReducedCoordinate* articulationJoint); void updatePvdProperties(const NpArticulationJointReducedCoordinate* articulationJoint); void releasePvdInstance (const NpArticulationJointReducedCoordinate* articulationJoint); void createPvdInstance(const NpArticulationSpatialTendon* articulationTendon); void updatePvdProperties(const NpArticulationSpatialTendon* articulationTendon); void releasePvdInstance(const NpArticulationSpatialTendon* articulationTendon); void createPvdInstance(const NpArticulationFixedTendon* articulationTendon); void updatePvdProperties(const NpArticulationFixedTendon* articulationTendon); void releasePvdInstance(const NpArticulationFixedTendon* articulationTendon); void createPvdInstance(const NpArticulationSensor* sensor); void updatePvdProperties(const NpArticulationSensor* sensor); void releasePvdInstance(const NpArticulationSensor* sensor); /////////////////////////////////////////////////////////////////////////// void createPvdInstance (const PxsMaterialCore* materialCore); void updatePvdProperties(const PxsMaterialCore* materialCore); void releasePvdInstance (const PxsMaterialCore* materialCore); void createPvdInstance (const PxsFEMSoftBodyMaterialCore* materialCore); void updatePvdProperties(const PxsFEMSoftBodyMaterialCore* materialCore); void releasePvdInstance (const PxsFEMSoftBodyMaterialCore* materialCore); void createPvdInstance (const PxsFEMClothMaterialCore* materialCore); void updatePvdProperties(const PxsFEMClothMaterialCore* materialCore); void releasePvdInstance (const PxsFEMClothMaterialCore* materialCore); void createPvdInstance (const PxsPBDMaterialCore* materialCore); void updatePvdProperties(const PxsPBDMaterialCore* materialCore); void releasePvdInstance (const PxsPBDMaterialCore* materialCore); void createPvdInstance (const PxsFLIPMaterialCore* materialCore); void updatePvdProperties(const PxsFLIPMaterialCore* materialCore); void releasePvdInstance (const PxsFLIPMaterialCore* materialCore); void createPvdInstance (const PxsMPMMaterialCore* materialCore); void updatePvdProperties(const PxsMPMMaterialCore* materialCore); void releasePvdInstance (const PxsMPMMaterialCore* materialCore); /////////////////////////////////////////////////////////////////////////// void createPvdInstance (const NpShape* shape, PxActor& owner); void updateMaterials (const NpShape* shape); void updatePvdProperties (const NpShape* shape); void releaseAndRecreateGeometry (const NpShape* shape); void releasePvdInstance (const NpShape* shape, PxActor& owner); void addBodyAndShapesToPvd (NpRigidDynamic& b); void addStaticAndShapesToPvd (NpRigidStatic& s); void createPvdInstance (const NpAggregate* aggregate); void updatePvdProperties (const NpAggregate* aggregate); void attachAggregateActor (const NpAggregate* aggregate, NpActor* actor); void detachAggregateActor (const NpAggregate* aggregate, NpActor* actor); void releasePvdInstance (const NpAggregate* aggregate); #if PX_SUPPORT_GPU_PHYSX void createPvdInstance(const NpSoftBody* softBody); void updatePvdProperties(const NpSoftBody* softBody); void attachAggregateActor(const NpSoftBody* softBody, NpActor* actor); void detachAggregateActor(const NpSoftBody* softBody, NpActor* actor); void releasePvdInstance(const NpSoftBody* softBody); void createPvdInstance(const NpFEMCloth* femCloth); void updatePvdProperties(const NpFEMCloth* femCloth); void attachAggregateActor(const NpFEMCloth* femCloth, NpActor* actor); void detachAggregateActor(const NpFEMCloth* femCloth, NpActor* actor); void releasePvdInstance(const NpFEMCloth* femCloth); void createPvdInstance(const NpPBDParticleSystem* particleSystem); void updatePvdProperties(const NpPBDParticleSystem* particleSystem); void attachAggregateActor(const NpPBDParticleSystem* particleSystem, NpActor* actor); void detachAggregateActor(const NpPBDParticleSystem* particleSystem, NpActor* actor); void releasePvdInstance(const NpPBDParticleSystem* particleSystem); void createPvdInstance(const NpFLIPParticleSystem* particleSystem); void updatePvdProperties(const NpFLIPParticleSystem* particleSystem); void attachAggregateActor(const NpFLIPParticleSystem* particleSystem, NpActor* actor); void detachAggregateActor(const NpFLIPParticleSystem* particleSystem, NpActor* actor); void releasePvdInstance(const NpFLIPParticleSystem* particleSystem); void createPvdInstance(const NpMPMParticleSystem* particleSystem); void updatePvdProperties(const NpMPMParticleSystem* particleSystem); void attachAggregateActor(const NpMPMParticleSystem* particleSystem, NpActor* actor); void detachAggregateActor(const NpMPMParticleSystem* particleSystem, NpActor* actor); void releasePvdInstance(const NpMPMParticleSystem* particleSystem); void createPvdInstance(const NpHairSystem* hairSystem); void updatePvdProperties(const NpHairSystem* hairSystem); void attachAggregateActor(const NpHairSystem* hairSystem, NpActor* actor); void detachAggregateActor(const NpHairSystem* hairSystem, NpActor* actor); void releasePvdInstance(const NpHairSystem* hairSystem); #endif void originShift(PxVec3 shift); void updateJoints(); void updateContacts(); void updateSceneQueries(); // PvdVisualizer void visualize(PxArticulationLink& link); void visualize(const PxRenderBuffer& debugRenderable); private: void sendEntireScene(); void updateConstraint(const Sc::ConstraintCore& scConstraint, PxU32 updateType); PxPvdSceneFlags mFlags; PsPvd* mPvd; NpScene& mScene; PvdDataStream* mPvdDataStream; PvdMetaDataBinding mMetaDataBinding; PvdUserRenderer* mUserRender; RendererEventClient* mRenderClient; bool mIsConnected; }; } // pvd } // physx #endif // PX_SUPPORT_PVD #endif // NP_SCENE_PVD_CLIENT_H
12,161
C
41.673684
147
0.794096
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpScene.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 NP_SCENE_H #define NP_SCENE_H #define NEW_DIRTY_SHADERS_CODE #include "foundation/PxUserAllocated.h" #include "foundation/PxHashSet.h" #include "foundation/PxSync.h" #include "foundation/PxArray.h" #include "foundation/PxThread.h" #include "PxPhysXConfig.h" #include "CmRenderBuffer.h" #include "CmIDPool.h" #if PX_SUPPORT_GPU_PHYSX #include "device/PhysXIndicator.h" #endif #include "NpSceneQueries.h" #include "NpSceneAccessor.h" #include "NpPruningStructure.h" #if PX_SUPPORT_PVD #include "PxPhysics.h" #include "NpPvdSceneClient.h" #endif #include "ScScene.h" namespace physx { namespace Sc { class Joint; class ConstraintBreakEvent; } namespace Sq { class PrunerManager; } class PhysicsThread; class NpMaterial; class NpScene; class NpArticulationReducedCoordinate; class NpAggregate; class NpObjectFactory; class NpRigidStatic; class NpRigidDynamic; class NpConstraint; class NpArticulationLink; class NpArticulationJointReducedCoordinate; class NpArticulationAttachment; class NpArticulationTendonJoint; class NpArticulationSpatialTendon; class NpArticulationFixedTendon; class NpArticulationSensor; class NpShapeManager; class NpBatchQuery; class NpActor; class NpShape; class NpPhysics; #if PX_SUPPORT_GPU_PHYSX class NpSoftBody; class NpFEMCloth; class NpHairSystem; class NpPBDParticleSystem; class NpFLIPParticleSystem; class NpMPMParticleSystem; class NpFEMSoftBodyMaterial; class NpFEMClothMaterial; class NpPBDMaterial; class NpFLIPMaterial; class NpMPMMaterial; #endif class NpContactCallbackTask : public physx::PxLightCpuTask { NpScene* mScene; const PxContactPairHeader* mContactPairHeaders; uint32_t mNbContactPairHeaders; public: void setData(NpScene* scene, const PxContactPairHeader* contactPairHeaders, const uint32_t nbContactPairHeaders); virtual void run(); virtual const char* getName() const { return "NpContactCallbackTask"; } }; class NpScene : public NpSceneAccessor, public PxUserAllocated { //virtual interfaces: PX_NOCOPY(NpScene) public: virtual void release(); virtual void setFlag(PxSceneFlag::Enum flag, bool value); virtual PxSceneFlags getFlags() const; virtual void setName(const char* name); virtual const char* getName() const; // implement PxScene: virtual void setGravity(const PxVec3&); virtual PxVec3 getGravity() const; virtual void setBounceThresholdVelocity(const PxReal t); virtual PxReal getBounceThresholdVelocity() const; virtual void setMaxBiasCoefficient(const PxReal t); virtual PxReal getMaxBiasCoefficient() const; virtual void setFrictionOffsetThreshold(const PxReal t); virtual PxReal getFrictionOffsetThreshold() const; virtual void setFrictionCorrelationDistance(const PxReal t); virtual PxReal getFrictionCorrelationDistance() const; virtual void setLimits(const PxSceneLimits& limits); virtual PxSceneLimits getLimits() const; virtual bool addActor(PxActor& actor, const PxBVH* bvh); virtual void removeActor(PxActor& actor, bool wakeOnLostTouch); virtual PxU32 getNbConstraints() const; virtual PxU32 getConstraints(PxConstraint** buffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual bool addArticulation(PxArticulationReducedCoordinate&); virtual void removeArticulation(PxArticulationReducedCoordinate&, bool wakeOnLostTouch); virtual PxU32 getNbArticulations() const; virtual PxU32 getArticulations(PxArticulationReducedCoordinate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxU32 getNbSoftBodies() const; virtual PxU32 getSoftBodies(PxSoftBody** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getNbParticleSystems(PxParticleSolverType::Enum type) const; virtual PxU32 getParticleSystems(PxParticleSolverType::Enum type, PxParticleSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getNbFEMCloths() const; virtual PxU32 getFEMCloths(PxFEMCloth** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getNbHairSystems() const; virtual PxU32 getHairSystems(PxHairSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; // Aggregates virtual bool addAggregate(PxAggregate&); virtual void removeAggregate(PxAggregate&, bool wakeOnLostTouch); virtual PxU32 getNbAggregates() const; virtual PxU32 getAggregates(PxAggregate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual bool addCollection(const PxCollection& collection); // Groups virtual void setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance); virtual PxDominanceGroupPair getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const; // Actors virtual PxU32 getNbActors(PxActorTypeFlags types) const; virtual PxU32 getActors(PxActorTypeFlags types, PxActor** buffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxActor** getActiveActors(PxU32& nbActorsOut); // Run virtual void getSimulationStatistics(PxSimulationStatistics& s) const; // Multiclient virtual PxClientID createClient(); // FrictionModel virtual PxFrictionType::Enum getFrictionType() const; // Callbacks virtual void setSimulationEventCallback(PxSimulationEventCallback* callback); virtual PxSimulationEventCallback* getSimulationEventCallback() const; virtual void setContactModifyCallback(PxContactModifyCallback* callback); virtual PxContactModifyCallback* getContactModifyCallback() const; virtual void setCCDContactModifyCallback(PxCCDContactModifyCallback* callback); virtual PxCCDContactModifyCallback* getCCDContactModifyCallback() const; virtual void setBroadPhaseCallback(PxBroadPhaseCallback* callback); virtual PxBroadPhaseCallback* getBroadPhaseCallback() const; //CCD virtual void setCCDMaxPasses(PxU32 ccdMaxPasses); virtual PxU32 getCCDMaxPasses() const; virtual void setCCDMaxSeparation(const PxReal t); virtual PxReal getCCDMaxSeparation() const; virtual void setCCDThreshold(const PxReal t); virtual PxReal getCCDThreshold() const; // Collision filtering virtual void setFilterShaderData(const void* data, PxU32 dataSize); virtual const void* getFilterShaderData() const; virtual PxU32 getFilterShaderDataSize() const; virtual PxSimulationFilterShader getFilterShader() const; virtual PxSimulationFilterCallback* getFilterCallback() const; virtual bool resetFiltering(PxActor& actor); virtual bool resetFiltering(PxRigidActor& actor, PxShape*const* shapes, PxU32 shapeCount); virtual PxPairFilteringMode::Enum getKinematicKinematicFilteringMode() const; virtual PxPairFilteringMode::Enum getStaticKinematicFilteringMode() const; // Get Physics SDK virtual PxPhysics& getPhysics(); // new API methods virtual bool simulate(PxReal elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation); virtual bool advance(physx::PxBaseTask* completionTask); virtual bool collide(PxReal elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation = true); virtual bool checkResults(bool block); virtual bool checkCollision(bool block); virtual bool fetchCollision(bool block); virtual bool fetchResults(bool block, PxU32* errorState); virtual bool fetchResultsStart(const PxContactPairHeader*& contactPairs, PxU32& nbContactPairs, bool block = false); virtual void processCallbacks(physx::PxBaseTask* continuation); virtual void fetchResultsFinish(PxU32* errorState = 0); virtual void flush(bool sendPendingReports) { flushSimulation(sendPendingReports); } virtual void flushSimulation(bool sendPendingReports); virtual const PxRenderBuffer& getRenderBuffer(); virtual void setSolverBatchSize(PxU32 solverBatchSize); virtual PxU32 getSolverBatchSize(void) const; virtual void setSolverArticulationBatchSize(PxU32 solverBatchSize); virtual PxU32 getSolverArticulationBatchSize(void) const; virtual bool setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value); virtual PxReal getVisualizationParameter(PxVisualizationParameter::Enum param) const; virtual void setVisualizationCullingBox(const PxBounds3& box); virtual PxBounds3 getVisualizationCullingBox() const; virtual PxTaskManager* getTaskManager() const { return mTaskManager; } void checkBeginWrite() const {} virtual PxCudaContextManager* getCudaContextManager() { return mCudaContextManager; } virtual void setNbContactDataBlocks(PxU32 numBlocks); virtual PxU32 getNbContactDataBlocksUsed() const; virtual PxU32 getMaxNbContactDataBlocksUsed() const; virtual PxU32 getContactReportStreamBufferSize() const; virtual PxU32 getTimestamp() const; virtual PxCpuDispatcher* getCpuDispatcher() const; virtual PxCudaContextManager* getCudaContextManager() const; virtual PxBroadPhaseType::Enum getBroadPhaseType() const; virtual bool getBroadPhaseCaps(PxBroadPhaseCaps& caps) const; virtual PxU32 getNbBroadPhaseRegions() const; virtual PxU32 getBroadPhaseRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxU32 addBroadPhaseRegion(const PxBroadPhaseRegion& region, bool populateRegion); virtual bool removeBroadPhaseRegion(PxU32 handle); virtual bool addActors(PxActor*const* actors, PxU32 nbActors); virtual bool addActors(const PxPruningStructure& prunerStructure); virtual void removeActors(PxActor*const* actors, PxU32 nbActors, bool wakeOnLostTouch); virtual void lockRead(const char* file=NULL, PxU32 line=0); virtual void unlockRead(); virtual void lockWrite(const char* file=NULL, PxU32 line=0); virtual void unlockWrite(); virtual PxReal getWakeCounterResetValue() const; virtual void shiftOrigin(const PxVec3& shift); virtual PxPvdSceneClient* getScenePvdClient(); virtual void copyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbCopyArticulations, CUevent copyEvent); virtual void applyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbUpdatedArticulations, CUevent waitEvent, CUevent signalEvent); virtual void updateArticulationsKinematic(CUevent signalEvent); virtual void copyContactData(void* data, const PxU32 numContactPatches, void* numContactPairs, CUevent copyEvent); virtual void copySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbCopySoftBodies, const PxU32 maxSize, CUevent copyEvent); virtual void applySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbUpdatedSoftBodies, const PxU32 maxSize, CUevent applyEvent, CUevent signalEvent); virtual void copyBodyData(PxGpuBodyData* data, PxGpuActorPair* index, const PxU32 nbCopyActors, CUevent copyEvent); virtual void applyActorData(void* data, PxGpuActorPair* index, PxActorCacheFlag::Enum flag, const PxU32 nbUpdatedActors, CUevent waitEvent, CUevent signalEvent); virtual void evaluateSDFDistances(const PxU32* sdfShapeIds, const PxU32 nbShapes, const PxVec4* samplePointsConcatenated, const PxU32* samplePointCountPerShape, const PxU32 maxPointCount, PxVec4* localGradientAndSDFConcatenated, CUevent event); virtual void computeDenseJacobians(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void computeGeneralizedMassMatrices(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void computeGeneralizedGravityForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void computeCoriolisAndCentrifugalForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent); virtual void applyParticleBufferData(const PxU32* indices, const PxGpuParticleBufferIndexPair* bufferIndexPairs, const PxParticleBufferFlags* flags, PxU32 nbUpdatedBuffers, CUevent waitEvent, CUevent signalEvent); virtual PxSolverType::Enum getSolverType() const; // NpSceneAccessor virtual PxsSimulationController* getSimulationController(); virtual void setActiveActors(PxActor** actors, PxU32 nbActors); virtual PxActor** getFrozenActors(PxU32& nbActorsOut); virtual void setFrozenActorFlag(const bool buildFrozenActors); virtual void forceSceneQueryRebuild(); virtual void frameEnd(); //~NpSceneAccessor // PxSceneQuerySystemBase virtual void setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint); virtual PxU32 getDynamicTreeRebuildRateHint() const; virtual void forceRebuildDynamicTree(PxU32 prunerIndex); virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode); virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const; virtual PxU32 getStaticTimestamp() const; virtual void flushUpdates(); virtual 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; virtual 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; virtual bool overlap( const PxGeometry& geometry, const PxTransform& transform, // GeomObject data PxOverlapCallback& hitCall, const PxQueryFilterData& filterData, PxQueryFilterCallback* filterCall, const PxQueryCache* cache, PxGeometryQueryFlags flags) const; //~PxSceneQuerySystemBase // PxSceneSQSystem virtual PxPruningStructureType::Enum getStaticStructure() const; virtual PxPruningStructureType::Enum getDynamicStructure() const; virtual void sceneQueriesUpdate(physx::PxBaseTask* completionTask, bool controlSimulation); virtual bool checkQueries(bool block); virtual bool fetchQueries(bool block); //~PxSceneSQSystem public: NpScene(const PxSceneDesc& desc, NpPhysics&); ~NpScene(); PX_FORCE_INLINE NpSceneQueries& getNpSQ() { return mNpSQ; } PX_FORCE_INLINE const NpSceneQueries& getNpSQ() const { return mNpSQ; } PX_FORCE_INLINE PxSceneQuerySystem& getSQAPI() { return mNpSQ.getSQAPI(); } PX_FORCE_INLINE const PxSceneQuerySystem& getSQAPI() const { return mNpSQ.getSQAPI(); } PX_FORCE_INLINE PxU64 getContextId() const { return PxU64(this); } PX_FORCE_INLINE PxTaskManager* getTaskManagerFast() const { return mTaskManager; } PX_FORCE_INLINE Sc::SimulationStage::Enum getSimulationStage() const { return mScene.getSimulationStage(); } PX_FORCE_INLINE void setSimulationStage(Sc::SimulationStage::Enum stage) { mScene.setSimulationStage(stage); } bool addActorInternal(PxActor& actor, const PxBVH* bvh); void removeActorInternal(PxActor& actor, bool wakeOnLostTouch, bool removeFromAggregate); bool addActorsInternal(PxActor*const* PX_RESTRICT actors, PxU32 nbActors, const Sq::PruningStructure* ps = NULL); bool addArticulationInternal(PxArticulationReducedCoordinate&); void removeArticulationInternal(PxArticulationReducedCoordinate&, bool wakeOnLostTouch, bool removeFromAggregate); // materials void addMaterial(const NpMaterial& mat); void updateMaterial(const NpMaterial& mat); void removeMaterial(const NpMaterial& mat); #if PX_SUPPORT_GPU_PHYSX void addMaterial(const NpFEMSoftBodyMaterial& mat); void updateMaterial(const NpFEMSoftBodyMaterial& mat); void removeMaterial(const NpFEMSoftBodyMaterial& mat); void addMaterial(const NpFEMClothMaterial& mat); void updateMaterial(const NpFEMClothMaterial& mat); void removeMaterial(const NpFEMClothMaterial& mat); void addMaterial(const NpPBDMaterial& mat); void updateMaterial(const NpPBDMaterial& mat); void removeMaterial(const NpPBDMaterial& mat); void addMaterial(const NpFLIPMaterial& mat); void updateMaterial(const NpFLIPMaterial& mat); void removeMaterial(const NpFLIPMaterial& mat); void addMaterial(const NpMPMMaterial& mat); void updateMaterial(const NpMPMMaterial& mat); void removeMaterial(const NpMPMMaterial& mat); #endif void executeScene(PxBaseTask* continuation); void executeCollide(PxBaseTask* continuation); void executeAdvance(PxBaseTask* continuation); void constraintBreakEventNotify(PxConstraint *const *constraints, PxU32 count); bool loadFromDesc(const PxSceneDesc&); template<typename T> void removeFromRigidActorList(T&); void removeFromRigidDynamicList(NpRigidDynamic&); void removeFromRigidStaticList(NpRigidStatic&); PX_FORCE_INLINE void removeFromArticulationList(PxArticulationReducedCoordinate&); PX_FORCE_INLINE void removeFromSoftBodyList(PxSoftBody&); PX_FORCE_INLINE void removeFromFEMClothList(PxFEMCloth&); PX_FORCE_INLINE void removeFromParticleSystemList(PxPBDParticleSystem&); PX_FORCE_INLINE void removeFromParticleSystemList(PxFLIPParticleSystem&); PX_FORCE_INLINE void removeFromParticleSystemList(PxMPMParticleSystem&); PX_FORCE_INLINE void removeFromHairSystemList(PxHairSystem&); PX_FORCE_INLINE void removeFromAggregateList(PxAggregate&); #ifdef NEW_DIRTY_SHADERS_CODE void addDirtyConstraint(NpConstraint* constraint); #endif void addToConstraintList(PxConstraint&); void removeFromConstraintList(PxConstraint&); void addArticulationLink(NpArticulationLink& link); void addArticulationLinkBody(NpArticulationLink& link); void addArticulationLinkConstraint(NpArticulationLink& link); void removeArticulationLink(NpArticulationLink& link, bool wakeOnLostTouch); void addArticulationAttachment(NpArticulationAttachment& attachment); void removeArticulationAttachment(NpArticulationAttachment& attachment); void addArticulationTendonJoint(NpArticulationTendonJoint& joint); void removeArticulationTendonJoint(NpArticulationTendonJoint& joint); void removeArticulationTendons(PxArticulationReducedCoordinate& articulation); void removeArticulationSensors(PxArticulationReducedCoordinate& articulation); struct StartWriteResult { enum Enum { eOK, eNO_LOCK, eIN_FETCHRESULTS, eRACE_DETECTED }; }; StartWriteResult::Enum startWrite(bool allowReentry); void stopWrite(bool allowReentry); bool startRead() const; void stopRead() const; PxU32 getReadWriteErrorCount() const { return PxU32(mConcurrentErrorCount); } #if PX_CHECKED void checkPositionSanity(const PxRigidActor& a, const PxTransform& pose, const char* fnName) const; #endif #if PX_SUPPORT_GPU_PHYSX void updatePhysXIndicator(); #else PX_FORCE_INLINE void updatePhysXIndicator() {} #endif void scAddAggregate(NpAggregate&); void scRemoveAggregate(NpAggregate&); void scSwitchRigidToNoSim(NpActor&); void scSwitchRigidFromNoSim(NpActor&); #if PX_SUPPORT_PVD PX_FORCE_INLINE Vd::PvdSceneClient& getScenePvdClientInternal() { return mScenePvdClient; } PX_FORCE_INLINE const Vd::PvdSceneClient& getScenePvdClientInternal() const { return mScenePvdClient; } #endif PX_FORCE_INLINE bool isAPIReadForbidden() const { return mIsAPIReadForbidden; } PX_FORCE_INLINE void setAPIReadToForbidden() { mIsAPIReadForbidden = true; } PX_FORCE_INLINE void setAPIReadToAllowed() { mIsAPIReadForbidden = false; } PX_FORCE_INLINE bool isCollisionPhaseActive() const { return mScene.isCollisionPhaseActive(); } PX_FORCE_INLINE bool isAPIWriteForbidden() const { return mIsAPIWriteForbidden; } PX_FORCE_INLINE void setAPIWriteToForbidden() { mIsAPIWriteForbidden = true; } PX_FORCE_INLINE void setAPIWriteToAllowed() { mIsAPIWriteForbidden = false; } PX_FORCE_INLINE const Sc::Scene& getScScene() const { return mScene; } PX_FORCE_INLINE Sc::Scene& getScScene() { return mScene; } PX_FORCE_INLINE PxU32 getFlagsFast() const { return mScene.getFlags(); } PX_FORCE_INLINE PxReal getWakeCounterResetValueInternal() const { return mWakeCounterResetValue; } PX_FORCE_INLINE bool isDirectGPUAPIInitialized() { return mScene.isDirectGPUAPIInitialized(); } // PT: TODO: consider merging the "sc" methods with the np ones, as we did for constraints void scAddActor(NpRigidStatic&, bool noSim, PxBounds3* uninflatedBounds, const Gu::BVH* bvh); void scRemoveActor(NpRigidStatic&, bool wakeOnLostTouch, bool noSim); void scAddActor(NpRigidDynamic&, bool noSim, PxBounds3* uninflatedBounds, const Gu::BVH* bvh); void scRemoveActor(NpRigidDynamic&, bool wakeOnLostTouch, bool noSim); void scAddActor(NpArticulationLink&, bool noSim, PxBounds3* uninflatedBounds, const Gu::BVH* bvh); void scRemoveActor(NpArticulationLink&, bool wakeOnLostTouch, bool noSim); #if PX_SUPPORT_GPU_PHYSX void scAddSoftBody(NpSoftBody&); void scRemoveSoftBody(NpSoftBody&); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void scAddFEMCloth(NpScene* npScene, NpFEMCloth&); void scRemoveFEMCloth(NpFEMCloth&); #endif void scAddParticleSystem(NpPBDParticleSystem&); void scRemoveParticleSystem(NpPBDParticleSystem&); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void scAddParticleSystem(NpFLIPParticleSystem&); void scRemoveParticleSystem(NpFLIPParticleSystem&); void scAddParticleSystem(NpMPMParticleSystem&); void scRemoveParticleSystem(NpMPMParticleSystem&); #endif void scAddHairSystem(NpHairSystem&); void scRemoveHairSystem(NpHairSystem&); #endif void scAddArticulation(NpArticulationReducedCoordinate&); void scRemoveArticulation(NpArticulationReducedCoordinate&); void scAddArticulationJoint(NpArticulationJointReducedCoordinate&); void scRemoveArticulationJoint(NpArticulationJointReducedCoordinate&); void scAddArticulationSpatialTendon(NpArticulationSpatialTendon&); void scRemoveArticulationSpatialTendon(NpArticulationSpatialTendon&); void scAddArticulationFixedTendon(NpArticulationFixedTendon&); void scRemoveArticulationFixedTendon(NpArticulationFixedTendon&); void scAddArticulationSensor(NpArticulationSensor&); void scRemoveArticulationSensor(NpArticulationSensor&); void createInOmniPVD(const PxSceneDesc& desc); PX_FORCE_INLINE void updatePvdProperties() { #if PX_SUPPORT_PVD // PT: TODO: shouldn't we test PxPvdInstrumentationFlag::eDEBUG here? if(mScenePvdClient.isConnected()) mScenePvdClient.updatePvdProperties(); #endif } void updateConstants(const PxArray<NpConstraint*>& constraints); virtual PxgDynamicsMemoryConfig getGpuDynamicsConfig() const { return mGpuDynamicsConfig; } private: bool checkResultsInternal(bool block); bool checkCollisionInternal(bool block); bool checkSceneQueriesInternal(bool block); bool simulateOrCollide(PxReal elapsedTime, physx::PxBaseTask* completionTask, void* scratchBlock, PxU32 scratchBlockSize, bool controlSimulation, const char* invalidCallMsg, Sc::SimulationStage::Enum simStage); bool addRigidStatic(NpRigidStatic& , const Gu::BVH* bvh, const Sq::PruningStructure* ps = NULL); void removeRigidStatic(NpRigidStatic&, bool wakeOnLostTouch, bool removeFromAggregate); bool addRigidDynamic(NpRigidDynamic& , const Gu::BVH* bvh, const Sq::PruningStructure* ps = NULL); void removeRigidDynamic(NpRigidDynamic&, bool wakeOnLostTouch, bool removeFromAggregate); bool addSoftBody(PxSoftBody&); void removeSoftBody(PxSoftBody&, bool wakeOnLostTouch); bool addParticleSystem(PxParticleSystem& particleSystem); void removeParticleSystem(PxParticleSystem& particleSystem, bool wakeOnLostTouch); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION bool addFEMCloth(PxFEMCloth&); void removeFEMCloth(PxFEMCloth&, bool wakeOnLostTouch); bool addHairSystem(PxHairSystem&); void removeHairSystem(PxHairSystem&, bool wakeOnLostTouch); #endif void visualize(); void updateDirtyShaders(); void fetchResultsPreContactCallbacks(); void fetchResultsPostContactCallbacks(); void fetchResultsParticleSystem(); bool addSpatialTendonInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim); bool addFixedTendonInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim); bool addArticulationSensorInternal(NpArticulationReducedCoordinate* npaRC, Sc::ArticulationSim* scArtSim); void syncSQ(); void sceneQueriesStaticPrunerUpdate(PxBaseTask* continuation); void sceneQueriesDynamicPrunerUpdate(PxBaseTask* continuation); void syncMaterialEvents(); NpSceneQueries mNpSQ; PxPruningStructureType::Enum mPrunerType[2]; typedef Cm::DelegateTask<NpScene, &NpScene::sceneQueriesStaticPrunerUpdate> SceneQueriesStaticPrunerUpdate; typedef Cm::DelegateTask<NpScene, &NpScene::sceneQueriesDynamicPrunerUpdate> SceneQueriesDynamicPrunerUpdate; SceneQueriesStaticPrunerUpdate mSceneQueriesStaticPrunerUpdate; SceneQueriesDynamicPrunerUpdate mSceneQueriesDynamicPrunerUpdate; Cm::RenderBuffer mRenderBuffer; public: Cm::IDPool mRigidActorIndexPool; private: PxArray<NpRigidDynamic*> mRigidDynamics; // no hash set used because it would be quite a bit slower when adding a large number of actors PxArray<NpRigidStatic*> mRigidStatics; // no hash set used because it would be quite a bit slower when adding a large number of actors PxCoalescedHashSet<PxArticulationReducedCoordinate*> mArticulations; PxCoalescedHashSet<PxSoftBody*> mSoftBodies; PxCoalescedHashSet<PxFEMCloth*> mFEMCloths; PxCoalescedHashSet<PxPBDParticleSystem*> mPBDParticleSystems; PxCoalescedHashSet<PxFLIPParticleSystem*> mFLIPParticleSystems; PxCoalescedHashSet<PxMPMParticleSystem*> mMPMParticleSystems; PxCoalescedHashSet<PxHairSystem*> mHairSystems; PxCoalescedHashSet<PxAggregate*> mAggregates; #ifdef NEW_DIRTY_SHADERS_CODE PxArray<NpConstraint*> mAlwaysUpdatedConstraints; PxArray<NpConstraint*> mDirtyConstraints; PxMutex mDirtyConstraintsLock; #endif PxBounds3 mSanityBounds; #if PX_SUPPORT_GPU_PHYSX PhysXIndicator mPhysXIndicator; #endif PxSync mPhysicsDone; // physics thread signals this when update ready PxSync mCollisionDone; // physics thread signals this when all collisions ready PxSync mSceneQueriesDone; // physics thread signals this when all scene queries update ready //legacy timing settings: PxReal mElapsedTime; //needed to transfer the elapsed time param from the user to the sim thread. PxU32 mNbClients; // Tracks reserved clients for multiclient support. struct SceneCompletion : public Cm::Task { SceneCompletion(PxU64 contextId, PxSync& sync) : Cm::Task(contextId), mSync(sync){} virtual void runInternal() {} //ML: As soon as mSync.set is called, and the scene is shutting down, //the scene may be deleted. That means this running task may also be deleted. //As such, we call mSync.set() inside release() to avoid a crash because the v-table on this //task might be deleted between the call to runInternal() and release() in the worker thread. virtual void release() { //We cache the continuation pointer because this class may be deleted //as soon as mSync.set() is called if the application releases the scene. PxBaseTask* c = mCont; //once mSync.set(), fetchResults() will be allowed to run. mSync.set(); //Call the continuation task that we cached above. If we use mCont or //any other member variable of this class, there is a small chance //that the variables might have become corrupted if the class //was deleted. if(c) c->removeReference(); } virtual const char* getName() const { return "NpScene.completion"; } // //This method just is called in the split sim approach as a way to set continuation after the task has been initialized void setDependent(PxBaseTask* task){PX_ASSERT(mCont == NULL); mCont = task; if(task)task->addReference();} PxSync& mSync; private: SceneCompletion& operator=(const SceneCompletion&); }; typedef Cm::DelegateTask<NpScene, &NpScene::executeScene> SceneExecution; typedef Cm::DelegateTask<NpScene, &NpScene::executeCollide> SceneCollide; typedef Cm::DelegateTask<NpScene, &NpScene::executeAdvance> SceneAdvance; PxTaskManager* mTaskManager; PxCudaContextManager* mCudaContextManager; SceneCompletion mSceneCompletion; SceneCompletion mCollisionCompletion; SceneCompletion mSceneQueriesCompletion; SceneExecution mSceneExecution; SceneCollide mSceneCollide; SceneAdvance mSceneAdvance; PxSQBuildStepHandle mStaticBuildStepHandle; PxSQBuildStepHandle mDynamicBuildStepHandle; bool mControllingSimulation; bool mIsAPIReadForbidden; // Set to true when the user is not allowed to call certain read APIs // (properties that get written to during the simulation. Search the macros PX_CHECK_SCENE_API_READ_FORBIDDEN... // to see which calls) bool mIsAPIWriteForbidden; // Set to true when the user is not allowed to do API write calls PxU32 mSimThreadStackSize; volatile PxI32 mConcurrentWriteCount; mutable volatile PxI32 mConcurrentReadCount; mutable volatile PxI32 mConcurrentErrorCount; // TLS slot index, keeps track of re-entry depth for this thread PxU32 mThreadReadWriteDepth; PxThread::Id mCurrentWriter; PxReadWriteLock mRWLock; bool mSQUpdateRunning; bool mBetweenFetchResults; bool mBuildFrozenActors; // public: enum MATERIAL_EVENT { MATERIAL_ADD, MATERIAL_UPDATE, MATERIAL_REMOVE }; class MaterialEvent { public: PX_FORCE_INLINE MaterialEvent(PxU16 handle, MATERIAL_EVENT type) : mHandle(handle), mType(type) {} PX_FORCE_INLINE MaterialEvent() {} PxU16 mHandle;//handle to the master material table MATERIAL_EVENT mType; }; private: PxArray<MaterialEvent> mSceneMaterialBuffer; PxArray<MaterialEvent> mSceneFEMSoftBodyMaterialBuffer; PxArray<MaterialEvent> mSceneFEMClothMaterialBuffer; PxArray<MaterialEvent> mScenePBDMaterialBuffer; PxArray<MaterialEvent> mSceneFLIPMaterialBuffer; PxArray<MaterialEvent> mSceneMPMMaterialBuffer; PxMutex mSceneMaterialBufferLock; PxMutex mSceneFEMSoftBodyMaterialBufferLock; PxMutex mSceneFEMClothMaterialBufferLock; PxMutex mScenePBDMaterialBufferLock; PxMutex mSceneFLIPMaterialBufferLock; PxMutex mSceneMPMMaterialBufferLock; Sc::Scene mScene; #if PX_SUPPORT_PVD Vd::PvdSceneClient mScenePvdClient; #endif const PxReal mWakeCounterResetValue; PxgDynamicsMemoryConfig mGpuDynamicsConfig; NpPhysics& mPhysics; const char* mName; }; template<> PX_FORCE_INLINE void NpScene::removeFromRigidActorList<NpRigidDynamic>(NpRigidDynamic& rigidDynamic) { removeFromRigidDynamicList(rigidDynamic); } template<> PX_FORCE_INLINE void NpScene::removeFromRigidActorList<NpRigidStatic>(NpRigidStatic& rigidStatic) { removeFromRigidStaticList(rigidStatic); } PX_FORCE_INLINE void NpScene::removeFromArticulationList(PxArticulationReducedCoordinate& articulation) { const bool exists = mArticulations.erase(&articulation); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromSoftBodyList(PxSoftBody& softBody) { const bool exists = mSoftBodies.erase(&softBody); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromFEMClothList(PxFEMCloth& femCloth) { const bool exists = mFEMCloths.erase(&femCloth); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromParticleSystemList(PxPBDParticleSystem& particleSystem) { const bool exists = mPBDParticleSystems.erase(&particleSystem); PX_ASSERT(exists); PX_UNUSED(exists); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PX_FORCE_INLINE void NpScene::removeFromParticleSystemList(PxFLIPParticleSystem& particleSystem) { const bool exists = mFLIPParticleSystems.erase(&particleSystem); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromParticleSystemList(PxMPMParticleSystem& particleSystem) { const bool exists = mMPMParticleSystems.erase(&particleSystem); PX_ASSERT(exists); PX_UNUSED(exists); } #endif PX_FORCE_INLINE void NpScene::removeFromHairSystemList(PxHairSystem& hairSystem) { const bool exists = mHairSystems.erase(&hairSystem); PX_ASSERT(exists); PX_UNUSED(exists); } PX_FORCE_INLINE void NpScene::removeFromAggregateList(PxAggregate& aggregate) { const bool exists = mAggregates.erase(&aggregate); PX_ASSERT(exists); PX_UNUSED(exists); } PxU32 NpRigidStaticGetShapes(NpRigidStatic& rigid, NpShape* const *& shapes); PxU32 NpRigidDynamicGetShapes(NpRigidDynamic& actor, NpShape* const *& shapes, bool* isCompound = NULL); PxU32 NpArticulationGetShapes(NpArticulationLink& actor, NpShape* const *& shapes, bool* isCompound = NULL); } #endif
37,619
C
43.679335
253
0.730987
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSceneFetchResults.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 "NpScene.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationTendon.h" #include "NpArticulationSensor.h" #include "NpAggregate.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #include "NpFEMCloth.h" #include "NpHairSystem.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #endif #include "ScArticulationSim.h" #include "ScArticulationTendonSim.h" #include "CmCollection.h" #include "PxsSimulationController.h" #include "common/PxProfileZone.h" #include "BpBroadPhase.h" #include "BpAABBManagerBase.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// using namespace physx; bool NpScene::checkResultsInternal(bool block) { PX_PROFILE_ZONE("Basic.checkResults", getContextId()); /*if(0 && block) { PxCpuDispatcher* d = mTaskManager->getCpuDispatcher(); while(!mPhysicsDone.wait(0)) { PxBaseTask* nextTask = d->fetchNextTask(); if(nextTask) { PX_PROFILE_ZONE(nextTask->getName(), getContextId()); nextTask->run(); nextTask->release(); } } }*/ return mPhysicsDone.wait(block ? PxSync::waitForever : 0); } bool NpScene::checkResults(bool block) { return checkResultsInternal(block); } void NpScene::fetchResultsParticleSystem() { mScene.getSimulationController()->syncParticleData(); } // The order of the following operations is important! // 1. Mark the simulation as not running internally to allow reading data which should not be read otherwise // 2. Fire callbacks with latest state. void NpScene::fetchResultsPreContactCallbacks() { #if PX_SUPPORT_PVD mScenePvdClient.updateContacts(); #endif mScene.endSimulation(); setAPIReadToAllowed(); { PX_PROFILE_ZONE("Sim.fireCallbacksPreSync", getContextId()); { PX_PROFILE_ZONE("Sim.fireOutOfBoundsCallbacks", getContextId()); if(mScene.fireOutOfBoundsCallbacks()) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "At least one object is out of the broadphase bounds. To manage those objects, define a PxBroadPhaseCallback for each used client."); } mScene.fireBrokenConstraintCallbacks(); mScene.fireTriggerCallbacks(); } } void NpScene::fetchResultsPostContactCallbacks() { mScene.postCallbacksPreSync(); syncSQ(); #if PX_SUPPORT_PVD mScenePvdClient.updateSceneQueries(); mNpSQ.getSingleSqCollector().clear(); #endif // fire sleep and wake-up events { PX_PROFILE_ZONE("Sim.fireCallbacksPostSync", getContextId()); mScene.fireCallbacksPostSync(); } mScene.postReportsCleanup(); // build the list of active actors { PX_PROFILE_ZONE("Sim.buildActiveActors", getContextId()); const bool buildActiveActors = (mScene.getFlags() & PxSceneFlag::eENABLE_ACTIVE_ACTORS) || OMNI_PVD_ACTIVE; if (buildActiveActors && mBuildFrozenActors) mScene.buildActiveAndFrozenActors(); else if (buildActiveActors) mScene.buildActiveActors(); } mRenderBuffer.append(mScene.getRenderBuffer()); PX_ASSERT(getSimulationStage() != Sc::SimulationStage::eCOMPLETE); if (mControllingSimulation) mTaskManager->stopSimulation(); setSimulationStage(Sc::SimulationStage::eCOMPLETE); setAPIWriteToAllowed(); mPhysicsDone.reset(); // allow Physics to run again mCollisionDone.reset(); } bool NpScene::fetchResults(bool block, PxU32* errorState) { if(getSimulationStage() != Sc::SimulationStage::eADVANCE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchResults: fetchResults() called illegally! It must be called after advance() or simulate()"); if(!checkResultsInternal(block)) return false; #if PX_SUPPORT_GPU_PHYSX if (mCudaContextManager) { if (mScene.isUsingGpuDynamicsOrBp()) { PxCUresult res = mCudaContextManager->getCudaContext()->getLastError(); if (res) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PhysX Internal CUDA error. Simulation can not continue! Error code %i!\n", PxI32(res)); //outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "PhysX Internal CUDA error. Simulation can not continue!"); if(errorState) *errorState = res; } } } #endif PX_SIMD_GUARD; { // take write check *after* simulation has finished, otherwise // we will block simulation callbacks from using the API // disallow re-entry to detect callbacks making write calls NP_WRITE_CHECK_NOREENTRY(this); // we use cross thread profile here, to show the event in cross thread view // PT: TODO: why do we want to show it in the cross thread view? PX_PROFILE_START_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_ZONE("Sim.fetchResults", getContextId()); fetchResultsPreContactCallbacks(); { // PT: TODO: why a cross-thread event here? PX_PROFILE_START_CROSSTHREAD("Basic.processCallbacks", getContextId()); mScene.fireQueuedContactCallbacks(); PX_PROFILE_STOP_CROSSTHREAD("Basic.processCallbacks", getContextId()); } fetchResultsPostContactCallbacks(); PX_PROFILE_STOP_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_STOP_CROSSTHREAD("Basic.simulate", getContextId()); if(errorState) *errorState = 0; #if PX_SUPPORT_OMNI_PVD OmniPvdPxSampler* omniPvdSampler = NpPhysics::getInstance().mOmniPvdSampler; if (omniPvdSampler && omniPvdSampler->isSampling()) { OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) //send all xforms updated by the sim: PxU32 nActiveActors; PxActor ** activeActors = mScene.getActiveActors(nActiveActors); while (nActiveActors--) { PxActor * a = *activeActors++; if ((a->getType() == PxActorType::eRIGID_STATIC) || (a->getType() == PxActorType::eRIGID_DYNAMIC)) { PxRigidActor* ra = static_cast<PxRigidActor*>(a); PxTransform t = ra->getGlobalPose(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, *ra, t.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, *ra, t.q) if (a->getType() == PxActorType::eRIGID_DYNAMIC) { PxRigidDynamic* rdyn = static_cast<PxRigidDynamic*>(a); PxRigidBody& rb = *static_cast<PxRigidBody*>(a); const PxVec3 linVel = rdyn->getLinearVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, rb, linVel) const PxVec3 angVel = rdyn->getAngularVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, rb, angVel) const PxRigidBodyFlags rFlags = rdyn->getRigidBodyFlags(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, rb, rFlags) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, wakeCounter, *rdyn, rdyn->getWakeCounter()); } } else if (a->getType() == PxActorType::eARTICULATION_LINK) { PxArticulationLink* pxArticulationParentLink = 0; PxArticulationLink* pxArticulationLink = static_cast<PxArticulationLink*>(a); PxArticulationJointReducedCoordinate* pxArticulationJoint = pxArticulationLink->getInboundJoint(); if (pxArticulationJoint) { pxArticulationParentLink = &(pxArticulationJoint->getParentArticulationLink()); PxArticulationJointReducedCoordinate& jcord = *pxArticulationJoint; PxReal vals[PxArticulationAxis::eCOUNT]; for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) vals[ax] = jcord.getJointPosition(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointPosition, jcord, vals, PxArticulationAxis::eCOUNT); for (PxU32 ax = 0; ax < PxArticulationAxis::eCOUNT; ++ax) vals[ax] = jcord.getJointVelocity(static_cast<PxArticulationAxis::Enum>(ax)); OMNI_PVD_SET_ARRAY_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationJointReducedCoordinate, jointVelocity, jcord, vals, PxArticulationAxis::eCOUNT); } physx::PxTransform TArtLinkLocal; if (pxArticulationParentLink) { // TGlobal = TFatherGlobal * TLocal // Inv(TFatherGlobal)* TGlobal = Inv(TFatherGlobal)*TFatherGlobal * TLocal // Inv(TFatherGlobal)* TGlobal = TLocal // TLocal = Inv(TFatherGlobal) * TGlobal //physx::PxTransform TParentGlobal = pxArticulationParentLink->getGlobalPose(); physx::PxTransform TParentGlobalInv = pxArticulationParentLink->getGlobalPose().getInverse(); physx::PxTransform TArtLinkGlobal = pxArticulationLink->getGlobalPose(); // PT:: tag: scalar transform*transform TArtLinkLocal = TParentGlobalInv * TArtLinkGlobal; } else { TArtLinkLocal = pxArticulationLink->getGlobalPose(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxArticulationReducedCoordinate, worldBounds, pxArticulationLink->getArticulation(), pxArticulationLink->getArticulation().getWorldBounds()); } OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, static_cast<PxRigidActor&>(*a), TArtLinkLocal.p) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, static_cast<PxRigidActor&>(*a), TArtLinkLocal.q) const PxVec3 linVel = pxArticulationLink->getLinearVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, static_cast<PxRigidBody&>(*a), linVel) const PxVec3 angVel = pxArticulationLink->getAngularVelocity(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, static_cast<PxRigidBody&>(*a), angVel) const PxRigidBodyFlags rFlags = pxArticulationLink->getRigidBodyFlags(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, static_cast<PxRigidBody&>(*a), rFlags) } const PxBounds3 worldBounds = a->getWorldBounds(); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxActor, worldBounds, *a, worldBounds) // update active actors' joints const PxRigidActor* ra = a->is<PxRigidActor>(); if (ra) { static const PxU32 MAX_CONSTRAINTS = 32; PxConstraint* constraints[MAX_CONSTRAINTS]; PxU32 index = 0; while (true) { PxU32 count = ra->getConstraints(constraints, MAX_CONSTRAINTS, index); for (PxU32 i = 0; i < count; ++i) { const NpConstraint& c = static_cast<const NpConstraint&>(*constraints[i]); PxRigidActor *ra0, *ra1; c.getActors(ra0, ra1); bool ra0static = !ra0 || !!ra0->is<PxRigidStatic>(), ra1static = !ra1 || !!ra1->is<PxRigidStatic>(); // this check is to not update a joint twice if ((ra == ra0 && (ra1static || ra0 > ra1)) || (ra == ra1 && (ra0static || ra1 > ra0))) c.getCore().getPxConnector()->updateOmniPvdProperties(); } if (count == MAX_CONSTRAINTS) { index += MAX_CONSTRAINTS; continue; } break; } } } // send contacts info omniPvdSampler->streamSceneContacts(*this); //end frame omniPvdSampler->sampleScene(this); OMNI_PVD_WRITE_SCOPE_END } #endif } #if PX_SUPPORT_PVD mScenePvdClient.frameEnd(); #endif return true; } bool NpScene::fetchResultsStart(const PxContactPairHeader*& contactPairs, PxU32& nbContactPairs, bool block) { if (getSimulationStage() != Sc::SimulationStage::eADVANCE) return outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxScene::fetchResultsStart: fetchResultsStart() called illegally! It must be called after advance() or simulate()"); if (!checkResultsInternal(block)) return false; PX_SIMD_GUARD; NP_WRITE_CHECK(this); // we use cross thread profile here, to show the event in cross thread view PX_PROFILE_START_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_ZONE("Sim.fetchResultsStart", getContextId()); fetchResultsPreContactCallbacks(); const PxArray<PxContactPairHeader>& pairs = mScene.getQueuedContactPairHeaders(); nbContactPairs = pairs.size(); contactPairs = pairs.begin(); mBetweenFetchResults = true; return true; } void NpContactCallbackTask::setData(NpScene* scene, const PxContactPairHeader* contactPairHeaders, const uint32_t nbContactPairHeaders) { mScene = scene; mContactPairHeaders = contactPairHeaders; mNbContactPairHeaders = nbContactPairHeaders; } void NpContactCallbackTask::run() { PxSimulationEventCallback* callback = mScene->getSimulationEventCallback(); if (!callback) return; mScene->lockRead(); for (uint32_t i = 0; i<mNbContactPairHeaders; ++i) { const PxContactPairHeader& pairHeader = mContactPairHeaders[i]; callback->onContact(pairHeader, pairHeader.pairs, pairHeader.nbPairs); } mScene->unlockRead(); } void NpScene::processCallbacks(PxBaseTask* continuation) { PX_PROFILE_START_CROSSTHREAD("Basic.processCallbacks", getContextId()); PX_PROFILE_ZONE("Sim.processCallbacks", getContextId()); //ML: because Apex destruction callback isn't thread safe so that we make this run single thread first const PxArray<PxContactPairHeader>& pairs = mScene.getQueuedContactPairHeaders(); const PxU32 nbPairs = pairs.size(); const PxContactPairHeader* contactPairs = pairs.begin(); const PxU32 nbToProcess = 256; Cm::FlushPool* flushPool = mScene.getFlushPool(); for (PxU32 i = 0; i < nbPairs; i += nbToProcess) { NpContactCallbackTask* task = PX_PLACEMENT_NEW(flushPool->allocate(sizeof(NpContactCallbackTask)), NpContactCallbackTask)(); task->setData(this, contactPairs+i, PxMin(nbToProcess, nbPairs - i)); task->setContinuation(continuation); task->removeReference(); } } void NpScene::fetchResultsFinish(PxU32* errorState) { #if PX_SUPPORT_GPU_PHYSX if (mCudaContextManager) { if (mScene.isUsingGpuDynamicsOrBp()) { PxCUresult res = mCudaContextManager->getCudaContext()->getLastError(); if (res) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PhysX Internal CUDA error. Simulation can not continue! Error code %i!\n", PxI32(res)); //outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "PhysX Internal CUDA error. Simulation can not continue!"); if (errorState) *errorState = mCudaContextManager->getCudaContext()->getLastError(); } } } #endif { PX_SIMD_GUARD; PX_PROFILE_STOP_CROSSTHREAD("Basic.processCallbacks", getContextId()); PX_PROFILE_ZONE("Basic.fetchResultsFinish", getContextId()); mBetweenFetchResults = false; NP_WRITE_CHECK(this); fetchResultsPostContactCallbacks(); if (errorState) *errorState = 0; PX_PROFILE_STOP_CROSSTHREAD("Basic.fetchResults", getContextId()); PX_PROFILE_STOP_CROSSTHREAD("Basic.simulate", getContextId()); #if PX_SUPPORT_OMNI_PVD OmniPvdPxSampler* omniPvdSampler = NpPhysics::getInstance().mOmniPvdSampler; if (omniPvdSampler && omniPvdSampler->isSampling()) { omniPvdSampler->sampleScene(this); } #endif } #if PX_SUPPORT_PVD mScenePvdClient.frameEnd(); #endif }
17,040
C++
35.027484
217
0.726232
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMPMMaterial.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 "NpMPMMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION using namespace physx; using namespace Cm; NpMPMMaterial::NpMPMMaterial(const PxsMPMMaterialCore& desc) : PxMPMMaterial(PxConcreteType::eMPM_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpMPMMaterial::~NpMPMMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpMPMMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: missing line here? } void NpMPMMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseMPMMaterialToPool(*this); } else this->~NpMPMMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpMPMMaterial* NpMPMMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpMPMMaterial* obj = PX_PLACEMENT_NEW(address, NpMPMMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpMPMMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpMPMMaterial::release() { RefCountable_decRefCount(*this); } void NpMPMMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpMPMMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpMPMMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setFriction: invalid float"); mMaterial.friction = x; updateMaterial(); } PxReal NpMPMMaterial::getFriction() const { return mMaterial.friction; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpMPMMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setStretchAndShearDamping(PxReal stretchAndShearDamping) { mMaterial.stretchAndShearDamping = stretchAndShearDamping; updateMaterial(); } PxReal NpMPMMaterial::getStretchAndShearDamping() const { return mMaterial.stretchAndShearDamping; } void NpMPMMaterial::setRotationalDamping(PxReal rotationalDamping) { mMaterial.rotationalDamping = rotationalDamping; updateMaterial(); } PxReal NpMPMMaterial::getRotationalDamping() const { return mMaterial.rotationalDamping; } void NpMPMMaterial::setDensity(PxReal density) { mMaterial.density = density; updateMaterial(); } PxReal NpMPMMaterial::getDensity() const { return mMaterial.density; } void NpMPMMaterial::setMaterialModel(PxMPMMaterialModel::Enum materialModel) { mMaterial.materialModel = materialModel; updateMaterial(); } PxMPMMaterialModel::Enum NpMPMMaterial::getMaterialModel() const { return mMaterial.materialModel; } void NpMPMMaterial::setCuttingFlags(PxMPMCuttingFlags cuttingFlags) { mMaterial.cuttingFlags = cuttingFlags; updateMaterial(); } PxMPMCuttingFlags NpMPMMaterial::getCuttingFlags() const { return mMaterial.cuttingFlags; } void NpMPMMaterial::setSandFrictionAngle(PxReal sandFrictionAngle) { mMaterial.sandFrictionAngle = sandFrictionAngle; updateMaterial(); } PxReal NpMPMMaterial::getSandFrictionAngle() const { return mMaterial.sandFrictionAngle; } void NpMPMMaterial::setYieldStress(PxReal yieldStress) { mMaterial.yieldStress = yieldStress; updateMaterial(); } PxReal NpMPMMaterial::getYieldStress() const { return mMaterial.yieldStress; } void NpMPMMaterial::setIsPlastic(bool x) { mMaterial.isPlastic = x; updateMaterial(); } bool NpMPMMaterial::getIsPlastic() const { return mMaterial.isPlastic != 0; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setYoungsModulus(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setYoungsModulus: invalid float"); mMaterial.youngsModulus = x; updateMaterial(); } PxReal NpMPMMaterial::getYoungsModulus() const { return mMaterial.youngsModulus; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setPoissons(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x <= 0.5f, "PxMPMMaterial::setPoissons: invalid float"); mMaterial.poissonsRatio = x; updateMaterial(); } PxReal NpMPMMaterial::getPoissons() const { return mMaterial.poissonsRatio; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setHardening(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setPoissons: invalid float"); mMaterial.hardening = x; updateMaterial(); } PxReal NpMPMMaterial::getHardening() const { return mMaterial.hardening; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setCriticalCompression(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setCriticalCompression: invalid float"); mMaterial.criticalCompression = x; updateMaterial(); } PxReal NpMPMMaterial::getCriticalCompression() const { return mMaterial.criticalCompression; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setCriticalStretch(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setCriticalStretch: invalid float"); mMaterial.criticalStretch = x; updateMaterial(); } PxReal NpMPMMaterial::getCriticalStretch() const { return mMaterial.criticalStretch; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setTensileDamageSensitivity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setTensileDamageSensitivity: invalid float"); mMaterial.tensileDamageSensitivity = x; updateMaterial(); } PxReal NpMPMMaterial::getTensileDamageSensitivity() const { return mMaterial.tensileDamageSensitivity; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setCompressiveDamageSensitivity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setCompressiveDamageSensitivity: invalid float"); mMaterial.compressiveDamageSensitivity = x; updateMaterial(); } PxReal NpMPMMaterial::getCompressiveDamageSensitivity() const { return mMaterial.compressiveDamageSensitivity; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setAttractiveForceResidual(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setAttractiveForceResidual: invalid float"); mMaterial.attractiveForceResidual = x; updateMaterial(); } PxReal NpMPMMaterial::getAttractiveForceResidual() const { return mMaterial.attractiveForceResidual; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setAdhesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setAdhesion: invalid float"); mMaterial.adhesion = x; updateMaterial(); } PxReal NpMPMMaterial::getAdhesion() const { return mMaterial.adhesion; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setGravityScale(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMPMMaterial::setAdhesion: invalid float"); mMaterial.gravityScale = x; updateMaterial(); } PxReal NpMPMMaterial::getGravityScale() const { return mMaterial.gravityScale; } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::setAdhesionRadiusScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxMPMMaterial::setAdhesionRadiusScale: scale must be positive"); mMaterial.adhesionRadiusScale = x; updateMaterial(); } PxReal NpMPMMaterial::getAdhesionRadiusScale() const { return mMaterial.adhesionRadiusScale; } ////////////////////////////////////////////////////////////////////////////// #endif #endif
10,389
C++
24.218447
102
0.683415
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpActor.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 "NpActor.h" #include "PxRigidActor.h" #include "NpConstraint.h" #include "NpFactory.h" #include "NpShape.h" #include "NpPhysics.h" #include "NpAggregate.h" #include "NpScene.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "CmTransformUtils.h" #include "omnipvd/NpOmniPvdSetData.h" #if PX_SUPPORT_GPU_PHYSX #include "NpSoftBody.h" #include "NpParticleSystem.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "NpHairSystem.h" #include "NpFEMCloth.h" #endif #endif using namespace physx; /////////////////////////////////////////////////////////////////////////////// const Sc::BodyCore* physx::getBodyCore(const PxRigidActor* actor) { const Sc::BodyCore* core = NULL; if(actor) { const PxType type = actor->getConcreteType(); if(type == PxConcreteType::eRIGID_DYNAMIC) { const NpRigidDynamic* dyn = static_cast<const NpRigidDynamic*>(actor); core = &dyn->getCore(); } else if(type == PxConcreteType::eARTICULATION_LINK) { const NpArticulationLink* link = static_cast<const NpArticulationLink*>(actor); core = &link->getCore(); } } return core; } /////////////////////////////////////////////////////////////////////////////// NpActor::NpActor(NpType::Enum type) : NpBase (type), mName (NULL), mConnectorArray (NULL) { } typedef PxHashMap<NpActor*, NpConnectorArray*> ConnectorMap; struct NpActorUserData { PxU32 referenceCount; ConnectorMap* tmpOriginalConnectors; }; void NpActor::exportExtraData(PxSerializationContext& stream) { const PxCollection& collection = stream.getCollection(); if(mConnectorArray) { PxU32 connectorSize = mConnectorArray->size(); PxU32 missedCount = 0; for(PxU32 i = 0; i < connectorSize; ++i) { NpConnector& c = (*mConnectorArray)[i]; PxBase* object = c.mObject; if(!collection.contains(*object)) { ++missedCount; } } NpConnectorArray* exportConnectorArray = mConnectorArray; if(missedCount > 0) { exportConnectorArray = NpFactory::getInstance().acquireConnectorArray(); if(missedCount < connectorSize) { exportConnectorArray->reserve(connectorSize - missedCount); for(PxU32 i = 0; i < connectorSize; ++i) { NpConnector& c = (*mConnectorArray)[i]; PxBase* object = c.mObject; if(collection.contains(*object)) { exportConnectorArray->pushBack(c); } } } } stream.alignData(PX_SERIAL_ALIGN); stream.writeData(exportConnectorArray, sizeof(NpConnectorArray)); Cm::exportInlineArray(*exportConnectorArray, stream); if(missedCount > 0) NpFactory::getInstance().releaseConnectorArray(exportConnectorArray); } stream.writeName(mName); } void NpActor::importExtraData(PxDeserializationContext& context) { if(mConnectorArray) { mConnectorArray = context.readExtraData<NpConnectorArray, PX_SERIAL_ALIGN>(); PX_PLACEMENT_NEW(mConnectorArray, NpConnectorArray(PxEmpty)); if(mConnectorArray->size() == 0) mConnectorArray = NULL; else Cm::importInlineArray(*mConnectorArray, context); } context.readName(mName); } void NpActor::resolveReferences(PxDeserializationContext& context) { // Resolve connector pointers if needed if(mConnectorArray) { const PxU32 nbConnectors = mConnectorArray->size(); for(PxU32 i=0; i<nbConnectors; i++) { NpConnector& c = (*mConnectorArray)[i]; context.translatePxBase(c.mObject); } } } /////////////////////////////////////////////////////////////////////////////// void NpActor::removeConstraints(PxRigidActor& owner) { if(mConnectorArray) { PxU32 nbConnectors = mConnectorArray->size(); PxU32 currentIndex = 0; while(nbConnectors--) { NpConnector& connector = (*mConnectorArray)[currentIndex]; if (connector.mType == NpConnectorType::eConstraint) { NpConstraint* c = static_cast<NpConstraint*>(connector.mObject); c->actorDeleted(&owner); NpScene* s = c->getNpScene(); if(s) s->removeFromConstraintList(*c); removeConnector(owner, currentIndex); } else currentIndex++; } } } void NpActor::removeFromAggregate(PxActor& owner) { if(mConnectorArray) // Need to test again because the code above might purge the connector array if no element remains { PX_ASSERT(mConnectorArray->size() == 1); // At this point only the aggregate should remain PX_ASSERT((*mConnectorArray)[0].mType == NpConnectorType::eAggregate); NpAggregate* a = static_cast<NpAggregate*>((*mConnectorArray)[0].mObject); bool status = a->removeActorAndReinsert(owner, false); PX_ASSERT(status); PX_UNUSED(status); PX_ASSERT(!mConnectorArray); // Remove should happen in aggregate code } PX_ASSERT(!mConnectorArray); // All the connector objects should have been removed at this point } /////////////////////////////////////////////////////////////////////////////// PxU32 NpActor::findConnector(NpConnectorType::Enum type, PxBase* object) const { if(!mConnectorArray) return 0xffffffff; for(PxU32 i=0; i < mConnectorArray->size(); i++) { NpConnector& c = (*mConnectorArray)[i]; if (c.mType == type && c.mObject == object) return i; } return 0xffffffff; } void NpActor::addConnector(NpConnectorType::Enum type, PxBase* object, const char* errMsg) { if(!mConnectorArray) mConnectorArray = NpFactory::getInstance().acquireConnectorArray(); PX_CHECK_MSG(findConnector(type, object) == 0xffffffff, errMsg); PX_UNUSED(errMsg); if(mConnectorArray->isInUserMemory() && mConnectorArray->size() == mConnectorArray->capacity()) { NpConnectorArray* newConnectorArray = NpFactory::getInstance().acquireConnectorArray(); newConnectorArray->assign(mConnectorArray->begin(), mConnectorArray->end()); mConnectorArray->~NpConnectorArray(); mConnectorArray = newConnectorArray; } NpConnector c(type, object); mConnectorArray->pushBack(c); } void NpActor::removeConnector(PxActor& /*owner*/, PxU32 index) { PX_ASSERT(mConnectorArray); PX_ASSERT(index < mConnectorArray->size()); mConnectorArray->replaceWithLast(index); if(mConnectorArray->size() == 0) { if(!mConnectorArray->isInUserMemory()) NpFactory::getInstance().releaseConnectorArray(mConnectorArray); else mConnectorArray->~NpConnectorArray(); mConnectorArray = NULL; } } void NpActor::removeConnector(PxActor& owner, NpConnectorType::Enum type, PxBase* object, const char* errorMsg) { PX_CHECK_MSG(mConnectorArray, errorMsg); PX_UNUSED(errorMsg); if(mConnectorArray) { PxU32 index = findConnector(type, object); PX_CHECK_MSG(index != 0xffffffff, errorMsg); removeConnector(owner, index); } } PxU32 NpActor::getNbConnectors(NpConnectorType::Enum type) const { PxU32 nbConnectors = 0; if(mConnectorArray) { for(PxU32 i=0; i < mConnectorArray->size(); i++) { if ((*mConnectorArray)[i].mType == type) nbConnectors++; } } return nbConnectors; } /////////////////////////////////////////////////////////////////////////////// NpAggregate* NpActor::getNpAggregate(PxU32& index) const { PX_ASSERT(getNbConnectors(NpConnectorType::eAggregate) <= 1); if(mConnectorArray) { // PT: TODO: sort by type to optimize this... for(PxU32 i=0; i < mConnectorArray->size(); i++) { NpConnector& c = (*mConnectorArray)[i]; if (c.mType == NpConnectorType::eAggregate) { index = i; return static_cast<NpAggregate*>(c.mObject); } } } return NULL; } void NpActor::setAggregate(NpAggregate* np, PxActor& owner) { PxU32 index = 0xffffffff; NpAggregate* a = getNpAggregate(index); if (!a) { PX_ASSERT(np); addConnector(NpConnectorType::eAggregate, np, "NpActor::setAggregate() failed"); } else { PX_ASSERT(mConnectorArray); PX_ASSERT(index != 0xffffffff); if (!np) removeConnector(owner, index); else (*mConnectorArray)[index].mObject = np; } } PxAggregate* NpActor::getAggregate() const { PxU32 index = 0xffffffff; NpAggregate* a = getNpAggregate(index); return static_cast<PxAggregate*>(a); } /////////////////////////////////////////////////////////////////////////////// void NpActor::removeConstraintsFromScene() { NpConnectorIterator iter = getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); NpScene* s = c->getNpScene(); if(s) s->removeFromConstraintList(*c); } } void NpActor::addConstraintsToSceneInternal() { if(!mConnectorArray) return; NpConnectorIterator iter = getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); PX_ASSERT(c->getNpScene() == NULL); c->markDirty(); // PT: "temp" fix for crash when removing/re-adding jointed actor from/to a scene NpScene* s = c->getSceneFromActors(); if(s) s->addToConstraintList(*c); } } /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE const NpShapeManager* getShapeManager(const PxRigidActor& actor) { // DS: if the performance here becomes an issue we can use the same kind of offset hack as below const PxType actorType = actor.getConcreteType(); if (actorType == PxConcreteType::eRIGID_DYNAMIC) return &static_cast<const NpRigidDynamic&>(actor).getShapeManager(); else if(actorType == PxConcreteType::eRIGID_STATIC) return &static_cast<const NpRigidStatic&>(actor).getShapeManager(); else if (actorType == PxConcreteType::eARTICULATION_LINK) return &static_cast<const NpArticulationLink&>(actor).getShapeManager(); else { PX_ASSERT(0); return NULL; } } NpShapeManager* NpActor::getShapeManager_(PxRigidActor& actor) { return const_cast<NpShapeManager*>(getShapeManager(actor)); } const NpShapeManager* NpActor::getShapeManager_(const PxRigidActor& actor) { return getShapeManager(actor); } void NpActor::onActorRelease(PxActor* actor) { NpFactory::getInstance().onActorRelease(actor); } void NpActor::scSetDominanceGroup(PxDominanceGroup v) { PX_ASSERT(!isAPIWriteForbidden()); getActorCore().setDominanceGroup(v); UPDATE_PVD_PROPERTY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, dominance, *getPxActor(), v) } void NpActor::scSetOwnerClient(PxClientID inId) { //This call is only valid if we aren't in a scene. PX_ASSERT(!isAPIWriteForbidden()); getActorCore().setOwnerClient(inId); UPDATE_PVD_PROPERTY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, ownerClient, *getPxActor(), inId) } const PxActor* NpActor::getPxActor() const { const PxActorType::Enum type = getActorCore().getActorCoreType(); if(type == PxActorType::eRIGID_DYNAMIC) return static_cast<const NpRigidDynamic*>(this); else if(type == PxActorType::eRIGID_STATIC) return static_cast<const NpRigidStatic*>(this); else if(type == PxActorType::eARTICULATION_LINK) return static_cast<const NpArticulationLink*>(this); PX_ASSERT(0); return NULL; } namespace { template <typename N> NpActor* pxToNpActor(PxActor *p) { return static_cast<NpActor*>(static_cast<N*>(p)); } } NpActor::Offsets::Offsets() { for(PxU32 i=0;i<PxConcreteType::ePHYSX_CORE_COUNT;i++) pxActorToNpActor[i] = 0; size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want PxActor* n = reinterpret_cast<PxActor*>(addr); pxActorToNpActor[PxConcreteType::eRIGID_STATIC] = size_t(pxToNpActor<NpRigidStatic>(n)) - addr; pxActorToNpActor[PxConcreteType::eRIGID_DYNAMIC] = size_t(pxToNpActor<NpRigidDynamic>(n)) - addr; pxActorToNpActor[PxConcreteType::eARTICULATION_LINK] = size_t(pxToNpActor<NpArticulationLink>(n)) - addr; #if PX_SUPPORT_GPU_PHYSX pxActorToNpActor[PxConcreteType::eSOFT_BODY] = size_t(pxToNpActor<NpSoftBody>(n)) - addr; pxActorToNpActor[PxConcreteType::ePBD_PARTICLESYSTEM] = size_t(pxToNpActor<NpPBDParticleSystem>(n)) - addr; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION pxActorToNpActor[PxConcreteType::eFLIP_PARTICLESYSTEM] = size_t(pxToNpActor<NpFLIPParticleSystem>(n)) - addr; pxActorToNpActor[PxConcreteType::eMPM_PARTICLESYSTEM] = size_t(pxToNpActor<NpMPMParticleSystem>(n)) - addr; pxActorToNpActor[PxConcreteType::eFEM_CLOTH] = size_t(pxToNpActor<NpFEMCloth>(n)) - addr; pxActorToNpActor[PxConcreteType::eHAIR_SYSTEM] = size_t(pxToNpActor<NpHairSystem>(n)) - addr; #endif #endif } const NpActor::Offsets NpActor::sOffsets; NpActor::NpOffsets::NpOffsets() { // PT: ..... { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpRigidStatic* n = reinterpret_cast<NpRigidStatic*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t staticOffset = NpRigidStatic::getCoreOffset() - npOffset; npToSc[NpType::eRIGID_STATIC] = staticOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpRigidDynamic* n = reinterpret_cast<NpRigidDynamic*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpRigidDynamic::getCoreOffset() - npOffset; npToSc[NpType::eBODY] = bodyOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpArticulationLink* n = reinterpret_cast<NpArticulationLink*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpArticulationLink::getCoreOffset() - npOffset; npToSc[NpType::eBODY_FROM_ARTICULATION_LINK] = bodyOffset; } #if PX_SUPPORT_GPU_PHYSX { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpSoftBody* n = reinterpret_cast<NpSoftBody*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpSoftBody::getCoreOffset() - npOffset; npToSc[NpType::eSOFTBODY] = bodyOffset; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpFEMCloth* n = reinterpret_cast<NpFEMCloth*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpFEMCloth::getCoreOffset() - npOffset; npToSc[NpType::eFEMCLOTH] = bodyOffset; } #endif { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpPBDParticleSystem* n = reinterpret_cast<NpPBDParticleSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpPBDParticleSystem::getCoreOffset() - npOffset; npToSc[NpType::ePBD_PARTICLESYSTEM] = bodyOffset; } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpFLIPParticleSystem* n = reinterpret_cast<NpFLIPParticleSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpFLIPParticleSystem::getCoreOffset() - npOffset; npToSc[NpType::eFLIP_PARTICLESYSTEM] = bodyOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpMPMParticleSystem* n = reinterpret_cast<NpMPMParticleSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpMPMParticleSystem::getCoreOffset() - npOffset; npToSc[NpType::eMPM_PARTICLESYSTEM] = bodyOffset; } { size_t addr = 0x100; // casting the null ptr takes a special-case code path, which we don't want NpHairSystem* n = reinterpret_cast<NpHairSystem*>(addr); const size_t npOffset = size_t(static_cast<NpActor*>(n)) - addr; const size_t bodyOffset = NpHairSystem::getCoreOffset() - npOffset; npToSc[NpType::eHAIRSYSTEM] = bodyOffset; } #endif #endif } const NpActor::NpOffsets NpActor::sNpOffsets;
17,524
C++
30.633574
129
0.702751
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationSensor.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 "NpArticulationSensor.h" #include "PxArticulationLink.h" #include "NpArticulationLink.h" #include "ScArticulationSensorSim.h" #include "NpArticulationReducedCoordinate.h" using namespace physx; namespace physx { // PX_SERIALIZATION void NpArticulationSensor::resolveReferences(PxDeserializationContext& context) { context.translatePxBase(mLink); } NpArticulationSensor* NpArticulationSensor::createObject(PxU8*& address, PxDeserializationContext& context) { NpArticulationSensor* obj = PX_PLACEMENT_NEW(address, NpArticulationSensor(PxBaseFlags(0))); address += sizeof(NpArticulationSensor); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION NpArticulationSensor::NpArticulationSensor(PxArticulationLink* link, const PxTransform& relativePose) : PxArticulationSensor(PxConcreteType::eARTICULATION_SENSOR, PxBaseFlag::eOWNS_MEMORY), NpBase(NpType::eARTICULATION_SENSOR) { mLink = link; mCore.mRelativePose = relativePose; mCore.mSim = NULL; mCore.mFlags = 0; } void NpArticulationSensor::release() { if (getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxArticulationSensor::release() not allowed while the articulation is in a scene. Call will be ignored."); return; } NpArticulationReducedCoordinate* articulation = static_cast<NpArticulationReducedCoordinate*>(&mLink->getArticulation()); PxArray<NpArticulationSensor*>& sensors = articulation->getSensors(); PX_CHECK_AND_RETURN(mHandle < sensors.size() && sensors[mHandle] == this, "PxArticulationSensor::release() attempt to release sensor that is not part of this articulation."); sensors.back()->setHandle(mHandle); sensors.replaceWithLast(mHandle); this->~NpArticulationSensor(); if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) PX_FREE_THIS; } PxSpatialForce NpArticulationSensor::getForces() const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(getNpScene(), "PxArticulationSensor::getForces() not allowed while simulation is running, except in a split simulation during PxScene::collide() and up to PxScene::advance().", PxSpatialForce()); if (mCore.getSim()) return mCore.getSim()->getForces(); PxSpatialForce zero; zero.force = PxVec3(0.f); zero.torque = PxVec3(0.f); return zero; } PxTransform NpArticulationSensor::getRelativePose() const { return mCore.mRelativePose; } void NpArticulationSensor::setRelativePose(const PxTransform& pose) { mCore.mRelativePose = pose; if (mCore.getSim()) { mCore.getSim()->setRelativePose(pose); } } PxArticulationLink* NpArticulationSensor::getLink() const { return mLink; } PxU32 NpArticulationSensor::getIndex() const { NP_READ_CHECK(getNpScene()); if(mCore.getSim()) return mCore.getSim()->getLowLevelIndex(); return 0xFFFFFFFFu; } PxArticulationReducedCoordinate* NpArticulationSensor::getArticulation() const { return &mLink->getArticulation(); } PxArticulationSensorFlags NpArticulationSensor::getFlags() const { return PxArticulationSensorFlags(PxU8(mCore.mFlags)); } void NpArticulationSensor::setFlag(PxArticulationSensorFlag::Enum flag, bool enabled) { if(enabled) mCore.mFlags |= flag; else mCore.mFlags &= (~flag); if (mCore.getSim()) { mCore.getSim()->setFlag(mCore.mFlags); } } }
5,021
C++
30.78481
260
0.767975
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFLIPMaterial.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 "NpFLIPMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION using namespace physx; using namespace Cm; NpFLIPMaterial::NpFLIPMaterial(const PxsFLIPMaterialCore& desc) : PxFLIPMaterial(PxConcreteType::eFLIP_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpFLIPMaterial::~NpFLIPMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpFLIPMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: missing line here? } void NpFLIPMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseFLIPMaterialToPool(*this); } else this->~NpFLIPMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpFLIPMaterial* NpFLIPMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpFLIPMaterial* obj = PX_PLACEMENT_NEW(address, NpFLIPMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpFLIPMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpFLIPMaterial::release() { RefCountable_decRefCount(*this); } void NpFLIPMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpFLIPMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpFLIPMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setFriction: invalid float"); mMaterial.friction = x; updateMaterial(); } PxReal NpFLIPMaterial::getFriction() const { return mMaterial.friction; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setViscosity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setViscosity: invalid float"); mMaterial.viscosity = x; updateMaterial(); } PxReal NpFLIPMaterial::getViscosity() const { return mMaterial.viscosity; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpFLIPMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setAdhesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.adhesion = x; updateMaterial(); } PxReal NpFLIPMaterial::getAdhesion() const { return mMaterial.adhesion; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setGravityScale(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.gravityScale = x; updateMaterial(); } PxReal NpFLIPMaterial::getGravityScale() const { return mMaterial.gravityScale; } /////////////////////////////////////////////////////////////////////////////// void NpFLIPMaterial::setAdhesionRadiusScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setAdhesionRadiusScale: scale must be positive"); mMaterial.adhesionRadiusScale = x; updateMaterial(); } PxReal NpFLIPMaterial::getAdhesionRadiusScale() const { return mMaterial.adhesionRadiusScale; } /////////////////////////////////////////////////////////////////////////////// #endif #endif
5,918
C++
28.447761
103
0.690267
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFactory.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/PxGeometryQuery.h" #include "NpFactory.h" #include "NpPhysics.h" #include "ScPhysics.h" #include "GuHeightField.h" #include "GuTriangleMesh.h" #include "GuConvexMesh.h" #include "NpConnector.h" #include "NpPtrTableStorageManager.h" #include "CmCollection.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationTendon.h" #include "NpAggregate.h" #include "PxvGlobals.h" #if PX_SUPPORT_GPU_PHYSX #include "NpParticleSystem.h" #include "NpSoftBody.h" #include "NpFEMCloth.h" #include "NpHairSystem.h" #include "PxPhysXGpu.h" #endif #if PX_SUPPORT_OMNI_PVD # define OMNI_PVD_NOTIFY_ADD(OBJECT) notifyListenersAdd(OBJECT) # define OMNI_PVD_NOTIFY_REMOVE(OBJECT) notifyListenersRemove(OBJECT) #else # define OMNI_PVD_NOTIFY_ADD(OBJECT) # define OMNI_PVD_NOTIFY_REMOVE(OBJECT) #endif using namespace physx; using namespace Cm; NpFactory::NpFactory() : Gu::MeshFactory() , mConnectorArrayPool("connectorArrayPool") , mPtrTableStorageManager(PX_NEW(NpPtrTableStorageManager)) , mMaterialPool("MaterialPool") , mGpuMemStat(0) #if PX_SUPPORT_PVD , mNpFactoryListener(NULL) #endif { } template <typename T> static void releaseAll(PxHashSet<T*>& container) { // a bit tricky: release will call the factory back to remove the object from // the tracking array, immediately invalidating the iterator. Reconstructing the // iterator per delete can be expensive. So, we use a temporary object. // // a coalesced hash would be efficient too, but we only ever iterate over it // here so it's not worth the 2x remove penalty over the normal hash. PxArray<T*, PxReflectionAllocator<T*> > tmp; tmp.reserve(container.size()); for(typename PxHashSet<T*>::Iterator iter = container.getIterator(); !iter.done(); ++iter) tmp.pushBack(*iter); PX_ASSERT(tmp.size() == container.size()); for(PxU32 i=0;i<tmp.size();i++) tmp[i]->release(); } NpFactory::~NpFactory() { PX_DELETE(mPtrTableStorageManager); } void NpFactory::release() { releaseAll(mAggregateTracking); releaseAll(mConstraintTracking); releaseAll(mArticulationTracking); releaseAll(mActorTracking); while(mShapeTracking.size()) static_cast<NpShape*>(mShapeTracking.getEntries()[0])->releaseInternal(); #if PX_SUPPORT_GPU_PHYSX releaseAll(mParticleBufferTracking); #endif Gu::MeshFactory::release(); // deletes the class } void NpFactory::createInstance() { PX_ASSERT(!mInstance); mInstance = PX_NEW(NpFactory)(); } void NpFactory::destroyInstance() { PX_ASSERT(mInstance); mInstance->release(); mInstance = NULL; } NpFactory* NpFactory::mInstance = NULL; /////////////////////////////////////////////////////////////////////////////// template <class T0, class T1> static void addToTracking(T1& set, T0* element, PxMutex& mutex, bool lock) { if(!element) return; if(lock) mutex.lock(); set.insert(element); if(lock) mutex.unlock(); } /////////////////////////////////////////////////////////////////////////////// Actors void NpFactory::addRigidStatic(PxRigidStatic* npActor, bool lock) { addToTracking(mActorTracking, npActor, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npActor); } void NpFactory::addRigidDynamic(PxRigidDynamic* npBody, bool lock) { addToTracking(mActorTracking, npBody, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npBody); } void NpFactory::addShape(PxShape* shape, bool lock) { addToTracking(mShapeTracking, shape, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(shape); } void NpFactory::onActorRelease(PxActor* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mActorTracking.erase(a); } void NpFactory::onShapeRelease(PxShape* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mShapeTracking.erase(a); } void NpFactory::addArticulation(PxArticulationReducedCoordinate* npArticulation, bool lock) { addToTracking(mArticulationTracking, npArticulation, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npArticulation); } #if PX_SUPPORT_GPU_PHYSX void NpFactory::addParticleBuffer(PxParticleBuffer* buffer, bool lock) { addToTracking(mParticleBufferTracking, buffer, mTrackingMutex, lock); } void NpFactory::onParticleBufferReleaseInternal(PxParticleBuffer* buffer) { PxMutex::ScopedLock lock(mTrackingMutex); mParticleBufferTracking.erase(buffer); } #endif void NpFactory::releaseArticulationToPool(PxArticulationReducedCoordinate& articulation) { PX_ASSERT(articulation.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PX_ASSERT(articulation.getConcreteType() == PxConcreteType::eARTICULATION_REDUCED_COORDINATE); PxMutex::ScopedLock lock(mArticulationRCPoolLock); mArticulationRCPool.destroy(static_cast<NpArticulationReducedCoordinate*>(&articulation)); } PxArticulationReducedCoordinate* NpFactory::createArticulationRC() { NpArticulationReducedCoordinate* npArticulation = NpFactory::getInstance().createNpArticulationRC(); if(npArticulation) addArticulation(npArticulation); else PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation initialization failed: returned NULL."); // OMNI_PVD_CREATE() return npArticulation; } NpArticulationReducedCoordinate* NpFactory::createNpArticulationRC() { PxMutex::ScopedLock lock(mArticulationRCPoolLock); return mArticulationRCPool.construct(); } void NpFactory::onArticulationRelease(PxArticulationReducedCoordinate* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mArticulationTracking.erase(a); } NpArticulationLink* NpFactory::createNpArticulationLink(NpArticulationReducedCoordinate& root, NpArticulationLink* parent, const PxTransform& pose) { NpArticulationLink* npArticulationLink; { PxMutex::ScopedLock lock(mArticulationLinkPoolLock); npArticulationLink = mArticulationLinkPool.construct(pose, root, parent); } return npArticulationLink; } void NpFactory::releaseArticulationLinkToPool(NpArticulationLink& articulationLink) { PX_ASSERT(articulationLink.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); OMNI_PVD_NOTIFY_REMOVE(&articulationLink); PxMutex::ScopedLock lock(mArticulationLinkPoolLock); mArticulationLinkPool.destroy(&articulationLink); } PxArticulationLink* NpFactory::createArticulationLink(NpArticulationReducedCoordinate& root, NpArticulationLink* parent, const PxTransform& pose) { PX_CHECK_AND_RETURN_NULL(pose.isValid(),"Supplied articulation link pose is not valid. Articulation link creation method returns NULL."); PX_CHECK_AND_RETURN_NULL((!parent || (&parent->getRoot() == &root)), "specified parent link is not part of the destination articulation. Articulation link creation method returns NULL."); NpArticulationLink* npArticulationLink = NpFactory::getInstance().createNpArticulationLink(root, parent, pose); if (!npArticulationLink) { PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation link initialization failed: returned NULL."); return NULL; } OMNI_PVD_NOTIFY_ADD(npArticulationLink); PxArticulationJointReducedCoordinate* npArticulationJoint = 0; if (parent) { PxTransform parentPose = parent->getCMassLocalPose().transformInv(pose); PxTransform childPose = PxTransform(PxIdentity); npArticulationJoint = root.createArticulationJoint(*parent, parentPose, *npArticulationLink, childPose); if (!npArticulationJoint) { PX_DELETE(npArticulationLink); PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation link initialization failed due to joint creation failure: returned NULL."); return NULL; } npArticulationLink->setInboundJoint(*npArticulationJoint); } return npArticulationLink; } NpArticulationJointReducedCoordinate* NpFactory::createNpArticulationJointRC(NpArticulationLink& parent, const PxTransform& parentFrame, NpArticulationLink& child, const PxTransform& childFrame) { NpArticulationJointReducedCoordinate* npArticulationJoint; { PxMutex::ScopedLock lock(mArticulationJointRCPoolLock); npArticulationJoint = mArticulationRCJointPool.construct(parent, parentFrame, child, childFrame); } OMNI_PVD_NOTIFY_ADD(npArticulationJoint); return npArticulationJoint; } void NpFactory::releaseArticulationJointRCToPool(NpArticulationJointReducedCoordinate& articulationJoint) { PX_ASSERT(articulationJoint.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); OMNI_PVD_NOTIFY_REMOVE(&articulationJoint); PxMutex::ScopedLock lock(mArticulationJointRCPoolLock); mArticulationRCJointPool.destroy(&articulationJoint); } /////////////////////////////////////////////////////////////////////////////// soft body #if PX_SUPPORT_GPU_PHYSX PxSoftBody* NpFactory::createSoftBody(PxCudaContextManager& cudaContextManager) { NpSoftBody* sb; { PxMutex::ScopedLock lock(mSoftBodyPoolLock); sb = mSoftBodyPool.construct(cudaContextManager); } OMNI_PVD_NOTIFY_ADD(sb); return sb; } void NpFactory::releaseSoftBodyToPool(PxSoftBody& softBody) { PX_ASSERT(softBody.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); OMNI_PVD_NOTIFY_REMOVE(&softBody); PxMutex::ScopedLock lock(mSoftBodyPoolLock); mSoftBodyPool.destroy(static_cast<NpSoftBody*>(&softBody)); } /////////////////////////////////////////////////////////////////////////////// FEM cloth #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFEMCloth* NpFactory::createFEMCloth(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mFEMClothPoolLock); return mFEMClothPool.construct(cudaContextManager); } void NpFactory::releaseFEMClothToPool(PxFEMCloth& femCloth) { PX_ASSERT(femCloth.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFEMClothPoolLock); mFEMClothPool.destroy(static_cast<NpFEMCloth*>(&femCloth)); } #endif //////////////////////////////////////////////////////////////////////////////// particle system PxPBDParticleSystem* NpFactory::createPBDParticleSystem(PxU32 maxNeighborhood, PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mPBDParticleSystemPoolLock); //PX_CHECK_MSG(NpPBDParticleSystem::getNumAvailableSystems() > 0, "Max. number of concurrent PxParticleSystem is 256."); return mPBDParticleSystemPool.construct(maxNeighborhood, cudaContextManager); } void NpFactory::releasePBDParticleSystemToPool(PxPBDParticleSystem& particleSystem) { PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mPBDParticleSystemPoolLock); mPBDParticleSystemPool.destroy(static_cast<NpPBDParticleSystem*>(&particleSystem)); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFLIPParticleSystem* NpFactory::createFLIPParticleSystem(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mFLIPParticleSystemPoolLock); //PX_CHECK_MSG(NpFLIPParticleSystem::getNumAvailableSystems() > 0, "Max. number of concurrent PxParticleSystem is 256."); return mFLIPParticleSystemPool.construct(cudaContextManager); } void NpFactory::releaseFLIPParticleSystemToPool(PxFLIPParticleSystem& particleSystem) { PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFLIPParticleSystemPoolLock); mFLIPParticleSystemPool.destroy(static_cast<NpFLIPParticleSystem*>(&particleSystem)); } PxMPMParticleSystem* NpFactory::createMPMParticleSystem(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mMPMParticleSystemPoolLock); //PX_CHECK_MSG(NpMPMParticleSystem::getNumAvailableSystems() > 0, "Max. number of concurrent PxParticleSystem is 256."); return mMPMParticleSystemPool.construct(cudaContextManager); } void NpFactory::releaseMPMParticleSystemToPool(PxMPMParticleSystem& particleSystem) { PX_ASSERT(particleSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mMPMParticleSystemPoolLock); mMPMParticleSystemPool.destroy(static_cast<NpMPMParticleSystem*>(&particleSystem)); } #endif /////////////////////////////////////////////////////////////////////////////// Particle Buffers PxParticleBuffer* NpFactory::createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleBuffer* buffer = physxGpu->createParticleBuffer(maxParticles, maxVolumes, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(buffer); return buffer; } PxParticleAndDiffuseBuffer* NpFactory::createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleAndDiffuseBuffer* diffuseBuffer = physxGpu->createParticleAndDiffuseBuffer(maxParticles, maxVolumes, maxDiffuseParticles, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(diffuseBuffer); return diffuseBuffer; } PxParticleClothBuffer* NpFactory::createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleClothBuffer* clothBuffer = physxGpu->createParticleClothBuffer(maxParticles, maxNumVolumes, maxNumCloths, maxNumTriangles, maxNumSprings, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(clothBuffer); return clothBuffer; } PxParticleRigidBuffer* NpFactory::createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager) { if(!cudaContextManager) return NULL; PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true); PX_ASSERT(physxGpu); PxParticleRigidBuffer* rigidBuffer = physxGpu->createParticleRigidBuffer(maxParticles, maxNumVolumes, maxNumRigids, cudaContextManager, &mGpuMemStat, NpFactory::onParticleBufferRelease); addParticleBuffer(rigidBuffer); return rigidBuffer; } void NpFactory::onParticleBufferRelease(PxParticleBuffer* buffer) { NpFactory::getInstance().onParticleBufferReleaseInternal(buffer); } /////////////////////////////////////////////////////////////////////////////// HairSystem #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxHairSystem* NpFactory::createHairSystem(PxCudaContextManager& cudaContextManager) { PxMutex::ScopedLock lock(mHairSystemPoolLock); return mHairSystemPool.construct(cudaContextManager); } void NpFactory::releaseHairSystemToPool(PxHairSystem& hairSystem) { PX_ASSERT(hairSystem.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mHairSystemPoolLock); mHairSystemPool.destroy(static_cast<NpHairSystem*>(&hairSystem)); } #endif #endif /////////////////////////////////////////////////////////////////////////////// constraint void NpFactory::addConstraint(PxConstraint* npConstraint, bool lock) { addToTracking(mConstraintTracking, npConstraint, mTrackingMutex, lock); } PxConstraint* NpFactory::createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) { PX_CHECK_AND_RETURN_NULL((actor0 && actor0->getConcreteType()!=PxConcreteType::eRIGID_STATIC) || (actor1 && actor1->getConcreteType()!=PxConcreteType::eRIGID_STATIC), "createConstraint: At least one actor must be dynamic or an articulation link"); NpConstraint* npConstraint; { PxMutex::ScopedLock lock(mConstraintPoolLock); npConstraint = mConstraintPool.construct(actor0, actor1, connector, shaders, dataSize); } addConstraint(npConstraint); connector.connectToConstraint(npConstraint); return npConstraint; } void NpFactory::releaseConstraintToPool(NpConstraint& constraint) { PX_ASSERT(constraint.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mConstraintPoolLock); mConstraintPool.destroy(&constraint); } void NpFactory::onConstraintRelease(PxConstraint* c) { PxMutex::ScopedLock lock(mTrackingMutex); mConstraintTracking.erase(c); } /////////////////////////////////////////////////////////////////////////////// aggregate void NpFactory::addAggregate(PxAggregate* npAggregate, bool lock) { addToTracking(mAggregateTracking, npAggregate, mTrackingMutex, lock); OMNI_PVD_NOTIFY_ADD(npAggregate); } PxAggregate* NpFactory::createAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint) { NpAggregate* npAggregate; { PxMutex::ScopedLock lock(mAggregatePoolLock); npAggregate = mAggregatePool.construct(maxActors, maxShapes, filterHint); } addAggregate(npAggregate); return npAggregate; } void NpFactory::releaseAggregateToPool(NpAggregate& aggregate) { PX_ASSERT(aggregate.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mAggregatePoolLock); mAggregatePool.destroy(&aggregate); } void NpFactory::onAggregateRelease(PxAggregate* a) { OMNI_PVD_NOTIFY_REMOVE(a); PxMutex::ScopedLock lock(mTrackingMutex); mAggregateTracking.erase(a); } /////////////////////////////////////////////////////////////////////////////// PxMaterial* NpFactory::createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution) { PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0."); PX_CHECK_AND_RETURN_NULL(staticFriction >= 0.0f, "createMaterial: staticFriction must be >= 0."); PX_CHECK_AND_RETURN_NULL(restitution >= 0.0f || restitution <= 1.0f, "createMaterial: restitution must be between 0 and 1."); PxsMaterialData materialData; materialData.staticFriction = staticFriction; materialData.dynamicFriction = dynamicFriction; materialData.restitution = restitution; NpMaterial* npMaterial; { PxMutex::ScopedLock lock(mMaterialPoolLock); npMaterial = mMaterialPool.construct(materialData); } return npMaterial; } void NpFactory::releaseMaterialToPool(NpMaterial& material) { PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mMaterialPoolLock); mMaterialPool.destroy(&material); } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_GPU_PHYSX PxFEMSoftBodyMaterial* NpFactory::createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction) { #if PX_SUPPORT_GPU_PHYSX PX_CHECK_AND_RETURN_NULL(youngs >= 0.0f, "createFEMSoftBodyMaterial: youngs must be >= 0."); PX_CHECK_AND_RETURN_NULL(poissons >= 0.0f && poissons < 0.5f, "createFEMSoftBodyMaterial: poissons must be in range[0.f, 0.5f)."); PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0."); PxsFEMSoftBodyMaterialData materialData; materialData.youngs = youngs; materialData.poissons = poissons; materialData.dynamicFriction = dynamicFriction; materialData.damping = 0.f; materialData.dampingScale = toUniformU16(1.f); materialData.materialModel = PxFEMSoftBodyMaterialModel::eCO_ROTATIONAL; materialData.deformThreshold = PX_MAX_F32; materialData.deformLowLimitRatio = 1.f; materialData.deformHighLimitRatio = 1.f; NpFEMSoftBodyMaterial* npMaterial; { PxMutex::ScopedLock lock(mFEMMaterialPoolLock); npMaterial = mFEMMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(youngs); PX_UNUSED(poissons); PX_UNUSED(dynamicFriction); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxFEMMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseFEMMaterialToPool(PxFEMSoftBodyMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpFEMSoftBodyMaterial& material = static_cast<NpFEMSoftBodyMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFEMMaterialPoolLock); mFEMMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFEMClothMaterial* NpFactory::createFEMClothMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal thickness) { #if PX_SUPPORT_GPU_PHYSX PX_CHECK_AND_RETURN_NULL(youngs >= 0.0f, "createFEMClothMaterial: youngs must be >= 0."); PX_CHECK_AND_RETURN_NULL(poissons >= 0.0f && poissons < 0.5f, "createFEMClothMaterial: poissons must be in range[0.f, 0.5f)."); PX_CHECK_AND_RETURN_NULL(dynamicFriction >= 0.0f, "createMaterial: dynamicFriction must be >= 0."); PX_CHECK_AND_RETURN_NULL(thickness >= 0.0f, "createMaterial: thickness must be > 0."); PxsFEMClothMaterialData materialData; materialData.youngs = youngs; materialData.poissons = poissons; materialData.dynamicFriction = dynamicFriction; materialData.thickness = thickness; NpFEMClothMaterial* npMaterial = NULL; { PxMutex::ScopedLock lock(mFEMClothMaterialPoolLock); npMaterial = mFEMClothMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(youngs); PX_UNUSED(poissons); PX_UNUSED(dynamicFriction); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxFEMClothMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseFEMClothMaterialToPool(PxFEMClothMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpFEMClothMaterial& material = static_cast<NpFEMClothMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFEMClothMaterialPoolLock); mFEMClothMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } #endif /////////////////////////////////////////////////////////////////////////////// PxPBDMaterial* NpFactory::createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient, PxReal gravityScale) { #if PX_SUPPORT_GPU_PHYSX PxsPBDMaterialData materialData; materialData.friction = friction; materialData.damping = damping; materialData.viscosity = viscosity; materialData.vorticityConfinement = vorticityConfinement; materialData.surfaceTension = surfaceTension; materialData.cohesion = cohesion; materialData.adhesion = adhesion; materialData.lift = lift; materialData.drag = drag; materialData.cflCoefficient = cflCoefficient; materialData.gravityScale = gravityScale; materialData.particleFrictionScale = 1.f; materialData.adhesionRadiusScale = 0.f; materialData.particleAdhesionScale = 1.f; NpPBDMaterial* npMaterial; { PxMutex::ScopedLock lock(mPBDMaterialPoolLock); npMaterial = mPBDMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(friction); PX_UNUSED(damping); PX_UNUSED(adhesion); PX_UNUSED(viscosity); PX_UNUSED(vorticityConfinement); PX_UNUSED(surfaceTension); PX_UNUSED(cohesion); PX_UNUSED(lift); PX_UNUSED(drag); PX_UNUSED(cflCoefficient); PX_UNUSED(gravityScale); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxPBDMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releasePBDMaterialToPool(PxPBDMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpPBDMaterial& material = static_cast<NpPBDMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mPBDMaterialPoolLock); mPBDMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION PxFLIPMaterial* NpFactory::createFLIPMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal gravityScale) { #if PX_SUPPORT_GPU_PHYSX PxsFLIPMaterialData materialData; materialData.friction = friction; materialData.damping = damping; materialData.adhesion = adhesion; materialData.viscosity = viscosity; materialData.gravityScale = gravityScale; materialData.adhesionRadiusScale = 0.f; NpFLIPMaterial* npMaterial; { PxMutex::ScopedLock lock(mFLIPMaterialPoolLock); npMaterial = mFLIPMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(friction); PX_UNUSED(damping); PX_UNUSED(adhesion); PX_UNUSED(viscosity); PX_UNUSED(gravityScale); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxFLIPMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseFLIPMaterialToPool(PxFLIPMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpFLIPMaterial& material = static_cast<NpFLIPMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mFLIPMaterialPoolLock); mFLIPMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } /////////////////////////////////////////////////////////////////////////////// PxMPMMaterial* NpFactory::createMPMMaterial( PxReal friction, PxReal damping, PxReal adhesion, bool isPlastic, PxReal youngsModulus, PxReal poissons, PxReal hardening, PxReal criticalCompression, PxReal criticalStretch, PxReal tensileDamageSensitivity, PxReal compressiveDamageSensitivity, PxReal attractiveForceResidual, PxReal gravityScale) { #if PX_SUPPORT_GPU_PHYSX PxsMPMMaterialData materialData; materialData.friction = friction; materialData.damping = damping; materialData.adhesion = adhesion; materialData.adhesionRadiusScale = 0.f; materialData.isPlastic = isPlastic; materialData.youngsModulus = youngsModulus; materialData.poissonsRatio = poissons; materialData.hardening = hardening; materialData.criticalCompression = criticalCompression; materialData.criticalStretch = criticalStretch; materialData.tensileDamageSensitivity = tensileDamageSensitivity; materialData.compressiveDamageSensitivity = compressiveDamageSensitivity; materialData.attractiveForceResidual = attractiveForceResidual; materialData.gravityScale = gravityScale; materialData.materialModel = PxMPMMaterialModel::eNEO_HOOKEAN; materialData.cuttingFlags = PxMPMCuttingFlag::eNONE; materialData.yieldStress = 30000; materialData.sandFrictionAngle = 3.1415926535898f * 0.25f; materialData.density = 500.0f; materialData.stretchAndShearDamping = 0.0f; materialData.rotationalDamping = 0.0f; NpMPMMaterial* npMaterial; { PxMutex::ScopedLock lock(mMPMMaterialPoolLock); npMaterial = mMPMMaterialPool.construct(materialData); } return npMaterial; #else PX_UNUSED(friction); PX_UNUSED(damping); PX_UNUSED(adhesion); PX_UNUSED(isPlastic); PX_UNUSED(youngsModulus); PX_UNUSED(poissons); PX_UNUSED(hardening); PX_UNUSED(criticalCompression); PX_UNUSED(criticalStretch); PX_UNUSED(tensileDamageSensitivity); PX_UNUSED(compressiveDamageSensitivity); PX_UNUSED(attractiveForceResidual); PX_UNUSED(gravityScale); PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxMPMMaterial is not supported on this platform."); return NULL; #endif } void NpFactory::releaseMPMMaterialToPool(PxMPMMaterial& material_) { #if PX_SUPPORT_GPU_PHYSX NpMPMMaterial& material = static_cast<NpMPMMaterial&>(material_); PX_ASSERT(material.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mMPMMaterialPoolLock); mMPMMaterialPool.destroy(&material); #else PX_UNUSED(material_); #endif } #endif // PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #endif // PX_SUPPORT_GPU_PHYSX /////////////////////////////////////////////////////////////////////////////// NpConnectorArray* NpFactory::acquireConnectorArray() { PxMutexT<>::ScopedLock l(mConnectorArrayPoolLock); return mConnectorArrayPool.construct(); } void NpFactory::releaseConnectorArray(NpConnectorArray* array) { PxMutexT<>::ScopedLock l(mConnectorArrayPoolLock); mConnectorArrayPool.destroy(array); } /////////////////////////////////////////////////////////////////////////////// #if PX_CHECKED bool checkShape(const PxGeometry& g, const char* errorMsg) { const bool isValid = PxGeometryQuery::isValid(g); if(!isValid) PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, errorMsg); return isValid; } #endif template <typename PxMaterialType, typename NpMaterialType> NpShape* NpFactory::createShapeInternal(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxMaterialType*const* materials, PxU16 materialCount, bool isExclusive, PxShapeCoreFlag::Enum flag) { #if PX_CHECKED if(!checkShape(geometry, "Supplied PxGeometry is not valid. Shape creation method returns NULL.")) return NULL; // Check for invalid material table setups if(!NpShape::checkMaterialSetup(geometry, "Shape creation", materials, materialCount)) return NULL; #endif PxInlineArray<PxU16, 4> materialIndices("NpFactory::TmpMaterialIndexBuffer"); materialIndices.resize(materialCount); if (materialCount == 1) materialIndices[0] = static_cast<NpMaterialType*>(materials[0])->mMaterial.mMaterialIndex; else NpMaterialType::getMaterialIndices(materials, materialIndices.begin(), materialCount); NpShape* npShape; { PxMutex::ScopedLock lock(mShapePoolLock); PxU16* mi = materialIndices.begin(); // required to placate pool constructor arg passing npShape = mShapePool.construct(geometry, shapeFlags, mi, materialCount, isExclusive, flag); } if (!npShape) return NULL; // PT: TODO: add material base class, move this to NpShape, drop getMaterial<> for (PxU32 i = 0; i < materialCount; i++) { PxMaterialType* mat = npShape->getMaterial<PxMaterialType, NpMaterialType>(i); RefCountable_incRefCount(*mat); } addShape(npShape); return npShape; } NpShape* NpFactory::createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxMaterial*const* materials, PxU16 materialCount, bool isExclusive) { return createShapeInternal<PxMaterial, NpMaterial>(geometry, shapeFlags, materials, materialCount, isExclusive, PxShapeCoreFlag::Enum(0)); } NpShape* NpFactory::createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxFEMSoftBodyMaterial*const* materials, PxU16 materialCount, bool isExclusive) { #if PX_SUPPORT_GPU_PHYSX return createShapeInternal<PxFEMSoftBodyMaterial, NpFEMSoftBodyMaterial>(geometry, shapeFlags, materials, materialCount, isExclusive, PxShapeCoreFlag::eSOFT_BODY_SHAPE); #else PX_UNUSED(geometry); PX_UNUSED(shapeFlags); PX_UNUSED(materials); PX_UNUSED(materialCount); PX_UNUSED(isExclusive); return NULL; #endif } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION && PX_SUPPORT_GPU_PHYSX NpShape* NpFactory::createShape(const PxGeometry& geometry, PxShapeFlags shapeFlags, PxFEMClothMaterial*const* materials, PxU16 materialCount, bool isExclusive) { return createShapeInternal<PxFEMClothMaterial, NpFEMClothMaterial>(geometry, shapeFlags, materials, materialCount, isExclusive, PxShapeCoreFlag::eCLOTH_SHAPE); } #endif void NpFactory::releaseShapeToPool(NpShape& shape) { PX_ASSERT(shape.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mShapePoolLock); mShapePool.destroy(&shape); } PxU32 NpFactory::getNbShapes() const { // PT: TODO: isn't there a lock missing here? See usage in MeshFactory return mShapeTracking.size(); } PxU32 NpFactory::getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { // PT: TODO: isn't there a lock missing here? See usage in MeshFactory return getArrayOfPointers(userBuffer, bufferSize, startIndex, mShapeTracking.getEntries(), mShapeTracking.size()); } /////////////////////////////////////////////////////////////////////////////// PxRigidStatic* NpFactory::createRigidStatic(const PxTransform& pose) { PX_CHECK_AND_RETURN_NULL(pose.isValid(), "pose is not valid. createRigidStatic returns NULL."); NpRigidStatic* npActor; { PxMutex::ScopedLock lock(mRigidStaticPoolLock); npActor = mRigidStaticPool.construct(pose); } addRigidStatic(npActor); return npActor; } void NpFactory::releaseRigidStaticToPool(NpRigidStatic& rigidStatic) { PX_ASSERT(rigidStatic.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mRigidStaticPoolLock); mRigidStaticPool.destroy(&rigidStatic); } /////////////////////////////////////////////////////////////////////////////// PxRigidDynamic* NpFactory::createRigidDynamic(const PxTransform& pose) { PX_CHECK_AND_RETURN_NULL(pose.isValid(), "pose is not valid. createRigidDynamic returns NULL."); NpRigidDynamic* npBody; { PxMutex::ScopedLock lock(mRigidDynamicPoolLock); npBody = mRigidDynamicPool.construct(pose); } addRigidDynamic(npBody); return npBody; } void NpFactory::releaseRigidDynamicToPool(NpRigidDynamic& rigidDynamic) { PX_ASSERT(rigidDynamic.getBaseFlags() & PxBaseFlag::eOWNS_MEMORY); PxMutex::ScopedLock lock(mRigidDynamicPoolLock); mRigidDynamicPool.destroy(&rigidDynamic); } /////////////////////////////////////////////////////////////////////////////// // PT: this function is here to minimize the amount of locks when deserializing a collection void NpFactory::addCollection(const Collection& collection) { PxU32 nb = collection.getNbObjects(); const PxPair<PxBase* const, PxSerialObjectId>* entries = collection.internalGetObjects(); // PT: we take the lock only once, here PxMutex::ScopedLock lock(mTrackingMutex); for(PxU32 i=0;i<nb;i++) { PxBase* s = entries[i].first; const PxType serialType = s->getConcreteType(); ////////////////////////// if(serialType==PxConcreteType::eHEIGHTFIELD) { Gu::HeightField* gu = static_cast<Gu::HeightField*>(s); gu->setMeshFactory(this); addHeightField(gu, false); } else if(serialType==PxConcreteType::eCONVEX_MESH) { Gu::ConvexMesh* gu = static_cast<Gu::ConvexMesh*>(s); gu->setMeshFactory(this); addConvexMesh(gu, false); } else if(serialType==PxConcreteType::eTRIANGLE_MESH_BVH33 || serialType==PxConcreteType::eTRIANGLE_MESH_BVH34) { Gu::TriangleMesh* gu = static_cast<Gu::TriangleMesh*>(s); gu->setMeshFactory(this); addTriangleMesh(gu, false); } else if(serialType==PxConcreteType::eRIGID_DYNAMIC) { NpRigidDynamic* np = static_cast<NpRigidDynamic*>(s); addRigidDynamic(np, false); } else if(serialType==PxConcreteType::eRIGID_STATIC) { NpRigidStatic* np = static_cast<NpRigidStatic*>(s); addRigidStatic(np, false); } else if(serialType==PxConcreteType::eSHAPE) { NpShape* np = static_cast<NpShape*>(s); addShape(np, false); } else if(serialType==PxConcreteType::eMATERIAL) { } else if(serialType==PxConcreteType::eCONSTRAINT) { NpConstraint* np = static_cast<NpConstraint*>(s); addConstraint(np, false); } else if(serialType==PxConcreteType::eAGGREGATE) { NpAggregate* np = static_cast<NpAggregate*>(s); addAggregate(np, false); // PT: TODO: double-check this.... is it correct? for(PxU32 j=0;j<np->getCurrentSizeFast();j++) { PxBase* actor = np->getActorFast(j); const PxType serialType1 = actor->getConcreteType(); if(serialType1==PxConcreteType::eRIGID_STATIC) addRigidStatic(static_cast<NpRigidStatic*>(actor), false); else if(serialType1==PxConcreteType::eRIGID_DYNAMIC) addRigidDynamic(static_cast<NpRigidDynamic*>(actor), false); else if(serialType1==PxConcreteType::eARTICULATION_LINK) {} else PX_ASSERT(0); } } else if (serialType == PxConcreteType::eARTICULATION_REDUCED_COORDINATE) { NpArticulationReducedCoordinate* np = static_cast<NpArticulationReducedCoordinate*>(s); addArticulation(np, false); } else if(serialType==PxConcreteType::eARTICULATION_LINK) { // NpArticulationLink* np = static_cast<NpArticulationLink*>(s); } else if(serialType==PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE) { // NpArticulationJoint* np = static_cast<NpArticulationJoint*>(s); } else { // assert(0); } } } /////////////////////////////////////////////////////////////////////////////// #if PX_SUPPORT_PVD void NpFactory::setNpFactoryListener( NpFactoryListener& inListener) { mNpFactoryListener = &inListener; addFactoryListener(inListener); } #endif /////////////////////////////////////////////////////////////////////////////// static PX_FORCE_INLINE void releaseToPool(NpRigidStatic* np) { NpFactory::getInstance().releaseRigidStaticToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpRigidDynamic* np) { NpFactory::getInstance().releaseRigidDynamicToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpArticulationLink* np) { NpFactory::getInstance().releaseArticulationLinkToPool(*np); } static PX_FORCE_INLINE void releaseToPool(PxArticulationJointReducedCoordinate* np) { PX_ASSERT(np->getConcreteType() == PxConcreteType::eARTICULATION_JOINT_REDUCED_COORDINATE); NpFactory::getInstance().releaseArticulationJointRCToPool(*static_cast<NpArticulationJointReducedCoordinate*>(np)); } static PX_FORCE_INLINE void releaseToPool(PxArticulationReducedCoordinate* np) { NpFactory::getInstance().releaseArticulationToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpAggregate* np) { NpFactory::getInstance().releaseAggregateToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpShape* np) { NpFactory::getInstance().releaseShapeToPool(*np); } static PX_FORCE_INLINE void releaseToPool(NpConstraint* np) { NpFactory::getInstance().releaseConstraintToPool(*np); } #if PX_SUPPORT_GPU_PHYSX static PX_FORCE_INLINE void releaseToPool(NpSoftBody* np) { NpFactory::getInstance().releaseSoftBodyToPool(*np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpFEMCloth* np) { NpFactory::getInstance().releaseFEMClothToPool(*np); } #endif static PX_FORCE_INLINE void releaseToPool(NpPBDParticleSystem* np) { NpFactory::getInstance().releasePBDParticleSystemToPool(*np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpFLIPParticleSystem* np) { NpFactory::getInstance().releaseFLIPParticleSystemToPool(*np); } #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpMPMParticleSystem* np) { NpFactory::getInstance().releaseMPMParticleSystemToPool(*np); } #endif #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION static PX_FORCE_INLINE void releaseToPool(NpHairSystem* np) { NpFactory::getInstance().releaseHairSystemToPool(*np); } #endif #endif template<class T> static PX_FORCE_INLINE void NpDestroy(T* np) { void* ud = np->userData; if(np->getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) releaseToPool(np); else np->~T(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(np, ud); } void physx::NpDestroyRigidActor(NpRigidStatic* np) { NpDestroy(np); } void physx::NpDestroyRigidDynamic(NpRigidDynamic* np) { NpDestroy(np); } void physx::NpDestroyAggregate(NpAggregate* np) { NpDestroy(np); } void physx::NpDestroyShape(NpShape* np) { NpDestroy(np); } void physx::NpDestroyConstraint(NpConstraint* np) { NpDestroy(np); } void physx::NpDestroyArticulationLink(NpArticulationLink* np) { NpDestroy(np); } void physx::NpDestroyArticulationJoint(PxArticulationJointReducedCoordinate* np) { NpDestroy(np); } void physx::NpDestroyArticulation(PxArticulationReducedCoordinate* np) { NpDestroy(np); } #if PX_SUPPORT_GPU_PHYSX void physx::NpDestroySoftBody(NpSoftBody* np) { NpDestroy(np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void physx::NpDestroyFEMCloth(NpFEMCloth* np) { NpDestroy(np); } #endif void physx::NpDestroyParticleSystem(NpPBDParticleSystem* np) { NpDestroy(np); } #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void physx::NpDestroyParticleSystem(NpFLIPParticleSystem* np) { NpDestroy(np); } void physx::NpDestroyParticleSystem(NpMPMParticleSystem* np) { NpDestroy(np); } void physx::NpDestroyHairSystem(NpHairSystem* np) { NpDestroy(np); } #endif #endif
41,394
C++
32.599838
248
0.751607
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidActorTemplate.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 NP_RIGID_ACTOR_TEMPLATE_H #define NP_RIGID_ACTOR_TEMPLATE_H #include "NpActorTemplate.h" #include "NpShapeManager.h" #include "NpConstraint.h" #include "NpFactory.h" #include "NpActor.h" // PX_SERIALIZATION #include "foundation/PxErrors.h" //~PX_SERIALIZATION #include "omnipvd/NpOmniPvdSetData.h" namespace physx { template<class APIClass> class NpRigidActorTemplate : public NpActorTemplate<APIClass> { private: typedef NpActorTemplate<APIClass> ActorTemplateClass; public: // PX_SERIALIZATION NpRigidActorTemplate(PxBaseFlags baseFlags) : ActorTemplateClass(baseFlags), mShapeManager(PxEmpty)//, mIndex(0xFFFFFFFF) { NpBase::mFreeSlot = 0xFFFFFFFF; } virtual void requiresObjects(PxProcessPxBaseCallback& c); void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); //~PX_SERIALIZATION virtual ~NpRigidActorTemplate(); // The rule is: If an API method is used somewhere in here, it has to be redeclared, else GCC whines // PxActor void removeShapes(PxSceneQuerySystem* sqManager); virtual PxActorType::Enum getType() const = 0; virtual PxBounds3 getWorldBounds(float inflation=1.01f) const PX_OVERRIDE; virtual void setActorFlag(PxActorFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setActorFlags(PxActorFlags inFlags) PX_OVERRIDE; //~PxActor // PxRigidActor virtual PxU32 getInternalActorIndex() const PX_OVERRIDE; virtual bool attachShape(PxShape& s) PX_OVERRIDE; virtual void detachShape(PxShape& s, bool wakeOnLostTouch) PX_OVERRIDE; virtual PxU32 getNbShapes() const PX_OVERRIDE; virtual PxU32 getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; virtual PxU32 getNbConstraints() const PX_OVERRIDE; virtual PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const PX_OVERRIDE; //~PxRigidActor NpRigidActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type); // not optimal but the template alternative is hardly more readable and perf is not that critical here virtual void switchToNoSim() { PX_ASSERT(false); } virtual void switchFromNoSim() { PX_ASSERT(false); } PX_FORCE_INLINE NpShapeManager& getShapeManager() { return mShapeManager; } PX_FORCE_INLINE const NpShapeManager& getShapeManager() const { return mShapeManager; } void updateShaderComs(); // index for the NpScene rigid dynamic or static array // PT: note that this index changes during the lifetime of the object, e.g. when another object // is removed and swaps happen in the scene's mRigidStatics/mRigidDynamics arrays. PX_FORCE_INLINE PxU32 getRigidActorArrayIndex() const { return NpBase::mFreeSlot; } PX_FORCE_INLINE void setRigidActorArrayIndex(PxU32 index) { NpBase::mFreeSlot = index; } // PX_FORCE_INLINE PxU32 getRigidActorArrayIndex() const { return mIndex; } // PX_FORCE_INLINE void setRigidActorArrayIndex(PxU32 index) { mIndex = index; } PX_FORCE_INLINE PxU32 getRigidActorSceneIndex() const { return NpBase::getBaseIndex(); } PX_FORCE_INLINE void setRigidActorSceneIndex(PxU32 index) { NpBase::setBaseIndex(index); } bool resetFiltering_(NpActor& ro, Sc::RigidCore& core, PxShape*const* shapes, PxU32 shapeCount); #if PX_ENABLE_DEBUG_VISUALIZATION public: void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif protected: PX_FORCE_INLINE void setActorSimFlag(bool value); NpShapeManager mShapeManager; // PT: note that this index changes during the lifetime of the object, e.g. when another object // is removed and swaps happen in the scene's mRigidStatics/mRigidDynamics arrays. // PxU32 mIndex; // index for the NpScene rigid dynamic or static array // PT: TODO: reduce padding }; // PX_SERIALIZATION template<class APIClass> void NpRigidActorTemplate<APIClass>::requiresObjects(PxProcessPxBaseCallback& c) { // export shapes PxU32 nbShapes = mShapeManager.getNbShapes(); for(PxU32 i=0;i<nbShapes;i++) { NpShape* np = mShapeManager.getShapes()[i]; c.process(*np); } } template<class APIClass> void NpRigidActorTemplate<APIClass>::preExportDataReset() { //Clearing the aggregate ID for serialization so we avoid having a stale //reference after deserialization. The aggregate ID get's reset on readding to the //scene anyway. Sc::ActorCore& actorCore = NpActor::getActorCore(); actorCore.setAggregateID(PX_INVALID_U32); mShapeManager.preExportDataReset(); //mIndex = 0xFFFFFFFF; NpBase::mFreeSlot = 0xFFFFFFFF; NpBase::setBaseIndex(NP_UNUSED_BASE_INDEX); } template<class APIClass> void NpRigidActorTemplate<APIClass>::exportExtraData(PxSerializationContext& context) { mShapeManager.exportExtraData(context); ActorTemplateClass::exportExtraData(context); } template<class APIClass> void NpRigidActorTemplate<APIClass>::importExtraData(PxDeserializationContext& context) { mShapeManager.importExtraData(context); ActorTemplateClass::importExtraData(context); } template<class APIClass> void NpRigidActorTemplate<APIClass>::resolveReferences(PxDeserializationContext& context) { const PxU32 nbShapes = mShapeManager.getNbShapes(); NpShape** shapes = const_cast<NpShape**>(mShapeManager.getShapes()); for(PxU32 j=0;j<nbShapes;j++) { context.translatePxBase(shapes[j]); shapes[j]->onActorAttach(*this); } ActorTemplateClass::resolveReferences(context); } //~PX_SERIALIZATION template<class APIClass> NpRigidActorTemplate<APIClass>::NpRigidActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type) : ActorTemplateClass (concreteType, baseFlags, type) //mIndex (0xffffffff) { NpBase::mFreeSlot = 0xFFFFFFFF; } template<class APIClass> NpRigidActorTemplate<APIClass>::~NpRigidActorTemplate() { // TODO: no mechanism for notifying shaders of actor destruction yet } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getInternalActorIndex() const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); const PxU32 index = NpBase::getBaseIndex(); return index!=NP_UNUSED_BASE_INDEX ? index : 0xffffffff; } template<class APIClass> void NpRigidActorTemplate<APIClass>::removeShapes(PxSceneQuerySystem* sqManager) { if(mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::release: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } mShapeManager.detachAll(sqManager, *this); } template<class APIClass> bool NpRigidActorTemplate<APIClass>::attachShape(PxShape& shape) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); NpShape& npShape = static_cast<NpShape&>(shape); PX_CHECK_AND_RETURN_VAL(!static_cast<NpShape&>(shape).isExclusive() || shape.getActor()==NULL, "PxRigidActor::attachShape: shape must be shared or unowned", false); PX_CHECK_AND_RETURN_VAL(!(npShape.getCore().getCore().mShapeCoreFlags & PxShapeCoreFlag::eSOFT_BODY_SHAPE), "PxRigidActor::attachShape() not allowed to attach a soft body shape to a rigid actor", false); PX_CHECK_AND_RETURN_VAL(!(npShape.getCore().getCore().mShapeCoreFlags & PxShapeCoreFlag::eCLOTH_SHAPE), "PxRigidActor::attachShape() not allowed to attach a cloth shape to a rigid actor", false); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxRigidActor::attachShape() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD // invalidate the pruning structure if the actor bounds changed if (mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::attachShape: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } mShapeManager.attachShape(npShape, *this); OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, shapes, static_cast<PxRigidActor&>(*this), shape) return true; } template<class APIClass> void NpRigidActorTemplate<APIClass>::detachShape(PxShape& shape, bool wakeOnLostTouch) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidActor::detachShape() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, shapes, static_cast<PxRigidActor&>(*this), shape) //this needs to happen before the actual detach happens below, because that detach might actually delete the shape, which invalidates the shape handle. if (mShapeManager.getPruningStructure()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::detachShape: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } if(!mShapeManager.detachShape(static_cast<NpShape&>(shape), *this, wakeOnLostTouch)) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxRigidActor::detachShape: shape is not attached to this actor!"); } } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getNbShapes() const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return mShapeManager.getNbShapes(); } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return mShapeManager.getShapes(buffer, bufferSize, startIndex); } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getNbConstraints() const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return ActorTemplateClass::getNbConnectors(NpConnectorType::eConstraint); } template<class APIClass> PxU32 NpRigidActorTemplate<APIClass>::getConstraints(PxConstraint** buffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); return ActorTemplateClass::template getConnectors<PxConstraint>(NpConnectorType::eConstraint, buffer, bufferSize, startIndex); // Some people will love me for this one... The syntax is to be standard compliant and // picky gcc won't compile without it. It is needed if you call a templated member function // of a templated class } template<class APIClass> PxBounds3 NpRigidActorTemplate<APIClass>::getWorldBounds(float inflation) const { NP_READ_CHECK(ActorTemplateClass::getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(ActorTemplateClass::getNpScene(), "PxRigidActor::getWorldBounds() not allowed while simulation is running (except during PxScene::collide()).", PxBounds3::empty()); PX_SIMD_GUARD; const PxBounds3 bounds = mShapeManager.getWorldBounds_(*this); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } template<class APIClass> PX_FORCE_INLINE void NpRigidActorTemplate<APIClass>::setActorSimFlag(bool value) { NpScene* scene = ActorTemplateClass::getNpScene(); PxActorFlags oldFlags = ActorTemplateClass::getActorFlags(); bool hadNoSimFlag = oldFlags.isSet(PxActorFlag::eDISABLE_SIMULATION); PX_CHECK_AND_RETURN((getType() != PxActorType::eARTICULATION_LINK) || (!value && !hadNoSimFlag), "PxActor::setActorFlag: PxActorFlag::eDISABLE_SIMULATION is only supported by PxRigidDynamic and PxRigidStatic objects."); if (hadNoSimFlag && (!value)) { switchFromNoSim(); ActorTemplateClass::setActorFlagsInternal(oldFlags & (~PxActorFlag::eDISABLE_SIMULATION)); // needs to be done before the code below to make sure the latest flags get picked up if (scene) NpActor::addConstraintsToScene(); } else if ((!hadNoSimFlag) && value) { if (scene) NpActor::removeConstraintsFromScene(); ActorTemplateClass::setActorFlagsInternal(oldFlags | PxActorFlag::eDISABLE_SIMULATION); switchToNoSim(); } } template<class APIClass> void NpRigidActorTemplate<APIClass>::setActorFlag(PxActorFlag::Enum flag, bool value) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidActor::setActorFlag() not allowed while simulation is running. Call will be ignored.") if (flag == PxActorFlag::eDISABLE_SIMULATION) setActorSimFlag(value); ActorTemplateClass::setActorFlagInternal(flag, value); } template<class APIClass> void NpRigidActorTemplate<APIClass>::setActorFlags(PxActorFlags inFlags) { NpScene* npScene = ActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidActor::setActorFlags() not allowed while simulation is running. Call will be ignored.") bool noSim = inFlags.isSet(PxActorFlag::eDISABLE_SIMULATION); setActorSimFlag(noSim); ActorTemplateClass::setActorFlagsInternal(inFlags); } template<class APIClass> void NpRigidActorTemplate<APIClass>::updateShaderComs() { NpConnectorIterator iter = ActorTemplateClass::getConnectorIterator(NpConnectorType::eConstraint); while (PxBase* ser = iter.getNext()) { NpConstraint* c = static_cast<NpConstraint*>(ser); c->comShift(this); } } template<class APIClass> bool NpRigidActorTemplate<APIClass>::resetFiltering_(NpActor& ro, Sc::RigidCore& core, PxShape*const* shapes, PxU32 shapeCount) { #if PX_CHECKED PX_CHECK_AND_RETURN_VAL(!(ro.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxScene::resetFiltering(): Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!", false); for(PxU32 i=0; i < shapeCount; i++) { PxRigidActor* ra = shapes[i]->getActor(); if (ra != this) { bool found = false; if (ra == NULL) { NpShape*const* sh = mShapeManager.getShapes(); for(PxU32 j=0; j < mShapeManager.getNbShapes(); j++) { if (sh[j] == shapes[i]) { found = true; break; } } } PX_CHECK_AND_RETURN_VAL(found, "PxScene::resetFiltering(): specified shape not in actor!", false); } PX_CHECK_AND_RETURN_VAL(static_cast<NpShape*>(shapes[i])->getCore().getFlags() & (PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE), "PxScene::resetFiltering(): specified shapes not of type eSIMULATION_SHAPE or eTRIGGER_SHAPE!", false); } #endif PxU32 sCount; if (shapes) sCount = shapeCount; else sCount = mShapeManager.getNbShapes(); PX_ALLOCA(scShapes, NpShape*, sCount); if (scShapes) { if (shapes) // the user specified the shapes { PxU32 sAccepted = 0; for(PxU32 i=0; i < sCount; i++) scShapes[sAccepted++] = static_cast<NpShape*>(shapes[i]); sCount = sAccepted; } else // the user just specified the actor and the shapes are taken from the actor { NpShape* const* sh = mShapeManager.getShapes(); PxU32 sAccepted = 0; for(PxU32 i=0; i < sCount; i++) { if(sh[i]->getCore().getFlags() & (PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) scShapes[sAccepted++] = sh[i]; } sCount = sAccepted; } if (sCount) { PX_ASSERT(!(core.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))); PX_ASSERT(!ro.isAPIWriteForbidden()); PX_UNUSED(ro); // PT: TODO: rewrite this thing, we end up in getSimForShape() each time for(PxU32 i=0; i < sCount; i++) core.onShapeChange(scShapes[i]->getCore(), Sc::ShapeChangeNotifyFlag::eRESET_FILTERING); } } return true; } #if PX_ENABLE_DEBUG_VISUALIZATION template<class APIClass> void NpRigidActorTemplate<APIClass>::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { mShapeManager.visualize(out, scene, *this, scale); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif } #endif
17,896
C
37.488172
257
0.750726
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPtrTableStorageManager.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 NP_PTR_TABLE_STORAGE_MANAGER_H #define NP_PTR_TABLE_STORAGE_MANAGER_H #include "foundation/PxMutex.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxBitUtils.h" #include "CmPtrTable.h" namespace physx { class NpPtrTableStorageManager : public Cm::PtrTableStorageManager, public PxUserAllocated { PX_NOCOPY(NpPtrTableStorageManager) public: NpPtrTableStorageManager() {} ~NpPtrTableStorageManager() {} // PtrTableStorageManager virtual void** allocate(PxU32 capacity) { PX_ASSERT(PxIsPowerOfTwo(capacity)); PxMutex::ScopedLock lock(mMutex); return capacity<=4 ? reinterpret_cast<void**>(mPool4.construct()) : capacity<=16 ? reinterpret_cast<void**>(mPool16.construct()) : capacity<=64 ? reinterpret_cast<void**>(mPool64.construct()) : reinterpret_cast<void**>(PX_ALLOC(capacity*sizeof(void*), "CmPtrTable pointer array")); } virtual void deallocate(void** addr, PxU32 capacity) { PX_ASSERT(PxIsPowerOfTwo(capacity)); PxMutex::ScopedLock lock(mMutex); if(capacity<=4) mPool4.destroy(reinterpret_cast< PtrBlock<4>*>(addr)); else if(capacity<=16) mPool16.destroy(reinterpret_cast< PtrBlock<16>*>(addr)); else if(capacity<=64) mPool64.destroy(reinterpret_cast< PtrBlock<64>*>(addr)); else PX_FREE(addr); } // originalCapacity is the only way we know which pool the alloc request belongs to, // so if those are no longer going to match, we need to realloc. virtual bool canReuse(PxU32 originalCapacity, PxU32 newCapacity) { PX_ASSERT(PxIsPowerOfTwo(originalCapacity)); PX_ASSERT(PxIsPowerOfTwo(newCapacity)); return poolId(originalCapacity) == poolId(newCapacity) && newCapacity<=64; } //~PtrTableStorageManager private: PxMutex mMutex; int poolId(PxU32 size) { return size<=4 ? 0 : size<=16 ? 1 : size<=64 ? 2 : 3; } template<int N> class PtrBlock { void* ptr[N]; }; PxPool2<PtrBlock<4>, 4096 > mPool4; PxPool2<PtrBlock<16>, 4096 > mPool16; PxPool2<PtrBlock<64>, 4096 > mPool64; }; } #endif
3,713
C
34.371428
97
0.74118
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPhysicsInsertionCallback.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 NP_PHYSICS_INSERTION_CALLBACK_H #define NP_PHYSICS_INSERTION_CALLBACK_H #include "common/PxInsertionCallback.h" #include "GuTriangleMesh.h" #include "GuHeightField.h" #include "GuConvexMesh.h" #include "NpFactory.h" #include "GuTetrahedronMesh.h" namespace physx { class NpPhysicsInsertionCallback : public PxInsertionCallback { public: NpPhysicsInsertionCallback() {} virtual PxBase* buildObjectFromData(PxConcreteType::Enum type, void* data) { if(type == PxConcreteType::eTRIANGLE_MESH_BVH33 || type == PxConcreteType::eTRIANGLE_MESH_BVH34) return NpFactory::getInstance().createTriangleMesh(data); if (type == PxConcreteType::eCONVEX_MESH) return NpFactory::getInstance().createConvexMesh(data); if (type == PxConcreteType::eHEIGHTFIELD) return NpFactory::getInstance().createHeightField(data); if (type == PxConcreteType::eBVH) return NpFactory::getInstance().createBVH(data); if (type == PxConcreteType::eTETRAHEDRON_MESH) return NpFactory::getInstance().createTetrahedronMesh(data); if (type == PxConcreteType::eSOFTBODY_MESH) return NpFactory::getInstance().createSoftBodyMesh(data); PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Inserting object failed: " "Object type not supported for buildObjectFromData."); return NULL; } }; } #endif
3,045
C
38.558441
99
0.757635
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpHairSystem.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 NP_HAIR_SYSTEM_H #define NP_HAIR_SYSTEM_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxHairSystem.h" #include "ScHairSystemCore.h" #include "NpActorTemplate.h" namespace physx { class NpScene; class NpShape; class NpHairSystem : public NpActorTemplate<PxHairSystem> { public: template <class T> class MemoryWithAlloc { PX_NOCOPY(MemoryWithAlloc) public: MemoryWithAlloc() : mData(NULL), mSize(0), mAlloc(NULL) {} ~MemoryWithAlloc() { deallocate(); } void allocate(uint32_t size) { if (size == mSize) return; deallocate(); if (size > 0) { mData = reinterpret_cast<T*>(mAlloc->allocate(sizeof(T) * size, 0, PX_FL)); if (mData != NULL) mSize = size; } else { mData = NULL; mSize = 0; } } void setAllocatorCallback(physx::PxVirtualAllocatorCallback* cb) { if (mSize > 0) { deallocate(); } mAlloc = cb; } void reset() { if (mSize > 0) { deallocate(); } } void swap(MemoryWithAlloc<T>& other) { physx::PxSwap(mData, other.mData); physx::PxSwap(mSize, other.mSize); physx::PxSwap(mAlloc, other.mAlloc); } uint32_t size() const { return mSize; } const T& operator[](uint32_t i) const { PX_ASSERT(i < mSize); return mData[i]; } T& operator[](uint32_t i) { PX_ASSERT(i < mSize); return mData[i]; } const T* begin() const { return mData; } T* begin() { return mData; } private: void deallocate() { if (mSize > 0) { mAlloc->deallocate(mData); mSize = 0; } } private: T* mData; uint32_t mSize; physx::PxVirtualAllocatorCallback* mAlloc; }; public: NpHairSystem(PxCudaContextManager& cudaContextManager); NpHairSystem(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager); virtual ~NpHairSystem() PX_OVERRIDE; // external API virtual void release() PX_OVERRIDE; virtual PxActorType::Enum getType() const PX_OVERRIDE { return PxActorType::eHAIRSYSTEM; } virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const PX_OVERRIDE; virtual void setHairSystemFlag(PxHairSystemFlag::Enum flag, bool val) PX_OVERRIDE; virtual void setHairSystemFlags(PxHairSystemFlags flags) PX_OVERRIDE { mCore.setFlags(flags); } virtual PxHairSystemFlags getHairSystemFlags() const PX_OVERRIDE { return mCore.getFlags(); } virtual void setReadRequestFlag(PxHairSystemData::Enum flag, bool val) PX_OVERRIDE; virtual void setReadRequestFlags(PxHairSystemDataFlags flags) PX_OVERRIDE; virtual PxHairSystemDataFlags getReadRequestFlags() const PX_OVERRIDE; virtual void setBendingRestAngles(const PxReal* bendingRestAngles, PxReal bendingCompliance) PX_OVERRIDE; virtual void setTwistingCompliance(PxReal twistingCompliance) PX_OVERRIDE; virtual void getTwistingRestPositions(PxReal* buffer) PX_OVERRIDE; virtual PxCudaContextManager* getCudaContextManager() const PX_OVERRIDE { return mCudaContextManager; } virtual void setWakeCounter(PxReal wakeCounterValue) PX_OVERRIDE; virtual PxReal getWakeCounter() const PX_OVERRIDE; virtual bool isSleeping() const PX_OVERRIDE; virtual void setRestPositions(PxVec4* restPos, bool isGpuPtr) PX_OVERRIDE; virtual PxVec4* getRestPositionsGpu() PX_OVERRIDE; virtual void addRigidAttachment(const PxRigidBody& rigidBody) PX_OVERRIDE; virtual void removeRigidAttachment(const PxRigidBody& rigidBody) PX_OVERRIDE; virtual void setRigidAttachments(PxParticleRigidAttachment* attachments, PxU32 numAttachments, bool isGpuPtr) PX_OVERRIDE; virtual PxParticleRigidAttachment* getRigidAttachmentsGpu(PxU32* numAttachments = NULL) PX_OVERRIDE; virtual PxU32 addSoftbodyAttachment(const PxSoftBody& softbody, const PxU32* tetIds, const PxVec4* tetmeshBarycentrics, const PxU32* hairVertices, PxConeLimitedConstraint* constraints, PxReal* constraintOffsets, PxU32 numAttachments) PX_OVERRIDE; virtual void removeSoftbodyAttachment(const PxSoftBody& softbody, PxU32 handle) PX_OVERRIDE; virtual void initFromDesc(const PxHairSystemDesc& desc) PX_OVERRIDE; virtual void setTopology(PxVec4* vertexPositionsInvMass, PxVec4* vertexVelocities, const PxU32* strandPastEndIndices, PxReal segmentLength, PxReal segmentRadius, PxU32 numVertices, PxU32 numStrands, const PxBounds3& bounds) PX_OVERRIDE; virtual void setLevelOfDetailGradations(const PxReal* proportionOfStrands, const PxReal* proportionOfVertices, PxU32 numLevels) PX_OVERRIDE; virtual void setLevelOfDetail(PxU32 level) PX_OVERRIDE; virtual PxU32 getLevelOfDetail(PxU32* numLevels) const PX_OVERRIDE; virtual void setPositionsInvMass(PxVec4* vertexPositionsInvMass, const PxBounds3& bounds) PX_OVERRIDE; virtual PxVec4* getPositionInvMass() PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mPositionInvMass; } virtual const PxVec4* getPositionInvMass() const PX_OVERRIDE{ return mCore.getShapeCore().getLLCore().mPositionInvMass; } virtual const PxVec4* getPositionInvMassGpuSim() const PX_OVERRIDE{ return mCore.getShapeCore().getLLCore().mPositionInvMassGpuSim; } virtual void setVelocities(PxVec4* vertexVelocities) PX_OVERRIDE; virtual PxVec4* getVelocities() PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mVelocity; } virtual const PxVec4* getVelocities() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mVelocity; } virtual PxU32 getNumVertices() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mNumVertices; } virtual PxU32 getNumStrands() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mNumStrands; } virtual const PxU32* getStrandPastEndIndices() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mStrandPastEndIndices; } virtual const PxU32* getStrandPastEndIndicesGpuSim() const PX_OVERRIDE { return mCore.getShapeCore().getLLCore().mStrandPastEndIndicesGpuSim; } virtual void setSolverIterationCounts(PxU32 iters) PX_OVERRIDE; virtual PxU32 getSolverIterationCounts() const PX_OVERRIDE; virtual void setWind(const PxVec3& wind) PX_OVERRIDE; virtual PxVec3 getWind() const PX_OVERRIDE; virtual void setAerodynamicDrag(PxReal dragCoefficient) PX_OVERRIDE; virtual PxReal getAerodynamicDrag() const PX_OVERRIDE; virtual void setAerodynamicLift(PxReal liftCoefficient) PX_OVERRIDE; virtual PxReal getAerodynamicLift() const PX_OVERRIDE; virtual void setSegmentRadius(PxReal radius) PX_OVERRIDE; virtual void getSegmentDimensions(PxReal& length, PxReal& radius) const PX_OVERRIDE; virtual void setFrictionParameters(PxReal interHairVelDamping, PxReal frictionCoeff) PX_OVERRIDE; virtual void getFrictionParameters(PxReal& interHairVelDamping, PxReal& frictionCoeff) const PX_OVERRIDE; virtual void setMaxDepenetrationVelocity(PxReal maxDepenetrationVelocity) PX_OVERRIDE; virtual PxReal getMaxDepenetrationVelocity() const PX_OVERRIDE; virtual void setShapeCompliance(PxReal startCompliance, PxReal strandRatio) PX_OVERRIDE; virtual void getShapeCompliance(PxReal& startCompliance, PxReal& strandRatio) const PX_OVERRIDE; virtual void setInterHairRepulsion(PxReal repulsion) PX_OVERRIDE; virtual PxReal getInterHairRepulsion() const PX_OVERRIDE; virtual void setSelfCollisionRelaxation(PxReal relaxation) PX_OVERRIDE; virtual PxReal getSelfCollisionRelaxation() const PX_OVERRIDE; virtual void setStretchingRelaxation(PxReal relaxation) PX_OVERRIDE; virtual PxReal getStretchingRelaxation() const PX_OVERRIDE; virtual void setContactOffset(PxReal contactOffset) PX_OVERRIDE; virtual PxReal getContactOffset() const PX_OVERRIDE; virtual void setHairContactOffset(PxReal hairContactOffset) PX_OVERRIDE; virtual PxReal getHairContactOffset() const PX_OVERRIDE; virtual void setShapeMatchingParameters(PxReal compliance, PxReal linearStretching, PxU16 numVerticesPerGroup, PxU16 numVerticesOverlap) PX_OVERRIDE; virtual PxReal getShapeMatchingCompliance() const PX_OVERRIDE; #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& npScene) const; #endif PX_FORCE_INLINE const Sc::HairSystemCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::HairSystemCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpHairSystem, mCore); } // Debug name void setName(const char*); const char* getName() const; private: void init(); void setLlGridSize(const PxBounds3& bounds); void createAllocator(); void releaseAllocator(); private: Sc::HairSystemCore mCore; PxHairSystemGeometry mGeometry; PxCudaContextManager* mCudaContextManager; PxsMemoryManager* mMemoryManager; PxVirtualAllocatorCallback* mHostMemoryAllocator; PxVirtualAllocatorCallback* mDeviceMemoryAllocator; // internal buffers populated when hair system initialized from desc instead of user-provided buffers MemoryWithAlloc<PxVec4> mPosInvMassInternal; MemoryWithAlloc<PxVec4> mVelInternal; MemoryWithAlloc<PxU32> mStrandPastEndIndicesInternal; // internal buffers in case user gives us CPU-buffers MemoryWithAlloc<PxParticleRigidAttachment> mParticleRigidAttachmentsInternal; MemoryWithAlloc<PxVec4> mRestPositionsInternal; PxArray<PxReal> mLodProportionOfStrands; PxArray<PxReal> mLodProportionOfVertices; PxHashMap<PxU32, PxPair<PxU32, PxU32>> mSoftbodyAttachmentsOffsets; // map from handle to {offset, size} PxPinnedArray<Dy::SoftbodyHairAttachment> mSoftbodyAttachments; }; } #endif #endif #endif
11,371
C
38.486111
154
0.755255
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidBodyTemplate.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 NP_RIGIDBODY_TEMPLATE_H #define NP_RIGIDBODY_TEMPLATE_H #include "NpRigidActorTemplate.h" #include "ScBodyCore.h" #include "NpPhysics.h" #include "NpShape.h" #include "NpScene.h" #include "CmVisualization.h" #include "NpDebugViz.h" #include "omnipvd/NpOmniPvdSetData.h" #if PX_SUPPORT_PVD // PT: updatePvdProperties() is overloaded and the compiler needs to know 'this' type to do the right thing. // Thus we can't just move this as an inlined Base function. #define UPDATE_PVD_PROPERTY_BODY \ { \ NpScene* sceneForPVD = RigidActorTemplateClass::getNpScene(); /* shared shapes also return zero here */ \ if(sceneForPVD) \ sceneForPVD->getScenePvdClientInternal().updateBodyPvdProperties(static_cast<NpActor*>(this)); \ } #else #define UPDATE_PVD_PROPERTY_BODY #endif namespace physx { PX_INLINE PxVec3 invertDiagInertia(const PxVec3& m) { return PxVec3( m.x == 0.0f ? 0.0f : 1.0f/m.x, m.y == 0.0f ? 0.0f : 1.0f/m.y, m.z == 0.0f ? 0.0f : 1.0f/m.z); } #if PX_ENABLE_DEBUG_VISUALIZATION /* given the diagonal of the body space inertia tensor, and the total mass this returns the body space AABB width, height and depth of an equivalent box */ PX_INLINE PxVec3 getDimsFromBodyInertia(const PxVec3& inertiaMoments, PxReal mass) { const PxVec3 inertia = inertiaMoments * (6.0f/mass); return PxVec3( PxSqrt(PxAbs(- inertia.x + inertia.y + inertia.z)), PxSqrt(PxAbs(+ inertia.x - inertia.y + inertia.z)), PxSqrt(PxAbs(+ inertia.x + inertia.y - inertia.z))); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif template<class APIClass> class NpRigidBodyTemplate : public NpRigidActorTemplate<APIClass> { protected: typedef NpRigidActorTemplate<APIClass> RigidActorTemplateClass; public: // PX_SERIALIZATION NpRigidBodyTemplate(PxBaseFlags baseFlags) : RigidActorTemplateClass(baseFlags), mCore(PxEmpty) {} //~PX_SERIALIZATION virtual ~NpRigidBodyTemplate(); // The rule is: If an API method is used somewhere in here, it has to be redeclared, else GCC whines // PxRigidActor virtual PxTransform getGlobalPose() const = 0; virtual bool attachShape(PxShape& shape) PX_OVERRIDE; //~PxRigidActor // PxRigidBody virtual PxTransform getCMassLocalPose() const PX_OVERRIDE; virtual void setMass(PxReal mass) PX_OVERRIDE; virtual PxReal getMass() const PX_OVERRIDE; virtual PxReal getInvMass() const PX_OVERRIDE; virtual void setMassSpaceInertiaTensor(const PxVec3& m) PX_OVERRIDE; virtual PxVec3 getMassSpaceInertiaTensor() const PX_OVERRIDE; virtual PxVec3 getMassSpaceInvInertiaTensor() const PX_OVERRIDE; virtual void setLinearDamping(PxReal linDamp) PX_OVERRIDE; virtual PxReal getLinearDamping() const PX_OVERRIDE; virtual void setAngularDamping(PxReal angDamp) PX_OVERRIDE; virtual PxReal getAngularDamping() const PX_OVERRIDE; virtual PxVec3 getLinearVelocity() const PX_OVERRIDE; virtual PxVec3 getAngularVelocity() const PX_OVERRIDE; virtual void setMaxLinearVelocity(PxReal maxLinVel) PX_OVERRIDE; virtual PxReal getMaxLinearVelocity() const PX_OVERRIDE; virtual void setMaxAngularVelocity(PxReal maxAngVel) PX_OVERRIDE; virtual PxReal getMaxAngularVelocity() const PX_OVERRIDE; //~PxRigidBody //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpRigidBodyTemplate(PxType concreteType, PxBaseFlags baseFlags, const PxActorType::Enum type, NpType::Enum npType, const PxTransform& bodyPose); PX_FORCE_INLINE const Sc::BodyCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::BodyCore& getCore() { return mCore; } // Flags virtual void setRigidBodyFlag(PxRigidBodyFlag::Enum, bool value) PX_OVERRIDE; virtual void setRigidBodyFlags(PxRigidBodyFlags inFlags) PX_OVERRIDE; PX_FORCE_INLINE PxRigidBodyFlags getRigidBodyFlagsFast() const { return mCore.getFlags(); } virtual PxRigidBodyFlags getRigidBodyFlags() const PX_OVERRIDE { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return getRigidBodyFlagsFast() & ~PxRigidBodyFlag::eRESERVED; } virtual void setMinCCDAdvanceCoefficient(PxReal advanceCoefficient) PX_OVERRIDE; virtual PxReal getMinCCDAdvanceCoefficient() const PX_OVERRIDE; virtual void setMaxDepenetrationVelocity(PxReal maxDepenVel) PX_OVERRIDE; virtual PxReal getMaxDepenetrationVelocity() const PX_OVERRIDE; virtual void setMaxContactImpulse(PxReal maxDepenVel) PX_OVERRIDE; virtual PxReal getMaxContactImpulse() const PX_OVERRIDE; virtual void setContactSlopCoefficient(PxReal slopCoefficient) PX_OVERRIDE; virtual PxReal getContactSlopCoefficient() const PX_OVERRIDE; virtual PxNodeIndex getInternalIslandNodeIndex() const PX_OVERRIDE; protected: void setCMassLocalPoseInternal(const PxTransform&); void addSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode); void clearSpatialForce(PxForceMode::Enum mode, bool force, bool torque); void setSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode); PX_FORCE_INLINE void setRigidBodyFlagsInternal(const PxRigidBodyFlags& currentFlags, const PxRigidBodyFlags& newFlags); public: #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif PX_FORCE_INLINE bool isKinematic() const { return (APIClass::getConcreteType() == PxConcreteType::eRIGID_DYNAMIC) && (mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC); } PX_INLINE void scSetSolverIterationCounts(PxU16 c) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setSolverIterationCounts(c); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetLockFlags(PxRigidDynamicLockFlags f) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setRigidDynamicLockFlags(f); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetBody2World(const PxTransform& p) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setBody2World(p); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetCMassLocalPose(const PxTransform& newBody2Actor) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setCMassLocalPose(newBody2Actor); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetLinearVelocity(const PxVec3& v) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setLinearVelocity(v); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetAngularVelocity(const PxVec3& v) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setAngularVelocity(v); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scWakeUpInternal(PxReal wakeCounter) { PX_ASSERT(RigidActorTemplateClass::getNpScene()); PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.wakeUp(wakeCounter); } PX_FORCE_INLINE void scWakeUp() { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); NpScene* scene = RigidActorTemplateClass::getNpScene(); PX_ASSERT(scene); // only allowed for an object in a scene scWakeUpInternal(scene->getWakeCounterResetValueInternal()); } PX_INLINE void scPutToSleepInternal() { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.putToSleep(); } PX_FORCE_INLINE void scPutToSleep() { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); scPutToSleepInternal(); } PX_INLINE void scSetWakeCounter(PxReal w) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setWakeCounter(w); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetFlags(PxRigidBodyFlags f) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbidden()); mCore.setFlags(f); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scAddSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.addSpatialAcceleration(linAcc, angAcc); //Spatial acceleration isn't sent to PVD. } PX_INLINE void scSetSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setSpatialAcceleration(linAcc, angAcc); //Spatial acceleration isn't sent to PVD. } PX_INLINE void scClearSpatialAcceleration(bool force, bool torque) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.clearSpatialAcceleration(force, torque); //Spatial acceleration isn't sent to PVD. } PX_INLINE void scAddSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.addSpatialVelocity(linVelDelta, angVelDelta); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scClearSpatialVelocity(bool force, bool torque) { PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.clearSpatialVelocity(force, torque); UPDATE_PVD_PROPERTY_BODY } PX_INLINE void scSetKinematicTarget(const PxTransform& p) { NpScene* scene = RigidActorTemplateClass::getNpScene(); PX_ASSERT(scene); // only allowed for an object in a scene const PxReal wakeCounterResetValue = scene->getWakeCounterResetValueInternal(); PX_ASSERT(!RigidActorTemplateClass::isAPIWriteForbiddenExceptSplitSim()); mCore.setKinematicTarget(p, wakeCounterResetValue); UPDATE_PVD_PROPERTY_BODY #if PX_SUPPORT_PVD scene->getScenePvdClientInternal().updateKinematicTarget(this, p); #endif } PX_INLINE PxMat33 scGetGlobalInertiaTensorInverse() const { PxMat33 inverseInertiaWorldSpace; Cm::transformInertiaTensor(mCore.getInverseInertia(), PxMat33Padded(mCore.getBody2World().q), inverseInertiaWorldSpace); return inverseInertiaWorldSpace; } PX_FORCE_INLINE bool scCheckSleepReadinessBesidesWakeCounter() { return (getLinearVelocity().isZero() && getAngularVelocity().isZero()); // no need to test for pending force updates yet since currently this is not supported on scene insertion } protected: Sc::BodyCore mCore; }; template<class APIClass> NpRigidBodyTemplate<APIClass>::NpRigidBodyTemplate(PxType concreteType, PxBaseFlags baseFlags, PxActorType::Enum type, NpType::Enum npType, const PxTransform& bodyPose) : RigidActorTemplateClass (concreteType, baseFlags, npType), mCore (type, bodyPose) { } template<class APIClass> NpRigidBodyTemplate<APIClass>::~NpRigidBodyTemplate() { } namespace { PX_FORCE_INLINE static bool hasNegativeMass(const PxShape& shape) { const PxGeometry& geom = shape.getGeometry(); const PxGeometryType::Enum t = geom.getType(); if (t == PxGeometryType::eTRIANGLEMESH) { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const Gu::TriangleMesh* mesh = static_cast<const Gu::TriangleMesh*>(triGeom.triangleMesh); return mesh->getSdfDataFast().mSdf != NULL && mesh->getMass() < 0.f; } return false; } PX_FORCE_INLINE static bool isDynamicMesh(const PxGeometry& geom) { const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(geom); const Gu::TriangleMesh* mesh = static_cast<const Gu::TriangleMesh*>(triGeom.triangleMesh); return mesh->getSdfDataFast().mSdf != NULL && mesh->getMass() > 0.f; } PX_FORCE_INLINE static bool isSimGeom(const PxShape& shape) { const PxGeometryType::Enum t = shape.getGeometry().getType(); return t != PxGeometryType::ePLANE && t != PxGeometryType::eHEIGHTFIELD && t != PxGeometryType::eTETRAHEDRONMESH && (t != PxGeometryType::eTRIANGLEMESH || isDynamicMesh(shape.getGeometry())); } } template<class APIClass> bool NpRigidBodyTemplate<APIClass>::attachShape(PxShape& shape) { NP_WRITE_CHECK(RigidActorTemplateClass::getNpScene()); PX_CHECK_AND_RETURN_VAL(!(shape.getFlags() & PxShapeFlag::eSIMULATION_SHAPE) || !hasNegativeMass(shape) || isKinematic(), "attachShape: The faces of the mesh are oriented the wrong way round leading to a negative mass. Please invert the orientation of all faces and try again.", false); PX_CHECK_AND_RETURN_VAL(!(shape.getFlags() & PxShapeFlag::eSIMULATION_SHAPE) || isSimGeom(shape) || isKinematic(), "attachShape: non-SDF triangle mesh, tetrahedron mesh, heightfield or plane geometry shapes configured as eSIMULATION_SHAPE are not supported for non-kinematic PxRigidDynamic instances.", false); return RigidActorTemplateClass::attachShape(shape); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setCMassLocalPoseInternal(const PxTransform& body2Actor) { //the point here is to change the mass distribution w/o changing the actors' pose in the world // AD note: I added an interface directly into the bodycore and pushed calculations there to avoid // NP and BP transform/bounds update notifications because this does not change the global pose. scSetCMassLocalPose(body2Actor); RigidActorTemplateClass::updateShaderComs(); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, cMassLocalPose, static_cast<PxRigidBody&>(*this), body2Actor) } template<class APIClass> PxTransform NpRigidBodyTemplate<APIClass>::getCMassLocalPose() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getBody2Actor(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMass(PxReal mass) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(mass), "PxRigidBody::setMass(): invalid float"); PX_CHECK_AND_RETURN(mass>=0, "PxRigidBody::setMass(): mass must be non-negative!"); PX_CHECK_AND_RETURN(this->getType() != PxActorType::eARTICULATION_LINK || mass > 0.0f, "PxRigidBody::setMass(): components must be > 0 for articulations"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMass() not allowed while simulation is running. Call will be ignored.") mCore.setInverseMass(mass > 0.0f ? 1.0f/mass : 0.0f); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, mass, static_cast<PxRigidBody&>(*this), mass) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMass() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); const PxReal invMass = mCore.getInverseMass(); return invMass > 0.0f ? 1.0f/invMass : 0.0f; } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getInvMass() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getInverseMass(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMassSpaceInertiaTensor(const PxVec3& m) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(m.isFinite(), "PxRigidBody::setMassSpaceInertiaTensor(): invalid inertia"); PX_CHECK_AND_RETURN(m.x>=0.0f && m.y>=0.0f && m.z>=0.0f, "PxRigidBody::setMassSpaceInertiaTensor(): components must be non-negative"); PX_CHECK_AND_RETURN(this->getType() != PxActorType::eARTICULATION_LINK || (m.x > 0.0f && m.y > 0.0f && m.z > 0.0f), "PxRigidBody::setMassSpaceInertiaTensor(): components must be > 0 for articulations"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMassSpaceInertiaTensor() not allowed while simulation is running. Call will be ignored.") mCore.setInverseInertia(invertDiagInertia(m)); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, massSpaceInertiaTensor, static_cast<PxRigidBody&>(*this), m) } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getMassSpaceInertiaTensor() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return invertDiagInertia(mCore.getInverseInertia()); } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getMassSpaceInvInertiaTensor() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getInverseInertia(); } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getLinearVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(RigidActorTemplateClass::getNpScene(), "PxRigidBody::getLinearVelocity() not allowed while simulation is running (except during PxScene::collide()).", PxVec3(PxZero)); return mCore.getLinearVelocity(); } template<class APIClass> PxVec3 NpRigidBodyTemplate<APIClass>::getAngularVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_EXCEPT_COLLIDE_AND_RETURN_VAL(RigidActorTemplateClass::getNpScene(), "PxRigidBody::getAngularVelocity() not allowed while simulation is running (except during PxScene::collide()).", PxVec3(PxZero)); return mCore.getAngularVelocity(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::addSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); switch (mode) { case PxForceMode::eFORCE: { PxVec3 linAcc, angAcc; if (force) { linAcc = (*force) * mCore.getInverseMass(); force = &linAcc; } if (torque) { angAcc = scGetGlobalInertiaTensorInverse() * (*torque); torque = &angAcc; } scAddSpatialAcceleration(force, torque); } break; case PxForceMode::eACCELERATION: scAddSpatialAcceleration(force, torque); break; case PxForceMode::eIMPULSE: { PxVec3 linVelDelta, angVelDelta; if (force) { linVelDelta = ((*force) * mCore.getInverseMass()); force = &linVelDelta; } if (torque) { angVelDelta = (scGetGlobalInertiaTensorInverse() * (*torque)); torque = &angVelDelta; } scAddSpatialVelocity(force, torque); } break; case PxForceMode::eVELOCITY_CHANGE: scAddSpatialVelocity(force, torque); break; } } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setSpatialForce(const PxVec3* force, const PxVec3* torque, PxForceMode::Enum mode) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); switch (mode) { case PxForceMode::eFORCE: { PxVec3 linAcc, angAcc; if (force) { linAcc = (*force) * mCore.getInverseMass(); force = &linAcc; } if (torque) { angAcc = scGetGlobalInertiaTensorInverse() * (*torque); torque = &angAcc; } scSetSpatialAcceleration(force, torque); } break; case PxForceMode::eACCELERATION: scSetSpatialAcceleration(force, torque); break; case PxForceMode::eIMPULSE: { PxVec3 linVelDelta, angVelDelta; if (force) { linVelDelta = ((*force) * mCore.getInverseMass()); force = &linVelDelta; } if (torque) { angVelDelta = (scGetGlobalInertiaTensorInverse() * (*torque)); torque = &angVelDelta; } scAddSpatialVelocity(force, torque); } break; case PxForceMode::eVELOCITY_CHANGE: scAddSpatialVelocity(force, torque); break; } } template<class APIClass> void NpRigidBodyTemplate<APIClass>::clearSpatialForce(PxForceMode::Enum mode, bool force, bool torque) { PX_ASSERT(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC)); switch (mode) { case PxForceMode::eFORCE: case PxForceMode::eACCELERATION: scClearSpatialAcceleration(force, torque); break; case PxForceMode::eIMPULSE: case PxForceMode::eVELOCITY_CHANGE: scClearSpatialVelocity(force, torque); break; } } #if PX_ENABLE_DEBUG_VISUALIZATION template<class APIClass> void NpRigidBodyTemplate<APIClass>::visualize(PxRenderOutput& out, NpScene& scene, float scale) const { RigidActorTemplateClass::visualize(out, scene, scale); visualizeRigidBody(out, scene, *this, mCore, scale); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif template<class APIClass> PX_FORCE_INLINE void NpRigidBodyTemplate<APIClass>::setRigidBodyFlagsInternal(const PxRigidBodyFlags& currentFlags, const PxRigidBodyFlags& newFlags) { PxRigidBodyFlags filteredNewFlags = newFlags; //Test to ensure we are not enabling both CCD and kinematic state on a body. This is unsupported if((filteredNewFlags & PxRigidBodyFlag::eENABLE_CCD) && (filteredNewFlags & PxRigidBodyFlag::eKINEMATIC)) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBody::setRigidBodyFlag(): kinematic bodies with CCD enabled are not supported! CCD will be ignored."); filteredNewFlags &= PxRigidBodyFlags(~PxRigidBodyFlag::eENABLE_CCD); } NpScene* scene = RigidActorTemplateClass::getNpScene(); Sc::Scene* scScene = scene ? &scene->getScScene() : NULL; const bool isKinematic = currentFlags & PxRigidBodyFlag::eKINEMATIC; const bool willBeKinematic = filteredNewFlags & PxRigidBodyFlag::eKINEMATIC; const bool kinematicSwitchingToDynamic = isKinematic && (!willBeKinematic); const bool dynamicSwitchingToKinematic = (!isKinematic) && willBeKinematic; bool mustUpdateSQ = false; if(kinematicSwitchingToDynamic) { NpShapeManager& shapeManager = this->getShapeManager(); PxU32 nbShapes = shapeManager.getNbShapes(); NpShape*const* shapes = shapeManager.getShapes(); bool hasTriangleMesh = false; for(PxU32 i=0;i<nbShapes;i++) { if((shapes[i]->getFlags() & PxShapeFlag::eSIMULATION_SHAPE) && (shapes[i]->getGeometryTypeFast()==PxGeometryType::eTRIANGLEMESH || shapes[i]->getGeometryTypeFast()==PxGeometryType::ePLANE || shapes[i]->getGeometryTypeFast()==PxGeometryType::eHEIGHTFIELD)) { hasTriangleMesh = true; break; } } if(hasTriangleMesh) { PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBody::setRigidBodyFlag(): dynamic meshes/planes/heightfields are not supported!"); return; } PxTransform bodyTarget; if ((currentFlags & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) && mCore.getKinematicTarget(bodyTarget) && scene) mustUpdateSQ = true; if(scScene) { scScene->decreaseNumKinematicsCounter(); scScene->increaseNumDynamicsCounter(); } } else if (dynamicSwitchingToKinematic) { if (this->getType() == PxActorType::eARTICULATION_LINK) { //We're an articulation, raise an issue PxGetFoundation().error(physx::PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxRigidBody::setRigidBodyFlag(): kinematic articulation links are not supported!"); return; } if(scScene) { scScene->decreaseNumDynamicsCounter(); scScene->increaseNumKinematicsCounter(); } } const bool kinematicSwitchingUseTargetForSceneQuery = isKinematic && willBeKinematic && ((currentFlags & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) != (filteredNewFlags & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES)); if (kinematicSwitchingUseTargetForSceneQuery) { PxTransform bodyTarget; if (mCore.getKinematicTarget(bodyTarget) && scene) mustUpdateSQ = true; } scSetFlags(filteredNewFlags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, rigidBodyFlags, static_cast<PxRigidBody&>(*this), filteredNewFlags) // PT: the SQ update should be done after the scSetFlags() call if(mustUpdateSQ) this->getShapeManager().markActorForSQUpdate(scene->getSQAPI(), *this); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setRigidBodyFlag(PxRigidBodyFlag::Enum flag, bool value) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setRigidBodyFlag() not allowed while simulation is running. Call will be ignored.") const PxRigidBodyFlags currentFlags = mCore.getFlags(); const PxRigidBodyFlags newFlags = value ? currentFlags | flag : currentFlags & (~PxRigidBodyFlags(flag)); setRigidBodyFlagsInternal(currentFlags, newFlags); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setRigidBodyFlags(PxRigidBodyFlags inFlags) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setRigidBodyFlags() not allowed while simulation is running. Call will be ignored.") const PxRigidBodyFlags currentFlags = mCore.getFlags(); setRigidBodyFlagsInternal(currentFlags, inFlags); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMinCCDAdvanceCoefficient(PxReal minCCDAdvanceCoefficient) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMinCCDAdvanceCoefficient() not allowed while simulation is running. Call will be ignored.") mCore.setCCDAdvanceCoefficient(minCCDAdvanceCoefficient); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, minAdvancedCCDCoefficient, static_cast<PxRigidBody&>(*this), minCCDAdvanceCoefficient) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMinCCDAdvanceCoefficient() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getCCDAdvanceCoefficient(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxDepenetrationVelocity(PxReal maxDepenVel) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(maxDepenVel > 0.0f, "PxRigidBody::setMaxDepenetrationVelocity(): maxDepenVel must be greater than zero."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxDepenetrationVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxPenetrationBias(-maxDepenVel); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxDepenetrationVelocity, static_cast<PxRigidBody&>(*this), maxDepenVel) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxDepenetrationVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return -mCore.getMaxPenetrationBias(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxContactImpulse(const PxReal maxImpulse) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(maxImpulse >= 0.f, "PxRigidBody::setMaxContactImpulse(): impulse limit must be greater than or equal to zero."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxContactImpulse() not allowed while simulation is running. Call will be ignored.") mCore.setMaxContactImpulse(maxImpulse); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxContactImpulse, static_cast<PxRigidBody&>(*this), maxImpulse) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxContactImpulse() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getMaxContactImpulse(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setContactSlopCoefficient(const PxReal contactSlopCoefficient) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(contactSlopCoefficient >= 0.f, "PxRigidBody::setContactSlopCoefficient(): contact slop coefficientmust be greater than or equal to zero."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setContactSlopCoefficient() not allowed while simulation is running. Call will be ignored.") mCore.setOffsetSlop(contactSlopCoefficient); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, contactSlopCoefficient, static_cast<PxRigidBody&>(*this), contactSlopCoefficient) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getContactSlopCoefficient() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getOffsetSlop(); } template<class APIClass> PxNodeIndex NpRigidBodyTemplate<APIClass>::getInternalIslandNodeIndex() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getInternalIslandNodeIndex(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setLinearDamping(PxReal linearDamping) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(linearDamping), "PxRigidBody::setLinearDamping(): invalid float"); PX_CHECK_AND_RETURN(linearDamping >= 0, "PxRigidBody::setLinearDamping(): The linear damping must be nonnegative!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setLinearDamping() not allowed while simulation is running. Call will be ignored.") mCore.setLinearDamping(linearDamping); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearDamping, static_cast<PxRigidBody&>(*this), linearDamping) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getLinearDamping() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getLinearDamping(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setAngularDamping(PxReal angularDamping) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(angularDamping), "PxRigidBody::setAngularDamping(): invalid float"); PX_CHECK_AND_RETURN(angularDamping>=0, "PxRigidBody::setAngularDamping(): The angular damping must be nonnegative!") PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setAngularDamping() not allowed while simulation is running. Call will be ignored.") mCore.setAngularDamping(angularDamping); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularDamping, static_cast<PxRigidBody&>(*this), angularDamping) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getAngularDamping() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return mCore.getAngularDamping(); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxAngularVelocity(PxReal maxAngularVelocity) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(maxAngularVelocity), "PxRigidBody::setMaxAngularVelocity(): invalid float"); PX_CHECK_AND_RETURN(maxAngularVelocity>=0.0f, "PxRigidBody::setMaxAngularVelocity(): threshold must be non-negative!"); PX_CHECK_AND_RETURN(maxAngularVelocity <= PxReal(1.00000003e+16f), "PxRigidBody::setMaxAngularVelocity(): maxAngularVelocity*maxAngularVelocity must be less than 1e16"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxAngularVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxAngVelSq(maxAngularVelocity * maxAngularVelocity); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxAngularVelocity, static_cast<PxRigidBody&>(*this), maxAngularVelocity) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxAngularVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return PxSqrt(mCore.getMaxAngVelSq()); } template<class APIClass> void NpRigidBodyTemplate<APIClass>::setMaxLinearVelocity(PxReal maxLinearVelocity) { NpScene* npScene = RigidActorTemplateClass::getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(maxLinearVelocity), "PxRigidBody::setMaxLinearVelocity(): invalid float"); PX_CHECK_AND_RETURN(maxLinearVelocity >= 0.0f, "PxRigidBody::setMaxLinearVelocity(): threshold must be non-negative!"); PX_CHECK_AND_RETURN(maxLinearVelocity <= PxReal(1.00000003e+16), "PxRigidBody::setMaxLinearVelocity(): maxLinearVelocity*maxLinearVelocity must be less than 1e16"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidBody::setMaxLinearVelocity() not allowed while simulation is running. Call will be ignored.") mCore.setMaxLinVelSq(maxLinearVelocity * maxLinearVelocity); UPDATE_PVD_PROPERTY_BODY OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, maxLinearVelocity, static_cast<PxRigidBody&>(*this), maxLinearVelocity) } template<class APIClass> PxReal NpRigidBodyTemplate<APIClass>::getMaxLinearVelocity() const { NP_READ_CHECK(RigidActorTemplateClass::getNpScene()); return PxSqrt(mCore.getMaxLinVelSq()); } } #endif
34,983
C
36.536481
258
0.739816
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMetaData.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 "PxPhysicsSerialization.h" #include "NpShape.h" #include "NpShapeManager.h" #include "NpConstraint.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpArticulationReducedCoordinate.h" #include "NpArticulationLink.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationSensor.h" #include "NpArticulationTendon.h" #include "NpAggregate.h" #include "NpPruningStructure.h" #include "NpMaterial.h" #include "NpFEMSoftBodyMaterial.h" #include "NpFEMClothMaterial.h" #include "NpMPMMaterial.h" #include "NpFLIPMaterial.h" #include "NpPBDMaterial.h" #include "GuConvexMesh.h" #include "GuTriangleMesh.h" #include "GuTriangleMeshBV4.h" #include "GuTriangleMeshRTree.h" #include "GuHeightField.h" #include "GuPrunerMergeData.h" using namespace physx; using namespace Cm; using namespace Gu; /////////////////////////////////////////////////////////////////////////////// // PT: the offsets can be different for different templated classes so I need macros here. #define DefineMetaData_PxActor(x) \ PX_DEF_BIN_METADATA_ITEM(stream, x, void, userData, PxMetaDataFlag::ePTR) #define DefineMetaData_NpRigidActorTemplate(x) \ PX_DEF_BIN_METADATA_ITEM(stream, x, NpShapeManager, mShapeManager, 0) // PX_DEF_BIN_METADATA_ITEM(stream, x, PxU32, mIndex, 0) #define DefineMetaData_NpRigidBodyTemplate(x) \ PX_DEF_BIN_METADATA_ITEM(stream, x, Sc::BodyCore, mCore, 0) /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PxVec3(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxVec3) PX_DEF_BIN_METADATA_ITEM(stream, PxVec3, PxReal, x, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec3, PxReal, y, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec3, PxReal, z, 0) } static void getBinaryMetaData_PxVec4(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxVec4) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, x, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, y, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, z, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxVec4, PxReal, w, 0) } static void getBinaryMetaData_PxQuat(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxQuat) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, x, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, y, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, z, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxQuat, PxReal, w, 0) } static void getBinaryMetaData_PxBounds3(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxBounds3) PX_DEF_BIN_METADATA_ITEM(stream, PxBounds3, PxVec3, minimum, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxBounds3, PxVec3, maximum, 0) } static void getBinaryMetaData_PxTransform(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxTransform) PX_DEF_BIN_METADATA_ITEM(stream, PxTransform, PxQuat, q, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxTransform, PxVec3, p, 0) } static void getBinaryMetaData_PxTransform32(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxTransform32) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxTransform32, PxTransform) PX_DEF_BIN_METADATA_ITEM(stream, PxTransform32, PxU32, padding, 0) } static void getBinaryMetaData_PxMat33(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxMat33) PX_DEF_BIN_METADATA_ITEM(stream, PxMat33, PxVec3, column0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxMat33, PxVec3, column1, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxMat33, PxVec3, column2, 0) } static void getBinaryMetaData_SpatialVectorF(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, Cm::SpatialVectorF) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxVec3, top, 0) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxReal, pad0, 0) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxVec3, bottom, 0) PX_DEF_BIN_METADATA_ITEM(stream, Cm::SpatialVectorF, PxReal, pad1, 0) } namespace { class ShadowBitMap : public PxBitMap { public: static void getBinaryMetaData(PxOutputStream& stream_) { PX_DEF_BIN_METADATA_CLASS(stream_, ShadowBitMap) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBitMap, PxU32, mMap, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBitMap, PxU32, mWordCount, 0) PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBitMap, PxAllocator, mAllocator, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream_, ShadowBitMap, PxU8, mPadding, PxMetaDataFlag::ePADDING) //------ Extra-data ------ // mMap PX_DEF_BIN_METADATA_EXTRA_ARRAY(stream_, ShadowBitMap, PxU32, mWordCount, PX_SERIAL_ALIGN, PxMetaDataFlag::eCOUNT_MASK_MSB) } }; } static void getBinaryMetaData_BitMap(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxAllocator, PxU8) ShadowBitMap::getBinaryMetaData(stream); PX_DEF_BIN_METADATA_TYPEDEF(stream, BitMap, ShadowBitMap) } static void getBinaryMetaData_PxPlane(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxPlane) PX_DEF_BIN_METADATA_ITEM(stream, PxPlane, PxVec3, n, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxPlane, PxReal, d, 0) } static void getBinaryMetaData_PxConstraintInvMassScale(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxConstraintInvMassScale) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, linear0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, angular0, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, linear1, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxConstraintInvMassScale, PxReal, angular1, 0) } /////////////////////////////////////////////////////////////////////////////// void NpBase::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, NpType::Enum, PxU32) PX_DEF_BIN_METADATA_CLASS(stream, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpBase, NpScene, mScene, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpBase, PxU32, mBaseIndexAndType, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpBase, PxU32, mFreeSlot, 0) } /////////////////////////////////////////////////////////////////////////////// void NpActor::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpActor) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpActor, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpActor, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpActor, NpConnectorArray, mConnectorArray, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void NpMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpMaterial, PxsMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// void NpFEMSoftBodyMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpFEMSoftBodyMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpFEMSoftBodyMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMSoftBodyMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMSoftBodyMaterial, PxsFEMSoftBodyMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpFEMClothMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpFEMClothMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpFEMClothMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMClothMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpFEMClothMaterial, PxsFEMClothMaterialCore, mMaterial, 0) } #endif /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpPBDMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpPBDMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpPBDMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpPBDMaterial, PxsPBDMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION void NpFLIPMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpFLIPMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpFLIPMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpFLIPMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpFLIPMaterial, PxsFLIPMaterialCore, mMaterial, 0) } /////////////////////////////////////////////////////////////////////////////// void NpMPMMaterial::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpMPMMaterial) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpMPMMaterial, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpMPMMaterial, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpMPMMaterial, PxsMPMMaterialCore, mMaterial, 0) } #endif /////////////////////////////////////////////////////////////////////////////// void NpConstraint::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpConstraint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpConstraint, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpConstraint, NpBase) // PxConstraint PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, void, userData, PxMetaDataFlag::ePTR) // NpConstraint PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, PxRigidActor, mActor0, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, PxRigidActor, mActor1, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpConstraint, ConstraintCore, mCore, 0) } /////////////////////////////////////////////////////////////////////////////// void NpShapeManager::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpShapeManager) PX_DEF_BIN_METADATA_ITEM(stream, NpShapeManager, PtrTable, mShapes, 0) // PX_DEF_BIN_METADATA_ITEM(stream, NpShapeManager, PxU32, mSqCompoundId, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpShapeManager, Sq::PruningStructure, mPruningStructure, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void NpShape::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpShape) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpShape, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpShape, NpBase) // PxShape PX_DEF_BIN_METADATA_ITEM(stream, NpShape, void, userData, PxMetaDataFlag::ePTR) // NpShape PX_DEF_BIN_METADATA_ITEM(stream, NpShape, PxRigidActor, mExclusiveShapeActor, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpShape, ShapeCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpShape, PxFilterData, mQueryFilterData, 0) } /////////////////////////////////////////////////////////////////////////////// void NpRigidStatic::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpRigidStatic) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidStatic, PxBase) // PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidStatic, NpRigidStaticT) // ### ??? PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidStatic, NpActor) DefineMetaData_PxActor(NpRigidStatic) DefineMetaData_NpRigidActorTemplate(NpRigidStatic) // NpRigidStatic PX_DEF_BIN_METADATA_ITEM(stream, NpRigidStatic, Sc::StaticCore, mCore, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, NpRigidStatic, NpConnectorArray, mConnectorArray, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpRigidStatic, mName, 0) } /////////////////////////////////////////////////////////////////////////////// void NpConnector::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpConnector) PX_DEF_BIN_METADATA_ITEM(stream, NpConnector, PxU8, mType, 0) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, NpConnector, PxU8, mPadding, PxMetaDataFlag::ePADDING) PX_DEF_BIN_METADATA_ITEM(stream, NpConnector, PxBase, mObject, PxMetaDataFlag::ePTR) } void NpConnectorArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpConnectorArray) PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, NpConnectorArray, NpConnector, mBuffer, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitly in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpConnectorArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, NpConnector, mData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpConnectorArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpConnectorArray, NpConnector, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB, 0) } /////////////////////////////////////////////////////////////////////////////// void NpRigidDynamic::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpRigidDynamic) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidDynamic, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpRigidDynamic, NpActor) DefineMetaData_PxActor(NpRigidDynamic) DefineMetaData_NpRigidActorTemplate(NpRigidDynamic) DefineMetaData_NpRigidBodyTemplate(NpRigidDynamic) // NpRigidDynamic //------ Extra-data ------ // Extra data: // - inline array from shape manager // - optional constraint array // PX_DEF_BIN_METADATA_ITEM(stream,NpRigidDynamic, NpShapeManager, mShapeManager.mShapes, 0) /* virtual void exportExtraData(PxOutputStream& stream) { mShapeManager.exportExtraData(stream); ActorTemplateClass::exportExtraData(stream); } void NpActorTemplate<APIClass, LeafClass>::exportExtraData(PxOutputStream& stream) { if(mConnectorArray) { stream.storeBuffer(mConnectorArray, sizeof(NpConnectorArray) mConnectorArray->exportExtraData(stream); } } */ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, NpRigidDynamic, NpConnectorArray, mConnectorArray, PX_SERIAL_ALIGN) //### missing inline array data here... only works for "buffered" arrays so far /* Big issue: we can't output the "offset of" the inline array within the class, since the inline array itself is extra-data. But we need to read the array itself to know if it's inline or not (the "is buffered" bool). So we need to read from the extra data! */ /* [17:41:39] Gordon Yeoman nvidia: PxsBodyCore need to be 16-byte aligned for spu. If it is 128-byte aligned then that is a mistake. Feel free to change it to 16. */ PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpRigidDynamic, mName, 0) } /////////////////////////////////////////////////////////////////////////////// void NpArticulationLinkArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpArticulationLinkArray) PX_DEF_BIN_METADATA_ITEMS(stream, NpArticulationLinkArray, NpArticulationLink, mBuffer, PxMetaDataFlag::ePTR, 4) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitely in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpArticulationLinkArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, NpArticulationLink, mData, PxMetaDataFlag::ePTR) // ### PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLinkArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpArticulationLinkArray, NpArticulationLink, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) } void NpArticulationAttachmentArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpArticulationAttachmentArray) PX_DEF_BIN_METADATA_ITEMS(stream, NpArticulationAttachmentArray, NpArticulationAttachment, mBuffer, PxMetaDataFlag::ePTR, 4) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitely in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpArticulationAttachmentArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, NpArticulationAttachment, mData, PxMetaDataFlag::ePTR) // ### PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachmentArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpArticulationAttachmentArray, NpArticulationAttachment, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) } namespace { struct ShadowLoopJointArray : public PxArray<PxConstraint*> { static void getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, ShadowLoopJointArray) PX_DEF_BIN_METADATA_ITEM(stream, ShadowLoopJointArray, NpConstraint, mData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, ShadowLoopJointArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, ShadowLoopJointArray, PxU32, mCapacity, 0) } }; #define DECL_SHADOW_PTR_ARRAY(T) \ struct ShadowArray##T : public PxArray<T*> \ { \ static void getBinaryMetaData(PxOutputStream& stream) \ { \ PX_DEF_BIN_METADATA_CLASS(stream, ShadowArray##T) \ PX_DEF_BIN_METADATA_ITEM(stream, ShadowArray##T, T, mData, PxMetaDataFlag::ePTR)\ PX_DEF_BIN_METADATA_ITEM(stream, ShadowArray##T, PxU32, mSize, 0) \ PX_DEF_BIN_METADATA_ITEM(stream, ShadowArray##T, PxU32, mCapacity, 0) \ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, ShadowArray##T, T, mData, mCapacity, PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) \ } \ }; DECL_SHADOW_PTR_ARRAY(NpArticulationSpatialTendon) DECL_SHADOW_PTR_ARRAY(NpArticulationFixedTendon) DECL_SHADOW_PTR_ARRAY(NpArticulationSensor) } void NpArticulationReducedCoordinate::getBinaryMetaData(PxOutputStream& stream) { ShadowLoopJointArray::getBinaryMetaData(stream); ShadowArrayNpArticulationSpatialTendon::getBinaryMetaData(stream); ShadowArrayNpArticulationFixedTendon::getBinaryMetaData(stream); ShadowArrayNpArticulationSensor::getBinaryMetaData(stream); //sticking this here, since typedefs are only allowed to declared once. PX_DEF_BIN_METADATA_TYPEDEF(stream, ArticulationTendonHandle, PxU32) PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationReducedCoordinate) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationReducedCoordinate, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationReducedCoordinate, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ArticulationCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, NpArticulationLinkArray, mArticulationLinks, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, PxU32, mNumShapes, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, NpAggregate, mAggregate, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, char, mName, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpArticulationReducedCoordinate, mName, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, PxU32, mCacheVersion, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, bool, mTopologyChanged, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowLoopJointArray, mLoopJoints, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowArrayNpArticulationSpatialTendon, mSpatialTendons, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowArrayNpArticulationFixedTendon, mFixedTendons, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationReducedCoordinate, ShadowArrayNpArticulationSensor, mSensors, 0) } void NpArticulationSensor::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationSensor) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSensor, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSensor, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, PxArticulationLink, mLink, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, ArticulationSensorCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSensor, PxU32, mHandle, 0) } void NpArticulationAttachment::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationAttachment) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationAttachment, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationAttachment, NpBase) PX_DEF_BIN_METADATA_TYPEDEF(stream, ArticulationAttachmentHandle, PxU32); PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, PxArticulationLink, mLink, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, PxArticulationAttachment, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, ArticulationAttachmentHandle, mHandle, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, NpArticulationAttachmentArray, mChildren, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, NpArticulationSpatialTendon, mTendon, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationAttachment, ArticulationAttachmentCore, mCore, 0) } void NpArticulationTendonJoint::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationTendonJoint) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationTendonJoint, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationTendonJoint, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, PxArticulationLink, mLink, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, PxArticulationTendonJoint, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, NpArticulationTendonJointArray, mChildren, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, NpArticulationFixedTendon, mTendon, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, ArticulationTendonJointCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJoint, PxU32, mHandle, 0) } void NpArticulationTendonJointArray::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, NpArticulationTendonJointArray) PX_DEF_BIN_METADATA_ITEMS(stream, NpArticulationTendonJointArray, NpArticulationTendonJoint, mBuffer, PxMetaDataFlag::ePTR, 4) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, bool, mBufferUsed, 0) // PT: OMG this is so painful... I can't put the padding explicitely in the template { PxMetaDataEntry tmp = {"char", "mPadding", 1 + PxU32(PX_OFFSET_OF_RT(NpArticulationTendonJointArray, mBufferUsed)), 3, 3, 0, PxMetaDataFlag::ePADDING, 0}; PX_STORE_METADATA(stream, tmp); } PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, NpArticulationTendonJoint, mData, PxMetaDataFlag::ePTR) // ### PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, PxU32, mSize, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationTendonJointArray, PxU32, mCapacity, 0) //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpArticulationTendonJointArray, NpArticulationTendonJoint, mBufferUsed, mCapacity, PxMetaDataFlag::eCONTROL_FLIP|PxMetaDataFlag::eCOUNT_MASK_MSB|PxMetaDataFlag::ePTR, 0) } void NpArticulationSpatialTendon::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationSpatialTendon) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSpatialTendon, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationSpatialTendon, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, NpArticulationAttachmentArray, mAttachments, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, NpArticulationReducedCoordinate, mArticulation, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, PxU32, mLLIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, ArticulationSpatialTendonCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationSpatialTendon, ArticulationTendonHandle, mHandle, 0) } void NpArticulationFixedTendon::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationFixedTendon) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationFixedTendon, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationFixedTendon, NpBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, NpArticulationTendonJointArray, mTendonJoints, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, NpArticulationReducedCoordinate, mArticulation, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, PxU32, mLLIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, ArticulationFixedTendonCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationFixedTendon, ArticulationTendonHandle, mHandle, 0) } void NpArticulationLink::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationLink) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationLink, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationLink, NpActor) DefineMetaData_PxActor(NpArticulationLink) DefineMetaData_NpRigidActorTemplate(NpArticulationLink) DefineMetaData_NpRigidBodyTemplate(NpArticulationLink) // NpArticulationLink PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulation, mRoot, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulationJoint, mInboundJoint, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulationLink, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, NpArticulationLinkArray, mChildLinks, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, PxU32, mLLIndex, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationLink, PxU32, mInboundJointDof, 0); //------ Extra-data ------ PX_DEF_BIN_METADATA_EXTRA_ITEM(stream, NpArticulationLink, NpConnectorArray, mConnectorArray, PX_SERIAL_ALIGN) PX_DEF_BIN_METADATA_EXTRA_NAME(stream, NpArticulationLink, mName, 0) } void NpArticulationJointReducedCoordinate::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpArticulationJointReducedCoordinate) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationJointReducedCoordinate, NpBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpArticulationJointReducedCoordinate, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, void, userData, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, ArticulationJointCore, mCore, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, NpArticulationLink, mParent, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, NpArticulationJointReducedCoordinate, NpArticulationLink, mChild, PxMetaDataFlag::ePTR) } /////////////////////////////////////////////////////////////////////////////// void NpAggregate::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, NpAggregate) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpAggregate, PxBase) PX_DEF_BIN_METADATA_BASE_CLASS(stream, NpAggregate, NpBase) // PxAggregate PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, void, userData, PxMetaDataFlag::ePTR) // NpAggregate PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mAggregateID, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mMaxNbActors, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mMaxNbShapes, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mFilterHint, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mNbActors, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxU32, mNbShapes, 0) PX_DEF_BIN_METADATA_ITEM(stream, NpAggregate, PxActor, mActors, PxMetaDataFlag::ePTR) //------ Extra-data ------ // mActors PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, NpAggregate, PxActor, mActors, mNbActors, PxMetaDataFlag::ePTR, PX_SERIAL_ALIGN) } /////////////////////////////////////////////////////////////////////////////// static void getBinaryMetaData_PxMeshScale(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, PxMeshScale) PX_DEF_BIN_METADATA_ITEM(stream, PxMeshScale, PxVec3, scale, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxMeshScale, PxQuat, rotation, 0) } static void getBinaryMetaData_AABBPrunerMergeData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_CLASS(stream, AABBPrunerMergeData) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, PxU32, mNbNodes, 0) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, Gu::BVHNode, mAABBTreeNodes, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, PxU32, mNbObjects, 0) PX_DEF_BIN_METADATA_ITEM(stream, AABBPrunerMergeData, PxU32, mAABBTreeIndices, PxMetaDataFlag::ePTR) } void Sq::PruningStructure::getBinaryMetaData(PxOutputStream& stream) { getBinaryMetaData_AABBPrunerMergeData(stream); PX_DEF_BIN_METADATA_VCLASS(stream, PruningStructure) PX_DEF_BIN_METADATA_BASE_CLASS(stream, PruningStructure, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, AABBPrunerMergeData, mData[0], 0) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, AABBPrunerMergeData, mData[1], 0) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, PxU32, mNbActors, 0) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, PxActor*, mActors, PxMetaDataFlag::ePTR) PX_DEF_BIN_METADATA_ITEM(stream, PruningStructure, bool, mValid, 0) } /////////////////////////////////////////////////////////////////////////////// namespace physx { void getBinaryMetaData_PxBase(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxBaseFlags, PxU16) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxType, PxU16) PX_DEF_BIN_METADATA_VCLASS(stream, PxBase) PX_DEF_BIN_METADATA_ITEM(stream, PxBase, PxType, mConcreteType, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxBase, PxBaseFlags, mBaseFlags, 0) PX_DEF_BIN_METADATA_ITEM(stream, PxBase, PxI32, mBuiltInRefCount, 0) } } void RefCountable::getBinaryMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_VCLASS(stream, RefCountable) PX_DEF_BIN_METADATA_ITEM(stream, RefCountable, PxI32, mRefCount, 0) } static void getFoundationMetaData(PxOutputStream& stream) { PX_DEF_BIN_METADATA_TYPEDEF(stream, PxU8, char) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxI8, char) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxU16, short) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxI16, short) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxU32, int) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxI32, int) PX_DEF_BIN_METADATA_TYPEDEF(stream, PxReal, float) getBinaryMetaData_PxVec3(stream); getBinaryMetaData_PxVec4(stream); getBinaryMetaData_PxQuat(stream); getBinaryMetaData_PxBounds3(stream); getBinaryMetaData_PxTransform(stream); getBinaryMetaData_PxTransform32(stream); getBinaryMetaData_PxMat33(stream); getBinaryMetaData_SpatialVectorF(stream); getBinaryMetaData_BitMap(stream); Cm::PtrTable::getBinaryMetaData(stream); getBinaryMetaData_PxPlane(stream); getBinaryMetaData_PxConstraintInvMassScale(stream); getBinaryMetaData_PxBase(stream); RefCountable::getBinaryMetaData(stream); } /////////////////////////////////////////////////////////////////////////////// namespace physx { template<> void PxsMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsFEMSoftBodyMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsFEMClothMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsPBDMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsFLIPMaterialCore::getBinaryMetaData(PxOutputStream& stream); template<> void PxsMPMMaterialCore::getBinaryMetaData(PxOutputStream& stream); } void PxGetPhysicsBinaryMetaData(PxOutputStream& stream) { getFoundationMetaData(stream); getBinaryMetaData_PxMeshScale(stream); Gu::ConvexMesh::getBinaryMetaData(stream); Gu::TriangleMesh::getBinaryMetaData(stream); Gu::RTreeTriangleMesh::getBinaryMetaData(stream); Gu::BV4TriangleMesh::getBinaryMetaData(stream); Gu::HeightField::getBinaryMetaData(stream); PxsMaterialCore::getBinaryMetaData(stream); PxsFEMSoftBodyMaterialCore::getBinaryMetaData(stream); PxsFEMClothMaterialCore::getBinaryMetaData(stream); PxsPBDMaterialCore::getBinaryMetaData(stream); PxsFLIPMaterialCore::getBinaryMetaData(stream); PxsMPMMaterialCore::getBinaryMetaData(stream); MaterialIndicesStruct::getBinaryMetaData(stream); GeometryUnion::getBinaryMetaData(stream); Sc::ActorCore::getBinaryMetaData(stream); Sc::RigidCore::getBinaryMetaData(stream); Sc::StaticCore::getBinaryMetaData(stream); Sc::BodyCore::getBinaryMetaData(stream); Sc::ShapeCore::getBinaryMetaData(stream); Sc::ConstraintCore::getBinaryMetaData(stream); Sc::ArticulationCore::getBinaryMetaData(stream); Sc::ArticulationJointCore::getBinaryMetaData(stream); Sc::ArticulationSensorCore::getBinaryMetaData(stream); Sc::ArticulationTendonCore::getBinaryMetaData(stream); Sc::ArticulationSpatialTendonCore::getBinaryMetaData(stream); Sc::ArticulationAttachmentCore::getBinaryMetaData(stream); Sc::ArticulationFixedTendonCore::getBinaryMetaData(stream); Sc::ArticulationTendonJointCore::getBinaryMetaData(stream); NpConnector::getBinaryMetaData(stream); NpConnectorArray::getBinaryMetaData(stream); NpBase::getBinaryMetaData(stream); NpActor::getBinaryMetaData(stream); NpMaterial::getBinaryMetaData(stream); NpFEMSoftBodyMaterial::getBinaryMetaData(stream); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFEMClothMaterial::getBinaryMetaData(stream); #endif NpPBDMaterial::getBinaryMetaData(stream); #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFLIPMaterial::getBinaryMetaData(stream); NpMPMMaterial::getBinaryMetaData(stream); #endif NpRigidDynamic::getBinaryMetaData(stream); NpRigidStatic::getBinaryMetaData(stream); NpShape::getBinaryMetaData(stream); NpConstraint::getBinaryMetaData(stream); NpArticulationReducedCoordinate::getBinaryMetaData(stream); NpArticulationLink::getBinaryMetaData(stream); NpArticulationJointReducedCoordinate::getBinaryMetaData(stream); NpArticulationLinkArray::getBinaryMetaData(stream); NpArticulationSensor::getBinaryMetaData(stream); NpArticulationSpatialTendon::getBinaryMetaData(stream); NpArticulationFixedTendon::getBinaryMetaData(stream); NpArticulationAttachment::getBinaryMetaData(stream); NpArticulationAttachmentArray::getBinaryMetaData(stream); NpArticulationTendonJoint::getBinaryMetaData(stream); NpArticulationTendonJointArray::getBinaryMetaData(stream); NpShapeManager::getBinaryMetaData(stream); NpAggregate::getBinaryMetaData(stream); }
38,206
C++
44.811751
210
0.75407
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdTypeNames.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 PVD_TYPE_NAMES_H #define PVD_TYPE_NAMES_H #if PX_SUPPORT_PVD #include "geometry/PxHeightFieldSample.h" #include "PxPvdObjectModelBaseTypes.h" #include "PxMetaDataObjects.h" namespace physx { namespace Vd { struct PvdSqHit; struct PvdRaycast; struct PvdOverlap; struct PvdSweep; struct PvdHullPolygonData { PxU16 mNumVertices; PxU16 mIndexBase; PvdHullPolygonData(PxU16 numVert, PxU16 idxBase) : mNumVertices(numVert), mIndexBase(idxBase) { } }; struct PxArticulationLinkUpdateBlock { PxTransform GlobalPose; PxVec3 LinearVelocity; PxVec3 AngularVelocity; }; struct PxArticulationJointUpdateBlock { PxReal JointPosition_eX; PxReal JointPosition_eY; PxReal JointPosition_eZ; PxReal JointPosition_eTwist; PxReal JointPosition_eSwing1; PxReal JointPosition_eSwing2; PxReal JointVelocity_eX; PxReal JointVelocity_eY; PxReal JointVelocity_eZ; PxReal JointVelocity_eTwist; PxReal JointVelocity_eSwing1; PxReal JointVelocity_eSwing2; }; struct PxRigidDynamicUpdateBlock : public PxArticulationLinkUpdateBlock { bool IsSleeping; }; struct PvdContact { PxVec3 point; PxVec3 axis; const void* shape0; const void* shape1; PxF32 separation; PxF32 normalForce; PxU32 internalFaceIndex0; PxU32 internalFaceIndex1; bool normalForceAvailable; }; struct PvdPositionAndRadius { PxVec3 position; PxF32 radius; }; } //Vd } //physx 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(PxPhysics) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxScene) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTolerancesScale) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTolerancesScaleGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSceneDescGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSceneDesc) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSimulationStatistics) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSimulationStatisticsGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxMaterial) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxMaterialGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMSoftBodyMaterial) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMSoftBodyMaterialGeneratedValues) // DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMClothMaterial) // jcarius: Commented-out until FEMCloth is not under construction anymore // DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxFEMClothMaterialGeneratedValues) // jcarius: Commented-out until FEMCloth is not under construction anymore DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPBDMaterial) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPBDMaterialGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightField) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldDesc) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldDescGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTriangleMesh) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTetrahedronMesh) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConvexMesh) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxActor) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidActor) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidBody) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidDynamic) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidDynamicGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidStatic) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxRigidStaticGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxShape) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxShapeGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxBoxGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPlaneGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCapsuleGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSphereGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTriangleMeshGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTetrahedronMeshGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConvexMeshGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCustomGeometry) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxBoxGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxPlaneGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCapsuleGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxSphereGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTetrahedronMeshGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxTriangleMeshGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConvexMeshGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxCustomGeometryGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxHeightFieldSample) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConstraint) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxConstraintGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationReducedCoordinate) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationReducedCoordinateGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationLink) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationLinkGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationJointReducedCoordinate) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxArticulationJointReducedCoordinateGeneratedValues) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxAggregate) DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP(PxAggregateGeneratedValues) #undef DEFINE_NATIVE_PVD_PHYSX3_TYPE_MAP #define DEFINE_NATIVE_PVD_TYPE_MAP(type) DEFINE_PVD_TYPE_NAME_MAP(physx::Vd::type, "physx3", #type) DEFINE_NATIVE_PVD_TYPE_MAP(PvdHullPolygonData) DEFINE_NATIVE_PVD_TYPE_MAP(PxRigidDynamicUpdateBlock) DEFINE_NATIVE_PVD_TYPE_MAP(PxArticulationLinkUpdateBlock) DEFINE_NATIVE_PVD_TYPE_MAP(PxArticulationJointUpdateBlock) DEFINE_NATIVE_PVD_TYPE_MAP(PvdContact) DEFINE_NATIVE_PVD_TYPE_MAP(PvdRaycast) DEFINE_NATIVE_PVD_TYPE_MAP(PvdSweep) DEFINE_NATIVE_PVD_TYPE_MAP(PvdOverlap) DEFINE_NATIVE_PVD_TYPE_MAP(PvdSqHit) DEFINE_NATIVE_PVD_TYPE_MAP(PvdPositionAndRadius) #undef DEFINE_NATIVE_PVD_TYPE_MAP DEFINE_PVD_TYPE_ALIAS(physx::PxFilterData, U32Array4) } } #endif #endif
7,640
C
37.590909
146
0.821073
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterial.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 NP_MATERIAL_H #define NP_MATERIAL_H #include "common/PxSerialFramework.h" #include "foundation/PxUserAllocated.h" #include "foundation/PxUtilities.h" #include "CmRefCountable.h" #include "PxsMaterialCore.h" namespace physx { // Compared to other objects, materials are special since they belong to the SDK and not to scenes // (similar to meshes). That's why the NpMaterial does have direct access to the core material instead // of having a buffered interface for it. Scenes will have copies of the SDK material table and there // the materials will be buffered. class NpMaterial : public PxMaterial, public PxUserAllocated { public: // PX_SERIALIZATION NpMaterial(PxBaseFlags baseFlags) : PxMaterial(baseFlags), mMaterial(PxEmpty) {} virtual void resolveReferences(PxDeserializationContext& context); static NpMaterial* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); } void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} virtual void requiresObjects(PxProcessPxBaseCallback&){} //~PX_SERIALIZATION NpMaterial(const PxsMaterialCore& desc); virtual ~NpMaterial(); // PxBase virtual void release() PX_OVERRIDE; //~PxBase // PxRefCounted virtual void acquireReference() PX_OVERRIDE; virtual PxU32 getReferenceCount() const PX_OVERRIDE; virtual void onRefCountZero() PX_OVERRIDE; //~PxRefCounted // PxMaterial virtual void setDynamicFriction(PxReal) PX_OVERRIDE; virtual PxReal getDynamicFriction() const PX_OVERRIDE; virtual void setStaticFriction(PxReal) PX_OVERRIDE; virtual PxReal getStaticFriction() const PX_OVERRIDE; virtual void setRestitution(PxReal) PX_OVERRIDE; virtual PxReal getRestitution() const PX_OVERRIDE; virtual void setDamping(PxReal) PX_OVERRIDE; virtual PxReal getDamping() const PX_OVERRIDE; virtual void setFlag(PxMaterialFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setFlags(PxMaterialFlags inFlags) PX_OVERRIDE; virtual PxMaterialFlags getFlags() const PX_OVERRIDE; virtual void setFrictionCombineMode(PxCombineMode::Enum) PX_OVERRIDE; virtual PxCombineMode::Enum getFrictionCombineMode() const PX_OVERRIDE; virtual void setRestitutionCombineMode(PxCombineMode::Enum) PX_OVERRIDE; virtual PxCombineMode::Enum getRestitutionCombineMode() const PX_OVERRIDE; //~PxMaterial PX_FORCE_INLINE static void getMaterialIndices(PxMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount); private: PX_INLINE void updateMaterial(); // PX_SERIALIZATION public: //~PX_SERIALIZATION PxsMaterialCore mMaterial; }; PX_FORCE_INLINE void NpMaterial::getMaterialIndices(PxMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount) { for(PxU32 i=0; i < materialCount; i++) materialIndices[i] = static_cast<NpMaterial*>(materials[i])->mMaterial.mMaterialIndex; } } #endif
4,816
C
43.19266
125
0.761005
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpActorTemplate.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 NP_ACTOR_TEMPLATE_H #define NP_ACTOR_TEMPLATE_H #include "NpCheck.h" #include "NpActor.h" #include "NpScene.h" #include "omnipvd/NpOmniPvdSetData.h" namespace physx { // PT: only API (virtual) functions should be implemented here. Other shared non-virtual functions should go to NpActor. /** This is an API class. API classes run in a different thread than the simulation. For the sake of simplicity they have their own methods, and they do not call simulation methods directly. To set simulation state, they also have their own custom set methods in the implementation classes. Changing the data layout of this class breaks the binary serialization format. See comments for PX_BINARY_SERIAL_VERSION. */ template<class APIClass> class NpActorTemplate : public APIClass, public NpActor { PX_NOCOPY(NpActorTemplate) public: // PX_SERIALIZATION NpActorTemplate(PxBaseFlags baseFlags) : APIClass(baseFlags), NpActor(PxEmpty) {} virtual void exportExtraData(PxSerializationContext& context) { NpActor::exportExtraData(context); } virtual void importExtraData(PxDeserializationContext& context) { NpActor::importExtraData(context); } virtual void resolveReferences(PxDeserializationContext& context) { NpActor::resolveReferences(context); } //~PX_SERIALIZATION NpActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type); virtual ~NpActorTemplate(); // The rule is: If an API method is used somewhere in here, it has to be redeclared, else GCC whines // PxActor virtual void release() = 0; virtual PxActorType::Enum getType() const = 0; virtual PxScene* getScene() const PX_OVERRIDE; virtual void setName(const char*) PX_OVERRIDE; virtual const char* getName() const PX_OVERRIDE; virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0; virtual void setActorFlag(PxActorFlag::Enum flag, bool value) PX_OVERRIDE; virtual void setActorFlags(PxActorFlags inFlags) PX_OVERRIDE; virtual PxActorFlags getActorFlags() const PX_OVERRIDE; virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) PX_OVERRIDE; virtual PxDominanceGroup getDominanceGroup() const PX_OVERRIDE; virtual void setOwnerClient( PxClientID inClient ) PX_OVERRIDE; virtual PxClientID getOwnerClient() const PX_OVERRIDE; virtual PxAggregate* getAggregate() const PX_OVERRIDE { return NpActor::getAggregate(); } //~PxActor protected: PX_FORCE_INLINE void setActorFlagInternal(PxActorFlag::Enum flag, bool value); PX_FORCE_INLINE void setActorFlagsInternal(PxActorFlags inFlags); }; /////////////////////////////////////////////////////////////////////////////// template<class APIClass> NpActorTemplate<APIClass>::NpActorTemplate(PxType concreteType, PxBaseFlags baseFlags, NpType::Enum type) : APIClass(concreteType, baseFlags), NpActor (type) { PX_ASSERT(!APIClass::userData); } template<class APIClass> NpActorTemplate<APIClass>::~NpActorTemplate() { NpActor::onActorRelease(this); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> PxScene* NpActorTemplate<APIClass>::getScene() const { return getNpScene(); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> void NpActorTemplate<APIClass>::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(getNpScene(), "PxActor::setName() not allowed while simulation is running. Call will be ignored.") mName = debugName; #if PX_SUPPORT_OMNI_PVD PxActor & a = *this; streamActorName(a, mName); #endif #if PX_SUPPORT_PVD NpScene* npScene = getNpScene(); //Name changing is not bufferred if(npScene) npScene->getScenePvdClientInternal().updatePvdProperties(static_cast<NpActor*>(this)); #endif } template<class APIClass> const char* NpActorTemplate<APIClass>::getName() const { NP_READ_CHECK(getNpScene()); return mName; } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> void NpActorTemplate<APIClass>::setDominanceGroup(PxDominanceGroup dominanceGroup) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxActor::setDominanceGroup() not allowed while simulation is running. Call will be ignored.") NpActor::scSetDominanceGroup(dominanceGroup); } template<class APIClass> PxDominanceGroup NpActorTemplate<APIClass>::getDominanceGroup() const { NP_READ_CHECK(getNpScene()); return NpActor::getDominanceGroup(); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> void NpActorTemplate<APIClass>::setOwnerClient( PxClientID inId ) { if ( getNpScene() != NULL ) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Attempt to set the client id when an actor is already in a scene."); } else NpActor::scSetOwnerClient( inId ); } template<class APIClass> PxClientID NpActorTemplate<APIClass>::getOwnerClient() const { return NpActor::getOwnerClient(); } /////////////////////////////////////////////////////////////////////////////// template<class APIClass> PX_FORCE_INLINE void NpActorTemplate<APIClass>::setActorFlagInternal(PxActorFlag::Enum flag, bool value) { NpActor& a = *this; if (value) a.scSetActorFlags( a.getActorFlags() | flag ); else a.scSetActorFlags( a.getActorFlags() & (~PxActorFlags(flag)) ); } template<class APIClass> PX_FORCE_INLINE void NpActorTemplate<APIClass>::setActorFlagsInternal(PxActorFlags inFlags) { NpActor::scSetActorFlags(inFlags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxActor, flags, static_cast<PxActor&>(*this), inFlags) } template<class APIClass> void NpActorTemplate<APIClass>::setActorFlag(PxActorFlag::Enum flag, bool value) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxActor::setActorFlag() not allowed while simulation is running. Call will be ignored.") setActorFlagInternal(flag, value); } template<class APIClass> void NpActorTemplate<APIClass>::setActorFlags(PxActorFlags inFlags) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxActor::setActorFlags() not allowed while simulation is running. Call will be ignored.") setActorFlagsInternal(inFlags); } template<class APIClass> PxActorFlags NpActorTemplate<APIClass>::getActorFlags() const { NP_READ_CHECK(getNpScene()); return NpActor::getActorFlags(); } /////////////////////////////////////////////////////////////////////////////// } #endif
8,361
C
33.697095
151
0.714867
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpConstraint.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 NP_CONSTRAINT_H #define NP_CONSTRAINT_H #include "foundation/PxUserAllocated.h" #include "PxConstraint.h" #include "NpBase.h" #include "../../../simulationcontroller/include/ScConstraintCore.h" #include "NpActor.h" namespace physx { class NpScene; class NpConstraint : public PxConstraint, public NpBase { public: // PX_SERIALIZATION NpConstraint(PxBaseFlags baseFlags) : PxConstraint(baseFlags), NpBase(PxEmpty), mCore(PxEmpty) {} static NpConstraint* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() {} void exportExtraData(PxSerializationContext&) {} void importExtraData(PxDeserializationContext&) {} void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback&) {} virtual bool isSubordinate() const { return true; } //~PX_SERIALIZATION NpConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize); virtual ~NpConstraint(); // PxConstraint virtual void release() PX_OVERRIDE; virtual PxScene* getScene() const PX_OVERRIDE; virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const PX_OVERRIDE; virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) PX_OVERRIDE; virtual void markDirty() PX_OVERRIDE; virtual PxConstraintFlags getFlags() const PX_OVERRIDE; virtual void setFlags(PxConstraintFlags flags) PX_OVERRIDE; virtual void setFlag(PxConstraintFlag::Enum flag, bool value) PX_OVERRIDE; virtual void getForce(PxVec3& linear, PxVec3& angular) const PX_OVERRIDE; virtual bool isValid() const PX_OVERRIDE; virtual void setBreakForce(PxReal linear, PxReal angular) PX_OVERRIDE; virtual void getBreakForce(PxReal& linear, PxReal& angular) const PX_OVERRIDE; virtual void setMinResponseThreshold(PxReal threshold) PX_OVERRIDE; virtual PxReal getMinResponseThreshold() const PX_OVERRIDE; virtual void* getExternalReference(PxU32& typeID) PX_OVERRIDE; virtual void setConstraintFunctions(PxConstraintConnector& n, const PxConstraintShaderTable& t) PX_OVERRIDE; //~PxConstraint void updateConstants(PxsSimulationController& simController); void comShift(PxRigidActor*); void actorDeleted(PxRigidActor*); NpScene* getSceneFromActors() const; PX_FORCE_INLINE Sc::ConstraintCore& getCore() { return mCore; } PX_FORCE_INLINE const Sc::ConstraintCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpConstraint, mCore); } PX_FORCE_INLINE bool isDirty() const { return mCore.isDirty(); } PX_FORCE_INLINE void markClean() { mCore.clearDirty(); } private: PxRigidActor* mActor0; PxRigidActor* mActor1; Sc::ConstraintCore mCore; void addConnectors(PxRigidActor* actor0, PxRigidActor* actor1); void removeConnectors(const char* errorMsg0, const char* errorMsg1); PX_INLINE void scSetFlags(PxConstraintFlags f) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setFlags(f); markDirty(); UPDATE_PVD_PROPERTY } }; } #endif
5,170
C
46.440367
159
0.723985
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMClothMaterial.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 "NpFEMClothMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX using namespace physx; using namespace Cm; #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFEMClothMaterial::NpFEMClothMaterial(const PxsFEMClothMaterialCore& desc) : PxFEMClothMaterial(PxConcreteType::eCLOTH_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpFEMClothMaterial::~NpFEMClothMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpFEMClothMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: why commented out? //NpPhysics::getInstance().addFEMMaterial(this); } void NpFEMClothMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releaseFEMClothMaterialToPool(*this); } else this->~NpFEMClothMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpFEMClothMaterial* NpFEMClothMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpFEMClothMaterial* obj = PX_PLACEMENT_NEW(address, NpFEMClothMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpFEMClothMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpFEMClothMaterial::release() { RefCountable_decRefCount(*this); } void NpFEMClothMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpFEMClothMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpFEMClothMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setYoungsModulus(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMClothMaterial::setYoungsModulus: invalid float"); mMaterial.youngs = x; updateMaterial(); } PxReal NpFEMClothMaterial::getYoungsModulus() const { return mMaterial.youngs; } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setPoissons(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f && x < 0.5f, "PxFEMClothMaterial::setPoissons: invalid float"); mMaterial.poissons = x; updateMaterial(); } PxReal NpFEMClothMaterial::getPoissons() const { return mMaterial.poissons; } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setDynamicFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFEMClothMaterial::setDynamicFriction: invalid float"); mMaterial.dynamicFriction = x; updateMaterial(); } PxReal NpFEMClothMaterial::getDynamicFriction() const { return mMaterial.dynamicFriction; } /////////////////////////////////////////////////////////////////////////////// void NpFEMClothMaterial::setThickness(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFEMClothMaterial::setThickness: invalid float"); mMaterial.thickness = x; updateMaterial(); } PxReal NpFEMClothMaterial::getThickness() const { return mMaterial.thickness; } ////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #endif #endif
5,489
C++
30.371428
108
0.703771
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpAggregate.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 "NpAggregate.h" #include "PxActor.h" #include "NpRigidStatic.h" #include "NpRigidDynamic.h" #include "NpActor.h" #include "GuBVH.h" #include "CmUtils.h" #include "NpArticulationReducedCoordinate.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; using namespace Gu; namespace { #if PX_SUPPORT_PVD PX_FORCE_INLINE void PvdAttachActorToAggregate(NpAggregate* pAggregate, NpActor* pscActor) { NpScene* npScene = pAggregate->getNpScene(); if(npScene/* && scScene->getScenePvdClient().isInstanceValid(pAggregate)*/) npScene->getScenePvdClientInternal().attachAggregateActor( pAggregate, pscActor ); } PX_FORCE_INLINE void PvdDetachActorFromAggregate(NpAggregate* pAggregate, NpActor* pscActor) { NpScene* npScene = pAggregate->getNpScene(); if(npScene/*&& scScene->getScenePvdClient().isInstanceValid(pAggregate)*/) npScene->getScenePvdClientInternal().detachAggregateActor( pAggregate, pscActor ); } PX_FORCE_INLINE void PvdUpdateProperties(NpAggregate* pAggregate) { NpScene* npScene = pAggregate->getNpScene(); if(npScene /*&& scScene->getScenePvdClient().isInstanceValid(pAggregate)*/) npScene->getScenePvdClientInternal().updatePvdProperties( pAggregate ); } #else #define PvdAttachActorToAggregate(aggregate, scActor) {} #define PvdDetachActorFromAggregate(aggregate, scActor) {} #define PvdUpdateProperties(aggregate) {} #endif } /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// PX_FORCE_INLINE void setAggregate(NpAggregate* aggregate, PxActor& actor) { NpActor& np = NpActor::getFromPxActor(actor); np.setAggregate(aggregate, actor); } /////////////////////////////////////////////////////////////////////////////// NpAggregate::NpAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint) : PxAggregate (PxConcreteType::eAGGREGATE, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), NpBase (NpType::eAGGREGATE), mAggregateID (PX_INVALID_U32), mMaxNbActors (maxActors), mMaxNbShapes (maxShapes), mFilterHint (filterHint), mNbActors (0), mNbShapes (0) { mActors = PX_ALLOCATE(PxActor*, maxActors, "PxActor*"); } NpAggregate::~NpAggregate() { NpFactory::getInstance().onAggregateRelease(this); if(getBaseFlags()&PxBaseFlag::eOWNS_MEMORY) PX_FREE(mActors); } void NpAggregate::scAddActor(NpActor& actor) { PX_ASSERT(!isAPIWriteForbidden()); actor.getActorCore().setAggregateID(mAggregateID); PvdAttachActorToAggregate( this, &actor ); PvdUpdateProperties( this ); } void NpAggregate::scRemoveActor(NpActor& actor, bool reinsert) { PX_ASSERT(!isAPIWriteForbidden()); Sc::ActorCore& ac = actor.getActorCore(); ac.setAggregateID(PX_INVALID_U32); if(getNpScene() && reinsert) ac.reinsertShapes(); //Update pvd status PvdDetachActorFromAggregate( this, &actor ); PvdUpdateProperties( this ); } void NpAggregate::removeAndReinsert(PxActor& actor, bool reinsert) { NpActor& np = NpActor::getFromPxActor(actor); np.setAggregate(NULL, actor); scRemoveActor(np, reinsert); } void NpAggregate::release() { NpScene* s = getNpScene(); NP_WRITE_CHECK(s); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(s, "PxAggregate::release() not allowed while simulation is running. Call will be ignored.") PX_SIMD_GUARD; NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, NULL); // "An aggregate should be empty when it gets released. If it isn't, the behavior should be: remove the actors from // the aggregate, then remove the aggregate from the scene (if any) then delete it. I guess that implies the actors // get individually reinserted into the broad phase if the aggregate is in a scene." for(PxU32 i=0;i<mNbActors;i++) { if (mActors[i]->getType() == PxActorType::eARTICULATION_LINK) { NpArticulationLink* link = static_cast<NpArticulationLink*>(mActors[i]); NpArticulationReducedCoordinate& articulation = static_cast<NpArticulationReducedCoordinate&>(link->getRoot()); articulation.setAggregate(NULL); } removeAndReinsert(*mActors[i], true); } if(s) { s->scRemoveAggregate(*this); s->removeFromAggregateList(*this); } NpDestroyAggregate(this); } void NpAggregate::addActorInternal(PxActor& actor, NpScene& s, const PxBVH* bvh) { if (actor.getType() != PxActorType::eARTICULATION_LINK) { NpActor& np = NpActor::getFromPxActor(actor); scAddActor(np); s.addActorInternal(actor, bvh); } else if (!actor.getScene()) // This check makes sure that a link of an articulation gets only added once. { NpArticulationLink& al = static_cast<NpArticulationLink&>(actor); PxArticulationReducedCoordinate& npArt = al.getRoot(); for(PxU32 i=0; i < npArt.getNbLinks(); i++) { PxArticulationLink* link; npArt.getLinks(&link, 1, i); scAddActor(*static_cast<NpArticulationLink*>(link)); } s.addArticulationInternal(npArt); } } void NpAggregate::addToScene(NpScene& scene) { const PxU32 nb = mNbActors; for(PxU32 i=0;i<nb;i++) { PX_ASSERT(mActors[i]); PxActor& actor = *mActors[i]; //A.B. check if a bvh was connected to that actor, we will use it for the insert and remove it NpActor& npActor = NpActor::getFromPxActor(actor); BVH* bvh = NULL; if(npActor.getConnectors<BVH>(NpConnectorType::eBvh, &bvh, 1)) npActor.removeConnector(actor, NpConnectorType::eBvh, bvh, "PxBVH connector could not have been removed!"); addActorInternal(actor, scene, bvh); // if a bvh was used dec ref count, we increased the ref count when adding the actor connection if(bvh) bvh->decRefCount(); } } bool NpAggregate::addActor(PxActor& actor, const PxBVH* bvh) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::addActor() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if(mNbActors==mMaxNbActors) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, max number of actors reached"); PxRigidActor* rigidActor = actor.is<PxRigidActor>(); PxU32 numShapes = 0; if(rigidActor) { numShapes = rigidActor->getNbShapes(); if ((mNbShapes + numShapes) > mMaxNbShapes) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, max number of shapes reached"); } if(actor.getAggregate()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, actor already belongs to an aggregate"); if(actor.getScene()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add actor to aggregate, actor already belongs to a scene"); const PxType ctype = actor.getConcreteType(); if(ctype == PxConcreteType::eARTICULATION_LINK) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation link to aggregate, only whole articulations can be added"); if(PxGetAggregateType(mFilterHint)==PxAggregateType::eSTATIC && ctype != PxConcreteType::eRIGID_STATIC) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add non-static actor to static aggregate"); if(PxGetAggregateType(mFilterHint)==PxAggregateType::eKINEMATIC) { bool isKine = false; if(ctype == PxConcreteType::eRIGID_DYNAMIC) { PxRigidDynamic& dyna = static_cast<PxRigidDynamic&>(actor); isKine = dyna.getRigidBodyFlags().isSet(PxRigidBodyFlag::eKINEMATIC); } if(!isKine) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add non-kinematic actor to kinematic aggregate"); } setAggregate(this, actor); mActors[mNbActors++] = &actor; mNbShapes += numShapes; OMNI_PVD_ADD(OMNI_PVD_CONTEXT_HANDLE, PxAggregate, actors, static_cast<PxAggregate&>(*this), actor); // PT: when an object is added to a aggregate at runtime, i.e. when the aggregate has already been added to the scene, // we need to immediately add the newcomer to the scene as well. if(npScene) { addActorInternal(actor, *npScene, bvh); } else { // A.B. if BVH is provided we need to keep it stored till the aggregate is inserted into a scene if(bvh) { PxBVH* bvhMutable = const_cast<PxBVH*>(bvh); static_cast<BVH*>(bvhMutable)->incRefCount(); NpActor::getFromPxActor(actor).addConnector(NpConnectorType::eBvh, bvhMutable, "PxBVH already added to the PxActor!"); } } return true; } bool NpAggregate::removeActorAndReinsert(PxActor& actor, bool reinsert) { for(PxU32 i=0;i<mNbActors;i++) { if(mActors[i]==&actor) { PxRigidActor* rigidActor = actor.is<PxRigidActor>(); if(rigidActor) mNbShapes -= rigidActor->getNbShapes(); mActors[i] = mActors[--mNbActors]; removeAndReinsert(actor, reinsert); return true; } } return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't remove actor, actor doesn't belong to aggregate"); } bool NpAggregate::removeActor(PxActor& actor) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::removeActor() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if(actor.getType() == PxActorType::eARTICULATION_LINK) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't remove articulation link, only whole articulations can be removed"); // A.B. remove the BVH reference if there is and the aggregate was not added to a scene if(!npScene) { NpActor& np = NpActor::getFromPxActor(actor); BVH* bvh = NULL; if(np.getConnectors<BVH>(NpConnectorType::eBvh, &bvh, 1)) { np.removeConnector(actor, NpConnectorType::eBvh, bvh, "PxBVH connector could not have been removed!"); bvh->decRefCount(); } } OMNI_PVD_REMOVE(OMNI_PVD_CONTEXT_HANDLE, PxAggregate, actors, static_cast<PxAggregate&>(*this), actor); // PT: there are really 2 cases here: // a) the user just wants to remove the actor from the aggregate, but the actor is still alive so if the aggregate has been added to a scene, // we must reinsert the removed actor to that same scene // b) this is called by the framework when releasing an actor, in which case we don't want to reinsert it anywhere. // // We assume that when called by the user, we always want to reinsert. The framework however will call the internal function // without reinsertion. return removeActorAndReinsert(actor, true); } bool NpAggregate::addArticulation(PxArticulationReducedCoordinate& art) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::addArticulation() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; if((mNbActors+art.getNbLinks()) > mMaxNbActors) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation links, max number of actors reached"); const PxU32 numShapes = art.getNbShapes(); if((mNbShapes + numShapes) > mMaxNbShapes) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation, max number of shapes reached"); if(art.getAggregate()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation to aggregate, articulation already belongs to an aggregate"); if(art.getScene()) return outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't add articulation to aggregate, articulation already belongs to a scene"); NpArticulationReducedCoordinate* impl = static_cast<NpArticulationReducedCoordinate*>(&art); impl->setAggregate(this); NpArticulationLink* const* links = impl->getLinks(); for(PxU32 i=0; i < impl->getNbLinks(); i++) { NpArticulationLink& l = *links[i]; setAggregate(this, l); mActors[mNbActors++] = &l; scAddActor(l); } mNbShapes += numShapes; // PT: when an object is added to a aggregate at runtime, i.e. when the aggregate has already been added to the scene, // we need to immediately add the newcomer to the scene as well. if(npScene) npScene->addArticulationInternal(art); return true; } bool NpAggregate::removeArticulationAndReinsert(PxArticulationReducedCoordinate& art, bool reinsert) { bool found = false; PxU32 idx = 0; while(idx < mNbActors) { if ((mActors[idx]->getType() == PxActorType::eARTICULATION_LINK) && (&static_cast<NpArticulationLink*>(mActors[idx])->getRoot() == &art)) { PxActor* a = mActors[idx]; mNbShapes -= static_cast<NpArticulationLink*>(mActors[idx])->getNbShapes(); mActors[idx] = mActors[--mNbActors]; removeAndReinsert(*a, reinsert); found = true; } else idx++; } static_cast<NpArticulationReducedCoordinate&>(art).setAggregate(NULL); if(!found) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxAggregate: can't remove articulation, articulation doesn't belong to aggregate"); return found; } bool NpAggregate::removeArticulation(PxArticulationReducedCoordinate& art) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(npScene, "PxAggregate::removeArticulation() not allowed while simulation is running. Call will be ignored.", false); PX_SIMD_GUARD; // see comments in removeActor() return removeArticulationAndReinsert(art, true); } PxU32 NpAggregate::getNbActors() const { NP_READ_CHECK(getNpScene()); return mNbActors; } PxU32 NpAggregate::getMaxNbActors() const { NP_READ_CHECK(getNpScene()); return mMaxNbActors; } PxU32 NpAggregate::getMaxNbShapes() const { NP_READ_CHECK(getNpScene()); return mMaxNbShapes; } PxU32 NpAggregate::getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { NP_READ_CHECK(getNpScene()); return Cm::getArrayOfPointers(userBuffer, bufferSize, startIndex, mActors, getCurrentSizeFast()); } PxScene* NpAggregate::getScene() { return getNpScene(); } bool NpAggregate::getSelfCollision() const { NP_READ_CHECK(getNpScene()); return getSelfCollideFast(); } // PX_SERIALIZATION void NpAggregate::preExportDataReset() { mAggregateID = PX_INVALID_U32; } void NpAggregate::exportExtraData(PxSerializationContext& stream) { if(mActors) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mActors, mNbActors * sizeof(PxActor*)); } } void NpAggregate::importExtraData(PxDeserializationContext& context) { if(mActors) mActors = context.readExtraData<PxActor*, PX_SERIAL_ALIGN>(mNbActors); } void NpAggregate::resolveReferences(PxDeserializationContext& context) { // Resolve actor pointers if needed for(PxU32 i=0; i < mNbActors; i++) { context.translatePxBase(mActors[i]); { //update aggregate if mActors is in external reference NpActor& np = NpActor::getFromPxActor(*mActors[i]); if(np.getAggregate() == NULL) { np.setAggregate(this, *mActors[i]); } if(mActors[i]->getType() == PxActorType::eARTICULATION_LINK) { PxArticulationReducedCoordinate& articulation = static_cast<NpArticulationLink*>(mActors[i])->getRoot(); if(!articulation.getAggregate()) static_cast<NpArticulationReducedCoordinate&>(articulation).setAggregate(this); } } } } NpAggregate* NpAggregate::createObject(PxU8*& address, PxDeserializationContext& context) { NpAggregate* obj = PX_PLACEMENT_NEW(address, NpAggregate(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpAggregate); obj->importExtraData(context); obj->resolveReferences(context); return obj; } void NpAggregate::requiresObjects(PxProcessPxBaseCallback& c) { for(PxU32 i=0; i < mNbActors; i++) { PxArticulationLink* link = mActors[i]->is<PxArticulationLink>(); if(link) c.process(link->getArticulation()); else c.process(*mActors[i]); } } // ~PX_SERIALIZATION void NpAggregate::incShapeCount() { if(mNbShapes == mMaxNbShapes) outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "PxRigidActor::attachShape: Actor is part of an aggregate and max number of shapes reached!"); mNbShapes++; } void NpAggregate::decShapeCount() { PX_ASSERT(mNbShapes > 0); mNbShapes--; }
17,839
C++
31.377495
167
0.730478
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpAggregate.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 NP_AGGREGATE_H #define NP_AGGREGATE_H #include "PxAggregate.h" #include "NpBase.h" namespace physx { class NpScene; class NpAggregate : public PxAggregate, public NpBase { public: // PX_SERIALIZATION NpAggregate(PxBaseFlags baseFlags) : PxAggregate(baseFlags), NpBase(PxEmpty) {} void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& context); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpAggregate* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION NpAggregate(PxU32 maxActors, PxU32 maxShapes, PxAggregateFilterHint filterHint); virtual ~NpAggregate(); // PxAggregate virtual void release() PX_OVERRIDE; virtual bool addActor(PxActor&, const PxBVH*) PX_OVERRIDE; virtual bool removeActor(PxActor&) PX_OVERRIDE; virtual bool addArticulation(PxArticulationReducedCoordinate&) PX_OVERRIDE; virtual bool removeArticulation(PxArticulationReducedCoordinate&) PX_OVERRIDE; virtual PxU32 getNbActors() const PX_OVERRIDE; virtual PxU32 getMaxNbActors() const PX_OVERRIDE; virtual PxU32 getMaxNbShapes() const PX_OVERRIDE; virtual PxU32 getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE; virtual PxScene* getScene() PX_OVERRIDE; virtual bool getSelfCollision() const PX_OVERRIDE; //~PxAggregate PX_FORCE_INLINE PxU32 getMaxNbShapesFast() const { return mMaxNbShapes; } PX_FORCE_INLINE PxU32 getCurrentSizeFast() const { return mNbActors; } PX_FORCE_INLINE PxActor* getActorFast(PxU32 i) const { return mActors[i]; } PX_FORCE_INLINE PxU32 getAggregateID() const { return mAggregateID; } PX_FORCE_INLINE void setAggregateID(PxU32 cid) { mAggregateID = cid; } PX_FORCE_INLINE bool getSelfCollideFast() const { return PxGetAggregateSelfCollisionBit(mFilterHint)!=0; } PX_FORCE_INLINE PxAggregateFilterHint getFilterHint() const { return mFilterHint; } void scRemoveActor(NpActor& actor, bool reinsert); bool removeActorAndReinsert(PxActor& actor, bool reinsert); bool removeArticulationAndReinsert(PxArticulationReducedCoordinate& art, bool reinsert); void addToScene(NpScene& scene); void incShapeCount(); void decShapeCount(); private: PxU32 mAggregateID; PxU32 mMaxNbActors; PxU32 mMaxNbShapes; PxAggregateFilterHint mFilterHint; PxU32 mNbActors; PxU32 mNbShapes; PxActor** mActors; void scAddActor(NpActor&); void removeAndReinsert(PxActor& actor, bool reinsert); void addActorInternal(PxActor& actor, NpScene& s, const PxBVH* bvh); }; } #endif
4,748
C
45.558823
112
0.726411
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpShapeManager.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 NP_SHAPE_MANAGER_H #define NP_SHAPE_MANAGER_H #include "NpShape.h" #include "CmPtrTable.h" #include "GuBVH.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif #include "SqTypedef.h" namespace physx { namespace Sq { class PruningStructure; class PrunerManager; } class NpScene; // PT: if we go through an SQ virtual interface then the implementation can be different from our internal version, // and nothing says it uses the same types as what we have internally in SQ. So we need a separate set of types. typedef PxSQCompoundHandle NpCompoundId; static const NpCompoundId NP_INVALID_COMPOUND_ID = NpCompoundId(Sq::INVALID_COMPOUND_ID); class NpShapeManager : public PxUserAllocated { public: // PX_SERIALIZATION static void getBinaryMetaData(PxOutputStream& stream); NpShapeManager(const PxEMPTY); void preExportDataReset(); void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); //~PX_SERIALIZATION NpShapeManager(); ~NpShapeManager(); PX_FORCE_INLINE PxU32 getNbShapes() const { return mShapes.getCount(); } PX_FORCE_INLINE NpShape* const* getShapes() const { return reinterpret_cast<NpShape*const*>(mShapes.getPtrs()); } PxU32 getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex=0) const; void attachShape(NpShape& shape, PxRigidActor& actor); bool detachShape(NpShape& s, PxRigidActor& actor, bool wakeOnLostTouch); void detachAll(PxSceneQuerySystem* pxsq, const PxRigidActor& actor); void setupSQShape(PxSceneQuerySystem& pxsq, const NpShape& shape, const NpActor& npActor, const PxRigidActor& actor, bool dynamic, const PxBounds3* bounds, const Sq::PruningStructure* ps); void setupSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape); void setupAllSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const Sq::PruningStructure* ps, const PxBounds3* bounds, bool isDynamic); void setupAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const Sq::PruningStructure* ps, const PxBounds3* bounds=NULL, const Gu::BVH* bvh = NULL); void teardownAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor); void teardownSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const NpShape& shape); void markShapeForSQUpdate(PxSceneQuerySystem& pxsq, const PxShape& shape, const PxRigidActor& actor); void markActorForSQUpdate(PxSceneQuerySystem& pxsq, const PxRigidActor& actor); PxBounds3 getWorldBounds_(const PxRigidActor&) const; PX_FORCE_INLINE void setPruningStructure(Sq::PruningStructure* ps) { mPruningStructure = ps; } PX_FORCE_INLINE Sq::PruningStructure* getPruningStructure() const { return mPruningStructure; } // PX_FORCE_INLINE bool isSqCompound() const { return mSqCompoundId != NP_INVALID_COMPOUND_ID; } // PX_FORCE_INLINE NpCompoundId getCompoundID() const { return mSqCompoundId; } // PX_FORCE_INLINE void setCompoundID(NpCompoundId id) { mSqCompoundId = id; } // PT: TODO: we don't really need to store the compound id anymore PX_FORCE_INLINE bool isSqCompound() const { return mShapes.mFreeSlot != NP_INVALID_COMPOUND_ID; } PX_FORCE_INLINE NpCompoundId getCompoundID() const { return mShapes.mFreeSlot; } PX_FORCE_INLINE void setCompoundID(NpCompoundId id) { mShapes.mFreeSlot = id; } void clearShapesOnRelease(NpScene& s, PxRigidActor&); #if PX_ENABLE_DEBUG_VISUALIZATION void visualize(PxRenderOutput& out, NpScene& scene, const PxRigidActor& actor, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif // for batching PX_FORCE_INLINE const Cm::PtrTable& getShapeTable() const { return mShapes; } static PX_FORCE_INLINE size_t getShapeTableOffset() { return PX_OFFSET_OF_RT(NpShapeManager, mShapes); } private: Cm::PtrTable mShapes; Sq::PruningStructure* mPruningStructure; // Shape scene query data are pre-build in pruning structure // NpCompoundId mSqCompoundId; void releaseExclusiveUserReferences(); void setupSceneQuery_(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape); void addBVHShapes(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const Gu::BVH& bvh); }; } #endif
6,320
C
48.771653
197
0.743987
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpDebugViz.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 NP_DEBUG_VIZ_H #define NP_DEBUG_VIZ_H #include "common/PxPhysXCommonConfig.h" #if PX_ENABLE_DEBUG_VISUALIZATION namespace physx { class PxRenderOutput; class NpScene; class PxRigidActor; namespace Sc { class BodyCore; } void visualizeRigidBody(PxRenderOutput& out, NpScene& scene, const PxRigidActor& actor, const Sc::BodyCore& mCore, float scale); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif #endif
2,141
C
37.249999
129
0.76553
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpShapeManager.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 "NpShapeManager.h" #include "NpPtrTableStorageManager.h" #include "NpRigidDynamic.h" #include "NpArticulationLink.h" #include "ScBodySim.h" #include "GuBounds.h" #include "NpAggregate.h" #include "CmTransformUtils.h" #include "NpRigidStatic.h" #include "foundation/PxSIMDHelpers.h" using namespace physx; using namespace Sq; using namespace Gu; using namespace Cm; // PT: TODO: refactor if we keep it static void getSQGlobalPose(PxTransform& globalPose, const NpShape& npShape, const NpActor& npActor) { const PxTransform& shape2Actor = npShape.getCore().getShape2Actor(); PX_ALIGN(16, PxTransform) kinematicTarget; // PT: TODO: duplicated from SqBounds.cpp. Refactor. const NpType::Enum actorType = npActor.getNpType(); const PxTransform* actor2World; if(actorType==NpType::eRIGID_STATIC) { actor2World = &static_cast<const NpRigidStatic&>(npActor).getCore().getActor2World(); if(npShape.getCore().getCore().mShapeCoreFlags.isSet(PxShapeCoreFlag::eIDT_TRANSFORM)) { PX_ASSERT(shape2Actor.p.isZero() && shape2Actor.q.isIdentity()); globalPose = *actor2World; return; } } else { PX_ASSERT(actorType==NpType::eBODY || actorType == NpType::eBODY_FROM_ARTICULATION_LINK); const PxU16 sqktFlags = PxRigidBodyFlag::eKINEMATIC | PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES; // PT: TODO: revisit this once the dust has settled const Sc::BodyCore& core = actorType==NpType::eBODY ? static_cast<const NpRigidDynamic&>(npActor).getCore() : static_cast<const NpArticulationLink&>(npActor).getCore(); const bool useTarget = (PxU16(core.getFlags()) & sqktFlags) == sqktFlags; const PxTransform& body2World = (useTarget && core.getKinematicTarget(kinematicTarget)) ? kinematicTarget : core.getBody2World(); if(!core.getCore().hasIdtBody2Actor()) { Cm::getDynamicGlobalPoseAligned(body2World, shape2Actor, core.getBody2Actor(), globalPose); return; } actor2World = &body2World; } Cm::getStaticGlobalPoseAligned(*actor2World, shape2Actor, globalPose); } static PX_FORCE_INLINE bool isSceneQuery(const NpShape& shape) { return shape.getFlagsFast() & PxShapeFlag::eSCENE_QUERY_SHAPE; } static PX_FORCE_INLINE bool isDynamicActor(const PxRigidActor& actor) { const PxType actorType = actor.getConcreteType(); return actorType != PxConcreteType::eRIGID_STATIC; } static PX_FORCE_INLINE bool isDynamicActor(const NpActor& actor) { const NpType::Enum actorType = actor.getNpType(); return actorType != NpType::eRIGID_STATIC; } NpShapeManager::NpShapeManager() : mPruningStructure (NULL) { setCompoundID(NP_INVALID_COMPOUND_ID); } // PX_SERIALIZATION NpShapeManager::NpShapeManager(const PxEMPTY) : mShapes (PxEmpty) { } NpShapeManager::~NpShapeManager() { PX_ASSERT(!mPruningStructure); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); mShapes.clear(sm); } void NpShapeManager::preExportDataReset() { } void NpShapeManager::exportExtraData(PxSerializationContext& stream) { mShapes.exportExtraData(stream); } void NpShapeManager::importExtraData(PxDeserializationContext& context) { mShapes.importExtraData(context); } //~PX_SERIALIZATION static PX_INLINE void onShapeAttach(NpActor& ro, NpShape& shape) { // * if the shape is exclusive, set its Sc control state appropriately. // * add the shape to pvd. NpScene* npScene = ro.getNpScene(); if(!npScene) return; PX_ASSERT(!npScene->isAPIWriteForbidden()); if(!(ro.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) ro.getScRigidCore().addShapeToScene(shape.getCore()); #if PX_SUPPORT_PVD npScene->getScenePvdClientInternal().createPvdInstance(&shape, *ro.getScRigidCore().getPxActor()); #endif shape.setSceneIfExclusive(npScene); } static PX_INLINE void onShapeDetach(NpActor& ro, NpShape& shape, bool wakeOnLostTouch) { // see comments in onShapeAttach NpScene* npScene = ro.getNpScene(); if(!npScene) return; PX_ASSERT(!npScene->isAPIWriteForbidden()); #if PX_SUPPORT_PVD npScene->getScenePvdClientInternal().releasePvdInstance(&shape, *ro.getScRigidCore().getPxActor()); #endif if(!(ro.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) ro.getScRigidCore().removeShapeFromScene(shape.getCore(), wakeOnLostTouch); shape.setSceneIfExclusive(NULL); } void NpShapeManager::attachShape(NpShape& shape, PxRigidActor& actor) { PX_ASSERT(!mPruningStructure); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); const PxU32 index = getNbShapes(); mShapes.add(&shape, sm); NpActor& ro = NpActor::getFromPxActor(actor); NpScene* scene = NpActor::getNpSceneFromActor(actor); if(scene && isSceneQuery(shape)) { // PT: SQ_CODEPATH2 setupSceneQuery_(scene->getSQAPI(), ro, actor, shape); } onShapeAttach(ro, shape); PxAggregate* agg = ro.getAggregate(); if(agg) static_cast<NpAggregate*>(agg)->incShapeCount(); PX_ASSERT(!shape.isExclusive() || shape.getActor()==NULL); shape.onActorAttach(actor); shape.setShapeManagerArrayIndex(index); } bool NpShapeManager::detachShape(NpShape& s, PxRigidActor& actor, bool wakeOnLostTouch) { PX_ASSERT(!mPruningStructure); const PxU32 index = s.getShapeManagerArrayIndex(mShapes); if(index==0xffffffff) return false; NpScene* scene = NpActor::getNpSceneFromActor(actor); if(scene && isSceneQuery(s)) { scene->getSQAPI().removeSQShape(actor, s); // if this is the last shape of a compound shape, we have to remove the compound id // and in case of a dynamic actor, remove it from the active list if(isSqCompound() && (mShapes.getCount() == 1)) { setCompoundID(NP_INVALID_COMPOUND_ID); const PxType actorType = actor.getConcreteType(); // for PxRigidDynamic and PxArticulationLink we need to remove the compound rigid flag and remove them from active list if(actorType == PxConcreteType::eRIGID_DYNAMIC) static_cast<NpRigidDynamic&>(actor).getCore().getSim()->disableCompound(); else if(actorType == PxConcreteType::eARTICULATION_LINK) static_cast<NpArticulationLink&>(actor).getCore().getSim()->disableCompound(); } } NpActor& ro = NpActor::getFromPxActor(actor); onShapeDetach(ro, s, wakeOnLostTouch); PxAggregate* agg = ro.getAggregate(); if (agg) static_cast<NpAggregate*>(agg)->decShapeCount(); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); void** ptrs = mShapes.getPtrs(); PX_ASSERT(reinterpret_cast<NpShape*>(ptrs[index]) == &s); const PxU32 last = mShapes.getCount() - 1; if (index != last) { NpShape* moved = reinterpret_cast<NpShape*>(ptrs[last]); PX_ASSERT(moved->checkShapeManagerArrayIndex(mShapes)); moved->setShapeManagerArrayIndex(index); } mShapes.replaceWithLast(index, sm); s.clearShapeManagerArrayIndex(); s.onActorDetach(); return true; } void NpShapeManager::detachAll(PxSceneQuerySystem* pxsq, const PxRigidActor& actor) { // assumes all SQ data has been released, which is currently the responsibility of the owning actor const PxU32 nbShapes = getNbShapes(); NpShape*const *shapes = getShapes(); if(pxsq) teardownAllSceneQuery(*pxsq, actor); // actor cleanup in Sc will remove any outstanding references corresponding to sim objects, so we don't need to do that here. for(PxU32 i=0;i<nbShapes;i++) shapes[i]->onActorDetach(); PtrTableStorageManager& sm = NpFactory::getInstance().getPtrTableStorageManager(); mShapes.clear(sm); } PxU32 NpShapeManager::getShapes(PxShape** buffer, PxU32 bufferSize, PxU32 startIndex) const { return getArrayOfPointers(buffer, bufferSize, startIndex, getShapes(), getNbShapes()); } // PT: this one is only used by the API getWorldBounds() functions PxBounds3 NpShapeManager::getWorldBounds_(const PxRigidActor& actor) const { PxBounds3 bounds(PxBounds3::empty()); const PxU32 nbShapes = getNbShapes(); NpShape*const* PX_RESTRICT shapes = getShapes(); const PxTransform32 actorPose(actor.getGlobalPose()); for(PxU32 i=0;i<nbShapes;i++) { PxTransform32 shapeAbsPose; aos::transformMultiply<true, true>(shapeAbsPose, actorPose, shapes[i]->getLocalPoseFast()); bounds.include(computeBounds(shapes[i]->getCore().getGeometry(), shapeAbsPose)); } return bounds; } void NpShapeManager::clearShapesOnRelease(NpScene& s, PxRigidActor& r) { PX_ASSERT(NpActor::getFromPxActor(r).getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)); const PxU32 nbShapes = getNbShapes(); #if PX_SUPPORT_PVD NpShape*const* PX_RESTRICT shapes = getShapes(); #endif for(PxU32 i=0;i<nbShapes;i++) { #if PX_SUPPORT_PVD s.getScenePvdClientInternal().releasePvdInstance(shapes[i], r); #else PX_UNUSED(s); PX_UNUSED(r); #endif } } void NpShapeManager::releaseExclusiveUserReferences() { // when the factory is torn down, release any shape owner refs that are still outstanding const PxU32 nbShapes = getNbShapes(); NpShape*const* PX_RESTRICT shapes = getShapes(); for(PxU32 i=0;i<nbShapes;i++) { if(shapes[i]->isExclusiveFast() && shapes[i]->getReferenceCount()>1) shapes[i]->release(); } } void NpShapeManager::setupSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape) { PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE); setupSceneQuery_(pxsq, npActor, actor, shape); } // PT: TODO: function called from a single place? void NpShapeManager::teardownSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const NpShape& shape) { pxsq.removeSQShape(actor, shape); } void NpShapeManager::setupAllSceneQuery(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const PruningStructure* ps, const PxBounds3* bounds, bool isDynamic) { const PxU32 nbShapes = getNbShapes(); NpShape*const *shapes = getShapes(); for(PxU32 i=0;i<nbShapes;i++) { if(isSceneQuery(*shapes[i])) setupSQShape(pxsq, *shapes[i], npActor, actor, isDynamic, bounds ? bounds + i : NULL, ps); } } void NpShapeManager::setupAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const PruningStructure* ps, const PxBounds3* bounds, const BVH* bvh) { // if BVH was provided, we add shapes into compound pruner if(bvh) addBVHShapes(pxsq, actor, *bvh); else setupAllSceneQuery(pxsq, NpActor::getFromPxActor(actor), actor, ps, bounds, isDynamicActor(actor)); } void NpShapeManager::teardownAllSceneQuery(PxSceneQuerySystem& pxsq, const PxRigidActor& actor) { NpShape*const *shapes = getShapes(); const PxU32 nbShapes = getNbShapes(); if(isSqCompound()) { pxsq.removeSQCompound(getCompoundID()); setCompoundID(NP_INVALID_COMPOUND_ID); } else { for(PxU32 i=0;i<nbShapes;i++) { if(isSceneQuery(*shapes[i])) pxsq.removeSQShape(actor, *shapes[i]); } } } void NpShapeManager::markShapeForSQUpdate(PxSceneQuerySystem& pxsq, const PxShape& shape, const PxRigidActor& actor) { // PT: SQ_CODEPATH4 PX_ALIGN(16, PxTransform) transform; const NpShape& nbShape = static_cast<const NpShape&>(shape); const NpActor& npActor = NpActor::getFromPxActor(actor); if(getCompoundID() == NP_INVALID_COMPOUND_ID) getSQGlobalPose(transform, nbShape, npActor); else transform = nbShape.getCore().getShape2Actor(); pxsq.updateSQShape(actor, shape, transform); } void NpShapeManager::markActorForSQUpdate(PxSceneQuerySystem& pxsq, const PxRigidActor& actor) { // PT: SQ_CODEPATH5 if(isSqCompound()) { pxsq.updateSQCompound(getCompoundID(), actor.getGlobalPose()); } else { const NpActor& npActor = NpActor::getFromPxActor(actor); const PxU32 nbShapes = getNbShapes(); for(PxU32 i=0;i<nbShapes;i++) { const NpShape& npShape = *getShapes()[i]; if(isSceneQuery(npShape)) { PX_ALIGN(16, PxTransform) transform; getSQGlobalPose(transform, npShape, npActor); pxsq.updateSQShape(actor, npShape, transform); } } } } // // internal methods // #include "NpBounds.h" void NpShapeManager::addBVHShapes(PxSceneQuerySystem& pxsq, const PxRigidActor& actor, const BVH& bvh) { const PxU32 nbShapes = getNbShapes(); PX_ALLOCA(scShapes, const PxShape*, nbShapes); PxU32 numSqShapes = 0; { for(PxU32 i=0; i<nbShapes; i++) { const NpShape& shape = *getShapes()[i]; if(isSceneQuery(shape)) scShapes[numSqShapes++] = &shape; } PX_ASSERT(numSqShapes == bvh.getNbBounds()); } PX_ALLOCA(transforms, PxTransform, numSqShapes); for(PxU32 i=0; i<numSqShapes; i++) { const NpShape* npShape = static_cast<const NpShape*>(scShapes[i]); transforms[i] = npShape->getLocalPoseFast(); } const PxSQCompoundHandle cid = pxsq.addSQCompound(actor, scShapes, bvh, transforms); setCompoundID(cid); } void NpShapeManager::setupSQShape(PxSceneQuerySystem& pxsq, const NpShape& shape, const NpActor& npActor, const PxRigidActor& actor, bool dynamic, const PxBounds3* bounds, const PruningStructure* ps) { PX_ALIGN(16, PxTransform) transform; PxBounds3 b; if(getCompoundID() == NP_INVALID_COMPOUND_ID) { if(bounds) inflateBounds<true>(b, *bounds, SQ_PRUNER_EPSILON); else (gComputeBoundsTable[dynamic])(b, shape, npActor); // PT: TODO: don't recompute it? getSQGlobalPose(transform, shape, npActor); } else { const PxTransform& shape2Actor = shape.getCore().getShape2Actor(); Gu::computeBounds(b, shape.getCore().getGeometry(), shape2Actor, 0.0f, SQ_PRUNER_INFLATION); transform = shape2Actor; } const NpCompoundId cid = getCompoundID(); pxsq.addSQShape(actor, shape, b, transform, &cid, ps!=NULL); } void NpShapeManager::setupSceneQuery_(PxSceneQuerySystem& pxsq, const NpActor& npActor, const PxRigidActor& actor, const NpShape& shape) { const bool isDynamic = isDynamicActor(npActor); setupSQShape(pxsq, shape, npActor, actor, isDynamic, NULL, NULL); }
15,376
C++
29.815631
199
0.744927
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpArticulationReducedCoordinate.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 NP_ARTICULATION_RC_H #define NP_ARTICULATION_RC_H #include "PxArticulationReducedCoordinate.h" #if PX_ENABLE_DEBUG_VISUALIZATION #include "common/PxRenderOutput.h" #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif #include "NpArticulationLink.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationTendon.h" #include "ScArticulationCore.h" namespace physx { class NpArticulationLink; class NpScene; class PxAggregate; class PxConstraint; class NpArticulationSpatialTendon; class NpArticulationFixedTendon; class NpArticulationSensor; class NpArticulationReducedCoordinate : public PxArticulationReducedCoordinate, public NpBase { public: virtual ~NpArticulationReducedCoordinate(); // PX_SERIALIZATION NpArticulationReducedCoordinate(PxBaseFlags baseFlags) : PxArticulationReducedCoordinate(baseFlags), NpBase(PxEmpty), mCore(PxEmpty), mArticulationLinks(PxEmpty), mLoopJoints(PxEmpty), mSpatialTendons(PxEmpty), mFixedTendons(PxEmpty), mSensors(PxEmpty) { } void preExportDataReset(); virtual void exportExtraData(PxSerializationContext& stream); void importExtraData(PxDeserializationContext& context); void resolveReferences(PxDeserializationContext& context); virtual void requiresObjects(PxProcessPxBaseCallback& c); static NpArticulationReducedCoordinate* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); //~PX_SERIALIZATION virtual void release(); //--------------------------------------------------------------------------------- // PxArticulationReducedCoordinate implementation //--------------------------------------------------------------------------------- virtual PxScene* getScene() const { return NpBase::getNpScene(); } virtual void setSleepThreshold(PxReal threshold); virtual PxReal getSleepThreshold() const; virtual void setStabilizationThreshold(PxReal threshold); virtual PxReal getStabilizationThreshold() const; virtual void setWakeCounter(PxReal wakeCounterValue); virtual PxReal getWakeCounter() const; virtual void setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters);// { mImpl.setSolverIterationCounts(positionIters, velocityIters); } virtual void getSolverIterationCounts(PxU32 & positionIters, PxU32 & velocityIters) const;// { mImpl.getSolverIterationCounts(positionIters, velocityIters); } virtual bool isSleeping() const; virtual void wakeUp(); virtual void putToSleep(); virtual void setMaxCOMLinearVelocity(const PxReal maxLinearVelocity); virtual PxReal getMaxCOMLinearVelocity() const; virtual void setMaxCOMAngularVelocity(const PxReal maxAngularVelocity); virtual PxReal getMaxCOMAngularVelocity() const; virtual PxU32 getNbLinks() const; virtual PxU32 getLinks(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; /*{ return mImpl.getLinks(userBuffer, bufferSize, startIndex); } */ virtual PxU32 getNbShapes() const; virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const; virtual PxAggregate* getAggregate() const; // Debug name virtual void setName(const char* name); virtual const char* getName() const; virtual PxArticulationLink* createLink(PxArticulationLink* parent, const PxTransform& pose); virtual void setArticulationFlags(PxArticulationFlags flags); virtual void setArticulationFlag(PxArticulationFlag::Enum flag, bool value); virtual PxArticulationFlags getArticulationFlags() const; virtual PxU32 getDofs() const; virtual PxArticulationCache* createCache() const; virtual PxU32 getCacheDataSize() const; virtual void zeroCache(PxArticulationCache& cache) const; virtual void applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags, bool autowake); virtual void copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags) const; virtual void packJointData(const PxReal* maximum, PxReal* reduced) const; virtual void unpackJointData(const PxReal* reduced, PxReal* maximum) const; virtual void commonInit() const; virtual void computeGeneralizedGravityForce(PxArticulationCache& cache) const; virtual void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const; virtual void computeGeneralizedExternalForce(PxArticulationCache& cache) const; virtual void computeJointAcceleration(PxArticulationCache& cache) const; virtual void computeJointForce(PxArticulationCache& cache) const; virtual void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const; virtual void computeCoefficientMatrix(PxArticulationCache& cache) const; virtual bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* const jointTorque, const PxU32 maxIter) const; virtual void computeGeneralizedMassMatrix(PxArticulationCache& cache) const; virtual void addLoopJoint(PxConstraint* joint); virtual void removeLoopJoint(PxConstraint* constraint); virtual PxU32 getNbLoopJoints() const; virtual PxU32 getLoopJoints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const; virtual PxU32 getCoefficientMatrixSize() const; virtual void setRootGlobalPose(const PxTransform& pose, bool autowake = true); virtual PxTransform getRootGlobalPose() const; virtual void setRootLinearVelocity(const PxVec3& velocity, bool autowake = true); virtual void setRootAngularVelocity(const PxVec3& velocity, bool autowake = true); virtual PxVec3 getRootLinearVelocity() const; virtual PxVec3 getRootAngularVelocity() const; virtual PxSpatialVelocity getLinkAcceleration(const PxU32 linkId); virtual PxU32 getGpuArticulationIndex(); virtual const char* getConcreteTypeName() const { return "PxArticulationReducedCoordinate"; } virtual PxArticulationSpatialTendon* createSpatialTendon(); virtual PxU32 getSpatialTendons(PxArticulationSpatialTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbSpatialTendons(); NpArticulationSpatialTendon* getSpatialTendon(const PxU32 index) const; virtual PxArticulationFixedTendon* createFixedTendon(); virtual PxU32 getFixedTendons(PxArticulationFixedTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbFixedTendons(); NpArticulationFixedTendon* getFixedTendon(const PxU32 index) const; virtual PxArticulationSensor* createSensor(PxArticulationLink* link, const PxTransform& relativePose); virtual void releaseSensor(PxArticulationSensor& sensor); virtual PxU32 getSensors(PxArticulationSensor** userBuffer, PxU32 bufferSize, PxU32 startIndex) const; virtual PxU32 getNbSensors(); NpArticulationSensor* getSensor(const PxU32 index) const; virtual void updateKinematic(PxArticulationKinematicFlags flags); PX_FORCE_INLINE PxArray<NpArticulationSpatialTendon*>& getSpatialTendons() { return mSpatialTendons; } PX_FORCE_INLINE PxArray<NpArticulationFixedTendon*>& getFixedTendons() { return mFixedTendons; } PX_FORCE_INLINE PxArray<NpArticulationSensor*>& getSensors() { return mSensors; } //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- NpArticulationReducedCoordinate(); virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationReducedCoordinate", PxBase); } PxArticulationJointReducedCoordinate* createArticulationJoint(PxArticulationLink& parent, const PxTransform& parentFrame, PxArticulationLink& child, const PxTransform& childFrame); PX_INLINE void incrementShapeCount() { mNumShapes++; } PX_INLINE void decrementShapeCount() { mNumShapes--; } //--------------------------------------------------------------------------------- // Miscellaneous //--------------------------------------------------------------------------------- PX_INLINE void addToLinkList(NpArticulationLink& link) { mArticulationLinks.pushBack(&link); mNumShapes += link.getNbShapes(); } PX_INLINE bool removeLinkFromList(NpArticulationLink& link) { PX_ASSERT(mArticulationLinks.find(&link) != mArticulationLinks.end()); mTopologyChanged = true; return mArticulationLinks.findAndReplaceWithLast(&link); } PX_FORCE_INLINE NpArticulationLink* const* getLinks() { return mArticulationLinks.begin(); } NpArticulationLink* getRoot(); void setAggregate(PxAggregate* a); void wakeUpInternal(bool forceWakeUp, bool autowake); void autoWakeInternal(); void setGlobalPose(); PX_FORCE_INLINE Sc::ArticulationCore& getCore() { return mCore; } PX_FORCE_INLINE const Sc::ArticulationCore& getCore() const { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpArticulationReducedCoordinate, mCore); } PX_INLINE void scSetSolverIterationCounts(PxU16 v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setSolverIterationCounts(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetSleepThreshold(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setSleepThreshold(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetFreezeThreshold(const PxReal v) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setFreezeThreshold(v); UPDATE_PVD_PROPERTY } PX_INLINE void scSetWakeCounter(PxReal counter) { PX_ASSERT(!isAPIWriteForbiddenExceptSplitSim()); mCore.setWakeCounter(counter); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE void scSetArticulationFlags(PxArticulationFlags flags) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setArticulationFlags(flags); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE void scWakeUpInternal(PxReal wakeCounter) { PX_ASSERT(getNpScene()); PX_ASSERT(!isAPIWriteForbiddenExceptSplitSim()); mCore.wakeUp(wakeCounter); } PX_FORCE_INLINE void scSetMaxLinearVelocity(PxReal maxLinearVelocity) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMaxLinearVelocity(maxLinearVelocity); UPDATE_PVD_PROPERTY } PX_FORCE_INLINE void scSetMaxAngularVelocity(PxReal maxAngularVelocity) { PX_ASSERT(!isAPIWriteForbidden()); mCore.setMaxAngularVelocity(maxAngularVelocity); UPDATE_PVD_PROPERTY } void recomputeLinkIDs(); #if PX_ENABLE_DEBUG_VISUALIZATION public: void visualize(PxRenderOutput& out, NpScene& scene, float scale) const; #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif Sc::ArticulationCore mCore; NpArticulationLinkArray mArticulationLinks; PxU32 mNumShapes; NpAggregate* mAggregate; const char* mName; PxU32 mCacheVersion; bool mTopologyChanged; private: void removeSpatialTendonInternal(NpArticulationSpatialTendon* tendon); void removeFixedTendonInternal(NpArticulationFixedTendon* tendon); void removeSensorInternal(NpArticulationSensor* sensor); PxArray<NpConstraint*> mLoopJoints; PxArray<NpArticulationSpatialTendon*> mSpatialTendons; PxArray<NpArticulationFixedTendon*> mFixedTendons; PxArray<NpArticulationSensor*> mSensors; friend class NpScene; }; } #endif
13,700
C
37.378151
167
0.711971
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidDynamic.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 "NpRigidDynamic.h" #include "NpRigidActorTemplateInternal.h" #include "omnipvd/NpOmniPvdSetData.h" using namespace physx; /////////////////////////////////////////////////////////////////////////////// PX_IMPLEMENT_OUTPUT_ERROR /////////////////////////////////////////////////////////////////////////////// NpRigidDynamic::NpRigidDynamic(const PxTransform& bodyPose) : NpRigidDynamicT(PxConcreteType::eRIGID_DYNAMIC, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, PxActorType::eRIGID_DYNAMIC, NpType::eBODY, bodyPose) {} NpRigidDynamic::~NpRigidDynamic() { } // PX_SERIALIZATION void NpRigidDynamic::requiresObjects(PxProcessPxBaseCallback& c) { NpRigidDynamicT::requiresObjects(c); } void NpRigidDynamic::preExportDataReset() { NpRigidDynamicT::preExportDataReset(); if (isKinematic() && getNpScene()) { //Restore dynamic data in case the actor is configured as a kinematic. //otherwise we would loose the data for switching the kinematic actor back to dynamic //after deserialization. Not necessary if the kinematic is not yet part of //a scene since the dynamic data will still hold the original values. mCore.restoreDynamicData(); } } NpRigidDynamic* NpRigidDynamic::createObject(PxU8*& address, PxDeserializationContext& context) { NpRigidDynamic* obj = PX_PLACEMENT_NEW(address, NpRigidDynamic(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpRigidDynamic); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpRigidDynamic::release() { if(releaseRigidActorT<PxRigidDynamic>(*this)) { PX_ASSERT(!isAPIWriteForbidden()); // the code above should return false in that case NpDestroyRigidDynamic(this); } } void NpRigidDynamic::setGlobalPose(const PxTransform& pose, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidDynamic::setGlobalPose: pose is not valid."); #if PX_CHECKED if(npScene) npScene->checkPositionSanity(*this, pose, "PxRigidDynamic::setGlobalPose"); #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setGlobalPose() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setGlobalPose(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } const PxTransform newPose = pose.getNormalized(); //AM: added to fix 1461 where users read and write orientations for no reason. const PxTransform body2World = newPose * mCore.getBody2Actor(); scSetBody2World(body2World); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, translation, *static_cast<PxRigidActor*>(this), newPose.p); OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidActor, rotation, *static_cast<PxRigidActor*>(this), newPose.q); OMNI_PVD_WRITE_SCOPE_END if(npScene) mShapeManager.markActorForSQUpdate(npScene->getSQAPI(), *this); // invalidate the pruning structure if the actor bounds changed if(mShapeManager.getPruningStructure()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setGlobalPose: Actor is part of a pruning structure, pruning structure is now invalid!"); mShapeManager.getPruningStructure()->invalidate(this); } if(npScene && autowake && !(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION))) wakeUpInternal(); } PX_FORCE_INLINE void NpRigidDynamic::setKinematicTargetInternal(const PxTransform& targetPose) { // The target is actor related. Transform to body related target const PxTransform bodyTarget = targetPose * mCore.getBody2Actor(); scSetKinematicTarget(bodyTarget); NpScene* scene = getNpScene(); if((mCore.getFlags() & PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES) && scene) mShapeManager.markActorForSQUpdate(scene->getSQAPI(), *this); } void NpRigidDynamic::setKinematicTarget(const PxTransform& destination) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(destination.isSane(), "PxRigidDynamic::setKinematicTarget: destination is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::setKinematicTarget: Body must be in a scene!"); PX_CHECK_AND_RETURN((mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setKinematicTarget: Body must be kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setKinematicTarget: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); #if PX_CHECKED if(npScene) npScene->checkPositionSanity(*this, destination, "PxRigidDynamic::setKinematicTarget"); #endif PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setKinematicTarget() not allowed while simulation is running. Call will be ignored.") setKinematicTargetInternal(destination.getNormalized()); } bool NpRigidDynamic::getKinematicTarget(PxTransform& target) const { NP_READ_CHECK(getNpScene()); if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { PxTransform bodyTarget; if(mCore.getKinematicTarget(bodyTarget)) { // The internal target is body related. Transform to actor related target target = bodyTarget * mCore.getBody2Actor().getInverse(); return true; } } return false; } void NpRigidDynamic::setCMassLocalPose(const PxTransform& pose) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(pose.isSane(), "PxRigidDynamic::setCMassLocalPose pose is not valid."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setCMassLocalPose() not allowed while simulation is running. Call will be ignored.") const PxTransform p = pose.getNormalized(); const PxTransform oldBody2Actor = mCore.getBody2Actor(); NpRigidDynamicT::setCMassLocalPoseInternal(p); if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { PxTransform bodyTarget; if(mCore.getKinematicTarget(bodyTarget)) { PxTransform actorTarget = bodyTarget * oldBody2Actor.getInverse(); // get old target pose for the actor from the body target setKinematicTargetInternal(actorTarget); } } } void NpRigidDynamic::setLinearVelocity(const PxVec3& velocity, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(velocity.isFinite(), "PxRigidDynamic::setLinearVelocity: velocity is not valid."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setLinearVelocity: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setLinearVelocity: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setLinearVelocity() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setLinearVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } scSetLinearVelocity(velocity); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, linearVelocity, *static_cast<PxRigidBody*>(this), velocity); if(npScene) wakeUpInternalNoKinematicTest((!velocity.isZero()), autowake); } void NpRigidDynamic::setAngularVelocity(const PxVec3& velocity, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(velocity.isFinite(), "PxRigidDynamic::setAngularVelocity: velocity is not valid."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setAngularVelocity: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setAngularVelocity: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setAngularVelocity() not allowed while simulation is running. Call will be ignored.") scSetAngularVelocity(velocity); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidBody, angularVelocity, *static_cast<PxRigidBody*>(this), velocity); if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setAngularVelocity(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } if(npScene) wakeUpInternalNoKinematicTest((!velocity.isZero()), autowake); } void NpRigidDynamic::addForce(const PxVec3& force, PxForceMode::Enum mode, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(force.isFinite(), "PxRigidDynamic::addForce: force is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::addForce: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::addForce: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::addForce() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::addForce: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::addForce(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } addSpatialForce(&force, NULL, mode); wakeUpInternalNoKinematicTest(!force.isZero(), autowake); } void NpRigidDynamic::setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(force.isFinite(), "PxRigidDynamic::setForceAndTorque: force is not valid."); PX_CHECK_AND_RETURN(torque.isFinite(), "PxRigidDynamic::setForceAndTorque: torque is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::setForceAndTorque: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setForceAndTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setForceAndTorque() not allowed while simulation is running. Call will be ignored.") if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::setForceAndTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::setForceAndTorque: Body must be non-kinematic!"); return; } setSpatialForce(&force, &torque, mode); wakeUpInternalNoKinematicTest(!force.isZero(), true); } void NpRigidDynamic::addTorque(const PxVec3& torque, PxForceMode::Enum mode, bool autowake) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(torque.isFinite(), "PxRigidDynamic::addTorque: torque is not valid."); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::addTorque: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::addTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::addTorque() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::addTorque: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::addTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } addSpatialForce(NULL, &torque, mode); wakeUpInternalNoKinematicTest(!torque.isZero(), autowake); } void NpRigidDynamic::clearForce(PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::clearForce: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::clearForce: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::clearForce() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::clearForce: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::clearForce(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } clearSpatialForce(mode, true, false); } void NpRigidDynamic::clearTorque(PxForceMode::Enum mode) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::clearTorque: Body must be in a scene!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::clearTorque: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::clearTorque() not allowed while simulation is running. Call will be ignored.") if(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC) { outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxRigidDynamic::clearTorque: Body must be non-kinematic!"); return; } if (npScene && (npScene->getFlags() & PxSceneFlag::eENABLE_DIRECT_GPU_API) && npScene->isDirectGPUAPIInitialized()) { outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "PxRigidDynamic::clearTorque(): it is illegal to call this method if PxSceneFlag::eENABLE_DIRECT_GPU_API is enabled!"); return; } clearSpatialForce(mode, false, true); } bool NpRigidDynamic::isSleeping() const { NP_READ_CHECK(getNpScene()); PX_CHECK_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::isSleeping: Body must be in a scene.", true); PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::isSleeping() not allowed while simulation is running.", true); return mCore.isSleeping(); } void NpRigidDynamic::setSleepThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setSleepThreshold: invalid float."); PX_CHECK_AND_RETURN(threshold>=0.0f, "PxRigidDynamic::setSleepThreshold: threshold must be non-negative!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setSleepThreshold() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, sleepThreshold, static_cast<PxRigidDynamic&>(*this), threshold); // @@@ mCore.setSleepThreshold(threshold); UPDATE_PVD_PROPERTY_BODY } PxReal NpRigidDynamic::getSleepThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getSleepThreshold(); } void NpRigidDynamic::setStabilizationThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setSleepThreshold: invalid float."); PX_CHECK_AND_RETURN(threshold>=0.0f, "PxRigidDynamic::setSleepThreshold: threshold must be non-negative!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setStabilizationThreshold() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, stabilizationThreshold, static_cast<PxRigidDynamic&>(*this), threshold); // @@@ mCore.setFreezeThreshold(threshold); UPDATE_PVD_PROPERTY_BODY } PxReal NpRigidDynamic::getStabilizationThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getFreezeThreshold(); } void NpRigidDynamic::setWakeCounter(PxReal wakeCounterValue) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(wakeCounterValue), "PxRigidDynamic::setWakeCounter: invalid float."); PX_CHECK_AND_RETURN(wakeCounterValue>=0.0f, "PxRigidDynamic::setWakeCounter: wakeCounterValue must be non-negative!"); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::setWakeCounter: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::setWakeCounter: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::setWakeCounter() not allowed while simulation is running. Call will be ignored.") scSetWakeCounter(wakeCounterValue); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, wakeCounter, static_cast<PxRigidDynamic&>(*this), wakeCounterValue); // @@@ } PxReal NpRigidDynamic::getWakeCounter() const { NP_READ_CHECK(getNpScene()); PX_CHECK_SCENE_API_READ_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxRigidDynamic::getWakeCounter() not allowed while simulation is running.", 0.0f); return mCore.getWakeCounter(); } void NpRigidDynamic::wakeUp() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::wakeUp: Body must be in a scene."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::wakeUp: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::wakeUp: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_EXCEPT_SPLIT_SIM(npScene, "PxRigidDynamic::wakeUp() not allowed while simulation is running. Call will be ignored.") scWakeUp(); } void NpRigidDynamic::putToSleep() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(npScene, "PxRigidDynamic::putToSleep: Body must be in a scene."); PX_CHECK_AND_RETURN(!(mCore.getFlags() & PxRigidBodyFlag::eKINEMATIC), "PxRigidDynamic::putToSleep: Body must be non-kinematic!"); PX_CHECK_AND_RETURN(!(mCore.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION)), "PxRigidDynamic::putToSleep: Not allowed if PxActorFlag::eDISABLE_SIMULATION is set!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::putToSleep() not allowed while simulation is running. Call will be ignored.") scPutToSleep(); } void NpRigidDynamic::setSolverIterationCounts(PxU32 positionIters, PxU32 velocityIters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(positionIters > 0, "PxRigidDynamic::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(positionIters <= 255, "PxRigidDynamic::setSolverIterationCounts: positionIters must be no greater than 255!"); PX_CHECK_AND_RETURN(velocityIters <= 255, "PxRigidDynamic::setSolverIterationCounts: velocityIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") scSetSolverIterationCounts((velocityIters & 0xff) << 8 | (positionIters & 0xff)); OMNI_PVD_WRITE_SCOPE_BEGIN(pvdWriter, pvdRegData) OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, positionIterations, static_cast<PxRigidDynamic&>(*this), positionIters); // @@@ OMNI_PVD_SET_EXPLICIT(pvdWriter, pvdRegData, OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, velocityIterations, static_cast<PxRigidDynamic&>(*this), velocityIters); // @@@ OMNI_PVD_WRITE_SCOPE_END } void NpRigidDynamic::getSolverIterationCounts(PxU32 & positionIters, PxU32 & velocityIters) const { NP_READ_CHECK(getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); velocityIters = PxU32(x >> 8); positionIters = PxU32(x & 0xff); } void NpRigidDynamic::setContactReportThreshold(PxReal threshold) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(PxIsFinite(threshold), "PxRigidDynamic::setContactReportThreshold: invalid float."); PX_CHECK_AND_RETURN(threshold >= 0.0f, "PxRigidDynamic::setContactReportThreshold: Force threshold must be greater than zero!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxRigidDynamic::setContactReportThreshold() not allowed while simulation is running. Call will be ignored.") OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, contactReportThreshold, static_cast<PxRigidDynamic&>(*this), threshold); // @@@ mCore.setContactReportThreshold(threshold<0 ? 0 : threshold); UPDATE_PVD_PROPERTY_BODY } PxReal NpRigidDynamic::getContactReportThreshold() const { NP_READ_CHECK(getNpScene()); return mCore.getContactReportThreshold(); } PxU32 physx::NpRigidDynamicGetShapes(NpRigidDynamic& actor, NpShape* const*& shapes, bool* isCompound) { NpShapeManager& sm = actor.getShapeManager(); shapes = sm.getShapes(); if(isCompound) *isCompound = sm.isSqCompound(); return sm.getNbShapes(); } void NpRigidDynamic::switchToNoSim() { NpActor::scSwitchToNoSim(); scPutToSleepInternal(); } void NpRigidDynamic::switchFromNoSim() { NpActor::scSwitchFromNoSim(); } void NpRigidDynamic::wakeUpInternalNoKinematicTest(bool forceWakeUp, bool autowake) { NpScene* scene = getNpScene(); PX_ASSERT(scene); PxReal wakeCounterResetValue = scene->getWakeCounterResetValueInternal(); PxReal wakeCounter = mCore.getWakeCounter(); bool needsWakingUp = mCore.isSleeping() && (autowake || forceWakeUp); if (autowake && (wakeCounter < wakeCounterResetValue)) { wakeCounter = wakeCounterResetValue; needsWakingUp = true; } if (needsWakingUp) scWakeUpInternal(wakeCounter); } PxRigidDynamicLockFlags NpRigidDynamic::getRigidDynamicLockFlags() const { return mCore.getRigidDynamicLockFlags(); } void NpRigidDynamic::setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxRigidDynamic::setRigidDynamicLockFlags() not allowed while simulation is running. Call will be ignored.") scSetLockFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, rigidDynamicLockFlags, static_cast<PxRigidDynamic&>(*this), flags); // @@@ } void NpRigidDynamic::setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) { PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxRigidDynamic::setRigidDynamicLockFlag() not allowed while simulation is running. Call will be ignored.") PxRigidDynamicLockFlags flags = mCore.getRigidDynamicLockFlags(); if (value) flags = flags | flag; else flags = flags & (~flag); scSetLockFlags(flags); OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxRigidDynamic, rigidDynamicLockFlags, static_cast<PxRigidDynamic&>(*this), flags); // @@@ }
25,543
C++
41.502496
183
0.763379
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPBDMaterial.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 "NpPBDMaterial.h" #include "NpPhysics.h" #include "CmUtils.h" #if PX_SUPPORT_GPU_PHYSX using namespace physx; using namespace Cm; NpPBDMaterial::NpPBDMaterial(const PxsPBDMaterialCore& desc) : PxPBDMaterial(PxConcreteType::ePBD_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), mMaterial(desc) { mMaterial.mMaterial = this; // back-reference } NpPBDMaterial::~NpPBDMaterial() { NpPhysics::getInstance().removeMaterialFromTable(*this); } // PX_SERIALIZATION void NpPBDMaterial::resolveReferences(PxDeserializationContext&) { // ### this one could be automated if NpMaterial would inherit from MaterialCore // ### well actually in that case the pointer would not even be needed.... mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial // Maybe not the best place to do it but it has to be done before the shapes resolve material indices // since the material index translation table is needed there. This requires that the materials have // been added to the table already. // PT: TODO: missing line here? } void NpPBDMaterial::onRefCountZero() { void* ud = userData; if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY) { NpFactory::getInstance().releasePBDMaterialToPool(*this); } else this->~NpPBDMaterial(); NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud); } NpPBDMaterial* NpPBDMaterial::createObject(PxU8*& address, PxDeserializationContext& context) { NpPBDMaterial* obj = PX_PLACEMENT_NEW(address, NpPBDMaterial(PxBaseFlag::eIS_RELEASABLE)); address += sizeof(NpPBDMaterial); obj->importExtraData(context); obj->resolveReferences(context); return obj; } //~PX_SERIALIZATION void NpPBDMaterial::release() { RefCountable_decRefCount(*this); } void NpPBDMaterial::acquireReference() { RefCountable_incRefCount(*this); } PxU32 NpPBDMaterial::getReferenceCount() const { return RefCountable_getRefCount(*this); } PX_INLINE void NpPBDMaterial::updateMaterial() { NpPhysics::getInstance().updateMaterial(*this); } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setFriction(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setFriction: invalid float"); mMaterial.friction = x; updateMaterial(); } PxReal NpPBDMaterial::getFriction() const { return mMaterial.friction; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setViscosity(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setViscosity: invalid float"); mMaterial.viscosity = x; updateMaterial(); } PxReal NpPBDMaterial::getViscosity() const { return mMaterial.viscosity; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setDamping(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setDamping: invalid float"); mMaterial.damping = x; updateMaterial(); } PxReal NpPBDMaterial::getDamping() const { return mMaterial.damping; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setLift(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setLift: invalid float"); mMaterial.lift = x; updateMaterial(); } PxReal NpPBDMaterial::getLift() const { return mMaterial.lift; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setDrag(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setDrag: invalid float"); mMaterial.drag = x; updateMaterial(); } PxReal NpPBDMaterial::getDrag() const { return mMaterial.drag; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setCFLCoefficient(PxReal x) { PX_CHECK_AND_RETURN(x >= 1.f, "PxPBDMaterial::setCFLCoefficient: invalid float"); mMaterial.cflCoefficient = x; updateMaterial(); } PxReal NpPBDMaterial::getCFLCoefficient() const { return mMaterial.cflCoefficient; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setVorticityConfinement(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setVorticityConfinement: invalid float"); mMaterial.vorticityConfinement = x; updateMaterial(); } PxReal NpPBDMaterial::getVorticityConfinement() const { return mMaterial.vorticityConfinement; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setSurfaceTension(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setSurfaceTension: invalid float"); mMaterial.surfaceTension = x; updateMaterial(); } PxReal NpPBDMaterial::getSurfaceTension() const { return mMaterial.surfaceTension; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setCohesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setCohesion: invalid float"); mMaterial.cohesion = x; updateMaterial(); } PxReal NpPBDMaterial::getCohesion() const { return mMaterial.cohesion; } ////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setAdhesion(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.adhesion = x; updateMaterial(); } PxReal NpPBDMaterial::getAdhesion() const { return mMaterial.adhesion; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setGravityScale(PxReal x) { PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFLIPMaterial::setAdhesion: invalid float"); mMaterial.gravityScale = x; updateMaterial(); } PxReal NpPBDMaterial::getGravityScale() const { return mMaterial.gravityScale; } ////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setAdhesionRadiusScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setAdhesionRadiusScale: invalid float"); mMaterial.adhesionRadiusScale = x; updateMaterial(); } PxReal NpPBDMaterial::getAdhesionRadiusScale() const { return mMaterial.adhesionRadiusScale; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setParticleFrictionScale(PxReal x) { PX_CHECK_AND_RETURN(x >= 0.f, "PxPBDMaterial::setParticleFrictionScale: invalid float"); mMaterial.particleFrictionScale = x; updateMaterial(); } PxReal NpPBDMaterial::getParticleFrictionScale() const { return mMaterial.particleFrictionScale; } /////////////////////////////////////////////////////////////////////////////// void NpPBDMaterial::setParticleAdhesionScale(PxReal adhesionScale) { PX_CHECK_AND_RETURN(adhesionScale >= 0.f, "PxPBDMaterial::setParticleAdhesionScale: adhesion value must be >= 0"); mMaterial.particleAdhesionScale = adhesionScale; updateMaterial(); } PxReal NpPBDMaterial::getParticleAdhesionScale() const { return mMaterial.particleAdhesionScale; } /////////////////////////////////////////////////////////////////////////////// #endif
8,691
C++
25.419453
115
0.655276
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpPruningStructure.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 NP_PRUNING_STRUCTURE_H #define NP_PRUNING_STRUCTURE_H /** \addtogroup physics @{ */ #include "PxPruningStructure.h" #include "foundation/PxUserAllocated.h" #include "GuPrunerMergeData.h" namespace physx { namespace Sq { class PruningStructure : public PxPruningStructure, public PxUserAllocated { PX_NOCOPY(PruningStructure) public: // PX_SERIALIZATION PruningStructure(PxBaseFlags baseFlags); virtual void resolveReferences(PxDeserializationContext& ); static PruningStructure* createObject(PxU8*& address, PxDeserializationContext& context); static void getBinaryMetaData(PxOutputStream& stream); void preExportDataReset() {} void exportExtraData(PxSerializationContext&); void importExtraData(PxDeserializationContext&); virtual void requiresObjects(PxProcessPxBaseCallback&); //~PX_SERIALIZATION // PxPruningStructure virtual void release(); virtual PxU32 getRigidActors(PxRigidActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const; virtual PxU32 getNbRigidActors() const; virtual const void* getStaticMergeData() const; virtual const void* getDynamicMergeData() const; // ~PxPruningStructure PruningStructure(); virtual ~PruningStructure(); bool build(PxRigidActor*const* actors, PxU32 nbActors); PX_FORCE_INLINE PxU32 getNbActors() const { return mNbActors; } PX_FORCE_INLINE PxActor*const* getActors() const { return mActors; } PX_FORCE_INLINE bool isValid() const { return mValid; } void invalidate(PxActor* actor); private: Gu::AABBPrunerMergeData mData[2]; PxU32 mNbActors; // Nb actors from which the pruner structure was build PxActor** mActors; // actors used for pruner structure build, used later for serialization bool mValid; // pruning structure validity }; } } /** @} */ #endif
3,710
C
41.655172
109
0.720485
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpSoftBody.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 NP_SOFTBODY_H #define NP_SOFTBODY_H #include "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "PxSoftBody.h" #include "ScSoftBodyCore.h" #include "NpActorTemplate.h" #include "GuTetrahedronMesh.h" namespace physx { class NpScene; class NpShape; class NpSoftBody : public NpActorTemplate<PxSoftBody> { public: NpSoftBody(PxCudaContextManager& cudaContextManager); NpSoftBody(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager); virtual ~NpSoftBody() {} void exportData(PxSerializationContext& /*context*/) const{} //external API virtual PxActorType::Enum getType() const { return PxActorType::eSOFTBODY; } virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const; virtual PxU32 getGpuSoftBodyIndex(); virtual void setSoftBodyFlag(PxSoftBodyFlag::Enum flag, bool val); virtual void setSoftBodyFlags(PxSoftBodyFlags flags); virtual PxSoftBodyFlags getSoftBodyFlag() const; virtual void setParameter(PxFEMParameters paramters); virtual PxFEMParameters getParameter() const; virtual PxVec4* getPositionInvMassBufferD(); virtual PxVec4* getRestPositionBufferD(); virtual PxVec4* getSimPositionInvMassBufferD(); virtual PxVec4* getSimVelocityBufferD(); virtual void markDirty(PxSoftBodyDataFlags flags); virtual void setKinematicTargetBufferD(const PxVec4* positions, PxSoftBodyFlags flags); virtual PxCudaContextManager* getCudaContextManager() const; virtual void setWakeCounter(PxReal wakeCounterValue); virtual PxReal getWakeCounter() const; virtual bool isSleeping() const; virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters); virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const; virtual PxShape* getShape(); virtual PxTetrahedronMesh* getCollisionMesh(); virtual const PxTetrahedronMesh* getCollisionMesh() const; virtual PxTetrahedronMesh* getSimulationMesh() { return mSimulationMesh; } virtual const PxTetrahedronMesh* getSimulationMesh() const { return mSimulationMesh; } virtual PxSoftBodyAuxData* getSoftBodyAuxData() { return mSoftBodyAuxData; } virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const { return mSoftBodyAuxData; } virtual bool attachShape(PxShape& shape); virtual bool attachSimulationMesh(PxTetrahedronMesh& simulationMesh, PxSoftBodyAuxData& softBodyAuxData); virtual void detachShape(); virtual void detachSimulationMesh(); virtual void release(); PX_FORCE_INLINE const Sc::SoftBodyCore& getCore() const { return mCore; } PX_FORCE_INLINE Sc::SoftBodyCore& getCore() { return mCore; } static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpSoftBody, mCore); } virtual void addParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId); virtual void removeParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId); virtual PxU32 addParticleAttachment(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId, const PxVec4& barycentric); virtual void removeParticleAttachment(PxPBDParticleSystem* particlesystem, PxU32 handle); virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId); virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle); virtual void addTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx); virtual void removeTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx); virtual PxU32 addTetRigidAttachment(PxRigidActor* actor, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint); virtual void addSoftBodyFilter(PxSoftBody* softbody0, PxU32 tetIdx0, PxU32 tetIdx1); virtual void removeSoftBodyFilter(PxSoftBody* softbody0, PxU32 tetIdx0, PxU32 tetIdx1); virtual void addSoftBodyFilters(PxSoftBody* softbody0, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); virtual void removeSoftBodyFilters(PxSoftBody* softbody0, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize); virtual PxU32 addSoftBodyAttachment(PxSoftBody* softbody0, PxU32 tetIdx0, const PxVec4& tetBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset); virtual void removeSoftBodyAttachment(PxSoftBody* softbody0, PxU32 handle); virtual void addClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx); virtual void removeClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx); virtual void addVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx); virtual void removeVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx); virtual PxU32 addClothAttachment(PxFEMCloth* cloth, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset); virtual void removeClothAttachment(PxFEMCloth* cloth, PxU32 handle); // Debug name void setName(const char*); const char* getName() const; void updateMaterials(); private: NpShape* mShape; //soft body should just have one shape. The geometry type should be tetrahedron mesh Gu::TetrahedronMesh* mSimulationMesh; Gu::SoftBodyAuxData* mSoftBodyAuxData; Sc::SoftBodyCore mCore; PxCudaContextManager* mCudaContextManager; }; } #endif #endif
7,805
C
47.185185
169
0.747598
NVIDIA-Omniverse/PhysX/physx/source/physx/src/PvdMetaDataPvdBinding.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 PVD_META_DATA_PVD_BINDING_H #define PVD_META_DATA_PVD_BINDING_H #if PX_SUPPORT_PVD #include "PxPhysXConfig.h" #include "foundation/PxArray.h" namespace physx { namespace pvdsdk { class PsPvd; class PvdDataStream; struct PvdMetaDataBindingData; } } namespace physx { namespace Sc { struct Contact; } namespace Vd { using namespace physx::pvdsdk; class PvdVisualizer { protected: virtual ~PvdVisualizer() { } public: virtual void visualize(PxArticulationLink& link) = 0; }; class PvdMetaDataBinding { PvdMetaDataBindingData* mBindingData; public: PvdMetaDataBinding(); ~PvdMetaDataBinding(); void registerSDKProperties(PvdDataStream& inStream); void sendAllProperties(PvdDataStream& inStream, const PxPhysics& inPhysics); void sendAllProperties(PvdDataStream& inStream, const PxScene& inScene); // per frame update void sendBeginFrame(PvdDataStream& inStream, const PxScene* inScene, PxReal simulateElapsedTime); void sendContacts(PvdDataStream& inStream, const PxScene& inScene, PxArray<Sc::Contact>& inContacts); void sendContacts(PvdDataStream& inStream, const PxScene& inScene); void sendStats(PvdDataStream& inStream, const PxScene* inScene); void sendSceneQueries(PvdDataStream& inStream, const PxScene& inScene, PsPvd* pvd); void sendEndFrame(PvdDataStream& inStream, const PxScene* inScene); void createInstance(PvdDataStream& inStream, const PxMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxFEMSoftBodyMaterial& inMaterial, const PxPhysics& ownerPhysics); // jcarius: Commented-out until FEMCloth is not under construction anymore // void createInstance(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial, const PxPhysics& ownerPhysics); // void sendAllProperties(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial); // void destroyInstance(PvdDataStream& inStream, const PxFEMClothMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxPBDMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxPBDMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxPBDMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxFLIPMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxFLIPMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxFLIPMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxMPMMaterial& inMaterial, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxMPMMaterial& inMaterial); void destroyInstance(PvdDataStream& inStream, const PxMPMMaterial& inMaterial, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxHeightField& inData, const PxPhysics& ownerPhysics); void sendAllProperties(PvdDataStream& inStream, const PxHeightField& inData); void destroyInstance(PvdDataStream& inStream, const PxHeightField& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxConvexMesh& inData, const PxPhysics& ownerPhysics); void destroyInstance(PvdDataStream& inStream, const PxConvexMesh& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxTetrahedronMesh& inData, const PxPhysics& ownerPhysics); void destroyInstance(PvdDataStream& inStream, const PxTetrahedronMesh& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxTriangleMesh& inData, const PxPhysics& ownerPhysics); void destroyInstance(PvdDataStream& inStream, const PxTriangleMesh& inData, const PxPhysics& ownerPhysics); void createInstance(PvdDataStream& inStream, const PxRigidStatic& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxRigidStatic& inObj); void destroyInstance(PvdDataStream& inStream, const PxRigidStatic& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxRigidDynamic& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxRigidDynamic& inObj); void destroyInstance(PvdDataStream& inStream, const PxRigidDynamic& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxSoftBody& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxSoftBody& inObj); void destroyInstance(PvdDataStream& inStream, const PxSoftBody& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxFEMCloth& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxFEMCloth& inObj); void destroyInstance(PvdDataStream& inStream, const PxFEMCloth& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxPBDParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxPBDParticleSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxPBDParticleSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxFLIPParticleSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxMPMParticleSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxMPMParticleSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxMPMParticleSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxHairSystem& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxHairSystem& inObj); void destroyInstance(PvdDataStream& inStream, const PxHairSystem& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj, const PxScene& ownerScene, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj); void destroyInstance(PvdDataStream& inStream, const PxArticulationReducedCoordinate& inObj, const PxScene& ownerScene); void createInstance(PvdDataStream& inStream, const PxArticulationLink& inObj, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxArticulationLink& inObj); void destroyInstance(PvdDataStream& inStream, const PxArticulationLink& inObj); void createInstance(PvdDataStream& inStream, const PxShape& inObj, const PxRigidActor& owner, const PxPhysics& ownerPhysics, PsPvd* pvd); void sendAllProperties(PvdDataStream& inStream, const PxShape& inObj); void releaseAndRecreateGeometry(PvdDataStream& inStream, const PxShape& inObj, PxPhysics& ownerPhysics, PsPvd* pvd); void updateMaterials(PvdDataStream& inStream, const PxShape& inObj, PsPvd* pvd); void destroyInstance(PvdDataStream& inStream, const PxShape& inObj, const PxRigidActor& owner); // These are created as part of the articulation link's creation process, so outside entities don't need to // create them. void sendAllProperties(PvdDataStream& inStream, const PxArticulationJointReducedCoordinate& inObj); // per frame update void updateDynamicActorsAndArticulations(PvdDataStream& inStream, const PxScene* inScene, PvdVisualizer* linkJointViz); // Origin Shift void originShift(PvdDataStream& inStream, const PxScene* inScene, PxVec3 shift); void createInstance(PvdDataStream& inStream, const PxAggregate& inObj, const PxScene& ownerScene); void sendAllProperties(PvdDataStream& inStream, const PxAggregate& inObj); void destroyInstance(PvdDataStream& inStream, const PxAggregate& inObj, const PxScene& ownerScene); void detachAggregateActor(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor); void attachAggregateActor(PvdDataStream& inStream, const PxAggregate& inObj, const PxActor& inActor); template <typename TDataType> void registrarPhysicsObject(PvdDataStream&, const TDataType&, PsPvd*); }; } } #endif #endif
10,880
C
53.405
162
0.809375
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpHairSystem.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 "foundation/PxPreprocessor.h" #if PX_SUPPORT_GPU_PHYSX #include "NpHairSystem.h" #include "NpCheck.h" #include "NpScene.h" #include "ScHairSystemSim.h" #include "NpFactory.h" #include "NpRigidDynamic.h" #include "NpArticulationJointReducedCoordinate.h" #include "NpArticulationLink.h" #include "ScBodyCore.h" #include "ScBodySim.h" #include "geometry/PxHairSystemDesc.h" #include "PxsMemoryManager.h" #include "NpSoftBody.h" #include "PxPhysXGpu.h" #include "PxvGlobals.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #include "GuTetrahedronMeshUtils.h" using namespace physx; namespace physx { #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpHairSystem::NpHairSystem(PxCudaContextManager& cudaContextManager) : NpActorTemplate(PxConcreteType::eHAIR_SYSTEM, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, NpType::eHAIRSYSTEM), mCudaContextManager(&cudaContextManager), mMemoryManager(NULL), mHostMemoryAllocator(NULL), mDeviceMemoryAllocator(NULL) { init(); } NpHairSystem::NpHairSystem(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager) : NpActorTemplate(baseFlags), mCudaContextManager(&cudaContextManager), mMemoryManager(NULL), mHostMemoryAllocator(NULL), mDeviceMemoryAllocator(NULL) { init(); } NpHairSystem::~NpHairSystem() { releaseAllocator(); } void NpHairSystem::init() { mCore.getShapeCore().createBuffers(mCudaContextManager); createAllocator(); mSoftbodyAttachments.getAllocator().setCallback(mHostMemoryAllocator); } void NpHairSystem::releaseAllocator() { // destroy internal buffers if they exist before destroying allocators if(mStrandPastEndIndicesInternal.size() > 0) mStrandPastEndIndicesInternal.reset(); if (mPosInvMassInternal.size() > 0) mPosInvMassInternal.reset(); if (mVelInternal.size() > 0) mVelInternal.reset(); if (mParticleRigidAttachmentsInternal.size() > 0) mParticleRigidAttachmentsInternal.reset(); if (mRestPositionsInternal.size() > 0) mRestPositionsInternal.reset(); mSoftbodyAttachments.reset(); if (mMemoryManager != NULL) { mMemoryManager->~PxsMemoryManager(); mHostMemoryAllocator = NULL; // released by memory manager mDeviceMemoryAllocator = NULL; // released by memory manager PX_FREE(mMemoryManager); } } PxBounds3 NpHairSystem::getWorldBounds(float inflation) const { NP_READ_CHECK(getNpScene()); if (!getNpScene()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Querying bounds of a PxHairSystem which is not part of a PxScene is not supported."); return PxBounds3::empty(); } const Sc::HairSystemSim* sim = mCore.getSim(); PX_ASSERT(sim); PX_SIMD_GUARD; PxBounds3 bounds = sim->getBounds(); PX_ASSERT(bounds.isValid()); // PT: unfortunately we can't just scale the min/max vectors, we need to go through center/extents. const PxVec3 center = bounds.getCenter(); const PxVec3 inflatedExtents = bounds.getExtents() * inflation; return PxBounds3::centerExtents(center, inflatedExtents); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpHairSystem::visualize(PxRenderOutput& out, NpScene& scene) const { if(!(mCore.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; const Sc::Scene& scScene = scene.getScScene(); const bool visualizeAABBs = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AABBS) != 0.0f; if(visualizeAABBs) { out << PxU32(PxDebugColor::eARGB_YELLOW) << PxMat44(PxIdentity); Cm::renderOutputDebugBox(out, mCore.getSim()->getBounds()); } } #endif void NpHairSystem::setHairSystemFlag(PxHairSystemFlag::Enum flag, bool val) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setHairSystemFlag() not allowed while simulation is running. Call will be ignored."); PxHairSystemFlags flags = mCore.getFlags(); if (val) { flags.raise(flag); } else { flags.clear(flag); } mCore.setFlags(flags); mCore.getShapeCore().getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setReadRequestFlag(PxHairSystemData::Enum flag, bool val) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setReadRequestFlag() not allowed while simulation is running. Call will be ignored."); if (val) { mCore.getShapeCore().getLLCore().mReadRequests.raise(flag); } else { mCore.getShapeCore().getLLCore().mReadRequests.clear(flag); } } void NpHairSystem::setReadRequestFlags(PxHairSystemDataFlags flags) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setReadRequestFlag() not allowed while simulation is running. Call will be ignored."); mCore.getShapeCore().getLLCore().mReadRequests = flags; } PxHairSystemDataFlags NpHairSystem::getReadRequestFlags() const { NP_READ_CHECK(getNpScene()); return mCore.getShapeCore().getLLCore().mReadRequests; } void NpHairSystem::setPositionsInvMass(PxVec4* vertexPositionsInvMass, const PxBounds3& bounds) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(vertexPositionsInvMass != NULL, "PxHairSystem::setPositionsInvMass vertexPositionsInvMass must not be NULL.") PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexPositionsInvMass) & 15), "PxHairSystem::setPositionsInvMass vertexPositionInvMass not aligned to 16 bytes"); PX_CHECK_AND_RETURN(!bounds.isEmpty(), "PxHairSystem::setPositionsInvMass bounds must not be empty"); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mNumVertices > 0, "PxHairSystem::setPositionsInvMass numVertices must be greater than zero. Use setTopology().") PX_CHECK_AND_RETURN(llCore.mNumStrands > 0, "PxHairSystem::setPositionsInvMass numStrands must be greater than zero. Use setTopology().") PX_CHECK_AND_RETURN(llCore.mStrandPastEndIndices != NULL, "PxHairSystem::setPositionsInvMass StrandPastEndIndices are not set. Use setTopology().") setLlGridSize(bounds); llCore.mPositionInvMass = vertexPositionsInvMass; // release internal buffers if they're not needed anymore if (vertexPositionsInvMass != mPosInvMassInternal.begin()) mPosInvMassInternal.reset(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePOSITIONS_VELOCITIES_MASS | Dy::HairSystemDirtyFlag::eGRID_SIZE; } void NpHairSystem::setVelocities(PxVec4* vertexVelocities) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(vertexVelocities != NULL, "PxHairSystem::setVelocities vertexVelocities must not be NULL.") PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexVelocities) & 15), "PxHairSystem::setVelocities vertexVelocities not aligned to 16 bytes"); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mNumVertices > 0, "PxHairSystem::setPositionsInvMass numVertices must be greater than zero. Use setTopology().") // release internal buffers if they're not needed anymore if (vertexVelocities != mVelInternal.begin()) mVelInternal.reset(); llCore.mVelocity = vertexVelocities; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePOSITIONS_VELOCITIES_MASS; } void NpHairSystem::setBendingRestAngles(const PxReal* bendingRestAngles, PxReal bendingCompliance) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(bendingRestAngles || llCore.mRestPositionsD, "PxHairSystem::setBendingRestAngles() NULL bendingRestAngles only allowed if restPositions have been set."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setBendingRestAngles() not allowed while simulation is running. Call will be ignored."); llCore.mBendingRestAngles = bendingRestAngles; llCore.mParams.mBendingCompliance = bendingCompliance; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eBENDING_REST_ANGLES | Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setTwistingCompliance(PxReal twistingCompliance) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setTwistingCompliance() not allowed while simulation is running. Call will be ignored.") Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mTwistingCompliance = twistingCompliance; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::getTwistingRestPositions(PxReal* buffer) { NP_READ_CHECK(getNpScene()); PxScopedCudaLock lock(*mCudaContextManager); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); mCudaContextManager->getCudaContext()->memcpyDtoH(buffer, reinterpret_cast<CUdeviceptr>(llCore.mTwistingRestPositionsGpuSim), sizeof(float) * llCore.mNumVertices); } void NpHairSystem::setWakeCounter(PxReal wakeCounterValue) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setWakeCounter() not allowed while simulation is running. Call will be ignored.") mCore.setWakeCounter(wakeCounterValue); mCore.getShapeCore().getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getWakeCounter() const { NP_READ_CHECK(getNpScene()); return mCore.getWakeCounter(); } bool NpHairSystem::isSleeping() const { NP_READ_CHECK(getNpScene()); return mCore.isSleeping(); } void NpHairSystem::setSolverIterationCounts(PxU32 iters) { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); PX_CHECK_AND_RETURN(iters > 0, "PxHairSystem::setSolverIterationCounts: positionIters must be more than zero!"); PX_CHECK_AND_RETURN(iters <= 255, "PxHairSystem::setSolverIterationCounts: positionIters must be no greater than 255!"); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(npScene, "PxHairSystem::setSolverIterationCounts() not allowed while simulation is running. Call will be ignored.") mCore.setSolverIterationCounts(static_cast<PxU16>(iters)); } PxU32 NpHairSystem::getSolverIterationCounts() const { NP_READ_CHECK(getNpScene()); PxU16 x = mCore.getSolverIterationCounts(); return x; } void NpHairSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); if (npScene) { npScene->scRemoveHairSystem(*this); npScene->removeFromHairSystemList(*this); } // detachShape(); PX_ASSERT(!isAPIWriteForbidden()); mCore.getShapeCore().releaseBuffers(); releaseAllocator(); NpDestroyHairSystem(this); } void NpHairSystem::addRigidAttachment(const PxRigidBody& rigidBody) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "PxHairSystem::addRigidAttachment: Hair system must be inserted into the scene."); PX_CHECK_AND_RETURN(rigidBody.getScene() != NULL, "PxHairSystem::addRigidAttachment: Actor not part of a scene."); PX_CHECK_AND_RETURN(getScene() == rigidBody.getScene(), "PxHairSystem::addRigidAttachment: Actor and hair must be part of the same scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::addRigidAttachment: Illegal to call while simulation is running."); const Sc::BodyCore* attachmentBodyCore = getBodyCore(&rigidBody); PX_CHECK_AND_RETURN(attachmentBodyCore != NULL, "PxHairSystem::addRigidAttachment: Attachment body must be rigid dynamic or articulation link."); if(attachmentBodyCore != NULL) { const Sc::BodySim* bodySim = attachmentBodyCore->getSim(); if(bodySim) mCore.addAttachment(*bodySim); } } void NpHairSystem::removeRigidAttachment(const PxRigidBody& rigidBody) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "PxHairSystem::removeRigidAttachment: Hair system must be inserted into the scene."); PX_CHECK_AND_RETURN(rigidBody.getScene() != NULL, "PxHairSystem::removeRigidAttachment: Actor not part of a scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::removeRigidAttachment: Illegal to call while simulation is running."); const Sc::BodyCore* attachmentBodyCore = getBodyCore(&rigidBody); if(attachmentBodyCore != NULL) { const Sc::BodySim* bodySim = attachmentBodyCore->getSim(); if(bodySim) mCore.removeAttachment(*bodySim); } } void NpHairSystem::setRigidAttachments(PxParticleRigidAttachment* attachments, PxU32 numAttachments, bool isGpuPtr) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "PxHairSystem::setRigidAttachments: Hair system must be inserted into the scene."); PX_CHECK_AND_RETURN(attachments != NULL || numAttachments == 0, "PxHairSystem::setRigidAttachments: attachments must not be NULL if numAttachments > 0."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::setRigidAttachments: Illegal to call while simulation is running."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mNumRigidAttachments = numAttachments; if(!isGpuPtr) { // create fresh buffer mParticleRigidAttachmentsInternal.reset(); mParticleRigidAttachmentsInternal.setAllocatorCallback(mDeviceMemoryAllocator); mParticleRigidAttachmentsInternal.allocate(numAttachments); llCore.mRigidAttachments = mParticleRigidAttachmentsInternal.begin(); // copy H2D PxScopedCudaLock lock(*mCudaContextManager); PxCUresult result = mCudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(llCore.mRigidAttachments), attachments, sizeof(PxParticleRigidAttachment) * numAttachments); PX_ASSERT(result == 0); PX_UNUSED(result); } else if (mParticleRigidAttachmentsInternal.begin() != attachments) { mParticleRigidAttachmentsInternal.reset(); llCore.mRigidAttachments = attachments; } // Don't clear mParticleRigidAttachmentsInternal if isGpuPtr==true and user has passed in the same pointer again llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eRIGID_ATTACHMENTS; } PxParticleRigidAttachment* NpHairSystem::getRigidAttachmentsGpu(PxU32* numAttachments) { NP_READ_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); if(numAttachments) *numAttachments = llCore.mNumRigidAttachments; return llCore.mRigidAttachments; } PxU32 NpHairSystem::addSoftbodyAttachment(const PxSoftBody& softbody, const PxU32* tetIds, const PxVec4* tetmeshBarycentrics, const PxU32* hairVertices, PxConeLimitedConstraint* constraints, PxReal* constraintOffsets, PxU32 numAttachments) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(getNpScene(), "PxHairSystem::addSoftbodyAttachment: Illegal to call while simulation is running.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(tetIds != NULL, "PxHairSystem::addSoftbodyAttachment: tetIds must not be null.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(tetmeshBarycentrics != NULL, "PxHairSystem::addSoftbodyAttachment: tetmeshBarycentrics must not be null.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(hairVertices != NULL, "PxHairSystem::addSoftbodyAttachment: hairVertices must not be null.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(softbody.getScene() != NULL, "PxHairSystem::addSoftbodyAttachment: Softbody must be inserted into the scene.", 0xffFFffFF); PX_CHECK_AND_RETURN_VAL(getScene() == softbody.getScene(), "PxHairSystem::addSoftbodyAttachment: Softbody and hair must be part of the same scene.", 0xffFFffFF); if(numAttachments == 0) return 0xffFFffFF; Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); const NpSoftBody& npSoftbody = static_cast<const NpSoftBody&>(softbody); const PxU32 softbodyIdx = npSoftbody.getCore().getGpuSoftBodyIndex(); const PxTetrahedronMesh* simMesh = softbody.getSimulationMesh(); PX_CHECK_AND_RETURN_VAL(NULL != simMesh, "PxHairSystem::addSoftbodyAttachment: The softbody doesn't have a valid simulation mesh.", 0xffFFffFF); const PxSoftBodyAuxData* auxData = softbody.getSoftBodyAuxData(); PX_CHECK_AND_RETURN_VAL(auxData->getConcreteType() == PxConcreteType::eSOFT_BODY_STATE, "PxHairSystem::addSoftbodyAttachment: The softbodies aux data must be of type Gu::SoftBodyAuxData.", 0xffFFffFF); const Gu::SoftBodyAuxData* guAuxData = static_cast<const Gu::SoftBodyAuxData*>(auxData); // Gu::BVTetrahedronMesh does not have a concrete type const PxTetrahedronMesh* collisionMesh = softbody.getCollisionMesh(); const Gu::BVTetrahedronMesh* bvCollisionMesh = static_cast<const Gu::BVTetrahedronMesh*>(collisionMesh); // assign handle by finding the first nonexistent key in the hashmap PxU32 handle = PX_MAX_U32; for(PxU32 i = 0; i < PX_MAX_U32; i++) { if(mSoftbodyAttachmentsOffsets.find(i) == NULL) { handle = i; break; } } PX_ASSERT(handle != PX_MAX_U32); // new attachments will be added to the end of the contiguous array mSoftbodyAttachmentsOffsets[handle] = PxPair<PxU32, PxU32>(mSoftbodyAttachments.size(), numAttachments); mSoftbodyAttachments.reserve(mSoftbodyAttachments.size() + numAttachments); for(PxU32 i=0; i<numAttachments; i++) { // convert to sim mesh tets/barycentrics PxU32 simTetId; PxVec4 simBarycentric; Gu::convertSoftbodyCollisionToSimMeshTets(*simMesh, *guAuxData, *bvCollisionMesh, tetIds[i], tetmeshBarycentrics[i], simTetId, simBarycentric); Dy::SoftbodyHairAttachment attachment; attachment.hairVtxIdx = hairVertices[i]; attachment.softbodyNodeIdx = softbodyIdx; attachment.tetBarycentric = simBarycentric; attachment.tetId = simTetId; if(constraints) { const PxConeLimitedConstraint* constraint = constraints + i; attachment.constraintOffset = constraintOffsets ? constraintOffsets[i] : 0.0f; attachment.low_high_angle = PxVec4(constraint->mLowLimit, constraint->mHighLimit, constraint->mAngle, 0.f); if(constraint->mAngle >= 0.f) { attachment.attachmentBarycentric = Gu::addAxisToSimMeshBarycentric(*simMesh, simTetId, simBarycentric, constraint->mAxis.getNormalized()); } else { attachment.attachmentBarycentric = PxVec4(0.f, 0.f, 0.f, 0.f); } } else { attachment.low_high_angle = PxVec4(-1.f, -1.f, -1.f, 0.f); attachment.attachmentBarycentric = PxVec4(0.f, 0.f, 0.f, 0.f); } mSoftbodyAttachments.pushBack(attachment); } mCore.addAttachment(*npSoftbody.getCore().getSim()); // add edge for island generation llCore.mSoftbodyAttachments = mSoftbodyAttachments.begin(); llCore.mNumSoftbodyAttachments = mSoftbodyAttachments.size(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eSOFTBODY_ATTACHMENTS; return handle; } void NpHairSystem::removeSoftbodyAttachment(const PxSoftBody& softbody, PxU32 handle) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::removeSoftbodyAttachment: Illegal to call while simulation is running."); PX_CHECK_AND_RETURN(softbody.getScene() != NULL, "PxHairSystem::removeSoftbodyAttachment: Softbody must still be inserted into the scene."); const PxPair<const PxU32, PxPair<PxU32, PxU32>>* handleOffsetSize = mSoftbodyAttachmentsOffsets.find(handle); PX_ASSERT(handleOffsetSize != NULL); if(handleOffsetSize == NULL) return; PX_ASSERT(handle == handleOffsetSize->first); const PxU32 offset = handleOffsetSize->second.first; const PxU32 numRemoved = handleOffsetSize->second.second; const PxU32 totSize = mSoftbodyAttachments.size(); // shift all subsequent elements in the attachment array to the left for(PxU32 i=offset; i + numRemoved < totSize; i++) { mSoftbodyAttachments[i] = mSoftbodyAttachments[i+numRemoved]; } mSoftbodyAttachments.resize(mSoftbodyAttachments.size() - numRemoved); // correct all offsets of the still existing attachments and delete the current handle mSoftbodyAttachmentsOffsets.erase(handle); for(PxHashMap<PxU32, PxPair<PxU32, PxU32>>::Iterator it = mSoftbodyAttachmentsOffsets.getIterator(); !it.done(); it++) { if(it->second.first > offset) it->second.first -= numRemoved; } const NpSoftBody& npSoftbody = static_cast<const NpSoftBody&>(softbody); mCore.removeAttachment(*npSoftbody.getCore().getSim()); // remove edge for island generation Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mSoftbodyAttachments = mSoftbodyAttachments.begin(); llCore.mNumSoftbodyAttachments = mSoftbodyAttachments.size(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eSOFTBODY_ATTACHMENTS; } void NpHairSystem::setRestPositions(PxVec4* restPos, bool isGpuPtr) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "PxHairSystem::setRestPositions: Illegal to call while simulation is running."); if(restPos == NULL) isGpuPtr = false; Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); if(!isGpuPtr) { // create fresh buffer mRestPositionsInternal.reset(); mRestPositionsInternal.setAllocatorCallback(mDeviceMemoryAllocator); mRestPositionsInternal.allocate(llCore.mNumVertices); llCore.mRestPositionsD = mRestPositionsInternal.begin(); // use user-provided restPos if available, otherwise current positions mCudaContextManager->copyHToD<PxVec4>(llCore.mRestPositionsD, restPos ? restPos : llCore.mPositionInvMass, llCore.mNumVertices); } else if (mRestPositionsInternal.begin() != restPos) { mRestPositionsInternal.reset(); llCore.mRestPositionsD = restPos; } // Don't clear mRestPositionsInternal if isGpuPtr==true and user has passed in the same pointer again llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eREST_POSITIONS; } PxVec4* NpHairSystem::getRestPositionsGpu() { NP_READ_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mRestPositionsD; } void NpHairSystem::setLlGridSize(const PxBounds3& bounds) { // give system some space to expand: create a grid to accomodate at least 1.5 times the initial size Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); const PxVec3 dimensions = bounds.getDimensions(); const PxReal maxXZ = PxMax(dimensions.x, dimensions.z); // rotations in plane perpendicular to gravity are very likely const PxReal cellSize = llCore.mParams.getCellSize(); const PxU32 tightGridSizeXZ = static_cast<PxU32>(maxXZ / cellSize) + 1; const PxU32 tightGridSizeY = static_cast<PxU32>(dimensions.y / cellSize) + 1; PxU32 gridSizeXZ = PxNextPowerOfTwo(tightGridSizeXZ); PxU32 gridSizeY = PxNextPowerOfTwo(tightGridSizeY); if(gridSizeXZ < 1.5f * tightGridSizeXZ) gridSizeXZ *= 2; if(gridSizeY < 1.5f * tightGridSizeY) gridSizeY *= 2; llCore.mParams.mGridSize[0] = gridSizeXZ; llCore.mParams.mGridSize[1] = gridSizeY; llCore.mParams.mGridSize[2] = llCore.mParams.mGridSize[0]; if (static_cast<PxU32>(dimensions.maxElement() / cellSize) > 512) PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL, "Grid of hair system appears very large (%i by %i by %i). Double check ratio of segment" " length (%f) to extent of the hair system defined by the vertices (%f, %f, %f).", llCore.mParams.mGridSize[0], llCore.mParams.mGridSize[1], llCore.mParams.mGridSize[2], static_cast<double>(llCore.mParams.mSegmentLength), static_cast<double>(dimensions.x), static_cast<double>(dimensions.y), static_cast<double>(dimensions.z)); } void NpHairSystem::createAllocator() { if (!mMemoryManager) { PxPhysXGpu* physXGpu = PxvGetPhysXGpu(true); PX_ASSERT(physXGpu != NULL); mMemoryManager = physXGpu->createGpuMemoryManager(mCudaContextManager); mHostMemoryAllocator = mMemoryManager->getHostMemoryAllocator(); mDeviceMemoryAllocator = mMemoryManager->getDeviceMemoryAllocator(); } PX_ASSERT(mMemoryManager != NULL); PX_ASSERT(mHostMemoryAllocator != NULL); PX_ASSERT(mDeviceMemoryAllocator != NULL); } void NpHairSystem::initFromDesc(const PxHairSystemDesc& desc) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(desc.isValid(), "PxHairSystem::initFromDesc desc is not valid."); PX_ASSERT(mCudaContextManager != NULL); // destroy internal buffers if they exist because we might switch allocators if(mStrandPastEndIndicesInternal.size() > 0) mStrandPastEndIndicesInternal.reset(); if (mPosInvMassInternal.size() > 0) mPosInvMassInternal.reset(); if (mVelInternal.size() > 0) mVelInternal.reset(); // create internal buffers if (desc.flags.isSet(PxHairSystemDescFlag::eDEVICE_MEMORY)) { mPosInvMassInternal.setAllocatorCallback(mDeviceMemoryAllocator); mVelInternal.setAllocatorCallback(mDeviceMemoryAllocator); mStrandPastEndIndicesInternal.setAllocatorCallback(mDeviceMemoryAllocator); } else { mPosInvMassInternal.setAllocatorCallback(mHostMemoryAllocator); mVelInternal.setAllocatorCallback(mHostMemoryAllocator); mStrandPastEndIndicesInternal.setAllocatorCallback(mHostMemoryAllocator); } PxScopedCudaLock lock(*mCudaContextManager); // StrandPastEndIndices MemoryWithAlloc<PxU32> strandPastEndIndicesLocal; strandPastEndIndicesLocal.setAllocatorCallback(mHostMemoryAllocator); strandPastEndIndicesLocal.allocate(desc.numStrands); const PxU32* hostStrandPastEndIndices = strandPastEndIndicesLocal.begin(); PxU32 numVertices = 0; for (PxU32 strandIdx = 0; strandIdx < desc.numStrands; strandIdx++) { PxU32 strandLength = desc.numVerticesPerStrand.at<PxU32>(strandIdx); numVertices += strandLength; strandPastEndIndicesLocal[strandIdx] = numVertices; } if (desc.flags.isSet(PxHairSystemDescFlag::eDEVICE_MEMORY)) { mStrandPastEndIndicesInternal.allocate(desc.numStrands); mCudaContextManager->getCudaContext()->memcpyHtoD( reinterpret_cast<CUdeviceptr>(mStrandPastEndIndicesInternal.begin()), strandPastEndIndicesLocal.begin(), desc.numStrands * sizeof(PxU32)); } else { strandPastEndIndicesLocal.swap(mStrandPastEndIndicesInternal); } // positions, velocities const bool onlyRootPositionsGiven = desc.numStrands == desc.vertices.count; const bool velocitiesGiven = desc.velocities.count > 0; MemoryWithAlloc<PxVec4> posInvMassLocal, velLocal; posInvMassLocal.setAllocatorCallback(mHostMemoryAllocator); posInvMassLocal.allocate(numVertices); velLocal.setAllocatorCallback(mHostMemoryAllocator); velLocal.allocate(numVertices); PxBounds3 bounds = PxBounds3::empty(); PxU32 overallVertexIdx = 0; for (PxU32 strandIdx = 0; strandIdx < desc.numStrands; strandIdx++) { for (; overallVertexIdx < hostStrandPastEndIndices[strandIdx]; overallVertexIdx++) { const PxU32 inputVertexIdx = onlyRootPositionsGiven ? strandIdx : overallVertexIdx; posInvMassLocal[overallVertexIdx] = desc.vertices.at<PxVec4>(inputVertexIdx); velLocal[overallVertexIdx] = velocitiesGiven ? desc.velocities.at<PxVec4>(overallVertexIdx) : PxVec4(PxZero); bounds.include(desc.vertices.at<PxVec4>(inputVertexIdx).getXYZ()); } } PX_ASSERT(overallVertexIdx == numVertices); if (desc.flags.isSet(PxHairSystemDescFlag::eDEVICE_MEMORY)) { mPosInvMassInternal.allocate(numVertices); mVelInternal.allocate(numVertices); mCudaContextManager->getCudaContext()->memcpyHtoD( reinterpret_cast<CUdeviceptr>(mPosInvMassInternal.begin()), posInvMassLocal.begin(), numVertices * sizeof(PxVec4)); mCudaContextManager->getCudaContext()->memcpyHtoD( reinterpret_cast<CUdeviceptr>(mVelInternal.begin()), velLocal.begin(), numVertices * sizeof(PxVec4)); } else { posInvMassLocal.swap(mPosInvMassInternal); velLocal.swap(mVelInternal); } setTopology(mPosInvMassInternal.begin(), mVelInternal.begin(), mStrandPastEndIndicesInternal.begin(), desc.segmentLength, desc.segmentRadius, numVertices, desc.numStrands, bounds); } void NpHairSystem::setTopology(PxVec4* vertexPositionsInvMass, PxVec4* vertexVelocities, const PxU32* strandPastEndIndices, PxReal segmentLength, PxReal segmentRadius, PxU32 numVertices, PxU32 numStrands, const PxBounds3& bounds) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(numVertices > 0, "PxHairSystem::setTopology numVertices must be greater than zero"); PX_CHECK_AND_RETURN(numStrands > 0, "PxHairSystem::setTopology numStrands must be greater than zero"); PX_CHECK_AND_RETURN(segmentLength > 0.0f, "PxHairSystem::setTopology segmentLength must be greater than zero"); PX_CHECK_AND_RETURN(segmentRadius > 0.0f, "PxHairSystem::setTopology segmentRadius must be greater than zero"); PX_CHECK_AND_RETURN(2.0f * segmentRadius < segmentLength, "PxHairSystem::setTopology segmentRadius must be smaller than half of segmentLength. Call ignored"); PX_CHECK_AND_RETURN(!bounds.isEmpty(), "PxHairSystem::setTopology bounds must not be empty"); PX_CHECK_AND_RETURN((vertexPositionsInvMass != NULL && vertexVelocities != NULL), "PxHairSystem::setTopology positions and velocities must not be NULL") PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexPositionsInvMass) & 15), "PxHairSystem::setTopology vertexPositionInvMass not aligned to 16 bytes"); PX_CHECK_AND_RETURN(!((uintptr_t)static_cast<const void *>(vertexVelocities) & 15), "PxHairSystem::setTopology vertexVelocities not aligned to 16 bytes"); PX_CHECK_AND_RETURN(numVertices < (1 << 24), "PxHairSystem::setTopology numVertices must be smaller than 1<<24"); // due to encoding compressedVtxIndex with hairsystem index Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); // release internal buffers if they're not needed anymore if (vertexPositionsInvMass != mPosInvMassInternal.begin()) mPosInvMassInternal.reset(); if (vertexVelocities != mVelInternal.begin()) mVelInternal.reset(); if (strandPastEndIndices != mStrandPastEndIndicesInternal.begin()) mStrandPastEndIndicesInternal.reset(); llCore.mParams.mSegmentLength = segmentLength; setSegmentRadius(segmentRadius); llCore.mParams.mSegmentRadius = segmentRadius; llCore.mNumVertices = numVertices; llCore.mNumStrands = numStrands; llCore.mStrandPastEndIndices = strandPastEndIndices; llCore.mPositionInvMass = vertexPositionsInvMass; llCore.mVelocity = vertexVelocities; // reset rest positions setRestPositions(NULL, false); setLlGridSize(bounds); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eNUM_STRANDS_OR_VERTS | Dy::HairSystemDirtyFlag::ePOSITIONS_VELOCITIES_MASS | Dy::HairSystemDirtyFlag::ePARAMETERS | Dy::HairSystemDirtyFlag::eSTRAND_LENGTHS | Dy::HairSystemDirtyFlag::eGRID_SIZE; } void NpHairSystem::setLevelOfDetailGradations(const PxReal* proportionOfStrands, const PxReal* proportionOfVertices, PxU32 numLevels) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(numLevels > 0, "PxHairSystem::defineLevelOfDetailGradations Must specify at least one level."); for (PxU32 i = 0; i < numLevels; i++) { PX_CHECK_AND_RETURN(proportionOfStrands[i] <= 1.0f && proportionOfStrands[i] > 0.0f, "PxHairSystem::defineLevelOfDetailGradations proportionOfStrands must be in (0, 1] "); PX_CHECK_AND_RETURN(proportionOfVertices[i] <= 1.0f && proportionOfVertices[i] > 0.0f, "PxHairSystem::defineLevelOfDetailGradations proportionOfStrands must be in (0, 1] "); } // deep copy because user buffers may go out of scope / deallocate mLodProportionOfStrands.assign(proportionOfStrands, proportionOfStrands + numLevels); mLodProportionOfVertices.assign(proportionOfVertices, proportionOfVertices + numLevels); // TODO(jcarius) check that hair system is initialized already Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mLodNumLevels = numLevels; llCore.mLodProportionOfStrands = mLodProportionOfStrands.begin(); llCore.mLodProportionOfVertices = mLodProportionOfVertices.begin(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eLOD_DATA; // in case the level that we were on got removed switch to closest one if(llCore.mLodLevel > numLevels) { llCore.mLodLevel = numLevels; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eLOD_SWITCH; } } void NpHairSystem::setLevelOfDetail(PxU32 level) { NP_WRITE_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(level == 0 || llCore.mLodNumLevels >= level, "PxHairSystem::setLevelOfDetail Invalid level given"); llCore.mLodLevel = level; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eLOD_SWITCH; } PxU32 NpHairSystem::getLevelOfDetail(PxU32* numLevels) const { NP_READ_CHECK(getNpScene()); if(numLevels != NULL) { *numLevels = mCore.getShapeCore().getLLCore().mLodNumLevels; } return mCore.getShapeCore().getLLCore().mLodLevel; } void NpHairSystem::setName(const char* debugName) { NP_WRITE_CHECK(getNpScene()); mName = debugName; } const char* NpHairSystem::getName() const { NP_READ_CHECK(getNpScene()); return mName; } void NpHairSystem::getSegmentDimensions(PxReal& length, PxReal& radius) const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); length = llCore.mParams.mSegmentLength; radius = llCore.mParams.mSegmentRadius; } void NpHairSystem::setSegmentRadius(PxReal radius) { NP_WRITE_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(2.0f * radius < llCore.mParams.mSegmentLength, "PxHairSystem::setSegmentRadius radius must be smaller than half of segment length. Call ignored"); llCore.mParams.mSegmentRadius = radius; mCore.setContactOffset(2.0f * radius); // sensible default llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setWind(const PxVec3& wind) { NP_WRITE_CHECK(getNpScene()); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PxVec3 windNormalized = wind; const PxReal magnitude = windNormalized.normalize(); llCore.mWind = PxVec4(windNormalized, magnitude); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxVec3 NpHairSystem::getWind() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mWind.getXYZ() * llCore.mWind.w; } void NpHairSystem::setAerodynamicDrag(PxReal dragCoefficient) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(dragCoefficient >= 0.0f, "PxHairSystem::setAerodynamicDrag: dragCoefficient must be greater or equal zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mAeroDrag = dragCoefficient; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::setAerodynamicLift(PxReal liftCoefficient) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(liftCoefficient >= 0.0f, "PxHairSystem::setAerodynamicLift: liftCoefficient must be greater or equal zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mAeroLift = liftCoefficient; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getAerodynamicDrag() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mAeroDrag; } PxReal NpHairSystem::getAerodynamicLift() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mAeroLift; } void NpHairSystem::setFrictionParameters(PxReal interHairVelDamping, PxReal frictionCoeff) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(interHairVelDamping >= 0.0f, "PxHairSystem::setFrictionParameters interHairVelDamping must be greater or equal zero."); PX_CHECK_AND_RETURN(interHairVelDamping <= 1.0f, "PxHairSystem::setFrictionParameters interHairVelDamping must be smaller or equal one."); PX_CHECK_AND_RETURN(frictionCoeff >= 0.0f, "PxHairSystem::setFrictionParameters frictionCoeff must be greater or equal zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mInterHairVelocityDamping = interHairVelDamping; llCore.mParams.mFrictionCoeff = frictionCoeff; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::getFrictionParameters(PxReal& interHairVelDamping, PxReal& frictionCoeff) const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); interHairVelDamping = llCore.mParams.mInterHairVelocityDamping; frictionCoeff = llCore.mParams.mFrictionCoeff; } void NpHairSystem::setMaxDepenetrationVelocity(PxReal maxDepenetrationVelocity) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(maxDepenetrationVelocity > 0.0f, "PxHairSystem::setMaxDepenetrationVelocity maxDepenetrationVelocity must be larger than zero."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mMaxDepenetrationVelocity = maxDepenetrationVelocity; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getMaxDepenetrationVelocity() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mMaxDepenetrationVelocity; } void NpHairSystem::setShapeCompliance(PxReal startCompliance, PxReal strandRatio) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(strandRatio >= 0.0f, "PxHairSystem::setShapeCompliance strandRatio must not be negative."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mRestPositionsD, "PxHairSystem::setShapeCompliance restPositions must be set before enabling shape compliance"); llCore.mParams.mShapeCompliance[0] = startCompliance; llCore.mParams.mShapeCompliance[1] = strandRatio; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } void NpHairSystem::getShapeCompliance(PxReal& startCompliance, PxReal& strandRatio) const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); startCompliance = llCore.mParams.mShapeCompliance[0]; strandRatio = llCore.mParams.mShapeCompliance[1]; } void NpHairSystem::setInterHairRepulsion(PxReal repulsion) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(repulsion >= 0.0f, "PxHairSystem::setInterHairRepulsion repulsion must not be negative."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mInterHairRepulsion = repulsion; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getInterHairRepulsion() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mInterHairRepulsion; } void NpHairSystem::setSelfCollisionRelaxation(PxReal relaxation) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(relaxation > 0.0f, "PxHairSystem::setSelfCollisionRelaxation relaxation must be greater zero."); PX_CHECK_AND_RETURN(relaxation <= 1.0f, "PxHairSystem::setSelfCollisionRelaxation relaxation must not be greater 1.0."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mSelfCollisionRelaxation = relaxation; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getSelfCollisionRelaxation() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mSelfCollisionRelaxation; } void NpHairSystem::setStretchingRelaxation(PxReal relaxation) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(relaxation > 0.0f, "PxHairSystem::setStretchingRelaxation relaxation must be greater zero."); PX_CHECK_AND_RETURN(relaxation <= 1.0f, "PxHairSystem::setStretchingRelaxation relaxation must not be greater 1.0."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mLraRelaxation = relaxation; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getStretchingRelaxation() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mLraRelaxation; } void NpHairSystem::setContactOffset(PxReal contactOffset) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(contactOffset >= 0.0f, "PxHairSystem::setContactOffset contactOffset must not be negative."); mCore.setContactOffset(contactOffset); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getContactOffset() const { NP_READ_CHECK(getNpScene()); return mCore.getContactOffset(); } void NpHairSystem::setHairContactOffset(PxReal hairContactOffset) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(hairContactOffset >= 1.0f, "PxHairSystem::setHairContactOffset hairContactOffset must not be below 1.0."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); llCore.mParams.mSelfCollisionContactDist = hairContactOffset; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS; } PxReal NpHairSystem::getHairContactOffset() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mSelfCollisionContactDist; } void NpHairSystem::setShapeMatchingParameters(PxReal compliance, PxReal linearStretching, PxU16 numVerticesPerGroup, PxU16 numVerticesOverlap) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(linearStretching >= 0.0f, "PxHairSystem::setShapeMatchingParameters linearStretching must not be below 0.0."); PX_CHECK_AND_RETURN(linearStretching <= 1.0f, "PxHairSystem::setShapeMatchingParameters linearStretching must not be above 1.0."); PX_CHECK_AND_RETURN(numVerticesPerGroup > 1, "PxHairSystem::setShapeMatchingParameters numVerticesPerGroup must be greater 1."); PX_CHECK_AND_RETURN(numVerticesPerGroup >= 2 * numVerticesOverlap, "PxHairSystem::setShapeMatchingParameters numVerticesOverlap must at most be numVerticesPerGroup/2."); Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); PX_CHECK_AND_RETURN(llCore.mRestPositionsD, "PxHairSystem::setShapeMatchingParameters restPositions must be set before enabling shape compliance"); llCore.mParams.mShapeMatchingCompliance = compliance; llCore.mParams.mShapeMatchingBeta = linearStretching; llCore.mParams.mShapeMatchingNumVertsPerGroup = numVerticesPerGroup; llCore.mParams.mShapeMatchingNumVertsOverlap = numVerticesOverlap; llCore.mDirtyFlags |= Dy::HairSystemDirtyFlag::eSHAPE_MATCHING_SIZES; } PxReal NpHairSystem::getShapeMatchingCompliance() const { NP_READ_CHECK(getNpScene()); const Dy::HairSystemCore& llCore = mCore.getShapeCore().getLLCore(); return llCore.mParams.mShapeMatchingCompliance; } #endif } // namespace physx #endif //PX_SUPPORT_GPU_PHYSX
44,510
C++
38.706512
203
0.763941
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpParticleSystem.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" #if PX_SUPPORT_GPU_PHYSX #include "NpParticleSystem.h" #include "foundation/PxAllocator.h" #include "foundation/PxArray.h" #include "foundation/PxMath.h" #include "foundation/PxMemory.h" #include "foundation/PxSort.h" #include "common/PxPhysXCommonConfig.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION #include "PxGridParticleSystem.h" #endif #include "PxRigidActor.h" #include "PxsSimulationController.h" #include "NpArticulationLink.h" #include "NpRigidDynamic.h" #include "NpScene.h" #include "NpCheck.h" #include "ScBodyCore.h" #include "ScParticleSystemCore.h" #include "ScParticleSystemSim.h" #include "ScParticleSystemShapeCore.h" #include "DyParticleSystemCore.h" #include "CmVisualization.h" #define PARTICLE_MAX_NUM_PARTITIONS_TEMP 32 #define PARTICLE_MAX_NUM_PARTITIONS_FINAL 8 using namespace physx; namespace physx { #if PX_ENABLE_DEBUG_VISUALIZATION static void visualizeParticleSystem(PxRenderOutput& out, NpScene& npScene, const Sc::ParticleSystemCore& core) { if (!(core.getActorFlags() & PxActorFlag::eVISUALIZATION)) return; const Sc::Scene& scScene = npScene.getScScene(); const bool visualizeAABBs = scScene.getVisualizationParameter(PxVisualizationParameter::eCOLLISION_AABBS) != 0.0f; if (visualizeAABBs) { out << PxU32(PxDebugColor::eARGB_YELLOW) << PxMat44(PxIdentity); Cm::renderOutputDebugBox(out, core.getSim()->getBounds()); } } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif //////////////////////////////////////////////////////////////////////////////////////// PxPartitionedParticleCloth::PxPartitionedParticleCloth() { PxMemZero(this, sizeof(*this)); } PxPartitionedParticleCloth::~PxPartitionedParticleCloth() { if (mCudaManager) { PxScopedCudaLock lock(*mCudaManager); PxCudaContext* context = mCudaManager->getCudaContext(); if (context) { context->memFreeHost(accumulatedSpringsPerPartitions); context->memFreeHost(accumulatedCopiesPerParticles); context->memFreeHost(remapOutput); context->memFreeHost(orderedSprings); context->memFreeHost(sortedClothStartIndices); context->memFreeHost(cloths); } } } void PxPartitionedParticleCloth::allocateBuffers(PxU32 nbParticles, PxCudaContextManager* cudaManager) { mCudaManager = cudaManager; PxScopedCudaLock lock(*mCudaManager); PxCudaContext* context = mCudaManager->getCudaContext(); const unsigned int CU_MEMHOSTALLOC_DEVICEMAP = 0x02; const unsigned int CU_MEMHOSTALLOC_PORTABLE = 0x01; PxCUresult result = context->memHostAlloc(reinterpret_cast<void**>(&accumulatedSpringsPerPartitions), size_t(sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_FINAL), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); // TODO AD: WTF where does 32 come from? result = context->memHostAlloc(reinterpret_cast<void**>(&accumulatedCopiesPerParticles), size_t(sizeof(PxU32) * nbParticles), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&orderedSprings), size_t(sizeof(PxParticleSpring) * nbSprings), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&remapOutput), size_t(sizeof(PxU32) * nbSprings * 2), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&sortedClothStartIndices), size_t(sizeof(PxU32) * nbCloths), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); result = context->memHostAlloc(reinterpret_cast<void**>(&cloths), size_t(sizeof(PxParticleCloth) * nbCloths), CU_MEMHOSTALLOC_DEVICEMAP | CU_MEMHOSTALLOC_PORTABLE); } //////////////////////////////////////////////////////////////////////////////////////// PxU32 NpParticleClothPreProcessor::computeSpringPartition(const PxParticleSpring& spring, const PxU32 partitionStartIndex, PxU32* partitionProgresses) { PxU32 partitionA = partitionProgresses[spring.ind0]; PxU32 partitionB = partitionProgresses[spring.ind1]; const PxU32 combinedMask = (~partitionA & ~partitionB); PxU32 availablePartition = combinedMask == 0 ? PARTICLE_MAX_NUM_PARTITIONS_TEMP : PxLowestSetBit(combinedMask); if (availablePartition == PARTICLE_MAX_NUM_PARTITIONS_TEMP) { return 0xFFFFFFFF; } const PxU32 partitionBit = (1u << availablePartition); partitionA |= partitionBit; partitionB |= partitionBit; availablePartition += partitionStartIndex; partitionProgresses[spring.ind0] = partitionA; partitionProgresses[spring.ind1] = partitionB; return availablePartition; } void NpParticleClothPreProcessor::writeSprings(const PxParticleSpring* springs, PxU32* partitionProgresses, PxU32* tempSprings, PxU32* orderedSprings, PxU32* accumulatedSpringsPerPartition) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); PxU32 numUnpartitionedSprings = 0; // Goes through all the springs and assigns them to a partition. This code is exactly the same as in classifySprings // except that we now know the start indices of all the partitions so we can write THEIR INDEX into the ordered spring // index list. // AD: All of this relies on the fact that we partition exactly the same way twice. Remember that when changing anything // here. for (PxU32 i = 0; i < mNumSprings; ++i) { const PxParticleSpring& spring = springs[i]; const PxU32 availablePartition = computeSpringPartition(spring, 0, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { tempSprings[numUnpartitionedSprings++] = i; continue; } //output springs orderedSprings[accumulatedSpringsPerPartition[availablePartition]++] = i; } PxU32 partitionStartIndex = 0; // handle the overflow of springs we couldn't partition above. while (numUnpartitionedSprings > 0) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); partitionStartIndex += PARTICLE_MAX_NUM_PARTITIONS_TEMP; PxU32 newNumUnpartitionedSprings = 0; for (PxU32 i = 0; i < numUnpartitionedSprings; ++i) { const PxU32 springInd = tempSprings[i]; const PxParticleSpring& spring = springs[springInd]; const PxU32 availablePartition = computeSpringPartition(spring, partitionStartIndex, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { tempSprings[newNumUnpartitionedSprings++] = springInd; continue; } //output springs orderedSprings[accumulatedSpringsPerPartition[availablePartition]++] = springInd; } numUnpartitionedSprings = newNumUnpartitionedSprings; } // at this point all of the springs are partitioned and in the ordered list. } void NpParticleClothPreProcessor::classifySprings(const PxParticleSpring* springs, PxU32* partitionProgresses, PxU32* tempSprings, physx::PxArray<PxU32>& tempSpringsPerPartition) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); PxU32 numUnpartitionedSprings = 0; // Goes through all the springs and tries to partition, but will max out at 32 partitions (because we only have 32 bits) for (PxU32 i = 0; i < mNumSprings; ++i) { const PxParticleSpring& spring = springs[i]; // will return the first partition where it's possible to place this spring. const PxU32 availablePartition = computeSpringPartition(spring, 0, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { // we couldn't find a partition, so we add the index to this list for later. tempSprings[numUnpartitionedSprings++] = i; continue; } // tracks how many springs we have in each partition. tempSpringsPerPartition[availablePartition]++; } PxU32 partitionStartIndex = 0; // handle the overflow of the springs we couldn't partition above // we work in batches of 32 bits. while (numUnpartitionedSprings > 0) { //initialize the partition progress counter to be zero PxMemZero(partitionProgresses, sizeof(PxU32) * mNumParticles); partitionStartIndex += PARTICLE_MAX_NUM_PARTITIONS_TEMP; //Keep partitioning the un-partitioned constraints and blat the whole thing to 0! tempSpringsPerPartition.resize(PARTICLE_MAX_NUM_PARTITIONS_TEMP + tempSpringsPerPartition.size()); PxMemZero(tempSpringsPerPartition.begin() + partitionStartIndex, sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_TEMP); PxU32 newNumUnpartitionedSprings = 0; for (PxU32 i = 0; i < numUnpartitionedSprings; ++i) { const PxU32 springInd = tempSprings[i]; const PxParticleSpring& spring = springs[springInd]; const PxU32 availablePartition = computeSpringPartition(spring, partitionStartIndex, partitionProgresses); if (availablePartition == 0xFFFFFFFF) { tempSprings[newNumUnpartitionedSprings++] = springInd; continue; } tempSpringsPerPartition[availablePartition]++; } numUnpartitionedSprings = newNumUnpartitionedSprings; } // after all of this we have the number of springs per partition in tempSpringsPerPartition. we don't really know what spring will // go where yet, that will follow later. } PxU32* NpParticleClothPreProcessor::partitions(const PxParticleSpring* springs, PxU32* orderedSpringIndices) { //each particle has a partition progress counter PxU32* tempPartitionProgresses = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumParticles, "tempPartitionProgresses")); //this stores the spring index for the unpartitioned springs PxU32* tempSprings = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumSprings, "tempSprings")); PxArray<PxU32> tempSpringsPerPartition; tempSpringsPerPartition.reserve(PARTICLE_MAX_NUM_PARTITIONS_TEMP); tempSpringsPerPartition.forceSize_Unsafe(PARTICLE_MAX_NUM_PARTITIONS_TEMP); PxMemZero(tempSpringsPerPartition.begin(), sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_TEMP); classifySprings(springs, tempPartitionProgresses, tempSprings, tempSpringsPerPartition); //compute number of partitions PxU32 maxPartitions = 0; for (PxU32 a = 0; a < tempSpringsPerPartition.size(); ++a, maxPartitions++) { if (tempSpringsPerPartition[a] == 0) break; } PxU32* tempAccumulatedSpringsPerPartition = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * maxPartitions, "mAccumulatedSpringsPerPartition")); mNbPartitions = maxPartitions; // save the current number of partitions //compute run sum PxU32 accumulation = 0; for (PxU32 a = 0; a < maxPartitions; ++a) { PxU32 count = tempSpringsPerPartition[a]; tempAccumulatedSpringsPerPartition[a] = accumulation; accumulation += count; } PX_ASSERT(accumulation == mNumSprings); // this will assign the springs to partitions writeSprings(springs, tempPartitionProgresses, tempSprings, orderedSpringIndices, tempAccumulatedSpringsPerPartition); #if 0 && PX_CHECKED //validate spring partitions for (PxU32 i = 0; i < mNumSprings; ++i) { PxU32 springInd = orderedSprings[i]; for (PxU32 j = i + 1; j < mNumSprings; ++j) { PxU32 otherSpringInd = orderedSprings[j]; PX_ASSERT(springInd != otherSpringInd); } } PxArray<bool> mFound(mNumParticles); PxU32 startIndex = 0; for (PxU32 i = 0; i < maxPartition; ++i) { PxU32 endIndex = tempAccumulatedSpringsPerPartition[i]; PxMemZero(mFound.begin(), sizeof(bool) * mNumParticles); for (PxU32 j = startIndex; j < endIndex; ++j) { PxU32 tetrahedronIdx = orderedSprings[j]; const PxParticleSpring& spring = springs[tetrahedronIdx]; PX_ASSERT(!mFound[spring.ind0]); PX_ASSERT(!mFound[spring.ind1]); mFound[spring.ind0] = true; mFound[spring.ind1] = true; } startIndex = endIndex; } #endif PX_FREE(tempPartitionProgresses); PX_FREE(tempSprings); return tempAccumulatedSpringsPerPartition; } PxU32 NpParticleClothPreProcessor::combinePartitions(const PxParticleSpring* springs, const PxU32* orderedSpringIndices, const PxU32* accumulatedSpringsPerPartition, PxU32* accumulatedSpringsPerCombinedPartition, PxParticleSpring* orderedSprings, PxU32* accumulatedCopiesPerParticles, PxU32* remapOutput) { // reduces the number of partitions from mNbPartitions to PARTICLE_MAX_NUM_PARTITIONS_FINAL const PxU32 nbPartitions = mNbPartitions; mNbPartitions = PARTICLE_MAX_NUM_PARTITIONS_FINAL; PxMemZero(accumulatedSpringsPerCombinedPartition, sizeof(PxU32) * PARTICLE_MAX_NUM_PARTITIONS_FINAL); // ceil(nbPartitions/maxPartitions) -basically the number of "repetitions" before combining. Example, MAX_FINAL is 8, we have 20 total, so this is 3. const PxU32 maxAccumulatedCP = (nbPartitions + PARTICLE_MAX_NUM_PARTITIONS_FINAL - 1) / PARTICLE_MAX_NUM_PARTITIONS_FINAL; // enough space for all partitions. const PxU32 partitionArraySize = maxAccumulatedCP * PARTICLE_MAX_NUM_PARTITIONS_FINAL; // for each particle, have a table of all partitions. const PxU32 nbPartitionTables = partitionArraySize * mNumParticles; // per-particle, stores whether particle is part of partition PxU32* tempPartitionTablePerVert = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * nbPartitionTables, "tempPartitionTablePerVert")); // per-particle, stores remapping ????? PxU32* tempRemapTablePerVert = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * nbPartitionTables, "tempRemapTablePerVert")); // per-particle, stores the number of copies for each particle. PxU32* tempNumCopiesEachVerts = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumParticles, "tempNumCopiesEachVerts")); PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * mNumParticles); //initialize partitionTablePerVert for (PxU32 i = 0; i < nbPartitionTables; ++i) { tempPartitionTablePerVert[i] = 0xffffffff; tempRemapTablePerVert[i] = 0xffffffff; } // combine partitions: // let PARTICLE_MAX_NUM_PARTITIONS_FINAL be 8 and the current number of partitions be 20 // this will merge partition 0, 8, 16 into the first partition, // then put 1, 9, 17 into the second partition, etc. // we move all the springs of partition x*PARTICLE_MAX_NUM_PARTITION_FINAL to the end of partition x, // using the count variable. // output of this stage // orderedSprings - has springs per partition // accumulatedSpringsPerCombinedPartition - has number of springs of each partition // tempPartitionTablePerVert - has spring index of spring that connects to this particle in this partition. mMaxSpringsPerPartition = 0; PxU32 count = 0; for (PxU32 i = 0; i < PARTICLE_MAX_NUM_PARTITIONS_FINAL; ++i) { PxU32 totalSpringsInPartition = 0; for (PxU32 j = 0; j < maxAccumulatedCP; ++j) { PxU32 partitionId = i + PARTICLE_MAX_NUM_PARTITIONS_FINAL * j; if (partitionId < nbPartitions) { const PxU32 startInd = partitionId == 0 ? 0 : accumulatedSpringsPerPartition[partitionId - 1]; const PxU32 endInd = accumulatedSpringsPerPartition[partitionId]; const PxU32 index = i * maxAccumulatedCP + j; for (PxU32 k = startInd; k < endInd; ++k) { const PxU32 springInd = orderedSpringIndices[k]; const PxParticleSpring& spring = springs[springInd]; orderedSprings[count] = spring; PX_ASSERT(spring.ind0 != spring.ind1); tempPartitionTablePerVert[spring.ind0 * partitionArraySize + index] = count; tempPartitionTablePerVert[spring.ind1 * partitionArraySize + index] = count + mNumSprings; count++; } totalSpringsInPartition += (endInd - startInd); } } accumulatedSpringsPerCombinedPartition[i] = count; mMaxSpringsPerPartition = PxMax(mMaxSpringsPerPartition, totalSpringsInPartition); } PX_ASSERT(count == mNumSprings); PxMemZero(tempNumCopiesEachVerts, sizeof(PxU32) * mNumParticles); bool* tempHasOccupied = reinterpret_cast<bool*>(PX_ALLOC(sizeof(bool) * partitionArraySize, "tempOrderedSprings")); // compute num of copies and remap index // // remap table - builds a chain of indices of the same particle across partitions // if particle x is at index y in partition 1, we build a table such that particle x in partition 2 can look up the index in partition 1 // This basically maintains the gauss-seidel part of the solver, where each partition works on the results of the another partition. // This remap table is build across combined partitions. So there will never be a remap into the same partition. // // numCopies is then the number of final copies, meaning all copies of each particle that don't have a remap into one of the following // partitions. // for (PxU32 i = 0; i < mNumParticles; ++i) { // for each particle, use this list to track which partition is occupied. PxMemZero(tempHasOccupied, sizeof(bool) * partitionArraySize); // partition table has size numPartitions for each particle, tells you the spring index for this partition const PxU32* partitionTable = &tempPartitionTablePerVert[i * partitionArraySize]; // remapTable is still empty (0xFFFFFFFF) PxU32* remapTable = &tempRemapTablePerVert[i * partitionArraySize]; // for all of the final partitions. for (PxU32 j = 0; j < PARTICLE_MAX_NUM_PARTITIONS_FINAL; ++j) { // start index of this combined partition in the initial partition array const PxU32 startInd = j * maxAccumulatedCP; // start index if the next combined partition in the initial partition array PxU32 nextStartInd = (j + 1) * maxAccumulatedCP; // for our 8/20 example, that would be startInd 0, nextStartInd 3 because every // final partition will be combined from 3 partitions. // go through the indices of this combined partition (0-2) for (PxU32 k = 0; k < maxAccumulatedCP; ++k) { const PxU32 index = startInd + k; if (partitionTable[index] != 0xffffffff) { // there is a spring in this partition connected to this particle bool found = false; // look at the next partition, potentially also further ahead to figure out if there is any other partition having this particle index. for (PxU32 h = nextStartInd; h < partitionArraySize; ++h) { // check if any of the partitions in this combined partition is occupied. const PxU32 remapInd = partitionTable[h]; if (remapInd != 0xffffffff && !tempHasOccupied[h]) { // if it is, and none of the other partitions in the partition before already remapped to that one remapTable[index] = remapInd; // maps from partition i to one of the next ones. found = true; tempHasOccupied[h] = true; // mark as occupied nextStartInd++; // look one more (initial!) partition ahead for next remap. break; } } if (!found) { tempNumCopiesEachVerts[i]++; // if not found, add one more copy as there won't be any follow-up partition taking this position as an input. } } } } } const PxU32 totalNumVerts = mNumSprings * 2; // compute a runSum for the number of copies for each particle PxU32 totalCopies = 0; for (PxU32 i = 0; i < mNumParticles; ++i) { totalCopies += tempNumCopiesEachVerts[i]; accumulatedCopiesPerParticles[i] = totalCopies; } const PxU32 remapOutputSize = totalNumVerts + totalCopies; // fill the output of the remap // // for all particle copies that are at the end of a remap chain, calculate the remap // into the final accumulation buffer. // // the final accumulation buffer will have numCopies entries for each particle. // for (PxU32 i = 0; i < mNumParticles; ++i) { const PxU32 index = i * partitionArraySize; const PxU32* partitionTable = &tempPartitionTablePerVert[index]; PxU32* remapTable = &tempRemapTablePerVert[index]; PxU32 accumulatedCount = 0; for (PxU32 j = 0; j < partitionArraySize; ++j) { const PxU32 vertInd = partitionTable[j]; if (vertInd != 0xffffffff) { PxU32 remapInd = remapTable[j]; //this remap is in the accumulation buffer if (remapInd == 0xffffffff) { const PxU32 start = i == 0 ? 0 : accumulatedCopiesPerParticles[i - 1]; remapInd = totalNumVerts + start + accumulatedCount; accumulatedCount++; } PX_ASSERT(remapInd < remapOutputSize); remapOutput[vertInd] = remapInd; } } } PX_FREE(tempHasOccupied); PX_FREE(tempPartitionTablePerVert); PX_FREE(tempRemapTablePerVert); PX_FREE(tempNumCopiesEachVerts); return remapOutputSize; } void NpParticleClothPreProcessor::partitionSprings(const PxParticleClothDesc& clothDesc, PxPartitionedParticleCloth& output) { mNumSprings = clothDesc.nbSprings; mNumParticles = clothDesc.nbParticles; // prepare the output output.nbSprings = clothDesc.nbSprings; output.nbCloths = clothDesc.nbCloths; output.allocateBuffers(mNumParticles, mCudaContextManager); // will create a temp partitioning with too many partitions PxU32* orderedSpringIndices = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32) * mNumSprings, "orderedSpringIndices")); PxU32* accumulatedSpringsPerPartitionTemp = partitions(clothDesc.springs, orderedSpringIndices); // combine these partitions to a max of PARTICLE_MAX_NUM_PARTITIONS_FINAL // build remap chains and accumulation buffer. output.remapOutputSize = combinePartitions(clothDesc.springs, orderedSpringIndices, accumulatedSpringsPerPartitionTemp, output.accumulatedSpringsPerPartitions, output.orderedSprings, output.accumulatedCopiesPerParticles, output.remapOutput); // get the max number of partitions for each cloth // AD Todo: figure out why blendScale is computed like this. PxParticleCloth* cloths = clothDesc.cloths; for (PxU32 i = 0; i < clothDesc.nbCloths; ++i) { PxU32 maxPartitions = 0; for (PxU32 p = cloths[i].startVertexIndex, endIndex = cloths[i].startVertexIndex + cloths[i].numVertices; p < endIndex; p++) { PxU32 copyStart = p == 0 ? 0 : output.accumulatedCopiesPerParticles[p - 1]; PxU32 copyEnd = output.accumulatedCopiesPerParticles[p]; maxPartitions = PxMax(maxPartitions, copyEnd - copyStart); } cloths[i].clothBlendScale = 1.f / (maxPartitions + 1); } // sort the cloths in this clothDesc according to their startVertexIndex into the particle list. PxSort(cloths, clothDesc.nbCloths); // reorder such that things still match after the sorting. for (PxU32 i = 0; i < clothDesc.nbCloths; ++i) { output.sortedClothStartIndices[i] = cloths[i].startVertexIndex; output.cloths[i] = cloths[i]; } output.nbPartitions = mNbPartitions; output.maxSpringsPerPartition = mMaxSpringsPerPartition; PX_FREE(accumulatedSpringsPerPartitionTemp); PX_FREE(orderedSpringIndices); } void NpParticleClothPreProcessor::release() { PX_DELETE_THIS; } /////////////////////////////////////////////////////////////////////////////////////// NpPBDParticleSystem::NpPBDParticleSystem(PxU32 maxNeighborhood, PxCudaContextManager& cudaContextManager) : NpParticleSystem<PxPBDParticleSystem>(cudaContextManager, PxConcreteType::ePBD_PARTICLESYSTEM, NpType::ePBD_PARTICLESYSTEM, PxActorType::ePBD_PARTICLESYSTEM) { //PX_ASSERT(mCudaContextManager); setSolverType(PxParticleSolverType::ePBD); mCore.getShapeCore().initializeLLCoreData(maxNeighborhood); enableCCD(false); } PxU32 NpPBDParticleSystem::createPhase(PxParticleMaterial* material, const PxParticlePhaseFlags flags) { if (material->getConcreteType() == PxConcreteType::ePBD_MATERIAL) { Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); Dy::ParticleSystemCore& core = shapeCore.getLLCore(); PxU16 materialHandle = static_cast<NpPBDMaterial*>(material)->mMaterial.mMaterialIndex; const PxU32 groupID = mNextPhaseGroupID++; core.mPhaseGroupToMaterialHandle.pushBack(materialHandle); PxU16* foundHandle = core.mUniqueMaterialHandles.find(materialHandle); if(foundHandle == core.mUniqueMaterialHandles.end()) { core.mUniqueMaterialHandles.pushBack(materialHandle); } if (mCore.getSim()) mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PHASE; return (groupID & PxParticlePhaseFlag::eParticlePhaseGroupMask) | (PxU32(flags) & PxParticlePhaseFlag::eParticlePhaseFlagsMask); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxPBDParticleSystem:createPhase(): the provided material is not supported by this type of particle system."); return 0; } } void NpPBDParticleSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveParticleSystem(*this); npScene->removeFromParticleSystemList(*this); } PX_ASSERT(!isAPIWriteForbidden()); NpDestroyParticleSystem(this); } PxU32 NpPBDParticleSystem::getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return getParticleMaterialsInternal<NpPBDMaterial>(userBuffer, bufferSize, startIndex); } void NpPBDParticleSystem::addParticleBuffer(PxParticleBuffer* clothBuffer) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpPBDParticleSystem::addParticleBuffer: this function cannot be called when the particle system is not inserted into the scene!"); mCore.getShapeCore().addParticleBuffer(clothBuffer); } void NpPBDParticleSystem::removeParticleBuffer(PxParticleBuffer* clothBuffer) { mCore.getShapeCore().removeParticleBuffer(clothBuffer); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpPBDParticleSystem::visualize(PxRenderOutput& out, NpScene& npScene) const { visualizeParticleSystem(out, npScene, mCore); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif static void internalAddRigidAttachment(PxRigidActor* actor, Sc::ParticleSystemCore& psCore) { Sc::BodyCore* core = getBodyCore(actor); psCore.addRigidAttachment(core); } static void internalRemoveRigidAttachment(PxRigidActor* actor, Sc::ParticleSystemCore& psCore) { Sc::BodyCore* core = getBodyCore(actor); psCore.removeRigidAttachment(core); } void NpPBDParticleSystem::addRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpPBDParticleSystem::addRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpPBDParticleSystem::addRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpPBDParticleSystem::addRigidAttachment: Illegal to call while simulation is running."); internalAddRigidAttachment(actor, mCore); } void NpPBDParticleSystem::removeRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpPBDParticleSystem::removeRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpPBDParticleSystem::removeRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpPBDParticleSystem::removeRigidAttachment: Illegal to call while simulation is running."); internalRemoveRigidAttachment(actor, mCore); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION NpFLIPParticleSystem::NpFLIPParticleSystem(PxCudaContextManager& cudaContextManager) : NpParticleSystem<PxFLIPParticleSystem>(cudaContextManager, PxConcreteType::eFLIP_PARTICLESYSTEM, NpType::eFLIP_PARTICLESYSTEM, PxActorType::eFLIP_PARTICLESYSTEM) { //PX_ASSERT(mCudaContextManager); setSolverType(PxParticleSolverType::eFLIP); mCore.getShapeCore().initializeLLCoreData(0); enableCCD(false); } PxU32 NpFLIPParticleSystem::createPhase(PxParticleMaterial* material, const PxParticlePhaseFlags flags) { if (material->getConcreteType() == PxConcreteType::eFLIP_MATERIAL) { Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); Dy::ParticleSystemCore& core = shapeCore.getLLCore(); PxU16 materialHandle = static_cast<NpFLIPMaterial*>(material)->mMaterial.mMaterialIndex; const PxU32 groupID = mNextPhaseGroupID++; core.mPhaseGroupToMaterialHandle.pushBack(materialHandle); PxU16* foundHandle = core.mUniqueMaterialHandles.find(materialHandle); if(foundHandle == core.mUniqueMaterialHandles.end()) { core.mUniqueMaterialHandles.pushBack(materialHandle); } if (mCore.getSim()) mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PHASE; return (groupID & PxParticlePhaseFlag::eParticlePhaseGroupMask) | (PxU32(flags) & PxParticlePhaseFlag::eParticlePhaseFlagsMask); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxFLIPParticleSystem:createPhase(): the provided material is not supported by this type of particle system."); return 0; } } void NpFLIPParticleSystem::getSparseGridCoord(PxI32& x, PxI32& y, PxI32& z, PxU32 id) { const PxI32 iid = static_cast<PxI32>(id); x = iid % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; y = (iid / MAX_SPARSEGRID_DIM) % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; z = iid / MAX_SPARSEGRID_DIM / MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; } void NpFLIPParticleSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveParticleSystem(*this); npScene->removeFromParticleSystemList(*this); } PX_ASSERT(!isAPIWriteForbidden()); NpDestroyParticleSystem(this); } void* NpFLIPParticleSystem::getSparseGridDataPointer(PxSparseGridDataFlag::Enum flags) { NpScene* scene = getNpScene(); if (!scene) return NULL; if ((flags & (PxSparseGridDataFlag::eSUBGRID_MASK | PxSparseGridDataFlag::eSUBGRID_ID | PxSparseGridDataFlag::eGRIDCELL_SOLID_GRADIENT_AND_SDF | PxSparseGridDataFlag::eGRIDCELL_SOLID_VELOCITY | PxSparseGridDataFlag::eGRIDCELL_FLUID_SDF | PxSparseGridDataFlag::eGRIDCELL_FLUID_VELOCITY )) == 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxParticleSystem::getSparseGridDataPointer, specified data is not available."); return NULL; } NP_READ_CHECK(scene); return scene->getSimulationController()->getSparseGridDataPointer(*getCore().getSim()->getLowLevelParticleSystem(), flags, getCore().getSolverType()); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpFLIPParticleSystem::visualize(PxRenderOutput& out, NpScene& npScene) const { visualizeParticleSystem(out, npScene, mCore); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif PxU32 NpFLIPParticleSystem::getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return getParticleMaterialsInternal<NpFLIPMaterial>(userBuffer, bufferSize, startIndex); } void NpFLIPParticleSystem::addParticleBuffer(PxParticleBuffer* particleBuffer) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpFLIPParticleSystem::addParticleBuffer: this function cannot be called when the particle system is not inserted into the scene!"); PxType type = particleBuffer->getConcreteType(); if (type == PxConcreteType::ePARTICLE_BUFFER || type == PxConcreteType::ePARTICLE_DIFFUSE_BUFFER) { mCore.getShapeCore().addParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpFLIPParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } void NpFLIPParticleSystem::removeParticleBuffer(PxParticleBuffer* particleBuffer) { PxType type = particleBuffer->getConcreteType(); if (type == PxConcreteType::ePARTICLE_BUFFER || type == PxConcreteType::ePARTICLE_DIFFUSE_BUFFER) { mCore.getShapeCore().removeParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpFLIPParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// NpMPMParticleSystem::NpMPMParticleSystem(PxCudaContextManager& cudaContextManager) : NpParticleSystem<PxMPMParticleSystem>(cudaContextManager, PxConcreteType::eMPM_PARTICLESYSTEM, NpType::eMPM_PARTICLESYSTEM, PxActorType::eMPM_PARTICLESYSTEM) { //PX_ASSERT(mCudaContextManager); setSolverType(PxParticleSolverType::eMPM); mCore.getShapeCore().initializeLLCoreData(0); enableCCD(false); } PxU32 NpMPMParticleSystem::createPhase(PxParticleMaterial* material, const PxParticlePhaseFlags flags) { if (material->getConcreteType() == PxConcreteType::eMPM_MATERIAL) { Sc::ParticleSystemShapeCore& shapeCore = mCore.getShapeCore(); Dy::ParticleSystemCore& core = shapeCore.getLLCore(); PxU16 materialHandle = static_cast<NpMPMMaterial*>(material)->mMaterial.mMaterialIndex; const PxU32 groupID = mNextPhaseGroupID++; core.mPhaseGroupToMaterialHandle.pushBack(materialHandle); PxU16* foundHandle = core.mUniqueMaterialHandles.find(materialHandle); if(foundHandle == core.mUniqueMaterialHandles.end()) { core.mUniqueMaterialHandles.pushBack(materialHandle); } if (mCore.getSim()) mCore.getSim()->getLowLevelParticleSystem()->mFlag |= Dy::ParticleSystemFlag::eUPDATE_PHASE; return (groupID & PxParticlePhaseFlag::eParticlePhaseGroupMask) | (PxU32(flags) & PxParticlePhaseFlag::eParticlePhaseFlagsMask); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMPMParticleSystem:createPhase(): the provided material is not supported by this type of particle system."); return 0; } } void NpMPMParticleSystem::getSparseGridCoord(PxI32& x, PxI32& y, PxI32& z, PxU32 id) { const PxI32 iid = static_cast<PxI32>(id); x = iid % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; y = (iid / MAX_SPARSEGRID_DIM) % MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; z = iid / MAX_SPARSEGRID_DIM / MAX_SPARSEGRID_DIM + MIN_SPARSEGRID_ID; } void NpMPMParticleSystem::release() { NpScene* npScene = getNpScene(); NP_WRITE_CHECK(npScene); // NpPhysics::getInstance().notifyDeletionListenersUserRelease(this, PxArticulationBase::userData); if (npScene) { npScene->scRemoveParticleSystem(*this); npScene->removeFromParticleSystemList(*this); } PX_ASSERT(!isAPIWriteForbidden()); NpDestroyParticleSystem(this); } void* NpMPMParticleSystem::getSparseGridDataPointer(PxSparseGridDataFlag::Enum flags) { if ((flags & (PxSparseGridDataFlag::eSUBGRID_MASK | PxSparseGridDataFlag::eSUBGRID_ID | PxSparseGridDataFlag::eGRIDCELL_SOLID_GRADIENT_AND_SDF | PxSparseGridDataFlag::eGRIDCELL_SOLID_VELOCITY | PxSparseGridDataFlag::eGRIDCELL_FLUID_SDF | PxSparseGridDataFlag::eGRIDCELL_FLUID_VELOCITY )) == 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxParticleSystem::getSparseGridDataPointer, specified data is not available."); return NULL; } NP_READ_CHECK(getNpScene()); NpScene* scene = getNpScene(); return scene->getSimulationController()->getSparseGridDataPointer(*getCore().getSim()->getLowLevelParticleSystem(), flags, getCore().getSolverType()); } void* NpMPMParticleSystem::getMPMDataPointer(PxMPMParticleDataFlag::Enum flags) { NpScene* scene = getNpScene(); if (!scene) return NULL; if ((flags & (PxMPMParticleDataFlag::eMPM_AFFINE_C1 | PxMPMParticleDataFlag::eMPM_AFFINE_C2 | PxMPMParticleDataFlag::eMPM_AFFINE_C3 | PxMPMParticleDataFlag::eMPM_DEFORMATION_GRADIENT_F1 | PxMPMParticleDataFlag::eMPM_DEFORMATION_GRADIENT_F2 | PxMPMParticleDataFlag::eMPM_DEFORMATION_GRADIENT_F3)) == 0) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "PxMPMParticleSystem::copyData, specified data is not available."); return NULL; } NP_READ_CHECK(scene); return scene->getSimulationController()->getMPMDataPointer(*getCore().getSim()->getLowLevelParticleSystem(), flags); } #if PX_ENABLE_DEBUG_VISUALIZATION void NpMPMParticleSystem::visualize(PxRenderOutput& out, NpScene& npScene) const { visualizeParticleSystem(out, npScene, mCore); } #else PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION #endif PxU32 NpMPMParticleSystem::getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex) const { return getParticleMaterialsInternal<NpMPMMaterial>(userBuffer, bufferSize, startIndex); } void NpMPMParticleSystem::addParticleBuffer(PxParticleBuffer* particleBuffer) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpMPMParticleSystem::addParticleBuffer: this function cannot be called when the particle system is not inserted into the scene!"); if (particleBuffer->getConcreteType() == PxConcreteType::ePARTICLE_BUFFER) { mCore.getShapeCore().addParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpMPMParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } void NpMPMParticleSystem::removeParticleBuffer(PxParticleBuffer* particleBuffer) { if (particleBuffer->getConcreteType() == PxConcreteType::ePARTICLE_BUFFER) { mCore.getShapeCore().removeParticleBuffer(particleBuffer); } else { PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "NpMPMParticleSystem:addParticleBuffer(): the provided buffer type is not supported by this type of particle system."); } } void NpMPMParticleSystem::addRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpMPMParticleSystem::addRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpMPMParticleSystem::addRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpMPMParticleSystem::addRigidAttachment: Illegal to call while simulation is running."); internalAddRigidAttachment(actor, mCore); } void NpMPMParticleSystem::removeRigidAttachment(PxRigidActor* actor) { NP_WRITE_CHECK(getNpScene()); PX_CHECK_AND_RETURN(getNpScene() != NULL, "NpMPMParticleSystem::removeRigidAttachment: particleSystem must be inserted into the scene."); PX_CHECK_AND_RETURN((actor == NULL || actor->getScene() != NULL), "NpMPMParticleSystem::removeRigidAttachment: actor must be inserted into the scene."); PX_CHECK_SCENE_API_WRITE_FORBIDDEN(getNpScene(), "NpMPMParticleSystem::removeRigidAttachment: Illegal to call while simulation is running."); internalRemoveRigidAttachment(actor, mCore); } #endif } physx::PxParticleClothPreProcessor* PxCreateParticleClothPreProcessor(physx::PxCudaContextManager* cudaContextManager) { physx::PxParticleClothPreProcessor* processor = PX_NEW(physx::NpParticleClothPreProcessor)(cudaContextManager); return processor; } #endif //PX_SUPPORT_GPU_PHYSX
41,369
C++
37.27012
258
0.739563