file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/snippets/snippetdelayloadhook/SnippetDelayLoadHook.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
// ****************************************************************************
// This snippet illustrates the use of the dll delay load hooks in physx.
//
// The hooks are needed if the application executable either doesn't reside
// in the same directory as the PhysX dlls, or if the PhysX dlls have been renamed.
// Some PhysX dlls delay load the PhysXFoundation, PhysXCommon or PhysXGpu dlls and
// the non-standard names or loactions of these dlls need to be communicated so the
// delay loading can succeed.
//
// This snippet shows how this can be done using the delay load hooks.
//
// In order to show functionality with the renamed dlls some basic physics
// simulation is performed.
// ****************************************************************************
#include <ctype.h>
#include <wtypes.h>
#include "PxPhysicsAPI.h"
// Include the delay load hook headers
#include "common/windows/PxWindowsDelayLoadHook.h"
#include "../snippetcommon/SnippetPrint.h"
#include "../snippetcommon/SnippetPVD.h"
#include "../snippetutils/SnippetUtils.h"
// This snippet uses the default PhysX distro dlls, making the example here somewhat artificial,
// as default locations and default naming makes implementing delay load hooks unnecessary.
#define APP_BIN_DIR "..\\"
#if PX_WIN64
#define DLL_NAME_BITS "64"
#else
#define DLL_NAME_BITS "32"
#endif
#if PX_DEBUG
#define DLL_DIR "debug\\"
#elif PX_CHECKED
#define DLL_DIR "checked\\"
#elif PX_PROFILE
#define DLL_DIR "profile\\"
#else
#define DLL_DIR "release\\"
#endif
const char* foundationLibraryPath = APP_BIN_DIR DLL_DIR "PhysXFoundation_" DLL_NAME_BITS ".dll";
const char* commonLibraryPath = APP_BIN_DIR DLL_DIR "PhysXCommon_" DLL_NAME_BITS ".dll";
const char* physxLibraryPath = APP_BIN_DIR DLL_DIR "PhysX_" DLL_NAME_BITS ".dll";
const char* gpuLibraryPath = APP_BIN_DIR DLL_DIR "PhysXGpu_" DLL_NAME_BITS ".dll";
HMODULE foundationLibrary = NULL;
HMODULE commonLibrary = NULL;
HMODULE physxLibrary = NULL;
using namespace physx;
static PxDefaultAllocator gAllocator;
static PxDefaultErrorCallback gErrorCallback;
static PxFoundation* gFoundation = NULL;
static PxPhysics* gPhysics = NULL;
static PxDefaultCpuDispatcher* gDispatcher = NULL;
PxScene* gScene = NULL;
static PxMaterial* gMaterial = NULL;
static PxPvd* gPvd = NULL;
// typedef the PhysX entry points
typedef PxFoundation*(PxCreateFoundation_FUNC)(PxU32, PxAllocatorCallback&, PxErrorCallback&);
typedef PxPhysics* (PxCreatePhysics_FUNC)(PxU32,PxFoundation&,const PxTolerancesScale& scale,bool,PxPvd*);
typedef void (PxSetPhysXDelayLoadHook_FUNC)(const PxDelayLoadHook* hook);
typedef void (PxSetPhysXCommonDelayLoadHook_FUNC)(const PxDelayLoadHook* hook);
#if PX_SUPPORT_GPU_PHYSX
typedef void (PxSetPhysXGpuLoadHook_FUNC)(const PxGpuLoadHook* hook);
typedef int (PxGetSuggestedCudaDeviceOrdinal_FUNC)(PxErrorCallback& errc);
typedef PxCudaContextManager* (PxCreateCudaContextManager_FUNC)(PxFoundation& foundation, const PxCudaContextManagerDesc& desc, physx::PxProfilerCallback* profilerCallback);
#endif
// set the function pointers to NULL
PxCreateFoundation_FUNC* s_PxCreateFoundation_Func = NULL;
PxCreatePhysics_FUNC* s_PxCreatePhysics_Func = NULL;
PxSetPhysXDelayLoadHook_FUNC* s_PxSetPhysXDelayLoadHook_Func = NULL;
PxSetPhysXCommonDelayLoadHook_FUNC* s_PxSetPhysXCommonDelayLoadHook_Func = NULL;
#if PX_SUPPORT_GPU_PHYSX
PxSetPhysXGpuLoadHook_FUNC* s_PxSetPhysXGpuLoadHook_Func = NULL;
PxGetSuggestedCudaDeviceOrdinal_FUNC* s_PxGetSuggestedCudaDeviceOrdinal_Func = NULL;
PxCreateCudaContextManager_FUNC* s_PxCreateCudaContextManager_Func = NULL;
#endif
bool loadPhysicsExplicitely()
{
// load the dlls
foundationLibrary = LoadLibraryA(foundationLibraryPath);
if(!foundationLibrary)
return false;
commonLibrary = LoadLibraryA(commonLibraryPath);
if(!commonLibrary)
{
FreeLibrary(foundationLibrary);
return false;
}
physxLibrary = LoadLibraryA(physxLibraryPath);
if(!physxLibrary)
{
FreeLibrary(foundationLibrary);
FreeLibrary(commonLibrary);
return false;
}
// get the function pointers
s_PxCreateFoundation_Func = (PxCreateFoundation_FUNC*)GetProcAddress(foundationLibrary, "PxCreateFoundation");
s_PxCreatePhysics_Func = (PxCreatePhysics_FUNC*)GetProcAddress(physxLibrary, "PxCreatePhysics");
s_PxSetPhysXDelayLoadHook_Func = (PxSetPhysXDelayLoadHook_FUNC*)GetProcAddress(physxLibrary, "PxSetPhysXDelayLoadHook");
s_PxSetPhysXCommonDelayLoadHook_Func = (PxSetPhysXCommonDelayLoadHook_FUNC*)GetProcAddress(commonLibrary, "PxSetPhysXCommonDelayLoadHook");
#if PX_SUPPORT_GPU_PHYSX
s_PxSetPhysXGpuLoadHook_Func = (PxSetPhysXGpuLoadHook_FUNC*)GetProcAddress(physxLibrary, "PxSetPhysXGpuLoadHook");
s_PxGetSuggestedCudaDeviceOrdinal_Func = (PxGetSuggestedCudaDeviceOrdinal_FUNC*)GetProcAddress(physxLibrary, "PxGetSuggestedCudaDeviceOrdinal");
s_PxCreateCudaContextManager_Func = (PxCreateCudaContextManager_FUNC*)GetProcAddress(physxLibrary, "PxCreateCudaContextManager");
#endif
// check if we have all required function pointers
if(s_PxCreateFoundation_Func == NULL || s_PxCreatePhysics_Func == NULL || s_PxSetPhysXDelayLoadHook_Func == NULL || s_PxSetPhysXCommonDelayLoadHook_Func == NULL)
return false;
#if PX_SUPPORT_GPU_PHYSX
if(s_PxSetPhysXGpuLoadHook_Func == NULL || s_PxGetSuggestedCudaDeviceOrdinal_Func == NULL || s_PxCreateCudaContextManager_Func == NULL)
return false;
#endif
return true;
}
// unload the dlls
void unloadPhysicsExplicitely()
{
FreeLibrary(physxLibrary);
FreeLibrary(commonLibrary);
FreeLibrary(foundationLibrary);
}
// Overriding the PxDelayLoadHook allows the load of a custom name dll inside PhysX, PhysXCommon and PhysXCooking dlls
struct SnippetDelayLoadHook : public PxDelayLoadHook
{
virtual const char* getPhysXFoundationDllName() const
{
return foundationLibraryPath;
}
virtual const char* getPhysXCommonDllName() const
{
return commonLibraryPath;
}
};
#if PX_SUPPORT_GPU_PHYSX
// Overriding the PxGpuLoadHook allows the load of a custom GPU name dll
struct SnippetGpuLoadHook : public PxGpuLoadHook
{
virtual const char* getPhysXGpuDllName() const
{
return gpuLibraryPath;
}
};
#endif
PxReal stackZ = 10.0f;
PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0))
{
PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f);
dynamic->setAngularDamping(0.5f);
dynamic->setLinearVelocity(velocity);
gScene->addActor(*dynamic);
return dynamic;
}
void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent)
{
PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial);
for(PxU32 i=0; i<size;i++)
{
for(PxU32 j=0;j<size-i;j++)
{
PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent);
PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm));
body->attachShape(*shape);
PxRigidBodyExt::updateMassAndInertia(*body, 10.0f);
gScene->addActor(*body);
}
}
shape->release();
}
void initPhysics(bool interactive)
{
// load the explictely named dlls
const bool isLoaded = loadPhysicsExplicitely();
if (!isLoaded)
return;
gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback);
// set PhysX and PhysXCommon delay load hook, this must be done before the create physics is called, before
// the PhysXFoundation, PhysXCommon delay load happens.
SnippetDelayLoadHook delayLoadHook;
s_PxSetPhysXDelayLoadHook_Func(&delayLoadHook);
s_PxSetPhysXCommonDelayLoadHook_Func(&delayLoadHook);
#if PX_SUPPORT_GPU_PHYSX
// set PhysXGpu load hook
SnippetGpuLoadHook gpuLoadHook;
s_PxSetPhysXGpuLoadHook_Func(&gpuLoadHook);
#endif
gPvd = PxCreatePvd(*gFoundation);
PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10);
gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL);
gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd);
// We setup the delay load hooks first
PxSceneDesc sceneDesc(gPhysics->getTolerancesScale());
sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f);
gDispatcher = PxDefaultCpuDispatcherCreate(2);
sceneDesc.cpuDispatcher = gDispatcher;
sceneDesc.filterShader = PxDefaultSimulationFilterShader;
gScene = gPhysics->createScene(sceneDesc);
PxPvdSceneClient* pvdClient = gScene->getScenePvdClient();
if(pvdClient)
{
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true);
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true);
pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true);
}
gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f);
PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial);
gScene->addActor(*groundPlane);
for(PxU32 i=0;i<5;i++)
createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f);
if(!interactive)
createDynamic(PxTransform(PxVec3(0,40,100)), PxSphereGeometry(10), PxVec3(0,-50,-100));
}
void stepPhysics(bool /*interactive*/)
{
if (gScene)
{
gScene->simulate(1.0f/60.0f);
gScene->fetchResults(true);
}
}
void cleanupPhysics(bool /*interactive*/)
{
PX_RELEASE(gScene);
PX_RELEASE(gDispatcher);
PX_RELEASE(gPhysics);
if(gPvd)
{
PxPvdTransport* transport = gPvd->getTransport();
gPvd->release(); gPvd = NULL;
PX_RELEASE(transport);
}
PX_RELEASE(gFoundation);
unloadPhysicsExplicitely();
printf("SnippetDelayLoadHook done.\n");
}
void keyPress(unsigned char key, const PxTransform& camera)
{
switch(toupper(key))
{
case 'B': createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); break;
case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break;
}
}
int snippetMain(int, const char*const*)
{
#ifdef RENDER_SNIPPET
extern void renderLoop();
renderLoop();
#else
static const PxU32 frameCount = 100;
initPhysics(false);
for(PxU32 i=0; i<frameCount; i++)
stepPhysics(false);
cleanupPhysics(false);
#endif
return 0;
}
| 11,775 | C++ | 35.012232 | 173 | 0.759745 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdFileReadStreamImpl.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 "OmniPvdFileReadStreamImpl.h"
OmniPvdFileReadStreamImpl::OmniPvdFileReadStreamImpl()
{
mFileName = 0;
mFileWasOpened = false;
mPFile = 0;
}
OmniPvdFileReadStreamImpl::~OmniPvdFileReadStreamImpl()
{
closeFile();
delete[] mFileName;
mFileName = 0;
}
void OMNI_PVD_CALL OmniPvdFileReadStreamImpl::setFileName(const char* fileName)
{
if (!fileName) return;
int n = (int)strlen(fileName) + 1;
if (n < 2) return;
delete[] mFileName;
mFileName = new char[n];
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
strcpy_s(mFileName, n, fileName);
#else
strcpy(mFileName, fileName);
#endif
mFileName[n - 1] = 0;
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::openFile()
{
if (mFileWasOpened)
{
return true;
}
if (!mFileName)
{
return false;
}
mPFile = 0;
mFileWasOpened = true;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
errno_t err = fopen_s(&mPFile, mFileName, "rb");
if (err != 0)
{
mFileWasOpened = false;
}
else
{
fseek(mPFile, 0, SEEK_SET);
}
#else
mPFile = fopen(mFileName, "rb");
if (mPFile)
{
fseek(mPFile, 0, SEEK_SET);
}
else
{
mFileWasOpened = false;
}
#endif
return mFileWasOpened;
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::closeFile()
{
if (mFileWasOpened)
{
fclose(mPFile);
mPFile = 0;
mFileWasOpened = false;
}
return true;
}
uint64_t OMNI_PVD_CALL OmniPvdFileReadStreamImpl::readBytes(uint8_t* bytes, uint64_t nbrBytes)
{
if (mFileWasOpened)
{
size_t result = fread(bytes, 1, nbrBytes, mPFile);
return (int)result;
} else {
return 0;
}
}
uint64_t OMNI_PVD_CALL OmniPvdFileReadStreamImpl::skipBytes(uint64_t nbrBytes)
{
if (mFileWasOpened)
{
fseek(mPFile, (long)nbrBytes, SEEK_CUR);
return 0;
}
else {
return 0;
}
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::openStream()
{
return openFile();
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::closeStream()
{
return closeFile();
}
| 3,658 | C++ | 25.323741 | 94 | 0.723619 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdWriterImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 OMNI_PVD_WRITER_IMPL_H
#define OMNI_PVD_WRITER_IMPL_H
#include "OmniPvdWriter.h"
#include "OmniPvdLog.h"
class OmniPvdWriterImpl : public OmniPvdWriter {
public:
OmniPvdWriterImpl();
~OmniPvdWriterImpl();
void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction);
void setVersionHelper();
void setVersion(OmniPvdVersionType majorVersion, OmniPvdVersionType minorVersion, OmniPvdVersionType patch);
void OMNI_PVD_CALL setWriteStream(OmniPvdWriteStream& stream);
OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream();
OmniPvdClassHandle OMNI_PVD_CALL registerClass(const char* className, OmniPvdClassHandle baseClass);
OmniPvdAttributeHandle OMNI_PVD_CALL registerEnumValue(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdEnumValueType value);
OmniPvdAttributeHandle OMNI_PVD_CALL registerAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType, uint32_t nbElements);
OmniPvdAttributeHandle OMNI_PVD_CALL registerFlagsAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle enumClassHandle);
OmniPvdAttributeHandle OMNI_PVD_CALL registerClassAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle classAttributeHandle);
OmniPvdAttributeHandle OMNI_PVD_CALL registerUniqueListAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType);
void OMNI_PVD_CALL setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes);
void OMNI_PVD_CALL addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes);
void OMNI_PVD_CALL removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes);
void OMNI_PVD_CALL createObject(OmniPvdContextHandle contextHandle, OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName);
void OMNI_PVD_CALL destroyObject(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle);
void OMNI_PVD_CALL startFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp);
void OMNI_PVD_CALL stopFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp);
bool mIsFirstWrite;
OmniPvdLog mLog;
OmniPvdWriteStream* mStream;
int mLastClassHandle;
int mLastAttributeHandle;};
#endif
| 4,411 | C | 62.942028 | 236 | 0.818635 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdLibraryFunctionsImpl.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 "OmniPvdLibraryFunctions.h"
#include "OmniPvdReaderImpl.h"
#include "OmniPvdWriterImpl.h"
#include "OmniPvdFileReadStreamImpl.h"
#include "OmniPvdFileWriteStreamImpl.h"
#include "OmniPvdMemoryStreamImpl.h"
OMNI_PVD_EXPORT OmniPvdReader* OMNI_PVD_CALL createOmniPvdReader()
{
return new OmniPvdReaderImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdReader(OmniPvdReader& reader)
{
OmniPvdReaderImpl* impl = (OmniPvdReaderImpl*)(&reader);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdWriter* OMNI_PVD_CALL createOmniPvdWriter()
{
return new OmniPvdWriterImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdWriter(OmniPvdWriter& writer)
{
OmniPvdWriterImpl* impl = (OmniPvdWriterImpl*)(&writer);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdFileReadStream* OMNI_PVD_CALL createOmniPvdFileReadStream()
{
return new OmniPvdFileReadStreamImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdFileReadStream(OmniPvdFileReadStream& readStream)
{
OmniPvdFileReadStreamImpl* impl = (OmniPvdFileReadStreamImpl*)(&readStream);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdFileWriteStream* OMNI_PVD_CALL createOmniPvdFileWriteStream()
{
return new OmniPvdFileWriteStreamImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdFileWriteStream(OmniPvdFileWriteStream& writeStream)
{
OmniPvdFileWriteStreamImpl* impl = (OmniPvdFileWriteStreamImpl*)(&writeStream);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdMemoryStream* OMNI_PVD_CALL createOmniPvdMemoryStream()
{
return new OmniPvdMemoryStreamImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdMemoryStream(OmniPvdMemoryStream& memoryStream)
{
OmniPvdMemoryStreamImpl* impl = (OmniPvdMemoryStreamImpl*)(&memoryStream);
delete impl;
}
| 3,409 | C++ | 36.888888 | 101 | 0.787914 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryStreamImpl.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 "OmniPvdMemoryStreamImpl.h"
#include "OmniPvdMemoryReadStreamImpl.h"
#include "OmniPvdMemoryWriteStreamImpl.h"
#include <string.h>
OmniPvdMemoryStreamImpl::OmniPvdMemoryStreamImpl()
{
mReadStream = 0;
mWriteStream = 0;
mBuffer = 0;
mBufferLength = 0;
mWrittenBytes = 0;
mWritePosition = 0;
mReadPosition = 0;
mReadStream = new OmniPvdMemoryReadStreamImpl();
mReadStream->mMemoryStream = this;
mWriteStream = new OmniPvdMemoryWriteStreamImpl();
mWriteStream->mMemoryStream = this;
}
OmniPvdMemoryStreamImpl::~OmniPvdMemoryStreamImpl()
{
delete[] mBuffer;
delete mReadStream;
delete mWriteStream;
}
OmniPvdReadStream* OMNI_PVD_CALL OmniPvdMemoryStreamImpl::getReadStream()
{
return mReadStream;
}
OmniPvdWriteStream* OMNI_PVD_CALL OmniPvdMemoryStreamImpl::getWriteStream()
{
return mWriteStream;
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryStreamImpl::setBufferSize(uint64_t bufferLength)
{
if (bufferLength < mBufferLength)
{
return mBufferLength;
}
delete[] mBuffer;
mBuffer = new uint8_t[bufferLength];
mBufferLength = bufferLength;
mWrittenBytes = 0;
mWritePosition = 0;
mReadPosition = 0;
return bufferLength;
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryStreamImpl::readBytes(uint8_t* destination, uint64_t nbrBytes)
{
if (mWrittenBytes < 1) return 0;
////////////////////////////////////////////////////////////////////////////////
// Limit the number of bytes requested to requestedReadBytes
////////////////////////////////////////////////////////////////////////////////
uint64_t requestedReadBytes = nbrBytes;
if (requestedReadBytes > mBufferLength)
{
requestedReadBytes = mBufferLength;
}
if (requestedReadBytes > mWrittenBytes)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Separate the reading of bytes into two operations:
// tail bytes : bytes from mReadPosition until maximum the end of the buffer
// head bytes : bytes from start of the buffer until maximum the mReadPosition-1
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Tail bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t tailBytes = mBufferLength - mReadPosition;
if (tailBytes > requestedReadBytes)
{
tailBytes = requestedReadBytes;
}
if (destination)
{
memcpy(destination, mBuffer + mReadPosition, tailBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Head bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t headBytes = requestedReadBytes - tailBytes;
if (destination)
{
memcpy(destination + tailBytes, mBuffer, headBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Update the internal parameters : mReadPosition and mWrittenBytes
////////////////////////////////////////////////////////////////////////////////
mReadPosition += requestedReadBytes;
if (mReadPosition >= mBufferLength)
{
mReadPosition -= mBufferLength;
}
mWrittenBytes -= requestedReadBytes;
return requestedReadBytes;
}
uint64_t OmniPvdMemoryStreamImpl::skipBytes(uint64_t nbrBytes)
{
return readBytes(0, nbrBytes);
}
uint64_t OmniPvdMemoryStreamImpl::writeBytes(const uint8_t* source, uint64_t nbrBytes)
{
if (mWrittenBytes >= mBufferLength)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Limit the number of bytes requested to requestedWriteBytes
////////////////////////////////////////////////////////////////////////////////
uint64_t requestedWriteBytes = nbrBytes;
if (requestedWriteBytes > mBufferLength)
{
requestedWriteBytes = mBufferLength;
}
uint64_t writeBytesLeft = mBufferLength - mWrittenBytes;
if (requestedWriteBytes > writeBytesLeft)
{
return 0;
//requestedWriteBytes = writeBytesLeft;
}
////////////////////////////////////////////////////////////////////////////////
// Tail bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t tailBytes = mBufferLength - mWritePosition;
if (tailBytes > requestedWriteBytes)
{
tailBytes = requestedWriteBytes;
}
if (source)
{
memcpy(mBuffer + mWritePosition, source, tailBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Head bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t headBytes = requestedWriteBytes - tailBytes;
if (source)
{
memcpy(mBuffer, source + tailBytes, headBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Update the internal parameters : mReadPosition and mWrittenBytes
////////////////////////////////////////////////////////////////////////////////
mWritePosition += requestedWriteBytes;
if (mWritePosition >= mBufferLength)
{
mWritePosition -= mBufferLength;
}
mWrittenBytes += requestedWriteBytes;
return requestedWriteBytes;
}
bool OmniPvdMemoryStreamImpl::flush()
{
return true;
}
| 6,836 | C++ | 32.679803 | 98 | 0.597572 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryStreamImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 OMNI_PVD_MEMORY_STREAM_IMPL_H
#define OMNI_PVD_MEMORY_STREAM_IMPL_H
#include "OmniPvdMemoryStream.h"
class OmniPvdMemoryReadStreamImpl;
class OmniPvdMemoryWriteStreamImpl;
class OmniPvdMemoryStreamImpl : public OmniPvdMemoryStream
{
public:
OmniPvdMemoryStreamImpl();
~OmniPvdMemoryStreamImpl();
OmniPvdReadStream* OMNI_PVD_CALL getReadStream();
OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream();
uint64_t OMNI_PVD_CALL setBufferSize(uint64_t bufferLength);
////////////////////////////////////////////////////////////////////////////////
// Read part
////////////////////////////////////////////////////////////////////////////////
uint64_t readBytes(uint8_t* destination, uint64_t nbrBytes);
uint64_t skipBytes(uint64_t nbrBytes);
////////////////////////////////////////////////////////////////////////////////
// Write part
////////////////////////////////////////////////////////////////////////////////
uint64_t writeBytes(const uint8_t* source, uint64_t nbrBytes);
bool flush();
////////////////////////////////////////////////////////////////////////////////
// Read/write streams
////////////////////////////////////////////////////////////////////////////////
OmniPvdMemoryReadStreamImpl *mReadStream;
OmniPvdMemoryWriteStreamImpl *mWriteStream;
////////////////////////////////////////////////////////////////////////////////
// Round robin buffer
////////////////////////////////////////////////////////////////////////////////
uint8_t *mBuffer;
uint64_t mBufferLength;
uint64_t mWrittenBytes;
uint64_t mWritePosition;
uint64_t mReadPosition;
};
#endif
| 3,310 | C | 42.565789 | 81 | 0.620846 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdReaderImpl.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 "OmniPvdDefinesInternal.h"
#include "OmniPvdReaderImpl.h"
#include <inttypes.h>
OmniPvdReaderImpl::OmniPvdReaderImpl()
{
mMajorVersion = OMNI_PVD_VERSION_MAJOR;
mMinorVersion = OMNI_PVD_VERSION_MINOR;
mPatch = OMNI_PVD_VERSION_PATCH;
mDataBuffer = 0;
mDataBuffAllocatedLen = 0;
mCmdAttributeDataPtr = 0;
mIsReadingStarted = false;
mReadBaseClassHandle = 1;
}
OmniPvdReaderImpl::~OmniPvdReaderImpl()
{
mCmdAttributeDataPtr = 0;
delete[] mDataBuffer;
mDataBuffer = 0;
mDataBuffAllocatedLen = 0;
}
void OMNI_PVD_CALL OmniPvdReaderImpl::setLogFunction(OmniPvdLogFunction logFunction)
{
mLog.setLogFunction(logFunction);
}
void OMNI_PVD_CALL OmniPvdReaderImpl::setReadStream(OmniPvdReadStream& stream)
{
mStream = &stream;
mStream->openStream();
}
bool OMNI_PVD_CALL OmniPvdReaderImpl::startReading(OmniPvdVersionType& majorVersion, OmniPvdVersionType& minorVersion, OmniPvdVersionType& patch)
{
if (mIsReadingStarted)
{
return true;
}
if (mStream)
{
mStream->readBytes((uint8_t*)&majorVersion, sizeof(OmniPvdVersionType));
mStream->readBytes((uint8_t*)&minorVersion, sizeof(OmniPvdVersionType));
mStream->readBytes((uint8_t*)&patch, sizeof(OmniPvdVersionType));
mCmdMajorVersion = majorVersion;
mCmdMinorVersion = minorVersion;
mCmdPatch = patch;
if ((mCmdMajorVersion == 0) && (mCmdMinorVersion < 3))
{
mCmdBaseClassHandle = 0;
mReadBaseClassHandle = 0;
}
else
{
mCmdBaseClassHandle = 0;
mReadBaseClassHandle = 1;
}
mLog.outputLine("OmniPvdRuntimeReaderImpl::startReading majorVersion(%lu), minorVersion(%lu), patch(%lu)", static_cast<unsigned long>(majorVersion), static_cast<unsigned long>(minorVersion), static_cast<unsigned long>(patch));
if (majorVersion > mMajorVersion)
{
mLog.outputLine("[parser] major version too new\n");
return false;
}
else if (majorVersion == mMajorVersion)
{
if (minorVersion > mMinorVersion)
{
mLog.outputLine("[parser] minor version too new\n");
return false;
}
else if (minorVersion == mMinorVersion)
{
if (patch > mPatch)
{
mLog.outputLine("[parser] patch too new\n");
return false;
}
}
}
mIsReadingStarted = true;
return true;
}
else {
return false;
}
}
static OmniPvdDataType::Enum readDataType(OmniPvdReadStream& stream)
{
OmniPvdDataTypeStorageType dataType;
stream.readBytes((uint8_t*)&dataType, sizeof(OmniPvdDataTypeStorageType));
return static_cast<OmniPvdDataType::Enum>(dataType);
}
OmniPvdCommand::Enum OMNI_PVD_CALL OmniPvdReaderImpl::getNextCommand()
{
OmniPvdCommand::Enum cmdType = OmniPvdCommand::eINVALID;
if (!mIsReadingStarted)
{
if (!startReading(mCmdMajorVersion, mCmdMinorVersion, mCmdPatch))
{
return cmdType;
}
}
if (mStream) {
OmniPvdCommandStorageType command;
if (mStream->readBytes(&command, sizeof(OmniPvdCommandStorageType)))
{
switch (command) {
case OmniPvdCommand::eREGISTER_CLASS:
{
cmdType = OmniPvdCommand::eREGISTER_CLASS;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
////////////////////////////////////////////////////////////////////////////////
// Skip reading the base class if the stream is older or equal to (0,2,x)
////////////////////////////////////////////////////////////////////////////////
if (mReadBaseClassHandle)
{
mStream->readBytes((uint8_t*)&mCmdBaseClassHandle, sizeof(OmniPvdClassHandle));
}
mStream->readBytes((uint8_t*)&mCmdClassNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdClassName, mCmdClassNameLen);
mCmdClassName[mCmdClassNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register class (handle: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), mCmdClassName);
}
break;
case OmniPvdCommand::eREGISTER_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREGISTER_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
mCmdAttributeDataType = readDataType(*mStream);
if (mCmdAttributeDataType == OmniPvdDataType::eENUM_VALUE)
{
mStream->readBytes((uint8_t*)&mCmdEnumValue, sizeof(OmniPvdEnumValueType));
}
else if (mCmdAttributeDataType == OmniPvdDataType::eFLAGS_WORD)
{
mStream->readBytes((uint8_t*)&mCmdEnumClassHandle, sizeof(OmniPvdClassHandle));
}
else
{
mCmdEnumValue = 0;
mStream->readBytes((uint8_t*)&mCmdAttributeNbElements, sizeof(uint32_t));
}
mStream->readBytes((uint8_t*)&mCmdAttributeNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdAttributeName, mCmdAttributeNameLen);
mCmdAttributeName[mCmdAttributeNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register attribute (classHandle: %llu, handle: %llu, dataType: %llu, nrFields: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataType), static_cast<unsigned long long>(mCmdAttributeNbElements), mCmdAttributeName);
}
break;
case OmniPvdCommand::eREGISTER_CLASS_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREGISTER_CLASS_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdAttributeName, mCmdAttributeNameLen);
mCmdAttributeName[mCmdAttributeNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register class attribute (classHandle: %llu, handle: %llu, classAttributeHandle: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeClassHandle), mCmdAttributeName);
}
break;
case OmniPvdCommand::eREGISTER_UNIQUE_LIST_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREGISTER_UNIQUE_LIST_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
mCmdAttributeDataType = readDataType(*mStream);
mStream->readBytes((uint8_t*)&mCmdAttributeNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdAttributeName, mCmdAttributeNameLen);
mCmdAttributeName[mCmdAttributeNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register attributeSet (classHandle: %llu, handle: %llu, dataType: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataType), mCmdAttributeName);
}
break;
case OmniPvdCommand::eSET_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eSET_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandleDepth, sizeof(uint8_t));
uint32_t* attributeHandleStack = mCmdAttributeHandleStack;
for (int i = 0; i < mCmdAttributeHandleDepth; i++) {
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
attributeHandleStack++;
}
mStream->readBytes((uint8_t*)&mCmdAttributeDataLen, sizeof(uint32_t));
readLongDataFromStream(mCmdAttributeDataLen);
mLog.outputLine("[parser] set attribute (contextHandle:%llu, objectHandle: %llu, handle: %llu, dataLen: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataLen));
}
break;
case OmniPvdCommand::eADD_TO_UNIQUE_LIST_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eADD_TO_UNIQUE_LIST_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandleDepth, sizeof(uint8_t));
uint32_t* attributeHandleStack = mCmdAttributeHandleStack;
for (int i = 0; i < mCmdAttributeHandleDepth; i++) {
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
attributeHandleStack++;
}
mStream->readBytes((uint8_t*)&mCmdAttributeDataLen, sizeof(uint32_t));
readLongDataFromStream(mCmdAttributeDataLen);
mLog.outputLine("[parser] add to attributeSet (contextHandle:%llu, objectHandle: %llu, attributeHandle: %llu, dataLen: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataLen));
}
break;
case OmniPvdCommand::eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandleDepth, sizeof(uint8_t));
uint32_t* attributeHandleStack = mCmdAttributeHandleStack;
for (int i = 0; i < mCmdAttributeHandleDepth; i++) {
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
attributeHandleStack++;
}
mStream->readBytes((uint8_t*)&mCmdAttributeDataLen, sizeof(uint32_t));
readLongDataFromStream(mCmdAttributeDataLen);
mLog.outputLine("[parser] remove from attributeSet (contextHandle:%llu, objectHandle: %llu, handle: %llu, dataLen: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataLen));
}
break;
case OmniPvdCommand::eCREATE_OBJECT:
{
cmdType = OmniPvdCommand::eCREATE_OBJECT;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdObjectNameLen, sizeof(uint16_t));
if (mCmdObjectNameLen) {
mStream->readBytes((uint8_t*)mCmdObjectName, mCmdObjectNameLen);
}
mCmdObjectName[mCmdObjectNameLen] = 0; // trailing zero
mLog.outputLine("[parser] create object (contextHandle: %llu, classHandle: %llu, objectHandle: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdObjectHandle), mCmdObjectName);
}
break;
case OmniPvdCommand::eDESTROY_OBJECT:
{
cmdType = OmniPvdCommand::eDESTROY_OBJECT;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mLog.outputLine("[parser] destroy object (contextHandle: %llu, objectHandle: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle));
}
break;
case OmniPvdCommand::eSTART_FRAME:
{
cmdType = OmniPvdCommand::eSTART_FRAME;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdFrameTimeStart, sizeof(uint64_t));
mLog.outputLine("[parser] start frame (contextHandle: %llu, timeStamp: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdFrameTimeStart));
}
break;
case OmniPvdCommand::eSTOP_FRAME:
{
cmdType = OmniPvdCommand::eSTOP_FRAME;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdFrameTimeStop, sizeof(uint64_t));
mLog.outputLine("[parser] stop frame (contextHandle: %llu, timeStamp: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdFrameTimeStop));
}
break;
default:
{
}
break;
}
return cmdType;
} else {
return cmdType;
}
}
else {
return cmdType;
}
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getMajorVersion()
{
return mCmdMajorVersion;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getMinorVersion()
{
return mCmdMinorVersion;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getPatch()
{
return mCmdPatch;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getContextHandle()
{
return mCmdContextHandle;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getClassHandle()
{
return mCmdClassHandle;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getBaseClassHandle()
{
return mCmdBaseClassHandle;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeHandle() {
return mCmdAttributeHandle;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getObjectHandle() {
return mCmdObjectHandle;
}
const char* OMNI_PVD_CALL OmniPvdReaderImpl::getClassName() {
return mCmdClassName;
}
const char* OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeName() {
return mCmdAttributeName;
}
const char* OMNI_PVD_CALL OmniPvdReaderImpl::getObjectName() {
return mCmdObjectName;
}
const uint8_t* OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeDataPointer() {
return mCmdAttributeDataPtr;
}
OmniPvdDataType::Enum OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeDataType() {
return mCmdAttributeDataType;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeDataLength() {
return mCmdAttributeDataLen;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeNumberElements() {
return mCmdAttributeNbElements;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeClassHandle() {
return mCmdAttributeClassHandle;
}
uint8_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeNumberHandles() {
return mCmdAttributeHandleDepth;
}
uint32_t* OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeHandles() {
return mCmdAttributeHandleStack;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getFrameTimeStart() {
return mCmdFrameTimeStart;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getFrameTimeStop() {
return mCmdFrameTimeStop;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getEnumClassHandle()
{
return mCmdEnumClassHandle;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getEnumValue()
{
return mCmdEnumValue;
}
void OmniPvdReaderImpl::readLongDataFromStream(uint32_t streamByteLen) {
if (streamByteLen < 1) return;
if (streamByteLen > mDataBuffAllocatedLen) {
delete[] mDataBuffer;
mDataBuffAllocatedLen = (uint32_t)(streamByteLen * 1.3f);
mDataBuffer = new uint8_t[mDataBuffAllocatedLen];
mCmdAttributeDataPtr = mDataBuffer;
}
mStream->readBytes(mCmdAttributeDataPtr, streamByteLen);
}
| 16,972 | C++ | 39.315914 | 367 | 0.737155 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdWriterImpl.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 "OmniPvdDefinesInternal.h"
#include "OmniPvdWriterImpl.h"
#include "OmniPvdCommands.h"
#include <string.h>
OmniPvdWriterImpl::OmniPvdWriterImpl()
{
mLastClassHandle = 0;
mLastAttributeHandle = 0;
mIsFirstWrite = true;
mStream = 0;
}
OmniPvdWriterImpl::~OmniPvdWriterImpl()
{
}
void OMNI_PVD_CALL OmniPvdWriterImpl::setLogFunction(OmniPvdLogFunction logFunction)
{
mLog.setLogFunction(logFunction);
}
void OmniPvdWriterImpl::setVersionHelper()
{
if (mStream && mIsFirstWrite)
{
const OmniPvdVersionType omniPvdVersionMajor = OMNI_PVD_VERSION_MAJOR;
const OmniPvdVersionType omniPvdVersionMinor = OMNI_PVD_VERSION_MINOR;
const OmniPvdVersionType omniPvdVersionPatch = OMNI_PVD_VERSION_PATCH;
setVersion(omniPvdVersionMajor, omniPvdVersionMinor, omniPvdVersionPatch);
}
}
void OmniPvdWriterImpl::setVersion(OmniPvdVersionType majorVersion, OmniPvdVersionType minorVersion, OmniPvdVersionType patch)
{
if (mStream && mIsFirstWrite)
{
if (!mStream->openStream())
{
return;
}
mStream->writeBytes((const uint8_t*)&majorVersion, sizeof(OmniPvdVersionType));
mStream->writeBytes((const uint8_t*)&minorVersion, sizeof(OmniPvdVersionType));
mStream->writeBytes((const uint8_t*)&patch, sizeof(OmniPvdVersionType));
mLog.outputLine("OmniPvdRuntimeWriterImpl::setVersion majorVersion(%lu), minorVersion(%lu), patch(%lu)", static_cast<unsigned long>(majorVersion), static_cast<unsigned long>(minorVersion), static_cast<unsigned long>(patch));
mIsFirstWrite = false;
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::setWriteStream(OmniPvdWriteStream& stream)
{
mLog.outputLine("OmniPvdRuntimeWriterImpl::setWriteStream");
mStream = &stream;
}
OmniPvdWriteStream* OMNI_PVD_CALL OmniPvdWriterImpl::getWriteStream()
{
return mStream;
}
static void writeCommand(OmniPvdWriteStream& stream, OmniPvdCommand::Enum command)
{
const OmniPvdCommandStorageType commandTmp = static_cast<OmniPvdCommandStorageType>(command);
stream.writeBytes((const uint8_t*)&commandTmp, sizeof(OmniPvdCommandStorageType));
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerClass(const char* className, OmniPvdClassHandle baseClass)
{
setVersionHelper();
if (mStream)
{
mLog.outputLine("OmniPvdWriterImpl::registerClass className(%s)", className);
int classNameLen = (int)strlen(className);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_CLASS);
mLastClassHandle++;
mStream->writeBytes((const uint8_t*)&mLastClassHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&baseClass, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&classNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)className, classNameLen);
return mLastClassHandle;
} else {
return 0;
}
}
static void writeDataType(OmniPvdWriteStream& stream, OmniPvdDataType::Enum attributeDataType)
{
const OmniPvdDataTypeStorageType dataType = static_cast<OmniPvdDataTypeStorageType>(attributeDataType);
stream.writeBytes((const uint8_t*)&dataType, sizeof(OmniPvdDataTypeStorageType));
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType, uint32_t nbElements)
{
setVersionHelper();
if (mStream) {
mLog.outputLine("OmniPvdWriterImpl::registerAttribute classHandle(%llu), attributeName(%s), attributeDataType(%d), nbrFields(%llu)", static_cast<unsigned long long>(classHandle), attributeName, static_cast<int>(attributeDataType), static_cast<unsigned long long>(nbElements));
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, attributeDataType);
mStream->writeBytes((const uint8_t*)&nbElements, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerFlagsAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle enumClassHandle)
{
setVersionHelper();
if (mStream) {
mLog.outputLine("OmniPvdWriterImpl::registerFlagsAttribute classHandle(%llu), enumClassHandle(%llu), attributeName(%s)", static_cast<unsigned long long>(classHandle), static_cast<unsigned long long>(enumClassHandle), attributeName);
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, OmniPvdDataType::eFLAGS_WORD);
mStream->writeBytes((const uint8_t*)&enumClassHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerEnumValue(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdEnumValueType value)
{
setVersionHelper();
if (mStream) {
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, OmniPvdDataType::eENUM_VALUE);
mStream->writeBytes((const uint8_t*)&value, sizeof(OmniPvdEnumValueType));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerClassAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle classAttributeHandle)
{
setVersionHelper();
if (mStream)
{
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_CLASS_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
mStream->writeBytes((const uint8_t*)&classAttributeHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerUniqueListAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType)
{
setVersionHelper();
if (mStream)
{
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_UNIQUE_LIST_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, attributeDataType);
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else
{
return 0;
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eSET_ATTRIBUTE);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
mStream->writeBytes((const uint8_t*)&nbAttributeHandles, sizeof(uint8_t));
for (int i = 0; i < nbAttributeHandles; i++)
{
mStream->writeBytes((const uint8_t*)attributeHandles, sizeof(OmniPvdAttributeHandle));
attributeHandles++;
}
mStream->writeBytes((const uint8_t*)&nbrBytes, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)data, nbrBytes);
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eADD_TO_UNIQUE_LIST_ATTRIBUTE);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
mStream->writeBytes((const uint8_t*)&nbAttributeHandles, sizeof(uint8_t));
for (int i = 0; i < nbAttributeHandles; i++)
{
mStream->writeBytes((const uint8_t*)attributeHandles, sizeof(OmniPvdAttributeHandle));
attributeHandles++;
}
mStream->writeBytes((const uint8_t*)&nbrBytes, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)data, nbrBytes);
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
mStream->writeBytes((const uint8_t*)&nbAttributeHandles, sizeof(uint8_t));
for (int i = 0; i < nbAttributeHandles; i++)
{
mStream->writeBytes((const uint8_t*)attributeHandles, sizeof(OmniPvdAttributeHandle));
attributeHandles++;
}
mStream->writeBytes((const uint8_t*)&nbrBytes, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)data, nbrBytes);
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::createObject(OmniPvdContextHandle contextHandle, OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eCREATE_OBJECT);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
int objectNameLen = 0;
if (objectName)
{
objectNameLen = (int)strlen(objectName);
mStream->writeBytes((const uint8_t*)&objectNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)objectName, objectNameLen);
}
else
{
mStream->writeBytes((const uint8_t*)&objectNameLen, sizeof(uint16_t));
}
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::destroyObject(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eDESTROY_OBJECT);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::startFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eSTART_FRAME);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&timeStamp, sizeof(uint64_t));
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::stopFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eSTOP_FRAME);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&timeStamp, sizeof(uint64_t));
}
}
| 14,149 | C++ | 40.374269 | 278 | 0.778076 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdReaderImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 OMNI_PVD_RUNTIME_READER_IMPL_H
#define OMNI_PVD_RUNTIME_READER_IMPL_H
#include "OmniPvdReader.h"
#include "OmniPvdLog.h"
class OmniPvdReaderImpl : public OmniPvdReader {
public:
OmniPvdReaderImpl();
~OmniPvdReaderImpl();
void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction);
void OMNI_PVD_CALL setReadStream(OmniPvdReadStream& stream);
bool OMNI_PVD_CALL startReading(OmniPvdVersionType& majorVersion, OmniPvdVersionType& minorVersion, OmniPvdVersionType& patch);
OmniPvdCommand::Enum OMNI_PVD_CALL getNextCommand();
OmniPvdVersionType OMNI_PVD_CALL getMajorVersion();
OmniPvdVersionType OMNI_PVD_CALL getMinorVersion();
OmniPvdVersionType OMNI_PVD_CALL getPatch();
OmniPvdContextHandle OMNI_PVD_CALL getContextHandle();
OmniPvdObjectHandle OMNI_PVD_CALL getObjectHandle();
OmniPvdClassHandle OMNI_PVD_CALL getClassHandle();
OmniPvdClassHandle OMNI_PVD_CALL getBaseClassHandle();
OmniPvdAttributeHandle OMNI_PVD_CALL getAttributeHandle();
const char* OMNI_PVD_CALL getClassName();
const char* OMNI_PVD_CALL getAttributeName();
const char* OMNI_PVD_CALL getObjectName();
const uint8_t* OMNI_PVD_CALL getAttributeDataPointer();
OmniPvdDataType::Enum OMNI_PVD_CALL getAttributeDataType();
uint32_t OMNI_PVD_CALL getAttributeDataLength();
uint32_t OMNI_PVD_CALL getAttributeNumberElements();
OmniPvdClassHandle OMNI_PVD_CALL getAttributeClassHandle();
uint8_t OMNI_PVD_CALL getAttributeNumberHandles();
OmniPvdAttributeHandle* OMNI_PVD_CALL getAttributeHandles();
uint64_t OMNI_PVD_CALL getFrameTimeStart();
uint64_t OMNI_PVD_CALL getFrameTimeStop();
OmniPvdClassHandle OMNI_PVD_CALL getEnumClassHandle();
uint32_t OMNI_PVD_CALL getEnumValue();
// Internal helper
void readLongDataFromStream(uint32_t streamByteLen);
OmniPvdLog mLog;
OmniPvdReadStream *mStream;
OmniPvdVersionType mMajorVersion;
OmniPvdVersionType mMinorVersion;
OmniPvdVersionType mPatch;
OmniPvdVersionType mCmdMajorVersion;
OmniPvdVersionType mCmdMinorVersion;
OmniPvdVersionType mCmdPatch;
OmniPvdContextHandle mCmdContextHandle;
OmniPvdObjectHandle mCmdObjectHandle;
uint32_t mCmdClassHandle;
uint32_t mCmdBaseClassHandle;
uint32_t mCmdAttributeHandle;
////////////////////////////////////////////////////////////////////////////////
// TODO : take care of buffer length limit at read time!
////////////////////////////////////////////////////////////////////////////////
char mCmdClassName[1000];
char mCmdAttributeName[1000];
char mCmdObjectName[1000];
uint16_t mCmdClassNameLen;
uint16_t mCmdAttributeNameLen;
uint16_t mCmdObjectNameLen;
uint8_t* mCmdAttributeDataPtr;
OmniPvdDataType::Enum mCmdAttributeDataType;
uint32_t mCmdAttributeDataLen;
uint32_t mCmdAttributeNbElements;
OmniPvdEnumValueType mCmdEnumValue;
OmniPvdClassHandle mCmdEnumClassHandle;
OmniPvdClassHandle mCmdAttributeClassHandle;
OmniPvdAttributeHandle mCmdAttributeHandleStack[32];
uint8_t mCmdAttributeHandleDepth;
uint64_t mCmdFrameTimeStart;
uint64_t mCmdFrameTimeStop;
uint8_t *mDataBuffer;
uint32_t mDataBuffAllocatedLen;
bool mIsReadingStarted;
uint8_t mReadBaseClassHandle;
};
#endif
| 4,852 | C | 36.330769 | 128 | 0.771228 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdLoader.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 OMNI_PVD_LOADER_H
#define OMNI_PVD_LOADER_H
#include "OmniPvdWriter.h"
#include "OmniPvdReader.h"
#include "OmniPvdLibraryFunctions.h"
#include <stdio.h>
#ifdef OMNI_PVD_WIN
#ifndef _WINDOWS_ // windows already included otherwise
#include <foundation/windows/PxWindowsInclude.h>
#endif
#elif defined(__linux__)
#include <dlfcn.h>
#endif
class OmniPvdLoader
{
public:
OmniPvdLoader();
~OmniPvdLoader();
bool loadOmniPvd(const char *libFile);
void unloadOmniPvd();
void* mLibraryHandle;
createOmniPvdWriterFp mCreateOmniPvdWriter;
destroyOmniPvdWriterFp mDestroyOmniPvdWriter;
createOmniPvdReaderFp mCreateOmniPvdReader;
destroyOmniPvdReaderFp mDestroyOmniPvdReader;
createOmniPvdFileReadStreamFp mCreateOmniPvdFileReadStream;
destroyOmniPvdFileReadStreamFp mDestroyOmniPvdFileReadStream;
createOmniPvdFileWriteStreamFp mCreateOmniPvdFileWriteStream;
destroyOmniPvdFileWriteStreamFp mDestroyOmniPvdFileWriteStream;
createOmniPvdMemoryStreamFp mCreateOmniPvdMemoryStream;
destroyOmniPvdMemoryStreamFp mDestroyOmniPvdMemoryStream;
};
inline OmniPvdLoader::OmniPvdLoader()
{
mLibraryHandle = 0;
mCreateOmniPvdWriter = 0;
mDestroyOmniPvdWriter = 0;
mCreateOmniPvdReader = 0;
mDestroyOmniPvdReader = 0;
mCreateOmniPvdFileReadStream = 0;
mDestroyOmniPvdFileReadStream = 0;
mCreateOmniPvdFileWriteStream = 0;
mDestroyOmniPvdFileWriteStream = 0;
mCreateOmniPvdMemoryStream = 0;
mDestroyOmniPvdMemoryStream = 0;
}
inline OmniPvdLoader::~OmniPvdLoader()
{
unloadOmniPvd();
}
inline bool OmniPvdLoader::loadOmniPvd(const char *libFile)
{
#ifdef OMNI_PVD_WIN
mLibraryHandle = LoadLibraryA(libFile);
#elif defined(__linux__)
mLibraryHandle = dlopen(libFile, RTLD_NOW);
#endif
if (mLibraryHandle)
{
#ifdef OMNI_PVD_WIN
mCreateOmniPvdWriter = (createOmniPvdWriterFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdWriter");
mDestroyOmniPvdWriter = (destroyOmniPvdWriterFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdWriter");
mCreateOmniPvdReader = (createOmniPvdReaderFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdReader");
mDestroyOmniPvdReader = (destroyOmniPvdReaderFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdReader");
mCreateOmniPvdFileReadStream = (createOmniPvdFileReadStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdFileReadStream");
mDestroyOmniPvdFileReadStream = (destroyOmniPvdFileReadStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdFileReadStream");
mCreateOmniPvdFileWriteStream = (createOmniPvdFileWriteStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdFileWriteStream");
mDestroyOmniPvdFileWriteStream = (destroyOmniPvdFileWriteStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdFileWriteStream");
mCreateOmniPvdMemoryStream = (createOmniPvdMemoryStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdMemoryStream");
mDestroyOmniPvdMemoryStream = (destroyOmniPvdMemoryStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdMemoryStream");
#elif defined(__linux__)
mCreateOmniPvdWriter = (createOmniPvdWriterFp)dlsym(mLibraryHandle, "createOmniPvdWriter");
mDestroyOmniPvdWriter = (destroyOmniPvdWriterFp)dlsym(mLibraryHandle, "destroyOmniPvdWriter");
mCreateOmniPvdReader = (createOmniPvdReaderFp)dlsym(mLibraryHandle, "createOmniPvdReader");
mDestroyOmniPvdReader = (destroyOmniPvdReaderFp)dlsym(mLibraryHandle, "destroyOmniPvdReader");
mCreateOmniPvdFileReadStream = (createOmniPvdFileReadStreamFp)dlsym(mLibraryHandle, "createOmniPvdFileReadStream");
mDestroyOmniPvdFileReadStream = (destroyOmniPvdFileReadStreamFp)dlsym(mLibraryHandle, "destroyOmniPvdFileReadStream");
mCreateOmniPvdFileWriteStream = (createOmniPvdFileWriteStreamFp)dlsym(mLibraryHandle, "createOmniPvdFileWriteStream");
mDestroyOmniPvdFileWriteStream = (destroyOmniPvdFileWriteStreamFp)dlsym(mLibraryHandle, "destroyOmniPvdFileWriteStream");
mCreateOmniPvdMemoryStream = (createOmniPvdMemoryStreamFp)dlsym(mLibraryHandle, "createOmniPvdMemoryStream");
mDestroyOmniPvdMemoryStream = (destroyOmniPvdMemoryStreamFp)dlsym(mLibraryHandle, "destroyOmniPvdMemoryStream");
#endif
if ((!mCreateOmniPvdWriter) ||
(!mDestroyOmniPvdWriter) ||
(!mCreateOmniPvdReader) ||
(!mDestroyOmniPvdReader) ||
(!mCreateOmniPvdFileReadStream) ||
(!mDestroyOmniPvdFileReadStream) ||
(!mCreateOmniPvdFileWriteStream) ||
(!mDestroyOmniPvdFileWriteStream) ||
(!mCreateOmniPvdMemoryStream) ||
(!mDestroyOmniPvdMemoryStream)
)
{
#ifdef OMNI_PVD_WIN
FreeLibrary((HINSTANCE)mLibraryHandle);
#elif defined(__linux__)
dlclose(mLibraryHandle);
#endif
mLibraryHandle = 0;
return false;
}
}
else {
return false;
}
return true;
}
inline void OmniPvdLoader::unloadOmniPvd()
{
if (mLibraryHandle)
{
#ifdef OMNI_PVD_WIN
FreeLibrary((HINSTANCE)mLibraryHandle);
#elif defined(__linux__)
dlclose(mLibraryHandle);
#endif
mLibraryHandle = 0;
}
}
#endif
| 6,616 | C | 35.96648 | 143 | 0.797612 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdReader.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 OMNI_PVD_READER_H
#define OMNI_PVD_READER_H
#include "OmniPvdDefines.h"
#include "OmniPvdCommands.h"
#include "OmniPvdReadStream.h"
/**
* @brief Used to read debug information from an OmniPvdReadStream
*
* Using the getNextCommand function in a while loop for example one can traverse the stream one command after another. Given the command, different functions below will be available.
*
* Using the OmniPvdCommand::Enum one can determine the type of command and like that use the appropriate get functions to extract the payload from the command.
*/
class OmniPvdReader
{
public:
virtual ~OmniPvdReader()
{
}
/**
* @brief Sets the log function to print the internal debug messages of the OmniPVD Reader instance
*
* @param logFunction The function pointer to receive the log messages
*/
virtual void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction) = 0;
/**
* @brief Sets the read stream that contains the OmniPVD API command stream
*
* @param stream The OmniPvdReadStream that holds the stream of API calls/notifications
*/
virtual void OMNI_PVD_CALL setReadStream(OmniPvdReadStream& stream) = 0;
/**
* @brief Extracts the versions from the binary file to read and tests if the file is older or equal to that of the reader.
*
* @param majorVersion The major versions of the stream
* @param minorVersion The minor versions of the stream
* @param patch The patch number of the stream
* @return If the reading was possible to start or not
*/
virtual bool OMNI_PVD_CALL startReading(OmniPvdVersionType& majorVersion, OmniPvdVersionType& minorVersion, OmniPvdVersionType& patch) = 0;
/**
* @brief The heartbeat function of the reader class. As long as the command that is returned is not equal to OmniPvdCommand::eINVALID, then one can safely extract the data fields from the command.
*
* @return The command enum type
*/
virtual OmniPvdCommand::Enum OMNI_PVD_CALL getNextCommand() = 0;
/**
* @brief Returns the major version of the stream
*
* @return The major version
*/
virtual OmniPvdVersionType OMNI_PVD_CALL getMajorVersion() = 0;
/**
* @brief Returns the minor version of the stream
*
* @return The minor version
*/
virtual OmniPvdVersionType OMNI_PVD_CALL getMinorVersion() = 0;
/**
* @brief Returns the patch number of the stream
*
* @return The patch value
*/
virtual OmniPvdVersionType OMNI_PVD_CALL getPatch() = 0;
/**
* @brief Returns the context handle of the latest commmnd, if it had one, else 0
*
* @return The context handle of the latest command
*/
virtual OmniPvdContextHandle OMNI_PVD_CALL getContextHandle() = 0;
/**
* @brief Returns the object handle of the latest commmnd, if it had one, else 0
*
* @return The object handle of the latest command
*/
virtual OmniPvdObjectHandle OMNI_PVD_CALL getObjectHandle() = 0;
/**
* @brief Returns the class handle of the latest commmnd, if it had one, else 0
*
* @return The class handle of the latest command
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getClassHandle() = 0;
/**
* @brief Returns the base class handle of the latest commmnd, if it had one, else 0
*
* @return The base class handle of the latest command
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getBaseClassHandle() = 0;
/**
* @brief Returns the attribute handle of the latest commmnd, if it had one, else 0
*
* @return The attribute handle of the latest command
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL getAttributeHandle() = 0;
/**
* @brief Returns the class name of the latest commmnd, if it had one, else a null terminated string of length 0
*
* @return The string containing the class name
*/
virtual const char* OMNI_PVD_CALL getClassName() = 0;
/**
* @brief Returns the attribute name of the latest commmnd, if it had one, else a null terminated string of length 0
*
* @return The string containing the attribute name
*/
virtual const char* OMNI_PVD_CALL getAttributeName() = 0;
/**
* @brief Returns the object name of the latest commmnd, if it had one, else a null terminated string of length 0
*
* @return The string containing the object name
*/
virtual const char* OMNI_PVD_CALL getObjectName() = 0;
/**
* @brief Returns the attribute data pointer, the data is undefined if the last command did not contain attribute data
*
* @return The array containing the attribute data
*/
virtual const uint8_t* OMNI_PVD_CALL getAttributeDataPointer() = 0;
/**
* @brief Returns the attribute data type, the data is undefined if the last command did not contain attribute data
*
* @return The attribute data type
*/
virtual OmniPvdDataType::Enum OMNI_PVD_CALL getAttributeDataType() = 0;
/**
* @brief Returns the attribute data length, the data length of the last command
*
* @return The attribute data length
*/
virtual uint32_t OMNI_PVD_CALL getAttributeDataLength() = 0;
/**
* @brief Returns the number of elements contained in the last set operation
*
* @return The number of elements
*/
virtual uint32_t OMNI_PVD_CALL getAttributeNumberElements() = 0;
/**
* @brief Returns the numberclass handle of the attribute class
*
* @return The attibute class handle
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getAttributeClassHandle() = 0;
/**
* @brief Returns the frame start value
*
* @return The frame ID value
*/
virtual uint64_t OMNI_PVD_CALL getFrameTimeStart() = 0;
/**
* @brief Returns the frame stop value
*
* @return The frame ID value
*/
virtual uint64_t OMNI_PVD_CALL getFrameTimeStop() = 0;
/**
* @brief Returns the class handle containing the enum values
*
* @return The enum class handle
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getEnumClassHandle() = 0;
/**
* @brief Returns the enum value for a specific flag
*
* @return The enum value
*/
virtual OmniPvdEnumValueType OMNI_PVD_CALL getEnumValue() = 0;
};
#endif
| 7,683 | C | 33.303571 | 198 | 0.729793 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdWriter.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 OMNI_PVD_WRITER_H
#define OMNI_PVD_WRITER_H
#include "OmniPvdDefines.h"
#include "OmniPvdWriteStream.h"
/**
* @brief Used to write debug information to an OmniPvdWriteStream
*
* Allows the registration of OmniPVD classes and attributes, in a similar fashion to an object oriented language. A registration returns a unique identifier or handle.
*
* Once classes and attributes have been registered, one can create for example object instances of a class and set the values of the attributes of a specific object.
*
* Objects can be grouped by context using the context handle. The context handle is a user-specified handle which is passed to the set functions and object creation and destruction functions.
*
* Each context can have its own notion of time. The current time of a context can be exported with calls to the startFrame and stopFrame functions.
*/
class OmniPvdWriter
{
public:
virtual ~OmniPvdWriter()
{
}
/**
* @brief Sets the log function to print the internal debug messages of the OmniPVD API
*
* @param logFunction The function pointer to receive the log messages
*/
virtual void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction) = 0;
/**
* @brief Sets the write stream to receive the API command stream
*
* @param writeStream The OmniPvdWriteStream to receive the stream of API calls/notifications
*/
virtual void OMNI_PVD_CALL setWriteStream(OmniPvdWriteStream& writeStream) = 0;
/**
* @brief Gets the pointer to the write stream
*
* @return A pointer to the write stream
*/
virtual OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream() = 0;
/**
* @brief Registers an OmniPVD class
*
* Returns a unique handle to a class, which can be used to register class attributes and express object lifetimes with the createObject and destroyObject functions. Class inheritance can be described by calling registerClass with a base class handle. Derived classes inherit the attributes of the parent classes.
*
* @param className The class name
* @param baseClassHandle The handle to the base class. This handle is obtained by pre-registering the base class. Defaults to 0 which means the class has no parent class
* @return A unique class handle for the registered class
*
* @see OmniPvdWriter::registerAttribute()
* @see OmniPvdWriter::registerEnumValue()
* @see OmniPvdWriter::registerFlagsAttribute()
* @see OmniPvdWriter::registerClassAttribute()
* @see OmniPvdWriter::registerUniqueListAttribute()
* @see OmniPvdWriter::createObject()
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL registerClass(const char* className, OmniPvdClassHandle baseClassHandle = 0) = 0;
/**
* @brief Registers an enum name and corresponding value for a pre-registered class.
*
* Registering enums happens in two steps. First, registerClass() is called with the name of the enum. This returns a class handle, which is used in a second step for the enum value registration with registerEnumValue(). If an enum has multiple values, registerEnumValue() has to be called with the different values.
*
* Note that enums differ from usual classes because their attributes, the enum values, do not change over time and there is no need to call setAttribute().
*
* @param classHandle The handle from the registerClass() call
* @param attributeName The name of the enum value
* @param value The value of the enum value
* @return A unique attribute handle for the registered enum value
*
* @see OmniPvdWriter::registerClass()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerEnumValue(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdEnumValueType value) = 0;
/**
* @brief Registers an attribute.
*
* The class handle is obtained from a previous call to registerClass(). After registering an attribute, one gets an attribute handle which can be used to set data values of an attribute with setAttribute(). All attributes are treated as arrays, even if the attribute has only a single data item. Set nbElements to 0 to indicate that the array has a variable length.
*
* @param classHandle The handle from the registerClass() call
* @param attributeName The attribute name
* @param attributeDataType The attribute data type
* @param nbElements The number of elements in the array. Set this to 0 to indicate a variable length array
* @return A unique attribute handle for the registered attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::setAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType, uint32_t nbElements) = 0;
/**
* @brief Registers an attribute which is a flag.
*
* Use this function to indicate that a pre-registered class has a flag attribute, i.e., the attribute is a pre-registered enum.
*
* The returned attribute handle can be used in setAttribute() to set an object's flags.
*
* @param classHandle The handle from the registerClass() call of the class
* @param attributeName The attribute name
* @param enumClassHandle The handle from the registerClass() call of the enum
* @return A unique attribute handle for the registered flags attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::setAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerFlagsAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle enumClassHandle) = 0;
/**
* @brief Registers an attribute which is a class.
*
* Use this function to indicate that a pre-registered class has an attribute which is a pre-registered class.
*
* The returned attribute handle can be used in setAttribute() to set an object's class attribute.
*
* @param classHandle The handle from the registerClass() call of the class
* @param attributeName The attribute name
* @param classAttributeHandle The handle from the registerClass() call of the class attribute
* @return A unique handle for the registered class attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::setAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerClassAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle classAttributeHandle) = 0;
/**
* @brief Registers an attribute which can hold a list of unique items.
*
* The returned attribute handle can be used in calls to addToUniqueListAttribute() and removeFromUniqueListAttribute(), to add an item to and remove it from the list, respectively.
*
* @param classHandle The handle from the registerClass() call of the class
* @param attributeName The attribute name
* @param attributeDataType The data type of the items which will get added to the list attribute
* @return A unique handle for the registered list attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::addToUniqueListAttribute()
* @see OmniPvdWriter::removeFromUniqueListAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerUniqueListAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType) = 0;
/**
* @brief Sets an attribute value.
*
* Since an attribute can be part of a nested construct of class attributes, the method
* expects an array of attribute handles as input to uniquely identify the attribute.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandles The attribute handles containing all class attribute handles of a nested class
* construct. The last one has to be the handle from the registerUniqueListAttribute() call.
* @param nbAttributeHandles The number of attribute handles provided in attributeHandles
* @param data The pointer to the data of the element(s) to remove from the set
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerAttribute()
*/
virtual void OMNI_PVD_CALL setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t *data, uint32_t nbrBytes) = 0;
/**
* @brief Sets an attribute value.
*
* See other setAttribute method for details. This special version covers the case where the
* attribute is not part of a class attribute construct.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandle The handle from the registerAttribute() call
* @param data The pointer to the data
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerAttribute()
*/
inline void OMNI_PVD_CALL setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, OmniPvdAttributeHandle attributeHandle, const uint8_t *data, uint32_t nbrBytes)
{
setAttribute(contextHandle, objectHandle, &attributeHandle, 1, data, nbrBytes);
}
/**
* @brief Adds an item to a unique list attribute.
*
* A unique list attribute is defined like a set in mathematics, where each element must be unique.
*
* Since an attribute can be part of a nested construct of class attributes, the method
* expects an array of attribute handles as input to uniquely identify the attribute.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandles The attribute handles containing all class attribute handles of a nested class
* construct. The last one has to be the handle from the registerUniqueListAttribute() call.
* @param nbAttributeHandles The number of attribute handles provided in attributeHandles
* @param data The pointer to the data of the item to add to the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
virtual void OMNI_PVD_CALL addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes) = 0;
/**
* @brief Adds an item to a unique list attribute.
*
* See other addToUniqueListAttribute method for details. This special version covers the case where the
* attribute is not part of a class attribute construct.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandle The handle from the registerUniqueListAttribute() call
* @param data The pointer to the data of the item to add to the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
inline void OMNI_PVD_CALL addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, OmniPvdAttributeHandle attributeHandle, const uint8_t* data, uint32_t nbrBytes)
{
addToUniqueListAttribute(contextHandle, objectHandle, &attributeHandle, 1, data, nbrBytes);
}
/**
* @brief Removes an item from a uniqe list attribute
*
* A uniqe list attribute is defined like a set in mathematics, where each element must be unique.
*
* Since an attribute can be part of a nested construct of class attributes, the method
* expects an array of attribute handles as input to uniquely identify the attribute.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandles The attribute handles containing all class attribute handles of a nested class
* construct. The last one has to be the handle from the registerUniqueListAttribute() call.
* @param nbAttributeHandles The number of attribute handles provided in attributeHandles
* @param data The pointer to the data of the item to remove from the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
virtual void OMNI_PVD_CALL removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes) = 0;
/**
* @brief Removes an item from a uniqe list attribute
*
* See other removeFromUniqueListAttribute method for details. This special version covers the case where the
* attribute is not part of a class attribute construct.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandle The handle from the registerUniqueListAttribute() call
* @param data The pointer to the data of the item to remove from the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
inline void OMNI_PVD_CALL removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, OmniPvdAttributeHandle attributeHandle, const uint8_t* data, uint32_t nbrBytes)
{
removeFromUniqueListAttribute(contextHandle, objectHandle, &attributeHandle, 1, data, nbrBytes);
}
/**
* @brief Creates an object creation event
*
* Indicates that an object is created. One can freely choose a context handle for grouping objects.
*
* The class handle is obtained from a registerClass() call. The object handle should be unique, but as it's not tracked by the OmniPVD API, it's important this is set to a valid handle such as the object's physical memory address.
*
* The object name can be freely choosen or not set.
*
* Create about object destruction event by calling destroyObject().
*
* @param contextHandle The user-defined context handle for grouping objects
* @param classHandle The handle from the registerClass() call
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param objectName The user-defined name of the object. Can be the empty string
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::destroyObject()
*/
virtual void OMNI_PVD_CALL createObject(OmniPvdContextHandle contextHandle, OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName) = 0;
/**
* @brief Creates an object destruction event
*
* Use this to indicate that an object is destroyed. Use the same user-defined context and object handles as were used in the create object calls.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::createObject()
*/
virtual void OMNI_PVD_CALL destroyObject(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle) = 0;
/**
* @brief Creates a frame start event
*
* Time or frames are counted separatly per user-defined context.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param timeStamp The timestamp of the frame start event
*/
virtual void OMNI_PVD_CALL startFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp) = 0;
/**
* @brief Creates a stop frame event
*
* Time is counted separately per user-defined context.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param timeStamp The timestamp of the frame stop event
*/
virtual void OMNI_PVD_CALL stopFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp) = 0;
};
#endif
| 17,924 | C | 50.65706 | 367 | 0.767742 |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdDefines.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 OMNI_PVD_DEFINES_H
#define OMNI_PVD_DEFINES_H
#define OMNI_PVD_VERSION_MAJOR 0
#define OMNI_PVD_VERSION_MINOR 3
#define OMNI_PVD_VERSION_PATCH 0
////////////////////////////////////////////////////////////////////////////////
// Versions so far : (major, minor, patch), top one is newest
//
// [0, 3, 0]
// writes/read out the base class handle in the class registration call
// backwards compatible with [0, 2, 0] and [0, 1, 42]
// [0, 2, 0]
// intermediate version was never official, no real change, but there are many files with this version
// [0, 1, 42]
// no proper base class written/read in the class registration call
//
////////////////////////////////////////////////////////////////////////////////
#include <stdint.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#define OMNI_PVD_WIN
#define OMNI_PVD_CALL __cdecl
#define OMNI_PVD_EXPORT extern "C" __declspec(dllexport)
#else
#ifdef __cdecl__
#define OMNI_PVD_CALL __attribute__((__cdecl__))
#else
#define OMNI_PVD_CALL
#endif
#if __GNUC__ >= 4
#define OMNI_PVD_EXPORT extern "C" __attribute__((visibility("default")))
#else
#define OMNI_PVD_EXPORT extern "C"
#endif
#endif
typedef uint64_t OmniPvdObjectHandle;
typedef uint64_t OmniPvdContextHandle;
typedef uint32_t OmniPvdClassHandle;
typedef uint32_t OmniPvdAttributeHandle;
typedef uint32_t OmniPvdVersionType;
typedef uint32_t OmniPvdEnumValueType;
typedef void (OMNI_PVD_CALL *OmniPvdLogFunction)(char *logLine);
struct OmniPvdDataType
{
enum Enum
{
eINT8,
eINT16,
eINT32,
eINT64,
eUINT8,
eUINT16,
eUINT32,
eUINT64,
eFLOAT32,
eFLOAT64,
eSTRING,
eOBJECT_HANDLE,
eENUM_VALUE,
eFLAGS_WORD
};
};
template<uint32_t tType>
inline uint32_t getOmniPvdDataTypeSize() { return 0; }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT8>() { return sizeof(int8_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT16>() { return sizeof(int16_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT32>() { return sizeof(int32_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT64>() { return sizeof(int64_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT8>() { return sizeof(uint8_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT16>() { return sizeof(uint16_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT32>() { return sizeof(uint32_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT64>() { return sizeof(uint64_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT32>() { return sizeof(float); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT64>() { return sizeof(double); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eSTRING>() { return 0; }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eOBJECT_HANDLE>() { return sizeof(OmniPvdObjectHandle); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eENUM_VALUE>() { return sizeof(OmniPvdEnumValueType); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eFLAGS_WORD>() { return sizeof(OmniPvdClassHandle); }
#endif
| 5,026 | C | 33.909722 | 113 | 0.729009 |
NVIDIA-Omniverse/PhysX/physx/source/physxgpu/include/PxPhysXGpu.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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_PHYSX_GPU_H
#define PX_PHYSX_GPU_H
#include "task/PxTask.h"
#include "foundation/PxPinnedArray.h"
#include "common/PxPhysXCommonConfig.h"
#include "PxSceneDesc.h"
#include "cudamanager/PxCudaContextManager.h"
#include "PxSparseGridParams.h"
namespace physx
{
class PxFoundation;
class PxCudaContextManagerDesc;
class PxvNphaseImplementationContext;
class PxsContext;
class PxsKernelWranglerManager;
class PxvNphaseImplementationFallback;
struct PxgDynamicsMemoryConfig;
class PxsMemoryManager;
class PxsHeapMemoryAllocatorManager;
class PxsSimulationController;
class PxsSimulationControllerCallback;
class PxDelayLoadHook;
class PxParticleBuffer;
class PxParticleAndDiffuseBuffer;
class PxParticleClothBuffer;
class PxParticleRigidBuffer;
class PxIsosurfaceExtractor;
class PxSparseGridIsosurfaceExtractor;
struct PxIsosurfaceParams;
class PxAnisotropyGenerator;
class PxSmoothedPositionGenerator;
class PxParticleNeighborhoodProvider;
class PxPhysicsGpu;
struct PxvSimStats;
namespace Bp
{
class BroadPhase;
class AABBManagerBase;
class BoundsArray;
}
namespace Dy
{
class Context;
}
namespace IG
{
class IslandSim;
class SimpleIslandManager;
}
namespace Cm
{
class FlushPool;
}
/**
\brief Interface to create and run CUDA enabled PhysX features.
The methods of this interface are expected not to be called concurrently.
Also they are expected to not be called concurrently with any tasks spawned before the end pipeline ... TODO make clear.
*/
class PxPhysXGpu
{
protected:
virtual ~PxPhysXGpu() {}
PxPhysXGpu() {}
public:
/**
\brief Closes this instance of the interface.
*/
virtual void release() = 0;
virtual PxParticleBuffer* createParticleBuffer(PxU32 maxNumParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
virtual PxParticleClothBuffer* createParticleClothBuffer(PxU32 maxNumParticles, PxU32 maxVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
virtual PxParticleRigidBuffer* createParticleRigidBuffer(PxU32 maxNumParticles, PxU32 maxVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
virtual PxParticleAndDiffuseBuffer* createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
/**
Create GPU memory manager.
*/
virtual PxsMemoryManager* createGpuMemoryManager(PxCudaContextManager* cudaContextManager) = 0;
virtual PxsHeapMemoryAllocatorManager* createGpuHeapMemoryAllocatorManager(
const PxU32 heapCapacity,
PxsMemoryManager* memoryManager,
const PxU32 gpuComputeVersion) = 0;
/**
Create GPU kernel wrangler manager. If a kernel wrangler manager already exists, then that one will be returned.
The kernel wrangler manager should not be deleted. It will automatically be deleted when the PxPhysXGpu singleton gets released.
*/
virtual PxsKernelWranglerManager* getGpuKernelWranglerManager(
PxCudaContextManager* cudaContextManager) = 0;
/**
Create GPU broadphase.
*/
virtual Bp::BroadPhase* createGpuBroadPhase(
PxsKernelWranglerManager* gpuKernelWrangler,
PxCudaContextManager* cudaContextManager,
const PxU32 gpuComputeVersion,
const PxgDynamicsMemoryConfig& config,
PxsHeapMemoryAllocatorManager* heapMemoryManager, PxU64 contextID) = 0;
/**
Create GPU aabb manager.
*/
virtual Bp::AABBManagerBase* createGpuAABBManager(
PxsKernelWranglerManager* gpuKernelWrangler,
PxCudaContextManager* cudaContextManager,
const PxU32 gpuComputeVersion,
const PxgDynamicsMemoryConfig& config,
PxsHeapMemoryAllocatorManager* heapMemoryManager,
Bp::BroadPhase& bp,
Bp::BoundsArray& boundsArray,
PxFloatArrayPinned& contactDistance,
PxU32 maxNbAggregates, PxU32 maxNbShapes,
PxVirtualAllocator& allocator,
PxU64 contextID,
PxPairFilteringMode::Enum kineKineFilteringMode,
PxPairFilteringMode::Enum staticKineFilteringMode) = 0;
/**
Create GPU narrow phase context.
*/
virtual PxvNphaseImplementationContext* createGpuNphaseImplementationContext(PxsContext& context,
PxsKernelWranglerManager* gpuKernelWrangler,
PxvNphaseImplementationFallback* fallbackForUnsupportedCMs,
const PxgDynamicsMemoryConfig& gpuDynamicsConfig, void* contactStreamBase, void* patchStreamBase, void* forceAndIndiceStreamBase,
PxBoundsArrayPinned& bounds, IG::IslandSim* islandSim,
physx::Dy::Context* dynamicsContext, const PxU32 gpuComputeVersion, PxsHeapMemoryAllocatorManager* heapMemoryManager,
bool useGpuBP) = 0;
/**
Create GPU simulation controller.
*/
virtual PxsSimulationController* createGpuSimulationController(PxsKernelWranglerManager* gpuWranglerManagers,
PxCudaContextManager* cudaContextManager,
Dy::Context* dynamicContext, PxvNphaseImplementationContext* npContext, Bp::BroadPhase* bp,
const bool useGpuBroadphase, IG::SimpleIslandManager* simpleIslandSim,
PxsSimulationControllerCallback* callback, const PxU32 gpuComputeVersion, PxsHeapMemoryAllocatorManager* heapMemoryManager,
const PxU32 maxSoftBodyContacts, const PxU32 maxFemClothContacts, const PxU32 maxParticleContacts, const PxU32 maxHairContacts) = 0;
/**
Create GPU dynamics context.
*/
virtual Dy::Context* createGpuDynamicsContext(Cm::FlushPool& taskPool, PxsKernelWranglerManager* gpuKernelWragler,
PxCudaContextManager* cudaContextManager,
const PxgDynamicsMemoryConfig& config, IG::SimpleIslandManager* islandManager, const PxU32 maxNumPartitions, const PxU32 maxNumStaticPartitions,
const bool enableStabilization, const bool useEnhancedDeterminism, const PxReal maxBiasCoefficient,
const PxU32 gpuComputeVersion, PxvSimStats& simStats, PxsHeapMemoryAllocatorManager* heapMemoryManager,
const bool frictionEveryIteration, PxSolverType::Enum solverType, const PxReal lengthScale, bool enableDirectGPUAPI) = 0;
};
}
/**
Create PxPhysXGpu interface class.
*/
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxPhysXGpu* PX_CALL_CONV PxCreatePhysXGpu();
/**
Create a cuda context manager. Set launchSynchronous to true for Cuda to report the actual point of failure.
*/
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxCudaContextManager* PX_CALL_CONV PxCreateCudaContextManager(physx::PxFoundation& foundation, const physx::PxCudaContextManagerDesc& desc, physx::PxProfilerCallback* profilerCallback = NULL, bool launchSynchronous = false);
/**
Set profiler callback.
*/
PX_C_EXPORT PX_PHYSX_GPU_API void PX_CALL_CONV PxSetPhysXGpuProfilerCallback(physx::PxProfilerCallback* profilerCallback);
/**
Query the device ordinal - depends on control panel settings.
*/
PX_C_EXPORT PX_PHYSX_GPU_API int PX_CALL_CONV PxGetSuggestedCudaDeviceOrdinal(physx::PxErrorCallback& errc);
// Implementation of the corresponding functions from PxGpu.h/cpp in the GPU shared library
PX_C_EXPORT PX_PHYSX_GPU_API void PX_CALL_CONV PxGpuCudaRegisterFunction(int moduleIndex, const char* functionName);
PX_C_EXPORT PX_PHYSX_GPU_API void** PX_CALL_CONV PxGpuCudaRegisterFatBinary(void* fatBin);
#if PX_SUPPORT_GPU_PHYSX
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxKernelIndex* PX_CALL_CONV PxGpuGetCudaFunctionTable();
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxU32 PX_CALL_CONV PxGpuGetCudaFunctionTableSize();
PX_C_EXPORT PX_PHYSX_GPU_API void** PX_CALL_CONV PxGpuGetCudaModuleTable();
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxU32 PX_CALL_CONV PxGpuGetCudaModuleTableSize();
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxPhysicsGpu* PX_CALL_CONV PxGpuCreatePhysicsGpu();
#endif
#endif // PX_PHYSX_GPU_H
| 9,495 | C | 40.286956 | 284 | 0.807056 |
NVIDIA-Omniverse/PhysX/physx/source/immediatemode/src/NpImmediateMode.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 "PxImmediateMode.h"
#include "PxBroadPhase.h"
#include "../../lowleveldynamics/src/DyBodyCoreIntegrator.h"
#include "../../lowleveldynamics/src/DyContactPrep.h"
#include "../../lowleveldynamics/src/DyCorrelationBuffer.h"
#include "../../lowleveldynamics/src/DyConstraintPrep.h"
#include "../../lowleveldynamics/src/DySolverControl.h"
#include "../../lowleveldynamics/src/DySolverContext.h"
#include "../../lowlevel/common/include/collision/PxcContactMethodImpl.h"
#include "../../lowleveldynamics/src/DyTGSContactPrep.h"
#include "../../lowleveldynamics/src/DyTGS.h"
#include "../../lowleveldynamics/src/DyConstraintPartition.h"
#include "../../lowleveldynamics/src/DyArticulationCpuGpu.h"
#include "GuPersistentContactManifold.h"
#include "NpConstraint.h"
#include "common/PxProfileZone.h"
// PT: just for Dy::DY_ARTICULATION_MAX_SIZE
#include "../../lowleveldynamics/include/DyFeatherstoneArticulation.h"
#include "../../lowlevel/common/include/utils/PxcScratchAllocator.h"
using namespace physx;
using namespace Dy;
using namespace immediate;
void immediate::PxConstructSolverBodies(const PxRigidBodyData* inRigidData, PxSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity, PxReal dt, bool gyroscopicForces)
{
PX_ASSERT((size_t(inRigidData) & 0xf) == 0);
PX_ASSERT((size_t(outSolverBodyData) & 0xf) == 0);
for(PxU32 a=0; a<nbBodies; a++)
{
const PxRigidBodyData& rigidData = inRigidData[a];
PxVec3 lv = rigidData.linearVelocity, av = rigidData.angularVelocity;
Dy::bodyCoreComputeUnconstrainedVelocity(gravity, dt, rigidData.linearDamping, rigidData.angularDamping, 1.0f, rigidData.maxLinearVelocitySq, rigidData.maxAngularVelocitySq, lv, av, false);
Dy::copyToSolverBodyData(lv, av, rigidData.invMass, rigidData.invInertia, rigidData.body2World, -rigidData.maxDepenetrationVelocity, rigidData.maxContactImpulse,
PX_INVALID_NODE, PX_MAX_F32, outSolverBodyData[a], 0, dt, gyroscopicForces);
}
}
void immediate::PxConstructStaticSolverBody(const PxTransform& globalPose, PxSolverBodyData& solverBodyData)
{
PX_ASSERT((size_t(&solverBodyData) & 0xf) == 0);
const PxVec3 zero(0.0f);
Dy::copyToSolverBodyData(zero, zero, 0.0f, zero, globalPose, -PX_MAX_F32, PX_MAX_F32, PX_INVALID_NODE, PX_MAX_F32, solverBodyData, 0, 0.0f, false);
}
void immediate::PxIntegrateSolverBodies(PxSolverBodyData* solverBodyData, PxSolverBody* solverBody, const PxVec3* linearMotionVelocity, const PxVec3* angularMotionState, PxU32 nbBodiesToIntegrate, PxReal dt)
{
PX_ASSERT((size_t(solverBodyData) & 0xf) == 0);
PX_ASSERT((size_t(solverBody) & 0xf) == 0);
for(PxU32 i=0; i<nbBodiesToIntegrate; ++i)
{
PxVec3 lmv = linearMotionVelocity[i];
PxVec3 amv = angularMotionState[i];
Dy::integrateCore(lmv, amv, solverBody[i], solverBodyData[i], dt, 0);
}
}
namespace
{
// PT: local structure to provide a ctor for the PxArray below, I don't want to make it visible to the regular PhysX code
struct immArticulationJointCore : Dy::ArticulationJointCore
{
immArticulationJointCore() : Dy::ArticulationJointCore(PxTransform(PxIdentity), PxTransform(PxIdentity))
{
}
};
// PT: this class makes it possible to call the FeatherstoneArticulation protected functions from here.
class immArticulation : public FeatherstoneArticulation
{
public:
immArticulation(const PxArticulationDataRC& data);
~immArticulation();
PX_FORCE_INLINE void immSolveInternalConstraints(PxReal dt, PxReal invDt, Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV, PxReal elapsedTime, bool velocityIteration, bool isTGS)
{
// PT: TODO: revisit the TGS coeff (PX-4516)
FeatherstoneArticulation::solveInternalConstraints(dt, invDt, impulses, DeltaV, velocityIteration, isTGS, elapsedTime, isTGS ? 0.7f : DY_ARTICULATION_PGS_BIAS_COEFFICIENT);
}
PX_FORCE_INLINE void immComputeUnconstrainedVelocitiesTGS(PxReal dt, PxReal totalDt, PxReal invDt, PxReal /*invTotalDt*/, const PxVec3& gravity, PxReal invLengthScale)
{
mArticulationData.setDt(totalDt);
Cm::SpatialVectorF* Z = mTempZ.begin();
Cm::SpatialVectorF* deltaV = mTempDeltaV.begin();
FeatherstoneArticulation::computeUnconstrainedVelocitiesInternal(gravity, Z, deltaV, invLengthScale);
setupInternalConstraints(mArticulationData.getLinks(), mArticulationData.getLinkCount(),
mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE, mArticulationData, Z, dt, totalDt, invDt, true);
}
PX_FORCE_INLINE void immComputeUnconstrainedVelocities(PxReal dt, const PxVec3& gravity, PxReal invLengthScale)
{
mArticulationData.setDt(dt);
Cm::SpatialVectorF* Z = mTempZ.begin();
Cm::SpatialVectorF* deltaV = mTempDeltaV.begin();
FeatherstoneArticulation::computeUnconstrainedVelocitiesInternal(gravity, Z, deltaV, invLengthScale);
const PxReal invDt = 1.0f/dt;
setupInternalConstraints(mArticulationData.getLinks(), mArticulationData.getLinkCount(),
mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE, mArticulationData, Z, dt, dt, invDt, false);
}
void allocate(const PxU32 nbLinks);
PxU32 addLink(const PxU32 parent, const PxArticulationLinkDataRC& data);
void complete();
PxArray<Dy::ArticulationLink> mLinks;
PxArray<PxsBodyCore> mBodyCores;
PxArray<immArticulationJointCore> mArticulationJointCores;
PxArticulationFlags mFlags; // PT: PX-1399. Stored in Dy::ArticulationCore for retained mode.
// PT: quick and dirty version, to improve later
struct immArticulationLinkDataRC : PxArticulationLinkDataRC
{
PxArticulationLinkCookie parent;
PxU32 userID;
};
PxArray<immArticulationLinkDataRC> mTemp;
PxArray<Cm::SpatialVectorF> mTempDeltaV;
PxArray<Cm::SpatialVectorF> mTempZ;
bool mImmDirty;
bool mJCalcDirty;
private:
void initJointCore(Dy::ArticulationJointCore& core, const PxArticulationJointDataRC& inboundJoint);
};
class RigidBodyClassification : public RigidBodyClassificationBase
{
public:
RigidBodyClassification(PxU8* bodies, PxU32 bodyCount, PxU32 bodyStride) : RigidBodyClassificationBase(bodies, bodyCount, bodyStride)
{
}
PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxU32* numConstraintsPerPartition)
{
for (PxU32 a = 0; a < mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
for (PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b)
{
PxU32 partId = PxMin(PxU32(body.maxSolverNormalProgress + b), MAX_NUM_PARTITIONS);
numConstraintsPerPartition[partId]++;
}
}
}
PX_FORCE_INLINE void zeroBodies()
{
for(PxU32 a=0; a<mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
body.maxSolverFrictionProgress = 0;
body.maxSolverNormalProgress = 0;
}
}
PX_FORCE_INLINE void afterClassification() const
{
for(PxU32 a=0; a<mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
}
};
class ExtendedRigidBodyClassification : public ExtendedRigidBodyClassificationBase
{
public:
ExtendedRigidBodyClassification(PxU8* bodies, PxU32 numBodies, PxU32 stride, Dy::FeatherstoneArticulation** articulations, PxU32 numArticulations)
: ExtendedRigidBodyClassificationBase(bodies, numBodies, stride, articulations, numArticulations)
{
}
// PT: this version is slightly different from the SDK version, no mArticulationIndex!
//Returns true if it is a dynamic-dynamic constraint; false if it is a dynamic-static or dynamic-kinematic constraint
PX_FORCE_INLINE bool classifyConstraint(const PxSolverConstraintDesc& desc, uintptr_t& indexA, uintptr_t& indexB,
bool& activeA, bool& activeB, PxU32& bodyAProgress, PxU32& bodyBProgress) const
{
bool hasStatic = false;
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
{
indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mStride;
activeA = indexA < mBodyCount;
hasStatic = !activeA;//desc.bodyADataIndex == 0;
bodyAProgress = activeA ? desc.bodyA->solverProgress : 0;
}
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
indexA = mBodyCount;
//bodyAProgress = articulationA->getFsDataPtr()->solverProgress;
bodyAProgress = articulationA->solverProgress;
activeA = true;
}
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
{
indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mStride;
activeB = indexB < mBodyCount;
hasStatic = hasStatic || !activeB;
bodyBProgress = activeB ? desc.bodyB->solverProgress : 0;
}
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
indexB = mBodyCount;
activeB = true;
bodyBProgress = articulationB->solverProgress;
}
return !hasStatic;
}
PX_FORCE_INLINE void recordStaticConstraint(const PxSolverConstraintDesc& desc, bool& activeA, bool& activeB)
{
if (activeA)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
desc.bodyA->maxSolverFrictionProgress++;
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
articulationA->maxSolverFrictionProgress++;
}
}
if (activeB)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
desc.bodyB->maxSolverFrictionProgress++;
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
articulationB->maxSolverFrictionProgress++;
}
}
}
PX_FORCE_INLINE PxU32 getStaticContactWriteIndex(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const
{
if (activeA)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
{
return PxU32(desc.bodyA->maxSolverNormalProgress + desc.bodyA->maxSolverFrictionProgress++);
}
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
return PxU32(articulationA->maxSolverNormalProgress + articulationA->maxSolverFrictionProgress++);
}
}
else if (activeB)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
{
return PxU32(desc.bodyB->maxSolverNormalProgress + desc.bodyB->maxSolverFrictionProgress++);
}
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
return PxU32(articulationB->maxSolverNormalProgress + articulationB->maxSolverFrictionProgress++);
}
}
return 0xffffffff;
}
PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress, PxU16 availablePartition)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
{
desc.bodyA->solverProgress = bodyAProgress;
desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, availablePartition);
}
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
articulationA->solverProgress = bodyAProgress;
articulationA->maxSolverNormalProgress = PxMax(articulationA->maxSolverNormalProgress, availablePartition);
}
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
{
desc.bodyB->solverProgress = bodyBProgress;
desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, availablePartition);
}
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
articulationB->solverProgress = bodyBProgress;
articulationB->maxSolverNormalProgress = PxMax(articulationB->maxSolverNormalProgress, availablePartition);
}
}
PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxU32* numConstraintsPerPartition)
{
for (PxU32 a = 0; a < mBodySize; a += mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
for (PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b)
{
PxU32 partId = PxMin(PxU32(body.maxSolverNormalProgress + b), MAX_NUM_PARTITIONS);
numConstraintsPerPartition[partId]++;
}
}
for (PxU32 a = 0; a < mNumArticulations; ++a)
{
Dy::FeatherstoneArticulation* articulation = mArticulations[a];
articulation->solverProgress = 0;
for (PxU32 b = 0; b < articulation->maxSolverFrictionProgress; ++b)
{
PxU32 partId = PxMin(PxU32(articulation->maxSolverNormalProgress + b), MAX_NUM_PARTITIONS);
numConstraintsPerPartition[partId]++;
}
}
}
PX_FORCE_INLINE void zeroBodies()
{
for(PxU32 a=0; a<mBodySize; a += mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
body.maxSolverFrictionProgress = 0;
body.maxSolverNormalProgress = 0;
}
for(PxU32 a=0; a<mNumArticulations; ++a)
{
Dy::FeatherstoneArticulation* articulation = mArticulations[a];
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
articulation->maxSolverNormalProgress = 0;
}
}
PX_FORCE_INLINE void afterClassification() const
{
for(PxU32 a=0; a<mBodySize; a += mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
for(PxU32 a=0; a<mNumArticulations; ++a)
{
Dy::FeatherstoneArticulation* articulation = mArticulations[a];
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
}
}
};
template <typename Classification>
void classifyConstraintDesc(const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification,
PxU32* numConstraintsPerPartition)
{
const PxSolverConstraintDesc* _desc = descs;
const PxU32 numConstraintsMin1 = numConstraints - 1;
PxMemZero(numConstraintsPerPartition, sizeof(PxU32) * (MAX_NUM_PARTITIONS+1));
for(PxU32 i=0; i<numConstraints; ++i, _desc++)
{
const PxU32 prefetchOffset = PxMin(numConstraintsMin1 - i, 4u);
PxPrefetchLine(_desc[prefetchOffset].constraint);
PxPrefetchLine(_desc[prefetchOffset].bodyA);
PxPrefetchLine(_desc[prefetchOffset].bodyB);
PxPrefetchLine(_desc + 8);
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
const bool notContainsStatic = classification.classifyConstraint(*_desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB);
if(notContainsStatic)
{
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
{
//Write to overflow partition...
numConstraintsPerPartition[availablePartition]++;
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(MAX_NUM_PARTITIONS));
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
partitionsA |= partitionBit;
partitionsB |= partitionBit;
}
numConstraintsPerPartition[availablePartition]++;
availablePartition++;
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition));
}
else
{
//Just count the number of static constraints and store in maxSolverFrictionProgress...
classification.recordStaticConstraint(*_desc, activeA, activeB);
}
}
classification.reserveSpaceForStaticConstraints(numConstraintsPerPartition);
}
template <typename Classification>
void writeConstraintDesc( const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification,
PxU32* accumulatedConstraintsPerPartition, PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDesc)
{
const PxSolverConstraintDesc* _desc = descs;
const PxU32 numConstraintsMin1 = numConstraints - 1;
for(PxU32 i=0; i<numConstraints; ++i, _desc++)
{
const PxU32 prefetchOffset = PxMin(numConstraintsMin1 - i, 4u);
PxPrefetchLine(_desc[prefetchOffset].constraint);
PxPrefetchLine(_desc[prefetchOffset].bodyA);
PxPrefetchLine(_desc[prefetchOffset].bodyB);
PxPrefetchLine(_desc + 8);
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
const bool notContainsStatic = classification.classifyConstraint(*_desc, indexA, indexB, activeA, activeB,
partitionsA, partitionsB);
if (notContainsStatic)
{
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
{
eaOrderedConstraintDesc[accumulatedConstraintsPerPartition[availablePartition]++] = *_desc;
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
partitionsA |= partitionBit;
partitionsB |= partitionBit;
}
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition+1));
eaOrderedConstraintDesc[accumulatedConstraintsPerPartition[availablePartition]++] = *_desc;
}
else
{
//Just count the number of static constraints and store in maxSolverFrictionProgress...
//KS - TODO - handle registration of static contacts with articulations here!
PxU32 index = classification.getStaticContactWriteIndex(*_desc, activeA, activeB);
eaOrderedConstraintDesc[accumulatedConstraintsPerPartition[index]++] = *_desc;
}
}
}
template <typename Classification>
PxU32 BatchConstraints(const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxConstraintBatchHeader* outBatchHeaders,
PxSolverConstraintDesc* outOrderedConstraintDescs, Classification& classification)
{
if(!nbConstraints)
return 0;
PxU32 constraintsPerPartition[MAX_NUM_PARTITIONS + 1];
classification.zeroBodies();
classifyConstraintDesc(solverConstraintDescs, nbConstraints, classification, constraintsPerPartition);
PxU32 accumulation = 0;
for (PxU32 a = 0; a < MAX_NUM_PARTITIONS + 1; ++a)
{
PxU32 count = constraintsPerPartition[a];
constraintsPerPartition[a] = accumulation;
accumulation += count;
}
classification.afterClassification();
writeConstraintDesc(solverConstraintDescs, nbConstraints, classification, constraintsPerPartition, outOrderedConstraintDescs);
PxU32 numHeaders = 0;
PxU32 currentPartition = 0;
PxU32 maxJ = nbConstraints == 0 ? 0 : constraintsPerPartition[0];
const PxU32 maxBatchPartition = MAX_NUM_PARTITIONS;
for (PxU32 a = 0; a < nbConstraints;)
{
PxConstraintBatchHeader& header = outBatchHeaders[numHeaders++];
header.startIndex = a;
PxU32 loopMax = PxMin(maxJ - a, 4u);
PxU16 j = 0;
if (loopMax > 0)
{
j = 1;
PxSolverConstraintDesc& desc = outOrderedConstraintDescs[a];
if(isArticulationConstraint(desc))
loopMax = 1;
if (currentPartition < maxBatchPartition)
{
for (; j < loopMax && desc.constraintLengthOver16 == outOrderedConstraintDescs[a + j].constraintLengthOver16
&& !isArticulationConstraint(outOrderedConstraintDescs[a + j]); ++j);
}
header.stride = j;
header.constraintType = desc.constraintLengthOver16;
}
if (maxJ == (a + j) && maxJ != nbConstraints)
{
currentPartition++;
maxJ = constraintsPerPartition[currentPartition];
}
a += j;
}
return numHeaders;
}
}
PxU32 immediate::PxBatchConstraints(const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxSolverBody* solverBodies, PxU32 nbBodies,
PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs,
PxArticulationHandle* articulations, PxU32 nbArticulations)
{
PX_ASSERT((size_t(solverBodies) & 0xf) == 0);
if(!nbArticulations)
{
RigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxSolverBody));
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
else
{
ExtendedRigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxSolverBody), reinterpret_cast<Dy::FeatherstoneArticulation**>(articulations), nbArticulations);
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
}
bool immediate::PxCreateContactConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverContactDesc* contactDescs,
PxConstraintAllocator& allocator, PxReal invDt, PxReal bounceThreshold, PxReal frictionOffsetThreshold,
PxReal correlationDistance, PxSpatialVector* ZV)
{
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
PX_ASSERT(bounceThreshold < 0.0f);
PX_ASSERT(frictionOffsetThreshold > 0.0f);
PX_ASSERT(correlationDistance > 0.0f);
Dy::CorrelationBuffer cb;
PxU32 currentContactDescIdx = 0;
const PxReal dt = 1.0f / invDt;
for(PxU32 i=0; i<nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
if (batchHeader.stride == 4)
{
PxU32 totalContacts = contactDescs[currentContactDescIdx].numContacts + contactDescs[currentContactDescIdx + 1].numContacts +
contactDescs[currentContactDescIdx + 2].numContacts + contactDescs[currentContactDescIdx + 3].numContacts;
if (totalContacts <= 64)
{
state = Dy::createFinalizeSolverContacts4(cb,
contactDescs + currentContactDescIdx,
invDt,
dt,
bounceThreshold,
frictionOffsetThreshold,
correlationDistance,
allocator);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(ZV);
for(PxU32 a=0; a<batchHeader.stride; ++a)
{
Dy::createFinalizeSolverContacts(contactDescs[currentContactDescIdx + a], cb, invDt, dt, bounceThreshold,
frictionOffsetThreshold, correlationDistance, allocator, Z);
}
}
if(contactDescs[currentContactDescIdx].desc->constraint)
{
PxU8 type = *contactDescs[currentContactDescIdx].desc->constraint;
if(type == DY_SC_TYPE_STATIC_CONTACT)
{
//Check if any block of constraints is classified as type static (single) contact constraint.
//If they are, iterate over all constraints grouped with it and switch to "dynamic" contact constraint
//type if there's a dynamic contact constraint in the group.
for(PxU32 c=1; c<batchHeader.stride; ++c)
{
if (*contactDescs[currentContactDescIdx + c].desc->constraint == DY_SC_TYPE_RB_CONTACT)
{
type = DY_SC_TYPE_RB_CONTACT;
break;
}
}
}
batchHeader.constraintType = type;
}
currentContactDescIdx += batchHeader.stride;
}
return true;
}
bool immediate::PxCreateJointConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxSpatialVector* ZV, PxReal dt, PxReal invDt)
{
PX_ASSERT(dt > 0.0f);
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
PxU32 currentDescIdx = 0;
for(PxU32 i=0; i<nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
PxU8 type = DY_SC_TYPE_BLOCK_1D;
if (batchHeader.stride == 4)
{
PxU32 totalRows = 0;
PxU32 maxRows = 0;
bool batchable = true;
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
if (jointDescs[currentDescIdx + a].numRows == 0)
{
batchable = false;
break;
}
totalRows += jointDescs[currentDescIdx + a].numRows;
maxRows = PxMax(maxRows, jointDescs[currentDescIdx + a].numRows);
}
if (batchable)
{
state = Dy::setupSolverConstraint4
(jointDescs + currentDescIdx,
dt, invDt, totalRows,
allocator, maxRows);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
type = DY_SC_TYPE_RB_1D;
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(ZV);
for(PxU32 a=0; a<batchHeader.stride; ++a)
{
// PT: TODO: And "isExtended" is already computed in Dy::ConstraintHelper::setupSolverConstraint
PxSolverConstraintDesc& desc = *jointDescs[currentDescIdx + a].desc;
const bool isExtended = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY;
if(isExtended)
type = DY_SC_TYPE_EXT_1D;
Dy::ConstraintHelper::setupSolverConstraint(jointDescs[currentDescIdx + a], allocator, dt, invDt, Z);
}
}
batchHeader.constraintType = type;
currentDescIdx += batchHeader.stride;
}
return true;
}
template<class LeafTestT, class ParamsT>
static bool PxCreateJointConstraintsWithShadersT(PxConstraintBatchHeader* batchHeaders, const PxU32 nbHeaders, ParamsT* params, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxSpatialVector* Z, PxReal dt, PxReal invDt)
{
Px1DConstraint allRows[Dy::MAX_CONSTRAINT_ROWS * 4];
//Runs shaders to fill in rows...
PxU32 currentDescIdx = 0;
for(PxU32 i=0; i<nbHeaders; i++)
{
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
for(PxU32 a=0; a<batchHeader.stride; a++)
{
PxSolverConstraintPrepDesc& desc = jointDescs[currentDescIdx + a];
PxConstraintSolverPrep prep;
const void* constantBlock;
const bool useExtendedLimits = LeafTestT::getData(params, currentDescIdx + a, &prep, &constantBlock);
PX_ASSERT(prep);
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
PxVec3p unused_cA2w, unused_cB2w;
//TAG:solverprepcall
const PxU32 constraintCount = prep(rows,
desc.body0WorldOffset,
Dy::MAX_CONSTRAINT_ROWS,
desc.invMassScales,
constantBlock,
desc.bodyFrame0, desc.bodyFrame1,
useExtendedLimits,
unused_cA2w, unused_cB2w);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
}
PxCreateJointConstraints(&batchHeader, 1, jointDescs + currentDescIdx, allocator, Z, dt, invDt);
currentDescIdx += batchHeader.stride;
}
return true; //KS - TODO - do some error reporting/management...
}
namespace
{
class PxConstraintAdapter
{
public:
static PX_FORCE_INLINE bool getData(PxConstraint** constraints, PxU32 i, PxConstraintSolverPrep* prep, const void** constantBlock)
{
NpConstraint* npConstraint = static_cast<NpConstraint*>(constraints[i]);
const Sc::ConstraintCore& core = npConstraint->getCore();
if (npConstraint->isDirty())
{
core.getPxConnector()->prepareData();
npConstraint->markClean();
}
*prep = core.getPxConnector()->getPrep();
*constantBlock = core.getPxConnector()->getConstantBlock();
return core.getFlags() & PxConstraintFlag::eENABLE_EXTENDED_LIMITS;
}
};
}
bool immediate::PxCreateJointConstraintsWithShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxConstraint** constraints, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z)
{
return PxCreateJointConstraintsWithShadersT<PxConstraintAdapter>(batchHeaders, nbHeaders, constraints, jointDescs, allocator, Z, dt, invDt);
}
bool immediate::PxCreateJointConstraintsWithImmediateShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxImmediateConstraint* constraints, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z)
{
class immConstraintAdapter
{
public:
static PX_FORCE_INLINE bool getData(PxImmediateConstraint* constraints_, PxU32 i, PxConstraintSolverPrep* prep, const void** constantBlock)
{
const PxImmediateConstraint& ic = constraints_[i];
*prep = ic.prep;
*constantBlock = ic.constantBlock;
return false;
}
};
return PxCreateJointConstraintsWithShadersT<immConstraintAdapter>(batchHeaders, nbHeaders, constraints, jointDescs, allocator, Z, dt, invDt);
}
/*static*/ PX_FORCE_INLINE bool PxIsZero(const PxSolverBody* bodies, PxU32 nbBodies)
{
for(PxU32 i=0; i<nbBodies; i++)
{
if( !bodies[i].linearVelocity.isZero() ||
!bodies[i].angularState.isZero())
return false;
}
return true;
}
void immediate::PxSolveConstraints(const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs,
const PxSolverBody* solverBodies, PxVec3* linearMotionVelocity, PxVec3* angularMotionVelocity, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations,
float dt, float invDt, PxU32 nbSolverArticulations, PxArticulationHandle* solverArticulations, PxSpatialVector* pxZ, PxSpatialVector* pxDeltaV)
{
PX_ASSERT(nbPositionIterations > 0);
PX_ASSERT(nbVelocityIterations > 0);
PX_ASSERT(PxIsZero(solverBodies, nbSolverBodies)); //Ensure that solver body velocities have been zeroed before solving
PX_ASSERT((size_t(solverBodies) & 0xf) == 0);
const Dy::SolveBlockMethod* solveTable = Dy::getSolveBlockTable();
const Dy::SolveBlockMethod* solveConcludeTable = Dy::getSolverConcludeBlockTable();
const Dy::SolveWriteBackBlockMethod* solveWritebackTable = Dy::getSolveWritebackBlockTable();
Dy::SolverContext cache;
cache.mThresholdStreamIndex = 0;
cache.mThresholdStreamLength = 0xFFFFFFF;
PX_ASSERT(nbPositionIterations > 0);
PX_ASSERT(nbVelocityIterations > 0);
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(pxZ);
Cm::SpatialVectorF* deltaV = reinterpret_cast<Cm::SpatialVectorF*>(pxDeltaV);
cache.Z = Z;
cache.deltaV = deltaV;
Dy::FeatherstoneArticulation** articulations = reinterpret_cast<Dy::FeatherstoneArticulation**>(solverArticulations);
struct PGS
{
static PX_FORCE_INLINE void solveArticulationInternalConstraints(float dt_, float invDt_, PxU32 nbSolverArticulations_, Dy::FeatherstoneArticulation** solverArticulations_, Cm::SpatialVectorF* Z_, Cm::SpatialVectorF* deltaV_, bool velIter_)
{
while(nbSolverArticulations_--)
{
immArticulation* immArt = static_cast<immArticulation*>(*solverArticulations_++);
immArt->immSolveInternalConstraints(dt_, invDt_, Z_, deltaV_, 0.0f, velIter_, false);
}
}
static PX_FORCE_INLINE void runIter(const PxConstraintBatchHeader* batchHeaders_, PxU32 nbBatchHeaders_, const PxSolverConstraintDesc* solverConstraintDescs_,
PxU32 nbSolverArticulations_, Dy::FeatherstoneArticulation** articulations_, Cm::SpatialVectorF* Z_, Cm::SpatialVectorF* deltaV_,
const Dy::SolveBlockMethod* solveTable_, Dy::SolverContext& solverCache_, float dt_, float invDt_, bool doFriction, bool velIter_)
{
solverCache_.doFriction = doFriction;
for(PxU32 a=0; a<nbBatchHeaders_; ++a)
{
const PxConstraintBatchHeader& batch = batchHeaders_[a];
solveTable_[batch.constraintType](solverConstraintDescs_ + batch.startIndex, batch.stride, solverCache_);
}
solveArticulationInternalConstraints(dt_, invDt_, nbSolverArticulations_, articulations_, Z_, deltaV_, velIter_);
}
};
for(PxU32 i=nbPositionIterations; i>1; --i)
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveTable, cache, dt, invDt, i <= 3, false);
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveConcludeTable, cache, dt, invDt, true, false);
//Save motion velocities...
for(PxU32 a=0; a<nbSolverBodies; a++)
{
linearMotionVelocity[a] = solverBodies[a].linearVelocity;
angularMotionVelocity[a] = solverBodies[a].angularState;
}
for(PxU32 a=0; a<nbSolverArticulations; a++)
FeatherstoneArticulation::saveVelocity(reinterpret_cast<Dy::FeatherstoneArticulation*>(solverArticulations[a]), deltaV);
for(PxU32 i=nbVelocityIterations; i>1; --i)
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveTable, cache, dt, invDt, true, true);
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveWritebackTable, cache, dt, invDt, true, true);
}
static void createCache(Gu::Cache& cache, PxGeometryType::Enum geomType0, PxGeometryType::Enum geomType1, PxCacheAllocator& allocator)
{
if(gEnablePCMCaching[geomType0][geomType1])
{
if(geomType0 <= PxGeometryType::eCONVEXMESH && geomType1 <= PxGeometryType::eCONVEXMESH)
{
if(geomType0 == PxGeometryType::eSPHERE || geomType1 == PxGeometryType::eSPHERE)
{
Gu::PersistentContactManifold* manifold = PX_PLACEMENT_NEW(allocator.allocateCacheData(sizeof(Gu::SpherePersistentContactManifold)), Gu::SpherePersistentContactManifold)();
cache.setManifold(manifold);
}
else
{
Gu::PersistentContactManifold* manifold = PX_PLACEMENT_NEW(allocator.allocateCacheData(sizeof(Gu::LargePersistentContactManifold)), Gu::LargePersistentContactManifold)();
cache.setManifold(manifold);
}
cache.getManifold().clearManifold();
}
else
{
//ML: raised 1 to indicate the manifold is multiManifold which is for contact gen in mesh/height field
//cache.manifold = 1;
cache.setMultiManifold(NULL);
}
}
else
{
//cache.manifold = 0;
cache.mCachedData = NULL;
cache.mManifoldFlags = 0;
}
}
bool immediate::PxGenerateContacts( const PxGeometry* const * geom0, const PxGeometry* const * geom1, const PxTransform* pose0, const PxTransform* pose1, PxCache* contactCache, PxU32 nbPairs,
PxContactRecorder& contactRecorder, PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength, PxCacheAllocator& allocator)
{
PX_ASSERT(meshContactMargin > 0.0f);
PX_ASSERT(toleranceLength > 0.0f);
PX_ASSERT(contactDistance > 0.0f);
PxContactBuffer contactBuffer;
PxTransform32 transform0;
PxTransform32 transform1;
for (PxU32 i = 0; i < nbPairs; ++i)
{
contactBuffer.count = 0;
PxGeometryType::Enum type0 = geom0[i]->getType();
PxGeometryType::Enum type1 = geom1[i]->getType();
const PxGeometry* tempGeom0 = geom0[i];
const PxGeometry* tempGeom1 = geom1[i];
const bool bSwap = type0 > type1;
if (bSwap)
{
PxSwap(tempGeom0, tempGeom1);
PxSwap(type0, type1);
transform1 = pose0[i];
transform0 = pose1[i];
}
else
{
transform0 = pose0[i];
transform1 = pose1[i];
}
//Now work out which type of PCM we need...
Gu::Cache& cache = static_cast<Gu::Cache&>(contactCache[i]);
bool needsMultiManifold = type1 > PxGeometryType::eCONVEXMESH;
Gu::NarrowPhaseParams params(contactDistance, meshContactMargin, toleranceLength);
if (needsMultiManifold)
{
Gu::MultiplePersistentContactManifold multiManifold;
if (cache.isMultiManifold())
{
multiManifold.fromBuffer(reinterpret_cast<PxU8*>(&cache.getMultipleManifold()));
}
else
{
multiManifold.initialize();
}
cache.setMultiManifold(&multiManifold);
//Do collision detection, then write manifold out...
g_PCMContactMethodTable[type0][type1](*tempGeom0, *tempGeom1, transform0, transform1, params, cache, contactBuffer, NULL);
const PxU32 size = (sizeof(Gu::MultiPersistentManifoldHeader) +
multiManifold.mNumManifolds * sizeof(Gu::SingleManifoldHeader) +
multiManifold.mNumTotalContacts * sizeof(Gu::CachedMeshPersistentContact));
PxU8* buffer = allocator.allocateCacheData(size);
multiManifold.toBuffer(buffer);
cache.setMultiManifold(buffer);
}
else
{
//Allocate the type of manifold we need again...
Gu::PersistentContactManifold* oldManifold = NULL;
if (cache.isManifold())
oldManifold = &cache.getManifold();
//Allocates and creates the PCM...
createCache(cache, type0, type1, allocator);
//Copy PCM from old to new manifold...
if (oldManifold)
{
Gu::PersistentContactManifold& manifold = cache.getManifold();
manifold.mRelativeTransform = oldManifold->mRelativeTransform;
manifold.mQuatA = oldManifold->mQuatA;
manifold.mQuatB = oldManifold->mQuatB;
manifold.mNumContacts = oldManifold->mNumContacts;
manifold.mNumWarmStartPoints = oldManifold->mNumWarmStartPoints;
manifold.mAIndice[0] = oldManifold->mAIndice[0]; manifold.mAIndice[1] = oldManifold->mAIndice[1];
manifold.mAIndice[2] = oldManifold->mAIndice[2]; manifold.mAIndice[3] = oldManifold->mAIndice[3];
manifold.mBIndice[0] = oldManifold->mBIndice[0]; manifold.mBIndice[1] = oldManifold->mBIndice[1];
manifold.mBIndice[2] = oldManifold->mBIndice[2]; manifold.mBIndice[3] = oldManifold->mBIndice[3];
PxMemCopy(manifold.mContactPoints, oldManifold->mContactPoints, sizeof(Gu::PersistentContact)*manifold.mNumContacts);
}
g_PCMContactMethodTable[type0][type1](*tempGeom0, *tempGeom1, transform0, transform1, params, cache, contactBuffer, NULL);
}
if (bSwap)
{
for (PxU32 a = 0; a < contactBuffer.count; ++a)
{
contactBuffer.contacts[a].normal = -contactBuffer.contacts[a].normal;
}
}
if (contactBuffer.count != 0)
{
//Record this contact pair...
contactRecorder.recordContacts(contactBuffer.contacts, contactBuffer.count, i);
}
}
return true;
}
immArticulation::immArticulation(const PxArticulationDataRC& data) :
FeatherstoneArticulation(this),
mFlags (data.flags),
mImmDirty (true),
mJCalcDirty (true)
{
// PT: TODO: we only need the flags here, maybe drop the solver desc?
getSolverDesc().initData(NULL, &mFlags);
}
immArticulation::~immArticulation()
{
}
void immArticulation::initJointCore(Dy::ArticulationJointCore& core, const PxArticulationJointDataRC& inboundJoint)
{
core.init(inboundJoint.parentPose, inboundJoint.childPose);
core.jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eMOTION | Dy::ArticulationJointCoreDirtyFlag::eFRAME;
const PxU32* binP = reinterpret_cast<const PxU32*>(inboundJoint.targetPos);
const PxU32* binV = reinterpret_cast<const PxU32*>(inboundJoint.targetVel);
for(PxU32 i=0; i<PxArticulationAxis::eCOUNT; i++)
{
core.initLimit(PxArticulationAxis::Enum(i), inboundJoint.limits[i]);
core.initDrive(PxArticulationAxis::Enum(i), inboundJoint.drives[i]);
// See Sc::ArticulationJointCore::setTargetP and Sc::ArticulationJointCore::setTargetV
if(binP[i]!=0xffffffff)
{
core.targetP[i] = inboundJoint.targetPos[i];
core.jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eTARGETPOSE;
}
if(binV[i]!=0xffffffff)
{
core.targetV[i] = inboundJoint.targetVel[i];
core.jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eTARGETVELOCITY;
}
core.armature[i] = inboundJoint.armature[i];
core.jointPos[i] = inboundJoint.jointPos[i];
core.jointVel[i] = inboundJoint.jointVel[i];
core.motion[i] = PxU8(inboundJoint.motion[i]);
}
core.initFrictionCoefficient(inboundJoint.frictionCoefficient);
core.initMaxJointVelocity(inboundJoint.maxJointVelocity);
core.initJointType(inboundJoint.type);
}
void immArticulation::allocate(const PxU32 nbLinks)
{
mLinks.reserve(nbLinks);
mBodyCores.resize(nbLinks);
mArticulationJointCores.resize(nbLinks);
}
PxU32 immArticulation::addLink(const PxU32 parentIndex, const PxArticulationLinkDataRC& data)
{
PX_ASSERT(data.pose.p.isFinite());
PX_ASSERT(data.pose.q.isFinite());
mImmDirty = true;
mJCalcDirty = true;
// Replicate ArticulationSim::addBody
addBody();
const PxU32 index = mLinks.size();
const PxTransform& bodyPose = data.pose;
//
PxsBodyCore* bodyCore = &mBodyCores[index];
{
// PT: this function inits everything but we only need a fraction of the data there for articulations
bodyCore->init( bodyPose, data.inverseInertia, data.inverseMass, 0.0f, 0.0f,
data.linearDamping, data.angularDamping,
data.maxLinearVelocitySq, data.maxAngularVelocitySq, PxActorType::eARTICULATION_LINK);
// PT: TODO: consider exposing all used data to immediate mode API (PX-1398)
// bodyCore->maxPenBias = -1e32f; // <= this one is related to setMaxDepenetrationVelocity
// bodyCore->linearVelocity = PxVec3(0.0f);
// bodyCore->angularVelocity = PxVec3(0.0f);
// bodyCore->linearVelocity = PxVec3(0.0f, 10.0f, 0.0f);
// bodyCore->angularVelocity = PxVec3(0.0f, 10.0f, 0.0f);
bodyCore->cfmScale = data.cfmScale;
}
/* PX_ASSERT((((index==0) && (joint == 0)) && (parent == 0)) ||
(((index!=0) && joint) && (parent && (parent->getArticulation() == this))));*/
// PT: TODO: add ctors everywhere
ArticulationLink& link = mLinks.insert();
// void BodySim::postActorFlagChange(PxU32 oldFlags, PxU32 newFlags)
bodyCore->disableGravity = data.disableGravity;
link.bodyCore = bodyCore;
link.children = 0;
link.mPathToRootStartIndex = 0;
link.mPathToRootCount = 0;
link.mChildrenStartIndex = 0xffffffff;
link.mNumChildren = 0;
const bool isRoot = parentIndex==0xffffffff;
if(!isRoot)
{
link.parent = parentIndex;
//link.pathToRoot = mLinks[parentIndex].pathToRoot | ArticulationBitField(1)<<index;
link.inboundJoint = &mArticulationJointCores[index];
ArticulationLink& parentLink = mLinks[parentIndex];
parentLink.children |= ArticulationBitField(1)<<index;
if(parentLink.mChildrenStartIndex == 0xffffffff)
parentLink.mChildrenStartIndex = index;
parentLink.mNumChildren++;
initJointCore(*link.inboundJoint, data.inboundJoint);
}
else
{
link.parent = DY_ARTICULATION_LINK_NONE;
//link.pathToRoot = 1;
link.inboundJoint = NULL;
}
return index;
}
void immArticulation::complete()
{
// Based on Sc::ArticulationSim::checkResize()
if(!mImmDirty)
return;
mImmDirty = false;
const PxU32 linkSize = mLinks.size();
setupLinks(linkSize, const_cast<ArticulationLink*>(mLinks.begin()));
jcalc<true>(mArticulationData);
mJCalcDirty = false;
initPathToRoot();
mTempDeltaV.resize(linkSize);
mTempZ.resize(linkSize);
}
PxArticulationCookie immediate::PxBeginCreateArticulationRC(const PxArticulationDataRC& data)
{
// PT: we create the same class as before under the hood, we just don't tell users yet. Returning a void pointer/cookie
// means we can prevent them from using the articulation before it's fully completed. We do this because we're going to
// delay the link creation, so we don't want them to call PxAddArticulationLink and expect the link to be here already.
void* memory = PxAlignedAllocator<64>().allocate(sizeof(immArticulation), PX_FL);
PX_PLACEMENT_NEW(memory, immArticulation(data));
return memory;
}
PxArticulationLinkCookie immediate::PxAddArticulationLink(PxArticulationCookie articulation, const PxArticulationLinkCookie* parent, const PxArticulationLinkDataRC& data)
{
if(!articulation)
return PxCreateArticulationLinkCookie();
immArticulation* immArt = reinterpret_cast<immArticulation*>(articulation);
const PxU32 id = immArt->mTemp.size();
// PT: TODO: this is the quick-and-dirty version, we could try something smarter where we don't just batch everything like barbarians
immArticulation::immArticulationLinkDataRC tmp;
static_cast<PxArticulationLinkDataRC&>(tmp) = data;
tmp.userID = id;
tmp.parent = parent ? *parent : PxCreateArticulationLinkCookie();
immArt->mTemp.pushBack(tmp);
// WARNING: cannot be null, snippet uses null for regular rigid bodies (non articulation links)
return PxCreateArticulationLinkCookie(articulation, id);
}
PxArticulationHandle immediate::PxEndCreateArticulationRC(PxArticulationCookie articulation, PxArticulationLinkHandle* handles, PxU32 bufferSize)
{
if(!articulation)
return NULL;
immArticulation* immArt = reinterpret_cast<immArticulation*>(articulation);
PxU32 nbLinks = immArt->mTemp.size();
if(nbLinks!=bufferSize)
return NULL;
immArticulation::immArticulationLinkDataRC* linkData = immArt->mTemp.begin();
{
struct _{ bool operator()(const immArticulation::immArticulationLinkDataRC& data1, const immArticulation::immArticulationLinkDataRC& data2) const
{
if(!data1.parent.articulation)
return true;
if(!data2.parent.articulation)
return false;
return data1.parent.linkId < data2.parent.linkId;
}};
PxSort(linkData, nbLinks, _());
}
PxMemSet(handles, 0, sizeof(PxArticulationLinkHandle)*nbLinks);
immArt->allocate(nbLinks);
while(nbLinks--)
{
const PxU32 userID = linkData->userID;
PxU32 parentID = linkData->parent.linkId;
if(parentID != 0xffffffff)
parentID = handles[parentID].linkId;
const PxU32 realID = immArt->addLink(parentID, *linkData);
handles[userID] = PxArticulationLinkHandle(immArt, realID);
linkData++;
}
immArt->complete();
return immArt;
}
void immediate::PxReleaseArticulation(PxArticulationHandle articulation)
{
if(!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->~immArticulation();
PxAlignedAllocator<64>().deallocate(articulation);
}
PxArticulationCache* immediate::PxCreateArticulationCache(PxArticulationHandle articulation)
{
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->complete();
return FeatherstoneArticulation::createCache(immArt->getDofs(), immArt->getBodyCount(), 0);
}
void immediate::PxCopyInternalStateToArticulationCache(PxArticulationHandle articulation, PxArticulationCache& cache, PxArticulationCacheFlags flag)
{
immArticulation* immArt = static_cast<immArticulation *>(articulation);
immArt->copyInternalStateToCache(cache, flag, false);
}
void immediate::PxApplyArticulationCache(PxArticulationHandle articulation, PxArticulationCache& cache, PxArticulationCacheFlags flag)
{
bool shouldWake = false;
immArticulation* immArt = static_cast<immArticulation *>(articulation);
immArt->applyCache(cache, flag, shouldWake);
}
void immediate::PxReleaseArticulationCache(PxArticulationCache& cache)
{
PxcScratchAllocator* scratchAlloc = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
PX_DELETE(scratchAlloc);
cache.scratchAllocator = NULL;
PX_FREE(cache.scratchMemory);
PxArticulationCache* ptr = &cache;
PX_FREE(ptr);
}
void immediate::PxComputeUnconstrainedVelocities(PxArticulationHandle articulation, const PxVec3& gravity, PxReal dt, PxReal invLengthScale)
{
if(!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->complete();
if(immArt->mJCalcDirty)
{
immArt->mJCalcDirty = false;
immArt->jcalc<true>(immArt->mArticulationData);
}
immArt->immComputeUnconstrainedVelocities(dt, gravity, invLengthScale);
}
void immediate::PxUpdateArticulationBodies(PxArticulationHandle articulation, PxReal dt)
{
if(!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
FeatherstoneArticulation::updateBodies(immArt, immArt->mTempDeltaV.begin(), dt, true);
}
void immediate::PxComputeUnconstrainedVelocitiesTGS(PxArticulationHandle articulation, const PxVec3& gravity, PxReal dt,
PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal invLengthScale)
{
if (!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->complete();
if(immArt->mJCalcDirty)
{
immArt->mJCalcDirty = false;
immArt->jcalc<true>(immArt->mArticulationData);
}
immArt->immComputeUnconstrainedVelocitiesTGS(dt, totalDt, invDt, invTotalDt, gravity, invLengthScale);
}
void immediate::PxUpdateArticulationBodiesTGS(PxArticulationHandle articulation, PxReal dt)
{
if (!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
FeatherstoneArticulation::updateBodies(immArt, immArt->mTempDeltaV.begin(), dt, false);
}
static void copyLinkData(PxArticulationLinkDerivedDataRC& data, const immArticulation* immArt, PxU32 index)
{
data.pose = immArt->mBodyCores[index].body2World;
// data.linearVelocity = immArt->mBodyCores[index].linearVelocity;
// data.angularVelocity = immArt->mBodyCores[index].angularVelocity;
const Cm::SpatialVectorF& velocity = immArt->getArticulationData().getMotionVelocity(index);
data.linearVelocity = velocity.bottom;
data.angularVelocity = velocity.top;
}
static PX_FORCE_INLINE const immArticulation* getFromLink(const PxArticulationLinkHandle& link, PxU32& index)
{
if(!link.articulation)
return NULL;
const immArticulation* immArt = static_cast<const immArticulation*>(link.articulation);
index = link.linkId;
if(index>=immArt->mLinks.size())
return NULL;
return immArt;
}
bool immediate::PxGetLinkData(const PxArticulationLinkHandle& link, PxArticulationLinkDerivedDataRC& data)
{
PxU32 index;
const immArticulation* immArt = getFromLink(link, index);
if(!immArt)
return false;
copyLinkData(data, immArt, index);
return true;
}
PxU32 immediate::PxGetAllLinkData(const PxArticulationHandle articulation, PxArticulationLinkDerivedDataRC* data)
{
if(!articulation)
return 0;
const immArticulation* immArt = static_cast<const immArticulation*>(articulation);
const PxU32 nb = immArt->mLinks.size();
if(data)
{
for(PxU32 i=0;i<nb;i++)
copyLinkData(data[i], immArt, i);
}
return nb;
}
bool immediate::PxGetMutableLinkData(const PxArticulationLinkHandle& link , PxArticulationLinkMutableDataRC& data)
{
PxU32 index;
const immArticulation* immArt = getFromLink(link, index);
if(!immArt)
return false;
data.inverseInertia = immArt->mBodyCores[index].inverseInertia;
data.inverseMass = immArt->mBodyCores[index].inverseMass;
data.linearDamping = immArt->mBodyCores[index].linearDamping;
data.angularDamping = immArt->mBodyCores[index].angularDamping;
data.maxLinearVelocitySq = immArt->mBodyCores[index].maxLinearVelocitySq;
data.maxAngularVelocitySq = immArt->mBodyCores[index].maxAngularVelocitySq;
data.cfmScale = immArt->mBodyCores[index].cfmScale;
data.disableGravity = immArt->mBodyCores[index].disableGravity!=0;
return true;
}
bool immediate::PxSetMutableLinkData(const PxArticulationLinkHandle& link , const PxArticulationLinkMutableDataRC& data)
{
PxU32 index;
immArticulation* immArt = const_cast<immArticulation*>(getFromLink(link, index));
if(!immArt)
return false;
immArt->mBodyCores[index].inverseInertia = data.inverseInertia; // See Sc::BodyCore::setInverseInertia
immArt->mBodyCores[index].inverseMass = data.inverseMass; // See Sc::BodyCore::setInverseMass
immArt->mBodyCores[index].linearDamping = data.linearDamping; // See Sc::BodyCore::setLinearDamping
immArt->mBodyCores[index].angularDamping = data.angularDamping; // See Sc::BodyCore::setAngularDamping
immArt->mBodyCores[index].maxLinearVelocitySq = data.maxLinearVelocitySq; // See Sc::BodyCore::setMaxLinVelSq
immArt->mBodyCores[index].maxAngularVelocitySq = data.maxAngularVelocitySq; // See Sc::BodyCore::setMaxAngVelSq
immArt->mBodyCores[index].cfmScale = data.cfmScale; // See Sc::BodyCore::setCfmScale
immArt->mBodyCores[index].disableGravity = data.disableGravity; // See BodySim::postActorFlagChange
return true;
}
bool immediate::PxGetJointData(const PxArticulationLinkHandle& link, PxArticulationJointDataRC& data)
{
PxU32 index;
const immArticulation* immArt = getFromLink(link, index);
if(!immArt)
return false;
const Dy::ArticulationJointCore& core = immArt->mArticulationJointCores[index];
data.parentPose = core.parentPose;
data.childPose = core.childPose;
data.frictionCoefficient = core.frictionCoefficient;
data.maxJointVelocity = core.maxJointVelocity;
data.type = PxArticulationJointType::Enum(core.jointType);
for(PxU32 i=0;i<PxArticulationAxis::eCOUNT;i++)
{
data.motion[i] = PxArticulationMotion::Enum(PxU8(core.motion[i]));
data.limits[i] = core.limits[i];
data.drives[i] = core.drives[i];
data.targetPos[i] = core.targetP[i];
data.targetVel[i] = core.targetV[i];
data.armature[i] = core.armature[i];
data.jointPos[i] = core.jointPos[i];
data.jointVel[i] = core.jointVel[i];
}
return true;
}
static bool samePoses(const PxTransform& pose0, const PxTransform& pose1)
{
return (pose0.p == pose1.p) && (pose0.q == pose1.q);
}
// PT: this is not super efficient if you only want to change one parameter. We could consider adding individual, atomic accessors (but that would
// bloat the API) or flags to validate the desired parameters.
bool immediate::PxSetJointData(const PxArticulationLinkHandle& link, const PxArticulationJointDataRC& data)
{
PxU32 index;
immArticulation* immArt = const_cast<immArticulation*>(getFromLink(link, index));
if(!immArt)
return false;
Dy::ArticulationJointCore& core = immArt->mArticulationJointCores[index];
// PT: poses read by jcalc in ArticulationJointCore::setJointFrame. We need to set ArticulationJointCoreDirtyFlag::eFRAME for this.
{
if(!samePoses(core.parentPose, data.parentPose))
{
core.setParentPose(data.parentPose); // PT: also sets ArticulationJointCoreDirtyFlag::eFRAME
immArt->mJCalcDirty = true;
}
if(!samePoses(core.childPose, data.childPose))
{
core.setChildPose(data.childPose); // PT: also sets ArticulationJointCoreDirtyFlag::eFRAME
immArt->mJCalcDirty = true;
}
}
// PT: joint type read by jcalc in computeMotionMatrix, called from ArticulationJointCore::setJointFrame
if(core.jointType!=PxU8(data.type))
{
core.initJointType(data.type);
immArt->mJCalcDirty = true;
}
// PT: TODO: do we need to recompute jcalc for these?
core.frictionCoefficient = data.frictionCoefficient;
core.maxJointVelocity = data.maxJointVelocity;
for(PxU32 i=0;i<PxArticulationAxis::eCOUNT;i++)
{
// PT: we don't need to recompute jcalc for these
core.limits[i] = data.limits[i];
core.drives[i] = data.drives[i];
core.jointPos[i] = data.jointPos[i];
core.jointVel[i] = data.jointVel[i];
// PT: joint motion read by jcalc in computeJointDof. We need to set Dy::ArticulationJointCoreDirtyFlag::eMOTION for this.
if(core.motion[i]!=data.motion[i])
{
core.setMotion(PxArticulationAxis::Enum(i), data.motion[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eMOTION
immArt->mJCalcDirty = true;
}
// PT: targetP read by jcalc in setJointPoseDrive. We need to set ArticulationJointCoreDirtyFlag::eTARGETPOSE for this.
if(core.targetP[i] != data.targetPos[i])
{
core.setTargetP(PxArticulationAxis::Enum(i), data.targetPos[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eTARGETPOSE
immArt->mJCalcDirty = true;
}
// PT: targetV read by jcalc in setJointVelocityDrive. We need to set ArticulationJointCoreDirtyFlag::eTARGETVELOCITY for this.
if(core.targetV[i] != data.targetVel[i])
{
core.setTargetV(PxArticulationAxis::Enum(i), data.targetVel[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eTARGETVELOCITY
immArt->mJCalcDirty = true;
}
// PT: armature read by jcalc in setArmature. We need to set ArticulationJointCoreDirtyFlag::eARMATURE for this.
if(core.armature[i] != data.armature[i])
{
core.setArmature(PxArticulationAxis::Enum(i), data.armature[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eARMATURE
immArt->mJCalcDirty = true;
}
}
return true;
}
namespace physx
{
namespace Dy
{
void copyToSolverBodyDataStep(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold,
PxReal maxAngVelSq, PxU32 lockFlags, bool isKinematic,
PxTGSSolverBodyVel& solverVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData,
PxReal dt, bool gyroscopicForces);
void integrateCoreStep(PxTGSSolverBodyVel& vel, PxTGSSolverBodyTxInertia& txInertia, PxF32 dt);
}
}
void immediate::PxConstructSolverBodiesTGS(const PxRigidBodyData* inRigidData, PxTGSSolverBodyVel* outSolverBodyVel,
PxTGSSolverBodyTxInertia* outSolverBodyTxInertia, PxTGSSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity,
PxReal dt, bool gyroscopicForces)
{
for (PxU32 a = 0; a<nbBodies; a++)
{
const PxRigidBodyData& rigidData = inRigidData[a];
PxVec3 lv = rigidData.linearVelocity, av = rigidData.angularVelocity;
Dy::bodyCoreComputeUnconstrainedVelocity(gravity, dt, rigidData.linearDamping, rigidData.angularDamping, 1.0f, rigidData.maxLinearVelocitySq, rigidData.maxAngularVelocitySq, lv, av, false);
Dy::copyToSolverBodyDataStep(lv, av, rigidData.invMass, rigidData.invInertia, rigidData.body2World, -rigidData.maxDepenetrationVelocity, rigidData.maxContactImpulse, PX_INVALID_NODE,
PX_MAX_F32, rigidData.maxAngularVelocitySq, 0, false, outSolverBodyVel[a], outSolverBodyTxInertia[a], outSolverBodyData[a], dt, gyroscopicForces);
}
}
void immediate::PxConstructStaticSolverBodyTGS(const PxTransform& globalPose, PxTGSSolverBodyVel& solverBodyVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData)
{
const PxVec3 zero(0.0f);
Dy::copyToSolverBodyDataStep(zero, zero, 0.0f, zero, globalPose, -PX_MAX_F32, PX_MAX_F32, PX_INVALID_NODE, PX_MAX_F32, PX_MAX_F32, 0, true, solverBodyVel, solverBodyTxInertia, solverBodyData, 0.0f, false);
}
PxU32 immediate::PxBatchConstraintsTGS(const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxTGSSolverBodyVel* solverBodies, PxU32 nbBodies,
PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs,
PxArticulationHandle* articulations, PxU32 nbArticulations)
{
if (!nbArticulations)
{
RigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxTGSSolverBodyVel));
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
else
{
ExtendedRigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxTGSSolverBodyVel), reinterpret_cast<Dy::FeatherstoneArticulation**>(articulations), nbArticulations);
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
}
bool immediate::PxCreateContactConstraintsTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxTGSSolverContactDesc* contactDescs,
PxConstraintAllocator& allocator, PxReal invDt, PxReal invTotalDt, PxReal bounceThreshold, PxReal frictionOffsetThreshold, PxReal correlationDistance)
{
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
PX_ASSERT(bounceThreshold < 0.0f);
PX_ASSERT(frictionOffsetThreshold > 0.0f);
PX_ASSERT(correlationDistance > 0.0f);
Dy::CorrelationBuffer cb;
PxU32 currentContactDescIdx = 0;
const PxReal biasCoefficient = 2.f*PxSqrt(invTotalDt/invDt);
const PxReal totalDt = 1.f/invTotalDt;
const PxReal dt = 1.f / invDt;
for (PxU32 i = 0; i < nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
if (batchHeader.stride == 4)
{
PxU32 totalContacts = contactDescs[currentContactDescIdx].numContacts + contactDescs[currentContactDescIdx + 1].numContacts +
contactDescs[currentContactDescIdx + 2].numContacts + contactDescs[currentContactDescIdx + 3].numContacts;
if (totalContacts <= 64)
{
state = Dy::createFinalizeSolverContacts4Step(cb,
contactDescs + currentContactDescIdx,
invDt,
totalDt,
invTotalDt,
dt,
bounceThreshold,
frictionOffsetThreshold,
correlationDistance,
biasCoefficient,
allocator);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
Dy::createFinalizeSolverContactsStep(contactDescs[currentContactDescIdx + a], cb, invDt, invTotalDt, totalDt, dt, bounceThreshold,
frictionOffsetThreshold, correlationDistance, biasCoefficient, allocator);
}
}
if(contactDescs[currentContactDescIdx].desc->constraint)
{
PxU8 type = *contactDescs[currentContactDescIdx].desc->constraint;
if (type == DY_SC_TYPE_STATIC_CONTACT)
{
//Check if any block of constraints is classified as type static (single) contact constraint.
//If they are, iterate over all constraints grouped with it and switch to "dynamic" contact constraint
//type if there's a dynamic contact constraint in the group.
for (PxU32 c = 1; c < batchHeader.stride; ++c)
{
if (*contactDescs[currentContactDescIdx + c].desc->constraint == DY_SC_TYPE_RB_CONTACT)
{
type = DY_SC_TYPE_RB_CONTACT;
break;
}
}
}
batchHeader.constraintType = type;
}
currentContactDescIdx += batchHeader.stride;
}
return true;
}
bool immediate::PxCreateJointConstraintsTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders,
PxTGSSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt,
PxReal invTotalDt, PxReal lengthScale)
{
PX_ASSERT(dt > 0.0f);
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
const PxReal biasCoefficient = 2.f*PxSqrt(dt/totalDt);
PxU32 currentDescIdx = 0;
for (PxU32 i = 0; i < nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
PxU8 type = DY_SC_TYPE_BLOCK_1D;
if (batchHeader.stride == 4)
{
PxU32 totalRows = 0;
PxU32 maxRows = 0;
bool batchable = true;
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
if (jointDescs[currentDescIdx + a].numRows == 0)
{
batchable = false;
break;
}
totalRows += jointDescs[currentDescIdx + a].numRows;
maxRows = PxMax(maxRows, jointDescs[currentDescIdx + a].numRows);
}
if (batchable)
{
state = Dy::setupSolverConstraintStep4
(jointDescs + currentDescIdx,
dt, totalDt, invDt, invTotalDt, totalRows,
allocator, maxRows, lengthScale, biasCoefficient);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
type = DY_SC_TYPE_RB_1D;
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
// PT: TODO: And "isExtended" is already computed in Dy::ConstraintHelper::setupSolverConstraint
PxSolverConstraintDesc& desc = *jointDescs[currentDescIdx + a].desc;
const bool isExtended = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY;
if (isExtended)
type = DY_SC_TYPE_EXT_1D;
Dy::setupSolverConstraintStep(jointDescs[currentDescIdx + a], allocator, dt, totalDt, invDt, invTotalDt, lengthScale, biasCoefficient);
}
}
batchHeader.constraintType = type;
currentDescIdx += batchHeader.stride;
}
return true;
}
template<class LeafTestT, class ParamsT>
static bool PxCreateJointConstraintsWithShadersTGS_T(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, ParamsT* params, PxTGSSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal lengthScale)
{
Px1DConstraint allRows[Dy::MAX_CONSTRAINT_ROWS * 4];
//Runs shaders to fill in rows...
PxU32 currentDescIdx = 0;
for (PxU32 i = 0; i<nbHeaders; i++)
{
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
for (PxU32 a = 0; a<batchHeader.stride; a++)
{
PxTGSSolverConstraintPrepDesc& desc = jointDescs[currentDescIdx + a];
PxConstraintSolverPrep prep;
const void* constantBlock;
const bool useExtendedLimits = LeafTestT::getData(params, currentDescIdx + a, &prep, &constantBlock);
PX_ASSERT(prep);
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
//TAG:solverprepcall
const PxU32 constraintCount = prep(rows,
desc.body0WorldOffset,
Dy::MAX_CONSTRAINT_ROWS,
desc.invMassScales,
constantBlock,
desc.bodyFrame0, desc.bodyFrame1,
useExtendedLimits,
desc.cA2w, desc.cB2w);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
}
PxCreateJointConstraintsTGS(&batchHeader, 1, jointDescs + currentDescIdx, allocator, dt, totalDt, invDt,
invTotalDt, lengthScale);
currentDescIdx += batchHeader.stride;
}
return true; //KS - TODO - do some error reporting/management...
}
bool immediate::PxCreateJointConstraintsWithShadersTGS(PxConstraintBatchHeader* batchHeaders, const PxU32 nbBatchHeaders, PxConstraint** constraints, PxTGSSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, const PxReal dt,
const PxReal totalDt, const PxReal invDt, const PxReal invTotalDt, const PxReal lengthScale)
{
return PxCreateJointConstraintsWithShadersTGS_T<PxConstraintAdapter>(batchHeaders, nbBatchHeaders, constraints, jointDescs, allocator, dt, totalDt, invDt, invTotalDt, lengthScale);
}
bool immediate::PxCreateJointConstraintsWithImmediateShadersTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxImmediateConstraint* constraints, PxTGSSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal lengthScale)
{
class immConstraintAdapter
{
public:
static PX_FORCE_INLINE bool getData(PxImmediateConstraint* constraints_, PxU32 i, PxConstraintSolverPrep* prep, const void** constantBlock)
{
const PxImmediateConstraint& ic = constraints_[i];
*prep = ic.prep;
*constantBlock = ic.constantBlock;
return false;
}
};
return PxCreateJointConstraintsWithShadersTGS_T<immConstraintAdapter>(batchHeaders, nbHeaders, constraints, jointDescs, allocator, dt, totalDt, invDt, invTotalDt, lengthScale);
}
void immediate::PxSolveConstraintsTGS(const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs,
PxTGSSolverBodyVel* solverBodies, PxTGSSolverBodyTxInertia* txInertias, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations,
float dt, float invDt, PxU32 nbSolverArticulations, PxArticulationHandle* solverArticulations, PxSpatialVector* pxZ, PxSpatialVector* pxDeltaV)
{
PX_ASSERT(nbPositionIterations > 0);
PX_ASSERT(nbVelocityIterations > 0);
const Dy::TGSSolveBlockMethod* solveTable = Dy::g_SolveTGSMethods;
const Dy::TGSSolveConcludeMethod* solveConcludeTable = Dy::g_SolveConcludeTGSMethods;
const Dy::TGSWriteBackMethod* writebackTable = Dy::g_WritebackTGSMethods;
Dy::SolverContext cache;
cache.mThresholdStreamIndex = 0;
cache.mThresholdStreamLength = 0xFFFFFFF;
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(pxZ);
Cm::SpatialVectorF* deltaV = reinterpret_cast<Cm::SpatialVectorF*>(pxDeltaV);
cache.Z = Z;
cache.deltaV = deltaV;
cache.doFriction = true;
Dy::FeatherstoneArticulation** articulations = reinterpret_cast<Dy::FeatherstoneArticulation**>(solverArticulations);
struct TGS
{
static PX_FORCE_INLINE void solveArticulationInternalConstraints(float dt_, float invDt_, PxU32 nbSolverArticulations_, Dy::FeatherstoneArticulation** solverArticulations_, Cm::SpatialVectorF* Z_, Cm::SpatialVectorF* deltaV_,
PxReal elapsedTime, bool velIter_)
{
while(nbSolverArticulations_--)
{
immArticulation* immArt = static_cast<immArticulation*>(*solverArticulations_++);
immArt->immSolveInternalConstraints(dt_, invDt_, Z_, deltaV_, elapsedTime, velIter_, true);
}
}
};
const PxReal invTotalDt = 1.0f/(dt*nbPositionIterations);
PxReal elapsedTime = 0.0f;
while(nbPositionIterations--)
{
TGS::solveArticulationInternalConstraints(dt, invDt, nbSolverArticulations, articulations, Z, deltaV, elapsedTime, false);
for(PxU32 a=0; a<nbBatchHeaders; ++a)
{
const PxConstraintBatchHeader& batch = batchHeaders[a];
if(nbPositionIterations)
solveTable[batch.constraintType](batch, solverConstraintDescs, txInertias, -PX_MAX_F32, elapsedTime, cache);
else
solveConcludeTable[batch.constraintType](batch, solverConstraintDescs, txInertias, elapsedTime, cache);
}
{
for(PxU32 j=0; j<nbSolverBodies; ++j)
Dy::integrateCoreStep(solverBodies[j], txInertias[j], dt);
for(PxU32 j=0; j<nbSolverArticulations; ++j)
{
immArticulation* immArt = static_cast<immArticulation*>(solverArticulations[j]);
immArt->recordDeltaMotion(immArt->getSolverDesc(), dt, deltaV, invTotalDt);
}
}
elapsedTime += dt;
}
for (PxU32 a=0; a<nbSolverArticulations; a++)
{
immArticulation* immArt = static_cast<immArticulation*>(articulations[a]);
immArt->saveVelocityTGS(immArt, invTotalDt);
}
while(nbVelocityIterations--)
{
TGS::solveArticulationInternalConstraints(dt, invDt, nbSolverArticulations, articulations, Z, deltaV, elapsedTime, true);
for(PxU32 a=0; a<nbBatchHeaders; ++a)
{
const PxConstraintBatchHeader& batch = batchHeaders[a];
solveTable[batch.constraintType](batch, solverConstraintDescs, txInertias, 0.0f, elapsedTime, cache);
if(!nbVelocityIterations)
writebackTable[batch.constraintType](batch, solverConstraintDescs, &cache);
}
}
}
void immediate::PxIntegrateSolverBodiesTGS(PxTGSSolverBodyVel* solverBody, PxTGSSolverBodyTxInertia* txInertia, PxTransform* poses, PxU32 nbBodiesToIntegrate, PxReal /*dt*/)
{
for(PxU32 i = 0; i < nbBodiesToIntegrate; ++i)
{
solverBody[i].angularVelocity = txInertia[i].sqrtInvInertia * solverBody[i].angularVelocity;
poses[i].p = txInertia[i].deltaBody2World.p;
poses[i].q = (txInertia[i].deltaBody2World.q * poses[i].q).getNormalized();
}
}
#include "PxvGlobals.h"
#include "PxPhysXGpu.h"
#include "BpBroadPhase.h"
#include "PxsHeapMemoryAllocator.h"
#include "PxsKernelWrangler.h"
#include "PxsMemoryManager.h"
PX_COMPILE_TIME_ASSERT(sizeof(Bp::FilterGroup::Enum)==sizeof(PxBpFilterGroup));
PX_IMPLEMENT_OUTPUT_ERROR
PxBpFilterGroup physx::PxGetBroadPhaseStaticFilterGroup()
{
return Bp::getFilterGroup_Statics();
}
PxBpFilterGroup physx::PxGetBroadPhaseDynamicFilterGroup(PxU32 id)
{
return Bp::getFilterGroup_Dynamics(id, false);
}
PxBpFilterGroup physx::PxGetBroadPhaseKinematicFilterGroup(PxU32 id)
{
return Bp::getFilterGroup_Dynamics(id, true);
}
namespace
{
// PT: the Bp::BroadPhase API is quite confusing and the file cannot be included from everywhere
// so let's have a user-friendly wrapper for now.
class ImmCPUBP : public PxBroadPhase, public PxBroadPhaseRegions, public PxUserAllocated
{
public:
ImmCPUBP(const PxBroadPhaseDesc& desc);
virtual ~ImmCPUBP();
virtual bool init(const PxBroadPhaseDesc& desc);
// PxBroadPhase
virtual void release() PX_OVERRIDE;
virtual PxBroadPhaseType::Enum getType() const PX_OVERRIDE;
virtual void getCaps(PxBroadPhaseCaps& caps) const PX_OVERRIDE;
virtual PxBroadPhaseRegions* getRegions() PX_OVERRIDE;
virtual PxAllocatorCallback* getAllocator() PX_OVERRIDE;
virtual PxU64 getContextID() const PX_OVERRIDE;
virtual void setScratchBlock(void* scratchBlock, PxU32 size) PX_OVERRIDE;
virtual void update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation) PX_OVERRIDE;
virtual void fetchResults(PxBroadPhaseResults& results) PX_OVERRIDE;
//~PxBroadPhase
// PxBroadPhaseRegions
virtual PxU32 getNbRegions() const PX_OVERRIDE;
virtual PxU32 getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE;
virtual PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const float* contactDistance) PX_OVERRIDE;
virtual bool removeRegion(PxU32 handle) PX_OVERRIDE;
virtual PxU32 getNbOutOfBoundsObjects() const PX_OVERRIDE;
virtual const PxU32* getOutOfBoundsObjects() const PX_OVERRIDE;
//~PxBroadPhaseRegions
Bp::BroadPhase* mBroadPhase;
PxcScratchAllocator mScratchAllocator;
Bp::BpFilter mFilters;
PxArray<PxBroadPhasePair> mCreatedPairs;
PxArray<PxBroadPhasePair> mDeletedPairs;
const PxU64 mContextID;
void* mAABBManager;
void releaseBP();
};
}
///////////////////////////////////////////////////////////////////////////////
ImmCPUBP::ImmCPUBP(const PxBroadPhaseDesc& desc) :
mBroadPhase (NULL),
mFilters (desc.mDiscardKinematicVsKinematic, desc.mDiscardStaticVsKinematic),
mContextID (desc.mContextID),
mAABBManager(NULL)
{
}
ImmCPUBP::~ImmCPUBP()
{
releaseBP();
}
void ImmCPUBP::releaseBP()
{
PX_RELEASE(mBroadPhase);
}
bool ImmCPUBP::init(const PxBroadPhaseDesc& desc)
{
if(!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxCreateBroadPhase: invalid broadphase descriptor");
const PxU32 maxNbRegions = 0;
const PxU32 maxNbBroadPhaseOverlaps = 0;
const PxU32 maxNbStaticShapes = 0;
const PxU32 maxNbDynamicShapes = 0;
// PT: TODO: unify creation of CPU and GPU BPs (PX-2542)
mBroadPhase = Bp::BroadPhase::create(desc.mType, maxNbRegions, maxNbBroadPhaseOverlaps, maxNbStaticShapes, maxNbDynamicShapes, desc.mContextID);
return mBroadPhase!=NULL;
}
///////////////////////////////////////////////////////////////////////////////
void ImmCPUBP::release()
{
if(mAABBManager)
{
outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "ImmCPUBP::release: AABB manager is still present, release the AABB manager first");
return;
}
PX_DELETE_THIS;
}
PxBroadPhaseType::Enum ImmCPUBP::getType() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getType();
}
void ImmCPUBP::getCaps(PxBroadPhaseCaps& caps) const
{
PX_ASSERT(mBroadPhase);
mBroadPhase->getCaps(caps);
}
PxBroadPhaseRegions* ImmCPUBP::getRegions()
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getType() == PxBroadPhaseType::eMBP ? this : NULL;
}
PxAllocatorCallback* ImmCPUBP::getAllocator()
{
return PxGetAllocatorCallback();
}
PxU64 ImmCPUBP::getContextID() const
{
return mContextID;
}
void ImmCPUBP::setScratchBlock(void* scratchBlock, PxU32 size)
{
if(scratchBlock && size)
mScratchAllocator.setBlock(scratchBlock, size);
}
void ImmCPUBP::update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation)
{
PX_PROFILE_ZONE("ImmCPUBP::update", mContextID);
PX_ASSERT(mBroadPhase);
// PT: convert PxBroadPhaseUpdateData to Bp::BroadPhaseUpdateData. Main differences is the two undocumented bools
// added for the GPU version. For now we just set them to true, which may not be the fastest but it should always
// be correct.
// TODO: revisit this / get rid of the bools in the low-level API (PX-2835)
const Bp::BroadPhaseUpdateData defaultUpdateData(
updateData.mCreated, updateData.mNbCreated,
updateData.mUpdated, updateData.mNbUpdated,
updateData.mRemoved, updateData.mNbRemoved,
updateData.mBounds,
reinterpret_cast<const Bp::FilterGroup::Enum*>(updateData.mGroups),
updateData.mDistances, updateData.mCapacity,
mFilters,
true, true);
// PT: preBroadPhase & fetchBroadPhaseResults are only needed for the GPU BP.
// The PxBroadPhase API hides this from users and gives them an easier API that
// deals with these differences under the hood.
mBroadPhase->preBroadPhase(defaultUpdateData); // ### could be skipped for CPU BPs
// PT: BP UPDATE CALL
mBroadPhase->update(&mScratchAllocator, defaultUpdateData, continuation);
mBroadPhase->fetchBroadPhaseResults(); // ### could be skipped for CPU BPs
}
void ImmCPUBP::fetchResults(PxBroadPhaseResults& results)
{
PX_PROFILE_ZONE("ImmCPUBP::fetchResults", mContextID);
PX_ASSERT(mBroadPhase);
// PT: TODO: flags to skip the copies (PX-2929)
if(0)
{
results.mCreatedPairs = reinterpret_cast<const PxBroadPhasePair*>(mBroadPhase->getCreatedPairs(results.mNbCreatedPairs));
results.mDeletedPairs = reinterpret_cast<const PxBroadPhasePair*>(mBroadPhase->getDeletedPairs(results.mNbDeletedPairs));
}
else
{
struct Local
{
static void copyPairs(PxArray<PxBroadPhasePair>& pairs, PxU32 nbPairs, const Bp::BroadPhasePair* bpPairs)
{
pairs.resetOrClear();
const PxBroadPhasePair* src = reinterpret_cast<const PxBroadPhasePair*>(bpPairs);
PxBroadPhasePair* dst = Cm::reserveContainerMemory(pairs, nbPairs);
PxMemCopy(dst, src, sizeof(PxBroadPhasePair)*nbPairs);
}
};
{
PX_PROFILE_ZONE("copyPairs", mContextID);
{
PxU32 nbCreatedPairs;
const Bp::BroadPhasePair* createdPairs = mBroadPhase->getCreatedPairs(nbCreatedPairs);
Local::copyPairs(mCreatedPairs, nbCreatedPairs, createdPairs);
}
{
PxU32 nbDeletedPairs;
const Bp::BroadPhasePair* deletedPairs = mBroadPhase->getDeletedPairs(nbDeletedPairs);
Local::copyPairs(mDeletedPairs, nbDeletedPairs, deletedPairs);
}
}
results.mNbCreatedPairs = mCreatedPairs.size();
results.mNbDeletedPairs = mDeletedPairs.size();
results.mCreatedPairs = mCreatedPairs.begin();
results.mDeletedPairs = mDeletedPairs.begin();
}
// PT: TODO: this function got introduced in the "GRB merge" (CL 20888255) for the SAP but wasn't necessary before,
// and isn't necessary for the other BPs (even the GPU one). That makes no sense and should probably be removed.
//mBroadPhase->deletePairs();
// PT: similarly this is only needed for the SAP. This is also called at the exact same time as "deletePairs" so
// I'm not sure why we used 2 separate functions. It just bloats the API for no reason.
mBroadPhase->freeBuffers();
}
///////////////////////////////////////////////////////////////////////////////
// PT: the following calls are just re-routed to the LL functions. This should only be available/needed for MBP.
PxU32 ImmCPUBP::getNbRegions() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getNbRegions();
}
PxU32 ImmCPUBP::getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getRegions(userBuffer, bufferSize, startIndex);
}
PxU32 ImmCPUBP::addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const float* contactDistance)
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->addRegion(region, populateRegion, boundsArray, contactDistance);
}
bool ImmCPUBP::removeRegion(PxU32 handle)
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->removeRegion(handle);
}
PxU32 ImmCPUBP::getNbOutOfBoundsObjects() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getNbOutOfBoundsObjects();
}
const PxU32* ImmCPUBP::getOutOfBoundsObjects() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getOutOfBoundsObjects();
}
///////////////////////////////////////////////////////////////////////////////
#if PX_SUPPORT_GPU_PHYSX
namespace
{
class ImmGPUBP : public ImmCPUBP, public PxAllocatorCallback
{
public:
ImmGPUBP(const PxBroadPhaseDesc& desc);
virtual ~ImmGPUBP();
// PxAllocatorCallback
virtual void* allocate(size_t size, const char* /*typeName*/, const char* filename, int line) PX_OVERRIDE;
virtual void deallocate(void* ptr) PX_OVERRIDE;
//~PxAllocatorCallback
// PxBroadPhase
virtual PxAllocatorCallback* getAllocator() PX_OVERRIDE;
//~PxBroadPhase
// ImmCPUBP
virtual bool init(const PxBroadPhaseDesc& desc) PX_OVERRIDE;
//~ImmCPUBP
PxPhysXGpu* mPxGpu;
PxsMemoryManager* mMemoryManager;
PxsKernelWranglerManager* mGpuWranglerManagers;
PxsHeapMemoryAllocatorManager* mHeapMemoryAllocationManager;
};
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if PX_SUPPORT_GPU_PHYSX
ImmGPUBP::ImmGPUBP(const PxBroadPhaseDesc& desc) :
ImmCPUBP (desc),
mPxGpu (NULL),
mMemoryManager (NULL),
mGpuWranglerManagers (NULL),
mHeapMemoryAllocationManager(NULL)
{
}
ImmGPUBP::~ImmGPUBP()
{
releaseBP(); // PT: must release the BP first, before the base dtor is called
PX_DELETE(mHeapMemoryAllocationManager);
PX_DELETE(mMemoryManager);
//PX_RELEASE(mPxGpu);
PxvReleasePhysXGpu(mPxGpu);
mPxGpu = NULL;
}
void* ImmGPUBP::allocate(size_t size, const char* /*typeName*/, const char* filename, int line)
{
PX_ASSERT(mMemoryManager);
PxVirtualAllocatorCallback* cb = mMemoryManager->getHostMemoryAllocator();
return cb->allocate(size, 0, filename, line);
}
void ImmGPUBP::deallocate(void* ptr)
{
PX_ASSERT(mMemoryManager);
PxVirtualAllocatorCallback* cb = mMemoryManager->getHostMemoryAllocator();
cb->deallocate(ptr);
}
PxAllocatorCallback* ImmGPUBP::getAllocator()
{
return this;
}
bool ImmGPUBP::init(const PxBroadPhaseDesc& desc)
{
PX_ASSERT(desc.mType==PxBroadPhaseType::eGPU);
if(!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxCreateBroadPhase: invalid broadphase descriptor");
PxCudaContextManager* contextManager = desc.mContextManager;
// PT: one issue with PxvGetPhysXGpu is that it creates the whole PxPhysXGpu object, not just the BP. Questionable coupling there.
//mPxGpu = PxCreatePhysXGpu();
mPxGpu = PxvGetPhysXGpu(true);
if(!mPxGpu)
return false;
const PxU32 gpuComputeVersion = 0;
// PT: what's the difference between the "GPU memory manager" and the "GPU heap memory allocator manager" ?
mMemoryManager = mPxGpu->createGpuMemoryManager(contextManager);
if(!mMemoryManager)
return false;
mGpuWranglerManagers = mPxGpu->getGpuKernelWranglerManager(contextManager);
if(!mGpuWranglerManagers)
return false;
PxgDynamicsMemoryConfig gpuDynamicsConfig;
gpuDynamicsConfig.foundLostPairsCapacity = desc.mFoundLostPairsCapacity;
mHeapMemoryAllocationManager = mPxGpu->createGpuHeapMemoryAllocatorManager(gpuDynamicsConfig.heapCapacity, mMemoryManager, gpuComputeVersion);
if(!mHeapMemoryAllocationManager)
return false;
mBroadPhase = mPxGpu->createGpuBroadPhase(mGpuWranglerManagers, contextManager, gpuComputeVersion, gpuDynamicsConfig, mHeapMemoryAllocationManager, desc.mContextID);
return mBroadPhase!=NULL;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// PT: TODO: why don't we even have a PxBroadPhaseDesc in the main Px API by now? (PX-2933)
// The BP parameters are scattered in PxSceneDesc/PxSceneLimits/etc
// The various BP-related APIs are particularly messy.
PxBroadPhase* physx::PxCreateBroadPhase(const PxBroadPhaseDesc& desc)
{
ImmCPUBP* immBP;
if(desc.mType == PxBroadPhaseType::eGPU)
#if PX_SUPPORT_GPU_PHYSX
immBP = PX_NEW(ImmGPUBP)(desc);
#else
return NULL;
#endif
else
immBP = PX_NEW(ImmCPUBP)(desc);
if(!immBP->init(desc))
{
PX_DELETE(immBP);
return NULL;
}
return immBP;
}
namespace
{
// TODO: user-data? (PX-2934)
// TODO: aggregates? (PX-2935)
// TODO: do we really need the bitmaps in this wrapper anyway?
class HighLevelBroadPhaseAPI : public PxAABBManager, public PxUserAllocated
{
public:
HighLevelBroadPhaseAPI(PxBroadPhase& broadphase);
virtual ~HighLevelBroadPhaseAPI();
// PxAABBManager
virtual void release() PX_OVERRIDE { PX_DELETE_THIS; }
virtual void addObject(PxU32 index, const PxBounds3& bounds, PxBpFilterGroup group, float distance) PX_OVERRIDE;
virtual void removeObject(PxU32 index) PX_OVERRIDE;
virtual void updateObject(PxU32 index, const PxBounds3* bounds, const float* distance) PX_OVERRIDE;
virtual void update(PxBaseTask* continuation) PX_OVERRIDE;
virtual void fetchResults(PxBroadPhaseResults& results) PX_OVERRIDE;
virtual PxBroadPhase& getBroadPhase() PX_OVERRIDE { return mBroadPhase; }
virtual const PxBounds3* getBounds() const PX_OVERRIDE { return mBounds; }
virtual const float* getDistances() const PX_OVERRIDE { return mDistances; }
virtual const PxBpFilterGroup* getGroups() const PX_OVERRIDE { return mGroups; }
virtual PxU32 getCapacity() const PX_OVERRIDE { return mCapacity; }
//~PxAABBManager
void reserveSpace(PxU32 nbTotalBounds);
PxBroadPhase& mBroadPhase;
PxBounds3* mBounds;
float* mDistances;
PxBpFilterGroup* mGroups;
PxU32 mCapacity; // PT: same capacity for all the above buffers
// PT: TODO: pinned? (PX-2936)
PxBitMap mAddedHandleMap; // PT: indexed by BoundsIndex
PxBitMap mRemovedHandleMap; // PT: indexed by BoundsIndex
PxBitMap mUpdatedHandleMap; // PT: indexed by BoundsIndex
// PT: TODO: pinned? (PX-2936)
PxArray<PxU32> mAddedHandles;
PxArray<PxU32> mUpdatedHandles;
PxArray<PxU32> mRemovedHandles;
const PxU64 mContextID;
};
}
HighLevelBroadPhaseAPI::HighLevelBroadPhaseAPI(PxBroadPhase& broadphase) :
mBroadPhase (broadphase),
mBounds (NULL),
mDistances (NULL),
mGroups (NULL),
mCapacity (0),
mContextID (broadphase.getContextID())
{
ImmCPUBP& baseBP = static_cast<ImmCPUBP&>(broadphase);
PX_ASSERT(!baseBP.mAABBManager);
baseBP.mAABBManager = this;
}
HighLevelBroadPhaseAPI::~HighLevelBroadPhaseAPI()
{
PxAllocatorCallback* allocator = mBroadPhase.getAllocator();
if(mDistances)
{
allocator->deallocate(mDistances);
mDistances = NULL;
}
if(mGroups)
{
allocator->deallocate(mGroups);
mGroups = NULL;
}
if(mBounds)
{
allocator->deallocate(mBounds);
mBounds = NULL;
}
ImmCPUBP& baseBP = static_cast<ImmCPUBP&>(mBroadPhase);
baseBP.mAABBManager = NULL;
}
void HighLevelBroadPhaseAPI::reserveSpace(PxU32 nbEntriesNeeded)
{
PX_PROFILE_ZONE("HighLevelBroadPhaseAPI::reserveSpace", mContextID);
PX_ASSERT(mCapacity<nbEntriesNeeded); // PT: otherwise don't call this function
// PT: allocate more than necessary to minimize the amount of reallocations
nbEntriesNeeded = PxNextPowerOfTwo(nbEntriesNeeded);
// PT: use the allocator provided by the BP, in case we need CUDA-friendly buffers
PxAllocatorCallback* allocator = mBroadPhase.getAllocator();
{
// PT: for bounds we always allocate one more entry to ensure safe SIMD loads
PxBounds3* newBounds = reinterpret_cast<PxBounds3*>(allocator->allocate(sizeof(PxBounds3)*(nbEntriesNeeded+1), "HighLevelBroadPhaseAPI::mBounds", PX_FL));
if(mCapacity && mBounds)
PxMemCopy(newBounds, mBounds, sizeof(PxBounds3)*mCapacity);
for(PxU32 i=mCapacity;i<nbEntriesNeeded;i++)
newBounds[i].setEmpty(); // PT: maybe we could skip this for perf
if(mBounds)
allocator->deallocate(mBounds);
mBounds = newBounds;
}
{
PxBpFilterGroup* newGroups = reinterpret_cast<PxBpFilterGroup*>(allocator->allocate(sizeof(PxBpFilterGroup)*nbEntriesNeeded, "HighLevelBroadPhaseAPI::mGroups", PX_FL));
if(mCapacity && mGroups)
PxMemCopy(newGroups, mGroups, sizeof(PxBpFilterGroup)*mCapacity);
for(PxU32 i=mCapacity;i<nbEntriesNeeded;i++)
newGroups[i] = PX_INVALID_BP_FILTER_GROUP; // PT: maybe we could skip this for perf
if(mGroups)
allocator->deallocate(mGroups);
mGroups = newGroups;
}
{
float* newDistances = reinterpret_cast<float*>(allocator->allocate(sizeof(float)*nbEntriesNeeded, "HighLevelBroadPhaseAPI::mDistances", PX_FL));
if(mCapacity && mDistances)
PxMemCopy(newDistances, mDistances, sizeof(float)*mCapacity);
for(PxU32 i=mCapacity;i<nbEntriesNeeded;i++)
newDistances[i] = 0.0f; // PT: maybe we could skip this for perf
if(mDistances)
allocator->deallocate(mDistances);
mDistances = newDistances;
}
mAddedHandleMap.resize(nbEntriesNeeded);
mRemovedHandleMap.resize(nbEntriesNeeded);
mCapacity = nbEntriesNeeded;
}
// PT: TODO: version with internal index management? (PX-2942)
// PT: TODO: batched version?
void HighLevelBroadPhaseAPI::addObject(PxBpIndex index, const PxBounds3& bounds, PxBpFilterGroup group, float distance)
{
PX_ASSERT(group != PX_INVALID_BP_FILTER_GROUP); // PT: we use group == PX_INVALID_BP_FILTER_GROUP to mark removed/invalid entries
const PxU32 nbEntriesNeeded = index + 1;
if(mCapacity<nbEntriesNeeded)
reserveSpace(nbEntriesNeeded);
mBounds[index] = bounds;
mGroups[index] = group;
mDistances[index] = distance;
if(mRemovedHandleMap.test(index))
mRemovedHandleMap.reset(index);
else // PT: for case where an object in the BP gets removed and then we re-add same frame (we don't want to set the add bit in this case)
mAddedHandleMap.set(index);
}
// PT: TODO: batched version?
void HighLevelBroadPhaseAPI::removeObject(PxBpIndex index)
{
PX_ASSERT(index < mCapacity);
PX_ASSERT(mGroups[index] != PX_INVALID_BP_FILTER_GROUP);
if(mAddedHandleMap.test(index)) // PT: if object had been added this frame...
mAddedHandleMap.reset(index); // PT: ...then simply revert the previous operation locally (it hasn't been passed to the BP yet).
else
mRemovedHandleMap.set(index); // PT: else we need to remove it from the BP
mBounds[index].setEmpty();
mGroups[index] = PX_INVALID_BP_FILTER_GROUP;
mDistances[index] = 0.0f;
}
// PT: TODO: batched version?
void HighLevelBroadPhaseAPI::updateObject(PxBpIndex index, const PxBounds3* bounds, const float* distance)
{
PX_ASSERT(index < mCapacity);
mUpdatedHandleMap.growAndSet(index);
if(bounds)
mBounds[index] = *bounds;
if(distance)
mDistances[index] = *distance;
}
namespace
{
struct HandleTest_Add
{
static PX_FORCE_INLINE void processEntry(HighLevelBroadPhaseAPI& bp, PxU32 handle)
{
PX_ASSERT(bp.mGroups[handle] != PX_INVALID_BP_FILTER_GROUP);
bp.mAddedHandles.pushBack(handle);
}
};
struct HandleTest_Update
{
static PX_FORCE_INLINE void processEntry(HighLevelBroadPhaseAPI& bp, PxU32 handle)
{
// PT: TODO: revisit the logic here (PX-2937)
PX_ASSERT(!bp.mRemovedHandleMap.test(handle)); // a handle may only be updated and deleted if it was just added.
if(bp.mAddedHandleMap.test(handle)) // just-inserted handles may also be marked updated, so skip them
return;
PX_ASSERT(bp.mGroups[handle] != PX_INVALID_BP_FILTER_GROUP);
bp.mUpdatedHandles.pushBack(handle);
}
};
struct HandleTest_Remove
{
static PX_FORCE_INLINE void processEntry(HighLevelBroadPhaseAPI& bp, PxU32 handle)
{
PX_ASSERT(bp.mGroups[handle] == PX_INVALID_BP_FILTER_GROUP);
bp.mRemovedHandles.pushBack(handle);
}
};
}
template<class FunctionT, class ParamsT>
static void iterateBitmap(const PxBitMap& bitmap, ParamsT& params)
{
const PxU32* bits = bitmap.getWords();
if(bits)
{
const PxU32 lastSetBit = bitmap.findLast();
for(PxU32 w = 0; w <= lastSetBit >> 5; ++w)
{
for(PxU32 b = bits[w]; b; b &= b-1)
{
const PxU32 index = PxU32(w<<5|PxLowestSetBit(b));
FunctionT::processEntry(params, index);
}
}
}
}
/*static void shuffle(PxArray<PxU32>& handles)
{
PxU32 nb = handles.size();
PxU32* data = handles.begin();
for(PxU32 i=0;i<nb*10;i++)
{
PxU32 id0 = rand() % nb;
PxU32 id1 = rand() % nb;
PxSwap(data[id0], data[id1]);
}
}*/
void HighLevelBroadPhaseAPI::update(PxBaseTask* continuation)
{
PX_PROFILE_ZONE("HighLevelBroadPhaseAPI::update", mContextID);
{
PX_PROFILE_ZONE("resetOrClear", mContextID);
mAddedHandles.resetOrClear();
mUpdatedHandles.resetOrClear();
mRemovedHandles.resetOrClear();
}
{
{
PX_PROFILE_ZONE("iterateBitmap added", mContextID);
iterateBitmap<HandleTest_Add>(mAddedHandleMap, *this);
}
{
PX_PROFILE_ZONE("iterateBitmap updated", mContextID);
iterateBitmap<HandleTest_Update>(mUpdatedHandleMap, *this);
}
{
PX_PROFILE_ZONE("iterateBitmap removed", mContextID);
iterateBitmap<HandleTest_Remove>(mRemovedHandleMap, *this);
}
}
// PT: call the low-level BP API
{
PX_PROFILE_ZONE("BP update", mContextID);
/* if(1) // Suffle test
{
shuffle(mAddedHandles);
shuffle(mUpdatedHandles);
shuffle(mRemovedHandles);
}*/
const PxBroadPhaseUpdateData updateData(
mAddedHandles.begin(), mAddedHandles.size(),
mUpdatedHandles.begin(), mUpdatedHandles.size(),
mRemovedHandles.begin(), mRemovedHandles.size(),
mBounds, mGroups, mDistances,
mCapacity);
mBroadPhase.update(updateData, continuation);
}
{
PX_PROFILE_ZONE("clear bitmaps", mContextID);
mAddedHandleMap.clear();
mRemovedHandleMap.clear();
mUpdatedHandleMap.clear();
}
}
void HighLevelBroadPhaseAPI::fetchResults(PxBroadPhaseResults& results)
{
PX_PROFILE_ZONE("HighLevelBroadPhaseAPI::fetchResults", mContextID);
mBroadPhase.fetchResults(results);
}
PxAABBManager* physx::PxCreateAABBManager(PxBroadPhase& bp)
{
// PT: make sure we cannot link a bp to multiple managers
ImmCPUBP& baseBP = static_cast<ImmCPUBP&>(bp);
if(baseBP.mAABBManager)
return NULL;
return PX_NEW(HighLevelBroadPhaseAPI)(bp);
}
| 95,660 | C++ | 34.104954 | 243 | 0.740268 |
NVIDIA-Omniverse/PhysX/physx/source/filebuf/include/PsFileBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 PSFILEBUFFER_PSFILEBUFFER_H
#define PSFILEBUFFER_PSFILEBUFFER_H
#include "filebuf/PxFileBuf.h"
#include "foundation/PxUserAllocated.h"
#include <stdio.h>
namespace physx
{
namespace general_PxIOStream2
{
//Use this class if you want to use your own allocator
class PxFileBufferBase : public PxFileBuf
{
public:
PxFileBufferBase(const char *fileName,OpenMode mode)
{
mOpenMode = mode;
mFph = NULL;
mFileLength = 0;
mSeekRead = 0;
mSeekWrite = 0;
mSeekCurrent = 0;
switch ( mode )
{
case OPEN_READ_ONLY:
mFph = fopen(fileName,"rb");
break;
case OPEN_WRITE_ONLY:
mFph = fopen(fileName,"wb");
break;
case OPEN_READ_WRITE_NEW:
mFph = fopen(fileName,"wb+");
break;
case OPEN_READ_WRITE_EXISTING:
mFph = fopen(fileName,"rb+");
break;
case OPEN_FILE_NOT_FOUND:
break;
}
if ( mFph )
{
fseek(mFph,0L,SEEK_END);
mFileLength = static_cast<uint32_t>(ftell(mFph));
fseek(mFph,0L,SEEK_SET);
}
else
{
mOpenMode = OPEN_FILE_NOT_FOUND;
}
}
virtual ~PxFileBufferBase()
{
close();
}
virtual void close()
{
if( mFph )
{
fclose(mFph);
mFph = 0;
}
}
virtual SeekType isSeekable(void) const
{
return mSeekType;
}
virtual uint32_t read(void* buffer, uint32_t size)
{
uint32_t ret = 0;
if ( mFph )
{
setSeekRead();
ret = static_cast<uint32_t>(::fread(buffer,1,size,mFph));
mSeekRead+=ret;
mSeekCurrent+=ret;
}
return ret;
}
virtual uint32_t peek(void* buffer, uint32_t size)
{
uint32_t ret = 0;
if ( mFph )
{
uint32_t loc = tellRead();
setSeekRead();
ret = static_cast<uint32_t>(::fread(buffer,1,size,mFph));
mSeekCurrent+=ret;
seekRead(loc);
}
return ret;
}
virtual uint32_t write(const void* buffer, uint32_t size)
{
uint32_t ret = 0;
if ( mFph )
{
setSeekWrite();
ret = static_cast<uint32_t>(::fwrite(buffer,1,size,mFph));
mSeekWrite+=ret;
mSeekCurrent+=ret;
if ( mSeekWrite > mFileLength )
{
mFileLength = mSeekWrite;
}
}
return ret;
}
virtual uint32_t tellRead(void) const
{
return mSeekRead;
}
virtual uint32_t tellWrite(void) const
{
return mSeekWrite;
}
virtual uint32_t seekRead(uint32_t loc)
{
mSeekRead = loc;
if ( mSeekRead > mFileLength )
{
mSeekRead = mFileLength;
}
return mSeekRead;
}
virtual uint32_t seekWrite(uint32_t loc)
{
mSeekWrite = loc;
if ( mSeekWrite > mFileLength )
{
mSeekWrite = mFileLength;
}
return mSeekWrite;
}
virtual void flush(void)
{
if ( mFph )
{
::fflush(mFph);
}
}
virtual OpenMode getOpenMode(void) const
{
return mOpenMode;
}
virtual uint32_t getFileLength(void) const
{
return mFileLength;
}
private:
// Moves the actual file pointer to the current read location
void setSeekRead(void)
{
if ( mSeekRead != mSeekCurrent && mFph )
{
if ( mSeekRead >= mFileLength )
{
fseek(mFph,0L,SEEK_END);
}
else
{
fseek(mFph,static_cast<long>(mSeekRead),SEEK_SET);
}
mSeekCurrent = mSeekRead = static_cast<uint32_t>(ftell(mFph));
}
}
// Moves the actual file pointer to the current write location
void setSeekWrite(void)
{
if ( mSeekWrite != mSeekCurrent && mFph )
{
if ( mSeekWrite >= mFileLength )
{
fseek(mFph,0L,SEEK_END);
}
else
{
fseek(mFph,static_cast<long>(mSeekWrite),SEEK_SET);
}
mSeekCurrent = mSeekWrite = static_cast<uint32_t>(ftell(mFph));
}
}
FILE *mFph;
uint32_t mSeekRead;
uint32_t mSeekWrite;
uint32_t mSeekCurrent;
uint32_t mFileLength;
SeekType mSeekType;
OpenMode mOpenMode;
};
//Use this class if you want to use PhysX memory allocator
class PsFileBuffer: public PxFileBufferBase, public PxUserAllocated
{
public:
PsFileBuffer(const char *fileName,OpenMode mode): PxFileBufferBase(fileName, mode) {}
};
}
using namespace general_PxIOStream2;
}
#endif // PSFILEBUFFER_PSFILEBUFFER_H
| 5,490 | C | 21.141129 | 86 | 0.684699 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyThreadContext.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 "DyThreadContext.h"
#include "foundation/PxBitUtils.h"
namespace physx
{
namespace Dy
{
ThreadContext::ThreadContext(PxcNpMemBlockPool* memBlockPool):
mFrictionPatchStreamPair(*memBlockPool),
mConstraintBlockManager (*memBlockPool),
mConstraintBlockStream (*memBlockPool),
mNumDifferentBodyConstraints(0),
mNumSelfConstraints(0),
mNumStaticConstraints(0),
mConstraintsPerPartition("ThreadContext::mConstraintsPerPartition"),
mFrictionConstraintsPerPartition("ThreadContext::frictionsConstraintsPerPartition"),
mPartitionNormalizationBitmap("ThreadContext::mPartitionNormalizationBitmap"),
frictionConstraintDescArray("ThreadContext::solverFrictionConstraintArray"),
frictionConstraintBatchHeaders("ThreadContext::frictionConstraintBatchHeaders"),
compoundConstraints("ThreadContext::compoundConstraints"),
orderedContactList("ThreadContext::orderedContactList"),
tempContactList("ThreadContext::tempContactList"),
sortIndexArray("ThreadContext::sortIndexArray"),
mConstraintSize (0),
mAxisConstraintCount(0),
mSelfConstraintBlocks(NULL),
mMaxPartitions(0),
mMaxSolverPositionIterations(0),
mMaxSolverVelocityIterations(0),
mContactDescPtr(NULL),
mFrictionDescPtr(NULL),
mArticulations("ThreadContext::articulations")
{
#if PX_ENABLE_SIM_STATS
mThreadSimStats.clear();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//Defaulted to have space for 16384 bodies
mPartitionNormalizationBitmap.reserve(512);
//Defaulted to have space for 128 partitions (should be more-than-enough)
mConstraintsPerPartition.reserve(128);
}
void ThreadContext::resizeArrays(PxU32 frictionConstraintDescCount, PxU32 articulationCount)
{
// resize resizes smaller arrays to the exact target size, which can generate a lot of churn
frictionConstraintDescArray.forceSize_Unsafe(0);
frictionConstraintDescArray.reserve((frictionConstraintDescCount+63)&~63);
mArticulations.forceSize_Unsafe(0);
mArticulations.reserve(PxMax<PxU32>(PxNextPowerOfTwo(articulationCount), 16));
mArticulations.forceSize_Unsafe(articulationCount);
mContactDescPtr = contactConstraintDescArray;
mFrictionDescPtr = frictionConstraintDescArray.begin();
}
void ThreadContext::reset()
{
// TODO: move these to the PxcNpThreadContext
mFrictionPatchStreamPair.reset();
mConstraintBlockStream.reset();
mContactDescPtr = contactConstraintDescArray;
mFrictionDescPtr = frictionConstraintDescArray.begin();
mAxisConstraintCount = 0;
mMaxSolverPositionIterations = 0;
mMaxSolverVelocityIterations = 0;
mNumDifferentBodyConstraints = 0;
mNumSelfConstraints = 0;
mNumStaticConstraints = 0;
mSelfConstraintBlocks = NULL;
mConstraintSize = 0;
}
}
}
| 4,357 | C++ | 38.261261 | 93 | 0.800551 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintsShared.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONSTRAINT_SHARED_H
#define DY_SOLVER_CONSTRAINT_SHARED_H
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DySolverBody.h"
#include "DySolverContact.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
namespace physx
{
namespace Dy
{
PX_FORCE_INLINE static FloatV solveDynamicContacts(SolverContactPoint* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
const FloatVArg invMassA, const FloatVArg invMassB, const FloatVArg angDom0, const FloatVArg angDom1, Vec3V& linVel0_, Vec3V& angState0_,
Vec3V& linVel1_, Vec3V& angState1_, PxF32* PX_RESTRICT forceBuffer)
{
Vec3V linVel0 = linVel0_;
Vec3V angState0 = angState0_;
Vec3V linVel1 = linVel1_;
Vec3V angState1 = angState1_;
FloatV accumulatedNormalImpulse = FZero();
const Vec3V delLinVel0 = V3Scale(contactNormal, invMassA);
const Vec3V delLinVel1 = V3Scale(contactNormal, invMassB);
for(PxU32 i=0;i<nbContactPoints;i++)
{
SolverContactPoint& c = contacts[i];
PxPrefetchLine(&contacts[i], 128);
const Vec3V raXn = Vec3V_From_Vec4V(c.raXn_velMultiplierW);
const Vec3V rbXn = Vec3V_From_Vec4V(c.rbXn_maxImpulseW);
const FloatV appliedForce = FLoad(forceBuffer[i]);
const FloatV velMultiplier = c.getVelMultiplier();
const FloatV impulseMultiplier = c.getImpulseMultiplier();
/*const FloatV targetVel = c.getTargetVelocity();
const FloatV nScaledBias = c.getScaledBias();*/
const FloatV maxImpulse = c.getMaxImpulse();
//Compute the normal velocity of the constraint.
const Vec3V v0 = V3MulAdd(linVel0, contactNormal, V3Mul(angState0, raXn));
const Vec3V v1 = V3MulAdd(linVel1, contactNormal, V3Mul(angState1, rbXn));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV biasedErr = c.getBiasedErr();//FScaleAdd(targetVel, velMultiplier, nScaledBias);
//KS - clamp the maximum force
const FloatV _deltaF = FMax(FNegScaleSub(normalVel, velMultiplier, biasedErr), FNeg(appliedForce));
const FloatV _newForce = FAdd(FMul(impulseMultiplier, appliedForce), _deltaF);
const FloatV newForce = FMin(_newForce, maxImpulse);
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1);
angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0);
angState1 = V3NegScaleSub(rbXn, FMul(deltaF, angDom1), angState1);
FStore(newForce, &forceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newForce);
}
linVel0_ = linVel0;
angState0_ = angState0;
linVel1_ = linVel1;
angState1_ = angState1;
return accumulatedNormalImpulse;
}
PX_FORCE_INLINE static FloatV solveStaticContacts(SolverContactPoint* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
const FloatVArg invMassA, const FloatVArg angDom0, Vec3V& linVel0_, Vec3V& angState0_, PxF32* PX_RESTRICT forceBuffer)
{
Vec3V linVel0 = linVel0_;
Vec3V angState0 = angState0_;
FloatV accumulatedNormalImpulse = FZero();
const Vec3V delLinVel0 = V3Scale(contactNormal, invMassA);
for(PxU32 i=0;i<nbContactPoints;i++)
{
SolverContactPoint& c = contacts[i];
PxPrefetchLine(&contacts[i],128);
const Vec3V raXn = Vec3V_From_Vec4V(c.raXn_velMultiplierW);
const FloatV appliedForce = FLoad(forceBuffer[i]);
const FloatV velMultiplier = c.getVelMultiplier();
const FloatV impulseMultiplier = c.getImpulseMultiplier();
/*const FloatV targetVel = c.getTargetVelocity();
const FloatV nScaledBias = c.getScaledBias();*/
const FloatV maxImpulse = c.getMaxImpulse();
const Vec3V v0 = V3MulAdd(linVel0, contactNormal, V3Mul(angState0, raXn));
const FloatV normalVel = V3SumElems(v0);
const FloatV biasedErr = c.getBiasedErr();//FScaleAdd(targetVel, velMultiplier, nScaledBias);
// still lots to do here: using loop pipelining we can interweave this code with the
// above - the code here has a lot of stalls that we would thereby eliminate
const FloatV _deltaF = FMax(FNegScaleSub(normalVel, velMultiplier, biasedErr), FNeg(appliedForce));
const FloatV _newForce = FAdd(FMul(appliedForce, impulseMultiplier), _deltaF);
const FloatV newForce = FMin(_newForce, maxImpulse);
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0);
FStore(newForce, &forceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newForce);
}
linVel0_ = linVel0;
angState0_ = angState0;
return accumulatedNormalImpulse;
}
FloatV solveExtContacts(SolverContactPointExt* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
Vec3V& linVel0, Vec3V& angVel0,
Vec3V& linVel1, Vec3V& angVel1,
Vec3V& li0, Vec3V& ai0,
Vec3V& li1, Vec3V& ai1,
PxF32* PX_RESTRICT appliedForceBuffer);
}
}
#endif
| 6,679 | C | 38.064327 | 140 | 0.76239 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep4.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
using namespace aos;
namespace physx
{
namespace Dy
{
PxcCreateFinalizeSolverContactMethod4 createFinalizeMethods4[3] =
{
createFinalizeSolverContacts4,
createFinalizeSolverContacts4Coulomb1D,
createFinalizeSolverContacts4Coulomb2D
};
inline bool ValidateVec4(const Vec4V v)
{
PX_ALIGN(16, PxVec4 vF);
aos::V4StoreA(v, &vF.x);
return vF.isFinite();
}
static void setupFinalizeSolverConstraints4(PxSolverContactDesc* PX_RESTRICT descs, CorrelationBuffer& c, PxU8* PX_RESTRICT workspace,
PxReal invDtF32, PxReal dtF32, PxReal bounceThresholdF32,
const aos::Vec4VArg invMassScale0, const aos::Vec4VArg invInertiaScale0,
const aos::Vec4VArg invMassScale1, const aos::Vec4VArg invInertiaScale1)
{
//OK, we have a workspace of pre-allocated space to store all 4 descs in. We now need to create the constraints in it
const Vec4V ccdMaxSeparation = aos::V4LoadXYZW(descs[0].maxCCDSeparation, descs[1].maxCCDSeparation, descs[2].maxCCDSeparation, descs[3].maxCCDSeparation);
const Vec4V solverOffsetSlop = aos::V4LoadXYZW(descs[0].offsetSlop, descs[1].offsetSlop, descs[2].offsetSlop, descs[3].offsetSlop);
const Vec4V zero = V4Zero();
const BoolV bFalse = BFFFF();
const BoolV bTrue = BTTTT();
const FloatV fZero = FZero();
const PxU8 flags[4] = { PxU8(descs[0].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[1].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[2].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[3].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0) };
bool hasMaxImpulse = descs[0].hasMaxImpulse || descs[1].hasMaxImpulse || descs[2].hasMaxImpulse || descs[3].hasMaxImpulse;
//The block is dynamic if **any** of the constraints have a non-static body B. This allows us to batch static and non-static constraints but we only get a memory/perf
//saving if all 4 are static. This simplifies the constraint partitioning such that it only needs to care about separating contacts and 1D constraints (which it already does)
bool isDynamic = false;
bool hasKinematic = false;
for(PxU32 a = 0; a < 4; ++a)
{
isDynamic = isDynamic || (descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY);
hasKinematic = hasKinematic || descs[a].bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY;
}
const PxU32 constraintSize = isDynamic ? sizeof(SolverContactBatchPointDynamic4) : sizeof(SolverContactBatchPointBase4);
const PxU32 frictionSize = isDynamic ? sizeof(SolverContactFrictionDynamic4) : sizeof(SolverContactFrictionBase4);
PxU8* PX_RESTRICT ptr = workspace;
const Vec4V dom0 = invMassScale0;
const Vec4V dom1 = invMassScale1;
const Vec4V angDom0 = invInertiaScale0;
const Vec4V angDom1 = invInertiaScale1;
const Vec4V maxPenBias = V4Max(V4LoadXYZW(descs[0].data0->penBiasClamp, descs[1].data0->penBiasClamp,
descs[2].data0->penBiasClamp, descs[3].data0->penBiasClamp),
V4LoadXYZW(descs[0].data1->penBiasClamp, descs[1].data1->penBiasClamp,
descs[2].data1->penBiasClamp, descs[3].data1->penBiasClamp));
const Vec4V restDistance = V4LoadXYZW(descs[0].restDistance, descs[1].restDistance, descs[2].restDistance,
descs[3].restDistance);
//load up velocities
Vec4V linVel00 = V4LoadA(&descs[0].data0->linearVelocity.x);
Vec4V linVel10 = V4LoadA(&descs[1].data0->linearVelocity.x);
Vec4V linVel20 = V4LoadA(&descs[2].data0->linearVelocity.x);
Vec4V linVel30 = V4LoadA(&descs[3].data0->linearVelocity.x);
Vec4V linVel01 = V4LoadA(&descs[0].data1->linearVelocity.x);
Vec4V linVel11 = V4LoadA(&descs[1].data1->linearVelocity.x);
Vec4V linVel21 = V4LoadA(&descs[2].data1->linearVelocity.x);
Vec4V linVel31 = V4LoadA(&descs[3].data1->linearVelocity.x);
Vec4V angVel00 = V4LoadA(&descs[0].data0->angularVelocity.x);
Vec4V angVel10 = V4LoadA(&descs[1].data0->angularVelocity.x);
Vec4V angVel20 = V4LoadA(&descs[2].data0->angularVelocity.x);
Vec4V angVel30 = V4LoadA(&descs[3].data0->angularVelocity.x);
Vec4V angVel01 = V4LoadA(&descs[0].data1->angularVelocity.x);
Vec4V angVel11 = V4LoadA(&descs[1].data1->angularVelocity.x);
Vec4V angVel21 = V4LoadA(&descs[2].data1->angularVelocity.x);
Vec4V angVel31 = V4LoadA(&descs[3].data1->angularVelocity.x);
Vec4V linVelT00, linVelT10, linVelT20;
Vec4V linVelT01, linVelT11, linVelT21;
Vec4V angVelT00, angVelT10, angVelT20;
Vec4V angVelT01, angVelT11, angVelT21;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVelT00, linVelT10, linVelT20);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVelT01, linVelT11, linVelT21);
PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVelT00, angVelT10, angVelT20);
PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVelT01, angVelT11, angVelT21);
const Vec4V vrelX = V4Sub(linVelT00, linVelT01);
const Vec4V vrelY = V4Sub(linVelT10, linVelT11);
const Vec4V vrelZ = V4Sub(linVelT20, linVelT21);
//Load up masses and invInertia
/*const Vec4V sqrtInvMass0 = V4Merge(FLoad(descs[0].data0->sqrtInvMass), FLoad(descs[1].data0->sqrtInvMass), FLoad(descs[2].data0->sqrtInvMass),
FLoad(descs[3].data0->sqrtInvMass));
const Vec4V sqrtInvMass1 = V4Merge(FLoad(descs[0].data1->sqrtInvMass), FLoad(descs[1].data1->sqrtInvMass), FLoad(descs[2].data1->sqrtInvMass),
FLoad(descs[3].data1->sqrtInvMass));*/
const Vec4V invMass0 = V4LoadXYZW(descs[0].data0->invMass, descs[1].data0->invMass, descs[2].data0->invMass, descs[3].data0->invMass);
const Vec4V invMass1 = V4LoadXYZW(descs[0].data1->invMass, descs[1].data1->invMass, descs[2].data1->invMass, descs[3].data1->invMass);
const Vec4V invMass0D0 = V4Mul(dom0, invMass0);
const Vec4V invMass1D1 = V4Mul(dom1, invMass1);
Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column2));
Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column2));
Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column2));
Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column2));
Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column2));
Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column2));
Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column2));
Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column2));
Vec4V invInertia0X0, invInertia0X1, invInertia0X2;
Vec4V invInertia0Y0, invInertia0Y1, invInertia0Y2;
Vec4V invInertia0Z0, invInertia0Z1, invInertia0Z2;
Vec4V invInertia1X0, invInertia1X1, invInertia1X2;
Vec4V invInertia1Y0, invInertia1Y1, invInertia1Y2;
Vec4V invInertia1Z0, invInertia1Z1, invInertia1Z2;
PX_TRANSPOSE_44_34(invInertia00X, invInertia10X, invInertia20X, invInertia30X, invInertia0X0, invInertia0Y0, invInertia0Z0);
PX_TRANSPOSE_44_34(invInertia00Y, invInertia10Y, invInertia20Y, invInertia30Y, invInertia0X1, invInertia0Y1, invInertia0Z1);
PX_TRANSPOSE_44_34(invInertia00Z, invInertia10Z, invInertia20Z, invInertia30Z, invInertia0X2, invInertia0Y2, invInertia0Z2);
PX_TRANSPOSE_44_34(invInertia01X, invInertia11X, invInertia21X, invInertia31X, invInertia1X0, invInertia1Y0, invInertia1Z0);
PX_TRANSPOSE_44_34(invInertia01Y, invInertia11Y, invInertia21Y, invInertia31Y, invInertia1X1, invInertia1Y1, invInertia1Z1);
PX_TRANSPOSE_44_34(invInertia01Z, invInertia11Z, invInertia21Z, invInertia31Z, invInertia1X2, invInertia1Y2, invInertia1Z2);
const FloatV invDt = FLoad(invDtF32);
const FloatV dt = FLoad(dtF32);
const FloatV p8 = FLoad(0.8f);
const Vec4V p84 = V4Splat(p8);
const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32));
const FloatV invDtp8 = FMul(invDt, p8);
const Vec3V bodyFrame00p = V3LoadU(descs[0].bodyFrame0.p);
const Vec3V bodyFrame01p = V3LoadU(descs[1].bodyFrame0.p);
const Vec3V bodyFrame02p = V3LoadU(descs[2].bodyFrame0.p);
const Vec3V bodyFrame03p = V3LoadU(descs[3].bodyFrame0.p);
Vec4V bodyFrame00p4 = Vec4V_From_Vec3V(bodyFrame00p);
Vec4V bodyFrame01p4 = Vec4V_From_Vec3V(bodyFrame01p);
Vec4V bodyFrame02p4 = Vec4V_From_Vec3V(bodyFrame02p);
Vec4V bodyFrame03p4 = Vec4V_From_Vec3V(bodyFrame03p);
Vec4V bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ;
PX_TRANSPOSE_44_34(bodyFrame00p4, bodyFrame01p4, bodyFrame02p4, bodyFrame03p4, bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ);
const Vec3V bodyFrame10p = V3LoadU(descs[0].bodyFrame1.p);
const Vec3V bodyFrame11p = V3LoadU(descs[1].bodyFrame1.p);
const Vec3V bodyFrame12p = V3LoadU(descs[2].bodyFrame1.p);
const Vec3V bodyFrame13p = V3LoadU(descs[3].bodyFrame1.p);
Vec4V bodyFrame10p4 = Vec4V_From_Vec3V(bodyFrame10p);
Vec4V bodyFrame11p4 = Vec4V_From_Vec3V(bodyFrame11p);
Vec4V bodyFrame12p4 = Vec4V_From_Vec3V(bodyFrame12p);
Vec4V bodyFrame13p4 = Vec4V_From_Vec3V(bodyFrame13p);
Vec4V bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ;
PX_TRANSPOSE_44_34(bodyFrame10p4, bodyFrame11p4, bodyFrame12p4, bodyFrame13p4, bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ);
const QuatV bodyFrame00q = QuatVLoadU(&descs[0].bodyFrame0.q.x);
const QuatV bodyFrame01q = QuatVLoadU(&descs[1].bodyFrame0.q.x);
const QuatV bodyFrame02q = QuatVLoadU(&descs[2].bodyFrame0.q.x);
const QuatV bodyFrame03q = QuatVLoadU(&descs[3].bodyFrame0.q.x);
const QuatV bodyFrame10q = QuatVLoadU(&descs[0].bodyFrame1.q.x);
const QuatV bodyFrame11q = QuatVLoadU(&descs[1].bodyFrame1.q.x);
const QuatV bodyFrame12q = QuatVLoadU(&descs[2].bodyFrame1.q.x);
const QuatV bodyFrame13q = QuatVLoadU(&descs[3].bodyFrame1.q.x);
PxU32 frictionPatchWritebackAddrIndex0 = 0;
PxU32 frictionPatchWritebackAddrIndex1 = 0;
PxU32 frictionPatchWritebackAddrIndex2 = 0;
PxU32 frictionPatchWritebackAddrIndex3 = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
PxU32 frictionIndex0 = 0, frictionIndex1 = 0, frictionIndex2 = 0, frictionIndex3 = 0;
//PxU32 contactIndex0 = 0, contactIndex1 = 0, contactIndex2 = 0, contactIndex3 = 0;
//OK, we iterate through all friction patch counts in the constraint patch, building up the constraint list etc.
PxU32 maxPatches = PxMax(descs[0].numFrictionPatches, PxMax(descs[1].numFrictionPatches, PxMax(descs[2].numFrictionPatches, descs[3].numFrictionPatches)));
const Vec4V p1 = V4Splat(FLoad(0.0001f));
const Vec4V orthoThreshold = V4Splat(FLoad(0.70710678f));
PxU32 contact0 = 0, contact1 = 0, contact2 = 0, contact3 = 0;
PxU32 patch0 = 0, patch1 = 0, patch2 = 0, patch3 = 0;
PxU8 flag = 0;
if(hasMaxImpulse)
flag |= SolverContactHeader4::eHAS_MAX_IMPULSE;
bool hasFinished[4];
for(PxU32 i=0;i<maxPatches;i++)
{
hasFinished[0] = i >= descs[0].numFrictionPatches;
hasFinished[1] = i >= descs[1].numFrictionPatches;
hasFinished[2] = i >= descs[2].numFrictionPatches;
hasFinished[3] = i >= descs[3].numFrictionPatches;
frictionIndex0 = hasFinished[0] ? frictionIndex0 : descs[0].startFrictionPatchIndex + i;
frictionIndex1 = hasFinished[1] ? frictionIndex1 : descs[1].startFrictionPatchIndex + i;
frictionIndex2 = hasFinished[2] ? frictionIndex2 : descs[2].startFrictionPatchIndex + i;
frictionIndex3 = hasFinished[3] ? frictionIndex3 : descs[3].startFrictionPatchIndex + i;
const PxU32 clampedContacts0 = hasFinished[0] ? 0 : c.frictionPatchContactCounts[frictionIndex0];
const PxU32 clampedContacts1 = hasFinished[1] ? 0 : c.frictionPatchContactCounts[frictionIndex1];
const PxU32 clampedContacts2 = hasFinished[2] ? 0 : c.frictionPatchContactCounts[frictionIndex2];
const PxU32 clampedContacts3 = hasFinished[3] ? 0 : c.frictionPatchContactCounts[frictionIndex3];
const PxU32 firstPatch0 = c.correlationListHeads[frictionIndex0];
const PxU32 firstPatch1 = c.correlationListHeads[frictionIndex1];
const PxU32 firstPatch2 = c.correlationListHeads[frictionIndex2];
const PxU32 firstPatch3 = c.correlationListHeads[frictionIndex3];
const PxContactPoint* contactBase0 = descs[0].contacts + c.contactPatches[firstPatch0].start;
const PxContactPoint* contactBase1 = descs[1].contacts + c.contactPatches[firstPatch1].start;
const PxContactPoint* contactBase2 = descs[2].contacts + c.contactPatches[firstPatch2].start;
const PxContactPoint* contactBase3 = descs[3].contacts + c.contactPatches[firstPatch3].start;
const Vec4V restitution = V4Neg(V4LoadXYZW(contactBase0->restitution, contactBase1->restitution, contactBase2->restitution,
contactBase3->restitution));
const Vec4V damping = V4LoadXYZW(contactBase0->damping, contactBase1->damping, contactBase2->damping, contactBase3->damping);
SolverContactHeader4* PX_RESTRICT header = reinterpret_cast<SolverContactHeader4*>(ptr);
ptr += sizeof(SolverContactHeader4);
header->flags[0] = flags[0];
header->flags[1] = flags[1];
header->flags[2] = flags[2];
header->flags[3] = flags[3];
header->flag = flag;
PxU32 totalContacts = PxMax(clampedContacts0, PxMax(clampedContacts1, PxMax(clampedContacts2, clampedContacts3)));
Vec4V* PX_RESTRICT appliedNormalForces = reinterpret_cast<Vec4V*>(ptr);
ptr += sizeof(Vec4V)*totalContacts;
PxMemZero(appliedNormalForces, sizeof(Vec4V) * totalContacts);
header->numNormalConstr = PxTo8(totalContacts);
header->numNormalConstr0 = PxTo8(clampedContacts0);
header->numNormalConstr1 = PxTo8(clampedContacts1);
header->numNormalConstr2 = PxTo8(clampedContacts2);
header->numNormalConstr3 = PxTo8(clampedContacts3);
//header->sqrtInvMassA = sqrtInvMass0;
//header->sqrtInvMassB = sqrtInvMass1;
header->invMass0D0 = invMass0D0;
header->invMass1D1 = invMass1D1;
header->angDom0 = angDom0;
header->angDom1 = angDom1;
header->shapeInteraction[0] = getInteraction(descs[0]); header->shapeInteraction[1] = getInteraction(descs[1]);
header->shapeInteraction[2] = getInteraction(descs[2]); header->shapeInteraction[3] = getInteraction(descs[3]);
Vec4V* maxImpulse = reinterpret_cast<Vec4V*>(ptr + constraintSize * totalContacts);
header->restitution = restitution;
Vec4V normal0 = V4LoadA(&contactBase0->normal.x);
Vec4V normal1 = V4LoadA(&contactBase1->normal.x);
Vec4V normal2 = V4LoadA(&contactBase2->normal.x);
Vec4V normal3 = V4LoadA(&contactBase3->normal.x);
Vec4V normalX, normalY, normalZ;
PX_TRANSPOSE_44_34(normal0, normal1, normal2, normal3, normalX, normalY, normalZ);
PX_ASSERT(ValidateVec4(normalX));
PX_ASSERT(ValidateVec4(normalY));
PX_ASSERT(ValidateVec4(normalZ));
header->normalX = normalX;
header->normalY = normalY;
header->normalZ = normalZ;
const Vec4V norVel0 = V4MulAdd(normalZ, linVelT20, V4MulAdd(normalY, linVelT10, V4Mul(normalX, linVelT00)));
const Vec4V norVel1 = V4MulAdd(normalZ, linVelT21, V4MulAdd(normalY, linVelT11, V4Mul(normalX, linVelT01)));
const Vec4V relNorVel = V4Sub(norVel0, norVel1);
//For all correlation heads - need to pull this out I think
//OK, we have a counter for all our patches...
PxU32 finished = (PxU32(hasFinished[0])) |
((PxU32(hasFinished[1])) << 1) |
((PxU32(hasFinished[2])) << 2) |
((PxU32(hasFinished[3])) << 3);
CorrelationListIterator iter0(c, firstPatch0);
CorrelationListIterator iter1(c, firstPatch1);
CorrelationListIterator iter2(c, firstPatch2);
CorrelationListIterator iter3(c, firstPatch3);
//PxU32 contact0, contact1, contact2, contact3;
//PxU32 patch0, patch1, patch2, patch3;
if(!hasFinished[0])
iter0.nextContact(patch0, contact0);
if(!hasFinished[1])
iter1.nextContact(patch1, contact1);
if(!hasFinished[2])
iter2.nextContact(patch2, contact2);
if(!hasFinished[3])
iter3.nextContact(patch3, contact3);
PxU8* p = ptr;
PxU32 contactCount = 0;
PxU32 newFinished =
( PxU32(hasFinished[0] || !iter0.hasNextContact())) |
((PxU32(hasFinished[1] || !iter1.hasNextContact())) << 1) |
((PxU32(hasFinished[2] || !iter2.hasNextContact())) << 2) |
((PxU32(hasFinished[3] || !iter3.hasNextContact())) << 3);
// finished flags are used to be able to handle pairs with varying number
// of contact points in the same loop
BoolV bFinished = BLoad(hasFinished);
while(finished != 0xf)
{
finished = newFinished;
++contactCount;
PxPrefetchLine(p, 384);
PxPrefetchLine(p, 512);
PxPrefetchLine(p, 640);
SolverContactBatchPointBase4* PX_RESTRICT solverContact = reinterpret_cast<SolverContactBatchPointBase4*>(p);
p += constraintSize;
const PxContactPoint& con0 = descs[0].contacts[c.contactPatches[patch0].start + contact0];
const PxContactPoint& con1 = descs[1].contacts[c.contactPatches[patch1].start + contact1];
const PxContactPoint& con2 = descs[2].contacts[c.contactPatches[patch2].start + contact2];
const PxContactPoint& con3 = descs[3].contacts[c.contactPatches[patch3].start + contact3];
//Now we need to splice these 4 contacts into a single structure
{
Vec4V point0 = V4LoadA(&con0.point.x);
Vec4V point1 = V4LoadA(&con1.point.x);
Vec4V point2 = V4LoadA(&con2.point.x);
Vec4V point3 = V4LoadA(&con3.point.x);
Vec4V pointX, pointY, pointZ;
PX_TRANSPOSE_44_34(point0, point1, point2, point3, pointX, pointY, pointZ);
PX_ASSERT(ValidateVec4(pointX));
PX_ASSERT(ValidateVec4(pointY));
PX_ASSERT(ValidateVec4(pointZ));
Vec4V cTargetVel0 = V4LoadA(&con0.targetVel.x);
Vec4V cTargetVel1 = V4LoadA(&con1.targetVel.x);
Vec4V cTargetVel2 = V4LoadA(&con2.targetVel.x);
Vec4V cTargetVel3 = V4LoadA(&con3.targetVel.x);
Vec4V cTargetVelX, cTargetVelY, cTargetVelZ;
PX_TRANSPOSE_44_34(cTargetVel0, cTargetVel1, cTargetVel2, cTargetVel3, cTargetVelX, cTargetVelY, cTargetVelZ);
const Vec4V separation = V4LoadXYZW(con0.separation, con1.separation, con2.separation, con3.separation);
const Vec4V cTargetNorVel = V4MulAdd(cTargetVelX, normalX, V4MulAdd(cTargetVelY, normalY, V4Mul(cTargetVelZ, normalZ)));
const Vec4V raX = V4Sub(pointX, bodyFrame0pX);
const Vec4V raY = V4Sub(pointY, bodyFrame0pY);
const Vec4V raZ = V4Sub(pointZ, bodyFrame0pZ);
const Vec4V rbX = V4Sub(pointX, bodyFrame1pX);
const Vec4V rbY = V4Sub(pointY, bodyFrame1pY);
const Vec4V rbZ = V4Sub(pointZ, bodyFrame1pZ);
/*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);
rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/
PX_ASSERT(ValidateVec4(raX));
PX_ASSERT(ValidateVec4(raY));
PX_ASSERT(ValidateVec4(raZ));
PX_ASSERT(ValidateVec4(rbX));
PX_ASSERT(ValidateVec4(rbY));
PX_ASSERT(ValidateVec4(rbZ));
//raXn = cross(ra, normal) which = Vec3V( a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x);
Vec4V raXnX = V4NegMulSub(raZ, normalY, V4Mul(raY, normalZ));
Vec4V raXnY = V4NegMulSub(raX, normalZ, V4Mul(raZ, normalX));
Vec4V raXnZ = V4NegMulSub(raY, normalX, V4Mul(raX, normalY));
Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ));
Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX));
Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY));
Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
Vec4V relAng = V4Sub(dotRaXnAngVel0, dotRbXnAngVel1);
const Vec4V slop = V4Mul(solverOffsetSlop, V4Max(V4Sel(V4IsEq(relNorVel, zero), V4Splat(FMax()), V4Div(relAng, relNorVel)), V4One()));
raXnX = V4Sel(V4IsGrtr(slop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(slop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(slop, V4Abs(raXnZ)), zero, raXnZ);
rbXnX = V4Sel(V4IsGrtr(slop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(slop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(slop, V4Abs(rbXnZ)), zero, rbXnZ);
//Re-do this because we need an accurate and updated angular velocity
dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
relAng = V4Sub(dotRaXnAngVel0, dotRbXnAngVel1);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
PX_ASSERT(ValidateVec4(delAngVel0X));
PX_ASSERT(ValidateVec4(delAngVel0Y));
PX_ASSERT(ValidateVec4(delAngVel0Z));
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0X, delAngVel0X, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0Z, delAngVel0Z)));
Vec4V unitResponse = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
Vec4V vrel = V4Add(relNorVel, relAng);
//The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much
if(isDynamic)
{
SolverContactBatchPointDynamic4* PX_RESTRICT dynamicContact = static_cast<SolverContactBatchPointDynamic4*>(solverContact);
Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
PX_ASSERT(ValidateVec4(delAngVel1X));
PX_ASSERT(ValidateVec4(delAngVel1Y));
PX_ASSERT(ValidateVec4(delAngVel1Z));
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1X, delAngVel1X, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1Z, delAngVel1Z)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
unitResponse = V4Add(unitResponse, resp1);
//These are for dynamic-only contacts.
dynamicContact->rbXnX = delAngVel1X;
dynamicContact->rbXnY = delAngVel1Y;
dynamicContact->rbXnZ = delAngVel1Z;
}
const Vec4V penetration = V4Sub(separation, restDistance);
const Vec4V penInvDtPt8 = V4Max(maxPenBias, V4Scale(penetration, invDtp8));
//..././....
const BoolV isCompliant = V4IsGrtr(restitution, zero);
const Vec4V rdt = V4Scale(restitution, dt);
const Vec4V a = V4Scale(V4Add(damping, rdt), dt);
const Vec4V b = V4Scale(V4Mul(restitution, penetration), dt);
const Vec4V x = V4Recip(V4MulAdd(a, unitResponse, V4One()));
const Vec4V velMultiplier = V4Sel(isCompliant, V4Mul(x, a), V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero));
const Vec4V impulseMultiplier = V4Sub(V4One(), V4Sel(isCompliant, x, zero));
Vec4V scaledBias = V4Mul(penInvDtPt8, velMultiplier);
const Vec4V penetrationInvDt = V4Scale(penetration, invDt);
const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(zero, restitution), V4IsGrtr(bounceThreshold, vrel)),
V4IsGrtr(V4Neg(vrel), penetrationInvDt));
const BoolV ccdSeparationCondition = V4IsGrtrOrEq(ccdMaxSeparation, penetration);
scaledBias = V4Neg(V4Sel(isCompliant, V4Mul(x, b), V4Sel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias)));
const Vec4V targetVelocity = V4Mul(V4Add(V4Sub(cTargetNorVel, vrel), V4Sel(isGreater2, V4Mul(vrel, restitution), zero)), velMultiplier);
const Vec4V biasedErr = V4Add(targetVelocity, scaledBias);
//These values are present for static and dynamic contacts
solverContact->raXnX = delAngVel0X;
solverContact->raXnY = delAngVel0Y;
solverContact->raXnZ = delAngVel0Z;
solverContact->velMultiplier = V4Sel(bFinished, zero, velMultiplier);
solverContact->biasedErr = V4Sel(bFinished, zero, biasedErr);
solverContact->impulseMultiplier = impulseMultiplier;
//solverContact->scaledBias = V4Max(zero, scaledBias);
solverContact->scaledBias = V4Sel(BOr(bFinished, isCompliant), zero, V4Sel(isGreater2, scaledBias, V4Max(zero, scaledBias)));
if(hasMaxImpulse)
{
maxImpulse[contactCount-1] = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse),
FLoad(con3.maxImpulse));
}
}
// update the finished flags
if (!(finished & 0x1))
{
iter0.nextContact(patch0, contact0);
newFinished |= PxU32(!iter0.hasNextContact());
}
else
bFinished = BSetX(bFinished, bTrue);
if(!(finished & 0x2))
{
iter1.nextContact(patch1, contact1);
newFinished |= (PxU32(!iter1.hasNextContact()) << 1);
}
else
bFinished = BSetY(bFinished, bTrue);
if(!(finished & 0x4))
{
iter2.nextContact(patch2, contact2);
newFinished |= (PxU32(!iter2.hasNextContact()) << 2);
}
else
bFinished = BSetZ(bFinished, bTrue);
if(!(finished & 0x8))
{
iter3.nextContact(patch3, contact3);
newFinished |= (PxU32(!iter3.hasNextContact()) << 3);
}
else
bFinished = BSetW(bFinished, bTrue);
}
ptr = p;
if(hasMaxImpulse)
{
ptr += sizeof(Vec4V) * totalContacts;
}
//OK...friction time :-)
Vec4V maxImpulseScale = V4One();
{
const FrictionPatch& frictionPatch0 = c.frictionPatches[frictionIndex0];
const FrictionPatch& frictionPatch1 = c.frictionPatches[frictionIndex1];
const FrictionPatch& frictionPatch2 = c.frictionPatches[frictionIndex2];
const FrictionPatch& frictionPatch3 = c.frictionPatches[frictionIndex3];
const PxU32 anchorCount0 = frictionPatch0.anchorCount;
const PxU32 anchorCount1 = frictionPatch1.anchorCount;
const PxU32 anchorCount2 = frictionPatch2.anchorCount;
const PxU32 anchorCount3 = frictionPatch3.anchorCount;
const PxU32 clampedAnchorCount0 = hasFinished[0] || (contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount0;
const PxU32 clampedAnchorCount1 = hasFinished[1] || (contactBase1->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount1;
const PxU32 clampedAnchorCount2 = hasFinished[2] || (contactBase2->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount2;
const PxU32 clampedAnchorCount3 = hasFinished[3] || (contactBase3->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount3;
const PxU32 maxAnchorCount = PxMax(clampedAnchorCount0, PxMax(clampedAnchorCount1, PxMax(clampedAnchorCount2, clampedAnchorCount3)));
const PxReal coefficient0 = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount0 == 2) ? 0.5f : 1.f;
const PxReal coefficient1 = (contactBase1->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount1 == 2) ? 0.5f : 1.f;
const PxReal coefficient2 = (contactBase2->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount2 == 2) ? 0.5f : 1.f;
const PxReal coefficient3 = (contactBase3->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount3 == 2) ? 0.5f : 1.f;
const Vec4V staticFriction = V4LoadXYZW(contactBase0->staticFriction*coefficient0, contactBase1->staticFriction*coefficient1,
contactBase2->staticFriction*coefficient2, contactBase3->staticFriction*coefficient3);
const Vec4V dynamicFriction = V4LoadXYZW(contactBase0->dynamicFriction*coefficient0, contactBase1->dynamicFriction*coefficient1,
contactBase2->dynamicFriction*coefficient2, contactBase3->dynamicFriction*coefficient3);
PX_ASSERT(totalContacts == contactCount);
header->dynamicFriction = dynamicFriction;
header->staticFriction = staticFriction;
//if(clampedAnchorCount0 != clampedAnchorCount1 || clampedAnchorCount0 != clampedAnchorCount2 || clampedAnchorCount0 != clampedAnchorCount3)
// PxDebugBreak();
//const bool haveFriction = maxAnchorCount != 0;
header->numFrictionConstr = PxTo8(maxAnchorCount*2);
header->numFrictionConstr0 = PxTo8(clampedAnchorCount0*2);
header->numFrictionConstr1 = PxTo8(clampedAnchorCount1*2);
header->numFrictionConstr2 = PxTo8(clampedAnchorCount2*2);
header->numFrictionConstr3 = PxTo8(clampedAnchorCount3*2);
//KS - TODO - extend this if needed
header->type = PxTo8(isDynamic ? DY_SC_TYPE_BLOCK_RB_CONTACT : DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT);
if(maxAnchorCount)
{
//Allocate the shared friction data...
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(ptr);
ptr += sizeof(SolverFrictionSharedData4);
PX_UNUSED(fd);
const BoolV cond = V4IsGrtr(orthoThreshold, V4Abs(normalX));
const Vec4V t0FallbackX = V4Sel(cond, zero, V4Neg(normalY));
const Vec4V t0FallbackY = V4Sel(cond, V4Neg(normalZ), normalX);
const Vec4V t0FallbackZ = V4Sel(cond, normalY, zero);
//const Vec4V dotNormalVrel = V4MulAdd(normalZ, vrelZ, V4MulAdd(normalY, vrelY, V4Mul(normalX, vrelX)));
const Vec4V vrelSubNorVelX = V4NegMulSub(normalX, relNorVel, vrelX);
const Vec4V vrelSubNorVelY = V4NegMulSub(normalY, relNorVel, vrelY);
const Vec4V vrelSubNorVelZ = V4NegMulSub(normalZ, relNorVel, vrelZ);
const Vec4V lenSqvrelSubNorVelZ = V4MulAdd(vrelSubNorVelX, vrelSubNorVelX, V4MulAdd(vrelSubNorVelY, vrelSubNorVelY, V4Mul(vrelSubNorVelZ, vrelSubNorVelZ)));
const BoolV bcon2 = V4IsGrtr(lenSqvrelSubNorVelZ, p1);
Vec4V t0X = V4Sel(bcon2, vrelSubNorVelX, t0FallbackX);
Vec4V t0Y = V4Sel(bcon2, vrelSubNorVelY, t0FallbackY);
Vec4V t0Z = V4Sel(bcon2, vrelSubNorVelZ, t0FallbackZ);
//Now normalize this...
const Vec4V recipLen = V4Rsqrt(V4MulAdd(t0Z, t0Z, V4MulAdd(t0Y, t0Y, V4Mul(t0X, t0X))));
t0X = V4Mul(t0X, recipLen);
t0Y = V4Mul(t0Y, recipLen);
t0Z = V4Mul(t0Z, recipLen);
Vec4V t1X = V4NegMulSub(normalZ, t0Y, V4Mul(normalY, t0Z));
Vec4V t1Y = V4NegMulSub(normalX, t0Z, V4Mul(normalZ, t0X));
Vec4V t1Z = V4NegMulSub(normalY, t0X, V4Mul(normalX, t0Y));
PX_ASSERT((uintptr_t(descs[0].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[1].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[2].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[3].frictionPtr) & 0xF) == 0);
PxU8* PX_RESTRICT writeback0 = descs[0].frictionPtr + frictionPatchWritebackAddrIndex0*sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback1 = descs[1].frictionPtr + frictionPatchWritebackAddrIndex1*sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback2 = descs[2].frictionPtr + frictionPatchWritebackAddrIndex2*sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback3 = descs[3].frictionPtr + frictionPatchWritebackAddrIndex3*sizeof(FrictionPatch);
PxU32 index0 = 0, index1 = 0, index2 = 0, index3 = 0;
fd->broken = bFalse;
fd->frictionBrokenWritebackByte[0] = writeback0;
fd->frictionBrokenWritebackByte[1] = writeback1;
fd->frictionBrokenWritebackByte[2] = writeback2;
fd->frictionBrokenWritebackByte[3] = writeback3;
fd->normalX[0] = t0X;
fd->normalY[0] = t0Y;
fd->normalZ[0] = t0Z;
fd->normalX[1] = t1X;
fd->normalY[1] = t1Y;
fd->normalZ[1] = t1Z;
Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(ptr);
ptr += sizeof(Vec4V)*header->numFrictionConstr;
PxMemZero(appliedForces, sizeof(Vec4V) * header->numFrictionConstr);
for(PxU32 j = 0; j < maxAnchorCount; j++)
{
PxPrefetchLine(ptr, 384);
PxPrefetchLine(ptr, 512);
PxPrefetchLine(ptr, 640);
SolverContactFrictionBase4* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionBase4*>(ptr);
ptr += frictionSize;
SolverContactFrictionBase4* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionBase4*>(ptr);
ptr += frictionSize;
index0 = j < clampedAnchorCount0 ? j : index0;
index1 = j < clampedAnchorCount1 ? j : index1;
index2 = j < clampedAnchorCount2 ? j : index2;
index3 = j < clampedAnchorCount3 ? j : index3;
if(j >= clampedAnchorCount0)
maxImpulseScale = V4SetX(maxImpulseScale, fZero);
if(j >= clampedAnchorCount1)
maxImpulseScale = V4SetY(maxImpulseScale, fZero);
if(j >= clampedAnchorCount2)
maxImpulseScale = V4SetZ(maxImpulseScale, fZero);
if(j >= clampedAnchorCount3)
maxImpulseScale = V4SetW(maxImpulseScale, fZero);
t0X = V4Mul(maxImpulseScale, t0X);
t0Y = V4Mul(maxImpulseScale, t0Y);
t0Z = V4Mul(maxImpulseScale, t0Z);
t1X = V4Mul(maxImpulseScale, t1X);
t1Y = V4Mul(maxImpulseScale, t1Y);
t1Z = V4Mul(maxImpulseScale, t1Z);
const Vec3V body0Anchor0 = V3LoadU(frictionPatch0.body0Anchors[index0]);
const Vec3V body0Anchor1 = V3LoadU(frictionPatch1.body0Anchors[index1]);
const Vec3V body0Anchor2 = V3LoadU(frictionPatch2.body0Anchors[index2]);
const Vec3V body0Anchor3 = V3LoadU(frictionPatch3.body0Anchors[index3]);
Vec4V ra0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame00q, body0Anchor0));
Vec4V ra1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame01q, body0Anchor1));
Vec4V ra2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame02q, body0Anchor2));
Vec4V ra3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame03q, body0Anchor3));
Vec4V raX, raY, raZ;
PX_TRANSPOSE_44_34(ra0, ra1, ra2, ra3, raX, raY, raZ);
/*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);*/
const Vec4V raWorldX = V4Add(raX, bodyFrame0pX);
const Vec4V raWorldY = V4Add(raY, bodyFrame0pY);
const Vec4V raWorldZ = V4Add(raZ, bodyFrame0pZ);
const Vec3V body1Anchor0 = V3LoadU(frictionPatch0.body1Anchors[index0]);
const Vec3V body1Anchor1 = V3LoadU(frictionPatch1.body1Anchors[index1]);
const Vec3V body1Anchor2 = V3LoadU(frictionPatch2.body1Anchors[index2]);
const Vec3V body1Anchor3 = V3LoadU(frictionPatch3.body1Anchors[index3]);
Vec4V rb0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame10q, body1Anchor0));
Vec4V rb1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame11q, body1Anchor1));
Vec4V rb2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame12q, body1Anchor2));
Vec4V rb3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame13q, body1Anchor3));
Vec4V rbX, rbY, rbZ;
PX_TRANSPOSE_44_34(rb0, rb1, rb2, rb3, rbX, rbY, rbZ);
/*rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/
const Vec4V rbWorldX = V4Add(rbX, bodyFrame1pX);
const Vec4V rbWorldY = V4Add(rbY, bodyFrame1pY);
const Vec4V rbWorldZ = V4Add(rbZ, bodyFrame1pZ);
const Vec4V errorX = V4Sub(raWorldX, rbWorldX);
const Vec4V errorY = V4Sub(raWorldY, rbWorldY);
const Vec4V errorZ = V4Sub(raWorldZ, rbWorldZ);
/*errorX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorX)), zero, errorX);
errorY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorY)), zero, errorY);
errorZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorZ)), zero, errorZ);*/
//KS - todo - get this working with per-point friction
const PxU32 contactIndex0 = c.contactID[frictionIndex0][index0];
const PxU32 contactIndex1 = c.contactID[frictionIndex1][index1];
const PxU32 contactIndex2 = c.contactID[frictionIndex2][index2];
const PxU32 contactIndex3 = c.contactID[frictionIndex3][index3];
//Ensure that the contact indices are valid
PX_ASSERT(contactIndex0 == 0xffff || contactIndex0 < descs[0].numContacts);
PX_ASSERT(contactIndex1 == 0xffff || contactIndex1 < descs[1].numContacts);
PX_ASSERT(contactIndex2 == 0xffff || contactIndex2 < descs[2].numContacts);
PX_ASSERT(contactIndex3 == 0xffff || contactIndex3 < descs[3].numContacts);
Vec4V targetVel0 = V4LoadA(contactIndex0 == 0xFFFF ? &contactBase0->targetVel.x : &descs[0].contacts[contactIndex0].targetVel.x);
Vec4V targetVel1 = V4LoadA(contactIndex1 == 0xFFFF ? &contactBase1->targetVel.x : &descs[1].contacts[contactIndex1].targetVel.x);
Vec4V targetVel2 = V4LoadA(contactIndex2 == 0xFFFF ? &contactBase2->targetVel.x : &descs[2].contacts[contactIndex2].targetVel.x);
Vec4V targetVel3 = V4LoadA(contactIndex3 == 0xFFFF ? &contactBase3->targetVel.x : &descs[3].contacts[contactIndex3].targetVel.x);
Vec4V targetVelX, targetVelY, targetVelZ;
PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ);
{
Vec4V raXnX = V4NegMulSub(raZ, t0Y, V4Mul(raY, t0Z));
Vec4V raXnY = V4NegMulSub(raX, t0Z, V4Mul(raZ, t0X));
Vec4V raXnZ = V4NegMulSub(raY, t0X, V4Mul(raX, t0Y));
raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
const Vec4V tVel0 = V4MulAdd(t0Z, linVelT20, V4MulAdd(t0Y, linVelT10, V4Mul(t0X, linVelT00)));
Vec4V vrel = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0)));
if(isDynamic)
{
SolverContactFrictionDynamic4* PX_RESTRICT dynamicF0 = static_cast<SolverContactFrictionDynamic4*>(f0);
Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z));
Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X));
Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y));
rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ);
Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
resp = V4Add(resp, resp1);
dynamicF0->rbXnX = delAngVel1X;
dynamicF0->rbXnY = delAngVel1Y;
dynamicF0->rbXnZ = delAngVel1Z;
const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01)));
const Vec4V vel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, vel1);
}
else if(hasKinematic)
{
const Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z));
const Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X));
const Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y));
const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01)));
const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, dotRbXnAngVel1);
}
const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero));
Vec4V bias = V4Scale(V4MulAdd(t0Z, errorZ, V4MulAdd(t0Y, errorY, V4Mul(t0X, errorX))), invDt);
Vec4V targetVel = V4MulAdd(t0Z, targetVelZ,V4MulAdd(t0Y, targetVelY, V4Mul(t0X, targetVelX)));
targetVel = V4Sub(targetVel, vrel);
f0->targetVelocity = V4Neg(V4Mul(targetVel, velMultiplier));
bias = V4Sub(bias, targetVel);
f0->raXnX = delAngVel0X;
f0->raXnY = delAngVel0Y;
f0->raXnZ = delAngVel0Z;
f0->scaledBias = V4Mul(bias, velMultiplier);
f0->velMultiplier = velMultiplier;
}
{
Vec4V raXnX = V4NegMulSub(raZ, t1Y, V4Mul(raY, t1Z));
Vec4V raXnY = V4NegMulSub(raX, t1Z, V4Mul(raZ, t1X));
Vec4V raXnZ = V4NegMulSub(raY, t1X, V4Mul(raX, t1Y));
raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
const Vec4V tVel0 = V4MulAdd(t1Z, linVelT20, V4MulAdd(t1Y, linVelT10, V4Mul(t1X, linVelT00)));
Vec4V vrel = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0)));
if(isDynamic)
{
SolverContactFrictionDynamic4* PX_RESTRICT dynamicF1 = static_cast<SolverContactFrictionDynamic4*>(f1);
Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z));
Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X));
Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y));
rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ);
Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
resp = V4Add(resp, resp1);
dynamicF1->rbXnX = delAngVel1X;
dynamicF1->rbXnY = delAngVel1Y;
dynamicF1->rbXnZ = delAngVel1Z;
const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01)));
const Vec4V vel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, vel1);
}
else if(hasKinematic)
{
const Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z));
const Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X));
const Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y));
const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01)));
const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, dotRbXnAngVel1);
}
const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero));
Vec4V bias = V4Scale(V4MulAdd(t1Z, errorZ, V4MulAdd(t1Y, errorY, V4Mul(t1X, errorX))), invDt);
Vec4V targetVel = V4MulAdd(t1Z, targetVelZ,V4MulAdd(t1Y, targetVelY, V4Mul(t1X, targetVelX)));
targetVel = V4Sub(targetVel, vrel);
f1->targetVelocity = V4Neg(V4Mul(targetVel, velMultiplier));
bias = V4Sub(bias, targetVel);
f1->raXnX = delAngVel0X;
f1->raXnY = delAngVel0Y;
f1->raXnZ = delAngVel0Z;
f1->scaledBias = V4Mul(bias, velMultiplier);
f1->velMultiplier = velMultiplier;
}
}
frictionPatchWritebackAddrIndex0++;
frictionPatchWritebackAddrIndex1++;
frictionPatchWritebackAddrIndex2++;
frictionPatchWritebackAddrIndex3++;
}
}
}
}
PX_FORCE_INLINE void computeBlockStreamFrictionByteSizes(const CorrelationBuffer& c,
PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches,
PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex)
{
// PT: use local vars to remove LHS
PxU32 numFrictionPatches = 0;
for(PxU32 i = frictionPatchStartIndex; i < frictionPatchEndIndex; i++)
{
//Friction patches.
if(c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
}
PxU32 frictionPatchByteSize = numFrictionPatches*sizeof(FrictionPatch);
_numFrictionPatches = numFrictionPatches;
//16-byte alignment.
_frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f));
}
static bool reserveFrictionBlockStreams(const CorrelationBuffer& c, PxConstraintAllocator& constraintAllocator, PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex,
FrictionPatch*& _frictionPatches, PxU32& numFrictionPatches)
{
//From frictionPatchStream we just need to reserve a single buffer.
PxU32 frictionPatchByteSize = 0;
//Compute the sizes of all the buffers.
computeBlockStreamFrictionByteSizes(c, frictionPatchByteSize, numFrictionPatches, frictionPatchStartIndex, frictionPatchEndIndex);
FrictionPatch* frictionPatches = NULL;
//If the constraint block reservation didn't fail then reserve the friction buffer too.
if(frictionPatchByteSize > 0)
{
frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize));
if(0==frictionPatches || (reinterpret_cast<FrictionPatch*>(-1))==frictionPatches)
{
if(0==frictionPatches)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
frictionPatches=NULL;
}
}
}
_frictionPatches = frictionPatches;
//Return true if neither of the two block reservations failed.
return (0==frictionPatchByteSize || frictionPatches);
}
//The persistent friction patch correlation/allocation will already have happenned as this is per-pair.
//This function just computes the size of the combined solve data.
void computeBlockStreamByteSizes4(PxSolverContactDesc* descs,
PxU32& _solverConstraintByteSize, PxU32* _axisConstraintCount,
const CorrelationBuffer& c)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PxU32 maxPatches = 0;
PxU32 maxFrictionPatches = 0;
PxU32 maxContactCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxU32 maxFrictionCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxMemZero(maxContactCount, sizeof(maxContactCount));
PxMemZero(maxFrictionCount, sizeof(maxFrictionCount));
bool hasMaxImpulse = false;
for(PxU32 a = 0; a < 4; ++a)
{
PxU32 axisConstraintCount = 0;
hasMaxImpulse = hasMaxImpulse || descs[a].hasMaxImpulse;
for(PxU32 i = 0; i < descs[a].numFrictionPatches; i++)
{
PxU32 ind = i + descs[a].startFrictionPatchIndex;
const FrictionPatch& frictionPatch = c.frictionPatches[ind];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0
&& frictionPatch.anchorCount != 0;
//Solver constraint data.
if(c.frictionPatchContactCounts[ind]!=0)
{
maxContactCount[i] = PxMax(c.frictionPatchContactCounts[ind], maxContactCount[i]);
axisConstraintCount += c.frictionPatchContactCounts[ind];
if(haveFriction)
{
const PxU32 fricCount = PxU32(c.frictionPatches[ind].anchorCount) * 2;
maxFrictionCount[i] = PxMax(fricCount, maxFrictionCount[i]);
axisConstraintCount += fricCount;
}
}
}
maxPatches = PxMax(descs[a].numFrictionPatches, maxPatches);
_axisConstraintCount[a] = axisConstraintCount;
}
for(PxU32 a = 0; a < maxPatches; ++a)
{
if(maxFrictionCount[a] > 0)
maxFrictionPatches++;
}
PxU32 totalContacts = 0, totalFriction = 0;
for(PxU32 a = 0; a < maxPatches; ++a)
{
totalContacts += maxContactCount[a];
totalFriction += maxFrictionCount[a];
}
//OK, we have a given number of friction patches, contact points and friction constraints so we can calculate how much memory we need
//Body 2 is considered static if it is either *not dynamic* or *kinematic*
bool hasDynamicBody = false;
for(PxU32 a = 0; a < 4; ++a)
{
hasDynamicBody = hasDynamicBody || ((descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY));
}
const bool isStatic = !hasDynamicBody;
const PxU32 headerSize = sizeof(SolverContactHeader4) * maxPatches + sizeof(SolverFrictionSharedData4) * maxFrictionPatches;
PxU32 constraintSize = isStatic ? (sizeof(SolverContactBatchPointBase4) * totalContacts) + ( sizeof(SolverContactFrictionBase4) * totalFriction) :
(sizeof(SolverContactBatchPointDynamic4) * totalContacts) + (sizeof(SolverContactFrictionDynamic4) * totalFriction);
//Space for the appliedForce buffer
constraintSize += sizeof(Vec4V)*(totalContacts+totalFriction);
//If we have max impulse, reserve a buffer for it
if(hasMaxImpulse)
constraintSize += sizeof(aos::Vec4V) * totalContacts;
_solverConstraintByteSize = ((constraintSize + headerSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
}
static SolverConstraintPrepState::Enum reserveBlockStreams4(PxSolverContactDesc* descs, Dy::CorrelationBuffer& c,
PxU8*& solverConstraint, PxU32* axisConstraintCount,
PxU32& solverConstraintByteSize,
PxConstraintAllocator& constraintAllocator)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(0 == solverConstraintByteSize);
//Compute the sizes of all the buffers.
computeBlockStreamByteSizes4(descs,
solverConstraintByteSize, axisConstraintCount,
c);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if(constraintBlockByteSize > 0)
{
if((constraintBlockByteSize + 16u) > 16384)
return SolverConstraintPrepState::eUNBATCHABLE;
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock)
{
if(0==constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock=NULL;
}
}
}
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if(0==constraintBlockByteSize || constraintBlock)
{
if(solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f));
}
}
return ((0==constraintBlockByteSize || constraintBlock)) ? SolverConstraintPrepState::eSUCCESS : SolverConstraintPrepState::eOUT_OF_MEMORY;
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4(
Dy::CorrelationBuffer& c,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator)
{
PX_ALIGN(16, PxReal invMassScale0[4]);
PX_ALIGN(16, PxReal invMassScale1[4]);
PX_ALIGN(16, PxReal invInertiaScale0[4]);
PX_ALIGN(16, PxReal invInertiaScale1[4]);
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
for (PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
invMassScale0[a] = blockDesc.invMassScales.linear0;
invMassScale1[a] = blockDesc.invMassScales.linear1;
invInertiaScale0[a] = blockDesc.invMassScales.angular0;
invInertiaScale1[a] = blockDesc.invMassScales.angular1;
blockDesc.startFrictionPatchIndex = c.frictionPatchCount;
if (!(blockDesc.disableStrongFriction))
{
bool valid = getFrictionPatches(c, blockDesc.frictionPtr, blockDesc.frictionCount,
blockDesc.bodyFrame0, blockDesc.bodyFrame1, correlationDistance);
if (!valid)
return SolverConstraintPrepState::eUNBATCHABLE;
}
//Create the contact patches
blockDesc.startContactPatchIndex = c.contactPatchCount;
if (!createContactPatches(c, blockDesc.contacts, blockDesc.numContacts, PXC_SAME_NORMAL))
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContactPatches = PxU16(c.contactPatchCount - blockDesc.startContactPatchIndex);
bool overflow = correlatePatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, PXC_SAME_NORMAL,
blockDesc.startContactPatchIndex, blockDesc.startFrictionPatchIndex);
if (overflow)
return SolverConstraintPrepState::eUNBATCHABLE;
growPatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, blockDesc.startFrictionPatchIndex,
frictionOffsetThreshold + blockDescs[a].restDistance);
//Remove the empty friction patches - do we actually need to do this?
for (PxU32 p = c.frictionPatchCount; p > blockDesc.startFrictionPatchIndex; --p)
{
if (c.correlationListHeads[p - 1] == 0xffff)
{
//We have an empty patch...need to bin this one...
for (PxU32 p2 = p; p2 < c.frictionPatchCount; ++p2)
{
c.correlationListHeads[p2 - 1] = c.correlationListHeads[p2];
c.frictionPatchContactCounts[p2 - 1] = c.frictionPatchContactCounts[p2];
}
c.frictionPatchCount--;
}
}
PxU32 numFricPatches = c.frictionPatchCount - blockDesc.startFrictionPatchIndex;
blockDesc.numFrictionPatches = numFricPatches;
}
FrictionPatch* frictionPatchArray[4];
PxU32 frictionPatchCounts[4];
for (PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
const bool successfulReserve = reserveFrictionBlockStreams(c, constraintAllocator, blockDesc.startFrictionPatchIndex, blockDesc.numFrictionPatches + blockDesc.startFrictionPatchIndex,
frictionPatchArray[a],
frictionPatchCounts[a]);
//KS - TODO - how can we recover if we failed to allocate this memory?
if (!successfulReserve)
{
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
}
//At this point, all the friction data has been calculated, the correlation has been done. Provided this was all successful,
//we are ready to create the batched constraints
PxU8* solverConstraint = NULL;
PxU32 solverConstraintByteSize = 0;
{
PxU32 axisConstraintCount[4];
SolverConstraintPrepState::Enum state = reserveBlockStreams4(blockDescs, c,
solverConstraint, axisConstraintCount,
solverConstraintByteSize,
constraintAllocator);
if (state != SolverConstraintPrepState::eSUCCESS)
return state;
for (PxU32 a = 0; a < 4; ++a)
{
FrictionPatch* frictionPatches = frictionPatchArray[a];
PxSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
blockDesc.frictionPtr = reinterpret_cast<PxU8*>(frictionPatches);
blockDesc.frictionCount = PxTo8(frictionPatchCounts[a]);
//Initialise friction buffer.
if (frictionPatches)
{
// PT: TODO: revisit this... not very satisfying
//const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch);
PxPrefetchLine(frictionPatches);
PxPrefetchLine(frictionPatches, 128);
PxPrefetchLine(frictionPatches, 256);
for (PxU32 i = 0; i<blockDesc.numFrictionPatches; i++)
{
if (c.correlationListHeads[blockDesc.startFrictionPatchIndex + i] != CorrelationBuffer::LIST_END)
{
//*frictionPatches++ = c.frictionPatches[blockDesc.startFrictionPatchIndex + i];
PxMemCopy(frictionPatches++, &c.frictionPatches[blockDesc.startFrictionPatchIndex + i], sizeof(FrictionPatch));
//PxPrefetchLine(frictionPatches, 256);
}
}
}
blockDesc.axisConstraintCount += PxTo16(axisConstraintCount[a]);
desc.constraint = solverConstraint;
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize / 16);
desc.writeBack = blockDesc.contactForces;
}
const Vec4V iMassScale0 = V4LoadA(invMassScale0);
const Vec4V iInertiaScale0 = V4LoadA(invInertiaScale0);
const Vec4V iMassScale1 = V4LoadA(invMassScale1);
const Vec4V iInertiaScale1 = V4LoadA(invInertiaScale1);
setupFinalizeSolverConstraints4(blockDescs, c, solverConstraint, invDtF32, dtF32, bounceThresholdF32,
iMassScale0, iInertiaScale0, iMassScale1, iInertiaScale1);
PX_ASSERT((*solverConstraint == DY_SC_TYPE_BLOCK_RB_CONTACT) || (*solverConstraint == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT));
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
}
return SolverConstraintPrepState::eSUCCESS;
}
//This returns 1 of 3 states: success, unbatchable or out-of-memory. If the constraint is unbatchable, we must fall back on 4 separate constraint
//prep calls
SolverConstraintPrepState::Enum createFinalizeSolverContacts4(
PxsContactManagerOutput** cmOutputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator)
{
for (PxU32 a = 0; a < 4; ++a)
{
blockDescs[a].desc->constraintLengthOver16 = 0;
}
PX_ASSERT(cmOutputs[0]->nbContacts && cmOutputs[1]->nbContacts && cmOutputs[2]->nbContacts && cmOutputs[3]->nbContacts);
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
//PxTransform idt = PxTransform(PxIdentity);
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
for (PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
//blockDesc.startContactIndex = buffer.count;
blockDesc.contacts = buffer.contacts + buffer.count;
PxPrefetchLine(desc.bodyA);
PxPrefetchLine(desc.bodyB);
if ((buffer.count + cmOutputs[a]->nbContacts) > 64)
{
return SolverConstraintPrepState::eUNBATCHABLE;
}
bool hasMaxImpulse = false;
bool hasTargetVelocity = false;
//OK...do the correlation here as well...
PxPrefetchLine(blockDescs[a].frictionPtr);
PxPrefetchLine(blockDescs[a].frictionPtr, 64);
PxPrefetchLine(blockDescs[a].frictionPtr, 128);
if (a < 3)
{
PxPrefetchLine(cmOutputs[a]->contactPatches);
PxPrefetchLine(cmOutputs[a]->contactPoints);
}
PxReal invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1;
const PxReal defaultMaxImpulse = PxMin(blockDesc.data0->maxContactImpulse, blockDesc.data1->maxContactImpulse);
PxU32 contactCount = extractContacts(buffer, *cmOutputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, defaultMaxImpulse);
if (contactCount == 0)
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContacts = contactCount;
blockDesc.hasMaxImpulse = hasMaxImpulse;
blockDesc.disableStrongFriction = blockDesc.disableStrongFriction || hasTargetVelocity;
blockDesc.invMassScales.linear0 *= invMassScale0;
blockDesc.invMassScales.linear1 *= invMassScale1;
blockDesc.invMassScales.angular0 *= invInertiaScale0;
blockDesc.invMassScales.angular1 *= invInertiaScale1;
//blockDesc.frictionPtr = &blockDescs[a].frictionPtr;
//blockDesc.frictionCount = blockDescs[a].frictionCount;
}
return createFinalizeSolverContacts4(c, blockDescs,
invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold,
correlationDistance, constraintAllocator);
}
}
}
| 66,380 | C++ | 43.136303 | 185 | 0.737391 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyDynamics.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_DYNAMICS_H
#define DY_DYNAMICS_H
#include "PxvConfig.h"
#include "CmTask.h"
#include "CmPool.h"
#include "PxcThreadCoherentCache.h"
#include "DyThreadContext.h"
#include "PxcConstraintBlockStream.h"
#include "DySolverBody.h"
#include "DyContext.h"
#include "PxsIslandManagerTypes.h"
#include "PxvNphaseImplementationContext.h"
#include "solver/PxSolverDefs.h"
namespace physx
{
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
}
class PxsRigidBody;
struct PxsBodyCore;
class PxsIslandIndices;
struct PxsIndexedInteraction;
struct PxsIndexedContactManager;
struct PxSolverConstraintDesc;
namespace Cm
{
class SpatialVector;
}
namespace Dy
{
class SolverCore;
struct SolverIslandParams;
class DynamicsContext;
#define SOLVER_PARALLEL_METHOD_ARGS \
DynamicsContext& context, \
SolverIslandParams& params, \
IG::IslandSim& islandSim
/**
\brief Solver body pool (array) that enforces 128-byte alignment for base address of array.
\note This reduces cache misses on platforms with 128-byte-size cache lines by aligning the start of the array to the beginning of a cache line.
*/
class SolverBodyPool : public PxArray<PxSolverBody, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverBody> > >
{
PX_NOCOPY(SolverBodyPool)
public:
SolverBodyPool() {}
};
/**
\brief Solver body data pool (array) that enforces 128-byte alignment for base address of array.
\note This reduces cache misses on platforms with 128-byte-size cache lines by aligning the start of the array to the beginning of a cache line.
*/
class SolverBodyDataPool : public PxArray<PxSolverBodyData, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverBodyData> > >
{
PX_NOCOPY(SolverBodyDataPool)
public:
SolverBodyDataPool() {}
};
class SolverConstraintDescPool : public PxArray<PxSolverConstraintDesc, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverConstraintDesc> > >
{
PX_NOCOPY(SolverConstraintDescPool)
public:
SolverConstraintDescPool() { }
};
/**
\brief Encapsulates an island's context
*/
struct IslandContext
{
//The thread context for this island (set in in the island start task, released in the island end task)
ThreadContext* mThreadContext;
PxsIslandIndices mCounts;
};
/**
\brief Encapsules the data used by the constraint solver.
*/
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class DynamicsContext : public Context
{
PX_NOCOPY(DynamicsContext)
public:
DynamicsContext(PxcNpMemBlockPool* memBlockPool,
PxcScratchAllocator& scratchAllocator,
Cm::FlushPool& taskPool,
PxvSimStats& simStats,
PxTaskManager* taskManager,
PxVirtualAllocatorCallback* allocator,
PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager,
PxU64 contextID,
bool enableStabilization,
bool useEnhancedDeterminism,
PxReal maxBiasCoefficient,
bool frictionEveryIteration,
PxReal lengthScale
);
virtual ~DynamicsContext();
// Context
virtual void destroy() PX_OVERRIDE;
virtual void update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask,
PxvNphaseImplementationContext* nPhase, PxU32 maxPatchesPerCM, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& changedHandleMap) PX_OVERRIDE;
virtual void mergeResults() PX_OVERRIDE;
virtual void setSimulationController(PxsSimulationController* simulationController ) PX_OVERRIDE { mSimulationController = simulationController; }
virtual PxSolverType::Enum getSolverType() const PX_OVERRIDE { return PxSolverType::ePGS; }
//~Context
/**
\brief Allocates and returns a thread context object.
\return A thread context.
*/
PX_FORCE_INLINE ThreadContext* getThreadContext() { return mThreadContextPool.get(); }
/**
\brief Returns a thread context to the thread context pool.
\param[in] context The thread context to return to the thread context pool.
*/
void putThreadContext(ThreadContext* context) { mThreadContextPool.put(context); }
PX_FORCE_INLINE Cm::FlushPool& getTaskPool() { return mTaskPool; }
PX_FORCE_INLINE ThresholdStream& getThresholdStream() { return *mThresholdStream; }
PX_FORCE_INLINE PxvSimStats& getSimStats() { return mSimStats; }
PX_FORCE_INLINE PxU32 getKinematicCount() const { return mKinematicCount; }
void updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxU32 maxLinks);
protected:
#if PX_ENABLE_SIM_STATS
void addThreadStats(const ThreadContext::ThreadSimStats& stats);
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
// Solver helper-methods
/**
\brief Computes the unconstrained velocity for a given PxsRigidBody
\param[in] atom The PxsRigidBody
*/
void computeUnconstrainedVelocity(PxsRigidBody* atom) const;
/**
\brief fills in a PxSolverConstraintDesc from an indexed interaction
\param[in,out] desc The PxSolverConstraintDesc
\param[in] constraint The PxsIndexedInteraction
*/
void setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim,
const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset);
void setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex,
const IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxU32 solverBodyOffset);
/**
\brief Compute the unconstrained velocity for set of bodies in parallel. This function may spawn additional tasks.
\param[in] dt The timestep
\param[in] bodyArray The array of body cores
\param[in] originalBodyArray The array of PxsRigidBody
\param[in] nodeIndexArray The array of island node index
\param[in] bodyCount The number of bodies
\param[out] solverBodyPool The pool of solver bodies. These are synced with the corresponding body in bodyArray.
\param[out] solverBodyDataPool The pool of solver body data. These are synced with the corresponding body in bodyArray
\param[out] motionVelocityArray The motion velocities for the bodies
\param[out] maxSolverPositionIterations The maximum number of position iterations requested by any body in the island
\param[out] maxSolverVelocityIterations The maximum number of velocity iterations requested by any body in the island
\param[out] integrateTask The continuation task for any tasks spawned by this function.
*/
void preIntegrationParallel(
PxF32 dt,
PxsBodyCore*const* bodyArray, // INOUT: core body attributes
PxsRigidBody*const* originalBodyArray, // IN: original body atom names (LEGACY - DON'T deref the ptrs!!)
PxU32 const* nodeIndexArray, // IN: island node index
PxU32 bodyCount, // IN: body count
PxSolverBody* solverBodyPool, // IN: solver atom pool (space preallocated)
PxSolverBodyData* solverBodyDataPool,
Cm::SpatialVector* motionVelocityArray, // OUT: motion velocities
PxU32& maxSolverPositionIterations,
PxU32& maxSolverVelocityIterations,
PxBaseTask& integrateTask
);
/**
\brief Solves an island in parallel.
\param[in] params Solver parameter structure
*/
void solveParallel(SolverIslandParams& params, IG::IslandSim& islandSim, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV);
void integrateCoreParallel(SolverIslandParams& params, Cm::SpatialVectorF* deltaV, IG::IslandSim& islandSim);
/**
\brief Resets the thread contexts
*/
void resetThreadContexts();
/**
\brief Returns the scratch memory allocator.
\return The scratch memory allocator.
*/
PX_FORCE_INLINE PxcScratchAllocator& getScratchAllocator() { return mScratchAllocator; }
//Data
/**
\brief Body to represent the world static body.
*/
PX_ALIGN(16, PxSolverBody mWorldSolverBody);
/**
\brief Body data to represent the world static body.
*/
PX_ALIGN(16, PxSolverBodyData mWorldSolverBodyData);
/**
\brief A thread context pool
*/
PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool> mThreadContextPool;
/**
\brief Solver constraint desc array
*/
SolverConstraintDescPool mSolverConstraintDescPool;
/**
\brief Ordered solver constraint desc array (after partitioning)
*/
SolverConstraintDescPool mOrderedSolverConstraintDescPool;
/**
\brief A temporary array of constraint descs used for partitioning
*/
SolverConstraintDescPool mTempSolverConstraintDescPool;
/**
\brief An array of contact constraint batch headers
*/
PxArray<PxConstraintBatchHeader> mContactConstraintBatchHeaders;
/**
\brief Array of motion velocities for all bodies in the scene.
*/
PxArray<Cm::SpatialVector> mMotionVelocityArray;
/**
\brief Array of body core pointers for all bodies in the scene.
*/
PxArray<PxsBodyCore*> mBodyCoreArray;
/**
\brief Array of rigid body pointers for all bodies in the scene.
*/
PxArray<PxsRigidBody*> mRigidBodyArray;
/**
\brief Array of articulation pointers for all articulations in the scene.
*/
PxArray<FeatherstoneArticulation*> mArticulationArray;
/**
\brief Global pool for solver bodies. Kinematic bodies are at the start, and then dynamic bodies
*/
SolverBodyPool mSolverBodyPool;
/**
\brief Global pool for solver body data. Kinematic bodies are at the start, and then dynamic bodies
*/
SolverBodyDataPool mSolverBodyDataPool;
ThresholdStream* mExceededForceThresholdStream[2]; //this store previous and current exceeded force thresholdStream
PxArray<PxU32> mExceededForceThresholdStreamMask;
/**
\brief Interface to the solver core.
\note We currently only support PxsSolverCoreSIMD. Other cores may be added in future releases.
*/
SolverCore* mSolverCore[PxFrictionType::eFRICTION_COUNT];
PxArray<PxU32> mSolverBodyRemapTable; //Remaps from the "active island" index to the index within a solver island
PxArray<PxU32> mNodeIndexArray; //island node index
PxArray<PxsIndexedContactManager> mContactList;
/**
\brief The total number of kinematic bodies in the scene
*/
PxU32 mKinematicCount;
/**
\brief Atomic counter for the number of threshold stream elements.
*/
PxI32 mThresholdStreamOut;
PxsMaterialManager* mMaterialManager;
PxsContactManagerOutputIterator mOutputIterator;
private:
//private:
PxcScratchAllocator& mScratchAllocator;
Cm::FlushPool& mTaskPool;
PxTaskManager* mTaskManager;
PxU32 mCurrentIndex; // this is the index point to the current exceeded force threshold stream
protected:
friend class PxsSolverStartTask;
friend class PxsSolverAticulationsTask;
friend class PxsSolverSetupConstraintsTask;
friend class PxsSolverCreateFinalizeConstraintsTask;
friend class PxsSolverConstraintPartitionTask;
friend class PxsSolverSetupSolveTask;
friend class PxsSolverIntegrateTask;
friend class PxsSolverEndTask;
friend class PxsSolverConstraintPostProcessTask;
friend class PxsForceThresholdTask;
friend class SolverArticulationUpdateTask;
friend void solveParallel(SOLVER_PARALLEL_METHOD_ARGS);
};
#if PX_VC
#pragma warning(pop)
#endif
}
}
#endif
| 13,138 | C | 33.395288 | 181 | 0.752169 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverPFConstraintsBlock.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxFPU.h"
#include "DySolverBody.h"
#include "DySolverContactPF4.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "DyThresholdTable.h"
#include "DySolverContext.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
#include "DySolverContact.h"
#include "DyPGS.h"
namespace physx
{
namespace Dy
{
static void solveContactCoulomb4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
const PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
//const PxU8* PX_RESTRICT endPtr = desc[0].constraint + getConstraintLength(desc[0]);
//TODO - can I avoid this many tests???
while(currPtr < last)
{
SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
Vec4V* appliedForceBuffer = reinterpret_cast<Vec4V*>(currPtr + hdr->frictionOffset + sizeof(SolverFrictionHeader4));
//PX_ASSERT((PxU8*)appliedForceBuffer < endPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
SolverContact4Dynamic* PX_RESTRICT contacts = reinterpret_cast<SolverContact4Dynamic*>(currPtr);
//const Vec4V dominance1 = V4Neg(__dominance1);
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V invMass1D1 = hdr->invMassBDom;
const Vec4V angD0 = hdr->angD0;
const Vec4V angD1 = hdr->angD1;
const Vec4V normalT0 = hdr->normalX;
const Vec4V normalT1 = hdr->normalY;
const Vec4V normalT2 = hdr->normalZ;
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalT0);
const Vec4V normalVel3_tmp2 = V4Mul(linVel1T0, normalT0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalT1, normalVel1_tmp2);
const Vec4V normalVel3_tmp1 = V4MulAdd(linVel1T1, normalT1, normalVel3_tmp2);
Vec4V normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1_tmp1);
Vec4V normalVel3 = V4MulAdd(linVel1T2, normalT2, normalVel3_tmp1);
Vec4V accumDeltaF = vZero;
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContact4Dynamic& c = contacts[i];
PxPrefetchLine((&contacts[i+1]));
PxPrefetchLine((&contacts[i+1]), 128);
PxPrefetchLine((&contacts[i+1]), 256);
PxPrefetchLine((&contacts[i+1]), 384);
const Vec4V appliedForce = c.appliedForce;
const Vec4V velMultiplier = c.velMultiplier;
const Vec4V targetVel = c.targetVelocity;
const Vec4V scaledBias = c.scaledBias;
const Vec4V maxImpulse = c.maxImpulse;
const Vec4V raXnT0 = c.raXnX;
const Vec4V raXnT1 = c.raXnY;
const Vec4V raXnT2 = c.raXnZ;
const Vec4V rbXnT0 = c.rbXnX;
const Vec4V rbXnT1 = c.rbXnY;
const Vec4V rbXnT2 = c.rbXnZ;
const Vec4V normalVel2_tmp2 = V4Mul(raXnT0, angState0T0);
const Vec4V normalVel4_tmp2 = V4Mul(rbXnT0, angState1T0);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnT1, angState0T1, normalVel2_tmp2);
const Vec4V normalVel4_tmp1 = V4MulAdd(rbXnT1, angState1T1, normalVel4_tmp2);
const Vec4V normalVel2 = V4MulAdd(raXnT2, angState0T2, normalVel2_tmp1);
const Vec4V normalVel4 = V4MulAdd(rbXnT2, angState1T2, normalVel4_tmp1);
const Vec4V biasedErr = V4MulAdd(targetVel, velMultiplier, V4Neg(scaledBias));
//Linear component - normal * invMass_dom
const Vec4V normalVel_tmp2(V4Add(normalVel1, normalVel2));
const Vec4V normalVel_tmp1(V4Add(normalVel3, normalVel4));
const Vec4V normalVel = V4Sub(normalVel_tmp2, normalVel_tmp1 );
const Vec4V _deltaF = V4NegMulSub(normalVel, velMultiplier, biasedErr);
const Vec4V nAppliedForce = V4Neg(appliedForce);
const Vec4V _deltaF2 = V4Max(_deltaF, nAppliedForce);
const Vec4V _newAppliedForce(V4Add(appliedForce, _deltaF2));
const Vec4V newAppliedForce = V4Min(_newAppliedForce, maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
normalVel1 = V4MulAdd(invMass0D0, deltaF, normalVel1);
normalVel3 = V4NegMulSub(invMass1D1, deltaF, normalVel3);
accumDeltaF = V4Add(deltaF, accumDeltaF);
const Vec4V deltaFAng0 = V4Mul(angD0, deltaF);
const Vec4V deltaFAng1 = V4Mul(angD1, deltaF);
angState0T0 = V4MulAdd(raXnT0, deltaFAng0, angState0T0);
angState1T0 = V4NegMulSub(rbXnT0, deltaFAng1, angState1T0);
angState0T1 = V4MulAdd(raXnT1, deltaFAng0, angState0T1);
angState1T1 = V4NegMulSub(rbXnT1, deltaFAng1, angState1T1);
angState0T2 = V4MulAdd(raXnT2, deltaFAng0, angState0T2);
angState1T2 = V4NegMulSub(rbXnT2, deltaFAng1, angState1T2);
c.appliedForce = newAppliedForce;
appliedForceBuffer[i] = newAppliedForce;
}
const Vec4V accumDeltaF0 = V4Mul(accumDeltaF, invMass0D0);
const Vec4V accumDeltaF1 = V4Mul(accumDeltaF, invMass1D1);
linVel0T0 = V4MulAdd(normalT0, accumDeltaF0, linVel0T0);
linVel1T0 = V4NegMulSub(normalT0, accumDeltaF1, linVel1T0);
linVel0T1 = V4MulAdd(normalT1, accumDeltaF0, linVel0T1);
linVel1T1 = V4NegMulSub(normalT1, accumDeltaF1, linVel1T1);
linVel0T2 = V4MulAdd(normalT2, accumDeltaF0, linVel0T2);
linVel1T2 = V4NegMulSub(normalT2, accumDeltaF1, linVel1T2);
}
PX_ASSERT(currPtr == last);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
V4StoreA(angState01, &b01.angularState.x);
V4StoreA(angState11, &b11.angularState.x);
V4StoreA(angState21, &b21.angularState.x);
V4StoreA(angState31, &b31.angularState.x);
}
static void solveContactCoulomb4_StaticBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b30 = *desc[3].bodyA;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
const PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
//TODO - can I avoid this many tests???
while(currPtr < last)
{
SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
Vec4V* appliedForceBuffer = reinterpret_cast<Vec4V*>(currPtr + hdr->frictionOffset + sizeof(SolverFrictionHeader4));
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
SolverContact4Base* PX_RESTRICT contacts = reinterpret_cast<SolverContact4Base*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V angD0 = hdr->angD0;
const Vec4V normalT0 = hdr->normalX;
const Vec4V normalT1 = hdr->normalY;
const Vec4V normalT2 = hdr->normalZ;
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalT0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalT1, normalVel1_tmp2);
Vec4V normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1_tmp1);
Vec4V accumDeltaF = vZero;
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContact4Base& c = contacts[i];
PxPrefetchLine((&contacts[i+1]));
PxPrefetchLine((&contacts[i+1]), 128);
PxPrefetchLine((&contacts[i+1]), 256);
const Vec4V appliedForce = c.appliedForce;
const Vec4V velMultiplier = c.velMultiplier;
const Vec4V targetVel = c.targetVelocity;
const Vec4V scaledBias = c.scaledBias;
const Vec4V maxImpulse = c.maxImpulse;
const Vec4V raXnT0 = c.raXnX;
const Vec4V raXnT1 = c.raXnY;
const Vec4V raXnT2 = c.raXnZ;
const Vec4V normalVel2_tmp2 = V4Mul(raXnT0, angState0T0);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnT1, angState0T1, normalVel2_tmp2);
const Vec4V normalVel2 = V4MulAdd(raXnT2, angState0T2, normalVel2_tmp1);
const Vec4V biasedErr = V4MulAdd(targetVel, velMultiplier, V4Neg(scaledBias));
//Linear component - normal * invMass_dom
const Vec4V normalVel(V4Add(normalVel1, normalVel2));
const Vec4V _deltaF = V4NegMulSub(normalVel, velMultiplier, biasedErr);
const Vec4V nAppliedForce = V4Neg(appliedForce);
const Vec4V _deltaF2 = V4Max(_deltaF, nAppliedForce);
const Vec4V _newAppliedForce(V4Add(appliedForce, _deltaF2));
const Vec4V newAppliedForce = V4Min(_newAppliedForce, maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaAngF = V4Mul(deltaF, angD0);
normalVel1 = V4MulAdd(invMass0D0, deltaF, normalVel1);
accumDeltaF = V4Add(deltaF, accumDeltaF);
angState0T0 = V4MulAdd(raXnT0, deltaAngF, angState0T0);
angState0T1 = V4MulAdd(raXnT1, deltaAngF, angState0T1);
angState0T2 = V4MulAdd(raXnT2, deltaAngF, angState0T2);
c.appliedForce = newAppliedForce;
appliedForceBuffer[i] = newAppliedForce;
}
const Vec4V scaledAccumDeltaF = V4Mul(accumDeltaF, invMass0D0);
linVel0T0 = V4MulAdd(normalT0, scaledAccumDeltaF, linVel0T0);
linVel0T1 = V4MulAdd(normalT1, scaledAccumDeltaF, linVel0T1);
linVel0T2 = V4MulAdd(normalT2, scaledAccumDeltaF, linVel0T2);
}
PX_ASSERT(currPtr == last);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
// Write back
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
}
static void solveFriction4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxU8* PX_RESTRICT endPtr = desc[0].constraint + getConstraintLength(desc[0]);
while(currPtr < endPtr)
{
SolverFrictionHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverFrictionHeader4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
Vec4V* appliedImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += hdr->numNormalConstr * sizeof(Vec4V);
PxPrefetchLine(currPtr, 128);
PxPrefetchLine(currPtr,256);
PxPrefetchLine(currPtr,384);
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverFriction4Dynamic* PX_RESTRICT frictions = reinterpret_cast<SolverFriction4Dynamic*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(frictions + hdr->numFrictionConstr);
const PxU32 maxFrictionConstr = numFrictionConstr;
const Vec4V staticFric = hdr->staticFriction;
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V invMass1D1 = hdr->invMassBDom;
const Vec4V angD0 = hdr->angD0;
const Vec4V angD1 = hdr->angD1;
for(PxU32 i=0;i<maxFrictionConstr;i++)
{
SolverFriction4Dynamic& f = frictions[i];
PxPrefetchLine((&f)+1);
PxPrefetchLine((&f)+1,128);
PxPrefetchLine((&f)+1,256);
PxPrefetchLine((&f)+1,384);
const Vec4V appliedImpulse = appliedImpulses[i>>hdr->frictionPerContact];
const Vec4V maxFriction = V4Mul(staticFric, appliedImpulse);
const Vec4V nMaxFriction = V4Neg(maxFriction);
const Vec4V normalX = f.normalX;
const Vec4V normalY = f.normalY;
const Vec4V normalZ = f.normalZ;
const Vec4V raXnX = f.raXnX;
const Vec4V raXnY = f.raXnY;
const Vec4V raXnZ = f.raXnZ;
const Vec4V rbXnX = f.rbXnX;
const Vec4V rbXnY = f.rbXnY;
const Vec4V rbXnZ = f.rbXnZ;
const Vec4V appliedForce(f.appliedForce);
const Vec4V velMultiplier(f.velMultiplier);
const Vec4V targetVel(f.targetVelocity);
//4 x 4 Dot3 products encoded as 8 M44 transposes, 4 MulV and 8 MulAdd ops
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalX);
const Vec4V normalVel2_tmp2 = V4Mul(raXnX, angState0T0);
const Vec4V normalVel3_tmp2 = V4Mul(linVel1T0, normalX);
const Vec4V normalVel4_tmp2 = V4Mul(rbXnX, angState1T0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalY, normalVel1_tmp2);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnY, angState0T1, normalVel2_tmp2);
const Vec4V normalVel3_tmp1 = V4MulAdd(linVel1T1, normalY, normalVel3_tmp2);
const Vec4V normalVel4_tmp1 = V4MulAdd(rbXnY, angState1T1, normalVel4_tmp2);
const Vec4V normalVel1 = V4MulAdd(linVel0T2, normalZ, normalVel1_tmp1);
const Vec4V normalVel2 = V4MulAdd(raXnZ, angState0T2, normalVel2_tmp1);
const Vec4V normalVel3 = V4MulAdd(linVel1T2, normalZ, normalVel3_tmp1);
const Vec4V normalVel4 = V4MulAdd(rbXnZ, angState1T2, normalVel4_tmp1);
const Vec4V normalVel_tmp2 = V4Add(normalVel1, normalVel2);
const Vec4V normalVel_tmp1 = V4Add(normalVel3, normalVel4);
const Vec4V normalVel = V4Sub(normalVel_tmp2, normalVel_tmp1 );
const Vec4V tmp = V4NegMulSub(targetVel, velMultiplier, appliedForce);
Vec4V newAppliedForce = V4MulAdd(normalVel, velMultiplier, tmp);
newAppliedForce = V4Clamp(newAppliedForce,nMaxFriction, maxFriction);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaLinF0 = V4Mul(invMass0D0, deltaF);
const Vec4V deltaLinF1 = V4Mul(invMass1D1, deltaF);
const Vec4V deltaAngF0 = V4Mul(angD0, deltaF);
const Vec4V deltaAngF1 = V4Mul(angD1, deltaF);
linVel0T0 = V4MulAdd(normalX, deltaLinF0, linVel0T0);
linVel1T0 = V4NegMulSub(normalX, deltaLinF1, linVel1T0);
angState0T0 = V4MulAdd(raXnX, deltaAngF0, angState0T0);
angState1T0 = V4NegMulSub(rbXnX, deltaAngF1, angState1T0);
linVel0T1 = V4MulAdd(normalY, deltaLinF0, linVel0T1);
linVel1T1 = V4NegMulSub(normalY, deltaLinF1, linVel1T1);
angState0T1 = V4MulAdd(raXnY, deltaAngF0, angState0T1);
angState1T1 = V4NegMulSub(rbXnY, deltaAngF1, angState1T1);
linVel0T2 = V4MulAdd(normalZ, deltaLinF0, linVel0T2);
linVel1T2 = V4NegMulSub(normalZ, deltaLinF1, linVel1T2);
angState0T2 = V4MulAdd(raXnZ, deltaAngF0, angState0T2);
angState1T2 = V4NegMulSub(rbXnZ, deltaAngF1, angState1T2);
f.appliedForce = newAppliedForce;
}
}
PX_ASSERT(currPtr == endPtr);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
// Write back
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
V4StoreA(angState01, &b01.angularState.x);
V4StoreA(angState11, &b11.angularState.x);
V4StoreA(angState21, &b21.angularState.x);
V4StoreA(angState31, &b31.angularState.x);
}
static void solveFriction4_StaticBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b30 = *desc[3].bodyA;
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxU8* PX_RESTRICT endPtr = desc[0].constraint + getConstraintLength(desc[0]);
while(currPtr < endPtr)
{
SolverFrictionHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverFrictionHeader4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
Vec4V* appliedImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += hdr->numNormalConstr * sizeof(Vec4V);
PxPrefetchLine(currPtr, 128);
PxPrefetchLine(currPtr,256);
PxPrefetchLine(currPtr,384);
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverFriction4Base* PX_RESTRICT frictions = reinterpret_cast<SolverFriction4Base*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(frictions + hdr->numFrictionConstr);
const PxU32 maxFrictionConstr = numFrictionConstr;
const Vec4V staticFric = hdr->staticFriction;
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V angD0 = hdr->angD0;
for(PxU32 i=0;i<maxFrictionConstr;i++)
{
SolverFriction4Base& f = frictions[i];
PxPrefetchLine((&f)+1);
PxPrefetchLine((&f)+1,128);
PxPrefetchLine((&f)+1,256);
const Vec4V appliedImpulse = appliedImpulses[i>>hdr->frictionPerContact];
const Vec4V maxFriction = V4Mul(staticFric, appliedImpulse);
const Vec4V nMaxFriction = V4Neg(maxFriction);
const Vec4V normalX = f.normalX;
const Vec4V normalY = f.normalY;
const Vec4V normalZ = f.normalZ;
const Vec4V raXnX = f.raXnX;
const Vec4V raXnY = f.raXnY;
const Vec4V raXnZ = f.raXnZ;
const Vec4V appliedForce(f.appliedForce);
const Vec4V velMultiplier(f.velMultiplier);
const Vec4V targetVel(f.targetVelocity);
//4 x 4 Dot3 products encoded as 8 M44 transposes, 4 MulV and 8 MulAdd ops
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalX);
const Vec4V normalVel2_tmp2 = V4Mul(raXnX, angState0T0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalY, normalVel1_tmp2);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnY, angState0T1, normalVel2_tmp2);
const Vec4V normalVel1 = V4MulAdd(linVel0T2, normalZ, normalVel1_tmp1);
const Vec4V normalVel2 = V4MulAdd(raXnZ, angState0T2, normalVel2_tmp1);
const Vec4V delLinVel00 = V4Mul(normalX, invMass0D0);
const Vec4V delLinVel10 = V4Mul(normalY, invMass0D0);
const Vec4V normalVel = V4Add(normalVel1, normalVel2);
const Vec4V delLinVel20 = V4Mul(normalZ, invMass0D0);
const Vec4V tmp = V4NegMulSub(targetVel, velMultiplier, appliedForce);
Vec4V newAppliedForce = V4MulAdd(normalVel, velMultiplier, tmp);
newAppliedForce = V4Clamp(newAppliedForce,nMaxFriction, maxFriction);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaAngF0 = V4Mul(angD0, deltaF);
linVel0T0 = V4MulAdd(delLinVel00, deltaF, linVel0T0);
angState0T0 = V4MulAdd(raXnX, deltaAngF0, angState0T0);
linVel0T1 = V4MulAdd(delLinVel10, deltaF, linVel0T1);
angState0T1 = V4MulAdd(raXnY, deltaAngF0, angState0T1);
linVel0T2 = V4MulAdd(delLinVel20, deltaF, linVel0T2);
angState0T2 = V4MulAdd(raXnZ, deltaAngF0, angState0T2);
f.appliedForce = newAppliedForce;
}
}
PX_ASSERT(currPtr == endPtr);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
// Write back
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
}
static void concludeContactCoulomb4(const PxSolverConstraintDesc* desc, SolverContext& /*cache*/)
{
PxU8* PX_RESTRICT cPtr = desc[0].constraint;
const Vec4V zero = V4Zero();
const SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
PxU32 pointStride = firstHeader->type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContact4Dynamic) : sizeof(SolverContact4Base);
while(cPtr < last)
{
const SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
cPtr += sizeof(SolverContactCoulombHeader4);
const PxU32 numNormalConstr = hdr->numNormalConstr;
//if(cPtr < last)
//PxPrefetchLine(cPtr, 512);
PxPrefetchLine(cPtr,128);
PxPrefetchLine(cPtr,256);
PxPrefetchLine(cPtr,384);
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContact4Base *c = reinterpret_cast<SolverContact4Base*>(cPtr);
cPtr += pointStride;
c->scaledBias = V4Max(c->scaledBias, zero);
}
}
PX_ASSERT(cPtr == last);
}
static void writeBackContactCoulomb4(const PxSolverConstraintDesc* desc, SolverContext& cache,
const PxSolverBodyData** PX_RESTRICT bd0, const PxSolverBodyData** PX_RESTRICT bd1)
{
Vec4V normalForceV = V4Zero();
PxU8* PX_RESTRICT cPtr = desc[0].constraint;
PxReal* PX_RESTRICT vForceWriteback0 = reinterpret_cast<PxReal*>(desc[0].writeBack);
PxReal* PX_RESTRICT vForceWriteback1 = reinterpret_cast<PxReal*>(desc[1].writeBack);
PxReal* PX_RESTRICT vForceWriteback2 = reinterpret_cast<PxReal*>(desc[2].writeBack);
PxReal* PX_RESTRICT vForceWriteback3 = reinterpret_cast<PxReal*>(desc[3].writeBack);
const SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
const PxU32 pointStride = firstHeader->type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContact4Dynamic)
: sizeof(SolverContact4Base);
bool writeBackThresholds[4] = {false, false, false, false};
while(cPtr < last)
{
const SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
cPtr += sizeof(SolverContactCoulombHeader4);
writeBackThresholds[0] = hdr->flags[0] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[1] = hdr->flags[1] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[2] = hdr->flags[2] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[3] = hdr->flags[3] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
const PxU32 numNormalConstr = hdr->numNormalConstr;
PxPrefetchLine(cPtr, 256);
PxPrefetchLine(cPtr, 384);
for(PxU32 i=0; i<numNormalConstr; i++)
{
SolverContact4Base* c = reinterpret_cast<SolverContact4Base*>(cPtr);
cPtr += pointStride;
const Vec4V appliedForce = c->appliedForce;
if(vForceWriteback0 && i < hdr->numNormalConstr0)
FStore(V4GetX(appliedForce), vForceWriteback0++);
if(vForceWriteback1 && i < hdr->numNormalConstr1)
FStore(V4GetY(appliedForce), vForceWriteback1++);
if(vForceWriteback2 && i < hdr->numNormalConstr2)
FStore(V4GetZ(appliedForce), vForceWriteback2++);
if(vForceWriteback3 && i < hdr->numNormalConstr3)
FStore(V4GetW(appliedForce), vForceWriteback3++);
normalForceV = V4Add(normalForceV, appliedForce);
}
}
PX_ASSERT(cPtr == last);
PX_ALIGN(16, PxReal nf[4]);
V4StoreA(normalForceV, nf);
//all constraint pointer in descs are the same constraint
Sc::ShapeInteraction** shapeInteractions = reinterpret_cast<SolverContactCoulombHeader4*>(desc[0].constraint)->shapeInteraction;
for(PxU32 a = 0; a < 4; ++a)
{
if(writeBackThresholds[a] && desc[a].linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc[a].linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
nf[a] !=0.f && (bd0[a]->reportThreshold < PX_MAX_REAL || bd1[a]->reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = nf[a];
elt.threshold = PxMin<float>(bd0[a]->reportThreshold, bd1[a]->reportThreshold);
elt.nodeIndexA = PxNodeIndex(bd0[a]->nodeIndex);
elt.nodeIndexB = PxNodeIndex(bd1[a]->nodeIndex);
elt.shapeInteraction = shapeInteractions[a];
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
}
void solveContactCoulombPreBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_Block(desc, cache);
}
void solveContactCoulombPreBlock_Static(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_StaticBlock(desc, cache);
}
void solveContactCoulombPreBlock_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_Block(desc, cache);
concludeContactCoulomb4(desc, cache);
}
void solveContactCoulombPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_StaticBlock(desc, cache);
concludeContactCoulomb4(desc, cache);
}
void solveContactCoulombPreBlock_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_Block(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContactCoulomb4(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveContactCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_StaticBlock(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContactCoulomb4(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveFrictionCoulombPreBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_Block(desc, cache);
}
void solveFrictionCoulombPreBlock_Static(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_StaticBlock(desc, cache);
}
void solveFrictionCoulombPreBlock_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_Block(desc, cache);
}
void solveFrictionCoulombPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_StaticBlock(desc, cache);
}
void solveFrictionCoulombPreBlock_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_Block(desc, cache);
}
void solveFrictionCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_StaticBlock(desc, cache);
}
}
}
| 36,257 | C++ | 36.887147 | 150 | 0.75362 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFrictionCorrelation.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 "PxvConfig.h"
#include "DyCorrelationBuffer.h"
#include "PxsMaterialManager.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxVecMath.h"
#include "GuBounds.h"
using namespace physx;
using namespace aos;
namespace physx
{
namespace Dy
{
static PX_FORCE_INLINE void initContactPatch(CorrelationBuffer::ContactPatchData& patch, PxU16 index, PxReal restitution, PxReal staticFriction, PxReal dynamicFriction,
PxU8 flags)
{
patch.start = index;
patch.count = 1;
patch.next = 0;
patch.flags = flags;
patch.restitution = restitution;
patch.staticFriction = staticFriction;
patch.dynamicFriction = dynamicFriction;
}
bool createContactPatches(CorrelationBuffer& fb, const PxContactPoint* cb, PxU32 contactCount, PxReal normalTolerance)
{
// PT: this rewritten version below doesn't have LHS
PxU32 contactPatchCount = fb.contactPatchCount;
if(contactPatchCount == PxContactBuffer::MAX_CONTACTS)
return false;
if(contactCount>0)
{
CorrelationBuffer::ContactPatchData* PX_RESTRICT currentPatchData = fb.contactPatches + contactPatchCount;
const PxContactPoint* PX_RESTRICT contacts = cb;
initContactPatch(fb.contactPatches[contactPatchCount++], PxTo16(0), contacts[0].restitution,
contacts[0].staticFriction, contacts[0].dynamicFriction, PxU8(contacts[0].materialFlags));
Vec4V minV = V4LoadA(&contacts[0].point.x);
Vec4V maxV = minV;
PxU32 patchIndex = 0;
PxU8 count = 1;
for (PxU32 i = 1; i<contactCount; i++)
{
const PxContactPoint& curContact = contacts[i];
const PxContactPoint& preContact = contacts[patchIndex];
if(curContact.staticFriction == preContact.staticFriction
&& curContact.dynamicFriction == preContact.dynamicFriction
&& curContact.restitution == preContact.restitution
&& curContact.normal.dot(preContact.normal)>=normalTolerance)
{
const Vec4V ptV = V4LoadA(&curContact.point.x);
minV = V4Min(minV, ptV);
maxV = V4Max(maxV, ptV);
count++;
}
else
{
if(contactPatchCount == PxContactBuffer::MAX_CONTACTS)
return false;
patchIndex = i;
currentPatchData->count = count;
count = 1;
StoreBounds(currentPatchData->patchBounds, minV, maxV);
currentPatchData = fb.contactPatches + contactPatchCount;
initContactPatch(fb.contactPatches[contactPatchCount++], PxTo16(i), curContact.restitution,
curContact.staticFriction, curContact.dynamicFriction, PxU8(curContact.materialFlags));
minV = V4LoadA(&curContact.point.x);
maxV = minV;
}
}
if(count!=1)
currentPatchData->count = count;
StoreBounds(currentPatchData->patchBounds, minV, maxV);
}
fb.contactPatchCount = contactPatchCount;
return true;
}
static PX_FORCE_INLINE void initFrictionPatch(FrictionPatch& p, const PxVec3& worldNormal, const PxTransform& body0Pose, const PxTransform& body1Pose,
PxReal restitution, PxReal staticFriction, PxReal dynamicFriction, PxU8 materialFlags)
{
p.body0Normal = body0Pose.rotateInv(worldNormal);
p.body1Normal = body1Pose.rotateInv(worldNormal);
p.relativeQuat = body0Pose.q.getConjugate() * body1Pose.q;
p.anchorCount = 0;
p.broken = 0;
p.staticFriction = staticFriction;
p.dynamicFriction = dynamicFriction;
p.restitution = restitution;
p.materialFlags = materialFlags;
}
bool correlatePatches(CorrelationBuffer& fb,
const PxContactPoint* cb,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxReal normalTolerance,
PxU32 startContactPatchIndex,
PxU32 startFrictionPatchIndex)
{
bool overflow = false;
PxU32 frictionPatchCount = fb.frictionPatchCount;
for(PxU32 i=startContactPatchIndex;i<fb.contactPatchCount;i++)
{
CorrelationBuffer::ContactPatchData &c = fb.contactPatches[i];
const PxVec3 patchNormal = cb[c.start].normal;
PxU32 j=startFrictionPatchIndex;
for(;j<frictionPatchCount && ((patchNormal.dot(fb.frictionPatchWorldNormal[j]) < normalTolerance)
|| fb.frictionPatches[j].restitution != c.restitution|| fb.frictionPatches[j].staticFriction != c.staticFriction ||
fb.frictionPatches[j].dynamicFriction != c.dynamicFriction);j++)
;
if(j==frictionPatchCount)
{
overflow |= j==CorrelationBuffer::MAX_FRICTION_PATCHES;
if(overflow)
continue;
initFrictionPatch(fb.frictionPatches[frictionPatchCount], patchNormal, bodyFrame0, bodyFrame1, c.restitution, c.staticFriction, c.dynamicFriction, c.flags);
fb.frictionPatchWorldNormal[j] = patchNormal;
fb.frictionPatchContactCounts[frictionPatchCount] = c.count;
fb.patchBounds[frictionPatchCount] = c.patchBounds;
fb.contactID[frictionPatchCount][0] = 0xffff;
fb.contactID[frictionPatchCount++][1] = 0xffff;
c.next = CorrelationBuffer::LIST_END;
}
else
{
fb.patchBounds[j].include(c.patchBounds);
fb.frictionPatchContactCounts[j] += c.count;
c.next = PxTo16(fb.correlationListHeads[j]);
}
fb.correlationListHeads[j] = i;
}
fb.frictionPatchCount = frictionPatchCount;
return overflow;
}
// run over the friction patches, trying to find two anchors per patch. If we already have
// anchors that are close, we keep them, which gives us persistent spring behavior
void growPatches(CorrelationBuffer& fb,
const PxContactPoint* cb,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU32 frictionPatchStartIndex,
PxReal frictionOffsetThreshold)
{
for(PxU32 i=frictionPatchStartIndex;i<fb.frictionPatchCount;i++)
{
FrictionPatch& fp = fb.frictionPatches[i];
if (fp.anchorCount == 2 || fb.correlationListHeads[i] == CorrelationBuffer::LIST_END)
{
const PxReal frictionPatchDiagonalSq = fb.patchBounds[i].getDimensions().magnitudeSquared();
const PxReal anchorSqDistance = (fp.body0Anchors[0] - fp.body0Anchors[1]).magnitudeSquared();
//If the squared distance between the anchors is more than a quarter of the patch diagonal, we can keep,
//otherwise the anchors are potentially clustered around a corner so force a rebuild of the patch
if (fb.frictionPatchContactCounts[i] == 0 || (anchorSqDistance * 4.f) >= frictionPatchDiagonalSq)
continue;
fp.anchorCount = 0;
}
PxVec3 worldAnchors[2];
PxU16 anchorCount = 0;
PxReal pointDistSq = 0.0f, dist0, dist1;
// if we have an anchor already, keep it
if(fp.anchorCount == 1)
{
worldAnchors[anchorCount++] = bodyFrame0.transform(fp.body0Anchors[0]);
}
const PxReal eps = 1e-8f;
for(PxU32 patch = fb.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = fb.contactPatches[patch].next)
{
CorrelationBuffer::ContactPatchData& cp = fb.contactPatches[patch];
for(PxU16 j=0;j<cp.count;j++)
{
const PxVec3& worldPoint = cb[cp.start+j].point;
if(cb[cp.start+j].separation < frictionOffsetThreshold)
{
switch(anchorCount)
{
case 0:
fb.contactID[i][0] = PxU16(cp.start+j);
worldAnchors[0] = worldPoint;
anchorCount++;
break;
case 1:
pointDistSq = (worldPoint-worldAnchors[0]).magnitudeSquared();
if (pointDistSq > eps)
{
fb.contactID[i][1] = PxU16(cp.start+j);
worldAnchors[1] = worldPoint;
anchorCount++;
}
break;
default: //case 2
dist0 = (worldPoint-worldAnchors[0]).magnitudeSquared();
dist1 = (worldPoint-worldAnchors[1]).magnitudeSquared();
if (dist0 > dist1)
{
if(dist0 > pointDistSq)
{
fb.contactID[i][1] = PxU16(cp.start+j);
worldAnchors[1] = worldPoint;
pointDistSq = dist0;
}
}
else if (dist1 > pointDistSq)
{
fb.contactID[i][0] = PxU16(cp.start+j);
worldAnchors[0] = worldPoint;
pointDistSq = dist1;
}
}
}
}
}
//PX_ASSERT(anchorCount > 0);
// add the new anchor(s) to the patch
for(PxU32 j = fp.anchorCount; j < anchorCount; j++)
{
fp.body0Anchors[j] = bodyFrame0.transformInv(worldAnchors[j]);
fp.body1Anchors[j] = bodyFrame1.transformInv(worldAnchors[j]);
}
// the block contact solver always reads at least one anchor per patch for performance reasons even if there are no valid patches,
// so we need to initialize this in the unexpected case that we have no anchors
if(anchorCount==0)
fp.body0Anchors[0] = fp.body1Anchors[0] = PxVec3(0);
fp.anchorCount = anchorCount;
}
}
}
}
| 10,042 | C++ | 32.929054 | 168 | 0.723362 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintSetupBlock.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 "DyConstraintPrep.h"
#include "PxsRigidBody.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraint1D4.h"
#include "foundation/PxSort.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
namespace physx
{
namespace Dy
{
namespace
{
void setConstants(PxReal& constant, PxReal& unbiasedConstant, PxReal& velMultiplier, PxReal& impulseMultiplier,
const Px1DConstraint& c, PxReal unitResponse, PxReal minRowResponse, PxReal erp, PxReal dt, PxReal recipdt,
const PxSolverBodyData& b0, const PxSolverBodyData& b1, const bool finished)
{
if(finished)
{
constant = 0.f;
unbiasedConstant = 0.f;
velMultiplier = 0.f;
impulseMultiplier = 0.f;
return;
}
PxReal nv = needsNormalVel(c) ? b0.projectVelocity(c.linear0, c.angular0) - b1.projectVelocity(c.linear1, c.angular1)
: 0;
setSolverConstants(constant, unbiasedConstant, velMultiplier, impulseMultiplier,
c, nv, unitResponse, minRowResponse, erp, dt, recipdt);
}
}
SolverConstraintPrepState::Enum setupSolverConstraint4
(PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows);
SolverConstraintPrepState::Enum setupSolverConstraint4
(SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs,
PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator)
{
//KS - we will never get here with constraints involving articulations so we don't need to stress about those in here
totalRows = 0;
Px1DConstraint allRows[MAX_CONSTRAINT_ROWS * 4];
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
for (PxU32 a = 0; a < 4; ++a)
{
SolverConstraintShaderPrepDesc& shaderDesc = constraintShaderDescs[a];
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
if (!shaderDesc.solverPrep)
return SolverConstraintPrepState::eUNBATCHABLE;
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
PxVec3p unused_ra, unused_rb;
//TAG:solverprepcall
const PxU32 constraintCount = desc.disableConstraint ? 0 : (*shaderDesc.solverPrep)(rows,
desc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
desc.invMassScales,
shaderDesc.constantBlock,
desc.bodyFrame0, desc.bodyFrame1, desc.extendedLimits, unused_ra, unused_rb);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
if (constraintCount == 0)
return SolverConstraintPrepState::eUNBATCHABLE;
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
}
return setupSolverConstraint4(constraintDescs, dt, recipdt, totalRows, allocator, maxRows);
}
SolverConstraintPrepState::Enum setupSolverConstraint4
(PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows)
{
const Vec4V zero = V4Zero();
Px1DConstraint* allSorted[MAX_CONSTRAINT_ROWS * 4];
PxU32 startIndex[4];
PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS * 4];
PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS * 4];
PxU32 numRows = 0;
for (PxU32 a = 0; a < 4; ++a)
{
startIndex[a] = numRows;
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
Px1DConstraint** sorted = allSorted + numRows;
preprocessRows(sorted, desc.rows, angSqrtInvInertia0 + numRows, angSqrtInvInertia1 + numRows, desc.numRows,
desc.data0->sqrtInvInertia, desc.data1->sqrtInvInertia, desc.data0->invMass, desc.data1->invMass,
desc.invMassScales, desc.disablePreprocessing, desc.improvedSlerp);
numRows += desc.numRows;
}
const PxU32 stride = sizeof(SolverConstraint1DDynamic4);
const PxU32 constraintLength = sizeof(SolverConstraint1DHeader4) + stride * maxRows;
//KS - +16 is for the constraint progress counter, which needs to be the last element in the constraint (so that we
//know SPU DMAs have completed)
PxU8* ptr = allocator.reserveConstraintData(constraintLength + 16u);
if(NULL == ptr || (reinterpret_cast<PxU8*>(-1))==ptr)
{
for(PxU32 a = 0; a < 4; ++a)
{
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
desc.desc->constraint = NULL;
setConstraintLength(*desc.desc, 0);
desc.desc->writeBack = desc.writeback;
}
if(NULL==ptr)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept joints detaching/exploding or increase buffer size allocated for constraint prep by increasing PxSceneDesc::maxNbContactDataBlocks.");
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of constraint data. "
"Either accept joints detaching/exploding or simplify constraints.");
ptr=NULL;
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
}
//desc.constraint = ptr;
totalRows = numRows;
for(PxU32 a = 0; a < 4; ++a)
{
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
desc.desc->constraint = ptr;
setConstraintLength(*desc.desc, constraintLength);
desc.desc->writeBack = desc.writeback;
}
const PxReal erp[4] = { 1.0f, 1.0f, 1.0f, 1.0f};
//OK, now we build all 4 constraints into a single set of rows
{
PxU8* currPtr = ptr;
SolverConstraint1DHeader4* header = reinterpret_cast<SolverConstraint1DHeader4*>(currPtr);
currPtr += sizeof(SolverConstraint1DHeader4);
const PxSolverBodyData& bd00 = *constraintDescs[0].data0;
const PxSolverBodyData& bd01 = *constraintDescs[1].data0;
const PxSolverBodyData& bd02 = *constraintDescs[2].data0;
const PxSolverBodyData& bd03 = *constraintDescs[3].data0;
const PxSolverBodyData& bd10 = *constraintDescs[0].data1;
const PxSolverBodyData& bd11 = *constraintDescs[1].data1;
const PxSolverBodyData& bd12 = *constraintDescs[2].data1;
const PxSolverBodyData& bd13 = *constraintDescs[3].data1;
//Load up masses, invInertia, velocity etc.
const Vec4V invMassScale0 = V4LoadXYZW(constraintDescs[0].invMassScales.linear0, constraintDescs[1].invMassScales.linear0,
constraintDescs[2].invMassScales.linear0, constraintDescs[3].invMassScales.linear0);
const Vec4V invMassScale1 = V4LoadXYZW(constraintDescs[0].invMassScales.linear1, constraintDescs[1].invMassScales.linear1,
constraintDescs[2].invMassScales.linear1, constraintDescs[3].invMassScales.linear1);
const Vec4V iMass0 = V4LoadXYZW(bd00.invMass, bd01.invMass, bd02.invMass, bd03.invMass);
const Vec4V iMass1 = V4LoadXYZW(bd10.invMass, bd11.invMass, bd12.invMass, bd13.invMass);
const Vec4V invMass0 = V4Mul(iMass0, invMassScale0);
const Vec4V invMass1 = V4Mul(iMass1, invMassScale1);
const Vec4V invInertiaScale0 = V4LoadXYZW(constraintDescs[0].invMassScales.angular0, constraintDescs[1].invMassScales.angular0,
constraintDescs[2].invMassScales.angular0, constraintDescs[3].invMassScales.angular0);
const Vec4V invInertiaScale1 = V4LoadXYZW(constraintDescs[0].invMassScales.angular1, constraintDescs[1].invMassScales.angular1,
constraintDescs[2].invMassScales.angular1, constraintDescs[3].invMassScales.angular1);
//Velocities
Vec4V linVel00 = V4LoadA(&bd00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&bd10.linearVelocity.x);
Vec4V angVel00 = V4LoadA(&bd00.angularVelocity.x);
Vec4V angVel01 = V4LoadA(&bd10.angularVelocity.x);
Vec4V linVel10 = V4LoadA(&bd01.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&bd11.linearVelocity.x);
Vec4V angVel10 = V4LoadA(&bd01.angularVelocity.x);
Vec4V angVel11 = V4LoadA(&bd11.angularVelocity.x);
Vec4V linVel20 = V4LoadA(&bd02.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&bd12.linearVelocity.x);
Vec4V angVel20 = V4LoadA(&bd02.angularVelocity.x);
Vec4V angVel21 = V4LoadA(&bd12.angularVelocity.x);
Vec4V linVel30 = V4LoadA(&bd03.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&bd13.linearVelocity.x);
Vec4V angVel30 = V4LoadA(&bd03.angularVelocity.x);
Vec4V angVel31 = V4LoadA(&bd13.angularVelocity.x);
Vec4V linVel0T0, linVel0T1, linVel0T2;
Vec4V linVel1T0, linVel1T1, linVel1T2;
Vec4V angVel0T0, angVel0T1, angVel0T2;
Vec4V angVel1T0, angVel1T1, angVel1T2;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2);
PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVel0T0, angVel0T1, angVel0T2);
PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVel1T0, angVel1T1, angVel1T2);
//body world offsets
Vec4V workOffset0 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[0].body0WorldOffset));
Vec4V workOffset1 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[1].body0WorldOffset));
Vec4V workOffset2 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[2].body0WorldOffset));
Vec4V workOffset3 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[3].body0WorldOffset));
Vec4V workOffsetX, workOffsetY, workOffsetZ;
PX_TRANSPOSE_44_34(workOffset0, workOffset1, workOffset2, workOffset3, workOffsetX, workOffsetY, workOffsetZ);
const FloatV dtV = FLoad(dt);
const Vec4V linBreakForce = V4LoadXYZW(constraintDescs[0].linBreakForce, constraintDescs[1].linBreakForce,
constraintDescs[2].linBreakForce, constraintDescs[3].linBreakForce);
const Vec4V angBreakForce = V4LoadXYZW(constraintDescs[0].angBreakForce, constraintDescs[1].angBreakForce,
constraintDescs[2].angBreakForce, constraintDescs[3].angBreakForce);
header->break0 = PxU8((constraintDescs[0].linBreakForce != PX_MAX_F32) || (constraintDescs[0].angBreakForce != PX_MAX_F32));
header->break1 = PxU8((constraintDescs[1].linBreakForce != PX_MAX_F32) || (constraintDescs[1].angBreakForce != PX_MAX_F32));
header->break2 = PxU8((constraintDescs[2].linBreakForce != PX_MAX_F32) || (constraintDescs[2].angBreakForce != PX_MAX_F32));
header->break3 = PxU8((constraintDescs[3].linBreakForce != PX_MAX_F32) || (constraintDescs[3].angBreakForce != PX_MAX_F32));
//OK, I think that's everything loaded in
header->invMass0D0 = invMass0;
header->invMass1D1 = invMass1;
header->angD0 = invInertiaScale0;
header->angD1 = invInertiaScale1;
header->body0WorkOffsetX = workOffsetX;
header->body0WorkOffsetY = workOffsetY;
header->body0WorkOffsetZ = workOffsetZ;
header->count = maxRows;
header->type = DY_SC_TYPE_BLOCK_1D;
header->linBreakImpulse = V4Scale(linBreakForce, dtV);
header->angBreakImpulse = V4Scale(angBreakForce, dtV);
header->count0 = PxTo8(constraintDescs[0].numRows);
header->count1 = PxTo8(constraintDescs[1].numRows);
header->count2 = PxTo8(constraintDescs[2].numRows);
header->count3 = PxTo8(constraintDescs[3].numRows);
//Now we loop over the constraints and build the results...
PxU32 index0 = 0;
PxU32 endIndex0 = constraintDescs[0].numRows - 1;
PxU32 index1 = startIndex[1];
PxU32 endIndex1 = index1 + constraintDescs[1].numRows - 1;
PxU32 index2 = startIndex[2];
PxU32 endIndex2 = index2 + constraintDescs[2].numRows - 1;
PxU32 index3 = startIndex[3];
PxU32 endIndex3 = index3 + constraintDescs[3].numRows - 1;
const FloatV one = FOne();
for(PxU32 a = 0; a < maxRows; ++a)
{
SolverConstraint1DDynamic4* c = reinterpret_cast<SolverConstraint1DDynamic4*>(currPtr);
currPtr += stride;
Px1DConstraint* con0 = allSorted[index0];
Px1DConstraint* con1 = allSorted[index1];
Px1DConstraint* con2 = allSorted[index2];
Px1DConstraint* con3 = allSorted[index3];
Vec4V cangDelta00 = V4LoadA(&angSqrtInvInertia0[index0].x);
Vec4V cangDelta01 = V4LoadA(&angSqrtInvInertia0[index1].x);
Vec4V cangDelta02 = V4LoadA(&angSqrtInvInertia0[index2].x);
Vec4V cangDelta03 = V4LoadA(&angSqrtInvInertia0[index3].x);
Vec4V cangDelta10 = V4LoadA(&angSqrtInvInertia1[index0].x);
Vec4V cangDelta11 = V4LoadA(&angSqrtInvInertia1[index1].x);
Vec4V cangDelta12 = V4LoadA(&angSqrtInvInertia1[index2].x);
Vec4V cangDelta13 = V4LoadA(&angSqrtInvInertia1[index3].x);
index0 = index0 == endIndex0 ? index0 : index0 + 1;
index1 = index1 == endIndex1 ? index1 : index1 + 1;
index2 = index2 == endIndex2 ? index2 : index2 + 1;
index3 = index3 == endIndex3 ? index3 : index3 + 1;
Vec4V driveScale = V4Splat(one);
if (con0->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[0].driveLimitsAreForces)
driveScale = V4SetX(driveScale, FMin(one, dtV));
if (con1->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[1].driveLimitsAreForces)
driveScale = V4SetY(driveScale, FMin(one, dtV));
if (con2->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[2].driveLimitsAreForces)
driveScale = V4SetZ(driveScale, FMin(one, dtV));
if (con3->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[3].driveLimitsAreForces)
driveScale = V4SetW(driveScale, FMin(one, dtV));
Vec4V clin00 = V4LoadA(&con0->linear0.x);
Vec4V clin01 = V4LoadA(&con1->linear0.x);
Vec4V clin02 = V4LoadA(&con2->linear0.x);
Vec4V clin03 = V4LoadA(&con3->linear0.x);
Vec4V cang00 = V4LoadA(&con0->angular0.x);
Vec4V cang01 = V4LoadA(&con1->angular0.x);
Vec4V cang02 = V4LoadA(&con2->angular0.x);
Vec4V cang03 = V4LoadA(&con3->angular0.x);
Vec4V clin0X, clin0Y, clin0Z;
Vec4V cang0X, cang0Y, cang0Z;
PX_TRANSPOSE_44_34(clin00, clin01, clin02, clin03, clin0X, clin0Y, clin0Z);
PX_TRANSPOSE_44_34(cang00, cang01, cang02, cang03, cang0X, cang0Y, cang0Z);
const Vec4V maxImpulse = V4LoadXYZW(con0->maxImpulse, con1->maxImpulse, con2->maxImpulse, con3->maxImpulse);
const Vec4V minImpulse = V4LoadXYZW(con0->minImpulse, con1->minImpulse, con2->minImpulse, con3->minImpulse);
Vec4V angDelta0X, angDelta0Y, angDelta0Z;
PX_TRANSPOSE_44_34(cangDelta00, cangDelta01, cangDelta02, cangDelta03, angDelta0X, angDelta0Y, angDelta0Z);
c->flags[0] = 0;
c->flags[1] = 0;
c->flags[2] = 0;
c->flags[3] = 0;
c->lin0X = clin0X;
c->lin0Y = clin0Y;
c->lin0Z = clin0Z;
c->ang0X = angDelta0X;
c->ang0Y = angDelta0Y;
c->ang0Z = angDelta0Z;
c->ang0WritebackX = cang0X;
c->ang0WritebackY = cang0Y;
c->ang0WritebackZ = cang0Z;
c->minImpulse = V4Mul(minImpulse, driveScale);
c->maxImpulse = V4Mul(maxImpulse, driveScale);
c->appliedForce = zero;
const Vec4V lin0MagSq = V4MulAdd(clin0Z, clin0Z, V4MulAdd(clin0Y, clin0Y, V4Mul(clin0X, clin0X)));
const Vec4V cang0DotAngDelta = V4MulAdd(angDelta0Z, angDelta0Z, V4MulAdd(angDelta0Y, angDelta0Y, V4Mul(angDelta0X, angDelta0X)));
c->flags[0] = 0;
c->flags[1] = 0;
c->flags[2] = 0;
c->flags[3] = 0;
Vec4V unitResponse = V4MulAdd(lin0MagSq, invMass0, V4Mul(cang0DotAngDelta, invInertiaScale0));
Vec4V clin10 = V4LoadA(&con0->linear1.x);
Vec4V clin11 = V4LoadA(&con1->linear1.x);
Vec4V clin12 = V4LoadA(&con2->linear1.x);
Vec4V clin13 = V4LoadA(&con3->linear1.x);
Vec4V cang10 = V4LoadA(&con0->angular1.x);
Vec4V cang11 = V4LoadA(&con1->angular1.x);
Vec4V cang12 = V4LoadA(&con2->angular1.x);
Vec4V cang13 = V4LoadA(&con3->angular1.x);
Vec4V clin1X, clin1Y, clin1Z;
Vec4V cang1X, cang1Y, cang1Z;
PX_TRANSPOSE_44_34(clin10, clin11, clin12, clin13, clin1X, clin1Y, clin1Z);
PX_TRANSPOSE_44_34(cang10, cang11, cang12, cang13, cang1X, cang1Y, cang1Z);
Vec4V angDelta1X, angDelta1Y, angDelta1Z;
PX_TRANSPOSE_44_34(cangDelta10, cangDelta11, cangDelta12, cangDelta13, angDelta1X, angDelta1Y, angDelta1Z);
const Vec4V lin1MagSq = V4MulAdd(clin1Z, clin1Z, V4MulAdd(clin1Y, clin1Y, V4Mul(clin1X, clin1X)));
const Vec4V cang1DotAngDelta = V4MulAdd(angDelta1Z, angDelta1Z, V4MulAdd(angDelta1Y, angDelta1Y, V4Mul(angDelta1X, angDelta1X)));
c->lin1X = clin1X;
c->lin1Y = clin1Y;
c->lin1Z = clin1Z;
c->ang1X = angDelta1X;
c->ang1Y = angDelta1Y;
c->ang1Z = angDelta1Z;
unitResponse = V4Add(unitResponse, V4MulAdd(lin1MagSq, invMass1, V4Mul(cang1DotAngDelta, invInertiaScale1)));
Vec4V linProj0(V4Mul(clin0X, linVel0T0));
Vec4V linProj1(V4Mul(clin1X, linVel1T0));
Vec4V angProj0(V4Mul(cang0X, angVel0T0));
Vec4V angProj1(V4Mul(cang1X, angVel1T0));
linProj0 = V4MulAdd(clin0Y, linVel0T1, linProj0);
linProj1 = V4MulAdd(clin1Y, linVel1T1, linProj1);
angProj0 = V4MulAdd(cang0Y, angVel0T1, angProj0);
angProj1 = V4MulAdd(cang1Y, angVel1T1, angProj1);
linProj0 = V4MulAdd(clin0Z, linVel0T2, linProj0);
linProj1 = V4MulAdd(clin1Z, linVel1T2, linProj1);
angProj0 = V4MulAdd(cang0Z, angVel0T2, angProj0);
angProj1 = V4MulAdd(cang1Z, angVel1T2, angProj1);
const Vec4V projectVel0 = V4Add(linProj0, angProj0);
const Vec4V projectVel1 = V4Add(linProj1, angProj1);
const Vec4V normalVel = V4Sub(projectVel0, projectVel1);
{
const PxVec4& ur = reinterpret_cast<const PxVec4&>(unitResponse);
PxVec4& cConstant = reinterpret_cast<PxVec4&>(c->constant);
PxVec4& cUnbiasedConstant = reinterpret_cast<PxVec4&>(c->unbiasedConstant);
PxVec4& cVelMultiplier = reinterpret_cast<PxVec4&>(c->velMultiplier);
PxVec4& cImpulseMultiplier = reinterpret_cast<PxVec4&>(c->impulseMultiplier);
setConstants(cConstant.x, cUnbiasedConstant.x, cVelMultiplier.x, cImpulseMultiplier.x,
*con0, ur.x, constraintDescs[0].minResponseThreshold, erp[0], dt, recipdt,
*constraintDescs[0].data0, *constraintDescs[0].data1, a >= constraintDescs[0].numRows);
setConstants(cConstant.y, cUnbiasedConstant.y, cVelMultiplier.y, cImpulseMultiplier.y,
*con1, ur.y, constraintDescs[1].minResponseThreshold, erp[1], dt, recipdt,
*constraintDescs[1].data0, *constraintDescs[1].data1, a >= constraintDescs[1].numRows);
setConstants(cConstant.z, cUnbiasedConstant.z, cVelMultiplier.z, cImpulseMultiplier.z,
*con2, ur.z, constraintDescs[2].minResponseThreshold, erp[2], dt, recipdt,
*constraintDescs[2].data0, *constraintDescs[2].data1, a >= constraintDescs[2].numRows);
setConstants(cConstant.w, cUnbiasedConstant.w, cVelMultiplier.w, cImpulseMultiplier.w,
*con3, ur.w, constraintDescs[3].minResponseThreshold, erp[3], dt, recipdt,
*constraintDescs[3].data0, *constraintDescs[3].data1, a >= constraintDescs[3].numRows);
}
const Vec4V velBias = V4Mul(c->velMultiplier, normalVel);
c->constant = V4Add(c->constant, velBias);
c->unbiasedConstant = V4Add(c->unbiasedConstant, velBias);
if(con0->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[0] |= DY_SC_FLAG_OUTPUT_FORCE;
if(con1->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[1] |= DY_SC_FLAG_OUTPUT_FORCE;
if(con2->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[2] |= DY_SC_FLAG_OUTPUT_FORCE;
if(con3->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[3] |= DY_SC_FLAG_OUTPUT_FORCE;
}
*(reinterpret_cast<PxU32*>(currPtr)) = 0;
*(reinterpret_cast<PxU32*>(currPtr + 4)) = 0;
}
//OK, we're ready to allocate and solve prep these constraints now :-)
return SolverConstraintPrepState::eSUCCESS;
}
}
}
| 21,066 | C++ | 40.799603 | 153 | 0.73996 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationContactPrep.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_ARTICULATION_CONTACT_PREP_H
#define DY_ARTICULATION_CONTACT_PREP_H
#include "DySolverExt.h"
#include "foundation/PxVecMath.h"
namespace physx
{
struct PxcNpWorkUnit;
class PxContactBuffer;
struct PxContactPoint;
namespace Dy
{
struct CorrelationBuffer;
PxReal getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxReal dom0, PxReal angDom0,
const SolverExtBody& b1, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, PxReal dom1, PxReal angDom1,
Cm::SpatialVectorF* Z, bool allowSelfCollision = false);
aos::FloatV getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, const aos::FloatV& dom0, const aos::FloatV& angDom0,
const SolverExtBody& b1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1, const aos::FloatV& dom1, const aos::FloatV& angDom1,
Cm::SpatialVectorV* Z, bool allowSelfCollision = false);
Cm::SpatialVector createImpulseResponseVector(const PxVec3& linear, const PxVec3& angular, const SolverExtBody& body);
Cm::SpatialVectorV createImpulseResponseVector(const aos::Vec3V& linear, const aos::Vec3V& angular, const SolverExtBody& body);
void setupFinalizeExtSolverContacts(
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const SolverExtBody& b0,
const SolverExtBody& b1,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
PxReal restDistance, PxU8* frictionDataPtr,
PxReal ccdMaxContactDist,
Cm::SpatialVectorF* Z,
const PxReal offsetSlop);
bool setupFinalizeExtSolverContactsCoulomb(
const PxContactBuffer& buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
PxReal invDt,
PxReal dtF32,
PxReal bounceThreshold,
const SolverExtBody& b0,
const SolverExtBody& b1,
PxU32 frictionCountPerPoint,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
PxReal restDist,
PxReal ccdMaxContactDist,
Cm::SpatialVectorF* Z,
const PxReal solverOffsetSlop);
} //namespace Dy
}
#endif
| 4,036 | C | 38.970297 | 174 | 0.777255 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationUtils.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_ARTICULATION_UTILS_H
#define DY_ARTICULATION_UTILS_H
#include "foundation/PxBitUtils.h"
#include "foundation/PxVecMath.h"
#include "CmSpatialVector.h"
#include "DyVArticulation.h"
namespace physx
{
namespace Dy
{
struct ArticulationCore;
struct ArticulationLink;
#define DY_ARTICULATION_DEBUG_VERIFY 0
PX_FORCE_INLINE PxU32 ArticulationLowestSetBit(ArticulationBitField val)
{
PxU32 low = PxU32(val&0xffffffff), high = PxU32(val>>32);
PxU32 mask = PxU32((!low)-1);
PxU32 result = (mask&PxLowestSetBitUnsafe(low)) | ((~mask)&(PxLowestSetBitUnsafe(high)+32));
PX_ASSERT(val & (PxU64(1)<<result));
PX_ASSERT(!(val & ((PxU64(1)<<result)-1)));
return result;
}
PX_FORCE_INLINE PxU32 ArticulationHighestSetBit(ArticulationBitField val)
{
PxU32 low = PxU32(val & 0xffffffff), high = PxU32(val >> 32);
PxU32 mask = PxU32((!high) - 1);
PxU32 result = ((~mask)&PxHighestSetBitUnsafe(low)) | ((mask)&(PxHighestSetBitUnsafe(high) + 32));
PX_ASSERT(val & (PxU64(1) << result));
return result;
}
using namespace aos;
PX_FORCE_INLINE Cm::SpatialVector& unsimdRef(Cm::SpatialVectorV& v) { return reinterpret_cast<Cm::SpatialVector&>(v); }
PX_FORCE_INLINE const Cm::SpatialVector& unsimdRef(const Cm::SpatialVectorV& v) { return reinterpret_cast<const Cm::SpatialVector&>(v); }
}
}
#endif
| 3,007 | C | 39.106666 | 137 | 0.749584 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSDynamics.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_TGS_DYNAMICS_H
#define DY_TGS_DYNAMICS_H
#include "PxvConfig.h"
#include "CmSpatialVector.h"
#include "CmTask.h"
#include "CmPool.h"
#include "PxcThreadCoherentCache.h"
#include "DyThreadContext.h"
#include "PxcConstraintBlockStream.h"
#include "DySolverBody.h"
#include "DyContext.h"
#include "PxsIslandManagerTypes.h"
#include "PxvNphaseImplementationContext.h"
#include "solver/PxSolverDefs.h"
#include "PxsIslandSim.h"
namespace physx
{
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
}
class PxsRigidBody;
struct PxsBodyCore;
class PxsIslandIndices;
struct PxsIndexedInteraction;
struct PxsIndexedContactManager;
namespace Dy
{
struct SolverContext;
struct SolverIslandObjectsStep
{
PxsRigidBody** bodies;
FeatherstoneArticulation** articulations;
FeatherstoneArticulation** articulationOwners;
PxsIndexedContactManager* contactManagers;
const IG::IslandId* islandIds;
PxU32 numIslands;
PxU32* bodyRemapTable;
PxU32* nodeIndexArray;
PxSolverConstraintDesc* constraintDescs;
PxSolverConstraintDesc* orderedConstraintDescs;
PxSolverConstraintDesc* tempConstraintDescs;
PxConstraintBatchHeader* constraintBatchHeaders;
Cm::SpatialVector* motionVelocities;
PxsBodyCore** bodyCoreArray;
PxU32 solverBodyOffset;
SolverIslandObjectsStep() : bodies(NULL), articulations(NULL), articulationOwners(NULL),
contactManagers(NULL), islandIds(NULL), numIslands(0), nodeIndexArray(NULL), constraintDescs(NULL), motionVelocities(NULL), bodyCoreArray(NULL),
solverBodyOffset(0)
{
}
};
struct IslandContextStep
{
//The thread context for this island (set in in the island start task, released in the island end task)
ThreadContext* mThreadContext;
PxsIslandIndices mCounts;
SolverIslandObjectsStep mObjects;
PxU32 mPosIters;
PxU32 mVelIters;
PxU32 mArticulationOffset;
PxReal mStepDt;
PxReal mInvStepDt;
PxReal mBiasCoefficient;
PxI32 mSharedSolverIndex;
PxI32 mSolvedCount;
PxI32 mSharedRigidBodyIndex;
PxI32 mRigidBodyIntegratedCount;
PxI32 mSharedArticulationIndex;
PxI32 mArticulationIntegratedCount;
};
struct SolverIslandObjectsStep;
class SolverBodyVelDataPool : public PxArray<PxTGSSolverBodyVel, PxAlignedAllocator<128, PxReflectionAllocator<PxTGSSolverBodyVel> > >
{
PX_NOCOPY(SolverBodyVelDataPool)
public:
SolverBodyVelDataPool() {}
};
class SolverBodyTxInertiaPool : public PxArray<PxTGSSolverBodyTxInertia, PxAlignedAllocator<128, PxReflectionAllocator<PxTGSSolverBodyTxInertia> > >
{
PX_NOCOPY(SolverBodyTxInertiaPool)
public:
SolverBodyTxInertiaPool() {}
};
class SolverBodyDataStepPool : public PxArray<PxTGSSolverBodyData, PxAlignedAllocator<128, PxReflectionAllocator<PxTGSSolverBodyData> > >
{
PX_NOCOPY(SolverBodyDataStepPool)
public:
SolverBodyDataStepPool() {}
};
class SolverStepConstraintDescPool : public PxArray<PxSolverConstraintDesc, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverConstraintDesc> > >
{
PX_NOCOPY(SolverStepConstraintDescPool)
public:
SolverStepConstraintDescPool() { }
};
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class DynamicsTGSContext : public Context
{
PX_NOCOPY(DynamicsTGSContext)
public:
DynamicsTGSContext(PxcNpMemBlockPool* memBlockPool,
PxcScratchAllocator& scratchAllocator,
Cm::FlushPool& taskPool,
PxvSimStats& simStats,
PxTaskManager* taskManager,
PxVirtualAllocatorCallback* allocator,
PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager,
PxU64 contextID,
bool enableStabilization,
bool useEnhancedDeterminism,
PxReal lengthScale
);
virtual ~DynamicsTGSContext();
// Context
virtual void destroy() PX_OVERRIDE;
virtual void update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask,
PxvNphaseImplementationContext* nphase, PxU32 maxPatchesPerCM, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& changedHandleMap) PX_OVERRIDE;
virtual void mergeResults() PX_OVERRIDE;
virtual void setSimulationController(PxsSimulationController* simulationController) PX_OVERRIDE { mSimulationController = simulationController; }
virtual PxSolverType::Enum getSolverType() const PX_OVERRIDE { return PxSolverType::eTGS; }
//~Context
/**
\brief Allocates and returns a thread context object.
\return A thread context.
*/
PX_FORCE_INLINE ThreadContext* getThreadContext() { return mThreadContextPool.get(); }
/**
\brief Returns a thread context to the thread context pool.
\param[in] context The thread context to return to the thread context pool.
*/
void putThreadContext(ThreadContext* context) { mThreadContextPool.put(context); }
PX_FORCE_INLINE Cm::FlushPool& getTaskPool() { return mTaskPool; }
PX_FORCE_INLINE ThresholdStream& getThresholdStream() { return *mThresholdStream; }
PX_FORCE_INLINE PxvSimStats& getSimStats() { return mSimStats; }
PX_FORCE_INLINE PxU32 getKinematicCount() const { return mKinematicCount; }
void updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxU32 maxLinks);
protected:
// PT: TODO: the thread stats are missing for TGS
/*#if PX_ENABLE_SIM_STATS
void addThreadStats(const ThreadContext::ThreadSimStats& stats);
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif*/
// Solver helper-methods
/**
\brief Computes the unconstrained velocity for a given PxsRigidBody
\param[in] atom The PxsRigidBody
*/
void computeUnconstrainedVelocity(PxsRigidBody* atom) const;
/**
\brief fills in a PxSolverConstraintDesc from an indexed interaction
\param[in,out] desc The PxSolverConstraintDesc
\param[in] constraint The PxsIndexedInteraction
*/
void setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim,
const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies);
void setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex,
const IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies);
void solveIsland(const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts,
PxU32 solverBodyOffset,
IG::SimpleIslandManager& islandManager,
PxU32* bodyRemapTable, PxsMaterialManager* materialManager,
PxsContactManagerOutputIterator& iterator,
PxBaseTask* continuation);
void prepareBodiesAndConstraints(const SolverIslandObjectsStep& objects,
IG::SimpleIslandManager& islandManager,
IslandContextStep& islandContext);
void setupDescs(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, PxU32* mBodyRemapTable, PxU32 mSolverBodyOffset,
PxsContactManagerOutputIterator& outputs);
void preIntegrateBodies(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray,
PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2,
PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, PxU32 iteration);
void setupArticulations(IslandContextStep& islandContext, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, PxBaseTask* continuation);
PxU32 setupArticulationInternalConstraints(IslandContextStep& islandContext, PxReal dt, PxReal invStepDt);
void createSolverConstraints(PxSolverConstraintDesc* contactDescPtr, PxConstraintBatchHeader* headers, PxU32 nbHeaders,
PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& islandThreadContext, Dy::ThreadContext& threadContext, PxReal stepDt, PxReal totalDt,
PxReal invStepDt, PxReal biasCoefficient, PxI32 velIters);
void solveConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxReal invStepDt,
const PxTGSSolverBodyTxInertia* const solverTxInertia, PxReal elapsedTime, PxReal minPenetration, SolverContext& cache);
template <bool TSync>
void solveConcludeConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders,
PxTGSSolverBodyTxInertia* solverTxInertia, PxReal elapsedTime, SolverContext& cache, PxU32 iterCount);
template <bool Sync>
void parallelSolveConstraints(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxTGSSolverBodyTxInertia* solverTxInertia,
PxReal elapsedTime, PxReal minPenetration, SolverContext& cache, PxU32 iterCount);
void writebackConstraintsIteration(const PxConstraintBatchHeader* const hdrs, const PxSolverConstraintDesc* const contactDescPtr, PxU32 nbHeaders);
void parallelWritebackConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders);
void integrateBodies(const SolverIslandObjectsStep& objects,
PxU32 count, PxTGSSolverBodyVel* vels,
PxTGSSolverBodyTxInertia* txInertias, const PxTGSSolverBodyData*const bodyDatas, PxReal dt, PxReal invTotalDt, bool averageBodies,
PxReal ratio);
void parallelIntegrateBodies(PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
const PxTGSSolverBodyData* const bodyDatas, PxU32 count, PxReal dt, PxU32 iteration, PxReal invTotalDt, bool average,
PxReal ratio);
void copyBackBodies(const SolverIslandObjectsStep& objects,
PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
PxTGSSolverBodyData* solverBodyData, PxReal invDt, IG::IslandSim& islandSim,
PxU32 startIdx, PxU32 endIdx);
void updateArticulations(Dy::ThreadContext& threadContext, PxU32 startIdx, PxU32 endIdx, PxReal dt);
void stepArticulations(Dy::ThreadContext& threadContext, const PxsIslandIndices& counts, PxReal dt, PxReal stepInvDt);
void iterativeSolveIsland(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext,
PxReal stepDt, PxReal invStepDt, PxU32 posIters, PxU32 velIters, SolverContext& cache, PxReal ratio,
PxReal biasCoefficient);
void iterativeSolveIslandParallel(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext,
PxReal stepDt, PxU32 posIters, PxU32 velIters, PxI32* solverCounts, PxI32* integrationCounts, PxI32* articulationIntegrationCounts,
PxI32* solverProgressCount, PxI32* integrationProgressCount, PxI32* articulationProgressCount, PxU32 solverUnrollSize, PxU32 integrationUnrollSize,
PxReal ratio, PxReal biasCoefficient);
void endIsland(ThreadContext& mThreadContext);
void finishSolveIsland(ThreadContext& mThreadContext, const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts, IG::SimpleIslandManager& islandManager, PxBaseTask* continuation);
/**
\brief Resets the thread contexts
*/
void resetThreadContexts();
/**
\brief Returns the scratch memory allocator.
\return The scratch memory allocator.
*/
PX_FORCE_INLINE PxcScratchAllocator& getScratchAllocator() { return mScratchAllocator; }
//Data
PxTGSSolverBodyVel mWorldSolverBodyVel;
PxTGSSolverBodyTxInertia mWorldSolverBodyTxInertia;
PxTGSSolverBodyData mWorldSolverBodyData2;
/**
\brief A thread context pool
*/
PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool> mThreadContextPool;
/**
\brief Solver constraint desc array
*/
SolverStepConstraintDescPool mSolverConstraintDescPool;
SolverStepConstraintDescPool mOrderedSolverConstraintDescPool;
SolverStepConstraintDescPool mTempSolverConstraintDescPool;
PxArray<PxConstraintBatchHeader> mContactConstraintBatchHeaders;
/**
\brief Array of motion velocities for all bodies in the scene.
*/
PxArray<Cm::SpatialVector> mMotionVelocityArray;
/**
\brief Array of body core pointers for all bodies in the scene.
*/
PxArray<PxsBodyCore*> mBodyCoreArray;
/**
\brief Array of rigid body pointers for all bodies in the scene.
*/
PxArray<PxsRigidBody*> mRigidBodyArray;
/**
\brief Array of articulationpointers for all articulations in the scene.
*/
PxArray<FeatherstoneArticulation*> mArticulationArray;
SolverBodyVelDataPool mSolverBodyVelPool;
SolverBodyTxInertiaPool mSolverBodyTxInertiaPool;
SolverBodyDataStepPool mSolverBodyDataPool2;
ThresholdStream* mExceededForceThresholdStream[2]; //this store previous and current exceeded force thresholdStream
PxArray<PxU32> mExceededForceThresholdStreamMask;
PxArray<PxU32> mSolverBodyRemapTable; //Remaps from the "active island" index to the index within a solver island
PxArray<PxU32> mNodeIndexArray; //island node index
PxArray<PxsIndexedContactManager> mContactList;
/**
\brief The total number of kinematic bodies in the scene
*/
PxU32 mKinematicCount;
/**
\brief Atomic counter for the number of threshold stream elements.
*/
PxI32 mThresholdStreamOut;
PxsMaterialManager* mMaterialManager;
PxsContactManagerOutputIterator mOutputIterator;
private:
//private:
PxcScratchAllocator& mScratchAllocator;
Cm::FlushPool& mTaskPool;
PxTaskManager* mTaskManager;
PxU32 mCurrentIndex; // this is the index point to the current exceeded force threshold stream
friend class SetupDescsTask;
friend class PreIntegrateTask;
friend class SetupArticulationTask;
friend class SetupArticulationInternalConstraintsTask;
friend class SetupSolverConstraintsTask;
friend class SolveIslandTask;
friend class EndIslandTask;
friend class SetupSolverConstraintsSubTask;
friend class ParallelSolveTask;
friend class PreIntegrateParallelTask;
friend class CopyBackTask;
friend class UpdateArticTask;
friend class FinishSolveIslandTask;
};
#if PX_VC
#pragma warning(pop)
#endif
}
}
#endif
| 16,271 | C | 38.115385 | 195 | 0.77168 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
#include "DyConstraintPrep.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
using namespace aos;
namespace physx
{
namespace Dy
{
PxcCreateFinalizeSolverContactMethod createFinalizeMethods[3] =
{
createFinalizeSolverContacts,
createFinalizeSolverContactsCoulomb1D,
createFinalizeSolverContactsCoulomb2D
};
static void setupFinalizeSolverConstraints(Sc::ShapeInteraction* shapeInteraction,
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const PxSolverBodyData& data0,
const PxSolverBodyData& data1,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
bool hasForceThreshold, bool staticOrKinematicBody,
const PxReal restDist, PxU8* frictionDataPtr,
const PxReal maxCCDSeparation,
const PxReal solverOffsetSlopF32)
{
// NOTE II: the friction patches are sparse (some of them have no contact patches, and
// therefore did not get written back to the cache) but the patch addresses are dense,
// corresponding to valid patches
const Vec3V solverOffsetSlop = V3Load(solverOffsetSlopF32);
const FloatV ccdMaxSeparation = FLoad(maxCCDSeparation);
PxU8 flags = PxU8(hasForceThreshold ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0);
PxU8* PX_RESTRICT ptr = workspace;
PxU8 type = PxTo8(staticOrKinematicBody ? DY_SC_TYPE_STATIC_CONTACT
: DY_SC_TYPE_RB_CONTACT);
const FloatV zero=FZero();
const Vec3V v3Zero = V3Zero();
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
const FloatV nDom1fV = FNeg(d1);
const FloatV invMass0 = FLoad(data0.invMass);
const FloatV invMass1 = FLoad(data1.invMass);
const FloatV invMass0_dom0fV = FMul(d0, invMass0);
const FloatV invMass1_dom1fV = FMul(nDom1fV, invMass1);
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero();
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, invMass0_dom0fV);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, invMass1_dom1fV);
const FloatV restDistance = FLoad(restDist);
const FloatV maxPenBias = FMax(FLoad(data0.penBiasClamp), FLoad(data1.penBiasClamp));
const QuatV bodyFrame0q = QuatVLoadU(&bodyFrame0.q.x);
const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p);
const QuatV bodyFrame1q = QuatVLoadU(&bodyFrame1.q.x);
const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p);
PxU32 frictionPatchWritebackAddrIndex = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
const Vec3V linVel0 = V3LoadU_SafeReadW(data0.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
const Vec3V linVel1 = V3LoadU_SafeReadW(data1.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
const Vec3V angVel0 = V3LoadU_SafeReadW(data0.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
const Vec3V angVel1 = V3LoadU_SafeReadW(data1.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
PX_ALIGN(16, const Mat33V invSqrtInertia0)
(
V3LoadU_SafeReadW(data0.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33
V3LoadU_SafeReadW(data0.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33
V3LoadU(data0.sqrtInvInertia.column2)
);
PX_ALIGN(16, const Mat33V invSqrtInertia1)
(
V3LoadU_SafeReadW(data1.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33
V3LoadU_SafeReadW(data1.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33
V3LoadU(data1.sqrtInvInertia.column2)
);
const FloatV invDt = FLoad(invDtF32);
const FloatV p8 = FLoad(0.8f);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const FloatV invDtp8 = FMul(invDt, p8);
const FloatV dt = FLoad(dtF32);
for(PxU32 i=0;i<c.frictionPatchCount;i++)
{
PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
PX_ASSERT(frictionPatch.anchorCount <= 2);
PxU32 firstPatch = c.correlationListHeads[i];
const PxContactPoint* contactBase0 = buffer + c.contactPatches[firstPatch].start;
SolverContactHeader* PX_RESTRICT header = reinterpret_cast<SolverContactHeader*>(ptr);
ptr += sizeof(SolverContactHeader);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
header->shapeInteraction = shapeInteraction;
header->flags = flags;
FStore(invMass0_dom0fV, &header->invMass0);
FStore(FNeg(invMass1_dom1fV), &header->invMass1);
const FloatV restitution = FLoad(contactBase0->restitution);
const FloatV damping = FLoad(contactBase0->damping);
PxU32 pointStride = sizeof(SolverContactPoint);
PxU32 frictionStride = sizeof(SolverContactFriction);
const Vec3V normal = V3LoadA(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV normalLenSq = V3LengthSq(normal);
const VecCrossV norCross = V3PrepareCross(normal);
const FloatV norVel = V3SumElems(V3NegMulSub(normal, linVel1, V3Mul(normal, linVel0)));
const FloatV invMassNorLenSq0 = FMul(invMass0_dom0fV, normalLenSq);
const FloatV invMassNorLenSq1 = FMul(invMass1_dom1fV, normalLenSq);
header->normal_minAppliedImpulseForFrictionW = Vec4V_From_Vec3V(normal);
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer + c.contactPatches[patch].start;
PxU8* p = ptr;
for(PxU32 j=0;j<count;j++)
{
PxPrefetchLine(p, 256);
const PxContactPoint& contact = contactBase[j];
SolverContactPoint* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPoint*>(p);
p += pointStride;
constructContactConstraint(invSqrtInertia0, invSqrtInertia1, invMassNorLenSq0,
invMassNorLenSq1, angD0, angD1, bodyFrame0p, bodyFrame1p,
normal, norVel, norCross, angVel0, angVel1,
invDt, invDtp8, dt, restDistance, maxPenBias, restitution,
bounceThreshold, contact, *solverContact,
ccdMaxSeparation, solverOffsetSlop, damping);
}
ptr = p;
}
PxF32* forceBuffers = reinterpret_cast<PxF32*>(ptr);
PxMemZero(forceBuffers, sizeof(PxF32) * contactCount);
ptr += ((contactCount + 3) & (~3)) * sizeof(PxF32); // jump to next 16-byte boundary
const PxReal frictionCoefficient = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f;
const PxReal staticFriction = contactBase0->staticFriction * frictionCoefficient;
const PxReal dynamicFriction = contactBase0->dynamicFriction* frictionCoefficient;
const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(staticFriction));
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(dynamicFriction));
const bool haveFriction = (disableStrongFriction == 0 && frictionPatch.anchorCount != 0);//PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;
header->numNormalConstr = PxTo8(contactCount);
header->numFrictionConstr = PxTo8(haveFriction ? frictionPatch.anchorCount*2 : 0);
header->type = type;
header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W;
FStore(angD0, &header->angDom0);
FStore(angD1, &header->angDom1);
header->broken = 0;
if(haveFriction)
{
const Vec3V linVrel = V3Sub(linVel0, linVel1);
//const Vec3V normal = Vec3V_From_PxVec3_Aligned(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV orthoThreshold = FLoad(0.70710678f);
const FloatV p1 = FLoad(0.0001f);
// fallback: normal.cross((1,0,0)) or normal.cross((0,0,1))
const FloatV normalX = V3GetX(normal);
const FloatV normalY = V3GetY(normal);
const FloatV normalZ = V3GetZ(normal);
Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY);
Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero);
Vec3V t0Fallback = V3Sel(FIsGrtr(orthoThreshold, FAbs(normalX)), t0Fallback1, t0Fallback2);
Vec3V t0 = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel)));
t0 = V3Sel(FIsGrtr(V3LengthSq(t0), p1), t0, t0Fallback);
t0 = V3Normalize(t0);
const VecCrossV t0Cross = V3PrepareCross(t0);
const Vec3V t1 = V3Cross(norCross, t0Cross);
const VecCrossV t1Cross = V3PrepareCross(t1);
// since we don't even have the body velocities we can't compute the tangent dirs, so
// the only thing we can do right now is to write the geometric information (which is the
// same for both axis constraints of an anchor) We put ra in the raXn field, rb in the rbXn
// field, and the error in the normal field. See corresponding comments in
// completeContactFriction()
//We want to set the writeBack ptr to point to the broken flag of the friction patch.
//On spu we have a slight problem here because the friction patch array is
//in local store rather than in main memory. The good news is that the address of the friction
//patch array in main memory is stored in the work unit. These two addresses will be equal
//except on spu where one is local store memory and the other is the effective address in main memory.
//Using the value stored in the work unit guarantees that the main memory address is used on all platforms.
PxU8* PX_RESTRICT writeback = frictionDataPtr + frictionPatchWritebackAddrIndex*sizeof(FrictionPatch);
header->frictionBrokenWritebackByte = writeback;
for(PxU32 j = 0; j < frictionPatch.anchorCount; j++)
{
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
SolverContactFriction* PX_RESTRICT f0 = reinterpret_cast<SolverContactFriction*>(ptr);
ptr += frictionStride;
SolverContactFriction* PX_RESTRICT f1 = reinterpret_cast<SolverContactFriction*>(ptr);
ptr += frictionStride;
Vec3V body0Anchor = V3LoadU(frictionPatch.body0Anchors[j]);
Vec3V body1Anchor = V3LoadU(frictionPatch.body1Anchors[j]);
const Vec3V ra = QuatRotate(bodyFrame0q, body0Anchor);
const Vec3V rb = QuatRotate(bodyFrame1q, body1Anchor);
/*ra = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(ra)), v3Zero, ra);
rb = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rb)), v3Zero, rb);*/
PxU32 index = c.contactID[i][j];
Vec3V error = V3Sub(V3Add(ra, bodyFrame0p), V3Add(rb, bodyFrame1p));
error = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(error)), v3Zero, error);
index = index == 0xFFFF ? c.contactPatches[c.correlationListHeads[i]].start : index;
const Vec3V tvel = V3LoadA(buffer[index].targetVel);
{
Vec3V raXn = V3Cross(ra, t0Cross);
Vec3V rbXn = V3Cross(rb, t0Cross);
raXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnSqrtInertia = M33MulV3(invSqrtInertia0, raXn);
const Vec3V rbXnSqrtInertia = M33MulV3(invSqrtInertia1, rbXn);
const FloatV resp0 = FAdd(invMass0_dom0fV, FMul(angD0, V3Dot(raXnSqrtInertia, raXnSqrtInertia)));
const FloatV resp1 = FSub(FMul(angD1, V3Dot(rbXnSqrtInertia, rbXnSqrtInertia)), invMass1_dom1fV);
const FloatV resp = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(resp, zero), FDiv(p8, resp), zero);
FloatV targetVel = V3Dot(tvel, t0);
const FloatV vrel1 = FAdd(V3Dot(t0, linVel0), V3Dot(raXn, angVel0));
const FloatV vrel2 = FAdd(V3Dot(t0, linVel1), V3Dot(rbXn, angVel1));
const FloatV vrel = FSub(vrel1, vrel2);
targetVel = FSub(targetVel, vrel);
f0->normalXYZ_appliedForceW = V4SetW(t0, zero);
f0->raXnXYZ_velMultiplierW = V4SetW(raXnSqrtInertia, velMultiplier);
f0->rbXnXYZ_biasW = V4SetW(rbXnSqrtInertia, FMul(V3Dot(t0, error), invDt));
FStore(targetVel, &f0->targetVel);
}
{
Vec3V raXn = V3Cross(ra, t1Cross);
Vec3V rbXn = V3Cross(rb, t1Cross);
raXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnSqrtInertia = M33MulV3(invSqrtInertia0, raXn);
const Vec3V rbXnSqrtInertia = M33MulV3(invSqrtInertia1, rbXn);
const FloatV resp0 = FAdd(invMass0_dom0fV, FMul(angD0, V3Dot(raXnSqrtInertia, raXnSqrtInertia)));
const FloatV resp1 = FSub(FMul(angD1, V3Dot(rbXnSqrtInertia, rbXnSqrtInertia)), invMass1_dom1fV);
const FloatV resp = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(resp, zero), FDiv(p8, resp), zero);
FloatV targetVel = V3Dot(tvel, t1);
const FloatV vrel1 = FAdd(V3Dot(t1, linVel0), V3Dot(raXn, angVel0));
const FloatV vrel2 = FAdd(V3Dot(t1, linVel1), V3Dot(rbXn, angVel1));
const FloatV vrel = FSub(vrel1, vrel2);
targetVel = FSub(targetVel, vrel);
f1->normalXYZ_appliedForceW = V4SetW(t1, zero);
f1->raXnXYZ_velMultiplierW = V4SetW(raXnSqrtInertia, velMultiplier);
f1->rbXnXYZ_biasW = V4SetW(rbXnSqrtInertia, FMul(V3Dot(t1, error), invDt));
FStore(targetVel, &f1->targetVel);
}
}
}
frictionPatchWritebackAddrIndex++;
}
}
PX_FORCE_INLINE void computeBlockStreamByteSizes(const bool useExtContacts, const CorrelationBuffer& c,
PxU32& _solverConstraintByteSize, PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches,
PxU32& _axisConstraintCount)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PX_ASSERT(0 == _frictionPatchByteSize);
PX_ASSERT(0 == _numFrictionPatches);
PX_ASSERT(0 == _axisConstraintCount);
// PT: use local vars to remove LHS
PxU32 solverConstraintByteSize = 0;
PxU32 numFrictionPatches = 0;
PxU32 axisConstraintCount = 0;
for(PxU32 i = 0; i < c.frictionPatchCount; i++)
{
//Friction patches.
if(c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0;
//Solver constraint data.
if(c.frictionPatchContactCounts[i]!=0)
{
solverConstraintByteSize += sizeof(SolverContactHeader);
solverConstraintByteSize += useExtContacts ? c.frictionPatchContactCounts[i] * sizeof(SolverContactPointExt)
: c.frictionPatchContactCounts[i] * sizeof(SolverContactPoint);
solverConstraintByteSize += sizeof(PxF32) * ((c.frictionPatchContactCounts[i] + 3)&(~3)); //Add on space for applied impulses
axisConstraintCount += c.frictionPatchContactCounts[i];
if(haveFriction)
{
solverConstraintByteSize += useExtContacts ? c.frictionPatches[i].anchorCount * 2 * sizeof(SolverContactFrictionExt)
: c.frictionPatches[i].anchorCount * 2 * sizeof(SolverContactFriction);
axisConstraintCount += c.frictionPatches[i].anchorCount * 2;
}
}
}
PxU32 frictionPatchByteSize = numFrictionPatches*sizeof(FrictionPatch);
_numFrictionPatches = numFrictionPatches;
_axisConstraintCount = axisConstraintCount;
//16-byte alignment.
_frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f);
_solverConstraintByteSize = ((solverConstraintByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f));
}
static bool reserveBlockStreams(const bool useExtContacts, Dy::CorrelationBuffer& cBuffer,
PxU8*& solverConstraint,
FrictionPatch*& _frictionPatches,
PxU32& numFrictionPatches, PxU32& solverConstraintByteSize,
PxU32& axisConstraintCount, PxConstraintAllocator& constraintAllocator)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(NULL == _frictionPatches);
PX_ASSERT(0 == numFrictionPatches);
PX_ASSERT(0 == solverConstraintByteSize);
PX_ASSERT(0 == axisConstraintCount);
//From frictionPatchStream we just need to reserve a single buffer.
PxU32 frictionPatchByteSize = 0;
//Compute the sizes of all the buffers.
computeBlockStreamByteSizes(
useExtContacts, cBuffer,
solverConstraintByteSize, frictionPatchByteSize, numFrictionPatches,
axisConstraintCount);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if(constraintBlockByteSize > 0)
{
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock)
{
if(0==constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock=NULL;
}
}
PX_ASSERT((size_t(constraintBlock) & 0xF) == 0);
}
FrictionPatch* frictionPatches = NULL;
//If the constraint block reservation didn't fail then reserve the friction buffer too.
if(frictionPatchByteSize >0 && (0==constraintBlockByteSize || constraintBlock))
{
frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize));
if(0==frictionPatches || (reinterpret_cast<FrictionPatch*>(-1))==frictionPatches)
{
if(0==frictionPatches)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
frictionPatches=NULL;
}
}
}
_frictionPatches = frictionPatches;
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if(0==constraintBlockByteSize || constraintBlock)
{
if(solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f));
}
}
//Return true if neither of the two block reservations failed.
return ((0==constraintBlockByteSize || constraintBlock) && (0==frictionPatchByteSize || frictionPatches));
}
bool createFinalizeSolverContacts(
PxSolverContactDesc& contactDesc,
CorrelationBuffer& c,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z)
{
PxPrefetchLine(contactDesc.body0);
PxPrefetchLine(contactDesc.body1);
PxPrefetchLine(contactDesc.data0);
PxPrefetchLine(contactDesc.data1);
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
const bool hasForceThreshold = contactDesc.hasForceThresholds;
const bool staticOrKinematicBody = contactDesc.bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY || contactDesc.bodyState1 == PxSolverContactDesc::eSTATIC_BODY;
const bool disableStrongFriction = contactDesc.disableStrongFriction;
PxSolverConstraintDesc& desc = *contactDesc.desc;
const bool useExtContacts = (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY);
desc.constraintLengthOver16 = 0;
if (contactDesc.numContacts == 0)
{
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
desc.constraint = NULL;
return true;
}
if (!disableStrongFriction)
{
getFrictionPatches(c, contactDesc.frictionPtr, contactDesc.frictionCount, contactDesc.bodyFrame0, contactDesc.bodyFrame1, correlationDistance);
}
bool overflow = !createContactPatches(c, contactDesc.contacts, contactDesc.numContacts, PXC_SAME_NORMAL);
overflow = correlatePatches(c, contactDesc.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, PXC_SAME_NORMAL, 0, 0) || overflow;
PX_UNUSED(overflow);
#if PX_CHECKED
if (overflow)
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL, "Dropping contacts in solver because we exceeded limit of 32 friction patches.");
#endif
growPatches(c, contactDesc.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, 0, frictionOffsetThreshold + contactDesc.restDistance);
//PX_ASSERT(patchCount == c.frictionPatchCount);
FrictionPatch* frictionPatches = NULL;
PxU8* solverConstraint = NULL;
PxU32 numFrictionPatches = 0;
PxU32 solverConstraintByteSize = 0;
PxU32 axisConstraintCount = 0;
const bool successfulReserve = reserveBlockStreams(
useExtContacts, c,
solverConstraint, frictionPatches,
numFrictionPatches,
solverConstraintByteSize,
axisConstraintCount,
constraintAllocator);
// initialise the work unit's ptrs to the various buffers.
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
desc.constraint = NULL;
desc.constraintLengthOver16 = 0;
// patch up the work unit with the reserved buffers and set the reserved buffer data as appropriate.
if (successfulReserve)
{
PxU8* frictionDataPtr = reinterpret_cast<PxU8*>(frictionPatches);
contactDesc.frictionPtr = frictionDataPtr;
desc.constraint = solverConstraint;
//output.nbContacts = PxTo8(numContacts);
contactDesc.frictionCount = PxTo8(numFrictionPatches);
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize / 16);
desc.writeBack = contactDesc.contactForces;
//Initialise friction buffer.
if (frictionPatches)
{
// PT: TODO: revisit this... not very satisfying
//const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch);
PxPrefetchLine(frictionPatches);
PxPrefetchLine(frictionPatches, 128);
PxPrefetchLine(frictionPatches, 256);
for (PxU32 i = 0; i<c.frictionPatchCount; i++)
{
//if(c.correlationListHeads[i]!=CorrelationBuffer::LIST_END)
if (c.frictionPatchContactCounts[i])
{
*frictionPatches++ = c.frictionPatches[i];
PxPrefetchLine(frictionPatches, 256);
}
}
}
//Initialise solverConstraint buffer.
if (solverConstraint)
{
const PxSolverBodyData& data0 = *contactDesc.data0;
const PxSolverBodyData& data1 = *contactDesc.data1;
if (useExtContacts)
{
const SolverExtBody b0(reinterpret_cast<const void*>(contactDesc.body0), reinterpret_cast<const void*>(&data0), desc.linkIndexA);
const SolverExtBody b1(reinterpret_cast<const void*>(contactDesc.body1), reinterpret_cast<const void*>(&data1), desc.linkIndexB);
setupFinalizeExtSolverContacts(contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
b0, b1, invDtF32, dtF32, bounceThresholdF32,
contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1,
contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, Z, contactDesc.offsetSlop);
}
else
{
setupFinalizeSolverConstraints(getInteraction(contactDesc), contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
data0, data1, invDtF32, dtF32, bounceThresholdF32,
contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1,
hasForceThreshold, staticOrKinematicBody, contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, contactDesc.offsetSlop);
}
//KS - set to 0 so we have a counter for the number of times we solved the constraint
//only going to be used on SPU but might as well set on all platforms because this code is shared
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
}
}
return successfulReserve;
}
FloatV setupExtSolverContact(const SolverExtBody& b0, const SolverExtBody& b1,
const FloatV& d0, const FloatV& d1, const FloatV& angD0, const FloatV& angD1, const Vec3V& bodyFrame0p, const Vec3V& bodyFrame1p,
const Vec3VArg normal, const FloatVArg invDt, const FloatVArg invDtp8, const FloatVArg dt, const FloatVArg restDistance,
const FloatVArg maxPenBias, const FloatVArg restitution,const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointExt& solverContact, const FloatVArg ccdMaxSeparation, Cm::SpatialVectorF* zVector,
const Cm::SpatialVectorV& v0, const Cm::SpatialVectorV& v1, const FloatV& cfm, const Vec3VArg solverOffsetSlop,
const FloatVArg norVel0, const FloatVArg norVel1, const FloatVArg damping )
{
const FloatV zero = FZero();
const FloatV separation = FLoad(contact.separation);
const FloatV penetration = FSub(separation, restDistance);
const Vec3V point = V3LoadA(contact.point);
const Vec3V ra = V3Sub(point, bodyFrame0p);
const Vec3V rb = V3Sub(point, bodyFrame1p);
Vec3V raXn = V3Cross(ra, normal);
Vec3V rbXn = V3Cross(rb, normal);
FloatV aVel0 = V3Dot(v0.angular, raXn);
FloatV aVel1 = V3Dot(v1.angular, raXn);
FloatV relLinVel = FSub(norVel0, norVel1);
FloatV relAngVel = FSub(aVel0, aVel1);
const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(relLinVel, zero), FMax(), FDiv(relAngVel, relLinVel)), FOne()));
raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn);
aVel0 = V3Dot(raXn, v0.angular);
aVel1 = V3Dot(rbXn, v1.angular);
relAngVel = FSub(aVel0, aVel1);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(normal, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(normal), V3Neg(rbXn), b1);
const FloatV unitResponse = getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(zVector));
const FloatV vrel = FAdd(relLinVel, relAngVel);
const FloatV penetrationInvDt = FMul(penetration, invDt);
const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt));
FloatV velMultiplier, impulseMultiplier;
FloatV biasedErr, unbiasedErr;
const FloatV tVel = FSel(isGreater2, FMul(FNeg(vrel), restitution), zero);
FloatV targetVelocity = tVel;
//Get the rigid body's current velocity and embed into the constraint target velocities
if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVelocity = FSub(targetVelocity, FAdd(norVel0, aVel0));
else if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVelocity = FAdd(targetVelocity, FAdd(norVel1, aVel1));
targetVelocity = FAdd(targetVelocity, V3Dot(V3LoadA(contact.targetVel), normal));
if (FAllGrtr(zero, restitution)) // negative restitution -> interpret as spring stiffness for compliant contact
{
const FloatV nrdt = FMul(dt, restitution);
const FloatV a = FMul(dt, FSub(damping, nrdt));
const FloatV b = FMul(dt, FNeg(FMul(restitution, penetration)));
const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne()));
velMultiplier = FMul(x, a);
//FloatV scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier));
const FloatV scaledBias = FMul(x, b);
impulseMultiplier = FSub(FOne(), x);
unbiasedErr = biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias));
}
else
{
const BoolV ccdSeparationCondition = FIsGrtrOrEq(ccdMaxSeparation, penetration);
velMultiplier = FSel(FIsGrtr(unitResponse, FZero()), FRecip(FAdd(unitResponse, cfm)), zero);
FloatV scaledBias = FMul(velMultiplier, FMax(maxPenBias, FMul(penetration, invDtp8)));
scaledBias = FSel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias);
biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias));
unbiasedErr = FScaleAdd(targetVelocity, velMultiplier, FSel(isGreater2, zero, FNeg(FMax(scaledBias, zero))));
impulseMultiplier = FOne();
}
const FloatV deltaF = FMax(FMul(FSub(tVel, FAdd(vrel, FMax(penetrationInvDt, zero))), velMultiplier), zero);
FStore(biasedErr, &solverContact.biasedErr);
FStore(unbiasedErr, &solverContact.unbiasedErr);
solverContact.raXn_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), velMultiplier);
solverContact.rbXn_maxImpulseW = V4SetW(Vec4V_From_Vec3V(V3Neg(resp1.angular)), FLoad(contact.maxImpulse));;
solverContact.linDeltaVA = deltaV0.linear;
solverContact.angDeltaVA = deltaV0.angular;
solverContact.linDeltaVB = deltaV1.linear;
solverContact.angDeltaVB = deltaV1.angular;
FStore(impulseMultiplier, &solverContact.impulseMultiplier);
return deltaF;
}
bool createFinalizeSolverContacts(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
// We pull the friction patches out of the cache to remove the dependency on how
// the cache is organized. Remember original addrs so we can write them back
// efficiently.
PxU32 numContacts = 0;
{
PxReal invMassScale0 = 1.f;
PxReal invMassScale1 = 1.f;
PxReal invInertiaScale0 = 1.f;
PxReal invInertiaScale1 = 1.f;
bool hasMaxImpulse = false, hasTargetVelocity = false;
numContacts = extractContacts(buffer, output, hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, PxMin(contactDesc.data0->maxContactImpulse, contactDesc.data1->maxContactImpulse));
contactDesc.contacts = buffer.contacts;
contactDesc.numContacts = numContacts;
contactDesc.disableStrongFriction = contactDesc.disableStrongFriction || hasTargetVelocity;
contactDesc.hasMaxImpulse = hasMaxImpulse;
contactDesc.invMassScales.linear0 *= invMassScale0;
contactDesc.invMassScales.linear1 *= invMassScale1;
contactDesc.invMassScales.angular0 *= invInertiaScale0;
contactDesc.invMassScales.angular1 *= invInertiaScale1;
}
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
return createFinalizeSolverContacts(contactDesc, c, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold,
correlationDistance, constraintAllocator, Z);
}
PxU32 getContactManagerConstraintDesc(const PxsContactManagerOutput& cmOutput, const PxsContactManager& /*cm*/, PxSolverConstraintDesc& desc)
{
desc.writeBack = cmOutput.contactForces;
return cmOutput.nbContacts;// cm.getWorkUnit().axisConstraintCount;
}
}
}
| 33,521 | C++ | 39.98044 | 221 | 0.755407 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyBodyCoreIntegrator.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_BODYCORE_INTEGRATOR_H
#define DY_BODYCORE_INTEGRATOR_H
#include "PxvDynamics.h"
#include "DySolverBody.h"
namespace physx
{
namespace Dy
{
PX_FORCE_INLINE void bodyCoreComputeUnconstrainedVelocity
(const PxVec3& gravity, PxReal dt, PxReal linearDamping, PxReal angularDamping, PxReal accelScale,
PxReal maxLinearVelocitySq, PxReal maxAngularVelocitySq, PxVec3& inOutLinearVelocity, PxVec3& inOutAngularVelocity,
bool disableGravity)
{
//Multiply everything that needs multiplied by dt to improve code generation.
PxVec3 linearVelocity = inOutLinearVelocity;
PxVec3 angularVelocity = inOutAngularVelocity;
const PxReal linearDampingTimesDT=linearDamping*dt;
const PxReal angularDampingTimesDT=angularDamping*dt;
const PxReal oneMinusLinearDampingTimesDT=1.0f-linearDampingTimesDT;
const PxReal oneMinusAngularDampingTimesDT=1.0f-angularDampingTimesDT;
//TODO context-global gravity
if(!disableGravity)
{
const PxVec3 linearAccelTimesDT = gravity*dt *accelScale;
linearVelocity += linearAccelTimesDT;
}
//Apply damping.
const PxReal linVelMultiplier = physx::intrinsics::fsel(oneMinusLinearDampingTimesDT, oneMinusLinearDampingTimesDT, 0.0f);
const PxReal angVelMultiplier = physx::intrinsics::fsel(oneMinusAngularDampingTimesDT, oneMinusAngularDampingTimesDT, 0.0f);
linearVelocity*=linVelMultiplier;
angularVelocity*=angVelMultiplier;
// Clamp velocity
const PxReal linVelSq = linearVelocity.magnitudeSquared();
if(linVelSq > maxLinearVelocitySq)
{
linearVelocity *= PxSqrt(maxLinearVelocitySq / linVelSq);
}
const PxReal angVelSq = angularVelocity.magnitudeSquared();
if(angVelSq > maxAngularVelocitySq)
{
angularVelocity *= PxSqrt(maxAngularVelocitySq / angVelSq);
}
inOutLinearVelocity = linearVelocity;
inOutAngularVelocity = angularVelocity;
}
PX_FORCE_INLINE void integrateCore(PxVec3& motionLinearVelocity, PxVec3& motionAngularVelocity,
PxSolverBody& solverBody, PxSolverBodyData& solverBodyData, PxF32 dt, PxU32 lockFlags)
{
if (lockFlags)
{
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
{
motionLinearVelocity.x = 0.f;
solverBody.linearVelocity.x = 0.f;
solverBodyData.linearVelocity.x = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
{
motionLinearVelocity.y = 0.f;
solverBody.linearVelocity.y = 0.f;
solverBodyData.linearVelocity.y = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
{
motionLinearVelocity.z = 0.f;
solverBody.linearVelocity.z = 0.f;
solverBodyData.linearVelocity.z = 0.f;
}
//The angular velocity should be 0 because it is now impossible to make it rotate around that axis!
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
{
motionAngularVelocity.x = 0.f;
solverBody.angularState.x = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
{
motionAngularVelocity.y = 0.f;
solverBody.angularState.y = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
{
motionAngularVelocity.z = 0.f;
solverBody.angularState.z = 0.f;
}
}
// Integrate linear part
const PxVec3 linearMotionVel = solverBodyData.linearVelocity + motionLinearVelocity;
const PxVec3 delta = linearMotionVel * dt;
PxVec3 angularMotionVel = solverBodyData.angularVelocity + solverBodyData.sqrtInvInertia * motionAngularVelocity;
PxReal w = angularMotionVel.magnitudeSquared();
solverBodyData.body2World.p += delta;
PX_ASSERT(solverBodyData.body2World.p.isFinite());
//Store back the linear and angular velocities
//core.linearVelocity += solverBody.linearVelocity * solverBodyData.sqrtInvMass;
solverBodyData.linearVelocity += solverBody.linearVelocity;
solverBodyData.angularVelocity += solverBodyData.sqrtInvInertia * solverBody.angularState;
// Integrate the rotation using closed form quaternion integrator
if (w != 0.0f)
{
w = PxSqrt(w);
// Perform a post-solver clamping
// TODO(dsequeira): ignore this for the moment
//just clamp motionVel to half float-range
const PxReal maxW = 1e+7f; //Should be about sqrt(PX_MAX_REAL/2) or smaller
if (w > maxW)
{
angularMotionVel = angularMotionVel.getNormalized() * maxW;
w = maxW;
}
const PxReal v = dt * w * 0.5f;
PxReal s, q;
PxSinCos(v, s, q);
s /= w;
const PxVec3 pqr = angularMotionVel * s;
const PxQuat quatVel(pqr.x, pqr.y, pqr.z, 0);
PxQuat result = quatVel * solverBodyData.body2World.q;
result += solverBodyData.body2World.q * q;
solverBodyData.body2World.q = result.getNormalized();
PX_ASSERT(solverBodyData.body2World.q.isSane());
PX_ASSERT(solverBodyData.body2World.q.isFinite());
}
motionLinearVelocity = linearMotionVel;
motionAngularVelocity = angularMotionVel;
}
}
}
#endif
| 6,417 | C | 35.885057 | 125 | 0.76609 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyCorrelationBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CORRELATION_BUFFER_H
#define DY_CORRELATION_BUFFER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxBounds3.h"
#include "geomutils/PxContactBuffer.h"
#include "PxvConfig.h"
#include "DyFrictionPatch.h"
namespace physx
{
namespace Dy
{
struct CorrelationBuffer
{
static const PxU32 MAX_FRICTION_PATCHES = 32;
static const PxU16 LIST_END = 0xffff;
struct ContactPatchData
{
PxBounds3 patchBounds;
PxU32 boundsPadding;
PxReal staticFriction;
PxReal dynamicFriction;
PxReal restitution;
PxU16 start;
PxU16 next;
PxU8 flags;
PxU8 count;
};
// we can have as many contact patches as contacts, unfortunately
ContactPatchData PX_ALIGN(16, contactPatches[PxContactBuffer::MAX_CONTACTS]);
FrictionPatch PX_ALIGN(16, frictionPatches[MAX_FRICTION_PATCHES]);
PxVec3 PX_ALIGN(16, frictionPatchWorldNormal[MAX_FRICTION_PATCHES]);
PxBounds3 patchBounds[MAX_FRICTION_PATCHES];
PxU32 frictionPatchContactCounts[MAX_FRICTION_PATCHES];
PxU32 correlationListHeads[MAX_FRICTION_PATCHES+1];
// contact IDs are only used to identify auxiliary contact data when velocity
// targets have been set.
PxU16 contactID[MAX_FRICTION_PATCHES][2];
PxU32 contactPatchCount, frictionPatchCount;
};
bool createContactPatches(CorrelationBuffer& fb, const PxContactPoint* cb, PxU32 contactCount, PxReal normalTolerance);
bool correlatePatches(CorrelationBuffer& fb,
const PxContactPoint* cb,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxReal normalTolerance,
PxU32 startContactPatchIndex,
PxU32 startFrictionPatchIndex);
void growPatches(CorrelationBuffer& fb,
const PxContactPoint* buffer,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU32 frictionPatchStartIndex,
PxReal frictionOffsetThreshold);
}
}
#endif
| 3,643 | C | 34.37864 | 119 | 0.763382 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintsBlock.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxFPU.h"
#include "DySolverBody.h"
#include "DySolverContact.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "DyThresholdTable.h"
#include "DySolverContext.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
#include "DySolverContact4.h"
#include "DySolverConstraint1D4.h"
#include "DyPGS.h"
namespace physx
{
namespace Dy
{
static void solveContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& cache)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
Vec4V vMax = V4Splat(FMax());
const PxU8* PX_RESTRICT prefetchAddress = currPtr + sizeof(SolverContactHeader4) + sizeof(SolverContactBatchPointDynamic4);
const SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
const Vec4V invMassA = hdr->invMass0D0;
const Vec4V invMassB = hdr->invMass1D1;
const Vec4V sumInvMass = V4Add(invMassA, invMassB);
while(currPtr < last)
{
hdr = reinterpret_cast<const SolverContactHeader4*>(currPtr);
PX_ASSERT(hdr->type == DY_SC_TYPE_BLOCK_RB_CONTACT);
currPtr = reinterpret_cast<PxU8*>(const_cast<SolverContactHeader4*>(hdr) + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
Vec4V* appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactBatchPointDynamic4* PX_RESTRICT contacts = reinterpret_cast<SolverContactBatchPointDynamic4*>(currPtr);
Vec4V* maxImpulses;
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
PxU32 maxImpulseMask = 0;
if(hasMaxImpulse)
{
maxImpulseMask = 0xFFFFFFFF;
maxImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V) * numNormalConstr;
}
else
{
maxImpulses = &vMax;
}
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
Vec4V* frictionAppliedForce = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numFrictionConstr;
const SolverContactFrictionDynamic4* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionDynamic4*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionDynamic4);
Vec4V accumulatedNormalImpulse = vZero;
const Vec4V angD0 = hdr->angDom0;
const Vec4V angD1 = hdr->angDom1;
const Vec4V _normalT0 = hdr->normalX;
const Vec4V _normalT1 = hdr->normalY;
const Vec4V _normalT2 = hdr->normalZ;
Vec4V contactNormalVel1 = V4Mul(linVel0T0, _normalT0);
Vec4V contactNormalVel3 = V4Mul(linVel1T0, _normalT0);
contactNormalVel1 = V4MulAdd(linVel0T1, _normalT1, contactNormalVel1);
contactNormalVel3 = V4MulAdd(linVel1T1, _normalT1, contactNormalVel3);
contactNormalVel1 = V4MulAdd(linVel0T2, _normalT2, contactNormalVel1);
contactNormalVel3 = V4MulAdd(linVel1T2, _normalT2, contactNormalVel3);
Vec4V relVel1 = V4Sub(contactNormalVel1, contactNormalVel3);
Vec4V accumDeltaF = vZero;
for(PxU32 i=0;i<numNormalConstr;i++)
{
const SolverContactBatchPointDynamic4& c = contacts[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = appliedForces[i];
const Vec4V maxImpulse = maxImpulses[i & maxImpulseMask];
Vec4V contactNormalVel2 = V4Mul(c.raXnX, angState0T0);
Vec4V contactNormalVel4 = V4Mul(c.rbXnX, angState1T0);
contactNormalVel2 = V4MulAdd(c.raXnY, angState0T1, contactNormalVel2);
contactNormalVel4 = V4MulAdd(c.rbXnY, angState1T1, contactNormalVel4);
contactNormalVel2 = V4MulAdd(c.raXnZ, angState0T2, contactNormalVel2);
contactNormalVel4 = V4MulAdd(c.rbXnZ, angState1T2, contactNormalVel4);
const Vec4V normalVel = V4Add(relVel1, V4Sub(contactNormalVel2, contactNormalVel4));
Vec4V deltaF = V4NegMulSub(normalVel, c.velMultiplier, c.biasedErr);
deltaF = V4Max(deltaF, V4Neg(appliedForce));
const Vec4V newAppliedForce = V4Min(V4MulAdd(c.impulseMultiplier, appliedForce, deltaF), maxImpulse);
deltaF = V4Sub(newAppliedForce, appliedForce);
accumDeltaF = V4Add(accumDeltaF, deltaF);
const Vec4V angDetaF0 = V4Mul(deltaF, angD0);
const Vec4V angDetaF1 = V4Mul(deltaF, angD1);
relVel1 = V4MulAdd(sumInvMass, deltaF, relVel1);
angState0T0 = V4MulAdd(c.raXnX, angDetaF0, angState0T0);
angState1T0 = V4NegMulSub(c.rbXnX, angDetaF1, angState1T0);
angState0T1 = V4MulAdd(c.raXnY, angDetaF0, angState0T1);
angState1T1 = V4NegMulSub(c.rbXnY, angDetaF1, angState1T1);
angState0T2 = V4MulAdd(c.raXnZ, angDetaF0, angState0T2);
angState1T2 = V4NegMulSub(c.rbXnZ, angDetaF1, angState1T2);
appliedForces[i] = newAppliedForce;
accumulatedNormalImpulse = V4Add(accumulatedNormalImpulse, newAppliedForce);
}
const Vec4V accumDeltaF_IM0 = V4Mul(accumDeltaF, invMassA);
const Vec4V accumDeltaF_IM1 = V4Mul(accumDeltaF, invMassB);
linVel0T0 = V4MulAdd(_normalT0, accumDeltaF_IM0, linVel0T0);
linVel1T0 = V4NegMulSub(_normalT0, accumDeltaF_IM1, linVel1T0);
linVel0T1 = V4MulAdd(_normalT1, accumDeltaF_IM0, linVel0T1);
linVel1T1 = V4NegMulSub(_normalT1, accumDeltaF_IM1, linVel1T1);
linVel0T2 = V4MulAdd(_normalT2, accumDeltaF_IM0, linVel0T2);
linVel1T2 = V4NegMulSub(_normalT2, accumDeltaF_IM1, linVel1T2);
if(cache.doFriction && numFrictionConstr)
{
const Vec4V staticFric = hdr->staticFriction;
const Vec4V dynamicFric = hdr->dynamicFriction;
const Vec4V maxFrictionImpulse = V4Mul(staticFric, accumulatedNormalImpulse);
const Vec4V maxDynFrictionImpulse = V4Mul(dynamicFric, accumulatedNormalImpulse);
const Vec4V negMaxDynFrictionImpulse = V4Neg(maxDynFrictionImpulse);
//const Vec4V negMaxFrictionImpulse = V4Neg(maxFrictionImpulse);
BoolV broken = BFFFF();
if(cache.writeBackIteration)
{
PxPrefetchLine(fd->frictionBrokenWritebackByte[0]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[1]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[2]);
}
for(PxU32 i=0;i<numFrictionConstr;i++)
{
const SolverContactFrictionDynamic4& f = frictions[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = frictionAppliedForce[i];
const Vec4V normalT0 = fd->normalX[i&1];
const Vec4V normalT1 = fd->normalY[i&1];
const Vec4V normalT2 = fd->normalZ[i&1];
Vec4V normalVel1 = V4Mul(linVel0T0, normalT0);
Vec4V normalVel2 = V4Mul(f.raXnX, angState0T0);
Vec4V normalVel3 = V4Mul(linVel1T0, normalT0);
Vec4V normalVel4 = V4Mul(f.rbXnX, angState1T0);
normalVel1 = V4MulAdd(linVel0T1, normalT1, normalVel1);
normalVel2 = V4MulAdd(f.raXnY, angState0T1, normalVel2);
normalVel3 = V4MulAdd(linVel1T1, normalT1, normalVel3);
normalVel4 = V4MulAdd(f.rbXnY, angState1T1, normalVel4);
normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1);
normalVel2 = V4MulAdd(f.raXnZ, angState0T2, normalVel2);
normalVel3 = V4MulAdd(linVel1T2, normalT2, normalVel3);
normalVel4 = V4MulAdd(f.rbXnZ, angState1T2, normalVel4);
const Vec4V normalVel_tmp2 = V4Add(normalVel1, normalVel2);
const Vec4V normalVel_tmp1 = V4Add(normalVel3, normalVel4);
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const Vec4V normalVel = V4Sub(normalVel_tmp2, normalVel_tmp1 );
const Vec4V tmp1 = V4Sub(appliedForce, f.scaledBias);
const Vec4V totalImpulse = V4NegMulSub(normalVel, f.velMultiplier, tmp1);
broken = BOr(broken, V4IsGrtr(V4Abs(totalImpulse), maxFrictionImpulse));
const Vec4V newAppliedForce = V4Sel(broken, V4Min(maxDynFrictionImpulse, V4Max(negMaxDynFrictionImpulse, totalImpulse)), totalImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
frictionAppliedForce[i] = newAppliedForce;
const Vec4V deltaFIM0 = V4Mul(deltaF, invMassA);
const Vec4V deltaFIM1 = V4Mul(deltaF, invMassB);
const Vec4V angDetaF0 = V4Mul(deltaF, angD0);
const Vec4V angDetaF1 = V4Mul(deltaF, angD1);
linVel0T0 = V4MulAdd(normalT0, deltaFIM0, linVel0T0);
linVel1T0 = V4NegMulSub(normalT0, deltaFIM1, linVel1T0);
angState0T0 = V4MulAdd(f.raXnX, angDetaF0, angState0T0);
angState1T0 = V4NegMulSub(f.rbXnX, angDetaF1, angState1T0);
linVel0T1 = V4MulAdd(normalT1, deltaFIM0, linVel0T1);
linVel1T1 = V4NegMulSub(normalT1, deltaFIM1, linVel1T1);
angState0T1 = V4MulAdd(f.raXnY, angDetaF0, angState0T1);
angState1T1 = V4NegMulSub(f.rbXnY, angDetaF1, angState1T1);
linVel0T2 = V4MulAdd(normalT2, deltaFIM0, linVel0T2);
linVel1T2 = V4NegMulSub(normalT2, deltaFIM1, linVel1T2);
angState0T2 = V4MulAdd(f.raXnZ, angDetaF0, angState0T2);
angState1T2 = V4NegMulSub(f.rbXnZ, angDetaF1, angState1T2);
}
fd->broken = broken;
}
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularState.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularState.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularState.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularState.isFinite());
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState30, &b30.angularState.x);
if(desc[0].bodyBDataIndex != 0)
{
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(angState01, &b01.angularState.x);
}
if(desc[1].bodyBDataIndex != 0)
{
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(angState11, &b11.angularState.x);
}
if(desc[2].bodyBDataIndex != 0)
{
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(angState21, &b21.angularState.x);
}
if(desc[3].bodyBDataIndex != 0)
{
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState31, &b31.angularState.x);
}
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularState.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularState.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularState.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularState.isFinite());
}
static void solveContact4_StaticBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& cache)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b30 = *desc[3].bodyA;
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V vMax = V4Splat(FMax());
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
const PxU8* PX_RESTRICT prefetchAddress = currPtr + sizeof(SolverContactHeader4) + sizeof(SolverContactBatchPointBase4);
const SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
const Vec4V invMass0 = hdr->invMass0D0;
while((currPtr < last))
{
hdr = reinterpret_cast<const SolverContactHeader4*>(currPtr);
PX_ASSERT(hdr->type == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT);
currPtr = const_cast<PxU8*>(reinterpret_cast<const PxU8*>(hdr + 1));
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
Vec4V* appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactBatchPointBase4* PX_RESTRICT contacts = reinterpret_cast<SolverContactBatchPointBase4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
Vec4V* maxImpulses;
PxU32 maxImpulseMask;
if(hasMaxImpulse)
{
maxImpulseMask = 0xFFFFFFFF;
maxImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V) * numNormalConstr;
}
else
{
maxImpulseMask = 0;
maxImpulses = &vMax;
}
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
Vec4V* frictionAppliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numFrictionConstr;
const SolverContactFrictionBase4* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionBase4*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionBase4);
Vec4V accumulatedNormalImpulse = vZero;
const Vec4V angD0 = hdr->angDom0;
const Vec4V _normalT0 = hdr->normalX;
const Vec4V _normalT1 = hdr->normalY;
const Vec4V _normalT2 = hdr->normalZ;
Vec4V contactNormalVel1 = V4Mul(linVel0T0, _normalT0);
contactNormalVel1 = V4MulAdd(linVel0T1, _normalT1, contactNormalVel1);
contactNormalVel1 = V4MulAdd(linVel0T2, _normalT2, contactNormalVel1);
Vec4V accumDeltaF = vZero;
// numNormalConstr is the maxium number of normal constraints any of these 4 contacts have.
// Contacts with fewer normal constraints than that maximum apply zero force because their
// c.velMultiplier and c.biasedErr were set to zero in contact prepping (see the bFinished variables there)
for(PxU32 i=0;i<numNormalConstr;i++)
{
const SolverContactBatchPointBase4& c = contacts[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = appliedForces[i];
const Vec4V maxImpulse = maxImpulses[i&maxImpulseMask];
Vec4V contactNormalVel2 = V4MulAdd(c.raXnX, angState0T0, contactNormalVel1);
contactNormalVel2 = V4MulAdd(c.raXnY, angState0T1, contactNormalVel2);
const Vec4V normalVel = V4MulAdd(c.raXnZ, angState0T2, contactNormalVel2);
const Vec4V _deltaF = V4Max(V4NegMulSub(normalVel, c.velMultiplier, c.biasedErr), V4Neg(appliedForce));
Vec4V newAppliedForce(V4MulAdd(c.impulseMultiplier, appliedForce, _deltaF));
newAppliedForce = V4Min(newAppliedForce, maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V angDeltaF = V4Mul(angD0, deltaF);
accumDeltaF = V4Add(accumDeltaF, deltaF);
contactNormalVel1 = V4MulAdd(invMass0, deltaF, contactNormalVel1);
angState0T0 = V4MulAdd(c.raXnX, angDeltaF, angState0T0);
angState0T1 = V4MulAdd(c.raXnY, angDeltaF, angState0T1);
angState0T2 = V4MulAdd(c.raXnZ, angDeltaF, angState0T2);
#if 1
appliedForces[i] = newAppliedForce;
#endif
accumulatedNormalImpulse = V4Add(accumulatedNormalImpulse, newAppliedForce);
}
const Vec4V deltaFInvMass0 = V4Mul(accumDeltaF, invMass0);
linVel0T0 = V4MulAdd(_normalT0, deltaFInvMass0, linVel0T0);
linVel0T1 = V4MulAdd(_normalT1, deltaFInvMass0, linVel0T1);
linVel0T2 = V4MulAdd(_normalT2, deltaFInvMass0, linVel0T2);
if(cache.doFriction && numFrictionConstr)
{
const Vec4V staticFric = hdr->staticFriction;
const Vec4V dynamicFric = hdr->dynamicFriction;
const Vec4V maxFrictionImpulse = V4Mul(staticFric, accumulatedNormalImpulse);
const Vec4V maxDynFrictionImpulse = V4Mul(dynamicFric, accumulatedNormalImpulse);
const Vec4V negMaxDynFrictionImpulse = V4Neg(maxDynFrictionImpulse);
BoolV broken = BFFFF();
if(cache.writeBackIteration)
{
PxPrefetchLine(fd->frictionBrokenWritebackByte[0]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[1]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[2]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[3]);
}
for(PxU32 i=0;i<numFrictionConstr;i++)
{
const SolverContactFrictionBase4& f = frictions[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = frictionAppliedForces[i];
const Vec4V normalT0 = fd->normalX[i&1];
const Vec4V normalT1 = fd->normalY[i&1];
const Vec4V normalT2 = fd->normalZ[i&1];
Vec4V normalVel1 = V4Mul(linVel0T0, normalT0);
Vec4V normalVel2 = V4Mul(f.raXnX, angState0T0);
normalVel1 = V4MulAdd(linVel0T1, normalT1, normalVel1);
normalVel2 = V4MulAdd(f.raXnY, angState0T1, normalVel2);
normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1);
normalVel2 = V4MulAdd(f.raXnZ, angState0T2, normalVel2);
//relative normal velocity for all 4 constraints
const Vec4V normalVel = V4Add(normalVel1, normalVel2);
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const Vec4V tmp1 = V4Sub(appliedForce, f.scaledBias);
const Vec4V totalImpulse = V4NegMulSub(normalVel, f.velMultiplier, tmp1);
broken = BOr(broken, V4IsGrtr(V4Abs(totalImpulse), maxFrictionImpulse));
const Vec4V newAppliedForce = V4Sel(broken, V4Min(maxDynFrictionImpulse, V4Max(negMaxDynFrictionImpulse, totalImpulse)), totalImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaFInvMass = V4Mul(invMass0, deltaF);
const Vec4V angDeltaF = V4Mul(angD0, deltaF);
linVel0T0 = V4MulAdd(normalT0, deltaFInvMass, linVel0T0);
angState0T0 = V4MulAdd(f.raXnX, angDeltaF, angState0T0);
linVel0T1 = V4MulAdd(normalT1, deltaFInvMass, linVel0T1);
angState0T1 = V4MulAdd(f.raXnY, angDeltaF, angState0T1);
linVel0T2 = V4MulAdd(normalT2, deltaFInvMass, linVel0T2);
angState0T2 = V4MulAdd(f.raXnZ, angDeltaF, angState0T2);
#if 1
frictionAppliedForces[i] = newAppliedForce;
#endif
}
fd->broken = broken;
}
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
}
static void concludeContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/, PxU32 contactSize, PxU32 frictionSize)
{
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
while((currPtr < last))
{
const SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
currPtr = const_cast<PxU8*>(reinterpret_cast<const PxU8*>(hdr + 1));
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactBatchPointBase4* PX_RESTRICT contacts = reinterpret_cast<SolverContactBatchPointBase4*>(currPtr);
currPtr += (numNormalConstr * contactSize);
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
if(hasMaxImpulse)
currPtr += sizeof(Vec4V) * numNormalConstr;
currPtr += sizeof(Vec4V)*numFrictionConstr;
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
PX_UNUSED(fd);
SolverContactFrictionBase4* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionBase4*>(currPtr);
currPtr += (numFrictionConstr * frictionSize);
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContactBatchPointBase4& c = *contacts;
contacts = reinterpret_cast<SolverContactBatchPointBase4*>((reinterpret_cast<PxU8*>(contacts)) + contactSize);
c.biasedErr = V4Sub(c.biasedErr, c.scaledBias);
}
for(PxU32 i=0;i<numFrictionConstr;i++)
{
SolverContactFrictionBase4& f = *frictions;
frictions = reinterpret_cast<SolverContactFrictionBase4*>((reinterpret_cast<PxU8*>(frictions)) + frictionSize);
f.scaledBias = f.targetVelocity;
}
}
}
static void writeBackContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& cache,
const PxSolverBodyData** PX_RESTRICT bd0, const PxSolverBodyData** PX_RESTRICT bd1)
{
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxReal* PX_RESTRICT vForceWriteback0 = reinterpret_cast<PxReal*>(desc[0].writeBack);
PxReal* PX_RESTRICT vForceWriteback1 = reinterpret_cast<PxReal*>(desc[1].writeBack);
PxReal* PX_RESTRICT vForceWriteback2 = reinterpret_cast<PxReal*>(desc[2].writeBack);
PxReal* PX_RESTRICT vForceWriteback3 = reinterpret_cast<PxReal*>(desc[3].writeBack);
const PxU8 type = *desc[0].constraint;
const PxU32 contactSize = type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContactBatchPointDynamic4) : sizeof(SolverContactBatchPointBase4);
const PxU32 frictionSize = type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContactFrictionDynamic4) : sizeof(SolverContactFrictionBase4);
Vec4V normalForce = V4Zero();
//We'll need this.
//const Vec4V vZero = V4Zero();
bool writeBackThresholds[4] = {false, false, false, false};
while((currPtr < last))
{
SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
//SolverContactBatchPointBase4* PX_RESTRICT contacts = (SolverContactBatchPointBase4*)currPtr;
currPtr += (numNormalConstr * contactSize);
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
if(hasMaxImpulse)
currPtr += sizeof(Vec4V) * numNormalConstr;
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
currPtr += sizeof(Vec4V)*numFrictionConstr;
//SolverContactFrictionBase4* PX_RESTRICT frictions = (SolverContactFrictionBase4*)currPtr;
currPtr += (numFrictionConstr * frictionSize);
writeBackThresholds[0] = hdr->flags[0] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[1] = hdr->flags[1] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[2] = hdr->flags[2] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[3] = hdr->flags[3] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
for(PxU32 i=0;i<numNormalConstr;i++)
{
//contacts = (SolverContactBatchPointBase4*)(((PxU8*)contacts) + contactSize);
const FloatV appliedForce0 = V4GetX(appliedForces[i]);
const FloatV appliedForce1 = V4GetY(appliedForces[i]);
const FloatV appliedForce2 = V4GetZ(appliedForces[i]);
const FloatV appliedForce3 = V4GetW(appliedForces[i]);
normalForce = V4Add(normalForce, appliedForces[i]);
if(vForceWriteback0 && i < hdr->numNormalConstr0)
FStore(appliedForce0, vForceWriteback0++);
if(vForceWriteback1 && i < hdr->numNormalConstr1)
FStore(appliedForce1, vForceWriteback1++);
if(vForceWriteback2 && i < hdr->numNormalConstr2)
FStore(appliedForce2, vForceWriteback2++);
if(vForceWriteback3 && i < hdr->numNormalConstr3)
FStore(appliedForce3, vForceWriteback3++);
}
if(numFrictionConstr)
{
PX_ALIGN(16, PxU32 broken[4]);
BStoreA(fd->broken, broken);
PxU8* frictionCounts = &hdr->numFrictionConstr0;
for(PxU32 a = 0; a < 4; ++a)
{
if(frictionCounts[a] && broken[a])
*fd->frictionBrokenWritebackByte[a] = 1; // PT: bad L2 miss here
}
}
}
PX_ALIGN(16, PxReal nf[4]);
V4StoreA(normalForce, nf);
Sc::ShapeInteraction** shapeInteractions = reinterpret_cast<SolverContactHeader4*>(desc[0].constraint)->shapeInteraction;
for(PxU32 a = 0; a < 4; ++a)
{
if(writeBackThresholds[a] && desc[a].linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc[a].linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
nf[a] !=0.f && (bd0[a]->reportThreshold < PX_MAX_REAL || bd1[a]->reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = nf[a];
elt.threshold = PxMin<float>(bd0[a]->reportThreshold, bd1[a]->reportThreshold);
elt.nodeIndexA = PxNodeIndex(bd0[a]->nodeIndex);
elt.nodeIndexB = PxNodeIndex(bd1[a]->nodeIndex);
elt.shapeInteraction = shapeInteractions[a];
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
}
static void solve1D4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
PxU8* PX_RESTRICT bPtr = desc[0].constraint;
//PxU32 length = desc.constraintLength;
SolverConstraint1DHeader4* PX_RESTRICT header = reinterpret_cast<SolverConstraint1DHeader4*>(bPtr);
SolverConstraint1DDynamic4* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DDynamic4*>(header+1);
//const FloatV fZero = FZero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
const Vec4V invMass0D0 = header->invMass0D0;
const Vec4V invMass1D1 = header->invMass1D1;
const Vec4V angD0 = header->angD0;
const Vec4V angD1 = header->angD1;
const PxU32 maxConstraints = header->count;
for(PxU32 a = 0; a < maxConstraints; ++a)
{
SolverConstraint1DDynamic4& c = *base;
base++;
PxPrefetchLine(base);
PxPrefetchLine(base, 64);
PxPrefetchLine(base, 128);
PxPrefetchLine(base, 192);
PxPrefetchLine(base, 256);
const Vec4V appliedForce = c.appliedForce;
Vec4V linProj0(V4Mul(c.lin0X, linVel0T0));
Vec4V linProj1(V4Mul(c.lin1X, linVel1T0));
Vec4V angProj0(V4Mul(c.ang0X, angState0T0));
Vec4V angProj1(V4Mul(c.ang1X, angState1T0));
linProj0 = V4MulAdd(c.lin0Y, linVel0T1, linProj0);
linProj1 = V4MulAdd(c.lin1Y, linVel1T1, linProj1);
angProj0 = V4MulAdd(c.ang0Y, angState0T1, angProj0);
angProj1 = V4MulAdd(c.ang1Y, angState1T1, angProj1);
linProj0 = V4MulAdd(c.lin0Z, linVel0T2, linProj0);
linProj1 = V4MulAdd(c.lin1Z, linVel1T2, linProj1);
angProj0 = V4MulAdd(c.ang0Z, angState0T2, angProj0);
angProj1 = V4MulAdd(c.ang1Z, angState1T2, angProj1);
const Vec4V projectVel0 = V4Add(linProj0, angProj0);
const Vec4V projectVel1 = V4Add(linProj1, angProj1);
const Vec4V normalVel = V4Sub(projectVel0, projectVel1);
const Vec4V unclampedForce = V4MulAdd(appliedForce, c.impulseMultiplier, V4MulAdd(normalVel, c.velMultiplier, c.constant));
const Vec4V clampedForce = V4Max(c.minImpulse, V4Min(c.maxImpulse, unclampedForce));
const Vec4V deltaF = V4Sub(clampedForce, appliedForce);
c.appliedForce = clampedForce;
const Vec4V deltaFInvMass0 = V4Mul(deltaF, invMass0D0);
const Vec4V deltaFInvMass1 = V4Mul(deltaF, invMass1D1);
const Vec4V angDeltaFInvMass0 = V4Mul(deltaF, angD0);
const Vec4V angDeltaFInvMass1 = V4Mul(deltaF, angD1);
linVel0T0 = V4MulAdd(c.lin0X, deltaFInvMass0, linVel0T0);
linVel1T0 = V4NegMulSub(c.lin1X, deltaFInvMass1, linVel1T0);
angState0T0 = V4MulAdd(c.ang0X, angDeltaFInvMass0, angState0T0);
angState1T0 = V4NegMulSub(c.ang1X, angDeltaFInvMass1, angState1T0);
linVel0T1 = V4MulAdd(c.lin0Y, deltaFInvMass0, linVel0T1);
linVel1T1 = V4NegMulSub(c.lin1Y, deltaFInvMass1, linVel1T1);
angState0T1 = V4MulAdd(c.ang0Y, angDeltaFInvMass0, angState0T1);
angState1T1 = V4NegMulSub(c.ang1Y, angDeltaFInvMass1, angState1T1);
linVel0T2 = V4MulAdd(c.lin0Z, deltaFInvMass0, linVel0T2);
linVel1T2 = V4NegMulSub(c.lin1Z, deltaFInvMass1, linVel1T2);
angState0T2 = V4MulAdd(c.ang0Z, angDeltaFInvMass0, angState0T2);
angState1T2 = V4NegMulSub(c.ang1Z, angDeltaFInvMass1, angState1T2);
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
V4StoreA(angState01, &b01.angularState.x);
V4StoreA(angState11, &b11.angularState.x);
V4StoreA(angState21, &b21.angularState.x);
V4StoreA(angState31, &b31.angularState.x);
}
static void conclude1D4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
SolverConstraint1DHeader4* header = reinterpret_cast<SolverConstraint1DHeader4*>(desc[0].constraint);
PxU8* base = desc[0].constraint + sizeof(SolverConstraint1DHeader4);
const PxU32 stride = header->type == DY_SC_TYPE_BLOCK_1D ? sizeof(SolverConstraint1DDynamic4) : sizeof(SolverConstraint1DBase4);
const PxU32 count = header->count;
for(PxU32 i=0; i<count; i++)
{
SolverConstraint1DBase4& c = *reinterpret_cast<SolverConstraint1DBase4*>(base);
c.constant = c.unbiasedConstant;
base += stride;
}
PX_ASSERT(desc[0].constraint + getConstraintLength(desc[0]) == base);
}
static void writeBack1D4(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/,
const PxSolverBodyData** PX_RESTRICT /*bd0*/, const PxSolverBodyData** PX_RESTRICT /*bd1*/)
{
ConstraintWriteback* writeback0 = reinterpret_cast<ConstraintWriteback*>(desc[0].writeBack);
ConstraintWriteback* writeback1 = reinterpret_cast<ConstraintWriteback*>(desc[1].writeBack);
ConstraintWriteback* writeback2 = reinterpret_cast<ConstraintWriteback*>(desc[2].writeBack);
ConstraintWriteback* writeback3 = reinterpret_cast<ConstraintWriteback*>(desc[3].writeBack);
if(writeback0 || writeback1 || writeback2 || writeback3)
{
SolverConstraint1DHeader4* header = reinterpret_cast<SolverConstraint1DHeader4*>(desc[0].constraint);
PxU8* base = desc[0].constraint + sizeof(SolverConstraint1DHeader4);
PxU32 stride = header->type == DY_SC_TYPE_BLOCK_1D ? sizeof(SolverConstraint1DDynamic4) : sizeof(SolverConstraint1DBase4);
const Vec4V zero = V4Zero();
Vec4V linX(zero), linY(zero), linZ(zero);
Vec4V angX(zero), angY(zero), angZ(zero);
const PxU32 count = header->count;
for(PxU32 i=0; i<count; i++)
{
const SolverConstraint1DBase4* c = reinterpret_cast<SolverConstraint1DBase4*>(base);
//Load in flags
const VecI32V flags = I4LoadU(reinterpret_cast<const PxI32*>(&c->flags[0]));
//Work out masks
const VecI32V mask = I4Load(DY_SC_FLAG_OUTPUT_FORCE);
const VecI32V masked = VecI32V_And(flags, mask);
const BoolV isEq = VecI32V_IsEq(masked, mask);
const Vec4V appliedForce = V4Sel(isEq, c->appliedForce, zero);
linX = V4MulAdd(c->lin0X, appliedForce, linX);
linY = V4MulAdd(c->lin0Y, appliedForce, linY);
linZ = V4MulAdd(c->lin0Z, appliedForce, linZ);
angX = V4MulAdd(c->ang0WritebackX, appliedForce, angX);
angY = V4MulAdd(c->ang0WritebackY, appliedForce, angY);
angZ = V4MulAdd(c->ang0WritebackZ, appliedForce, angZ);
base += stride;
}
//We need to do the cross product now
angX = V4Sub(angX, V4NegMulSub(header->body0WorkOffsetZ, linY, V4Mul(header->body0WorkOffsetY, linZ)));
angY = V4Sub(angY, V4NegMulSub(header->body0WorkOffsetX, linZ, V4Mul(header->body0WorkOffsetZ, linX)));
angZ = V4Sub(angZ, V4NegMulSub(header->body0WorkOffsetY, linX, V4Mul(header->body0WorkOffsetX, linY)));
const Vec4V linLenSq = V4MulAdd(linZ, linZ, V4MulAdd(linY, linY, V4Mul(linX, linX)));
const Vec4V angLenSq = V4MulAdd(angZ, angZ, V4MulAdd(angY, angY, V4Mul(angX, angX)));
const Vec4V linLen = V4Sqrt(linLenSq);
const Vec4V angLen = V4Sqrt(angLenSq);
const BoolV broken = BOr(V4IsGrtr(linLen, header->linBreakImpulse), V4IsGrtr(angLen, header->angBreakImpulse));
PX_ALIGN(16, PxU32 iBroken[4]);
BStoreA(broken, iBroken);
Vec4V lin0, lin1, lin2, lin3;
Vec4V ang0, ang1, ang2, ang3;
PX_TRANSPOSE_34_44(linX, linY, linZ, lin0, lin1, lin2, lin3);
PX_TRANSPOSE_34_44(angX, angY, angZ, ang0, ang1, ang2, ang3);
if(writeback0)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin0), writeback0->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang0), writeback0->angularImpulse);
writeback0->broken = header->break0 ? PxU32(iBroken[0] != 0) : 0;
}
if(writeback1)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin1), writeback1->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang1), writeback1->angularImpulse);
writeback1->broken = header->break1 ? PxU32(iBroken[1] != 0) : 0;
}
if(writeback2)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin2), writeback2->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang2), writeback2->angularImpulse);
writeback2->broken = header->break2 ? PxU32(iBroken[2] != 0) : 0;
}
if(writeback3)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin3), writeback3->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang3), writeback3->angularImpulse);
writeback3->broken = header->break3 ? PxU32(iBroken[3] != 0) : 0;
}
PX_ASSERT(desc[0].constraint + getConstraintLength(desc[0]) == base);
}
}
void solveContactPreBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_Block(desc, cache);
}
void solveContactPreBlock_Static(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_StaticBlock(desc, cache);
}
void solveContactPreBlock_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_Block(desc, cache);
concludeContact4_Block(desc, cache, sizeof(SolverContactBatchPointDynamic4), sizeof(SolverContactFrictionDynamic4));
}
void solveContactPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_StaticBlock(desc, cache);
concludeContact4_Block(desc, cache, sizeof(SolverContactBatchPointBase4), sizeof(SolverContactFrictionBase4));
}
void solveContactPreBlock_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_Block(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContact4_Block(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveContactPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_StaticBlock(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContact4_Block(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solve1D4_Block(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solve1D4_Block(desc, cache);
}
void solve1D4Block_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solve1D4_Block(desc, cache);
conclude1D4_Block(desc, cache);
}
void solve1D4Block_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solve1D4_Block(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBack1D4(desc, cache, bd0, bd1);
}
void writeBack1D4Block(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 /*constraintCount*/, SolverContext& cache)
{
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBack1D4(desc, cache, bd0, bd1);
}
}
}
| 47,064 | C++ | 37.736625 | 150 | 0.748895 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CORE_H
#define DY_SOLVER_CORE_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxThread.h"
#include "foundation/PxUserAllocated.h"
// PT: it is not wrong to include DyPGS.h here because the SolverCore class is actually only used by PGS.
// (for patch / point friction). TGS doesn't use the same architecture / class hierarchy.
#include "DyPGS.h"
namespace physx
{
struct PxSolverBody;
struct PxSolverBodyData;
struct PxSolverConstraintDesc;
struct PxConstraintBatchHeader;
namespace Dy
{
struct ThresholdStreamElement;
struct ArticulationSolverDesc;
#define PX_PROFILE_SOLVE_STALLS 0
#if PX_PROFILE_SOLVE_STALLS
#if PX_WINDOWS
#include "foundation/windows/PxWindowsInclude.h"
PX_FORCE_INLINE PxU64 readTimer()
{
//return __rdtsc();
LARGE_INTEGER i;
QueryPerformanceCounter(&i);
return i.QuadPart;
}
#endif
#endif
#define YIELD_THREADS 1
#if YIELD_THREADS
#define ATTEMPTS_BEFORE_BACKOFF 30000
#define ATTEMPTS_BEFORE_RETEST 10000
#endif
PX_INLINE void WaitForProgressCount(volatile PxI32* pGlobalIndex, const PxI32 targetIndex)
{
#if YIELD_THREADS
if(*pGlobalIndex < targetIndex)
{
bool satisfied = false;
PxU32 count = ATTEMPTS_BEFORE_BACKOFF;
do
{
satisfied = true;
while(*pGlobalIndex < targetIndex)
{
if(--count == 0)
{
satisfied = false;
break;
}
}
if(!satisfied)
PxThread::yield();
count = ATTEMPTS_BEFORE_RETEST;
}
while(!satisfied);
}
#else
while(*pGlobalIndex < targetIndex);
#endif
}
#if PX_PROFILE_SOLVE_STALLS
PX_INLINE void WaitForProgressCount(volatile PxI32* pGlobalIndex, const PxI32 targetIndex, PxU64& stallTime)
{
if(*pGlobalIndex < targetIndex)
{
bool satisfied = false;
PxU32 count = ATTEMPTS_BEFORE_BACKOFF;
do
{
satisfied = true;
PxU64 startTime = readTimer();
while(*pGlobalIndex < targetIndex)
{
if(--count == 0)
{
satisfied = false;
break;
}
}
PxU64 endTime = readTimer();
stallTime += (endTime - startTime);
if(!satisfied)
PxThread::yield();
count = ATTEMPTS_BEFORE_BACKOFF;
}
while(!satisfied);
}
}
#define WAIT_FOR_PROGRESS(pGlobalIndex, targetIndex) if(*pGlobalIndex < targetIndex) WaitForProgressCount(pGlobalIndex, targetIndex, stallCount)
#else
#define WAIT_FOR_PROGRESS(pGlobalIndex, targetIndex) if(*pGlobalIndex < targetIndex) WaitForProgressCount(pGlobalIndex, targetIndex)
#endif
#define WAIT_FOR_PROGRESS_NO_TIMER(pGlobalIndex, targetIndex) if(*pGlobalIndex < targetIndex) WaitForProgressCount(pGlobalIndex, targetIndex)
struct SolverIslandParams
{
//Default friction model params
PxU32 positionIterations;
PxU32 velocityIterations;
PxSolverBody* PX_RESTRICT bodyListStart;
PxSolverBodyData* PX_RESTRICT bodyDataList;
PxU32 bodyListSize;
PxU32 solverBodyOffset;
ArticulationSolverDesc* PX_RESTRICT articulationListStart;
PxU32 articulationListSize;
PxSolverConstraintDesc* PX_RESTRICT constraintList;
PxConstraintBatchHeader* constraintBatchHeaders;
PxU32 numConstraintHeaders;
PxU32* headersPerPartition;
PxU32 nbPartitions;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray;
PxU32 batchSize;
PxsBodyCore*const* bodyArray;
PxsRigidBody** PX_RESTRICT rigidBodies;
//Shared state progress counters
PxI32 constraintIndex;
PxI32 constraintIndexCompleted;
PxI32 bodyListIndex;
PxI32 bodyListIndexCompleted;
PxI32 articSolveIndex;
PxI32 articSolveIndexCompleted;
PxI32 bodyIntegrationListIndex;
PxI32 numObjectsIntegrated;
PxReal dt;
PxReal invDt;
//Additional 1d/2d friction model params
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList;
PxConstraintBatchHeader* frictionConstraintBatches;
PxU32 numFrictionConstraintHeaders;
PxU32* frictionHeadersPerPartition;
PxU32 nbFrictionPartitions;
//Additional Shared state progress counters
PxI32 frictionConstraintIndex;
//Write-back threshold information
ThresholdStreamElement* PX_RESTRICT thresholdStream;
PxU32 thresholdStreamLength;
PxI32* outThresholdPairs;
PxU32 mMaxArticulationLinks;
Cm::SpatialVectorF* Z;
Cm::SpatialVectorF* deltaV;
};
/*!
Interface to constraint solver cores
*/
class SolverCore : public PxUserAllocated
{
public:
virtual ~SolverCore() {}
/*
solves dual problem exactly by GS-iterating until convergence stops
only uses regular velocity vector for storing results, and backs up initial state, which is restored.
the solution forces are saved in a vector.
state should not be stored, this function is safe to call from multiple threads.
*/
virtual void solveVParallelAndWriteBack
(SolverIslandParams& params, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const = 0;
virtual void solveV_Blocks
(SolverIslandParams& params) const = 0;
};
}
}
#endif
| 6,443 | C | 27.64 | 144 | 0.767344 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSContactPrep.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_TGS_CONTACT_PREP_H
#define DY_TGS_CONTACT_PREP_H
#include "foundation/PxPreprocessor.h"
#include "DySolverConstraintDesc.h"
#include "PxSceneDesc.h"
#include "DySolverContact4.h"
namespace physx
{
struct PxsContactManagerOutput;
struct PxSolverConstraintDesc;
namespace Dy
{
class ThreadContext;
struct CorrelationBuffer;
bool createFinalizeSolverContactsStep(PxTGSSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal invTotalDtF32,
const PxReal totalDtF32,
const PxReal stepDt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
bool createFinalizeSolverContactsStep(
PxTGSSolverContactDesc& contactDesc,
CorrelationBuffer& c,
const PxReal invDtF32,
const PxReal invTotalDtF32,
const PxReal totalDtF32,
const PxReal dtF32,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows,
const PxReal lengthScale, const PxReal biasCoefficient);
PxU32 SetupSolverConstraintStep(SolverConstraintShaderPrepDesc& shaderDesc,
PxTGSSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
const PxReal dt, const PxReal totalDt, const PxReal invdt, const PxReal invTotalDt,
const PxReal lengthScale, const PxReal biasCoefficient);
PxU32 setupSolverConstraintStep(
const PxTGSSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
const PxReal dt, const PxReal totalDt, const PxReal invdt, const PxReal invTotalDt,
const PxReal lengthScale, const PxReal biasCoefficient);
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs,
PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, const PxReal lengthScale, const PxReal biasCoefficient);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step(
PxsContactManagerOutput** cmOutputs,
ThreadContext& threadContext,
PxTGSSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal totalDtF32,
const PxReal invTotalDtF32,
const PxReal dt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step(
Dy::CorrelationBuffer& c,
PxTGSSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal totalDt,
const PxReal invTotalDtF32,
const PxReal dt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
}
}
#endif
| 5,154 | C | 39.590551 | 108 | 0.794529 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyRigidBodyToSolverBody.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 "CmUtils.h"
#include "DySolverBody.h"
#include "PxsRigidBody.h"
#include "PxvDynamics.h"
#include "foundation/PxSIMDHelpers.h"
using namespace physx;
// PT: TODO: SIMDify all this...
void Dy::copyToSolverBodyData(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold, PxSolverBodyData& data, PxU32 lockFlags,
PxReal dt, bool gyroscopicForces)
{
data.nodeIndex = nodeIndex;
const PxVec3 safeSqrtInvInertia = computeSafeSqrtInertia(invInertia);
const PxMat33Padded rotation(globalPose.q);
Cm::transformInertiaTensor(safeSqrtInvInertia, rotation, data.sqrtInvInertia);
PxVec3 ang = angularVelocity;
PxVec3 lin = linearVelocity;
if (gyroscopicForces)
{
const PxVec3 localInertia(
invInertia.x == 0.f ? 0.f : 1.f / invInertia.x,
invInertia.y == 0.f ? 0.f : 1.f / invInertia.y,
invInertia.z == 0.f ? 0.f : 1.f / invInertia.z);
const PxVec3 localAngVel = globalPose.q.rotateInv(ang);
const PxVec3 origMom = localInertia.multiply(localAngVel);
const PxVec3 torque = -localAngVel.cross(origMom);
PxVec3 newMom = origMom + torque * dt;
const PxReal denom = newMom.magnitude();
const PxReal ratio = denom > 0.f ? origMom.magnitude() / denom : 0.f;
newMom *= ratio;
const PxVec3 newDeltaAngVel = globalPose.q.rotate(invInertia.multiply(newMom) - localAngVel);
ang += newDeltaAngVel;
}
if (lockFlags)
{
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
data.linearVelocity.x = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
data.linearVelocity.y = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
data.linearVelocity.z = 0.f;
//KS - technically, we can zero the inertia columns and produce stiffer constraints. However, this can cause numerical issues with the
//joint solver, which is fixed by disabling joint preprocessing and setting minResponseThreshold to some reasonable value > 0. However, until
//this is handled automatically, it's probably better not to zero these inertia rows
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
{
ang.x = 0.f;
//data.sqrtInvInertia.column0 = PxVec3(0.f);
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
{
ang.y = 0.f;
//data.sqrtInvInertia.column1 = PxVec3(0.f);
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
{
ang.z = 0.f;
//data.sqrtInvInertia.column2 = PxVec3(0.f);
}
}
PX_ASSERT(lin.isFinite());
PX_ASSERT(ang.isFinite());
data.angularVelocity = ang;
data.linearVelocity = lin;
data.invMass = invMass;
data.penBiasClamp = maxDepenetrationVelocity;
data.maxContactImpulse = maxContactImpulse;
data.body2World = globalPose;
data.reportThreshold = reportThreshold;
}
| 4,574 | C++ | 39.131579 | 163 | 0.749016 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintSetup.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "foundation/PxMathUtils.h"
#include "DyConstraintPrep.h"
#include "DyArticulationCpuGpu.h"
#include "PxsRigidBody.h"
#include "DySolverConstraint1D.h"
#include "foundation/PxSort.h"
#include "DySolverConstraintDesc.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
#include "foundation/PxSIMDHelpers.h"
namespace physx
{
namespace Dy
{
// dsequeira:
//
// we can choose any linear combination of equality constraints and get the same solution
// Hence we can orthogonalize the constraints using the inner product given by the
// inverse mass matrix, so that when we use PGS, solving a constraint row for a joint
// don't disturb the solution of prior rows.
//
// We also eliminate the equality constraints from the hard inequality constraints -
// (essentially projecting the direction corresponding to the lagrange multiplier
// onto the equality constraint subspace) but 'til I've verified this generates
// exactly the same KKT/complementarity conditions, status is 'experimental'.
//
// since for equality constraints the resulting rows have the property that applying
// an impulse along one row doesn't alter the projected velocity along another row,
// all equality constraints (plus one inequality constraint) can be processed in parallel
// using SIMD
//
// Eliminating the inequality constraints from each other would require a solver change
// and not give us any more parallelism, although we might get better convergence.
namespace
{
PX_FORCE_INLINE Vec3V V3FromV4(Vec4V x) { return Vec3V_From_Vec4V(x); }
PX_FORCE_INLINE Vec3V V3FromV4Unsafe(Vec4V x) { return Vec3V_From_Vec4V_WUndefined(x); }
PX_FORCE_INLINE Vec4V V4FromV3(Vec3V x) { return Vec4V_From_Vec3V(x); }
//PX_FORCE_INLINE Vec4V V4ClearW(Vec4V x) { return V4SetW(x, FZero()); }
struct MassProps
{
FloatV invMass0;
FloatV invMass1;
FloatV invInertiaScale0;
FloatV invInertiaScale1;
PX_FORCE_INLINE MassProps(const PxReal imass0, const PxReal imass1, const PxConstraintInvMassScale& ims) :
invMass0(FLoad(imass0 * ims.linear0)),
invMass1(FLoad(imass1 * ims.linear1)),
invInertiaScale0(FLoad(ims.angular0)),
invInertiaScale1(FLoad(ims.angular1))
{}
};
PX_FORCE_INLINE PxReal innerProduct(const Px1DConstraint& row0, Px1DConstraint& row1,
PxVec4& row0AngSqrtInvInertia0, PxVec4& row0AngSqrtInvInertia1,
PxVec4& row1AngSqrtInvInertia0, PxVec4& row1AngSqrtInvInertia1, const MassProps& m)
{
const Vec3V l0 = V3Mul(V3Scale(V3LoadA(row0.linear0), m.invMass0), V3LoadA(row1.linear0));
const Vec3V l1 = V3Mul(V3Scale(V3LoadA(row0.linear1), m.invMass1), V3LoadA(row1.linear1));
const Vec4V r0ang0 = V4LoadA(&row0AngSqrtInvInertia0.x);
const Vec4V r1ang0 = V4LoadA(&row1AngSqrtInvInertia0.x);
const Vec4V r0ang1 = V4LoadA(&row0AngSqrtInvInertia1.x);
const Vec4V r1ang1 = V4LoadA(&row1AngSqrtInvInertia1.x);
const Vec3V i0 = V3ScaleAdd(V3Mul(Vec3V_From_Vec4V(r0ang0), Vec3V_From_Vec4V(r1ang0)), m.invInertiaScale0, l0);
const Vec3V i1 = V3ScaleAdd(V3MulAdd(Vec3V_From_Vec4V(r0ang1), Vec3V_From_Vec4V(r1ang1), i0), m.invInertiaScale1, l1);
PxF32 f;
FStore(V3SumElems(i1), &f);
return f;
}
// indexed rotation around axis, with sine and cosine of half-angle
PX_FORCE_INLINE PxQuat indexedRotation(PxU32 axis, PxReal s, PxReal c)
{
PxQuat q(0,0,0,c);
reinterpret_cast<PxReal*>(&q)[axis] = s;
return q;
}
PxQuat diagonalize(const PxMat33& m) // jacobi rotation using quaternions
{
const PxU32 MAX_ITERS = 5;
PxQuat q(PxIdentity);
PxMat33 d;
for(PxU32 i=0; i < MAX_ITERS;i++)
{
const PxMat33Padded axes(q);
d = axes.getTranspose() * m * axes;
const PxReal d0 = PxAbs(d[1][2]), d1 = PxAbs(d[0][2]), d2 = PxAbs(d[0][1]);
const PxU32 a = PxU32(d0 > d1 && d0 > d2 ? 0 : d1 > d2 ? 1 : 2); // rotation axis index, from largest off-diagonal element
const PxU32 a1 = PxGetNextIndex3(a), a2 = PxGetNextIndex3(a1);
if(d[a1][a2] == 0.0f || PxAbs(d[a1][a1]-d[a2][a2]) > 2e6f*PxAbs(2.0f*d[a1][a2]))
break;
const PxReal w = (d[a1][a1]-d[a2][a2]) / (2.0f*d[a1][a2]); // cot(2 * phi), where phi is the rotation angle
const PxReal absw = PxAbs(w);
PxQuat r;
if(absw>1000)
r = indexedRotation(a, 1.0f/(4.0f*w), 1.f); // h will be very close to 1, so use small angle approx instead
else
{
const PxReal t = 1 / (absw + PxSqrt(w*w+1)); // absolute value of tan phi
const PxReal h = 1 / PxSqrt(t*t+1); // absolute value of cos phi
PX_ASSERT(h!=1); // |w|<1000 guarantees this with typical IEEE754 machine eps (approx 6e-8)
r = indexedRotation(a, PxSqrt((1-h)/2) * PxSign(w), PxSqrt((1+h)/2));
}
q = (q*r).getNormalized();
}
return q;
}
PX_FORCE_INLINE void rescale(const Mat33V& m, PxVec3& a0, PxVec3& a1, PxVec3& a2)
{
const Vec3V va0 = V3LoadU(a0);
const Vec3V va1 = V3LoadU(a1);
const Vec3V va2 = V3LoadU(a2);
const Vec3V b0 = V3ScaleAdd(va0, V3GetX(m.col0), V3ScaleAdd(va1, V3GetY(m.col0), V3Scale(va2, V3GetZ(m.col0))));
const Vec3V b1 = V3ScaleAdd(va0, V3GetX(m.col1), V3ScaleAdd(va1, V3GetY(m.col1), V3Scale(va2, V3GetZ(m.col1))));
const Vec3V b2 = V3ScaleAdd(va0, V3GetX(m.col2), V3ScaleAdd(va1, V3GetY(m.col2), V3Scale(va2, V3GetZ(m.col2))));
V3StoreU(b0, a0);
V3StoreU(b1, a1);
V3StoreU(b2, a2);
}
PX_FORCE_INLINE void rescale4(const Mat33V& m, PxReal* a0, PxReal* a1, PxReal* a2)
{
const Vec4V va0 = V4LoadA(a0);
const Vec4V va1 = V4LoadA(a1);
const Vec4V va2 = V4LoadA(a2);
const Vec4V b0 = V4ScaleAdd(va0, V3GetX(m.col0), V4ScaleAdd(va1, V3GetY(m.col0), V4Scale(va2, V3GetZ(m.col0))));
const Vec4V b1 = V4ScaleAdd(va0, V3GetX(m.col1), V4ScaleAdd(va1, V3GetY(m.col1), V4Scale(va2, V3GetZ(m.col1))));
const Vec4V b2 = V4ScaleAdd(va0, V3GetX(m.col2), V4ScaleAdd(va1, V3GetY(m.col2), V4Scale(va2, V3GetZ(m.col2))));
V4StoreA(b0, a0);
V4StoreA(b1, a1);
V4StoreA(b2, a2);
}
void diagonalize(Px1DConstraint** row,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
const MassProps &m)
{
const PxReal a00 = innerProduct(*row[0], *row[0], angSqrtInvInertia0[0], angSqrtInvInertia1[0], angSqrtInvInertia0[0], angSqrtInvInertia1[0], m);
const PxReal a01 = innerProduct(*row[0], *row[1], angSqrtInvInertia0[0], angSqrtInvInertia1[0], angSqrtInvInertia0[1], angSqrtInvInertia1[1], m);
const PxReal a02 = innerProduct(*row[0], *row[2], angSqrtInvInertia0[0], angSqrtInvInertia1[0], angSqrtInvInertia0[2], angSqrtInvInertia1[2], m);
const PxReal a11 = innerProduct(*row[1], *row[1], angSqrtInvInertia0[1], angSqrtInvInertia1[1], angSqrtInvInertia0[1], angSqrtInvInertia1[1], m);
const PxReal a12 = innerProduct(*row[1], *row[2], angSqrtInvInertia0[1], angSqrtInvInertia1[1], angSqrtInvInertia0[2], angSqrtInvInertia1[2], m);
const PxReal a22 = innerProduct(*row[2], *row[2], angSqrtInvInertia0[2], angSqrtInvInertia1[2], angSqrtInvInertia0[2], angSqrtInvInertia1[2], m);
const PxMat33 a(PxVec3(a00, a01, a02),
PxVec3(a01, a11, a12),
PxVec3(a02, a12, a22));
const PxQuat q = diagonalize(a);
const PxMat33 n(-q);
const Mat33V mn(V3LoadU(n.column0), V3LoadU(n.column1), V3LoadU(n.column2));
//KS - We treat as a Vec4V so that we get geometricError rescaled for free along with linear0
rescale4(mn, &row[0]->linear0.x, &row[1]->linear0.x, &row[2]->linear0.x);
rescale(mn, row[0]->linear1, row[1]->linear1, row[2]->linear1);
//KS - We treat as a PxVec4 so that we get velocityTarget rescaled for free
rescale4(mn, &row[0]->angular0.x, &row[1]->angular0.x, &row[2]->angular0.x);
rescale(mn, row[0]->angular1, row[1]->angular1, row[2]->angular1);
rescale4(mn, &angSqrtInvInertia0[0].x, &angSqrtInvInertia0[1].x, &angSqrtInvInertia0[2].x);
rescale4(mn, &angSqrtInvInertia1[0].x, &angSqrtInvInertia1[1].x, &angSqrtInvInertia1[2].x);
}
void orthogonalize(Px1DConstraint** row,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
PxU32 rowCount,
PxU32 eqRowCount,
const MassProps &m)
{
PX_ASSERT(eqRowCount<=6);
const FloatV zero = FZero();
Vec3V lin1m[6], ang1m[6], lin1[6], ang1[6];
Vec4V lin0m[6], ang0m[6]; // must have 0 in the W-field
Vec4V lin0AndG[6], ang0AndT[6];
for(PxU32 i=0;i<rowCount;i++)
{
Vec4V l0AndG = V4LoadA(&row[i]->linear0.x); // linear0 and geometric error
Vec4V a0AndT = V4LoadA(&row[i]->angular0.x); // angular0 and velocity target
Vec3V l1 = V3FromV4(V4LoadA(&row[i]->linear1.x));
Vec3V a1 = V3FromV4(V4LoadA(&row[i]->angular1.x));
Vec4V angSqrtL0 = V4LoadA(&angSqrtInvInertia0[i].x);
Vec4V angSqrtL1 = V4LoadA(&angSqrtInvInertia1[i].x);
const PxU32 eliminationRows = PxMin<PxU32>(i, eqRowCount);
for(PxU32 j=0;j<eliminationRows;j++)
{
const Vec3V s0 = V3MulAdd(l1, lin1m[j], V3FromV4Unsafe(V4Mul(l0AndG, lin0m[j])));
const Vec3V s1 = V3MulAdd(V3FromV4Unsafe(angSqrtL1), ang1m[j], V3FromV4Unsafe(V4Mul(angSqrtL0, ang0m[j])));
const FloatV t = V3SumElems(V3Add(s0, s1));
l0AndG = V4NegScaleSub(lin0AndG[j], t, l0AndG);
a0AndT = V4NegScaleSub(ang0AndT[j], t, a0AndT);
l1 = V3NegScaleSub(lin1[j], t, l1);
a1 = V3NegScaleSub(ang1[j], t, a1);
angSqrtL0 = V4NegScaleSub(V4LoadA(&angSqrtInvInertia0[j].x), t, angSqrtL0);
angSqrtL1 = V4NegScaleSub(V4LoadA(&angSqrtInvInertia1[j].x), t, angSqrtL1);
}
V4StoreA(l0AndG, &row[i]->linear0.x);
V4StoreA(a0AndT, &row[i]->angular0.x);
V3StoreA(l1, row[i]->linear1);
V3StoreA(a1, row[i]->angular1);
V4StoreA(angSqrtL0, &angSqrtInvInertia0[i].x);
V4StoreA(angSqrtL1, &angSqrtInvInertia1[i].x);
if(i<eqRowCount)
{
lin0AndG[i] = l0AndG;
ang0AndT[i] = a0AndT;
lin1[i] = l1;
ang1[i] = a1;
const Vec3V l0 = V3FromV4(l0AndG);
const Vec3V l0m = V3Scale(l0, m.invMass0);
const Vec3V l1m = V3Scale(l1, m.invMass1);
const Vec4V a0m = V4Scale(angSqrtL0, m.invInertiaScale0);
const Vec4V a1m = V4Scale(angSqrtL1, m.invInertiaScale1);
const Vec3V s0 = V3MulAdd(l0, l0m, V3Mul(l1, l1m));
const Vec4V s1 = V4MulAdd(a0m, angSqrtL0, V4Mul(a1m, angSqrtL1));
const FloatV s = V3SumElems(V3Add(s0, V3FromV4Unsafe(s1)));
const FloatV a = FSel(FIsGrtr(s, zero), FRecip(s), zero); // with mass scaling, it's possible for the inner product of a row to be zero
lin0m[i] = V4Scale(V4ClearW(V4FromV3(l0m)), a);
ang0m[i] = V4Scale(V4ClearW(a0m), a);
lin1m[i] = V3Scale(l1m, a);
ang1m[i] = V3Scale(V3FromV4Unsafe(a1m), a);
}
}
}
}
// PT: make sure that there's at least a PxU32 after sqrtInvInertia in the PxSolverBodyData structure (for safe SIMD reads)
//PX_COMPILE_TIME_ASSERT((sizeof(PxSolverBodyData) - PX_OFFSET_OF_RT(PxSolverBodyData, sqrtInvInertia)) >= (sizeof(PxMat33) + sizeof(PxU32)));
// PT: make sure that there's at least a PxU32 after angular0/angular1 in the Px1DConstraint structure (for safe SIMD reads)
// Note that the code was V4LoadAding these before anyway so it must be safe already.
// PT: removed for now because some compilers didn't like it
//PX_COMPILE_TIME_ASSERT((sizeof(Px1DConstraint) - PX_OFFSET_OF_RT(Px1DConstraint, angular0)) >= (sizeof(PxVec3) + sizeof(PxU32)));
//PX_COMPILE_TIME_ASSERT((sizeof(Px1DConstraint) - PX_OFFSET_OF_RT(Px1DConstraint, angular1)) >= (sizeof(PxVec3) + sizeof(PxU32)));
// PT: TODO: move somewhere else
PX_FORCE_INLINE Vec3V M33MulV4(const Mat33V& a, const Vec4V b)
{
const FloatV x = V4GetX(b);
const FloatV y = V4GetY(b);
const FloatV z = V4GetZ(b);
const Vec3V v0 = V3Scale(a.col0, x);
const Vec3V v1 = V3Scale(a.col1, y);
const Vec3V v2 = V3Scale(a.col2, z);
const Vec3V v0PlusV1 = V3Add(v0, v1);
return V3Add(v0PlusV1, v2);
}
void preprocessRows(Px1DConstraint** sorted,
Px1DConstraint* rows,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
PxU32 rowCount,
const PxMat33& sqrtInvInertia0F32,
const PxMat33& sqrtInvInertia1F32,
const PxReal invMass0,
const PxReal invMass1,
const PxConstraintInvMassScale& ims,
bool disablePreprocessing,
bool diagonalizeDrive)
{
// j is maxed at 12, typically around 7, so insertion sort is fine
for(PxU32 i=0; i<rowCount; i++)
{
Px1DConstraint* r = rows+i;
PxU32 j = i;
for(;j>0 && r->solveHint < sorted[j-1]->solveHint; j--)
sorted[j] = sorted[j-1];
sorted[j] = r;
}
for(PxU32 i=0;i<rowCount-1;i++)
PX_ASSERT(sorted[i]->solveHint <= sorted[i+1]->solveHint);
for (PxU32 i = 0; i<rowCount; i++)
rows[i].forInternalUse = rows[i].flags & Px1DConstraintFlag::eKEEPBIAS ? rows[i].geometricError : 0;
const Mat33V sqrtInvInertia0 = Mat33V(V3LoadU(sqrtInvInertia0F32.column0), V3LoadU(sqrtInvInertia0F32.column1),
V3LoadU(sqrtInvInertia0F32.column2));
const Mat33V sqrtInvInertia1 = Mat33V(V3LoadU(sqrtInvInertia1F32.column0), V3LoadU(sqrtInvInertia1F32.column1),
V3LoadU(sqrtInvInertia1F32.column2));
PX_ASSERT(((uintptr_t(angSqrtInvInertia0)) & 0xF) == 0);
PX_ASSERT(((uintptr_t(angSqrtInvInertia1)) & 0xF) == 0);
for(PxU32 i=0; i<rowCount; ++i)
{
// PT: new version is 10 instructions smaller
//const Vec3V angDelta0_ = M33MulV3(sqrtInvInertia0, V3LoadU(sorted[i]->angular0));
//const Vec3V angDelta1_ = M33MulV3(sqrtInvInertia1, V3LoadU(sorted[i]->angular1));
const Vec3V angDelta0 = M33MulV4(sqrtInvInertia0, V4LoadA(&sorted[i]->angular0.x));
const Vec3V angDelta1 = M33MulV4(sqrtInvInertia1, V4LoadA(&sorted[i]->angular1.x));
V4StoreA(Vec4V_From_Vec3V(angDelta0), &angSqrtInvInertia0[i].x);
V4StoreA(Vec4V_From_Vec3V(angDelta1), &angSqrtInvInertia1[i].x);
}
if(disablePreprocessing)
return;
MassProps m(invMass0, invMass1, ims);
for(PxU32 i=0;i<rowCount;)
{
const PxU32 groupMajorId = PxU32(sorted[i]->solveHint>>8), start = i++;
while(i<rowCount && PxU32(sorted[i]->solveHint>>8) == groupMajorId)
i++;
if(groupMajorId == 4 || (groupMajorId == 8))
{
PxU32 bCount = start; // count of bilateral constraints
for(; bCount<i && (sorted[bCount]->solveHint&255)==0; bCount++)
;
orthogonalize(sorted+start, angSqrtInvInertia0+start, angSqrtInvInertia1+start, i-start, bCount-start, m);
}
if(groupMajorId == 1 && diagonalizeDrive)
{
PxU32 slerp = start; // count of bilateral constraints
for(; slerp<i && (sorted[slerp]->solveHint&255)!=2; slerp++)
;
if(slerp+3 == i)
diagonalize(sorted+slerp, angSqrtInvInertia0+slerp, angSqrtInvInertia1+slerp, m);
PX_ASSERT(i-start==3);
diagonalize(sorted+start, angSqrtInvInertia0+start, angSqrtInvInertia1+start, m);
}
}
}
PxU32 ConstraintHelper::setupSolverConstraint(
PxSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
PxReal dt, PxReal invdt,
Cm::SpatialVectorF* Z)
{
if (prepDesc.numRows == 0)
{
prepDesc.desc->constraint = NULL;
prepDesc.desc->writeBack = NULL;
prepDesc.desc->constraintLengthOver16 = 0;
return 0;
}
PxSolverConstraintDesc& desc = *prepDesc.desc;
const bool isExtended = (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY)
|| (desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY);
const PxU32 stride = isExtended ? sizeof(SolverConstraint1DExt) : sizeof(SolverConstraint1D);
const PxU32 constraintLength = sizeof(SolverConstraint1DHeader) + stride * prepDesc.numRows;
//KS - +16 is for the constraint progress counter, which needs to be the last element in the constraint (so that we
//know SPU DMAs have completed)
PxU8* ptr = allocator.reserveConstraintData(constraintLength + 16u);
if(NULL == ptr || (reinterpret_cast<PxU8*>(-1))==ptr)
{
if(NULL==ptr)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept joints detaching/exploding or increase buffer size allocated for constraint prep by increasing PxSceneDesc::maxNbContactDataBlocks.");
return 0;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of constraint data. "
"Either accept joints detaching/exploding or simplify constraints.");
ptr=NULL;
return 0;
}
}
desc.constraint = ptr;
setConstraintLength(desc,constraintLength);
desc.writeBack = prepDesc.writeback;
PxMemSet(desc.constraint, 0, constraintLength);
SolverConstraint1DHeader* header = reinterpret_cast<SolverConstraint1DHeader*>(desc.constraint);
PxU8* constraints = desc.constraint + sizeof(SolverConstraint1DHeader);
init(*header, PxTo8(prepDesc.numRows), isExtended, prepDesc.invMassScales);
header->body0WorldOffset = prepDesc.body0WorldOffset;
header->linBreakImpulse = prepDesc.linBreakForce * dt;
header->angBreakImpulse = prepDesc.angBreakForce * dt;
header->breakable = PxU8((prepDesc.linBreakForce != PX_MAX_F32) || (prepDesc.angBreakForce != PX_MAX_F32));
header->invMass0D0 = prepDesc.data0->invMass * prepDesc.invMassScales.linear0;
header->invMass1D1 = prepDesc.data1->invMass * prepDesc.invMassScales.linear1;
PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS];
PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS];
Px1DConstraint* sorted[MAX_CONSTRAINT_ROWS];
preprocessRows(sorted, prepDesc.rows, angSqrtInvInertia0, angSqrtInvInertia1, prepDesc.numRows,
prepDesc.data0->sqrtInvInertia, prepDesc.data1->sqrtInvInertia, prepDesc.data0->invMass, prepDesc.data1->invMass,
prepDesc.invMassScales, isExtended || prepDesc.disablePreprocessing, prepDesc.improvedSlerp);
PxReal erp = 1.0f;
PxU32 outCount = 0;
const SolverExtBody eb0(reinterpret_cast<const void*>(prepDesc.body0), prepDesc.data0, desc.linkIndexA);
const SolverExtBody eb1(reinterpret_cast<const void*>(prepDesc.body1), prepDesc.data1, desc.linkIndexB);
PxReal cfm = 0.f;
if (isExtended)
{
cfm = PxMax(eb0.getCFM(), eb1.getCFM());
erp = 0.8f;
}
for (PxU32 i = 0; i<prepDesc.numRows; i++)
{
PxPrefetchLine(constraints, 128);
SolverConstraint1D& s = *reinterpret_cast<SolverConstraint1D *>(constraints);
Px1DConstraint& c = *sorted[i];
const PxReal driveScale = c.flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && prepDesc.driveLimitsAreForces ? PxMin(dt, 1.0f) : 1.0f;
PxReal unitResponse;
PxReal normalVel = 0.0f;
PxReal initVel = 0.f;
PxReal minResponseThreshold = prepDesc.minResponseThreshold;
if(!isExtended)
{
init(s, c.linear0, c.linear1, PxVec3(angSqrtInvInertia0[i].x, angSqrtInvInertia0[i].y, angSqrtInvInertia0[i].z),
PxVec3(angSqrtInvInertia1[i].x, angSqrtInvInertia1[i].y, angSqrtInvInertia1[i].z), c.minImpulse * driveScale, c.maxImpulse * driveScale);
s.ang0Writeback = c.angular0;
const PxReal resp0 = s.lin0.magnitudeSquared() * prepDesc.data0->invMass * prepDesc.invMassScales.linear0 + s.ang0.magnitudeSquared() * prepDesc.invMassScales.angular0;
const PxReal resp1 = s.lin1.magnitudeSquared() * prepDesc.data1->invMass * prepDesc.invMassScales.linear1 + s.ang1.magnitudeSquared() * prepDesc.invMassScales.angular1;
unitResponse = resp0 + resp1;
initVel = normalVel = prepDesc.data0->projectVelocity(c.linear0, c.angular0) - prepDesc.data1->projectVelocity(c.linear1, c.angular1);
}
else
{
//this is articulation/soft body
init(s, c.linear0, c.linear1, c.angular0, c.angular1, c.minImpulse * driveScale, c.maxImpulse * driveScale);
SolverConstraint1DExt& e = static_cast<SolverConstraint1DExt&>(s);
const Cm::SpatialVector resp0 = createImpulseResponseVector(e.lin0, e.ang0, eb0);
const Cm::SpatialVector resp1 = createImpulseResponseVector(-e.lin1, -e.ang1, eb1);
unitResponse = getImpulseResponse(eb0, resp0, unsimdRef(e.deltaVA), prepDesc.invMassScales.linear0, prepDesc.invMassScales.angular0,
eb1, resp1, unsimdRef(e.deltaVB), prepDesc.invMassScales.linear1, prepDesc.invMassScales.angular1, Z, false);
//Add CFM term!
if(unitResponse <= DY_ARTICULATION_MIN_RESPONSE)
continue;
unitResponse += cfm;
s.ang0Writeback = c.angular0;
s.lin0 = resp0.linear;
s.ang0 = resp0.angular;
s.lin1 = -resp1.linear;
s.ang1 = -resp1.angular;
PxReal vel0, vel1;
if(needsNormalVel(c) || eb0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY || eb1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
vel0 = eb0.projectVelocity(c.linear0, c.angular0);
vel1 = eb1.projectVelocity(c.linear1, c.angular1);
normalVel = vel0 - vel1;
//normalVel = eb0.projectVelocity(s.lin0, s.ang0) - eb1.projectVelocity(s.lin1, s.ang1);
if(eb0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
initVel = vel0;
else if(eb1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
initVel = -vel1;
}
//minResponseThreshold = PxMax(minResponseThreshold, DY_ARTICULATION_MIN_RESPONSE);
}
setSolverConstants(s.constant, s.unbiasedConstant, s.velMultiplier, s.impulseMultiplier,
c, normalVel, unitResponse, minResponseThreshold, erp, dt, invdt);
//If we have a spring then we will do the following:
//s.constant = -dt*kd*(vTar - v0)/denom - dt*ks*(xTar - x0)/denom
//s.unbiasedConstant = -dt*kd*(vTar - v0)/denom - dt*ks*(xTar - x0)/denom
const PxReal velBias = initVel * s.velMultiplier;
s.constant += velBias;
s.unbiasedConstant += velBias;
if(c.flags & Px1DConstraintFlag::eOUTPUT_FORCE)
s.flags |= DY_SC_FLAG_OUTPUT_FORCE;
outCount++;
constraints += stride;
}
//Reassign count to the header because we may have skipped some rows if they were degenerate
header->count = PxU8(outCount);
return prepDesc.numRows;
}
PxU32 SetupSolverConstraint(SolverConstraintShaderPrepDesc& shaderDesc,
PxSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
PxReal dt, PxReal invdt, Cm::SpatialVectorF* Z)
{
// LL shouldn't see broken constraints
PX_ASSERT(!(reinterpret_cast<ConstraintWriteback*>(prepDesc.writeback)->broken));
setConstraintLength(*prepDesc.desc, 0);
if (!shaderDesc.solverPrep)
return 0;
//PxU32 numAxisConstraints = 0;
Px1DConstraint rows[MAX_CONSTRAINT_ROWS];
setupConstraintRows(rows, MAX_CONSTRAINT_ROWS);
prepDesc.invMassScales.linear0 = prepDesc.invMassScales.linear1 = prepDesc.invMassScales.angular0 = prepDesc.invMassScales.angular1 = 1.0f;
prepDesc.body0WorldOffset = PxVec3(0.0f);
PxVec3p unused_ra, unused_rb;
//TAG::solverprepcall
prepDesc.numRows = prepDesc.disableConstraint ? 0 : (*shaderDesc.solverPrep)(rows,
prepDesc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
prepDesc.invMassScales,
shaderDesc.constantBlock,
prepDesc.bodyFrame0, prepDesc.bodyFrame1, prepDesc.extendedLimits, unused_ra, unused_rb);
prepDesc.rows = rows;
return ConstraintHelper::setupSolverConstraint(prepDesc, allocator, dt, invdt, Z);
}
}
}
| 24,180 | C++ | 38.771382 | 171 | 0.722498 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverControlPF.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxIntrinsics.h"
#include "DySolverBody.h"
#include "DySolverConstraint1D.h"
#include "DySolverContact.h"
#include "DyThresholdTable.h"
#include "DySolverControl.h"
#include "DyArticulationPImpl.h"
#include "foundation/PxThread.h"
#include "DySolverConstraintDesc.h"
#include "DySolverContext.h"
#include "DySolverControlPF.h"
#include "DyArticulationCpuGpu.h"
namespace physx
{
namespace Dy
{
void solve1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4_Block (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4Block_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4Block_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void writeBack1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void ext1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void writeBack1D4Block (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFriction_BStaticBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtFrictionBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactCoulombBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulomb_BStaticBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactCoulombConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulomb_BStaticConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactCoulombBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulomb_BStaticBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFriction_BStaticBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtFrictionBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
//Pre-block 1d/2d friction stuff...
void solveContactCoulombPreBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_Static (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_ConcludeStatic (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_Static (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS);
static SolveBlockMethod gVTableSolveBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombBlock, // DY_SC_TYPE_RB_CONTACT
solve1DBlock, // DY_SC_TYPE_RB_1D
solveExtContactCoulombBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlock, // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_Static, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4_Block, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlock, // DY_SC_TYPE_FRICTION
solveFriction_BStaticBlock, // DY_SC_TYPE_STATIC_FRICTION
solveExtFrictionBlock, // DY_SC_TYPE_EXT_FRICTION
solveFrictionCoulombPreBlock, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_Static // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
static SolveWriteBackBlockMethod gVTableSolveWriteBackBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombBlockWriteBack, // DY_SC_TYPE_RB_CONTACT
solve1DBlockWriteBack, // DY_SC_TYPE_RB_1D
solveExtContactCoulombBlockWriteBack, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlockWriteBack, // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombBlockWriteBack, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_WriteBackStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_WriteBack, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlockWriteBack, // DY_SC_TYPE_FRICTION
solveFriction_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_FRICTION
solveExtFrictionBlockWriteBack, // DY_SC_TYPE_EXT_FRICTION
solveFrictionCoulombPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_WriteBackStatic // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
static SolveBlockMethod gVTableSolveConcludeBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombConcludeBlock, // DY_SC_TYPE_RB_CONTACT
solve1DConcludeBlock, // DY_SC_TYPE_RB_1D
solveExtContactCoulombConcludeBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DConcludeBlock, // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticConcludeBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombConcludeBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock_Conclude, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_ConcludeStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_Conclude, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlock, // DY_SC_TYPE_FRICTION
solveFriction_BStaticBlock, // DY_SC_TYPE_STATIC_FRICTION
solveExtFrictionBlock, // DY_SC_TYPE_EXT_FRICTION
solveFrictionCoulombPreBlock_Conclude, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_ConcludeStatic // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
// PT: code shared with patch friction solver. Ideally should move to a shared DySolverCore.cpp file.
void solveNoContactsCase( PxU32 bodyListSize, PxSolverBody* PX_RESTRICT bodyListStart, Cm::SpatialVector* PX_RESTRICT motionVelocityArray,
PxU32 articulationListSize, ArticulationSolverDesc* PX_RESTRICT articulationListStart, Cm::SpatialVectorF* PX_RESTRICT Z, Cm::SpatialVectorF* PX_RESTRICT deltaV,
PxU32 positionIterations, PxU32 velocityIterations, PxF32 dt, PxF32 invDt);
void saveMotionVelocities(PxU32 nbBodies, PxSolverBody* PX_RESTRICT solverBodies, Cm::SpatialVector* PX_RESTRICT motionVelocityArray);
void SolverCoreGeneralPF::solveV_Blocks(SolverIslandParams& params) const
{
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT;
const bool isTGS = false;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.writeBackIteration = false;
cache.deltaV = params.deltaV;
cache.Z = params.Z;
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
const PxU32 bodyListSize = params.bodyListSize;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
const PxU32 velocityIterations = params.velocityIterations;
const PxU32 positionIterations = params.positionIterations;
const PxU32 numConstraintHeaders = params.numConstraintHeaders;
const PxU32 articulationListSize = params.articulationListSize;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
if(numConstraintHeaders == 0)
{
solveNoContactsCase(bodyListSize, bodyListStart, motionVelocityArray,
articulationListSize, articulationListStart, cache.Z, cache.deltaV,
positionIterations, velocityIterations, params.dt, params.invDt);
return;
}
BatchIterator contactIterator(params.constraintBatchHeaders, params.numConstraintHeaders);
BatchIterator frictionIterator(params.frictionConstraintBatches, params.numFrictionConstraintHeaders);
const PxI32 frictionBatchCount = PxI32(params.numFrictionConstraintHeaders);
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList = params.frictionConstraintList;
//0-(n-1) iterations
PxI32 normalIter = 0;
PxI32 frictionIter = 0;
for (PxU32 iteration = positionIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, iteration == 1 ? gVTableSolveConcludeBlockCoulomb : gVTableSolveBlockCoulomb, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
++normalIter;
}
if(frictionBatchCount>0)
{
const PxU32 numIterations = positionIterations * 2;
for (PxU32 iteration = numIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, iteration == 1 ? gVTableSolveConcludeBlockCoulomb : gVTableSolveBlockCoulomb, frictionIter);
++frictionIter;
}
}
saveMotionVelocities(bodyListSize, bodyListStart, motionVelocityArray);
for (PxU32 i = 0; i < articulationListSize; i++)
ArticulationPImpl::saveVelocity(articulationListStart[i].articulation, cache.deltaV);
const PxU32 velItersMinOne = velocityIterations - 1;
PxU32 iteration = 0;
for(; iteration < velItersMinOne; ++iteration)
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveBlockCoulomb, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
++normalIter;
if(frictionBatchCount > 0)
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, gVTableSolveBlockCoulomb, frictionIter);
++frictionIter;
}
}
PxI32* outThresholdPairs = params.outThresholdPairs;
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
PxU32 thresholdStreamLength = params.thresholdStreamLength;
cache.writeBackIteration = true;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
cache.mSharedThresholdStream = thresholdStream;
//PGS always runs one velocity iteration
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveWriteBackBlockCoulomb, normalIter);
++normalIter;
for (PxU32 i = 0; i < articulationListSize; ++i)
{
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
articulationListStart[i].articulation->writebackInternalConstraints(false);
}
if(frictionBatchCount > 0)
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, gVTableSolveWriteBackBlockCoulomb, frictionIter);
++frictionIter;
}
}
//Write back remaining threshold streams
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
const PxI32 threshIndex = PxAtomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
}
void SolverCoreGeneralPF::solveVParallelAndWriteBack(SolverIslandParams& params,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const
{
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT;
const bool isTGS = false;
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
const PxI32 UnrollCount = PxI32(params.batchSize);
const PxI32 SaveUnrollCount = 64;
const PxI32 ArticCount = 2;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
const PxI32 frictionBatchCount = PxI32(params.numFrictionConstraintHeaders);//frictionConstraintBatches.size();
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.Z = Z;
cache.deltaV = deltaV;
const PxReal dt = params.dt;
const PxReal invDt = params.invDt;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
const PxI32 positionIterations = PxI32(params.positionIterations);
const PxU32 velocityIterations = params.velocityIterations;
const PxI32 bodyListSize = PxI32(params.bodyListSize);
const PxI32 articulationListSize = PxI32(params.articulationListSize);
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
PxI32* constraintIndex = ¶ms.constraintIndex;
PxI32* constraintIndexCompleted = ¶ms.constraintIndexCompleted;
PxI32* frictionConstraintIndex = ¶ms.frictionConstraintIndex;
PxI32 endIndexCount = UnrollCount;
PxI32 index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
PxI32 frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
BatchIterator contactIter(params.constraintBatchHeaders, params.numConstraintHeaders);
BatchIterator frictionIter(params.frictionConstraintBatches, params.numFrictionConstraintHeaders);
PxU32* headersPerPartition = params.headersPerPartition;
PxU32 nbPartitions = params.nbPartitions;
PxU32* frictionHeadersPerPartition = params.frictionHeadersPerPartition;
PxU32 nbFrictionPartitions = params.nbFrictionPartitions;
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList = params.frictionConstraintList;
PxI32 maxNormalIndex = 0;
PxI32 maxProgress = 0;
PxI32 frictionEndIndexCount = UnrollCount;
PxI32 maxFrictionIndex = 0;
PxI32 articSolveStart = 0;
PxI32 articSolveEnd = 0;
PxI32 maxArticIndex = 0;
PxI32 articIndexCounter = 0;
PxI32 targetArticIndex = 0;
PxI32* articIndex = ¶ms.articSolveIndex;
PxI32* articIndexCompleted = ¶ms.articSolveIndexCompleted;
PxI32 normalIteration = 0;
PxI32 frictionIteration = 0;
PxU32 a = 0;
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlockCoulomb : gVTableSolveConcludeBlockCoulomb;
for(; a < positionIterations - 1 + i; ++a)
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, solveTable,
normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
const PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize;
++normalIteration;
}
}
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlockCoulomb : gVTableSolveConcludeBlockCoulomb;
const PxI32 numIterations = positionIterations *2;
for(; a < numIterations - 1 + i; ++a)
{
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxProgress += frictionHeadersPerPartition[b];
maxFrictionIndex += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter,
solveTable, frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++frictionIteration;
}
}
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
PxI32* bodyListIndex = ¶ms.bodyListIndex;
PxI32* bodyListIndexCompleted = ¶ms.bodyListIndexCompleted;
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
PxI32 endIndexCount2 = SaveUnrollCount;
PxI32 index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
{
PxI32 nbConcluded = 0;
while(index2 < articulationListSize)
{
const PxI32 remainder = PxMin(SaveUnrollCount, (articulationListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
ArticulationPImpl::saveVelocity(articulationListStart[index2].articulation, cache.deltaV);
}
nbConcluded += remainder;
if(endIndexCount2 == 0)
{
index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
endIndexCount2 = SaveUnrollCount;
}
}
index2 -= articulationListSize;
//save velocity
while(index2 < bodyListSize)
{
const PxI32 remainder = PxMin(endIndexCount2, (bodyListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
PxPrefetchLine(&bodyListStart[index2 + 8]);
PxPrefetchLine(&motionVelocityArray[index2 + 8]);
PxSolverBody& body = bodyListStart[index2];
Cm::SpatialVector& motionVel = motionVelocityArray[index2];
motionVel.linear = body.linearVelocity;
motionVel.angular = body.angularState;
PX_ASSERT(motionVel.linear.isFinite());
PX_ASSERT(motionVel.angular.isFinite());
}
nbConcluded += remainder;
//Branch not required because this is the last time we use this atomic variable
//if(index2 < articulationListSizePlusbodyListSize)
{
index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount - articulationListSize;
endIndexCount2 = SaveUnrollCount;
}
}
if(nbConcluded)
{
PxMemoryBarrier();
PxAtomicAdd(bodyListIndexCompleted, nbConcluded);
}
}
WAIT_FOR_PROGRESS(bodyListIndexCompleted, (bodyListSize + articulationListSize));
a = 0;
for(; a < velocityIterations-1; ++a)
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveBlockCoulomb, normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++normalIteration;
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxFrictionIndex += frictionHeadersPerPartition[b];
maxProgress += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter, gVTableSolveBlockCoulomb,
frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++frictionIteration;
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
const PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize;
}
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
const PxU32 thresholdStreamLength = params.thresholdStreamLength;
PxI32* outThresholdPairs = params.outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
// last velocity + write-back iteration
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount,
cache, contactIter, gVTableSolveWriteBackBlockCoulomb, normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++normalIteration;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxFrictionIndex += frictionHeadersPerPartition[b];
maxProgress += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter,
gVTableSolveWriteBackBlockCoulomb, frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++frictionIteration;
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
articulationListStart[articSolveStart - articIndexCounter].articulation->writebackInternalConstraints(false);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize; // not strictly necessary but better safe than sorry
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
}
// At this point we've awaited the completion all rigid partitions and all articulations
// No more syncing on the outside of this function is required.
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
PxI32 threshIndex = PxAtomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
}
}
}
}
//#endif
| 29,280 | C++ | 35.647059 | 173 | 0.762705 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFrictionPatchStreamPair.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_FRICTION_PATCH_STREAM_PAIR_H
#define DY_FRICTION_PATCH_STREAM_PAIR_H
#include "foundation/PxSimpleTypes.h"
#include "PxvConfig.h"
#include "foundation/PxMutex.h"
#include "foundation/PxArray.h"
// Each narrow phase thread has an input stream of friction patches from the
// previous frame and an output stream of friction patches which will be
// saved for next frame. The patches persist for exactly one frame at which
// point they get thrown away.
// There is a stream pair per thread. A contact callback reserves space
// for its friction patches and gets a cookie in return that can stash
// for next frame. Cookies are valid for one frame only.
//
// note that all friction patches reserved are guaranteed to be contiguous;
// this might turn out to be a bit inefficient if we often have a large
// number of friction patches
#include "PxcNpMemBlockPool.h"
namespace physx
{
class FrictionPatchStreamPair
{
public:
FrictionPatchStreamPair(PxcNpMemBlockPool& blockPool);
// reserve can fail and return null. Read should never fail
template<class FrictionPatch>
FrictionPatch* reserve(const PxU32 size);
template<class FrictionPatch>
const FrictionPatch* findInputPatches(const PxU8* ptr) const;
void reset();
PxcNpMemBlockPool& getBlockPool() { return mBlockPool;}
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock;
PxU32 mUsed;
FrictionPatchStreamPair& operator=(const FrictionPatchStreamPair&);
};
PX_FORCE_INLINE FrictionPatchStreamPair::FrictionPatchStreamPair(PxcNpMemBlockPool& blockPool):
mBlockPool(blockPool), mBlock(NULL), mUsed(0)
{
}
PX_FORCE_INLINE void FrictionPatchStreamPair::reset()
{
mBlock = NULL;
mUsed = 0;
}
// reserve can fail and return null. Read should never fail
template <class FrictionPatch>
FrictionPatch* FrictionPatchStreamPair::reserve(const PxU32 size)
{
if(size>PxcNpMemBlock::SIZE)
{
return reinterpret_cast<FrictionPatch*>(-1);
}
PX_ASSERT(size <= PxcNpMemBlock::SIZE);
FrictionPatch* ptr = NULL;
if(mBlock == NULL || mUsed + size > PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireFrictionBlock();
mUsed = 0;
}
if(mBlock)
{
ptr = reinterpret_cast<FrictionPatch*>(mBlock->data+mUsed);
mUsed += size;
}
return ptr;
}
template <class FrictionPatch>
const FrictionPatch* FrictionPatchStreamPair::findInputPatches(const PxU8* ptr) const
{
return reinterpret_cast<const FrictionPatch*>(ptr);
}
}
#endif
| 4,132 | C | 31.801587 | 95 | 0.762585 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSContactPrep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
#include "DyFeatherstoneArticulation.h"
#include "DyArticulationCpuGpu.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
#include "DyConstraintPrep.h"
#include "DySolverContext.h"
#include "DySolverConstraint1DStep.h"
#include "DyTGS.h"
using namespace aos;
namespace physx
{
namespace Dy
{
PX_FORCE_INLINE void computeBlockStreamByteSizesStep(const bool useExtContacts, const CorrelationBuffer& c,
PxU32& _solverConstraintByteSize, PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches,
PxU32& _axisConstraintCount, PxReal torsionalPatchRadius)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PX_ASSERT(0 == _frictionPatchByteSize);
PX_ASSERT(0 == _numFrictionPatches);
PX_ASSERT(0 == _axisConstraintCount);
// PT: use local vars to remove LHS
PxU32 solverConstraintByteSize = 0;
PxU32 numFrictionPatches = 0;
PxU32 axisConstraintCount = 0;
for (PxU32 i = 0; i < c.frictionPatchCount; i++)
{
//Friction patches.
if (c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0;
//Solver constraint data.
if (c.frictionPatchContactCounts[i] != 0)
{
solverConstraintByteSize += sizeof(SolverContactHeaderStep);
solverConstraintByteSize += useExtContacts ? c.frictionPatchContactCounts[i] * sizeof(SolverContactPointStepExt)
: c.frictionPatchContactCounts[i] * sizeof(SolverContactPointStep);
solverConstraintByteSize += sizeof(PxF32) * ((c.frictionPatchContactCounts[i] + 3)&(~3)); //Add on space for applied impulses
axisConstraintCount += c.frictionPatchContactCounts[i];
if (haveFriction)
{
PxU32 nbAnchors = PxU32(c.frictionPatches[i].anchorCount * 2);
if (torsionalPatchRadius > 0.f && c.frictionPatches[i].anchorCount == 1)
nbAnchors++;
solverConstraintByteSize += useExtContacts ? nbAnchors * sizeof(SolverContactFrictionStepExt)
: nbAnchors * sizeof(SolverContactFrictionStep);
axisConstraintCount += nbAnchors;
}
}
}
PxU32 frictionPatchByteSize = numFrictionPatches*sizeof(FrictionPatch);
_numFrictionPatches = numFrictionPatches;
_axisConstraintCount = axisConstraintCount;
//16-byte alignment.
_frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f);
_solverConstraintByteSize = ((solverConstraintByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f));
}
static bool reserveBlockStreams(const bool useExtContacts, Dy::CorrelationBuffer& cBuffer,
PxU8*& solverConstraint,
FrictionPatch*& _frictionPatches,
PxU32& numFrictionPatches, PxU32& solverConstraintByteSize,
PxU32& axisConstraintCount, PxConstraintAllocator& constraintAllocator,
PxReal torsionalPatchRadius)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(NULL == _frictionPatches);
PX_ASSERT(0 == numFrictionPatches);
PX_ASSERT(0 == solverConstraintByteSize);
PX_ASSERT(0 == axisConstraintCount);
//From frictionPatchStream we just need to reserve a single buffer.
PxU32 frictionPatchByteSize = 0;
//Compute the sizes of all the buffers.
computeBlockStreamByteSizesStep(
useExtContacts, cBuffer,
solverConstraintByteSize, frictionPatchByteSize, numFrictionPatches,
axisConstraintCount, torsionalPatchRadius);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if (constraintBlockByteSize > 0)
{
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if (0 == constraintBlock || (reinterpret_cast<PxU8*>(-1)) == constraintBlock)
{
if (0 == constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock = NULL;
}
}
PX_ASSERT((size_t(constraintBlock) & 0xF) == 0);
}
FrictionPatch* frictionPatches = NULL;
//If the constraint block reservation didn't fail then reserve the friction buffer too.
if (frictionPatchByteSize > 0 && (0 == constraintBlockByteSize || constraintBlock))
{
frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize));
if (0 == frictionPatches || (reinterpret_cast<FrictionPatch*>(-1)) == frictionPatches)
{
if (0 == frictionPatches)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
frictionPatches = NULL;
}
}
}
_frictionPatches = frictionPatches;
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if (0 == constraintBlockByteSize || constraintBlock)
{
if (solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0 == (uintptr_t(solverConstraint) & 0x0f));
}
}
//Return true if neither of the two block reservations failed.
return ((0 == constraintBlockByteSize || constraintBlock) && (0 == frictionPatchByteSize || frictionPatches));
}
class SolverExtBodyStep
{
public:
union
{
const FeatherstoneArticulation* mArticulation;
const PxTGSSolverBodyVel* mBody;
};
const PxTGSSolverBodyTxInertia* mTxI;
const PxTGSSolverBodyData* mData;
PxU32 mLinkIndex;
SolverExtBodyStep(const void* bodyOrArticulation, const PxTGSSolverBodyTxInertia* txI,
const PxTGSSolverBodyData* data, PxU32 linkIndex) :
mBody(reinterpret_cast<const PxTGSSolverBodyVel*>(bodyOrArticulation)),
mTxI(txI),
mData(data),
mLinkIndex(linkIndex)
{}
PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const;
PxVec3 getLinVel() const;
PxVec3 getAngVel() const;
Cm::SpatialVectorV getVelocity() const;
bool isKinematic() const
{
return (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) && mBody->isKinematic;
}
PxReal getCFM() const
{
return (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) ? 0.f :
mArticulation->getCfm(mLinkIndex);
}
};
Cm::SpatialVector createImpulseResponseVector(const PxVec3& linear, const PxVec3& angular, const SolverExtBodyStep& body)
{
if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return Cm::SpatialVector(linear, body.mTxI->sqrtInvInertia * angular);
return Cm::SpatialVector(linear, angular);
}
Cm::SpatialVectorV createImpulseResponseVector(const aos::Vec3V& linear, const aos::Vec3V& angular, const SolverExtBodyStep& body)
{
if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
return Cm::SpatialVectorV(linear, M33MulV3(M33Load(body.mTxI->sqrtInvInertia), angular));
}
return Cm::SpatialVectorV(linear, angular);
}
PxReal getImpulseResponse(const SolverExtBodyStep& b0, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxReal dom0, PxReal angDom0,
const SolverExtBodyStep& b1, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, PxReal dom1, PxReal angDom1,
bool allowSelfCollision)
{
PxReal response;
if (allowSelfCollision && b0.mArticulation == b1.mArticulation)
{
Cm::SpatialVectorF Z[64];
b0.mArticulation->getImpulseSelfResponse(b0.mLinkIndex, b1.mLinkIndex, Z,
impulse0.scale(dom0, angDom0), impulse1.scale(dom1, angDom1), deltaV0, deltaV1);
response = impulse0.dot(deltaV0) + impulse1.dot(deltaV1);
}
else
{
if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV0.linear = impulse0.linear * b0.mData->invMass * dom0;
deltaV0.angular =/* b0.mBody->sqrtInvInertia * */impulse0.angular * angDom0;
}
else
{
//ArticulationHelper::getImpulseResponse(*b0.mFsData, b0.mLinkIndex, impulse0.scale(dom0, angDom0), deltaV0);
const FeatherstoneArticulation* articulation = b0.mArticulation;
Cm::SpatialVectorF Z[64];
articulation->getImpulseResponse(b0.mLinkIndex, Z, impulse0.scale(dom0, angDom0), deltaV0);
}
response = impulse0.dot(deltaV0);
if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV1.linear = impulse1.linear * b1.mData->invMass * dom1;
deltaV1.angular = /*b1.mBody->sqrtInvInertia * */impulse1.angular * angDom1;
}
else
{
const FeatherstoneArticulation* articulation = b1.mArticulation;
Cm::SpatialVectorF Z[64];
articulation->getImpulseResponse(b1.mLinkIndex, Z, impulse1.scale(dom1, angDom1), deltaV1);
//ArticulationHelper::getImpulseResponse(*b1.mFsData, b1.mLinkIndex, impulse1.scale(dom1, angDom1), deltaV1);
}
response += impulse1.dot(deltaV1);
}
return response;
}
FloatV getImpulseResponse(const SolverExtBodyStep& b0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, const FloatV& dom0, const FloatV& angDom0,
const SolverExtBodyStep& b1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1, const FloatV& dom1, const FloatV& angDom1,
bool /*allowSelfCollision*/)
{
Vec3V response;
{
if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV0.linear = V3Scale(impulse0.linear, FMul(FLoad(b0.mData->invMass), dom0));
deltaV0.angular = V3Scale(impulse0.angular, angDom0);
}
else
{
b0.mArticulation->getImpulseResponse(b0.mLinkIndex, NULL, impulse0.scale(dom0, angDom0), deltaV0);
}
response = V3Add(V3Mul(impulse0.linear, deltaV0.linear), V3Mul(impulse0.angular, deltaV0.angular));
if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV1.linear = V3Scale(impulse1.linear, FMul(FLoad(b1.mData->invMass), dom1));
deltaV1.angular = V3Scale(impulse1.angular, angDom1);
}
else
{
b1.mArticulation->getImpulseResponse(b1.mLinkIndex, NULL, impulse1.scale(dom1, angDom1), deltaV1);
}
response = V3Add(response, V3Add(V3Mul(impulse1.linear, deltaV1.linear), V3Mul(impulse1.angular, deltaV1.angular)));
}
return V3SumElems(response);
}
PxReal SolverExtBodyStep::projectVelocity(const PxVec3& linear, const PxVec3& angular) const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return mData->projectVelocity(linear, angular);
else
{
Cm::SpatialVectorV velocities = mArticulation->getLinkVelocity(mLinkIndex);
FloatV fv = velocities.dot(Cm::SpatialVector(linear, angular));
PxF32 f;
FStore(fv, &f);
/*PxF32 f;
FStore(getVelocity(*mFsData)[mLinkIndex].dot(Cm::SpatialVector(linear, angular)), &f);
return f;*/
return f;
}
}
static FloatV constructContactConstraintStep(const Mat33V& sqrtInvInertia0, const Mat33V& sqrtInvInertia1, const FloatVArg invMassNorLenSq0,
const FloatVArg invMassNorLenSq1, const FloatVArg angD0, const FloatVArg angD1, const Vec3VArg bodyFrame0p, const Vec3VArg bodyFrame1p,
const QuatV& /*bodyFrame0q*/, const QuatV& /*bodyFrame1q*/,
const Vec3VArg normal, const FloatVArg norVel0, const FloatVArg norVel1, const VecCrossV& norCross, const Vec3VArg angVel0, const Vec3VArg angVel1,
const FloatVArg invDtp8, const FloatVArg invStepDt, const FloatVArg totalDt, const FloatVArg invTotalDt,
const FloatVArg restDistance, const FloatVArg restitution,
const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointStep& solverContact,
const FloatVArg /*ccdMaxSeparation*/, const bool isKinematic0, const bool isKinematic1,
const Vec3VArg solverOffsetSlop, const FloatVArg dt, const FloatVArg damping)
{
const FloatV zero = FZero();
const Vec3V point = V3LoadA(contact.point);
const FloatV separation = FLoad(contact.separation);
const FloatV cTargetVel = V3Dot(normal, V3LoadA(contact.targetVel));
const Vec3V ra = V3Sub(point, bodyFrame0p);
const Vec3V rb = V3Sub(point, bodyFrame1p);
Vec3V raXn = V3Cross(ra, norCross);
Vec3V rbXn = V3Cross(rb, norCross);
const FloatV angV0 = V3Dot(raXn, angVel0);
const FloatV angV1 = V3Dot(rbXn, angVel1);
const FloatV vRelAng = FSub(angV0, angV1);
const FloatV vRelLin = FSub(norVel0, norVel1);
const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(vRelLin,zero), FMax(), FDiv(vRelAng, vRelLin)), FOne()));
const FloatV vrel1 = FAdd(norVel0, angV0);
const FloatV vrel2 = FAdd(norVel1, angV1);
const FloatV vrel = FSub(vrel1, vrel2);
raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, raXn);
const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, rbXn);
const FloatV i0 = FMul(V3Dot(raXnInertia, raXnInertia), angD0);
const FloatV i1 = FMul(V3Dot(rbXnInertia, rbXnInertia), angD1);
const FloatV resp0 = FAdd(invMassNorLenSq0, i0);
const FloatV resp1 = FSub(i1, invMassNorLenSq1);
const FloatV unitResponse = FAdd(resp0, resp1);
const FloatV penetration = FSub(separation, restDistance);
const BoolV isSeparated = FIsGrtr(penetration, zero);
const FloatV penetrationInvDt = FMul(penetration, invTotalDt);
const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt));
//The following line was replaced by an equivalent to avoid triggering an assert when FAdd sums totalDt to infinity which happens if vrel==0
//const FloatV ratio = FSel(isGreater2, FAdd(totalDt, FDiv(penetration, vrel)), zero);
const FloatV ratio = FAdd(totalDt, FSel(isGreater2, FDiv(penetration, vrel), FNeg(totalDt)));
FloatV scaledBias;
FloatV velMultiplier;
FloatV recipResponse = FSel(FIsGrtr(unitResponse, FZero()), FRecip(unitResponse), FZero());
if (FAllGrtr(zero, restitution))
{
//-ve restitution, so we treat it as a -spring coefficient.
const FloatV nrdt = FMul(dt, restitution);
const FloatV a = FMul(dt, FSub(damping, nrdt));
const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne()));
velMultiplier = FMul(x, a);
//scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier));
scaledBias = FMul(nrdt, FMul(x, unitResponse));
}
else
{
scaledBias = FNeg(FSel(isSeparated, invStepDt, invDtp8));
velMultiplier = recipResponse;
}
FloatV totalError = penetration;
const FloatV sumVRel(vrel);
FloatV targetVelocity = FAdd(cTargetVel, FSel(isGreater2, FMul(FNeg(sumVRel), restitution), zero));
totalError = FScaleAdd(targetVelocity, ratio, totalError);
if(isKinematic0)
targetVelocity = FSub(targetVelocity, vrel1);
if(isKinematic1)
targetVelocity = FAdd(targetVelocity, vrel2);
//KS - don't store scaled by angD0/angD1 here! It'll corrupt the velocity projection...
V3StoreA(raXnInertia, solverContact.raXnI);
V3StoreA(rbXnInertia, solverContact.rbXnI);
FStore(velMultiplier, &solverContact.velMultiplier);
FStore(totalError, &solverContact.separation);
FStore(scaledBias, &solverContact.biasCoefficient);
FStore(targetVelocity, &solverContact.targetVelocity);
FStore(recipResponse, &solverContact.recipResponse);
solverContact.maxImpulse = contact.maxImpulse;
return penetration;
}
static void setupFinalizeSolverConstraints(Sc::ShapeInteraction* shapeInteraction,
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const PxTGSSolverBodyVel& b0,
const PxTGSSolverBodyVel& b1,
const PxTGSSolverBodyTxInertia& txI0,
const PxTGSSolverBodyTxInertia& txI1,
const PxTGSSolverBodyData& data0,
const PxTGSSolverBodyData& data1,
const PxReal invDtF32,
const PxReal totalDtF32,
const PxReal invTotalDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
bool hasForceThreshold, bool staticOrKinematicBody,
const PxReal restDist, PxU8* frictionDataPtr,
const PxReal maxCCDSeparation,
const bool disableStrongFriction,
const PxReal torsionalPatchRadiusF32,
const PxReal minTorsionalPatchRadiusF32,
const PxReal biasCoefficient,
const PxReal solverOffsetSlop)
{
const bool hasTorsionalFriction = torsionalPatchRadiusF32 > 0.f || minTorsionalPatchRadiusF32 > 0.f;
// NOTE II: the friction patches are sparse (some of them have no contact patches, and
// therefore did not get written back to the cache) but the patch addresses are dense,
// corresponding to valid patches
const bool isKinematic0 = b0.isKinematic;
const bool isKinematic1 = b1.isKinematic;
const FloatV ccdMaxSeparation = FLoad(maxCCDSeparation);
const PxU8 flags = PxU8(hasForceThreshold ? SolverContactHeaderStep::eHAS_FORCE_THRESHOLDS : 0);
PxU8* PX_RESTRICT ptr = workspace;
const PxU8 type = PxTo8(staticOrKinematicBody ? DY_SC_TYPE_STATIC_CONTACT : DY_SC_TYPE_RB_CONTACT);
const FloatV zero = FZero();
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
const Vec3V offsetSlop = V3Load(solverOffsetSlop);
const FloatV nDom1fV = FNeg(d1);
const FloatV invMass0 = FLoad(data0.invMass);
const FloatV invMass1 = FLoad(data1.invMass);
const FloatV invMass0_dom0fV = FMul(d0, invMass0);
const FloatV invMass1_dom1fV = FMul(nDom1fV, invMass1);
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero();
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, invMass0_dom0fV);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, invMass1_dom1fV);
const FloatV restDistance = FLoad(restDist);
const PxReal maxPenBias = PxMax(data0.penBiasClamp, data1.penBiasClamp);
const QuatV bodyFrame0q = QuatVLoadU(&bodyFrame0.q.x);
const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p);
const QuatV bodyFrame1q = QuatVLoadU(&bodyFrame1.q.x);
const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p);
PxU32 frictionPatchWritebackAddrIndex = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
//const Vec3V linVel0 = V3LoadU_SafeReadW(b0.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
//const Vec3V linVel1 = V3LoadU_SafeReadW(b1.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
//const Vec3V angVel0 = V3LoadU_SafeReadW(b0.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
//const Vec3V angVel1 = V3LoadU_SafeReadW(b1.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
const Vec3V linVel0 = V3LoadU_SafeReadW(data0.originalLinearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
const Vec3V linVel1 = V3LoadU_SafeReadW(data1.originalLinearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
const Vec3V angVel0 = V3LoadU_SafeReadW(data0.originalAngularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
const Vec3V angVel1 = V3LoadU_SafeReadW(data1.originalAngularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
PX_ALIGN(16, const Mat33V sqrtInvInertia0)
(
V3LoadU_SafeReadW(txI0.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33
V3LoadU_SafeReadW(txI0.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33
V3LoadU(txI0.sqrtInvInertia.column2)
);
PX_ALIGN(16, const Mat33V sqrtInvInertia1)
(
V3LoadU_SafeReadW(txI1.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33
V3LoadU_SafeReadW(txI1.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33
V3LoadU(txI1.sqrtInvInertia.column2)
);
const FloatV invDt = FLoad(invDtF32);
const FloatV dt = FLoad(dtF32);
const FloatV totalDt = FLoad(totalDtF32);
const FloatV invTotalDt = FLoad(invTotalDtF32);
const PxReal scale = PxMin(0.8f, biasCoefficient);
const FloatV p8 = FLoad(scale);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const FloatV invDtp8 = FMul(invDt, p8);
const PxReal frictionBiasScale = disableStrongFriction ? 0.f : invDtF32 * scale;
for (PxU32 i = 0; i<c.frictionPatchCount; i++)
{
PxU32 contactCount = c.frictionPatchContactCounts[i];
if (contactCount == 0)
continue;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
PX_ASSERT(frictionPatch.anchorCount <= 2);
PxU32 firstPatch = c.correlationListHeads[i];
const PxContactPoint* contactBase0 = buffer + c.contactPatches[firstPatch].start;
const PxReal combinedRestitution = contactBase0->restitution;
const PxReal combinedDamping = contactBase0->damping;
SolverContactHeaderStep* PX_RESTRICT header = reinterpret_cast<SolverContactHeaderStep*>(ptr);
ptr += sizeof(SolverContactHeaderStep);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
header->shapeInteraction = shapeInteraction;
header->flags = flags;
header->minNormalForce = 0.f;
FStore(invMass0_dom0fV, &header->invMass0);
FStore(FNeg(invMass1_dom1fV), &header->invMass1);
const FloatV restitution = FLoad(combinedRestitution);
const FloatV damping = FLoad(combinedDamping);
PxU32 pointStride = sizeof(SolverContactPointStep);
PxU32 frictionStride = sizeof(SolverContactFrictionStep);
const Vec3V normal = V3LoadA(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV normalLenSq = V3LengthSq(normal);
const VecCrossV norCross = V3PrepareCross(normal);
//const FloatV norVel = V3SumElems(V3NegMulSub(normal, linVel1, V3Mul(normal, linVel0)));
const FloatV norVel0 = V3Dot(linVel0, normal);
const FloatV norVel1 = V3Dot(linVel1, normal);
const FloatV invMassNorLenSq0 = FMul(invMass0_dom0fV, normalLenSq);
const FloatV invMassNorLenSq1 = FMul(invMass1_dom1fV, normalLenSq);
V3StoreA(normal, header->normal);
header->maxPenBias = contactBase0->restitution < 0.f ? -PX_MAX_F32 : maxPenBias;
FloatV maxPenetration = FMax();
for (PxU32 patch = c.correlationListHeads[i];
patch != CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer + c.contactPatches[patch].start;
PxU8* p = ptr;
for (PxU32 j = 0; j<count; j++)
{
PxPrefetchLine(p, 256);
const PxContactPoint& contact = contactBase[j];
SolverContactPointStep* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointStep*>(p);
p += pointStride;
maxPenetration = FMin(maxPenetration, constructContactConstraintStep(sqrtInvInertia0, sqrtInvInertia1, invMassNorLenSq0,
invMassNorLenSq1, angD0, angD1, bodyFrame0p, bodyFrame1p, bodyFrame0q, bodyFrame1q,
normal, norVel0, norVel1, norCross, angVel0, angVel1,
invDtp8, invDt, totalDt, invTotalDt, restDistance, restitution,
bounceThreshold, contact, *solverContact,
ccdMaxSeparation, isKinematic0, isKinematic1, offsetSlop, dt, damping));
}
ptr = p;
}
PxF32* forceBuffers = reinterpret_cast<PxF32*>(ptr);
PxMemZero(forceBuffers, sizeof(PxF32) * contactCount);
ptr += ((contactCount + 3) & (~3)) * sizeof(PxF32); // jump to next 16-byte boundary
const PxReal staticFriction = contactBase0->staticFriction;
const PxReal dynamicFriction = contactBase0->dynamicFriction;
const bool disableFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(staticFriction));
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(dynamicFriction));
const bool haveFriction = (disableFriction == 0 && frictionPatch.anchorCount != 0);//PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;
header->numNormalConstr = PxTo8(contactCount);
header->numFrictionConstr = PxTo8(haveFriction ? frictionPatch.anchorCount * 2 : 0);
header->type = type;
header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W;
FStore(angD0, &header->angDom0);
FStore(angD1, &header->angDom1);
header->broken = 0;
if (haveFriction)
{
const Vec3V linVrel = V3Sub(linVel0, linVel1);
//const Vec3V normal = Vec3V_From_PxVec3_Aligned(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV orthoThreshold = FLoad(0.70710678f);
const FloatV p1 = FLoad(0.0001f);
// fallback: normal.cross((1,0,0)) or normal.cross((0,0,1))
const FloatV normalX = V3GetX(normal);
const FloatV normalY = V3GetY(normal);
const FloatV normalZ = V3GetZ(normal);
Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY);
Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero);
Vec3V t0Fallback = V3Sel(FIsGrtr(orthoThreshold, FAbs(normalX)), t0Fallback1, t0Fallback2);
Vec3V t0 = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel)));
t0 = V3Sel(FIsGrtr(V3LengthSq(t0), p1), t0, t0Fallback);
t0 = V3Normalize(t0);
const VecCrossV t0Cross = V3PrepareCross(t0);
const Vec3V t1 = V3Normalize(V3Cross(norCross, t0Cross));
//const VecCrossV t1Cross = V3PrepareCross(t1);
// since we don't even have the body velocities we can't compute the tangent dirs, so
// the only thing we can do right now is to write the geometric information (which is the
// same for both axis constraints of an anchor) We put ra in the raXn field, rb in the rbXn
// field, and the error in the normal field. See corresponding comments in
// completeContactFriction()
//We want to set the writeBack ptr to point to the broken flag of the friction patch.
//On spu we have a slight problem here because the friction patch array is
//in local store rather than in main memory. The good news is that the address of the friction
//patch array in main memory is stored in the work unit. These two addresses will be equal
//except on spu where one is local store memory and the other is the effective address in main memory.
//Using the value stored in the work unit guarantees that the main memory address is used on all platforms.
PxU8* PX_RESTRICT writeback = frictionDataPtr + frictionPatchWritebackAddrIndex*sizeof(FrictionPatch);
const FloatV norVel00 = V3Dot(linVel0, t0);
const FloatV norVel01 = V3Dot(linVel1, t0);
const FloatV norVel10 = V3Dot(linVel0, t1);
const FloatV norVel11 = V3Dot(linVel1, t1);
const Vec3V relTr = V3Sub(bodyFrame0p, bodyFrame1p);
header->frictionBrokenWritebackByte = writeback;
PxReal frictionScale = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f;
for (PxU32 j = 0; j < frictionPatch.anchorCount; j++)
{
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
SolverContactFrictionStep* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionStep*>(ptr);
ptr += frictionStride;
SolverContactFrictionStep* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionStep*>(ptr);
ptr += frictionStride;
Vec3V body0Anchor = V3LoadU(frictionPatch.body0Anchors[j]);
Vec3V body1Anchor = V3LoadU(frictionPatch.body1Anchors[j]);
Vec3V ra = QuatRotate(bodyFrame0q, body0Anchor);
Vec3V rb = QuatRotate(bodyFrame1q, body1Anchor);
PxU32 index = c.contactID[i][j];
index = index == 0xFFFF ? c.contactPatches[c.correlationListHeads[i]].start : index;
const Vec3V tvel = V3LoadA(buffer[index].targetVel);
const Vec3V error = V3Add(V3Sub(ra, rb), relTr);
{
Vec3V raXn = V3Cross(ra, t0);
Vec3V rbXn = V3Cross(rb, t0);
raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, raXn);
const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, rbXn);
const FloatV resp0 = FAdd(invMassNorLenSq0, FMul(V3Dot(raXnInertia, raXnInertia), angD0));
const FloatV resp1 = FSub(FMul(V3Dot(rbXnInertia, rbXnInertia), angD1), invMassNorLenSq1);
const FloatV unitResponse = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FDiv(p8, unitResponse), zero);
//const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FRecip(unitResponse), zero);
FloatV targetVel = V3Dot(tvel, t0);
if(isKinematic0)
targetVel = FSub(targetVel, FAdd(norVel00, V3Dot(raXn, angVel0)));
if (isKinematic1)
targetVel = FAdd(targetVel, FAdd(norVel01, V3Dot(rbXn, angVel1)));
f0->normalXYZ_ErrorW = V4SetW(t0, V3Dot(error, t0));
//f0->raXnXYZ_targetVelW = V4SetW(body0Anchor, targetVel);
//f0->rbXnXYZ_biasW = V4SetW(body1Anchor, FZero());
/*f0->raXn_biasScaleW = V4SetW(Vec4V_From_Vec3V(raXn), frictionBiasScale);
f0->rbXn_errorW = V4SetW(rbXn, V3Dot(error, t0));*/
f0->raXnI_targetVelW = V4SetW(raXnInertia, targetVel);
f0->rbXnI_velMultiplierW = V4SetW(rbXnInertia, velMultiplier);
f0->appliedForce = 0.f;
f0->frictionScale = frictionScale;
f0->biasScale = frictionBiasScale;
}
{
FloatV targetVel = V3Dot(tvel, t1);
Vec3V raXn = V3Cross(ra, t1);
Vec3V rbXn = V3Cross(rb, t1);
raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, raXn);
const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, rbXn);
const FloatV resp0 = FAdd(invMassNorLenSq0, FMul(V3Dot(raXnInertia, raXnInertia), angD0));
const FloatV resp1 = FSub(FMul(V3Dot(rbXnInertia, rbXnInertia), angD1), invMassNorLenSq1);
const FloatV unitResponse = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FDiv(p8, unitResponse), zero);
//const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FRecip(unitResponse), zero);
if (isKinematic0)
targetVel = FSub(targetVel, FAdd(norVel10, V3Dot(raXn, angVel0)));
if (isKinematic1)
targetVel = FAdd(targetVel, FAdd(norVel11, V3Dot(rbXn, angVel1)));
f1->normalXYZ_ErrorW = V4SetW(t1, V3Dot(error, t1));
//f1->raXnXYZ_targetVelW = V4SetW(body0Anchor, targetVel);
//f1->rbXnXYZ_biasW = V4SetW(body1Anchor, FZero());
//f1->raXn_biasScaleW = V4SetW(Vec4V_From_Vec3V(V3Cross(ra, t1)), frictionBiasScale);
//f1->rbXn_errorW = V4SetW(V3Cross(rb, t1), V3Dot(error, t1));
f1->raXnI_targetVelW = V4SetW(raXnInertia, targetVel);
f1->rbXnI_velMultiplierW = V4SetW(rbXnInertia, velMultiplier);
f1->appliedForce = 0.f;
f1->frictionScale = frictionScale;
f1->biasScale = frictionBiasScale;
}
}
if (hasTorsionalFriction && frictionPatch.anchorCount == 1)
{
const FloatV torsionalPatchRadius = FLoad(torsionalPatchRadiusF32);
const FloatV minTorsionalPatchRadius = FLoad(minTorsionalPatchRadiusF32);
const FloatV torsionalFriction = FMax(minTorsionalPatchRadius, FSqrt(FMul(FMax(zero, FNeg(maxPenetration)), torsionalPatchRadius)));
header->numFrictionConstr++;
SolverContactFrictionStep* PX_RESTRICT f = reinterpret_cast<SolverContactFrictionStep*>(ptr);
ptr += frictionStride;
const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, normal);
const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, normal);
const FloatV resp0 = FMul(V3Dot(raXnInertia, raXnInertia), angD0);
const FloatV resp1 = FMul(V3Dot(rbXnInertia, rbXnInertia), angD1);
const FloatV unitResponse = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FDiv(p8, unitResponse), zero);
FloatV targetVel = zero;
if (isKinematic0)
targetVel = V3Dot(normal, angVel0);
if (isKinematic1)
targetVel = V3Dot(normal, angVel1);
f->normalXYZ_ErrorW = V4Zero();
f->raXnI_targetVelW = V4SetW(raXnInertia, targetVel);
f->rbXnI_velMultiplierW = V4SetW(rbXnInertia, velMultiplier);
f->biasScale = 0.f;
f->appliedForce = 0.f;
FStore(torsionalFriction, &f->frictionScale);
}
}
frictionPatchWritebackAddrIndex++;
}
}
static FloatV setupExtSolverContactStep(const SolverExtBodyStep& b0, const SolverExtBodyStep& b1,
const FloatV& d0, const FloatV& d1, const FloatV& angD0, const FloatV& angD1, const Vec3V& bodyFrame0p, const Vec3V& bodyFrame1p,
const Vec3VArg normal, const FloatVArg invDt, const FloatVArg invDtp8, const FloatVArg invStepDt, const FloatVArg totalDt,
const FloatVArg dt, const FloatVArg restDistance, const FloatVArg restitution, const FloatVArg damping,
const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointStepExt& solverContact, const FloatVArg /*ccdMaxSeparation*/,
const bool isKinematic0, const bool isKinematic1, const FloatVArg cfm,
const Cm::SpatialVectorV& v0, const Cm::SpatialVectorV& v1,
const Vec3VArg solverOffsetSlop, const FloatVArg norVel0, const FloatVArg norVel1)
{
const FloatV zero = FZero();
const FloatV separation = FLoad(contact.separation);
FloatV penetration = FSub(separation, restDistance);
const Vec3V ra = V3Sub(V3LoadA(contact.point),bodyFrame0p);
const Vec3V rb = V3Sub(V3LoadA(contact.point), bodyFrame1p);
Vec3V raXn = V3Cross(ra, normal);
Vec3V rbXn = V3Cross(rb, normal);
Cm::SpatialVectorV deltaV0, deltaV1;
const FloatV vRelAng = V3SumElems(V3Sub(V3Mul(v0.angular, raXn), V3Mul(v1.angular, rbXn)));
const FloatV vRelLin = FSub(norVel0, norVel1);
const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(vRelLin, zero), FOne(), FDiv(vRelAng, vRelLin)), FOne()));
raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn);
const FloatV angV0 = V3Dot(v0.angular, raXn);
const FloatV angV1 = V3Dot(v1.angular, rbXn);
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(normal, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(normal), V3Neg(rbXn), b1);
FloatV unitResponse = getImpulseResponse(
b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1,
false);
const FloatV vrel = FAdd(vRelAng, vRelLin);
FloatV scaledBias, velMultiplier;
FloatV recipResponse = FSel(FIsGrtr(unitResponse, FZero()), FRecip(FAdd(unitResponse, cfm)), zero);
if (FAllGrtr(zero, restitution))
{
const FloatV nrdt = FMul(dt, restitution);
const FloatV a = FMul(dt, FSub(damping, nrdt));
const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne()));
velMultiplier = FMul(x, a);
//scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier));
scaledBias = FMul(nrdt, FMul(x, unitResponse));
}
else
{
velMultiplier = recipResponse;
scaledBias = FNeg(FSel(FIsGrtr(penetration, zero), invStepDt, invDtp8));
}
const FloatV penetrationInvDt = FMul(penetration, invDt);
const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt));
FloatV targetVelocity = FSel(isGreater2, FMul(FNeg(vrel), restitution), zero);
const FloatV cTargetVel = V3Dot(V3LoadA(contact.targetVel), normal);
targetVelocity = FAdd(targetVelocity, cTargetVel);
//const FloatV deltaF = FMax(FMul(FSub(targetVelocity, FAdd(vrel, FMax(zero, penetrationInvDt))), velMultiplier), zero);
const FloatV deltaF = FMax(FMul(FAdd(targetVelocity, FSub(FNeg(penetrationInvDt), vrel)), velMultiplier), zero);
const FloatV ratio = FSel(isGreater2, FAdd(totalDt, FDiv(penetration, vrel)), zero);
penetration = FScaleAdd(targetVelocity, ratio, penetration);
if (isKinematic0)
targetVelocity = FSub(targetVelocity, FAdd(norVel0, angV0));
if(isKinematic1)
targetVelocity = FAdd(targetVelocity, FAdd(norVel1, angV1));
FStore(scaledBias, &solverContact.biasCoefficient);
FStore(targetVelocity, &solverContact.targetVelocity);
FStore(recipResponse, &solverContact.recipResponse);
const Vec4V raXnI_Sepw = V4SetW(Vec4V_From_Vec3V(resp0.angular), penetration);
const Vec4V rbXnI_velMulW = V4SetW(Vec4V_From_Vec3V(V3Neg(resp1.angular)), velMultiplier);
//solverContact.raXnI = resp0.angular;
//solverContact.rbXnI = -resp1.angular;
V4StoreA(raXnI_Sepw, &solverContact.raXnI.x);
V4StoreA(rbXnI_velMulW, &solverContact.rbXnI.x);
solverContact.linDeltaVA = deltaV0.linear;
solverContact.angDeltaVA = deltaV0.angular;
solverContact.linDeltaVB = deltaV1.linear;
solverContact.angDeltaVB = deltaV1.angular;
solverContact.maxImpulse = contact.maxImpulse;
return deltaF;
}
//PX_INLINE void computeFrictionTangents(const PxVec3& vrel, const PxVec3& unitNormal, PxVec3& t0, PxVec3& t1)
//{
// PX_ASSERT(PxAbs(unitNormal.magnitude() - 1)<1e-3f);
// t0 = vrel - unitNormal * unitNormal.dot(vrel);
// PxReal ll = t0.magnitudeSquared();
// if (ll > 0.1f) //can set as low as 0.
// {
// t0 *= PxRecipSqrt(ll);
// t1 = unitNormal.cross(t0);
// }
// else
// PxNormalToTangents(unitNormal, t0, t1); //fallback
//}
PxVec3 SolverExtBodyStep::getLinVel() const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return mBody->linearVelocity;
else
{
Cm::SpatialVectorV velocity = mArticulation->getLinkVelocity(mLinkIndex);
PxVec3 result;
V3StoreU(velocity.linear, result);
return result;
}
}
Cm::SpatialVectorV SolverExtBodyStep::getVelocity() const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return Cm::SpatialVectorV(V3LoadA(mData->originalLinearVelocity), V3LoadA(mData->originalAngularVelocity));
else
return mArticulation->getLinkVelocity(mLinkIndex);
}
void setupFinalizeExtSolverContactsStep(
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const SolverExtBodyStep& b0,
const SolverExtBodyStep& b1,
const PxReal invDtF32,
const PxReal invTotalDtF32,
const PxReal totalDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
const PxReal restDist,
PxU8* frictionDataPtr,
PxReal ccdMaxContactDist,
const PxReal torsionalPatchRadiusF32,
const PxReal minTorsionalPatchRadiusF32,
const PxReal biasCoefficient,
const PxReal solverOffsetSlop)
{
// NOTE II: the friction patches are sparse (some of them have no contact patches, and
// therefore did not get written back to the cache) but the patch addresses are dense,
// corresponding to valid patches
/*const bool haveFriction = PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;*/
const bool isKinematic0 = b0.isKinematic();
const bool isKinematic1 = b1.isKinematic();
const FloatV ccdMaxSeparation = FLoad(ccdMaxContactDist);
bool hasTorsionalFriction = torsionalPatchRadiusF32 > 0.f || minTorsionalPatchRadiusF32 > 0.f;
const FloatV quarter = FLoad(0.25f);
PxU8* PX_RESTRICT ptr = workspace;
const FloatV zero = FZero();
const PxF32 maxPenBias0 = b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY ? b0.mData->penBiasClamp : b0.mArticulation->getLinkMaxPenBias(b0.mLinkIndex);
const PxF32 maxPenBias1 = b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY ? b1.mData->penBiasClamp : b1.mArticulation->getLinkMaxPenBias(b1.mLinkIndex);
const PxReal maxPenBias = PxMax(maxPenBias0, maxPenBias1);
const Cm::SpatialVectorV v0 = b0.getVelocity();
const Cm::SpatialVectorV v1 = b1.getVelocity();
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p);
const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p);
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero();
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d0);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d1);
const FloatV restDistance = FLoad(restDist);
PxU32 frictionPatchWritebackAddrIndex = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
const FloatV invDt = FLoad(invDtF32);
const FloatV invTotalDt = FLoad(invTotalDtF32);
const PxReal scale = PxMin(0.8f, biasCoefficient);
const FloatV p8 = FLoad(scale);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const FloatV totalDt = FLoad(totalDtF32);
const FloatV dt = FLoad(dtF32);
const FloatV invDtp8 = FMul(invDt, p8);
const FloatV cfm = FLoad(PxMax(b0.getCFM(), b1.getCFM()));
PxU8 flags = 0;
const Vec3V offsetSlop = V3Load(solverOffsetSlop);
for (PxU32 i = 0; i<c.frictionPatchCount; i++)
{
PxU32 contactCount = c.frictionPatchContactCounts[i];
if (contactCount == 0)
continue;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
PX_ASSERT(frictionPatch.anchorCount <= 2); //0==anchorCount is allowed if all the contacts in the manifold have a large offset.
const PxContactPoint* contactBase0 = buffer + c.contactPatches[c.correlationListHeads[i]].start;
const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(contactBase0->staticFriction));
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(contactBase0->dynamicFriction));
const PxReal frictionBiasScale = disableStrongFriction ? 0.f : invDtF32 * 0.8f;
SolverContactHeaderStep* PX_RESTRICT header = reinterpret_cast<SolverContactHeaderStep*>(ptr);
ptr += sizeof(SolverContactHeaderStep);
PxPrefetchLine(ptr + 128);
PxPrefetchLine(ptr + 256);
PxPrefetchLine(ptr + 384);
const bool haveFriction = (disableStrongFriction == 0);//PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;
header->numNormalConstr = PxTo8(contactCount);
header->numFrictionConstr = PxTo8(haveFriction ? frictionPatch.anchorCount * 2 : 0);
header->type = PxTo8(DY_SC_TYPE_EXT_CONTACT);
header->flags = flags;
const FloatV restitution = FLoad(contactBase0->restitution);
const FloatV damping = FLoad(contactBase0->damping);
header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W;
header->angDom0 = invInertiaScale0;
header->angDom1 = invInertiaScale1;
const PxU32 pointStride = sizeof(SolverContactPointStepExt);
const PxU32 frictionStride = sizeof(SolverContactFrictionStepExt);
const Vec3V normal = V3LoadU(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal);
V3StoreA(normal, header->normal);
header->maxPenBias = maxPenBias;
FloatV maxPenetration = FZero();
FloatV accumulatedImpulse = FZero();
const FloatV norVel0 = V3Dot(v0.linear, normal);
const FloatV norVel1 = V3Dot(v1.linear, normal);
for (PxU32 patch = c.correlationListHeads[i];
patch != CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer + c.contactPatches[patch].start;
PxU8* p = ptr;
for (PxU32 j = 0; j<count; j++)
{
const PxContactPoint& contact = contactBase[j];
SolverContactPointStepExt* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointStepExt*>(p);
p += pointStride;
accumulatedImpulse = FAdd(accumulatedImpulse, setupExtSolverContactStep(b0, b1, d0, d1, angD0, angD1, bodyFrame0p, bodyFrame1p, normal, invTotalDt, invDtp8,
invDt, totalDt, dt, restDistance, restitution, damping, bounceThreshold, contact, *solverContact, ccdMaxSeparation, isKinematic0, isKinematic1,
cfm, v0, v1, offsetSlop, norVel0, norVel1));
maxPenetration = FMin(FLoad(contact.separation), maxPenetration);
}
ptr = p;
}
accumulatedImpulse = FMul(FDiv(accumulatedImpulse, FLoad(PxF32(contactCount))), quarter);
FStore(accumulatedImpulse, &header->minNormalForce);
PxF32* forceBuffer = reinterpret_cast<PxF32*>(ptr);
PxMemZero(forceBuffer, sizeof(PxF32) * contactCount);
ptr += sizeof(PxF32) * ((contactCount + 3) & (~3));
header->broken = 0;
if (haveFriction)
{
//const Vec3V normal = Vec3V_From_PxVec3(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const Vec3V linVrel = V3Sub(v0.linear, v1.linear);
//const Vec3V normal = Vec3V_From_PxVec3_Aligned(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV orthoThreshold = FLoad(0.70710678f);
const FloatV p1 = FLoad(0.0001f);
// fallback: normal.cross((1,0,0)) or normal.cross((0,0,1))
const FloatV normalX = V3GetX(normal);
const FloatV normalY = V3GetY(normal);
const FloatV normalZ = V3GetZ(normal);
Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY);
Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero);
Vec3V t0Fallback = V3Sel(FIsGrtr(orthoThreshold, FAbs(normalX)), t0Fallback1, t0Fallback2);
Vec3V t0 = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel)));
t0 = V3Sel(FIsGrtr(V3LengthSq(t0), p1), t0, t0Fallback);
t0 = V3Normalize(t0);
const VecCrossV t0Cross = V3PrepareCross(t0);
const Vec3V t1 = V3Cross(normal, t0Cross);
const VecCrossV t1Cross = V3PrepareCross(t1);
//We want to set the writeBack ptr to point to the broken flag of the friction patch.
//On spu we have a slight problem here because the friction patch array is
//in local store rather than in main memory. The good news is that the address of the friction
//patch array in main memory is stored in the work unit. These two addresses will be equal
//except on spu where one is local store memory and the other is the effective address in main memory.
//Using the value stored in the work unit guarantees that the main memory address is used on all platforms.
PxU8* PX_RESTRICT writeback = frictionDataPtr + frictionPatchWritebackAddrIndex * sizeof(FrictionPatch);
header->frictionBrokenWritebackByte = writeback;
PxReal frictionScale = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f;
for (PxU32 j = 0; j < frictionPatch.anchorCount; j++)
{
SolverContactFrictionStepExt* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionStepExt*>(ptr);
ptr += frictionStride;
SolverContactFrictionStepExt* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionStepExt*>(ptr);
ptr += frictionStride;
Vec3V ra = V3LoadU(bodyFrame0.q.rotate(frictionPatch.body0Anchors[j]));
Vec3V rb = V3LoadU(bodyFrame1.q.rotate(frictionPatch.body1Anchors[j]));
Vec3V error = V3Sub(V3Add(ra, bodyFrame0p), V3Add(rb,bodyFrame1p));
{
Vec3V raXn = V3Cross(ra, t0Cross);
Vec3V rbXn = V3Cross(rb, t0Cross);
raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t0, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t0), V3Neg(rbXn), b1);
FloatV resp = getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, false);
const FloatV velMultiplier = FSel(FIsGrtr(resp, FEps()), FDiv(p8, FAdd(cfm, resp)), zero);
PxU32 index = c.contactPatches[c.correlationListHeads[i]].start;
FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t0);
if(isKinematic0)
targetVel = FSub(targetVel, v0.dot(resp0));
if(isKinematic1)
targetVel = FSub(targetVel, v1.dot(resp1));
f0->normalXYZ_ErrorW = V4SetW(Vec4V_From_Vec3V(t0), V3Dot(error, t0));
f0->raXnI_targetVelW = V4SetW(Vec4V_From_Vec3V(resp0.angular), targetVel);
f0->rbXnI_velMultiplierW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), velMultiplier);
f0->appliedForce = 0.f;
f0->biasScale = frictionBiasScale;
f0->linDeltaVA = deltaV0.linear;
f0->linDeltaVB = deltaV1.linear;
f0->angDeltaVA = deltaV0.angular;
f0->angDeltaVB = deltaV1.angular;
f0->frictionScale = frictionScale;
}
{
Vec3V raXn = V3Cross(ra, t1Cross);
Vec3V rbXn = V3Cross(rb, t1Cross);
raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t1, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t1), V3Neg(rbXn), b1);
FloatV resp = getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, false);
const FloatV velMultiplier = FSel(FIsGrtr(resp, FEps()), FDiv(p8, FAdd(cfm, resp)), zero);
PxU32 index = c.contactPatches[c.correlationListHeads[i]].start;
FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t1);
if (isKinematic0)
targetVel = FSub(targetVel, v0.dot(resp0));
if (isKinematic1)
targetVel = FSub(targetVel, v1.dot(resp1));
f1->normalXYZ_ErrorW = V4SetW(Vec4V_From_Vec3V(t1), V3Dot(error, t1));
f1->raXnI_targetVelW = V4SetW(Vec4V_From_Vec3V(resp0.angular), targetVel);
f1->rbXnI_velMultiplierW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), velMultiplier);
f1->appliedForce = 0.f;
f1->biasScale = frictionBiasScale;
f1->linDeltaVA = deltaV0.linear;
f1->linDeltaVB = deltaV1.linear;
f1->angDeltaVA = deltaV0.angular;
f1->angDeltaVB = deltaV1.angular;
f1->frictionScale = frictionScale;
}
}
if (hasTorsionalFriction && frictionPatch.anchorCount == 1)
{
const FloatV torsionalPatchRadius = FLoad(torsionalPatchRadiusF32);
const FloatV minTorsionalPatchRadius = FLoad(minTorsionalPatchRadiusF32);
const FloatV torsionalFriction = FMax(minTorsionalPatchRadius, FSqrt(FMul(FMax(zero, FNeg(maxPenetration)), torsionalPatchRadius)));
header->numFrictionConstr++;
SolverContactFrictionStepExt* PX_RESTRICT f = reinterpret_cast<SolverContactFrictionStepExt*>(ptr);
ptr += frictionStride;
const Cm::SpatialVector resp0 = createImpulseResponseVector(PxVec3(0.f), header->normal, b0);
const Cm::SpatialVector resp1 = createImpulseResponseVector(PxVec3(0.f), -header->normal, b1);
Cm::SpatialVector deltaV0, deltaV1;
PxReal ur = getImpulseResponse(b0, resp0, deltaV0, invMassScale0, invInertiaScale0,
b1, resp1, deltaV1, invMassScale1, invInertiaScale1, false);
FloatV resp = FLoad(ur);
const FloatV velMultiplier = FSel(FIsGrtr(resp, FEps()), FDiv(p8, FAdd(cfm, resp)), zero);
f->normalXYZ_ErrorW = V4Zero();
f->raXnI_targetVelW = V4SetW(V3LoadA(resp0.angular), zero);
f->rbXnI_velMultiplierW = V4SetW(V4Neg(Vec4V_From_Vec3V(V3LoadA(resp1.angular))), velMultiplier);
f->biasScale = 0.f;
f->appliedForce = 0.f;
FStore(torsionalFriction, &f->frictionScale);
f->linDeltaVA = V3LoadA(deltaV0.linear);
f->linDeltaVB = V3LoadA(deltaV1.linear);
f->angDeltaVA = V3LoadA(deltaV0.angular);
f->angDeltaVB = V3LoadA(deltaV1.angular);
}
}
frictionPatchWritebackAddrIndex++;
}
}
bool createFinalizeSolverContactsStep(
PxTGSSolverContactDesc& contactDesc,
CorrelationBuffer& c,
const PxReal invDtF32,
const PxReal invTotalDtF32,
const PxReal totalDtF32,
const PxReal dtF32,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator)
{
PxPrefetchLine(contactDesc.body0);
PxPrefetchLine(contactDesc.body1);
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
const bool hasForceThreshold = contactDesc.hasForceThresholds;
const bool staticOrKinematicBody = contactDesc.bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY || contactDesc.bodyState1 == PxSolverContactDesc::eSTATIC_BODY;
const bool disableStrongFriction = contactDesc.disableStrongFriction;
PxSolverConstraintDesc& desc = *contactDesc.desc;
const bool useExtContacts = (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY);
desc.constraintLengthOver16 = 0;
if (contactDesc.numContacts == 0)
{
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
desc.constraint = NULL;
return true;
}
if (!disableStrongFriction)
{
getFrictionPatches(c, contactDesc.frictionPtr, contactDesc.frictionCount, contactDesc.bodyFrame0, contactDesc.bodyFrame1, correlationDistance);
}
bool overflow = !createContactPatches(c, contactDesc.contacts, contactDesc.numContacts, PXC_SAME_NORMAL);
overflow = correlatePatches(c, contactDesc.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, PXC_SAME_NORMAL, 0, 0) || overflow;
PX_UNUSED(overflow);
#if PX_CHECKED
if (overflow)
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL, "Dropping contacts in solver because we exceeded limit of 32 friction patches.");
#endif
growPatches(c, contactDesc.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, 0, frictionOffsetThreshold + contactDesc.restDistance);
//PX_ASSERT(patchCount == c.frictionPatchCount);
FrictionPatch* frictionPatches = NULL;
PxU8* solverConstraint = NULL;
PxU32 numFrictionPatches = 0;
PxU32 solverConstraintByteSize = 0;
PxU32 axisConstraintCount = 0;
const bool successfulReserve = reserveBlockStreams(
useExtContacts, c,
solverConstraint, frictionPatches,
numFrictionPatches,
solverConstraintByteSize,
axisConstraintCount,
constraintAllocator,
PxMax(contactDesc.torsionalPatchRadius, contactDesc.minTorsionalPatchRadius));
// initialise the work unit's ptrs to the various buffers.
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
desc.constraint = NULL;
desc.constraintLengthOver16 = 0;
// patch up the work unit with the reserved buffers and set the reserved buffer data as appropriate.
if (successfulReserve)
{
PxU8* frictionDataPtr = reinterpret_cast<PxU8*>(frictionPatches);
contactDesc.frictionPtr = frictionDataPtr;
desc.constraint = solverConstraint;
//output.nbContacts = PxTo8(numContacts);
contactDesc.frictionCount = PxTo8(numFrictionPatches);
PX_ASSERT((solverConstraintByteSize & 0xf) == 0);
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize / 16);
desc.writeBack = contactDesc.contactForces;
//Initialise friction buffer.
if (frictionPatches)
{
// PT: TODO: revisit this... not very satisfying
//const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch);
PxPrefetchLine(frictionPatches);
PxPrefetchLine(frictionPatches, 128);
PxPrefetchLine(frictionPatches, 256);
for (PxU32 i = 0; i<c.frictionPatchCount; i++)
{
//if(c.correlationListHeads[i]!=CorrelationBuffer::LIST_END)
if (c.frictionPatchContactCounts[i])
{
*frictionPatches++ = c.frictionPatches[i];
PxPrefetchLine(frictionPatches, 256);
}
}
}
//Initialise solverConstraint buffer.
if (solverConstraint)
{
if (useExtContacts)
{
const SolverExtBodyStep b0(reinterpret_cast<const void*>(contactDesc.body0), contactDesc.body0TxI, contactDesc.bodyData0, desc.linkIndexA);
const SolverExtBodyStep b1(reinterpret_cast<const void*>(contactDesc.body1), contactDesc.body1TxI, contactDesc.bodyData1, desc.linkIndexB);
setupFinalizeExtSolverContactsStep(contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
b0, b1, invDtF32, invTotalDtF32, totalDtF32, dtF32, bounceThresholdF32,
contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1,
contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, contactDesc.torsionalPatchRadius, contactDesc.minTorsionalPatchRadius,
biasCoefficient, contactDesc.offsetSlop);
}
else
{
const PxTGSSolverBodyVel& b0 = *contactDesc.body0;
const PxTGSSolverBodyVel& b1 = *contactDesc.body1;
setupFinalizeSolverConstraints(getInteraction(contactDesc), contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
b0, b1, *contactDesc.body0TxI, *contactDesc.body1TxI, *contactDesc.bodyData0, *contactDesc.bodyData1, invDtF32, totalDtF32, invTotalDtF32, dtF32, bounceThresholdF32,
contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1,
hasForceThreshold, staticOrKinematicBody, contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, disableStrongFriction,
contactDesc.torsionalPatchRadius, contactDesc.minTorsionalPatchRadius, biasCoefficient,
contactDesc.offsetSlop);
}
//KS - set to 0 so we have a counter for the number of times we solved the constraint
//only going to be used on SPU but might as well set on all platforms because this code is shared
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
}
}
return successfulReserve;
}
bool createFinalizeSolverContactsStep(PxTGSSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal invTotalDt,
const PxReal totalDtF32,
const PxReal dt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
// We pull the friction patches out of the cache to remove the dependency on how
// the cache is organized. Remember original addrs so we can write them back
// efficiently.
PxU32 numContacts = 0;
{
PxReal invMassScale0 = 1.f;
PxReal invMassScale1 = 1.f;
PxReal invInertiaScale0 = 1.f;
PxReal invInertiaScale1 = 1.f;
contactDesc.invMassScales.angular0 = (contactDesc.bodyState0 != PxSolverContactDesc::eARTICULATION && contactDesc.body0->isKinematic) ? 0.f : contactDesc.invMassScales.angular0;
contactDesc.invMassScales.angular1 = (contactDesc.bodyState1 != PxSolverContactDesc::eARTICULATION && contactDesc.body1->isKinematic) ? 0.f : contactDesc.invMassScales.angular1;
bool hasMaxImpulse = false, hasTargetVelocity = false;
numContacts = extractContacts(buffer, output, hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, contactDesc.maxImpulse);
contactDesc.contacts = buffer.contacts;
contactDesc.numContacts = numContacts;
contactDesc.disableStrongFriction = contactDesc.disableStrongFriction || hasTargetVelocity;
contactDesc.hasMaxImpulse = hasMaxImpulse;
contactDesc.invMassScales.linear0 *= invMassScale0;
contactDesc.invMassScales.linear1 *= invMassScale1;
contactDesc.invMassScales.angular0 *= invInertiaScale0;
contactDesc.invMassScales.angular1 *= invInertiaScale1;
}
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
return createFinalizeSolverContactsStep(contactDesc, c, invDtF32, invTotalDt, totalDtF32, dt, bounceThresholdF32,
frictionOffsetThreshold, correlationDistance, biasCoefficient, constraintAllocator);
}
static FloatV solveDynamicContactsStep(SolverContactPointStep* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
const FloatVArg invMassA, const FloatVArg invMassB, Vec3V& linVel0_, Vec3V& angState0_,
Vec3V& linVel1_, Vec3V& angState1_, PxF32* PX_RESTRICT forceBuffer,
const Vec3V& angMotion0, const Vec3V& angMotion1,
const Vec3V& linRelMotion, const FloatVArg maxPenBias,
const FloatVArg angD0, const FloatVArg angD1, const FloatVArg minPen,
const FloatVArg elapsedTime)
{
Vec3V linVel0 = linVel0_;
Vec3V angState0 = angState0_;
Vec3V linVel1 = linVel1_;
Vec3V angState1 = angState1_;
const FloatV zero = FZero();
FloatV accumulatedNormalImpulse = zero;
const Vec3V delLinVel0 = V3Scale(contactNormal, invMassA);
const Vec3V delLinVel1 = V3Scale(contactNormal, invMassB);
const FloatV deltaV = V3Dot(linRelMotion, contactNormal);
for (PxU32 i = 0; i<nbContactPoints; i++)
{
SolverContactPointStep& c = contacts[i];
PxPrefetchLine(&contacts[i], 128);
const Vec3V raXnI = V3LoadA(c.raXnI);
const Vec3V rbXnI = V3LoadA(c.rbXnI);
const FloatV angDelta0 = V3Dot(angMotion0, raXnI);
const FloatV angDelta1 = V3Dot(angMotion1, rbXnI);
const FloatV deltaAng = FSub(angDelta0, angDelta1);
const FloatV targetVel = FLoad(c.targetVelocity);
//const FloatV tVelBias = FLoad(c.targetVelBias);
const FloatV deltaBias = FSub(FAdd(deltaV, deltaAng), FMul(targetVel, elapsedTime));
const FloatV biasCoefficient = FLoad(c.biasCoefficient);
FloatV sep = FMax(minPen, FAdd(FLoad(c.separation), deltaBias));
const FloatV bias = FMin(FNeg(maxPenBias), FMul(biasCoefficient, sep));
const Vec3V v0 = V3MulAdd(linVel0, contactNormal, V3Mul(angState0, raXnI));
const Vec3V v1 = V3MulAdd(linVel1, contactNormal, V3Mul(angState1, rbXnI));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV velMultiplier = FLoad(c.velMultiplier);
const FloatV biasNV = FMul(bias, FLoad(c.recipResponse));
const FloatV tVelBias = FNegScaleSub(FSub(normalVel, targetVel), velMultiplier, biasNV);
const FloatV appliedForce = FLoad(forceBuffer[i]);
const FloatV maxImpulse = FLoad(c.maxImpulse); //KS - todo - hook up!
//Compute the normal velocity of the constraint.
const FloatV _deltaF = FMax(tVelBias, FNeg(appliedForce));
const FloatV _newForce = FAdd(appliedForce, _deltaF);
const FloatV newForce = FMin(_newForce, maxImpulse);
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1);
angState0 = V3ScaleAdd(raXnI, FMul(deltaF, angD0), angState0);
angState1 = V3NegScaleSub(rbXnI, FMul(deltaF, angD1), angState1);
FStore(newForce, &forceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newForce);
}
linVel0_ = linVel0;
angState0_ = angState0;
linVel1_ = linVel1;
angState1_ = angState1;
return accumulatedNormalImpulse;
}
void solveContact(const PxSolverConstraintDesc& desc, bool doFriction, const PxReal minPenetration,
const PxReal elapsedTimeF32)
{
PxTGSSolverBodyVel& b0 = *desc.tgsBodyA;
PxTGSSolverBodyVel& b1 = *desc.tgsBodyB;
const FloatV minPen = FLoad(minPenetration);
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V linVel1 = V3LoadA(b1.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularVelocity);
Vec3V angState1 = V3LoadA(b1.angularVelocity);
const Vec3V angMotion0 = V3LoadA(b0.deltaAngDt);
const Vec3V angMotion1 = V3LoadA(b1.deltaAngDt);
const Vec3V linMotion0 = V3LoadA(b0.deltaLinDt);
const Vec3V linMotion1 = V3LoadA(b1.deltaLinDt);
const Vec3V relMotion = V3Sub(linMotion0, linMotion1);
const FloatV zero = FZero();
const FloatV elapsedTime = FLoad(elapsedTimeF32);
const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
while (currPtr < last)
{
SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr);
currPtr += sizeof(SolverContactHeaderStep);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverContactPointStep* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStep*>(currPtr);
PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPointStep);
PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr);
currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
SolverContactFrictionStep* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStep*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionStep);
const FloatV invMassA = FLoad(hdr->invMass0);
const FloatV invMassB = FLoad(hdr->invMass1);
const FloatV angDom0 = FLoad(hdr->angDom0);
const FloatV angDom1 = FLoad(hdr->angDom1);
//const FloatV sumMass = FAdd(invMassA, invMassB);
const Vec3V contactNormal = V3LoadA(hdr->normal);
const FloatV maxPenBias = FLoad(hdr->maxPenBias);
const FloatV accumulatedNormalImpulse = solveDynamicContactsStep(contacts, numNormalConstr, contactNormal, invMassA, invMassB,
linVel0, angState0, linVel1, angState1, forceBuffer,angMotion0, angMotion1, relMotion, maxPenBias, angDom0, angDom1, minPen,
elapsedTime);
FStore(accumulatedNormalImpulse, &hdr->minNormalForce);
if (numFrictionConstr && doFriction)
{
const FloatV staticFrictionCof = hdr->getStaticFriction();
const FloatV dynamicFrictionCof = hdr->getDynamicFriction();
const FloatV maxFrictionImpulse = FMul(staticFrictionCof, accumulatedNormalImpulse);
const FloatV maxDynFrictionImpulse = FMul(dynamicFrictionCof, accumulatedNormalImpulse);
const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse);
BoolV broken = BFFFF();
//We will have either 4 or 2 frictions (with friction pairs).
//With torsional friction, we may have 3 (a single friction anchor + twist).
const PxU32 numFrictionPairs = (numFrictionConstr&6);
for (PxU32 i = 0; i<numFrictionPairs; i += 2)
{
SolverContactFrictionStep& f0 = frictions[i];
SolverContactFrictionStep& f1 = frictions[i + 1];
PxPrefetchLine(&frictions[i + 2], 128);
const FloatV frictionScale = FLoad(f0.frictionScale);
const Vec4V normalXYZ_ErrorW0 = f0.normalXYZ_ErrorW;
const Vec4V raXnI_targetVelW0 = f0.raXnI_targetVelW;
const Vec4V rbXnI_velMultiplierW0 = f0.rbXnI_velMultiplierW;
const Vec4V normalXYZ_ErrorW1 = f1.normalXYZ_ErrorW;
const Vec4V raXnI_targetVelW1 = f1.raXnI_targetVelW;
const Vec4V rbXnI_velMultiplierW1 = f1.rbXnI_velMultiplierW;
const Vec3V normal0 = Vec3V_From_Vec4V(normalXYZ_ErrorW0);
const Vec3V normal1 = Vec3V_From_Vec4V(normalXYZ_ErrorW1);
const FloatV initialError0 = V4GetW(normalXYZ_ErrorW0);
const FloatV initialError1 = V4GetW(normalXYZ_ErrorW1);
const FloatV biasScale = FLoad(f0.biasScale); //Bias scale will be common
const Vec3V raXnI0 = Vec3V_From_Vec4V(raXnI_targetVelW0);
const Vec3V rbXnI0 = Vec3V_From_Vec4V(rbXnI_velMultiplierW0);
const Vec3V raXnI1 = Vec3V_From_Vec4V(raXnI_targetVelW1);
const Vec3V rbXnI1 = Vec3V_From_Vec4V(rbXnI_velMultiplierW1);
const FloatV appliedForce0 = FLoad(f0.appliedForce);
const FloatV appliedForce1 = FLoad(f1.appliedForce);
const FloatV targetVel0 = V4GetW(raXnI_targetVelW0);
const FloatV targetVel1 = V4GetW(raXnI_targetVelW1);
FloatV deltaV0 = FAdd(FSub(V3Dot(raXnI0, angMotion0), V3Dot(rbXnI0, angMotion1)), V3Dot(normal0, relMotion));
FloatV deltaV1 = FAdd(FSub(V3Dot(raXnI1, angMotion0), V3Dot(rbXnI1, angMotion1)), V3Dot(normal1, relMotion));
deltaV0 = FSub(deltaV0, FMul(targetVel0, elapsedTime));
deltaV1 = FSub(deltaV1, FMul(targetVel1, elapsedTime));
const FloatV error0 = FAdd(initialError0, deltaV0);
const FloatV error1 = FAdd(initialError1, deltaV1);
const FloatV bias0 = FMul(error0, biasScale);
const FloatV bias1 = FMul(error1, biasScale);
const FloatV velMultiplier0 = V4GetW(rbXnI_velMultiplierW0);
const FloatV velMultiplier1 = V4GetW(rbXnI_velMultiplierW1);
const Vec3V delLinVel00 = V3Scale(normal0, invMassA);
const Vec3V delLinVel10 = V3Scale(normal0, invMassB);
const Vec3V delLinVel01 = V3Scale(normal1, invMassA);
const Vec3V delLinVel11 = V3Scale(normal1, invMassB);
const Vec3V v00 = V3MulAdd(linVel0, normal0, V3Mul(angState0, raXnI0));
const Vec3V v10 = V3MulAdd(linVel1, normal0, V3Mul(angState1, rbXnI0));
const FloatV normalVel0 = V3SumElems(V3Sub(v00, v10));
const Vec3V v01 = V3MulAdd(linVel0, normal1, V3Mul(angState0, raXnI1));
const Vec3V v11 = V3MulAdd(linVel1, normal1, V3Mul(angState1, rbXnI1));
const FloatV normalVel1 = V3SumElems(V3Sub(v01, v11));
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp10 = FNegScaleSub(FSub(bias0, targetVel0), velMultiplier0, appliedForce0);
const FloatV tmp11 = FNegScaleSub(FSub(bias1, targetVel1), velMultiplier1, appliedForce1);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse0 = FNegScaleSub(normalVel0, velMultiplier0, tmp10);
const FloatV totalImpulse1 = FNegScaleSub(normalVel1, velMultiplier1, tmp11);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const FloatV totalImpulse = FSqrt(FAdd(FMul(totalImpulse0, totalImpulse0), FMul(totalImpulse1, totalImpulse1)));
const BoolV clamp = FIsGrtr(totalImpulse, FMul(frictionScale, maxFrictionImpulse));
const FloatV totalClamped = FSel(clamp, FMin(FMul(frictionScale, maxDynFrictionImpulse), totalImpulse), totalImpulse);
const FloatV ratio = FSel(FIsGrtr(totalImpulse, zero), FDiv(totalClamped, totalImpulse), zero);
const FloatV newAppliedForce0 = FMul(totalImpulse0, ratio);
const FloatV newAppliedForce1 = FMul(totalImpulse1, ratio);
broken = BOr(broken, clamp);
FloatV deltaF0 = FSub(newAppliedForce0, appliedForce0);
FloatV deltaF1 = FSub(newAppliedForce1, appliedForce1);
// we could get rid of the stall here by calculating and clamping delta separately, but
// the complexity isn't really worth it.
linVel0 = V3ScaleAdd(delLinVel00, deltaF0, V3ScaleAdd(delLinVel01, deltaF1, linVel0));
linVel1 = V3NegScaleSub(delLinVel10, deltaF0, V3NegScaleSub(delLinVel11, deltaF1, linVel1));
angState0 = V3ScaleAdd(raXnI0, FMul(deltaF0, angDom0), V3ScaleAdd(raXnI1, FMul(deltaF1, angDom0), angState0));
angState1 = V3NegScaleSub(rbXnI0, FMul(deltaF0, angDom1), V3NegScaleSub(rbXnI1, FMul(deltaF1, angDom1), angState1));
f0.setAppliedForce(newAppliedForce0);
f1.setAppliedForce(newAppliedForce1);
}
for (PxU32 i = numFrictionPairs; i<numFrictionConstr; i++)
{
SolverContactFrictionStep& f = frictions[i];
const FloatV frictionScale = FLoad(f.frictionScale);
const Vec4V raXnI_targetVelW = f.raXnI_targetVelW;
const Vec4V rbXnI_velMultiplierW = f.rbXnI_velMultiplierW;
const Vec3V raXnI = Vec3V_From_Vec4V(raXnI_targetVelW);
const Vec3V rbXnI = Vec3V_From_Vec4V(rbXnI_velMultiplierW);
const FloatV appliedForce = FLoad(f.appliedForce);
const FloatV targetVel = V4GetW(raXnI_targetVelW);
const FloatV velMultiplier = V4GetW(rbXnI_velMultiplierW);
const Vec3V v0 =V3Mul(angState0, raXnI);
const Vec3V v1 =V3Mul(angState1, rbXnI);
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp1 = FNegScaleSub(FNeg(targetVel), velMultiplier, appliedForce);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const BoolV clamp = FIsGrtr(FAbs(totalImpulse), FMul(frictionScale, maxFrictionImpulse));
const FloatV totalClamped = FMin(FMul(frictionScale, maxDynFrictionImpulse), FMax(FMul(frictionScale, negMaxDynFrictionImpulse), totalImpulse));
const FloatV newAppliedForce = FSel(clamp, totalClamped, totalImpulse);
broken = BOr(broken, clamp);
FloatV deltaF = FSub(newAppliedForce, appliedForce);
// we could get rid of the stall here by calculating and clamping delta separately, but
// the complexity isn't really worth it.
angState0 = V3ScaleAdd(raXnI, FMul(deltaF, angDom0), angState0);
angState1 = V3NegScaleSub(rbXnI, FMul(deltaF, angDom1), angState1);
f.setAppliedForce(newAppliedForce);
}
Store_From_BoolV(broken, &hdr->broken);
}
}
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularVelocity.isFinite());
PX_ASSERT(b1.linearVelocity.isFinite());
PX_ASSERT(b1.angularVelocity.isFinite());
// Write back
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(linVel1, b1.linearVelocity);
V3StoreA(angState0, b0.angularVelocity);
V3StoreA(angState1, b1.angularVelocity);
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularVelocity.isFinite());
PX_ASSERT(b1.linearVelocity.isFinite());
PX_ASSERT(b1.angularVelocity.isFinite());
PX_ASSERT(currPtr == last);
}
void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext* /*cache*/)
{
// PxReal normalForce = 0;
PxU8* PX_RESTRICT cPtr = desc.constraint;
PxReal* PX_RESTRICT vForceWriteback = reinterpret_cast<PxReal*>(desc.writeBack);
PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16 * 16;
bool forceThreshold = false;
while (cPtr < last)
{
const SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<const SolverContactHeaderStep*>(cPtr);
cPtr += sizeof(SolverContactHeaderStep);
forceThreshold = hdr->flags & SolverContactHeaderStep::eHAS_FORCE_THRESHOLDS;
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
//if(cPtr < last)
PxPrefetchLine(cPtr, 256);
PxPrefetchLine(cPtr, 384);
const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointStepExt)
: sizeof(SolverContactPointStep);
cPtr += pointStride * numNormalConstr;
PxF32* forceBuffer = reinterpret_cast<PxF32*>(cPtr);
cPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
if (vForceWriteback != NULL)
{
for (PxU32 i = 0; i<numNormalConstr; i++)
{
PxReal appliedForce = forceBuffer[i];
*vForceWriteback++ = appliedForce;
// normalForce += appliedForce;
}
}
const PxU32 frictionStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactFrictionStepExt)
: sizeof(SolverContactFrictionStep);
if (hdr->broken && hdr->frictionBrokenWritebackByte != NULL)
{
*hdr->frictionBrokenWritebackByte = 1;
}
cPtr += frictionStride * numFrictionConstr;
}
PX_ASSERT(cPtr == last);
PX_UNUSED(forceThreshold);
#if 0
if (cache && forceThreshold && desc.linkIndexA == PxSolverConstraintDesc::NO_LINK && desc.linkIndexB == PxSolverConstraintDesc::NO_LINK &&
normalForce != 0 && (desc.bodyA->reportThreshold < PX_MAX_REAL || desc.bodyB->reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = normalForce;
elt.threshold = PxMin<float>(desc.bodyA->reportThreshold, desc.bodyB->reportThreshold);
elt.nodeIndexA = desc.bodyA->nodeIndex;
elt.nodeIndexB = desc.bodyB->nodeIndex;
elt.shapeInteraction = reinterpret_cast<const SolverContactHeader*>(desc.constraint)->shapeInteraction;
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache->mThresholdStreamIndex<cache->mThresholdStreamLength);
cache->mThresholdStream[cache->mThresholdStreamIndex++] = elt;
}
#endif
}
PX_FORCE_INLINE Vec3V V3FromV4(Vec4V x) { return Vec3V_From_Vec4V(x); }
PX_FORCE_INLINE Vec3V V3FromV4Unsafe(Vec4V x) { return Vec3V_From_Vec4V_WUndefined(x); }
PX_FORCE_INLINE Vec4V V4FromV3(Vec3V x) { return Vec4V_From_Vec3V(x); }
//PX_FORCE_INLINE Vec4V V4ClearW(Vec4V x) { return V4SetW(x, FZero()); }
void setSolverConstantsStep(PxReal& error,
PxReal& biasScale,
PxReal& targetVel,
PxReal& maxBias,
PxReal& velMultiplier,
PxReal& rcpResponse,
const Px1DConstraint& c,
PxReal normalVel,
PxReal unitResponse,
PxReal minRowResponse,
PxReal erp,
PxReal dt,
PxReal /*totalDt*/,
PxReal biasClamp,
PxReal recipdt,
PxReal recipTotalDt,
PxReal velTarget)
{
PX_ASSERT(PxIsFinite(unitResponse));
PxReal recipResponse = unitResponse <= minRowResponse ? 0 : 1.0f / unitResponse;
//PX_ASSERT(recipResponse < 1e5f);
PxReal geomError = c.geometricError;
rcpResponse = recipResponse;
if (c.flags & Px1DConstraintFlag::eSPRING)
{
const PxReal a = dt * (dt*c.mods.spring.stiffness + c.mods.spring.damping);
const PxReal aDamp = dt * dt * (c.mods.spring.damping + c.mods.spring.stiffness);
const PxReal b = dt * (c.mods.spring.damping * (c.velocityTarget));// - c.mods.spring.stiffness * geomError);
maxBias = PX_MAX_F32;
PxReal errorTerm;
if (c.flags & Px1DConstraintFlag::eACCELERATION_SPRING)
{
const PxReal x = 1.0f / (1.0f + a);
const PxReal xDamp = 1.0f / (1.0f + aDamp);
targetVel = x * b;
velMultiplier = -x * a;
errorTerm = -x * c.mods.spring.stiffness * dt;
biasScale = errorTerm - xDamp*c.mods.spring.damping*dt;
}
else
{
const PxReal x = 1.0f / (1.0f + a*unitResponse);
const PxReal xDamp = 1.0f / (1.0f + aDamp*unitResponse);
targetVel = x * b*unitResponse;
velMultiplier = -x * a*unitResponse;
errorTerm = -x * c.mods.spring.stiffness * unitResponse * dt;
biasScale = errorTerm - xDamp*c.mods.spring.damping*unitResponse*dt;
}
error = geomError * errorTerm;
}
else
{
velMultiplier = -1.f;
if (c.flags & Px1DConstraintFlag::eRESTITUTION && -normalVel>c.mods.bounce.velocityThreshold)
{
error = 0.f;
biasScale = 0.f;
targetVel = c.mods.bounce.restitution*-normalVel;
maxBias = 0.f;
}
else
{
biasScale = -recipdt*erp;// *recipResponse;
if (c.flags & Px1DConstraintFlag::eDEPRECATED_DRIVE_ROW)
{
error = 0.f;
targetVel = c.velocityTarget - geomError *recipTotalDt;
}
else
{
error = geomError * biasScale;
//KS - if there is a velocity target, then we cannot also have bias otherwise the two compete against each-other.
//Therefore, we set the velocity target
targetVel = c.velocityTarget;// *recipResponse;
}
maxBias = biasClamp;// *recipResponse;
/*PxReal errorBias = PxClamp(geomError*erp*recipdt, -biasClamp, biasClamp);
constant = (c.velocityTarget - errorBias) * recipResponse;*/
}
}
targetVel -= velMultiplier * velTarget;
}
PxU32 setupSolverConstraintStep(
const PxTGSSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
const PxReal dt, const PxReal totalDt, const PxReal invdt, const PxReal invTotalDt,
const PxReal lengthScale, const PxReal biasCoefficient)
{
if (prepDesc.numRows == 0)
{
prepDesc.desc->constraint = NULL;
prepDesc.desc->writeBack = NULL;
prepDesc.desc->constraintLengthOver16 = 0;
return 0;
}
PxSolverConstraintDesc& desc = *prepDesc.desc;
const bool isExtended = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY
|| desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY;
const bool isKinematic0 = desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY &&
desc.tgsBodyA->isKinematic;
const bool isKinematic1 = desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
desc.tgsBodyB->isKinematic;
const PxU32 stride = isExtended ? sizeof(SolverConstraint1DExtStep) : sizeof(SolverConstraint1DStep);
const PxU32 constraintLength = sizeof(SolverConstraint1DHeaderStep) + stride * prepDesc.numRows;
//KS - +16 is for the constraint progress counter, which needs to be the last element in the constraint (so that we
//know SPU DMAs have completed)
PxU8* ptr = allocator.reserveConstraintData(constraintLength + 16u);
if (NULL == ptr || (reinterpret_cast<PxU8*>(-1)) == ptr)
{
if (NULL == ptr)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept joints detaching/exploding or increase buffer size allocated for constraint prep by increasing PxSceneDesc::maxNbContactDataBlocks.");
return 0;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of constraint data. "
"Either accept joints detaching/exploding or simplify constraints.");
ptr = NULL;
return 0;
}
}
desc.constraint = ptr;
//setConstraintLength(desc, constraintLength);
PX_ASSERT((constraintLength & 0xf) == 0);
desc.constraintLengthOver16 = PxTo16(constraintLength / 16);
desc.writeBack = prepDesc.writeback;
PxMemSet(desc.constraint, 0, constraintLength);
SolverConstraint1DHeaderStep* header = reinterpret_cast<SolverConstraint1DHeaderStep*>(desc.constraint);
PxU8* constraints = desc.constraint + sizeof(SolverConstraint1DHeaderStep);
init(*header, PxTo8(prepDesc.numRows), isExtended, prepDesc.invMassScales);
header->body0WorldOffset = prepDesc.body0WorldOffset;
header->linBreakImpulse = prepDesc.linBreakForce * totalDt;
header->angBreakImpulse = prepDesc.angBreakForce * totalDt;
header->breakable = PxU8((prepDesc.linBreakForce != PX_MAX_F32) || (prepDesc.angBreakForce != PX_MAX_F32));
header->invMass0D0 = prepDesc.bodyData0->invMass * prepDesc.invMassScales.linear0;
header->invMass1D1 = prepDesc.bodyData1->invMass * prepDesc.invMassScales.linear1;
header->rAWorld = prepDesc.cA2w - prepDesc.bodyFrame0.p;
header->rBWorld = prepDesc.cB2w - prepDesc.bodyFrame1.p;
/*printf("prepDesc.cA2w.p = (%f, %f, %f), prepDesc.cB2w.p = (%f, %f, %f)\n",
prepDesc.cA2w.x, prepDesc.cA2w.y, prepDesc.cA2w.z,
prepDesc.cB2w.x, prepDesc.cB2w.y, prepDesc.cB2w.z);*/
Px1DConstraint* sorted[MAX_CONSTRAINT_ROWS];
PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS];
PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS];
for (PxU32 i = 0; i < prepDesc.numRows; ++i)
{
if (prepDesc.rows[i].flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT)
{
if (prepDesc.rows[i].solveHint == PxConstraintSolveHint::eEQUALITY)
prepDesc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_EQUALITY;
else if (prepDesc.rows[i].solveHint == PxConstraintSolveHint::eINEQUALITY)
prepDesc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_INEQUALITY;
}
}
preprocessRows(sorted, prepDesc.rows, angSqrtInvInertia0, angSqrtInvInertia1, prepDesc.numRows,
prepDesc.body0TxI->sqrtInvInertia, prepDesc.body1TxI->sqrtInvInertia, prepDesc.bodyData0->invMass, prepDesc.bodyData1->invMass,
prepDesc.invMassScales, isExtended || prepDesc.disablePreprocessing, prepDesc.improvedSlerp);
const PxReal erp = 0.5f * biasCoefficient;
const PxReal recipDt = invdt;
const PxReal angSpeedLimit = invTotalDt*0.75f;
const PxReal linSpeedLimit = isExtended ? invTotalDt*1.5f*lengthScale : invTotalDt*15.f*lengthScale;
PxU32 orthoCount = 0;
PxU32 outCount = 0;
const SolverExtBodyStep eb0(reinterpret_cast<const void*>(prepDesc.body0), prepDesc.body0TxI, prepDesc.bodyData0, desc.linkIndexA);
const SolverExtBodyStep eb1(reinterpret_cast<const void*>(prepDesc.body1), prepDesc.body1TxI, prepDesc.bodyData1, desc.linkIndexB);
PxReal cfm = 0.f;
if (isExtended)
{
cfm = PxMax(eb0.getCFM(), eb1.getCFM());
}
for (PxU32 i = 0; i<prepDesc.numRows; i++)
{
PxPrefetchLine(constraints, 128);
SolverConstraint1DStep &s = *reinterpret_cast<SolverConstraint1DStep *>(constraints);
Px1DConstraint& c = *sorted[i];
PxReal driveScale = c.flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && prepDesc.driveLimitsAreForces ? PxMin(totalDt, 1.0f) : 1.0f;
PxReal unitResponse;
PxReal normalVel = 0.0f;
PxReal vel0, vel1;
if (!isExtended)
{
const PxVec3 angSqrtInvInertia0V3(angSqrtInvInertia0[i].x, angSqrtInvInertia0[i].y, angSqrtInvInertia0[i].z);
const PxVec3 angSqrtInvInertia1V3(angSqrtInvInertia1[i].x, angSqrtInvInertia1[i].y, angSqrtInvInertia1[i].z);
init(s, c.linear0, c.linear1, c.angular0, c.angular1, c.minImpulse * driveScale, c.maxImpulse * driveScale);
/*unitResponse = prepDesc.body0->getResponse(c.linear0, c.angular0, s.ang0, prepDesc.mInvMassScales.linear0, prepDesc.mInvMassScales.angular0)
+ prepDesc.body1->getResponse(-c.linear1, -c.angular1, s.ang1, prepDesc.mInvMassScales.linear1, prepDesc.mInvMassScales.angular1);*/
const PxReal linSumMass = s.lin0.magnitudeSquared() * prepDesc.bodyData0->invMass * prepDesc.invMassScales.linear0 + s.lin1.magnitudeSquared() * prepDesc.bodyData1->invMass * prepDesc.invMassScales.linear1;
PxReal resp0 = angSqrtInvInertia0V3.magnitudeSquared() * prepDesc.invMassScales.angular0;
PxReal resp1 = angSqrtInvInertia1V3.magnitudeSquared() * prepDesc.invMassScales.angular1;
unitResponse = resp0 + resp1 + linSumMass;
//s.recipResponseOrLinearSumMass = linSumMass;
vel0 = prepDesc.bodyData0->projectVelocity(s.lin0, s.ang0);
vel1 = prepDesc.bodyData1->projectVelocity(s.lin1, s.ang1);
normalVel = vel0 - vel1;
//if (c.solveHint & PxConstraintSolveHint::eEQUALITY)
if(!(c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT))
{
s.ang0 = PxVec3(0.f);
s.ang1 = PxVec3(0.f);
s.angularErrorScale = 0.f;
}
}
else
{
const Cm::SpatialVector resp0 = createImpulseResponseVector(c.linear0, c.angular0, eb0);
const Cm::SpatialVector resp1 = createImpulseResponseVector(-c.linear1, -c.angular1, eb1);
init(s, resp0.linear, -resp1.linear, resp0.angular, -resp1.angular, c.minImpulse * driveScale, c.maxImpulse * driveScale);
SolverConstraint1DExtStep& e = static_cast<SolverConstraint1DExtStep&>(s);
Cm::SpatialVector& delta0 = unsimdRef(e.deltaVA);
Cm::SpatialVector& delta1 = unsimdRef(e.deltaVB);
unitResponse = getImpulseResponse(eb0, resp0, delta0, prepDesc.invMassScales.linear0, prepDesc.invMassScales.angular0,
eb1, resp1, delta1, prepDesc.invMassScales.linear1, prepDesc.invMassScales.angular1, false);
//PxReal totalVelChange = (delta0 - delta1).magnitude();
//PX_UNUSED(totalVelChange);
if (unitResponse < DY_ARTICULATION_MIN_RESPONSE)
{
continue;
}
else
unitResponse += cfm;
{
vel0 = eb0.projectVelocity(s.lin0, s.ang0);
vel1 = eb1.projectVelocity(s.lin1, s.ang1);
normalVel = vel0 - vel1;
}
if (!(c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT))
{
s.angularErrorScale = 0.f;
}
}
PxReal recipResponse = 0.f;
PxReal velTarget = 0.f;
if (isKinematic0)
velTarget -= vel0;
if (isKinematic1)
velTarget += vel1;
setSolverConstantsStep(s.error, s.biasScale, s.velTarget, s.maxBias, s.velMultiplier, recipResponse, c,
normalVel, unitResponse, prepDesc.minResponseThreshold, erp, dt, totalDt,
c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT ? angSpeedLimit : linSpeedLimit, recipDt, invTotalDt,
velTarget);
s.recipResponse = recipResponse;
if (c.flags & Px1DConstraintFlag::eOUTPUT_FORCE)
s.flags |= DY_SC_FLAG_OUTPUT_FORCE;
if ((c.flags & Px1DConstraintFlag::eKEEPBIAS))
s.flags |= DY_SC_FLAG_KEEP_BIAS;
if (c.solveHint & 1)
s.flags |= DY_SC_FLAG_INEQUALITY;
if (!(isExtended || prepDesc.disablePreprocessing))
{
//KS - the code that orthogonalizes constraints on-the-fly only works if the linear and angular constraints have already been pre-orthogonalized
if (c.solveHint == PxConstraintSolveHint::eROTATIONAL_EQUALITY)
{
s.flags |= DY_SC_FLAG_ROT_EQ;
PX_ASSERT(orthoCount < 3);
/*angOrtho0[orthoCount] = PxVec3(angSqrtInvInertia0[i].x, angSqrtInvInertia0[i].y, angSqrtInvInertia0[i].z);
angOrtho1[orthoCount] = PxVec3(angSqrtInvInertia1[i].x, angSqrtInvInertia1[i].y, angSqrtInvInertia1[i].z);
recipResponses[orthoCount] = recipResponse;*/
header->angOrthoAxis0_recipResponseW[orthoCount] =
PxVec4(angSqrtInvInertia0[i].x*prepDesc.invMassScales.angular0, angSqrtInvInertia0[i].y*prepDesc.invMassScales.angular0, angSqrtInvInertia0[i].z*prepDesc.invMassScales.angular0, recipResponse);
header->angOrthoAxis1_Error[orthoCount].x = angSqrtInvInertia1[i].x*prepDesc.invMassScales.angular1;
header->angOrthoAxis1_Error[orthoCount].y = angSqrtInvInertia1[i].y*prepDesc.invMassScales.angular1;
header->angOrthoAxis1_Error[orthoCount].z = angSqrtInvInertia1[i].z*prepDesc.invMassScales.angular1;
header->angOrthoAxis1_Error[orthoCount].w = c.geometricError;
orthoCount++;
}
else if (c.solveHint & PxConstraintSolveHint::eEQUALITY)
s.flags |= DY_SC_FLAG_ORTHO_TARGET;
}
constraints += stride;
outCount++;
}
//KS - we now need to re-set count because we may have skipped degenerate rows when solving articulation constraints.
//In this case, the degenerate rows would have produced no force. Skipping them is just an optimization
header->count = PxU8(outCount);
return prepDesc.numRows;
}
PxU32 SetupSolverConstraintStep(SolverConstraintShaderPrepDesc& shaderDesc,
PxTGSSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
const PxReal dt, const PxReal totalDt, const PxReal invdt, const PxReal invTotalDt,
const PxReal lengthScale, const PxReal biasCoefficient)
{
// LL shouldn't see broken constraints
PX_ASSERT(!(reinterpret_cast<ConstraintWriteback*>(prepDesc.writeback)->broken));
prepDesc.desc->constraintLengthOver16 = 0;
//setConstraintLength(*prepDesc.desc, 0);
if (!shaderDesc.solverPrep)
return 0;
//PxU32 numAxisConstraints = 0;
Px1DConstraint rows[MAX_CONSTRAINT_ROWS];
setupConstraintRows(rows, MAX_CONSTRAINT_ROWS);
prepDesc.invMassScales.linear0 = prepDesc.invMassScales.linear1 = prepDesc.invMassScales.angular0 = prepDesc.invMassScales.angular1 = 1.f;
prepDesc.body0WorldOffset = PxVec3(0.0f);
//TAG:solverprepcall
prepDesc.numRows = prepDesc.disableConstraint ? 0 : (*shaderDesc.solverPrep)(rows,
prepDesc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
prepDesc.invMassScales,
shaderDesc.constantBlock,
prepDesc.bodyFrame0, prepDesc.bodyFrame1,
prepDesc.extendedLimits, prepDesc.cA2w, prepDesc.cB2w);
prepDesc.rows = rows;
if (prepDesc.bodyState0 != PxSolverContactDesc::eARTICULATION && prepDesc.body0->isKinematic)
prepDesc.invMassScales.angular0 = 0.f;
if (prepDesc.bodyState1 != PxSolverContactDesc::eARTICULATION && prepDesc.body1->isKinematic)
prepDesc.invMassScales.angular1 = 0.f;
return setupSolverConstraintStep(prepDesc, allocator, dt, totalDt, invdt, invTotalDt, lengthScale, biasCoefficient);
}
void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
const Vec3V& linMotion0, const Vec3V& linMotion1, const Vec3V& angMotion0, const Vec3V& angMotion1,
const QuatV& rotA, const QuatV& rotB, const PxReal elapsedTimeF32, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0,
Vec3V& angImpulse1)
{
PxU8* PX_RESTRICT bPtr = desc.constraint;
const SolverConstraint1DHeaderStep* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep*>(bPtr);
SolverConstraint1DExtStep* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DExtStep*>(bPtr + sizeof(SolverConstraint1DHeaderStep));
const FloatV elapsedTime = FLoad(elapsedTimeF32);
const Vec3V raPrev = V3LoadA(header->rAWorld);
const Vec3V rbPrev = V3LoadA(header->rBWorld);
const Vec3V ra = QuatRotate(rotA, V3LoadA(header->rAWorld));
const Vec3V rb = QuatRotate(rotB, V3LoadA(header->rBWorld));
const Vec3V raMotion = V3Sub(V3Add(ra, linMotion0), raPrev);
const Vec3V rbMotion = V3Sub(V3Add(rb, linMotion1), rbPrev);
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; ++i, base++)
{
PxPrefetchLine(base + 1);
SolverConstraint1DExtStep& c = *base;
const Vec3V clinVel0 = V3LoadA(c.lin0);
const Vec3V clinVel1 = V3LoadA(c.lin1);
const Vec3V cangVel0 = V3LoadA(c.ang0);
const Vec3V cangVel1 = V3LoadA(c.ang1);
const FloatV recipResponse = FLoad(c.recipResponse);
const FloatV targetVel = FLoad(c.velTarget);
const FloatV deltaAng = FMul(FSub(V3Dot(cangVel0, angMotion0), V3Dot(cangVel1, angMotion1)), FLoad(c.angularErrorScale));
const FloatV errorChange = FNegScaleSub(targetVel, elapsedTime, FAdd(FSub(V3Dot(raMotion, clinVel0), V3Dot(rbMotion, clinVel1)), deltaAng));
const FloatV biasScale = FLoad(c.biasScale);
const FloatV maxBias = FLoad(c.maxBias);
const FloatV vMul = FMul(recipResponse, FLoad(c.velMultiplier));
const FloatV appliedForce = FLoad(c.appliedForce);
const FloatV unclampedBias = FScaleAdd(errorChange, biasScale, FLoad(c.error));
const FloatV minBias = c.flags & DY_SC_FLAG_INEQUALITY ? FNeg(FMax()) : FNeg(maxBias);
const FloatV bias = FClamp(unclampedBias, minBias, maxBias);
const FloatV constant = FMul(recipResponse, FAdd(bias, targetVel));
const FloatV maxImpulse = FLoad(c.maxImpulse);
const FloatV minImpulse = FLoad(c.minImpulse);
const Vec3V v0 = V3MulAdd(linVel0, clinVel0, V3Mul(angVel0, cangVel0));
const Vec3V v1 = V3MulAdd(linVel1, clinVel1, V3Mul(angVel1, cangVel1));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV unclampedForce = FAdd(appliedForce, FScaleAdd(vMul, normalVel, constant));
const FloatV clampedForce = FMin(maxImpulse, (FMax(minImpulse, unclampedForce)));
const FloatV deltaF = FSub(clampedForce, appliedForce);
FStore(clampedForce, &c.appliedForce);
//PX_ASSERT(FAllGrtr(FLoad(1000.f), FAbs(deltaF)));
FStore(clampedForce, &base->appliedForce);
li0 = V3ScaleAdd(clinVel0, deltaF, li0); ai0 = V3ScaleAdd(cangVel0, deltaF, ai0);
li1 = V3ScaleAdd(clinVel1, deltaF, li1); ai1 = V3ScaleAdd(cangVel1, deltaF, ai1);
linVel0 = V3ScaleAdd(base->deltaVA.linear, deltaF, linVel0); angVel0 = V3ScaleAdd(base->deltaVA.angular, deltaF, angVel0);
linVel1 = V3ScaleAdd(base->deltaVB.linear, deltaF, linVel1); angVel1 = V3ScaleAdd(base->deltaVB.angular, deltaF, angVel1);
/*PX_ASSERT(FAllGrtr(FLoad(40.f * 40.f), V3Dot(linVel0, linVel0)));
PX_ASSERT(FAllGrtr(FLoad(40.f * 40.f), V3Dot(linVel1, linVel1)));
PX_ASSERT(FAllGrtr(FLoad(20.f * 20.f), V3Dot(angVel0, angVel0)));
PX_ASSERT(FAllGrtr(FLoad(20.f * 20.f), V3Dot(angVel1, angVel1)));*/
}
linImpulse0 = V3Scale(li0, FLoad(header->linearInvMassScale0));
linImpulse1 = V3Scale(li1, FLoad(header->linearInvMassScale1));
angImpulse0 = V3Scale(ai0, FLoad(header->angularInvMassScale0));
angImpulse1 = V3Scale(ai1, FLoad(header->angularInvMassScale1));
}
//Port of scalar implementation to SIMD maths with some interleaving of instructions
void solveExt1DStep(const PxSolverConstraintDesc& desc, const PxReal elapsedTimeF32, SolverContext& cache,
const PxTGSSolverBodyTxInertia* const txInertias)
{
Vec3V linVel0, angVel0, linVel1, angVel1;
Vec3V linMotion0, angMotion0, linMotion1, angMotion1;
QuatV rotA, rotB;
Dy::FeatherstoneArticulation* artA = getArticulationA(desc);
Dy::FeatherstoneArticulation* artB = getArticulationB(desc);
if (artA == artB)
{
Cm::SpatialVectorV v0, v1;
artA->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1);
linVel0 = v0.linear;
angVel0 = v0.angular;
linVel1 = v1.linear;
angVel1 = v1.angular;
const Cm::SpatialVectorV motionV0 = artA->getLinkMotionVector(desc.linkIndexA); //PxcFsGetMotionVector(*artA, desc.linkIndexA);
const Cm::SpatialVectorV motionV1 = artB->getLinkMotionVector(desc.linkIndexB); //PxcFsGetMotionVector(*artB, desc.linkIndexB);
linMotion0 = motionV0.linear;
angMotion0 = motionV0.angular;
linMotion1 = motionV1.linear;
angMotion1 = motionV1.angular;
rotA = aos::QuatVLoadU(&artA->getDeltaQ(desc.linkIndexA).x);
rotB = aos::QuatVLoadU(&artB->getDeltaQ(desc.linkIndexB).x);
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = V3LoadA(desc.tgsBodyA->linearVelocity);
angVel0 = V3LoadA(desc.tgsBodyA->angularVelocity);
linMotion0 = V3LoadA(desc.tgsBodyA->deltaLinDt);
angMotion0 = V3LoadA(desc.tgsBodyA->deltaAngDt);
rotA = aos::QuatVLoadA(&txInertias[desc.bodyADataIndex].deltaBody2World.q.x);
}
else
{
const Cm::SpatialVectorV v = artA->pxcFsGetVelocity(desc.linkIndexA);
rotA = aos::QuatVLoadU(&artA->getDeltaQ(desc.linkIndexA).x);
const Cm::SpatialVectorV motionV = artA->getLinkMotionVector(desc.linkIndexA);//PxcFsGetMotionVector(*artA, desc.linkIndexA);
linVel0 = v.linear;
angVel0 = v.angular;
linMotion0 = motionV.linear;
angMotion0 = motionV.angular;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
linVel1 = V3LoadA(desc.tgsBodyB->linearVelocity);
angVel1 = V3LoadA(desc.tgsBodyB->angularVelocity);
linMotion1 = V3LoadA(desc.tgsBodyB->deltaLinDt);
angMotion1 = V3LoadA(desc.tgsBodyB->deltaAngDt);
rotB = aos::QuatVLoadA(&txInertias[desc.bodyBDataIndex].deltaBody2World.q.x);
}
else
{
Cm::SpatialVectorV v = artB->pxcFsGetVelocity(desc.linkIndexB);
rotB = aos::QuatVLoadU(&artB->getDeltaQ(desc.linkIndexB).x);
Cm::SpatialVectorV motionV = artB->getLinkMotionVector(desc.linkIndexB);// PxcFsGetMotionVector(*artB, desc.linkIndexB);
linVel1 = v.linear;
angVel1 = v.angular;
linMotion1 = motionV.linear;
angMotion1 = motionV.angular;
}
}
Vec3V li0, li1, ai0, ai1;
solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, linMotion0, linMotion1, angMotion0, angMotion1, rotA, rotB, elapsedTimeF32, li0, li1, ai0, ai1);
if (artA == artB)
{
artA->pxcFsApplyImpulses(desc.linkIndexA, li0,
ai0, desc.linkIndexB, li1,
ai1, cache.Z, cache.deltaV);
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel0, desc.tgsBodyA->linearVelocity);
V3StoreA(angVel0, desc.tgsBodyA->angularVelocity);
}
else
{
artA->pxcFsApplyImpulse(desc.linkIndexA, li0, ai0, cache.Z, cache.deltaV);
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel1, desc.tgsBodyB->linearVelocity);
V3StoreA(angVel1, desc.tgsBodyB->angularVelocity);
}
else
{
artB->pxcFsApplyImpulse(desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV);
}
}
}
//Port of scalar implementation to SIMD maths with some interleaving of instructions
void solve1DStep(const PxSolverConstraintDesc& desc, const PxTGSSolverBodyTxInertia* const txInertias, const PxReal elapsedTime)
{
PxU8* PX_RESTRICT bPtr = desc.constraint;
if (bPtr == NULL)
return;
PxTGSSolverBodyVel& b0 = *desc.tgsBodyA;
PxTGSSolverBodyVel& b1 = *desc.tgsBodyB;
const FloatV elapsed = FLoad(elapsedTime);
const PxTGSSolverBodyTxInertia& txI0 = txInertias[desc.bodyADataIndex];
const PxTGSSolverBodyTxInertia& txI1 = txInertias[desc.bodyBDataIndex];
const SolverConstraint1DHeaderStep* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep*>(bPtr);
SolverConstraint1DStep* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DStep*>(bPtr + sizeof(SolverConstraint1DHeaderStep));
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V linVel1 = V3LoadA(b1.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularVelocity);
Vec3V angState1 = V3LoadA(b1.angularVelocity);
Mat33V sqrtInvInertia0 = Mat33V(V3LoadU(txI0.sqrtInvInertia.column0), V3LoadU(txI0.sqrtInvInertia.column1), V3LoadU(txI0.sqrtInvInertia.column2));
Mat33V sqrtInvInertia1 = Mat33V(V3LoadU(txI1.sqrtInvInertia.column0), V3LoadU(txI1.sqrtInvInertia.column1), V3LoadU(txI1.sqrtInvInertia.column2));
const FloatV invMass0 = FLoad(header->invMass0D0);
const FloatV invMass1 = FLoad(header->invMass1D1);
const FloatV invInertiaScale0 = FLoad(header->angularInvMassScale0);
const FloatV invInertiaScale1 = FLoad(header->angularInvMassScale1);
const QuatV deltaRotA = aos::QuatVLoadA(&txI0.deltaBody2World.q.x);
const QuatV deltaRotB = aos::QuatVLoadA(&txI1.deltaBody2World.q.x);
const Vec3V raPrev = V3LoadA(header->rAWorld);
const Vec3V rbPrev = V3LoadA(header->rBWorld);
const Vec3V ra = QuatRotate(deltaRotA, raPrev);
const Vec3V rb = QuatRotate(deltaRotB, rbPrev);
const Vec3V ang0 = V3LoadA(b0.deltaAngDt);
const Vec3V ang1 = V3LoadA(b1.deltaAngDt);
const Vec3V lin0 = V3LoadA(b0.deltaLinDt);
const Vec3V lin1 = V3LoadA(b1.deltaLinDt);
const Vec3V raMotion = V3Sub(V3Add(ra, lin0), raPrev);
const Vec3V rbMotion = V3Sub(V3Add(rb, lin1), rbPrev);
const VecCrossV raCross = V3PrepareCross(ra);
const VecCrossV rbCross = V3PrepareCross(rb);
const Vec4V ang0Ortho0_recipResponseW = V4LoadA(&header->angOrthoAxis0_recipResponseW[0].x);
const Vec4V ang0Ortho1_recipResponseW = V4LoadA(&header->angOrthoAxis0_recipResponseW[1].x);
const Vec4V ang0Ortho2_recipResponseW = V4LoadA(&header->angOrthoAxis0_recipResponseW[2].x);
const Vec4V ang1Ortho0_Error0 = V4LoadA(&header->angOrthoAxis1_Error[0].x);
const Vec4V ang1Ortho1_Error1 = V4LoadA(&header->angOrthoAxis1_Error[1].x);
const Vec4V ang1Ortho2_Error2 = V4LoadA(&header->angOrthoAxis1_Error[2].x);
const FloatV recipResponse0 = V4GetW(ang0Ortho0_recipResponseW);
const FloatV recipResponse1 = V4GetW(ang0Ortho1_recipResponseW);
const FloatV recipResponse2 = V4GetW(ang0Ortho2_recipResponseW);
const Vec3V ang0Ortho0 = Vec3V_From_Vec4V(ang0Ortho0_recipResponseW);
const Vec3V ang0Ortho1 = Vec3V_From_Vec4V(ang0Ortho1_recipResponseW);
const Vec3V ang0Ortho2 = Vec3V_From_Vec4V(ang0Ortho2_recipResponseW);
const Vec3V ang1Ortho0 = Vec3V_From_Vec4V(ang1Ortho0_Error0);
const Vec3V ang1Ortho1 = Vec3V_From_Vec4V(ang1Ortho1_Error1);
const Vec3V ang1Ortho2 = Vec3V_From_Vec4V(ang1Ortho2_Error2);
FloatV error0 = FAdd(V4GetW(ang1Ortho0_Error0), FSub(V3Dot(ang0Ortho0, ang0), V3Dot(ang1Ortho0, ang1)));
FloatV error1 = FAdd(V4GetW(ang1Ortho1_Error1), FSub(V3Dot(ang0Ortho1, ang0), V3Dot(ang1Ortho1, ang1)));
FloatV error2 = FAdd(V4GetW(ang1Ortho2_Error2), FSub(V3Dot(ang0Ortho2, ang0), V3Dot(ang1Ortho2, ang1)));
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; ++i, base++)
{
PxPrefetchLine(base + 1);
SolverConstraint1DStep& c = *base;
const Vec3V clinVel0 = V3LoadA(c.lin0);
const Vec3V clinVel1 = V3LoadA(c.lin1);
const Vec3V cangVel0_ = V3LoadA(c.ang0);
const Vec3V cangVel1_ = V3LoadA(c.ang1);
const FloatV angularErrorScale = FLoad(c.angularErrorScale);
const FloatV biasScale = FLoad(c.biasScale);
const FloatV maxBias = FLoad(c.maxBias);
const FloatV targetVel = FLoad(c.velTarget);
const FloatV appliedForce = FLoad(c.appliedForce);
const FloatV velMultiplier = FLoad(c.velMultiplier);
const FloatV maxImpulse = FLoad(c.maxImpulse);
const FloatV minImpulse = FLoad(c.minImpulse);
Vec3V cangVel0 = V3Add(cangVel0_, V3Cross(raCross, clinVel0));
Vec3V cangVel1 = V3Add(cangVel1_, V3Cross(rbCross, clinVel1));
FloatV error = FLoad(c.error);
const FloatV minBias = (c.flags & DY_SC_FLAG_INEQUALITY) ? FNeg(FMax()) : FNeg(maxBias);
Vec3V raXnI = M33MulV3(sqrtInvInertia0, cangVel0);
Vec3V rbXnI = M33MulV3(sqrtInvInertia1, cangVel1);
if (c.flags & DY_SC_FLAG_ORTHO_TARGET)
{
//Re-orthogonalize the constraints before velocity projection and impulse response calculation
//Can be done in using instruction parallelism because angular locked axes are orthogonal to linear axes!
const FloatV proj0 = FMul(V3SumElems(V3MulAdd(raXnI, ang0Ortho0,
V3Mul(rbXnI, ang1Ortho0))), recipResponse0);
const FloatV proj1 = FMul(V3SumElems(V3MulAdd(raXnI, ang0Ortho1,
V3Mul(rbXnI, ang1Ortho1))), recipResponse1);
const FloatV proj2 = FMul(V3SumElems(V3MulAdd(raXnI, ang0Ortho2,
V3Mul(rbXnI, ang1Ortho2))), recipResponse2);
const Vec3V delta0 = V3ScaleAdd(ang0Ortho0, proj0, V3ScaleAdd(ang0Ortho1, proj1, V3Scale(ang0Ortho2, proj2)));
const Vec3V delta1 = V3ScaleAdd(ang1Ortho0, proj0, V3ScaleAdd(ang1Ortho1, proj1, V3Scale(ang1Ortho2, proj2)));
raXnI = V3Sub(raXnI, delta0);
rbXnI = V3Sub(rbXnI, delta1);
error = FSub(error, FScaleAdd(error0, proj0, FScaleAdd(error1, proj1, FMul(error2, proj2))));
}
const FloatV deltaAng = FMul(angularErrorScale, FSub(V3Dot(raXnI, ang0), V3Dot(rbXnI, ang1)));
FloatV errorChange = FNegScaleSub(targetVel, elapsed, FAdd(FSub(V3Dot(raMotion, clinVel0), V3Dot(rbMotion, clinVel1)), deltaAng));
const FloatV resp0 = FScaleAdd(invMass0, V3Dot(clinVel0, clinVel0), V3SumElems(V3Mul(V3Scale(raXnI, invInertiaScale0), raXnI)));
const FloatV resp1 = FSub(FMul(invMass1, V3Dot(clinVel1, clinVel1)), V3SumElems(V3Mul(V3Scale(rbXnI, invInertiaScale1), rbXnI)));
const FloatV response = FAdd(resp0, resp1);
const FloatV recipResponse = FSel(FIsGrtr(response, FZero()), FRecip(response), FZero());
const FloatV vMul = FMul(recipResponse, velMultiplier);
const FloatV unclampedBias = FScaleAdd(errorChange, biasScale, error);
const FloatV bias = FClamp(unclampedBias, minBias, maxBias);
const FloatV constant = FMul(recipResponse, FAdd(bias, targetVel));
const Vec3V v0 = V3MulAdd(linVel0, clinVel0, V3Mul(angState0, raXnI));
const Vec3V v1 = V3MulAdd(linVel1, clinVel1, V3Mul(angState1, rbXnI));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV unclampedForce = FAdd(appliedForce, FScaleAdd(vMul, normalVel, constant));
const FloatV clampedForce = FClamp(unclampedForce, minImpulse, maxImpulse);
const FloatV deltaF = FSub(clampedForce, appliedForce);
FStore(clampedForce, &c.appliedForce);
linVel0 = V3ScaleAdd(clinVel0, FMul(deltaF, invMass0), linVel0);
linVel1 = V3NegScaleSub(clinVel1, FMul(deltaF, invMass1), linVel1);
angState0 = V3ScaleAdd(raXnI, FMul(deltaF, invInertiaScale0), angState0);
angState1 = V3ScaleAdd(rbXnI, FMul(deltaF, invInertiaScale1), angState1);
}
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(angState0, b0.angularVelocity);
V3StoreA(linVel1, b1.linearVelocity);
V3StoreA(angState1, b1.angularVelocity);
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularVelocity.isFinite());
PX_ASSERT(b1.linearVelocity.isFinite());
PX_ASSERT(b1.angularVelocity.isFinite());
}
//Port of scalar implementation to SIMD maths with some interleaving of instructions
void conclude1DStep(const PxSolverConstraintDesc& desc)
{
PxU8* PX_RESTRICT bPtr = desc.constraint;
if (bPtr == NULL)
return;
const SolverConstraint1DHeaderStep* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep*>(bPtr);
PxU8* PX_RESTRICT base = bPtr + sizeof(SolverConstraint1DHeaderStep);
const PxU32 stride = header->type == DY_SC_TYPE_RB_1D ? sizeof(SolverConstraint1DStep) : sizeof(SolverConstraint1DExtStep);
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; ++i, base+=stride)
{
SolverConstraint1DStep& c = *reinterpret_cast<SolverConstraint1DStep*>(base);
PxPrefetchLine(&c + 1);
if (!(c.flags & DY_SC_FLAG_KEEP_BIAS))
{
c.biasScale = 0.f;
c.error = 0.f;
}
}
}
void concludeContact(const PxSolverConstraintDesc& desc)
{
PX_UNUSED(desc);
//const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc);
////hopefully pointer aliasing doesn't bite.
//PxU8* PX_RESTRICT currPtr = desc.constraint;
//SolverContactHeaderStep* PX_RESTRICT firstHdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr);
//bool isExtended = firstHdr->type == DY_SC_TYPE_EXT_CONTACT;
//const PxU32 contactStride = isExtended ? sizeof(SolverContactPointStepExt) : sizeof(SolverContactPointStep);
//const PxU32 frictionStride = isExtended ? sizeof(SolverContactFrictionStepExt) : sizeof(SolverContactFrictionStep);
//while (currPtr < last)
//{
// SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr);
// currPtr += sizeof(SolverContactHeaderStep);
// const PxU32 numNormalConstr = hdr->numNormalConstr;
// const PxU32 numFrictionConstr = hdr->numFrictionConstr;
// /*PxU8* PX_RESTRICT contacts = currPtr;
// prefetchLine(contacts);*/
// currPtr += numNormalConstr * contactStride;
// //PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr);
// currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
// PxU8* PX_RESTRICT frictions = currPtr;
// currPtr += numFrictionConstr * frictionStride;
// /*for (PxU32 i = 0; i < numNormalConstr; ++i)
// {
// SolverContactPointStep& c = *reinterpret_cast<SolverContactPointStep*>(contacts);
// contacts += contactStride;
// if(c.separation <= 0.f)
// c.biasCoefficient = 0.f;
// }*/
// for (PxU32 i = 0; i < numFrictionConstr; ++i)
// {
// SolverContactFrictionStep& f = *reinterpret_cast<SolverContactFrictionStep*>(frictions);
// frictions += frictionStride;
// f.biasScale = 0.f;
// }
//}
//PX_ASSERT(currPtr == last);
}
void writeBack1D(const PxSolverConstraintDesc& desc)
{
ConstraintWriteback* writeback = reinterpret_cast<ConstraintWriteback*>(desc.writeBack);
if (writeback)
{
SolverConstraint1DHeaderStep* header = reinterpret_cast<SolverConstraint1DHeaderStep*>(desc.constraint);
PxU8* base = desc.constraint + sizeof(SolverConstraint1DHeaderStep);
const PxU32 stride = header->type == DY_SC_TYPE_EXT_1D ? sizeof(SolverConstraint1DExtStep) : sizeof(SolverConstraint1DStep);
PxVec3 lin(0), ang(0);
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; i++)
{
const SolverConstraint1DStep* c = reinterpret_cast<SolverConstraint1DStep*>(base);
if (c->flags & DY_SC_FLAG_OUTPUT_FORCE)
{
lin += c->lin0 * c->appliedForce;
ang += (c->ang0 + c->lin0.cross(header->rAWorld)) * c->appliedForce;
}
base += stride;
}
ang -= header->body0WorldOffset.cross(lin);
writeback->linearImpulse = lin;
writeback->angularImpulse = ang;
writeback->broken = header->breakable ? PxU32(lin.magnitude()>header->linBreakImpulse || ang.magnitude()>header->angBreakImpulse) : 0;
//KS - the amount of memory we allocated may now be significantly larger than the number of constraint rows. This is because
//we discard degenerate rows in the articulation constraint prep code.
//PX_ASSERT(desc.constraint + (desc.constraintLengthOver16 * 16) == base);
}
}
static FloatV solveExtContactsStep(SolverContactPointStepExt* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
Vec3V& linVel0, Vec3V& angVel0,
Vec3V& linVel1, Vec3V& angVel1,
Vec3V& li0, Vec3V& ai0,
Vec3V& li1, Vec3V& ai1,
const Vec3V& linDeltaA, const Vec3V& linDeltaB, const Vec3V& angDeltaA, const Vec3V angDeltaB, const FloatV& maxPenBias,
PxF32* PX_RESTRICT appliedForceBuffer,
const FloatV& minPen,
const FloatV& elapsedTime)
{
const FloatV deltaV = V3Dot(contactNormal, V3Sub(linDeltaA, linDeltaB));
FloatV accumulatedNormalImpulse = FZero();
for (PxU32 i = 0; i<nbContactPoints; i++)
{
SolverContactPointStepExt& c = contacts[i];
PxPrefetchLine(&contacts[i + 1]);
const Vec3V raXn = V3LoadA(c.raXnI);
const Vec3V rbXn = V3LoadA(c.rbXnI);
const FloatV appliedForce = FLoad(appliedForceBuffer[i]);
const FloatV velMultiplier = FLoad(c.velMultiplier);
const FloatV recipResponse = FLoad(c.recipResponse);
//Component of relative velocity at contact point that is along the contact normal.
//n.[(va + wa X ra) - (vb + wb X rb)]
Vec3V v = V3MulAdd(linVel0, contactNormal, V3Mul(angVel0, raXn));
v = V3Sub(v, V3MulAdd(linVel1, contactNormal, V3Mul(angVel1, rbXn)));
const FloatV normalVel = V3SumElems(v);
const FloatV angDelta0 = V3Dot(angDeltaA, raXn);
const FloatV angDelta1 = V3Dot(angDeltaB, rbXn);
const FloatV deltaAng = FSub(angDelta0, angDelta1);
const FloatV targetVel = FLoad(c.targetVelocity);
const FloatV deltaBias = FSub(FAdd(deltaV, deltaAng), FMul(targetVel, elapsedTime));
//const FloatV deltaBias = FAdd(deltaV, deltaAng);
const FloatV biasCoefficient = FLoad(c.biasCoefficient);
FloatV sep = FMax(minPen, FAdd(FLoad(c.separation), deltaBias));
const FloatV bias = FMin(FNeg(maxPenBias), FMul(biasCoefficient, sep));
const FloatV tVelBias = FMul(bias, recipResponse);
const FloatV _deltaF = FMax(FSub(tVelBias, FMul(FSub(normalVel, targetVel), velMultiplier)), FNeg(appliedForce));
const FloatV _newForce = FAdd(appliedForce, _deltaF);
const FloatV newForce = FMin(_newForce, FLoad(c.maxImpulse));
const FloatV deltaF = FSub(newForce, appliedForce);
const Vec3V raXnI = c.angDeltaVA;
const Vec3V rbXnI = c.angDeltaVB;
linVel0 = V3ScaleAdd(c.linDeltaVA, deltaF, linVel0);
angVel0 = V3ScaleAdd(raXnI, deltaF, angVel0);
linVel1 = V3ScaleAdd(c.linDeltaVB, deltaF, linVel1);
angVel1 = V3ScaleAdd(rbXnI, deltaF, angVel1);
li0 = V3ScaleAdd(contactNormal, deltaF, li0); ai0 = V3ScaleAdd(raXn, deltaF, ai0);
li1 = V3ScaleAdd(contactNormal, deltaF, li1); ai1 = V3ScaleAdd(rbXn, deltaF, ai1);
const FloatV newAppliedForce = FAdd(appliedForce, deltaF);
FStore(newAppliedForce, &appliedForceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newAppliedForce);
}
return accumulatedNormalImpulse;
}
void solveExtContactStep(
const PxSolverConstraintDesc& desc,
Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
Vec3V& linDelta0, Vec3V& linDelta1, Vec3V& angDelta0, Vec3V& angDelta1,
Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1,
bool /*doFriction*/, const PxReal minPenetration, const PxReal elapsedTimeF32)
{
const FloatV elapsedTime = FLoad(elapsedTimeF32);
const FloatV minPen = FLoad(minPenetration);
const FloatV zero = FZero();
const PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16 * 16;
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
const Vec3V relMotion = V3Sub(linDelta0, linDelta1);
while (currPtr < last)
{
SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr);
currPtr += sizeof(SolverContactHeaderStep);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverContactPointStepExt* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStepExt*>(currPtr);
PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPointStepExt);
PxF32* appliedForceBuffer = reinterpret_cast<PxF32*>(currPtr);
currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
SolverContactFrictionStepExt* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStepExt*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionStepExt);
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
const Vec3V contactNormal = V3LoadA(hdr->normal);
const FloatV accumulatedNormalImpulse = FMax(solveExtContactsStep(
contacts, numNormalConstr, contactNormal,
linVel0, angVel0, linVel1, angVel1,
li0, ai0, li1, ai1,
linDelta0, linDelta1, angDelta0, angDelta1,
FLoad(hdr->maxPenBias), appliedForceBuffer, minPen, elapsedTime),
FLoad(hdr->minNormalForce));
if (numFrictionConstr)
{
PxPrefetchLine(frictions);
const FloatV maxFrictionImpulse = FMul(hdr->getStaticFriction(), accumulatedNormalImpulse);
const FloatV maxDynFrictionImpulse = FMul(hdr->getDynamicFriction(), accumulatedNormalImpulse);
BoolV broken = BFFFF();
const PxU32 numFrictionPairs = numFrictionConstr &6;
for (PxU32 i = 0; i<numFrictionPairs; i += 2)
{
SolverContactFrictionStepExt& f0 = frictions[i];
SolverContactFrictionStepExt& f1 = frictions[i+1];
PxPrefetchLine(&frictions[i + 2]);
const Vec4V normalXYZ_ErrorW0 = f0.normalXYZ_ErrorW;
const Vec4V raXn_targetVelW0 = f0.raXnI_targetVelW;
const Vec4V rbXn_velMultiplierW0 = f0.rbXnI_velMultiplierW;
const Vec4V normalXYZ_ErrorW1 = f1.normalXYZ_ErrorW;
const Vec4V raXn_targetVelW1 = f1.raXnI_targetVelW;
const Vec4V rbXn_velMultiplierW1 = f1.rbXnI_velMultiplierW;
const Vec3V normal0 = Vec3V_From_Vec4V(normalXYZ_ErrorW0);
const Vec3V raXn0 = Vec3V_From_Vec4V(raXn_targetVelW0);
const Vec3V rbXn0 = Vec3V_From_Vec4V(rbXn_velMultiplierW0);
const Vec3V raXnI0 = f0.angDeltaVA;
const Vec3V rbXnI0 = f0.angDeltaVB;
const Vec3V normal1 = Vec3V_From_Vec4V(normalXYZ_ErrorW1);
const Vec3V raXn1 = Vec3V_From_Vec4V(raXn_targetVelW1);
const Vec3V rbXn1 = Vec3V_From_Vec4V(rbXn_velMultiplierW1);
const Vec3V raXnI1 = f1.angDeltaVA;
const Vec3V rbXnI1 = f1.angDeltaVB;
const FloatV frictionScale = FLoad(f0.frictionScale);
const FloatV biasScale = FLoad(f0.biasScale);
const FloatV appliedForce0 = FLoad(f0.appliedForce);
const FloatV velMultiplier0 = V4GetW(rbXn_velMultiplierW0);
const FloatV targetVel0 = V4GetW(raXn_targetVelW0);
const FloatV initialError0 = V4GetW(normalXYZ_ErrorW0);
const FloatV appliedForce1 = FLoad(f1.appliedForce);
const FloatV velMultiplier1 = V4GetW(rbXn_velMultiplierW1);
const FloatV targetVel1 = V4GetW(raXn_targetVelW1);
const FloatV initialError1 = V4GetW(normalXYZ_ErrorW1);
const FloatV error0 = FAdd(initialError0, FNegScaleSub(targetVel0, elapsedTime, FAdd(FSub(V3Dot(raXn0, angDelta0), V3Dot(rbXn0, angDelta1)), V3Dot(normal0, relMotion))));
const FloatV error1 = FAdd(initialError1, FNegScaleSub(targetVel1, elapsedTime, FAdd(FSub(V3Dot(raXn1, angDelta0), V3Dot(rbXn1, angDelta1)), V3Dot(normal1, relMotion))));
const FloatV bias0 = FMul(error0, biasScale);
const FloatV bias1 = FMul(error1, biasScale);
const Vec3V v00 = V3MulAdd(linVel0, normal0, V3Mul(angVel0, raXn0));
const Vec3V v10 = V3MulAdd(linVel1, normal0, V3Mul(angVel1, rbXn0));
const FloatV normalVel0 = V3SumElems(V3Sub(v00, v10));
const Vec3V v01 = V3MulAdd(linVel0, normal1, V3Mul(angVel0, raXn1));
const Vec3V v11 = V3MulAdd(linVel1, normal1, V3Mul(angVel1, rbXn1));
const FloatV normalVel1 = V3SumElems(V3Sub(v01, v11));
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp10 = FNegScaleSub(FSub(bias0, targetVel0), velMultiplier0, appliedForce0);
const FloatV tmp11 = FNegScaleSub(FSub(bias1, targetVel1), velMultiplier1, appliedForce1);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse0 = FNegScaleSub(normalVel0, velMultiplier0, tmp10);
const FloatV totalImpulse1 = FNegScaleSub(normalVel1, velMultiplier1, tmp11);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const FloatV totalImpulse = FSqrt(FAdd(FMul(totalImpulse0, totalImpulse0), FMul(totalImpulse1, totalImpulse1)));
const BoolV clamp = FIsGrtr(totalImpulse, FMul(maxFrictionImpulse, frictionScale));
const FloatV totalClamped = FSel(clamp, FMin(FMul(maxDynFrictionImpulse, frictionScale), totalImpulse), totalImpulse);
const FloatV ratio = FSel(FIsGrtr(totalImpulse, zero), FDiv(totalClamped, totalImpulse), zero);
const FloatV newAppliedForce0 = FMul(ratio, totalImpulse0);
const FloatV newAppliedForce1 = FMul(ratio, totalImpulse1);
broken = BOr(broken, clamp);
const FloatV deltaF0 = FSub(newAppliedForce0, appliedForce0);
const FloatV deltaF1 = FSub(newAppliedForce1, appliedForce1);
linVel0 = V3ScaleAdd(f0.linDeltaVA, deltaF0, V3ScaleAdd(f1.linDeltaVA, deltaF1, linVel0));
angVel0 = V3ScaleAdd(raXnI0, deltaF0, V3ScaleAdd(raXnI1, deltaF1, angVel0));
linVel1 = V3ScaleAdd(f0.linDeltaVB, deltaF0, V3ScaleAdd(f1.linDeltaVB, deltaF1, linVel1));
angVel1 = V3ScaleAdd(rbXnI0, deltaF0, V3ScaleAdd(rbXnI1, deltaF1, angVel1));
/*PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel0, linVel0)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel1, linVel1)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel0, angVel0)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel1, angVel1)));*/
li0 = V3ScaleAdd(normal0, deltaF0, V3ScaleAdd(normal1, deltaF1, li0));
ai0 = V3ScaleAdd(raXn0, deltaF0, V3ScaleAdd(raXn1, deltaF1, ai0));
li1 = V3ScaleAdd(normal0, deltaF0, V3ScaleAdd(normal1, deltaF1, li1));
ai1 = V3ScaleAdd(rbXn0, deltaF0, V3ScaleAdd(rbXn1, deltaF1, ai1));
f0.setAppliedForce(newAppliedForce0);
f1.setAppliedForce(newAppliedForce1);
}
for (PxU32 i = numFrictionPairs; i<numFrictionConstr; i++)
{
SolverContactFrictionStepExt& f = frictions[i];
PxPrefetchLine(&frictions[i + 1]);
const Vec4V raXn_targetVelW = f.raXnI_targetVelW;
const Vec4V rbXn_velMultiplierW = f.rbXnI_velMultiplierW;
const Vec3V raXn = Vec3V_From_Vec4V(raXn_targetVelW);
const Vec3V rbXn = Vec3V_From_Vec4V(rbXn_velMultiplierW);
const Vec3V raXnI = f.angDeltaVA;
const Vec3V rbXnI = f.angDeltaVB;
const FloatV frictionScale = FLoad(f.frictionScale);
const FloatV appliedForce = FLoad(f.appliedForce);
const FloatV velMultiplier = V4GetW(rbXn_velMultiplierW);
const FloatV targetVel = V4GetW(raXn_targetVelW);
const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse);
//const FloatV negMaxFrictionImpulse = FNeg(maxFrictionImpulse);
const Vec3V v0 = V3Mul(angVel0, raXn);
const Vec3V v1 = V3Mul(angVel1, rbXn);
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp1 = FNegScaleSub(FNeg(targetVel), velMultiplier, appliedForce);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const BoolV clamp = FIsGrtr(FAbs(totalImpulse), FMul(maxFrictionImpulse, frictionScale));
const FloatV totalClamped = FMin(FMul(maxDynFrictionImpulse, frictionScale), FMax(FMul(negMaxDynFrictionImpulse, frictionScale), totalImpulse));
const FloatV newAppliedForce = FSel(clamp, totalClamped, totalImpulse);
broken = BOr(broken, clamp);
FloatV deltaF = FSub(newAppliedForce, appliedForce);
linVel0 = V3ScaleAdd(f.linDeltaVA, deltaF, linVel0);
angVel0 = V3ScaleAdd(raXnI, deltaF, angVel0);
linVel1 = V3ScaleAdd(f.linDeltaVB, deltaF, linVel1);
angVel1 = V3ScaleAdd(rbXnI, deltaF, angVel1);
/*PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel0, linVel0)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel1, linVel1)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel0, angVel0)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel1, angVel1)));*/
ai0 = V3ScaleAdd(raXn, deltaF, ai0);
ai1 = V3ScaleAdd(rbXn, deltaF, ai1);
f.setAppliedForce(newAppliedForce);
}
Store_From_BoolV(broken, &hdr->broken);
}
linImpulse0 = V3ScaleAdd(li0, hdr->getDominance0(), linImpulse0);
angImpulse0 = V3ScaleAdd(ai0, FLoad(hdr->angDom0), angImpulse0);
linImpulse1 = V3NegScaleSub(li1, hdr->getDominance1(), linImpulse1);
angImpulse1 = V3NegScaleSub(ai1, FLoad(hdr->angDom1), angImpulse1);
}
PX_ASSERT(currPtr == last);
}
static void solveExtContactStep(const PxSolverConstraintDesc& desc, bool doFriction, PxReal minPenetration, PxReal elapsedTimeF32, SolverContext& cache)
{
Vec3V linVel0, angVel0, linVel1, angVel1;
Vec3V linDelta0, angDelta0, linDelta1, angDelta1;
Dy::FeatherstoneArticulation* artA = getArticulationA(desc);
Dy::FeatherstoneArticulation* artB = getArticulationB(desc);
if (artA == artB)
{
Cm::SpatialVectorV v0, v1;
artA->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1);
linVel0 = v0.linear;
angVel0 = v0.angular;
linVel1 = v1.linear;
angVel1 = v1.angular;
Cm::SpatialVectorV motionV0 = artA->getLinkMotionVector(desc.linkIndexA);// PxcFsGetMotionVector(*artA, desc.linkIndexA);
Cm::SpatialVectorV motionV1 = artB->getLinkMotionVector(desc.linkIndexB);// PxcFsGetMotionVector(*artB, desc.linkIndexB);
linDelta0 = motionV0.linear;
angDelta0 = motionV0.angular;
linDelta1 = motionV1.linear;
angDelta1 = motionV1.angular;
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = V3LoadA(desc.tgsBodyA->linearVelocity);
angVel0 = V3LoadA(desc.tgsBodyA->angularVelocity);
linDelta0 = V3LoadA(desc.tgsBodyA->deltaLinDt);
angDelta0 = V3LoadA(desc.tgsBodyA->deltaAngDt);
}
else
{
Cm::SpatialVectorV v = artA->pxcFsGetVelocity(desc.linkIndexA);
Cm::SpatialVectorV deltaV = artA->getLinkMotionVector(desc.linkIndexA);// PxcFsGetMotionVector(*artA, desc.linkIndexA);
linVel0 = v.linear;
angVel0 = v.angular;
linDelta0 = deltaV.linear;
angDelta0 = deltaV.angular;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
linVel1 = V3LoadA(desc.tgsBodyB->linearVelocity);
angVel1 = V3LoadA(desc.tgsBodyB->angularVelocity);
linDelta1 = V3LoadA(desc.tgsBodyB->deltaLinDt);
angDelta1 = V3LoadA(desc.tgsBodyB->deltaAngDt);
}
else
{
Cm::SpatialVectorV v = artB->pxcFsGetVelocity(desc.linkIndexB);
Cm::SpatialVectorV deltaV = artB->getLinkMotionVector(desc.linkIndexB);// PxcFsGetMotionVector(*artB, desc.linkIndexB);
linVel1 = v.linear;
angVel1 = v.angular;
linDelta1 = deltaV.linear;
angDelta1 = deltaV.angular;
}
}
/*PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel0, linVel0)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel1, linVel1)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel0, angVel0)));
PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel1, angVel1)));*/
Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero();
solveExtContactStep(desc, linVel0, linVel1, angVel0, angVel1, linDelta0, linDelta1, angDelta0, angDelta1, linImpulse0, linImpulse1, angImpulse0,
angImpulse1, doFriction, minPenetration, elapsedTimeF32);
if (artA == artB)
{
artA->pxcFsApplyImpulses(desc.linkIndexA,
linImpulse0, angImpulse0, desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV);
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel0, desc.tgsBodyA->linearVelocity);
V3StoreA(angVel0, desc.tgsBodyA->angularVelocity);
}
else
{
artA->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV);
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel1, desc.tgsBodyB->linearVelocity);
V3StoreA(angVel1, desc.tgsBodyB->angularVelocity);
}
else
{
artB->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV);
}
}
}
void solveContactBlock(DY_TGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(txInertias);
PX_UNUSED(cache);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
solveContact(desc[i], true, minPenetration, elapsedTime);
}
void solve1DBlock(DY_TGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(minPenetration);
PX_UNUSED(cache);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
solve1DStep(desc[i], txInertias, elapsedTime);
}
void solveExtContactBlock(DY_TGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(txInertias);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
solveExtContactStep(desc[i], true, minPenetration, elapsedTime, cache);
}
void solveExt1DBlock(DY_TGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(minPenetration);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
solveExt1DStep(desc[i], elapsedTime, cache, txInertias);
}
void writeBackContact(DY_TGS_WRITEBACK_METHOD_PARAMS)
{
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
writeBackContact(desc[i], cache);
}
void writeBack1D(DY_TGS_WRITEBACK_METHOD_PARAMS)
{
PX_UNUSED(cache);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
writeBack1D(desc[i]);
}
void solveConclude1DBlock(DY_TGS_CONCLUDE_METHOD_PARAMS)
{
PX_UNUSED(cache);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
{
solve1DStep(desc[i], txInertias, elapsedTime);
conclude1DStep(desc[i]);
}
}
void solveConclude1DBlockExt(DY_TGS_CONCLUDE_METHOD_PARAMS)
{
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
{
solveExt1DStep(desc[i], elapsedTime, cache, txInertias);
conclude1DStep(desc[i]);
}
}
void solveConcludeContactBlock(DY_TGS_CONCLUDE_METHOD_PARAMS)
{
PX_UNUSED(txInertias);
PX_UNUSED(cache);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
{
solveContact(desc[i], true, -PX_MAX_F32, elapsedTime);
concludeContact(desc[i]);
}
}
void solveConcludeContactExtBlock(DY_TGS_CONCLUDE_METHOD_PARAMS)
{
PX_UNUSED(txInertias);
for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i)
{
solveExtContactStep(desc[i], true, -PX_MAX_F32, elapsedTime, cache);
concludeContact(desc[i]);
}
}
}
}
| 134,052 | C++ | 38.884856 | 209 | 0.738572 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraints.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DySolverBody.h"
#include "DySolverContact.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "DyThresholdTable.h"
#include "DySolverContext.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
#include "DySolverConstraintsShared.h"
#include "DyFeatherstoneArticulation.h"
#include "DyPGS.h"
using namespace physx;
using namespace Dy;
//Port of scalar implementation to SIMD maths with some interleaving of instructions
static void solve1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxSolverBody& b0 = *desc.bodyA;
PxSolverBody& b1 = *desc.bodyB;
PxU8* PX_RESTRICT bPtr = desc.constraint;
if (bPtr == NULL)
return;
//PxU32 length = desc.constraintLength;
const SolverConstraint1DHeader* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeader*>(bPtr);
SolverConstraint1D* PX_RESTRICT base = reinterpret_cast<SolverConstraint1D*>(bPtr + sizeof(SolverConstraint1DHeader));
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V linVel1 = V3LoadA(b1.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
Vec3V angState1 = V3LoadA(b1.angularState);
const FloatV invMass0 = FLoad(header->invMass0D0);
const FloatV invMass1 = FLoad(header->invMass1D1);
const FloatV invInertiaScale0 = FLoad(header->angularInvMassScale0);
const FloatV invInertiaScale1 = FLoad(header->angularInvMassScale1);
const PxU32 count = header->count;
for(PxU32 i=0; i<count;++i, base++)
{
PxPrefetchLine(base+1);
SolverConstraint1D& c = *base;
const Vec3V clinVel0 = V3LoadA(c.lin0);
const Vec3V clinVel1 = V3LoadA(c.lin1);
const Vec3V cangVel0 = V3LoadA(c.ang0);
const Vec3V cangVel1 = V3LoadA(c.ang1);
const FloatV constant = FLoad(c.constant);
const FloatV vMul = FLoad(c.velMultiplier);
const FloatV iMul = FLoad(c.impulseMultiplier);
const FloatV appliedForce = FLoad(c.appliedForce);
//const FloatV targetVel = FLoad(c.targetVelocity);
const FloatV maxImpulse = FLoad(c.maxImpulse);
const FloatV minImpulse = FLoad(c.minImpulse);
const Vec3V v0 = V3MulAdd(linVel0, clinVel0, V3Mul(angState0, cangVel0));
const Vec3V v1 = V3MulAdd(linVel1, clinVel1, V3Mul(angState1, cangVel1));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV unclampedForce = FScaleAdd(iMul, appliedForce, FScaleAdd(vMul, normalVel, constant));
const FloatV clampedForce = FMin(maxImpulse, (FMax(minImpulse, unclampedForce)));
const FloatV deltaF = FSub(clampedForce, appliedForce);
FStore(clampedForce, &c.appliedForce);
linVel0 = V3ScaleAdd(clinVel0, FMul(deltaF, invMass0), linVel0);
linVel1 = V3NegScaleSub(clinVel1, FMul(deltaF, invMass1), linVel1);
angState0 = V3ScaleAdd(cangVel0, FMul(deltaF, invInertiaScale0), angState0);
//This should be negScaleSub but invInertiaScale1 is negated already
angState1 = V3ScaleAdd(cangVel1, FMul(deltaF, invInertiaScale1), angState1);
}
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(angState0, b0.angularState);
V3StoreA(linVel1, b1.linearVelocity);
V3StoreA(angState1, b1.angularState);
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularState.isFinite());
PX_ASSERT(b1.linearVelocity.isFinite());
PX_ASSERT(b1.angularState.isFinite());
}
namespace physx
{
namespace Dy
{
void conclude1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
SolverConstraint1DHeader* header = reinterpret_cast<SolverConstraint1DHeader*>(desc.constraint);
if (header == NULL)
return;
PxU8* base = desc.constraint + sizeof(SolverConstraint1DHeader);
const PxU32 stride = header->type == DY_SC_TYPE_EXT_1D ? sizeof(SolverConstraint1DExt) : sizeof(SolverConstraint1D);
const PxU32 count = header->count;
for(PxU32 i=0; i<count; i++)
{
SolverConstraint1D& c = *reinterpret_cast<SolverConstraint1D*>(base);
c.constant = c.unbiasedConstant;
base += stride;
}
//The final row may no longer be at the end of the reserved memory range. This can happen if there were degenerate
//constraint rows with articulations, in which case the rows are skipped.
//PX_ASSERT(desc.constraint + getConstraintLength(desc) == base);
}
// ==============================================================
static void solveContact(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
PxSolverBody& b0 = *desc.bodyA;
PxSolverBody& b1 = *desc.bodyB;
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V linVel1 = V3LoadA(b1.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
Vec3V angState1 = V3LoadA(b1.angularState);
const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
while(currPtr < last)
{
SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader*>(currPtr);
currPtr += sizeof(SolverContactHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr);
PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPoint);
PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr);
currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFriction);
const FloatV invMassA = FLoad(hdr->invMass0);
const FloatV invMassB = FLoad(hdr->invMass1);
const FloatV angDom0 = FLoad(hdr->angDom0);
const FloatV angDom1 = FLoad(hdr->angDom1);
const Vec3V contactNormal = Vec3V_From_Vec4V_WUndefined(hdr->normal_minAppliedImpulseForFrictionW);
const FloatV accumulatedNormalImpulse = solveDynamicContacts(contacts, numNormalConstr, contactNormal, invMassA, invMassB,
angDom0, angDom1, linVel0, angState0, linVel1, angState1, forceBuffer);
if(cache.doFriction && numFrictionConstr)
{
const FloatV staticFrictionCof = hdr->getStaticFriction();
const FloatV dynamicFrictionCof = hdr->getDynamicFriction();
const FloatV maxFrictionImpulse = FMul(staticFrictionCof, accumulatedNormalImpulse);
const FloatV maxDynFrictionImpulse = FMul(dynamicFrictionCof, accumulatedNormalImpulse);
const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse);
BoolV broken = BFFFF();
if(cache.writeBackIteration)
PxPrefetchLine(hdr->frictionBrokenWritebackByte);
for(PxU32 i=0;i<numFrictionConstr;i++)
{
SolverContactFriction& f = frictions[i];
PxPrefetchLine(&frictions[i],128);
const Vec4V normalXYZ_appliedForceW = f.normalXYZ_appliedForceW;
const Vec4V raXnXYZ_velMultiplierW = f.raXnXYZ_velMultiplierW;
const Vec4V rbXnXYZ_biasW = f.rbXnXYZ_biasW;
const Vec3V normal = Vec3V_From_Vec4V(normalXYZ_appliedForceW);
const Vec3V raXn = Vec3V_From_Vec4V(raXnXYZ_velMultiplierW);
const Vec3V rbXn = Vec3V_From_Vec4V(rbXnXYZ_biasW);
const FloatV appliedForce = V4GetW(normalXYZ_appliedForceW);
const FloatV bias = V4GetW(rbXnXYZ_biasW);
const FloatV velMultiplier = V4GetW(raXnXYZ_velMultiplierW);
const FloatV targetVel = FLoad(f.targetVel);
const Vec3V delLinVel0 = V3Scale(normal, invMassA);
const Vec3V delLinVel1 = V3Scale(normal, invMassB);
const Vec3V v0 = V3MulAdd(linVel0, normal, V3Mul(angState0, raXn));
const Vec3V v1 = V3MulAdd(linVel1, normal, V3Mul(angState1, rbXn));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp1 = FNegScaleSub(FSub(bias, targetVel), velMultiplier, appliedForce);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const BoolV clamp = FIsGrtr(FAbs(totalImpulse), maxFrictionImpulse);
const FloatV totalClamped = FMin(maxDynFrictionImpulse, FMax(negMaxDynFrictionImpulse, totalImpulse));
const FloatV newAppliedForce = FSel(clamp, totalClamped,totalImpulse);
broken = BOr(broken, clamp);
FloatV deltaF = FSub(newAppliedForce, appliedForce);
// we could get rid of the stall here by calculating and clamping delta separately, but
// the complexity isn't really worth it.
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1);
angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0);
angState1 = V3NegScaleSub(rbXn, FMul(deltaF, angDom1), angState1);
f.setAppliedForce(newAppliedForce);
}
Store_From_BoolV(broken, &hdr->broken);
}
}
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularState.isFinite());
PX_ASSERT(b1.linearVelocity.isFinite());
PX_ASSERT(b1.angularState.isFinite());
// Write back
V3StoreU(linVel0, b0.linearVelocity);
V3StoreU(linVel1, b1.linearVelocity);
V3StoreU(angState0, b0.angularState);
V3StoreU(angState1, b1.angularState);
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularState.isFinite());
PX_ASSERT(b1.linearVelocity.isFinite());
PX_ASSERT(b1.angularState.isFinite());
PX_ASSERT(currPtr == last);
}
static void solveContact_BStatic(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
PxSolverBody& b0 = *desc.bodyA;
//PxSolverBody& b1 = *desc.bodyB;
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
while(currPtr < last)
{
SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader*>(currPtr);
currPtr += sizeof(SolverContactHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr);
//PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPoint);
PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr);
currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFriction);
const FloatV invMassA = FLoad(hdr->invMass0);
const Vec3V contactNormal = Vec3V_From_Vec4V_WUndefined(hdr->normal_minAppliedImpulseForFrictionW);
const FloatV angDom0 = FLoad(hdr->angDom0);
const FloatV accumulatedNormalImpulse = solveStaticContacts(contacts, numNormalConstr, contactNormal,
invMassA, angDom0, linVel0, angState0, forceBuffer);
if(cache.doFriction && numFrictionConstr)
{
const FloatV maxFrictionImpulse = FMul(hdr->getStaticFriction(), accumulatedNormalImpulse);
const FloatV maxDynFrictionImpulse = FMul(hdr->getDynamicFriction(), accumulatedNormalImpulse);
BoolV broken = BFFFF();
if(cache.writeBackIteration)
PxPrefetchLine(hdr->frictionBrokenWritebackByte);
for(PxU32 i=0;i<numFrictionConstr;i++)
{
SolverContactFriction& f = frictions[i];
PxPrefetchLine(&frictions[i],128);
const Vec4V normalXYZ_appliedForceW = f.normalXYZ_appliedForceW;
const Vec4V raXnXYZ_velMultiplierW = f.raXnXYZ_velMultiplierW;
const Vec4V rbXnXYZ_biasW = f.rbXnXYZ_biasW;
const Vec3V normal = Vec3V_From_Vec4V(normalXYZ_appliedForceW);
const Vec3V raXn = Vec3V_From_Vec4V(raXnXYZ_velMultiplierW);
const FloatV appliedForce = V4GetW(normalXYZ_appliedForceW);
const FloatV bias = V4GetW(rbXnXYZ_biasW);
const FloatV velMultiplier = V4GetW(raXnXYZ_velMultiplierW);
const FloatV targetVel = FLoad(f.targetVel);
const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse);
const Vec3V delLinVel0 = V3Scale(normal, invMassA);
//const FloatV negMaxFrictionImpulse = FNeg(maxFrictionImpulse);
const Vec3V v0 = V3MulAdd(linVel0, normal, V3Mul(angState0, raXn));
const FloatV normalVel = V3SumElems(v0);
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp1 = FNegScaleSub(FSub(bias, targetVel),velMultiplier,appliedForce);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const BoolV clamp = FIsGrtr(FAbs(totalImpulse), maxFrictionImpulse);
const FloatV totalClamped = FMin(maxDynFrictionImpulse, FMax(negMaxDynFrictionImpulse, totalImpulse));
broken = BOr(broken, clamp);
const FloatV newAppliedForce = FSel(clamp, totalClamped,totalImpulse);
FloatV deltaF = FSub(newAppliedForce, appliedForce);
// we could get rid of the stall here by calculating and clamping delta separately, but
// the complexity isn't really worth it.
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0);
f.setAppliedForce(newAppliedForce);
}
Store_From_BoolV(broken, &hdr->broken);
}
}
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularState.isFinite());
// Write back
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(angState0, b0.angularState);
PX_ASSERT(b0.linearVelocity.isFinite());
PX_ASSERT(b0.angularState.isFinite());
PX_ASSERT(currPtr == last);
}
void concludeContact(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxU8* PX_RESTRICT cPtr = desc.constraint;
const FloatV zero = FZero();
PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc);
while(cPtr < last)
{
const SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactHeader*>(cPtr);
cPtr += sizeof(SolverContactHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
//if(cPtr < last)
//PxPrefetchLine(cPtr, 512);
PxPrefetchLine(cPtr,128);
PxPrefetchLine(cPtr,256);
PxPrefetchLine(cPtr,384);
const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt)
: sizeof(SolverContactPoint);
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContactPoint *c = reinterpret_cast<SolverContactPoint*>(cPtr);
cPtr += pointStride;
//c->scaledBias = PxMin(c->scaledBias, 0.f);
c->biasedErr = c->unbiasedErr;
}
cPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); //Jump over force buffers
const PxU32 frictionStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactFrictionExt)
: sizeof(SolverContactFriction);
for(PxU32 i=0;i<numFrictionConstr;i++)
{
SolverContactFriction *f = reinterpret_cast<SolverContactFriction*>(cPtr);
cPtr += frictionStride;
f->setBias(zero);
}
}
PX_ASSERT(cPtr == last);
}
void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext& cache,
PxSolverBodyData& bd0, PxSolverBodyData& bd1)
{
PxReal normalForce = 0;
PxU8* PX_RESTRICT cPtr = desc.constraint;
PxReal* PX_RESTRICT vForceWriteback = reinterpret_cast<PxReal*>(desc.writeBack);
PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc);
bool forceThreshold = false;
while(cPtr < last)
{
const SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactHeader*>(cPtr);
cPtr += sizeof(SolverContactHeader);
forceThreshold = hdr->flags & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
//if(cPtr < last)
PxPrefetchLine(cPtr, 256);
PxPrefetchLine(cPtr, 384);
const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt)
: sizeof(SolverContactPoint);
cPtr += pointStride * numNormalConstr;
PxF32* forceBuffer = reinterpret_cast<PxF32*>(cPtr);
cPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
if(vForceWriteback!=NULL)
{
for(PxU32 i=0; i<numNormalConstr; i++)
{
PxReal appliedForce = forceBuffer[i];
*vForceWriteback++ = appliedForce;
normalForce += appliedForce;
}
}
const PxU32 frictionStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactFrictionExt)
: sizeof(SolverContactFriction);
if(hdr->broken && hdr->frictionBrokenWritebackByte != NULL)
{
*hdr->frictionBrokenWritebackByte = 1;
}
cPtr += frictionStride * numFrictionConstr;
}
PX_ASSERT(cPtr == last);
if(forceThreshold && desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
normalForce !=0 && (bd0.reportThreshold < PX_MAX_REAL || bd1.reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = normalForce;
elt.threshold = PxMin<float>(bd0.reportThreshold, bd1.reportThreshold);
elt.nodeIndexA = PxNodeIndex(bd0.nodeIndex);
elt.nodeIndexB = PxNodeIndex(bd1.nodeIndex);
elt.shapeInteraction = reinterpret_cast<const SolverContactHeader*>(desc.constraint)->shapeInteraction;
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
// adjust from CoM to joint
void writeBack1D(const PxSolverConstraintDesc& desc, SolverContext&, PxSolverBodyData&, PxSolverBodyData&)
{
ConstraintWriteback* writeback = reinterpret_cast<ConstraintWriteback*>(desc.writeBack);
if(writeback)
{
SolverConstraint1DHeader* header = reinterpret_cast<SolverConstraint1DHeader*>(desc.constraint);
PxU8* base = desc.constraint + sizeof(SolverConstraint1DHeader);
const PxU32 stride = header->type == DY_SC_TYPE_EXT_1D ? sizeof(SolverConstraint1DExt) : sizeof(SolverConstraint1D);
PxVec3 lin(0), ang(0);
const PxU32 count = header->count;
for(PxU32 i=0; i<count; i++)
{
const SolverConstraint1D* c = reinterpret_cast<SolverConstraint1D*>(base);
if(c->flags & DY_SC_FLAG_OUTPUT_FORCE)
{
lin += c->lin0 * c->appliedForce;
ang += c->ang0Writeback * c->appliedForce;
}
base += stride;
}
ang -= header->body0WorldOffset.cross(lin);
writeback->linearImpulse = lin;
writeback->angularImpulse = ang;
writeback->broken = header->breakable ? PxU32(lin.magnitude()>header->linBreakImpulse || ang.magnitude()>header->angBreakImpulse) : 0;
//If we had degenerate rows, the final constraint row may not end at getConstraintLength bytes from the base anymore
//PX_ASSERT(desc.constraint + getConstraintLength(desc) == base);
}
}
void solve1DBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
solve1D(desc[a-1], cache);
}
solve1D(desc[constraintCount-1], cache);
}
void solve1DConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
solve1D(desc[a-1], cache);
conclude1D(desc[a-1], cache);
}
solve1D(desc[constraintCount-1], cache);
conclude1D(desc[constraintCount-1], cache);
}
void solve1DBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex];
solve1D(desc[a-1], cache);
writeBack1D(desc[a-1], cache, bd0, bd1);
}
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex];
solve1D(desc[constraintCount-1], cache);
writeBack1D(desc[constraintCount-1], cache, bd0, bd1);
}
void writeBack1DBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex];
writeBack1D(desc[a-1], cache, bd0, bd1);
}
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex];
writeBack1D(desc[constraintCount-1], cache, bd0, bd1);
}
void solveContactBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
solveContact(desc[a-1], cache);
}
solveContact(desc[constraintCount-1], cache);
}
void solveContactConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
solveContact(desc[a-1], cache);
concludeContact(desc[a-1], cache);
}
solveContact(desc[constraintCount-1], cache);
concludeContact(desc[constraintCount-1], cache);
}
void solveContactBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex];
solveContact(desc[a-1], cache);
writeBackContact(desc[a-1], cache, bd0, bd1);
}
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex];
solveContact(desc[constraintCount-1], cache);
writeBackContact(desc[constraintCount-1], cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveContact_BStaticBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
solveContact_BStatic(desc[a-1], cache);
}
solveContact_BStatic(desc[constraintCount-1], cache);
}
void solveContact_BStaticConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
solveContact_BStatic(desc[a-1], cache);
concludeContact(desc[a-1], cache);
}
solveContact_BStatic(desc[constraintCount-1], cache);
concludeContact(desc[constraintCount-1], cache);
}
void solveContact_BStaticBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 1; a < constraintCount; ++a)
{
PxPrefetchLine(desc[a].constraint);
PxPrefetchLine(desc[a].constraint, 128);
PxPrefetchLine(desc[a].constraint, 256);
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex];
solveContact_BStatic(desc[a-1], cache);
writeBackContact(desc[a-1], cache, bd0, bd1);
}
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex];
solveContact_BStatic(desc[constraintCount-1], cache);
writeBackContact(desc[constraintCount-1], cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Not enough space to write 4 more thresholds back!
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void clearExt1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxU8* PX_RESTRICT bPtr = desc.constraint;
const SolverConstraint1DHeader* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeader*>(bPtr);
SolverConstraint1DExt* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DExt*>(bPtr + sizeof(SolverConstraint1DHeader));
const PxU32 count = header->count;
for (PxU32 i=0; i<count; ++i, base++)
{
base->appliedForce = 0.f;
}
}
void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
Vec3V& li0, Vec3V& li1, Vec3V& ai0, Vec3V& ai1)
{
PxU8* PX_RESTRICT bPtr = desc.constraint;
const SolverConstraint1DHeader* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeader*>(bPtr);
SolverConstraint1DExt* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DExt*>(bPtr + sizeof(SolverConstraint1DHeader));
const PxU32 count = header->count;
for (PxU32 i=0; i<count; ++i, base++)
{
PxPrefetchLine(base + 1);
const Vec4V lin0XYZ_constantW = V4LoadA(&base->lin0.x);
const Vec4V lin1XYZ_unbiasedConstantW = V4LoadA(&base->lin1.x);
const Vec4V ang0XYZ_velMultiplierW = V4LoadA(&base->ang0.x);
const Vec4V ang1XYZ_impulseMultiplierW = V4LoadA(&base->ang1.x);
const Vec4V minImpulseX_maxImpulseY_appliedForceZ = V4LoadA(&base->minImpulse);
const Vec3V lin0 = Vec3V_From_Vec4V(lin0XYZ_constantW); FloatV constant = V4GetW(lin0XYZ_constantW);
const Vec3V lin1 = Vec3V_From_Vec4V(lin1XYZ_unbiasedConstantW);
const Vec3V ang0 = Vec3V_From_Vec4V(ang0XYZ_velMultiplierW); FloatV vMul = V4GetW(ang0XYZ_velMultiplierW);
const Vec3V ang1 = Vec3V_From_Vec4V(ang1XYZ_impulseMultiplierW); FloatV iMul = V4GetW(ang1XYZ_impulseMultiplierW);
const FloatV minImpulse = V4GetX(minImpulseX_maxImpulseY_appliedForceZ);
const FloatV maxImpulse = V4GetY(minImpulseX_maxImpulseY_appliedForceZ);
const FloatV appliedForce = V4GetZ(minImpulseX_maxImpulseY_appliedForceZ);
const Vec3V v0 = V3MulAdd(linVel0, lin0, V3Mul(angVel0, ang0));
const Vec3V v1 = V3MulAdd(linVel1, lin1, V3Mul(angVel1, ang1));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV unclampedForce = FScaleAdd(iMul, appliedForce, FScaleAdd(vMul, normalVel, constant));
const FloatV clampedForce = FMin(maxImpulse, (FMax(minImpulse, unclampedForce)));
const FloatV deltaF = FSub(clampedForce, appliedForce);
FStore(clampedForce, &base->appliedForce);
li0 = V3ScaleAdd(lin0, deltaF, li0); ai0 = V3ScaleAdd(ang0, deltaF, ai0);
li1 = V3ScaleAdd(lin1, deltaF, li1); ai1 = V3ScaleAdd(ang1, deltaF, ai1);
linVel0 = V3ScaleAdd(base->deltaVA.linear, deltaF, linVel0); angVel0 = V3ScaleAdd(base->deltaVA.angular, deltaF, angVel0);
linVel1 = V3ScaleAdd(base->deltaVB.linear, deltaF, linVel1); angVel1 = V3ScaleAdd(base->deltaVB.angular, deltaF, angVel1);
#if 0
PxVec3 lv0, lv1, av0, av1;
V3StoreU(linVel0, lv0); V3StoreU(linVel1, lv1);
V3StoreU(angVel0, av0); V3StoreU(angVel1, av1);
PX_ASSERT(lv0.magnitude() < 30.f);
PX_ASSERT(lv1.magnitude() < 30.f);
PX_ASSERT(av0.magnitude() < 30.f);
PX_ASSERT(av1.magnitude() < 30.f);
#endif
}
li0 = V3Scale(li0, FLoad(header->linearInvMassScale0));
li1 = V3Scale(li1, FLoad(header->linearInvMassScale1));
ai0 = V3Scale(ai0, FLoad(header->angularInvMassScale0));
ai1 = V3Scale(ai1, FLoad(header->angularInvMassScale1));
}
//Port of scalar implementation to SIMD maths with some interleaving of instructions
void solveExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
//PxU32 length = desc.constraintLength;
Vec3V linVel0, angVel0, linVel1, angVel1;
if (desc.articulationA == desc.articulationB)
{
Cm::SpatialVectorV v0, v1;
getArticulationA(desc)->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1);
linVel0 = v0.linear;
angVel0 = v0.angular;
linVel1 = v1.linear;
angVel1 = v1.angular;
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = V3LoadA(desc.bodyA->linearVelocity);
angVel0 = V3LoadA(desc.bodyA->angularState);
}
else
{
Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA);
linVel0 = v.linear;
angVel0 = v.angular;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
linVel1 = V3LoadA(desc.bodyB->linearVelocity);
angVel1 = V3LoadA(desc.bodyB->angularState);
}
else
{
Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB);
linVel1 = v.linear;
angVel1 = v.angular;
}
}
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, li0, li1, ai0, ai1);
if (desc.articulationA == desc.articulationB)
{
getArticulationA(desc)->pxcFsApplyImpulses(desc.linkIndexA, li0, ai0,
desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV);
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel0, desc.bodyA->linearVelocity);
V3StoreA(angVel0, desc.bodyA->angularState);
}
else
{
getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, li0, ai0, cache.Z, cache.deltaV);
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel1, desc.bodyB->linearVelocity);
V3StoreA(angVel1, desc.bodyB->angularState);
}
else
{
getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV);
}
}
}
FloatV solveExtContacts(SolverContactPointExt* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
Vec3V& linVel0, Vec3V& angVel0,
Vec3V& linVel1, Vec3V& angVel1,
Vec3V& li0, Vec3V& ai0,
Vec3V& li1, Vec3V& ai1,
PxF32* PX_RESTRICT appliedForceBuffer)
{
FloatV accumulatedNormalImpulse = FZero();
for (PxU32 i = 0; i<nbContactPoints; i++)
{
SolverContactPointExt& c = contacts[i];
PxPrefetchLine(&contacts[i + 1]);
const Vec3V raXn = Vec3V_From_Vec4V(c.raXn_velMultiplierW);
const Vec3V rbXn = Vec3V_From_Vec4V(c.rbXn_maxImpulseW);
const FloatV appliedForce = FLoad(appliedForceBuffer[i]);
const FloatV velMultiplier = c.getVelMultiplier();
/*const FloatV targetVel = c.getTargetVelocity();
const FloatV scaledBias = c.getScaledBias();*/
//Compute the normal velocity of the constraint.
Vec3V v = V3MulAdd(linVel0, contactNormal, V3Mul(angVel0, raXn));
v = V3Sub(v, V3MulAdd(linVel1, contactNormal, V3Mul(angVel1, rbXn)));
const FloatV normalVel = V3SumElems(v);
const FloatV biasedErr = c.getBiasedErr();//FNeg(scaledBias);
// still lots to do here: using loop pipelining we can interweave this code with the
// above - the code here has a lot of stalls that we would thereby eliminate
const FloatV _deltaF = FMax(FNegScaleSub(normalVel, velMultiplier, biasedErr), FNeg(appliedForce));
const FloatV newForce = FMin(FAdd(FMul(c.getImpulseMultiplier(), appliedForce), _deltaF), c.getMaxImpulse());
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(c.linDeltaVA, deltaF, linVel0);
angVel0 = V3ScaleAdd(c.angDeltaVA, deltaF, angVel0);
linVel1 = V3ScaleAdd(c.linDeltaVB, deltaF, linVel1);
angVel1 = V3ScaleAdd(c.angDeltaVB, deltaF, angVel1);
li0 = V3ScaleAdd(contactNormal, deltaF, li0); ai0 = V3ScaleAdd(raXn, deltaF, ai0);
li1 = V3ScaleAdd(contactNormal, deltaF, li1); ai1 = V3ScaleAdd(rbXn, deltaF, ai1);
const FloatV newAppliedForce = FAdd(appliedForce, deltaF);
FStore(newAppliedForce, &appliedForceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newAppliedForce);
#if 0
PxVec3 lv0, lv1, av0, av1;
V3StoreU(linVel0, lv0); V3StoreU(linVel1, lv1);
V3StoreU(angVel0, av0); V3StoreU(angVel1, av1);
PX_ASSERT(lv0.magnitude() < 30.f);
PX_ASSERT(lv1.magnitude() < 30.f);
PX_ASSERT(av0.magnitude() < 30.f);
PX_ASSERT(av1.magnitude() < 30.f);
#endif
}
return accumulatedNormalImpulse;
}
void solveExtContact(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1, bool doFriction)
{
const PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16 * 16;
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
while (currPtr < last)
{
SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader*>(currPtr);
currPtr += sizeof(SolverContactHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverContactPointExt* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointExt*>(currPtr);
PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPointExt);
PxF32* appliedForceBuffer = reinterpret_cast<PxF32*>(currPtr);
currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3));
SolverContactFrictionExt* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionExt*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionExt);
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
const Vec3V contactNormal = Vec3V_From_Vec4V(hdr->normal_minAppliedImpulseForFrictionW);
const FloatV minNorImpulse = V4GetW(hdr->normal_minAppliedImpulseForFrictionW);
const FloatV accumulatedNormalImpulse = FMax(solveExtContacts(contacts, numNormalConstr, contactNormal, linVel0, angVel0, linVel1,
angVel1, li0, ai0, li1, ai1, appliedForceBuffer), minNorImpulse);
if (doFriction && numFrictionConstr)
{
PxPrefetchLine(frictions);
const FloatV maxFrictionImpulse = FMul(hdr->getStaticFriction(), accumulatedNormalImpulse);
const FloatV maxDynFrictionImpulse = FMul(hdr->getDynamicFriction(), accumulatedNormalImpulse);
BoolV broken = BFFFF();
for (PxU32 i = 0; i<numFrictionConstr; i++)
{
SolverContactFrictionExt& f = frictions[i];
PxPrefetchLine(&frictions[i + 1]);
const Vec4V normalXYZ_appliedForceW = f.normalXYZ_appliedForceW;
const Vec4V raXnXYZ_velMultiplierW = f.raXnXYZ_velMultiplierW;
const Vec4V rbXnXYZ_biasW = f.rbXnXYZ_biasW;
const Vec3V normal = Vec3V_From_Vec4V(normalXYZ_appliedForceW);
/*const Vec3V normal0 = V3Scale(normal, sqrtInvMass0);
const Vec3V normal1 = V3Scale(normal, sqrtInvMass1);*/
const Vec3V raXn = Vec3V_From_Vec4V(raXnXYZ_velMultiplierW);
const Vec3V rbXn = Vec3V_From_Vec4V(rbXnXYZ_biasW);
const FloatV appliedForce = V4GetW(normalXYZ_appliedForceW);
const FloatV bias = V4GetW(rbXnXYZ_biasW);
const FloatV velMultiplier = V4GetW(raXnXYZ_velMultiplierW);
const FloatV targetVel = FLoad(f.targetVel);
const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse);
const FloatV negMaxFrictionImpulse = FNeg(maxFrictionImpulse);
const Vec3V v0 = V3MulAdd(linVel0, normal, V3Mul(angVel0, raXn));
const Vec3V v1 = V3MulAdd(linVel1, normal, V3Mul(angVel1, rbXn));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const FloatV tmp1 = FNegScaleSub(FSub(bias, targetVel), velMultiplier, appliedForce);
// Algorithm:
// if abs(appliedForce + deltaF) > maxFrictionImpulse
// clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse]
// (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce]
// set broken flag to true || broken flag
// FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier);
// FloatV potentialSumF = FAdd(appliedForce, deltaF);
const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1);
// On XBox this clamping code uses the vector simple pipe rather than vector float,
// which eliminates a lot of stall cycles
const BoolV clampLow = FIsGrtr(negMaxFrictionImpulse, totalImpulse);
const BoolV clampHigh = FIsGrtr(totalImpulse, maxFrictionImpulse);
const FloatV totalClampedLow = FMax(negMaxDynFrictionImpulse, totalImpulse);
const FloatV totalClampedHigh = FMin(maxDynFrictionImpulse, totalImpulse);
const FloatV newAppliedForce = FSel(clampLow, totalClampedLow,
FSel(clampHigh, totalClampedHigh, totalImpulse));
broken = BOr(broken, BOr(clampLow, clampHigh));
FloatV deltaF = FSub(newAppliedForce, appliedForce);
linVel0 = V3ScaleAdd(f.linDeltaVA, deltaF, linVel0);
angVel0 = V3ScaleAdd(f.angDeltaVA, deltaF, angVel0);
linVel1 = V3ScaleAdd(f.linDeltaVB, deltaF, linVel1);
angVel1 = V3ScaleAdd(f.angDeltaVB, deltaF, angVel1);
li0 = V3ScaleAdd(normal, deltaF, li0); ai0 = V3ScaleAdd(raXn, deltaF, ai0);
li1 = V3ScaleAdd(normal, deltaF, li1); ai1 = V3ScaleAdd(rbXn, deltaF, ai1);
#if 0
PxVec3 lv0, lv1, av0, av1;
V3StoreU(linVel0, lv0); V3StoreU(linVel1, lv1);
V3StoreU(angVel0, av0); V3StoreU(angVel1, av1);
PX_ASSERT(lv0.magnitude() < 30.f);
PX_ASSERT(lv1.magnitude() < 30.f);
PX_ASSERT(av0.magnitude() < 30.f);
PX_ASSERT(av1.magnitude() < 30.f);
#endif
f.setAppliedForce(newAppliedForce);
}
Store_From_BoolV(broken, &hdr->broken);
}
linImpulse0 = V3ScaleAdd(li0, hdr->getDominance0(), linImpulse0);
angImpulse0 = V3ScaleAdd(ai0, FLoad(hdr->angDom0), angImpulse0);
linImpulse1 = V3NegScaleSub(li1, hdr->getDominance1(), linImpulse1);
angImpulse1 = V3NegScaleSub(ai1, FLoad(hdr->angDom1), angImpulse1);
/*linImpulse0 = V3ScaleAdd(li0, FZero(), linImpulse0);
angImpulse0 = V3ScaleAdd(ai0, FZero(), angImpulse0);
linImpulse1 = V3NegScaleSub(li1, FZero(), linImpulse1);
angImpulse1 = V3NegScaleSub(ai1, FZero(), angImpulse1);*/
}
}
static void solveExtContact(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
Vec3V linVel0, angVel0, linVel1, angVel1;
if (desc.articulationA == desc.articulationB)
{
Cm::SpatialVectorV v0, v1;
getArticulationA(desc)->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1);
linVel0 = v0.linear;
angVel0 = v0.angular;
linVel1 = v1.linear;
angVel1 = v1.angular;
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = V3LoadA(desc.bodyA->linearVelocity);
angVel0 = V3LoadA(desc.bodyA->angularState);
}
else
{
Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA);
linVel0 = v.linear;
angVel0 = v.angular;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
linVel1 = V3LoadA(desc.bodyB->linearVelocity);
angVel1 = V3LoadA(desc.bodyB->angularState);
}
else
{
Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB);
linVel1 = v.linear;
angVel1 = v.angular;
}
}
Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero();
//Vec3V origLin0 = linVel0, origAng0 = angVel0, origLin1 = linVel1, origAng1 = angVel1;
solveExtContact(desc, linVel0, linVel1, angVel0, angVel1, linImpulse0, linImpulse1, angImpulse0, angImpulse1, cache.doFriction);
if (desc.articulationA == desc.articulationB)
{
getArticulationA(desc)->pxcFsApplyImpulses(desc.linkIndexA, linImpulse0, angImpulse0, desc.linkIndexB, linImpulse1, angImpulse1,
cache.Z, cache.deltaV);
}
else
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel0, desc.bodyA->linearVelocity);
V3StoreA(angVel0, desc.bodyA->angularState);
}
else
{
getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA,
linImpulse0, angImpulse0, cache.Z, cache.deltaV);
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel1, desc.bodyB->linearVelocity);
V3StoreA(angVel1, desc.bodyB->angularState);
}
else
{
getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB,
linImpulse1, angImpulse1, cache.Z, cache.deltaV);
}
}
}
void solveExtContactBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveExtContact(desc[a], cache);
}
void solveExtContactConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
solveExtContact(desc[a], cache);
concludeContact(desc[a], cache);
}
}
void solveExtContactBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyBDataIndex];
solveExtContact(desc[a], cache);
writeBackContact(desc[a], cache, bd0, bd1);
}
if(cache.mThresholdStreamIndex > 0)
{
//Not enough space to write 4 more thresholds back!
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveExt1DBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveExt1D(desc[a], cache);
}
void solveExt1DConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
solveExt1D(desc[a], cache);
conclude1D(desc[a], cache);
}
}
void solveExt1DBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyBDataIndex];
solveExt1D(desc[a], cache);
writeBack1D(desc[a], cache, bd0, bd1);
}
}
// PT: not sure what happened but the following ones weren't actually used
/*void ext1DBlockWriteBack(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyBDataIndex];
writeBack1D(desc[a], cache, bd0, bd1);
}
}
void solveConcludeExtContact(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveExtContact(desc, cache);
concludeContact(desc, cache);
}
void solveConcludeExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveExt1D(desc, cache);
conclude1D(desc, cache);
}
void solveConclude1D(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solve1D(desc, cache);
conclude1D(desc, cache);
}
void solveConcludeContact(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveContact(desc, cache);
concludeContact(desc, cache);
}
void solveConcludeContact_BStatic(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveContact_BStatic(desc, cache);
concludeContact(desc, cache);
}*/
}
}
| 46,753 | C++ | 35.87224 | 146 | 0.740444 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneForwardDynamic.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMathUtils.h"
#include "CmConeLimitHelper.h"
#include "DySolverConstraint1D.h"
#include "DyFeatherstoneArticulation.h"
#include "PxsRigidBody.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
#include "DyDynamics.h"
#include "DyArticulationPImpl.h"
#include "DyFeatherstoneArticulationLink.h"
#include "DyFeatherstoneArticulationJointData.h"
#include "common/PxProfileZone.h"
#include <stdio.h>
#ifdef _MSC_VER
#pragma warning(disable:4505)
#endif
namespace physx
{
namespace Dy
{
void PxcFsFlushVelocity(FeatherstoneArticulation& articulation, Cm::SpatialVectorF* deltaV, bool computeSpatialForces);
#if (FEATHERSTONE_DEBUG && (PX_DEBUG || PX_CHECKED))
static bool isSpatialVectorEqual(Cm::SpatialVectorF& t0, Cm::SpatialVectorF& t1)
{
float eps = 0.0001f;
bool e0 = PxAbs(t0.top.x - t1.top.x) < eps &&
PxAbs(t0.top.y - t1.top.y) < eps &&
PxAbs(t0.top.z - t1.top.z) < eps;
bool e1 = PxAbs(t0.bottom.x - t1.bottom.x) < eps &&
PxAbs(t0.bottom.y - t1.bottom.y) < eps &&
PxAbs(t0.bottom.z - t1.bottom.z) < eps;
return e0 && e1;
}
static bool isSpatialVectorZero(Cm::SpatialVectorF& t0)
{
float eps = 0.000001f;
const bool c0 = PxAbs(t0.top.x) < eps && PxAbs(t0.top.y) < eps && PxAbs(t0.top.z) < eps;
const bool c1 = PxAbs(t0.bottom.x) < eps && PxAbs(t0.bottom.y) < eps && PxAbs(t0.bottom.z) < eps;
return c0 && c1;
}
#endif
#if FEATHERSTONE_DEBUG
static inline PxMat33 Outer(const PxVec3& a, const PxVec3& b)
{
return PxMat33(a * b.x, a * b.y, a * b.z);
}
#endif
SpatialMatrix FeatherstoneArticulation::computePropagateSpatialInertia_ZA_ZIc
(const PxArticulationJointType::Enum jointType, const PxU8 nbJointDofs,
const Cm::UnAlignedSpatialVector* jointMotionMatricesW, const Cm::SpatialVectorF* jointISW,
const PxReal* jointTargetArmatures, const PxReal* jointExternalForces,
const SpatialMatrix& linkArticulatedInertiaW,
const Cm::SpatialVectorF& linkZExtW, const Cm::SpatialVectorF& linkZIntIcW,
InvStIs& linkInvStISW, Cm::SpatialVectorF* jointDofISInvStISW,
PxReal* jointDofMinusStZExtW, PxReal* jointDofQStZIntIcW,
Cm::SpatialVectorF& deltaZAExtParent, Cm::SpatialVectorF& deltaZAIntIcParent)
{
deltaZAExtParent = linkZExtW;
deltaZAIntIcParent = linkZIntIcW;
// The goal is to propagate the articulated z.a force of a child link to the articulated z.a. force of its parent link.
// We will compute a term that can be added to the articulated z.a. force of the parent link.
// This function only references the child link.
// Mirtich uses the notation i for the child and i-1 for the parent.
// We have a more general configuration that allows a parent to have multiple children but in what follows "i" shall refer to the
// child and "i-1" to the parent.
// Another goal is to propagate the articulated spatial inertia from the child link to the parent link.
// We will compute a term that can be added to the articulated spatial inertia of the parent link.
// The Mirtich equivalent is:
// I_i^A - [I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A]
//The term that is to be added to the parent link has the Mirtich formulation:
// Delta_Z_i-1 = (Z_i^A + I_i^A * c_i) + [I_i^A * s_i]*[Q_i - s_i^T * (Z_i^A + I_i^A * c_i)]/[s_i^T * I_i^A * s_i]
//We do not have a single articulated z.a. force as outlined in Mirtich.
//Instead we have a term that accounts for external forces and a term that accounts for internal forces.
//We can generalise the Mirtich formulate to account for internal and external terms:
// Delta_ZExt_i-1 = ZAExt_i + [I_i^A * s_i] * [-s_i^T * ZAExt_i]/[s_i^T * I_i^A * s_i]
// Delta_ZInt_i-1 = ZAInt_i + I_i^A * c_i + [I_i^A * s_i] * [Q_i - s_i^T * (ZAInt_i + I_i^A * c_i)]/[s_i^T * I_i^A * s_i]
// Delta_Z_i-1 = Delta_ZExt_i-1 + Delta_ZInt_i-1
//We have function input arguments ZExt and ZIntIc.
//In Mirtich terms these are ZAExt_i and ZAInt_i + I_i^A * c_i.
//Using the function arguments here we have:
// Delta_ZExt_i-1 = ZAExt + [I_i^A * s_i] * [-s_i^T * ZAExt]/[s_i^T * I_i^A * s_i]
// Delta_ZInt_i-1 = ZAIntIc + [I_i^A * s_i] * [Q_i - s_i^T * ZAIntIc]/[s_i^T * I_i^A * s_i]
//Isn't it odd that we add Q_i to the internal term rather than the external term?
SpatialMatrix spatialInertia;
switch (jointType)
{
case PxArticulationJointType::ePRISMATIC:
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const Cm::UnAlignedSpatialVector& sa = jointMotionMatricesW[0];
#if FEATHERSTONE_DEBUG
PxVec3 u = (jointType == PxArticulationJointType::ePRISMATIC) ? sa.bottom : sa.top;
PxMat33 armatureV = Outer(u, u) * jointTarget.armature[0];
const PxReal armature = u.dot(armatureV * u);
#endif
const Cm::SpatialVectorF& Is = jointISW[0];
//Mirtich equivalent: 1/[s_i^T * I_i^A * s_i]
PxReal invStIS;
{
const PxReal stIs = (sa.innerProduct(Is) + jointTargetArmatures[0]);
invStIS = ((stIs > 0.f) ? (1.f / stIs) : 0.f);
}
linkInvStISW.invStIs[0][0] = invStIS;
//Mirtich equivalent: [I_i^A * s_i]/[s_i^T * I_i^A * s_i]
Cm::SpatialVectorF isID = Is * invStIS;
jointDofISInvStISW[0] = isID;
//(6x1)Is = [v0, v1]; (1x6)stI = [v1, v0]
//Cm::SpatialVector stI1(Is1.angular, Is1.linear);
Cm::SpatialVectorF stI(Is.bottom, Is.top);
//Mirtich equivalent: I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A
//Note we will compute I_i^A - [I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A] later in the function.
spatialInertia = SpatialMatrix::constructSpatialMatrix(isID, stI);
//[I_i^A * s_i] * [-s_i^T * ZAExt]/[s_i^T * I_i^A * s_i]
{
const PxReal innerprod = sa.innerProduct(linkZExtW);
const PxReal diff = -innerprod;
jointDofMinusStZExtW[0] = diff;
deltaZAExtParent += isID * diff;
}
//[I_i^A * s_i] * [Q_i - s_i^T * ZAIntIc]/[s_i^T * I_i^A * s_i]
{
const PxReal innerprod = sa.innerProduct(linkZIntIcW);
const PxReal diff = jointExternalForces[0] - innerprod;
jointDofQStZIntIcW[0] = diff;
deltaZAIntIcParent += isID * diff;
}
break;
}
case PxArticulationJointType::eSPHERICAL:
{
#if FEATHERSTONE_DEBUG
//This is for debugging
Temp6x6Matrix bigInertia(articulatedInertia);
Temp6x3Matrix bigS(motionMatrix.getColumns());
Temp6x3Matrix bigIs = bigInertia * bigS;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
Cm::SpatialVectorF tempIs = bigInertia * motionMatrix[ind];
PX_ASSERT(isSpatialVectorEqual(tempIs, linkIs[ind]));
PX_ASSERT(bigIs.isColumnEqual(ind, tempIs));
}
#endif
PxMat33 D(PxIdentity);
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
#if FEATHERSTONE_DEBUG
const Cm::UnAlignedSpatialVector& sa0 = motionMatrix[ind];
const PxVec3 u = sa0.top;
PxMat33 armatureV = Outer(u, u) * jointTarget.armature[ind];
PxVec3 armatureU = armatureV * u;
#endif
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
const Cm::UnAlignedSpatialVector& sa = jointMotionMatricesW[ind2];
#if FEATHERSTONE_DEBUG
const PxVec3 u1 = sa.top;
const PxReal armature = u1.dot(armatureU);
#endif
D[ind][ind2] = sa.innerProduct(jointISW[ind]);
}
D[ind][ind] += jointTargetArmatures[ind];
}
//PxMat33 invD = SpatialMatrix::invertSym33(D);
PxMat33 invD = D.getInverse();
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
linkInvStISW.invStIs[ind][ind2] = invD[ind][ind2];
}
}
#if FEATHERSTONE_DEBUG
//debugging
Temp6x3Matrix bigIsInvD = bigIs * invD;
#endif
Cm::SpatialVectorF columns[6];
columns[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[1] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[2] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[3] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[4] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[5] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
Cm::SpatialVectorF isID(PxVec3(0.f), PxVec3(0.f));
const Cm::UnAlignedSpatialVector& sa = jointMotionMatricesW[ind];
const PxReal stZ = sa.innerProduct(linkZExtW);
const PxReal stZInt = sa.innerProduct(linkZIntIcW);
//link.qstZIc[ind] = jF[ind] - stZ;
const PxReal localQstZ = - stZ;
const PxReal localQstZInt = jointExternalForces[ind] -stZInt;
jointDofMinusStZExtW[ind] = localQstZ;
jointDofQStZIntIcW[ind] = localQstZInt;
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
const Cm::SpatialVectorF& Is = jointISW[ind2];
isID += Is * invD[ind][ind2];
}
columns[0] += isID * jointISW[ind].bottom.x;
columns[1] += isID * jointISW[ind].bottom.y;
columns[2] += isID * jointISW[ind].bottom.z;
columns[3] += isID * jointISW[ind].top.x;
columns[4] += isID * jointISW[ind].top.y;
columns[5] += isID * jointISW[ind].top.z;
jointDofISInvStISW[ind] = isID;
deltaZAExtParent += isID * localQstZ;
deltaZAIntIcParent += isID * localQstZInt;
#if FEATHERSTONE_DEBUG
const bool equal = bigIsInvD.isColumnEqual(ind, isInvD.isInvD[ind]);
PX_ASSERT(equal);
#endif
}
#if FEATHERSTONE_DEBUG
Temp6x6Matrix transpose6x6 = bigInertia.getTranspose();
#endif
spatialInertia = SpatialMatrix::constructSpatialMatrix(columns);
#if FEATHERSTONE_DEBUG
Temp6x6Matrix result = bigIsInvD * stI;
PX_ASSERT(result.isEqual(columns));
#endif
break;
}
default:
return linkArticulatedInertiaW;
}
//(I - Is*Inv(sIs)*sI)
spatialInertia = linkArticulatedInertiaW - spatialInertia;
return spatialInertia;
}
SpatialMatrix FeatherstoneArticulation::computePropagateSpatialInertia_ZA_ZIc_NonSeparated
(const PxArticulationJointType::Enum jointType, const PxU8 nbJointDofs,
const Cm::UnAlignedSpatialVector* jointMotionMatrices, const Cm::SpatialVectorF* jointIs,
const PxReal* jointTargetArmatures, const PxReal* jointExternalForces,
const SpatialMatrix& articulatedInertia,
const Cm::SpatialVectorF& ZIc,
InvStIs& invStIs, Cm::SpatialVectorF* isInvD,
PxReal* qstZIc,
Cm::SpatialVectorF& deltaZParent)
{
deltaZParent = ZIc;
// The goal is to propagate the articulated z.a force of a child link to the articulated z.a. force of its parent link.
// We will compute a term that can be added to the articulated z.a. force of the parent link.
// This function only references the child link.
// Mirtich uses the notation i for the child and i-1 for the parent.
// We have a more general configuration that allows a parent to have multiple children but in what follows "i" shall refer to the
// child and "i-1" to the parent.
// Another goal is to propagate the articulated spatial inertia from the child link to the parent link.
// We will compute a term that can be added to the articulated spatial inertia of the parent link.
// The Mirtich equivalent is:
// I_i^A - [I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A]
//The term that is to be added to the parent link has the Mirtich formulation:
// Delta_Z_i-1 = (Z_i^A + I_i^A * c_i) + [I_i^A * s_i]*[Q_i - s_i^T * (Z_i^A + I_i^A * c_i)]/[s_i^T * I_i^A * s_i]
//We have function input arguments ZIntIc.
//In Mirtich terms this is: Z_i + I_i^A * c_i.
//Using the function arguments here we have:
// Delta_Z_i-1 = ZIc + [I_i^A * s_i] * [Q_i - s_i^T * ZIc]/[s_i^T * I_i^A * s_i]
SpatialMatrix spatialInertia;
switch (jointType)
{
case PxArticulationJointType::ePRISMATIC:
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const Cm::UnAlignedSpatialVector& sa = jointMotionMatrices[0];
#if FEATHERSTONE_DEBUG
PxVec3 u = (jointType == PxArticulationJointType::ePRISMATIC) ? sa.bottom : sa.top;
PxMat33 armatureV = Outer(u, u) * jointTarget.armature[0];
const PxReal armature = u.dot(armatureV * u);
#endif
const Cm::SpatialVectorF& Is = jointIs[0];
//Mirtich equivalent: 1/[s_i^T * I_i^A * s_i]
PxReal iStIs;
{
const PxReal stIs = (sa.innerProduct(Is) + jointTargetArmatures[0]);
iStIs = (stIs > 1e-10f) ? (1.f / stIs) : 0.f;
}
invStIs.invStIs[0][0] = iStIs;
//Mirtich equivalent: [I_i^A * s_i]/[s_i^T * I_i^A * s_i]
Cm::SpatialVectorF isID = Is * iStIs;
isInvD[0] = isID;
//(6x1)Is = [v0, v1]; (1x6)stI = [v1, v0]
//Cm::SpatialVector stI1(Is1.angular, Is1.linear);
Cm::SpatialVectorF stI(Is.bottom, Is.top);
//Mirtich equivalent: I_i^A * s_i^T *[1/(s_i^T *I_i^A * s_i)] * s_i^T * I_i^A
//Note we will compute I_i^A - [I_i^A * s_i^T *[1/(s_i^T *I_i^A * s_i)] * s_i^T * I_i^A] later in the function.
spatialInertia = SpatialMatrix::constructSpatialMatrix(isID, stI);
//Mirtich equivalent: [I_i^A * s_i] * [-s_i^T * Z_i^A]/[s_i^T * I_i^A * s_i]
{
const PxReal innerProd = sa.innerProduct(ZIc);
const PxReal diff = jointExternalForces[0] - innerProd;
qstZIc[0] = diff;
deltaZParent += isID * diff;
}
break;
}
case PxArticulationJointType::eSPHERICAL:
{
#if FEATHERSTONE_DEBUG
//This is for debugging
Temp6x6Matrix bigInertia(articulatedInertia);
Temp6x3Matrix bigS(motionMatrix.getColumns());
Temp6x3Matrix bigIs = bigInertia * bigS;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
Cm::SpatialVectorF tempIs = bigInertia * motionMatrix[ind];
PX_ASSERT(isSpatialVectorEqual(tempIs, linkIs[ind]));
PX_ASSERT(bigIs.isColumnEqual(ind, tempIs));
}
#endif
PxMat33 D(PxIdentity);
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
#if FEATHERSTONE_DEBUG
const Cm::UnAlignedSpatialVector& sa0 = motionMatrix[ind];
const PxVec3 u = sa0.top;
PxMat33 armatureV = Outer(u, u) * jointTarget.armature[ind];
PxVec3 armatureU = armatureV * u;
#endif
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
const Cm::UnAlignedSpatialVector& sa = jointMotionMatrices[ind2];
#if FEATHERSTONE_DEBUG
const PxVec3 u1 = sa.top;
const PxReal armature = u1.dot(armatureU);
#endif
D[ind][ind2] = sa.innerProduct(jointIs[ind]);
}
D[ind][ind] += jointTargetArmatures[ind];
//D[ind][ind] *= 10.f;
}
PxMat33 invD = SpatialMatrix::invertSym33(D);
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
invStIs.invStIs[ind][ind2] = invD[ind][ind2];
}
}
#if FEATHERSTONE_DEBUG
//debugging
Temp6x3Matrix bigIsInvD = bigIs * invD;
#endif
Cm::SpatialVectorF columns[6];
columns[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[1] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[2] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[3] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[4] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[5] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
Cm::SpatialVectorF isID(PxVec3(0.f), PxVec3(0.f));
const Cm::UnAlignedSpatialVector& sa = jointMotionMatrices[ind];
const PxReal stZ = sa.innerProduct(ZIc);
//link.qstZIc[ind] = jF[ind] - stZ;
const PxReal localQstZ = jointExternalForces[ind] - stZ;
qstZIc[ind] = localQstZ;
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
const Cm::SpatialVectorF& Is = jointIs[ind2];
isID += Is * invD[ind][ind2];
}
columns[0] += isID * jointIs[ind].bottom.x;
columns[1] += isID * jointIs[ind].bottom.y;
columns[2] += isID * jointIs[ind].bottom.z;
columns[3] += isID * jointIs[ind].top.x;
columns[4] += isID * jointIs[ind].top.y;
columns[5] += isID * jointIs[ind].top.z;
isInvD[ind] = isID;
deltaZParent += isID * localQstZ;
#if FEATHERSTONE_DEBUG
const bool equal = bigIsInvD.isColumnEqual(ind, isInvD.isInvD[ind]);
PX_ASSERT(equal);
#endif
}
#if FEATHERSTONE_DEBUG
Temp6x6Matrix transpose6x6 = bigInertia.getTranspose();
#endif
spatialInertia = SpatialMatrix::constructSpatialMatrix(columns);
#if FEATHERSTONE_DEBUG
Temp6x6Matrix result = bigIsInvD * stI;
PX_ASSERT(result.isEqual(columns));
#endif
break;
}
default:
spatialInertia.setZero();
break;
}
//(I - Is*Inv(sIs)*sI)
spatialInertia = articulatedInertia - spatialInertia;
return spatialInertia;
}
SpatialMatrix FeatherstoneArticulation::computePropagateSpatialInertia(
const PxArticulationJointType::Enum jointType, const PxU8 nbDofs,
const SpatialMatrix& articulatedInertia, const Cm::UnAlignedSpatialVector* motionMatrices,
const Cm::SpatialVectorF* linkIs,
InvStIs& invStIs, Cm::SpatialVectorF* isInvD)
{
SpatialMatrix spatialInertia;
switch (jointType)
{
case PxArticulationJointType::ePRISMATIC:
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const Cm::UnAlignedSpatialVector& sa = motionMatrices[0];
const Cm::SpatialVectorF& Is = linkIs[0];
const PxReal stIs = sa.innerProduct(Is);
const PxReal iStIs = (stIs > 1e-10f) ? (1.f / stIs) : 0.f;
invStIs.invStIs[0][0] = iStIs;
Cm::SpatialVectorF isID = Is * iStIs;
isInvD[0] = isID;
//(6x1)Is = [v0, v1]; (1x6)stI = [v1, v0]
//Cm::SpatialVector stI1(Is1.angular, Is1.linear);
Cm::SpatialVectorF stI(Is.bottom, Is.top);
spatialInertia = SpatialMatrix::constructSpatialMatrix(isID, stI);
break;
}
case PxArticulationJointType::eSPHERICAL:
{
#if FEATHERSTONE_DEBUG
//This is for debugging
Temp6x6Matrix bigInertia(articulatedInertia);
Temp6x3Matrix bigS(motionMatrix.getColumns());
Temp6x3Matrix bigIs = bigInertia * bigS;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
Cm::SpatialVectorF tempIs = bigInertia * motionMatrix[ind];
PX_ASSERT(isSpatialVectorEqual(tempIs, linkIs[ind]));
PX_ASSERT(bigIs.isColumnEqual(ind, tempIs));
}
#endif
PxMat33 D(PxIdentity);
for (PxU8 ind = 0; ind < nbDofs; ++ind)
{
for (PxU8 ind2 = 0; ind2 < nbDofs; ++ind2)
{
const Cm::UnAlignedSpatialVector& sa = motionMatrices[ind2];
D[ind][ind2] = sa.innerProduct(linkIs[ind]);
}
}
PxMat33 invD = SpatialMatrix::invertSym33(D);
for (PxU8 ind = 0; ind < nbDofs; ++ind)
{
for (PxU8 ind2 = 0; ind2 < nbDofs; ++ind2)
{
invStIs.invStIs[ind][ind2] = invD[ind][ind2];
}
}
#if FEATHERSTONE_DEBUG
//debugging
Temp6x3Matrix bigIsInvD = bigIs * invD;
#endif
Cm::SpatialVectorF columns[6];
columns[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[1] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[2] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[3] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[4] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
columns[5] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
for (PxU8 ind = 0; ind < nbDofs; ++ind)
{
Cm::SpatialVectorF isID(PxVec3(0.f), PxVec3(0.f));
for (PxU8 ind2 = 0; ind2 < nbDofs; ++ind2)
{
const Cm::SpatialVectorF& Is = linkIs[ind2];
isID += Is * invD[ind][ind2];
}
columns[0] += isID * linkIs[ind].bottom.x;
columns[1] += isID * linkIs[ind].bottom.y;
columns[2] += isID * linkIs[ind].bottom.z;
columns[3] += isID * linkIs[ind].top.x;
columns[4] += isID * linkIs[ind].top.y;
columns[5] += isID * linkIs[ind].top.z;
isInvD[ind] = isID;
#if FEATHERSTONE_DEBUG
const bool equal = bigIsInvD.isColumnEqual(ind, isInvD.isInvD[ind]);
PX_ASSERT(equal);
#endif
}
#if FEATHERSTONE_DEBUG
Temp6x6Matrix transpose6x6 = bigInertia.getTranspose();
#endif
spatialInertia = SpatialMatrix::constructSpatialMatrix(columns);
#if FEATHERSTONE_DEBUG
Temp6x6Matrix result = bigIsInvD * stI;
PX_ASSERT(result.isEqual(columns));
#endif
break;
}
default:
spatialInertia.setZero();
break;
}
//(I - Is*Inv(sIs)*sI)
spatialInertia = articulatedInertia - spatialInertia;
return spatialInertia;
}
void FeatherstoneArticulation::computeArticulatedSpatialInertiaAndZ
(const ArticulationLink* links, const PxU32 linkCount, const PxVec3* linkRsW,
const ArticulationJointCoreData* jointData,
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const Cm::SpatialVectorF* linkCoriolisVectors, const PxReal* jointDofForces,
Cm::SpatialVectorF* jointDofISW, InvStIs* linkInvStISW, Cm::SpatialVectorF* jointDofISInvStISW, PxReal* jointDofMinusStZExtW, PxReal* jointDofQStZIntIcW,
Cm::SpatialVectorF* linkZAExtForcesW, Cm::SpatialVectorF* linkZAIntForcesW, SpatialMatrix* linkSpatialArticulatedInertiaW,
SpatialMatrix& baseInvSpatialArticulatedInertiaW)
{
const PxU32 startIndex = PxU32(linkCount - 1);
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
const ArticulationLink& link = links[linkID];
const ArticulationJointCoreData& jointDatum = jointData[linkID];
const PxU32 jointOffset = jointDatum.jointOffset;
const PxU8 nbDofs = jointDatum.dof;
for (PxU8 ind = 0; ind < nbDofs; ++ind)
{
const Cm::UnAlignedSpatialVector tmp = linkSpatialArticulatedInertiaW[linkID] * jointDofMotionMatricesW[jointOffset + ind];
jointDofISW[jointOffset + ind].top = tmp.top;
jointDofISW[jointOffset + ind].bottom = tmp.bottom;
}
//Compute the terms to accumulate on the parent's articulated z.a force and articulated spatial inertia.
Cm::SpatialVectorF deltaZAExtParent;
Cm::SpatialVectorF deltaZAIntParent;
SpatialMatrix spatialInertiaW;
{
//calculate spatial zero acceleration force, this can move out of the loop
const Cm::SpatialVectorF linkZW = linkZAExtForcesW[linkID];
const Cm::SpatialVectorF linkIcW = linkSpatialArticulatedInertiaW[linkID] * linkCoriolisVectors[linkID];
const Cm::SpatialVectorF linkZIntIcW = linkZAIntForcesW[linkID] + linkIcW;
//(I - Is*Inv(sIs)*sI)
//KS - we also bury Articulated ZA force and ZIc force computation in here because that saves
//us some round-trips to memory!
spatialInertiaW =
computePropagateSpatialInertia_ZA_ZIc(
PxArticulationJointType::Enum(link.inboundJoint->jointType), jointDatum.dof,
&jointDofMotionMatricesW[jointOffset], &jointDofISW[jointOffset],
&jointDatum.armature[0], &jointDofForces[jointOffset],
linkSpatialArticulatedInertiaW[linkID],
linkZW, linkZIntIcW,
linkInvStISW[linkID], &jointDofISInvStISW[jointOffset],
&jointDofMinusStZExtW[jointOffset], &jointDofQStZIntIcW[jointOffset],
deltaZAExtParent, deltaZAIntParent);
}
//Accumulate the spatial inertia on the parent link.
{
//transform spatial inertia into parent space
FeatherstoneArticulation::translateInertia(constructSkewSymmetricMatrix(linkRsW[linkID]), spatialInertiaW);
// Make sure we do not propagate up negative inertias around the principal inertial axes
// due to numerical rounding errors
const PxReal minPropagatedInertia = 0.f;
spatialInertiaW.bottomLeft.column0.x = PxMax(minPropagatedInertia, spatialInertiaW.bottomLeft.column0.x);
spatialInertiaW.bottomLeft.column1.y = PxMax(minPropagatedInertia, spatialInertiaW.bottomLeft.column1.y);
spatialInertiaW.bottomLeft.column2.z = PxMax(minPropagatedInertia, spatialInertiaW.bottomLeft.column2.z);
linkSpatialArticulatedInertiaW[link.parent] += spatialInertiaW;
}
//Accumulate the articulated z.a force on the parent link.
{
Cm::SpatialVectorF translatedZA = FeatherstoneArticulation::translateSpatialVector(linkRsW[linkID], deltaZAExtParent);
Cm::SpatialVectorF translatedZAInt = FeatherstoneArticulation::translateSpatialVector(linkRsW[linkID], deltaZAIntParent);
linkZAExtForcesW[link.parent] += translatedZA;
linkZAIntForcesW[link.parent] += translatedZAInt;
}
}
//cache base link inverse spatial inertia
linkSpatialArticulatedInertiaW[0].invertInertiaV(baseInvSpatialArticulatedInertiaW);
}
void FeatherstoneArticulation::computeArticulatedSpatialInertiaAndZ_NonSeparated(ArticulationData& data, ScratchData& scratchData)
{
const ArticulationLink* links = data.getLinks();
ArticulationJointCoreData* jointData = data.getJointData();
SpatialMatrix* spatialArticulatedInertia = data.getWorldSpatialArticulatedInertia();
const Cm::UnAlignedSpatialVector* motionMatrix = data.getWorldMotionMatrix();
Cm::SpatialVectorF* Is = data.getIsW();
InvStIs* invStIs = data.getInvStIS();
Cm::SpatialVectorF* IsInvDW = data.getISInvStIS();
PxReal* qstZIc = data.getQstZIc();
SpatialMatrix& baseInvSpatialArticulatedInertia = data.getBaseInvSpatialArticulatedInertiaW();
const PxU32 linkCount = data.getLinkCount();
const PxU32 startIndex = PxU32(linkCount - 1);
Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors;
Cm::SpatialVectorF* articulatedZA = scratchData.spatialZAVectors;
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationJointCoreData& jointDatum = jointData[linkID];
const PxU32 jointOffset = jointDatum.jointOffset;
const PxU8 nbDofs = jointDatum.dof;
for (PxU8 ind = 0; ind < nbDofs; ++ind)
{
const Cm::UnAlignedSpatialVector tmp = spatialArticulatedInertia[linkID] * motionMatrix[jointOffset + ind];
Is[jointOffset + ind].top = tmp.top;
Is[jointOffset + ind].bottom = tmp.bottom;
}
//calculate spatial zero acceleration force, this can move out of the loop
Cm::SpatialVectorF deltaZParent;
SpatialMatrix spatialInertiaW;
{
Cm::SpatialVectorF Ic = spatialArticulatedInertia[linkID] * coriolisVectors[linkID];
Cm::SpatialVectorF Z = articulatedZA[linkID] + Ic;
//(I - Is*Inv(sIs)*sI)
//KS - we also bury Articulated ZA force and ZIc force computation in here because that saves
//us some round-trips to memory!
spatialInertiaW = computePropagateSpatialInertia_ZA_ZIc_NonSeparated(
PxArticulationJointType::Enum(link.inboundJoint->jointType), jointDatum.dof,
&motionMatrix[jointDatum.jointOffset], &Is[jointDatum.jointOffset],
&jointDatum.armature[0], &scratchData.jointForces[jointDatum.jointOffset], // AD what's the difference between the scratch and the articulation data?
spatialArticulatedInertia[linkID],
Z,
invStIs[linkID], &IsInvDW[jointDatum.jointOffset],
&qstZIc[jointDatum.jointOffset],
deltaZParent);
}
//transform spatial inertia into parent space
FeatherstoneArticulation::translateInertia(constructSkewSymmetricMatrix(data.getRw(linkID)), spatialInertiaW);
spatialArticulatedInertia[link.parent] += spatialInertiaW;
Cm::SpatialVectorF translatedZA = FeatherstoneArticulation::translateSpatialVector(data.getRw(linkID), deltaZParent);
articulatedZA[link.parent] += translatedZA;
}
//cache base link inverse spatial inertia
spatialArticulatedInertia[0].invertInertiaV(baseInvSpatialArticulatedInertia);
}
void FeatherstoneArticulation::computeArticulatedSpatialInertia(ArticulationData& data)
{
const ArticulationLink* links = data.getLinks();
const ArticulationJointCoreData* jointData = data.getJointData();
SpatialMatrix* spatialArticulatedInertia = data.getWorldSpatialArticulatedInertia();
const Cm::UnAlignedSpatialVector* motionMatrix = data.getWorldMotionMatrix();
Cm::SpatialVectorF* Is = data.getIsW();
InvStIs* invStIs = data.getInvStIS();
Cm::SpatialVectorF* IsInvDW = data.getISInvStIS();
SpatialMatrix& baseInvSpatialArticulatedInertia = data.getBaseInvSpatialArticulatedInertiaW();
const PxU32 linkCount = data.getLinkCount();
const PxU32 startIndex = PxU32(linkCount - 1);
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
const ArticulationLink& link = links[linkID];
const ArticulationJointCoreData& jointDatum = jointData[linkID];
const PxU32 jointOffset = jointDatum.jointOffset;
const PxU8 nbDofs = jointDatum.dof;
for (PxU8 ind = 0; ind < nbDofs; ++ind)
{
const Cm::UnAlignedSpatialVector tmp = spatialArticulatedInertia[linkID] * motionMatrix[jointOffset + ind];
Is[jointOffset + ind].top = tmp.top;
Is[jointOffset + ind].bottom = tmp.bottom;
}
//(I - Is*Inv(sIs)*sI)
//KS - we also bury Articulated ZA force and ZIc force computation in here because that saves
//us some round-trips to memory!
SpatialMatrix spatialInertiaW = computePropagateSpatialInertia(
PxArticulationJointType::Enum(link.inboundJoint->jointType),
jointDatum.dof, spatialArticulatedInertia[linkID], &motionMatrix[jointOffset],
&Is[jointOffset],
invStIs[linkID], &IsInvDW[jointOffset]);
//transform spatial inertia into parent space
FeatherstoneArticulation::translateInertia(constructSkewSymmetricMatrix(data.getRw(linkID)), spatialInertiaW);
spatialArticulatedInertia[link.parent] += spatialInertiaW;
}
//cache base link inverse spatial inertia
spatialArticulatedInertia[0].invertInertiaV(baseInvSpatialArticulatedInertia);
}
void FeatherstoneArticulation::computeArticulatedResponseMatrix
(const PxArticulationFlags& articulationFlags, const PxU32 linkCount,
const ArticulationJointCoreData* jointData,
const SpatialMatrix& baseInvArticulatedInertiaW,
const PxVec3* linkRsW, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const Cm::SpatialVectorF* jointDofISW, const InvStIs* linkInvStISW, const Cm::SpatialVectorF* jointDofIsInvDW,
ArticulationLink* links, SpatialImpulseResponseMatrix* linkResponsesW)
{
//PX_PROFILE_ZONE("ComputeResponseMatrix", 0);
//We can work out impulse response vectors by propagating an impulse to the root link, then back down to the child link using existing data.
//Alternatively, we can compute an impulse response matrix, which is a vector of 6x6 matrices, which can be multiplied by the impulse vector to
//compute the response. This can be stored in world space, saving transforms. It can also be computed incrementally, meaning it should not be
//dramatically more expensive than propagating the impulse for a single constraint. Furthermore, this will allow us to rapidly compute the
//impulse response with the TGS solver allowing us to improve quality of equality positional constraints by properly reflecting non-linear motion
//of the articulation rather than approximating it with linear projections.
//The input expected is a local-space impulse and the output is a local-space impulse response vector
if (articulationFlags & PxArticulationFlag::eFIX_BASE)
{
//Fixed base, so response is zero
PxMemZero(linkResponsesW, sizeof(SpatialImpulseResponseMatrix));
}
else
{
//Compute impulse response matrix. Compute the impulse response of unit responses on all 6 axes...
PxMat33 bottomRight = baseInvArticulatedInertiaW.getBottomRight();
linkResponsesW[0].rows[0] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topLeft.column0, baseInvArticulatedInertiaW.bottomLeft.column0);
linkResponsesW[0].rows[1] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topLeft.column1, baseInvArticulatedInertiaW.bottomLeft.column1);
linkResponsesW[0].rows[2] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topLeft.column2, baseInvArticulatedInertiaW.bottomLeft.column2);
linkResponsesW[0].rows[3] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topRight.column0, bottomRight.column0);
linkResponsesW[0].rows[4] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topRight.column1, bottomRight.column1);
linkResponsesW[0].rows[5] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topRight.column2, bottomRight.column2);
links[0].cfm *= PxMax(linkResponsesW[0].rows[0].bottom.x, PxMax(linkResponsesW[0].rows[1].bottom.y, linkResponsesW[0].rows[2].bottom.z));
}
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
PxVec3 offset = linkRsW[linkID];
const PxU32 jointOffset = jointData[linkID].jointOffset;
const PxU8 dofCount = jointData[linkID].dof;
for (PxU32 i = 0; i < 6; ++i)
{
//Impulse has to be negated!
Cm::SpatialVectorF vec = Cm::SpatialVectorF::Zero();
vec[i] = 1.f;
Cm::SpatialVectorF temp = -vec;
ArticulationLink& tLink = links[linkID];
//(1) Propagate impulse to parent
PxReal qstZ[3] = { 0.f, 0.f, 0.f };
Cm::SpatialVectorF Zp = FeatherstoneArticulation::propagateImpulseW(
offset,
temp,
&jointDofIsInvDW[jointOffset],
&jointDofMotionMatricesW[jointOffset], dofCount,
qstZ); //(2) Get deltaV response for parent
Cm::SpatialVectorF zR = -linkResponsesW[tLink.parent].getResponse(Zp);
const Cm::SpatialVectorF deltaV =
propagateAccelerationW(offset, linkInvStISW[linkID],
&jointDofMotionMatricesW[jointOffset], zR, dofCount, &jointDofISW[jointOffset], qstZ);
//Store in local space (required for propagation
linkResponsesW[linkID].rows[i] = deltaV;
}
links[linkID].cfm *= PxMax(linkResponsesW[linkID].rows[0].bottom.x, PxMax(linkResponsesW[linkID].rows[1].bottom.y, linkResponsesW[linkID].rows[2].bottom.z));
}
}
void FeatherstoneArticulation::computeArticulatedSpatialZ(ArticulationData& data, ScratchData& scratchData)
{
ArticulationLink* links = data.getLinks();
ArticulationJointCoreData* jointData = data.getJointData();
const PxU32 linkCount = data.getLinkCount();
const PxU32 startIndex = PxU32(linkCount - 1);
Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors;
Cm::SpatialVectorF* articulatedZA = scratchData.spatialZAVectors;
PxReal* jointForces = scratchData.jointForces;
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
ArticulationLink& link = links[linkID];
ArticulationJointCoreData& jointDatum = jointData[linkID];
//calculate spatial zero acceleration force, this can move out of the loop
Cm::SpatialVectorF Ic = data.mWorldSpatialArticulatedInertia[linkID] * coriolisVectors[linkID];
Cm::SpatialVectorF ZIc = articulatedZA[linkID] + Ic;
const PxReal* jF = &jointForces[jointDatum.jointOffset];
Cm::SpatialVectorF ZA = ZIc;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
const Cm::UnAlignedSpatialVector& sa = data.mWorldMotionMatrix[jointDatum.jointOffset + ind];
const PxReal stZ = sa.innerProduct(ZIc);
//link.qstZIc[ind] = jF[ind] - stZ;
const PxReal qstZic = jF[ind] - stZ;
data.qstZIc[jointDatum.jointOffset + ind] = qstZic;
PX_ASSERT(PxIsFinite(qstZic));
ZA += data.mISInvStIS[jointDatum.jointOffset + ind] * qstZic;
}
//accumulate childen's articulated zero acceleration force to parent's articulated zero acceleration
articulatedZA[link.parent] += FeatherstoneArticulation::translateSpatialVector(data.getRw(linkID), ZA);
}
}
void FeatherstoneArticulation::computeJointSpaceJacobians(ArticulationData& data)
{
//PX_PROFILE_ZONE("computeJointSpaceJacobians", 0);
const PxU32 linkCount = data.getLinkCount();
const PxU32 dofCount = data.getDofs();
PxTransform* trans = data.getAccumulatedPoses();
Cm::SpatialVectorF* jointSpaceJacobians = data.getJointSpaceJacobians();
Dy::ArticulationLink* links = data.mLinks;
Dy::ArticulationJointCoreData* jointData = data.mJointData;
Cm::UnAlignedSpatialVector* worldMotionMatrix = data.mWorldMotionMatrix.begin();
for (PxU32 linkID = 1; linkID < linkCount; linkID++)
{
const PxTransform pose = trans[linkID];
Cm::SpatialVectorF* myJacobian = &jointSpaceJacobians[linkID*dofCount];
const PxU32 lastDof = jointData[linkID].jointOffset + jointData[linkID].dof;
PxMemZero(myJacobian, sizeof(Cm::SpatialVectorF)*lastDof);
PxU32 link = linkID;
while (link != 0)
{
PxU32 parent = links[link].parent;
const Dy::ArticulationJointCoreData& jData = jointData[link];
const PxTransform parentPose = trans[link];
PxVec3 rw = parentPose.p - pose.p;
const PxU32 jointOffset = jData.jointOffset;
const PxU32 dofs = jData.dof;
Cm::UnAlignedSpatialVector* motionMatrix = &worldMotionMatrix[jointOffset];
for (PxU32 i = 0; i < dofs; ++i)
{
myJacobian[jointOffset + i].top = motionMatrix[i].top;
myJacobian[jointOffset + i].bottom = motionMatrix[i].bottom + rw.cross(motionMatrix[i].top);
}
link = parent;
}
#if 0
//Verify the jacobian...
Cm::SpatialVectorF velocity = FeatherstoneArticulation::translateSpatialVector((trans[0].p - trans[linkID].p), data.mMotionVelocities[0]);
PxReal* jointVelocity = data.getJointVelocities();
//KS - a bunch of these dofs can be skipped, we just need to follow path-to-root. However, that may be more expensive than
//just doing the full multiplication. Let's see how expensive it is now...
for (PxU32 i = 0; i < lastDof; ++i)
{
velocity += myJacobian[i] * jointVelocity[i];
}
int bob = 0;
PX_UNUSED(bob);
#endif
}
}
void FeatherstoneArticulation::computeJointAccelerationW(const PxU8 nbJointDofs,
const Cm::SpatialVectorF& parentMotionAcceleration, const Cm::SpatialVectorF* jointDofISW, const InvStIs& linkInvStISW,
const PxReal* jointDofQStZIcW,
PxReal* jointAcceleration)
{
PxReal tJAccel[6];
//Mirtich equivalent: Q_i - (s_i^T * I_i^A * a_i-1) - s_i^T * (Z_i^A + I_i^A * c_i)
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
//stI * pAcceleration
const PxReal temp = jointDofISW[ind].innerProduct(parentMotionAcceleration);
tJAccel[ind] = (jointDofQStZIcW[ind] - temp);
}
//calculate jointAcceleration
//Mirtich equivalent: [Q_i - (s_i^T * I_i^A * a_i-1) - s_i^T * (Z_i^A + I_i^A * c_i)]/[s_i^T * I_i^A * s_i]
for (PxU32 ind = 0; ind < nbJointDofs; ++ind)
{
jointAcceleration[ind] = 0.f;
for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2)
{
jointAcceleration[ind] += linkInvStISW.invStIs[ind2][ind] * tJAccel[ind2];
}
//PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000);
}
}
void FeatherstoneArticulation::computeLinkAcceleration
(const bool doIC, const PxReal dt,
const bool fixBase,
const ArticulationLink* links, const PxU32 linkCount, const ArticulationJointCoreData* jointDatas,
const Cm::SpatialVectorF* linkSpatialZAForces, const Cm::SpatialVectorF* linkCoriolisForces, const PxVec3* linkRws,
const Cm::UnAlignedSpatialVector* jointDofMotionMatrices,
const SpatialMatrix& baseInvSpatialArticulatedInertiaW,
const InvStIs* linkInvStIs,
const Cm::SpatialVectorF* jointDofIsWs, const PxReal* jointDofQstZics,
Cm::SpatialVectorF* linkMotionAccelerations, Cm::SpatialVectorF* linkMotionVelocities,
PxReal* jointDofAccelerations, PxReal* jointDofVelocities, PxReal* jointDofNewVelocities)
{
//we have initialized motionVelocity and motionAcceleration to be zero in the root link if
//fix based flag is raised
if (!fixBase)
{
//ArticulationLinkData& baseLinkDatum = data.getLinkData(0);
#if FEATHERSTONE_DEBUG
SpatialMatrix result = invInertia * baseLinkDatum.spatialArticulatedInertia;
bool isIdentity = result.isIdentity();
PX_ASSERT(isIdentity);
PX_UNUSED(isIdentity);
#endif
//ArticulationLink& baseLink = data.getLink(0);
//const PxTransform& body2World = baseLink.bodyCore->body2World;
Cm::SpatialVectorF accel = -(baseInvSpatialArticulatedInertiaW * linkSpatialZAForces[0]);
linkMotionAccelerations[0] = accel;
Cm::SpatialVectorF deltaV = accel * dt;
linkMotionVelocities[0] += deltaV;
}
#if FEATHERSTONE_DEBUG
else
{
PX_ASSERT(isSpatialVectorZero(motionAccelerations[0]));
PX_ASSERT(isSpatialVectorZero(motionVelocities[0]));
}
#endif
/*PxReal* jointAccelerations = data.getJointAccelerations();
PxReal* jointVelocities = data.getJointVelocities();
PxReal* jointPositions = data.getJointPositions();*/
//printf("===========================\n");
//calculate acceleration
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationJointCore& joint = *link.inboundJoint;
PX_UNUSED(joint);
Cm::SpatialVectorF pMotionAcceleration = FeatherstoneArticulation::translateSpatialVector(-linkRws[linkID], linkMotionAccelerations[link.parent]);
const ArticulationJointCoreData& jointDatum = jointDatas[linkID];
//calculate jointAcceleration
PxReal* jA = &jointDofAccelerations[jointDatum.jointOffset];
const InvStIs& invStIs = linkInvStIs[linkID];
computeJointAccelerationW(jointDatum.dof, pMotionAcceleration, &jointDofIsWs[jointDatum.jointOffset], invStIs,
&jointDofQstZics[jointDatum.jointOffset], jA);
Cm::SpatialVectorF motionAcceleration = pMotionAcceleration;
if (doIC)
motionAcceleration += linkCoriolisForces[linkID];
PxReal* jointVelocity = &jointDofVelocities[jointDatum.jointOffset];
PxReal* jointNewVelocity = &jointDofNewVelocities[jointDatum.jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
const PxReal accel = jA[ind];
PxReal jVel = jointVelocity[ind] + accel * dt;
jointVelocity[ind] = jVel;
jointNewVelocity[ind] = jVel;
motionAcceleration.top += jointDofMotionMatrices[jointDatum.jointOffset + ind].top * accel;
motionAcceleration.bottom += jointDofMotionMatrices[jointDatum.jointOffset + ind].bottom * accel;
}
//KS - can we just work out velocities by projecting out the joint velocities instead of accumulating all this?
linkMotionAccelerations[linkID] = motionAcceleration;
PX_ASSERT(linkMotionAccelerations[linkID].isFinite());
linkMotionVelocities[linkID] += motionAcceleration * dt;
/*Cm::SpatialVectorF spatialForce = mArticulationData.mWorldSpatialArticulatedInertia[linkID] * motionAcceleration;
Cm::SpatialVectorF zaForce = -spatialZAForces[linkID];
int bob = 0;
PX_UNUSED(bob);*/
}
}
void FeatherstoneArticulation::computeLinkInternalAcceleration
( const PxReal dt,
const bool fixBase,
const PxVec3& com, const PxReal invSumMass, const PxReal maxLinearVelocity, const PxReal maxAngularVelocity, const PxMat33* linkIsolatedSpatialArticulatedInertiasW,
const SpatialMatrix& baseInvSpatialArticulatedInertiaW,
const ArticulationLink* links, const PxU32 linkCount,
const PxReal* linkMasses, const PxVec3* linkRsW, const PxTransform* linkAccumulatedPosesW,
const Cm::SpatialVectorF* linkSpatialZAIntForcesW, const Cm::SpatialVectorF* linkCoriolisVectorsW,
const ArticulationJointCoreData* jointDatas, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const InvStIs* linkInvStISW, const Cm::SpatialVectorF* jointDofISW, const PxReal* jointDofQStZIntIcW,
Cm::SpatialVectorF* linkMotionAccelerationsW, Cm::SpatialVectorF* linkMotionIntAccelerationsW, Cm::SpatialVectorF* linkMotionVelocitiesW,
PxReal* jointDofAccelerations, PxReal* jointDofInternalAccelerations, PxReal* jointDofVelocities, PxReal* jointDofNewVelocities)
{
//we have initialized motionVelocity and motionAcceleration to be zero in the root link if
//fix based flag is raised
Cm::SpatialVectorF momentum0(PxVec3(0,0,0), PxVec3(0,0,0));
PxVec3 rootVel(PxZero);
{
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const Cm::SpatialVectorF& vel = linkMotionVelocitiesW[linkID];
const PxReal mass = linkMasses[linkID];
momentum0.top += vel.bottom*mass;
}
rootVel = momentum0.top * invSumMass;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const PxReal mass = linkMasses[linkID];
const Cm::SpatialVectorF& vel = linkMotionVelocitiesW[linkID];
const PxVec3 offsetMass = (linkAccumulatedPosesW[linkID].p - com)*mass;
const PxVec3 angMom = linkIsolatedSpatialArticulatedInertiasW[linkID] * vel.top + offsetMass.cross(linkMotionVelocitiesW[linkID].bottom - rootVel);
momentum0.bottom += angMom;
}
}
if (!fixBase)
{
//ArticulationLinkData& baseLinkDatum = data.getLinkData(0);
#if FEATHERSTONE_DEBUG
SpatialMatrix result = invInertia * baseLinkDatum.spatialArticulatedInertia;
bool isIdentity = result.isIdentity();
PX_ASSERT(isIdentity);
PX_UNUSED(isIdentity);
#endif
//ArticulationLink& baseLink = data.getLink(0);
//const PxTransform& body2World = baseLink.bodyCore->body2World;
const Cm::SpatialVectorF accel = -(baseInvSpatialArticulatedInertiaW * linkSpatialZAIntForcesW[0]);
linkMotionIntAccelerationsW[0] = accel;
linkMotionAccelerationsW[0] += accel;
const Cm::SpatialVectorF deltaV = accel * dt;
linkMotionVelocitiesW[0] += deltaV;
}
else
{
linkMotionIntAccelerationsW[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
}
//printf("===========================\n");
//calculate acceleration
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationJointCore& joint = *link.inboundJoint;
PX_UNUSED(joint);
const Cm::SpatialVectorF pMotionAcceleration = FeatherstoneArticulation::translateSpatialVector(-linkRsW[linkID], linkMotionIntAccelerationsW[link.parent]);
const ArticulationJointCoreData& jointDatum = jointDatas[linkID];
//calculate jointAcceleration
PxReal* jIntAccel = &jointDofInternalAccelerations[jointDatum.jointOffset];
computeJointAccelerationW(jointDatum.dof, pMotionAcceleration, &jointDofISW[jointDatum.jointOffset], linkInvStISW[linkID],
&jointDofQStZIntIcW[jointDatum.jointOffset], jIntAccel);
//printf("jA %f\n", jA[0]);
//KS - TODO - separate integration of coriolis vectors!
Cm::SpatialVectorF motionAcceleration = pMotionAcceleration + linkCoriolisVectorsW[linkID];
PxReal* jointVelocity = &jointDofVelocities[jointDatum.jointOffset];
PxReal* jointNewVelocity = &jointDofNewVelocities[jointDatum.jointOffset];
PxReal* jA = &jointDofAccelerations[jointDatum.jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
const PxReal accel = jIntAccel[ind];
PxReal jVel = jointVelocity[ind] + accel * dt;
jointVelocity[ind] = jVel;
jointNewVelocity[ind] = jVel;
motionAcceleration.top += jointDofMotionMatricesW[jointDatum.jointOffset + ind].top * accel;
motionAcceleration.bottom += jointDofMotionMatricesW[jointDatum.jointOffset + ind].bottom * accel;
jA[ind] += accel;
}
//KS - can we just work out velocities by projecting out the joint velocities instead of accumulating all this?
linkMotionIntAccelerationsW[linkID] = motionAcceleration;
linkMotionAccelerationsW[linkID] += motionAcceleration;
PX_ASSERT(linkMotionAccelerationsW[linkID].isFinite());
Cm::SpatialVectorF velDelta = (motionAcceleration)* dt;
linkMotionVelocitiesW[linkID] += velDelta;
}
if (!fixBase)
{
PxVec3 angMomentum1(0.f);
PxMat33 inertia(PxZero);
PxVec3 sumLinMomentum(0.f);
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
PxReal mass = linkMasses[linkID];
sumLinMomentum += linkMotionVelocitiesW[linkID].bottom * mass;
}
rootVel = sumLinMomentum * invSumMass;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
PxReal mass = linkMasses[linkID];
const PxVec3 offset = linkAccumulatedPosesW[linkID].p - com;
inertia += translateInertia(linkIsolatedSpatialArticulatedInertiasW[linkID], mass, offset);
angMomentum1 += linkIsolatedSpatialArticulatedInertiasW[linkID] * linkMotionVelocitiesW[linkID].top
+ offset.cross(linkMotionVelocitiesW[linkID].bottom - rootVel) * mass;
}
PxMat33 invCompoundInertia = inertia.getInverse();
PxReal denom0 = angMomentum1.magnitude();
PxReal num = momentum0.bottom.magnitude();
PxReal angRatio = denom0 == 0.f ? 1.f : num / denom0;
PxVec3 deltaAngMom = angMomentum1 * (angRatio - 1.f);
PxVec3 deltaAng = invCompoundInertia * deltaAngMom;
if (maxAngularVelocity > 0.0f)
{
const PxReal maxAng = maxAngularVelocity;
const PxReal maxAngSq = maxAng * maxAng;
PxVec3 ang = (invCompoundInertia * angMomentum1) + deltaAng;
if (ang.magnitudeSquared() > maxAngSq)
{
PxReal ratio = maxAng / ang.magnitude();
deltaAng += (ratio - 1.f)*ang;
}
}
#if 1
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const PxVec3 offset = (linkAccumulatedPosesW[linkID].p - com);
Cm::SpatialVectorF velChange(deltaAng, -offset.cross(deltaAng));
linkMotionVelocitiesW[linkID] += velChange;
const PxReal mass = linkMasses[linkID];
sumLinMomentum += velChange.bottom * mass;
}
#else
motionVelocities[0].top += deltaAng;
motionAccelerations[0] = Cm::SpatialVectorF(deltaAng, PxVec3(0.f));
//sumLinMomentum = motionVelocities[0].bottom * data.mMasses[0];
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
Cm::SpatialVectorF velChange = Dy::FeatherstoneArticulation::translateSpatialVector(-data.getRw(linkID), motionAccelerations[data.getLink(linkID).parent]);
motionVelocities[linkID] += velChange;
motionAccelerations[linkID] = velChange;
PxReal mass = data.mMasses[linkID];
//sumLinMomentum += motionVelocities[linkID].bottom * mass;
sumLinMomentum += velChange.bottom * mass;
}
#endif
#if 0
PxReal denom1 = sumLinMomentum.magnitude();
PxReal linRatio = PxMin(10.f, denom1 == 0.f ? 1.f : momentum0.top.magnitude() / denom1);
PxVec3 deltaLinMom = sumLinMomentum * (linRatio - 1.f);
#else
PxVec3 deltaLinMom = momentum0.top - sumLinMomentum;
#endif
PxVec3 deltaLin = deltaLinMom * invSumMass;
if (maxLinearVelocity >= 0.0f)
{
const PxReal maxLin = maxLinearVelocity;
const PxReal maxLinSq = maxLin * maxLin;
PxVec3 lin = (sumLinMomentum * invSumMass) + deltaLin;
if (lin.magnitudeSquared() > maxLinSq)
{
PxReal ratio = maxLin / lin.magnitude();
deltaLin += (ratio - 1.f)*lin;
}
}
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
linkMotionVelocitiesW[linkID].bottom += deltaLin;
}
#if PX_DEBUG && 0
const bool validateMomentum = false;
if (validateMomentum)
{
Cm::SpatialVectorF momentum2(PxVec3(0.f), PxVec3(0.f));
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const PxReal mass = data.mMasses[linkID];
momentum2.top += motionVelocities[linkID].bottom * mass;
}
rootVel = momentum2.top * sumInvMass;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const PxReal mass = data.mMasses[linkID];
const PxVec3 angMom = data.mWorldIsolatedSpatialArticulatedInertia[linkID] * motionVelocities[linkID].top +
(data.getAccumulatedPoses()[linkID].p - COM).cross(motionVelocities[linkID].bottom - rootVel) * mass;
momentum2.bottom += angMom;
}
static PxU32 count = 0;
count++;
printf("LinMom0 = %f, LinMom1 = %f, LinMom2 = %f\n", momentum0.top.magnitude(), sumLinMomentum.magnitude(), momentum2.top.magnitude());
printf("AngMom0 = %f, AngMom1 = %f, AngMom2 = %f\n", momentum0.bottom.magnitude(), angMomentum1.magnitude(), momentum2.bottom.magnitude());
printf("%i: Angular Momentum0 (%f, %f, %f), angularMomentum1 (%f, %f, %f), angularMomFinal (%f, %f, %f)\n",
count, momentum0.bottom.x, momentum0.bottom.y, momentum0.bottom.z, angMomentum1.x, angMomentum1.y, angMomentum1.z,
momentum2.bottom.x, momentum2.bottom.y, momentum2.bottom.z);
}
#endif
}
}
void FeatherstoneArticulation::computeLinkIncomingJointForce(
const PxU32 linkCount,
const Cm::SpatialVectorF* linkZAForcesExtW, const Cm::SpatialVectorF* linkZAForcesIntW,
const Cm::SpatialVectorF* linkMotionAccelerationsW, const SpatialMatrix* linkSpatialInertiasW,
Cm::SpatialVectorF* linkIncomingJointForces)
{
linkIncomingJointForces[0] = Cm::SpatialVectorF(PxVec3(0,0,0), PxVec3(0,0,0));
for(PxU32 i = 1; i < linkCount; i++)
{
linkIncomingJointForces[i] = linkSpatialInertiasW[i]*linkMotionAccelerationsW[i] + (linkZAForcesExtW[i] + linkZAForcesIntW[i]);
}
}
void FeatherstoneArticulation::computeJointTransmittedFrictionForce(
ArticulationData& data, ScratchData& scratchData, Cm::SpatialVectorF* /*Z*/, Cm::SpatialVectorF* /*DeltaV*/)
{
//const PxU32 linkCount = data.getLinkCount();
const PxU32 startIndex = data.getLinkCount() - 1;
//const PxReal frictionCoefficient =30.5f;
Cm::SpatialVectorF* transmittedForce = scratchData.spatialZAVectors;
for (PxU32 linkID = startIndex; linkID > 1; --linkID)
{
const ArticulationLink& link = data.getLink(linkID);
//joint force transmitted from parent to child
//transmittedForce[link.parent] += data.mChildToParent[linkID] * transmittedForce[linkID];
transmittedForce[link.parent] += FeatherstoneArticulation::translateSpatialVector(data.getRw(linkID), transmittedForce[linkID]);
}
transmittedForce[0] = Cm::SpatialVectorF::Zero();
//const PxReal dt = data.getDt();
//for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
//{
// //ArticulationLink& link = data.getLink(linkID);
// //ArticulationLinkData& linkDatum = data.getLinkData(linkID);
// transmittedForce[linkID] = transmittedForce[linkID] * (frictionCoefficient) * dt;
// //transmittedForce[link.parent] -= linkDatum.childToParent * transmittedForce[linkID];
//}
//
//applyImpulses(transmittedForce, Z, DeltaV);
//PxReal* deltaV = data.getJointDeltaVelocities();
//PxReal* jointV = data.getJointVelocities();
//for (PxU32 linkID = 1; linkID < data.getLinkCount(); ++linkID)
//{
// ArticulationJointCoreData& tJointDatum = data.getJointData()[linkID];
// for (PxU32 i = 0; i < tJointDatum.dof; ++i)
// {
// jointV[i + tJointDatum.jointOffset] += deltaV[i + tJointDatum.jointOffset];
// deltaV[i + tJointDatum.jointOffset] = 0.f;
// }
//}
}
//void FeatherstoneArticulation::computeJointFriction(ArticulationData& data,
// ScratchData& scratchData)
//{
// PX_UNUSED(scratchData);
// const PxU32 linkCount = data.getLinkCount();
// PxReal* jointForces = scratchData.jointForces;
// PxReal* jointFrictionForces = data.getJointFrictionForces();
// PxReal* jointVelocities = data.getJointVelocities();
// const PxReal coefficient = 0.5f;
// for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
// {
// ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
// //compute generalized force
// PxReal* jFs = &jointForces[jointDatum.jointOffset];
// PxReal* jVs = &jointVelocities[jointDatum.jointOffset];
// PxReal* jFFs = &jointFrictionForces[jointDatum.jointOffset];
// for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
// {
// PxReal sign = jVs[ind] > 0 ? -1.f : 1.f;
// jFFs[ind] = coefficient * PxAbs(jFs[ind]) *sign;
// //jFFs[ind] = coefficient * jVs[ind];
// }
// }
//}
// TODO AD: the following two functions could be just one.
PxU32 FeatherstoneArticulation::computeUnconstrainedVelocities(
const ArticulationSolverDesc& desc,
PxReal dt,
PxU32& acCount,
const PxVec3& gravity,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV,
const PxReal invLengthScale)
{
FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation);
ArticulationData& data = articulation->mArticulationData;
data.setDt(dt);
// AD: would be nicer to just have a list of all dirty articulations and process that one.
// but that means we need to add a task dependency before because we'll get problems with multithreading
// if we don't process the same lists.
if (articulation->mJcalcDirty)
{
articulation->mJcalcDirty = false;
articulation->jcalc(data);
}
articulation->computeUnconstrainedVelocitiesInternal(gravity, Z, deltaV, invLengthScale);
const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
return articulation->setupSolverConstraints(data.getLinks(), data.getLinkCount(), fixBase, data, Z, acCount);
}
void FeatherstoneArticulation::computeUnconstrainedVelocitiesTGS(
const ArticulationSolverDesc& desc,
PxReal dt, const PxVec3& gravity,
PxU64 contextID, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV,
const PxReal invLengthScale)
{
PX_UNUSED(contextID);
FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation);
ArticulationData& data = articulation->mArticulationData;
data.setDt(dt);
// AD: would be nicer to just have a list of all dirty articulations and process that one.
// but that means we need to add a task dependency before because we'll get problems with multithreading
// if we don't process the same lists.
if (articulation->mJcalcDirty)
{
articulation->mJcalcDirty = false;
articulation->jcalc(data);
}
articulation->computeUnconstrainedVelocitiesInternal(gravity, Z, DeltaV, invLengthScale);
}
//void FeatherstoneArticulation::computeCounteractJointForce(const ArticulationSolverDesc& desc, ScratchData& /*scratchData*/, const PxVec3& gravity)
//{
// const bool fixBase = mArticulationData.getCore()->flags & PxArticulationFlag::eFIX_BASE;
// const PxU32 linkCount = mArticulationData.getLinkCount();
// const PxU32 totalDofs = mArticulationData.getDofs();
// //common data
// computeRelativeTransform(mArticulationData);
// jcalc(mArticulationData);
// computeSpatialInertia(mArticulationData);
// DyScratchAllocator allocator(desc.scratchMemory, desc.scratchMemorySize);
// ScratchData tempScratchData;
// allocateScratchSpatialData(allocator, linkCount, tempScratchData);
// //PxReal* gravityJointForce = allocator.alloc<PxReal>(totalDofs);
// //{
// // PxMemZero(gravityJointForce, sizeof(PxReal) * totalDofs);
// // //compute joint force due to gravity
// // tempScratchData.jointVelocities = NULL;
// // tempScratchData.jointAccelerations = NULL;
// // tempScratchData.jointForces = gravityJointForce;
// // tempScratchData.externalAccels = NULL;
// // if (fixBase)
// // inverseDynamic(mArticulationData, gravity,tempScratchData);
// // else
// // inverseDynamicFloatingLink(mArticulationData, gravity, tempScratchData);
// //}
// ////PxReal* jointForce = mArticulationData.getJointForces();
// //PxReal* tempJointForce = mArticulationData.getTempJointForces();
// //{
// // PxMemZero(tempJointForce, sizeof(PxReal) * totalDofs);
// // //compute joint force due to coriolis force
// // tempScratchData.jointVelocities = mArticulationData.getJointVelocities();
// // tempScratchData.jointAccelerations = NULL;
// // tempScratchData.jointForces = tempJointForce;
// // tempScratchData.externalAccels = NULL;
// // if (fixBase)
// // inverseDynamic(mArticulationData, PxVec3(0.f), tempScratchData);
// // else
// // inverseDynamicFloatingLink(mArticulationData, PxVec3(0.f), tempScratchData);
// //}
// //PxReal* jointForce = mArticulationData.getJointForces();
// //for (PxU32 i = 0; i < mArticulationData.getDofs(); ++i)
// //{
// // jointForce[i] = tempJointForce[i] - gravityJointForce[i];
// //}
// //PxReal* jointForce = mArticulationData.getJointForces();
// PxReal* tempJointForce = mArticulationData.getTempJointForces();
// {
// PxMemZero(tempJointForce, sizeof(PxReal) * totalDofs);
// //compute joint force due to coriolis force
// tempScratchData.jointVelocities = mArticulationData.getJointVelocities();
// tempScratchData.jointAccelerations = NULL;
// tempScratchData.jointForces = tempJointForce;
// tempScratchData.externalAccels = mArticulationData.getExternalAccelerations();
// if (fixBase)
// inverseDynamic(mArticulationData, gravity, tempScratchData);
// else
// inverseDynamicFloatingLink(mArticulationData, gravity, tempScratchData);
// }
// PxReal* jointForce = mArticulationData.getJointForces();
// for (PxU32 i = 0; i < mArticulationData.getDofs(); ++i)
// {
// jointForce[i] = tempJointForce[i];
// }
//}
void FeatherstoneArticulation::updateArticulation(const PxVec3& gravity, const PxReal invLengthScale)
{
//Copy the link poses into a handy array.
//Update the link separation vectors with the latest link poses.
//Compute the motion matrices in the world frame uisng the latest link poses.
{
//constants
const ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
const ArticulationJointCoreData* jointCoreDatas = mArticulationData.getJointData();
const Cm::UnAlignedSpatialVector* jointDofMotionMatrices = mArticulationData.getMotionMatrix();
//outputs
PxTransform* linkAccumulatedPosesW = mArticulationData.getAccumulatedPoses();
PxVec3* linkRsW = mArticulationData.getRw();
Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix();
computeRelativeTransformC2P(
links, linkCount, jointCoreDatas, jointDofMotionMatrices,
linkAccumulatedPosesW, linkRsW, jointDofMotionMatricesW);
}
//computeLinkVelocities(mArticulationData, scratchData);
{
//constants
const PxReal dt = mArticulationData.mDt;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
const PxU32 nbLinks = mArticulationData.mLinkCount;
const PxU32 nbJointDofs = mArticulationData.mJointVelocity.size();
const PxTransform* linkAccumulatedPosesW = mArticulationData.mAccumulatedPoses.begin();
const Cm::SpatialVector* linkExternalAccelsW = mArticulationData.mExternalAcceleration;
const PxVec3* linkRsW = mArticulationData.mRw.begin();
//outputs
Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.mWorldMotionMatrix.begin();
const ArticulationJointCoreData* jointCoreData = mArticulationData.mJointData;
ArticulationLinkData* linkData = mArticulationData.mLinksData;
ArticulationLink* links = mArticulationData.mLinks;
Cm::SpatialVectorF* linkMotionVelocitiesW = mArticulationData.mMotionVelocities.begin();
Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin();
Cm::SpatialVectorF* linkCoriolisVectorsW = mArticulationData.mCorioliseVectors.begin();
Cm::SpatialVectorF* linkZAExtForcesW = mArticulationData.mZAForces.begin();
Cm::SpatialVectorF* linkZAIntForcesW = mArticulationData.mZAInternalForces.begin();
Dy::SpatialMatrix* linkSpatialArticulatedInertiasW = mArticulationData.mWorldSpatialArticulatedInertia.begin();
PxMat33* linkIsolatedSpatialArticulatedInertiasW = mArticulationData.mWorldIsolatedSpatialArticulatedInertia.begin();
PxReal* linkMasses = mArticulationData.mMasses.begin();
PxReal* jointDofVelocities = mArticulationData.mJointVelocity.begin();
Cm::SpatialVectorF& rootPreMotionVelocityW = mArticulationData.mRootPreMotionVelocity;
PxVec3& comW = mArticulationData.mCOM;
PxReal& invMass = mArticulationData.mInvSumMass;
computeLinkStates(
dt, invLengthScale, gravity, fixBase,
nbLinks,
linkAccumulatedPosesW, linkExternalAccelsW, linkRsW, jointDofMotionMatricesW, jointCoreData,
linkData, links, linkMotionAccelerationsW, linkMotionVelocitiesW, linkZAExtForcesW, linkZAIntForcesW, linkCoriolisVectorsW,
linkIsolatedSpatialArticulatedInertiasW, linkMasses, linkSpatialArticulatedInertiasW,
nbJointDofs,
jointDofVelocities,
rootPreMotionVelocityW, comW, invMass);
}
{
const PxU32 linkCount = mArticulationData.getLinkCount();
if (linkCount > 1)
{
const Cm::SpatialVectorF* ZAForcesExtW = mArticulationData.getSpatialZAVectors();
const Cm::SpatialVectorF* ZAForcesIntW = mArticulationData.mZAInternalForces.begin();
Cm::SpatialVectorF* ZAForcesTransmittedW = mArticulationData.getTransmittedForces();
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
ZAForcesTransmittedW[linkID] = ZAForcesExtW[linkID] + ZAForcesIntW[linkID];
}
}
}
{
//Constant inputs.
const ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
const PxVec3* linkRsW = mArticulationData.getRw();
const ArticulationJointCoreData* jointData = mArticulationData.getJointData();
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix();
const Cm::SpatialVectorF* linkCoriolisVectorsW = mArticulationData.getCorioliseVectors();
const PxReal* jointDofForces = mArticulationData.getJointForces();
//Values that we need now and will cache for later use.
Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW();
InvStIs* linkInvStISW = mArticulationData.getInvStIS();
Cm::SpatialVectorF* jointDofISInvStIS = mArticulationData.getISInvStIS(); //[(I * s)/(s^T * I * s)
PxReal* jointDofMinusStZExtW = mArticulationData.getMinusStZExt(); //[-s^t * ZExt]
PxReal* jointDofQStZIntIcW = mArticulationData.getQStZIntIc(); //[Q - s^T*(ZInt + I*c)]
//We need to compute these.
Cm::SpatialVectorF* linkZAForcesExtW = mArticulationData.getSpatialZAVectors();
Cm::SpatialVectorF* linkZAForcesIntW = mArticulationData.mZAInternalForces.begin();
SpatialMatrix* linkSpatialInertiasW = mArticulationData.getWorldSpatialArticulatedInertia();
SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW();
computeArticulatedSpatialInertiaAndZ(
links, linkCount, linkRsW, //constants
jointData, //constants
jointDofMotionMatricesW, linkCoriolisVectorsW, jointDofForces, //constants
jointDofISW, linkInvStISW, jointDofISInvStIS, //compute and cache for later use
jointDofMinusStZExtW, jointDofQStZIntIcW, //compute and cache for later use
linkZAForcesExtW, linkZAForcesIntW, //outputs
linkSpatialInertiasW, baseInvSpatialArticulatedInertiaW); //outputs
}
{
//Constants
const PxArticulationFlags& flags = mArticulationData.getArticulationFlags();
ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
const ArticulationJointCoreData* jointData = mArticulationData.getJointData();
const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW();
const PxVec3* linkRsW = mArticulationData.getRw();
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix();
const Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW();
const InvStIs* linkInvStIsW = mArticulationData.getInvStIS();
const Cm::SpatialVectorF* jointDofISInvDW = mArticulationData.getISInvStIS();
//outputs
SpatialImpulseResponseMatrix* linkImpulseResponseMatricesW = mArticulationData.getImpulseResponseMatrixWorld();
computeArticulatedResponseMatrix(
flags, linkCount, //constants
jointData, baseInvSpatialArticulatedInertiaW, //constants
linkRsW, jointDofMotionMatricesW, //constants
jointDofISW, linkInvStIsW, jointDofISInvDW, //constants
links, linkImpulseResponseMatricesW); //outputs
}
{
//Constant terms.
const bool doIC = false;
const PxReal dt = mArticulationData.getDt();
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
const ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
const ArticulationJointCoreData* jointDatas = mArticulationData.getJointData();
const Cm::SpatialVectorF* linkSpatialZAForcesExtW = mArticulationData.getSpatialZAVectors();
const Cm::SpatialVectorF* linkCoriolisForcesW = mArticulationData.getCorioliseVectors();
const PxVec3* linkRsW = mArticulationData.getRw();
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix();
const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW();
//Cached constant terms.
const InvStIs* linkInvStISW = mArticulationData.getInvStIS();
const Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW();
const PxReal* jointDofMinusStZExtW = mArticulationData.getMinusStZExt();
//Output
Cm::SpatialVectorF* linkMotionVelocitiesW = mArticulationData.getMotionVelocities();
Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.getMotionAccelerations();
PxReal* jointDofAccelerations = mArticulationData.getJointAccelerations();
PxReal* jointDofVelocities = mArticulationData.getJointVelocities();
PxReal* jointDofNewVelocities = mArticulationData.getJointNewVelocities();
computeLinkAcceleration(
doIC, dt,
fixBase,
links, linkCount, jointDatas,
linkSpatialZAForcesExtW, linkCoriolisForcesW, linkRsW,
jointDofMotionMatricesW, baseInvSpatialArticulatedInertiaW,
linkInvStISW, jointDofISW, jointDofMinusStZExtW,
linkMotionAccelerationsW,linkMotionVelocitiesW,
jointDofAccelerations, jointDofVelocities, jointDofNewVelocities);
}
{
//constants
const PxReal dt = mArticulationData.getDt();
const PxVec3& comW = mArticulationData.mCOM;
const PxReal invSumMass = mArticulationData.mInvSumMass;
const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.mBaseInvSpatialArticulatedInertiaW;
const PxReal linkMaxLinearVelocity = mSolverDesc.core ? mSolverDesc.core->maxLinearVelocity : -1.0f;
const PxReal linkMaxAngularVelocity = mSolverDesc.core ? mSolverDesc.core->maxAngularVelocity : -1.0f;
const ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
const ArticulationJointCoreData* jointDatas = mArticulationData.getJointData();
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
const Cm::SpatialVectorF* linkSpatialZAIntForcesW = mArticulationData.getSpatialZAInternalVectors();
const Cm::SpatialVectorF* linkCoriolisVectorsW = mArticulationData.getCorioliseVectors();
const PxReal* linkMasses = mArticulationData.mMasses.begin();
const PxVec3* linkRsW = mArticulationData.getRw();
const PxTransform* linkAccumulatedPosesW = mArticulationData.getAccumulatedPoses();
const PxMat33* linkIsolatedSpatialArticulatedInertiasW = mArticulationData.mWorldIsolatedSpatialArticulatedInertia.begin();
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix();
//cached data.
const InvStIs* linkInvStISW = mArticulationData.getInvStIS();
const Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW();
const PxReal* jointDofQStZIntIcW = mArticulationData.getQStZIntIc();
//output
Cm::SpatialVectorF* linkMotionVelocitiesW = mArticulationData.getMotionVelocities();
Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.getMotionAccelerations();
Cm::SpatialVectorF* linkMotionAccelerationIntW = mArticulationData.mMotionAccelerationsInternal.begin();
PxReal* jointDofAccelerations = mArticulationData.getJointAccelerations();
PxReal* jointDofInternalAccelerations = mArticulationData.mJointInternalAcceleration.begin();
PxReal* jointVelocities = mArticulationData.getJointVelocities();
PxReal* jointNewVelocities = mArticulationData.mJointNewVelocity.begin();
computeLinkInternalAcceleration(
dt, fixBase, comW, invSumMass, linkMaxLinearVelocity, linkMaxAngularVelocity, linkIsolatedSpatialArticulatedInertiasW,
baseInvSpatialArticulatedInertiaW,
links, linkCount,
linkMasses, linkRsW, linkAccumulatedPosesW,
linkSpatialZAIntForcesW, linkCoriolisVectorsW,
jointDatas, jointDofMotionMatricesW,
linkInvStISW, jointDofISW, jointDofQStZIntIcW,
linkMotionAccelerationsW, linkMotionAccelerationIntW, linkMotionVelocitiesW,
jointDofAccelerations, jointDofInternalAccelerations, jointVelocities, jointNewVelocities);
}
{
const PxU32 linkCount = mArticulationData.getLinkCount();
Cm::SpatialVectorF* solverLinkSpatialDeltaVels = mArticulationData.mSolverLinkSpatialDeltaVels.begin();
PxMemZero(solverLinkSpatialDeltaVels, sizeof(Cm::SpatialVectorF) * linkCount);
Cm::SpatialVectorF* solverLinkSpatialImpulses = mArticulationData.mSolverLinkSpatialImpulses.begin();
PxMemZero(solverLinkSpatialImpulses, sizeof(Cm::SpatialVectorF) * linkCount);
Cm::SpatialVectorF* solverLinkSpatialForcesW = mArticulationData.mSolverLinkSpatialForces.begin();
PxMemZero(solverLinkSpatialForcesW, linkCount * sizeof(Cm::SpatialVectorF));
}
}
void FeatherstoneArticulation::computeUnconstrainedVelocitiesInternal(
const PxVec3& gravity,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV, const PxReal invLengthScale)
{
//PX_PROFILE_ZONE("Articulations:computeUnconstrainedVelocities", 0);
//mStaticConstraints.forceSize_Unsafe(0);
mStatic1DConstraints.forceSize_Unsafe(0);
mStaticContactConstraints.forceSize_Unsafe(0);
PxMemZero(mArticulationData.mNbStatic1DConstraints.begin(), mArticulationData.mNbStatic1DConstraints.size()*sizeof(PxU32));
PxMemZero(mArticulationData.mNbStaticContactConstraints.begin(), mArticulationData.mNbStaticContactConstraints.size() * sizeof(PxU32));
//const PxU32 linkCount = mArticulationData.getLinkCount();
mArticulationData.init();
updateArticulation(gravity, invLengthScale);
ScratchData scratchData;
scratchData.motionVelocities = mArticulationData.getMotionVelocities();
scratchData.motionAccelerations = mArticulationData.getMotionAccelerations();
scratchData.coriolisVectors = mArticulationData.getCorioliseVectors();
scratchData.spatialZAVectors = mArticulationData.getSpatialZAVectors();
scratchData.jointAccelerations = mArticulationData.getJointAccelerations();
scratchData.jointVelocities = mArticulationData.getJointVelocities();
scratchData.jointPositions = mArticulationData.getJointPositions();
scratchData.jointForces = mArticulationData.getJointForces();
scratchData.externalAccels = mArticulationData.getExternalAccelerations();
if (mArticulationData.mLinkCount > 1)
{
//use individual zero acceleration force(we copy the initial Z value to the transmitted force buffers in initLink())
scratchData.spatialZAVectors = mArticulationData.getTransmittedForces();
computeZAForceInv(mArticulationData, scratchData);
computeJointTransmittedFrictionForce(mArticulationData, scratchData, Z, DeltaV);
}
//the dirty flag is used in inverse dynamic
mArticulationData.setDataDirty(true);
//zero zero acceleration vector in the articulation data so that we can use this buffer to accumulated
//impulse for the contacts/constraints in the PGS/TGS solvers
//PxMemZero(mArticulationData.getSpatialZAVectors(), sizeof(Cm::SpatialVectorF) * linkCount);
//Reset deferredQstZ and root deferredZ!
PxMemZero(mArticulationData.mDeferredQstZ.begin(), sizeof(PxReal)*mArticulationData.getDofs());
PxMemZero(mArticulationData.mJointConstraintForces.begin(), sizeof(PxReal)*mArticulationData.getDofs());
mArticulationData.mRootDeferredZ = Cm::SpatialVectorF::Zero();
// solver progress counters
maxSolverNormalProgress = 0;
maxSolverFrictionProgress = 0;
solverProgress = 0;
numTotalConstraints = 0;
for (PxU32 a = 0; a < mArticulationData.getLinkCount(); ++a)
{
mArticulationData.mAccumulatedPoses[a] = mArticulationData.getLink(a).bodyCore->body2World;
mArticulationData.mPreTransform[a] = mArticulationData.getLink(a).bodyCore->body2World;
mArticulationData.mDeltaQ[a] = PxQuat(PxIdentity);
}
}
void FeatherstoneArticulation::enforcePrismaticLimits(PxReal& jPosition, ArticulationJointCore* joint)
{
const PxU32 dofId = joint->dofIds[0];
if (joint->motion[dofId] == PxArticulationMotion::eLIMITED)
{
if (jPosition < (joint->limits[dofId].low))
jPosition = joint->limits[dofId].low;
if (jPosition > (joint->limits[dofId].high))
jPosition = joint->limits[dofId].high;
}
}
PxQuat computeSphericalJointPositions(const PxQuat& relativeQuat,
const PxQuat& newRot, const PxQuat& pBody2WorldRot,
PxReal* jPositions, const Cm::UnAlignedSpatialVector* motionMatrix,
const PxU32 dofs)
{
PxQuat newParentToChild = (newRot.getConjugate() * pBody2WorldRot).getNormalized();
if(newParentToChild.w < 0.f)
newParentToChild = -newParentToChild;
//PxQuat newParentToChild = (newRot * pBody2WorldRot.getConjugate()).getNormalized();
PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate();
if(jointRotation.w < 0.0f)
jointRotation = -jointRotation;
PxReal radians;
PxVec3 axis;
jointRotation.toRadiansAndUnitAxis(radians, axis);
axis *= radians;
for (PxU32 d = 0; d < dofs; ++d)
{
jPositions[d] = -motionMatrix[d].top.dot(axis);
}
return newParentToChild;
}
PxQuat computeSphericalJointPositions(const PxQuat& /*relativeQuat*/,
const PxQuat& newRot, const PxQuat& pBody2WorldRot)
{
PxQuat newParentToChild = (newRot.getConjugate() * pBody2WorldRot).getNormalized();
if (newParentToChild.w < 0.f)
newParentToChild = -newParentToChild;
/*PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate();
PxReal radians;
jointRotation.toRadiansAndUnitAxis(radians, axis);
axis *= radians;*/
return newParentToChild;
}
void FeatherstoneArticulation::computeAndEnforceJointPositions(ArticulationData& data)
{
ArticulationLink* links = data.getLinks();
const PxU32 linkCount = data.getLinkCount();
ArticulationJointCoreData* jointData = data.getJointData();
PxReal* jointPositions = data.getJointPositions();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
ArticulationJointCore* joint = link.inboundJoint;
ArticulationJointCoreData& jointDatum = jointData[linkID];
PxReal* jPositions = &jointPositions[jointDatum.jointOffset];
if (joint->jointType == PxArticulationJointType::eSPHERICAL)
{
ArticulationLink& pLink = links[link.parent];
//const PxTransform pBody2World = pLink.bodyCore->body2World;
const PxU32 dof = jointDatum.dof;
computeSphericalJointPositions(data.mRelativeQuat[linkID], link.bodyCore->body2World.q,
pLink.bodyCore->body2World.q, jPositions, &data.getMotionMatrix(jointDatum.jointOffset), dof);
}
else if (joint->jointType == PxArticulationJointType::eREVOLUTE)
{
PxReal jPos = jPositions[0];
if (jPos > PxTwoPi)
jPos -= PxTwoPi*2.f;
else if (jPos < -PxTwoPi)
jPos += PxTwoPi*2.f;
jPos = PxClamp(jPos, -PxTwoPi*2.f, PxTwoPi*2.f);
jPositions[0] = jPos;
}
else if(joint->jointType == PxArticulationJointType::ePRISMATIC)
{
enforcePrismaticLimits(jPositions[0], joint);
}
}
}
void FeatherstoneArticulation::updateJointProperties(PxReal* jointNewVelocities, PxReal* jointVelocities, PxReal* jointAccelerations)
{
using namespace Dy;
const PxU32 dofs = mArticulationData.getDofs();
const PxReal invDt = 1.f / mArticulationData.getDt();
for (PxU32 i = 0; i < dofs; ++i)
{
const PxReal jNewVel = jointNewVelocities[i];
PxReal delta = jNewVel - jointVelocities[i];
jointVelocities[i] = jNewVel;
jointAccelerations[i] += delta * invDt;
}
}
void FeatherstoneArticulation::propagateLinksDown(ArticulationData& data, PxReal* jointVelocities, PxReal* jointPositions,
Cm::SpatialVectorF* motionVelocities)
{
ArticulationLink* links = mArticulationData.getLinks();
ArticulationJointCoreData* jointData = mArticulationData.getJointData();
const PxQuat* const PX_RESTRICT relativeQuats = mArticulationData.mRelativeQuat.begin();
const PxU32 linkCount = mArticulationData.getLinkCount();
const PxReal dt = data.getDt();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
ArticulationJointCoreData& jointDatum = jointData[linkID];
//ArticulationLinkData& linkDatum = mArticulationData.getLinkData(linkID);
//const PxTransform oldTransform = preTransforms[linkID];
ArticulationLink& pLink = links[link.parent];
const PxTransform pBody2World = pLink.bodyCore->body2World;
ArticulationJointCore* joint = link.inboundJoint;
PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset];
PxReal* jPosition = &jointPositions[jointDatum.jointOffset];
PxQuat newParentToChild;
PxQuat newWorldQ;
PxVec3 r;
const PxVec3 childOffset = -joint->childPose.p;
const PxVec3 parentOffset = joint->parentPose.p;
PxTransform& body2World = link.bodyCore->body2World;
const PxQuat relativeQuat = relativeQuats[linkID];
switch (joint->jointType)
{
case PxArticulationJointType::ePRISMATIC:
{
const PxReal delta = (jVelocity[0]) * dt;
PxReal jPos = jPosition[0] + delta;
enforcePrismaticLimits(jPos, joint);
jPosition[0] = jPos;
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].bottom;
r = e + d + u * jPos;
break;
}
case PxArticulationJointType::eREVOLUTE:
{
//use positional iteration JointVelociy to integrate
const PxReal delta = (jVelocity[0]) * dt;
PxReal jPos = jPosition[0] + delta;
if (jPos > PxTwoPi)
jPos -= PxTwoPi*2.f;
else if (jPos < -PxTwoPi)
jPos += PxTwoPi*2.f;
jPos = PxClamp(jPos, -PxTwoPi*2.f, PxTwoPi*2.f);
jPosition[0] = jPos;
const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].top;
PxQuat jointRotation = PxQuat(-jPos, u);
if (jointRotation.w < 0) //shortest angle.
jointRotation = -jointRotation;
newParentToChild = (jointRotation * relativeQuat).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const PxReal delta = (jVelocity[0]) * dt;
PxReal jPos = jPosition[0] + delta;
jPosition[0] = jPos;
const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].top;
PxQuat jointRotation = PxQuat(-jPos, u);
if (jointRotation.w < 0) //shortest angle.
jointRotation = -jointRotation;
newParentToChild = (jointRotation * relativeQuat).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eSPHERICAL:
{
if (1)
{
const PxTransform oldTransform = data.mAccumulatedPoses[linkID];
#if 0
Cm::SpatialVectorF worldVel = FeatherstoneArticulation::translateSpatialVector(-mArticulationData.mRw[linkID], motionVelocities[link.parent]);
for (PxU32 i = 0; i < jointDatum.dof; ++i)
{
const PxReal delta = (jVelocity[i]) * dt;
const PxReal jPos = jPosition[i] + delta;
jPosition[i] = jPos;
worldVel.top += data.mWorldMotionMatrix[jointDatum.jointOffset + i].top * jVelocity[i];
worldVel.bottom += data.mWorldMotionMatrix[jointDatum.jointOffset + i].bottom * jVelocity[i];
}
motionVelocities[linkID] = worldVel;
#else
Cm::SpatialVectorF worldVel = motionVelocities[linkID];
//Cm::SpatialVectorF parentVel = motionVelocities[link.parent];
//PxVec3 relVel = oldTransform.rotateInv(worldVel.top - parentVel.top);
//for (PxU32 i = 0; i < jointDatum.dof; ++i)
//{
// const PxReal jVel = mArticulationData.mMotionMatrix[jointDatum.jointOffset + i].top.dot(relVel);
// jVelocity[i] = jVel;
// /*const PxReal delta = jVel * dt;
// jPosition[i] += delta;*/
//}
#endif
//Gp and Gc are centre of mass poses of parent(p) and child(c) in the world frame.
//Introduce Q(v, dt) = PxExp(worldAngVel*dt);
//Lp and Lc are joint frames of parent(p) and child(c) in the parent and child body frames.
//The rotational part of Gc will be updated as follows:
//GcNew.q = Q(v, dt) * Gc.q
//We could use GcNew for the new child pose but it isn't in quite the right form
//to use in a generic way with all the other joint types supported here.
//Here's what we do.
//Step 1) add Identity to the rhs.
//GcNew.q = Gp.q * Gp.q^-1 * Q(v, dt) * Gc.q
//Step 2) Remember that (A * B^-1) = (B * A ^-1)^-1.
//Gp.q^-1 * Q(v, dt) * Gc.q = (Q(v, dt) * Gc.q)^-1 * Gp.q
//GcNew.q = Gp.q * (Q(v, dt) * Gc.q)^-1 * Gp.q
//Write this out using the variable names used here.
//The final form is:
//body2World.q = pBody2World.q * newParent2Child
//The translational part of GcNew will be updated as follows:
//GcNew.p = Gp.p + Gp.q.rotate(Lp.p) - GcNew.q.rotate(Lc.p)
// = Gp.p + GcNew.q * (GcNew.q^-1 * Gp.q).rotate(Lp.p) - GcNew.q.rotate(Lc.p)
// = Gp.p + GcNew.q.rotate((GcNew.q^-1 * Gp.q).rotate(Lp.p) - GcNew.q.rotate(Lc.p)
// = Gp.p + GcNew.q.rotate((GcNew.q^-1 * Gp.q).rotate(Lp.p) - Lc.p)
//Write this out using the variable names used here.
//body2World.p = pBody2World.p + body2World.q.rotate(newParent2Child.rotate(parentOffset) + childOffset)
//Put r = newParent2Child.rotate(parentOffset) + childOffset
//and we have the final form used here:
//body2World.p = pBody2World.p + body2World.q.rotate(r)
//Now let's think about the rotation angles.
//Imagine that the joint frames are aligned in the world frame.
//The pose(Gc0) of the child body in the world frame will satisfy:
//Gp * Lp = Gc0 * Lc
//We can solve for Gc0:
//Gc0 = Gp * Lp * Lc^-1
//Gc0 = Gp * (Lc * Lp^-1)^-1
//Now compute the rotation J that rotates from Gc0 to GcNew.
//We seek a rotation J in the child body frame (in the aligned state so at Gc0) that satisfies:
//Gc0 * J = GcNew
//Let's actually solve for J^-1 (because that's what we do here).
//J^-1 = GcNew^-1 * Gp * (Lc * Lp^-1)^-1
//From J^-1 we can retrieve three rotation angles in the child body frame.
//We actually want the angles for J. We observe that
//toAngles(J^-1) = -toAngles(J)
//Our rotation angles r_b commensurate with J are then:
//r_b = -toAngles(J^-1)
//From r_b we can compute the angles r_j in the child joint frame.
// r_j = Lc.rotateInv(r_b)
//Remember that we began our calculation with aligned frames.
//We can equally apply r_j to the parent joint frame and achieve the same outcome.
//GcNew = Q(v, dt) * Gc.q
PxVec3 worldAngVel = worldVel.top;
newWorldQ = PxExp(worldAngVel*dt) * oldTransform.q;
//GcNew^-1 * Gp
newParentToChild = computeSphericalJointPositions(relativeQuat, newWorldQ,
pBody2World.q);
//J^-1 = GcNew^-1 * Gp * (Lc * Lp^-1)^-1
PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate();
if(jointRotation.w < 0.0f)
jointRotation = -jointRotation;
//PxVec3 axis = toRotationVector(jointRotation);
/*PxVec3 axis = jointRotation.getImaginaryPart();
for (PxU32 i = 0; i < jointDatum.dof; ++i)
{
PxVec3 sa = data.getMotionMatrix(jointDatum.jointOffset + i).top;
PxReal angle = -compAng(PxVec3(sa.x, sa.y, sa.z).dot(axis), jointRotation.w);
jPosition[i] = angle;
}*/
//r_j = -Lc.rotateInv(r_b)
PxVec3 axis; PxReal angle;
jointRotation.toRadiansAndUnitAxis(angle, axis);
axis *= angle;
for (PxU32 i = 0; i < jointDatum.dof; ++i)
{
PxVec3 sa = mArticulationData.getMotionMatrix(jointDatum.jointOffset + i).top;
PxReal ang = -sa.dot(axis);
jPosition[i] = ang;
}
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
}
break;
}
case PxArticulationJointType::eFIX:
{
//this is fix joint so joint don't have velocity
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
break;
}
default:
PX_ASSERT(false);
break;
}
body2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized();
body2World.p = pBody2World.p + body2World.q.rotate(r);
PX_ASSERT(body2World.isSane());
PX_ASSERT(body2World.isValid());
}
}
void FeatherstoneArticulation::updateBodies(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt)
{
updateBodies(static_cast<FeatherstoneArticulation*>(desc.articulation), tempDeltaV, dt, true);
}
void FeatherstoneArticulation::updateBodiesTGS(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt)
{
updateBodies(static_cast<FeatherstoneArticulation*>(desc.articulation), tempDeltaV, dt, false);
}
void FeatherstoneArticulation::updateBodies(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* tempDeltaV, PxReal dt, bool integrateJointPositions)
{
ArticulationData& data = articulation->mArticulationData;
ArticulationLink* links = data.getLinks();
const PxU32 linkCount = data.getLinkCount();
Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities();
Cm::SpatialVectorF* posMotionVelocities = data.getPosIterMotionVelocities();
Cm::SpatialVector* externalAccels = data.getExternalAccelerations();
Cm::SpatialVector zero = Cm::SpatialVector::zero();
data.setDt(dt);
const PxU32 nbSensors = data.mNbSensors;
bool doForces = data.getArticulationFlags() & PxArticulationFlag::eCOMPUTE_JOINT_FORCES
|| nbSensors;
//update joint velocities/accelerations due to contacts/constraints.
if (data.mJointDirty)
{
//update delta joint velocity and motion velocity due to velocity iteration changes
//update motionVelocities
PxcFsFlushVelocity(*articulation, tempDeltaV, doForces);
}
Cm::SpatialVectorF momentum0 = Cm::SpatialVectorF::Zero();
PxVec3 posMomentum(0.f);
const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
//PGS
if (!fixBase)
{
const PxVec3 COM = data.mCOM;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
PxReal mass = data.mMasses[linkID];
momentum0.top += motionVelocities[linkID].bottom * mass;
posMomentum += posMotionVelocities[linkID].bottom * mass;
}
PxVec3 rootVel = momentum0.top * data.mInvSumMass;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
PxReal mass = data.mMasses[linkID];
PxVec3 offsetMass = (data.mPreTransform[linkID].p - COM)*mass;
PxVec3 angMom = (data.mWorldIsolatedSpatialArticulatedInertia[linkID] * motionVelocities[linkID].top) +
offsetMass.cross(motionVelocities[linkID].bottom - rootVel);
momentum0.bottom += angMom;
}
}
if (!integrateJointPositions)
{
//TGS
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
links[linkID].bodyCore->body2World = data.mAccumulatedPoses[linkID].getNormalized();
}
articulation->computeAndEnforceJointPositions(data);
}
else
{
if (!fixBase)
{
const PxTransform& preTrans = data.mAccumulatedPoses[0];
const Cm::SpatialVectorF& posVel = data.getPosIterMotionVelocity(0);
updateRootBody(posVel, preTrans, data, dt);
}
//using the original joint velocities and delta velocities changed in the positional iter to update joint position/body transform
articulation->propagateLinksDown(data, data.getPosIterJointVelocities(), data.getJointPositions(), data.getPosIterMotionVelocities());
}
//Fix up momentum based on changes in pos. Only currently possible with non-fixed base
if (!fixBase)
{
PxVec3 COM = data.mLinks[0].bodyCore->body2World.p * data.mMasses[0];
data.mAccumulatedPoses[0] = data.mLinks[0].bodyCore->body2World;
PxVec3 sumLinMom = data.mMotionVelocities[0].bottom * data.mMasses[0];
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
PxU32 parent = data.mLinks[linkID].parent;
const PxTransform childPose = data.mLinks[linkID].bodyCore->body2World;
data.mAccumulatedPoses[linkID] = childPose;
PxVec3 rw = childPose.p - data.mAccumulatedPoses[parent].p;
data.mRw[linkID] = rw;
ArticulationJointCoreData& jointDatum = data.mJointData[linkID];
const PxReal* jVelocity = &data.mJointNewVelocity[jointDatum.jointOffset];
Cm::SpatialVectorF vel = FeatherstoneArticulation::translateSpatialVector(-rw, data.mMotionVelocities[parent]);
Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero();
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
PxReal jVel = jVelocity[ind];
//deltaV += data.mWorldMotionMatrix[jointDatum.jointOffset + ind] * jVel;
deltaV += data.mMotionMatrix[jointDatum.jointOffset + ind] * jVel;
}
vel.top += childPose.rotate(deltaV.top);
vel.bottom += childPose.rotate(deltaV.bottom);
data.mMotionVelocities[linkID] = vel;
PxReal mass = data.mMasses[linkID];
COM += childPose.p * mass;
sumLinMom += vel.bottom * mass;
}
COM *= data.mInvSumMass;
PxMat33 sumInertia(PxZero);
PxVec3 sumAngMom(0.f);
PxVec3 rootLinVel = sumLinMom * data.mInvSumMass;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
PxReal mass = data.mMasses[linkID];
const PxVec3 offset = data.mAccumulatedPoses[linkID].p - COM;
PxMat33 inertia;
PxMat33 R(data.mAccumulatedPoses[linkID].q);
const PxVec3 invInertiaDiag = data.getLink(linkID).bodyCore->inverseInertia;
PxVec3 inertiaDiag(1.f / invInertiaDiag.x, 1.f / invInertiaDiag.y, 1.f / invInertiaDiag.z);
const PxVec3 offsetMass = offset * mass;
Cm::transformInertiaTensor(inertiaDiag, R, inertia);
//Only needed for debug validation
#if PX_DEBUG
data.mWorldIsolatedSpatialArticulatedInertia[linkID] = inertia;
#endif
sumInertia += translateInertia(inertia, mass, offset);
sumAngMom += inertia * motionVelocities[linkID].top;
sumAngMom += offsetMass.cross(motionVelocities[linkID].bottom - rootLinVel);
}
PxMat33 invSumInertia = sumInertia.getInverse();
PxReal aDenom = sumAngMom.magnitude();
PxReal angRatio = aDenom == 0.f ? 0.f : momentum0.bottom.magnitude() / aDenom;
PxVec3 angMomDelta = sumAngMom * (angRatio - 1.f);
PxVec3 angDelta = invSumInertia * angMomDelta;
#if 0
motionVelocities[0].top += angDelta;
Cm::SpatialVectorF* motionAccelerations = data.getMotionAccelerations();
motionAccelerations[0] = Cm::SpatialVectorF(angDelta, PxVec3(0.f));
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
Cm::SpatialVectorF deltaV = Dy::FeatherstoneArticulation::translateSpatialVector(-data.getRw(linkID), motionAccelerations[data.getLink(linkID).parent]);
motionVelocities[linkID] += deltaV;
motionAccelerations[linkID] = deltaV;
sumLinMom += deltaV.bottom*data.mMasses[linkID];
}
#else
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const PxVec3 offset = (data.getAccumulatedPoses()[linkID].p - COM);
Cm::SpatialVectorF velChange(angDelta, -offset.cross(angDelta));
motionVelocities[linkID] += velChange;
PxReal mass = data.mMasses[linkID];
sumLinMom += velChange.bottom * mass;
}
#endif
PxVec3 linDelta = (momentum0.top - sumLinMom)*data.mInvSumMass;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
motionVelocities[linkID].bottom += linDelta;
}
//if (integrateJointPositions)
{
PxVec3 predictedCOM = data.mCOM + posMomentum * (data.mInvSumMass * dt);
PxVec3 posCorrection = predictedCOM - COM;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
link.bodyCore->body2World.p += posCorrection;
}
COM += posCorrection;
}
#if PX_DEBUG && 0
const bool validateMomentum = false;
if (validateMomentum)
{
PxVec3 rootVel = sumLinMom * data.mInvSumMass + linDelta;
Cm::SpatialVectorF momentum2(PxVec3(0.f), PxVec3(0.f));
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
const PxReal mass = data.mMasses[linkID];
PxVec3 offsetMass = (data.getLink(linkID).bodyCore->body2World.p - COM) * mass;
const PxVec3 angMom = data.mWorldIsolatedSpatialArticulatedInertia[linkID] * motionVelocities[linkID].top +
offsetMass.cross(motionVelocities[linkID].bottom - rootVel);
momentum2.bottom += angMom;
momentum2.top += motionVelocities[linkID].bottom * mass;
}
printf("COM = (%f, %f, %f)\n", COM.x, COM.y, COM.z);
printf("%i: linMom0 %f, linMom1 %f, angMom0 %f, angMom1 %f\n\n\n",
count, momentum0.top.magnitude(), momentum2.top.magnitude(),
momentum0.bottom.magnitude(), momentum2.bottom.magnitude());
}
#endif
}
{
//update joint velocity/accelerations
PxReal* jointVelocities = data.getJointVelocities();
PxReal* jointAccelerations = data.getJointAccelerations();
PxReal* jointNewVelocities = data.getJointNewVelocities();
articulation->updateJointProperties(jointNewVelocities, jointVelocities, jointAccelerations);
}
const PxReal invDt = 1.f/dt;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
PxsBodyCore* bodyCore = link.bodyCore;
bodyCore->linearVelocity = motionVelocities[linkID].bottom;
bodyCore->angularVelocity = motionVelocities[linkID].top;
//zero external accelerations
if(!(link.bodyCore->mFlags & PxRigidBodyFlag::eRETAIN_ACCELERATIONS))
externalAccels[linkID] = zero;
}
if (doForces)
{
data.mSolverLinkSpatialForces[0] *= invDt;
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
data.mSolverLinkSpatialForces[linkID] = (data.mWorldSpatialArticulatedInertia[linkID] * data.mSolverLinkSpatialForces[linkID]) * invDt;
}
if (data.getArticulationFlags() & PxArticulationFlag::eCOMPUTE_JOINT_FORCES)
{
//const PxU32 dofCount = data.getDofs();
PxReal* constraintForces = data.getJointConstraintForces();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const Cm::SpatialVectorF spatialForce = data.mSolverLinkSpatialForces[linkID] - (data.mZAForces[linkID] + data.mZAInternalForces[linkID]);
ArticulationJointCoreData& jointDatum = data.mJointData[linkID];
const PxU32 offset = jointDatum.jointOffset;
const PxU32 dofCount = jointDatum.dof;
for (PxU32 i = 0; i < dofCount; ++i)
{
const PxReal jointForce = data.mWorldMotionMatrix[offset + i].innerProduct(spatialForce);
constraintForces[offset + i] = jointForce;
}
}
}
for (PxU32 s = 0; s < nbSensors; ++s)
{
ArticulationSensor* sensor = data.mSensors[s];
const PxU32 linkID = sensor->mLinkID;
const PxTransform& transform = data.mPreTransform[linkID];
const PxTransform& relTrans = sensor->mRelativePose;
//Offset to translate the impulse by
const PxVec3 offset = transform.rotate(relTrans.p);
Cm::SpatialVectorF spatialForce(PxVec3(0.f), PxVec3(0.f));
if (sensor->mFlags & PxArticulationSensorFlag::eCONSTRAINT_SOLVER_FORCES)
spatialForce += data.mSolverLinkSpatialForces[linkID];
if (sensor->mFlags & PxArticulationSensorFlag::eFORWARD_DYNAMICS_FORCES)
spatialForce -= (data.mZAForces[linkID] + data.mZAInternalForces[linkID]);
// translate from body to sensor frame (offset is body->sensor)
spatialForce = translateSpatialVector(-offset, spatialForce);
if (sensor->mFlags & PxArticulationSensorFlag::eWORLD_FRAME)
{
data.mSensorForces[s].force = spatialForce.top;
data.mSensorForces[s].torque = spatialForce.bottom;
}
else
{
//Now we need to rotate into the sensor's frame. Forces are currently reported in world frame
const PxQuat rotate = transform.q * relTrans.q;
data.mSensorForces[s].force = rotate.rotateInv(spatialForce.top);
data.mSensorForces[s].torque = rotate.rotateInv(spatialForce.bottom);
}
}
}
}
void FeatherstoneArticulation::updateRootBody(const Cm::SpatialVectorF& motionVelocity,
const PxTransform& preTransform, ArticulationData& data, const PxReal dt)
{
ArticulationLink* links = data.getLinks();
//body2World store new body transform integrated from solver linear/angular velocity
PX_ASSERT(motionVelocity.top.isFinite());
PX_ASSERT(motionVelocity.bottom.isFinite());
ArticulationLink& baseLink = links[0];
PxsBodyCore* baseBodyCore = baseLink.bodyCore;
//(1) project the current body's velocity (based on its pre-pose) to the geometric COM that we're integrating around...
PxVec3 comLinVel = motionVelocity.bottom;
//using the position iteration motion velocity to compute the body2World
PxVec3 newP = (preTransform.p) + comLinVel * dt;
PxQuat deltaQ = PxExp(motionVelocity.top*dt);
baseBodyCore->body2World = PxTransform(newP, (deltaQ* preTransform.q).getNormalized());
PX_ASSERT(baseBodyCore->body2World.isFinite() && baseBodyCore->body2World.isValid());
}
void FeatherstoneArticulation::getJointAcceleration(const PxVec3& gravity, PxArticulationCache& cache)
{
PX_SIMD_GUARD
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getJointAcceleration() commonInit need to be called first to initialize data!");
return;
}
const PxU32 linkCount = mArticulationData.getLinkCount();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
scratchData.jointVelocities = cache.jointVelocity;
scratchData.jointForces = cache.jointForce;
//compute individual link's spatial inertia tensor
//[0, M]
//[I, 0]
computeSpatialInertia(mArticulationData);
computeLinkVelocities(mArticulationData, scratchData);
//compute individual zero acceleration force
computeZ(mArticulationData, gravity, scratchData);
//compute corolis and centrifugal force
computeC(mArticulationData, scratchData);
computeArticulatedSpatialInertiaAndZ_NonSeparated(mArticulationData, scratchData);
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
//we have initialized motionVelocity and motionAcceleration to be zero in the root link if
//fix based flag is raised
//ArticulationLinkData& baseLinkDatum = mArticulationData.getLinkData(0);
Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations;
Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors;
Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors;
if (!fixBase)
{
SpatialMatrix inverseArticulatedInertia = mArticulationData.mWorldSpatialArticulatedInertia[0].getInverse();
motionAccelerations[0] = -(inverseArticulatedInertia * spatialZAForces[0]);
}
#if FEATHERSTONE_DEBUG
else
{
PX_ASSERT(isSpatialVectorZero(motionAccelerations[0]));
}
#endif
PxReal* jointAccelerations = cache.jointAcceleration;
//calculate acceleration
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
ArticulationLink& link = mArticulationData.getLink(linkID);
//SpatialTransform p2C = linkDatum.childToParent.getTranspose();
//Cm::SpatialVectorF pMotionAcceleration = mArticulationData.mChildToParent[linkID].transposeTransform(motionAccelerations[link.parent]);
Cm::SpatialVectorF pMotionAcceleration = FeatherstoneArticulation::translateSpatialVector(-mArticulationData.getRw(linkID), motionAccelerations[link.parent]);
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
//calculate jointAcceleration
PxReal* jA = &jointAccelerations[jointDatum.jointOffset];
const InvStIs& invStIs = mArticulationData.mInvStIs[linkID];
computeJointAccelerationW(jointDatum.dof, pMotionAcceleration, &mArticulationData.mIsW[jointDatum.jointOffset], invStIs,
&mArticulationData.qstZIc[jointDatum.jointOffset], jA);
Cm::SpatialVectorF motionAcceleration(PxVec3(0.f), PxVec3(0.f));
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
motionAcceleration.top += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].top * jA[ind];
motionAcceleration.bottom += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].bottom * jA[ind];
}
motionAccelerations[linkID] = pMotionAcceleration + coriolisVectors[linkID] + motionAcceleration;
PX_ASSERT(motionAccelerations[linkID].isFinite());
}
allocator->free(tempMemory);
}
}//namespace Dy
}
| 105,900 | C++ | 37.135038 | 167 | 0.723985 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintPartition.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 "DyConstraintPartition.h"
#include "DyArticulationUtils.h"
#include "DySoftBody.h"
#include "foundation/PxHashMap.h"
#include "DyFeatherstoneArticulation.h"
#define INTERLEAVE_SELF_CONSTRAINTS 1
namespace physx
{
namespace Dy
{
namespace
{
class RigidBodyClassification : public RigidBodyClassificationBase
{
public:
RigidBodyClassification(PxU8* bodies, PxU32 bodyCount, PxU32 bodyStride) : RigidBodyClassificationBase(bodies, bodyCount, bodyStride)
{
}
/* PX_FORCE_INLINE void getProgress(const PxSolverConstraintDesc& desc, PxU32& bodyAProgress, PxU32& bodyBProgress) const
{
bodyAProgress = desc.bodyA->solverProgress;
bodyBProgress = desc.bodyB->solverProgress;
}*/
PX_FORCE_INLINE void getProgressRequirements(const PxSolverConstraintDesc& desc, PxU32& progressA, PxU32& progressB) const
{
const uintptr_t indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mBodyStride;
const uintptr_t indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mBodyStride;
const bool activeA = indexA < mBodyCount;
const bool activeB = indexB < mBodyCount;
if (activeA)
progressA = desc.bodyA->maxSolverFrictionProgress++;
else
progressA = 0;
if (activeB)
progressB = desc.bodyB->maxSolverFrictionProgress++;
else
progressB = 0;
}
PX_FORCE_INLINE void clearState()
{
for(PxU32 a = 0; a < mBodySize; a+= mBodyStride)
reinterpret_cast<PxSolverBody*>(mBodies+a)->solverProgress = 0;
}
PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxArray<PxU32>& numConstraintsPerPartition)
{
for(PxU32 a = 0; a < mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies+a);
body.solverProgress = 0;
PxU32 requiredSize = PxU32(body.maxSolverNormalProgress + body.maxSolverFrictionProgress);
if(requiredSize > numConstraintsPerPartition.size())
{
numConstraintsPerPartition.resize(requiredSize);
}
for(PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b)
{
numConstraintsPerPartition[body.maxSolverNormalProgress + b]++;
}
}
}
};
class ExtendedRigidBodyClassification : public ExtendedRigidBodyClassificationBase
{
const bool mForceStaticCollisionsToSolver; // PT: why is this one not present in the immediate mode version?
public:
ExtendedRigidBodyClassification(PxU8* bodies, PxU32 numBodies, PxU32 stride, Dy::FeatherstoneArticulation** articulations, PxU32 numArticulations, bool forceStaticCollisionsToSolver) :
ExtendedRigidBodyClassificationBase (bodies, numBodies, stride, articulations, numArticulations),
mForceStaticCollisionsToSolver (forceStaticCollisionsToSolver)
{
// PT: why is this loop not present in the immediate mode version?
for (PxU32 i = 0; i < mNumArticulations; ++i)
mArticulations[i]->mArticulationIndex = PxTo16(i);
}
// PT: this version is slightly different from the immediate mode version, see mArticulationIndex!
//Returns true if it is a dynamic-dynamic constraint; false if it is a dynamic-static or dynamic-kinematic constraint
PX_FORCE_INLINE bool classifyConstraint(const PxSolverConstraintDesc& desc, uintptr_t& indexA, uintptr_t& indexB,
bool& activeA, bool& activeB, PxU32& bodyAProgress, PxU32& bodyBProgress) const
{
bool hasStatic = false;
if(desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
indexA=uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies)/mStride;
activeA = indexA < mBodyCount;
hasStatic = !activeA;//desc.bodyADataIndex == 0;
bodyAProgress = activeA ? desc.bodyA->solverProgress: 0;
}
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
indexA=mBodyCount+ articulationA->mArticulationIndex;
//bodyAProgress = articulationA->getFsDataPtr()->solverProgress;
bodyAProgress = articulationA->solverProgress;
activeA = true;
}
if(desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
indexB=uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies)/mStride;
activeB = indexB < mBodyCount;
hasStatic = hasStatic || !activeB;
bodyBProgress = activeB ? desc.bodyB->solverProgress : 0;
}
else
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
indexB=mBodyCount+ articulationB->mArticulationIndex;
activeB = true;
bodyBProgress = articulationB->solverProgress;
}
return !hasStatic;
}
/* PX_FORCE_INLINE void getProgress(const PxSolverConstraintDesc& desc,
PxU32& bodyAProgress, PxU32& bodyBProgress) const
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
bodyAProgress = desc.bodyA->solverProgress;
}
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
bodyAProgress = articulationA->solverProgress;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
bodyBProgress = desc.bodyB->solverProgress;
}
else
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
bodyBProgress = articulationB->solverProgress;
}
}*/
PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress, PxU16 availablePartition)
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
desc.bodyA->solverProgress = bodyAProgress;
desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, availablePartition);
}
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
articulationA->solverProgress = bodyAProgress;
articulationA->maxSolverNormalProgress = PxMax(articulationA->maxSolverNormalProgress, availablePartition);
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
desc.bodyB->solverProgress = bodyBProgress;
desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, availablePartition);
}
else
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
articulationB->solverProgress = bodyBProgress;
articulationB->maxSolverNormalProgress = PxMax(articulationB->maxSolverNormalProgress, availablePartition);
}
}
PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress)
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
desc.bodyA->solverProgress = bodyAProgress;
}
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
articulationA->solverProgress = bodyAProgress;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
desc.bodyB->solverProgress = bodyBProgress;
}
else
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
articulationB->solverProgress = bodyBProgress;
}
}
PX_FORCE_INLINE void recordStaticConstraint(const PxSolverConstraintDesc& desc, bool& activeA, bool& activeB)
{
if (activeA)
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
desc.bodyA->maxSolverFrictionProgress++;
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
if(!articulationA->willStoreStaticConstraint() || mForceStaticCollisionsToSolver)
articulationA->maxSolverFrictionProgress++;
}
}
if (activeB)
{
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
desc.bodyB->maxSolverFrictionProgress++;
else
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
if (!articulationB->willStoreStaticConstraint() || mForceStaticCollisionsToSolver)
articulationB->maxSolverFrictionProgress++;
}
}
}
PX_FORCE_INLINE void getProgressRequirements(const PxSolverConstraintDesc& desc, PxU32& progressA, PxU32& progressB) const
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
uintptr_t indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mStride;
if(indexA < mBodyCount)
progressA = desc.bodyA->maxSolverFrictionProgress++;
else
progressA = 0;
}
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
progressA = articulationA->maxSolverFrictionProgress++;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
uintptr_t indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mStride;
if(indexB < mBodyCount)
progressB = desc.bodyB->maxSolverFrictionProgress++;
else
progressB = 0;
}
else
{
if (desc.articulationA != desc.articulationB)
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
progressB = articulationB->maxSolverFrictionProgress++;
}
else
progressB = progressA;
}
}
PX_FORCE_INLINE PxU32 getStaticContactWriteIndex(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const
{
if (activeA)
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
return PxU32(desc.bodyA->maxSolverNormalProgress + desc.bodyA->maxSolverFrictionProgress++);
}
else
{
FeatherstoneArticulation* articulationA = getArticulationA(desc);
//Attempt to store static constraints on the articulation (only supported with the reduced coordinate articulations).
//This acts as an optimization
if(!mForceStaticCollisionsToSolver && articulationA->storeStaticConstraint(desc))
return 0xffffffff;
return PxU32(articulationA->maxSolverNormalProgress + articulationA->maxSolverFrictionProgress++);
}
}
else if (activeB)
{
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
return PxU32(desc.bodyB->maxSolverNormalProgress + desc.bodyB->maxSolverFrictionProgress++);
}
else
{
FeatherstoneArticulation* articulationB = getArticulationB(desc);
//Attempt to store static constraints on the articulation (only supported with the reduced coordinate articulations).
//This acts as an optimization
if (!mForceStaticCollisionsToSolver && articulationB->storeStaticConstraint(desc))
return 0xffffffff;
return PxU32(articulationB->maxSolverNormalProgress + articulationB->maxSolverFrictionProgress++);
}
}
return 0xffffffff;
}
PX_FORCE_INLINE void clearState()
{
for(PxU32 a = 0; a < mBodySize; a+= mStride)
reinterpret_cast<PxSolverBody*>(mBodies+a)->solverProgress = 0;
for(PxU32 a = 0; a < mNumArticulations; ++a)
(reinterpret_cast<FeatherstoneArticulation*>(mArticulations[a]))->solverProgress = 0;
}
PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxArray<PxU32>& numConstraintsPerPartition)
{
for(PxU32 a = 0; a < mBodySize; a+= mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies+a);
body.solverProgress = 0;
PxU32 requiredSize = PxU32(body.maxSolverNormalProgress + body.maxSolverFrictionProgress);
if(requiredSize > numConstraintsPerPartition.size())
{
numConstraintsPerPartition.resize(requiredSize);
}
for(PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b)
{
numConstraintsPerPartition[body.maxSolverNormalProgress + b]++;
}
}
for(PxU32 a = 0; a < mNumArticulations; ++a)
{
FeatherstoneArticulation* articulation = reinterpret_cast<FeatherstoneArticulation*>(mArticulations[a]);
articulation->solverProgress = 0;
PxU32 requiredSize = PxU32(articulation->maxSolverNormalProgress + articulation->maxSolverFrictionProgress);
if(requiredSize > numConstraintsPerPartition.size())
{
numConstraintsPerPartition.resize(requiredSize);
}
for(PxU32 b = 0; b < articulation->maxSolverFrictionProgress; ++b)
{
numConstraintsPerPartition[articulation->maxSolverNormalProgress + b]++;
}
}
}
};
template <typename Classification>
static PxU32 classifyConstraintDesc(const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification,
PxArray<PxU32>& numConstraintsPerPartition, PxSolverConstraintDesc* PX_RESTRICT eaTempConstraintDescriptors,
PxU32 maxPartitions)
{
const PxSolverConstraintDesc* _desc = descs;
const PxU32 numConstraintsMin1 = numConstraints - 1;
PxU32 numUnpartitionedConstraints = 0;
numConstraintsPerPartition.forceSize_Unsafe(32);
PxMemZero(numConstraintsPerPartition.begin(), sizeof(PxU32) * 32);
for(PxU32 i = 0; i < numConstraints; ++i, _desc++)
{
const PxU32 prefetchOffset = PxMin(numConstraintsMin1 - i, 4u);
PxPrefetchLine(_desc[prefetchOffset].constraint);
PxPrefetchLine(_desc[prefetchOffset].bodyA);
PxPrefetchLine(_desc[prefetchOffset].bodyB);
PxPrefetchLine(_desc + 8);
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
const bool notContainsStatic = classification.classifyConstraint(*_desc, indexA, indexB, activeA, activeB,
partitionsA, partitionsB);
if(notContainsStatic)
{
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if(availablePartition == MAX_NUM_PARTITIONS)
{
eaTempConstraintDescriptors[numUnpartitionedConstraints++] = *_desc;
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
if (activeA)
partitionsA |= partitionBit;
if(activeB)
partitionsB |= partitionBit;
}
numConstraintsPerPartition[availablePartition]++;
availablePartition++;
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition));
}
else
{
classification.recordStaticConstraint(*_desc, activeA, activeB);
}
}
PxU32 partitionStartIndex = 0;
while (numUnpartitionedConstraints > 0)
{
classification.clearState();
partitionStartIndex += 32;
if(maxPartitions <= partitionStartIndex)
break;
//Keep partitioning the un-partitioned constraints and blat the whole thing to 0!
numConstraintsPerPartition.resize(32 + numConstraintsPerPartition.size());
PxMemZero(numConstraintsPerPartition.begin() + partitionStartIndex, sizeof(PxU32) * 32);
PxU32 newNumUnpartitionedConstraints = 0;
PxU32 partitionsA, partitionsB;
bool activeA, activeB;
uintptr_t indexA, indexB;
for (PxU32 i = 0; i < numUnpartitionedConstraints; ++i)
{
const PxSolverConstraintDesc& desc = eaTempConstraintDescriptors[i];
classification.classifyConstraint(desc, indexA, indexB, activeA, activeB,
partitionsA, partitionsB);
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
{
//Need to shuffle around unpartitioned constraints...
eaTempConstraintDescriptors[newNumUnpartitionedConstraints++] = desc;
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
if (activeA)
partitionsA |= partitionBit;
if (activeB)
partitionsB |= partitionBit;
}
/*desc.bodyA->solverProgress = partitionsA;
desc.bodyB->solverProgress = partitionsB;*/
availablePartition += partitionStartIndex;
numConstraintsPerPartition[availablePartition]++;
availablePartition++;
classification.storeProgress(desc, partitionsA, partitionsB, PxU16(availablePartition));
/* desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, PxU16(availablePartition));
desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, PxU16(availablePartition));*/
}
numUnpartitionedConstraints = newNumUnpartitionedConstraints;
}
classification.reserveSpaceForStaticConstraints(numConstraintsPerPartition);
return numUnpartitionedConstraints;
}
template <typename Classification>
static PxU32 writeConstraintDesc( const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification,
PxArray<PxU32>& accumulatedConstraintsPerPartition, PxSolverConstraintDesc* eaTempConstraintDescriptors,
PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDesc, PxU32 maxPartitions, PxU32 numOverflows)
{
PX_UNUSED(eaTempConstraintDescriptors);
const PxSolverConstraintDesc* _desc = descs;
const PxU32 numConstraintsMin1 = numConstraints - 1;
PxU32 numUnpartitionedConstraints = 0;
PxU32 numStaticConstraints = 0;
for(PxU32 i = 0; i < numConstraints; ++i, _desc++)
{
const PxU32 prefetchOffset = PxMin(numConstraintsMin1 - i, 4u);
PxPrefetchLine(_desc[prefetchOffset].constraint);
PxPrefetchLine(_desc[prefetchOffset].bodyA);
PxPrefetchLine(_desc[prefetchOffset].bodyB);
PxPrefetchLine(_desc + 8);
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
const bool notContainsStatic = classification.classifyConstraint(*_desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB);
if(notContainsStatic)
{
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if(availablePartition == MAX_NUM_PARTITIONS)
{
eaTempConstraintDescriptors[numUnpartitionedConstraints++] = *_desc;
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
if(activeA)
partitionsA |= partitionBit;
if(activeB)
partitionsB |= partitionBit;
}
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition + 1));
eaOrderedConstraintDesc[numOverflows + accumulatedConstraintsPerPartition[availablePartition]++] = *_desc;
}
else
{
//Just count the number of static constraints and store in maxSolverFrictionProgress...
PxU32 index = classification.getStaticContactWriteIndex(*_desc, activeA, activeB);
if (index != 0xffffffff)
{
eaOrderedConstraintDesc[numOverflows + accumulatedConstraintsPerPartition[index]++] = *_desc;
}
else
numStaticConstraints++;
}
}
PxU32 partitionStartIndex = 0;
while (numUnpartitionedConstraints > 0)
{
classification.clearState();
partitionStartIndex += 32;
if(partitionStartIndex >= maxPartitions)
break;
PxU32 newNumUnpartitionedConstraints = 0;
PxU32 partitionsA, partitionsB;
bool activeA, activeB;
uintptr_t indexA, indexB;
for (PxU32 i = 0; i < numUnpartitionedConstraints; ++i)
{
const PxSolverConstraintDesc& desc = eaTempConstraintDescriptors[i];
/* PxU32 partitionsA=desc.bodyA->solverProgress;
PxU32 partitionsB=desc.bodyB->solverProgress;*/
classification.classifyConstraint(desc, indexA, indexB,
activeA, activeB, partitionsA, partitionsB);
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
{
//Need to shuffle around unpartitioned constraints...
eaTempConstraintDescriptors[newNumUnpartitionedConstraints++] = desc;
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
if (activeA)
partitionsA |= partitionBit;
if (activeB)
partitionsB |= partitionBit;
}
/*desc.bodyA->solverProgress = partitionsA;
desc.bodyB->solverProgress = partitionsB;
*/
classification.storeProgress(desc, partitionsA, partitionsB);
availablePartition += partitionStartIndex;
eaOrderedConstraintDesc[numOverflows + accumulatedConstraintsPerPartition[availablePartition]++] = desc;
}
numUnpartitionedConstraints = newNumUnpartitionedConstraints;
}
return numStaticConstraints;
}
static void outputOverflowConstraints(
PxArray<PxU32>& accumulatedConstraintsPerPartition, PxSolverConstraintDesc* overflowConstraints, PxU32 nbOverflowConstraints,
PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDesc)
{
//Firstly, we resize and shuffle accumulatedConstraintsPerPartition
accumulatedConstraintsPerPartition.resize(accumulatedConstraintsPerPartition.size()+1);
PxU32 partitionCount = accumulatedConstraintsPerPartition.size();
while(partitionCount-- > 1)
{
accumulatedConstraintsPerPartition[partitionCount] = accumulatedConstraintsPerPartition[partitionCount -1] + nbOverflowConstraints;
}
accumulatedConstraintsPerPartition[0] = nbOverflowConstraints;
//Now fill in the constraints and work out the iter
for (PxU32 i = 0; i < nbOverflowConstraints; ++i)
{
eaOrderedConstraintDesc[i] = overflowConstraints[i];
}
}
}
#define PX_NORMALIZE_PARTITIONS 1
#if PX_NORMALIZE_PARTITIONS
#ifdef REMOVED_UNUSED
template<typename Classification>
PxU32 normalizePartitions(PxArray<PxU32>& accumulatedConstraintsPerPartition, PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDescriptors,
PxU32 numConstraintDescriptors, PxArray<PxU32>& bitField, const Classification& classification, PxU32 numBodies, PxU32 numArticulations)
{
PxU32 numPartitions = 0;
PxU32 prevAccumulation = 0;
for(; numPartitions < accumulatedConstraintsPerPartition.size() && accumulatedConstraintsPerPartition[numPartitions] > prevAccumulation;
prevAccumulation = accumulatedConstraintsPerPartition[numPartitions++]);
PxU32 targetSize = (numPartitions == 0 ? 0 : (numConstraintDescriptors)/numPartitions);
bitField.reserve((numBodies + numArticulations + 31)/32);
bitField.forceSize_Unsafe((numBodies + numArticulations + 31)/32);
for(PxU32 i = numPartitions; i > 0; i--)
{
PxU32 partitionIndex = i-1;
//Build the partition mask...
PxU32 startIndex = partitionIndex == 0 ? 0 : accumulatedConstraintsPerPartition[partitionIndex-1];
PxU32 endIndex = accumulatedConstraintsPerPartition[partitionIndex];
//If its greater than target size, there's nothing that will be pulled into it from earlier partitions
if((endIndex - startIndex) >= targetSize)
continue;
PxMemZero(bitField.begin(), sizeof(PxU32)*bitField.size());
for(PxU32 a = startIndex; a < endIndex; ++a)
{
PxSolverConstraintDesc& desc = eaOrderedConstraintDescriptors[a];
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
classification.classifyConstraint(desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB);
if (activeA)
bitField[PxU32(indexA) / 32] |= (1u << (indexA & 31));
if(activeB)
bitField[PxU32(indexB)/32] |= (1u << (indexB & 31));
}
bool bTerm = false;
for(PxU32 a = partitionIndex; a > 0 && !bTerm; --a)
{
PxU32 pInd = a-1;
PxU32 si = pInd == 0 ? 0 : accumulatedConstraintsPerPartition[pInd-1];
PxU32 ei = accumulatedConstraintsPerPartition[pInd];
for(PxU32 b = ei; b > si && !bTerm; --b)
{
PxU32 ind = b-1;
PxSolverConstraintDesc& desc = eaOrderedConstraintDescriptors[ind];
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
classification.classifyConstraint(desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB);
bool canAdd = true;
if(activeA && (bitField[PxU32(indexA)/32] & (1u << (indexA & 31))))
canAdd = false;
if(activeB && (bitField[PxU32(indexB)/32] & (1u << (indexB & 31))))
canAdd = false;
if(canAdd)
{
PxSolverConstraintDesc tmp = eaOrderedConstraintDescriptors[ind];
if(activeA)
bitField[PxU32(indexA)/32] |= (1u << (indexA & 31));
if(activeB)
bitField[PxU32(indexB)/32] |= (1u << (indexB & 31));
PxU32 index = ind;
for(PxU32 c = pInd; c < partitionIndex; ++c)
{
PxU32 newIndex = --accumulatedConstraintsPerPartition[c];
if(index != newIndex)
eaOrderedConstraintDescriptors[index] = eaOrderedConstraintDescriptors[newIndex];
index = newIndex;
}
if(index != ind)
eaOrderedConstraintDescriptors[index] = tmp;
if((accumulatedConstraintsPerPartition[partitionIndex] - accumulatedConstraintsPerPartition[partitionIndex-1]) >= targetSize)
{
bTerm = true;
break;
}
}
}
}
}
PxU32 partitionCount = 0;
PxU32 lastPartitionCount = 0;
for (PxU32 a = 0; a < numPartitions; ++a)
{
const PxU32 constraintCount = accumulatedConstraintsPerPartition[a];
accumulatedConstraintsPerPartition[partitionCount] = constraintCount;
if (constraintCount != lastPartitionCount)
{
lastPartitionCount = constraintCount;
partitionCount++;
}
}
accumulatedConstraintsPerPartition.forceSize_Unsafe(partitionCount);
return partitionCount;
}
#endif
#endif
PxU32 partitionContactConstraints(ConstraintPartitionArgs& args)
{
PxU32 maxPartition = 0;
//Unpack the input data.
const PxU32 numBodies = args.mNumBodies;
const PxU32 numArticulations = args.mNumArticulationPtrs;
const PxU32 numConstraintDescriptors = args.mNumContactConstraintDescriptors;
const PxSolverConstraintDesc* PX_RESTRICT eaConstraintDescriptors = args.mContactConstraintDescriptors;
PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDescriptors = args.mOrderedContactConstraintDescriptors;
PxSolverConstraintDesc* PX_RESTRICT eaOverflowConstraintDescriptors = args.mOverflowConstraintDescriptors;
PxArray<PxU32>& constraintsPerPartition = *args.mConstraintsPerPartition;
constraintsPerPartition.forceSize_Unsafe(0);
const PxU32 stride = args.mStride;
for(PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += stride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(args.mBodies + offset);
body.solverProgress = 0;
//We re-use maxSolverFrictionProgress and maxSolverNormalProgress to record the
//maximum partition used by dynamic constraints and the number of static constraints affecting
//a body. We use this to make partitioning much cheaper and be able to support an arbitrary number of dynamic partitions.
body.maxSolverFrictionProgress = 0;
body.maxSolverNormalProgress = 0;
}
PxU32 numOrderedConstraints=0;
PxU32 numStaticConstraints = 0;
PxU32 numOverflows = 0;
if(numArticulations == 0)
{
RigidBodyClassification classification(args.mBodies, numBodies, stride);
numOverflows = classifyConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition,
eaOverflowConstraintDescriptors, args.mMaxPartitions);
PxU32 accumulation = 0;
for(PxU32 a = 0; a < constraintsPerPartition.size(); ++a)
{
PxU32 count = constraintsPerPartition[a];
constraintsPerPartition[a] = accumulation;
accumulation += count;
}
for(PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += stride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(args.mBodies + offset);
PxPrefetchLine(&args.mBodies[a], 256);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
writeConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition,
eaOverflowConstraintDescriptors, eaOrderedConstraintDescriptors, args.mMaxPartitions, numOverflows);
numOrderedConstraints = numConstraintDescriptors;
//Next step, let's slot the overflow partitions into the first slot and work out targets for them...
if (numOverflows)
{
outputOverflowConstraints(constraintsPerPartition,
eaOverflowConstraintDescriptors, numOverflows, eaOrderedConstraintDescriptors);
}
}
else
{
const ArticulationSolverDesc* articulationDescs=args.mArticulationPtrs;
PX_ALLOCA(_eaArticulations, Dy::FeatherstoneArticulation*, numArticulations);
Dy::FeatherstoneArticulation** eaArticulations = _eaArticulations;
for(PxU32 i=0;i<numArticulations;i++)
{
FeatherstoneArticulation* articulation = articulationDescs[i].articulation;
eaArticulations[i]= articulation;
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
articulation->maxSolverNormalProgress = 0;
}
ExtendedRigidBodyClassification classification(args.mBodies, numBodies, stride, eaArticulations, numArticulations,
args.mForceStaticConstraintsToSolver);
numOverflows = classifyConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification,
constraintsPerPartition, eaOverflowConstraintDescriptors, args.mMaxPartitions);
PxU32 accumulation = 0;
for(PxU32 a = 0; a < constraintsPerPartition.size(); ++a)
{
PxU32 count = constraintsPerPartition[a];
constraintsPerPartition[a] = accumulation;
accumulation += count;
}
for(PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += stride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(args.mBodies+offset);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
for(PxU32 a = 0; a < numArticulations; ++a)
{
FeatherstoneArticulation* articulation = eaArticulations[a];
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
}
numStaticConstraints = writeConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition,
eaOverflowConstraintDescriptors, eaOrderedConstraintDescriptors, args.mMaxPartitions, numOverflows);
numOrderedConstraints = numConstraintDescriptors - numStaticConstraints;
if (numOverflows)
{
outputOverflowConstraints(constraintsPerPartition,
eaOverflowConstraintDescriptors, numOverflows, eaOrderedConstraintDescriptors);
}
}
const PxU32 numConstraintsDifferentBodies=numOrderedConstraints;
//PX_ASSERT(numConstraintsDifferentBodies == numConstraintDescriptors);
//Now handle the articulated self-constraints.
PxU32 totalConstraintCount = numConstraintsDifferentBodies;
args.mNumDifferentBodyConstraints=numConstraintsDifferentBodies;
args.mNumSelfConstraints=totalConstraintCount-numConstraintsDifferentBodies;
args.mNumStaticConstraints = numStaticConstraints;
args.mNumOverflowConstraints = numOverflows;
//if (args.enhancedDeterminism)
{
PxU32 prevPartitionSize = 0;
maxPartition = 0;
for (PxU32 a = 0; a < constraintsPerPartition.size(); ++a, maxPartition++)
{
if (constraintsPerPartition[a] == prevPartitionSize)
break;
prevPartitionSize = constraintsPerPartition[a];
}
}
return maxPartition;
}
void processOverflowConstraints(PxU8* bodies, PxU32 bodyStride, PxU32 numBodies, Dy::ArticulationSolverDesc* articulationDescs, PxU32 numArticulations,
PxSolverConstraintDesc* constraints, PxU32 numConstraints)
{
for (PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += bodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(bodies + offset);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
if (numConstraints == 0)
return;
if (numArticulations == 0)
{
RigidBodyClassification classification(bodies, numBodies, bodyStride);
for (PxU32 i = 0; i < numConstraints; ++i)
{
PxU32 progressA, progressB;
classification.getProgressRequirements(constraints[i], progressA, progressB);
constraints[i].progressA = PxTo16(progressA);
constraints[i].progressB = PxTo16(progressB);
}
}
else
{
PX_ALLOCA(_eaArticulations, Dy::FeatherstoneArticulation*, numArticulations);
Dy::FeatherstoneArticulation** eaArticulations = _eaArticulations;
for (PxU32 i = 0; i<numArticulations; i++)
{
FeatherstoneArticulation* articulation = articulationDescs[i].articulation;
eaArticulations[i] = articulation;
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
//articulation->maxSolverNormalProgress = 0;
}
ExtendedRigidBodyClassification classification(bodies, numBodies, bodyStride, eaArticulations, numArticulations, false);
for (PxU32 i = 0; i < numConstraints; ++i)
{
PxU32 progressA, progressB;
classification.getProgressRequirements(constraints[i], progressA, progressB);
constraints[i].progressA = PxTo16(progressA);
constraints[i].progressB = PxTo16(progressB);
}
}
}
}
}
| 33,895 | C++ | 33.482197 | 185 | 0.753356 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationContactPrep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DyCorrelationBuffer.h"
#include "DySolverConstraintExtShared.h"
#include "DyArticulationCpuGpu.h"
#include "DyFeatherstoneArticulation.h"
using namespace physx::Gu;
namespace physx
{
namespace Dy
{
// constraint-gen only, since these use getVelocity methods
// which aren't valid during the solver phase
//PX_INLINE void computeFrictionTangents(const aos::Vec3V& vrel,const aos::Vec3V& unitNormal, aos::Vec3V& t0, aos::Vec3V& t1)
//{
// using namespace aos;
// //PX_ASSERT(PxAbs(unitNormal.magnitude()-1)<1e-3f);
//
// t0 = V3Sub(vrel, V3Scale(unitNormal, V3Dot(unitNormal, vrel)));
// const FloatV ll = V3Dot(t0, t0);
//
// if (FAllGrtr(ll, FLoad(1e10f))) //can set as low as 0.
// {
// t0 = V3Scale(t0, FRsqrt(ll));
// t1 = V3Cross(unitNormal, t0);
// }
// else
// PxNormalToTangents(unitNormal, t0, t1); //fallback
//}
PxReal SolverExtBody::projectVelocity(const PxVec3& linear, const PxVec3& angular) const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
return mBodyData->projectVelocity(linear, angular);
}
else
{
const Cm::SpatialVectorV velocity = mArticulation->getLinkVelocity(mLinkIndex);
const FloatV fv = velocity.dot(Cm::SpatialVector(linear, angular));
PxF32 f;
FStore(fv, &f);
return f;
/*PxF32 f;
FStore(getVelocity(*mFsData)[mLinkIndex].dot(Cm::SpatialVector(linear, angular)), &f);
return f;*/
}
}
PxReal SolverExtBody::getCFM() const
{
return (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) ? 0.f :
mArticulation->getCfm(mLinkIndex);
}
aos::FloatV SolverExtBody::projectVelocity(const aos::Vec3V& linear, const aos::Vec3V& angular) const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
return V3SumElems(V3Add(V3Mul(V3LoadA(mBodyData->linearVelocity), linear), V3Mul(V3LoadA(mBodyData->angularVelocity), angular)));
}
else
{
const Cm::SpatialVectorV velocity = mArticulation->getLinkVelocity(mLinkIndex);
return velocity.dot(Cm::SpatialVectorV(linear, angular));
}
}
PxVec3 SolverExtBody::getLinVel() const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return mBodyData->linearVelocity;
else
{
const Vec3V linear = mArticulation->getLinkVelocity(mLinkIndex).linear;
PxVec3 result;
V3StoreU(linear, result);
/*PxVec3 result;
V3StoreU(getVelocity(*mFsData)[mLinkIndex].linear, result);*/
return result;
}
}
PxVec3 SolverExtBody::getAngVel() const
{
if(mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return mBodyData->angularVelocity;
else
{
const Vec3V angular = mArticulation->getLinkVelocity(mLinkIndex).angular;
PxVec3 result;
V3StoreU(angular, result);
/*PxVec3 result;
V3StoreU(getVelocity(*mFsData)[mLinkIndex].angular, result);*/
return result;
}
}
aos::Vec3V SolverExtBody::getLinVelV() const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return V3LoadA(mBodyData->linearVelocity);
else
{
return mArticulation->getLinkVelocity(mLinkIndex).linear;
}
}
Vec3V SolverExtBody::getAngVelV() const
{
if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return V3LoadA(mBodyData->angularVelocity);
else
{
return mArticulation->getLinkVelocity(mLinkIndex).angular;
}
}
Cm::SpatialVectorV SolverExtBody::getVelocity() const
{
if(mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
return Cm::SpatialVectorV(V3LoadA(mBodyData->linearVelocity), V3LoadA(mBodyData->angularVelocity));
else
return mArticulation->getLinkVelocity(mLinkIndex);
}
Cm::SpatialVector createImpulseResponseVector(const PxVec3& linear, const PxVec3& angular, const SolverExtBody& body)
{
if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
return Cm::SpatialVector(linear, body.mBodyData->sqrtInvInertia * angular);
}
return Cm::SpatialVector(linear, angular);
}
Cm::SpatialVectorV createImpulseResponseVector(const aos::Vec3V& linear, const aos::Vec3V& angular, const SolverExtBody& body)
{
if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
return Cm::SpatialVectorV(linear, M33MulV3(M33Load(body.mBodyData->sqrtInvInertia), angular));
}
return Cm::SpatialVectorV(linear, angular);
}
PxReal getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxReal dom0, PxReal angDom0,
const SolverExtBody& b1, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, PxReal dom1, PxReal angDom1,
Cm::SpatialVectorF* Z, bool allowSelfCollision)
{
PxReal response;
allowSelfCollision = false;
// right now self-collision with contacts crashes the solver
//KS - knocked this out to save some space on SPU
if(allowSelfCollision && b0.mLinkIndex!=PxSolverConstraintDesc::RIGID_BODY && b0.mArticulation == b1.mArticulation && 0)
{
/*ArticulationHelper::getImpulseSelfResponse(*b0.mFsData,b0.mLinkIndex, impulse0, deltaV0,
b1.mLinkIndex, impulse1, deltaV1);*/
b0.mArticulation->getImpulseSelfResponse(b0.mLinkIndex, b1.mLinkIndex, Z, impulse0.scale(dom0, angDom0), impulse1.scale(dom1, angDom1),
deltaV0, deltaV1);
response = impulse0.dot(deltaV0) + impulse1.dot(deltaV1);
}
else
{
if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV0.linear = impulse0.linear * b0.mBodyData->invMass * dom0;
deltaV0.angular = impulse0.angular * angDom0;
}
else
{
b0.mArticulation->getImpulseResponse(b0.mLinkIndex, Z, impulse0.scale(dom0, angDom0), deltaV0);
}
response = impulse0.dot(deltaV0);
if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV1.linear = impulse1.linear * b1.mBodyData->invMass * dom1;
deltaV1.angular = impulse1.angular * angDom1;
}
else
{
b1.mArticulation->getImpulseResponse( b1.mLinkIndex, Z, impulse1.scale(dom1, angDom1), deltaV1);
}
response += impulse1.dot(deltaV1);
}
return response;
}
FloatV getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, const FloatV& dom0, const FloatV& angDom0,
const SolverExtBody& b1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1, const FloatV& dom1, const FloatV& angDom1,
Cm::SpatialVectorV* Z, bool /*allowSelfCollision*/)
{
Vec3V response;
{
if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV0.linear = V3Scale(impulse0.linear, FMul(FLoad(b0.mBodyData->invMass), dom0));
deltaV0.angular = V3Scale(impulse0.angular, angDom0);
}
else
{
b0.mArticulation->getImpulseResponse(b0.mLinkIndex, Z, impulse0.scale(dom0, angDom0), deltaV0);
}
response = V3Add(V3Mul(impulse0.linear, deltaV0.linear), V3Mul(impulse0.angular, deltaV0.angular));
if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
deltaV1.linear = V3Scale(impulse1.linear, FMul(FLoad(b1.mBodyData->invMass), dom1));
deltaV1.angular = V3Scale(impulse1.angular, angDom1);
}
else
{
b1.mArticulation->getImpulseResponse(b1.mLinkIndex, Z, impulse1.scale(dom1, angDom1), deltaV1);
}
response = V3Add(response, V3Add(V3Mul(impulse1.linear, deltaV1.linear), V3Mul(impulse1.angular, deltaV1.angular)));
}
return V3SumElems(response);
}
void setupFinalizeExtSolverContacts(
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const SolverExtBody& b0,
const SolverExtBody& b1,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
const PxReal restDist,
PxU8* frictionDataPtr,
PxReal ccdMaxContactDist,
Cm::SpatialVectorF* Z,
const PxReal offsetSlop)
{
// NOTE II: the friction patches are sparse (some of them have no contact patches, and
// therefore did not get written back to the cache) but the patch addresses are dense,
// corresponding to valid patches
/*const bool haveFriction = PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;*/
const FloatV ccdMaxSeparation = FLoad(ccdMaxContactDist);
const Vec3VArg solverOffsetSlop = V3Load(offsetSlop);
PxU8* PX_RESTRICT ptr = workspace;
const FloatV zero = FZero();
//KS - TODO - this should all be done in SIMD to avoid LHS
//const PxF32 maxPenBias0 = b0.mLinkIndex == PxSolverConstraintDesc::NO_LINK ? b0.mBodyData->penBiasClamp : getMaxPenBias(*b0.mFsData)[b0.mLinkIndex];
//const PxF32 maxPenBias1 = b1.mLinkIndex == PxSolverConstraintDesc::NO_LINK ? b1.mBodyData->penBiasClamp : getMaxPenBias(*b1.mFsData)[b1.mLinkIndex];
PxF32 maxPenBias0;
PxF32 maxPenBias1;
if (b0.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY)
{
maxPenBias0 = b0.mArticulation->getLinkMaxPenBias(b0.mLinkIndex);
}
else
maxPenBias0 = b0.mBodyData->penBiasClamp;
if (b1.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY)
{
maxPenBias1 = b1.mArticulation->getLinkMaxPenBias(b1.mLinkIndex);
}
else
maxPenBias1 = b1.mBodyData->penBiasClamp;
const FloatV maxPenBias = FLoad(PxMax(maxPenBias0, maxPenBias1));
const Vec3V frame0p = V3LoadU(bodyFrame0.p);
const Vec3V frame1p = V3LoadU(bodyFrame1.p);
const Cm::SpatialVectorV vel0 = b0.getVelocity();
const Cm::SpatialVectorV vel1 = b1.getVelocity();
const FloatV quarter = FLoad(0.25f);
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV cfm = FLoad(PxMax(b0.getCFM(), b1.getCFM()));
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero();
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d0);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d1);
const FloatV restDistance = FLoad(restDist);
PxU32 frictionPatchWritebackAddrIndex = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
const FloatV invDt = FLoad(invDtF32);
const FloatV p8 = FLoad(0.8f);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const FloatV invDtp8 = FMul(invDt, p8);
const FloatV dt = FLoad(dtF32);
PxU8 flags = 0;
for(PxU32 i=0;i<c.frictionPatchCount;i++)
{
PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
PX_ASSERT(frictionPatch.anchorCount <= 2); //0==anchorCount is allowed if all the contacts in the manifold have a large offset.
const PxContactPoint* contactBase0 = buffer + c.contactPatches[c.correlationListHeads[i]].start;
const PxReal coefficient = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f;
const PxReal staticFriction = contactBase0->staticFriction * coefficient;
const PxReal dynamicFriction = contactBase0->dynamicFriction * coefficient;
const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(staticFriction));
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(dynamicFriction));
SolverContactHeader* PX_RESTRICT header = reinterpret_cast<SolverContactHeader*>(ptr);
ptr += sizeof(SolverContactHeader);
PxPrefetchLine(ptr + 128);
PxPrefetchLine(ptr + 256);
PxPrefetchLine(ptr + 384);
const bool haveFriction = (disableStrongFriction == 0) ;//PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;
header->numNormalConstr = PxTo8(contactCount);
header->numFrictionConstr = PxTo8(haveFriction ? frictionPatch.anchorCount*2 : 0);
header->type = PxTo8(DY_SC_TYPE_EXT_CONTACT);
header->flags = flags;
const FloatV restitution = FLoad(contactBase0->restitution);
const FloatV damping = FLoad(contactBase0->damping);
header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W;
header->angDom0 = invInertiaScale0;
header->angDom1 = invInertiaScale1;
const PxU32 pointStride = sizeof(SolverContactPointExt);
const PxU32 frictionStride = sizeof(SolverContactFrictionExt);
const Vec3V normal = V3LoadU(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal);
FloatV accumImpulse = FZero();
const FloatV norVel0 = V3Dot(normal, vel0.linear);
const FloatV norVel1 = V3Dot(normal, vel1.linear);
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer + c.contactPatches[patch].start;
PxU8* p = ptr;
for(PxU32 j=0;j<count;j++)
{
const PxContactPoint& contact = contactBase[j];
SolverContactPointExt* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointExt*>(p);
p += pointStride;
accumImpulse = FAdd(accumImpulse, setupExtSolverContact(b0, b1, d0, d1, angD0, angD1, frame0p, frame1p, normal, invDt, invDtp8, dt, restDistance, maxPenBias, restitution,
bounceThreshold, contact, *solverContact, ccdMaxSeparation, Z, vel0, vel1, cfm, solverOffsetSlop, norVel0, norVel1, damping));
}
ptr = p;
}
accumImpulse = FMul(FDiv(accumImpulse, FLoad(PxF32(contactCount))), quarter);
header->normal_minAppliedImpulseForFrictionW = V4SetW(Vec4V_From_Vec3V(normal), accumImpulse);
PxF32* forceBuffer = reinterpret_cast<PxF32*>(ptr);
PxMemZero(forceBuffer, sizeof(PxF32) * contactCount);
ptr += sizeof(PxF32) * ((contactCount + 3) & (~3));
header->broken = 0;
if(haveFriction)
{
//const Vec3V normal = Vec3V_From_PxVec3(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
//Vec3V normalS = V3LoadA(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal);
const Vec3V linVrel = V3Sub(vel0.linear, vel1.linear);
//const Vec3V normal = Vec3V_From_PxVec3_Aligned(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV orthoThreshold = FLoad(0.70710678f);
const FloatV p1 = FLoad(0.0001f);
// fallback: normal.cross((1,0,0)) or normal.cross((0,0,1))
const FloatV normalX = V3GetX(normal);
const FloatV normalY = V3GetY(normal);
const FloatV normalZ = V3GetZ(normal);
Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY);
Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero);
Vec3V t0Fallback = V3Sel(FIsGrtr(orthoThreshold, FAbs(normalX)), t0Fallback1, t0Fallback2);
Vec3V t0 = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel)));
t0 = V3Sel(FIsGrtr(V3LengthSq(t0), p1), t0, t0Fallback);
t0 = V3Normalize(t0);
const VecCrossV t0Cross = V3PrepareCross(t0);
const Vec3V t1 = V3Cross(normal, t0Cross);
const VecCrossV t1Cross = V3PrepareCross(t1);
//We want to set the writeBack ptr to point to the broken flag of the friction patch.
//On spu we have a slight problem here because the friction patch array is
//in local store rather than in main memory. The good news is that the address of the friction
//patch array in main memory is stored in the work unit. These two addresses will be equal
//except on spu where one is local store memory and the other is the effective address in main memory.
//Using the value stored in the work unit guarantees that the main memory address is used on all platforms.
PxU8* PX_RESTRICT writeback = frictionDataPtr + frictionPatchWritebackAddrIndex*sizeof(FrictionPatch);
header->frictionBrokenWritebackByte = writeback;
for(PxU32 j = 0; j < frictionPatch.anchorCount; j++)
{
SolverContactFrictionExt* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionExt*>(ptr);
ptr += frictionStride;
SolverContactFrictionExt* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionExt*>(ptr);
ptr += frictionStride;
Vec3V ra = V3LoadU(bodyFrame0.q.rotate(frictionPatch.body0Anchors[j]));
Vec3V rb = V3LoadU(bodyFrame1.q.rotate(frictionPatch.body1Anchors[j]));
Vec3V error = V3Sub(V3Add(ra, frame0p), V3Add(rb, frame1p));
{
Vec3V raXn = V3Cross(ra, t0Cross);
Vec3V rbXn = V3Cross(rb, t0Cross);
raXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t0, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t0), V3Neg(rbXn), b1);
FloatV resp = FAdd(cfm, getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(Z)));
const FloatV velMultiplier = FSel(FIsGrtr(resp, FLoad(DY_ARTICULATION_MIN_RESPONSE)), FDiv(p8, resp), zero);
const PxU32 index = c.contactPatches[c.correlationListHeads[i]].start;
FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t0);
if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVel = FSub(targetVel, b0.projectVelocity(t0, raXn));
else if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVel = FAdd(targetVel, b1.projectVelocity(t0, rbXn));
f0->normalXYZ_appliedForceW = V4SetW(t0, zero);
f0->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), velMultiplier);
f0->rbXnXYZ_biasW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), FMul(V3Dot(t0, error), invDt));
f0->linDeltaVA = deltaV0.linear;
f0->angDeltaVA = deltaV0.angular;
f0->linDeltaVB = deltaV1.linear;
f0->angDeltaVB = deltaV1.angular;
FStore(targetVel, &f0->targetVel);
}
{
Vec3V raXn = V3Cross(ra, t1Cross);
Vec3V rbXn = V3Cross(rb, t1Cross);
raXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t1, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t1), V3Neg(rbXn), b1);
FloatV resp = FAdd(cfm, getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(Z)));
//const FloatV velMultiplier = FSel(FIsGrtr(resp, FLoad(DY_ARTICULATION_MIN_RESPONSE)), FMul(p8, FRecip(resp)), zero);
const FloatV velMultiplier = FSel(FIsGrtr(resp, FLoad(DY_ARTICULATION_MIN_RESPONSE)), FDiv(p8, resp), zero);
const PxU32 index = c.contactPatches[c.correlationListHeads[i]].start;
FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t1);
if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVel = FSub(targetVel, b0.projectVelocity(t1, raXn));
else if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVel = FAdd(targetVel, b1.projectVelocity(t1, rbXn));
f1->normalXYZ_appliedForceW = V4SetW(t1, zero);
f1->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), velMultiplier);
f1->rbXnXYZ_biasW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), FMul(V3Dot(t1, error), invDt));
f1->linDeltaVA = deltaV0.linear;
f1->angDeltaVA = deltaV0.angular;
f1->linDeltaVB = deltaV1.linear;
f1->angDeltaVB = deltaV1.angular;
FStore(targetVel, &f1->targetVel);
}
}
}
frictionPatchWritebackAddrIndex++;
}
}
}
}
| 21,350 | C++ | 36.067708 | 174 | 0.739813 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSContactPrepBlock.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "PxcNpContactPrepShared.h"
#include "DyTGSDynamics.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
#include "DyConstraintPrep.h"
#include "DyTGS.h"
namespace physx
{
namespace Dy
{
inline bool ValidateVec4(const Vec4V v)
{
PX_ALIGN(16, PxVec4 vF);
aos::V4StoreA(v, &vF.x);
return vF.isFinite();
}
PX_FORCE_INLINE void QuatRotate4(const Vec4VArg qx, const Vec4VArg qy, const Vec4VArg qz, const Vec4VArg qw, const Vec4VArg vx, const Vec4VArg vy, const Vec4VArg vz,
Vec4V& rX, Vec4V& rY, Vec4V& rZ)
{
/*
const PxVec3 qv(x,y,z);
return (v*(w*w-0.5f) + (qv.cross(v))*w + qv*(qv.dot(v)))*2;
*/
const Vec4V two = V4Splat(FLoad(2.f));
const Vec4V nhalf = V4Splat(FLoad(-0.5f));
const Vec4V w2 = V4MulAdd(qw, qw, nhalf);
const Vec4V ax = V4Mul(vx, w2);
const Vec4V ay = V4Mul(vy, w2);
const Vec4V az = V4Mul(vz, w2);
const Vec4V crX = V4NegMulSub(qz, vy, V4Mul(qy, vz));
const Vec4V crY = V4NegMulSub(qx, vz, V4Mul(qz, vx));
const Vec4V crZ = V4NegMulSub(qy, vx, V4Mul(qx, vy));
const Vec4V tempX = V4MulAdd(crX, qw, ax);
const Vec4V tempY = V4MulAdd(crY, qw, ay);
const Vec4V tempZ = V4MulAdd(crZ, qw, az);
Vec4V dotuv = V4Mul(qx, vx);
dotuv = V4MulAdd(qy, vy, dotuv);
dotuv = V4MulAdd(qz, vz, dotuv);
rX = V4Mul(V4MulAdd(qx, dotuv, tempX), two);
rY = V4Mul(V4MulAdd(qy, dotuv, tempY), two);
rZ = V4Mul(V4MulAdd(qz, dotuv, tempZ), two);
}
struct SolverContactHeaderStepBlock
{
enum
{
eHAS_MAX_IMPULSE = 1 << 0,
eHAS_TARGET_VELOCITY = 1 << 1
};
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 numNormalConstr;
PxU8 numFrictionConstr;
PxU8 flag;
PxU8 flags[4];
//KS - used for write-back only
PxU8 numNormalConstrs[4];
PxU8 numFrictionConstrs[4];
//Vec4V restitution;
Vec4V staticFriction;
Vec4V dynamicFriction;
//Technically, these mass properties could be pulled out into a new structure and shared. For multi-manifold contacts,
//this would save 64 bytes per-manifold after the cost of the first manifold
Vec4V invMass0D0;
Vec4V invMass1D1;
Vec4V angDom0;
Vec4V angDom1;
//Normal is shared between all contacts in the batch. This will save some memory!
Vec4V normalX;
Vec4V normalY;
Vec4V normalZ;
Vec4V maxPenBias;
Sc::ShapeInteraction* shapeInteraction[4]; //192 or 208
BoolV broken;
PxU8* frictionBrokenWritebackByte[4];
};
struct SolverContactPointStepBlock
{
Vec4V raXnI[3];
Vec4V rbXnI[3];
Vec4V separation;
Vec4V velMultiplier;
Vec4V targetVelocity;
Vec4V biasCoefficient;
Vec4V recipResponse;
};
//KS - technically, this friction constraint has identical data to the above contact constraint.
//We make them separate structs for clarity
struct SolverContactFrictionStepBlock
{
Vec4V normal[3];
Vec4V raXnI[3];
Vec4V rbXnI[3];
Vec4V error;
Vec4V velMultiplier;
Vec4V targetVel;
Vec4V biasCoefficient;
};
struct SolverConstraint1DHeaderStep4
{
PxU8 type; // enum SolverConstraintType - must be first byte
PxU8 pad0[3];
//These counts are the max of the 4 sets of data.
//When certain pairs have fewer constraints than others, they are padded with 0s so that no work is performed but
//calculations are still shared (afterall, they're computationally free because we're doing 4 things at a time in SIMD)
PxU32 count;
PxU8 counts[4];
PxU8 breakable[4];
Vec4V linBreakImpulse;
Vec4V angBreakImpulse;
Vec4V invMass0D0;
Vec4V invMass1D1;
Vec4V angD0;
Vec4V angD1;
Vec4V body0WorkOffset[3];
Vec4V rAWorld[3];
Vec4V rBWorld[3];
Vec4V angOrthoAxis0X[3];
Vec4V angOrthoAxis0Y[3];
Vec4V angOrthoAxis0Z[3];
Vec4V angOrthoAxis1X[3];
Vec4V angOrthoAxis1Y[3];
Vec4V angOrthoAxis1Z[3];
Vec4V angOrthoRecipResponse[3];
Vec4V angOrthoError[3];
};
PX_ALIGN_PREFIX(16)
struct SolverConstraint1DStep4
{
public:
Vec4V lin0[3]; //!< linear velocity projection (body 0)
Vec4V error; //!< constraint error term - must be scaled by biasScale. Can be adjusted at run-time
Vec4V lin1[3]; //!< linear velocity projection (body 1)
Vec4V biasScale; //!< constraint constant bias scale. Constant
Vec4V ang0[3]; //!< angular velocity projection (body 0)
Vec4V velMultiplier; //!< constraint velocity multiplier
Vec4V ang1[3]; //!< angular velocity projection (body 1)
Vec4V velTarget; //!< Scaled target velocity of the constraint drive
Vec4V minImpulse; //!< Lower bound on impulse magnitude
Vec4V maxImpulse; //!< Upper bound on impulse magnitude
Vec4V appliedForce; //!< applied force to correct velocity+bias
Vec4V maxBias;
Vec4V angularErrorScale; //Constant
PxU32 flags[4];
} PX_ALIGN_SUFFIX(16);
static void setupFinalizeSolverConstraints4Step(PxTGSSolverContactDesc* PX_RESTRICT descs, CorrelationBuffer& c,
PxU8* PX_RESTRICT workspace, PxReal invDtF32, PxReal totalDtF32, PxReal invTotalDtF32,
PxReal dtF32, PxReal bounceThresholdF32, PxReal biasCoefficient,
const aos::Vec4VArg invMassScale0, const aos::Vec4VArg invInertiaScale0,
const aos::Vec4VArg invMassScale1, const aos::Vec4VArg invInertiaScale1)
{
//OK, we have a workspace of pre-allocated space to store all 4 descs in. We now need to create the constraints in it
//const Vec4V ccdMaxSeparation = aos::V4LoadXYZW(descs[0].maxCCDSeparation, descs[1].maxCCDSeparation, descs[2].maxCCDSeparation, descs[3].maxCCDSeparation);
const Vec4V solverOffsetSlop = aos::V4LoadXYZW(descs[0].offsetSlop, descs[1].offsetSlop, descs[2].offsetSlop, descs[3].offsetSlop);
const Vec4V zero = V4Zero();
const BoolV bFalse = BFFFF();
const BoolV bTrue = BTTTT();
const FloatV fZero = FZero();
PxU8 flags[4] = { PxU8(descs[0].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[1].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[2].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[3].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0) };
const bool hasMaxImpulse = descs[0].hasMaxImpulse || descs[1].hasMaxImpulse || descs[2].hasMaxImpulse || descs[3].hasMaxImpulse;
//The block is dynamic if **any** of the constraints have a non-static body B. This allows us to batch static and non-static constraints but we only get a memory/perf
//saving if all 4 are static. This simplifies the constraint partitioning such that it only needs to care about separating contacts and 1D constraints (which it already does)
bool isDynamic = false;
bool hasKinematic = false;
PxReal kinematicScale0F32[4];
PxReal kinematicScale1F32[4];
for (PxU32 a = 0; a < 4; ++a)
{
isDynamic = isDynamic || (descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY);
hasKinematic = hasKinematic || descs[a].bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY;
kinematicScale0F32[a] = descs[a].body0->isKinematic ? 1.f : 0.f;
kinematicScale1F32[a] = descs[a].body1->isKinematic ? 1.f : 0.f;
}
/*BoolV kinematic0 = BLoad(isKinematic0);
BoolV kinematic1 = BLoad(isKinematic1);*/
const Vec4V kinematicScale0 = V4LoadU(kinematicScale0F32);
const Vec4V kinematicScale1 = V4LoadU(kinematicScale1F32);
const PxU32 constraintSize = sizeof(SolverContactPointStepBlock);
const PxU32 frictionSize = sizeof(SolverContactFrictionStepBlock);
PxU8* PX_RESTRICT ptr = workspace;
const Vec4V dom0 = invMassScale0;
const Vec4V dom1 = invMassScale1;
const Vec4V angDom0 = invInertiaScale0;
const Vec4V angDom1 = invInertiaScale1;
const Vec4V maxPenBias = V4Max(V4LoadXYZW(descs[0].bodyData0->penBiasClamp, descs[1].bodyData0->penBiasClamp,
descs[2].bodyData0->penBiasClamp, descs[3].bodyData0->penBiasClamp),
V4LoadXYZW(descs[0].bodyData1->penBiasClamp, descs[1].bodyData1->penBiasClamp,
descs[2].bodyData1->penBiasClamp, descs[3].bodyData1->penBiasClamp));
const Vec4V restDistance = V4LoadXYZW(descs[0].restDistance, descs[1].restDistance, descs[2].restDistance,
descs[3].restDistance);
//load up velocities
Vec4V linVel00 = V4LoadA(&descs[0].bodyData0->originalLinearVelocity.x);
Vec4V linVel10 = V4LoadA(&descs[1].bodyData0->originalLinearVelocity.x);
Vec4V linVel20 = V4LoadA(&descs[2].bodyData0->originalLinearVelocity.x);
Vec4V linVel30 = V4LoadA(&descs[3].bodyData0->originalLinearVelocity.x);
Vec4V linVel01 = V4LoadA(&descs[0].bodyData1->originalLinearVelocity.x);
Vec4V linVel11 = V4LoadA(&descs[1].bodyData1->originalLinearVelocity.x);
Vec4V linVel21 = V4LoadA(&descs[2].bodyData1->originalLinearVelocity.x);
Vec4V linVel31 = V4LoadA(&descs[3].bodyData1->originalLinearVelocity.x);
Vec4V angVel00 = V4LoadA(&descs[0].bodyData0->originalAngularVelocity.x);
Vec4V angVel10 = V4LoadA(&descs[1].bodyData0->originalAngularVelocity.x);
Vec4V angVel20 = V4LoadA(&descs[2].bodyData0->originalAngularVelocity.x);
Vec4V angVel30 = V4LoadA(&descs[3].bodyData0->originalAngularVelocity.x);
Vec4V angVel01 = V4LoadA(&descs[0].bodyData1->originalAngularVelocity.x);
Vec4V angVel11 = V4LoadA(&descs[1].bodyData1->originalAngularVelocity.x);
Vec4V angVel21 = V4LoadA(&descs[2].bodyData1->originalAngularVelocity.x);
Vec4V angVel31 = V4LoadA(&descs[3].bodyData1->originalAngularVelocity.x);
Vec4V linVelT00, linVelT10, linVelT20;
Vec4V linVelT01, linVelT11, linVelT21;
Vec4V angVelT00, angVelT10, angVelT20;
Vec4V angVelT01, angVelT11, angVelT21;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVelT00, linVelT10, linVelT20);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVelT01, linVelT11, linVelT21);
PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVelT00, angVelT10, angVelT20);
PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVelT01, angVelT11, angVelT21);
const Vec4V vrelX = V4Sub(linVelT00, linVelT01);
const Vec4V vrelY = V4Sub(linVelT10, linVelT11);
const Vec4V vrelZ = V4Sub(linVelT20, linVelT21);
//Load up masses and invInertia
const Vec4V invMass0 = V4LoadXYZW(descs[0].bodyData0->invMass, descs[1].bodyData0->invMass, descs[2].bodyData0->invMass, descs[3].bodyData0->invMass);
const Vec4V invMass1 = V4LoadXYZW(descs[0].bodyData1->invMass, descs[1].bodyData1->invMass, descs[2].bodyData1->invMass, descs[3].bodyData1->invMass);
const Vec4V invMass0D0 = V4Mul(dom0, invMass0);
const Vec4V invMass1D1 = V4Mul(dom1, invMass1);
Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].body0TxI->sqrtInvInertia.column2));
Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].body0TxI->sqrtInvInertia.column2));
Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].body0TxI->sqrtInvInertia.column2));
Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].body0TxI->sqrtInvInertia.column2));
Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].body1TxI->sqrtInvInertia.column2));
Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].body1TxI->sqrtInvInertia.column2));
Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].body1TxI->sqrtInvInertia.column2));
Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(descs[3].body1TxI->sqrtInvInertia.column2));
Vec4V invInertia0X0, invInertia0X1, invInertia0X2;
Vec4V invInertia0Y0, invInertia0Y1, invInertia0Y2;
Vec4V invInertia0Z0, invInertia0Z1, invInertia0Z2;
Vec4V invInertia1X0, invInertia1X1, invInertia1X2;
Vec4V invInertia1Y0, invInertia1Y1, invInertia1Y2;
Vec4V invInertia1Z0, invInertia1Z1, invInertia1Z2;
PX_TRANSPOSE_44_34(invInertia00X, invInertia10X, invInertia20X, invInertia30X, invInertia0X0, invInertia0Y0, invInertia0Z0);
PX_TRANSPOSE_44_34(invInertia00Y, invInertia10Y, invInertia20Y, invInertia30Y, invInertia0X1, invInertia0Y1, invInertia0Z1);
PX_TRANSPOSE_44_34(invInertia00Z, invInertia10Z, invInertia20Z, invInertia30Z, invInertia0X2, invInertia0Y2, invInertia0Z2);
PX_TRANSPOSE_44_34(invInertia01X, invInertia11X, invInertia21X, invInertia31X, invInertia1X0, invInertia1Y0, invInertia1Z0);
PX_TRANSPOSE_44_34(invInertia01Y, invInertia11Y, invInertia21Y, invInertia31Y, invInertia1X1, invInertia1Y1, invInertia1Z1);
PX_TRANSPOSE_44_34(invInertia01Z, invInertia11Z, invInertia21Z, invInertia31Z, invInertia1X2, invInertia1Y2, invInertia1Z2);
const FloatV invDt = FLoad(invDtF32);
const PxReal scale = PxMin(0.8f, biasCoefficient);
const FloatV p8 = FLoad(scale);
const FloatV frictionBiasScale = FMul(invDt, p8);
const Vec4V totalDt = V4Load(totalDtF32);
const FloatV invTotalDt = FLoad(invTotalDtF32);
const Vec4V p84 = V4Splat(p8);
const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32));
const Vec4V invDtp8 = V4Splat(FMul(invDt, p8));
const Vec3V bodyFrame00p = V3LoadU(descs[0].bodyFrame0.p);
const Vec3V bodyFrame01p = V3LoadU(descs[1].bodyFrame0.p);
const Vec3V bodyFrame02p = V3LoadU(descs[2].bodyFrame0.p);
const Vec3V bodyFrame03p = V3LoadU(descs[3].bodyFrame0.p);
const FloatV dt = FLoad(dtF32);
Vec4V bodyFrame00p4 = Vec4V_From_Vec3V(bodyFrame00p);
Vec4V bodyFrame01p4 = Vec4V_From_Vec3V(bodyFrame01p);
Vec4V bodyFrame02p4 = Vec4V_From_Vec3V(bodyFrame02p);
Vec4V bodyFrame03p4 = Vec4V_From_Vec3V(bodyFrame03p);
Vec4V bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ;
PX_TRANSPOSE_44_34(bodyFrame00p4, bodyFrame01p4, bodyFrame02p4, bodyFrame03p4, bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ);
const Vec3V bodyFrame10p = V3LoadU(descs[0].bodyFrame1.p);
const Vec3V bodyFrame11p = V3LoadU(descs[1].bodyFrame1.p);
const Vec3V bodyFrame12p = V3LoadU(descs[2].bodyFrame1.p);
const Vec3V bodyFrame13p = V3LoadU(descs[3].bodyFrame1.p);
Vec4V bodyFrame10p4 = Vec4V_From_Vec3V(bodyFrame10p);
Vec4V bodyFrame11p4 = Vec4V_From_Vec3V(bodyFrame11p);
Vec4V bodyFrame12p4 = Vec4V_From_Vec3V(bodyFrame12p);
Vec4V bodyFrame13p4 = Vec4V_From_Vec3V(bodyFrame13p);
Vec4V bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ;
PX_TRANSPOSE_44_34(bodyFrame10p4, bodyFrame11p4, bodyFrame12p4, bodyFrame13p4, bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ);
const QuatV bodyFrame00q = QuatVLoadU(&descs[0].bodyFrame0.q.x);
const QuatV bodyFrame01q = QuatVLoadU(&descs[1].bodyFrame0.q.x);
const QuatV bodyFrame02q = QuatVLoadU(&descs[2].bodyFrame0.q.x);
const QuatV bodyFrame03q = QuatVLoadU(&descs[3].bodyFrame0.q.x);
const QuatV bodyFrame10q = QuatVLoadU(&descs[0].bodyFrame1.q.x);
const QuatV bodyFrame11q = QuatVLoadU(&descs[1].bodyFrame1.q.x);
const QuatV bodyFrame12q = QuatVLoadU(&descs[2].bodyFrame1.q.x);
const QuatV bodyFrame13q = QuatVLoadU(&descs[3].bodyFrame1.q.x);
PxU32 frictionPatchWritebackAddrIndex0 = 0;
PxU32 frictionPatchWritebackAddrIndex1 = 0;
PxU32 frictionPatchWritebackAddrIndex2 = 0;
PxU32 frictionPatchWritebackAddrIndex3 = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
PxU32 frictionIndex0 = 0, frictionIndex1 = 0, frictionIndex2 = 0, frictionIndex3 = 0;
//PxU32 contactIndex0 = 0, contactIndex1 = 0, contactIndex2 = 0, contactIndex3 = 0;
//OK, we iterate through all friction patch counts in the constraint patch, building up the constraint list etc.
PxU32 maxPatches = PxMax(descs[0].numFrictionPatches, PxMax(descs[1].numFrictionPatches, PxMax(descs[2].numFrictionPatches, descs[3].numFrictionPatches)));
const Vec4V p1 = V4Splat(FLoad(0.0001f));
const Vec4V orthoThreshold = V4Splat(FLoad(0.70710678f));
PxU32 contact0 = 0, contact1 = 0, contact2 = 0, contact3 = 0;
PxU32 patch0 = 0, patch1 = 0, patch2 = 0, patch3 = 0;
PxU8 flag = 0;
if (hasMaxImpulse)
flag |= SolverContactHeader4::eHAS_MAX_IMPULSE;
bool hasFinished[4];
for (PxU32 i = 0; i<maxPatches; i++)
{
hasFinished[0] = i >= descs[0].numFrictionPatches;
hasFinished[1] = i >= descs[1].numFrictionPatches;
hasFinished[2] = i >= descs[2].numFrictionPatches;
hasFinished[3] = i >= descs[3].numFrictionPatches;
frictionIndex0 = hasFinished[0] ? frictionIndex0 : descs[0].startFrictionPatchIndex + i;
frictionIndex1 = hasFinished[1] ? frictionIndex1 : descs[1].startFrictionPatchIndex + i;
frictionIndex2 = hasFinished[2] ? frictionIndex2 : descs[2].startFrictionPatchIndex + i;
frictionIndex3 = hasFinished[3] ? frictionIndex3 : descs[3].startFrictionPatchIndex + i;
PxU32 clampedContacts0 = hasFinished[0] ? 0 : c.frictionPatchContactCounts[frictionIndex0];
PxU32 clampedContacts1 = hasFinished[1] ? 0 : c.frictionPatchContactCounts[frictionIndex1];
PxU32 clampedContacts2 = hasFinished[2] ? 0 : c.frictionPatchContactCounts[frictionIndex2];
PxU32 clampedContacts3 = hasFinished[3] ? 0 : c.frictionPatchContactCounts[frictionIndex3];
PxU32 firstPatch0 = c.correlationListHeads[frictionIndex0];
PxU32 firstPatch1 = c.correlationListHeads[frictionIndex1];
PxU32 firstPatch2 = c.correlationListHeads[frictionIndex2];
PxU32 firstPatch3 = c.correlationListHeads[frictionIndex3];
const PxContactPoint* contactBase0 = descs[0].contacts + c.contactPatches[firstPatch0].start;
const PxContactPoint* contactBase1 = descs[1].contacts + c.contactPatches[firstPatch1].start;
const PxContactPoint* contactBase2 = descs[2].contacts + c.contactPatches[firstPatch2].start;
const PxContactPoint* contactBase3 = descs[3].contacts + c.contactPatches[firstPatch3].start;
const Vec4V restitution = V4Neg(V4LoadXYZW(contactBase0->restitution, contactBase1->restitution, contactBase2->restitution,
contactBase3->restitution));
const Vec4V damping = V4LoadXYZW(contactBase0->damping, contactBase1->damping, contactBase2->damping, contactBase3->damping);
SolverContactHeaderStepBlock* PX_RESTRICT header = reinterpret_cast<SolverContactHeaderStepBlock*>(ptr);
ptr += sizeof(SolverContactHeaderStepBlock);
header->flags[0] = flags[0];
header->flags[1] = flags[1];
header->flags[2] = flags[2];
header->flags[3] = flags[3];
header->flag = flag;
PxU32 totalContacts = PxMax(clampedContacts0, PxMax(clampedContacts1, PxMax(clampedContacts2, clampedContacts3)));
Vec4V* PX_RESTRICT appliedNormalForces = reinterpret_cast<Vec4V*>(ptr);
ptr += sizeof(Vec4V)*totalContacts;
PxMemZero(appliedNormalForces, sizeof(Vec4V) * totalContacts);
header->numNormalConstr = PxTo8(totalContacts);
header->numNormalConstrs[0] = PxTo8(clampedContacts0);
header->numNormalConstrs[1] = PxTo8(clampedContacts1);
header->numNormalConstrs[2] = PxTo8(clampedContacts2);
header->numNormalConstrs[3] = PxTo8(clampedContacts3);
//header->sqrtInvMassA = sqrtInvMass0;
//header->sqrtInvMassB = sqrtInvMass1;
header->invMass0D0 = invMass0D0;
header->invMass1D1 = invMass1D1;
header->angDom0 = angDom0;
header->angDom1 = angDom1;
header->shapeInteraction[0] = getInteraction(descs[0]); header->shapeInteraction[1] = getInteraction(descs[1]);
header->shapeInteraction[2] = getInteraction(descs[2]); header->shapeInteraction[3] = getInteraction(descs[3]);
Vec4V* maxImpulse = reinterpret_cast<Vec4V*>(ptr + constraintSize * totalContacts);
//header->restitution = restitution;
Vec4V normal0 = V4LoadA(&contactBase0->normal.x);
Vec4V normal1 = V4LoadA(&contactBase1->normal.x);
Vec4V normal2 = V4LoadA(&contactBase2->normal.x);
Vec4V normal3 = V4LoadA(&contactBase3->normal.x);
Vec4V normalX, normalY, normalZ;
PX_TRANSPOSE_44_34(normal0, normal1, normal2, normal3, normalX, normalY, normalZ);
PX_ASSERT(ValidateVec4(normalX));
PX_ASSERT(ValidateVec4(normalY));
PX_ASSERT(ValidateVec4(normalZ));
header->normalX = normalX;
header->normalY = normalY;
header->normalZ = normalZ;
header->maxPenBias = maxPenBias;
const Vec4V norVel0 = V4MulAdd(normalZ, linVelT20, V4MulAdd(normalY, linVelT10, V4Mul(normalX, linVelT00)));
const Vec4V norVel1 = V4MulAdd(normalZ, linVelT21, V4MulAdd(normalY, linVelT11, V4Mul(normalX, linVelT01)));
const Vec4V relNorVel = V4Sub(norVel0, norVel1);
//For all correlation heads - need to pull this out I think
//OK, we have a counter for all our patches...
PxU32 finished = (PxU32(hasFinished[0])) |
((PxU32(hasFinished[1])) << 1) |
((PxU32(hasFinished[2])) << 2) |
((PxU32(hasFinished[3])) << 3);
CorrelationListIterator iter0(c, firstPatch0);
CorrelationListIterator iter1(c, firstPatch1);
CorrelationListIterator iter2(c, firstPatch2);
CorrelationListIterator iter3(c, firstPatch3);
//PxU32 contact0, contact1, contact2, contact3;
//PxU32 patch0, patch1, patch2, patch3;
if (!hasFinished[0])
iter0.nextContact(patch0, contact0);
if (!hasFinished[1])
iter1.nextContact(patch1, contact1);
if (!hasFinished[2])
iter2.nextContact(patch2, contact2);
if (!hasFinished[3])
iter3.nextContact(patch3, contact3);
PxU8* p = ptr;
PxU32 contactCount = 0;
PxU32 newFinished =
(PxU32(hasFinished[0] || !iter0.hasNextContact())) |
((PxU32(hasFinished[1] || !iter1.hasNextContact())) << 1) |
((PxU32(hasFinished[2] || !iter2.hasNextContact())) << 2) |
((PxU32(hasFinished[3] || !iter3.hasNextContact())) << 3);
BoolV bFinished = BLoad(hasFinished);
while (finished != 0xf)
{
finished = newFinished;
++contactCount;
PxPrefetchLine(p, 384);
PxPrefetchLine(p, 512);
PxPrefetchLine(p, 640);
SolverContactPointStepBlock* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointStepBlock*>(p);
p += constraintSize;
const PxContactPoint& con0 = descs[0].contacts[c.contactPatches[patch0].start + contact0];
const PxContactPoint& con1 = descs[1].contacts[c.contactPatches[patch1].start + contact1];
const PxContactPoint& con2 = descs[2].contacts[c.contactPatches[patch2].start + contact2];
const PxContactPoint& con3 = descs[3].contacts[c.contactPatches[patch3].start + contact3];
//Now we need to splice these 4 contacts into a single structure
{
Vec4V point0 = V4LoadA(&con0.point.x);
Vec4V point1 = V4LoadA(&con1.point.x);
Vec4V point2 = V4LoadA(&con2.point.x);
Vec4V point3 = V4LoadA(&con3.point.x);
Vec4V pointX, pointY, pointZ;
PX_TRANSPOSE_44_34(point0, point1, point2, point3, pointX, pointY, pointZ);
Vec4V cTargetVel0 = V4LoadA(&con0.targetVel.x);
Vec4V cTargetVel1 = V4LoadA(&con1.targetVel.x);
Vec4V cTargetVel2 = V4LoadA(&con2.targetVel.x);
Vec4V cTargetVel3 = V4LoadA(&con3.targetVel.x);
Vec4V cTargetVelX, cTargetVelY, cTargetVelZ;
PX_TRANSPOSE_44_34(cTargetVel0, cTargetVel1, cTargetVel2, cTargetVel3, cTargetVelX, cTargetVelY, cTargetVelZ);
const Vec4V separation = V4LoadXYZW(con0.separation, con1.separation, con2.separation, con3.separation);
const Vec4V cTargetNorVel = V4MulAdd(cTargetVelX, normalX, V4MulAdd(cTargetVelY, normalY, V4Mul(cTargetVelZ, normalZ)));
const Vec4V raX = V4Sub(pointX, bodyFrame0pX);
const Vec4V raY = V4Sub(pointY, bodyFrame0pY);
const Vec4V raZ = V4Sub(pointZ, bodyFrame0pZ);
const Vec4V rbX = V4Sub(pointX, bodyFrame1pX);
const Vec4V rbY = V4Sub(pointY, bodyFrame1pY);
const Vec4V rbZ = V4Sub(pointZ, bodyFrame1pZ);
/*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);
rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/
PX_ASSERT(ValidateVec4(raX));
PX_ASSERT(ValidateVec4(raY));
PX_ASSERT(ValidateVec4(raZ));
PX_ASSERT(ValidateVec4(rbX));
PX_ASSERT(ValidateVec4(rbY));
PX_ASSERT(ValidateVec4(rbZ));
//raXn = cross(ra, normal) which = Vec3V( a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x);
Vec4V raXnX = V4NegMulSub(raZ, normalY, V4Mul(raY, normalZ));
Vec4V raXnY = V4NegMulSub(raX, normalZ, V4Mul(raZ, normalX));
Vec4V raXnZ = V4NegMulSub(raY, normalX, V4Mul(raX, normalY));
Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ));
Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX));
Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY));
const Vec4V relAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
const Vec4V relAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
const Vec4V relAng = V4Sub(relAngVel0, relAngVel1);
const Vec4V slop = V4Mul(solverOffsetSlop, V4Max(V4Sel(V4IsEq(relNorVel, zero), V4Splat(FMax()), V4Div(relAng, relNorVel)), V4One()));
raXnX = V4Sel(V4IsGrtr(slop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(slop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(slop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
PX_ASSERT(ValidateVec4(delAngVel0X));
PX_ASSERT(ValidateVec4(delAngVel0Y));
PX_ASSERT(ValidateVec4(delAngVel0Z));
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0X, delAngVel0X, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0Z, delAngVel0Z)));
Vec4V unitResponse = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
Vec4V vrel0 = V4Add(norVel0, relAngVel0);
Vec4V vrel1 = V4Add(norVel1, relAngVel1);
Vec4V delAngVel1X = zero;
Vec4V delAngVel1Y = zero;
Vec4V delAngVel1Z = zero;
//The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much
if (isDynamic)
{
rbXnX = V4Sel(V4IsGrtr(slop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(slop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(slop, V4Abs(rbXnZ)), zero, rbXnZ);
delAngVel1X = V4Mul(invInertia1X0, rbXnX);
delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
PX_ASSERT(ValidateVec4(delAngVel1X));
PX_ASSERT(ValidateVec4(delAngVel1Y));
PX_ASSERT(ValidateVec4(delAngVel1Z));
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1X, delAngVel1X, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1Z, delAngVel1Z)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
unitResponse = V4Add(unitResponse, resp1);
}
Vec4V vrel = V4Sub(vrel0, vrel1);
solverContact->rbXnI[0] = delAngVel1X;
solverContact->rbXnI[1] = delAngVel1Y;
solverContact->rbXnI[2] = delAngVel1Z;
Vec4V penetration = V4Sub(separation, restDistance);
const Vec4V penetrationInvDt = V4Scale(penetration, invTotalDt);
const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(zero, restitution), V4IsGrtr(bounceThreshold, vrel)),
V4IsGrtr(V4Neg(vrel), penetrationInvDt));
const Vec4V ratio = V4Sel(isGreater2, V4Add(totalDt, V4Div(penetration, vrel)), zero);
const Vec4V recipResponse = V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero);
//Restitution is negated in the block setup code
const BoolV isCompliant = V4IsGrtr(restitution, zero);
const Vec4V rdt = V4Scale(restitution, dt);
const Vec4V a = V4Scale(V4Add(damping, rdt), dt);
const Vec4V x = V4Recip(V4MulAdd(a, unitResponse, V4One()));
const Vec4V velMultiplier = V4Sel(isCompliant, V4Mul(x, a), recipResponse);
const Vec4V scaledBias = V4Neg(V4Sel(isCompliant, V4Mul(rdt, V4Mul(x, unitResponse)), V4Sel(V4IsGrtr(penetration, zero), V4Splat(invDt), invDtp8)));
Vec4V targetVelocity = V4NegMulSub(vrel0, kinematicScale0, V4MulAdd(vrel1, kinematicScale1, V4Sel(isGreater2, V4Mul(vrel, restitution), zero)));
penetration = V4MulAdd(targetVelocity, ratio, penetration);
//Vec4V biasedErr = V4Sel(isGreater2, targetVelocity, scaledBias);
//Vec4V biasedErr = V4Add(targetVelocity, scaledBias);
//biasedErr = V4NegMulSub(V4Sub(vrel, cTargetNorVel), velMultiplier, biasedErr);
//These values are present for static and dynamic contacts
solverContact->raXnI[0] = delAngVel0X;
solverContact->raXnI[1] = delAngVel0Y;
solverContact->raXnI[2] = delAngVel0Z;
solverContact->velMultiplier = V4Sel(bFinished, zero, velMultiplier);
solverContact->targetVelocity = V4Add(cTargetNorVel, targetVelocity);
solverContact->separation = penetration;
solverContact->biasCoefficient = V4Sel(bFinished, zero, scaledBias);
solverContact->recipResponse = V4Sel(bFinished, zero, recipResponse);
if (hasMaxImpulse)
{
maxImpulse[contactCount - 1] = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse),
FLoad(con3.maxImpulse));
}
}
if (!(finished & 0x1))
{
iter0.nextContact(patch0, contact0);
newFinished |= PxU32(!iter0.hasNextContact());
}
else
bFinished = BSetX(bFinished, bTrue);
if (!(finished & 0x2))
{
iter1.nextContact(patch1, contact1);
newFinished |= (PxU32(!iter1.hasNextContact()) << 1);
}
else
bFinished = BSetY(bFinished, bTrue);
if (!(finished & 0x4))
{
iter2.nextContact(patch2, contact2);
newFinished |= (PxU32(!iter2.hasNextContact()) << 2);
}
else
bFinished = BSetZ(bFinished, bTrue);
if (!(finished & 0x8))
{
iter3.nextContact(patch3, contact3);
newFinished |= (PxU32(!iter3.hasNextContact()) << 3);
}
else
bFinished = BSetW(bFinished, bTrue);
}
ptr = p;
if (hasMaxImpulse)
{
ptr += sizeof(Vec4V) * totalContacts;
}
//OK...friction time :-)
Vec4V maxImpulseScale = V4One();
{
const FrictionPatch& frictionPatch0 = c.frictionPatches[frictionIndex0];
const FrictionPatch& frictionPatch1 = c.frictionPatches[frictionIndex1];
const FrictionPatch& frictionPatch2 = c.frictionPatches[frictionIndex2];
const FrictionPatch& frictionPatch3 = c.frictionPatches[frictionIndex3];
PxU32 anchorCount0 = frictionPatch0.anchorCount;
PxU32 anchorCount1 = frictionPatch1.anchorCount;
PxU32 anchorCount2 = frictionPatch2.anchorCount;
PxU32 anchorCount3 = frictionPatch3.anchorCount;
PxU32 clampedAnchorCount0 = hasFinished[0] || (contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount0;
PxU32 clampedAnchorCount1 = hasFinished[1] || (contactBase1->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount1;
PxU32 clampedAnchorCount2 = hasFinished[2] || (contactBase2->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount2;
PxU32 clampedAnchorCount3 = hasFinished[3] || (contactBase3->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount3;
const PxU32 maxAnchorCount = PxMax(clampedAnchorCount0, PxMax(clampedAnchorCount1, PxMax(clampedAnchorCount2, clampedAnchorCount3)));
PX_ALIGN(16, PxReal staticFriction[4]);
PX_ALIGN(16, PxReal dynamicFriction[4]);
//for (PxU32 f = 0; f < 4; ++f)
{
PxReal coeff0 = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount0 == 2) ? 0.5f : 1.f;
PxReal coeff1 = (contactBase1->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount1 == 2) ? 0.5f : 1.f;
PxReal coeff2 = (contactBase2->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount2 == 2) ? 0.5f : 1.f;
PxReal coeff3 = (contactBase3->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount3 == 2) ? 0.5f : 1.f;
staticFriction[0] = contactBase0->staticFriction * coeff0;
dynamicFriction[0] = contactBase0->dynamicFriction * coeff0;
staticFriction[1] = contactBase1->staticFriction * coeff1;
dynamicFriction[1] = contactBase1->dynamicFriction * coeff1;
staticFriction[2] = contactBase2->staticFriction * coeff2;
dynamicFriction[2] = contactBase2->dynamicFriction * coeff2;
staticFriction[3] = contactBase3->staticFriction * coeff3;
dynamicFriction[3] = contactBase3->dynamicFriction * coeff3;
}
PX_ASSERT(totalContacts == contactCount);
header->numFrictionConstr = PxTo8(maxAnchorCount * 2);
header->numFrictionConstrs[0] = PxTo8(clampedAnchorCount0 * 2);
header->numFrictionConstrs[1] = PxTo8(clampedAnchorCount1 * 2);
header->numFrictionConstrs[2] = PxTo8(clampedAnchorCount2 * 2);
header->numFrictionConstrs[3] = PxTo8(clampedAnchorCount3 * 2);
//KS - TODO - extend this if needed
header->type = PxTo8(DY_SC_TYPE_BLOCK_RB_CONTACT);
if (maxAnchorCount)
{
const BoolV cond = V4IsGrtr(orthoThreshold, V4Abs(normalX));
const Vec4V t0FallbackX = V4Sel(cond, zero, V4Neg(normalY));
const Vec4V t0FallbackY = V4Sel(cond, V4Neg(normalZ), normalX);
const Vec4V t0FallbackZ = V4Sel(cond, normalY, zero);
//const Vec4V dotNormalVrel = V4MulAdd(normalZ, vrelZ, V4MulAdd(normalY, vrelY, V4Mul(normalX, vrelX)));
const Vec4V vrelSubNorVelX = V4NegMulSub(normalX, relNorVel, vrelX);
const Vec4V vrelSubNorVelY = V4NegMulSub(normalY, relNorVel, vrelY);
const Vec4V vrelSubNorVelZ = V4NegMulSub(normalZ, relNorVel, vrelZ);
const Vec4V lenSqvrelSubNorVelZ = V4MulAdd(vrelSubNorVelX, vrelSubNorVelX, V4MulAdd(vrelSubNorVelY, vrelSubNorVelY, V4Mul(vrelSubNorVelZ, vrelSubNorVelZ)));
const BoolV bcon2 = V4IsGrtr(lenSqvrelSubNorVelZ, p1);
Vec4V t0X = V4Sel(bcon2, vrelSubNorVelX, t0FallbackX);
Vec4V t0Y = V4Sel(bcon2, vrelSubNorVelY, t0FallbackY);
Vec4V t0Z = V4Sel(bcon2, vrelSubNorVelZ, t0FallbackZ);
//Now normalize this...
const Vec4V recipLen = V4Rsqrt(V4MulAdd(t0Z, t0Z, V4MulAdd(t0Y, t0Y, V4Mul(t0X, t0X))));
t0X = V4Mul(t0X, recipLen);
t0Y = V4Mul(t0Y, recipLen);
t0Z = V4Mul(t0Z, recipLen);
Vec4V t1X = V4NegMulSub(normalZ, t0Y, V4Mul(normalY, t0Z));
Vec4V t1Y = V4NegMulSub(normalX, t0Z, V4Mul(normalZ, t0X));
Vec4V t1Z = V4NegMulSub(normalY, t0X, V4Mul(normalX, t0Y));
PX_ASSERT((uintptr_t(descs[0].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[1].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[2].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[3].frictionPtr) & 0xF) == 0);
PxU8* PX_RESTRICT writeback0 = descs[0].frictionPtr + frictionPatchWritebackAddrIndex0 * sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback1 = descs[1].frictionPtr + frictionPatchWritebackAddrIndex1 * sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback2 = descs[2].frictionPtr + frictionPatchWritebackAddrIndex2 * sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback3 = descs[3].frictionPtr + frictionPatchWritebackAddrIndex3 * sizeof(FrictionPatch);
PxU32 index0 = 0, index1 = 0, index2 = 0, index3 = 0;
header->broken = bFalse;
header->frictionBrokenWritebackByte[0] = writeback0;
header->frictionBrokenWritebackByte[1] = writeback1;
header->frictionBrokenWritebackByte[2] = writeback2;
header->frictionBrokenWritebackByte[3] = writeback3;
/*header->frictionNormal[0][0] = t0X;
header->frictionNormal[0][1] = t0Y;
header->frictionNormal[0][2] = t0Z;
header->frictionNormal[1][0] = t1X;
header->frictionNormal[1][1] = t1Y;
header->frictionNormal[1][2] = t1Z;*/
Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(ptr);
ptr += sizeof(Vec4V)*header->numFrictionConstr;
PxMemZero(appliedForces, sizeof(Vec4V) * header->numFrictionConstr);
for (PxU32 j = 0; j < maxAnchorCount; j++)
{
PxPrefetchLine(ptr, 384);
PxPrefetchLine(ptr, 512);
PxPrefetchLine(ptr, 640);
SolverContactFrictionStepBlock* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionStepBlock*>(ptr);
ptr += frictionSize;
SolverContactFrictionStepBlock* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionStepBlock*>(ptr);
ptr += frictionSize;
index0 = j < clampedAnchorCount0 ? j : index0;
index1 = j < clampedAnchorCount1 ? j : index1;
index2 = j < clampedAnchorCount2 ? j : index2;
index3 = j < clampedAnchorCount3 ? j : index3;
if (j >= clampedAnchorCount0)
maxImpulseScale = V4SetX(maxImpulseScale, fZero);
if (j >= clampedAnchorCount1)
maxImpulseScale = V4SetY(maxImpulseScale, fZero);
if (j >= clampedAnchorCount2)
maxImpulseScale = V4SetZ(maxImpulseScale, fZero);
if (j >= clampedAnchorCount3)
maxImpulseScale = V4SetW(maxImpulseScale, fZero);
t0X = V4Mul(maxImpulseScale, t0X);
t0Y = V4Mul(maxImpulseScale, t0Y);
t0Z = V4Mul(maxImpulseScale, t0Z);
t1X = V4Mul(maxImpulseScale, t1X);
t1Y = V4Mul(maxImpulseScale, t1Y);
t1Z = V4Mul(maxImpulseScale, t1Z);
Vec3V body0Anchor0 = V3LoadU(frictionPatch0.body0Anchors[index0]);
Vec3V body0Anchor1 = V3LoadU(frictionPatch1.body0Anchors[index1]);
Vec3V body0Anchor2 = V3LoadU(frictionPatch2.body0Anchors[index2]);
Vec3V body0Anchor3 = V3LoadU(frictionPatch3.body0Anchors[index3]);
Vec4V ra0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame00q, body0Anchor0));
Vec4V ra1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame01q, body0Anchor1));
Vec4V ra2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame02q, body0Anchor2));
Vec4V ra3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame03q, body0Anchor3));
Vec4V raX, raY, raZ;
PX_TRANSPOSE_44_34(ra0, ra1, ra2, ra3, raX, raY, raZ);
/*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);*/
const Vec4V raWorldX = V4Add(raX, bodyFrame0pX);
const Vec4V raWorldY = V4Add(raY, bodyFrame0pY);
const Vec4V raWorldZ = V4Add(raZ, bodyFrame0pZ);
Vec3V body1Anchor0 = V3LoadU(frictionPatch0.body1Anchors[index0]);
Vec3V body1Anchor1 = V3LoadU(frictionPatch1.body1Anchors[index1]);
Vec3V body1Anchor2 = V3LoadU(frictionPatch2.body1Anchors[index2]);
Vec3V body1Anchor3 = V3LoadU(frictionPatch3.body1Anchors[index3]);
Vec4V rb0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame10q, body1Anchor0));
Vec4V rb1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame11q, body1Anchor1));
Vec4V rb2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame12q, body1Anchor2));
Vec4V rb3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame13q, body1Anchor3));
Vec4V rbX, rbY, rbZ;
PX_TRANSPOSE_44_34(rb0, rb1, rb2, rb3, rbX, rbY, rbZ);
/*rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/
const Vec4V rbWorldX = V4Add(rbX, bodyFrame1pX);
const Vec4V rbWorldY = V4Add(rbY, bodyFrame1pY);
const Vec4V rbWorldZ = V4Add(rbZ, bodyFrame1pZ);
Vec4V errorX = V4Sub(raWorldX, rbWorldX);
Vec4V errorY = V4Sub(raWorldY, rbWorldY);
Vec4V errorZ = V4Sub(raWorldZ, rbWorldZ);
/*errorX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorX)), zero, errorX);
errorY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorY)), zero, errorY);
errorZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorZ)), zero, errorZ);*/
//KS - todo - get this working with per-point friction
PxU32 contactIndex0 = c.contactID[frictionIndex0][index0];
PxU32 contactIndex1 = c.contactID[frictionIndex1][index1];
PxU32 contactIndex2 = c.contactID[frictionIndex2][index2];
PxU32 contactIndex3 = c.contactID[frictionIndex3][index3];
//Ensure that the contact indices are valid
PX_ASSERT(contactIndex0 == 0xffff || contactIndex0 < descs[0].numContacts);
PX_ASSERT(contactIndex1 == 0xffff || contactIndex1 < descs[1].numContacts);
PX_ASSERT(contactIndex2 == 0xffff || contactIndex2 < descs[2].numContacts);
PX_ASSERT(contactIndex3 == 0xffff || contactIndex3 < descs[3].numContacts);
Vec4V targetVel0 = V4LoadA(contactIndex0 == 0xFFFF ? &contactBase0->targetVel.x : &descs[0].contacts[contactIndex0].targetVel.x);
Vec4V targetVel1 = V4LoadA(contactIndex1 == 0xFFFF ? &contactBase0->targetVel.x : &descs[1].contacts[contactIndex1].targetVel.x);
Vec4V targetVel2 = V4LoadA(contactIndex2 == 0xFFFF ? &contactBase0->targetVel.x : &descs[2].contacts[contactIndex2].targetVel.x);
Vec4V targetVel3 = V4LoadA(contactIndex3 == 0xFFFF ? &contactBase0->targetVel.x : &descs[3].contacts[contactIndex3].targetVel.x);
Vec4V targetVelX, targetVelY, targetVelZ;
PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ);
{
Vec4V raXnX = V4NegMulSub(raZ, t0Y, V4Mul(raY, t0Z));
Vec4V raXnY = V4NegMulSub(raX, t0Z, V4Mul(raZ, t0X));
Vec4V raXnZ = V4NegMulSub(raY, t0X, V4Mul(raX, t0Y));
raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
const Vec4V tVel0 = V4MulAdd(t0Z, linVelT20, V4MulAdd(t0Y, linVelT10, V4Mul(t0X, linVelT00)));
Vec4V vrel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0)));
Vec4V delAngVel1X = zero;
Vec4V delAngVel1Y = zero;
Vec4V delAngVel1Z = zero;
Vec4V vrel1 = zero;
if (isDynamic)
{
Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z));
Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X));
Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y));
rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ);
delAngVel1X = V4Mul(invInertia1X0, rbXnX);
delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
resp = V4Add(resp, resp1);
const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01)));
vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
}
else if (hasKinematic)
{
const Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z));
const Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X));
const Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y));
const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01)));
vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
}
f0->rbXnI[0] = delAngVel1X;
f0->rbXnI[1] = delAngVel1Y;
f0->rbXnI[2] = delAngVel1Z;
const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero));
Vec4V error = V4MulAdd(t0Z, errorZ, V4MulAdd(t0Y, errorY, V4Mul(t0X, errorX)));
Vec4V targetVel = V4NegMulSub(vrel0, kinematicScale0, V4MulAdd(vrel1, kinematicScale1, V4MulAdd(t0Z, targetVelZ, V4MulAdd(t0Y, targetVelY, V4Mul(t0X, targetVelX)))));
f0->normal[0] = t0X;
f0->normal[1] = t0Y;
f0->normal[2] = t0Z;
f0->raXnI[0] = delAngVel0X;
f0->raXnI[1] = delAngVel0Y;
f0->raXnI[2] = delAngVel0Z;
f0->error = error;
f0->velMultiplier = velMultiplier;
f0->biasCoefficient = V4Splat(frictionBiasScale);
f0->targetVel = targetVel;
}
{
Vec4V raXnX = V4NegMulSub(raZ, t1Y, V4Mul(raY, t1Z));
Vec4V raXnY = V4NegMulSub(raX, t1Z, V4Mul(raZ, t1X));
Vec4V raXnZ = V4NegMulSub(raY, t1X, V4Mul(raX, t1Y));
raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
const Vec4V tVel0 = V4MulAdd(t1Z, linVelT20, V4MulAdd(t1Y, linVelT10, V4Mul(t1X, linVelT00)));
Vec4V vrel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0)));
Vec4V delAngVel1X = zero;
Vec4V delAngVel1Y = zero;
Vec4V delAngVel1Z = zero;
Vec4V vrel1 = zero;
if (isDynamic)
{
Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z));
Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X));
Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y));
rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ);
delAngVel1X = V4Mul(invInertia1X0, rbXnX);
delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
resp = V4Add(resp, resp1);
const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01)));
vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
}
else if (hasKinematic)
{
const Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z));
const Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X));
const Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y));
const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01)));
vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
}
f1->rbXnI[0] = delAngVel1X;
f1->rbXnI[1] = delAngVel1Y;
f1->rbXnI[2] = delAngVel1Z;
const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero));
Vec4V error = V4MulAdd(t1Z, errorZ, V4MulAdd(t1Y, errorY, V4Mul(t1X, errorX)));
Vec4V targetVel = V4NegMulSub(vrel0, kinematicScale0, V4MulAdd(vrel1, kinematicScale1, V4MulAdd(t1Z, targetVelZ, V4MulAdd(t1Y, targetVelY, V4Mul(t1X, targetVelX)))));
f1->normal[0] = t1X;
f1->normal[1] = t1Y;
f1->normal[2] = t1Z;
f1->raXnI[0] = delAngVel0X;
f1->raXnI[1] = delAngVel0Y;
f1->raXnI[2] = delAngVel0Z;
f1->error = error;
f1->velMultiplier = velMultiplier;
f1->targetVel = targetVel;
f1->biasCoefficient = V4Splat(frictionBiasScale);
}
}
header->dynamicFriction = V4LoadA(dynamicFriction);
header->staticFriction = V4LoadA(staticFriction);
frictionPatchWritebackAddrIndex0++;
frictionPatchWritebackAddrIndex1++;
frictionPatchWritebackAddrIndex2++;
frictionPatchWritebackAddrIndex3++;
}
}
}
}
static PX_FORCE_INLINE void computeBlockStreamFrictionByteSizes(const CorrelationBuffer& c,
PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches,
PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex)
{
// PT: use local vars to remove LHS
PxU32 numFrictionPatches = 0;
for (PxU32 i = frictionPatchStartIndex; i < frictionPatchEndIndex; i++)
{
//Friction patches.
if (c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
}
PxU32 frictionPatchByteSize = numFrictionPatches * sizeof(FrictionPatch);
_numFrictionPatches = numFrictionPatches;
//16-byte alignment.
_frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f));
}
static bool reserveFrictionBlockStreams(const CorrelationBuffer& c, PxConstraintAllocator& constraintAllocator, PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex,
FrictionPatch*& _frictionPatches,
PxU32& numFrictionPatches)
{
//From frictionPatchStream we just need to reserve a single buffer.
PxU32 frictionPatchByteSize = 0;
//Compute the sizes of all the buffers.
computeBlockStreamFrictionByteSizes(c, frictionPatchByteSize, numFrictionPatches, frictionPatchStartIndex, frictionPatchEndIndex);
FrictionPatch* frictionPatches = NULL;
//If the constraint block reservation didn't fail then reserve the friction buffer too.
if (frictionPatchByteSize > 0)
{
frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize));
if (0 == frictionPatches || (reinterpret_cast<FrictionPatch*>(-1)) == frictionPatches)
{
if (0 == frictionPatches)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
frictionPatches = NULL;
}
}
}
_frictionPatches = frictionPatches;
//Return true if neither of the two block reservations failed.
return (0 == frictionPatchByteSize || frictionPatches);
}
//The persistent friction patch correlation/allocation will already have happenned as this is per-pair.
//This function just computes the size of the combined solve data.
static void computeBlockStreamByteSizes4(PxTGSSolverContactDesc* descs,
PxU32& _solverConstraintByteSize, PxU32* _axisConstraintCount,
const CorrelationBuffer& c)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PxU32 maxPatches = 0;
PxU32 maxFrictionPatches = 0;
PxU32 maxContactCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxU32 maxFrictionCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxMemZero(maxContactCount, sizeof(maxContactCount));
PxMemZero(maxFrictionCount, sizeof(maxFrictionCount));
bool hasMaxImpulse = false;
for (PxU32 a = 0; a < 4; ++a)
{
PxU32 axisConstraintCount = 0;
hasMaxImpulse = hasMaxImpulse || descs[a].hasMaxImpulse;
for (PxU32 i = 0; i < descs[a].numFrictionPatches; i++)
{
PxU32 ind = i + descs[a].startFrictionPatchIndex;
const FrictionPatch& frictionPatch = c.frictionPatches[ind];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0
&& frictionPatch.anchorCount != 0;
//Solver constraint data.
if (c.frictionPatchContactCounts[ind] != 0)
{
maxContactCount[i] = PxMax(c.frictionPatchContactCounts[ind], maxContactCount[i]);
axisConstraintCount += c.frictionPatchContactCounts[ind];
if (haveFriction)
{
const PxU32 fricCount = PxU32(c.frictionPatches[ind].anchorCount) * 2;
maxFrictionCount[i] = PxMax(fricCount, maxFrictionCount[i]);
axisConstraintCount += fricCount;
}
}
}
maxPatches = PxMax(descs[a].numFrictionPatches, maxPatches);
_axisConstraintCount[a] = axisConstraintCount;
}
for (PxU32 a = 0; a < maxPatches; ++a)
{
if (maxFrictionCount[a] > 0)
maxFrictionPatches++;
}
PxU32 totalContacts = 0, totalFriction = 0;
for (PxU32 a = 0; a < maxPatches; ++a)
{
totalContacts += maxContactCount[a];
totalFriction += maxFrictionCount[a];
}
//OK, we have a given number of friction patches, contact points and friction constraints so we can calculate how much memory we need
//Body 2 is considered static if it is either *not dynamic* or *kinematic*
/*bool hasDynamicBody = false;
for (PxU32 a = 0; a < 4; ++a)
{
hasDynamicBody = hasDynamicBody || ((descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY));
}
const bool isStatic = !hasDynamicBody;*/
const PxU32 headerSize = sizeof(SolverContactHeaderStepBlock) * maxPatches;
//PxU32 constraintSize = isStatic ? (sizeof(SolverContactBatchPointBase4) * totalContacts) + (sizeof(SolverContactFrictionBase4) * totalFriction) :
// (sizeof(SolverContactBatchPointDynamic4) * totalContacts) + (sizeof(SolverContactFrictionDynamic4) * totalFriction);
PxU32 constraintSize = (sizeof(SolverContactPointStepBlock) * totalContacts) + (sizeof(SolverContactFrictionStepBlock) * totalFriction);
//Space for the appliedForce buffer
constraintSize += sizeof(Vec4V)*(totalContacts + totalFriction);
//If we have max impulse, reserve a buffer for it
if (hasMaxImpulse)
constraintSize += sizeof(aos::Vec4V) * totalContacts;
_solverConstraintByteSize = ((constraintSize + headerSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
}
static SolverConstraintPrepState::Enum reserveBlockStreams4(PxTGSSolverContactDesc* descs, Dy::CorrelationBuffer& c,
PxU8*& solverConstraint, PxU32* axisConstraintCount,
PxU32& solverConstraintByteSize,
PxConstraintAllocator& constraintAllocator)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(0 == solverConstraintByteSize);
//Compute the sizes of all the buffers.
computeBlockStreamByteSizes4(descs,
solverConstraintByteSize, axisConstraintCount,
c);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if (constraintBlockByteSize > 0)
{
if ((constraintBlockByteSize + 16u) > 16384)
return SolverConstraintPrepState::eUNBATCHABLE;
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if (0 == constraintBlock || (reinterpret_cast<PxU8*>(-1)) == constraintBlock)
{
if (0 == constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock = NULL;
}
}
}
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if (0 == constraintBlockByteSize || constraintBlock)
{
if (solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0 == (uintptr_t(solverConstraint) & 0x0f));
}
}
return ((0 == constraintBlockByteSize || constraintBlock)) ? SolverConstraintPrepState::eSUCCESS : SolverConstraintPrepState::eOUT_OF_MEMORY;
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step(
Dy::CorrelationBuffer& c,
PxTGSSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal totalDtF32,
const PxReal invTotalDtF32,
const PxReal dt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator)
{
PX_ALIGN(16, PxReal invMassScale0[4]);
PX_ALIGN(16, PxReal invMassScale1[4]);
PX_ALIGN(16, PxReal invInertiaScale0[4]);
PX_ALIGN(16, PxReal invInertiaScale1[4]);
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
for (PxU32 a = 0; a < 4; ++a)
{
PxTGSSolverContactDesc& blockDesc = blockDescs[a];
invMassScale0[a] = blockDesc.invMassScales.linear0;
invMassScale1[a] = blockDesc.invMassScales.linear1;
invInertiaScale0[a] = blockDesc.invMassScales.angular0;
invInertiaScale1[a] = blockDesc.invMassScales.angular1;
blockDesc.startFrictionPatchIndex = c.frictionPatchCount;
if (!(blockDesc.disableStrongFriction))
{
const bool valid = getFrictionPatches(c, blockDesc.frictionPtr, blockDesc.frictionCount,
blockDesc.bodyFrame0, blockDesc.bodyFrame1, correlationDistance);
if (!valid)
return SolverConstraintPrepState::eUNBATCHABLE;
}
//Create the contact patches
blockDesc.startContactPatchIndex = c.contactPatchCount;
if (!createContactPatches(c, blockDesc.contacts, blockDesc.numContacts, PXC_SAME_NORMAL))
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContactPatches = PxU16(c.contactPatchCount - blockDesc.startContactPatchIndex);
const bool overflow = correlatePatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, PXC_SAME_NORMAL,
blockDesc.startContactPatchIndex, blockDesc.startFrictionPatchIndex);
if (overflow)
return SolverConstraintPrepState::eUNBATCHABLE;
growPatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, blockDesc.startFrictionPatchIndex,
frictionOffsetThreshold + blockDescs[a].restDistance);
//Remove the empty friction patches - do we actually need to do this?
for (PxU32 p = c.frictionPatchCount; p > blockDesc.startFrictionPatchIndex; --p)
{
if (c.correlationListHeads[p - 1] == 0xffff)
{
//We have an empty patch...need to bin this one...
for (PxU32 p2 = p; p2 < c.frictionPatchCount; ++p2)
{
c.correlationListHeads[p2 - 1] = c.correlationListHeads[p2];
c.frictionPatchContactCounts[p2 - 1] = c.frictionPatchContactCounts[p2];
}
c.frictionPatchCount--;
}
}
PxU32 numFricPatches = c.frictionPatchCount - blockDesc.startFrictionPatchIndex;
blockDesc.numFrictionPatches = numFricPatches;
}
FrictionPatch* frictionPatchArray[4];
PxU32 frictionPatchCounts[4];
for (PxU32 a = 0; a < 4; ++a)
{
PxTGSSolverContactDesc& blockDesc = blockDescs[a];
const bool successfulReserve = reserveFrictionBlockStreams(c, constraintAllocator, blockDesc.startFrictionPatchIndex, blockDesc.numFrictionPatches + blockDesc.startFrictionPatchIndex,
frictionPatchArray[a],
frictionPatchCounts[a]);
//KS - TODO - how can we recover if we failed to allocate this memory?
if (!successfulReserve)
{
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
}
//At this point, all the friction data has been calculated, the correlation has been done. Provided this was all successful,
//we are ready to create the batched constraints
PxU8* solverConstraint = NULL;
PxU32 solverConstraintByteSize = 0;
{
PxU32 axisConstraintCount[4];
SolverConstraintPrepState::Enum state = reserveBlockStreams4(blockDescs, c,
solverConstraint, axisConstraintCount,
solverConstraintByteSize,
constraintAllocator);
if (state != SolverConstraintPrepState::eSUCCESS)
return state;
for (PxU32 a = 0; a < 4; ++a)
{
FrictionPatch* frictionPatches = frictionPatchArray[a];
PxTGSSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
blockDesc.frictionPtr = reinterpret_cast<PxU8*>(frictionPatches);
blockDesc.frictionCount = PxTo8(frictionPatchCounts[a]);
//Initialise friction buffer.
if (frictionPatches)
{
// PT: TODO: revisit this... not very satisfying
//const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch);
PxPrefetchLine(frictionPatches);
PxPrefetchLine(frictionPatches, 128);
PxPrefetchLine(frictionPatches, 256);
for (PxU32 i = 0; i<blockDesc.numFrictionPatches; i++)
{
if (c.correlationListHeads[blockDesc.startFrictionPatchIndex + i] != CorrelationBuffer::LIST_END)
{
//*frictionPatches++ = c.frictionPatches[blockDesc.startFrictionPatchIndex + i];
PxMemCopy(frictionPatches++, &c.frictionPatches[blockDesc.startFrictionPatchIndex + i], sizeof(FrictionPatch));
//PxPrefetchLine(frictionPatches, 256);
}
}
}
blockDesc.axisConstraintCount += PxTo16(axisConstraintCount[a]);
desc.constraint = solverConstraint;
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize / 16);
desc.writeBack = blockDesc.contactForces;
}
const Vec4V iMassScale0 = V4LoadA(invMassScale0);
const Vec4V iInertiaScale0 = V4LoadA(invInertiaScale0);
const Vec4V iMassScale1 = V4LoadA(invMassScale1);
const Vec4V iInertiaScale1 = V4LoadA(invInertiaScale1);
setupFinalizeSolverConstraints4Step(blockDescs, c, solverConstraint, invDtF32, totalDtF32, invTotalDtF32, dt, bounceThresholdF32,
biasCoefficient, iMassScale0, iInertiaScale0, iMassScale1, iInertiaScale1);
PX_ASSERT((*solverConstraint == DY_SC_TYPE_BLOCK_RB_CONTACT) || (*solverConstraint == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT));
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
}
return SolverConstraintPrepState::eSUCCESS;
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step(
PxsContactManagerOutput** cmOutputs,
ThreadContext& threadContext,
PxTGSSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal totalDtF32,
const PxReal invTotalDtF32,
const PxReal dtF32,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator)
{
for (PxU32 a = 0; a < 4; ++a)
{
blockDescs[a].desc->constraintLengthOver16 = 0;
}
//PX_ASSERT(cmOutputs[0]->nbContacts && cmOutputs[1]->nbContacts && cmOutputs[2]->nbContacts && cmOutputs[3]->nbContacts);
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
//PxTransform idt = PxTransform(PxIdentity);
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
for (PxU32 a = 0; a < 4; ++a)
{
PxTGSSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
//blockDesc.startContactIndex = buffer.count;
blockDesc.contacts = buffer.contacts + buffer.count;
PxPrefetchLine(desc.bodyA);
PxPrefetchLine(desc.bodyB);
//Unbatchable if we have (a) too many contacts or (b) torsional friction enabled - it just seems easier to handle this on an individual contact basis because it is expected to
//be used relatively rarely
if ((buffer.count + cmOutputs[a]->nbContacts) > 64 || (blockDesc.torsionalPatchRadius != 0.f || blockDesc.minTorsionalPatchRadius != 0.f) )
{
return SolverConstraintPrepState::eUNBATCHABLE;
}
bool hasMaxImpulse = false;
bool hasTargetVelocity = false;
//OK...do the correlation here as well...
PxPrefetchLine(blockDescs[a].frictionPtr);
PxPrefetchLine(blockDescs[a].frictionPtr, 64);
PxPrefetchLine(blockDescs[a].frictionPtr, 128);
if (a < 3)
{
PxPrefetchLine(cmOutputs[a]->contactPatches);
PxPrefetchLine(cmOutputs[a]->contactPoints);
}
PxReal invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1;
const PxReal defaultMaxImpulse = PxMin(blockDesc.bodyData0->maxContactImpulse, blockDesc.bodyData1->maxContactImpulse);
PxU32 contactCount = extractContacts(buffer, *cmOutputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, defaultMaxImpulse);
if (contactCount == 0 || hasTargetVelocity)
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContacts = contactCount;
blockDesc.hasMaxImpulse = hasMaxImpulse;
blockDesc.disableStrongFriction = blockDesc.disableStrongFriction || hasTargetVelocity;
blockDesc.invMassScales.linear0 *= invMassScale0;
blockDesc.invMassScales.linear1 *= invMassScale1;
blockDesc.invMassScales.angular0 *= blockDesc.body0->isKinematic ? 0.f : invInertiaScale0;
blockDesc.invMassScales.angular1 *= blockDesc.body1->isKinematic ? 0.f : invInertiaScale1;
}
return createFinalizeSolverContacts4Step(c, blockDescs,
invDtF32, totalDtF32, invTotalDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold,
correlationDistance, biasCoefficient, constraintAllocator);
}
void setSolverConstantsStep(PxReal& error,
PxReal& biasScale,
PxReal& targetVel,
PxReal& maxBias,
PxReal& velMultiplier,
PxReal& rcpResponse,
const Px1DConstraint& c,
PxReal normalVel,
PxReal unitResponse,
PxReal minRowResponse,
PxReal erp,
PxReal dt,
PxReal totalDt,
PxReal biasClamp,
PxReal recipdt,
PxReal recipTotalDt,
PxReal velTarget);
static void setConstants(PxReal& error, PxReal& biasScale, PxReal& targetVel, PxReal& maxBias, PxReal& velMultiplier,
PxReal& rcpResponse, const Px1DConstraint& c, PxReal unitResponse, PxReal minRowResponse, PxReal dt, PxReal totalDt,
PxReal recipdt, PxReal recipTotalDt, bool finished,
PxReal lengthScale, PxReal nv, PxReal nv0, PxReal nv1, bool isKinematic0, bool isKinematic1, PxReal erp)
{
if (finished)
{
error = 0.f;
biasScale = 0.f;
maxBias = 0.f;
velMultiplier = 0.f;
rcpResponse = 0.f;
targetVel = 0.f;
return;
}
//PxReal biasClamp = c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT ? 50.f : 200.f*lengthScale;
PxReal biasClamp = c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT ? 100.f : 1000.f*lengthScale;
PxReal vt = 0.f;
if (isKinematic0)
vt -= nv0;
if (isKinematic1)
vt += nv1;
setSolverConstantsStep(error, biasScale, targetVel, maxBias, velMultiplier, rcpResponse, c, nv, unitResponse,
minRowResponse, erp, dt, totalDt, biasClamp, recipdt, recipTotalDt, vt);
}
static void setOrthoData(const PxReal& ang0X, const PxReal& ang0Y, const PxReal& ang0Z, const PxReal& ang1X, const PxReal& ang1Y, const PxReal& ang1Z,
const PxReal& recipResponse, const PxReal& error, PxReal& orthoAng0X, PxReal& orthoAng0Y, PxReal& orthoAng0Z, PxReal& orthoAng1X, PxReal& orthoAng1Y, PxReal& orthoAng1Z,
PxReal& orthoRecipResponse, PxReal& orthoError, bool disableProcessing, PxU32 solveHint, PxU32& flags, PxU32& orthoCount, bool finished)
{
if (!finished && !disableProcessing)
{
if (solveHint == PxConstraintSolveHint::eROTATIONAL_EQUALITY)
{
flags |= DY_SC_FLAG_ROT_EQ;
orthoAng0X = ang0X; orthoAng0Y = ang0Y; orthoAng0Z = ang0Z;
orthoAng1X = ang1X; orthoAng1Y = ang1Y; orthoAng1Z = ang1Z;
orthoRecipResponse = recipResponse;
orthoError = error;
orthoCount++;
}
else if (solveHint & PxConstraintSolveHint::eEQUALITY)
flags |= DY_SC_FLAG_ORTHO_TARGET;
}
}
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows, const PxReal lengthScale, const PxReal biasCoefficient);
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs,
PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, const PxReal lengthScale, const PxReal biasCoefficient)
{
//KS - we will never get here with constraints involving articulations so we don't need to stress about those in here
totalRows = 0;
Px1DConstraint allRows[MAX_CONSTRAINT_ROWS * 4];
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
for (PxU32 a = 0; a < 4; ++a)
{
SolverConstraintShaderPrepDesc& shaderDesc = constraintShaderDescs[a];
PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a];
if (!shaderDesc.solverPrep)
return SolverConstraintPrepState::eUNBATCHABLE;
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
//TAG:solverprepcall
const PxU32 constraintCount = desc.disableConstraint ? 0 : (*shaderDesc.solverPrep)(rows,
desc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
desc.invMassScales,
shaderDesc.constantBlock,
desc.bodyFrame0, desc.bodyFrame1, desc.extendedLimits, desc.cA2w, desc.cB2w);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
if (constraintCount == 0)
return SolverConstraintPrepState::eUNBATCHABLE;
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
if (desc.body0->isKinematic)
desc.invMassScales.angular0 = 0.0f;
if (desc.body1->isKinematic)
desc.invMassScales.angular1 = 0.0f;
}
return setupSolverConstraintStep4(constraintDescs, dt, totalDt, recipdt, recipTotalDt, totalRows, allocator, maxRows, lengthScale, biasCoefficient);
}
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows,
const PxReal lengthScale, const PxReal biasCoefficient)
{
const Vec4V zero = V4Zero();
Px1DConstraint* allSorted[MAX_CONSTRAINT_ROWS * 4];
PxU32 startIndex[4];
PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS * 4];
PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS * 4];
PxU32 numRows = 0;
for (PxU32 a = 0; a < 4; ++a)
{
startIndex[a] = numRows;
PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a];
Px1DConstraint** sorted = allSorted + numRows;
for (PxU32 i = 0; i < desc.numRows; ++i)
{
if (desc.rows[i].flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT)
{
if (desc.rows[i].solveHint == PxConstraintSolveHint::eEQUALITY)
desc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_EQUALITY;
else if (desc.rows[i].solveHint == PxConstraintSolveHint::eINEQUALITY)
desc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_INEQUALITY;
}
}
preprocessRows(sorted, desc.rows, angSqrtInvInertia0 + numRows, angSqrtInvInertia1 + numRows, desc.numRows,
desc.body0TxI->sqrtInvInertia, desc.body1TxI->sqrtInvInertia, desc.bodyData0->invMass, desc.bodyData1->invMass,
desc.invMassScales, desc.disablePreprocessing, desc.improvedSlerp);
numRows += desc.numRows;
}
const PxU32 stride = sizeof(SolverConstraint1DStep4);
const PxU32 constraintLength = sizeof(SolverConstraint1DHeaderStep4) + stride * maxRows;
//KS - +16 is for the constraint progress counter, which needs to be the last element in the constraint (so that we
//know SPU DMAs have completed)
PxU8* ptr = allocator.reserveConstraintData(constraintLength + 16u);
if (NULL == ptr || (reinterpret_cast<PxU8*>(-1)) == ptr)
{
for (PxU32 a = 0; a < 4; ++a)
{
PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a];
desc.desc->constraint = NULL;
desc.desc->constraintLengthOver16 = 0;
desc.desc->writeBack = desc.writeback;
}
if (NULL == ptr)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept joints detaching/exploding or increase buffer size allocated for constraint prep by increasing PxSceneDesc::maxNbContactDataBlocks.");
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of constraint data. "
"Either accept joints detaching/exploding or simplify constraints.");
ptr = NULL;
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
}
//desc.constraint = ptr;
totalRows = numRows;
const PxReal erp = 0.5f * biasCoefficient;
const bool isKinematic00 = constraintDescs[0].body0->isKinematic;
const bool isKinematic01 = constraintDescs[0].body1->isKinematic;
const bool isKinematic10 = constraintDescs[1].body0->isKinematic;
const bool isKinematic11 = constraintDescs[1].body1->isKinematic;
const bool isKinematic20 = constraintDescs[2].body0->isKinematic;
const bool isKinematic21 = constraintDescs[2].body1->isKinematic;
const bool isKinematic30 = constraintDescs[3].body0->isKinematic;
const bool isKinematic31 = constraintDescs[3].body1->isKinematic;
for (PxU32 a = 0; a < 4; ++a)
{
PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a];
desc.desc->constraint = ptr;
desc.desc->constraintLengthOver16 = PxU16(constraintLength/16);
desc.desc->writeBack = desc.writeback;
}
{
PxU8* currPtr = ptr;
SolverConstraint1DHeaderStep4* header = reinterpret_cast<SolverConstraint1DHeaderStep4*>(currPtr);
currPtr += sizeof(SolverConstraint1DHeaderStep4);
const PxTGSSolverBodyData& bd00 = *constraintDescs[0].bodyData0;
const PxTGSSolverBodyData& bd01 = *constraintDescs[1].bodyData0;
const PxTGSSolverBodyData& bd02 = *constraintDescs[2].bodyData0;
const PxTGSSolverBodyData& bd03 = *constraintDescs[3].bodyData0;
const PxTGSSolverBodyData& bd10 = *constraintDescs[0].bodyData1;
const PxTGSSolverBodyData& bd11 = *constraintDescs[1].bodyData1;
const PxTGSSolverBodyData& bd12 = *constraintDescs[2].bodyData1;
const PxTGSSolverBodyData& bd13 = *constraintDescs[3].bodyData1;
//Load up masses, invInertia, velocity etc.
const Vec4V invMassScale0 = V4LoadXYZW(constraintDescs[0].invMassScales.linear0, constraintDescs[1].invMassScales.linear0,
constraintDescs[2].invMassScales.linear0, constraintDescs[3].invMassScales.linear0);
const Vec4V invMassScale1 = V4LoadXYZW(constraintDescs[0].invMassScales.linear1, constraintDescs[1].invMassScales.linear1,
constraintDescs[2].invMassScales.linear1, constraintDescs[3].invMassScales.linear1);
const Vec4V iMass0 = V4LoadXYZW(bd00.invMass, bd01.invMass, bd02.invMass, bd03.invMass);
const Vec4V iMass1 = V4LoadXYZW(bd10.invMass, bd11.invMass, bd12.invMass, bd13.invMass);
const Vec4V invMass0 = V4Mul(iMass0, invMassScale0);
const Vec4V invMass1 = V4Mul(iMass1, invMassScale1);
const Vec4V invInertiaScale0 = V4LoadXYZW(constraintDescs[0].invMassScales.angular0, constraintDescs[1].invMassScales.angular0,
constraintDescs[2].invMassScales.angular0, constraintDescs[3].invMassScales.angular0);
const Vec4V invInertiaScale1 = V4LoadXYZW(constraintDescs[0].invMassScales.angular1, constraintDescs[1].invMassScales.angular1,
constraintDescs[2].invMassScales.angular1, constraintDescs[3].invMassScales.angular1);
//body world offsets
Vec4V workOffset0 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[0].body0WorldOffset));
Vec4V workOffset1 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[1].body0WorldOffset));
Vec4V workOffset2 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[2].body0WorldOffset));
Vec4V workOffset3 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[3].body0WorldOffset));
Vec4V workOffsetX, workOffsetY, workOffsetZ;
PX_TRANSPOSE_44_34(workOffset0, workOffset1, workOffset2, workOffset3, workOffsetX, workOffsetY, workOffsetZ);
const FloatV dtV = FLoad(totalDt);
Vec4V linBreakForce = V4LoadXYZW(constraintDescs[0].linBreakForce, constraintDescs[1].linBreakForce,
constraintDescs[2].linBreakForce, constraintDescs[3].linBreakForce);
Vec4V angBreakForce = V4LoadXYZW(constraintDescs[0].angBreakForce, constraintDescs[1].angBreakForce,
constraintDescs[2].angBreakForce, constraintDescs[3].angBreakForce);
header->breakable[0] = PxU8((constraintDescs[0].linBreakForce != PX_MAX_F32) || (constraintDescs[0].angBreakForce != PX_MAX_F32));
header->breakable[1] = PxU8((constraintDescs[1].linBreakForce != PX_MAX_F32) || (constraintDescs[1].angBreakForce != PX_MAX_F32));
header->breakable[2] = PxU8((constraintDescs[2].linBreakForce != PX_MAX_F32) || (constraintDescs[2].angBreakForce != PX_MAX_F32));
header->breakable[3] = PxU8((constraintDescs[3].linBreakForce != PX_MAX_F32) || (constraintDescs[3].angBreakForce != PX_MAX_F32));
//OK, I think that's everything loaded in
header->invMass0D0 = invMass0;
header->invMass1D1 = invMass1;
header->angD0 = invInertiaScale0;
header->angD1 = invInertiaScale1;
header->body0WorkOffset[0] = workOffsetX;
header->body0WorkOffset[1] = workOffsetY;
header->body0WorkOffset[2] = workOffsetZ;
header->count = maxRows;
header->type = DY_SC_TYPE_BLOCK_1D;
header->linBreakImpulse = V4Scale(linBreakForce, dtV);
header->angBreakImpulse = V4Scale(angBreakForce, dtV);
header->counts[0] = PxTo8(constraintDescs[0].numRows);
header->counts[1] = PxTo8(constraintDescs[1].numRows);
header->counts[2] = PxTo8(constraintDescs[2].numRows);
header->counts[3] = PxTo8(constraintDescs[3].numRows);
Vec4V ca2WX, ca2WY, ca2WZ;
Vec4V cb2WX, cb2WY, cb2WZ;
Vec4V ca2W0 = V4LoadU(&constraintDescs[0].cA2w.x);
Vec4V ca2W1 = V4LoadU(&constraintDescs[1].cA2w.x);
Vec4V ca2W2 = V4LoadU(&constraintDescs[2].cA2w.x);
Vec4V ca2W3 = V4LoadU(&constraintDescs[3].cA2w.x);
Vec4V cb2W0 = V4LoadU(&constraintDescs[0].cB2w.x);
Vec4V cb2W1 = V4LoadU(&constraintDescs[1].cB2w.x);
Vec4V cb2W2 = V4LoadU(&constraintDescs[2].cB2w.x);
Vec4V cb2W3 = V4LoadU(&constraintDescs[3].cB2w.x);
PX_TRANSPOSE_44_34(ca2W0, ca2W1, ca2W2, ca2W3, ca2WX, ca2WY, ca2WZ);
PX_TRANSPOSE_44_34(cb2W0, cb2W1, cb2W2, cb2W3, cb2WX, cb2WY, cb2WZ);
Vec4V pos00 = V4LoadA(&constraintDescs[0].body0TxI->deltaBody2World.p.x);
Vec4V pos01 = V4LoadA(&constraintDescs[0].body1TxI->deltaBody2World.p.x);
Vec4V pos10 = V4LoadA(&constraintDescs[1].body0TxI->deltaBody2World.p.x);
Vec4V pos11 = V4LoadA(&constraintDescs[1].body1TxI->deltaBody2World.p.x);
Vec4V pos20 = V4LoadA(&constraintDescs[2].body0TxI->deltaBody2World.p.x);
Vec4V pos21 = V4LoadA(&constraintDescs[2].body1TxI->deltaBody2World.p.x);
Vec4V pos30 = V4LoadA(&constraintDescs[3].body0TxI->deltaBody2World.p.x);
Vec4V pos31 = V4LoadA(&constraintDescs[3].body1TxI->deltaBody2World.p.x);
Vec4V pos0X, pos0Y, pos0Z;
Vec4V pos1X, pos1Y, pos1Z;
PX_TRANSPOSE_44_34(pos00, pos10, pos20, pos30, pos0X, pos0Y, pos0Z);
PX_TRANSPOSE_44_34(pos01, pos11, pos21, pos31, pos1X, pos1Y, pos1Z);
Vec4V linVel00 = V4LoadA(&constraintDescs[0].bodyData0->originalLinearVelocity.x);
Vec4V linVel01 = V4LoadA(&constraintDescs[0].bodyData1->originalLinearVelocity.x);
Vec4V angState00 = V4LoadA(&constraintDescs[0].bodyData0->originalAngularVelocity.x);
Vec4V angState01 = V4LoadA(&constraintDescs[0].bodyData1->originalAngularVelocity.x);
Vec4V linVel10 = V4LoadA(&constraintDescs[1].bodyData0->originalLinearVelocity.x);
Vec4V linVel11 = V4LoadA(&constraintDescs[1].bodyData1->originalLinearVelocity.x);
Vec4V angState10 = V4LoadA(&constraintDescs[1].bodyData0->originalAngularVelocity.x);
Vec4V angState11 = V4LoadA(&constraintDescs[1].bodyData1->originalAngularVelocity.x);
Vec4V linVel20 = V4LoadA(&constraintDescs[2].bodyData0->originalLinearVelocity.x);
Vec4V linVel21 = V4LoadA(&constraintDescs[2].bodyData1->originalLinearVelocity.x);
Vec4V angState20 = V4LoadA(&constraintDescs[2].bodyData0->originalAngularVelocity.x);
Vec4V angState21 = V4LoadA(&constraintDescs[2].bodyData1->originalAngularVelocity.x);
Vec4V linVel30 = V4LoadA(&constraintDescs[3].bodyData0->originalLinearVelocity.x);
Vec4V linVel31 = V4LoadA(&constraintDescs[3].bodyData1->originalLinearVelocity.x);
Vec4V angState30 = V4LoadA(&constraintDescs[3].bodyData0->originalAngularVelocity.x);
Vec4V angState31 = V4LoadA(&constraintDescs[3].bodyData1->originalAngularVelocity.x);
Vec4V linVel0T0, linVel0T1, linVel0T2;
Vec4V linVel1T0, linVel1T1, linVel1T2;
Vec4V angState0T0, angState0T1, angState0T2;
Vec4V angState1T0, angState1T1, angState1T2;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2);
PX_TRANSPOSE_44_34(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2);
PX_TRANSPOSE_44_34(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2);
const Vec4V raWorldX = V4Sub(ca2WX, pos0X);
const Vec4V raWorldY = V4Sub(ca2WY, pos0Y);
const Vec4V raWorldZ = V4Sub(ca2WZ, pos0Z);
const Vec4V rbWorldX = V4Sub(cb2WX, pos1X);
const Vec4V rbWorldY = V4Sub(cb2WY, pos1Y);
const Vec4V rbWorldZ = V4Sub(cb2WZ, pos1Z);
header->rAWorld[0] = raWorldX;
header->rAWorld[1] = raWorldY;
header->rAWorld[2] = raWorldZ;
header->rBWorld[0] = rbWorldX;
header->rBWorld[1] = rbWorldY;
header->rBWorld[2] = rbWorldZ;
//Now we loop over the constraints and build the results...
PxU32 index0 = 0;
PxU32 endIndex0 = constraintDescs[0].numRows - 1;
PxU32 index1 = startIndex[1];
PxU32 endIndex1 = index1 + constraintDescs[1].numRows - 1;
PxU32 index2 = startIndex[2];
PxU32 endIndex2 = index2 + constraintDescs[2].numRows - 1;
PxU32 index3 = startIndex[3];
PxU32 endIndex3 = index3 + constraintDescs[3].numRows - 1;
const Vec4V one = V4One();
const FloatV fOne = FOne();
PxU32 orthoCount0 = 0, orthoCount1 = 0, orthoCount2 = 0, orthoCount3 = 0;
for (PxU32 a = 0; a < 3; ++a)
{
header->angOrthoAxis0X[a] = V4Zero();
header->angOrthoAxis0Y[a] = V4Zero();
header->angOrthoAxis0Z[a] = V4Zero();
header->angOrthoAxis1X[a] = V4Zero();
header->angOrthoAxis1Y[a] = V4Zero();
header->angOrthoAxis1Z[a] = V4Zero();
header->angOrthoRecipResponse[a] = V4Zero();
header->angOrthoError[a] = V4Zero();
}
for (PxU32 a = 0; a < maxRows; ++a)
{
const bool finished[] = { a >= constraintDescs[0].numRows, a >= constraintDescs[1].numRows, a >= constraintDescs[2].numRows, a >= constraintDescs[3].numRows };
BoolV bFinished = BLoad(finished);
SolverConstraint1DStep4* c = reinterpret_cast<SolverConstraint1DStep4*>(currPtr);
currPtr += stride;
Px1DConstraint* con0 = allSorted[index0];
Px1DConstraint* con1 = allSorted[index1];
Px1DConstraint* con2 = allSorted[index2];
Px1DConstraint* con3 = allSorted[index3];
const bool angularConstraint[4] =
{
!!(con0->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT),
!!(con1->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT),
!!(con2->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT),
!!(con3->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT),
};
BoolV bAngularConstraint = BLoad(angularConstraint);
Vec4V cangDelta00 = V4LoadA(&angSqrtInvInertia0[index0].x);
Vec4V cangDelta01 = V4LoadA(&angSqrtInvInertia0[index1].x);
Vec4V cangDelta02 = V4LoadA(&angSqrtInvInertia0[index2].x);
Vec4V cangDelta03 = V4LoadA(&angSqrtInvInertia0[index3].x);
Vec4V cangDelta10 = V4LoadA(&angSqrtInvInertia1[index0].x);
Vec4V cangDelta11 = V4LoadA(&angSqrtInvInertia1[index1].x);
Vec4V cangDelta12 = V4LoadA(&angSqrtInvInertia1[index2].x);
Vec4V cangDelta13 = V4LoadA(&angSqrtInvInertia1[index3].x);
index0 = index0 == endIndex0 ? index0 : index0 + 1;
index1 = index1 == endIndex1 ? index1 : index1 + 1;
index2 = index2 == endIndex2 ? index2 : index2 + 1;
index3 = index3 == endIndex3 ? index3 : index3 + 1;
Vec4V driveScale = one;
if (con0->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[0].driveLimitsAreForces)
driveScale = V4SetX(driveScale, FMin(fOne, dtV));
if (con1->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[1].driveLimitsAreForces)
driveScale = V4SetY(driveScale, FMin(fOne, dtV));
if (con2->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[2].driveLimitsAreForces)
driveScale = V4SetZ(driveScale, FMin(fOne, dtV));
if (con3->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[3].driveLimitsAreForces)
driveScale = V4SetW(driveScale, FMin(fOne, dtV));
Vec4V clin00 = V4LoadA(&con0->linear0.x);
Vec4V clin01 = V4LoadA(&con1->linear0.x);
Vec4V clin02 = V4LoadA(&con2->linear0.x);
Vec4V clin03 = V4LoadA(&con3->linear0.x);
Vec4V clin0X, clin0Y, clin0Z;
PX_TRANSPOSE_44_34(clin00, clin01, clin02, clin03, clin0X, clin0Y, clin0Z);
Vec4V cang00 = V4LoadA(&con0->angular0.x);
Vec4V cang01 = V4LoadA(&con1->angular0.x);
Vec4V cang02 = V4LoadA(&con2->angular0.x);
Vec4V cang03 = V4LoadA(&con3->angular0.x);
Vec4V cang0X, cang0Y, cang0Z;
PX_TRANSPOSE_44_34(cang00, cang01, cang02, cang03, cang0X, cang0Y, cang0Z);
Vec4V cang10 = V4LoadA(&con0->angular1.x);
Vec4V cang11 = V4LoadA(&con1->angular1.x);
Vec4V cang12 = V4LoadA(&con2->angular1.x);
Vec4V cang13 = V4LoadA(&con3->angular1.x);
Vec4V cang1X, cang1Y, cang1Z;
PX_TRANSPOSE_44_34(cang10, cang11, cang12, cang13, cang1X, cang1Y, cang1Z);
const Vec4V maxImpulse = V4LoadXYZW(con0->maxImpulse, con1->maxImpulse, con2->maxImpulse, con3->maxImpulse);
const Vec4V minImpulse = V4LoadXYZW(con0->minImpulse, con1->minImpulse, con2->minImpulse, con3->minImpulse);
Vec4V angDelta0X, angDelta0Y, angDelta0Z;
PX_TRANSPOSE_44_34(cangDelta00, cangDelta01, cangDelta02, cangDelta03, angDelta0X, angDelta0Y, angDelta0Z);
c->flags[0] = 0;
c->flags[1] = 0;
c->flags[2] = 0;
c->flags[3] = 0;
c->lin0[0] = V4Sel(bFinished, zero, clin0X);
c->lin0[1] = V4Sel(bFinished, zero, clin0Y);
c->lin0[2] = V4Sel(bFinished, zero, clin0Z);
c->ang0[0] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang0X, zero);
c->ang0[1] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang0Y, zero);
c->ang0[2] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang0Z, zero);
c->angularErrorScale = V4Sel(bAngularConstraint, one, zero);
c->minImpulse = V4Mul(minImpulse, driveScale);
c->maxImpulse = V4Mul(maxImpulse, driveScale);
c->appliedForce = zero;
const Vec4V lin0MagSq = V4MulAdd(clin0Z, clin0Z, V4MulAdd(clin0Y, clin0Y, V4Mul(clin0X, clin0X)));
const Vec4V cang0DotAngDelta = V4MulAdd(angDelta0Z, angDelta0Z, V4MulAdd(angDelta0Y, angDelta0Y, V4Mul(angDelta0X, angDelta0X)));
Vec4V unitResponse = V4MulAdd(lin0MagSq, invMass0, V4Mul(cang0DotAngDelta, invInertiaScale0));
Vec4V clin10 = V4LoadA(&con0->linear1.x);
Vec4V clin11 = V4LoadA(&con1->linear1.x);
Vec4V clin12 = V4LoadA(&con2->linear1.x);
Vec4V clin13 = V4LoadA(&con3->linear1.x);
Vec4V clin1X, clin1Y, clin1Z;
PX_TRANSPOSE_44_34(clin10, clin11, clin12, clin13, clin1X, clin1Y, clin1Z);
Vec4V angDelta1X, angDelta1Y, angDelta1Z;
PX_TRANSPOSE_44_34(cangDelta10, cangDelta11, cangDelta12, cangDelta13, angDelta1X, angDelta1Y, angDelta1Z);
const Vec4V lin1MagSq = V4MulAdd(clin1Z, clin1Z, V4MulAdd(clin1Y, clin1Y, V4Mul(clin1X, clin1X)));
const Vec4V cang1DotAngDelta = V4MulAdd(angDelta1Z, angDelta1Z, V4MulAdd(angDelta1Y, angDelta1Y, V4Mul(angDelta1X, angDelta1X)));
c->lin1[0] = V4Sel(bFinished, zero, clin1X);
c->lin1[1] = V4Sel(bFinished, zero, clin1Y);
c->lin1[2] = V4Sel(bFinished, zero, clin1Z);
c->ang1[0] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang1X, zero);
c->ang1[1] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang1Y, zero);
c->ang1[2] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang1Z, zero);
unitResponse = V4Add(unitResponse, V4MulAdd(lin1MagSq, invMass1, V4Mul(cang1DotAngDelta, invInertiaScale1)));
const Vec4V lnormalVel0 = V4MulAdd(clin0X, linVel0T0, V4MulAdd(clin0Y, linVel0T1, V4Mul(clin0Z, linVel0T2)));
const Vec4V lnormalVel1 = V4MulAdd(clin1X, linVel1T0, V4MulAdd(clin1Y, linVel1T1, V4Mul(clin1Z, linVel1T2)));
const Vec4V angVel0 = V4MulAdd(cang0X, angState0T0, V4MulAdd(cang0Y, angState0T1, V4Mul(cang0Z, angState0T2)));
const Vec4V angVel1 = V4MulAdd(angDelta1X, angState1T0, V4MulAdd(angDelta1Y, angState1T1, V4Mul(angDelta1Z, angState1T2)));
const Vec4V normalVel0 = V4Add(lnormalVel0, angVel0);
const Vec4V normalVel1 = V4Add(lnormalVel1, angVel1);
const Vec4V normalVel = V4Sub(normalVel0, normalVel1);
angDelta0X = V4Mul(angDelta0X, invInertiaScale0);
angDelta0Y = V4Mul(angDelta0Y, invInertiaScale0);
angDelta0Z = V4Mul(angDelta0Z, invInertiaScale0);
angDelta1X = V4Mul(angDelta1X, invInertiaScale1);
angDelta1Y = V4Mul(angDelta1Y, invInertiaScale1);
angDelta1Z = V4Mul(angDelta1Z, invInertiaScale1);
{
PxReal recipResponse[4];
const PxVec4& ur = reinterpret_cast<const PxVec4&>(unitResponse);
PxVec4& cBiasScale = reinterpret_cast<PxVec4&>(c->biasScale);
PxVec4& cError = reinterpret_cast<PxVec4&>(c->error);
PxVec4& cMaxBias = reinterpret_cast<PxVec4&>(c->maxBias);
PxVec4& cTargetVel = reinterpret_cast<PxVec4&>(c->velTarget);
PxVec4& cVelMultiplier = reinterpret_cast<PxVec4&>(c->velMultiplier);
const PxVec4& nVel = reinterpret_cast<const PxVec4&>(normalVel);
const PxVec4& nVel0 = reinterpret_cast<const PxVec4&>(normalVel0);
const PxVec4& nVel1 = reinterpret_cast<const PxVec4&>(normalVel1);
setConstants(cError.x, cBiasScale.x, cTargetVel.x, cMaxBias.x, cVelMultiplier.x,
recipResponse[0], *con0, ur.x, constraintDescs[0].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt,
a >= constraintDescs[0].numRows, lengthScale, nVel.x, nVel0.x, nVel1.x, isKinematic00, isKinematic01, erp);
setConstants(cError.y, cBiasScale.y, cTargetVel.y, cMaxBias.y, cVelMultiplier.y,
recipResponse[1], *con1, ur.y, constraintDescs[1].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt,
a >= constraintDescs[1].numRows, lengthScale, nVel.y, nVel0.y, nVel1.y, isKinematic10, isKinematic11, erp);
setConstants(cError.z, cBiasScale.z, cTargetVel.z, cMaxBias.z, cVelMultiplier.z,
recipResponse[2], *con2, ur.z, constraintDescs[2].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt,
a >= constraintDescs[2].numRows, lengthScale, nVel.z, nVel0.z, nVel1.z, isKinematic20, isKinematic21, erp);
setConstants(cError.w, cBiasScale.w, cTargetVel.w, cMaxBias.w, cVelMultiplier.w,
recipResponse[3], *con3, ur.w, constraintDescs[3].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt,
a >= constraintDescs[3].numRows, lengthScale, nVel.w, nVel0.w, nVel1.w, isKinematic30, isKinematic31, erp);
PxVec4* angOrthoAxes0X = reinterpret_cast<PxVec4*>(header->angOrthoAxis0X);
PxVec4* angOrthoAxes0Y = reinterpret_cast<PxVec4*>(header->angOrthoAxis0Y);
PxVec4* angOrthoAxes0Z = reinterpret_cast<PxVec4*>(header->angOrthoAxis0Z);
PxVec4* angOrthoAxes1X = reinterpret_cast<PxVec4*>(header->angOrthoAxis1X);
PxVec4* angOrthoAxes1Y = reinterpret_cast<PxVec4*>(header->angOrthoAxis1Y);
PxVec4* angOrthoAxes1Z = reinterpret_cast<PxVec4*>(header->angOrthoAxis1Z);
PxVec4* orthoRecipResponse = reinterpret_cast<PxVec4*>(header->angOrthoRecipResponse);
PxVec4* orthoError = reinterpret_cast<PxVec4*>(header->angOrthoError);
const PxVec4& ang0X = reinterpret_cast<const PxVec4&>(angDelta0X);
const PxVec4& ang0Y = reinterpret_cast<const PxVec4&>(angDelta0Y);
const PxVec4& ang0Z = reinterpret_cast<const PxVec4&>(angDelta0Z);
const PxVec4& ang1X = reinterpret_cast<const PxVec4&>(angDelta1X);
const PxVec4& ang1Y = reinterpret_cast<const PxVec4&>(angDelta1Y);
const PxVec4& ang1Z = reinterpret_cast<const PxVec4&>(angDelta1Z);
setOrthoData(ang0X.x, ang0Y.x, ang0Z.x, ang1X.x, ang1Y.x, ang1Z.x, recipResponse[0], cError.x, angOrthoAxes0X[orthoCount0].x,
angOrthoAxes0Y[orthoCount0].x, angOrthoAxes0Z[orthoCount0].x, angOrthoAxes1X[orthoCount0].x, angOrthoAxes1Y[orthoCount0].x,
angOrthoAxes1Z[orthoCount0].x, orthoRecipResponse[orthoCount0].x, orthoError[orthoCount0].x, constraintDescs[0].disablePreprocessing, con0->solveHint,
c->flags[0], orthoCount0, a >= constraintDescs[0].numRows);
setOrthoData(ang0X.y, ang0Y.y, ang0Z.y, ang1X.y, ang1Y.y, ang1Z.y, recipResponse[1], cError.y, angOrthoAxes0X[orthoCount1].y,
angOrthoAxes0Y[orthoCount1].y, angOrthoAxes0Z[orthoCount1].y, angOrthoAxes1X[orthoCount1].y, angOrthoAxes1Y[orthoCount1].y,
angOrthoAxes1Z[orthoCount1].y, orthoRecipResponse[orthoCount1].y, orthoError[orthoCount1].y, constraintDescs[1].disablePreprocessing, con1->solveHint,
c->flags[1], orthoCount1, a >= constraintDescs[1].numRows);
setOrthoData(ang0X.z, ang0Y.z, ang0Z.z, ang1X.z, ang1Y.z, ang1Z.z, recipResponse[2], cError.z, angOrthoAxes0X[orthoCount2].z,
angOrthoAxes0Y[orthoCount2].z, angOrthoAxes0Z[orthoCount2].z, angOrthoAxes1X[orthoCount2].z, angOrthoAxes1Y[orthoCount2].z,
angOrthoAxes1Z[orthoCount2].z, orthoRecipResponse[orthoCount2].z, orthoError[orthoCount2].z, constraintDescs[2].disablePreprocessing, con2->solveHint,
c->flags[2], orthoCount2, a >= constraintDescs[2].numRows);
setOrthoData(ang0X.w, ang0Y.w, ang0Z.w, ang1X.w, ang1Y.w, ang1Z.w, recipResponse[3], cError.w, angOrthoAxes0X[orthoCount3].w,
angOrthoAxes0Y[orthoCount3].w, angOrthoAxes0Z[orthoCount3].w, angOrthoAxes1X[orthoCount3].w, angOrthoAxes1Y[orthoCount3].w,
angOrthoAxes1Z[orthoCount3].w, orthoRecipResponse[orthoCount3].w, orthoError[orthoCount3].w, constraintDescs[3].disablePreprocessing, con3->solveHint,
c->flags[3], orthoCount3, a >= constraintDescs[3].numRows);
}
if (con0->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[0] |= DY_SC_FLAG_OUTPUT_FORCE;
if (con1->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[1] |= DY_SC_FLAG_OUTPUT_FORCE;
if (con2->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[2] |= DY_SC_FLAG_OUTPUT_FORCE;
if (con3->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[3] |= DY_SC_FLAG_OUTPUT_FORCE;
if ((con0->flags & Px1DConstraintFlag::eKEEPBIAS))
c->flags[0] |= DY_SC_FLAG_KEEP_BIAS;
if ((con1->flags & Px1DConstraintFlag::eKEEPBIAS))
c->flags[1] |= DY_SC_FLAG_KEEP_BIAS;
if ((con2->flags & Px1DConstraintFlag::eKEEPBIAS))
c->flags[2] |= DY_SC_FLAG_KEEP_BIAS;
if ((con3->flags & Px1DConstraintFlag::eKEEPBIAS))
c->flags[3] |= DY_SC_FLAG_KEEP_BIAS;
//Flag inequality constraints...
if (con0->solveHint & 1)
c->flags[0] |= DY_SC_FLAG_INEQUALITY;
if (con1->solveHint & 1)
c->flags[1] |= DY_SC_FLAG_INEQUALITY;
if (con2->solveHint & 1)
c->flags[2] |= DY_SC_FLAG_INEQUALITY;
if (con3->solveHint & 1)
c->flags[3] |= DY_SC_FLAG_INEQUALITY;
}
*(reinterpret_cast<PxU32*>(currPtr)) = 0;
*(reinterpret_cast<PxU32*>(currPtr + 4)) = 0;
}
//OK, we're ready to allocate and solve prep these constraints now :-)
return SolverConstraintPrepState::eSUCCESS;
}
static void solveContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, const bool doFriction, const PxReal minPenetration,
const PxReal elapsedTimeF32)
{
PxTGSSolverBodyVel& b00 = *desc[0].tgsBodyA;
PxTGSSolverBodyVel& b01 = *desc[0].tgsBodyB;
PxTGSSolverBodyVel& b10 = *desc[1].tgsBodyA;
PxTGSSolverBodyVel& b11 = *desc[1].tgsBodyB;
PxTGSSolverBodyVel& b20 = *desc[2].tgsBodyA;
PxTGSSolverBodyVel& b21 = *desc[2].tgsBodyB;
PxTGSSolverBodyVel& b30 = *desc[3].tgsBodyA;
PxTGSSolverBodyVel& b31 = *desc[3].tgsBodyB;
const Vec4V minPen = V4Load(minPenetration);
const Vec4V elapsedTime = V4Load(elapsedTimeF32);
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularVelocity.x);
Vec4V angState01 = V4LoadA(&b01.angularVelocity.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularVelocity.x);
Vec4V angState11 = V4LoadA(&b11.angularVelocity.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularVelocity.x);
Vec4V angState21 = V4LoadA(&b21.angularVelocity.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularVelocity.x);
Vec4V angState31 = V4LoadA(&b31.angularVelocity.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
Vec4V linDelta00_ = V4LoadA(&b00.deltaLinDt.x);
Vec4V linDelta01_ = V4LoadA(&b01.deltaLinDt.x);
Vec4V angDelta00_ = V4LoadA(&b00.deltaAngDt.x);
Vec4V angDelta01_ = V4LoadA(&b01.deltaAngDt.x);
Vec4V linDelta10_ = V4LoadA(&b10.deltaLinDt.x);
Vec4V linDelta11_ = V4LoadA(&b11.deltaLinDt.x);
Vec4V angDelta10_ = V4LoadA(&b10.deltaAngDt.x);
Vec4V angDelta11_ = V4LoadA(&b11.deltaAngDt.x);
Vec4V linDelta20_ = V4LoadA(&b20.deltaLinDt.x);
Vec4V linDelta21_ = V4LoadA(&b21.deltaLinDt.x);
Vec4V angDelta20_ = V4LoadA(&b20.deltaAngDt.x);
Vec4V angDelta21_ = V4LoadA(&b21.deltaAngDt.x);
Vec4V linDelta30_ = V4LoadA(&b30.deltaLinDt.x);
Vec4V linDelta31_ = V4LoadA(&b31.deltaLinDt.x);
Vec4V angDelta30_ = V4LoadA(&b30.deltaAngDt.x);
Vec4V angDelta31_ = V4LoadA(&b31.deltaAngDt.x);
Vec4V linDelta0T0, linDelta0T1, linDelta0T2;
Vec4V linDelta1T0, linDelta1T1, linDelta1T2;
Vec4V angDelta0T0, angDelta0T1, angDelta0T2;
Vec4V angDelta1T0, angDelta1T1, angDelta1T2;
PX_TRANSPOSE_44_34(linDelta00_, linDelta10_, linDelta20_, linDelta30_, linDelta0T0, linDelta0T1, linDelta0T2);
PX_TRANSPOSE_44_34(linDelta01_, linDelta11_, linDelta21_, linDelta31_, linDelta1T0, linDelta1T1, linDelta1T2);
PX_TRANSPOSE_44_34(angDelta00_, angDelta10_, angDelta20_, angDelta30_, angDelta0T0, angDelta0T1, angDelta0T2);
PX_TRANSPOSE_44_34(angDelta01_, angDelta11_, angDelta21_, angDelta31_, angDelta1T0, angDelta1T1, angDelta1T2);
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
Vec4V vMax = V4Splat(FMax());
SolverContactHeaderStepBlock* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr);
const Vec4V invMassA = hdr->invMass0D0;
const Vec4V invMassB = hdr->invMass1D1;
const Vec4V sumInvMass = V4Add(invMassA, invMassB);
Vec4V linDeltaX = V4Sub(linDelta0T0, linDelta1T0);
Vec4V linDeltaY = V4Sub(linDelta0T1, linDelta1T1);
Vec4V linDeltaZ = V4Sub(linDelta0T2, linDelta1T2);
while (currPtr < last)
{
hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr);
PX_ASSERT(hdr->type == DY_SC_TYPE_BLOCK_RB_CONTACT);
currPtr = reinterpret_cast<PxU8*>(const_cast<SolverContactHeaderStepBlock*>(hdr) + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
const bool hasMaxImpulse = (hdr->flag & SolverContactHeaderStepBlock::eHAS_MAX_IMPULSE) != 0;
Vec4V* appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactPointStepBlock* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStepBlock*>(currPtr);
Vec4V* maxImpulses;
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
PxU32 maxImpulseMask = 0;
if (hasMaxImpulse)
{
maxImpulseMask = 0xFFFFFFFF;
maxImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V) * numNormalConstr;
}
else
{
maxImpulses = &vMax;
}
/*SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if (numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);*/
Vec4V* frictionAppliedForce = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numFrictionConstr;
const SolverContactFrictionStepBlock* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStepBlock*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionStepBlock);
Vec4V accumulatedNormalImpulse = vZero;
const Vec4V angD0 = hdr->angDom0;
const Vec4V angD1 = hdr->angDom1;
const Vec4V _normalT0 = hdr->normalX;
const Vec4V _normalT1 = hdr->normalY;
const Vec4V _normalT2 = hdr->normalZ;
Vec4V contactNormalVel1 = V4Mul(linVel0T0, _normalT0);
Vec4V contactNormalVel3 = V4Mul(linVel1T0, _normalT0);
contactNormalVel1 = V4MulAdd(linVel0T1, _normalT1, contactNormalVel1);
contactNormalVel3 = V4MulAdd(linVel1T1, _normalT1, contactNormalVel3);
contactNormalVel1 = V4MulAdd(linVel0T2, _normalT2, contactNormalVel1);
contactNormalVel3 = V4MulAdd(linVel1T2, _normalT2, contactNormalVel3);
const Vec4V maxPenBias = hdr->maxPenBias;
Vec4V relVel1 = V4Sub(contactNormalVel1, contactNormalVel3);
Vec4V deltaNormalV = V4Mul(linDeltaX, _normalT0);
deltaNormalV = V4MulAdd(linDeltaY, _normalT1, deltaNormalV);
deltaNormalV = V4MulAdd(linDeltaZ, _normalT2, deltaNormalV);
Vec4V accumDeltaF = vZero;
for (PxU32 i = 0; i<numNormalConstr; i++)
{
const SolverContactPointStepBlock& c = contacts[i];
/*PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;*/
const Vec4V appliedForce = appliedForces[i];
const Vec4V maxImpulse = maxImpulses[i & maxImpulseMask];
Vec4V contactNormalVel2 = V4Mul(c.raXnI[0], angState0T0);
Vec4V contactNormalVel4 = V4Mul(c.rbXnI[0], angState1T0);
contactNormalVel2 = V4MulAdd(c.raXnI[1], angState0T1, contactNormalVel2);
contactNormalVel4 = V4MulAdd(c.rbXnI[1], angState1T1, contactNormalVel4);
contactNormalVel2 = V4MulAdd(c.raXnI[2], angState0T2, contactNormalVel2);
contactNormalVel4 = V4MulAdd(c.rbXnI[2], angState1T2, contactNormalVel4);
const Vec4V normalVel = V4Add(relVel1, V4Sub(contactNormalVel2, contactNormalVel4));
Vec4V angDelta0 = V4Mul(angDelta0T0, c.raXnI[0]);
Vec4V angDelta1 = V4Mul(angDelta1T0, c.rbXnI[0]);
angDelta0 = V4MulAdd(angDelta0T1, c.raXnI[1], angDelta0);
angDelta1 = V4MulAdd(angDelta1T1, c.rbXnI[1], angDelta1);
angDelta0 = V4MulAdd(angDelta0T2, c.raXnI[2], angDelta0);
angDelta1 = V4MulAdd(angDelta1T2, c.rbXnI[2], angDelta1);
const Vec4V deltaAng = V4Sub(angDelta0, angDelta1);
const Vec4V targetVel = c.targetVelocity;
const Vec4V deltaBias = V4Sub(V4Add(deltaNormalV, deltaAng), V4Mul(targetVel, elapsedTime));
//const Vec4V deltaBias = V4Add(deltaNormalV, deltaAng);
const Vec4V biasCoefficient = c.biasCoefficient;
const Vec4V sep = V4Max(minPen, V4Add(c.separation, deltaBias));
const Vec4V bias = V4Min(V4Neg(maxPenBias), V4Mul(biasCoefficient, sep));
const Vec4V velMultiplier = c.velMultiplier;
const Vec4V tVelBias = V4Mul(bias, c.recipResponse);
const Vec4V _deltaF = V4Max(V4Sub(tVelBias, V4Mul(V4Sub(normalVel, targetVel), velMultiplier)), V4Neg(appliedForce));
//Vec4V deltaF = V4NegMulSub(normalVel, c.velMultiplier, c.biasedErr);
const Vec4V newAppliedForce = V4Min(V4Add(appliedForce, _deltaF), maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
accumDeltaF = V4Add(accumDeltaF, deltaF);
const Vec4V angDetaF0 = V4Mul(deltaF, angD0);
const Vec4V angDetaF1 = V4Mul(deltaF, angD1);
relVel1 = V4MulAdd(sumInvMass, deltaF, relVel1);
angState0T0 = V4MulAdd(c.raXnI[0], angDetaF0, angState0T0);
angState1T0 = V4NegMulSub(c.rbXnI[0], angDetaF1, angState1T0);
angState0T1 = V4MulAdd(c.raXnI[1], angDetaF0, angState0T1);
angState1T1 = V4NegMulSub(c.rbXnI[1], angDetaF1, angState1T1);
angState0T2 = V4MulAdd(c.raXnI[2], angDetaF0, angState0T2);
angState1T2 = V4NegMulSub(c.rbXnI[2], angDetaF1, angState1T2);
appliedForces[i] = newAppliedForce;
accumulatedNormalImpulse = V4Add(accumulatedNormalImpulse, newAppliedForce);
}
const Vec4V accumDeltaF_IM0 = V4Mul(accumDeltaF, invMassA);
const Vec4V accumDeltaF_IM1 = V4Mul(accumDeltaF, invMassB);
linVel0T0 = V4MulAdd(_normalT0, accumDeltaF_IM0, linVel0T0);
linVel1T0 = V4NegMulSub(_normalT0, accumDeltaF_IM1, linVel1T0);
linVel0T1 = V4MulAdd(_normalT1, accumDeltaF_IM0, linVel0T1);
linVel1T1 = V4NegMulSub(_normalT1, accumDeltaF_IM1, linVel1T1);
linVel0T2 = V4MulAdd(_normalT2, accumDeltaF_IM0, linVel0T2);
linVel1T2 = V4NegMulSub(_normalT2, accumDeltaF_IM1, linVel1T2);
if (doFriction && numFrictionConstr)
{
const Vec4V staticFric = hdr->staticFriction;
const Vec4V dynamicFric = hdr->dynamicFriction;
const Vec4V maxFrictionImpulse = V4Add(V4Mul(staticFric, accumulatedNormalImpulse), V4Load(1e-5f));
const Vec4V maxDynFrictionImpulse = V4Mul(dynamicFric, accumulatedNormalImpulse);
BoolV broken = BFFFF();
for (PxU32 i = 0; i<numFrictionConstr; i+=2)
{
const SolverContactFrictionStepBlock& f0 = frictions[i];
const SolverContactFrictionStepBlock& f1 = frictions[i+1];
/*PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;*/
const Vec4V appliedForce0 = frictionAppliedForce[i];
const Vec4V appliedForce1 = frictionAppliedForce[i+1];
const Vec4V normalT00 = f0.normal[0];
const Vec4V normalT10 = f0.normal[1];
const Vec4V normalT20 = f0.normal[2];
const Vec4V normalT01 = f1.normal[0];
const Vec4V normalT11 = f1.normal[1];
const Vec4V normalT21 = f1.normal[2];
Vec4V normalVel10 = V4Mul(linVel0T0, normalT00);
Vec4V normalVel20 = V4Mul(f0.raXnI[0], angState0T0);
Vec4V normalVel30 = V4Mul(linVel1T0, normalT00);
Vec4V normalVel40 = V4Mul(f0.rbXnI[0], angState1T0);
Vec4V normalVel11 = V4Mul(linVel0T0, normalT01);
Vec4V normalVel21 = V4Mul(f1.raXnI[0], angState0T0);
Vec4V normalVel31 = V4Mul(linVel1T0, normalT01);
Vec4V normalVel41 = V4Mul(f1.rbXnI[0], angState1T0);
normalVel10 = V4MulAdd(linVel0T1, normalT10, normalVel10);
normalVel20 = V4MulAdd(f0.raXnI[1], angState0T1, normalVel20);
normalVel30 = V4MulAdd(linVel1T1, normalT10, normalVel30);
normalVel40 = V4MulAdd(f0.rbXnI[1], angState1T1, normalVel40);
normalVel11 = V4MulAdd(linVel0T1, normalT11, normalVel11);
normalVel21 = V4MulAdd(f1.raXnI[1], angState0T1, normalVel21);
normalVel31 = V4MulAdd(linVel1T1, normalT11, normalVel31);
normalVel41 = V4MulAdd(f1.rbXnI[1], angState1T1, normalVel41);
normalVel10 = V4MulAdd(linVel0T2, normalT20, normalVel10);
normalVel20 = V4MulAdd(f0.raXnI[2], angState0T2, normalVel20);
normalVel30 = V4MulAdd(linVel1T2, normalT20, normalVel30);
normalVel40 = V4MulAdd(f0.rbXnI[2], angState1T2, normalVel40);
normalVel11 = V4MulAdd(linVel0T2, normalT21, normalVel11);
normalVel21 = V4MulAdd(f1.raXnI[2], angState0T2, normalVel21);
normalVel31 = V4MulAdd(linVel1T2, normalT21, normalVel31);
normalVel41 = V4MulAdd(f1.rbXnI[2], angState1T2, normalVel41);
const Vec4V normalVel0_tmp1 = V4Add(normalVel10, normalVel20);
const Vec4V normalVel0_tmp2 = V4Add(normalVel30, normalVel40);
const Vec4V normalVel0 = V4Sub(normalVel0_tmp1, normalVel0_tmp2);
const Vec4V normalVel1_tmp1 = V4Add(normalVel11, normalVel21);
const Vec4V normalVel1_tmp2 = V4Add(normalVel31, normalVel41);
const Vec4V normalVel1 = V4Sub(normalVel1_tmp1, normalVel1_tmp2);
Vec4V deltaV0 = V4Mul(linDeltaX, normalT00);
deltaV0 = V4MulAdd(linDeltaY, normalT10, deltaV0);
deltaV0 = V4MulAdd(linDeltaZ, normalT20, deltaV0);
Vec4V deltaV1 = V4Mul(linDeltaX, normalT01);
deltaV1 = V4MulAdd(linDeltaY, normalT11, deltaV1);
deltaV1 = V4MulAdd(linDeltaZ, normalT21, deltaV1);
Vec4V angDelta00 = V4Mul(angDelta0T0, f0.raXnI[0]);
Vec4V angDelta10 = V4Mul(angDelta1T0, f0.rbXnI[0]);
angDelta00 = V4MulAdd(angDelta0T1, f0.raXnI[1], angDelta00);
angDelta10 = V4MulAdd(angDelta1T1, f0.rbXnI[1], angDelta10);
angDelta00 = V4MulAdd(angDelta0T2, f0.raXnI[2], angDelta00);
angDelta10 = V4MulAdd(angDelta1T2, f0.rbXnI[2], angDelta10);
Vec4V angDelta01 = V4Mul(angDelta0T0, f1.raXnI[0]);
Vec4V angDelta11 = V4Mul(angDelta1T0, f1.rbXnI[0]);
angDelta01 = V4MulAdd(angDelta0T1, f1.raXnI[1], angDelta01);
angDelta11 = V4MulAdd(angDelta1T1, f1.rbXnI[1], angDelta11);
angDelta01 = V4MulAdd(angDelta0T2, f1.raXnI[2], angDelta01);
angDelta11 = V4MulAdd(angDelta1T2, f1.rbXnI[2], angDelta11);
const Vec4V deltaAng0 = V4Sub(angDelta00, angDelta10);
const Vec4V deltaAng1 = V4Sub(angDelta01, angDelta11);
const Vec4V deltaBias0 = V4Sub(V4Add(deltaV0, deltaAng0), V4Mul(f0.targetVel, elapsedTime));
const Vec4V deltaBias1 = V4Sub(V4Add(deltaV1, deltaAng1), V4Mul(f1.targetVel, elapsedTime));
const Vec4V error0 = V4Add(f0.error, deltaBias0);
const Vec4V error1 = V4Add(f1.error, deltaBias1);
const Vec4V bias0 = V4Mul(error0, f0.biasCoefficient);
const Vec4V bias1 = V4Mul(error1, f1.biasCoefficient);
const Vec4V tmp10 = V4NegMulSub(V4Sub(bias0, f0.targetVel), f0.velMultiplier, appliedForce0);
const Vec4V tmp11 = V4NegMulSub(V4Sub(bias1, f1.targetVel), f1.velMultiplier, appliedForce1);
const Vec4V totalImpulse0 = V4NegMulSub(normalVel0, f0.velMultiplier, tmp10);
const Vec4V totalImpulse1 = V4NegMulSub(normalVel1, f1.velMultiplier, tmp11);
const Vec4V totalImpulse = V4Sqrt(V4MulAdd(totalImpulse0, totalImpulse0, V4Mul(totalImpulse1, totalImpulse1)));
const BoolV clamped = V4IsGrtr(totalImpulse, maxFrictionImpulse);
broken = BOr(broken, clamped);
const Vec4V totalClamped = V4Sel(broken, V4Min(totalImpulse, maxDynFrictionImpulse), totalImpulse);
const Vec4V ratio = V4Sel(V4IsGrtr(totalImpulse, vZero), V4Div(totalClamped, totalImpulse), vZero);
const Vec4V newAppliedForce0 = V4Mul(totalImpulse0, ratio);
const Vec4V newAppliedForce1 = V4Mul(totalImpulse1, ratio);
const Vec4V deltaF0 = V4Sub(newAppliedForce0, appliedForce0);
const Vec4V deltaF1 = V4Sub(newAppliedForce1, appliedForce1);
frictionAppliedForce[i] = newAppliedForce0;
frictionAppliedForce[i+1] = newAppliedForce1;
const Vec4V deltaFIM00 = V4Mul(deltaF0, invMassA);
const Vec4V deltaFIM10 = V4Mul(deltaF0, invMassB);
const Vec4V angDetaF00 = V4Mul(deltaF0, angD0);
const Vec4V angDetaF10 = V4Mul(deltaF0, angD1);
const Vec4V deltaFIM01 = V4Mul(deltaF1, invMassA);
const Vec4V deltaFIM11 = V4Mul(deltaF1, invMassB);
const Vec4V angDetaF01 = V4Mul(deltaF1, angD0);
const Vec4V angDetaF11 = V4Mul(deltaF1, angD1);
linVel0T0 = V4MulAdd(normalT00, deltaFIM00, V4MulAdd(normalT01, deltaFIM01, linVel0T0));
linVel1T0 = V4NegMulSub(normalT00, deltaFIM10, V4NegMulSub(normalT01, deltaFIM11, linVel1T0));
angState0T0 = V4MulAdd(f0.raXnI[0], angDetaF00, V4MulAdd(f1.raXnI[0], angDetaF01, angState0T0));
angState1T0 = V4NegMulSub(f0.rbXnI[0], angDetaF10, V4NegMulSub(f1.rbXnI[0], angDetaF11, angState1T0));
linVel0T1 = V4MulAdd(normalT10, deltaFIM00, V4MulAdd(normalT11, deltaFIM01, linVel0T1));
linVel1T1 = V4NegMulSub(normalT10, deltaFIM10, V4NegMulSub(normalT11, deltaFIM11, linVel1T1));
angState0T1 = V4MulAdd(f0.raXnI[1], angDetaF00, V4MulAdd(f1.raXnI[1], angDetaF01, angState0T1));
angState1T1 = V4NegMulSub(f0.rbXnI[1], angDetaF10, V4NegMulSub(f1.rbXnI[1], angDetaF11, angState1T1));
linVel0T2 = V4MulAdd(normalT20, deltaFIM00, V4MulAdd(normalT21, deltaFIM01, linVel0T2));
linVel1T2 = V4NegMulSub(normalT20, deltaFIM10, V4NegMulSub(normalT21, deltaFIM11, linVel1T2));
angState0T2 = V4MulAdd(f0.raXnI[2], angDetaF00, V4MulAdd(f1.raXnI[2], angDetaF01, angState0T2));
angState1T2 = V4NegMulSub(f0.rbXnI[2], angDetaF10, V4NegMulSub(f1.rbXnI[2], angDetaF11, angState1T2));
}
hdr->broken = broken;
}
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularVelocity.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularVelocity.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularVelocity.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularVelocity.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularVelocity.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularVelocity.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularVelocity.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularVelocity.isFinite());
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(angState00, &b00.angularVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(angState10, &b10.angularVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(angState20, &b20.angularVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState30, &b30.angularVelocity.x);
if (desc[0].bodyBDataIndex != 0)
{
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(angState01, &b01.angularVelocity.x);
}
if (desc[1].bodyBDataIndex != 0)
{
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(angState11, &b11.angularVelocity.x);
}
if (desc[2].bodyBDataIndex != 0)
{
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(angState21, &b21.angularVelocity.x);
}
if (desc[3].bodyBDataIndex != 0)
{
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState31, &b31.angularVelocity.x);
}
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularVelocity.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularVelocity.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularVelocity.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularVelocity.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularVelocity.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularVelocity.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularVelocity.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularVelocity.isFinite());
}
static void writeBackContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext* /*cache*/)
{
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxReal* PX_RESTRICT vForceWriteback0 = reinterpret_cast<PxReal*>(desc[0].writeBack);
PxReal* PX_RESTRICT vForceWriteback1 = reinterpret_cast<PxReal*>(desc[1].writeBack);
PxReal* PX_RESTRICT vForceWriteback2 = reinterpret_cast<PxReal*>(desc[2].writeBack);
PxReal* PX_RESTRICT vForceWriteback3 = reinterpret_cast<PxReal*>(desc[3].writeBack);
//const PxU8 type = *desc[0].constraint;
const PxU32 contactSize = sizeof(SolverContactPointStepBlock);
const PxU32 frictionSize = sizeof(SolverContactFrictionStepBlock);
Vec4V normalForce = V4Zero();
//We'll need this.
//const Vec4V vZero = V4Zero();
bool writeBackThresholds[4] = { false, false, false, false };
while ((currPtr < last))
{
SolverContactHeaderStepBlock* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
//SolverContactBatchPointBase4* PX_RESTRICT contacts = (SolverContactBatchPointBase4*)currPtr;
currPtr += (numNormalConstr * contactSize);
const bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
if (hasMaxImpulse)
currPtr += sizeof(Vec4V) * numNormalConstr;
currPtr += sizeof(Vec4V)*numFrictionConstr;
//SolverContactFrictionBase4* PX_RESTRICT frictions = (SolverContactFrictionBase4*)currPtr;
currPtr += (numFrictionConstr * frictionSize);
writeBackThresholds[0] = hdr->flags[0] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[1] = hdr->flags[1] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[2] = hdr->flags[2] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[3] = hdr->flags[3] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
for (PxU32 i = 0; i<numNormalConstr; i++)
{
//contacts = (SolverContactBatchPointBase4*)(((PxU8*)contacts) + contactSize);
const FloatV appliedForce0 = V4GetX(appliedForces[i]);
const FloatV appliedForce1 = V4GetY(appliedForces[i]);
const FloatV appliedForce2 = V4GetZ(appliedForces[i]);
const FloatV appliedForce3 = V4GetW(appliedForces[i]);
normalForce = V4Add(normalForce, appliedForces[i]);
if (vForceWriteback0 && i < hdr->numNormalConstrs[0])
FStore(appliedForce0, vForceWriteback0++);
if (vForceWriteback1 && i < hdr->numNormalConstrs[1])
FStore(appliedForce1, vForceWriteback1++);
if (vForceWriteback2 && i < hdr->numNormalConstrs[2])
FStore(appliedForce2, vForceWriteback2++);
if (vForceWriteback3 && i < hdr->numNormalConstrs[3])
FStore(appliedForce3, vForceWriteback3++);
}
if (numFrictionConstr)
{
PX_ALIGN(16, PxU32 broken[4]);
BStoreA(hdr->broken, broken);
PxU8* frictionCounts = hdr->numNormalConstrs;
for (PxU32 a = 0; a < 4; ++a)
{
if (frictionCounts[a] && broken[a])
*hdr->frictionBrokenWritebackByte[a] = 1; // PT: bad L2 miss here
}
}
}
PX_UNUSED(writeBackThresholds);
#if 0
if (cache)
{
PX_ALIGN(16, PxReal nf[4]);
V4StoreA(normalForce, nf);
Sc::ShapeInteraction** shapeInteractions = reinterpret_cast<SolverContactHeader4*>(desc[0].constraint)->shapeInteraction;
for (PxU32 a = 0; a < 4; ++a)
{
if (writeBackThresholds[a] && desc[a].linkIndexA == PxSolverConstraintDesc::NO_LINK && desc[a].linkIndexB == PxSolverConstraintDesc::NO_LINK &&
nf[a] != 0.f && (bd0[a]->reportThreshold < PX_MAX_REAL || bd1[a]->reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = nf[a];
elt.threshold = PxMin<float>(bd0[a]->reportThreshold, bd1[a]->reportThreshold);
elt.nodeIndexA = bd0[a]->nodeIndex;
elt.nodeIndexB = bd1[a]->nodeIndex;
elt.shapeInteraction = shapeInteractions[a];
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex < cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
}
#endif
}
void solveContact4(DY_TGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(txInertias);
PX_UNUSED(cache);
solveContact4_Block(desc + hdr.startIndex, true, minPenetration, elapsedTime);
}
void writeBackContact4(DY_TGS_WRITEBACK_METHOD_PARAMS)
{
writeBackContact4_Block(desc + hdr.startIndex, cache);
}
static PX_FORCE_INLINE Vec4V V4Dot3(const Vec4V& x0, const Vec4V& y0, const Vec4V& z0, const Vec4V& x1, const Vec4V& y1, const Vec4V& z1)
{
return V4MulAdd(x0, x1, V4MulAdd(y0, y1, V4Mul(z0, z1)));
}
static void solve1DStep4(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxTGSSolverBodyTxInertia* const txInertias, PxReal elapsedTimeF32)
{
PxU8* PX_RESTRICT bPtr = desc->constraint;
if (bPtr == NULL)
return;
const FloatV elapsedTime = FLoad(elapsedTimeF32);
PxTGSSolverBodyVel& b00 = *desc[0].tgsBodyA;
PxTGSSolverBodyVel& b01 = *desc[0].tgsBodyB;
PxTGSSolverBodyVel& b10 = *desc[1].tgsBodyA;
PxTGSSolverBodyVel& b11 = *desc[1].tgsBodyB;
PxTGSSolverBodyVel& b20 = *desc[2].tgsBodyA;
PxTGSSolverBodyVel& b21 = *desc[2].tgsBodyB;
PxTGSSolverBodyVel& b30 = *desc[3].tgsBodyA;
PxTGSSolverBodyVel& b31 = *desc[3].tgsBodyB;
const PxTGSSolverBodyTxInertia& txI00 = txInertias[desc[0].bodyADataIndex];
const PxTGSSolverBodyTxInertia& txI01 = txInertias[desc[0].bodyBDataIndex];
const PxTGSSolverBodyTxInertia& txI10 = txInertias[desc[1].bodyADataIndex];
const PxTGSSolverBodyTxInertia& txI11 = txInertias[desc[1].bodyBDataIndex];
const PxTGSSolverBodyTxInertia& txI20 = txInertias[desc[2].bodyADataIndex];
const PxTGSSolverBodyTxInertia& txI21 = txInertias[desc[2].bodyBDataIndex];
const PxTGSSolverBodyTxInertia& txI30 = txInertias[desc[3].bodyADataIndex];
const PxTGSSolverBodyTxInertia& txI31 = txInertias[desc[3].bodyBDataIndex];
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularVelocity.x);
Vec4V angState01 = V4LoadA(&b01.angularVelocity.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularVelocity.x);
Vec4V angState11 = V4LoadA(&b11.angularVelocity.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularVelocity.x);
Vec4V angState21 = V4LoadA(&b21.angularVelocity.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularVelocity.x);
Vec4V angState31 = V4LoadA(&b31.angularVelocity.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
Vec4V linDelta00 = V4LoadA(&b00.deltaLinDt.x);
Vec4V linDelta01 = V4LoadA(&b01.deltaLinDt.x);
Vec4V angDelta00 = V4LoadA(&b00.deltaAngDt.x);
Vec4V angDelta01 = V4LoadA(&b01.deltaAngDt.x);
Vec4V linDelta10 = V4LoadA(&b10.deltaLinDt.x);
Vec4V linDelta11 = V4LoadA(&b11.deltaLinDt.x);
Vec4V angDelta10 = V4LoadA(&b10.deltaAngDt.x);
Vec4V angDelta11 = V4LoadA(&b11.deltaAngDt.x);
Vec4V linDelta20 = V4LoadA(&b20.deltaLinDt.x);
Vec4V linDelta21 = V4LoadA(&b21.deltaLinDt.x);
Vec4V angDelta20 = V4LoadA(&b20.deltaAngDt.x);
Vec4V angDelta21 = V4LoadA(&b21.deltaAngDt.x);
Vec4V linDelta30 = V4LoadA(&b30.deltaLinDt.x);
Vec4V linDelta31 = V4LoadA(&b31.deltaLinDt.x);
Vec4V angDelta30 = V4LoadA(&b30.deltaAngDt.x);
Vec4V angDelta31 = V4LoadA(&b31.deltaAngDt.x);
Vec4V linDelta0T0, linDelta0T1, linDelta0T2;
Vec4V linDelta1T0, linDelta1T1, linDelta1T2;
Vec4V angDelta0T0, angDelta0T1, angDelta0T2;
Vec4V angDelta1T0, angDelta1T1, angDelta1T2;
PX_TRANSPOSE_44_34(linDelta00, linDelta10, linDelta20, linDelta30, linDelta0T0, linDelta0T1, linDelta0T2);
PX_TRANSPOSE_44_34(linDelta01, linDelta11, linDelta21, linDelta31, linDelta1T0, linDelta1T1, linDelta1T2);
PX_TRANSPOSE_44_34(angDelta00, angDelta10, angDelta20, angDelta30, angDelta0T0, angDelta0T1, angDelta0T2);
PX_TRANSPOSE_44_34(angDelta01, angDelta11, angDelta21, angDelta31, angDelta1T0, angDelta1T1, angDelta1T2);
const SolverConstraint1DHeaderStep4* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep4*>(bPtr);
SolverConstraint1DStep4* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DStep4*>(bPtr + sizeof(SolverConstraint1DHeaderStep4));
Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI00.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI00.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(txI00.sqrtInvInertia.column2));
Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI10.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI10.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(txI10.sqrtInvInertia.column2));
Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI20.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI20.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(txI20.sqrtInvInertia.column2));
Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI30.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI30.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(txI30.sqrtInvInertia.column2));
Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI01.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI01.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(txI01.sqrtInvInertia.column2));
Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI11.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI11.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(txI11.sqrtInvInertia.column2));
Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI21.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI21.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(txI21.sqrtInvInertia.column2));
Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI31.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI31.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(txI31.sqrtInvInertia.column2));
Vec4V invInertia0X0, invInertia0X1, invInertia0X2;
Vec4V invInertia0Y0, invInertia0Y1, invInertia0Y2;
Vec4V invInertia0Z0, invInertia0Z1, invInertia0Z2;
Vec4V invInertia1X0, invInertia1X1, invInertia1X2;
Vec4V invInertia1Y0, invInertia1Y1, invInertia1Y2;
Vec4V invInertia1Z0, invInertia1Z1, invInertia1Z2;
PX_TRANSPOSE_44_34(invInertia00X, invInertia10X, invInertia20X, invInertia30X, invInertia0X0, invInertia0Y0, invInertia0Z0);
PX_TRANSPOSE_44_34(invInertia00Y, invInertia10Y, invInertia20Y, invInertia30Y, invInertia0X1, invInertia0Y1, invInertia0Z1);
PX_TRANSPOSE_44_34(invInertia00Z, invInertia10Z, invInertia20Z, invInertia30Z, invInertia0X2, invInertia0Y2, invInertia0Z2);
PX_TRANSPOSE_44_34(invInertia01X, invInertia11X, invInertia21X, invInertia31X, invInertia1X0, invInertia1Y0, invInertia1Z0);
PX_TRANSPOSE_44_34(invInertia01Y, invInertia11Y, invInertia21Y, invInertia31Y, invInertia1X1, invInertia1Y1, invInertia1Z1);
PX_TRANSPOSE_44_34(invInertia01Z, invInertia11Z, invInertia21Z, invInertia31Z, invInertia1X2, invInertia1Y2, invInertia1Z2);
const Vec4V invInertiaScale0 = header->angD0;
const Vec4V invInertiaScale1 = header->angD1;
//KS - todo - load this a bit quicker...
Vec4V rot00 = V4LoadA(&txI00.deltaBody2World.q.x);
Vec4V rot01 = V4LoadA(&txI01.deltaBody2World.q.x);
Vec4V rot10 = V4LoadA(&txI10.deltaBody2World.q.x);
Vec4V rot11 = V4LoadA(&txI11.deltaBody2World.q.x);
Vec4V rot20 = V4LoadA(&txI20.deltaBody2World.q.x);
Vec4V rot21 = V4LoadA(&txI21.deltaBody2World.q.x);
Vec4V rot30 = V4LoadA(&txI30.deltaBody2World.q.x);
Vec4V rot31 = V4LoadA(&txI31.deltaBody2World.q.x);
Vec4V rot0X, rot0Y, rot0Z, rot0W;
Vec4V rot1X, rot1Y, rot1Z, rot1W;
PX_TRANSPOSE_44(rot00, rot10, rot20, rot30, rot0X, rot0Y, rot0Z, rot0W);
PX_TRANSPOSE_44(rot01, rot11, rot21, rot31, rot1X, rot1Y, rot1Z, rot1W);
Vec4V raX, raY, raZ;
Vec4V rbX, rbY, rbZ;
QuatRotate4(rot0X, rot0Y, rot0Z, rot0W, header->rAWorld[0], header->rAWorld[1], header->rAWorld[2], raX, raY, raZ);
QuatRotate4(rot1X, rot1Y, rot1Z, rot1W, header->rBWorld[0], header->rBWorld[1], header->rBWorld[2], rbX, rbY, rbZ);
const Vec4V raMotionX = V4Sub(V4Add(raX, linDelta0T0), header->rAWorld[0]);
const Vec4V raMotionY = V4Sub(V4Add(raY, linDelta0T1), header->rAWorld[1]);
const Vec4V raMotionZ = V4Sub(V4Add(raZ, linDelta0T2), header->rAWorld[2]);
const Vec4V rbMotionX = V4Sub(V4Add(rbX, linDelta1T0), header->rBWorld[0]);
const Vec4V rbMotionY = V4Sub(V4Add(rbY, linDelta1T1), header->rBWorld[1]);
const Vec4V rbMotionZ = V4Sub(V4Add(rbZ, linDelta1T2), header->rBWorld[2]);
const Vec4V mass0 = header->invMass0D0;
const Vec4V mass1 = header->invMass1D1;
const VecI32V orthoMask = I4Load(DY_SC_FLAG_ORTHO_TARGET);
const VecI32V limitMask = I4Load(DY_SC_FLAG_INEQUALITY);
const Vec4V zero = V4Zero();
const Vec4V one = V4One();
Vec4V error0 = V4Add(header->angOrthoError[0],
V4Sub(V4Dot3(header->angOrthoAxis0X[0], header->angOrthoAxis0Y[0], header->angOrthoAxis0Z[0], angDelta0T0, angDelta0T1, angDelta0T2),
V4Dot3(header->angOrthoAxis1X[0], header->angOrthoAxis1Y[0], header->angOrthoAxis1Z[0], angDelta1T0, angDelta1T1, angDelta1T2)));
Vec4V error1 = V4Add(header->angOrthoError[1],
V4Sub(V4Dot3(header->angOrthoAxis0X[1], header->angOrthoAxis0Y[1], header->angOrthoAxis0Z[1], angDelta0T0, angDelta0T1, angDelta0T2),
V4Dot3(header->angOrthoAxis1X[1], header->angOrthoAxis1Y[1], header->angOrthoAxis1Z[1], angDelta1T0, angDelta1T1, angDelta1T2)));
Vec4V error2 = V4Add(header->angOrthoError[2],
V4Sub(V4Dot3(header->angOrthoAxis0X[2], header->angOrthoAxis0Y[2], header->angOrthoAxis0Z[2], angDelta0T0, angDelta0T1, angDelta0T2),
V4Dot3(header->angOrthoAxis1X[2], header->angOrthoAxis1Y[2], header->angOrthoAxis1Z[2], angDelta1T0, angDelta1T1, angDelta1T2)));
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; ++i, base++)
{
PxPrefetchLine(base + 1);
SolverConstraint1DStep4& c = *base;
const Vec4V cangVel0X = V4Add(c.ang0[0], V4NegMulSub(raZ, c.lin0[1], V4Mul(raY, c.lin0[2])));
const Vec4V cangVel0Y = V4Add(c.ang0[1], V4NegMulSub(raX, c.lin0[2], V4Mul(raZ, c.lin0[0])));
const Vec4V cangVel0Z = V4Add(c.ang0[2], V4NegMulSub(raY, c.lin0[0], V4Mul(raX, c.lin0[1])));
const Vec4V cangVel1X = V4Add(c.ang1[0], V4NegMulSub(rbZ, c.lin1[1], V4Mul(rbY, c.lin1[2])));
const Vec4V cangVel1Y = V4Add(c.ang1[1], V4NegMulSub(rbX, c.lin1[2], V4Mul(rbZ, c.lin1[0])));
const Vec4V cangVel1Z = V4Add(c.ang1[2], V4NegMulSub(rbY, c.lin1[0], V4Mul(rbX, c.lin1[1])));
const VecI32V flags = I4LoadA(reinterpret_cast<PxI32*>(c.flags));
const BoolV useOrtho = VecI32V_IsEq(VecI32V_And(flags, orthoMask), orthoMask);
const Vec4V angOrthoCoefficient = V4Sel(useOrtho, one, zero);
Vec4V delAngVel0X = V4Mul(invInertia0X0, cangVel0X);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, cangVel0X);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, cangVel0X);
delAngVel0X = V4MulAdd(invInertia0Y0, cangVel0Y, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, cangVel0Y, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, cangVel0Y, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, cangVel0Z, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, cangVel0Z, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, cangVel0Z, delAngVel0Z);
Vec4V delAngVel1X = V4Mul(invInertia1X0, cangVel1X);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, cangVel1X);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, cangVel1X);
delAngVel1X = V4MulAdd(invInertia1Y0, cangVel1Y, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, cangVel1Y, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, cangVel1Y, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, cangVel1Z, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, cangVel1Z, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, cangVel1Z, delAngVel1Z);
Vec4V err = c.error;
{
const Vec4V proj0 = V4Mul(V4MulAdd(header->angOrthoAxis0X[0], delAngVel0X, V4MulAdd(header->angOrthoAxis0Y[0], delAngVel0Y,
V4MulAdd(header->angOrthoAxis0Z[0], delAngVel0Z, V4MulAdd(header->angOrthoAxis1X[0], delAngVel1X,
V4MulAdd(header->angOrthoAxis1Y[0], delAngVel1Y, V4Mul(header->angOrthoAxis1Z[0], delAngVel1Z)))))), header->angOrthoRecipResponse[0]);
const Vec4V proj1 = V4Mul(V4MulAdd(header->angOrthoAxis0X[1], delAngVel0X, V4MulAdd(header->angOrthoAxis0Y[1], delAngVel0Y,
V4MulAdd(header->angOrthoAxis0Z[1], delAngVel0Z, V4MulAdd(header->angOrthoAxis1X[1], delAngVel1X,
V4MulAdd(header->angOrthoAxis1Y[1], delAngVel1Y, V4Mul(header->angOrthoAxis1Z[1], delAngVel1Z)))))), header->angOrthoRecipResponse[1]);
const Vec4V proj2 = V4Mul(V4MulAdd(header->angOrthoAxis0X[2], delAngVel0X, V4MulAdd(header->angOrthoAxis0Y[2], delAngVel0Y,
V4MulAdd(header->angOrthoAxis0Z[2], delAngVel0Z, V4MulAdd(header->angOrthoAxis1X[2], delAngVel1X,
V4MulAdd(header->angOrthoAxis1Y[2], delAngVel1Y, V4Mul(header->angOrthoAxis1Z[2], delAngVel1Z)))))), header->angOrthoRecipResponse[2]);
const Vec4V delta0X = V4MulAdd(header->angOrthoAxis0X[0], proj0, V4MulAdd(header->angOrthoAxis0X[1], proj1, V4Mul(header->angOrthoAxis0X[2], proj2)));
const Vec4V delta0Y = V4MulAdd(header->angOrthoAxis0Y[0], proj0, V4MulAdd(header->angOrthoAxis0Y[1], proj1, V4Mul(header->angOrthoAxis0Y[2], proj2)));
const Vec4V delta0Z = V4MulAdd(header->angOrthoAxis0Z[0], proj0, V4MulAdd(header->angOrthoAxis0Z[1], proj1, V4Mul(header->angOrthoAxis0Z[2], proj2)));
const Vec4V delta1X = V4MulAdd(header->angOrthoAxis1X[0], proj0, V4MulAdd(header->angOrthoAxis1X[1], proj1, V4Mul(header->angOrthoAxis1X[2], proj2)));
const Vec4V delta1Y = V4MulAdd(header->angOrthoAxis1Y[0], proj0, V4MulAdd(header->angOrthoAxis1Y[1], proj1, V4Mul(header->angOrthoAxis1Y[2], proj2)));
const Vec4V delta1Z = V4MulAdd(header->angOrthoAxis1Z[0], proj0, V4MulAdd(header->angOrthoAxis1Z[1], proj1, V4Mul(header->angOrthoAxis1Z[2], proj2)));
delAngVel0X = V4NegMulSub(delta0X, angOrthoCoefficient, delAngVel0X);
delAngVel0Y = V4NegMulSub(delta0Y, angOrthoCoefficient, delAngVel0Y);
delAngVel0Z = V4NegMulSub(delta0Z, angOrthoCoefficient, delAngVel0Z);
delAngVel1X = V4NegMulSub(delta1X, angOrthoCoefficient, delAngVel1X);
delAngVel1Y = V4NegMulSub(delta1Y, angOrthoCoefficient, delAngVel1Y);
delAngVel1Z = V4NegMulSub(delta1Z, angOrthoCoefficient, delAngVel1Z);
err = V4Sub(err, V4Mul(V4MulAdd(error0, proj0, V4MulAdd(error1, proj1, V4Mul(error2, proj2))), angOrthoCoefficient));
}
Vec4V ang0IX = V4Mul(invInertia0X0, delAngVel0X);
Vec4V ang0IY = V4Mul(invInertia0X1, delAngVel0X);
Vec4V ang0IZ = V4Mul(invInertia0X2, delAngVel0X);
ang0IX = V4MulAdd(invInertia0Y0, delAngVel0Y, ang0IX);
ang0IY = V4MulAdd(invInertia0Y1, delAngVel0Y, ang0IY);
ang0IZ = V4MulAdd(invInertia0Y2, delAngVel0Y, ang0IZ);
ang0IX = V4MulAdd(invInertia0Z0, delAngVel0Z, ang0IX);
ang0IY = V4MulAdd(invInertia0Z1, delAngVel0Z, ang0IY);
ang0IZ = V4MulAdd(invInertia0Z2, delAngVel0Z, ang0IZ);
Vec4V ang1IX = V4Mul(invInertia1X0, delAngVel1X);
Vec4V ang1IY = V4Mul(invInertia1X1, delAngVel1X);
Vec4V ang1IZ = V4Mul(invInertia1X2, delAngVel1X);
ang1IX = V4MulAdd(invInertia1Y0, delAngVel1Y, ang1IX);
ang1IY = V4MulAdd(invInertia1Y1, delAngVel1Y, ang1IY);
ang1IZ = V4MulAdd(invInertia1Y2, delAngVel1Y, ang1IZ);
ang1IX = V4MulAdd(invInertia1Z0, delAngVel1Z, ang1IX);
ang1IY = V4MulAdd(invInertia1Z1, delAngVel1Z, ang1IY);
ang1IZ = V4MulAdd(invInertia1Z2, delAngVel1Z, ang1IZ);
const Vec4V clinVel0X = c.lin0[0];
const Vec4V clinVel0Y = c.lin0[1];
const Vec4V clinVel0Z = c.lin0[2];
const Vec4V clinVel1X = c.lin1[0];
const Vec4V clinVel1Y = c.lin1[1];
const Vec4V clinVel1Z = c.lin1[2];
const Vec4V clinVel0X_ = c.lin0[0];
const Vec4V clinVel0Y_ = c.lin0[1];
const Vec4V clinVel0Z_ = c.lin0[2];
const Vec4V clinVel1X_ = c.lin1[0];
const Vec4V clinVel1Y_ = c.lin1[1];
const Vec4V clinVel1Z_ = c.lin1[2];
//KS - compute raXnI and effective mass. Unfortunately, the joints are noticeably less stable if we don't do this each
//iteration. It's skippable. If we do that, there's no need for the invInertiaTensors
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0X, delAngVel0X, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0Z, delAngVel0Z)));
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1X, delAngVel1X, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1Z, delAngVel1Z)));
const Vec4V dotRbXnAngDelta0 = V4MulAdd(delAngVel0X, angDelta0T0, V4MulAdd(delAngVel0Y, angDelta0T1, V4Mul(delAngVel0Z, angDelta0T2)));
const Vec4V dotRbXnAngDelta1 = V4MulAdd(delAngVel1X, angDelta1T0, V4MulAdd(delAngVel1Y, angDelta1T1, V4Mul(delAngVel1Z, angDelta1T2)));
const Vec4V dotRaMotion = V4MulAdd(clinVel0X_, raMotionX, V4MulAdd(clinVel0Y_, raMotionY, V4Mul(clinVel0Z_, raMotionZ)));
const Vec4V dotRbMotion = V4MulAdd(clinVel1X_, rbMotionX, V4MulAdd(clinVel1Y_, rbMotionY, V4Mul(clinVel1Z_, rbMotionZ)));
const Vec4V deltaAng = V4Mul(c.angularErrorScale, V4Sub(dotRbXnAngDelta0, dotRbXnAngDelta1));
const Vec4V errorChange = V4NegScaleSub(c.velTarget, elapsedTime, V4Add(V4Sub(dotRaMotion, dotRbMotion), deltaAng));
const Vec4V dotClinVel0 = V4MulAdd(clinVel0X, clinVel0X, V4MulAdd(clinVel0Y, clinVel0Y, V4Mul(clinVel0Z, clinVel0Z)));
const Vec4V dotClinVel1 = V4MulAdd(clinVel1X, clinVel1X, V4MulAdd(clinVel1Y, clinVel1Y, V4Mul(clinVel1Z, clinVel1Z)));
const Vec4V resp0 = V4MulAdd(mass0, dotClinVel0, V4Mul(invInertiaScale0, dotDelAngVel0));
const Vec4V resp1 = V4MulAdd(mass1, dotClinVel1, V4Mul(invInertiaScale1, dotDelAngVel1));
const Vec4V response = V4Add(resp0, resp1);
const Vec4V recipResponse = V4Sel(V4IsGrtr(response, V4Zero()), V4Recip(response), V4Zero());
const Vec4V vMul = V4Mul(recipResponse, c.velMultiplier);
const BoolV isLimitConstraint = VecI32V_IsEq(VecI32V_And(flags, limitMask), limitMask);
const Vec4V minBias = V4Sel(isLimitConstraint, V4Neg(Vec4V_From_FloatV(FMax())), V4Neg(c.maxBias));
const Vec4V unclampedBias = V4MulAdd(errorChange, c.biasScale, err);
const Vec4V bias = V4Clamp(unclampedBias, minBias, c.maxBias);
const Vec4V constant = V4Mul(recipResponse, V4Add(bias, c.velTarget));
const Vec4V normalVel0 = V4MulAdd(clinVel0X_, linVel0T0, V4MulAdd(clinVel0Y_, linVel0T1, V4Mul(clinVel0Z_, linVel0T2)));
const Vec4V normalVel1 = V4MulAdd(clinVel1X_, linVel1T0, V4MulAdd(clinVel1Y_, linVel1T1, V4Mul(clinVel1Z_, linVel1T2)));
const Vec4V angVel0 = V4MulAdd(delAngVel0X, angState0T0, V4MulAdd(delAngVel0Y, angState0T1, V4Mul(delAngVel0Z, angState0T2)));
const Vec4V angVel1 = V4MulAdd(delAngVel1X, angState1T0, V4MulAdd(delAngVel1Y, angState1T1, V4Mul(delAngVel1Z, angState1T2)));
const Vec4V normalVel = V4Add(V4Sub(normalVel0, normalVel1), V4Sub(angVel0, angVel1));
const Vec4V unclampedForce = V4Add(c.appliedForce, V4MulAdd(vMul, normalVel, constant));
const Vec4V clampedForce = V4Clamp(unclampedForce, c.minImpulse, c.maxImpulse);
const Vec4V deltaF = V4Sub(clampedForce, c.appliedForce);
c.appliedForce = clampedForce;
const Vec4V deltaFIM0 = V4Mul(deltaF, mass0);
const Vec4V deltaFIM1 = V4Mul(deltaF, mass1);
const Vec4V angDetaF0 = V4Mul(deltaF, invInertiaScale0);
const Vec4V angDetaF1 = V4Mul(deltaF, invInertiaScale1);
linVel0T0 = V4MulAdd(clinVel0X_, deltaFIM0, linVel0T0);
linVel1T0 = V4NegMulSub(clinVel1X_, deltaFIM1, linVel1T0);
angState0T0 = V4MulAdd(delAngVel0X, angDetaF0, angState0T0);
angState1T0 = V4NegMulSub(delAngVel1X, angDetaF1, angState1T0);
linVel0T1 = V4MulAdd(clinVel0Y_, deltaFIM0, linVel0T1);
linVel1T1 = V4NegMulSub(clinVel1Y_, deltaFIM1, linVel1T1);
angState0T1 = V4MulAdd(delAngVel0Y, angDetaF0, angState0T1);
angState1T1 = V4NegMulSub(delAngVel1Y, angDetaF1, angState1T1);
linVel0T2 = V4MulAdd(clinVel0Z_, deltaFIM0, linVel0T2);
linVel1T2 = V4NegMulSub(clinVel1Z_, deltaFIM1, linVel1T2);
angState0T2 = V4MulAdd(delAngVel0Z, angDetaF0, angState0T2);
angState1T2 = V4NegMulSub(delAngVel1Z, angDetaF1, angState1T2);
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularVelocity.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularVelocity.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularVelocity.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularVelocity.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularVelocity.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularVelocity.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularVelocity.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularVelocity.isFinite());
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(angState00, &b00.angularVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(angState10, &b10.angularVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(angState20, &b20.angularVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState30, &b30.angularVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(angState01, &b01.angularVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(angState11, &b11.angularVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(angState21, &b21.angularVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState31, &b31.angularVelocity.x);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularVelocity.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularVelocity.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularVelocity.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularVelocity.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularVelocity.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularVelocity.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularVelocity.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularVelocity.isFinite());
}
void solve1D4(DY_TGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(minPenetration);
PX_UNUSED(cache);
solve1DStep4(desc + hdr.startIndex, txInertias, elapsedTime);
}
void writeBack1D4(DY_TGS_WRITEBACK_METHOD_PARAMS)
{
PX_UNUSED(cache);
ConstraintWriteback* writeback0 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex].writeBack);
ConstraintWriteback* writeback1 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex + 1].writeBack);
ConstraintWriteback* writeback2 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex + 2].writeBack);
ConstraintWriteback* writeback3 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex + 3].writeBack);
if (writeback0 || writeback1 || writeback2 || writeback3)
{
SolverConstraint1DHeaderStep4* header = reinterpret_cast<SolverConstraint1DHeaderStep4*>(desc[hdr.startIndex].constraint);
SolverConstraint1DStep4* base = reinterpret_cast<SolverConstraint1DStep4*>(desc[hdr.startIndex].constraint + sizeof(SolverConstraint1DHeaderStep4));
const Vec4V zero = V4Zero();
Vec4V linX(zero), linY(zero), linZ(zero);
Vec4V angX(zero), angY(zero), angZ(zero);
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; i++)
{
const SolverConstraint1DStep4* c = base;
//Load in flags
const VecI32V flags = I4LoadU(reinterpret_cast<const PxI32*>(&c->flags[0]));
//Work out masks
const VecI32V mask = I4Load(DY_SC_FLAG_OUTPUT_FORCE);
const VecI32V masked = VecI32V_And(flags, mask);
const BoolV isEq = VecI32V_IsEq(masked, mask);
const Vec4V appliedForce = V4Sel(isEq, c->appliedForce, zero);
linX = V4MulAdd(c->lin0[0], appliedForce, linX);
linY = V4MulAdd(c->lin0[1], appliedForce, linY);
linZ = V4MulAdd(c->lin0[2], appliedForce, linZ);
angX = V4MulAdd(c->ang0[0], appliedForce, angX);
angY = V4MulAdd(c->ang0[1], appliedForce, angY);
angZ = V4MulAdd(c->ang0[2], appliedForce, angZ);
base++;
}
//We need to do the cross product now
angX = V4Sub(angX, V4NegMulSub(header->body0WorkOffset[0], linY, V4Mul(header->body0WorkOffset[1], linZ)));
angY = V4Sub(angY, V4NegMulSub(header->body0WorkOffset[1], linZ, V4Mul(header->body0WorkOffset[2], linX)));
angZ = V4Sub(angZ, V4NegMulSub(header->body0WorkOffset[2], linX, V4Mul(header->body0WorkOffset[0], linY)));
const Vec4V linLenSq = V4MulAdd(linZ, linZ, V4MulAdd(linY, linY, V4Mul(linX, linX)));
const Vec4V angLenSq = V4MulAdd(angZ, angZ, V4MulAdd(angY, angY, V4Mul(angX, angX)));
const Vec4V linLen = V4Sqrt(linLenSq);
const Vec4V angLen = V4Sqrt(angLenSq);
const BoolV broken = BOr(V4IsGrtr(linLen, header->linBreakImpulse), V4IsGrtr(angLen, header->angBreakImpulse));
PX_ALIGN(16, PxU32 iBroken[4]);
BStoreA(broken, iBroken);
Vec4V lin0, lin1, lin2, lin3;
Vec4V ang0, ang1, ang2, ang3;
PX_TRANSPOSE_34_44(linX, linY, linZ, lin0, lin1, lin2, lin3);
PX_TRANSPOSE_34_44(angX, angY, angZ, ang0, ang1, ang2, ang3);
if (writeback0)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin0), writeback0->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang0), writeback0->angularImpulse);
writeback0->broken = header->breakable[0] ? PxU32(iBroken[0] != 0) : 0;
}
if (writeback1)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin1), writeback1->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang1), writeback1->angularImpulse);
writeback1->broken = header->breakable[1] ? PxU32(iBroken[1] != 0) : 0;
}
if (writeback2)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin2), writeback2->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang2), writeback2->angularImpulse);
writeback2->broken = header->breakable[2] ? PxU32(iBroken[2] != 0) : 0;
}
if (writeback3)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin3), writeback3->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang3), writeback3->angularImpulse);
writeback3->broken = header->breakable[3] ? PxU32(iBroken[3] != 0) : 0;
}
}
}
static void concludeContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc)
{
PX_UNUSED(desc);
//const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
////hopefully pointer aliasing doesn't bite.
//PxU8* PX_RESTRICT currPtr = desc[0].constraint;
//const Vec4V zero = V4Zero();
////const PxU8 type = *desc[0].constraint;
//const PxU32 contactSize = sizeof(SolverContactPointStepBlock);
//const PxU32 frictionSize = sizeof(SolverContactFrictionStepBlock);
//while ((currPtr < last))
//{
// SolverContactHeaderStepBlock* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr);
// currPtr = reinterpret_cast<PxU8*>(hdr + 1);
// const PxU32 numNormalConstr = hdr->numNormalConstr;
// const PxU32 numFrictionConstr = hdr->numFrictionConstr;
// //Applied forces
// currPtr += sizeof(Vec4V)*numNormalConstr;
// //SolverContactPointStepBlock* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStepBlock*>(currPtr);
// currPtr += (numNormalConstr * contactSize);
// bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
// if (hasMaxImpulse)
// currPtr += sizeof(Vec4V) * numNormalConstr;
// currPtr += sizeof(Vec4V)*numFrictionConstr;
// SolverContactFrictionStepBlock* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStepBlock*>(currPtr);
// currPtr += (numFrictionConstr * frictionSize);
// /*for (PxU32 i = 0; i<numNormalConstr; i++)
// {
// contacts[i].biasCoefficient = V4Sel(V4IsGrtr(contacts[i].separation, zero), contacts[i].biasCoefficient, zero);
// }*/
// for (PxU32 i = 0; i<numFrictionConstr; i++)
// {
// frictions[i].biasCoefficient = zero;
// }
//}
}
static void conclude1DStep4(const PxSolverConstraintDesc* PX_RESTRICT desc)
{
PxU8* PX_RESTRICT bPtr = desc->constraint;
if (bPtr == NULL)
return;
const SolverConstraint1DHeaderStep4* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep4*>(bPtr);
SolverConstraint1DStep4* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DStep4*>(bPtr + sizeof(SolverConstraint1DHeaderStep4));
const VecI32V mask = I4Load(DY_SC_FLAG_KEEP_BIAS);
const Vec4V zero = V4Zero();
const PxU32 count = header->count;
for (PxU32 i = 0; i<count; ++i, base++)
{
PxPrefetchLine(base + 1);
SolverConstraint1DStep4& c = *base;
const VecI32V flags = I4LoadA(reinterpret_cast<PxI32*>(c.flags));
const BoolV keepBias = VecI32V_IsEq(VecI32V_And(flags, mask), mask);
c.biasScale = V4Sel(keepBias, c.biasScale, zero);
c.error = V4Sel(keepBias, c.error, zero);
}
}
void solveConcludeContact4(DY_TGS_CONCLUDE_METHOD_PARAMS)
{
PX_UNUSED(txInertias);
PX_UNUSED(cache);
solveContact4_Block(desc + hdr.startIndex, true, -PX_MAX_F32, elapsedTime);
concludeContact4_Block(desc + hdr.startIndex);
}
void solveConclude1D4(DY_TGS_CONCLUDE_METHOD_PARAMS)
{
PX_UNUSED(cache);
solve1DStep4(desc + hdr.startIndex, txInertias, elapsedTime);
conclude1DStep4(desc + hdr.startIndex);
}
}
}
| 156,992 | C++ | 43.024958 | 185 | 0.743751 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContactPF4.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONTACT_PF_4_H
#define DY_SOLVER_CONTACT_PF_4_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
using namespace aos;
namespace Sc
{
class ShapeInteraction;
}
namespace Dy
{
struct SolverContactCoulombHeader4
{
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 numNormalConstr;
PxU16 frictionOffset;
PxU8 numNormalConstr0, numNormalConstr1, numNormalConstr2, numNormalConstr3;
PxU8 flags[4];
PxU32 pad; //16
Vec4V restitution; //32
Vec4V normalX; //48
Vec4V normalY; //64
Vec4V normalZ; //80
Vec4V invMassADom; //96
Vec4V invMassBDom; //112
Vec4V angD0; //128
Vec4V angD1; //144
Sc::ShapeInteraction* shapeInteraction[4]; //160 or 176
};
#if !PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactCoulombHeader4) == 160);
#else
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactCoulombHeader4) == 176);
#endif
struct SolverContact4Base
{
Vec4V raXnX;
Vec4V raXnY;
Vec4V raXnZ;
Vec4V appliedForce;
Vec4V velMultiplier;
Vec4V targetVelocity;
Vec4V scaledBias;
Vec4V maxImpulse;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContact4Base) == 128);
struct SolverContact4Dynamic : public SolverContact4Base
{
Vec4V rbXnX;
Vec4V rbXnY;
Vec4V rbXnZ;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContact4Dynamic) == 176);
struct SolverFrictionHeader4
{
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 numNormalConstr;
PxU8 numFrictionConstr;
PxU8 numNormalConstr0;
PxU8 numNormalConstr1;
PxU8 numNormalConstr2;
PxU8 numNormalConstr3;
PxU8 numFrictionConstr0;
PxU8 numFrictionConstr1;
PxU8 numFrictionConstr2;
PxU8 numFrictionConstr3;
PxU8 pad0;
PxU32 frictionPerContact;
Vec4V staticFriction;
Vec4V invMassADom;
Vec4V invMassBDom;
Vec4V angD0;
Vec4V angD1;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverFrictionHeader4) == 96);
struct SolverFriction4Base
{
Vec4V normalX;
Vec4V normalY;
Vec4V normalZ;
Vec4V raXnX;
Vec4V raXnY;
Vec4V raXnZ;
Vec4V appliedForce;
Vec4V velMultiplier;
Vec4V targetVelocity;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverFriction4Base) == 144);
struct SolverFriction4Dynamic : public SolverFriction4Base
{
Vec4V rbXnX;
Vec4V rbXnY;
Vec4V rbXnZ;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverFriction4Dynamic) == 192);
}
}
#endif
| 4,133 | C | 26.019608 | 93 | 0.760707 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyThresholdTable.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "foundation/PxHash.h"
#include "foundation/PxAllocator.h"
#include "DyThresholdTable.h"
#include "foundation/PxUtilities.h"
namespace physx
{
namespace Dy
{
bool ThresholdTable::check(const ThresholdStream& stream, const PxU32 nodeIndexA, const PxU32 nodeIndexB, PxReal dt)
{
PxU32* PX_RESTRICT hashes = mHash;
PxU32* PX_RESTRICT nextIndices = mNexts;
Pair* PX_RESTRICT pairs = mPairs;
/*const PxsRigidBody* b0 = PxMin(body0, body1);
const PxsRigidBody* b1 = PxMax(body0, body1);*/
const PxU32 nA = PxMin(nodeIndexA, nodeIndexB);
const PxU32 nB = PxMax(nodeIndexA, nodeIndexB);
PxU32 hashKey = computeHashKey(nodeIndexA, nodeIndexB, mHashSize);
PxU32 pairIndex = hashes[hashKey];
while(NO_INDEX != pairIndex)
{
Pair& pair = pairs[pairIndex];
const PxU32 thresholdStreamIndex = pair.thresholdStreamIndex;
PX_ASSERT(thresholdStreamIndex < stream.size());
const ThresholdStreamElement& otherElement = stream[thresholdStreamIndex];
if(otherElement.nodeIndexA.index()==nA && otherElement.nodeIndexB.index()==nB)
return (pair.accumulatedForce > (otherElement.threshold * dt));
pairIndex = nextIndices[pairIndex];
}
return false;
}
}
}
| 2,951 | C++ | 42.411764 | 118 | 0.749238 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep4PF.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
#include "DySolverContactPF4.h"
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
using namespace physx::Gu;
using namespace physx::aos;
namespace physx
{
namespace Dy
{
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb(
PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
PxFrictionType::Enum frictionType);
static bool setupFinalizeSolverConstraintsCoulomb4(PxSolverContactDesc* PX_RESTRICT descs, PxU8* PX_RESTRICT workspace,
const PxReal invDtF32, PxReal bounceThresholdF32, CorrelationBuffer& c, const PxU32 numFrictionPerPoint,
const PxU32 numContactPoints4, const PxU32 /*solverConstraintByteSize*/,
const aos::Vec4VArg invMassScale0, const aos::Vec4VArg invInertiaScale0,
const aos::Vec4VArg invMassScale1, const aos::Vec4VArg invInertiaScale1)
{
//KS - final step. Create the constraints in the place we pre-allocated...
const Vec4V ccdMaxSeparation = aos::V4LoadXYZW(descs[0].maxCCDSeparation, descs[1].maxCCDSeparation, descs[2].maxCCDSeparation, descs[3].maxCCDSeparation);
const Vec4V solverOffsetSlop = aos::V4LoadXYZW(descs[0].offsetSlop, descs[1].offsetSlop, descs[2].offsetSlop, descs[3].offsetSlop);
const Vec4V zero = V4Zero();
const BoolV bTrue = BTTTT();
PxU8 flags[4] = { PxU8(descs[0].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[1].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[2].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[3].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0) };
//The block is dynamic if **any** of the constraints have a non-static body B. This allows us to batch static and non-static constraints but we only get a memory/perf
//saving if all 4 are static. This simplifies the constraint partitioning such that it only needs to care about separating contacts and 1D constraints (which it already does)
const bool isDynamic = ((descs[0].bodyState1 | descs[1].bodyState1 | descs[2].bodyState1 | descs[3].bodyState1) & PxSolverContactDesc::eDYNAMIC_BODY) != 0;
const PxU32 constraintSize = isDynamic ? sizeof(SolverContact4Dynamic) : sizeof(SolverContact4Base);
const PxU32 frictionSize = isDynamic ? sizeof(SolverFriction4Dynamic) : sizeof(SolverFriction4Base);
PxU8* PX_RESTRICT ptr = workspace;
const Vec4V dom0 = invMassScale0;
const Vec4V dom1 = invMassScale1;
const Vec4V angDom0 = invInertiaScale0;
const Vec4V angDom1 = invInertiaScale1;
const Vec4V maxPenBias = V4Max(V4Merge(FLoad(descs[0].data0->penBiasClamp), FLoad(descs[1].data0->penBiasClamp),
FLoad(descs[2].data0->penBiasClamp), FLoad(descs[3].data0->penBiasClamp)),
V4Merge(FLoad(descs[0].data1->penBiasClamp), FLoad(descs[1].data1->penBiasClamp),
FLoad(descs[2].data1->penBiasClamp), FLoad(descs[3].data1->penBiasClamp)));
const Vec4V restDistance = V4Merge(FLoad(descs[0].restDistance), FLoad(descs[1].restDistance), FLoad(descs[2].restDistance),
FLoad(descs[3].restDistance));
//load up velocities
Vec4V linVel00 = V4LoadA(&descs[0].data0->linearVelocity.x);
Vec4V linVel10 = V4LoadA(&descs[1].data0->linearVelocity.x);
Vec4V linVel20 = V4LoadA(&descs[2].data0->linearVelocity.x);
Vec4V linVel30 = V4LoadA(&descs[3].data0->linearVelocity.x);
Vec4V linVel01 = V4LoadA(&descs[0].data1->linearVelocity.x);
Vec4V linVel11 = V4LoadA(&descs[1].data1->linearVelocity.x);
Vec4V linVel21 = V4LoadA(&descs[2].data1->linearVelocity.x);
Vec4V linVel31 = V4LoadA(&descs[3].data1->linearVelocity.x);
Vec4V angVel00 = V4LoadA(&descs[0].data0->angularVelocity.x);
Vec4V angVel10 = V4LoadA(&descs[1].data0->angularVelocity.x);
Vec4V angVel20 = V4LoadA(&descs[2].data0->angularVelocity.x);
Vec4V angVel30 = V4LoadA(&descs[3].data0->angularVelocity.x);
Vec4V angVel01 = V4LoadA(&descs[0].data1->angularVelocity.x);
Vec4V angVel11 = V4LoadA(&descs[1].data1->angularVelocity.x);
Vec4V angVel21 = V4LoadA(&descs[2].data1->angularVelocity.x);
Vec4V angVel31 = V4LoadA(&descs[3].data1->angularVelocity.x);
Vec4V linVelT00, linVelT10, linVelT20;
Vec4V linVelT01, linVelT11, linVelT21;
Vec4V angVelT00, angVelT10, angVelT20;
Vec4V angVelT01, angVelT11, angVelT21;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVelT00, linVelT10, linVelT20);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVelT01, linVelT11, linVelT21);
PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVelT00, angVelT10, angVelT20);
PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVelT01, angVelT11, angVelT21);
const Vec4V vrelX = V4Sub(linVelT00, linVelT01);
const Vec4V vrelY = V4Sub(linVelT10, linVelT11);
const Vec4V vrelZ = V4Sub(linVelT20, linVelT21);
//Load up masses and invInertia
const Vec4V invMass0 = V4Merge(FLoad(descs[0].data0->invMass), FLoad(descs[1].data0->invMass), FLoad(descs[2].data0->invMass),
FLoad(descs[3].data0->invMass));
const Vec4V invMass1 = V4Merge(FLoad(descs[0].data1->invMass), FLoad(descs[1].data1->invMass), FLoad(descs[2].data1->invMass),
FLoad(descs[3].data1->invMass));
const Vec4V invMass0_dom0fV = V4Mul(dom0, invMass0);
const Vec4V invMass1_dom1fV = V4Mul(dom1, invMass1);
Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column0));
Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column1));
Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column2));
Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column0));
Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column1));
Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column2));
Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column0));
Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column1));
Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column2));
Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column0));
Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column1));
Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column2));
Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column0));
Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column1));
Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column2));
Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column0));
Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column1));
Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column2));
Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column0));
Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column1));
Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column2));
Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column0));
Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column1));
Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column2));
Vec4V invInertia0X0, invInertia0X1, invInertia0X2;
Vec4V invInertia0Y0, invInertia0Y1, invInertia0Y2;
Vec4V invInertia0Z0, invInertia0Z1, invInertia0Z2;
Vec4V invInertia1X0, invInertia1X1, invInertia1X2;
Vec4V invInertia1Y0, invInertia1Y1, invInertia1Y2;
Vec4V invInertia1Z0, invInertia1Z1, invInertia1Z2;
PX_TRANSPOSE_44_34(invInertia00X, invInertia10X, invInertia20X, invInertia30X, invInertia0X0, invInertia0Y0, invInertia0Z0);
PX_TRANSPOSE_44_34(invInertia00Y, invInertia10Y, invInertia20Y, invInertia30Y, invInertia0X1, invInertia0Y1, invInertia0Z1);
PX_TRANSPOSE_44_34(invInertia00Z, invInertia10Z, invInertia20Z, invInertia30Z, invInertia0X2, invInertia0Y2, invInertia0Z2);
PX_TRANSPOSE_44_34(invInertia01X, invInertia11X, invInertia21X, invInertia31X, invInertia1X0, invInertia1Y0, invInertia1Z0);
PX_TRANSPOSE_44_34(invInertia01Y, invInertia11Y, invInertia21Y, invInertia31Y, invInertia1X1, invInertia1Y1, invInertia1Z1);
PX_TRANSPOSE_44_34(invInertia01Z, invInertia11Z, invInertia21Z, invInertia31Z, invInertia1X2, invInertia1Y2, invInertia1Z2);
const FloatV invDt = FLoad(invDtF32);
const FloatV p8 = FLoad(0.8f);
//const Vec4V p84 = V4Splat(p8);
const Vec4V p1 = V4Splat(FLoad(0.1f));
const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32));
const Vec4V orthoThreshold = V4Splat(FLoad(0.70710678f));
const FloatV invDtp8 = FMul(invDt, p8);
const Vec3V bodyFrame00p = V3LoadU(descs[0].bodyFrame0.p);
const Vec3V bodyFrame01p = V3LoadU(descs[1].bodyFrame0.p);
const Vec3V bodyFrame02p = V3LoadU(descs[2].bodyFrame0.p);
const Vec3V bodyFrame03p = V3LoadU(descs[3].bodyFrame0.p);
Vec4V bodyFrame00p4 = Vec4V_From_Vec3V(bodyFrame00p);
Vec4V bodyFrame01p4 = Vec4V_From_Vec3V(bodyFrame01p);
Vec4V bodyFrame02p4 = Vec4V_From_Vec3V(bodyFrame02p);
Vec4V bodyFrame03p4 = Vec4V_From_Vec3V(bodyFrame03p);
Vec4V bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ;
PX_TRANSPOSE_44_34(bodyFrame00p4, bodyFrame01p4, bodyFrame02p4, bodyFrame03p4, bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ);
const Vec3V bodyFrame10p = V3LoadU(descs[0].bodyFrame1.p);
const Vec3V bodyFrame11p = V3LoadU(descs[1].bodyFrame1.p);
const Vec3V bodyFrame12p = V3LoadU(descs[2].bodyFrame1.p);
const Vec3V bodyFrame13p = V3LoadU(descs[3].bodyFrame1.p);
Vec4V bodyFrame10p4 = Vec4V_From_Vec3V(bodyFrame10p);
Vec4V bodyFrame11p4 = Vec4V_From_Vec3V(bodyFrame11p);
Vec4V bodyFrame12p4 = Vec4V_From_Vec3V(bodyFrame12p);
Vec4V bodyFrame13p4 = Vec4V_From_Vec3V(bodyFrame13p);
Vec4V bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ;
PX_TRANSPOSE_44_34(bodyFrame10p4, bodyFrame11p4, bodyFrame12p4, bodyFrame13p4, bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ);
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
PxU32 frictionIndex0 = 0, frictionIndex1 = 0, frictionIndex2 = 0, frictionIndex3 = 0;
PxU32 maxPatches = PxMax(descs[0].numFrictionPatches, PxMax(descs[1].numFrictionPatches, PxMax(descs[2].numFrictionPatches, descs[3].numFrictionPatches)));
PxU32 maxContacts = numContactPoints4;
//This is the address at which the first friction patch exists
PxU8* ptr2 = ptr + ((sizeof(SolverContactCoulombHeader4) * maxPatches) + constraintSize * maxContacts);
//PxU32 contactId = 0;
for(PxU32 i=0;i<maxPatches;i++)
{
bool hasFinished[4];
hasFinished[0] = i >= descs[0].numFrictionPatches;
hasFinished[1] = i >= descs[1].numFrictionPatches;
hasFinished[2] = i >= descs[2].numFrictionPatches;
hasFinished[3] = i >= descs[3].numFrictionPatches;
frictionIndex0 = hasFinished[0] ? frictionIndex0 : descs[0].startFrictionPatchIndex + i;
frictionIndex1 = hasFinished[1] ? frictionIndex1 : descs[1].startFrictionPatchIndex + i;
frictionIndex2 = hasFinished[2] ? frictionIndex2 : descs[2].startFrictionPatchIndex + i;
frictionIndex3 = hasFinished[3] ? frictionIndex3 : descs[3].startFrictionPatchIndex + i;
const PxU32 clampedContacts0 = hasFinished[0] ? 0 : c.frictionPatchContactCounts[frictionIndex0];
const PxU32 clampedContacts1 = hasFinished[1] ? 0 : c.frictionPatchContactCounts[frictionIndex1];
const PxU32 clampedContacts2 = hasFinished[2] ? 0 : c.frictionPatchContactCounts[frictionIndex2];
const PxU32 clampedContacts3 = hasFinished[3] ? 0 : c.frictionPatchContactCounts[frictionIndex3];
const PxU32 clampedFric0 = clampedContacts0 * numFrictionPerPoint;
const PxU32 clampedFric1 = clampedContacts1 * numFrictionPerPoint;
const PxU32 clampedFric2 = clampedContacts2 * numFrictionPerPoint;
const PxU32 clampedFric3 = clampedContacts3 * numFrictionPerPoint;
const PxU32 numContacts = PxMax(clampedContacts0, PxMax(clampedContacts1, PxMax(clampedContacts2, clampedContacts3)));
const PxU32 numFrictions = PxMax(clampedFric0, PxMax(clampedFric1, PxMax(clampedFric2, clampedFric3)));
const PxU32 firstPatch0 = c.correlationListHeads[frictionIndex0];
const PxU32 firstPatch1 = c.correlationListHeads[frictionIndex1];
const PxU32 firstPatch2 = c.correlationListHeads[frictionIndex2];
const PxU32 firstPatch3 = c.correlationListHeads[frictionIndex3];
const PxContactPoint* contactBase0 = descs[0].contacts + c.contactPatches[firstPatch0].start;
const PxContactPoint* contactBase1 = descs[1].contacts + c.contactPatches[firstPatch1].start;
const PxContactPoint* contactBase2 = descs[2].contacts + c.contactPatches[firstPatch2].start;
const PxContactPoint* contactBase3 = descs[3].contacts + c.contactPatches[firstPatch3].start;
const Vec4V restitution = V4Merge(FLoad(contactBase0->restitution), FLoad(contactBase1->restitution), FLoad(contactBase2->restitution),
FLoad(contactBase3->restitution));
const Vec4V staticFriction = V4Merge(FLoad(contactBase0->staticFriction), FLoad(contactBase1->staticFriction), FLoad(contactBase2->staticFriction),
FLoad(contactBase3->staticFriction));
SolverContactCoulombHeader4* PX_RESTRICT header = reinterpret_cast<SolverContactCoulombHeader4*>(ptr);
header->frictionOffset = PxU16(ptr2 - ptr);
ptr += sizeof(SolverContactCoulombHeader4);
SolverFrictionHeader4* PX_RESTRICT fricHeader = reinterpret_cast<SolverFrictionHeader4*>(ptr2);
ptr2 += sizeof(SolverFrictionHeader4) + sizeof(Vec4V) * numContacts;
header->numNormalConstr0 = PxTo8(clampedContacts0);
header->numNormalConstr1 = PxTo8(clampedContacts1);
header->numNormalConstr2 = PxTo8(clampedContacts2);
header->numNormalConstr3 = PxTo8(clampedContacts3);
header->numNormalConstr = PxTo8(numContacts);
header->invMassADom = invMass0_dom0fV;
header->invMassBDom = invMass1_dom1fV;
header->angD0 = angDom0;
header->angD1 = angDom1;
header->restitution = restitution;
header->flags[0] = flags[0]; header->flags[1] = flags[1]; header->flags[2] = flags[2]; header->flags[3] = flags[3];
header->type = PxTo8(isDynamic ? DY_SC_TYPE_BLOCK_RB_CONTACT : DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT);
header->shapeInteraction[0] = getInteraction(descs[0]); header->shapeInteraction[1] = getInteraction(descs[1]);
header->shapeInteraction[2] = getInteraction(descs[2]); header->shapeInteraction[3] = getInteraction(descs[3]);
fricHeader->invMassADom = invMass0_dom0fV;
fricHeader->invMassBDom = invMass1_dom1fV;
fricHeader->angD0 = angDom0;
fricHeader->angD1 = angDom1;
fricHeader->numFrictionConstr0 = PxTo8(clampedFric0);
fricHeader->numFrictionConstr1 = PxTo8(clampedFric1);
fricHeader->numFrictionConstr2 = PxTo8(clampedFric2);
fricHeader->numFrictionConstr3 = PxTo8(clampedFric3);
fricHeader->numNormalConstr = PxTo8(numContacts);
fricHeader->numNormalConstr0 = PxTo8(clampedContacts0);
fricHeader->numNormalConstr1 = PxTo8(clampedContacts1);
fricHeader->numNormalConstr2 = PxTo8(clampedContacts2);
fricHeader->numNormalConstr3 = PxTo8(clampedContacts3);
fricHeader->type = PxTo8(isDynamic ? DY_SC_TYPE_BLOCK_FRICTION : DY_SC_TYPE_BLOCK_STATIC_FRICTION);
fricHeader->staticFriction = staticFriction;
fricHeader->frictionPerContact = PxU32(numFrictionPerPoint == 2 ? 1 : 0);
fricHeader->numFrictionConstr = PxTo8(numFrictions);
Vec4V normal0 = V4LoadA(&contactBase0->normal.x);
Vec4V normal1 = V4LoadA(&contactBase1->normal.x);
Vec4V normal2 = V4LoadA(&contactBase2->normal.x);
Vec4V normal3 = V4LoadA(&contactBase3->normal.x);
Vec4V normalX, normalY, normalZ;
PX_TRANSPOSE_44_34(normal0, normal1, normal2, normal3, normalX, normalY, normalZ);
header->normalX = normalX;
header->normalY = normalY;
header->normalZ = normalZ;
const Vec4V normalLenSq = V4MulAdd(normalZ, normalZ, V4MulAdd(normalY, normalY, V4Mul(normalX, normalX)));
const Vec4V linNorVel0 = V4MulAdd(normalZ, linVelT20, V4MulAdd(normalY, linVelT10, V4Mul(normalX, linVelT00)));
const Vec4V linNorVel1 = V4MulAdd(normalZ, linVelT21, V4MulAdd(normalY, linVelT11, V4Mul(normalX, linVelT01)));
const Vec4V invMassNorLenSq0 = V4Mul(invMass0_dom0fV, normalLenSq);
const Vec4V invMassNorLenSq1 = V4Mul(invMass1_dom1fV, normalLenSq);
//Calculate friction directions
const BoolV cond = V4IsGrtr(orthoThreshold, V4Abs(normalX));
const Vec4V t0FallbackX = V4Sel(cond, zero, V4Neg(normalY));
const Vec4V t0FallbackY = V4Sel(cond, V4Neg(normalZ), normalX);
const Vec4V t0FallbackZ = V4Sel(cond, normalY, zero);
const Vec4V dotNormalVrel = V4MulAdd(normalZ, vrelZ, V4MulAdd(normalY, vrelY, V4Mul(normalX, vrelX)));
const Vec4V vrelSubNorVelX = V4NegMulSub(normalX, dotNormalVrel, vrelX);
const Vec4V vrelSubNorVelY = V4NegMulSub(normalY, dotNormalVrel, vrelY);
const Vec4V vrelSubNorVelZ = V4NegMulSub(normalZ, dotNormalVrel, vrelZ);
const Vec4V lenSqvrelSubNorVelZ = V4MulAdd(vrelSubNorVelX, vrelSubNorVelX, V4MulAdd(vrelSubNorVelY, vrelSubNorVelY, V4Mul(vrelSubNorVelZ, vrelSubNorVelZ)));
const BoolV bcon2 = V4IsGrtr(lenSqvrelSubNorVelZ, p1);
Vec4V t0X = V4Sel(bcon2, vrelSubNorVelX, t0FallbackX);
Vec4V t0Y = V4Sel(bcon2, vrelSubNorVelY, t0FallbackY);
Vec4V t0Z = V4Sel(bcon2, vrelSubNorVelZ, t0FallbackZ);
//Now normalize this...
const Vec4V recipLen = V4Rsqrt(V4MulAdd(t0X, t0X, V4MulAdd(t0Y, t0Y, V4Mul(t0Z, t0Z))));
t0X = V4Mul(t0X, recipLen);
t0Y = V4Mul(t0Y, recipLen);
t0Z = V4Mul(t0Z, recipLen);
const Vec4V t1X = V4NegMulSub(normalZ, t0Y, V4Mul(normalY, t0Z));
const Vec4V t1Y = V4NegMulSub(normalX, t0Z, V4Mul(normalZ, t0X));
const Vec4V t1Z = V4NegMulSub(normalY, t0X, V4Mul(normalX, t0Y));
const Vec4V tFallbackX[2] = {t0X, t1X};
const Vec4V tFallbackY[2] = {t0Y, t1Y};
const Vec4V tFallbackZ[2] = {t0Z, t1Z};
//For all correlation heads - need to pull this out I think
//OK, we have a counter for all our patches...
PxU32 finished = (PxU32(hasFinished[0])) |
((PxU32(hasFinished[1])) << 1) |
((PxU32(hasFinished[2])) << 2) |
((PxU32(hasFinished[3])) << 3);
CorrelationListIterator iter0(c, firstPatch0);
CorrelationListIterator iter1(c, firstPatch1);
CorrelationListIterator iter2(c, firstPatch2);
CorrelationListIterator iter3(c, firstPatch3);
PxU32 contact0, contact1, contact2, contact3;
PxU32 patch0, patch1, patch2, patch3;
iter0.nextContact(patch0, contact0);
iter1.nextContact(patch1, contact1);
iter2.nextContact(patch2, contact2);
iter3.nextContact(patch3, contact3);
PxU8* p = ptr;
PxU32 contactCount = 0;
PxU32 newFinished =
(PxU32(hasFinished[0] || !iter0.hasNextContact())) |
((PxU32(hasFinished[1] || !iter1.hasNextContact())) << 1) |
((PxU32(hasFinished[2] || !iter2.hasNextContact())) << 2) |
((PxU32(hasFinished[3] || !iter3.hasNextContact())) << 3);
// finished flags are used to be able to handle pairs with varying number
// of contact points in the same loop
BoolV bFinished = BLoad(hasFinished);
PxU32 fricIndex = 0;
while(finished != 0xf)
{
finished = newFinished;
++contactCount;
PxPrefetchLine(p, 384);
PxPrefetchLine(p, 512);
PxPrefetchLine(p, 640);
SolverContact4Base* PX_RESTRICT solverContact = reinterpret_cast<SolverContact4Base*>(p);
p += constraintSize;
const PxContactPoint& con0 = descs[0].contacts[c.contactPatches[patch0].start + contact0];
const PxContactPoint& con1 = descs[1].contacts[c.contactPatches[patch1].start + contact1];
const PxContactPoint& con2 = descs[2].contacts[c.contactPatches[patch2].start + contact2];
const PxContactPoint& con3 = descs[3].contacts[c.contactPatches[patch3].start + contact3];
//Now we need to splice these 4 contacts into a single structure
{
Vec4V point0 = V4LoadA(&con0.point.x);
Vec4V point1 = V4LoadA(&con1.point.x);
Vec4V point2 = V4LoadA(&con2.point.x);
Vec4V point3 = V4LoadA(&con3.point.x);
Vec4V pointX, pointY, pointZ;
PX_TRANSPOSE_44_34(point0, point1, point2, point3, pointX, pointY, pointZ);
Vec4V targetVel0 = V4LoadA(&con0.targetVel.x);
Vec4V targetVel1 = V4LoadA(&con1.targetVel.x);
Vec4V targetVel2 = V4LoadA(&con2.targetVel.x);
Vec4V targetVel3 = V4LoadA(&con3.targetVel.x);
Vec4V targetVelX, targetVelY, targetVelZ;
PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ);
Vec4V raX = V4Sub(pointX, bodyFrame0pX);
Vec4V raY = V4Sub(pointY, bodyFrame0pY);
Vec4V raZ = V4Sub(pointZ, bodyFrame0pZ);
Vec4V rbX = V4Sub(pointX, bodyFrame1pX);
Vec4V rbY = V4Sub(pointY, bodyFrame1pY);
Vec4V rbZ = V4Sub(pointZ, bodyFrame1pZ);
raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);
rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);
{
const Vec4V separation = V4Merge(FLoad(con0.separation), FLoad(con1.separation), FLoad(con2.separation),
FLoad(con3.separation));
const Vec4V maxImpulse = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse),
FLoad(con3.maxImpulse));
const Vec4V cTargetVel = V4MulAdd(normalX, targetVelX, V4MulAdd(normalY, targetVelY, V4Mul(normalZ, targetVelZ)));
//raXn = cross(ra, normal) which = Vec3V( a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x);
const Vec4V raXnX = V4NegMulSub(raZ, normalY, V4Mul(raY, normalZ));
const Vec4V raXnY = V4NegMulSub(raX, normalZ, V4Mul(raZ, normalX));
const Vec4V raXnZ = V4NegMulSub(raY, normalX, V4Mul(raX, normalY));
const Vec4V v0a0 = V4Mul(invInertia0X0, raXnX);
const Vec4V v0a1 = V4Mul(invInertia0X1, raXnX);
const Vec4V v0a2 = V4Mul(invInertia0X2, raXnX);
const Vec4V v0PlusV1a0 = V4MulAdd(invInertia0Y0, raXnY, v0a0);
const Vec4V v0PlusV1a1 = V4MulAdd(invInertia0Y1, raXnY, v0a1);
const Vec4V v0PlusV1a2 = V4MulAdd(invInertia0Y2, raXnY, v0a2);
const Vec4V delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, v0PlusV1a0);
const Vec4V delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, v0PlusV1a1);
const Vec4V delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, v0PlusV1a2);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
const Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
Vec4V unitResponse = V4Add(invMassNorLenSq0, dotDelAngVel0);
Vec4V vrel = V4Add(linNorVel0, dotRaXnAngVel0);
//The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much
if(isDynamic)
{
SolverContact4Dynamic* PX_RESTRICT dynamicContact = static_cast<SolverContact4Dynamic*>(solverContact);
const Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ));
const Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX));
const Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY));
const Vec4V v0b0 = V4Mul(invInertia1X0, rbXnX);
const Vec4V v0b1 = V4Mul(invInertia1X1, rbXnX);
const Vec4V v0b2 = V4Mul(invInertia1X2, rbXnX);
const Vec4V v0PlusV1b0 = V4MulAdd(invInertia1Y0, rbXnY, v0b0);
const Vec4V v0PlusV1b1 = V4MulAdd(invInertia1Y1, rbXnY, v0b1);
const Vec4V v0PlusV1b2 = V4MulAdd(invInertia1Y2, rbXnY, v0b2);
const Vec4V delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, v0PlusV1b0);
const Vec4V delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, v0PlusV1b1);
const Vec4V delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, v0PlusV1b2);
//V3Dot(raXn, delAngVel0)
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
const Vec4V resp1 = V4Add(dotDelAngVel1, invMassNorLenSq1);
unitResponse = V4Add(unitResponse, resp1);
const Vec4V vrel2 = V4Add(linNorVel1, dotRbXnAngVel1);
vrel = V4Sub(vrel, vrel2);
//These are for dynamic-only contacts.
dynamicContact->rbXnX = delAngVel1X;
dynamicContact->rbXnY = delAngVel1Y;
dynamicContact->rbXnZ = delAngVel1Z;
}
const Vec4V velMultiplier = V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero);
const Vec4V penetration = V4Sub(separation, restDistance);
const Vec4V penInvDtp8 = V4Max(maxPenBias, V4Scale(penetration, invDtp8));
Vec4V scaledBias = V4Mul(velMultiplier, penInvDtp8);
const Vec4V penetrationInvDt = V4Scale(penetration, invDt);
const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(restitution, zero), V4IsGrtr(bounceThreshold, vrel)),
V4IsGrtr(V4Neg(vrel), penetrationInvDt));
const BoolV ccdSeparationCondition = V4IsGrtrOrEq(ccdMaxSeparation, penetration);
scaledBias = V4Sel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias);
const Vec4V sumVRel(vrel);
const Vec4V targetVelocity = V4Sub(V4Add(V4Sel(isGreater2, V4Mul(V4Neg(sumVRel), restitution), zero), cTargetVel), vrel);
//These values are present for static and dynamic contacts
solverContact->raXnX = delAngVel0X;
solverContact->raXnY = delAngVel0Y;
solverContact->raXnZ = delAngVel0Z;
solverContact->velMultiplier = V4Sel(bFinished, zero, velMultiplier);
solverContact->appliedForce = zero;
solverContact->scaledBias = V4Sel(bFinished, zero, scaledBias);
solverContact->targetVelocity = targetVelocity;
solverContact->maxImpulse = maxImpulse;
}
//PxU32 conId = contactId++;
/*Vec4V targetVel0 = V4LoadA(&con0.targetVel.x);
Vec4V targetVel1 = V4LoadA(&con1.targetVel.x);
Vec4V targetVel2 = V4LoadA(&con2.targetVel.x);
Vec4V targetVel3 = V4LoadA(&con3.targetVel.x);
Vec4V targetVelX, targetVelY, targetVelZ;
PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ);*/
for(PxU32 a = 0; a < numFrictionPerPoint; ++a)
{
SolverFriction4Base* PX_RESTRICT friction = reinterpret_cast<SolverFriction4Base*>(ptr2);
ptr2 += frictionSize;
const Vec4V tX = tFallbackX[fricIndex];
const Vec4V tY = tFallbackY[fricIndex];
const Vec4V tZ = tFallbackZ[fricIndex];
fricIndex = 1 - fricIndex;
const Vec4V raXnX = V4NegMulSub(raZ, tY, V4Mul(raY, tZ));
const Vec4V raXnY = V4NegMulSub(raX, tZ, V4Mul(raZ, tX));
const Vec4V raXnZ = V4NegMulSub(raY, tX, V4Mul(raX, tY));
const Vec4V v0a0 = V4Mul(invInertia0X0, raXnX);
const Vec4V v0a1 = V4Mul(invInertia0X1, raXnX);
const Vec4V v0a2 = V4Mul(invInertia0X2, raXnX);
const Vec4V v0PlusV1a0 = V4MulAdd(invInertia0Y0, raXnY, v0a0);
const Vec4V v0PlusV1a1 = V4MulAdd(invInertia0Y1, raXnY, v0a1);
const Vec4V v0PlusV1a2 = V4MulAdd(invInertia0Y2, raXnY, v0a2);
const Vec4V delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, v0PlusV1a0);
const Vec4V delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, v0PlusV1a1);
const Vec4V delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, v0PlusV1a2);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
const Vec4V norVel0 = V4MulAdd(tX, linVelT00, V4MulAdd(tY, linVelT10, V4Mul(tZ, linVelT20)));
const Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
Vec4V vrel = V4Add(norVel0, dotRaXnAngVel0);
Vec4V unitResponse = V4Add(invMass0_dom0fV, dotDelAngVel0);
if(isDynamic)
{
SolverFriction4Dynamic* PX_RESTRICT dFric = static_cast<SolverFriction4Dynamic*>(friction);
const Vec4V rbXnX = V4NegMulSub(rbZ, tY, V4Mul(rbY, tZ));
const Vec4V rbXnY = V4NegMulSub(rbX, tZ, V4Mul(rbZ, tX));
const Vec4V rbXnZ = V4NegMulSub(rbY, tX, V4Mul(rbX, tY));
const Vec4V v0b0 = V4Mul(invInertia1X0, rbXnX);
const Vec4V v0b1 = V4Mul(invInertia1X1, rbXnX);
const Vec4V v0b2 = V4Mul(invInertia1X2, rbXnX);
const Vec4V v0PlusV1b0 = V4MulAdd(invInertia1Y0, rbXnY, v0b0);
const Vec4V v0PlusV1b1 = V4MulAdd(invInertia1Y1, rbXnY, v0b1);
const Vec4V v0PlusV1b2 = V4MulAdd(invInertia1Y2, rbXnY, v0b2);
const Vec4V delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, v0PlusV1b0);
const Vec4V delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, v0PlusV1b1);
const Vec4V delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, v0PlusV1b2);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V norVel1 = V4MulAdd(tX, linVelT01, V4MulAdd(tY, linVelT11, V4Mul(tZ, linVelT21)));
const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
vrel = V4Sub(vrel, V4Add(norVel1, dotRbXnAngVel1));
const Vec4V resp1 = V4Add(dotDelAngVel1, invMassNorLenSq1);
unitResponse = V4Add(unitResponse, resp1);
dFric->rbXnX = delAngVel1X;
dFric->rbXnY = delAngVel1Y;
dFric->rbXnZ = delAngVel1Z;
}
const Vec4V velMultiplier = V4Neg(V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero));
friction->appliedForce = zero;
friction->raXnX = delAngVel0X;
friction->raXnY = delAngVel0Y;
friction->raXnZ = delAngVel0Z;
friction->velMultiplier = velMultiplier;
friction->targetVelocity = V4Sub(V4MulAdd(targetVelZ, tZ, V4MulAdd(targetVelY, tY, V4Mul(targetVelX, tX))), vrel);
friction->normalX = tX;
friction->normalY = tY;
friction->normalZ = tZ;
}
}
// update the finished flags
if(!(finished & 0x1))
{
iter0.nextContact(patch0, contact0);
newFinished |= PxU32(!iter0.hasNextContact());
}
else
bFinished = BSetX(bFinished, bTrue);
if(!(finished & 0x2))
{
iter1.nextContact(patch1, contact1);
newFinished |= (PxU32(!iter1.hasNextContact()) << 1);
}
else
bFinished = BSetY(bFinished, bTrue);
if(!(finished & 0x4))
{
iter2.nextContact(patch2, contact2);
newFinished |= (PxU32(!iter2.hasNextContact()) << 2);
}
else
bFinished = BSetZ(bFinished, bTrue);
if(!(finished & 0x8))
{
iter3.nextContact(patch3, contact3);
newFinished |= (PxU32(!iter3.hasNextContact()) << 3);
}
else
bFinished = BSetW(bFinished, bTrue);
}
ptr = p;
}
return true;
}
//The persistent friction patch correlation/allocation will already have happenned as this is per-pair.
//This function just computes the size of the combined solve data.
void computeBlockStreamByteSizesCoulomb4(PxSolverContactDesc* descs,
ThreadContext& threadContext, const CorrelationBuffer& c,
const PxU32 numFrictionPerPoint,
PxU32& _solverConstraintByteSize, PxU32* _axisConstraintCount, PxU32& _numContactPoints4)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PX_UNUSED(threadContext);
PxU32 maxPatches = 0;
PxU32 maxContactCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxU32 maxFrictionCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxMemZero(maxContactCount, sizeof(maxContactCount));
PxMemZero(maxFrictionCount, sizeof(maxFrictionCount));
for(PxU32 a = 0; a < 4; ++a)
{
PxU32 axisConstraintCount = 0;
for(PxU32 i = 0; i < descs[a].numFrictionPatches; i++)
{
PxU32 ind = i + descs[a].startFrictionPatchIndex;
const FrictionPatch& frictionPatch = c.frictionPatches[ind];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0;
//Solver constraint data.
if(c.frictionPatchContactCounts[ind]!=0)
{
maxContactCount[i] = PxMax(c.frictionPatchContactCounts[ind], maxContactCount[i]);
axisConstraintCount += c.frictionPatchContactCounts[ind];
if(haveFriction)
{
//const PxU32 fricCount = c.frictionPatches[ind].numConstraints;
const PxU32 fricCount = c.frictionPatchContactCounts[ind] * numFrictionPerPoint;
maxFrictionCount[i] = PxMax(fricCount, maxFrictionCount[i]);
axisConstraintCount += fricCount;
}
}
}
maxPatches = PxMax(descs[a].numFrictionPatches, maxPatches);
_axisConstraintCount[a] = axisConstraintCount;
}
PxU32 totalContacts = 0, totalFriction = 0;
for(PxU32 a = 0; a < maxPatches; ++a)
{
totalContacts += maxContactCount[a];
totalFriction += maxFrictionCount[a];
}
_numContactPoints4 = totalContacts;
//OK, we have a given number of friction patches, contact points and friction constraints so we can calculate how much memory we need
const bool isStatic = (((descs[0].bodyState1 | descs[1].bodyState1 | descs[2].bodyState1 | descs[3].bodyState1) & PxSolverContactDesc::eDYNAMIC_BODY) == 0);
const PxU32 headerSize = (sizeof(SolverContactCoulombHeader4) + sizeof(SolverFrictionHeader4)) * maxPatches;
//Add on 1 Vec4V per contact for the applied force buffer
const PxU32 constraintSize = isStatic ? ((sizeof(SolverContact4Base) + sizeof(Vec4V)) * totalContacts) + ( sizeof(SolverFriction4Base) * totalFriction) :
((sizeof(SolverContact4Dynamic) + sizeof(Vec4V)) * totalContacts) + (sizeof(SolverFriction4Dynamic) * totalFriction);
_solverConstraintByteSize = ((constraintSize + headerSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
}
static SolverConstraintPrepState::Enum reserveBlockStreamsCoulomb4(PxSolverContactDesc* descs, ThreadContext& threadContext, const CorrelationBuffer& c,
PxU8*& solverConstraint, const PxU32 numFrictionPerContactPoint,
PxU32& solverConstraintByteSize,
PxU32* axisConstraintCount, PxU32& numContactPoints4, PxConstraintAllocator& constraintAllocator)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(0 == solverConstraintByteSize);
//From constraintBlockStream we need to reserve contact points, contact forces, and a char buffer for the solver constraint data (already have a variable for this).
//From frictionPatchStream we just need to reserve a single buffer.
//Compute the sizes of all the buffers.
computeBlockStreamByteSizesCoulomb4(
descs, threadContext, c, numFrictionPerContactPoint, solverConstraintByteSize,
axisConstraintCount, numContactPoints4);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if(constraintBlockByteSize > 0)
{
if((constraintBlockByteSize + 16u) > 16384)
return SolverConstraintPrepState::eUNBATCHABLE;
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock)
{
if(0==constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock=NULL;
}
}
}
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if(0==constraintBlockByteSize || constraintBlock)
{
if(solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f));
}
}
//Return true if neither of the two block reservations failed.
return ((0==constraintBlockByteSize || constraintBlock)) ? SolverConstraintPrepState::eSUCCESS : SolverConstraintPrepState::eOUT_OF_MEMORY;
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb1D(
PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator)
{
return createFinalizeSolverContacts4Coulomb(outputs, threadContext, blockDescs, invDtF32, dtF32, bounceThresholdF32,
frictionOffsetThreshold, correlationDistance, constraintAllocator, PxFrictionType::eONE_DIRECTIONAL);
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb2D(
PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator)
{
return createFinalizeSolverContacts4Coulomb(outputs, threadContext, blockDescs, invDtF32, dtF32, bounceThresholdF32,
frictionOffsetThreshold, correlationDistance, constraintAllocator, PxFrictionType::eTWO_DIRECTIONAL);
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb(
PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
PxFrictionType::Enum frictionType)
{
PX_UNUSED(frictionOffsetThreshold);
PX_UNUSED(correlationDistance);
PX_UNUSED(dtF32);
for(PxU32 i = 0; i < 4; ++i)
{
blockDescs[i].desc->constraintLengthOver16 = 0;
}
PX_ASSERT(outputs[0]->nbContacts && outputs[1]->nbContacts && outputs[2]->nbContacts && outputs[3]->nbContacts);
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
PxU32 numContacts = 0;
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
PxU32 numFrictionPerPoint = PxU32(frictionType == PxFrictionType::eONE_DIRECTIONAL ? 1 : 2);
PX_ALIGN(16, PxReal invMassScale0[4]);
PX_ALIGN(16, PxReal invMassScale1[4]);
PX_ALIGN(16, PxReal invInertiaScale0[4]);
PX_ALIGN(16, PxReal invInertiaScale1[4]);
for(PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
//blockDesc.startContactIndex = numContacts;
blockDesc.contacts = &buffer.contacts[numContacts];
PxPrefetchLine(desc.bodyA);
PxPrefetchLine(desc.bodyB);
if((numContacts + outputs[a]->nbContacts) > 64)
{
return SolverConstraintPrepState::eUNBATCHABLE;
}
bool hasMaxImpulse, hasTargetVelocity;
const PxReal defaultMaxImpulse = PxMin(blockDesc.data0->maxContactImpulse, blockDesc.data1->maxContactImpulse);
PxU32 contactCount = extractContacts(buffer, *outputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0[a], invMassScale1[a],
invInertiaScale0[a], invInertiaScale1[a], defaultMaxImpulse);
if(contactCount == 0)
return SolverConstraintPrepState::eUNBATCHABLE;
numContacts+=contactCount;
blockDesc.numContacts = contactCount;
blockDesc.hasMaxImpulse = hasMaxImpulse;
blockDesc.startFrictionPatchIndex = c.frictionPatchCount;
blockDesc.startContactPatchIndex = c.contactPatchCount;
createContactPatches(c, blockDesc.contacts, contactCount, PXC_SAME_NORMAL);
bool overflow = correlatePatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, PXC_SAME_NORMAL, blockDesc.startContactPatchIndex,
blockDesc.startFrictionPatchIndex);
if(overflow)
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContactPatches = PxU16(c.contactPatchCount - blockDesc.startContactPatchIndex);
blockDesc.numFrictionPatches = c.frictionPatchCount - blockDesc.startFrictionPatchIndex;
invMassScale0[a] *= blockDesc.invMassScales.linear0;
invMassScale1[a] *= blockDesc.invMassScales.linear1;
invInertiaScale0[a] *= blockDesc.invMassScales.angular0;
invInertiaScale1[a] *= blockDesc.invMassScales.angular1;
}
//OK, now we need to work out how much memory to allocate, allocate it and then block-create the constraints...
PxU8* solverConstraint = NULL;
PxU32 solverConstraintByteSize = 0;
PxU32 axisConstraintCount[4];
PxU32 numContactPoints4 = 0;
SolverConstraintPrepState::Enum state = reserveBlockStreamsCoulomb4(blockDescs, threadContext, c,
solverConstraint, numFrictionPerPoint,
solverConstraintByteSize,
axisConstraintCount, numContactPoints4, constraintAllocator);
if(state != SolverConstraintPrepState::eSUCCESS)
return state;
//OK, we allocated the memory, now let's create the constraints
for(PxU32 a = 0; a < 4; ++a)
{
PxSolverConstraintDesc& desc = *blockDescs[a].desc;
//n[a]->solverConstraintPointer = solverConstraint;
desc.constraint = solverConstraint;
//KS - TODO - add back in counters for axisConstraintCount somewhere...
blockDescs[a].axisConstraintCount += PxTo16(axisConstraintCount[a]);
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize/16);
void* writeBack = outputs[a]->contactForces;
desc.writeBack = writeBack;
}
const Vec4V iMassScale0 = V4LoadA(invMassScale0);
const Vec4V iInertiaScale0 = V4LoadA(invInertiaScale0);
const Vec4V iMassScale1 = V4LoadA(invMassScale1);
const Vec4V iInertiaScale1 = V4LoadA(invInertiaScale1);
bool hasFriction = setupFinalizeSolverConstraintsCoulomb4(blockDescs, solverConstraint,
invDtF32, bounceThresholdF32, c, numFrictionPerPoint, numContactPoints4, solverConstraintByteSize,
iMassScale0, iInertiaScale0, iMassScale1, iInertiaScale1);
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize + 4)) = hasFriction ? 0xFFFFFFFF : 0;
return SolverConstraintPrepState::eSUCCESS;
}
}
}
| 44,333 | C++ | 43.113433 | 175 | 0.750186 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneArticulation.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMathUtils.h"
#include "CmConeLimitHelper.h"
#include "DySolverConstraint1D.h"
#include "DyFeatherstoneArticulation.h"
#include "PxsRigidBody.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
#include "DyDynamics.h"
#include "DyArticulationPImpl.h"
#include "DyFeatherstoneArticulationLink.h"
#include "DyFeatherstoneArticulationJointData.h"
#include "DySolverConstraint1DStep.h"
#include "DyTGSDynamics.h"
#include "DyConstraintPrep.h"
#include "common/PxProfileZone.h"
#include "PxsContactManager.h"
#include "DyContactPrep.h"
#include "DySolverContext.h"
#include "DyTGSContactPrep.h"
#include "DyArticulationCpuGpu.h"
#ifndef FEATURESTONE_DEBUG
#define FEATURESTONE_DEBUG 0
#endif
// we encode articulation link handles in the lower bits of the pointer, so the
// articulation has to be aligned, which in an aligned pool means we need to size it
// appropriately
namespace physx
{
namespace Dy
{
extern PxcCreateFinalizeSolverContactMethod createFinalizeMethods[3];
ArticulationData::~ArticulationData()
{
PX_FREE(mLinksData);
PX_FREE(mJointData);
PX_FREE(mPathToRootElements);
}
void ArticulationData::resizeLinkData(const PxU32 linkCount)
{
const PxU32 oldSize = mMotionVelocities.size();
mMotionVelocities.reserve(linkCount);
mMotionVelocities.forceSize_Unsafe(linkCount);
mSolverLinkSpatialDeltaVels.reserve(linkCount);
mSolverLinkSpatialDeltaVels.forceSize_Unsafe(linkCount);
mSolverLinkSpatialImpulses.reserve(linkCount);
mSolverLinkSpatialImpulses.forceSize_Unsafe(linkCount);
mSolverLinkSpatialForces.reserve(linkCount);
mSolverLinkSpatialForces.forceSize_Unsafe(linkCount);
mMotionAccelerations.reserve(linkCount);
mMotionAccelerations.forceSize_Unsafe(linkCount);
mLinkIncomingJointForces.reserve(linkCount);
mLinkIncomingJointForces.forceSize_Unsafe(linkCount);
mMotionAccelerationsInternal.reserve(linkCount);
mMotionAccelerationsInternal.forceSize_Unsafe(linkCount);
mCorioliseVectors.reserve(linkCount);
mCorioliseVectors.forceSize_Unsafe(linkCount);
mZAForces.reserve(linkCount);
mZAForces.forceSize_Unsafe(linkCount);
mZAInternalForces.reserve(linkCount);
mZAInternalForces.forceSize_Unsafe(linkCount);
mNbStatic1DConstraints.reserve(linkCount);
mNbStatic1DConstraints.forceSize_Unsafe(linkCount);
mStatic1DConstraintStartIndex.reserve(linkCount);
mStatic1DConstraintStartIndex.forceSize_Unsafe(linkCount);
mNbStaticContactConstraints.reserve(linkCount);
mNbStaticContactConstraints.forceSize_Unsafe(linkCount);
mStaticContactConstraintStartIndex.reserve(linkCount);
mStaticContactConstraintStartIndex.forceSize_Unsafe(linkCount);
mDeltaMotionVector.reserve(linkCount);
mDeltaMotionVector.forceSize_Unsafe(linkCount);
mPreTransform.reserve(linkCount);
mPreTransform.forceSize_Unsafe(linkCount);
mResponseMatrixW.reserve(linkCount);
mResponseMatrixW.forceSize_Unsafe(linkCount);
mWorldSpatialArticulatedInertia.reserve(linkCount);
mWorldSpatialArticulatedInertia.forceSize_Unsafe(linkCount);
mWorldIsolatedSpatialArticulatedInertia.reserve(linkCount);
mWorldIsolatedSpatialArticulatedInertia.forceSize_Unsafe(linkCount);
mMasses.reserve(linkCount);
mMasses.forceSize_Unsafe(linkCount);
mInvStIs.reserve(linkCount);
mInvStIs.forceSize_Unsafe(linkCount);
/*mMotionMatrix.resize(linkCount);
mWorldMotionMatrix.reserve(linkCount);
mWorldMotionMatrix.forceSize_Unsafe(linkCount);*/
mAccumulatedPoses.reserve(linkCount);
mAccumulatedPoses.forceSize_Unsafe(linkCount);
mDeltaQ.reserve(linkCount);
mDeltaQ.forceSize_Unsafe(linkCount);
mPosIterMotionVelocities.reserve(linkCount);
mPosIterMotionVelocities.forceSize_Unsafe(linkCount);
mJointTransmittedForce.reserve(linkCount);
mJointTransmittedForce.forceSize_Unsafe(linkCount);
mRw.reserve(linkCount);
mRw.forceSize_Unsafe(linkCount);
//This stores how much an impulse on a given link influences the root link.
//We combine this with the back-propagation of joint forces to compute the
//change in velocity of a given impulse!
mRootResponseMatrix.reserve(linkCount);
mRootResponseMatrix.forceSize_Unsafe(linkCount);
mRelativeQuat.resize(linkCount);
if (oldSize < linkCount)
{
ArticulationLinkData* oldLinks = mLinksData;
ArticulationJointCoreData* oldJoints = mJointData;
mLinksData = PX_ALLOCATE(ArticulationLinkData, linkCount, "ArticulationLinkData");
mJointData = PX_ALLOCATE(ArticulationJointCoreData, linkCount, "ArticulationJointCoreData");
PxMemCopy(mLinksData, oldLinks, sizeof(ArticulationLinkData)*oldSize);
PxMemCopy(mJointData, oldJoints, sizeof(ArticulationJointCoreData)*oldSize);
PX_FREE(oldLinks);
PX_FREE(oldJoints);
const PxU32 newElems = (linkCount - oldSize);
PxMemZero(mLinksData + oldSize, sizeof(ArticulationLinkData) * newElems);
PxMemZero(mJointData + oldSize, sizeof(ArticulationJointCoreData) * newElems);
for (PxU32 linkID = oldSize; linkID < linkCount; ++linkID)
{
PX_PLACEMENT_NEW(mLinksData + linkID, ArticulationLinkData)();
PX_PLACEMENT_NEW(mJointData + linkID, ArticulationJointCoreData)();
}
}
}
void ArticulationData::resizeJointData(const PxU32 dofs)
{
mJointAcceleration.reserve(dofs);
mJointAcceleration.forceSize_Unsafe(dofs);
mJointInternalAcceleration.reserve(dofs);
mJointInternalAcceleration.forceSize_Unsafe(dofs);
mJointVelocity.reserve(dofs);
mJointVelocity.forceSize_Unsafe(dofs);
mJointNewVelocity.reserve(dofs+3);
mJointNewVelocity.forceSize_Unsafe(dofs+3);
mJointPosition.reserve(dofs);
mJointPosition.forceSize_Unsafe(dofs);
mJointForce.reserve(dofs);
mJointForce.forceSize_Unsafe(dofs);
mJointTargetPositions.reserve(dofs);
mJointTargetPositions.forceSize_Unsafe(dofs);
mJointTargetVelocities.reserve(dofs);
mJointTargetVelocities.forceSize_Unsafe(dofs);
mMotionMatrix.resize(dofs);
mJointSpaceJacobians.resize(dofs*mLinkCount);
mJointSpaceDeltaVMatrix.resize(((dofs + 3) / 4)*mLinkCount);
mJointSpaceResponseMatrix.resize(dofs); //This is only an entry per-dof
mPropagationAccelerator.resize(dofs);
mWorldMotionMatrix.reserve(dofs);
mWorldMotionMatrix.forceSize_Unsafe(dofs);
mJointAxis.reserve(dofs);
mJointAxis.forceSize_Unsafe(dofs);
mIsW.reserve(dofs);
mIsW.forceSize_Unsafe(dofs);
mDeferredQstZ.reserve(dofs);
mDeferredQstZ.forceSize_Unsafe(dofs);
mJointConstraintForces.resizeUninitialized(dofs);
qstZIc.reserve(dofs);
qstZIc.forceSize_Unsafe(dofs);
qstZIntIc.reserve(dofs);
qstZIntIc.forceSize_Unsafe(dofs);
mISInvStIS.reserve(dofs);
mISInvStIS.forceSize_Unsafe(dofs);
mPosIterJointVelocities.reserve(dofs);
mPosIterJointVelocities.forceSize_Unsafe(dofs);
PxMemZero(mJointAcceleration.begin(), sizeof(PxReal) * dofs);
PxMemZero(mJointVelocity.begin(), sizeof(PxReal) * dofs);
PxMemZero(mJointPosition.begin(), sizeof(PxReal) * dofs);
PxMemZero(mJointForce.begin(), sizeof(PxReal) * dofs);
PxMemZero(mJointTargetPositions.begin(), sizeof(PxReal) * dofs);
PxMemZero(mJointTargetVelocities.begin(), sizeof(PxReal) * dofs);
}
ArticulationLinkData& ArticulationData::getLinkData(PxU32 index) const
{
PX_ASSERT(index < mLinkCount);
return mLinksData[index];
}
FeatherstoneArticulation::FeatherstoneArticulation(void* userData)
: mUserData(userData), mContext(NULL), mUpdateSolverData(true),
mMaxDepth(0), mJcalcDirty(true)
{
mGPUDirtyFlags = 0;
}
FeatherstoneArticulation::~FeatherstoneArticulation()
{
}
void FeatherstoneArticulation::copyJointData(const ArticulationData& data, PxReal* toJointData, const PxReal* fromJointData)
{
const PxU32 dofCount = data.getDofs();
PxMemCopy(toJointData, fromJointData, sizeof(PxReal)*dofCount);
}
PxU32 FeatherstoneArticulation::computeDofs()
{
const PxU32 linkCount = mArticulationData.getLinkCount();
PxU32 totalDofs = 0;
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = mArticulationData.getLink(linkID);
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
const PxU8 dof = jointDatum.computeJointDofs(link.inboundJoint);
totalDofs += dof;
}
return totalDofs;
}
bool FeatherstoneArticulation::resize(const PxU32 linkCount)
{
if (mUpdateSolverData)
{
if (linkCount != mSolverDesc.linkCount)
{
mSolverDesc.acceleration = mAcceleration.begin();
mSolverDesc.articulation = this;
}
mUpdateSolverData = false;
if (linkCount != mSolverDesc.linkCount)
mArticulationData.resizeLinkData(linkCount);
return true;
}
return false;
}
void FeatherstoneArticulation::getDataSizes(PxU32 /*linkCount*/, PxU32& solverDataSize, PxU32& totalSize, PxU32& scratchSize)
{
solverDataSize = 0;
totalSize = 0;
scratchSize = 0;
}
void FeatherstoneArticulation::setupLinks(PxU32 nbLinks, Dy::ArticulationLink* links)
{
//if this is needed, we need to re-allocated the link data
resize(nbLinks);
mSolverDesc.links = links;
mSolverDesc.linkCount = PxTo8(nbLinks);
mArticulationData.mLinks = links;
mArticulationData.mLinkCount = PxTo8(nbLinks);
mArticulationData.mFlags = mSolverDesc.core ? &mSolverDesc.core->flags : mSolverDesc.flags; // PT: PX-1399
mArticulationData.mExternalAcceleration = mSolverDesc.acceleration;
mArticulationData.mArticulation = this;
//allocate memory for articulation data
PxU32 totalDofs = computeDofs();
const PxU32 existedTotalDofs = mArticulationData.getDofs();
if (totalDofs != existedTotalDofs)
{
mArticulationData.resizeJointData(totalDofs + 1);
mArticulationData.setDofs(totalDofs);
}
}
void FeatherstoneArticulation::allocatePathToRootElements(const PxU32 totalPathToRootElements)
{
if (mArticulationData.mNumPathToRootElements < totalPathToRootElements)
{
mArticulationData.mPathToRootElements = PX_ALLOCATE(PxU32, totalPathToRootElements, "PxU32");
mArticulationData.mNumPathToRootElements = totalPathToRootElements;
}
}
void FeatherstoneArticulation::initPathToRoot()
{
Dy::ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
links[0].mPathToRootCount = 0;
links[0].mPathToRootStartIndex = 0;
PxU32 totalPathToRootCount = 1; //add on root
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
Dy::ArticulationLink& link = links[linkID];
PxU32 parent = link.parent;
PxU32 pathToRootCount = 1; // add myself to the path
while (parent != 0) // don't add the root
{
parent = links[parent].parent;
pathToRootCount++;
}
link.mPathToRootStartIndex = totalPathToRootCount;
link.mPathToRootCount = PxU16(pathToRootCount);
totalPathToRootCount += pathToRootCount;
}
allocatePathToRootElements(totalPathToRootCount);
PxU32* pathToRootElements = mArticulationData.getPathToRootElements();
pathToRootElements[0] = 0; //add on root index
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
Dy::ArticulationLink& link = links[linkID];
PxU32* pathToRoot = &pathToRootElements[link.mPathToRootStartIndex];
PxU32 numElements = link.mPathToRootCount;
pathToRoot[--numElements] = linkID;
PxU32 parent = links[linkID].parent;
while (parent != 0)
{
pathToRoot[--numElements] = parent;
parent = links[parent].parent;
}
}
}
void FeatherstoneArticulation::assignTendons(const PxU32 nbTendons, Dy::ArticulationSpatialTendon** tendons)
{
mArticulationData.mSpatialTendons = tendons;
mArticulationData.mNumSpatialTendons = nbTendons;
}
void FeatherstoneArticulation::assignTendons(const PxU32 nbTendons, Dy::ArticulationFixedTendon** tendons)
{
mArticulationData.mFixedTendons = tendons;
mArticulationData.mNumFixedTendons = nbTendons;
}
void FeatherstoneArticulation::assignSensors(const PxU32 nbSensors, Dy::ArticulationSensor** sensors, PxSpatialForce* sensorForces)
{
mArticulationData.mSensors = sensors;
mArticulationData.mNbSensors = nbSensors;
mArticulationData.mSensorForces = sensorForces;
}
PxU32 FeatherstoneArticulation::getDofs() const
{
return mArticulationData.getDofs();
}
PxU32 FeatherstoneArticulation::getDof(const PxU32 linkID)
{
const ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
return jointDatum.dof;
}
bool FeatherstoneArticulation::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, bool& shouldWake)
{
return applyCacheToDest(mArticulationData, cache, mArticulationData.getJointVelocities(), mArticulationData.getJointPositions(),
mArticulationData.getJointForces(), mArticulationData.getJointTargetPositions(), mArticulationData.getJointTargetVelocities(), flag, shouldWake);
}
void FeatherstoneArticulation::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled)
{
if (flag & PxArticulationCacheFlag::eVELOCITY)
{
copyJointData(mArticulationData, cache.jointVelocity, mArticulationData.getJointVelocities());
}
if (flag & PxArticulationCacheFlag::eACCELERATION)
{
copyJointData(mArticulationData, cache.jointAcceleration, mArticulationData.getJointAccelerations());
}
if (flag & PxArticulationCacheFlag::ePOSITION)
{
copyJointData(mArticulationData, cache.jointPosition, mArticulationData.getJointPositions());
}
if (flag & PxArticulationCacheFlag::eFORCE)
{
copyJointData(mArticulationData, cache.jointForce, mArticulationData.getJointForces());
}
if (flag & PxArticulationCacheFlag::eJOINT_SOLVER_FORCES)
{
copyJointData(mArticulationData, cache.jointSolverForces, mArticulationData.getJointConstraintForces());
}
if (flag & PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS)
{
copyJointData(mArticulationData, cache.jointTargetPositions, mArticulationData.getJointTargetPositions());
}
if (flag & PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES)
{
copyJointData(mArticulationData, cache.jointTargetVelocities, mArticulationData.getJointTargetVelocities());
}
if (flag & PxArticulationCacheFlag::eLINK_VELOCITY)
{
const Cm::SpatialVectorF* vels = mArticulationData.getMotionVelocities();
const PxU32 numLinks = mArticulationData.getLinkCount();
for (PxU32 i = 0; i < numLinks; ++i)
{
const Cm::SpatialVectorF& vel = vels[i];
cache.linkVelocity[i].linear = vel.bottom;
cache.linkVelocity[i].angular = vel.top;
}
}
if (flag & PxArticulationCacheFlag::eLINK_ACCELERATION)
{
const PxU32 linkCount = mArticulationData.getLinkCount();
if(mArticulationData.getDt() == 0.0f)
{
PxMemZero(cache.linkAcceleration, sizeof(PxSpatialVelocity)*linkCount);
}
else if(isGpuSimEnabled)
{
const Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin();
//Iterate over all links and compute the acceleration for each link.
for (PxU32 i = 0; i < linkCount; ++i)
{
cache.linkAcceleration[i].linear = linkMotionAccelerationsW[i].bottom;
cache.linkAcceleration[i].angular = linkMotionAccelerationsW[i].top;
}
}
else
{
const PxReal invDt = 1.0f/mArticulationData.getDt();
const Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin();
const Cm::SpatialVectorF* linkSpatialDeltaVelsW = mArticulationData.mSolverLinkSpatialDeltaVels.begin();
//Iterate over all links and compute the acceleration for each link.
for (PxU32 i = 0; i < linkCount; ++i)
{
cache.linkAcceleration[i].linear = linkMotionAccelerationsW[i].bottom + linkSpatialDeltaVelsW[i].bottom*invDt;
cache.linkAcceleration[i].angular = linkMotionAccelerationsW[i].top + linkSpatialDeltaVelsW[i].top*invDt;
}
}
}
if(flag & PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE)
{
const PxU32 linkCount = mArticulationData.getLinkCount();
if (mArticulationData.getDt() == 0.0f)
{
PxMemZero(cache.linkIncomingJointForce, sizeof(PxSpatialForce)*linkCount);
}
else if(isGpuSimEnabled)
{
//Calculation already completed on gpu.
const Cm::SpatialVectorF* incomingJointForces = mArticulationData.getLinkIncomingJointForces();
//Root links have no incoming joint.
cache.linkIncomingJointForce[0].force = PxVec3(PxZero);
cache.linkIncomingJointForce[0].torque = PxVec3(PxZero);
//Iterate over all links and get the incoming joint force for each link.
for (PxU32 i = 1; i < linkCount; ++i)
{
cache.linkIncomingJointForce[i].force = incomingJointForces[i].top;
cache.linkIncomingJointForce[i].torque = incomingJointForces[i].bottom;
}
}
else
{
const PxReal invDt = 1.0f/mArticulationData.getDt();
//Get everything we need.
const Cm::SpatialVectorF* linkZAForcesExtW = mArticulationData.mZAForces.begin();
const Cm::SpatialVectorF* linkZAForcesIntW = mArticulationData.mZAInternalForces.begin();
const Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin();
const SpatialMatrix* linkSpatialInertiasW = mArticulationData.mWorldSpatialArticulatedInertia.begin();
const Cm::SpatialVectorF* linkSpatialDeltaVelsW = mArticulationData.mSolverLinkSpatialDeltaVels.begin();
const Cm::SpatialVectorF* linkSpatialImpulsesW = mArticulationData.mSolverLinkSpatialImpulses.begin();
//Root links have no incoming joint.
cache.linkIncomingJointForce[0].force = PxVec3(PxZero);
cache.linkIncomingJointForce[0].torque = PxVec3(PxZero);
//Iterate over all links and compute the incoming joint force for each link.
for (PxU32 i = 1; i < linkCount; ++i)
{
const ArticulationLink& link = mArticulationData.getLink(i);
const ArticulationJointCore* joint = link.inboundJoint;
const PxTransform Gc = link.bodyCore->body2World;
const PxTransform Lc = joint->childPose;
const PxTransform GcLc = Gc*Lc;
const PxVec3 dW = Gc.rotate(Lc.p);
//Compute the force measured at the link.
const Cm::SpatialVectorF incomingJointForceAtLinkW =
linkSpatialInertiasW[i]*(linkMotionAccelerationsW[i] + linkSpatialDeltaVelsW[i]*invDt) +
(linkZAForcesExtW[i] + linkZAForcesIntW[i] + linkSpatialImpulsesW[i]*invDt);
//Compute the equivalent force measured at the joint.
const Cm::SpatialVectorF incomingJointForceAtJointW =
FeatherstoneArticulation::translateSpatialVector(-dW, incomingJointForceAtLinkW);
//Transform the force to the child joint frame.
cache.linkIncomingJointForce[i].force = GcLc.rotateInv(incomingJointForceAtJointW.top);
cache.linkIncomingJointForce[i].torque = GcLc.rotateInv(incomingJointForceAtJointW.bottom);
}
}
}
if (flag & PxArticulationCacheFlag::eROOT_TRANSFORM)
{
const ArticulationLink& rLink = mArticulationData.getLink(0);
const PxsBodyCore& rBodyCore = *rLink.bodyCore;
const PxTransform& body2World = rBodyCore.body2World;
// PT:: tag: scalar transform*transform
cache.rootLinkData->transform = body2World * rBodyCore.getBody2Actor().getInverse();
}
if (flag & PxArticulationCacheFlag::eROOT_VELOCITIES)
{
const Cm::SpatialVectorF& vel = mArticulationData.getMotionVelocity(0);
cache.rootLinkData->worldLinVel = vel.bottom;
cache.rootLinkData->worldAngVel = vel.top;
const Cm::SpatialVectorF& accel = mArticulationData.getMotionAcceleration(0);
cache.rootLinkData->worldLinAccel = accel.bottom;
cache.rootLinkData->worldAngAccel = accel.top;
}
if (flag & PxArticulationCacheFlag::eSENSOR_FORCES)
{
const PxU32 nbSensors = mArticulationData.mNbSensors;
PxMemCopy(cache.sensorForces, mArticulationData.mSensorForces, sizeof(PxSpatialForce)*nbSensors);
}
}
PxU32 FeatherstoneArticulation::getCacheDataSize(PxU32 totalDofs, PxU32 linkCount, PxU32 sensorCount)
{
const PxU32 totalSize =
sizeof(PxSpatialForce) * linkCount // external force
+ sizeof(PxSpatialForce) * sensorCount // sensors (PxArticulationCacheFlag::eSENSOR_FORCES)
+ sizeof(PxReal) * (6 + totalDofs) * (linkCount * 6) // Free floating base dofs = 6 + totalDofs, and each link (incl. base) velocity has 6 elements
// == offset to end of dense jacobian (assuming free floating base)
+ sizeof(PxReal) * totalDofs * totalDofs // mass matrix
+ sizeof(PxReal) * totalDofs * 7 // jointVelocity (PxArticulationCacheFlag::eVELOCITY)
// jointAcceleration (PxArticulationCacheFlag::eACCELERATION)
// jointPosition (PxArticulationCacheFlag::ePOSITION)
// joint force (PxArticulationCacheFlag::eFORCE)
// joint constraint force (PxArticulationCacheFlag::eJOINT_SOLVER_FORCES)
// joint target positions (PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS)
// joint target velocities (PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES)
+ sizeof(PxSpatialVelocity) * linkCount * 2 // link velocity, (PxArticulationCacheFlag::eLINK_VELOCITY)
// link acceleration (PxArticulationCacheFlag::eLINK_ACCELERATION)
+ sizeof(PxSpatialForce) * linkCount // link incoming joint forces (PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE)
+ sizeof(PxArticulationRootLinkData); // root link data (PxArticulationCacheFlag::eROOT_TRANSFORM, PxArticulationCacheFlag::eROOT_VELOCITIES)
return totalSize;
}
// AD: attention - some of the types here have 16B alignment requirements.
// But the size of PxArticulationCache is not necessarily a multiple of 16B.
PX_COMPILE_TIME_ASSERT(sizeof(Cm::SpatialVector)==sizeof(PxSpatialForce));
PxArticulationCache* FeatherstoneArticulation::createCache(PxU32 totalDofs, PxU32 linkCount, PxU32 sensorCount)
{
const PxU32 pxArticulationCacheSize16BAligned = (sizeof(PxArticulationCache) + 15) & ~15;
const PxU32 totalSize = getCacheDataSize(totalDofs, linkCount, sensorCount) + pxArticulationCacheSize16BAligned;
PxU8* tCache = reinterpret_cast<PxU8*>(PX_ALLOC(totalSize, "Articulation cache"));
PX_ASSERT(((size_t)tCache & 15) == 0);
PxMemZero(tCache, totalSize);
PxArticulationCache* cache = reinterpret_cast<PxArticulationCache*>(tCache);
PxU32 offset = pxArticulationCacheSize16BAligned;
// the following code assumes that the size of PxSpatialForce and PxSpatialVelocity are multiples of 16B
PX_COMPILE_TIME_ASSERT((sizeof(PxSpatialForce) & 15) == 0);
PX_COMPILE_TIME_ASSERT((sizeof(PxSpatialVelocity) & 15) == 0);
// PT: filled in FeatherstoneArticulation::getGeneralizedExternalForce, size = mArticulationData.getLinkCount()
// 16B aligned
PX_ASSERT((offset & 15) == 0);
cache->externalForces = reinterpret_cast<PxSpatialForce*>(tCache + offset);
offset += sizeof(PxSpatialForce) * linkCount;
// PT: PxArticulationCacheFlag::eSENSOR_FORCES
// 16B aligned
PX_ASSERT((offset & 15) == 0);
cache->sensorForces = reinterpret_cast<PxSpatialForce*>(tCache + offset);
offset += sizeof(PxSpatialForce) * sensorCount;
// PT: PxArticulationCacheFlag::eLINK_VELOCITY
// 16B aligned
PX_ASSERT((offset & 15) == 0);
cache->linkVelocity = reinterpret_cast<PxSpatialVelocity*>(tCache + offset);
offset += sizeof(PxSpatialVelocity) * linkCount;
// PT: PxArticulationCacheFlag::eLINK_ACCELERATION
// 16B aligned
PX_ASSERT((offset & 15) == 0);
cache->linkAcceleration = reinterpret_cast<PxSpatialVelocity*>(tCache + offset);
offset += sizeof(PxSpatialVelocity) * linkCount;
// PT: PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE
// 16B aligned
PX_ASSERT((offset & 15) == 0);
cache->linkIncomingJointForce = reinterpret_cast<PxSpatialForce*>(tCache + offset);
offset += sizeof(PxSpatialForce) * linkCount;
cache->denseJacobian = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * (6 + totalDofs) * (linkCount * 6); //size of dense jacobian assuming free floating base link.
cache->massMatrix = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs * totalDofs;
// PT: PxArticulationCacheFlag::eVELOCITY
cache->jointVelocity = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PT: PxArticulationCacheFlag::eACCELERATION
cache->jointAcceleration = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PT: PxArticulationCacheFlag::ePOSITION
cache->jointPosition = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PT: PxArticulationCacheFlag::eFORCE
cache->jointForce = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PT: PxArticulationCacheFlag::eJOINT_SOLVER_FORCES
cache->jointSolverForces = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS
cache->jointTargetPositions = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES
cache->jointTargetVelocities = reinterpret_cast<PxReal*>(tCache + offset);
offset += sizeof(PxReal) * totalDofs;
// PT: PxArticulationCacheFlag::eROOT_TRANSFORM, PxArticulationCacheFlag::eROOT_VELOCITIES
cache->rootLinkData = reinterpret_cast<PxArticulationRootLinkData*>(tCache + offset);
PX_ASSERT((offset + sizeof(PxArticulationRootLinkData)) == totalSize);
cache->coefficientMatrix = NULL;
cache->lambda = NULL;
PxU32 scratchMemorySize =
sizeof(Cm::SpatialVectorF) * linkCount * 5 //motionVelocity, motionAccelerations, coriolisVectors, spatialZAVectors, externalAccels;
+ sizeof(Dy::SpatialMatrix) * linkCount //compositeSpatialInertias;
+ sizeof(PxReal) * totalDofs * 7; //jointVelocity, jointAcceleration, jointForces, jointPositions, jointFrictionForces, jointTargetPositions, jointTargetVelocities
scratchMemorySize = (scratchMemorySize+15)&~15;
void* scratchMemory = PX_ALLOC(scratchMemorySize, "Cache scratch memory");
cache->scratchMemory = scratchMemory;
PxcScratchAllocator* sa = PX_NEW(PxcScratchAllocator);
sa->setBlock(scratchMemory, scratchMemorySize);
cache->scratchAllocator = sa;
return cache;
}
static PX_FORCE_INLINE Mat33V loadPxMat33(const PxMat33& m)
{
return Mat33V(Vec3V_From_Vec4V(V4LoadU(&m.column0.x)),
Vec3V_From_Vec4V(V4LoadU(&m.column1.x)), V3LoadU(&m.column2.x));
}
static PX_FORCE_INLINE void storePxMat33(const Mat33V& src, PxMat33& dst)
{
V3StoreU(src.col0, dst.column0);
V3StoreU(src.col1, dst.column1);
V3StoreU(src.col2, dst.column2);
}
void FeatherstoneArticulation::transformInertia(const SpatialTransform& sTod, SpatialMatrix& spatialInertia)
{
#if 1
const SpatialTransform dTos = sTod.getTranspose();
Mat33V tL = loadPxMat33(spatialInertia.topLeft);
Mat33V tR = loadPxMat33(spatialInertia.topRight);
Mat33V bL = loadPxMat33(spatialInertia.bottomLeft);
Mat33V R = loadPxMat33(sTod.R);
Mat33V T = loadPxMat33(sTod.T);
Mat33V tl = M33MulM33(R, tL);
Mat33V tr = M33MulM33(R, tR);
Mat33V bl = M33Add(M33MulM33(T, tL), M33MulM33(R, bL));
Mat33V br = M33Add(M33MulM33(T, tR), M33MulM33(R, M33Trnsps(tL)));
Mat33V dR = loadPxMat33(dTos.R);
Mat33V dT = loadPxMat33(dTos.T);
tL = M33Add(M33MulM33(tl, dR), M33MulM33(tr, dT));
tR = M33MulM33(tr, dR);
bL = M33Add(M33MulM33(bl, dR), M33MulM33(br, dT));
bL = M33Scale(M33Add(bL, M33Trnsps(bL)), FHalf());
storePxMat33(tL, spatialInertia.topLeft);
storePxMat33(tR, spatialInertia.topRight);
storePxMat33(bL, spatialInertia.bottomLeft);
#else
const SpatialTransform dTos = sTod.getTranspose();
PxMat33 tl = sTod.R * spatialInertia.topLeft;
PxMat33 tr = sTod.R * spatialInertia.topRight;
PxMat33 bl = sTod.T * spatialInertia.topLeft + sTod.R * spatialInertia.bottomLeft;
PxMat33 br = sTod.T * spatialInertia.topRight + sTod.R * spatialInertia.getBottomRight();
spatialInertia.topLeft = tl * dTos.R + tr * dTos.T;
spatialInertia.topRight = tr * dTos.R;
spatialInertia.bottomLeft = bl * dTos.R + br * dTos.T;
//aligned inertia
spatialInertia.bottomLeft = (spatialInertia.bottomLeft + spatialInertia.bottomLeft.getTranspose()) * 0.5f;
#endif
}
PxMat33 FeatherstoneArticulation::translateInertia(const PxMat33& inertia, const PxReal mass, const PxVec3& t)
{
PxMat33 s(PxVec3(0, t.z, -t.y),
PxVec3(-t.z, 0, t.x),
PxVec3(t.y, -t.x, 0));
PxMat33 translatedIT = s.getTranspose() * s * mass + inertia;
return translatedIT;
}
void FeatherstoneArticulation::translateInertia(const PxMat33& sTod, SpatialMatrix& inertia)
{
#if 1
Mat33V sTodV = loadPxMat33(sTod);
Mat33V dTos = M33Trnsps(sTodV);
const Mat33V tL = loadPxMat33(inertia.topLeft);
const Mat33V tR = loadPxMat33(inertia.topRight);
const Mat33V bL = loadPxMat33(inertia.bottomLeft);
const Mat33V bl = M33Add(M33MulM33(sTodV, tL), bL);
const Mat33V br = M33Add(M33MulM33(sTodV, tR), M33Trnsps(tL));
const Mat33V bottomLeft = M33Add(bl, M33MulM33(br, dTos));
storePxMat33(M33Add(tL, M33MulM33(tR, dTos)), inertia.topLeft);
storePxMat33(M33Scale(M33Add(bottomLeft, M33Trnsps(bottomLeft)), FHalf()), inertia.bottomLeft);
#else
const PxMat33 dTos = sTod.getTranspose();
PxMat33 bl = sTod * inertia.topLeft + inertia.bottomLeft;
PxMat33 br = sTod * inertia.topRight + inertia.getBottomRight();
inertia.topLeft = inertia.topLeft + inertia.topRight * dTos;
inertia.bottomLeft = bl + br * dTos;
//aligned inertia - make it symmetrical! OPTIONAL!!!!
inertia.bottomLeft = (inertia.bottomLeft + inertia.bottomLeft.getTranspose()) * 0.5f;
#endif
}
void FeatherstoneArticulation::getImpulseResponse(
PxU32 linkID,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse,
Cm::SpatialVector& deltaVV) const
{
PX_UNUSED(Z);
PX_ASSERT(impulse.pad0 == 0.f && impulse.pad1 == 0.f);
//impulse lin is contact normal, and ang is raxn. R is body2World, R(t) is world2Body
//| R(t), 0 |
//| R(t)*r, R(t)|
//r is the vector from center of mass to contact point
//p(impluse) = |n|
// |0|
Cm::SpatialVectorF deltaV = mArticulationData.getImpulseResponseMatrixWorld()[linkID].getResponse(reinterpret_cast<const Cm::SpatialVectorF&>(impulse));
deltaVV.linear = deltaV.bottom;
deltaVV.angular = deltaV.top;
}
void FeatherstoneArticulation::getImpulseResponse(
PxU32 linkID,
Cm::SpatialVectorV* /*Z*/,
const Cm::SpatialVectorV& impulse,
Cm::SpatialVectorV& deltaVV) const
{
#if 0
const PxTransform& body2World = mArticulationData.getPreTransform(linkID);
QuatV rot = QuatVLoadU(&body2World.q.x);
Cm::SpatialVectorV impl(QuatRotateInv(rot, impulse.linear), QuatRotateInv(rot, impulse.angular));
//transform p(impluse) from world space to the local space of linkId
//Cm::SpatialVectorF impl(impulse.linear, impulse.angular);
Cm::SpatialVectorV deltaV = mArticulationData.getImpulseResponseMatrix()[linkID].getResponse(impl);
deltaVV.linear = QuatRotate(rot, deltaV.angular);
deltaVV.angular = QuatRotate(rot, deltaV.linear);
#else
Cm::SpatialVectorV deltaV = mArticulationData.getImpulseResponseMatrixWorld()[linkID].getResponse(impulse);
deltaVV.linear = deltaV.angular;
deltaVV.angular = deltaV.linear;
#endif
}
//This will return world space SpatialVectorV
Cm::SpatialVectorV FeatherstoneArticulation::getLinkVelocity(const PxU32 linkID) const
{
//This is in the world space
const Cm::SpatialVectorF& motionVelocity = mArticulationData.getMotionVelocity(linkID);
Cm::SpatialVectorV velocity;
velocity.linear = V3LoadA(motionVelocity.bottom);
velocity.angular = V3LoadA(motionVelocity.top);
return velocity;
}
Cm::SpatialVector FeatherstoneArticulation::getLinkScalarVelocity(const PxU32 linkID) const
{
//This is in the world space
const Cm::SpatialVectorF& motionVelocity = mArticulationData.getMotionVelocity(linkID);
return Cm::SpatialVector(motionVelocity.bottom, motionVelocity.top);
}
Cm::SpatialVectorV FeatherstoneArticulation::getLinkMotionVector(const PxU32 linkID) const
{
const Cm::SpatialVectorF& motionVector = mArticulationData.getDeltaMotionVector(linkID);
Cm::SpatialVectorV velocity;
velocity.linear = V3LoadU(motionVector.bottom);
velocity.angular = V3LoadU(motionVector.top);
return velocity;
}
//this is called by island gen to determine whether the articulation should be awake or sleep
Cm::SpatialVector FeatherstoneArticulation::getMotionVelocity(const PxU32 linkID) const
{
//This is in the world space
const Cm::SpatialVectorF& motionVelocity = mArticulationData.getPosIterMotionVelocities()[linkID];
return Cm::SpatialVector(motionVelocity.bottom, motionVelocity.top);
}
Cm::SpatialVector FeatherstoneArticulation::getMotionAcceleration(const PxU32 linkID, const bool isGpuSimEnabled) const
{
Cm::SpatialVector a = Cm::SpatialVector::zero();
if(mArticulationData.getDt() > 0.0f)
{
if(isGpuSimEnabled)
{
const Cm::SpatialVectorF& linkAccel = mArticulationData.mMotionAccelerations[linkID];
a = Cm::SpatialVector(linkAccel.bottom, linkAccel.top);
}
else
{
const PxReal invDt = 1.0f/mArticulationData.getDt();
const Cm::SpatialVectorF linkAccel =
mArticulationData.mMotionAccelerations[linkID] + mArticulationData.mSolverLinkSpatialDeltaVels[linkID]*invDt;
a = Cm::SpatialVector(linkAccel.bottom, linkAccel.top);
}
}
return a;
}
void FeatherstoneArticulation::fillIndexType(const PxU32 linkId, PxU8& indexType)
{
ArticulationLink& link = mArticulationData.getLink(linkId);
//turn the fixed-base links to static for the solver
if(link.bodyCore->fixedBaseLink)
indexType = PxsIndexedInteraction::eWORLD;
else
indexType = PxsIndexedInteraction::eARTICULATION;
}
PxReal FeatherstoneArticulation::getLinkMaxPenBias(const PxU32 linkID) const
{
return mArticulationData.getLinkData(linkID).maxPenBias;
}
PxReal FeatherstoneArticulation::getCfm(const PxU32 linkID) const
{
return mArticulationData.getLink(linkID).cfm;
}
void PxcFsFlushVelocity(FeatherstoneArticulation& articulation, Cm::SpatialVectorF* deltaV, bool computeForces)
{
PX_ASSERT(deltaV);
ArticulationData& data = articulation.mArticulationData;
const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities();
//Cm::SpatialVectorF* deferredZ = data.getSpatialZAVectors();
ArticulationLink* links = data.getLinks();
ArticulationJointCoreData* jointData = data.getJointData();
//PxTransform* poses = data.getAccumulatedPoses();
//const PxTransform* poses = data.getPreTransform();
//This will be zero at the begining of the frame
PxReal* jointNewVelocities = data.getJointNewVelocities();
data.getSolverSpatialForce(0) -= data.getRootDeferredZ();
if (fixBase)
{
deltaV[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
}
else
{
//ArticulationLink& link = links[0];
deltaV[0] = data.getBaseInvSpatialArticulatedInertiaW() * -data.getRootDeferredZ();
motionVelocities[0] += deltaV[0];
PX_ASSERT(motionVelocities[0].isFinite());
}
const PxU32 linkCount = data.getLinkCount();
for (PxU32 i = 1; i < linkCount; i++)
{
const ArticulationLink& tLink = links[i];
const ArticulationJointCoreData& tJointDatum = jointData[i];
const Cm::SpatialVectorF dV = FeatherstoneArticulation::propagateAccelerationW(data.getRw(i), data.getInvStIs(i),
&data.getWorldMotionMatrix(tJointDatum.jointOffset), &jointNewVelocities[tJointDatum.jointOffset], deltaV[tLink.parent], tJointDatum.dof,
&data.getIsW(tJointDatum.jointOffset), &data.getDeferredQstZ()[tJointDatum.jointOffset]);
deltaV[i] = dV;
motionVelocities[i] += dV;
//Cm::SpatialVectorF& v = motionVelocities[i];
//printf("linkID %i motionV(%f, %f, %f, %f, %f, %f)\n", i, v.top.x, v.top.y, v.top.z, v.bottom.x, v.bottom.y, v.bottom.z);
/*if(computeForces)
data.getSolverSpatialForce(i) += data.getWorldSpatialArticulatedInertia(i) * dV;*/
data.incrementSolverSpatialDeltaVel(i, dV);
if (computeForces)
data.getSolverSpatialForce(i) += dV;
PX_ASSERT(motionVelocities[i].isFinite());
}
//PxMemZero(deferredZ, sizeof(Cm::SpatialVectorF)*linkCount);
PxMemZero(data.getDeferredQstZ(), sizeof(PxReal) * data.getDofs());
data.getRootDeferredZ() = Cm::SpatialVectorF::Zero();
}
void FeatherstoneArticulation::recordDeltaMotion(const ArticulationSolverDesc& desc,
const PxReal dt, Cm::SpatialVectorF* deltaV, const PxReal /*totalInvDt*/)
{
PX_ASSERT(deltaV);
FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation);
ArticulationData& data = articulation->mArticulationData;
const PxU32 linkCount = data.getLinkCount();
const PxU32 flags = data.getArticulationFlags();
if (data.mJointDirty)
{
bool doForces = (flags & PxArticulationFlag::eCOMPUTE_JOINT_FORCES) || data.getSensorCount();
PxcFsFlushVelocity(*articulation, deltaV, doForces);
}
Cm::SpatialVectorF* deltaMotion = data.getDeltaMotionVector();
Cm::SpatialVectorF* posMotionVelocities = data.getPosIterMotionVelocities();
Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities();
PxReal* jointPosition = data.getJointPositions();
PxReal* jointNewVelocities = data.getJointNewVelocities();
//data.mAccumulatedDt += dt;
data.setDt(dt);
const bool fixBase = flags & PxArticulationFlag::eFIX_BASE;
if (!fixBase)
{
Cm::SpatialVectorF& motionVelocity = motionVelocities[0];
PX_ASSERT(motionVelocity.top.isFinite());
PX_ASSERT(motionVelocity.bottom.isFinite());
const PxTransform preTrans = data.mAccumulatedPoses[0];
const PxVec3 lin = motionVelocity.bottom;
const PxVec3 ang = motionVelocity.top;
const PxVec3 newP = preTrans.p + lin * dt;
const PxTransform newPose = PxTransform(newP, PxExp(ang*dt) * preTrans.q);
//PxVec3 lin, ang;
/*calculateNewVelocity(newPose, data.mPreTransform[0],
1.f, lin, ang); */
data.mAccumulatedPoses[0] = newPose;
PxQuat dq = newPose.q * data.mPreTransform[0].q.getConjugate();
if (dq.w < 0.f)
dq = -dq;
data.mDeltaQ[0] = dq;
Cm::SpatialVectorF delta = motionVelocity * dt;
deltaMotion[0] += delta;
posMotionVelocities[0] += delta;
}
for (PxU32 linkID = 1; linkID < linkCount; linkID++)
{
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
const PxTransform newPose = articulation->propagateTransform(linkID, data.getLinks(), jointDatum, data.getMotionVelocities(),
dt, data.mAccumulatedPoses[data.getLink(linkID).parent], data.mAccumulatedPoses[linkID],
jointNewVelocities, jointPosition, &data.getMotionMatrix(jointDatum.jointOffset), &data.getWorldMotionMatrix(jointDatum.jointOffset));
//data.mDeltaQ[linkID] = data.mPreTransform[linkID].q.getConjugate() * newPose.q;
PxQuat dq = newPose.q * data.mPreTransform[linkID].q.getConjugate();
if(dq.w < 0.f)
dq = -dq;
data.mDeltaQ[linkID] = dq;
/*PxVec3 lin, ang;
calculateNewVelocity(newPose, data.mPreTransform[linkID],
1.f, lin, ang);*/
PxVec3 lin = (newPose.p - data.mPreTransform[linkID].p);
Cm::SpatialVectorF delta = motionVelocities[linkID] * dt;
//deltaMotion[linkID].top = ang;// motionVeloties[linkID].top * dt;
deltaMotion[linkID].top += delta.top;
deltaMotion[linkID].bottom = lin;// motionVeloties[linkID].top * dt;
posMotionVelocities[linkID] += delta;
//Record the new current pose
data.mAccumulatedPoses[linkID] = newPose;
}
}
void FeatherstoneArticulation::deltaMotionToMotionVelocity(const ArticulationSolverDesc& desc, PxReal invDt)
{
FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation);
ArticulationData& data = articulation->mArticulationData;
const PxU32 linkCount = data.getLinkCount();
const Cm::SpatialVectorF* deltaMotion = data.getDeltaMotionVector();
for (PxU32 linkID = 0; linkID<linkCount; linkID++)
{
Cm::SpatialVectorF& v = data.getMotionVelocity(linkID);
Cm::SpatialVectorF delta = deltaMotion[linkID] * invDt;
v = delta;
desc.motionVelocity[linkID] = reinterpret_cast<Cm::SpatialVectorV&>(delta);
}
}
//This is used in the solveExt1D, solveExtContact
Cm::SpatialVectorV FeatherstoneArticulation::pxcFsGetVelocity(PxU32 linkID)
{
//Cm::SpatialVectorF* deferredZ = mArticulationData.getSpatialZAVectors();
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
ArticulationLink* links = mArticulationData.getLinks();
Cm::SpatialVectorF deltaV(PxVec3(0.f), PxVec3(0.f));
if (!fixBase)
{
//deltaV = mArticulationData.mBaseInvSpatialArticulatedInertia * (-deferredZ[0]);
//DeferredZ now in world space!
deltaV = mArticulationData.mBaseInvSpatialArticulatedInertiaW * -mArticulationData.getRootDeferredZ();
}
const PxU32 startIndex = links[linkID].mPathToRootStartIndex;
const PxU32 elementCount = links[linkID].mPathToRootCount;
const PxU32* pathToRootElements = &mArticulationData.mPathToRootElements[startIndex];
for (PxU32 i = 0; i < elementCount; ++i)
{
const PxU32 index = pathToRootElements[i];
PX_ASSERT(links[index].parent < index);
const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(index).dof;
deltaV = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index],
&mArticulationData.mWorldMotionMatrix[jointOffset], deltaV, dofCount, &mArticulationData.mIsW[jointOffset],
&mArticulationData.mDeferredQstZ[jointOffset]);
}
Cm::SpatialVectorF vel = mArticulationData.getMotionVelocity(linkID) + deltaV;
return Cm::SpatialVector(vel.bottom, vel.top);
}
void FeatherstoneArticulation::pxcFsGetVelocities(PxU32 linkID, PxU32 linkID1, Cm::SpatialVectorV& v0, Cm::SpatialVectorV& v1)
{
{
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
ArticulationLink* links = mArticulationData.getLinks();
Cm::SpatialVectorF deltaV(PxVec3(0.f), PxVec3(0.f));
if (!fixBase)
{
//deltaV = mArticulationData.mBaseInvSpatialArticulatedInertia * (-deferredZ[0]);
deltaV = mArticulationData.mBaseInvSpatialArticulatedInertiaW * (-mArticulationData.mRootDeferredZ);
}
const PxU32* pathToRootElements = mArticulationData.mPathToRootElements;
Dy::ArticulationLink& link0 = links[linkID];
Dy::ArticulationLink& link1 = links[linkID1];
const PxU32* pathToRoot0 = &pathToRootElements[link0.mPathToRootStartIndex];
const PxU32* pathToRoot1 = &pathToRootElements[link1.mPathToRootStartIndex];
const PxU32 numElems0 = link0.mPathToRootCount;
const PxU32 numElems1 = link1.mPathToRootCount;
PxU32 offset = 0;
while (pathToRoot0[offset] == pathToRoot1[offset])
{
const PxU32 index = pathToRoot0[offset++];
PX_ASSERT(links[index].parent < index);
if (offset >= numElems0 || offset >= numElems1)
break;
const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(index).dof;
deltaV = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index],
&mArticulationData.mWorldMotionMatrix[jointOffset], deltaV, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]);
}
Cm::SpatialVectorF deltaV1 = deltaV;
for (PxU32 idx = offset; idx < numElems0; ++idx)
{
const PxU32 index = pathToRoot0[idx];
PX_ASSERT(links[index].parent < index);
const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(index).dof;
deltaV = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index],
&mArticulationData.mWorldMotionMatrix[jointOffset], deltaV, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]);
}
for (PxU32 idx = offset; idx < numElems1; ++idx)
{
const PxU32 index = pathToRoot1[idx];
PX_ASSERT(links[index].parent < index);
const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(index).dof;
deltaV1 = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index],
&mArticulationData.mWorldMotionMatrix[jointOffset], deltaV1, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]);
}
Cm::SpatialVectorF vel = mArticulationData.getMotionVelocity(linkID) + deltaV;
v0 = Cm::SpatialVector(vel.bottom, vel.top);
Cm::SpatialVectorF vel1 = mArticulationData.getMotionVelocity(linkID1) + deltaV1;
v1 = Cm::SpatialVector(vel1.bottom, vel1.top);
}
}
/*Cm::SpatialVectorV FeatherstoneArticulation::pxcFsGetVelocity(PxU32 linkID)
{
Cm::SpatialVectorF& vel = mArticulationData.getMotionVelocity(linkID);
return Cm::SpatialVector(vel.bottom, vel.top);
}*/
Cm::SpatialVectorV FeatherstoneArticulation::pxcFsGetVelocityTGS(PxU32 linkID)
{
return getLinkVelocity(linkID);
}
//This is used in the solveExt1D, solveExtContact
void FeatherstoneArticulation::pxcFsApplyImpulse(PxU32 linkID,
aos::Vec3V linear, aos::Vec3V angular,
Cm::SpatialVectorF* /*Z*/, Cm::SpatialVectorF* /*deltaV*/)
{
const ArticulationSolverDesc* desc = &mSolverDesc;
ArticulationLink* links = static_cast<ArticulationLink*>(desc->links);
//initialize all zero acceration impulse to be zero
ArticulationData& data = mArticulationData;
data.mJointDirty = true;
//impulse is in world space
Cm::SpatialVector impulse;
V4StoreA(Vec4V_From_Vec3V(angular), &impulse.angular.x);
V4StoreA(Vec4V_From_Vec3V(linear), &impulse.linear.x);
Cm::SpatialVectorF Z0(-impulse.linear, -impulse.angular);
for (PxU32 i = linkID; i; i = links[i].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(i).dof;
data.mSolverLinkSpatialImpulses[i] += Z0;
Z0 = FeatherstoneArticulation::propagateImpulseW(
mArticulationData.getRw(i),
Z0,
&data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount,
&mArticulationData.mDeferredQstZ[jointOffset]);
}
data.mRootDeferredZ += Z0;
}
void FeatherstoneArticulation::pxcFsApplyImpulses(Cm::SpatialVectorF* Z)
{
ArticulationLink* links = mArticulationData.getLinks();
//initialize all zero acceration impulse to be zero
ArticulationData& data = mArticulationData;
const PxU32 linkCount = mArticulationData.getLinkCount();
const PxU32 startIndex = PxU32(linkCount - 1);
data.mJointDirty = true;
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
ArticulationLink& tLink = links[linkID];
const PxU32 jointOffset = mArticulationData.getJointData(linkID).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(linkID).dof;
Cm::SpatialVectorF ZA = Z[linkID];
Z[tLink.parent] += propagateImpulseW(
mArticulationData.getRw(linkID),
ZA,
&data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount,
&mArticulationData.mDeferredQstZ[jointOffset]);
}
data.mRootDeferredZ += Z[0];
}
void FeatherstoneArticulation::pxcFsApplyImpulses(PxU32 linkID, const aos::Vec3V& linear,
const aos::Vec3V& angular, PxU32 linkID2, const aos::Vec3V& linear2,
const aos::Vec3V& angular2, Cm::SpatialVectorF* /*Z*/, Cm::SpatialVectorF* /*deltaV*/)
{
if (0)
{
pxcFsApplyImpulse(linkID, linear, angular, NULL, NULL);
pxcFsApplyImpulse(linkID2, linear2, angular2, NULL, NULL);
}
else
{
const ArticulationSolverDesc* desc = &mSolverDesc;
ArticulationData& data = mArticulationData;
data.mJointDirty = true;
ArticulationLink* links = static_cast<ArticulationLink*>(desc->links);
//impulse is in world space
Cm::SpatialVector impulse0;
V3StoreU(angular, impulse0.angular);
V3StoreU(linear, impulse0.linear);
Cm::SpatialVector impulse1;
V3StoreU(angular2, impulse1.angular);
V3StoreU(linear2, impulse1.linear);
Cm::SpatialVectorF Z1(-impulse0.linear, -impulse0.angular);
Cm::SpatialVectorF Z2(-impulse1.linear, -impulse1.angular);
ArticulationLink& link0 = links[linkID];
ArticulationLink& link1 = links[linkID2];
const PxU32* pathToRoot0 = &mArticulationData.mPathToRootElements[link0.mPathToRootStartIndex];
const PxU32* pathToRoot1 = &mArticulationData.mPathToRootElements[link1.mPathToRootStartIndex];
const PxU32 numElems0 = link0.mPathToRootCount;
const PxU32 numElems1 = link1.mPathToRootCount;
//find the common link, work from one to that common, then the other to that common, then go from there upwards...
PxU32 offset = 0;
PxU32 commonLink = 0;
while (pathToRoot0[offset] == pathToRoot1[offset])
{
commonLink = pathToRoot0[offset++];
PX_ASSERT(links[commonLink].parent < commonLink);
if (offset >= numElems0 || offset >= numElems1)
break;
}
//The common link will either be linkID2, or its ancestors.
//The common link cannot be an index before either linkID2 or linkID
for (PxU32 i = linkID2; i != commonLink; i = links[i].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(i).dof;
Z2 = propagateImpulseW(
mArticulationData.getRw(i),
Z2,
&data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount,
&data.mDeferredQstZ[jointOffset]);
}
for (PxU32 i = linkID; i != commonLink; i = links[i].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(i).dof;
Z1 = propagateImpulseW(
mArticulationData.getRw(i),
Z1,
&data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset],dofCount,
&data.mDeferredQstZ[jointOffset]);
}
Cm::SpatialVectorF ZCommon = Z1 + Z2;
for (PxU32 i = commonLink; i; i = links[i].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(i).dof;
ZCommon = propagateImpulseW(
mArticulationData.getRw(i),
ZCommon,
&data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount,
&data.mDeferredQstZ[jointOffset]);
}
data.mRootDeferredZ += ZCommon;
}
}
//Z is the link space(drag force)
void FeatherstoneArticulation::applyImpulses(Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV)
{
ArticulationLink* links = mArticulationData.getLinks();
//initialize all zero acceration impulse to be zero
ArticulationData& data = mArticulationData;
const PxU32 linkCount = mArticulationData.getLinkCount();
const PxU32 startIndex = PxU32(linkCount - 1);
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
ArticulationLink& tLink = links[linkID];
const PxU32 jointOffset = mArticulationData.getJointData(linkID).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(linkID).dof;
Z[tLink.parent] += propagateImpulseW(
mArticulationData.getRw(linkID),
Z[linkID],
&data.mISInvStIS[jointOffset],&data.mWorldMotionMatrix[jointOffset], dofCount);
}
getDeltaV(Z, deltaV);
}
void FeatherstoneArticulation::getDeltaV(Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV)
{
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
Cm::SpatialVectorF* motionVelocities = mArticulationData.getMotionVelocities();
ArticulationLink* links = mArticulationData.getLinks();
ArticulationJointCoreData* jointData = mArticulationData.getJointData();
//This will be zero at the begining of the frame
PxReal* jointDeltaVelocities = mArticulationData.getJointNewVelocities();
if (fixBase)
{
deltaV[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
}
else
{
deltaV[0] = mArticulationData.mBaseInvSpatialArticulatedInertiaW * (-Z[0]);
motionVelocities[0] += deltaV[0];
PX_ASSERT(motionVelocities[0].isFinite());
}
const PxU32 linkCount = mArticulationData.getLinkCount();
for (PxU32 i = 1; i < linkCount; i++)
{
ArticulationLink& tLink = links[i];
ArticulationJointCoreData& tJointDatum = jointData[i];
const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(i).dof;
Cm::SpatialVectorF dV = propagateVelocityW(mArticulationData.getRw(i), mArticulationData.mWorldSpatialArticulatedInertia[i],
mArticulationData.mInvStIs[i], &mArticulationData.mWorldMotionMatrix[jointOffset], Z[i], &jointDeltaVelocities[tJointDatum.jointOffset], deltaV[tLink.parent], dofCount);
deltaV[i] = dV;
motionVelocities[i] += dV;
PX_ASSERT(motionVelocities[i].isFinite());
}
}
//This version uses in updateBodies
PxQuat computeSphericalJointPositions(const PxQuat& relativeQuat,
const PxQuat& newRot, const PxQuat& pBody2WorldRot,
PxReal* jPositions, const Cm::UnAlignedSpatialVector* motionMatrix,
const PxU32 dofs);
PxQuat computeSphericalJointPositions(const PxQuat& relativeQuat,
const PxQuat& newRot, const PxQuat& pBody2WorldRot);
PxTransform FeatherstoneArticulation::propagateTransform(const PxU32 linkID, ArticulationLink* links,
ArticulationJointCoreData& jointDatum, Cm::SpatialVectorF* motionVelocities, const PxReal dt, const PxTransform& pBody2World,
const PxTransform& currentTransform, PxReal* jointVelocities, PxReal* jointPositions,
const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::UnAlignedSpatialVector* /*worldMotionMatrix*/)
{
ArticulationLink& link = links[linkID];
const PxQuat relativeQuat = mArticulationData.mRelativeQuat[linkID];
ArticulationJointCore* joint = link.inboundJoint;
PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset];
PxReal* jPosition = &jointPositions[jointDatum.jointOffset];
PxQuat newParentToChild;
PxQuat newWorldQ;
PxVec3 r;
const PxVec3 childOffset = -joint->childPose.p;
const PxVec3 parentOffset = joint->parentPose.p;
switch (joint->jointType)
{
case PxArticulationJointType::ePRISMATIC:
{
PxReal tJointPosition = jPosition[0] + (jVelocity[0]) * dt;
const PxU32 dofId = link.inboundJoint->dofIds[0];
if (link.inboundJoint->motion[dofId] == PxArticulationMotion::eLIMITED)
{
if (tJointPosition < (link.inboundJoint->limits[dofId].low))
tJointPosition = link.inboundJoint->limits[dofId].low;
if (tJointPosition >(link.inboundJoint->limits[dofId].high))
tJointPosition = link.inboundJoint->limits[dofId].high;
}
jPosition[0] = tJointPosition;
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d + motionMatrix[0].bottom * tJointPosition;
break;
}
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
PxReal tJointPosition = jPosition[0] + (jVelocity[0]) * dt;
/*PxU8 dofId = link.inboundJoint->dofIds[0];
if (link.inboundJoint->motion[dofId] == PxArticulationMotion::eLIMITED)
{
if (tJointPosition < (link.inboundJoint->limits[dofId].low))
tJointPosition = link.inboundJoint->limits[dofId].low;
if (tJointPosition >(link.inboundJoint->limits[dofId].high))
tJointPosition = link.inboundJoint->limits[dofId].high;
}*/
jPosition[0] = tJointPosition;
const PxVec3& u = motionMatrix[0].top;
PxQuat jointRotation = PxQuat(-tJointPosition, u);
if (jointRotation.w < 0) //shortest angle.
jointRotation = -jointRotation;
newParentToChild = (jointRotation * relativeQuat).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eSPHERICAL:
{
Cm::SpatialVectorF worldVel = motionVelocities[linkID];
const PxTransform oldTransform = currentTransform;
PxVec3 worldAngVel = worldVel.top;
//PxVec3 worldAngVel = motionVelocities[linkID].top;
PxReal dist = worldAngVel.normalize() * dt;
if (dist > 1e-6f)
newWorldQ = PxQuat(dist, worldAngVel) * oldTransform.q;
else
newWorldQ = oldTransform.q;
//newWorldQ = Ps::exp(worldAngVel*dt) * oldTransform.q;
//PxVec3 axis;
newParentToChild = computeSphericalJointPositions(mArticulationData.mRelativeQuat[linkID], newWorldQ,
pBody2World.q);
PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate();
if(jointRotation.w < 0.0f)
jointRotation = -jointRotation;
/*PxVec3 axis = jointRotation.getImaginaryPart();
for (PxU32 i = 0; i < jointDatum.dof; ++i)
{
PxVec3 sa = mArticulationData.getMotionMatrix(jointDatum.jointOffset + i).top;
PxReal angle = -compAng(sa.dot(axis), jointRotation.w);
jPosition[i] = angle;
}*/
PxVec3 axis; PxReal angle;
jointRotation.toRadiansAndUnitAxis(angle, axis);
axis *= angle;
for (PxU32 i = 0; i < jointDatum.dof; ++i)
{
PxVec3 sa = mArticulationData.getMotionMatrix(jointDatum.jointOffset + i).top;
PxReal ang = -sa.dot(axis);
jPosition[i] = ang;
}
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eFIX:
{
//this is fix joint so joint don't have velocity
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
break;
}
default:
break;
}
PxTransform cBody2World;
cBody2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized();
cBody2World.p = pBody2World.p + cBody2World.q.rotate(r);
PX_ASSERT(cBody2World.isSane());
return cBody2World;
}
const PxTransform& FeatherstoneArticulation::getCurrentTransform(PxU32 linkID) const
{
return mArticulationData.mAccumulatedPoses[linkID];
}
const PxQuat& FeatherstoneArticulation::getDeltaQ(PxU32 linkID) const
{
return mArticulationData.mDeltaQ[linkID];
}
////Z is the spatial acceleration impulse of links[linkID]
//Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocity(const Dy::SpatialTransform& c2p, const Dy::SpatialMatrix& spatialInertia,
// const InvStIs& invStIs, const SpatialSubspaceMatrix& motionMatrix, const Cm::SpatialVectorF& Z, PxReal* jointVelocity, const Cm::SpatialVectorF& hDeltaV)
//{
// const PxU32 dofCount = motionMatrix.getNumColumns();
// Cm::SpatialVectorF pDeltaV = c2p.transposeTransform(hDeltaV); //parent velocity change
// Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z;
// PxReal tJointDelta[6];
// for (PxU32 ind = 0; ind < dofCount; ++ind)
// {
// const Cm::SpatialVectorF& sa = motionMatrix[ind];
// tJointDelta[ind] = -sa.innerProduct(temp);
// }
// Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f));
// for (PxU32 ind = 0; ind < dofCount; ++ind)
// {
// PxReal jDelta = 0.f;
// for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
// {
// jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2];
// }
// jointVelocity[ind] += jDelta;
// const Cm::SpatialVectorF& sa = motionMatrix[ind];
// jointSpatialDeltaV += sa * jDelta;
// }
// return pDeltaV + jointSpatialDeltaV;
//}
////This method calculate the velocity change due to collision/constraint impulse
//Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocityTestImpulse(const Dy::SpatialTransform& c2p, const Dy::SpatialMatrix& spatialInertia,
// const InvStIs& invStIs, const SpatialSubspaceMatrix& motionMatrix, const Cm::SpatialVectorF& Z,
// const Cm::SpatialVectorF& hDeltaV)
//{
// const PxU32 dofCount = motionMatrix.getNumColumns();
// Cm::SpatialVectorF pDeltaV = c2p.transposeTransform(hDeltaV); //parent velocity change
// Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z;
// PxReal tJointDelta[6];
// for (PxU32 ind = 0; ind < dofCount; ++ind)
// {
// const Cm::SpatialVectorF& sa = motionMatrix[ind];
// tJointDelta[ind] = -sa.innerProduct(temp);
// }
// Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f));
// for (PxU32 ind = 0; ind < dofCount; ++ind)
// {
// PxReal jDelta = 0.f;
// for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
// {
// jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2];
// }
// const Cm::SpatialVectorF& sa = motionMatrix[ind];
// jointSpatialDeltaV += sa * jDelta;
// }
// return pDeltaV + jointSpatialDeltaV;
//}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF translateImpulse(const Cm::SpatialVectorF& s, const PxVec3& offset)
{
return Cm::SpatialVectorF(s.top, offset.cross(s.top) + s.bottom);
}
//This method calculate the velocity change due to collision/constraint impulse, record joint velocity and acceleration
Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocityW(const PxVec3& c2p, const Dy::SpatialMatrix& spatialInertia,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& Z,
PxReal* jointVelocity, const Cm::SpatialVectorF& hDeltaV, const PxU32 dofCount)
{
Cm::SpatialVectorF pDeltaV = translateImpulse(hDeltaV, -c2p); //parent velocity change
Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z;
PxReal tJointDelta[6];
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind];
tJointDelta[ind] = -sa.innerProduct(temp);
}
Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f));
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
PxReal jDelta = 0.f;
for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
{
jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2];
}
jointVelocity[ind] += jDelta;
const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind];
jointSpatialDeltaV.top += sa.top * jDelta;
jointSpatialDeltaV.bottom += sa.bottom * jDelta;
}
return pDeltaV + jointSpatialDeltaV;
}
Cm::SpatialVectorF FeatherstoneArticulation::propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix,
PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration, const PxU32 dofCount, const Cm::SpatialVectorF* IsW, PxReal* qstZIc)
{
Cm::SpatialVectorF motionAcceleration = translateImpulse(pAcceleration, -c2p); //parent velocity change
PxReal tJAccel[3];
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
//stI * pAcceleration
const PxReal temp = IsW[ind].innerProduct(motionAcceleration);
tJAccel[ind] = (qstZIc[ind] - temp);
}
//calculate jointAcceleration
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
PxReal jVel = 0.f;
//for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
{
jVel += invStIs.invStIs[ind2][ind] * tJAccel[ind2];
}
//PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000);
motionAcceleration.top += motionMatrix[ind].top * jVel;
motionAcceleration.bottom += motionMatrix[ind].bottom * jVel;
jointVelocity[ind] += jVel;
}
return motionAcceleration;
}
Cm::SpatialVectorF FeatherstoneArticulation::propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix,
const Cm::SpatialVectorF& pAcceleration, const PxU32 dofCount, const Cm::SpatialVectorF* IsW, PxReal* qstZ)
{
Cm::SpatialVectorF motionAcceleration = translateImpulse(pAcceleration, -c2p); //parent velocity change
PxReal tJAccel[3];
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
//stI * pAcceleration
const PxReal temp = IsW[ind].innerProduct(motionAcceleration);
tJAccel[ind] = (qstZ[ind] - temp);
}
//calculate jointAcceleration
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
PxReal jVel = 0.f;
for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
{
jVel += invStIs.invStIs[ind2][ind] * tJAccel[ind2];
}
//PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000);
motionAcceleration.top += motionMatrix[ind].top * jVel;
motionAcceleration.bottom += motionMatrix[ind].bottom * jVel;
}
return motionAcceleration;
}
Cm::SpatialVectorF FeatherstoneArticulation::propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix,
PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration, Cm::SpatialVectorF& Z, const PxU32 dofCount, const Cm::SpatialVectorF* IsW)
{
Cm::SpatialVectorF motionAcceleration = translateImpulse(pAcceleration, -c2p); //parent velocity change
PxReal tJAccel[3];
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
//stI * pAcceleration
const PxReal temp = IsW[ind].innerProduct(motionAcceleration);
PxReal qstZ = -motionMatrix[ind].innerProduct(Z);
tJAccel[ind] = (qstZ - temp);
}
//calculate jointAcceleration
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
PxReal jVel = 0.f;
for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
{
jVel += invStIs.invStIs[ind2][ind] * tJAccel[ind2];
}
//PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000);
motionAcceleration.top += motionMatrix[ind].top * jVel;
motionAcceleration.bottom += motionMatrix[ind].bottom * jVel;
jointVelocity[ind] += jVel;
}
return motionAcceleration;
}
//This method calculate the velocity change due to collision/constraint impulse
Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocityTestImpulseW(const PxVec3& c2p, const Dy::SpatialMatrix& spatialInertia, const InvStIs& invStIs,
const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& Z, const Cm::SpatialVectorF& hDeltaV, const PxU32 dofCount)
{
Cm::SpatialVectorF pDeltaV = translateImpulse(hDeltaV, -c2p); //parent velocity change
//Convert parent velocity change into an impulse
Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z;
PxReal tJointDelta[3];
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind];
tJointDelta[ind] = -sa.innerProduct(temp);
}
Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f));
for (PxU32 ind = 0; ind < dofCount; ++ind)
{
PxReal jDelta = 0.f;
for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2)
{
jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2];
}
const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind];
jointSpatialDeltaV.top += sa.top * jDelta;
jointSpatialDeltaV.bottom += sa.bottom * jDelta;
}
return pDeltaV + jointSpatialDeltaV;
}
//Cm::SpatialVectorF FeatherstoneArticulation::propagateImpulse(const IsInvD& isInvD,
// const SpatialTransform& childToParent, const SpatialSubspaceMatrix& motionMatrix, const Cm::SpatialVectorF& Z)
//{
// const PxU32 dofCount = motionMatrix.getNumColumns();
// Cm::SpatialVectorF temp(PxVec3(0.f), PxVec3(0.f));
// for (PxU32 ind = 0; ind < dofCount; ++ind)
// {
// const Cm::SpatialVectorF& sa = motionMatrix[ind];
// const PxReal stZ = sa.innerProduct(Z);
// temp += isInvD.isInvD[ind] * stZ;
// }
// //parent space's spatial zero acceleration impulse
// return childToParent * (Z - temp);
//}
Cm::SpatialVectorF FeatherstoneArticulation::propagateImpulseW(
const PxVec3& childToParent,
const Cm::SpatialVectorF& linkYW,
const Cm::SpatialVectorF* jointDofISInvStISW, const Cm::UnAlignedSpatialVector* jointDofMotionMatrixW, const PxU8 dofCount,
PxReal* jointDofQStY)
{
//See Mirtich Figure 5.7 page 141
//Mirtich equivalent: {1 - [(I * s)/(s^T * I * s)] * s^T} * Y
//We actually compute: Y - [(I * s)/(s^T * I * s)] * s^T * Y
Cm::SpatialVectorF temp = linkYW;
for (PxU8 ind = 0; ind < dofCount; ++ind)
{
//Y - [(I * s)/(s^T * I * s)] * s^T * Y
const Cm::UnAlignedSpatialVector& sa = jointDofMotionMatrixW[ind];
const PxReal stZY = -(sa.innerProduct(linkYW));
PX_ASSERT(PxIsFinite(stZY));
temp += jointDofISInvStISW[ind] * stZY;
//Accumulate (-s^T * Y)
PX_ASSERT(!jointDofQStY || PxIsFinite(jointDofQStY[ind]));
if(jointDofQStY)
jointDofQStY[ind] += stZY;
}
//parent space's spatial zero acceleration impulse
return FeatherstoneArticulation::translateSpatialVector(childToParent, temp);
}
Cm::SpatialVectorF FeatherstoneArticulation::getDeltaVWithDeltaJV(const bool fixBase, const PxU32 linkID,
const ArticulationData& data, Cm::SpatialVectorF* Z,
PxReal* jointVelocities)
{
Cm::SpatialVectorF deltaV = Cm::SpatialVectorF::Zero();
if (!fixBase)
{
//velocity change
//SpatialMatrix inverseArticulatedInertia = hLinkDatum.spatialArticulatedInertia.getInverse();
const SpatialMatrix& inverseArticulatedInertia = data.mBaseInvSpatialArticulatedInertiaW;
deltaV = inverseArticulatedInertia * (-Z[0]);
}
ArticulationLink* links = data.getLinks();
const ArticulationLink& link = links[linkID];
const PxU32* pathToRoot = &data.mPathToRootElements[link.mPathToRootStartIndex];
const PxU32 numElems = link.mPathToRootCount;
for (PxU32 i = 0; i < numElems; ++i)
{
const PxU32 index = pathToRoot[i];
PX_ASSERT(links[index].parent < index);
ArticulationJointCoreData& tJointDatum = data.getJointData(index);
PxReal* jVelocity = &jointVelocities[tJointDatum.jointOffset];
deltaV = FeatherstoneArticulation::propagateVelocityW(data.getRw(index), data.mWorldSpatialArticulatedInertia[index],
data.mInvStIs[index], &data.mWorldMotionMatrix[tJointDatum.jointOffset], Z[index], jVelocity, deltaV, tJointDatum.dof);
}
return deltaV;
}
void FeatherstoneArticulation::getZ(const PxU32 linkID,
const ArticulationData& data, Cm::SpatialVectorF* Z,
const Cm::SpatialVectorF& impulse)
{
ArticulationLink* links = data.getLinks();
//impulse need to be in linkID space!!!
Z[linkID] = -impulse;
for (PxU32 i = linkID; i; i = links[i].parent)
{
ArticulationLink& tLink = links[i];
const PxU32 jointOffset = data.getJointData(i).jointOffset;
const PxU8 dofCount = data.getJointData(i).dof;
Z[tLink.parent] = FeatherstoneArticulation::propagateImpulseW(
data.getRw(i),
Z[i],
&data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount);
}
}
Cm::SpatialVectorF FeatherstoneArticulation::getImpulseResponseW(
const PxU32 linkID,
const ArticulationData& data,
const Cm::SpatialVectorF& impulse)
{
return data.getImpulseResponseMatrixWorld()[linkID].getResponse(impulse);
}
//This method use in impulse self response. The input impulse is in the link space
Cm::SpatialVectorF FeatherstoneArticulation::getImpulseResponseWithJ(
const PxU32 linkID,
const bool fixBase,
const ArticulationData& data,
Cm::SpatialVectorF* Z,
const Cm::SpatialVectorF& impulse,
PxReal* jointVelocites)
{
getZ(linkID, data, Z, impulse);
return getDeltaVWithDeltaJV(fixBase, linkID, data, Z, jointVelocites);
}
void FeatherstoneArticulation::saveVelocity(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* deltaV)
{
ArticulationData& data = articulation->mArticulationData;
//update all links' motion velocity, joint delta velocity if there are contacts/constraints
if (data.mJointDirty)
{
bool doForces = (data.getArticulationFlags() & PxArticulationFlag::eCOMPUTE_JOINT_FORCES) || data.getSensorCount();
PxcFsFlushVelocity(*articulation, deltaV, doForces);
}
const PxU32 linkCount = data.getLinkCount();
//copy motion velocites
Cm::SpatialVectorF* vels = data.getMotionVelocities();
Cm::SpatialVectorF* posVels = data.getPosIterMotionVelocities();
PxMemCopy(posVels, vels, sizeof(Cm::SpatialVectorF) * linkCount);
//copy joint velocities
const PxU32 dofs = data.getDofs();
PxReal* jPosVels = data.getPosIterJointVelocities();
const PxReal* jNewVels = data.getJointNewVelocities();
PxMemCopy(jPosVels, jNewVels, sizeof(PxReal) * dofs);
articulation->concludeInternalConstraints(false);
/* for (PxU32 i = 0; i < dofs; ++i)
{
PX_ASSERT(PxAbs(jPosDeltaVels[i]) < 30.f);
}*/
}
void FeatherstoneArticulation::saveVelocityTGS(FeatherstoneArticulation* articulation, PxReal invDtF32)
{
ArticulationData& data = articulation->mArticulationData;
//KS - we should not need to flush velocity because we will have already stepped the articulation with TGS
const PxU32 linkCount = data.getLinkCount();
Cm::SpatialVectorF* posVels = data.getPosIterMotionVelocities();
for (PxU32 i = 0; i < linkCount; ++i)
{
posVels[i] = posVels[i] * invDtF32;
}
}
void FeatherstoneArticulation::getImpulseSelfResponse(
PxU32 linkID0,
PxU32 linkID1,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse0,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV0,
Cm::SpatialVector& deltaV1) const
{
FeatherstoneArticulation::getImpulseSelfResponse(mArticulationData.getLinks(),
Z, const_cast<Dy::ArticulationData&>(mArticulationData), linkID0, reinterpret_cast<const Cm::SpatialVectorV&>(impulse0),
reinterpret_cast<Cm::SpatialVectorV&>(deltaV0), linkID1, reinterpret_cast<const Cm::SpatialVectorV&>(impulse1),
reinterpret_cast<Cm::SpatialVectorV&>(deltaV1));
}
void FeatherstoneArticulation::getImpulseResponseSlow(Dy::ArticulationLink* links,
ArticulationData& data,
PxU32 linkID0_,
const Cm::SpatialVector& impulse0,
Cm::SpatialVector& deltaV0,
PxU32 linkID1_,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV1,
Cm::SpatialVectorF* /*Z*/)
{
const PxU32 linkCount = data.getLinkCount();
PX_ALLOCA(_stack, PxU32, linkCount);
PxU32* stack = _stack;
PxU32 i0, i1;//, ic;
PxU32 linkID0 = linkID0_;
PxU32 linkID1 = linkID1_;
for (i0 = linkID0, i1 = linkID1; i0 != i1;) // find common path
{
if (i0<i1)
i1 = links[i1].parent;
else
i0 = links[i0].parent;
}
PxU32 common = i0;
Cm::SpatialVectorF Z0(-impulse0.linear, -impulse0.angular);
Cm::SpatialVectorF Z1(-impulse1.linear, -impulse1.angular);
PxReal qstZ[192];
PxMemZero(qstZ, data.getDofs() * sizeof(PxReal));
//Z[linkID0] = Z0;
//Z[linkID1] = Z1;
for (i0 = 0; linkID0 != common; linkID0 = links[linkID0].parent)
{
const PxU32 jointOffset = data.getJointData(linkID0).jointOffset;
const PxU8 dofCount = data.getJointData(linkID0).dof;
Z0 = FeatherstoneArticulation::propagateImpulseW(
data.getRw(linkID0),
Z0,
&data.getWorldIsInvD(jointOffset),
&data.getWorldMotionMatrix(jointOffset), dofCount,
&qstZ[jointOffset]);
stack[i0++] = linkID0;
}
for (i1 = i0; linkID1 != common; linkID1 = links[linkID1].parent)
{
const PxU32 jointOffset = data.getJointData(linkID1).jointOffset;
const PxU8 dofCount = data.getJointData(linkID1).dof;
Z1 = FeatherstoneArticulation::propagateImpulseW(
data.getRw(linkID1),
Z1,
&data.getWorldIsInvD(jointOffset),
&data.getWorldMotionMatrix(jointOffset), dofCount,
&qstZ[jointOffset]);
stack[i1++] = linkID1;
}
Cm::SpatialVectorF ZZ = Z0 + Z1;
Cm::SpatialVectorF v = data.getImpulseResponseMatrixWorld()[common].getResponse(-ZZ);
Cm::SpatialVectorF dv1 = v;
for (PxU32 index = i1; (index--) > i0;)
{
//Dy::ArticulationLinkData& tLinkDatum = data.getLinkData(stack[index]);
const PxU32 id = stack[index];
const PxU32 jointOffset = data.getJointData(id).jointOffset;
const PxU32 dofCount = data.getJointData(id).dof;
dv1 = propagateAccelerationW(data.getRw(id), data.mInvStIs[id],
&data.mWorldMotionMatrix[jointOffset], dv1, dofCount, &data.mIsW[jointOffset], &qstZ[jointOffset]);
}
Cm::SpatialVectorF dv0= v;
for (PxU32 index = i0; (index--) > 0;)
{
const PxU32 id = stack[index];
const PxU32 jointOffset = data.getJointData(id).jointOffset;
const PxU32 dofCount = data.getJointData(id).dof;
dv0 = propagateAccelerationW(data.getRw(id), data.mInvStIs[id],
&data.mWorldMotionMatrix[jointOffset], dv0, dofCount, &data.mIsW[jointOffset], &qstZ[jointOffset]);
}
deltaV0.linear = dv0.bottom;
deltaV0.angular = dv0.top;
deltaV1.linear = dv1.bottom;
deltaV1.angular = dv1.top;
}
void FeatherstoneArticulation::getImpulseSelfResponse(ArticulationLink* links,
Cm::SpatialVectorF* Z,
ArticulationData& data,
PxU32 linkID0,
const Cm::SpatialVectorV& impulse0,
Cm::SpatialVectorV& deltaV0,
PxU32 linkID1,
const Cm::SpatialVectorV& impulse1,
Cm::SpatialVectorV& deltaV1)
{
ArticulationLink& link = links[linkID1];
if (link.parent == linkID0)
{
PX_ASSERT(linkID0 == link.parent);
PX_ASSERT(linkID0 < linkID1);
//impulse is in world space
Cm::SpatialVectorF imp1;
V4StoreA(Vec4V_From_Vec3V(impulse1.angular), &imp1.bottom.x);
V4StoreA(Vec4V_From_Vec3V(impulse1.linear), &imp1.top.x);
Cm::SpatialVectorF imp0;
V4StoreA(Vec4V_From_Vec3V(impulse0.angular), &imp0.bottom.x);
V4StoreA(Vec4V_From_Vec3V(impulse0.linear), &imp0.top.x);
Cm::SpatialVectorF Z1W(-imp1.top, -imp1.bottom);
const PxU32 jointOffset1 = data.getJointData(linkID1).jointOffset;
const PxU8 dofCount1 = data.getJointData(linkID1).dof;
PxReal qstZ[3] = { 0.f, 0.f, 0.f };
const Cm::SpatialVectorF Z0W = FeatherstoneArticulation::propagateImpulseW(
data.getRw(linkID1),
Z1W,
&data.mISInvStIS[jointOffset1], &data.mWorldMotionMatrix[jointOffset1], dofCount1,
qstZ);
//in parent space
const Cm::SpatialVectorF impulseDifW = imp0 - Z0W;
//calculate velocity change start from the parent link to the root
const Cm::SpatialVectorF delV0W = FeatherstoneArticulation::getImpulseResponseW(linkID0, data, impulseDifW);
//calculate velocity change for child link
/*const Cm::SpatialVectorF delV1W = FeatherstoneArticulation::propagateVelocityTestImpulseW(data.getLinkData(linkID1).rw,
data.mWorldSpatialArticulatedInertia[linkID1], data.mInvStIs[linkID1], &data.mWorldMotionMatrix[jointOffset1], Z1W, delV0W, dofCount1);*/
const Cm::SpatialVectorF delV1W = propagateAccelerationW(data.getRw(linkID1), data.mInvStIs[linkID1],
&data.mWorldMotionMatrix[jointOffset1], delV0W, dofCount1, &data.mIsW[jointOffset1], qstZ);
deltaV0.linear = Vec3V_From_Vec4V(V4LoadA(&delV0W.bottom.x));
deltaV0.angular = Vec3V_From_Vec4V(V4LoadA(&delV0W.top.x));
deltaV1.linear = Vec3V_From_Vec4V(V4LoadA(&delV1W.bottom.x));
deltaV1.angular = Vec3V_From_Vec4V(V4LoadA(&delV1W.top.x));
}
else
{
getImpulseResponseSlow(links, data, linkID0, reinterpret_cast<const Cm::SpatialVector&>(impulse0),
reinterpret_cast<Cm::SpatialVector&>(deltaV0), linkID1,
reinterpret_cast<const Cm::SpatialVector&>(impulse1), reinterpret_cast<Cm::SpatialVector&>(deltaV1),
Z);
}
}
struct ArticulationStaticConstraintSortPredicate
{
bool operator()(const PxSolverConstraintDesc& left, const PxSolverConstraintDesc& right) const
{
PxU32 linkIndexA = left.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? left.linkIndexA : left.linkIndexB;
PxU32 linkIndexB = right.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? right.linkIndexA : right.linkIndexB;
return linkIndexA < linkIndexB;
}
};
bool createFinalizeSolverContactsStep(PxTGSSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal invTotalDt,
const PxReal totalDt,
const PxReal stepDt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
void FeatherstoneArticulation::prepareStaticConstraintsTGS(const PxReal stepDt, const PxReal totalDt, const PxReal invStepDt, const PxReal invTotalDt,
PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& threadContext, PxReal correlationDist, PxReal bounceThreshold, PxReal frictionOffsetThreshold,
PxTGSSolverBodyData* solverBodyData, PxTGSSolverBodyTxInertia* txInertia, PxsConstraintBlockManager& blockManager,
Dy::ConstraintWriteback* constraintWritebackPool, const PxReal biasCoefficient, const PxReal lengthScale)
{
BlockAllocator blockAllocator(blockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize);
const PxTransform id(PxIdentity);
PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStatic1DConstraints.begin(), mStatic1DConstraints.size(), ArticulationStaticConstraintSortPredicate());
PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStaticContactConstraints.begin(), mStaticContactConstraints.size(), ArticulationStaticConstraintSortPredicate());
for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStatic1DConstraints[i];
PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB;
PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D);
const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint);
SolverConstraintShaderPrepDesc shaderPrepDesc;
PxTGSSolverConstraintPrepDesc prepDesc;
const PxConstraintSolverPrep solverPrep = constraint->solverPrep;
const void* constantBlock = constraint->constantBlock;
const PxU32 constantBlockByteSize = constraint->constantBlockSize;
const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : id);
const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : id);
const PxTGSSolverBodyVel* sbody0 = desc.tgsBodyA;
const PxTGSSolverBodyVel* sbody1 = desc.tgsBodyB;
PxTGSSolverBodyData* sbodyData0 = &solverBodyData[desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyADataIndex];
PxTGSSolverBodyData* sbodyData1 = &solverBodyData[desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyBDataIndex];
PxTGSSolverBodyTxInertia& txI0 = txInertia[desc.bodyADataIndex];
PxTGSSolverBodyTxInertia& txI1 = txInertia[desc.bodyBDataIndex];
shaderPrepDesc.constantBlock = constantBlock;
shaderPrepDesc.constantBlockByteSize = constantBlockByteSize;
shaderPrepDesc.constraint = constraint;
shaderPrepDesc.solverPrep = solverPrep;
prepDesc.desc = static_cast<PxSolverConstraintDesc*>(&desc);
prepDesc.bodyFrame0 = pose0;
prepDesc.bodyFrame1 = pose1;
prepDesc.body0 = sbody0;
prepDesc.body1 = sbody1;
prepDesc.body0TxI = &txI0;
prepDesc.body1TxI = &txI1;
prepDesc.bodyData0 = sbodyData0;
prepDesc.bodyData1 = sbodyData1;
prepDesc.linBreakForce = constraint->linBreakForce;
prepDesc.angBreakForce = constraint->angBreakForce;
prepDesc.writeback = &constraintWritebackPool[constraint->index];
setupConstraintFlags(prepDesc, constraint->flags);
prepDesc.minResponseThreshold = constraint->minResponseThreshold;
prepDesc.bodyState0 = desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION;
prepDesc.bodyState1 = desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION;
SetupSolverConstraintStep(shaderPrepDesc, prepDesc, blockAllocator, stepDt, totalDt, invStepDt, invTotalDt, lengthScale, biasCoefficient);
if (desc.constraint)
{
if (mArticulationData.mNbStatic1DConstraints[linkIndex] == 0)
mArticulationData.mStatic1DConstraintStartIndex[linkIndex] = i;
mArticulationData.mNbStatic1DConstraints[linkIndex]++;
}
else
{
//Shuffle down
mStatic1DConstraints.remove(i);
i--;
}
}
for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStaticContactConstraints[i];
PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB;
PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT);
PxTGSSolverContactDesc blockDesc;
PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint);
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxsContactManagerOutput* cmOutput = &outputs.getContactManager(unit.mNpIndex);
PxTGSSolverBodyVel& b0 = *desc.tgsBodyA;
PxTGSSolverBodyVel& b1 = *desc.tgsBodyB;
PxTGSSolverBodyData& data0 = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyADataIndex];
PxTGSSolverBodyData& data1 = desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyBDataIndex];
PxTGSSolverBodyTxInertia& txI0 = txInertia[desc.bodyADataIndex];
PxTGSSolverBodyTxInertia& txI1 = txInertia[desc.bodyBDataIndex];
blockDesc.bodyFrame0 = unit.rigidCore0->body2World;
blockDesc.bodyFrame1 = unit.rigidCore1->body2World;
blockDesc.shapeInteraction = cm->getShapeInteraction();
blockDesc.contactForces = cmOutput->contactForces;
blockDesc.desc = static_cast<PxSolverConstraintDesc*>(&desc);
blockDesc.body0 = &b0;
blockDesc.body1 = &b1;
blockDesc.body0TxI = &txI0;
blockDesc.body1TxI = &txI1;
blockDesc.bodyData0 = &data0;
blockDesc.bodyData1 = &data1;
blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION);
blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY;
blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? PxSolverContactDesc::eARTICULATION : (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY :
((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY);
//blockDesc.flags = unit.flags;
PxReal maxImpulse0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? static_cast<const PxsBodyCore*>(unit.rigidCore0)->maxContactImpulse : data0.maxContactImpulse;
PxReal maxImpulse1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? static_cast<const PxsBodyCore*>(unit.rigidCore1)->maxContactImpulse : data1.maxContactImpulse;
PxReal dominance0 = unit.dominance0 ? 1.f : 0.f;
PxReal dominance1 = unit.dominance1 ? 1.f : 0.f;
blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0;
blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1;
blockDesc.restDistance = unit.restDistance;
blockDesc.frictionPtr = unit.frictionDataPtr;
blockDesc.frictionCount = unit.frictionPatchCount;
blockDesc.maxCCDSeparation = PX_MAX_F32;
blockDesc.maxImpulse = PxMin(maxImpulse0, maxImpulse1);
blockDesc.torsionalPatchRadius = unit.mTorsionalPatchRadius;
blockDesc.minTorsionalPatchRadius = unit.mMinTorsionalPatchRadius;
blockDesc.offsetSlop = unit.mOffsetSlop;
createFinalizeSolverContactsStep(blockDesc, *cmOutput, threadContext,
invStepDt, invTotalDt, totalDt, stepDt, bounceThreshold, frictionOffsetThreshold,
correlationDist, biasCoefficient, blockAllocator);
getContactManagerConstraintDesc(*cmOutput, *cm, desc);
unit.frictionDataPtr = blockDesc.frictionPtr;
unit.frictionPatchCount = blockDesc.frictionCount;
//KS - Don't track this for now!
//axisConstraintCount += blockDesc.axisConstraintCount;
if (desc.constraint)
{
if (mArticulationData.mNbStaticContactConstraints[linkIndex] == 0)
mArticulationData.mStaticContactConstraintStartIndex[linkIndex] = i;
mArticulationData.mNbStaticContactConstraints[linkIndex]++;
}
else
{
//Shuffle down
mStaticContactConstraints.remove(i);
i--;
}
}
}
void FeatherstoneArticulation::prepareStaticConstraints(const PxReal dt, const PxReal invDt, PxsContactManagerOutputIterator& outputs,
Dy::ThreadContext& threadContext, PxReal correlationDist, PxReal bounceThreshold, PxReal frictionOffsetThreshold,
PxReal ccdMaxSeparation, PxSolverBodyData* solverBodyData, PxsConstraintBlockManager& blockManager,
Dy::ConstraintWriteback* constraintWritebackPool)
{
BlockAllocator blockAllocator(blockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize);
const PxTransform id(PxIdentity);
Cm::SpatialVectorF* Z = threadContext.mZVector.begin();
PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStatic1DConstraints.begin(), mStatic1DConstraints.size(), ArticulationStaticConstraintSortPredicate());
PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStaticContactConstraints.begin(), mStaticContactConstraints.size(), ArticulationStaticConstraintSortPredicate());
for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStatic1DConstraints[i];
PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB;
PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D);
const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint);
SolverConstraintShaderPrepDesc shaderPrepDesc;
PxSolverConstraintPrepDesc prepDesc;
const PxConstraintSolverPrep solverPrep = constraint->solverPrep;
const void* constantBlock = constraint->constantBlock;
const PxU32 constantBlockByteSize = constraint->constantBlockSize;
const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : id);
const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : id);
const PxSolverBody* sbody0 = desc.bodyA;
const PxSolverBody* sbody1 = desc.bodyB;
PxSolverBodyData* sbodyData0 = &solverBodyData[desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyADataIndex];
PxSolverBodyData* sbodyData1 = &solverBodyData[desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyBDataIndex];
shaderPrepDesc.constantBlock = constantBlock;
shaderPrepDesc.constantBlockByteSize = constantBlockByteSize;
shaderPrepDesc.constraint = constraint;
shaderPrepDesc.solverPrep = solverPrep;
prepDesc.desc = &desc;
prepDesc.bodyFrame0 = pose0;
prepDesc.bodyFrame1 = pose1;
prepDesc.data0 = sbodyData0;
prepDesc.data1 = sbodyData1;
prepDesc.body0 = sbody0;
prepDesc.body1 = sbody1;
prepDesc.linBreakForce = constraint->linBreakForce;
prepDesc.angBreakForce = constraint->angBreakForce;
prepDesc.writeback = &constraintWritebackPool[constraint->index];
setupConstraintFlags(prepDesc, constraint->flags);
prepDesc.minResponseThreshold = constraint->minResponseThreshold;
SetupSolverConstraint(shaderPrepDesc, prepDesc, blockAllocator, dt, invDt, Z);
if (desc.constraint)
{
if (mArticulationData.mNbStatic1DConstraints[linkIndex] == 0)
mArticulationData.mStatic1DConstraintStartIndex[linkIndex] = i;
mArticulationData.mNbStatic1DConstraints[linkIndex]++;
}
else
{
//Shuffle down
mStatic1DConstraints.remove(i);
i--;
}
}
for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStaticContactConstraints[i];
PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB;
PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT);
PxSolverContactDesc blockDesc;
PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint);
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxsContactManagerOutput* cmOutput = &outputs.getContactManager(unit.mNpIndex);
PxSolverBodyData& data0 = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyADataIndex];
PxSolverBodyData& data1 = desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyBDataIndex];
blockDesc.data0 = &data0;
blockDesc.data1 = &data1;
PxU8 flags = unit.rigidCore0->mFlags;
if (unit.rigidCore1)
flags |= PxU8(unit.rigidCore1->mFlags);
blockDesc.bodyFrame0 = unit.rigidCore0->body2World;
blockDesc.bodyFrame1 = unit.rigidCore1 ? unit.rigidCore1->body2World : id;
blockDesc.shapeInteraction = cm->getShapeInteraction();
blockDesc.contactForces = cmOutput->contactForces;
blockDesc.desc = &desc;
blockDesc.body0 = desc.bodyA;
blockDesc.body1 = desc.bodyB;
blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION);
blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY;
blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? PxSolverContactDesc::eARTICULATION : (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY :
((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY);
//blockDesc.flags = unit.flags;
PxReal dominance0 = unit.dominance0 ? 1.f : 0.f;
PxReal dominance1 = unit.dominance1 ? 1.f : 0.f;
blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0;
blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1;
blockDesc.restDistance = unit.restDistance;
blockDesc.frictionPtr = unit.frictionDataPtr;
blockDesc.frictionCount = unit.frictionPatchCount;
blockDesc.maxCCDSeparation = (flags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) ? ccdMaxSeparation : PX_MAX_F32;
blockDesc.offsetSlop = unit.mOffsetSlop;
createFinalizeSolverContacts(blockDesc, *cmOutput, threadContext, invDt, dt, bounceThreshold, frictionOffsetThreshold,
correlationDist, blockAllocator, Z);
getContactManagerConstraintDesc(*cmOutput, *cm, desc);
unit.frictionDataPtr = blockDesc.frictionPtr;
unit.frictionPatchCount = blockDesc.frictionCount;
//KS - Don't track this for now!
//axisConstraintCount += blockDesc.axisConstraintCount;
if (desc.constraint)
{
if (mArticulationData.mNbStaticContactConstraints[linkIndex] == 0)
mArticulationData.mStaticContactConstraintStartIndex[linkIndex] = i;
mArticulationData.mNbStaticContactConstraints[linkIndex]++;
}
else
{
mStaticContactConstraints.remove(i);
i--;
}
}
}
void setupComplexLimit(ArticulationLink* links, Cm::SpatialVectorF* Z, ArticulationData& data, const PxU32 linkID,
const PxReal angle, const PxReal lowLimit, const PxReal highLimit, const PxVec3& axis, const PxReal cfm, ArticulationInternalConstraint& complexConstraint,
ArticulationInternalLimit& limit)
{
Cm::SpatialVectorV deltaVA, deltaVB;
FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data,
links[linkID].parent, Cm::SpatialVector(PxVec3(0), axis), deltaVA,
linkID, Cm::SpatialVector(PxVec3(0), -axis), deltaVB);
const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA);
const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB);
const PxReal r0 = deltaV0.angular.dot(axis);
const PxReal r1 = deltaV1.angular.dot(axis);
const PxReal unitResponse = r0 - r1;
const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (cfm + unitResponse) : 0.0f;
complexConstraint.row0 = Cm::UnAlignedSpatialVector(PxVec3(0), axis);
complexConstraint.row1 = Cm::UnAlignedSpatialVector(PxVec3(0), axis);
complexConstraint.deltaVA.top = unsimdRef(deltaVA).angular;
complexConstraint.deltaVA.bottom = unsimdRef(deltaVA).linear;
complexConstraint.deltaVB.top = unsimdRef(deltaVB).angular;
complexConstraint.deltaVB.bottom = unsimdRef(deltaVB).linear;
complexConstraint.recipResponse = recipResponse;
complexConstraint.response = unitResponse;
complexConstraint.isLinearConstraint = true;
limit.errorLow = angle - lowLimit;
limit.errorHigh = highLimit - angle;
limit.lowImpulse = 0.f;
limit.highImpulse = 0.f;
}
void FeatherstoneArticulation::setupInternalConstraintsRecursive(
ArticulationLink* links,
const PxU32 linkCount,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
const PxReal stepDt,
const PxReal dt,
const PxReal invDt,
const bool isTGSSolver,
const PxU32 linkID,
const PxReal maxForceScale)
{
const ArticulationLink& link = links[linkID];
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
const ArticulationLink& pLink = links[link.parent];
const ArticulationJointCore& j = *link.inboundJoint;
//const bool jointDrive = (j.driveType != PxArticulationJointDriveType::eNONE);
bool hasFriction = j.frictionCoefficient > 0.f;
const PxReal fCoefficient = j.frictionCoefficient * stepDt;
const PxU32 limitedRows = jointDatum.limitMask;
PxU8 driveRows = 0;
for (PxU32 i = 0; i < PxArticulationAxis::eCOUNT; ++i)
{
if (j.drives[i].maxForce > 0.f && (j.drives[i].stiffness > 0.f || j.drives[i].damping > 0.f))
driveRows++;
}
const PxU8 frictionRows = hasFriction ? jointDatum.dof : PxU8(0);
const PxU8 constraintCount = PxU8(driveRows + frictionRows + limitedRows);
if (!constraintCount)
{
//Skip these constraints...
//constraints += jointDatum.dof;
jointDatum.dofInternalConstraintMask = 0;
}
else
{
const PxReal transmissionForce = data.getTransmittedForce(linkID).magnitude() * fCoefficient;
// PT:: tag: scalar transform*transform
const PxTransform cA2w = pLink.bodyCore->body2World.transform(j.parentPose);
const PxTransform cB2w = link.bodyCore->body2World.transform(j.childPose);
const PxU32 parent = link.parent;
const PxReal cfm = PxMax(link.cfm, pLink.cfm);
//Linear, then angular...
PxVec3 driveError(0.f);
PxVec3 angles(0.f);
PxVec3 row[3];
if (j.jointType == PxArticulationJointType::eSPHERICAL && jointDatum.dof > 1)
{
//It's a spherical joint. We can't directly work on joint positions with spherical joints, so we instead need to compute the quaternion
//and from that compute the joint error projected onto the DOFs. This will yield a rotation that is singularity-free, where the joint
//angles match the target joint angles provided provided the angles are within +/- Pi around each axis. Spherical joints do not support
//quaternion double cover cases/wide angles.
PxVec3 driveAxis(0.f);
bool hasAngularDrives = false;
PxU32 tmpDofId = 0;
for (PxU32 i = 0; i < PxArticulationAxis::eX; ++i)
{
if (j.motion[i] != PxArticulationMotion::eLOCKED)
{
const bool hasDrive = (j.motion[i] != PxArticulationMotion::eLOCKED && j.drives[i].driveType != PxArticulationDriveType::eNONE);
if (hasDrive)
{
const PxVec3 axis = data.mMotionMatrix[jointDatum.jointOffset + tmpDofId].top;
PxReal target = data.mJointTargetPositions[jointDatum.jointOffset + tmpDofId];
driveAxis += axis * target;
hasAngularDrives = true;
}
tmpDofId++;
}
}
{
PxQuat qB2qA = cA2w.q.getConjugate() * cB2w.q;
{
//Spherical joint drive calculation using 3x child-space Euler angles
if (hasAngularDrives)
{
PxReal angle = driveAxis.normalize();
if (angle < 1e-12f)
{
driveAxis = PxVec3(1.f, 0.f, 0.f);
angle = 0.f;
}
PxQuat targetQ = PxQuat(angle, driveAxis);
if (targetQ.dot(qB2qA) < 0.f)
targetQ = -targetQ;
driveError = -2.f * (targetQ.getConjugate() * qB2qA).getImaginaryPart();
}
for (PxU32 i = 0, tmpDof = 0; i < PxArticulationAxis::eX; ++i)
{
if (j.motion[i] != PxArticulationMotion::eLOCKED)
{
angles[i] = data.mJointPosition[j.jointOffset + tmpDof];
row[i] = data.mWorldMotionMatrix[jointDatum.jointOffset + tmpDof].top;
tmpDof++;
}
}
}
}
}
else
{
for (PxU32 i = 0; i < PxArticulationAxis::eX; ++i)
{
if (j.motion[i] != PxArticulationMotion::eLOCKED)
{
driveError[i] = data.mJointTargetPositions[j.jointOffset] - data.mJointPosition[j.jointOffset];
angles[i] = data.mJointPosition[j.jointOffset];
row[i] = data.mWorldMotionMatrix[jointDatum.jointOffset].top;
}
}
}
PxU32 dofId = 0;
PxU8 dofMask = 0;
for (PxU32 i = 0; i < PxArticulationAxis::eX; ++i)
{
if (j.motion[i] != PxArticulationMotion::eLOCKED)
{
const bool hasDrive = (j.motion[i] != PxArticulationMotion::eLOCKED && j.drives[i].driveType != PxArticulationDriveType::eNONE);
if (j.motion[i] == PxArticulationMotion::eLIMITED || hasDrive || frictionRows)
{
dofMask |= (1 << dofId);
//Impulse response vector and axes are common for all constraints on this axis besides locked axis!!!
const PxVec3 axis = row[i];
Cm::SpatialVectorV deltaVA, deltaVB;
FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data,
parent, Cm::SpatialVector(PxVec3(0), axis), deltaVA,
linkID, Cm::SpatialVector(PxVec3(0), -axis), deltaVB);
const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA);
const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB);
const PxReal r0 = deltaV0.angular.dot(axis);
const PxReal r1 = deltaV1.angular.dot(axis);
const PxReal unitResponse = r0 - r1;
const PxReal recipResponse = unitResponse <= 0.f ? 0.f : 1.0f / (unitResponse+cfm);
const PxU32 count = data.mInternalConstraints.size();
data.mInternalConstraints.forceSize_Unsafe(count + 1);
ArticulationInternalConstraint* constraints = &data.mInternalConstraints[count];
constraints->recipResponse = recipResponse;
constraints->response = unitResponse;
constraints->row0 = Cm::SpatialVectorF(PxVec3(0), axis);
constraints->row1 = Cm::SpatialVectorF(PxVec3(0), axis);
constraints->deltaVA.top = unsimdRef(deltaVA).angular;
constraints->deltaVA.bottom = unsimdRef(deltaVA).linear;
constraints->deltaVB.top = unsimdRef(deltaVB).angular;
constraints->deltaVB.bottom = unsimdRef(deltaVB).linear;
constraints->isLinearConstraint = false;
constraints->frictionForce = 0.f;
constraints->frictionMaxForce = hasFriction ? transmissionForce : 0.f;
constraints->frictionForceCoefficient = isTGSSolver ? 0.f : 1.f;
constraints->driveForce = 0.0f;
constraints->driveMaxForce = j.drives[i].maxForce * maxForceScale;
if(hasDrive)
{
constraints->setImplicitDriveDesc(
computeImplicitDriveParams(
j.drives[i].driveType, j.drives[i].stiffness, j.drives[i].damping,
isTGSSolver ? stepDt: dt,
unitResponse, recipResponse,
driveError[i], data.mJointTargetVelocities[j.jointOffset + dofId],
isTGSSolver));
}
else
{
constraints->setImplicitDriveDesc(ArticulationImplicitDriveDesc(PxZero));
}
if (j.motion[i] == PxArticulationMotion::eLIMITED)
{
const PxU32 limitCount = data.mInternalLimits.size();
data.mInternalLimits.forceSize_Unsafe(limitCount + 1);
ArticulationInternalLimit* limits = &data.mInternalLimits[limitCount];
const PxReal jPos = angles[i];
limits->errorHigh = j.limits[i].high - jPos;
limits->errorLow = jPos - j.limits[i].low;
limits->lowImpulse = 0.f;
limits->highImpulse = 0.f;
}
}
dofId++;
}
}
for (PxU32 i = PxArticulationAxis::eX; i < PxArticulationAxis::eCOUNT; ++i)
{
if (j.motion[i] != PxArticulationMotion::eLOCKED)
{
const bool hasDrive = (j.motion[i] != PxArticulationMotion::eLOCKED && j.drives[i].maxForce > 0.f && (j.drives[i].stiffness > 0.f || j.drives[i].damping > 0.f));
if (j.motion[i] == PxArticulationMotion::eLIMITED || hasDrive || frictionRows)
{
dofMask |= (1 << dofId);
//Impulse response vector and axes are common for all constraints on this axis besides locked axis!!!
const PxVec3 axis = data.mWorldMotionMatrix[jointDatum.jointOffset + dofId].bottom;
const PxVec3 ang0 = (cA2w.p - pLink.bodyCore->body2World.p).cross(axis);
const PxVec3 ang1 = (cB2w.p - link.bodyCore->body2World.p).cross(axis);
Cm::SpatialVectorV deltaVA, deltaVB;
FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data,
links[linkID].parent, Cm::SpatialVector(axis, ang0), deltaVA,
linkID, Cm::SpatialVector(-axis, -ang1), deltaVB);
//Now add in friction rows, then limit rows, then drives...
const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA);
const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB);
const PxReal r0 = deltaV0.linear.dot(axis) + deltaV0.angular.dot(ang0);
const PxReal r1 = deltaV1.linear.dot(axis) + deltaV1.angular.dot(ang1);
const PxReal unitResponse = r0 - r1;
//const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (unitResponse+cfm) : 0.0f;
const PxReal recipResponse = 1.0f / (unitResponse + cfm);
const PxU32 count = data.mInternalConstraints.size();
data.mInternalConstraints.forceSize_Unsafe(count + 1);
ArticulationInternalConstraint* constraints = &data.mInternalConstraints[count];
constraints->response = unitResponse;
constraints->recipResponse = recipResponse;
constraints->row0 = Cm::SpatialVectorF(axis, ang0);
constraints->row1 = Cm::SpatialVectorF(axis, ang1);
constraints->deltaVA.top = unsimdRef(deltaVA).angular;
constraints->deltaVA.bottom = unsimdRef(deltaVA).linear;
constraints->deltaVB.top = unsimdRef(deltaVB).angular;
constraints->deltaVB.bottom = unsimdRef(deltaVB).linear;
constraints->isLinearConstraint = true;
constraints->frictionForce = 0.f;
constraints->frictionMaxForce = hasFriction ? transmissionForce : 0.f;
constraints->frictionForceCoefficient = isTGSSolver ? 0.f : 1.f;
constraints->driveForce = 0.0f;
constraints->driveMaxForce = j.drives[i].maxForce * maxForceScale;
if(hasDrive)
{
constraints->setImplicitDriveDesc(
computeImplicitDriveParams(
j.drives[i].driveType, j.drives[i].stiffness, j.drives[i].damping,
isTGSSolver ? stepDt : dt,
unitResponse, recipResponse,
data.mJointTargetPositions[j.jointOffset + dofId] - data.mJointPosition[j.jointOffset + dofId],
data.mJointTargetVelocities[j.jointOffset + dofId],
isTGSSolver));
}
else
{
constraints->setImplicitDriveDesc(ArticulationImplicitDriveDesc(PxZero));
}
if (j.motion[i] == PxArticulationMotion::eLIMITED)
{
const PxU32 limitCount = data.mInternalLimits.size();
data.mInternalLimits.forceSize_Unsafe(limitCount + 1);
ArticulationInternalLimit* limits = &data.mInternalLimits[limitCount];
const PxReal jPos = data.mJointPosition[j.jointOffset + dofId];
limits->errorHigh = j.limits[i].high - jPos;
limits->errorLow = jPos - j.limits[i].low;
limits->lowImpulse = 0.f;
limits->highImpulse = 0.f;
}
}
dofId++;
}
}
if (jointDatum.limitMask)
{
for (PxU32 dof = 0; dof < jointDatum.dof; ++dof)
{
PxU32 i = j.dofIds[dof];
if (j.motion[i] == PxArticulationMotion::eLOCKED)
{
const PxU32 count = data.mInternalConstraints.size();
data.mInternalConstraints.forceSize_Unsafe(count + 1);
ArticulationInternalConstraint* constraints = &data.mInternalConstraints[count];
const PxU32 limitCount = data.mInternalLimits.size();
data.mInternalLimits.forceSize_Unsafe(limitCount + 1);
ArticulationInternalLimit* limits = &data.mInternalLimits[limitCount];
const PxVec3 axis = row[i];
PxReal angle = angles[i];
//A locked axis is equivalent to a limit of 0
PxReal low = 0.f;
PxReal high = 0.f;
setupComplexLimit(links, Z, data, linkID, angle,
low, high, axis, cfm, *constraints, *limits++);
}
}
}
jointDatum.dofInternalConstraintMask = dofMask;
}
const PxU32 numChildren = link.mNumChildren;
const PxU32 offset = link.mChildrenStartIndex;
for (PxU32 i = 0; i < numChildren; ++i)
{
const PxU32 child = offset + i;
setupInternalConstraintsRecursive(links, linkCount, fixBase, data, Z, stepDt, dt, invDt, isTGSSolver, child, maxForceScale);
}
}
void FeatherstoneArticulation::setupInternalSpatialTendonConstraintsRecursive(
ArticulationLink* links,
ArticulationAttachment* attachments,
const PxU32 attachmentCount,
const PxVec3& pAttachPoint,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
const PxReal stepDt,
const bool isTGSSolver,
const PxU32 attachmentID,
const PxReal stiffness,
const PxReal damping,
const PxReal limitStiffness,
const PxReal accumLength,
const PxU32 startLink,
const PxVec3& startAxis,
const PxVec3& startRaXn)
{
ArticulationAttachment& attachment = attachments[attachmentID];
ArticulationLink& cLink = links[attachment.linkInd];
const PxTransform cBody2World = cLink.bodyCore->body2World;
const PxVec3 rb = cBody2World.q.rotate(attachment.relativeOffset);
const PxVec3 cAttachPoint = cBody2World.p + rb;
const PxVec3 dif = pAttachPoint - cAttachPoint;
const PxReal distanceSq = dif.magnitudeSquared();
const PxReal distance = PxSqrt(distanceSq);
const PxReal u = distance * attachment.coefficient + accumLength;
const PxU32 childCount = attachment.childCount;
if (childCount)
{
for (ArticulationBitField children = attachment.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
setupInternalSpatialTendonConstraintsRecursive(links, attachments, attachmentCount, cAttachPoint, fixBase, data, Z, stepDt,
isTGSSolver, child, stiffness, damping, limitStiffness, u, startLink,
startAxis, startRaXn);
}
}
else
{
const PxVec3 axis = distance > 0.001f ? dif / distance : PxVec3(0.f);
const PxVec3 rbXn = rb.cross(axis);
Cm::SpatialVectorV deltaVA, deltaVB;
FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data,
startLink, Cm::SpatialVector(startAxis, startRaXn), deltaVA,
attachment.linkInd, Cm::SpatialVector(-axis, -rbXn), deltaVB);
const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA);
const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB);
const PxReal r0 = deltaV0.linear.dot(startAxis) + deltaV0.angular.dot(startRaXn);
const PxReal r1 = deltaV1.linear.dot(axis) + deltaV1.angular.dot(rbXn);
const PxReal unitResponse = (r0 - r1);
//const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (unitResponse + cfm) : 0.0f;
//const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (unitResponse) : 0.0f;
const PxReal recipResponse = 1.0f / (unitResponse + cLink.cfm);
const PxU32 count = data.mInternalSpatialTendonConstraints.size();
data.mInternalSpatialTendonConstraints.forceSize_Unsafe(count + 1);
ArticulationInternalTendonConstraint* constraint = &data.mInternalSpatialTendonConstraints[count];
attachment.mConstraintInd = PxU16(count);
constraint->row0 = Cm::SpatialVectorF(startAxis, startRaXn);
constraint->row1 = Cm::SpatialVectorF(axis, rbXn);
constraint->linkID0 = startLink;
constraint->linkID1 = attachment.linkInd;
constraint->recipResponse = recipResponse;
const PxReal a = stepDt * (stepDt*stiffness + damping);
const PxReal a2 = stepDt * (stepDt*limitStiffness + damping);
const PxReal x = unitResponse > 0.f ? 1.0f / (1.0f + a * unitResponse) : 0.f;
const PxReal x2 = unitResponse > 0.f ? 1.0f / (1.0f + a2 * unitResponse) : 0.f;
constraint->velMultiplier = -x * a;// * unitResponse;
//constraint->velMultiplier = -x * damping*stepDt;
constraint->impulseMultiplier = isTGSSolver ? 1.f : 1.f - x;
constraint->biasCoefficient = (-stiffness * x * stepDt);//*unitResponse;
constraint->appliedForce = 0.f;
constraint->accumulatedLength = u;// + u*0.2f;
constraint->restDistance = attachment.restLength;
constraint->lowLimit = attachment.lowLimit;
constraint->highLimit = attachment.highLimit;
constraint->limitBiasCoefficient = (-limitStiffness * x2 * stepDt);//*unitResponse;
constraint->limitImpulseMultiplier = isTGSSolver ? 1.f : 1.f - x2;
constraint->limitAppliedForce = 0.f;
}
}
void FeatherstoneArticulation::updateSpatialTendonConstraintsRecursive(ArticulationAttachment* attachments, ArticulationData& data, const PxU32 attachmentID, PxReal accumLength,
const PxVec3& pAttachPoint)
{
ArticulationAttachment& attachment = attachments[attachmentID];
//const PxReal restDist = attachment.restDistance;
const PxTransform& cBody2World = data.getAccumulatedPoses()[attachment.linkInd];
const PxVec3 rb = cBody2World.q.rotate(attachment.relativeOffset);
const PxVec3 cAttachPoint = cBody2World.p + rb;
const PxVec3 dif = pAttachPoint - cAttachPoint;
const PxReal distanceSq = dif.magnitudeSquared();
const PxReal distance = PxSqrt(distanceSq);
const PxReal u = distance * attachment.coefficient + accumLength;
const PxU32 childCount = attachment.childCount;
if (childCount)
{
for (ArticulationBitField children = attachment.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
updateSpatialTendonConstraintsRecursive(attachments, data, child, u, cAttachPoint);
}
}
else
{
PxU32 index = attachment.mConstraintInd;
ArticulationInternalTendonConstraint& constraint = data.mInternalSpatialTendonConstraints[index];
constraint.accumulatedLength = u;
}
}
void FeatherstoneArticulation::setupInternalFixedTendonConstraintsRecursive(
ArticulationLink* links,
ArticulationTendonJoint* tendonJoints,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
const PxReal stepDt,
const bool isTGSSolver,
const PxU32 tendonJointID,
const PxReal stiffness,
const PxReal damping,
const PxReal limitStiffness,
const PxU32 startLink,
const PxVec3& startAxis,
const PxVec3& startRaXn)
{
ArticulationTendonJoint& tendonJoint = tendonJoints[tendonJointID];
ArticulationLink& cLink = links[tendonJoint.linkInd];
const PxTransform& cBody2World = cLink.bodyCore->body2World;
const PxReal cfm = PxMax(cLink.cfm, links[startLink].cfm);
ArticulationJointCoreData& jointDatum = data.getJointData(tendonJoint.linkInd);
ArticulationJointCore& joint = *cLink.inboundJoint;
PxU16 tendonJointAxis = tendonJoint.axis;
PX_ASSERT(joint.motion[tendonJointAxis] != PxArticulationMotion::eLOCKED);
//Cm::SpatialVector cImpulse;
PxU32 dofIndex = joint.invDofIds[tendonJointAxis];
tendonJoint.startJointOffset = PxTo16(jointDatum.jointOffset + dofIndex);
///*PxReal jointPose = jointPositions[jointDatum.jointOffset + dofIndex] * tendonJoint.coefficient;
//jointPose += accumulatedJointPose;*/
{
PxVec3 axis, rbXn;
if (tendonJointAxis < PxArticulationAxis::eX)
{
const PxVec3 tAxis = data.mWorldMotionMatrix[jointDatum.jointOffset + dofIndex].top;
axis = PxVec3(0.f);
rbXn = tAxis;
}
else
{
// PT:: tag: scalar transform*transform
const PxTransform cB2w = cBody2World.transform(joint.childPose);
const PxVec3 tAxis = data.mWorldMotionMatrix[jointDatum.jointOffset + dofIndex].bottom;
axis = tAxis;
rbXn = (cB2w.p - cBody2World.p).cross(axis);
}
Cm::SpatialVectorV deltaVA, deltaVB;
FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data,
startLink, Cm::SpatialVector(startAxis, startRaXn), deltaVA,
tendonJoint.linkInd, Cm::SpatialVector(-axis, -rbXn), deltaVB);
const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA);
const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB);
/*const PxU32 pLinkInd = cLink.parent;
printf("(%i, %i) deltaV1(%f, %f, %f, %f, %f, %f)\n",
pLinkInd, tendonJoint.linkInd, deltaV1.linear.x, deltaV1.linear.y, deltaV1.linear.z, deltaV1.angular.x,
deltaV1.angular.y, deltaV1.angular.z);*/
const PxReal r0 = deltaV0.linear.dot(startAxis) + deltaV0.angular.dot(startRaXn);
const PxReal r1 = deltaV1.linear.dot(axis) + deltaV1.angular.dot(rbXn);
const PxReal unitResponse = r0 - r1;
const PxReal recipResponse = 1.0f / (unitResponse + cfm);
const PxU32 count = data.mInternalFixedTendonConstraints.size();
data.mInternalFixedTendonConstraints.forceSize_Unsafe(count + 1);
ArticulationInternalTendonConstraint* constraint = &data.mInternalFixedTendonConstraints[count];
tendonJoint.mConstraintInd = PxU16(count);
constraint->row0 = Cm::UnAlignedSpatialVector(startAxis, startRaXn);
constraint->row1 = Cm::UnAlignedSpatialVector(axis, rbXn);
constraint->deltaVA = r0; //We only need to record the change in velocity projected onto the dof for this!
constraint->deltaVB = Cm::UnAlignedSpatialVector(deltaV1.angular, deltaV1.linear);
constraint->linkID0 = startLink;
constraint->linkID1 = tendonJoint.linkInd;
constraint->recipResponse = recipResponse;
const PxReal a = stepDt * (stepDt*stiffness + damping);
const PxReal a2 = stepDt * (stepDt*limitStiffness + damping);
PxReal x = unitResponse > 0.f ? 1.0f / (1.0f + a * unitResponse) : 0.f;
PxReal x2 = unitResponse > 0.f ? 1.0f / (1.0f + a2* unitResponse) : 0.f;
constraint->velMultiplier = -x * a;// * unitResponse;
constraint->impulseMultiplier = isTGSSolver ? 1.f : 1.f - x;
constraint->biasCoefficient = (-stiffness * x * stepDt);//*unitResponse;
constraint->appliedForce = 0.f;
//constraint->accumulatedLength = jointPose;
constraint->limitImpulseMultiplier = isTGSSolver ? 1.f : 1.f - x2;
constraint->limitBiasCoefficient = (-limitStiffness * x2 * stepDt);//*unitResponse;
constraint->limitAppliedForce = 0.f;
/*printf("(%i, %i) r0 %f, r1 %f cmf %f unitResponse %f recipResponse %f a %f x %f\n",
pLinkInd, tendonJoint.linkInd, r0, r1, cLink.cfm, unitResponse, recipResponse, a, x);*/
}
const PxU32 childCount = tendonJoint.childCount;
if (childCount)
{
for (ArticulationBitField children = tendonJoint.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
setupInternalFixedTendonConstraintsRecursive(links, tendonJoints, fixBase, data, Z, stepDt,
isTGSSolver, child, stiffness, damping, limitStiffness, startLink, startAxis, startRaXn);
}
}
}
void FeatherstoneArticulation::setupInternalConstraints(
ArticulationLink* links,
const PxU32 linkCount,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
PxReal stepDt,
PxReal dt,
PxReal invDt,
bool isTGSSolver)
{
PX_UNUSED(linkCount);
data.mInternalConstraints.forceSize_Unsafe(0);
data.mInternalConstraints.reserve(data.getDofs());
data.mInternalLimits.forceSize_Unsafe(0);
data.mInternalLimits.reserve(data.getDofs());
const PxReal maxForceScale = data.getArticulationFlags() & PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES ? dt : 1.f;
const PxU32 numChildren = links[0].mNumChildren;
const PxU32 offset = links[0].mChildrenStartIndex;
for (PxU32 i = 0; i < numChildren; ++i)
{
const PxU32 child = offset + i;
setupInternalConstraintsRecursive(links, linkCount, fixBase, data, Z, stepDt, dt, invDt, isTGSSolver, child, maxForceScale);
}
PxU32 totalNumAttachments = 0;
for (PxU32 i = 0; i < data.mNumSpatialTendons; ++i)
{
Dy::ArticulationSpatialTendon* tendon = data.mSpatialTendons[i];
totalNumAttachments += tendon->getNumAttachments();
}
data.mInternalSpatialTendonConstraints.forceSize_Unsafe(0);
data.mInternalSpatialTendonConstraints.reserve(totalNumAttachments);
for (PxU32 i = 0; i < data.mNumSpatialTendons; ++i)
{
Dy::ArticulationSpatialTendon* tendon = data.mSpatialTendons[i];
Dy::ArticulationAttachment* attachments = tendon->getAttachments();
ArticulationAttachment& pAttachment = attachments[0];
//const PxU32 childCount = pAttachment.childCount;
//PxReal scale = 1.f/PxReal(childCount);
const PxReal coefficient = pAttachment.coefficient;
const PxU32 startLink = pAttachment.linkInd;
ArticulationLink& pLink = links[startLink];
const PxTransform pBody2World = pLink.bodyCore->body2World;
const PxVec3 ra = pBody2World.q.rotate(pAttachment.relativeOffset);
const PxVec3 pAttachPoint = pBody2World.p + ra;
for (ArticulationAttachmentBitField children = pAttachment.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
ArticulationAttachment& attachment = attachments[child];
ArticulationLink& cLink = links[attachment.linkInd];
const PxTransform cBody2World = cLink.bodyCore->body2World;
const PxVec3 rb = cBody2World.q.rotate(attachment.relativeOffset);
const PxVec3 cAttachPoint = cBody2World.p + rb;
const PxVec3 axis = (pAttachPoint - cAttachPoint).getNormalized();
const PxVec3 raXn = ra.cross(axis);
setupInternalSpatialTendonConstraintsRecursive(links, attachments, tendon->getNumAttachments(), pAttachPoint, fixBase, data, Z, stepDt, isTGSSolver,
child, tendon->mStiffness, tendon->mDamping, tendon->mLimitStiffness, tendon->mOffset*coefficient, startLink,
axis, raXn);
}
}
PxU32 totalNumTendonJoints = 0;
for (PxU32 i = 0; i < data.mNumFixedTendons; ++i)
{
Dy::ArticulationFixedTendon* tendon = data.mFixedTendons[i];
totalNumTendonJoints += tendon->getNumJoints();
}
data.mInternalFixedTendonConstraints.forceSize_Unsafe(0);
data.mInternalFixedTendonConstraints.reserve(totalNumTendonJoints);
for (PxU32 i = 0; i < data.mNumFixedTendons; ++i)
{
ArticulationFixedTendon* tendon = data.mFixedTendons[i];
ArticulationTendonJoint* tendonJoints = tendon->getTendonJoints();
ArticulationTendonJoint& pTendonJoint = tendonJoints[0];
const PxU32 startLinkInd = pTendonJoint.linkInd;
ArticulationLink& pLink = links[startLinkInd];
const PxTransform& pBody2World = pLink.bodyCore->body2World;
for (ArticulationAttachmentBitField children = pTendonJoint.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
ArticulationTendonJoint& cTendonJoint = tendonJoints[child];
ArticulationLink& cLink = links[cTendonJoint.linkInd];
ArticulationJointCore* joint = cLink.inboundJoint;
PX_ASSERT(joint != NULL);
ArticulationJointCoreData* jointDatum = &data.getJointData(cTendonJoint.linkInd);
PxU16 tendonJointAxis = cTendonJoint.axis;
PX_ASSERT(joint->motion[tendonJointAxis] != PxArticulationMotion::eLOCKED);
PxVec3 startAxis, raXn;
PxU32 dofIndex = joint->invDofIds[tendonJointAxis];
if (tendonJointAxis < PxArticulationAxis::eX)
{
const PxVec3 axis = data.mWorldMotionMatrix[jointDatum->jointOffset + dofIndex].top;
startAxis = PxVec3(0.f);
raXn = axis;
}
else
{
// PT:: tag: scalar transform*transform
const PxTransform cA2w = pBody2World.transform(joint->parentPose);
const PxVec3 axis = data.mWorldMotionMatrix[jointDatum->jointOffset + dofIndex].bottom;
const PxVec3 ang0 = (cA2w.p - pBody2World.p).cross(axis);
startAxis = axis;
raXn = ang0;
}
setupInternalFixedTendonConstraintsRecursive(links, tendonJoints, fixBase, data, Z, stepDt, isTGSSolver,
child, tendon->mStiffness, tendon->mDamping, tendon->mLimitStiffness, startLinkInd, startAxis, raXn);
}
}
}
PxU32 FeatherstoneArticulation::setupSolverConstraints(
ArticulationLink* links,
const PxU32 linkCount,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
PxU32& acCount)
{
acCount = 0;
setupInternalConstraints(links, linkCount, fixBase, data, Z, data.getDt(), data.getDt(), 1.f / data.getDt(), false);
return 0;
}
PxU32 FeatherstoneArticulation::setupSolverConstraintsTGS(const ArticulationSolverDesc& articDesc,
PxReal dt,
PxReal invDt,
PxReal totalDt,
PxU32& acCount,
Cm::SpatialVectorF* Z)
{
PX_UNUSED(dt);
PX_UNUSED(totalDt);
acCount = 0;
FeatherstoneArticulation* thisArtic = static_cast<FeatherstoneArticulation*>(articDesc.articulation);
ArticulationLink* links = thisArtic->mArticulationData.getLinks();
const PxU32 linkCount = thisArtic->mArticulationData.getLinkCount();
const bool fixBase = thisArtic->mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
thisArtic->setupInternalConstraints(links, linkCount, fixBase, thisArtic->mArticulationData, Z, dt, totalDt, invDt, true);
return 0;
}
void FeatherstoneArticulation::teleportLinks(ArticulationData& data)
{
ArticulationLink* links = mArticulationData.getLinks();
ArticulationJointCoreData* jointData = mArticulationData.getJointData();
const PxReal* jointPositions = data.getJointPositions();
const PxU32 linkCount = mArticulationData.getLinkCount();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
const ArticulationJointCoreData& jointDatum = jointData[linkID];
const ArticulationLink& pLink = links[link.parent];
const PxTransform pBody2World = pLink.bodyCore->body2World;
const ArticulationJointCore* joint = link.inboundJoint;
const PxReal* jPosition = &jointPositions[jointDatum.jointOffset];
PxQuat newParentToChild;
PxQuat newWorldQ;
PxVec3 r;
const PxVec3 childOffset = -joint->childPose.p;
const PxVec3 parentOffset = joint->parentPose.p;
const PxQuat relativeQuat = mArticulationData.mRelativeQuat[linkID];
switch (joint->jointType)
{
case PxArticulationJointType::ePRISMATIC:
{
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].bottom;
r = e + d + u * jPosition[0];
break;
}
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].top;
PxQuat jointRotation = PxQuat(-jPosition[0], u);
if (jointRotation.w < 0) //shortest angle.
jointRotation = -jointRotation;
newParentToChild = (jointRotation * relativeQuat).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eSPHERICAL:
{
PxQuat jointRotation(PxIdentity);
{
PxVec3 axis(0.f);
for (PxU32 d = 0; d < jointDatum.dof; ++d)
{
axis += data.mMotionMatrix[jointDatum.jointOffset + d].top * -jPosition[d];
}
PxReal angle = axis.normalize();
jointRotation = angle < 1e-10f ? PxQuat(PxIdentity) : PxQuat(angle, axis);
if(jointRotation.w < 0.f)
jointRotation = -jointRotation;
}
newParentToChild = (jointRotation * relativeQuat).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
break;
}
case PxArticulationJointType::eFIX:
{
//this is fix joint so joint don't have velocity
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
break;
}
default:
break;
}
PxTransform& body2World = link.bodyCore->body2World;
body2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized();
body2World.p = pBody2World.p + body2World.q.rotate(r);
PX_ASSERT(body2World.isSane());
}
}
void FeatherstoneArticulation::computeLinkVelocities(ArticulationData& data)
{
ArticulationLink* links = data.getLinks();
const PxU32 linkCount = data.getLinkCount();
Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities();
const PxReal* jointVelocities = data.mJointVelocity.begin();
// sync root motion vel:
const PxsBodyCore& rootBodyCore = *links[0].bodyCore;
motionVelocities[0].top = rootBodyCore.angularVelocity;
motionVelocities[0].bottom = rootBodyCore.linearVelocity;
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
PxsBodyCore& bodyCore = *link.bodyCore;
PxTransform body2World = bodyCore.body2World;
ArticulationLink& plink = links[link.parent];
const PxsBodyCore& pbodyCore = *plink.bodyCore;
Cm::SpatialVectorF parentVel(pbodyCore.angularVelocity, pbodyCore.linearVelocity);
PxTransform pBody2World = pbodyCore.body2World;
const PxVec3 rw = body2World.p - pBody2World.p;
Cm::SpatialVectorF vel = FeatherstoneArticulation::translateSpatialVector(-rw,parentVel);
if (jointVelocities)
{
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
const PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset];
Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero();
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
deltaV += data.mMotionMatrix[jointDatum.jointOffset + ind] * jVelocity[ind];
}
vel.top += body2World.q.rotate(deltaV.top);
vel.bottom += body2World.q.rotate(deltaV.bottom);
}
bodyCore.linearVelocity = vel.bottom;
bodyCore.angularVelocity = vel.top;
motionVelocities[linkID] = vel;
}
}
// AD: needed because we define the templated function in a CPP.
template void FeatherstoneArticulation::jcalc<false>(ArticulationData& data);
template void FeatherstoneArticulation::jcalc<true>(ArticulationData& data);
template<bool immediateMode>
void FeatherstoneArticulation::jcalc(ArticulationData& data)
{
const ArticulationLink* links = data.getLinks();
ArticulationJointCoreData* jointData = data.getJointData();
const PxU32 linkCount = data.getLinkCount();
PxU32 totalDof = 0;
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationJointCore* joint = link.inboundJoint;
ArticulationJointCoreData& jointDatum = jointData[linkID];
PX_CHECK_AND_RETURN(joint->jointType != PxArticulationJointType::eUNDEFINED, "FeatherstoneArticulation::jcalc application need to define valid joint type and motion");
//compute joint dof
const PxU32 dof = jointDatum.computeJointDof(joint, data.mJointAxis.begin() + totalDof);
joint->setJointFrame(&data.mMotionMatrix[totalDof], &data.mJointAxis[totalDof], mArticulationData.mRelativeQuat[linkID], dof);
// AD: only used in immediate mode because we don't have the llArticulation there to write directly.
if (immediateMode)
{
PxReal* PX_RESTRICT jointTargetPositions = data.getJointTargetPositions();
PxReal* PX_RESTRICT jointTargetVelocities = data.getJointTargetVelocities();
for (PxU32 dofId = 0; dofId < dof; ++dofId)
{
PxU32 id = totalDof + dofId;
PxU32 llDofId = joint->dofIds[dofId];
jointTargetPositions[id] = joint->targetP[llDofId];
jointTargetVelocities[id] = joint->targetV[llDofId];
}
joint->jointDirtyFlag &= ~(ArticulationJointCoreDirtyFlag::eTARGETPOSE | ArticulationJointCoreDirtyFlag::eTARGETVELOCITY);
}
jointDatum.setArmature(joint);
jointDatum.jointOffset = totalDof;
joint->jointOffset = totalDof;
totalDof += dof;
}
if (totalDof != mArticulationData.getDofs())
{
mArticulationData.resizeJointData(totalDof);
}
mArticulationData.setDofs(totalDof);
}
//compute link's spatial inertia tensor
void FeatherstoneArticulation::computeSpatialInertia(ArticulationData& data)
{
for (PxU32 linkID = 0; linkID < data.getLinkCount(); ++linkID)
{
const ArticulationLink& link = data.getLink(linkID);
//ArticulationLinkData& linkDatum = data.getLinkData(linkID);
const PxsBodyCore& core = *link.bodyCore;
const PxVec3& ii = core.inverseInertia;
const PxReal m = core.inverseMass == 0.f ? 0.f : 1.0f / core.inverseMass;
SpatialMatrix& worldArticulatedInertia = data.mWorldSpatialArticulatedInertia[linkID];
//construct inertia matrix
const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z));
PxMat33 rot(data.getLink(linkID).bodyCore->body2World.q);
worldArticulatedInertia.topLeft = PxMat33(PxZero);
worldArticulatedInertia.topRight = PxMat33::createDiagonal(PxVec3(m));
Cm::transformInertiaTensor(inertiaTensor, rot, worldArticulatedInertia.bottomLeft);
data.mWorldIsolatedSpatialArticulatedInertia[linkID] = worldArticulatedInertia.bottomLeft;
data.mMasses[linkID] = m;
}
}
void FeatherstoneArticulation::computeZ(const ArticulationData& data,
const PxVec3& gravity, ScratchData& scratchData)
{
const Cm::SpatialVectorF* motionVelocities = scratchData.motionVelocities;
Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors;
const Cm::SpatialVector* externalAccels = scratchData.externalAccels;
for (PxU32 linkID = 0; linkID < data.getLinkCount(); ++linkID)
{
ArticulationLink& link = data.getLink(linkID);
const PxsBodyCore& core = *link.bodyCore;
//const PxTransform& body2World = core.body2World;
const PxMat33& I = data.mWorldSpatialArticulatedInertia[linkID].bottomLeft;
//construct spatial zero acceleration
Cm::SpatialVectorF& z = spatialZAForces[linkID];
//Cm::SpatialVectorF v;
//v.top = motionVelocities[linkID].top;
//v.bottom = motionVelocities[linkID].bottom;
//KS - limit the magnitude of the angular velocity that contributes to the geometric term. This is a
//v^2 term and can become unstable if it is too large!
Cm::SpatialVectorF v = motionVelocities[linkID];
PxVec3 vA = v.top;
PxVec3 gravLinAccel(0.f);
if(!core.disableGravity)
gravLinAccel = -gravity;
PX_ASSERT(core.inverseMass != 0.f);
const PxReal m = 1.0f / core.inverseMass;
Cm::SpatialVectorF zTmp;
zTmp.top = (gravLinAccel * m);
zTmp.bottom = vA.cross(I * vA);
PX_ASSERT(zTmp.top.isFinite());
PX_ASSERT(zTmp.bottom.isFinite());
if (externalAccels)
{
const Cm::SpatialVector& externalAccel = externalAccels[linkID];
const PxVec3 exLinAccel = -externalAccel.linear;
const PxVec3 exAngAccel = -externalAccel.angular;
zTmp.top += (exLinAccel * m);
zTmp.bottom += I * exAngAccel;
}
z = zTmp;
}
}
void FeatherstoneArticulation::computeZD(const ArticulationData& data,
const PxVec3& gravity, ScratchData& scratchData)
{
const Cm::SpatialVectorF* motionVelocities = scratchData.motionVelocities;
Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors;
const Cm::SpatialVector* externalAccels = scratchData.externalAccels;
const PxReal dt = data.getDt();
const PxReal invDt = dt < 1e-6f ? PX_MAX_F32 : 1.f / data.mDt;
for (PxU32 linkID = 0; linkID < data.getLinkCount(); ++linkID)
{
ArticulationLink& link = data.getLink(linkID);
const PxsBodyCore& core = *link.bodyCore;
//const PxTransform& body2World = core.body2World;
const PxMat33& I = data.mWorldSpatialArticulatedInertia[linkID].bottomLeft;
//construct spatial zero acceleration
Cm::SpatialVectorF& z = spatialZAForces[linkID];
//Cm::SpatialVectorF v;
//v.top = motionVelocities[linkID].top;
//v.bottom = motionVelocities[linkID].bottom;
//KS - limit the magnitude of the angular velocity that contributes to the geometric term. This is a
//v^2 term and can become unstable if it is too large!
Cm::SpatialVectorF v = motionVelocities[linkID];
PxVec3 vA = v.top;
PxVec3 gravLinAccel(0.f);
if (!core.disableGravity)
gravLinAccel = -gravity;
PX_ASSERT(core.inverseMass != 0.f);
const PxReal m = 1.0f / core.inverseMass;
Cm::SpatialVectorF zTmp;
zTmp.top = (gravLinAccel * m);
zTmp.bottom = vA.cross(I * vA);
PX_ASSERT(zTmp.top.isFinite());
PX_ASSERT(zTmp.bottom.isFinite());
if (externalAccels)
{
const Cm::SpatialVector& externalAccel = externalAccels[linkID];
const PxVec3 exLinAccel = -externalAccel.linear;
const PxVec3 exAngAccel = -externalAccel.angular;
zTmp.top += (exLinAccel * m);
zTmp.bottom += I * exAngAccel;
}
if (core.linearDamping > 0.f || core.angularDamping > 0.f)
{
const PxReal linDamp = PxMin(core.linearDamping, invDt);
const PxReal angDamp = PxMin(core.angularDamping, invDt);
zTmp.top += (v.bottom * linDamp*m) - zTmp.top * linDamp*dt;
zTmp.bottom += I * (v.top* angDamp) - zTmp.bottom * angDamp*dt;
}
const PxReal maxAng = core.maxAngularVelocitySq;
const PxReal maxLin = core.maxLinearVelocitySq;
const PxReal angMag = v.top.magnitudeSquared();
const PxReal linMag = v.bottom.magnitudeSquared();
if (angMag > maxAng || linMag > maxLin)
{
if (angMag > maxAng)
{
const PxReal scale = 1.f - PxSqrt(maxAng) / PxSqrt(angMag);
const PxVec3 tmpaccelerationAng = (I * v.top)*scale;
zTmp.bottom += tmpaccelerationAng*invDt;
}
if (linMag > maxLin)
{
const PxReal scale = 1.f - (PxSqrt(maxLin) / PxSqrt(linMag));
const PxVec3 tmpaccelerationLin = (v.bottom*m*scale);
PX_UNUSED(tmpaccelerationLin);
zTmp.top += tmpaccelerationLin*invDt;
}
}
z = zTmp;
}
}
//compute coriolis and centrifugal term
void FeatherstoneArticulation::computeC(ArticulationData& data, ScratchData& scratchData)
{
const PxReal* jointVelocities = scratchData.jointVelocities;
Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors;
const PxU32 linkCount = data.getLinkCount();
coriolisVectors[0] = Cm::SpatialVectorF::Zero();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = data.getLink(linkID);
const ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
const PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset];
Cm::SpatialVectorF& coriolis = coriolisVectors[linkID];
//const PxTransform& body2World = link.bodyCore->body2World;
//transform parent link's angular velocity into current link's body space
const PxVec3 pAngular = scratchData.motionVelocities[link.parent].top;
PxVec3 torque = pAngular.cross(pAngular.cross(data.getRw(linkID)));
//PX_ASSERT(parentAngular.magnitude() < 100.f);
PxVec3 force(0.f);
if (jointDatum.dof > 0)
{
Cm::SpatialVectorF relVel(PxVec3(0.f), PxVec3(0.f));
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
//Clamp joint velocity used in coriolis terms to reduce chances of unstable feed-back loops
const PxReal jV = jVelocity[ind];
relVel.top += data.mWorldMotionMatrix[jointDatum.jointOffset + ind].top * jV;
relVel.bottom += data.mWorldMotionMatrix[jointDatum.jointOffset + ind].bottom * jV;
}
const PxVec3 aVec = relVel.top;
force = pAngular.cross(aVec);
//compute linear part
const PxVec3 lVel = relVel.bottom;
const PxVec3 temp1 = 2.f * pAngular.cross(lVel);
const PxVec3 temp2 = aVec.cross(lVel);
torque += temp1 + temp2;
}
PX_ASSERT(force.isFinite());
PX_ASSERT(torque.isFinite());
coriolis = Cm::SpatialVectorF(force, torque);//.rotateInv(body2World);
}
}
void FeatherstoneArticulation::computeRelativeTransformC2P(
const ArticulationLink* links, const PxU32 linkCount, const ArticulationJointCoreData* jointCoreDatas,
const Cm::UnAlignedSpatialVector* jonitDofMotionMatrices,
PxTransform* linkAccumulatedPoses, PxVec3* linkRws, Cm::UnAlignedSpatialVector* jointDofMotionMatricesW)
{
linkAccumulatedPoses[0] = links[0].bodyCore->body2World;
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
const PxsBodyCore& bodyCore = *link.bodyCore;
const PxU32 jointOffset = jointCoreDatas[linkID].jointOffset;
const PxU32 dofCount = jointCoreDatas[linkID].dof;
const PxTransform& body2World = bodyCore.body2World;
const ArticulationLink& pLink = links[link.parent];
const PxsBodyCore& pBodyCore = *pLink.bodyCore;
const PxTransform& pBody2World = pBodyCore.body2World;
//const PxTransform tC2P = pBody2World.transformInv(body2World).getNormalized();
linkRws[linkID] =body2World.p - pBody2World.p;
const Cm::UnAlignedSpatialVector* motionMatrix = &jonitDofMotionMatrices[jointOffset];
Cm::UnAlignedSpatialVector* worldMotionMatrix = &jointDofMotionMatricesW[jointOffset];
for (PxU32 i = 0; i < dofCount; ++i)
{
const Cm::UnAlignedSpatialVector worldRow = motionMatrix[i].rotate(body2World);
worldMotionMatrix[i] = worldRow;
}
linkAccumulatedPoses[linkID] = body2World;
#if FEATURESTONE_DEBUG
{
//debug
PxMat33 pToC = c2p.getTranspose();
//parentToChild -rR
PxMat33 T2 = skewMatrixPR * pToC;
PX_ASSERT(SpatialMatrix::isTranspose(linkDatum.childToParent.T, T2));
}
#endif
}
}
void FeatherstoneArticulation::computeRelativeTransformC2B(ArticulationData& data)
{
ArticulationLink* links = data.getLinks();
ArticulationLinkData* linkData = data.getLinkData();
const PxU32 linkCount = data.getLinkCount();
const ArticulationLink& bLink = links[0];
const PxTransform& bBody2World = bLink.bodyCore->body2World;
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationLinkData& linkDatum = linkData[linkID];
const PxsBodyCore& bodyCore = *link.bodyCore;
const PxTransform& body2World = bodyCore.body2World;
const PxVec3 rw = body2World.p - bBody2World.p;//body space of link i
//rotation matrix cToP's inverse is rotation matrix pToC
linkDatum.childToBase = rw;
}
}
void FeatherstoneArticulation::getDenseJacobian(PxArticulationCache& cache, PxU32 & nRows, PxU32 & nCols)
{
//make sure motionMatrix has been set
//jcalc(mArticulationData);
initializeCommonData();
const PxU32 linkCount = mArticulationData.getLinkCount();
ArticulationLink* links = mArticulationData.getLinks();
#if 0 //Enable this if you want to compare results of this function with results of computeLinkVelocities().
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getDenseJacobian(): commonInit need to be called first to initialize data!");
return;
}
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
scratchData.jointVelocities = mArticulationData.getJointVelocities();
computeLinkVelocities(mArticulationData, scratchData);
const ArticulationLink& baseLink = links[0];
PxsBodyCore& core0 = *baseLink.bodyCore;
#endif
ArticulationLinkData* linkData = mArticulationData.getLinkData();
const PxU32 totalDofs = getDofs();
const PxU32 jointCount = mArticulationData.getLinkCount() - 1;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
//matrix dims is
nCols = (fixBase ? 0 : 6) + totalDofs;
nRows = (fixBase ? 0 : 6) + jointCount * 6;
// auto jacobian = [&](PxU32 row, PxU32 col) -> PxReal & { return cache.denseJacobian[nCols * row + col]; } ;
#define jacobian(row, col) cache.denseJacobian[nCols * (row) + (col)]
PxU32 destRow = 0;
PxU32 destCol = 0;
if (!fixBase)
{
jacobian(0, 0) = 1.0f;
jacobian(0, 1) = 0.0f;
jacobian(0, 2) = 0.0f;
jacobian(0, 3) = 0.0f;
jacobian(0, 4) = 0.0f;
jacobian(0, 5) = 0.0f;
jacobian(1, 0) = 0.0f;
jacobian(1, 1) = 1.0f;
jacobian(1, 2) = 0.0f;
jacobian(1, 3) = 0.0f;
jacobian(1, 4) = 0.0f;
jacobian(1, 5) = 0.0f;
jacobian(2, 0) = 0.0f;
jacobian(2, 1) = 0.0f;
jacobian(2, 2) = 1.0f;
jacobian(2, 3) = 0.0f;
jacobian(2, 4) = 0.0f;
jacobian(2, 5) = 0.0f;
jacobian(3, 0) = 0.0f;
jacobian(3, 1) = 0.0f;
jacobian(3, 2) = 0.0f;
jacobian(3, 3) = 1.0f;
jacobian(3, 4) = 0.0f;
jacobian(3, 5) = 0.0f;
jacobian(4, 0) = 0.0f;
jacobian(4, 1) = 0.0f;
jacobian(4, 2) = 0.0f;
jacobian(4, 3) = 0.0f;
jacobian(4, 4) = 1.0f;
jacobian(4, 5) = 0.0f;
jacobian(5, 0) = 0.0f;
jacobian(5, 1) = 0.0f;
jacobian(5, 2) = 0.0f;
jacobian(5, 3) = 0.0f;
jacobian(5, 4) = 0.0f;
jacobian(5, 5) = 1.0f;
destRow += 6;
destCol += 6;
}
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)//each iteration of this writes 6 rows in the matrix
{
const ArticulationLink& link = links[linkID];
ArticulationLinkData& linkDatum = linkData[linkID];
const PxsBodyCore& bodyCore = *link.bodyCore;
linkDatum.maxPenBias = bodyCore.maxPenBias;
const PxTransform& body2World = bodyCore.body2World;
const ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
const PxU32 parentLinkID = link.parent;
if (parentLinkID || !fixBase)
{
// VR: mArticulationData.getJointData(0) isn't initialized. parentLinkID can be 0 if fixBase is false.
//const ArticulationJointCoreData& parentJointDatum = mArticulationData.getJointData(parentLinkID);
//const PxU32 parentsFirstDestCol = parentJointDatum.jointOffset + (fixBase ? 0 : 6);
//const PxU32 parentsLastDestCol = parentsFirstDestCol + parentJointDatum.dof;
const PxU32 parentsLastDestCol = parentLinkID ?
mArticulationData.getJointData(parentLinkID).jointOffset + (fixBase ? 0 : 6) + mArticulationData.getJointData(parentLinkID).dof :
6;
// VR: With parentLinkID == 0 this expression has two unsigned integer overflows, but the result is still correct.
const PxU32 parentsDestRow = (fixBase ? 0 : 6) + (parentLinkID - 1) * 6;
for (PxU32 col = 0; col < parentsLastDestCol; col++)
{
//copy downward the 6 cols from parent
const PxVec3 parentAng(
jacobian(parentsDestRow + 3, col),
jacobian(parentsDestRow + 4, col),
jacobian(parentsDestRow + 5, col)
);
const PxVec3 parentAngxRw = parentAng.cross(mArticulationData.getRw(linkID));
jacobian(destRow + 0, col) = jacobian(parentsDestRow + 0, col) + parentAngxRw.x;
jacobian(destRow + 1, col) = jacobian(parentsDestRow + 1, col) + parentAngxRw.y;
jacobian(destRow + 2, col) = jacobian(parentsDestRow + 2, col) + parentAngxRw.z;
jacobian(destRow + 3, col) = parentAng.x;
jacobian(destRow + 4, col) = parentAng.y;
jacobian(destRow + 5, col) = parentAng.z;
}
for (PxU32 col = parentsLastDestCol; col < destCol; col++)
{
//fill with zeros.
jacobian(destRow + 0, col) = 0.0f;
jacobian(destRow + 1, col) = 0.0f;
jacobian(destRow + 2, col) = 0.0f;
jacobian(destRow + 3, col) = 0.0f;
jacobian(destRow + 4, col) = 0.0f;
jacobian(destRow + 5, col) = 0.0f;
}
}
//diagonal block:
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
const Cm::UnAlignedSpatialVector& v = mArticulationData.mMotionMatrix[jointDatum.jointOffset + ind];
const PxVec3 ang = body2World.rotate(v.top);
const PxVec3 lin = body2World.rotate(v.bottom);
jacobian(destRow + 0, destCol) = lin.x;
jacobian(destRow + 1, destCol) = lin.y;
jacobian(destRow + 2, destCol) = lin.z;
jacobian(destRow + 3, destCol) = ang.x;
jacobian(destRow + 4, destCol) = ang.y;
jacobian(destRow + 5, destCol) = ang.z;
destCol++;
}
//above diagonal block: always zero
for (PxU32 col = destCol; col < nCols; col++)
{
jacobian(destRow + 0, col) = 0.0f;
jacobian(destRow + 1, col) = 0.0f;
jacobian(destRow + 2, col) = 0.0f;
jacobian(destRow + 3, col) = 0.0f;
jacobian(destRow + 4, col) = 0.0f;
jacobian(destRow + 5, col) = 0.0f;
}
destRow += 6;
}
#undef jacobian
#if 0 //Enable this if you want to compare results of this function with results of computeLinkVelocities().
PxReal * jointVels = mArticulationData.getJointVelocities();//size is totalDofs
PxReal * jointSpaceVelsVector = new PxReal[nCols];
PxReal * worldSpaceVelsVector = new PxReal[nRows];
PxU32 offset = 0;
//stack input:
if (!fixBase)
{
jointSpaceVelsVector[0] = core0.linearVelocity[0];
jointSpaceVelsVector[1] = core0.linearVelocity[1];
jointSpaceVelsVector[2] = core0.linearVelocity[2];
jointSpaceVelsVector[3] = core0.angularVelocity[0];
jointSpaceVelsVector[4] = core0.angularVelocity[1];
jointSpaceVelsVector[5] = core0.angularVelocity[2];
offset = 6;
}
for (PxU32 i = 0; i < totalDofs; i++)
jointSpaceVelsVector[i + offset] = jointVels[i];
//multiply:
for (PxU32 row = 0; row < nRows; row++)
{
worldSpaceVelsVector[row] = 0.0f;
for (PxU32 col = 0; col < nCols; col++)
{
worldSpaceVelsVector[row] += jacobian(row, col)*jointSpaceVelsVector[col];
}
}
//worldSpaceVelsVector should now contain the same result as scratchData.motionVelocities (except for swapped linear/angular vec3 order).
delete[] jointSpaceVelsVector;
delete[] worldSpaceVelsVector;
allocator->free(tempMemory);
#endif
}
void FeatherstoneArticulation::computeLinkStates(
const PxF32 dt, const PxReal invLengthScale, const PxVec3& gravity,
const bool fixBase,
const PxU32 linkCount,
const PxTransform* linkAccumulatedPosesW, const Cm::SpatialVector* linkExternalAccelsW, const PxVec3* linkRsW, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const Dy::ArticulationJointCoreData* jointCoreData,
Dy::ArticulationLinkData *linkData, Dy::ArticulationLink* links,
Cm::SpatialVectorF* jointDofMotionAccelerations, Cm::SpatialVectorF* jointDofMotionVelocities,
Cm::SpatialVectorF* linkZAExtForcesW, Cm::SpatialVectorF* linkZAIntForcesW, Cm::SpatialVectorF* linkCoriolisVectorsW,
PxMat33* linkIsolatedSpatialArticulatedInertiasW, PxF32* linkMasses, Dy::SpatialMatrix* linkSpatialArticulatedInertiasW,
const PxU32 jointDofCount,
PxReal* jointDofVelocities,
Cm::SpatialVectorF& rootPreMotionVelocityW, PxVec3& comW, PxF32& invSumMass)
{
PX_UNUSED(jointDofCount);
const PxReal invDt = dt < 1e-6f ? PX_MAX_F32 : 1.f / dt;
//Initialise motion velocity, motion acceleration and coriolis vector of root link.
Cm::SpatialVectorF rootLinkVel;
{
const Dy::ArticulationLink& baseLink = links[0];
const PxsBodyCore& core0 = *baseLink.bodyCore;
rootLinkVel = fixBase ? Cm::SpatialVectorF::Zero() : Cm::SpatialVectorF(core0.angularVelocity, core0.linearVelocity);
jointDofMotionVelocities[0] = rootLinkVel;
jointDofMotionAccelerations[0] = fixBase ? Cm::SpatialVectorF::Zero() : jointDofMotionAccelerations[0];
linkCoriolisVectorsW[0] = Cm::SpatialVectorF::Zero();
rootPreMotionVelocityW = rootLinkVel;
}
PxReal ratio = 1.f;
if (jointDofVelocities)
{
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
const ArticulationJointCoreData& jointDatum = jointCoreData[linkID];
PxReal* jVelocity = &jointDofVelocities[jointDatum.jointOffset];
const PxReal maxJVelocity = link.inboundJoint->maxJointVelocity;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
PxReal jVel = jVelocity[ind];
ratio = (jVel != 0.0f) ? PxMin(ratio, maxJVelocity / PxAbs(jVel)) : ratio;
}
}
}
PxReal sumMass = 0.f;
PxVec3 COM(0.f);
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
ArticulationLinkData& linkDatum = linkData[linkID];
const PxsBodyCore& bodyCore = *link.bodyCore;
//Set the maxPemBias and cfm values from bodyCore
linkDatum.maxPenBias = bodyCore.maxPenBias;
link.cfm = (fixBase && linkID == 0) ? 0.f : bodyCore.cfmScale * invLengthScale;
//Read the inertia and mass from bodyCore
const PxVec3& ii = bodyCore.inverseInertia;
const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z));
const PxReal invMass = bodyCore.inverseMass;
const PxReal m = invMass == 0.f ? 0.f : 1.0f / invMass;
//Compute the inertia matrix Iw = R * I * Rtranspose
//Compute the articulated inertia.
PxMat33 Iw; //R * I * Rtranspose
SpatialMatrix worldArticulatedInertia;
{
PxMat33 rot(linkAccumulatedPosesW[linkID].q);
Cm::transformInertiaTensor(inertiaTensor, rot, Iw);
worldArticulatedInertia.topLeft = PxMat33(PxZero);
worldArticulatedInertia.topRight = PxMat33::createDiagonal(PxVec3(m));
worldArticulatedInertia.bottomLeft = Iw;
}
//Set the articulated inertia, inertia and mass of the link.
linkSpatialArticulatedInertiasW[linkID] = worldArticulatedInertia;
linkIsolatedSpatialArticulatedInertiasW[linkID] = Iw;
linkMasses[linkID] = m;
//Accumulate the centre of mass.
sumMass += m;
COM += linkAccumulatedPosesW[linkID].p * m;
Cm::SpatialVectorF vel;
if (linkID != 0)
{
//Propagate spatial velocity of link parent to link's spatial velocity.
const Cm::SpatialVectorF pVel = jointDofMotionVelocities[link.parent];
vel = FeatherstoneArticulation::translateSpatialVector(-linkRsW[linkID], pVel);
//Propagate joint dof velocities to the link's spatial velocity vector.
//Accumulate spatial forces that the joint applies to the link.
if (jointDofVelocities)
{
//The coriolis vector depends on the type of joint and the joint motion matrix.
//However, some terms in the coriolis vector are common to all joint types.
//Write down the term that is independent of the joint.
Cm::SpatialVectorF coriolisVector(PxVec3(PxZero), pVel.top.cross(pVel.top.cross(linkRsW[linkID])));
const ArticulationJointCoreData& jointDatum = jointCoreData[linkID];
if (jointDatum.dof)
{
//Compute the effect of the joint velocities on the link.
PxReal* jVelocity = &jointDofVelocities[jointDatum.jointOffset];
Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero();
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
PxReal jVel = jVelocity[ind] * ratio;
deltaV += jointDofMotionMatricesW[jointDatum.jointOffset + ind] * jVel;
jVelocity[ind] = jVel;
}
//Add the effect of the joint velocities to the link.
vel.top += deltaV.top;
vel.bottom += deltaV.bottom;
//Compute the coriolis vector.
//mu(i) is the velocity arising from the joint motion: mu(i) = motionMatrix*qdot
//where qdot is the joint velocity.
//mu(i) is already computed and cached in deltaV.
//For the revolute joint we have:
//deltaV = {mu(i), mu(i) X d(i)}
//coriolis vector += {omega(i-1) X mu(i), 2*omega(i-1) X (mu(i) X d(i)) + mu(i) X (mu(i) X d(i))}
//For the prismatic joint we have:
//deltaV = {0, mu(i)}
//coriolis vector += {0, 2*omega(i-1) X mu(i)}
coriolisVector += Cm::SpatialVectorF(pVel.top.cross(deltaV.top), 2.0f*pVel.top.cross(deltaV.bottom) + deltaV.top.cross(deltaV.bottom));
}
//TODOGY - if jointVelocities is null we do not appear to set coriolisVectors[linkId] but we do set coriolisVectors[0]
linkCoriolisVectorsW[linkID] = coriolisVector;
}
//PX_ASSERT(vel.top.isFinite() && PxAbs(vel.top.x) < 10000.f && PxAbs(vel.top.y) < 10000.f && PxAbs(vel.top.z) < 10000.f);
//PX_ASSERT(vel.bottom.isFinite() && PxAbs(vel.bottom.x) < 10000.f && PxAbs(vel.bottom.y) < 10000.f && PxAbs(vel.bottom.z) < 10000.f);
jointDofMotionVelocities[linkID] = vel;
}
else
{
vel = rootLinkVel;
//Note: we have already set motionVelocities[0] and coriolisVectors[0] so no need to set them again.
}
//Account for force arising from external accelerations
//Account for damping force arising from the velocity and from the velocity that will accumulate from the acceleration terms.
//Account for scaling force that will bring velocity back to the maximum allowed velocity if velocity exceed the maximum allowed.
//Example for the linear term:
//acceleration force = m*(g + extLinAccel)
//linVelNew = linVel + (g + extLinAccel)*dt
//damping force = -m*linVelNew*linDamp = -m*linVel*linDamp - m*(g + extLinAccel)*linDamp*dt
//scaling force = -m*linVel*linScale/dt with linScale = (1.0f - maxLinVel/linVel)
//Put it all together
// m*(g + extLinAccel)*(1 - linDamp*dt) - m*linVel*(linDamp + linScale/dt)
//Bit more reordering:
//m*[g + extLinAccel)*(1 - linDamp*dt) - linVel*(linDamp + linScale/dt)]
//Zero acceleration means we need to work against change:
//-m*[g + extLinAccel)*(1 - linDamp*dt) - linVel*(linDamp + linScale/dt)]
Cm::SpatialVectorF zTmp;
{
const PxVec3 g = bodyCore.disableGravity ? PxVec3(PxZero) : gravity;
const PxVec3 extLinAccel = linkExternalAccelsW ? linkExternalAccelsW[linkID].linear : PxVec3(PxZero);
const PxF32 lindamp = bodyCore.linearDamping > 0.f ? PxMin(bodyCore.linearDamping, invDt) : 0.0f;
const PxF32 linscale = (vel.bottom.magnitudeSquared() > bodyCore.maxLinearVelocitySq) ? (1.0f - (PxSqrt(bodyCore.maxLinearVelocitySq)/PxSqrt(vel.bottom.magnitudeSquared()))): 0.0f;
zTmp.top = -(m*((g + extLinAccel)*(1.0f - lindamp*dt) - vel.bottom*(lindamp + linscale*invDt)));
}
{
const PxVec3 extAngAccel = linkExternalAccelsW ? linkExternalAccelsW[linkID].angular : PxVec3(PxZero);
const PxF32 angdamp = bodyCore.angularDamping > 0.f ? PxMin(bodyCore.angularDamping, invDt) : 0.0f;
const PxF32 angscale = (vel.top.magnitudeSquared() > bodyCore.maxAngularVelocitySq) ? (1.0f - (PxSqrt(bodyCore.maxAngularVelocitySq)/PxSqrt(vel.top.magnitudeSquared()))) : 0.0f;
zTmp.bottom = -(Iw*(extAngAccel*(1.0f - angdamp*dt) - vel.top*(angdamp + angscale*invDt)));
}
linkZAExtForcesW[linkID] = zTmp;
//Account for forces arising from internal accelerations.
//Note: Mirtich thesis introduces a single spatial zero acceleration force that contains an external [mass*gravity] term and the internal [omega X (Iw *omega)] term.
//In Mirtich it looks like this:
// [-m_i * g ]
// [omega_i * (I_i * omega_i) ]
//We split the spatial zero acceleration force into external (above) and internal (below).
//The sum of the two (external and internal) correspoinds to Z_i^A in the Mirtich formulation.
const Cm::SpatialVectorF zInternal(PxVec3(0.f), vel.top.cross(Iw*vel.top));
linkZAIntForcesW[linkID] = zInternal;
}
PxReal invMass = 1.f / sumMass;
comW = COM * invMass;
invSumMass = invMass;
}
//compute all links velocities
void FeatherstoneArticulation::computeLinkVelocities(ArticulationData& data,
ScratchData& scratchData)
{
Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors;
ArticulationLink* links = data.getLinks();
ArticulationLinkData* linkData = data.getLinkData();
const PxU32 linkCount = data.getLinkCount();
const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
//motion velocities has to be in world space to avoid numerical errors caused by space
Cm::SpatialVectorF* motionVelocities = scratchData.motionVelocities;
Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations;
PxReal* jointVelocities = scratchData.jointVelocities;
const ArticulationLink& baseLink = links[0];
ArticulationLinkData& baseLinkDatum = linkData[0];
PxsBodyCore& core0 = *baseLink.bodyCore;
baseLinkDatum.maxPenBias = core0.maxPenBias;
if (fixBase)
{
motionVelocities[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
motionAccelerations[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
}
else
{
motionVelocities[0] = Cm::SpatialVectorF(core0.angularVelocity, core0.linearVelocity);
//PX_ASSERT(core0.angularVelocity.isFinite() && PxAbs(core0.angularVelocity.x) < 10000.f && PxAbs(core0.angularVelocity.y) < 10000.f && PxAbs(core0.angularVelocity.z) < 10000.f);
//PX_ASSERT(core0.linearVelocity.isFinite() && PxAbs(core0.linearVelocity.x) < 10000.f && PxAbs(core0.linearVelocity.y) < 10000.f && PxAbs(core0.linearVelocity.z) < 10000.f);
}
coriolisVectors[0] = Cm::SpatialVectorF::Zero();
data.mRootPreMotionVelocity = motionVelocities[0];
//const PxU32 dofCount = data.mDofs;
PxReal ratio = 1.f;
if (jointVelocities)
{
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset];
const PxReal maxJVelocity = link.inboundJoint->maxJointVelocity;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
PxReal absJvel = PxAbs(jVelocity[ind]);
ratio = ratio * absJvel > maxJVelocity ? (maxJVelocity / absJvel) : ratio;
}
}
}
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
const ArticulationLink& link = links[linkID];
ArticulationLinkData& linkDatum = linkData[linkID];
const PxsBodyCore& bodyCore = *link.bodyCore;
linkDatum.maxPenBias = bodyCore.maxPenBias;
const Cm::SpatialVectorF pVel = motionVelocities[link.parent];
Cm::SpatialVectorF vel = FeatherstoneArticulation::translateSpatialVector(-mArticulationData.getRw(linkID), pVel);
const PxTransform& body2World = bodyCore.body2World;
if (jointVelocities)
{
PxVec3 torque = pVel.top.cross(pVel.top.cross(data.getRw(linkID)));
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset];
PxVec3 force(0.f);
if (jointDatum.dof)
{
Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero();
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
PxReal jVel = jVelocity[ind] * ratio;
//deltaV += data.mWorldMotionMatrix[jointDatum.jointOffset + ind] * jVel;
deltaV += data.mMotionMatrix[jointDatum.jointOffset+ind].rotate(body2World) * jVel;
jVelocity[ind] = jVel;
}
vel.top += deltaV.top;
vel.bottom += deltaV.bottom;
const PxVec3 aVec = deltaV.top;
force = pVel.top.cross(aVec);
//compute linear part
const PxVec3 lVel = deltaV.bottom;
const PxVec3 temp1 = 2.f * pVel.top.cross(lVel);
const PxVec3 temp2 = aVec.cross(lVel);
torque += temp1 + temp2;
}
coriolisVectors[linkID] = Cm::SpatialVectorF(force, torque);
}
//PX_ASSERT(vel.top.isFinite() && PxAbs(vel.top.x) < 10000.f && PxAbs(vel.top.y) < 10000.f && PxAbs(vel.top.z) < 10000.f);
//PX_ASSERT(vel.bottom.isFinite() && PxAbs(vel.bottom.x) < 10000.f && PxAbs(vel.bottom.y) < 10000.f && PxAbs(vel.bottom.z) < 10000.f);
motionVelocities[linkID] = vel;
}
}
void solveExtContact(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1, bool doFriction);
void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
Vec3V& li0, Vec3V& li1, Vec3V& ai0, Vec3V& ai1);
void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
const Vec3V& linMotion0, const Vec3V& linMotion1, const Vec3V& angMotion0, const Vec3V& angMotion1,
const QuatV& rotA, const QuatV& rotB, const PxReal elapsedTimeF32, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0,
Vec3V& angImpulse1);
void solveExtContactStep(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1,
Vec3V& linDelta0, Vec3V& linDelta1, Vec3V& angDelta0, Vec3V& angDelta1, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1,
bool doFriction, const PxReal minPenetration, const PxReal elapsedTimeF32);
void solveStaticConstraint(const PxSolverConstraintDesc& desc, Cm::SpatialVectorF& linkV,
Cm::SpatialVectorF& impulse, Cm::SpatialVectorF& deltaV, const Cm::SpatialVectorF& motion,
const PxQuat& rot, bool isTGS, PxReal elapsedTime, const PxReal minPenetration)
{
PX_UNUSED(isTGS);
PX_UNUSED(elapsedTime);
PX_UNUSED(minPenetration);
Vec3V linVel = V3LoadA(linkV.bottom);
Vec3V angVel = V3LoadA(linkV.top);
Vec3V linVel0, linVel1, angVel0, angVel1;
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
if (isTGS)
{
PxQuat idt(PxIdentity);
Vec3V linMotion0, angMotion0, linMotion1, angMotion1;
QuatV rotA, rotB;
if (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = linVel;
angVel0 = angVel;
linMotion0 = V3LoadA(motion.bottom);
angMotion0 = V3LoadA(motion.top);
rotA = QuatVLoadU(&rot.x);
rotB = QuatVLoadU(&idt.x);
linVel1 = angVel1 = linMotion1 = angMotion1 = V3Zero();
}
else
{
linVel1 = linVel;
angVel1 = angVel;
linMotion1 = V3LoadA(motion.bottom);
angMotion1 = V3LoadA(motion.top);
rotB = QuatVLoadU(&rot.x);
rotA = QuatVLoadU(&idt.x);
linVel0 = angVel0 = linMotion0 = angMotion0 = V3Zero();
}
if (*desc.constraint == DY_SC_TYPE_EXT_CONTACT)
{
Dy::solveExtContactStep(desc,
linVel0, linVel1, angVel0, angVel1,
linMotion0, linMotion1, angMotion0, angMotion1,
li0, li1, ai0, ai1,
true, minPenetration, elapsedTime);
}
else
{
Dy::solveExt1D(desc,
linVel0, linVel1, angVel0, angVel1,
linMotion0, linMotion1, angMotion0, angMotion1,
rotA, rotB, elapsedTime,
li0, li1, ai0, ai1);
}
}
else
{
if (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = linVel;
angVel0 = angVel;
linVel1 = angVel1 = V3Zero();
}
else
{
linVel1 = linVel;
angVel1 = angVel;
linVel0 = angVel0 = V3Zero();
}
if (*desc.constraint == DY_SC_TYPE_EXT_CONTACT)
{
Dy::solveExtContact(desc, linVel0, linVel1, angVel0, angVel1, li0, li1, ai0, ai1, true);
}
else
{
Dy::solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, li0, li1, ai0, ai1);
}
}
Cm::SpatialVectorF newVel, newImp;
if (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY)
{
V4StoreA(Vec4V_From_Vec3V(linVel0), &newVel.bottom.x);
V4StoreA(Vec4V_From_Vec3V(angVel0), &newVel.top.x);
V4StoreA(Vec4V_From_Vec3V(li0), &newImp.top.x);
V4StoreA(Vec4V_From_Vec3V(ai0), &newImp.bottom.x);
}
else
{
V4StoreA(Vec4V_From_Vec3V(linVel1), &newVel.bottom.x);
V4StoreA(Vec4V_From_Vec3V(angVel1), &newVel.top.x);
V4StoreA(Vec4V_From_Vec3V(li1), &newImp.top.x);
V4StoreA(Vec4V_From_Vec3V(ai1), &newImp.bottom.x);
}
deltaV.top += (newVel.top - linkV.top);
deltaV.bottom += (newVel.bottom - linkV.bottom);
linkV.top = newVel.top;
linkV.bottom = newVel.bottom;
impulse -= newImp;
}
void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext& cache,
PxSolverBodyData& bd0, PxSolverBodyData& bd1);
void writeBack1D(const PxSolverConstraintDesc& desc, SolverContext&,
PxSolverBodyData&, PxSolverBodyData&);
void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext* cache);
void writeBack1D(const PxSolverConstraintDesc& desc);
void FeatherstoneArticulation::writebackInternalConstraints(bool isTGS)
{
SolverContext context;
PxSolverBodyData data;
for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStatic1DConstraints[i];
PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_1D);
if (isTGS)
{
writeBack1D(static_cast<PxSolverConstraintDesc&>(desc));
}
else
{
writeBack1D(desc, context, data, data);
}
}
for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStaticContactConstraints[i];
PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_CONTACT);
if (isTGS)
{
writeBackContact(static_cast<PxSolverConstraintDesc&>(desc), NULL);
}
else
{
writeBackContact(desc, context, data, data);
}
}
}
void concludeContact(const PxSolverConstraintDesc& desc, SolverContext& cache);
void conclude1D(const PxSolverConstraintDesc& desc, SolverContext& cache);
void concludeContact(const PxSolverConstraintDesc& desc);
void conclude1DStep(const PxSolverConstraintDesc& desc);
void FeatherstoneArticulation::concludeInternalConstraints(bool isTGS)
{
SolverContext context;
for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStatic1DConstraints[i];
PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_1D);
if (isTGS)
{
conclude1DStep(desc);
}
else
{
conclude1D(desc, context);
}
}
for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i)
{
PxSolverConstraintDesc& desc = mStaticContactConstraints[i];
PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_CONTACT);
if (isTGS)
{
concludeContact(desc);
}
else
{
concludeContact(desc, context);
}
}
}
//Takes and updates jointV, returns deltaF
static PxReal solveLimit(ArticulationInternalLimit& limit, PxReal& jointV, const PxReal jointPDelta,
const PxReal response, const PxReal recipResponse, const InternalConstraintSolverData& data)
{
PxReal futureDeltaJointP = jointPDelta + jointV * data.dt;
bool limited = false;
const PxReal tolerance = 0.f;
PxReal deltaF = 0.f;
if ((limit.errorLow + jointPDelta) < tolerance || (limit.errorLow + futureDeltaJointP) < tolerance)
{
PxReal newJointV = jointV;
limited = true;
if ((limit.errorLow + jointPDelta) < tolerance)
{
if (!data.isVelIter)
newJointV = -(limit.errorLow + jointPDelta) * data.invDt*data.erp;
}
else
newJointV = -(limit.errorLow + jointPDelta) * data.invDt;
PxReal deltaV = newJointV - jointV;
const PxReal lowImpulse = limit.lowImpulse;
deltaF = PxMax(lowImpulse + deltaV * recipResponse, 0.f) - lowImpulse;
limit.lowImpulse = lowImpulse + deltaF;
}
else if ((limit.errorHigh - jointPDelta) < tolerance || (limit.errorHigh - futureDeltaJointP) < tolerance)
{
PxReal newJointV = jointV;
limited = true;
if ((limit.errorHigh - jointPDelta) < tolerance)
{
if (!data.isVelIter)
newJointV = (limit.errorHigh - jointPDelta) * data.invDt*data.erp;
}
else
newJointV = (limit.errorHigh - jointPDelta) * data.invDt;
PxReal deltaV = newJointV - jointV;
const PxReal highImpulse = limit.highImpulse;
deltaF = PxMin(highImpulse + deltaV * recipResponse, 0.f) - highImpulse;
limit.highImpulse = highImpulse + deltaF;
}
if (!limited)
{
const PxReal forceLimit = -jointV*recipResponse;
if (jointV > 0.f)
{
deltaF = PxMax(forceLimit, -limit.lowImpulse);
limit.lowImpulse += deltaF;
}
else
{
deltaF = PxMin(forceLimit, -limit.highImpulse);
limit.highImpulse += deltaF;
}
}
jointV += deltaF * response;
return deltaF;
}
Cm::SpatialVectorF FeatherstoneArticulation::solveInternalJointConstraintRecursive(InternalConstraintSolverData& data, const PxU32 linkID, const Cm::SpatialVectorF& parentDeltaV, const bool isTGS, const bool isVelIter)
{
//PxU32 linkID = stack[stackSize];
const ArticulationLink* links = mArticulationData.mLinks;
const ArticulationLink& link = links[linkID];
//const ArticulationLink& plink = links[link.parent];
ArticulationLinkData& linkDatum = mArticulationData.getLinkData(linkID);
//PxTransform* transforms = mArticulationData.mPreTransform.begin();
PX_UNUSED(linkDatum);
const ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
Cm::SpatialVectorF i1(PxVec3(0.f), PxVec3(0.f));
//We know the absolute parentDeltaV from the call to this function so no need to modify it.
Cm::SpatialVectorF parentV = parentDeltaV + mArticulationData.mMotionVelocities[link.parent];
Cm::SpatialVectorF parentVelContrib = propagateAccelerationW(mArticulationData.getRw(linkID), mArticulationData.mInvStIs[linkID],
&mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset], parentDeltaV, jointDatum.dof,
&mArticulationData.mIsW[jointDatum.jointOffset], &mArticulationData.mDeferredQstZ[jointDatum.jointOffset]);
Cm::SpatialVectorF childV = mArticulationData.mMotionVelocities[linkID] + parentVelContrib;
Cm::UnAlignedSpatialVector i0(PxVec3(0.f), PxVec3(0.f));
Cm::SpatialVectorF dv1 = parentVelContrib;
const PxReal maxJointVel = link.inboundJoint->maxJointVelocity;
//If we have any internal constraints to process (parent/child limits/locks/drives)
if (jointDatum.dofInternalConstraintMask)
{
for (PxU32 dof = 0; dof < jointDatum.dof; ++dof)
{
PxReal deltaF = 0.f;
PxReal clampedForce = 0.f;
PxU32 internalConstraint = jointDatum.dofInternalConstraintMask & (1 << dof);
if (internalConstraint)
{
ArticulationInternalConstraint& constraint = mArticulationData.mInternalConstraints[data.dofId++];
const PxReal jointPDelta = constraint.row1.innerProduct(mArticulationData.mDeltaMotionVector[linkID]) - constraint.row0.innerProduct(mArticulationData.mDeltaMotionVector[link.parent]);
const PxReal frictionForceCoefficient = constraint.frictionForceCoefficient;
PxReal jointV = constraint.row1.innerProduct(childV) - constraint.row0.innerProduct(parentV);
const PxReal appliedFriction =
constraint.frictionForce * frictionForceCoefficient;
PxReal frictionForce =
PxClamp(-jointV *constraint.recipResponse + appliedFriction, -constraint.frictionMaxForce, constraint.frictionMaxForce);
PxReal frictionDeltaF = frictionForce - appliedFriction;
constraint.frictionForce += frictionDeltaF;
jointV += frictionDeltaF * constraint.response;
PxReal unclampedForce = (isTGS && isVelIter) ? constraint.driveForce :
computeDriveImpulse(constraint.driveForce, jointV, jointPDelta, constraint.getImplicitDriveDesc());
clampedForce = PxClamp(unclampedForce, -constraint.driveMaxForce, constraint.driveMaxForce);
PxReal driveDeltaF = (clampedForce - constraint.driveForce);
//Where we will be next frame - we use this to compute error bias terms to correct limits and drives...
jointV += driveDeltaF * constraint.response;
driveDeltaF += frictionDeltaF;
//printf("LinkID %i driveDeltaV = %f, jointV = %f\n", linkID, driveDeltaF, jointV);
if (jointDatum.limitMask & (1 << dof))
{
ArticulationInternalLimit& limit = mArticulationData.mInternalLimits[data.limitId++];
deltaF = solveLimit(limit, jointV, jointPDelta, constraint.response, constraint.recipResponse, data);
}
if (PxAbs(jointV) > maxJointVel)
{
PxReal newJointV = PxClamp(jointV, -maxJointVel, maxJointVel);
deltaF += (newJointV - jointV) * constraint.recipResponse;
jointV = newJointV;
}
deltaF += driveDeltaF;
if (deltaF != 0.f)
{
//impulse = true;
constraint.driveForce = clampedForce;
i0 += constraint.row0 * deltaF;
i1.top -= constraint.row1.top * deltaF;
i1.bottom -= constraint.row1.bottom * deltaF;
const Cm::UnAlignedSpatialVector deltaVP = constraint.deltaVA * (-deltaF);
const Cm::UnAlignedSpatialVector deltaVC = constraint.deltaVB * (-deltaF);
parentV += Cm::SpatialVectorF(deltaVP.top, deltaVP.bottom);
childV += Cm::SpatialVectorF(deltaVC.top, deltaVC.bottom);
dv1.top += deltaVC.top;
dv1.bottom += deltaVC.bottom;
}
}
}
}
//Cache the impulse arising from internal constraints.
//We'll subtract this from the total impulse applied later in this function.
const Cm::SpatialVectorF i1Internal = i1;
const Cm::SpatialVectorF& deltaMotion = mArticulationData.getDeltaMotionVector(linkID);
const PxQuat& deltaQ = getDeltaQ(linkID);
const PxU32 nbStatic1DConstraints = mArticulationData.mNbStatic1DConstraints[linkID];
PxU32 start1DIdx = mArticulationData.mStatic1DConstraintStartIndex[linkID];
for (PxU32 i = 0; i < nbStatic1DConstraints; ++i)
{
PxSolverConstraintDesc& desc = mStatic1DConstraints[start1DIdx++];
solveStaticConstraint(
desc, childV, i1, dv1, deltaMotion, deltaQ, data.isTGS, data.elapsedTime, data.isVelIter ? 0.f : -PX_MAX_F32);
}
const PxU32 nbStaticContactConstraints = mArticulationData.mNbStaticContactConstraints[linkID];
PxU32 startContactIdx = mArticulationData.mStaticContactConstraintStartIndex[linkID];
for (PxU32 i = 0; i < nbStaticContactConstraints; ++i)
{
PxSolverConstraintDesc& desc = mStaticContactConstraints[startContactIdx++];
solveStaticConstraint(
desc, childV, i1, dv1, deltaMotion, deltaQ, data.isTGS, data.elapsedTime, data.isVelIter ? 0.f : -PX_MAX_F32);
}
PxU32 numChildren = link.mNumChildren;
PxU32 offset = link.mChildrenStartIndex;
for(PxU32 i = 0; i < numChildren; ++i)
{
const PxU32 child = offset+i;
Cm::SpatialVectorF childImp = solveInternalJointConstraintRecursive(data, child, dv1, isTGS, isVelIter);
i1 += childImp;
if ((numChildren-i) > 1)
{
//Propagate the childImp to my dv1 so that the next constraint gets to see an updated velocity state based
//on the propagation of the child velocities
Cm::SpatialVectorF deltaV = mArticulationData.mResponseMatrixW[linkID].getResponse(-childImp);
dv1 += deltaV;
childV += deltaV;
}
}
Cm::SpatialVectorF propagatedImpulseAtParentW;
{
//const inputs
const PxVec3& r = mArticulationData.getRw(linkID);
const Cm::SpatialVectorF* jointDofISInvStISW = &mArticulationData.mISInvStIS[jointDatum.jointOffset];
const Cm::UnAlignedSpatialVector* jointDofMotionMatrixW = &mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset];
const PxU8 nbDofs = jointDatum.dof;
//output
PxReal* jointDofDeferredQstZ = &mArticulationData.mDeferredQstZ[jointDatum.jointOffset];
propagatedImpulseAtParentW = propagateImpulseW(
r,
i1,
jointDofISInvStISW, jointDofMotionMatrixW, nbDofs,
jointDofDeferredQstZ);
}
//Accumulate the propagated impulse at the link.
//Don't forget to subtract the impulse arising from internal constraints.
//This can be used to compute the link's incoming joint force.
mArticulationData.mSolverLinkSpatialImpulses[linkID] += (i1 - i1Internal);
return Cm::SpatialVectorF(i0.top, i0.bottom) + propagatedImpulseAtParentW;
}
void FeatherstoneArticulation::solveInternalJointConstraints(const PxReal dt, const PxReal invDt,
Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV, bool isVelIter, bool isTGS,
const PxReal elapsedTime, const PxReal biasCoefficient)
{
//const PxU32 count = mArticulationData.getLinkCount();
if (mArticulationData.mInternalConstraints.size() == 0
&& mStatic1DConstraints.size() == 0 && mStaticContactConstraints.size() == 0)
return;
//const PxReal erp = isTGS ? 0.5f*biasCoefficient : biasCoefficient;
const PxReal erp = biasCoefficient;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
PxU32* static1DConstraintCounts = mArticulationData.mNbStatic1DConstraints.begin();
PxU32* static1DConstraintStarts = mArticulationData.mStatic1DConstraintStartIndex.begin();
PxU32* staticContactConstraintCounts = mArticulationData.mNbStaticContactConstraints.begin();
PxU32* staticContactConstraintStarts = mArticulationData.mStaticContactConstraintStartIndex.begin();
ArticulationLink* links = mArticulationData.getLinks();
Cm::SpatialVectorF* baseVelocities = mArticulationData.getMotionVelocities();
//PxTransform* transforms = mArticulationData.mPreTransform.begin();
//Cm::SpatialVectorF* deferredZ = mArticulationData.getSpatialZAVectors();
const PxReal minPenetration = isVelIter ? 0.f : -PX_MAX_F32;
Cm::SpatialVectorF rootLinkV;
{
Cm::SpatialVectorF rootLinkDeltaV(PxVec3(0.f), PxVec3(0.f));
if (!fixBase)
{
//Cm::SpatialVectorF temp = mArticulationData.getBaseInvSpatialArticulatedInertia() * (-deferredZ[0]);
//const PxTransform& body2World0 = transforms[0];
//rootLinkDeltaV = temp.rotate(body2World0);
//temp is now in world space!
rootLinkDeltaV = mArticulationData.getBaseInvSpatialArticulatedInertiaW() * -mArticulationData.mRootDeferredZ;
}
rootLinkV = rootLinkDeltaV + baseVelocities[0];
Cm::SpatialVectorF im0 = Cm::SpatialVectorF::Zero();
{
const PxU32 nbStatic1DConstraints = static1DConstraintCounts[0];
if (nbStatic1DConstraints)
{
const Cm::SpatialVectorF& deltaMotion = mArticulationData.getDeltaMotionVector(0);
const PxQuat& deltaQ = getDeltaQ(0);
PxU32 startIdx = static1DConstraintStarts[0];
for (PxU32 i = 0; i < nbStatic1DConstraints; ++i)
{
PxSolverConstraintDesc& desc = mStatic1DConstraints[startIdx++];
solveStaticConstraint(desc, rootLinkV, im0, rootLinkDeltaV, deltaMotion, deltaQ, isTGS, elapsedTime, minPenetration);
}
//Impulses and deferredZ are now in world space, not link space!
/*im0.top = transforms[0].rotateInv(im0.top);
im0.bottom = transforms[0].rotateInv(im0.bottom);*/
}
const PxU32 nbStaticContactConstraints = staticContactConstraintCounts[0];
if (nbStaticContactConstraints)
{
const Cm::SpatialVectorF& deltaMotion = mArticulationData.getDeltaMotionVector(0);
const PxQuat& deltaQ = getDeltaQ(0);
PxU32 startIdx = staticContactConstraintStarts[0];
for (PxU32 i = 0; i < nbStaticContactConstraints; ++i)
{
PxSolverConstraintDesc& desc = mStaticContactConstraints[startIdx++];
solveStaticConstraint(desc, rootLinkV, im0, rootLinkDeltaV, deltaMotion, deltaQ, isTGS, elapsedTime, minPenetration);
}
//Impulses and deferredZ are now in world space, not link space!
/*im0.top = transforms[0].rotateInv(im0.top);
im0.bottom = transforms[0].rotateInv(im0.bottom);*/
}
}
InternalConstraintSolverData data(dt, invDt, elapsedTime,
erp, impulses, DeltaV,
isVelIter, isTGS);
data.articId = mArticulationIndex;
const PxU32 numChildren = links[0].mNumChildren;
const PxU32 offset = links[0].mChildrenStartIndex;
for (PxU32 i = 0; i < numChildren; ++i)
{
const PxU32 child = offset + i;
Cm::SpatialVectorF imp = solveInternalJointConstraintRecursive(data, child, rootLinkDeltaV, isTGS, isVelIter);
im0 += imp;
//There's an impulse, we have to work out how it impacts our velocity (only if required (we have more children to traverse))!
if (!fixBase && (numChildren - 1) != 0)
{
//Impulses and deltaVs are all now in world space
rootLinkDeltaV += mArticulationData.getBaseInvSpatialArticulatedInertiaW() * (-imp);
}
}
mArticulationData.mRootDeferredZ += im0;
mArticulationData.mJointDirty = true;
}
}
void FeatherstoneArticulation::solveInternalSpatialTendonConstraints(bool isTGS)
{
if (mArticulationData.mInternalSpatialTendonConstraints.size() == 0)
return;
if (isTGS)
{
//Update the error terms in the tendons recursively...
const PxU32 nbTendons = mArticulationData.mNumSpatialTendons;
for (PxU32 i = 0; i < nbTendons; ++i)
{
Dy::ArticulationSpatialTendon* tendon = mArticulationData.mSpatialTendons[i];
Dy::ArticulationAttachment& attachment = tendon->getAttachment(0);
//const PxU32 childCount = attachment.childCount;
//PxReal scale = 1.f / PxReal(childCount);
PxReal coefficient = attachment.coefficient;
const PxU32 startLink = tendon->getAttachment(0).linkInd;
const PxTransform pBody2World = mArticulationData.getAccumulatedPoses()[startLink];
const PxVec3 pAttachPoint = pBody2World.transform(tendon->getAttachment(0).relativeOffset);
Dy::ArticulationAttachment* attachments = tendon->getAttachments();
for (ArticulationAttachmentBitField children = attachments[0].children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
updateSpatialTendonConstraintsRecursive(attachments, mArticulationData, child, tendon->mOffset*coefficient, pAttachPoint);
}
}
}
for (PxU32 i = 0; i < mArticulationData.mInternalSpatialTendonConstraints.size(); ++i)
{
ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalSpatialTendonConstraints[i];
const PxU32 parentID = constraint.linkID0;
const PxU32 linkID = constraint.linkID1;
//Cm::SpatialVectorF childDeltaP = mArticulationData.mDeltaMotionVector[linkID];
//Cm::SpatialVectorF parentDeltaP = mArticulationData.mDeltaMotionVector[parentID];
//PxReal deltaP = constraint.row1.innerProduct(childDeltaP) - constraint.row0.innerProduct(parentDeltaP);// + deltaErr;
Cm::SpatialVectorV childVel = pxcFsGetVelocity(linkID);
Cm::SpatialVectorV parentVel = pxcFsGetVelocity(parentID);
Cm::UnAlignedSpatialVector childV;
V3StoreU(childVel.angular, childV.top);
V3StoreU(childVel.linear, childV.bottom);
Cm::UnAlignedSpatialVector parentV;
V3StoreU(parentVel.angular, parentV.top);
V3StoreU(parentVel.linear, parentV.bottom);
PxReal error = constraint.restDistance - constraint.accumulatedLength;// + deltaP;
PxReal error2 = 0.f;
if (constraint.accumulatedLength > constraint.highLimit)
error2 = constraint.highLimit - constraint.accumulatedLength;
if (constraint.accumulatedLength < constraint.lowLimit)
error2 = constraint.lowLimit - constraint.accumulatedLength;
PxReal jointV = constraint.row1.innerProduct(childV) - constraint.row0.innerProduct(parentV);
PX_ASSERT(PxIsFinite(jointV));
PxReal unclampedForce = (jointV * constraint.velMultiplier + error * constraint.biasCoefficient) /** constraint.recipResponse*/
+ constraint.appliedForce * constraint.impulseMultiplier;
PxReal unclampedForce2 = (error2 * constraint.limitBiasCoefficient) + constraint.limitAppliedForce * constraint.limitImpulseMultiplier;
const PxReal deltaF = (unclampedForce - constraint.appliedForce) + (unclampedForce2 - constraint.limitAppliedForce);
constraint.appliedForce = unclampedForce;
constraint.limitAppliedForce = unclampedForce2;
if (deltaF != 0.f)
{
Cm::UnAlignedSpatialVector i0 = constraint.row0 * -deltaF;
Cm::UnAlignedSpatialVector i1 = constraint.row1 * deltaF;
pxcFsApplyImpulses(parentID, V3LoadU(i0.top), V3LoadU(i0.bottom),
linkID, V3LoadU(i1.top), V3LoadU(i1.bottom), NULL, NULL);
}
}
}
PxVec3 FeatherstoneArticulation::calculateFixedTendonVelocityAndPositionRecursive(FixedTendonSolveData& solveData,
const Cm::SpatialVectorF& parentV, const Cm::SpatialVectorF& parentDeltaV, const PxU32 tendonJointID)
{
ArticulationTendonJoint& tendonJoint = solveData.tendonJoints[tendonJointID];
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(tendonJoint.linkInd);
Cm::SpatialVectorF deltaV = propagateAccelerationW(mArticulationData.getRw(tendonJoint.linkInd), mArticulationData.mInvStIs[tendonJoint.linkInd],
&mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset], parentDeltaV, jointDatum.dof,
&mArticulationData.mIsW[jointDatum.jointOffset], &mArticulationData.mDeferredQstZ[jointDatum.jointOffset]);
Cm::SpatialVectorF childV = mArticulationData.mMotionVelocities[tendonJoint.linkInd] + deltaV;
PxU32 index = tendonJoint.mConstraintInd;
ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalFixedTendonConstraints[index];
const PxU32 childCount = tendonJoint.childCount;
PxVec3 jointVError;
const PxReal jointV = constraint.row1.innerProduct(childV) - constraint.row0.innerProduct(parentV);
const PxReal jointP = mArticulationData.mJointPosition[tendonJoint.startJointOffset];
jointVError.x = jointV * tendonJoint.coefficient;
jointVError.y = jointP * tendonJoint.coefficient;
//printf("%i: jointPose = %f, jointV = %f, coefficient = %f\n", tendonJoint.linkInd, jointP, jointV, tendonJoint.coefficient);
jointVError.z = 1.f;
if (childCount)
{
for (ArticulationBitField children = tendonJoint.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
jointVError += calculateFixedTendonVelocityAndPositionRecursive(solveData, childV, deltaV, child);
}
}
return jointVError;
}
Cm::SpatialVectorF FeatherstoneArticulation::solveFixedTendonConstraintsRecursive(FixedTendonSolveData& solveData,
const PxU32 tendonJointID)
{
ArticulationTendonJoint& tendonJoint = solveData.tendonJoints[tendonJointID];
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(tendonJoint.linkInd);
PxU32 index = tendonJoint.mConstraintInd;
ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalFixedTendonConstraints[index];
const PxU32 childCount = tendonJoint.childCount;
PxReal jointV = solveData.rootVel;
// calculate current accumulated tendon length from parent accumulated length
const PxReal lengthError = solveData.error;
PxReal limitError = solveData.limitError;
// the constraint bias coefficients need to flip signs together with the tendon joint's coefficient
// in order for the constraint force to point into the correct direction:
const PxReal coefficientSign = tendonJoint.recipCoefficient;// PxSign(tendonJoint.coefficient);
const PxReal biasCoefficient = constraint.biasCoefficient;
const PxReal limitBiasCoefficient = constraint.limitBiasCoefficient;
PxReal unclampedForce = ((jointV * constraint.velMultiplier + lengthError * biasCoefficient)*coefficientSign)
+ constraint.appliedForce * constraint.impulseMultiplier;
PxReal unclampedForce2 = (limitError * limitBiasCoefficient * coefficientSign)
+ constraint.limitAppliedForce * constraint.limitImpulseMultiplier;
const PxReal deltaF = ((unclampedForce - constraint.appliedForce) + (unclampedForce2 - constraint.limitAppliedForce));
constraint.appliedForce = unclampedForce;
constraint.limitAppliedForce = unclampedForce2;
solveData.rootImp += deltaF;
Cm::SpatialVectorF impulse(constraint.row1.top * -deltaF, constraint.row1.bottom * -deltaF);
const Cm::SpatialVectorF YInt = impulse;
if (childCount)
{
for (ArticulationBitField children = tendonJoint.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
Cm::SpatialVectorF propagatedImpulse = solveFixedTendonConstraintsRecursive(solveData, child);
impulse.top += propagatedImpulse.top;
impulse.bottom += propagatedImpulse.bottom;
}
}
mArticulationData.mSolverLinkSpatialImpulses[tendonJoint.linkInd] += impulse - YInt;
return propagateImpulseW(
mArticulationData.mRw[tendonJoint.linkInd],
impulse,
&mArticulationData.mISInvStIS[jointDatum.jointOffset], &mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset], jointDatum.dof,
&mArticulationData.mDeferredQstZ[jointDatum.jointOffset]);
}
void FeatherstoneArticulation::solveInternalFixedTendonConstraints(bool isTGS)
{
PX_UNUSED(isTGS);
if (mArticulationData.mInternalFixedTendonConstraints.size() == 0)
return;
{
//Update the error terms in the tendons recursively...
const PxU32 nbTendons = mArticulationData.mNumFixedTendons;
ArticulationLink* links = mArticulationData.getLinks();
for (PxU32 i = 0; i < nbTendons; ++i)
{
Dy::ArticulationFixedTendon* tendon = mArticulationData.mFixedTendons[i];
ArticulationTendonJoint* tendonJoints = tendon->getTendonJoints();
Dy::ArticulationTendonJoint& pTendonJoint = tendonJoints[0];
//const PxU32 childCount = pTendonJoint.childCount;
const PxU32 startLink = pTendonJoint.linkInd;
Cm::SpatialVectorV parentVel = pxcFsGetVelocity(startLink);
Cm::SpatialVectorF parentV;
V3StoreU(parentVel.angular, parentV.top);
V3StoreU(parentVel.linear, parentV.bottom);
Cm::SpatialVectorF Z(PxVec3(0.f), PxVec3(0.f));
Cm::SpatialVectorF parentDeltaV = parentV - mArticulationData.mMotionVelocities[startLink];
PxVec3 velError(0.f);
for (ArticulationAttachmentBitField children = pTendonJoint.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
FixedTendonSolveData solveData;
solveData.links = links;
solveData.erp = 1.f;
solveData.rootImp = 0.f;
solveData.error = tendon->mError;
solveData.tendonJoints = tendonJoints;
velError += calculateFixedTendonVelocityAndPositionRecursive(solveData, parentV, parentDeltaV, child);
}
const PxReal recipScale = velError.z == 0.f ? 0.f : 1.f / velError.z;
for (ArticulationAttachmentBitField children = pTendonJoint.children; children != 0; children &= (children - 1))
{
//index of child of link h on path to link linkID
const PxU32 child = ArticulationLowestSetBit(children);
ArticulationTendonJoint& tendonJoint = tendonJoints[child];
ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalFixedTendonConstraints[tendonJoint.mConstraintInd];
const PxReal length = (velError.y + tendon->mOffset);
FixedTendonSolveData solveData;
solveData.links = links;
solveData.erp = 1.f;
solveData.rootImp = 0.f;
solveData.error = (length - tendon->mRestLength) * recipScale;
solveData.rootVel = velError.x*recipScale;
PxReal limitError = 0.f;
if (length < tendon->mLowLimit)
limitError = length - tendon->mLowLimit;
else if (length > tendon->mHighLimit)
limitError = length - tendon->mHighLimit;
solveData.limitError = limitError * recipScale;
solveData.tendonJoints = tendonJoints;
//KS - TODO - hook up offsets
Cm::SpatialVectorF propagatedImpulse = solveFixedTendonConstraintsRecursive(solveData, child);
propagatedImpulse.top += constraint.row0.top * solveData.rootImp;
propagatedImpulse.bottom += constraint.row0.bottom * solveData.rootImp;
Z += propagatedImpulse;
}
for (PxU32 linkID = pTendonJoint.linkInd; linkID; linkID = links[linkID].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(linkID).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(linkID).dof;
Z = propagateImpulseW(
mArticulationData.getRw(linkID),
Z,
&mArticulationData.mISInvStIS[jointOffset], &mArticulationData.mWorldMotionMatrix[jointOffset], dofCount,
&mArticulationData.mDeferredQstZ[jointOffset]);
}
mArticulationData.mRootDeferredZ += Z;
mArticulationData.mJointDirty = true;
}
}
}
void FeatherstoneArticulation::solveInternalConstraints(const PxReal dt, const PxReal invDt,
Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV, bool velocityIteration, bool isTGS,
const PxReal elapsedTime, const PxReal biasCoefficient)
{
solveInternalSpatialTendonConstraints(isTGS);
solveInternalFixedTendonConstraints(isTGS);
solveInternalJointConstraints(dt, invDt, impulses, DeltaV, velocityIteration, isTGS, elapsedTime, biasCoefficient);
}
bool FeatherstoneArticulation::storeStaticConstraint(const PxSolverConstraintDesc& desc)
{
if (DY_STATIC_CONTACTS_IN_INTERNAL_SOLVER)
{
if (desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT)
mStaticContactConstraints.pushBack(desc);
else
mStatic1DConstraints.pushBack(desc);
}
return DY_STATIC_CONTACTS_IN_INTERNAL_SOLVER;
}
void FeatherstoneArticulation::setRootLinearVelocity(const PxVec3& velocity)
{
ArticulationLink& rLink = mArticulationData.getLink(0);
rLink.bodyCore->linearVelocity = velocity;
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_VELOCITIES;
computeLinkVelocities(mArticulationData);
}
void FeatherstoneArticulation::setRootAngularVelocity(const PxVec3& velocity)
{
ArticulationLink& rLink = mArticulationData.getLink(0);
rLink.bodyCore->angularVelocity = velocity;
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_VELOCITIES;
computeLinkVelocities(mArticulationData);
}
//This method is for user update the root link transform so we need to
//fix up other link's position. In this case, we should assume all joint
//velocity/pose is to be zero
void FeatherstoneArticulation::teleportRootLink()
{
//make sure motionMatrix has been set
//jcalc(mArticulationData);
const PxU32 linkCount = mArticulationData.getLinkCount();
ArticulationLink* links = mArticulationData.getLinks();
PxReal* jointPositions = mArticulationData.getJointPositions();
Cm::SpatialVectorF* motionVelocities = mArticulationData.getMotionVelocities();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
const PxTransform oldTransform = link.bodyCore->body2World;
ArticulationLink& pLink = links[link.parent];
const PxTransform pBody2World = pLink.bodyCore->body2World;
ArticulationJointCore* joint = link.inboundJoint;
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
PxReal* jPosition = &jointPositions[jointDatum.jointOffset];
PxQuat newParentToChild;
PxQuat newWorldQ;
PxVec3 r;
const PxVec3 childOffset = -joint->childPose.p;
const PxVec3 parentOffset = joint->parentPose.p;
const PxQuat relativeQuat = mArticulationData.mRelativeQuat[linkID];
switch (joint->jointType)
{
case PxArticulationJointType::ePRISMATIC:
{
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
const PxVec3& u = mArticulationData.mMotionMatrix[jointDatum.jointOffset].bottom;
r = e + d + u * jPosition[0];
break;
}
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const PxVec3& u = mArticulationData.mMotionMatrix[jointDatum.jointOffset].top;
PxQuat jointRotation = PxQuat(-jPosition[0], u);
if (jointRotation.w < 0) //shortest angle.
jointRotation = -jointRotation;
newParentToChild = (jointRotation * relativeQuat).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
/*PxVec3 worldAngVel = oldTransform.rotate(link.motionVelocity.top);
newWorldQ = PxExp(worldAngVel*dt) * oldTransform.q;
PxQuat newParentToChild2 = (newWorldQ.getConjugate() * joint->relativeQuat * pBody2World.q).getNormalized();
const PxVec3 e2 = newParentToChild2.rotate(parentOffset);
const PxVec3 d2 = childOffset;
r = e2 + d2;*/
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eSPHERICAL:
{
//PxVec3 angVel(joint->jointVelocity[0], joint->jointVelocity[1], joint->jointVelocity[2]);
//PxVec3 worldAngVel = pLink.bodyCore->angularVelocity + oldTransform.rotate(angVel);
PxVec3 worldAngVel = motionVelocities[linkID].top;
/*const PxReal eps = 0.001f;
const PxVec3 dif = worldAngVel - worldAngVel2;
PX_ASSERT(PxAbs(dif.x) < eps && PxAbs(dif.y) < eps && PxAbs(dif.z) < eps);*/
newWorldQ = PxExp(worldAngVel) * oldTransform.q;
newParentToChild = (newWorldQ.getConjugate() * relativeQuat * pBody2World.q).getNormalized();
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
PX_ASSERT(r.isFinite());
break;
}
case PxArticulationJointType::eFIX:
{
//this is fix joint so joint don't have velocity
newParentToChild = relativeQuat;
const PxVec3 e = newParentToChild.rotate(parentOffset);
const PxVec3 d = childOffset;
r = e + d;
break;
}
default:
break;
}
PxTransform& body2World = link.bodyCore->body2World;
body2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized();
body2World.p = pBody2World.p + body2World.q.rotate(r);
PX_ASSERT(body2World.isSane());
}
}
PxU8* FeatherstoneArticulation::allocateScratchSpatialData(PxcScratchAllocator* allocator,
const PxU32 linkCount, ScratchData& scratchData, bool fallBackToHeap)
{
const PxU32 size = sizeof(Cm::SpatialVectorF) * linkCount;
const PxU32 totalSize = size * 4 + sizeof(Dy::SpatialMatrix) * linkCount;
PxU8* tempMemory = reinterpret_cast<PxU8*>(allocator->alloc(totalSize, fallBackToHeap));
scratchData.motionVelocities = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory);
PxU32 offset = size;
scratchData.motionAccelerations = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset);
offset += size;
scratchData.coriolisVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset);
offset += size;
scratchData.spatialZAVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset);
offset += size;
scratchData.compositeSpatialInertias = reinterpret_cast<Dy::SpatialMatrix*>(tempMemory + offset);
return tempMemory;
}
/* void FeatherstoneArticulation::allocateScratchSpatialData(DyScratchAllocator& allocator,
const PxU32 linkCount, ScratchData& scratchData)
{
const PxU32 size = sizeof(Cm::SpatialVectorF) * linkCount;
const PxU32 totalSize = size * 5 + sizeof(Dy::SpatialMatrix) * linkCount;
PxU8* tempMemory = allocator.alloc<PxU8>(totalSize);
scratchData.motionVelocities = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory);
PxU32 offset = size;
scratchData.motionAccelerations = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset);
offset += size;
scratchData.coriolisVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset);
offset += size;
scratchData.spatialZAVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset);
offset += size;
scratchData.externalAccels = reinterpret_cast<Cm::SpatialVector*>(tempMemory + offset);
offset += size;
scratchData.compositeSpatialInertias = reinterpret_cast<Dy::SpatialMatrix*>(tempMemory + offset);
}*/
}//namespace Dy
}
| 204,611 | C++ | 35.394877 | 219 | 0.730093 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverControl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxIntrinsics.h"
#include "DySolverBody.h"
#include "DySolverConstraint1D.h"
#include "DySolverContact.h"
#include "DyThresholdTable.h"
#include "DySolverControl.h"
#include "DyArticulationPImpl.h"
#include "foundation/PxThread.h"
#include "DySolverConstraintDesc.h"
#include "DySolverContext.h"
#include "DyArticulationCpuGpu.h"
namespace physx
{
namespace Dy
{
void solve1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContact_BStaticBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactPreBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactPreBlock_Static (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4_Block (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContact_BStaticConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactPreBlock_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4Block_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContact_BStaticBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4Block_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
// PT: not sure what happened, these ones were declared but not actually used
//void writeBack1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
//void contactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
//void extContactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
//void ext1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
//void contactPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
//void writeBack1D4Block (DY_PGS_SOLVE_METHOD_PARAMS);
static SolveBlockMethod gVTableSolveBlock[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactBlock, // DY_SC_TYPE_RB_CONTACT
solve1DBlock, // DY_SC_TYPE_RB_1D
solveExtContactBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlock, // DY_SC_TYPE_EXT_1D
solveContact_BStaticBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactPreBlock, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactPreBlock_Static, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4_Block, // DY_SC_TYPE_BLOCK_1D,
};
static SolveWriteBackBlockMethod gVTableSolveWriteBackBlock[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactBlockWriteBack, // DY_SC_TYPE_RB_CONTACT
solve1DBlockWriteBack, // DY_SC_TYPE_RB_1D
solveExtContactBlockWriteBack, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlockWriteBack, // DY_SC_TYPE_EXT_1D
solveContact_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_CONTACT
solveContactBlockWriteBack, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactPreBlock_WriteBackStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_WriteBack, // DY_SC_TYPE_BLOCK_1D,
};
static SolveBlockMethod gVTableSolveConcludeBlock[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactConcludeBlock, // DY_SC_TYPE_RB_CONTACT
solve1DConcludeBlock, // DY_SC_TYPE_RB_1D
solveExtContactConcludeBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DConcludeBlock, // DY_SC_TYPE_EXT_1D
solveContact_BStaticConcludeBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactConcludeBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactPreBlock_Conclude, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactPreBlock_ConcludeStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_Conclude, // DY_SC_TYPE_BLOCK_1D,
};
SolveBlockMethod* getSolveBlockTable()
{
return gVTableSolveBlock;
}
SolveBlockMethod* getSolverConcludeBlockTable()
{
return gVTableSolveConcludeBlock;
}
SolveWriteBackBlockMethod* getSolveWritebackBlockTable()
{
return gVTableSolveWriteBackBlock;
}
// PT: TODO: ideally we could reuse this in immediate mode as well, but the code currently uses separate arrays of PxVec3s instead of
// spatial vectors so the SIMD code won't work there. Switching to spatial vectors requires a change in the immediate mode API (PxSolveConstraints).
void saveMotionVelocities(PxU32 nbBodies, PxSolverBody* PX_RESTRICT solverBodies, Cm::SpatialVector* PX_RESTRICT motionVelocityArray)
{
for(PxU32 i=0; i<nbBodies; i++)
{
Cm::SpatialVector& motionVel = motionVelocityArray[i];
const PxSolverBody& atom = solverBodies[i];
V4StoreA(V4LoadA(&atom.linearVelocity.x), &motionVel.linear.x);
V4StoreA(V4LoadA(&atom.angularState.x), &motionVel.angular.x);
}
}
// PT: this case is reached when e.g. a lot of objects falling but not touching yet. So there are no contacts but potentially a lot of bodies.
// See LegacyBenchmark/falling_spheres for example.
void solveNoContactsCase( PxU32 nbBodies, PxSolverBody* PX_RESTRICT solverBodies, Cm::SpatialVector* PX_RESTRICT motionVelocityArray,
PxU32 nbArticulations, ArticulationSolverDesc* PX_RESTRICT articulationListStart, Cm::SpatialVectorF* PX_RESTRICT Z, Cm::SpatialVectorF* PX_RESTRICT deltaV,
PxU32 nbPosIter, PxU32 nbVelIter, PxF32 dt, PxF32 invDt)
{
saveMotionVelocities(nbBodies, solverBodies, motionVelocityArray);
if(!nbArticulations)
return;
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT; // PT: TODO: unify this number with immediate mode (it's not 0.8 there!)
const bool isTGS = false;
//Even thought there are no external constraints, there may still be internal constraints in the articulations...
for(PxU32 i=0; i<nbPosIter; i++)
for(PxU32 j=0; j<nbArticulations; j++)
articulationListStart[j].articulation->solveInternalConstraints(dt, invDt, Z, deltaV, false, isTGS, 0.0f, biasCoefficient);
for(PxU32 i=0; i<nbArticulations; i++)
ArticulationPImpl::saveVelocity(articulationListStart[i].articulation, deltaV);
for(PxU32 i=0; i<nbVelIter; i++)
for(PxU32 j=0; j<nbArticulations; j++)
articulationListStart[j].articulation->solveInternalConstraints(dt, invDt, Z, deltaV, true, isTGS, 0.0f, biasCoefficient);
for(PxU32 j=0; j<nbArticulations; j++)
articulationListStart[j].articulation->writebackInternalConstraints(isTGS);
}
void SolverCoreGeneral::solveV_Blocks(SolverIslandParams& params) const
{
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT;
const bool isTGS = false;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.writeBackIteration = false;
cache.Z = params.Z;
cache.deltaV = params.deltaV;
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
const PxU32 bodyListSize = params.bodyListSize;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
const PxU32 velocityIterations = params.velocityIterations;
const PxU32 positionIterations = params.positionIterations;
const PxU32 numConstraintHeaders = params.numConstraintHeaders;
const PxU32 articulationListSize = params.articulationListSize;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
PX_ASSERT(positionIterations >= 1);
if(numConstraintHeaders == 0)
{
solveNoContactsCase(bodyListSize, bodyListStart, motionVelocityArray,
articulationListSize, articulationListStart, cache.Z, cache.deltaV,
positionIterations, velocityIterations, params.dt, params.invDt);
return;
}
BatchIterator contactIterator(params.constraintBatchHeaders, params.numConstraintHeaders);
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
//0-(n-1) iterations
PxI32 normalIter = 0;
for (PxU32 iteration = positionIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
cache.doFriction = mFrictionEveryIteration ? true : iteration <= 3;
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, iteration == 1 ? gVTableSolveConcludeBlock : gVTableSolveBlock, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
++normalIter;
}
saveMotionVelocities(bodyListSize, bodyListStart, motionVelocityArray);
for (PxU32 i = 0; i < articulationListSize; i++)
ArticulationPImpl::saveVelocity(articulationListStart[i].articulation, cache.deltaV);
const PxI32 velItersMinOne = (PxI32(velocityIterations)) - 1;
PxI32 iteration = 0;
for(; iteration < velItersMinOne; ++iteration)
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveBlock, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
++normalIter;
}
PxI32* outThresholdPairs = params.outThresholdPairs;
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
PxU32 thresholdStreamLength = params.thresholdStreamLength;
cache.writeBackIteration = true;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
cache.mSharedOutThresholdPairs = outThresholdPairs;
//PGS solver always runs at least one velocity iteration (otherwise writeback won't happen)
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveWriteBackBlock, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
{
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
articulationListStart[i].articulation->writebackInternalConstraints(false);
}
++normalIter;
}
//Write back remaining threshold streams
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
const PxI32 threshIndex = PxAtomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
}
void SolverCoreGeneral::solveVParallelAndWriteBack(SolverIslandParams& params, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const
{
#if PX_PROFILE_SOLVE_STALLS
PxU64 startTime = readTimer();
PxU64 stallCount = 0;
#endif
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT;
const bool isTGS = false;
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
const PxU32 batchSize = params.batchSize;
const PxI32 UnrollCount = PxI32(batchSize);
const PxI32 ArticCount = 2;
const PxI32 SaveUnrollCount = 32;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
const PxI32 bodyListSize = PxI32(params.bodyListSize);
const PxI32 articulationListSize = PxI32(params.articulationListSize);
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.writeBackIteration = false;
cache.Z = Z;
cache.deltaV = deltaV;
const PxReal dt = params.dt;
const PxReal invDt = params.invDt;
const PxI32 positionIterations = PxI32(params.positionIterations);
const PxI32 velocityIterations = PxI32(params.velocityIterations);
PxI32* constraintIndex = ¶ms.constraintIndex; // counter for distributing constraints to tasks, incremented before they're solved
PxI32* constraintIndexCompleted = ¶ms.constraintIndexCompleted; // counter for completed constraints, incremented after they're solved
PxI32* articIndex = ¶ms.articSolveIndex;
PxI32* articIndexCompleted = ¶ms.articSolveIndexCompleted;
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
const PxU32 nbPartitions = params.nbPartitions;
PxU32* headersPerPartition = params.headersPerPartition;
PX_UNUSED(velocityIterations);
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
PxI32 endIndexCount = UnrollCount;
PxI32 index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
PxI32 articSolveStart = 0;
PxI32 articSolveEnd = 0;
PxI32 maxArticIndex = 0;
PxI32 articIndexCounter = 0;
BatchIterator contactIter(params.constraintBatchHeaders, params.numConstraintHeaders);
PxI32 maxNormalIndex = 0;
PxI32 normalIteration = 0;
PxU32 a = 0;
PxI32 targetConstraintIndex = 0;
PxI32 targetArticIndex = 0;
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlock : gVTableSolveConcludeBlock;
for(; a < positionIterations - 1 + i; ++a)
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti solve of previous iteration
cache.doFriction = mFrictionEveryIteration ? true : (positionIterations - a) <= 3;
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid solve of previous partition
maxNormalIndex += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, solveTable,
normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
targetConstraintIndex += headersPerPartition[b]; //Increment target constraint index by batch count
}
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for all rigid partitions to be done
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
const PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize;
++normalIteration;
}
}
PxI32* bodyListIndex = ¶ms.bodyListIndex;
PxI32* bodyListIndexCompleted = ¶ms.bodyListIndexCompleted;
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
//Save velocity - articulated
PxI32 endIndexCount2 = SaveUnrollCount;
PxI32 index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for all articulation solves before saving velocity
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for all rigid partition solves before saving velocity
PxI32 nbConcluded = 0;
while(index2 < articulationListSize)
{
const PxI32 remainder = PxMin(SaveUnrollCount, (articulationListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
ArticulationPImpl::saveVelocity(articulationListStart[index2].articulation, cache.deltaV);
}
if(endIndexCount2 == 0)
{
index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
endIndexCount2 = SaveUnrollCount;
}
nbConcluded += remainder;
}
index2 -= articulationListSize;
//save velocity
while(index2 < bodyListSize)
{
const PxI32 remainder = PxMin(endIndexCount2, (bodyListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
PxPrefetchLine(&bodyListStart[index2 + 8]);
PxPrefetchLine(&motionVelocityArray[index2 + 8]);
PxSolverBody& body = bodyListStart[index2];
Cm::SpatialVector& motionVel = motionVelocityArray[index2];
motionVel.linear = body.linearVelocity;
motionVel.angular = body.angularState;
PX_ASSERT(motionVel.linear.isFinite());
PX_ASSERT(motionVel.angular.isFinite());
}
nbConcluded += remainder;
//Branch not required because this is the last time we use this atomic variable
//if(index2 < articulationListSizePlusbodyListSize)
{
index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount - articulationListSize;
endIndexCount2 = SaveUnrollCount;
}
}
if(nbConcluded)
{
PxMemoryBarrier();
PxAtomicAdd(bodyListIndexCompleted, nbConcluded);
}
}
WAIT_FOR_PROGRESS(bodyListIndexCompleted, (bodyListSize + articulationListSize)); // wait for all velocity saves to be done
a = 1;
for(; a < params.velocityIterations; ++a)
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti solve of previous iteration
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid solve of previous partition
maxNormalIndex += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveBlock,
normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
targetConstraintIndex += headersPerPartition[b]; //Increment target constraint index by batch count
}
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for all rigid partitions to be done
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
const PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
++normalIteration;
articIndexCounter += articulationListSize;
}
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
PxU32 thresholdStreamLength = params.thresholdStreamLength;
PxI32* outThresholdPairs = params.outThresholdPairs;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
//Last iteration - do writeback as well!
cache.writeBackIteration = true;
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti velocity iterations to be done
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid partition velocity iterations to be done resp. previous partition writeback iteration
maxNormalIndex += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveWriteBackBlock,
normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
targetConstraintIndex += headersPerPartition[b]; //Increment target constraint index by batch count
}
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid partitions writeback iterations to be done
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
articulationListStart[articSolveStart - articIndexCounter].articulation->writebackInternalConstraints(false);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize; // not strictly necessary but better safe than sorry
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti solve+writeback to be done
}
// At this point we've awaited the completion all rigid partitions and all articulations
// No more syncing on the outside of this function is required.
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
PxI32 threshIndex = PxAtomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
++normalIteration;
}
#if PX_PROFILE_SOLVE_STALLS
PxU64 endTime = readTimer();
PxReal totalTime = (PxReal)(endTime - startTime);
PxReal stallTime = (PxReal)stallCount;
PxReal stallRatio = stallTime/totalTime;
if(0)//stallRatio > 0.2f)
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency( &frequency );
printf("Warning -- percentage time stalled = %f; stalled for %f seconds; total Time took %f seconds\n",
stallRatio * 100.f, stallTime/(PxReal)frequency.QuadPart, totalTime/(PxReal)frequency.QuadPart);
}
#endif
}
}
}
| 26,054 | C++ | 36.221429 | 174 | 0.759231 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CONTACT_PREP_H
#define DY_CONTACT_PREP_H
#include "DySolverConstraintDesc.h"
#include "PxSceneDesc.h"
#include "DySolverContact4.h"
namespace physx
{
struct PxcNpWorkUnit;
class PxsConstraintBlockManager;
class PxcConstraintBlockStream;
struct PxsContactManagerOutput;
class FrictionPatchStreamPair;
struct PxSolverBody;
struct PxSolverBodyData;
struct PxSolverConstraintDesc;
class PxsContactManager;
namespace Dy
{
class ThreadContext;
struct CorrelationBuffer;
#define CREATE_FINALIZE_SOLVER_CONTACT_METHOD_ARGS \
PxSolverContactDesc& contactDesc, \
PxsContactManagerOutput& output, \
ThreadContext& threadContext, \
const PxReal invDtF32, \
const PxReal dtF32, \
PxReal bounceThresholdF32, \
PxReal frictionOffsetThreshold, \
PxReal correlationDistance, \
PxConstraintAllocator& constraintAllocator, \
Cm::SpatialVectorF* Z
#define CREATE_FINALIZE_SOVLER_CONTACT_METHOD_ARGS_4 \
PxsContactManagerOutput** outputs, \
ThreadContext& threadContext, \
PxSolverContactDesc* blockDescs, \
const PxReal invDtF32, \
const PxReal dtF32, \
PxReal bounceThresholdF32, \
PxReal frictionThresholdF32, \
PxReal correlationDistanceF32, \
PxConstraintAllocator& constraintAllocator
/*!
Method prototype for create finalize solver contact
*/
typedef bool (*PxcCreateFinalizeSolverContactMethod)(CREATE_FINALIZE_SOLVER_CONTACT_METHOD_ARGS);
extern PxcCreateFinalizeSolverContactMethod createFinalizeMethods[3];
typedef SolverConstraintPrepState::Enum (*PxcCreateFinalizeSolverContactMethod4)(CREATE_FINALIZE_SOVLER_CONTACT_METHOD_ARGS_4);
extern PxcCreateFinalizeSolverContactMethod4 createFinalizeMethods4[3];
bool createFinalizeSolverContacts( PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z);
bool createFinalizeSolverContacts( PxSolverContactDesc& contactDesc,
CorrelationBuffer& c,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4( PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4( Dy::CorrelationBuffer& c,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator);
bool createFinalizeSolverContactsCoulomb1D(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z);
bool createFinalizeSolverContactsCoulomb2D(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb1D( PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb2D(PxsContactManagerOutput** outputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator);
PxU32 getContactManagerConstraintDesc(const PxsContactManagerOutput& cmOutput, const PxsContactManager& cm, PxSolverConstraintDesc& desc);
class BlockAllocator : public PxConstraintAllocator
{
PxsConstraintBlockManager& mConstraintBlockManager;
PxcConstraintBlockStream& mConstraintBlockStream;
FrictionPatchStreamPair& mFrictionPatchStreamPair;
PxU32& mTotalConstraintByteSize;
public:
BlockAllocator(PxsConstraintBlockManager& constraintBlockManager, PxcConstraintBlockStream& constraintBlockStream, FrictionPatchStreamPair& frictionPatchStreamPair,
PxU32& totalConstraintByteSize) :
mConstraintBlockManager(constraintBlockManager), mConstraintBlockStream(constraintBlockStream), mFrictionPatchStreamPair(frictionPatchStreamPair),
mTotalConstraintByteSize(totalConstraintByteSize)
{
}
virtual PxU8* reserveConstraintData(const PxU32 size);
virtual PxU8* reserveFrictionData(const PxU32 size);
virtual PxU8* findInputPatches(PxU8* frictionCookie)
{
return frictionCookie;
}
PX_NOCOPY(BlockAllocator)
};
}
}
#endif
| 8,113 | C | 37.273585 | 165 | 0.719586 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyDynamics.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxTime.h"
#include "foundation/PxAtomic.h"
#include "PxvDynamics.h"
#include "common/PxProfileZone.h"
#include "PxsRigidBody.h"
#include "PxsContactManager.h"
#include "DyDynamics.h"
#include "DyBodyCoreIntegrator.h"
#include "DySolverCore.h"
#include "DySolverControl.h"
#include "DySolverContact.h"
#include "DySolverContactPF.h"
#include "DyArticulationContactPrep.h"
#include "DySolverBody.h"
#include "DyConstraintPrep.h"
#include "DyConstraintPartition.h"
#include "DySoftBody.h"
#include "CmFlushPool.h"
#include "DyArticulationPImpl.h"
#include "DyFeatherstoneArticulation.h"
#include "PxsMaterialManager.h"
#include "DySolverContactPF4.h"
#include "DyContactReduction.h"
#include "PxcNpContactPrepShared.h"
#include "DyContactPrep.h"
#include "DySolverControlPF.h"
#include "PxSceneDesc.h"
#include "PxsSimpleIslandManager.h"
#include "PxvNphaseImplementationContext.h"
#include "PxvSimStats.h"
#include "PxsContactManagerState.h"
#include "DyContactPrepShared.h"
#include "DySleep.h"
//KS - used to turn on/off batched SIMD constraints.
#define DY_BATCH_CONSTRAINTS 1
//KS - used to specifically turn on/off batches 1D SIMD constraints.
#define DY_BATCH_1D 1
namespace physx
{
namespace Dy
{
struct SolverIslandObjects
{
PxsRigidBody** bodies;
FeatherstoneArticulation** articulations;
PxsIndexedContactManager* contactManagers;
//PxsIndexedConstraint* constraints;
const IG::IslandId* islandIds;
PxU32 numIslands;
PxU32* bodyRemapTable;
PxU32* nodeIndexArray;
PxSolverConstraintDesc* constraintDescs;
PxSolverConstraintDesc* orderedConstraintDescs;
PxSolverConstraintDesc* tempConstraintDescs;
PxConstraintBatchHeader* constraintBatchHeaders;
Cm::SpatialVector* motionVelocities;
PxsBodyCore** bodyCoreArray;
SolverIslandObjects() : bodies(NULL), articulations(NULL),
contactManagers(NULL), islandIds(NULL), numIslands(0), nodeIndexArray(NULL), constraintDescs(NULL), orderedConstraintDescs(NULL),
tempConstraintDescs(NULL), constraintBatchHeaders(NULL), motionVelocities(NULL), bodyCoreArray(NULL)
{
}
};
Context* createDynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool,
PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback,
PxsMaterialManager* materialManager, IG::SimpleIslandManager* islandManager, PxU64 contextID,
bool enableStabilization, bool useEnhancedDeterminism,
PxReal maxBiasCoefficient, bool frictionEveryIteration, PxReal lengthScale)
{
return PX_NEW(DynamicsContext)( memBlockPool, scratchAllocator, taskPool, simStats, taskManager, allocatorCallback, materialManager, islandManager, contextID,
enableStabilization, useEnhancedDeterminism, maxBiasCoefficient, frictionEveryIteration, lengthScale);
}
void DynamicsContext::destroy()
{
this->~DynamicsContext();
PX_FREE_THIS;
}
void DynamicsContext::resetThreadContexts()
{
PxcThreadCoherentCacheIterator<ThreadContext, PxcNpMemBlockPool> threadContextIt(mThreadContextPool);
ThreadContext* threadContext = threadContextIt.getNext();
while(threadContext != NULL)
{
threadContext->reset();
threadContext = threadContextIt.getNext();
}
}
// =========================== Basic methods
DynamicsContext::DynamicsContext( PxcNpMemBlockPool* memBlockPool,
PxcScratchAllocator& scratchAllocator,
Cm::FlushPool& taskPool,
PxvSimStats& simStats,
PxTaskManager* taskManager,
PxVirtualAllocatorCallback* allocatorCallback,
PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager,
PxU64 contextID,
bool enableStabilization,
bool useEnhancedDeterminism,
PxReal maxBiasCoefficient,
bool frictionEveryIteration,
PxReal lengthScale) :
Dy::Context (islandManager, allocatorCallback, simStats, enableStabilization, useEnhancedDeterminism, maxBiasCoefficient, lengthScale, contextID),
// PT: TODO: would make sense to move all the following members to the base class but include paths get in the way atm
mThreadContextPool (memBlockPool),
mMaterialManager (materialManager),
mScratchAllocator (scratchAllocator),
mTaskPool (taskPool),
mTaskManager (taskManager)
{
createThresholdStream(*allocatorCallback);
createForceChangeThresholdStream(*allocatorCallback);
mExceededForceThresholdStream[0] = PX_NEW(ThresholdStream)(*allocatorCallback);
mExceededForceThresholdStream[1] = PX_NEW(ThresholdStream)(*allocatorCallback);
mThresholdStreamOut = 0;
mCurrentIndex = 0;
mWorldSolverBody.linearVelocity = PxVec3(0);
mWorldSolverBody.angularState = PxVec3(0);
mWorldSolverBodyData.invMass = 0;
mWorldSolverBodyData.sqrtInvInertia = PxMat33(PxZero);
mWorldSolverBodyData.nodeIndex = PX_INVALID_NODE;
mWorldSolverBodyData.reportThreshold = PX_MAX_REAL;
mWorldSolverBodyData.penBiasClamp = -PX_MAX_REAL;
mWorldSolverBodyData.maxContactImpulse = PX_MAX_REAL;
mWorldSolverBody.solverProgress=MAX_PERMITTED_SOLVER_PROGRESS;
mWorldSolverBody.maxSolverNormalProgress=MAX_PERMITTED_SOLVER_PROGRESS;
mWorldSolverBody.maxSolverFrictionProgress=MAX_PERMITTED_SOLVER_PROGRESS;
mWorldSolverBodyData.linearVelocity = mWorldSolverBodyData.angularVelocity = PxVec3(0.f);
mWorldSolverBodyData.body2World = PxTransform(PxIdentity);
mSolverCore[PxFrictionType::ePATCH] = PX_NEW(SolverCoreGeneral)(frictionEveryIteration);
mSolverCore[PxFrictionType::eONE_DIRECTIONAL] = PX_NEW(SolverCoreGeneralPF);
mSolverCore[PxFrictionType::eTWO_DIRECTIONAL] = PX_NEW(SolverCoreGeneralPF);
}
DynamicsContext::~DynamicsContext()
{
for(PxU32 i = 0; i < PxFrictionType::eFRICTION_COUNT; ++i)
{
PX_DELETE(mSolverCore[i]);
}
PX_DELETE(mExceededForceThresholdStream[1]);
PX_DELETE(mExceededForceThresholdStream[0]);
}
#if PX_ENABLE_SIM_STATS
void DynamicsContext::addThreadStats(const ThreadContext::ThreadSimStats& stats)
{
mSimStats.mNbActiveConstraints += stats.numActiveConstraints;
mSimStats.mNbActiveDynamicBodies += stats.numActiveDynamicBodies;
mSimStats.mNbActiveKinematicBodies += stats.numActiveKinematicBodies;
mSimStats.mNbAxisSolverConstraints += stats.numAxisSolverConstraints;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
// =========================== Solve methods!
void DynamicsContext::setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim, const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset)
{
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0);
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1);
const PxU32 offsetMap[] = {solverBodyOffset, 0};
//const PxU32 offsetMap[] = {mKinematicCount, 0};
if(constraint.indexType0 == PxsIndexedInteraction::eARTICULATION)
{
const PxNodeIndex& nodeIndex0 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation0);
const IG::Node& node0 = islandSim.getNode(nodeIndex0);
desc.articulationA = node0.getArticulation();
desc.linkIndexA = nodeIndex0.articulationLinkId();
}
else
{
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
//desc.articulationALength = 0; //this is unioned with bodyADataIndex
/*desc.bodyA = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBody
: &mSolverBodyPool[(PxU32)constraint.solverBody0 + offsetMap[constraint.indexType0]];
desc.bodyADataIndex = PxU16(constraint.indexType0 == PxsIndexedInteraction::eWORLD ? 0
: (PxU16)constraint.solverBody0 + 1 + offsetMap[constraint.indexType0]);*/
desc.bodyA = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBody
: &mSolverBodyPool[PxU32(constraint.solverBody0) + offsetMap[constraint.indexType0]];
desc.bodyADataIndex = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? 0
: PxU32(constraint.solverBody0) + 1 + offsetMap[constraint.indexType0];
}
if(constraint.indexType1 == PxsIndexedInteraction::eARTICULATION)
{
const PxNodeIndex& nodeIndex1 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation1);
const IG::Node& node1 = islandSim.getNode(nodeIndex1);
desc.articulationB = node1.getArticulation();
desc.linkIndexB = nodeIndex1.articulationLinkId();// PxTo8(getLinkIndex(constraint.articulation1));
}
else
{
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
//desc.articulationBLength = 0; //this is unioned with bodyBDataIndex
desc.bodyB = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBody
: &mSolverBodyPool[PxU32(constraint.solverBody1) + offsetMap[constraint.indexType1]];
desc.bodyBDataIndex = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? 0
: PxU32(constraint.solverBody1) + 1 + offsetMap[constraint.indexType1];
}
}
void DynamicsContext::setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex, const IG::SimpleIslandManager& islandManager, PxU32* bodyRemap, PxU32 solverBodyOffset)
{
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0);
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1);
const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim();
PxNodeIndex node1 = islandSim.getNodeIndex1(edgeIndex);
if (node1.isStaticBody())
{
desc.bodyA = &mWorldSolverBody;
desc.bodyADataIndex = 0;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
else
{
const IG::Node& node = islandSim.getNode(node1);
if (node.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
Dy::FeatherstoneArticulation* a = islandSim.getLLArticulation(node1);
PxU8 type;
a->fillIndexType(node1.articulationLinkId(), type);
if (type == PxsIndexedInteraction::eARTICULATION)
{
desc.articulationA = a;
desc.linkIndexA = node1.articulationLinkId();
}
else
{
desc.bodyA = &mWorldSolverBody;
desc.bodyADataIndex = 0;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
}
else
{
PxU32 activeIndex = islandSim.getActiveNodeIndex(node1);
PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset;
desc.bodyA = &mSolverBodyPool[index];
desc.bodyADataIndex = index + 1;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
}
PxNodeIndex node2 = islandSim.getNodeIndex2(edgeIndex);
if (node2.isStaticBody())
{
desc.bodyB = &mWorldSolverBody;
desc.bodyBDataIndex = 0;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
else
{
const IG::Node& node = islandSim.getNode(node2);
if (node.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
Dy::FeatherstoneArticulation* b = islandSim.getLLArticulation(node2);
PxU8 type;
b->fillIndexType(node2.articulationLinkId(), type);
if (type == PxsIndexedInteraction::eARTICULATION)
{
desc.articulationB = b;
desc.linkIndexB = node2.articulationLinkId();
}
else
{
desc.bodyB = &mWorldSolverBody;
desc.bodyBDataIndex = 0;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
}
else
{
PxU32 activeIndex = islandSim.getActiveNodeIndex(node2);
PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset;
desc.bodyB = &mSolverBodyPool[index];
desc.bodyBDataIndex = index + 1;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
}
}
class PxsPreIntegrateTask : public Cm::Task
{
PxsPreIntegrateTask& operator=(const PxsPreIntegrateTask&);
public:
PxsPreIntegrateTask( DynamicsContext& context,
PxsBodyCore*const* bodyArray,
PxsRigidBody*const* originalBodyArray,
PxU32 const* nodeIndexArray,
PxSolverBodyData* solverBodyDataPool,
PxF32 dt,
PxU32 numBodies,
volatile PxU32* maxSolverPositionIterations,
volatile PxU32* maxSolverVelocityIterations,
PxU32 startIndex,
PxU32 numToIntegrate,
const PxVec3& gravity) :
Cm::Task (context.getContextId()),
mContext (context),
mBodyArray (bodyArray),
mOriginalBodyArray (originalBodyArray),
mNodeIndexArray (nodeIndexArray),
mSolverBodyDataPool (solverBodyDataPool),
mDt (dt),
mNumBodies (numBodies),
mMaxSolverPositionIterations(maxSolverPositionIterations),
mMaxSolverVelocityIterations(maxSolverVelocityIterations),
mStartIndex (startIndex),
mNumToIntegrate (numToIntegrate),
mGravity (gravity)
{}
virtual void runInternal();
virtual const char* getName() const
{
return "PxsDynamics.preIntegrate";
}
public:
DynamicsContext& mContext;
PxsBodyCore*const* mBodyArray;
PxsRigidBody*const* mOriginalBodyArray;
PxU32 const* mNodeIndexArray;
PxSolverBody* mSolverBodies;
PxSolverBodyData* mSolverBodyDataPool;
PxF32 mDt;
PxU32 mNumBodies;
volatile PxU32* mMaxSolverPositionIterations;
volatile PxU32* mMaxSolverVelocityIterations;
PxU32 mStartIndex;
PxU32 mNumToIntegrate;
PxVec3 mGravity;
};
class PxsParallelSolverTask : public Cm::Task
{
PxsParallelSolverTask& operator=(PxsParallelSolverTask&);
public:
PxsParallelSolverTask(SolverIslandParams& params, DynamicsContext& context, IG::IslandSim& islandSim)
: Cm::Task(context.getContextId()), mParams(params), mContext(context), mIslandSim(islandSim)
{
}
virtual void runInternal()
{
solveParallel(mContext, mParams, mIslandSim);
}
virtual const char* getName() const
{
return "PxsDynamics.parallelSolver";
}
SolverIslandParams& mParams;
DynamicsContext& mContext;
IG::IslandSim& mIslandSim;
};
#define PX_CONTACT_REDUCTION 1
class PxsSolverConstraintPostProcessTask : public Cm::Task
{
PxsSolverConstraintPostProcessTask& operator=(const PxsSolverConstraintPostProcessTask&);
public:
PxsSolverConstraintPostProcessTask(DynamicsContext& context,
ThreadContext& threadContext,
const SolverIslandObjects& objects,
PxU32 solverBodyOffset,
PxU32 startIndex,
PxU32 stride,
PxsMaterialManager* materialManager,
PxsContactManagerOutputIterator& iterator) :
Cm::Task (context.getContextId()),
mContext (context),
mThreadContext (threadContext),
mObjects (objects),
mSolverBodyOffset (solverBodyOffset),
mStartIndex (startIndex),
mStride (stride),
mMaterialManager (materialManager),
mOutputs (iterator)
{}
void mergeContacts(CompoundContactManager& header, ThreadContext& threadContext)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
PxsMaterialInfo materialInfo[PxContactBuffer::MAX_CONTACTS];
PxU32 size = 0;
for(PxU32 a = 0; a < header.mStride; ++a)
{
PxsContactManager* manager = mThreadContext.orderedContactList[a+header.mStartIndex]->contactManager;
PxcNpWorkUnit& unit = manager->getWorkUnit();
PxsContactManagerOutput& output = mOutputs.getContactManager(unit.mNpIndex);
PxContactStreamIterator iter(output.contactPatches, output.contactPoints, output.getInternalFaceIndice(), output.nbPatches, output.nbContacts);
PxU32 origSize = size;
PX_UNUSED(origSize);
if(!iter.forceNoResponse)
{
while(iter.hasNextPatch())
{
iter.nextPatch();
while(iter.hasNextContact())
{
PX_ASSERT(size < PxContactBuffer::MAX_CONTACTS);
iter.nextContact();
PxsMaterialInfo& info = materialInfo[size];
PxContactPoint& point = buffer.contacts[size++];
point.dynamicFriction = iter.getDynamicFriction();
point.staticFriction = iter.getStaticFriction();
point.restitution = iter.getRestitution();
point.internalFaceIndex1 = iter.getFaceIndex1();
point.materialFlags = PxU8(iter.getMaterialFlags());
point.maxImpulse = iter.getMaxImpulse();
point.targetVel = iter.getTargetVel();
point.normal = iter.getContactNormal();
point.point = iter.getContactPoint();
point.separation = iter.getSeparation();
info.mMaterialIndex0 = iter.getMaterialIndex0();
info.mMaterialIndex1 = iter.getMaterialIndex1();
}
}
PX_ASSERT(output.nbContacts == (size - origSize));
}
}
PxU32 origSize = size;
#if PX_CONTACT_REDUCTION
ContactReduction<6> reduction(buffer.contacts, materialInfo, size);
reduction.reduceContacts();
//OK, now we write back the contacts...
PxU8 histo[PxContactBuffer::MAX_CONTACTS];
PxMemZero(histo, sizeof(histo));
size = 0;
for(PxU32 a = 0; a < reduction.mNumPatches; ++a)
{
ReducedContactPatch& patch = reduction.mPatches[a];
for(PxU32 b = 0; b < patch.numContactPoints; ++b)
{
histo[patch.contactPoints[b]] = 1;
++size;
}
}
#endif
PxU16* PX_RESTRICT data = reinterpret_cast<PxU16*>(threadContext.mConstraintBlockStream.reserve(size * sizeof(PxU16), mThreadContext.mConstraintBlockManager));
header.forceBufferList = data;
#if PX_CONTACT_REDUCTION
const PxU32 reservedSize = size;
PX_UNUSED(reservedSize);
size = 0;
for(PxU32 a = 0; a < origSize; ++a)
{
if(histo[a])
{
if(size != a)
{
buffer.contacts[size] = buffer.contacts[a];
materialInfo[size] = materialInfo[a];
}
data[size] = PxTo16(a);
size++;
}
}
PX_ASSERT(reservedSize >= size);
#else
for(PxU32 a = 0; a < size; ++a)
data[a] = a;
#endif
PxU32 contactForceByteSize = size * sizeof(PxReal);
PxsContactManagerOutput& output = mOutputs.getContactManager(header.unit->mNpIndex);
PxU16 compressedContactSize;
physx::writeCompressedContact(buffer.contacts, size, NULL, output.nbContacts, output.contactPatches, output.contactPoints, compressedContactSize,
reinterpret_cast<PxReal*&>(output.contactForces), contactForceByteSize, mMaterialManager, false,
false, materialInfo, output.nbPatches, 0, &mThreadContext.mConstraintBlockManager, &threadContext.mConstraintBlockStream, false);
}
virtual void runInternal()
{
PX_PROFILE_ZONE("ConstraintPostProcess", mContext.getContextId());
PxU32 endIndex = mStartIndex + mStride;
ThreadContext* threadContext = mContext.getThreadContext();
//TODO - we need to do this somewhere else
//threadContext->mContactBlockStream.reset();
threadContext->mConstraintBlockStream.reset();
for(PxU32 a = mStartIndex; a < endIndex; ++a)
{
mergeContacts(mThreadContext.compoundConstraints[a], *threadContext);
}
mContext.putThreadContext(threadContext);
}
virtual const char* getName() const { return "PxsDynamics.solverConstraintPostProcess"; }
DynamicsContext& mContext;
ThreadContext& mThreadContext;
const SolverIslandObjects mObjects;
const PxU32 mSolverBodyOffset;
const PxU32 mStartIndex;
const PxU32 mStride;
PxsMaterialManager* mMaterialManager;
PxsContactManagerOutputIterator& mOutputs;
};
class PxsForceThresholdTask : public Cm::Task
{
DynamicsContext& mDynamicsContext;
PxsForceThresholdTask& operator=(const PxsForceThresholdTask&);
public:
PxsForceThresholdTask(DynamicsContext& context): Cm::Task(context.getContextId()), mDynamicsContext(context)
{
}
void createForceChangeThresholdStream()
{
ThresholdStream& thresholdStream = mDynamicsContext.getThresholdStream();
//bool haveThresholding = thresholdStream.size()!=0;
ThresholdTable& thresholdTable = mDynamicsContext.getThresholdTable();
thresholdTable.build(thresholdStream);
//generate current force exceeded threshold stream
ThresholdStream& curExceededForceThresholdStream = *mDynamicsContext.mExceededForceThresholdStream[mDynamicsContext.mCurrentIndex];
ThresholdStream& preExceededForceThresholdStream = *mDynamicsContext.mExceededForceThresholdStream[1 - mDynamicsContext.mCurrentIndex];
curExceededForceThresholdStream.forceSize_Unsafe(0);
//fill in the currrent exceeded force threshold stream
for(PxU32 i=0; i<thresholdTable.mPairsSize; ++i)
{
ThresholdTable::Pair& pair = thresholdTable.mPairs[i];
ThresholdStreamElement& elem = thresholdStream[pair.thresholdStreamIndex];
if(pair.accumulatedForce > elem.threshold * mDynamicsContext.mDt)
{
elem.accumulatedForce = pair.accumulatedForce;
curExceededForceThresholdStream.pushBack(elem);
}
}
ThresholdStream& forceChangeThresholdStream = mDynamicsContext.getForceChangedThresholdStream();
forceChangeThresholdStream.forceSize_Unsafe(0);
PxArray<PxU32>& forceChangeMask = mDynamicsContext.mExceededForceThresholdStreamMask;
const PxU32 nbPreExceededForce = preExceededForceThresholdStream.size();
const PxU32 nbCurExceededForce = curExceededForceThresholdStream.size();
//generate force change thresholdStream
if(nbPreExceededForce)
{
thresholdTable.build(preExceededForceThresholdStream);
//set force change mask
const PxU32 nbTotalExceededForce = nbPreExceededForce + nbCurExceededForce;
forceChangeMask.reserve(nbTotalExceededForce);
forceChangeMask.forceSize_Unsafe(nbTotalExceededForce);
//initialize the forceChangeMask
for (PxU32 i = 0; i < nbTotalExceededForce; ++i)
forceChangeMask[i] = 1;
for(PxU32 i=0; i< nbCurExceededForce; ++i)
{
ThresholdStreamElement& curElem = curExceededForceThresholdStream[i];
PxU32 pos;
if(thresholdTable.check(preExceededForceThresholdStream, curElem, pos))
{
forceChangeMask[pos] = 0;
forceChangeMask[i + nbPreExceededForce] = 0;
}
}
//create force change threshold stream
for(PxU32 i=0; i<nbTotalExceededForce; ++i)
{
const PxU32 hasForceChange = forceChangeMask[i];
if(hasForceChange)
{
bool lostPair = (i < nbPreExceededForce);
ThresholdStreamElement& elem = lostPair ? preExceededForceThresholdStream[i] : curExceededForceThresholdStream[i - nbPreExceededForce];
ThresholdStreamElement elt;
elt = elem;
elt.accumulatedForce = lostPair ? 0.f : elem.accumulatedForce;
forceChangeThresholdStream.pushBack(elt);
}
else
{
//persistent pair
if (i < nbPreExceededForce)
{
ThresholdStreamElement& elem = preExceededForceThresholdStream[i];
ThresholdStreamElement elt;
elt = elem;
elt.accumulatedForce = elem.accumulatedForce;
forceChangeThresholdStream.pushBack(elt);
}
}
}
}
else
{
forceChangeThresholdStream.reserve(nbCurExceededForce);
forceChangeThresholdStream.forceSize_Unsafe(nbCurExceededForce);
PxMemCopy(forceChangeThresholdStream.begin(), curExceededForceThresholdStream.begin(), sizeof(ThresholdStreamElement) * nbCurExceededForce);
}
}
virtual void runInternal()
{
mDynamicsContext.getThresholdStream().forceSize_Unsafe(PxU32(mDynamicsContext.mThresholdStreamOut));
createForceChangeThresholdStream();
}
virtual const char* getName() const { return "PxsDynamics.createForceChangeThresholdStream"; }
};
struct ConstraintLess
{
bool operator()(const PxSolverConstraintDesc& left, const PxSolverConstraintDesc& right) const
{
return reinterpret_cast<Constraint*>(left.constraint)->index > reinterpret_cast<Constraint*>(right.constraint)->index;
}
};
struct ArticulationSortPredicate
{
bool operator()(const PxsIndexedContactManager*& left, const PxsIndexedContactManager*& right) const
{
return left->contactManager->getWorkUnit().index < right->contactManager->getWorkUnit().index;
}
};
class SolverArticulationUpdateTask : public Cm::Task
{
ThreadContext& mIslandThreadContext;
FeatherstoneArticulation** mArticulations;
ArticulationSolverDesc* mArticulationDescArray;
PxU32 mNbToProcess;
Dy::DynamicsContext& mContext;
public:
static const PxU32 NbArticulationsPerTask = 32;
SolverArticulationUpdateTask(ThreadContext& islandThreadContext, FeatherstoneArticulation** articulations, ArticulationSolverDesc* articulationDescArray, PxU32 nbToProcess, Dy::DynamicsContext& context) :
Cm::Task(context.getContextId()), mIslandThreadContext(islandThreadContext), mArticulations(articulations), mArticulationDescArray(articulationDescArray), mNbToProcess(nbToProcess), mContext(context)
{
}
virtual const char* getName() const { return "SolverArticulationUpdateTask"; }
virtual void runInternal()
{
ThreadContext& threadContext = *mContext.getThreadContext();
threadContext.mConstraintBlockStream.reset(); //Clear in case there's some left-over memory in this context, for which the block has already been freed
PxU32 maxVelIters = 0;
PxU32 maxPosIters = 0;
PxU32 maxLinks = 0;
for (PxU32 i = 0; i < mNbToProcess; i++)
{
FeatherstoneArticulation& a = *(mArticulations[i]);
a.getSolverDesc(mArticulationDescArray[i]);
maxLinks = PxMax(maxLinks, PxU32(mArticulationDescArray[i].linkCount));
}
threadContext.mZVector.forceSize_Unsafe(0);
threadContext.mZVector.reserve(maxLinks);
threadContext.mZVector.forceSize_Unsafe(maxLinks);
threadContext.mDeltaV.forceSize_Unsafe(0);
threadContext.mDeltaV.reserve(maxLinks);
threadContext.mDeltaV.forceSize_Unsafe(maxLinks);
BlockAllocator blockAllocator(mIslandThreadContext.mConstraintBlockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize);
const PxReal invLengthScale = 1.f/mContext.getLengthScale();
for(PxU32 i=0;i<mNbToProcess; i++)
{
FeatherstoneArticulation& a = *(mArticulations[i]);
PxU32 acCount, descCount;
descCount = ArticulationPImpl::computeUnconstrainedVelocities(mArticulationDescArray[i], mContext.mDt,
acCount, mContext.getGravity(),
threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), invLengthScale);
mArticulationDescArray[i].numInternalConstraints = PxTo8(descCount);
const PxU16 iterWord = a.getIterationCounts();
maxVelIters = PxMax<PxU32>(PxU32(iterWord >> 8), maxVelIters);
maxPosIters = PxMax<PxU32>(PxU32(iterWord & 0xff), maxPosIters);
}
PxAtomicMax(reinterpret_cast<PxI32*>(&mIslandThreadContext.mMaxSolverPositionIterations), PxI32(maxPosIters));
PxAtomicMax(reinterpret_cast<PxI32*>(&mIslandThreadContext.mMaxSolverVelocityIterations), PxI32(maxVelIters));
PxAtomicMax(reinterpret_cast<PxI32*>(&mIslandThreadContext.mMaxArticulationLinks), PxI32(maxLinks));
mContext.putThreadContext(&threadContext);
}
private:
PX_NOCOPY(SolverArticulationUpdateTask)
};
struct EnhancedSortPredicate
{
bool operator()(const PxsIndexedContactManager& left, const PxsIndexedContactManager& right) const
{
PxcNpWorkUnit& unit0 = left.contactManager->getWorkUnit();
PxcNpWorkUnit& unit1 = right.contactManager->getWorkUnit();
return (unit0.mTransformCache0 < unit1.mTransformCache0) ||
((unit0.mTransformCache0 == unit1.mTransformCache0) && (unit0.mTransformCache1 < unit1.mTransformCache1));
}
};
class PxsSolverStartTask : public Cm::Task
{
PxsSolverStartTask& operator=(const PxsSolverStartTask&);
public:
PxsSolverStartTask(DynamicsContext& context,
IslandContext& islandContext,
const SolverIslandObjects& objects,
PxU32 solverBodyOffset,
PxU32 kinematicCount,
IG::SimpleIslandManager& islandManager,
PxU32* bodyRemapTable,
PxsMaterialManager* materialManager,
PxsContactManagerOutputIterator& iterator,
bool enhancedDeterminism
) :
Cm::Task (context.getContextId()),
mContext (context),
mIslandContext (islandContext),
mObjects (objects),
mSolverBodyOffset (solverBodyOffset),
mKinematicCount (kinematicCount),
mIslandManager (islandManager),
mBodyRemapTable (bodyRemapTable),
mMaterialManager (materialManager),
mOutputs (iterator),
mEnhancedDeterminism (enhancedDeterminism)
{}
void startTasks()
{
PX_PROFILE_ZONE("Dynamics.solveGroup", mContext.getContextId());
{
ThreadContext& mThreadContext = *mContext.getThreadContext();
mIslandContext.mThreadContext = &mThreadContext;
mThreadContext.mMaxSolverPositionIterations = 0;
mThreadContext.mMaxSolverVelocityIterations = 0;
mThreadContext.mAxisConstraintCount = 0;
mThreadContext.mContactDescPtr = mThreadContext.contactConstraintDescArray;
mThreadContext.mFrictionDescPtr = mThreadContext.frictionConstraintDescArray.begin();
mThreadContext.mNumDifferentBodyConstraints = 0;
mThreadContext.mNumStaticConstraints = 0;
mThreadContext.mNumSelfConstraints = 0;
mThreadContext.mNumDifferentBodyFrictionConstraints = 0;
mThreadContext.mNumSelfConstraintFrictionBlocks = 0;
mThreadContext.mNumSelfFrictionConstraints = 0;
mThreadContext.numContactConstraintBatches = 0;
mThreadContext.contactDescArraySize = 0;
mThreadContext.mMaxArticulationLinks = 0;
mThreadContext.contactConstraintDescArray = mObjects.constraintDescs;
mThreadContext.orderedContactConstraints = mObjects.orderedConstraintDescs;
mThreadContext.mContactDescPtr = mObjects.constraintDescs;
mThreadContext.tempConstraintDescArray = mObjects.tempConstraintDescs;
mThreadContext.contactConstraintBatchHeaders = mObjects.constraintBatchHeaders;
mThreadContext.motionVelocityArray = mObjects.motionVelocities;
mThreadContext.mBodyCoreArray = mObjects.bodyCoreArray;
mThreadContext.mRigidBodyArray = mObjects.bodies;
mThreadContext.mArticulationArray = mObjects.articulations;
mThreadContext.bodyRemapTable = mObjects.bodyRemapTable;
mThreadContext.mNodeIndexArray = mObjects.nodeIndexArray;
const PxU32 frictionConstraintCount = mContext.getFrictionType() == PxFrictionType::ePATCH ? 0 : PxU32(mIslandContext.mCounts.contactManagers);
mThreadContext.resizeArrays(frictionConstraintCount, mIslandContext.mCounts.articulations);
PxsBodyCore** PX_RESTRICT bodyArrayPtr = mThreadContext.mBodyCoreArray;
PxsRigidBody** PX_RESTRICT rigidBodyPtr = mThreadContext.mRigidBodyArray;
FeatherstoneArticulation** PX_RESTRICT articulationPtr = mThreadContext.mArticulationArray;
PxU32* PX_RESTRICT bodyRemapTable = mThreadContext.bodyRemapTable;
PxU32* PX_RESTRICT nodeIndexArray = mThreadContext.mNodeIndexArray;
PxU32 nbIslands = mObjects.numIslands;
const IG::IslandId* const islandIds = mObjects.islandIds;
const IG::IslandSim& islandSim = mIslandManager.getAccurateIslandSim();
PxU32 bodyIndex = 0, articIndex = 0;
for (PxU32 i = 0; i < nbIslands; ++i)
{
const IG::Island& island = islandSim.getIsland(islandIds[i]);
PxNodeIndex currentIndex = island.mRootNode;
while (currentIndex.isValid())
{
const IG::Node& node = islandSim.getNode(currentIndex);
if (node.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
articulationPtr[articIndex++] = node.getArticulation();
}
else
{
PX_ASSERT(bodyIndex < (mIslandContext.mCounts.bodies + mContext.mKinematicCount + 1));
nodeIndexArray[bodyIndex++] = currentIndex.index();
}
currentIndex = node.mNextNode;
}
}
//Bodies can come in a slightly jumbled order from islandGen. It's deterministic if the scene is
//identical but can vary if there are additional bodies in the scene in a different island.
if (mEnhancedDeterminism)
PxSort(nodeIndexArray, bodyIndex);
for (PxU32 a = 0; a < bodyIndex; ++a)
{
PxNodeIndex currentIndex(nodeIndexArray[a]);
const IG::Node& node = islandSim.getNode(currentIndex);
PxsRigidBody* rigid = node.getRigidBody();
rigidBodyPtr[a] = rigid;
bodyArrayPtr[a] = &rigid->getCore();
bodyRemapTable[islandSim.getActiveNodeIndex(currentIndex)] = a;
}
PxsIndexedContactManager* indexedManagers = mObjects.contactManagers;
PxU32 currentContactIndex = 0;
for(PxU32 i = 0; i < nbIslands; ++i)
{
const IG::Island& island = islandSim.getIsland(islandIds[i]);
IG::EdgeIndex contactEdgeIndex = island.mFirstEdge[IG::Edge::eCONTACT_MANAGER];
while(contactEdgeIndex != IG_INVALID_EDGE)
{
const IG::Edge& edge = islandSim.getEdge(contactEdgeIndex);
PxsContactManager* contactManager = mIslandManager.getContactManager(contactEdgeIndex);
if(contactManager)
{
const PxNodeIndex nodeIndex1 = islandSim.getNodeIndex1(contactEdgeIndex);
const PxNodeIndex nodeIndex2 = islandSim.getNodeIndex2(contactEdgeIndex);
PxsIndexedContactManager& indexedManager = indexedManagers[currentContactIndex++];
indexedManager.contactManager = contactManager;
PX_ASSERT(!nodeIndex1.isStaticBody());
{
const IG::Node& node1 = islandSim.getNode(nodeIndex1);
//Is it an articulation or not???
if(node1.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
indexedManager.articulation0 = nodeIndex1.getInd();
const PxU32 linkId = nodeIndex1.articulationLinkId();
node1.getArticulation()->fillIndexType(linkId, indexedManager.indexType0);
}
else
{
if(node1.isKinematic())
{
indexedManager.indexType0 = PxsIndexedInteraction::eKINEMATIC;
indexedManager.solverBody0 = islandSim.getActiveNodeIndex(nodeIndex1);
}
else
{
indexedManager.indexType0 = PxsIndexedInteraction::eBODY;
indexedManager.solverBody0 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex1)];
}
PX_ASSERT(indexedManager.solverBody0 < (mIslandContext.mCounts.bodies + mContext.mKinematicCount + 1));
}
}
if(nodeIndex2.isStaticBody())
{
indexedManager.indexType1 = PxsIndexedInteraction::eWORLD;
}
else
{
const IG::Node& node2 = islandSim.getNode(nodeIndex2);
//Is it an articulation or not???
if(node2.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
indexedManager.articulation1 = nodeIndex2.getInd();
const PxU32 linkId = nodeIndex2.articulationLinkId();
node2.getArticulation()->fillIndexType(linkId, indexedManager.indexType1);
}
else
{
if(node2.isKinematic())
{
indexedManager.indexType1 = PxsIndexedInteraction::eKINEMATIC;
indexedManager.solverBody1 = islandSim.getActiveNodeIndex(nodeIndex2);
}
else
{
indexedManager.indexType1 = PxsIndexedInteraction::eBODY;
indexedManager.solverBody1 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex2)];
}
PX_ASSERT(indexedManager.solverBody1 < (mIslandContext.mCounts.bodies + mContext.mKinematicCount + 1));
}
}
}
contactEdgeIndex = edge.mNextIslandEdge;
}
}
if (mEnhancedDeterminism)
PxSort(indexedManagers, currentContactIndex, EnhancedSortPredicate());
mIslandContext.mCounts.contactManagers = currentContactIndex;
}
}
void integrate()
{
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
PxSolverBody* solverBodies = mContext.mSolverBodyPool.begin() + mSolverBodyOffset;
PxSolverBodyData* solverBodyData = mContext.mSolverBodyDataPool.begin() + mSolverBodyOffset;
{
PX_PROFILE_ZONE("Dynamics.updateVelocities", mContext.getContextId());
mContext.preIntegrationParallel(
mContext.mDt,
mThreadContext.mBodyCoreArray,
mObjects.bodies,
mThreadContext.mNodeIndexArray,
mIslandContext.mCounts.bodies,
solverBodies,
solverBodyData,
mThreadContext.motionVelocityArray,
mThreadContext.mMaxSolverPositionIterations,
mThreadContext.mMaxSolverVelocityIterations,
*mCont
);
}
}
void articulationTask()
{
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
ArticulationSolverDesc* articulationDescArray = mThreadContext.getArticulations().begin();
for(PxU32 i=0;i<mIslandContext.mCounts.articulations; i+= SolverArticulationUpdateTask::NbArticulationsPerTask)
{
SolverArticulationUpdateTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(SolverArticulationUpdateTask)), SolverArticulationUpdateTask)(mThreadContext,
&mObjects.articulations[i], &articulationDescArray[i], PxMin(SolverArticulationUpdateTask::NbArticulationsPerTask, mIslandContext.mCounts.articulations - i), mContext);
task->setContinuation(mCont);
task->removeReference();
}
}
void setupDescTask()
{
PX_PROFILE_ZONE("SetupDescs", mContext.getContextId());
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
PxSolverConstraintDesc* contactDescPtr = mThreadContext.mContactDescPtr;
//PxU32 constraintCount = mCounts.constraints + mCounts.contactManagers;
PxU32 nbIslands = mObjects.numIslands;
const IG::IslandId* const islandIds = mObjects.islandIds;
const IG::IslandSim& islandSim = mIslandManager.getAccurateIslandSim();
for(PxU32 i = 0; i < nbIslands; ++i)
{
const IG::Island& island = islandSim.getIsland(islandIds[i]);
IG::EdgeIndex edgeId = island.mFirstEdge[IG::Edge::eCONSTRAINT];
while(edgeId != IG_INVALID_EDGE)
{
PxSolverConstraintDesc& desc = *contactDescPtr;
const IG::Edge& edge = islandSim.getEdge(edgeId);
Dy::Constraint* constraint = mIslandManager.getConstraint(edgeId);
mContext.setDescFromIndices(desc, edgeId, mIslandManager, mBodyRemapTable, mSolverBodyOffset);
desc.constraint = reinterpret_cast<PxU8*>(constraint);
desc.constraintLengthOver16 = DY_SC_TYPE_RB_1D;
contactDescPtr++;
edgeId = edge.mNextIslandEdge;
}
}
#if 1
PxSort(mThreadContext.mContactDescPtr, PxU32(contactDescPtr - mThreadContext.mContactDescPtr), ConstraintLess());
#endif
mThreadContext.orderedContactList.forceSize_Unsafe(0);
mThreadContext.orderedContactList.reserve(mIslandContext.mCounts.contactManagers);
mThreadContext.orderedContactList.forceSize_Unsafe(mIslandContext.mCounts.contactManagers);
mThreadContext.tempContactList.forceSize_Unsafe(0);
mThreadContext.tempContactList.reserve(mIslandContext.mCounts.contactManagers);
mThreadContext.tempContactList.forceSize_Unsafe(mIslandContext.mCounts.contactManagers);
const PxsIndexedContactManager** constraints = mThreadContext.orderedContactList.begin();
//OK, we sort the orderedContactList
mThreadContext.compoundConstraints.forceSize_Unsafe(0);
if(mIslandContext.mCounts.contactManagers)
{
{
mThreadContext.sortIndexArray.forceSize_Unsafe(0);
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0);
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1);
const PxI32 offsetMap[] = {PxI32(mContext.mKinematicCount), 0};
const PxU32 totalBodies = mContext.mKinematicCount + mIslandContext.mCounts.bodies+1;
mThreadContext.sortIndexArray.reserve(totalBodies);
mThreadContext.sortIndexArray.forceSize_Unsafe(totalBodies);
PxMemZero(mThreadContext.sortIndexArray.begin(), totalBodies * 4);
//Iterate over the array based on solverBodyDatapool, creating a list of sorted constraints (in order of body pair)
//We only do this with contacts. It's important that this is done this way because we don't want to break our rules that all joints
//appear before all contacts in the constraint list otherwise we will lose all guarantees about sorting joints.
for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a)
{
PX_ASSERT(mObjects.contactManagers[a].indexType0 != PxsIndexedInteraction::eWORLD);
//Index first body...
PxU8 indexType = mObjects.contactManagers[a].indexType0;
if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType1 != PxsIndexedInteraction::eARTICULATION)
{
PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC));
PxI32 index = PxI32(mObjects.contactManagers[a].solverBody0 + offsetMap[indexType]);
PX_ASSERT(index >= 0);
mThreadContext.sortIndexArray[PxU32(index)]++;
}
}
PxU32 accumulatedCount = 0;
for(PxU32 a = mThreadContext.sortIndexArray.size(); a > 0; --a)
{
PxU32 ind = a - 1;
PxU32 val = mThreadContext.sortIndexArray[ind];
mThreadContext.sortIndexArray[ind] = accumulatedCount;
accumulatedCount += val;
}
//OK, now copy across data to orderedConstraintDescs, pushing articulations to the end...
for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a)
{
//Index first body...
PxU8 indexType = mObjects.contactManagers[a].indexType0;
if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType1 != PxsIndexedInteraction::eARTICULATION)
{
PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC));
PxI32 index = PxI32(mObjects.contactManagers[a].solverBody0 + offsetMap[indexType]);
PX_ASSERT(index >= 0);
mThreadContext.tempContactList[mThreadContext.sortIndexArray[PxU32(index)]++] = &mObjects.contactManagers[a];
}
else
{
mThreadContext.tempContactList[accumulatedCount++] = &mObjects.contactManagers[a];
}
}
//Now do the same again with bodyB, being careful not to overwrite the joints
PxMemZero(mThreadContext.sortIndexArray.begin(), totalBodies * 4);
for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a)
{
//Index first body...
PxU8 indexType = mThreadContext.tempContactList[a]->indexType1;
if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType0 != PxsIndexedInteraction::eARTICULATION)
{
PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC) || (indexType == PxsIndexedInteraction::eWORLD));
PxI32 index = (indexType == PxsIndexedInteraction::eWORLD) ? 0 : PxI32(mThreadContext.tempContactList[a]->solverBody1 + offsetMap[indexType]);
PX_ASSERT(index >= 0);
mThreadContext.sortIndexArray[PxU32(index)]++;
}
}
accumulatedCount = 0;
for(PxU32 a = mThreadContext.sortIndexArray.size(); a > 0; --a)
{
PxU32 ind = a - 1;
PxU32 val = mThreadContext.sortIndexArray[ind];
mThreadContext.sortIndexArray[ind] = accumulatedCount;
accumulatedCount += val;
}
PxU32 articulationStartIndex = accumulatedCount;
//OK, now copy across data to orderedConstraintDescs, pushing articulations to the end...
for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a)
{
//Index first body...
PxU8 indexType = mThreadContext.tempContactList[a]->indexType1;
if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType0 != PxsIndexedInteraction::eARTICULATION)
{
PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC) || (indexType == PxsIndexedInteraction::eWORLD));
PxI32 index = (indexType == PxsIndexedInteraction::eWORLD) ? 0 : PxI32(mThreadContext.tempContactList[a]->solverBody1 + offsetMap[indexType]);
PX_ASSERT(index >= 0);
constraints[mThreadContext.sortIndexArray[PxU32(index)]++] = mThreadContext.tempContactList[a];
}
else
{
constraints[accumulatedCount++] = mThreadContext.tempContactList[a];
}
}
#if 1
PxSort(constraints + articulationStartIndex, accumulatedCount - articulationStartIndex, ArticulationSortPredicate());
#endif
}
mThreadContext.mStartContactDescPtr = contactDescPtr;
mThreadContext.compoundConstraints.reserve(1024);
mThreadContext.compoundConstraints.forceSize_Unsafe(0);
//mThreadContext.compoundConstraints.forceSize_Unsafe(mCounts.contactManagers);
PxSolverConstraintDesc* startDesc = contactDescPtr;
mContext.setDescFromIndices(*startDesc, islandSim, *constraints[0], mSolverBodyOffset);
startDesc->constraint = reinterpret_cast<PxU8*>(constraints[0]->contactManager);
startDesc->constraintLengthOver16 = DY_SC_TYPE_RB_CONTACT;
PxsContactManagerOutput* startManagerOutput = &mOutputs.getContactManager(constraints[0]->contactManager->getWorkUnit().mNpIndex);
PxU32 contactCount = startManagerOutput->nbContacts;
PxU32 startIndex = 0;
PxU32 numHeaders = 0;
const bool gDisableConstraintWelding = false;
for(PxU32 a = 1; a < mIslandContext.mCounts.contactManagers; ++a)
{
PxSolverConstraintDesc& desc = *(contactDescPtr+1);
mContext.setDescFromIndices(desc, islandSim, *constraints[a], mSolverBodyOffset);
PxsContactManager* manager = constraints[a]->contactManager;
PxsContactManagerOutput& output = mOutputs.getContactManager(manager->getWorkUnit().mNpIndex);
desc.constraint = reinterpret_cast<PxU8*>(constraints[a]->contactManager);
desc.constraintLengthOver16 = DY_SC_TYPE_RB_CONTACT;
if (contactCount == 0)
{
//This is the first object in the pair
*startDesc = *(contactDescPtr + 1);
startIndex = a;
startManagerOutput = &output;
}
if(startDesc->bodyA != desc.bodyA || startDesc->bodyB != desc.bodyB
|| startDesc->linkIndexA != PxSolverConstraintDesc::RIGID_BODY || startDesc->linkIndexB != PxSolverConstraintDesc::RIGID_BODY
|| contactCount + output.nbContacts > PxContactBuffer::MAX_CONTACTS
|| manager->isChangeable()
|| gDisableConstraintWelding
) //If this is the first thing and no contacts...then we skip
{
const PxU32 stride = a - startIndex;
if(contactCount > 0)
{
if(stride > 1)
{
++numHeaders;
CompoundContactManager& header = mThreadContext.compoundConstraints.insert();
header.mStartIndex = startIndex;
header.mStride = PxTo16(stride);
header.mReducedContactCount = PxTo16(contactCount);
PxsContactManager* manager1 = constraints[startIndex]->contactManager;
PxcNpWorkUnit& unit = manager1->getWorkUnit();
PX_ASSERT(startManagerOutput == &mOutputs.getContactManager(unit.mNpIndex));
header.unit = &unit;
header.cmOutput = startManagerOutput;
header.originalContactPatches = startManagerOutput->contactPatches;
header.originalContactPoints = startManagerOutput->contactPoints;
header.originalContactCount = startManagerOutput->nbContacts;
header.originalPatchCount = startManagerOutput->nbPatches;
header.originalForceBuffer = reinterpret_cast<PxReal*>(startManagerOutput->contactForces);
header.originalStatusFlags = startManagerOutput->statusFlag;
}
startDesc = ++contactDescPtr;
}
else
{
//Copy back next contactDescPtr
*startDesc = *(contactDescPtr+1);
}
contactCount = 0;
startIndex = a;
startManagerOutput = &output;
}
contactCount += output.nbContacts;
}
const PxU32 stride = mIslandContext.mCounts.contactManagers - startIndex;
if(contactCount > 0)
{
if(stride > 1)
{
++numHeaders;
CompoundContactManager& header = mThreadContext.compoundConstraints.insert();
header.mStartIndex = startIndex;
header.mStride = PxTo16(stride);
header.mReducedContactCount = PxTo16(contactCount);
PxsContactManager* manager = constraints[startIndex]->contactManager;
PxcNpWorkUnit& unit = manager->getWorkUnit();
header.unit = &unit;
header.cmOutput = startManagerOutput;
header.originalContactPatches = startManagerOutput->contactPatches;
header.originalContactPoints = startManagerOutput->contactPoints;
header.originalContactCount = startManagerOutput->nbContacts;
header.originalPatchCount = startManagerOutput->nbPatches;
header.originalForceBuffer = reinterpret_cast<PxReal*>(startManagerOutput->contactForces);
header.originalStatusFlags = startManagerOutput->statusFlag;
}
contactDescPtr++;
}
if(numHeaders)
{
const PxU32 unrollSize = 8;
for(PxU32 a = 0; a < numHeaders; a+= unrollSize)
{
PxsSolverConstraintPostProcessTask* postProcessTask = PX_PLACEMENT_NEW( mContext.getTaskPool().allocate(sizeof(PxsSolverConstraintPostProcessTask)),
PxsSolverConstraintPostProcessTask)(mContext, mThreadContext, mObjects, mSolverBodyOffset, a, PxMin(unrollSize, numHeaders - a), mMaterialManager,
mOutputs);
postProcessTask->setContinuation(mCont);
postProcessTask->removeReference();
}
}
}
mThreadContext.contactDescArraySize = PxU32(contactDescPtr - mThreadContext.contactConstraintDescArray);
mThreadContext.mContactDescPtr = contactDescPtr;
}
virtual void runInternal()
{
startTasks();
integrate();
setupDescTask();
articulationTask();
}
virtual const char* getName() const
{
return "PxsDynamics.solverStart";
}
private:
DynamicsContext& mContext;
IslandContext& mIslandContext;
const SolverIslandObjects mObjects;
const PxU32 mSolverBodyOffset;
const PxU32 mKinematicCount;
IG::SimpleIslandManager& mIslandManager;
PxU32* mBodyRemapTable;
PxsMaterialManager* mMaterialManager;
PxsContactManagerOutputIterator& mOutputs;
const bool mEnhancedDeterminism;
};
class PxsSolverConstraintPartitionTask : public Cm::Task
{
PxsSolverConstraintPartitionTask& operator=(const PxsSolverConstraintPartitionTask&);
public:
PxsSolverConstraintPartitionTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, bool enhancedDeterminism) :
Cm::Task (context.getContextId()),
mContext (context),
mIslandContext (islandContext),
mObjects (objects),
mSolverBodyOffset (solverBodyOffset),
mEnhancedDeterminism(enhancedDeterminism)
{}
virtual void runInternal()
{
PX_PROFILE_ZONE("PartitionConstraints", mContext.getContextId());
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
//Compact articulation pairs...
const ArticulationSolverDesc* artics = mThreadContext.getArticulations().begin();
const PxSolverConstraintDesc* descBegin = mThreadContext.contactConstraintDescArray;
const PxU32 descCount = mThreadContext.contactDescArraySize;
PxSolverBody* solverBodies = mContext.mSolverBodyPool.begin() + mSolverBodyOffset;
mThreadContext.mNumDifferentBodyConstraints = descCount;
{
mThreadContext.mNumDifferentBodyConstraints = 0;
mThreadContext.mNumSelfConstraints = 0;
mThreadContext.mNumStaticConstraints = 0;
mThreadContext.mNumDifferentBodyFrictionConstraints = 0;
mThreadContext.mNumSelfConstraintFrictionBlocks = 0;
mThreadContext.mNumSelfFrictionConstraints = 0;
if(descCount > 0)
{
ConstraintPartitionArgs args;
args.mBodies = reinterpret_cast<PxU8*>(solverBodies);
args.mStride = sizeof(PxSolverBody);
args.mArticulationPtrs = artics;
args.mContactConstraintDescriptors = descBegin;
args.mNumArticulationPtrs = mThreadContext.getArticulations().size();
args.mNumBodies = mIslandContext.mCounts.bodies;
args.mNumContactConstraintDescriptors = descCount;
args.mOrderedContactConstraintDescriptors = mThreadContext.orderedContactConstraints;
args.mOverflowConstraintDescriptors = mThreadContext.tempConstraintDescArray;
args.mNumDifferentBodyConstraints = args.mNumSelfConstraints = args.mNumStaticConstraints = 0;
args.mConstraintsPerPartition = &mThreadContext.mConstraintsPerPartition;
args.mNumOverflowConstraints = 0;
//args.mBitField = &mThreadContext.mPartitionNormalizationBitmap; // PT: removed, unused
args.mEnhancedDeterminism = mEnhancedDeterminism;
args.mForceStaticConstraintsToSolver = mContext.getFrictionType() != PxFrictionType::ePATCH;
args.mMaxPartitions = PX_MAX_U32;
mThreadContext.mMaxPartitions = partitionContactConstraints(args);
mThreadContext.mNumDifferentBodyConstraints = args.mNumDifferentBodyConstraints;
mThreadContext.mNumSelfConstraints = args.mNumSelfConstraints;
mThreadContext.mNumStaticConstraints = args.mNumStaticConstraints;
}
else
{
PxMemZero(mThreadContext.mConstraintsPerPartition.begin(), sizeof(PxU32)*mThreadContext.mConstraintsPerPartition.capacity());
}
PX_ASSERT((mThreadContext.mNumDifferentBodyConstraints + mThreadContext.mNumSelfConstraints + mThreadContext.mNumStaticConstraints) == descCount);
}
}
virtual const char* getName() const { return "PxsDynamics.solverConstraintPartition"; }
DynamicsContext& mContext;
IslandContext& mIslandContext;
const SolverIslandObjects mObjects;
const PxU32 mSolverBodyOffset;
const bool mEnhancedDeterminism;
};
class PxsSolverSetupSolveTask : public Cm::Task
{
PxsSolverSetupSolveTask& operator=(const PxsSolverSetupSolveTask&);
public:
PxsSolverSetupSolveTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, IG::IslandSim& islandSim) :
Cm::Task (context.getContextId()),
mContext (context),
mIslandContext (islandContext),
mObjects (objects),
mSolverBodyOffset (solverBodyOffset),
mIslandSim (islandSim)
{}
virtual void runInternal()
{
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
PxSolverConstraintDesc* contactDescBegin = mThreadContext.orderedContactConstraints;
PxSolverConstraintDesc* contactDescPtr = mThreadContext.orderedContactConstraints;
PxSolverBody* solverBodies = mContext.mSolverBodyPool.begin() + mSolverBodyOffset;
PxSolverBodyData* solverBodyDatas = mContext.mSolverBodyDataPool.begin();
PxU32 frictionDescCount = mThreadContext.mNumDifferentBodyFrictionConstraints;
PxU32 j = 0, i = 0;
//On PS3, self-constraints will be bumped to the end of the constraint list
//and processed separately. On PC/360, they will be mixed in the array and
//classed as "different body" constraints regardless of the fact that they're self-constraints.
//PxU32 numBatches = mThreadContext.numDifferentBodyBatchHeaders;
// TODO: maybe replace with non-null joints from end of the array
PxU32 numBatches = 0;
PxU32 currIndex = 0;
for(PxU32 a = 0; a < mThreadContext.mConstraintsPerPartition.size(); ++a)
{
PxU32 endIndex = currIndex + mThreadContext.mConstraintsPerPartition[a];
PxU32 numBatchesInPartition = 0;
for(PxU32 b = currIndex; b < endIndex; ++b)
{
PxConstraintBatchHeader& _header = mThreadContext.contactConstraintBatchHeaders[b];
PxU16 stride = _header.stride, newStride = _header.stride;
PxU32 startIndex = j;
for(PxU16 c = 0; c < stride; ++c)
{
if(getConstraintLength(contactDescBegin[i]) == 0)
{
newStride--;
i++;
}
else
{
if(i!=j)
contactDescBegin[j] = contactDescBegin[i];
i++;
j++;
contactDescPtr++;
}
}
if(newStride != 0)
{
mThreadContext.contactConstraintBatchHeaders[numBatches].startIndex = startIndex;
mThreadContext.contactConstraintBatchHeaders[numBatches].stride = newStride;
PxU8 type = *contactDescBegin[startIndex].constraint;
if(type == DY_SC_TYPE_STATIC_CONTACT)
{
//Check if any block of constraints is classified as type static (single) contact constraint.
//If they are, iterate over all constraints grouped with it and switch to "dynamic" contact constraint
//type if there's a dynamic contact constraint in the group.
for(PxU32 c = 1; c < newStride; ++c)
{
if(*contactDescBegin[startIndex+c].constraint == DY_SC_TYPE_RB_CONTACT)
{
type = DY_SC_TYPE_RB_CONTACT;
}
}
}
mThreadContext.contactConstraintBatchHeaders[numBatches].constraintType = type;
numBatches++;
numBatchesInPartition++;
}
}
PxU32 numHeaders = numBatchesInPartition;
currIndex += mThreadContext.mConstraintsPerPartition[a];
mThreadContext.mConstraintsPerPartition[a] = numHeaders;
}
PxU32 contactDescCount = PxU32(contactDescPtr - contactDescBegin);
mThreadContext.mNumDifferentBodyConstraints = contactDescCount;
mThreadContext.numContactConstraintBatches = numBatches;
mThreadContext.mNumSelfConstraints = j - contactDescCount; //self constraint count
contactDescCount = j;
mThreadContext.mOrderedContactDescCount = j;
//Now do the friction constraints if we're not using the sticky model
if(mContext.getFrictionType() != PxFrictionType::ePATCH)
{
PxSolverConstraintDesc* frictionDescBegin = mThreadContext.frictionConstraintDescArray.begin();
PxSolverConstraintDesc* frictionDescPtr = frictionDescBegin;
PxArray<PxConstraintBatchHeader>& frictionHeaderArray = mThreadContext.frictionConstraintBatchHeaders;
frictionHeaderArray.forceSize_Unsafe(0);
frictionHeaderArray.reserve(mThreadContext.numContactConstraintBatches);
PxConstraintBatchHeader* headers = frictionHeaderArray.begin();
PxArray<PxU32>& constraintsPerPartition = mThreadContext.mConstraintsPerPartition;
PxArray<PxU32>& frictionConstraintsPerPartition = mThreadContext.mFrictionConstraintsPerPartition;
frictionConstraintsPerPartition.forceSize_Unsafe(0);
frictionConstraintsPerPartition.reserve(constraintsPerPartition.capacity());
PxU32 fricI = 0;
PxU32 startIndex = 0;
PxU32 fricHeaders = 0;
for(PxU32 k = 0; k < constraintsPerPartition.size(); ++k)
{
PxU32 numBatchesInK = constraintsPerPartition[k];
PxU32 endIndex = startIndex + numBatchesInK;
PxU32 startFricH = fricHeaders;
for(PxU32 a = startIndex; a < endIndex; ++a)
{
PxConstraintBatchHeader& _header = mThreadContext.contactConstraintBatchHeaders[a];
PxU16 stride = _header.stride;
if(_header.constraintType == DY_SC_TYPE_RB_CONTACT || _header.constraintType == DY_SC_TYPE_EXT_CONTACT ||
_header.constraintType == DY_SC_TYPE_STATIC_CONTACT)
{
PxU8 type = 0;
//Extract friction from this constraint
for(PxU16 b = 0; b < stride; ++b)
{
//create the headers...
PxSolverConstraintDesc& desc = contactDescBegin[_header.startIndex + b];
PX_ASSERT(desc.constraint);
SolverContactCoulombHeader* header = reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint);
PxU32 frictionOffset = header->frictionOffset;
PxU8* PX_RESTRICT constraint = reinterpret_cast<PxU8*>(header) + frictionOffset;
const PxU32 origLength = getConstraintLength(desc);
const PxU32 length = (origLength - frictionOffset);
setConstraintLength(*frictionDescPtr, length);
frictionDescPtr->constraint = constraint;
frictionDescPtr->bodyA = desc.bodyA;
frictionDescPtr->bodyB = desc.bodyB;
frictionDescPtr->bodyADataIndex = desc.bodyADataIndex;
frictionDescPtr->bodyBDataIndex = desc.bodyBDataIndex;
frictionDescPtr->linkIndexA = desc.linkIndexA;
frictionDescPtr->linkIndexB = desc.linkIndexB;
frictionDescPtr->writeBack = NULL;
type = *constraint;
frictionDescPtr++;
}
headers->startIndex = fricI;
headers->stride = stride;
headers->constraintType = type;
headers++;
fricHeaders++;
fricI += stride;
}
else if(_header.constraintType == DY_SC_TYPE_BLOCK_RB_CONTACT || _header.constraintType == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT)
{
//KS - TODO - Extract block of 4 contacts from this constraint. This isn't implemented yet for coulomb friction model
PX_ASSERT(contactDescBegin[_header.startIndex].constraint);
SolverContactCoulombHeader4* head = reinterpret_cast<SolverContactCoulombHeader4*>(contactDescBegin[_header.startIndex].constraint);
PxU32 frictionOffset = head->frictionOffset;
PxU8* PX_RESTRICT constraint = reinterpret_cast<PxU8*>(head) + frictionOffset;
const PxU32 origLength = getConstraintLength(contactDescBegin[_header.startIndex]);
const PxU32 length = (origLength - frictionOffset);
PxU8 type = *constraint;
PX_ASSERT(type == DY_SC_TYPE_BLOCK_FRICTION || type == DY_SC_TYPE_BLOCK_STATIC_FRICTION);
for(PxU32 b = 0; b < 4; ++b)
{
PxSolverConstraintDesc& desc = contactDescBegin[_header.startIndex+b];
setConstraintLength(*frictionDescPtr, length);
frictionDescPtr->constraint = constraint;
frictionDescPtr->bodyA = desc.bodyA;
frictionDescPtr->bodyB = desc.bodyB;
frictionDescPtr->bodyADataIndex = desc.bodyADataIndex;
frictionDescPtr->bodyBDataIndex = desc.bodyBDataIndex;
frictionDescPtr->linkIndexA = desc.linkIndexA;
frictionDescPtr->linkIndexB = desc.linkIndexB;
frictionDescPtr->writeBack = NULL;
frictionDescPtr++;
}
headers->startIndex = fricI;
headers->stride = stride;
headers->constraintType = type;
headers++;
fricHeaders++;
fricI += stride;
}
}
startIndex += numBatchesInK;
if(startFricH < fricHeaders)
{
frictionConstraintsPerPartition.pushBack(fricHeaders - startFricH);
}
}
frictionDescCount = PxU32(frictionDescPtr - frictionDescBegin);
mThreadContext.mNumDifferentBodyFrictionConstraints = frictionDescCount;
frictionHeaderArray.forceSize_Unsafe(PxU32(headers - frictionHeaderArray.begin()));
mThreadContext.mNumSelfFrictionConstraints = fricI - frictionDescCount; //self constraint count
mThreadContext.mNumDifferentBodyFrictionConstraints = frictionDescCount;
frictionDescCount = fricI;
mThreadContext.mOrderedFrictionDescCount = frictionDescCount;
}
{
{
PX_PROFILE_ZONE("Dynamics.solver", mContext.getContextId());
PxSolverConstraintDesc* contactDescs = mThreadContext.orderedContactConstraints;
PxSolverConstraintDesc* frictionDescs = mThreadContext.frictionConstraintDescArray.begin();
PxI32* thresholdPairsOut = &mContext.mThresholdStreamOut;
SolverIslandParams& params = *reinterpret_cast<SolverIslandParams*>(mContext.getTaskPool().allocate(sizeof(SolverIslandParams)));
params.positionIterations = mThreadContext.mMaxSolverPositionIterations;
params.velocityIterations = mThreadContext.mMaxSolverVelocityIterations;
params.bodyListStart = solverBodies;
params.bodyDataList = solverBodyDatas;
params.solverBodyOffset = mSolverBodyOffset;
params.bodyListSize = mIslandContext.mCounts.bodies;
params.articulationListStart = mThreadContext.getArticulations().begin();
params.articulationListSize = mThreadContext.getArticulations().size();
params.constraintList = contactDescs;
params.constraintIndex = 0;
params.constraintIndexCompleted = 0;
params.bodyListIndex = 0;
params.bodyListIndexCompleted = 0;
params.articSolveIndex = 0;
params.articSolveIndexCompleted = 0;
params.bodyIntegrationListIndex = 0;
params.thresholdStream = mContext.getThresholdStream().begin();
params.thresholdStreamLength = mContext.getThresholdStream().size();
params.outThresholdPairs = thresholdPairsOut;
params.motionVelocityArray = mThreadContext.motionVelocityArray;
params.bodyArray = mThreadContext.mBodyCoreArray;
params.numObjectsIntegrated = 0;
params.constraintBatchHeaders = mThreadContext.contactConstraintBatchHeaders;
params.numConstraintHeaders = mThreadContext.numContactConstraintBatches;
params.headersPerPartition = mThreadContext.mConstraintsPerPartition.begin();
params.nbPartitions = mThreadContext.mConstraintsPerPartition.size();
params.rigidBodies = const_cast<PxsRigidBody**>(mObjects.bodies);
params.frictionHeadersPerPartition = mThreadContext.mFrictionConstraintsPerPartition.begin();
params.nbFrictionPartitions = mThreadContext.mFrictionConstraintsPerPartition.size();
params.frictionConstraintBatches = mThreadContext.frictionConstraintBatchHeaders.begin();
params.numFrictionConstraintHeaders = mThreadContext.frictionConstraintBatchHeaders.size();
params.frictionConstraintIndex = 0;
params.frictionConstraintList = frictionDescs;
params.mMaxArticulationLinks = mThreadContext.mMaxArticulationLinks;
params.dt = mContext.mDt;
params.invDt = mContext.mInvDt;
const PxU32 unrollSize = 8;
const PxU32 denom = PxMax(1u, (mThreadContext.mMaxPartitions*unrollSize));
const PxU32 MaxTasks = getTaskManager()->getCpuDispatcher()->getWorkerCount();
// PT: small improvement: if there's no contacts, use the number of bodies instead.
// That way the integration work still benefits from multiple tasks.
const PxU32 numWorkItems = mThreadContext.numContactConstraintBatches ? mThreadContext.numContactConstraintBatches : mIslandContext.mCounts.bodies;
const PxU32 idealThreads = (numWorkItems+denom-1)/denom;
const PxU32 numTasks = PxMax(1u, PxMin(idealThreads, MaxTasks));
if(numTasks > 1)
{
const PxU32 idealBatchSize = PxMax(unrollSize, idealThreads*unrollSize/(numTasks*2));
params.batchSize = idealBatchSize; //assigning ideal batch size for the solver to grab work at. Only needed by the multi-threaded island solver.
for(PxU32 a = 1; a < numTasks; ++a)
{
void* tsk = mContext.getTaskPool().allocate(sizeof(PxsParallelSolverTask));
PxsParallelSolverTask* pTask = PX_PLACEMENT_NEW(tsk, PxsParallelSolverTask)(
params, mContext, mIslandSim);
//Force to complete before merge task!
pTask->setContinuation(mCont);
pTask->removeReference();
}
//Avoid kicking off one parallel task when we can do the work inline in this function
{
PX_PROFILE_ZONE("Dynamics.parallelSolve", mContext.getContextId());
solveParallel(mContext, params, mIslandSim);
}
const PxI32 numBodiesPlusArtics = PxI32( mIslandContext.mCounts.bodies + mIslandContext.mCounts.articulations );
PxI32* numObjectsIntegrated = ¶ms.numObjectsIntegrated;
WAIT_FOR_PROGRESS_NO_TIMER(numObjectsIntegrated, numBodiesPlusArtics);
}
else
{
mThreadContext.mZVector.forceSize_Unsafe(0);
mThreadContext.mZVector.reserve(mThreadContext.mMaxArticulationLinks);
mThreadContext.mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);
mThreadContext.mDeltaV.forceSize_Unsafe(0);
mThreadContext.mDeltaV.reserve(mThreadContext.mMaxArticulationLinks);
mThreadContext.mDeltaV.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);
params.Z = mThreadContext.mZVector.begin();
params.deltaV = mThreadContext.mDeltaV.begin();
//Only one task - a small island so do a sequential solve (avoid the atomic overheads)
mContext.mSolverCore[mContext.getFrictionType()]->solveV_Blocks(params);
const PxU32 bodyCountMin1 = mIslandContext.mCounts.bodies - 1u;
PxSolverBodyData* solverBodyData2 = solverBodyDatas + mSolverBodyOffset + 1;
for(PxU32 k=0; k < mIslandContext.mCounts.bodies; k++)
{
const PxU32 prefetchAddress = PxMin(k+4, bodyCountMin1);
PxPrefetchLine(mThreadContext.mBodyCoreArray[prefetchAddress]);
PxPrefetchLine(&mThreadContext.motionVelocityArray[k], 128);
PxPrefetchLine(&mThreadContext.mBodyCoreArray[prefetchAddress], 128);
PxPrefetchLine(&mObjects.bodies[prefetchAddress]);
PxSolverBodyData& solverBodyData = solverBodyData2[k];
PxsRigidBody& rBody = *mObjects.bodies[k];
PxsBodyCore& core = rBody.getCore();
integrateCore(mThreadContext.motionVelocityArray[k].linear, mThreadContext.motionVelocityArray[k].angular,
solverBodies[k], solverBodyData, mContext.mDt, core.lockFlags);
rBody.mLastTransform = core.body2World;
core.body2World = solverBodyData.body2World;
core.linearVelocity = solverBodyData.linearVelocity;
core.angularVelocity = solverBodyData.angularVelocity;
const bool hasStaticTouch = mIslandSim.getIslandStaticTouchCount(PxNodeIndex(solverBodyData.nodeIndex)) != 0;
sleepCheck(mObjects.bodies[k], mContext.mDt, mContext.mEnableStabilization, mThreadContext.motionVelocityArray[k], hasStaticTouch);
}
for(PxU32 cnt=0;cnt<mIslandContext.mCounts.articulations;cnt++)
{
ArticulationSolverDesc &d = mThreadContext.getArticulations()[cnt];
//PX_PROFILE_ZONE("Articulations.integrate", mContext.getContextId());
ArticulationPImpl::updateBodies(d, mThreadContext.mDeltaV.begin(), mContext.getDt());
}
}
}
}
}
virtual const char* getName() const { return "PxsDynamics.solverSetupSolve"; }
DynamicsContext& mContext;
IslandContext& mIslandContext;
const SolverIslandObjects mObjects;
const PxU32 mSolverBodyOffset;
IG::IslandSim& mIslandSim;
};
class PxsSolverEndTask : public Cm::Task
{
PxsSolverEndTask& operator=(const PxsSolverEndTask&);
public:
PxsSolverEndTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, PxsContactManagerOutputIterator& cmOutputs) :
Cm::Task (context.getContextId()),
mContext (context),
mIslandContext (islandContext),
mObjects (objects),
mSolverBodyOffset (solverBodyOffset),
mOutputs (cmOutputs)
{}
virtual void runInternal()
{
PX_PROFILE_ZONE("Dynamics.endTask", getContextId());
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
#if PX_ENABLE_SIM_STATS
mThreadContext.getSimStats().numAxisSolverConstraints += mThreadContext.mAxisConstraintCount;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//Patch up the contact managers (TODO - fix up force writeback)
PxU32 numCompoundConstraints = mThreadContext.compoundConstraints.size();
for(PxU32 i = 0; i < numCompoundConstraints; ++i)
{
CompoundContactManager& manager = mThreadContext.compoundConstraints[i];
PxsContactManagerOutput* cmOutput = manager.cmOutput;
PxReal* contactForces = reinterpret_cast<PxReal*>(cmOutput->contactForces);
PxU32 contactCount = cmOutput->nbContacts;
cmOutput->contactPatches = manager.originalContactPatches;
cmOutput->contactPoints = manager.originalContactPoints;
cmOutput->nbContacts = manager.originalContactCount;
cmOutput->nbPatches = manager.originalPatchCount;
cmOutput->statusFlag = manager.originalStatusFlags;
cmOutput->contactForces = manager.originalForceBuffer;
for(PxU32 a = 1; a < manager.mStride; ++a)
{
PxsContactManager* pManager = mThreadContext.orderedContactList[manager.mStartIndex + a]->contactManager;
pManager->getWorkUnit().frictionDataPtr = manager.unit->frictionDataPtr;
pManager->getWorkUnit().frictionPatchCount = manager.unit->frictionPatchCount;
//pManager->getWorkUnit().prevFrictionPatchCount = manager.unit->prevFrictionPatchCount;
}
//This is a stride-based contact force writer. The assumption is that we may have skipped certain unimportant contacts reported by the
//discrete narrow phase
if(contactForces)
{
PxU32 currentContactIndex = 0;
PxU32 currentManagerIndex = manager.mStartIndex;
PxU32 currentManagerContactIndex = 0;
for(PxU32 a = 0; a < contactCount; ++a)
{
PxU32 index = manager.forceBufferList[a];
PxsContactManager* pManager = mThreadContext.orderedContactList[currentManagerIndex]->contactManager;
PxsContactManagerOutput* output = &mOutputs.getContactManager(pManager->getWorkUnit().mNpIndex);
while(currentContactIndex < index || output->nbContacts == 0)
{
//Step forwards...first in this manager...
PxU32 numToStep = PxMin(index - currentContactIndex, PxU32(output->nbContacts) - currentManagerContactIndex);
currentContactIndex += numToStep;
currentManagerContactIndex += numToStep;
if(currentManagerContactIndex == output->nbContacts)
{
currentManagerIndex++;
currentManagerContactIndex = 0;
pManager = mThreadContext.orderedContactList[currentManagerIndex]->contactManager;
output = &mOutputs.getContactManager(pManager->getWorkUnit().mNpIndex);
}
}
if(output->nbContacts > 0 && output->contactForces)
output->contactForces[currentManagerContactIndex] = contactForces[a];
}
}
}
mThreadContext.compoundConstraints.forceSize_Unsafe(0);
mThreadContext.mConstraintBlockManager.reset();
mContext.putThreadContext(&mThreadContext);
}
virtual const char* getName() const
{
return "PxsDynamics.solverEnd";
}
DynamicsContext& mContext;
IslandContext& mIslandContext;
const SolverIslandObjects mObjects;
const PxU32 mSolverBodyOffset;
PxsContactManagerOutputIterator& mOutputs;
};
class PxsSolverCreateFinalizeConstraintsTask : public Cm::Task
{
PxsSolverCreateFinalizeConstraintsTask& operator=(const PxsSolverCreateFinalizeConstraintsTask&);
public:
PxsSolverCreateFinalizeConstraintsTask(DynamicsContext& context, IslandContext& islandContext, PxU32 solverDataOffset, PxsContactManagerOutputIterator& outputs, bool enhancedDeterminism) :
Cm::Task (context.getContextId()),
mContext (context),
mIslandContext (islandContext),
mSolverDataOffset (solverDataOffset),
mOutputs (outputs),
mEnhancedDeterminism (enhancedDeterminism)
{
}
virtual void runInternal();
virtual const char* getName() const { return "PxsDynamics.solverCreateFinalizeConstraints"; }
DynamicsContext& mContext;
IslandContext& mIslandContext;
const PxU32 mSolverDataOffset;
PxsContactManagerOutputIterator& mOutputs;
const bool mEnhancedDeterminism;
};
// helper function to join two tasks together and ensure ref counts are correct
static void chainTasks(PxLightCpuTask* first, PxLightCpuTask* next)
{
first->setContinuation(next);
next->removeReference();
}
static void createSolverTaskChain( DynamicsContext& dynamicContext,
const SolverIslandObjects& objects,
const PxsIslandIndices& counts,
PxU32 solverBodyOffset,
IG::SimpleIslandManager& islandManager,
PxU32* bodyRemapTable, PxsMaterialManager* materialManager, PxBaseTask* continuation,
PxsContactManagerOutputIterator& iterator, bool useEnhancedDeterminism)
{
Cm::FlushPool& taskPool = dynamicContext.getTaskPool();
taskPool.lock();
IslandContext* islandContext = reinterpret_cast<IslandContext*>(taskPool.allocate(sizeof(IslandContext)));
islandContext->mThreadContext = NULL;
islandContext->mCounts = counts;
// create lead task
PxsSolverStartTask* startTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverStartTask)), PxsSolverStartTask)(dynamicContext, *islandContext, objects, solverBodyOffset, dynamicContext.getKinematicCount(),
islandManager, bodyRemapTable, materialManager, iterator, useEnhancedDeterminism);
PxsSolverEndTask* endTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverEndTask)), PxsSolverEndTask)(dynamicContext, *islandContext, objects, solverBodyOffset, iterator);
PxsSolverCreateFinalizeConstraintsTask* createFinalizeConstraintsTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverCreateFinalizeConstraintsTask)), PxsSolverCreateFinalizeConstraintsTask)(dynamicContext, *islandContext, solverBodyOffset, iterator, useEnhancedDeterminism);
PxsSolverSetupSolveTask* setupSolveTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverSetupSolveTask)), PxsSolverSetupSolveTask)(dynamicContext, *islandContext, objects, solverBodyOffset, islandManager.getAccurateIslandSim());
PxsSolverConstraintPartitionTask* partitionConstraintsTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverConstraintPartitionTask)), PxsSolverConstraintPartitionTask)(dynamicContext, *islandContext, objects, solverBodyOffset, useEnhancedDeterminism);
taskPool.unlock();
endTask->setContinuation(continuation);
// set up task chain in reverse order
chainTasks(setupSolveTask, endTask);
chainTasks(createFinalizeConstraintsTask, setupSolveTask);
chainTasks(partitionConstraintsTask, createFinalizeConstraintsTask);
chainTasks(startTask, partitionConstraintsTask);
startTask->removeReference();
}
namespace
{
class UpdateContinuationTask : public Cm::Task
{
DynamicsContext& mContext;
IG::SimpleIslandManager& mSimpleIslandManager;
PxBaseTask* mLostTouchTask;
PxU32 mMaxArticulationLinks;
PX_NOCOPY(UpdateContinuationTask)
public:
UpdateContinuationTask(DynamicsContext& context,
IG::SimpleIslandManager& simpleIslandManager,
PxBaseTask* lostTouchTask, PxU64 contextID, PxU32 maxLinks) :
Cm::Task(contextID), mContext(context), mSimpleIslandManager(simpleIslandManager),
mLostTouchTask(lostTouchTask), mMaxArticulationLinks(maxLinks)
{
}
virtual const char* getName() const { return "UpdateContinuationTask"; }
virtual void runInternal()
{
mContext.updatePostKinematic(mSimpleIslandManager, mCont, mLostTouchTask, mMaxArticulationLinks);
//Allow lost touch task to run once all tasks have be scheduled
mLostTouchTask->removeReference();
}
};
class KinematicCopyTask : public Cm::Task
{
const PxNodeIndex* const mKinematicIndices;
const PxU32 mNbKinematics;
const IG::IslandSim& mIslandSim;
PxSolverBodyData* mBodyData;
PX_NOCOPY(KinematicCopyTask)
public:
static const PxU32 NbKinematicsPerTask = 1024;
KinematicCopyTask(const PxNodeIndex* const kinematicIndices,
PxU32 nbKinematics, const IG::IslandSim& islandSim,
PxSolverBodyData* datas, PxU64 contextID) : Cm::Task(contextID),
mKinematicIndices(kinematicIndices), mNbKinematics(nbKinematics),
mIslandSim(islandSim), mBodyData(datas)
{
}
virtual const char* getName() const { return "KinematicCopyTask"; }
virtual void runInternal()
{
for (PxU32 i = 0; i<mNbKinematics; i++)
{
PxsRigidBody* rigidBody = mIslandSim.getRigidBody(mKinematicIndices[i]);
const PxsBodyCore& core = rigidBody->getCore();
copyToSolverBodyData(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias,
core.maxContactImpulse, mKinematicIndices[i].index(), core.contactReportThreshold, mBodyData[i + 1], core.lockFlags, 0.f,
core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES);
rigidBody->saveLastCCDTransform();
}
}
};
}
void DynamicsContext::update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask,
PxvNphaseImplementationContext* nphase, PxU32 /*maxPatches*/, PxU32 maxArticulationLinks,
PxReal dt, const PxVec3& gravity, PxBitMapPinned& /*changedHandleMap*/)
{
PX_PROFILE_ZONE("Dynamics.solverQueueTasks", mContextID);
mOutputIterator = nphase->getContactManagerOutputs();
mDt = dt;
mInvDt = dt == 0.0f ? 0.0f : 1.0f / dt;
mGravity = gravity;
const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim();
const PxU32 islandCount = islandSim.getNbActiveIslands();
const PxU32 activatedContactCount = islandSim.getNbActivatedEdges(IG::Edge::eCONTACT_MANAGER);
const IG::EdgeIndex* const activatingEdges = islandSim.getActivatedEdges(IG::Edge::eCONTACT_MANAGER);
for (PxU32 a = 0; a < activatedContactCount; ++a)
{
PxsContactManager* cm = simpleIslandManager.getContactManager(activatingEdges[a]);
if (cm)
cm->getWorkUnit().frictionPatchCount = 0; //KS - zero the friction patch count on any activating edges
}
#if PX_ENABLE_SIM_STATS
if (islandCount > 0)
{
mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics();
mSimStats.mNbActiveDynamicBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE);
mSimStats.mNbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT);
}
else
{
mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics();
mSimStats.mNbActiveDynamicBodies = 0;
mSimStats.mNbActiveConstraints = 0;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
mThresholdStreamOut = 0;
resetThreadContexts();
//If there is no work to do then we can do nothing at all.
if(!islandCount)
return;
//Block to make sure it doesn't run before stage2 of update!
lostTouchTask->addReference();
UpdateContinuationTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(UpdateContinuationTask)), UpdateContinuationTask)
(*this, simpleIslandManager, lostTouchTask, mContextID, maxArticulationLinks);
task->setContinuation(continuation);
//KS - test that world solver body's velocities are finite and 0, then set it to 0.
//Technically, the velocity should always be 0 but can be stomped if a NAN creeps into the simulation.
PX_ASSERT(mWorldSolverBody.linearVelocity == PxVec3(0.0f));
PX_ASSERT(mWorldSolverBody.angularState == PxVec3(0.0f));
PX_ASSERT(mWorldSolverBody.linearVelocity.isFinite());
PX_ASSERT(mWorldSolverBody.angularState.isFinite());
mWorldSolverBody.linearVelocity = mWorldSolverBody.angularState = PxVec3(0.f);
const PxU32 kinematicCount = islandSim.getNbActiveKinematics();
const PxNodeIndex* const kinematicIndices = islandSim.getActiveKinematics();
mKinematicCount = kinematicCount;
const PxU32 bodyCount = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE);
const PxU32 numArtics = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE);
{
if (kinematicCount + bodyCount > mSolverBodyPool.capacity())
{
mSolverBodyPool.reserve((kinematicCount + bodyCount + 31) & ~31); // pad out to 32 * 128 = 4k to prevent alloc churn
mSolverBodyDataPool.reserve((kinematicCount + bodyCount + 31 + 1) & ~31); // pad out to 32 * 128 = 4k to prevent alloc churn
mSolverBodyRemapTable.reserve((kinematicCount + bodyCount + 31 + 1) & ~31);
}
{
PxSolverBody emptySolverBody;
PxMemZero(&emptySolverBody, sizeof(PxSolverBody));
mSolverBodyPool.resize(kinematicCount + bodyCount, emptySolverBody);
PxSolverBodyData emptySolverBodyData;
PxMemZero(&emptySolverBodyData, sizeof(PxSolverBodyData));
mSolverBodyDataPool.resize(kinematicCount + bodyCount + 1, emptySolverBodyData);
mSolverBodyRemapTable.resize(bodyCount);
}
// integrate and copy all the kinematics - overkill, since not all kinematics
// need solver bodies
mSolverBodyDataPool[0] = mWorldSolverBodyData;
if(kinematicCount)
{
PX_PROFILE_ZONE("Dynamics.updateKinematics", mContextID);
PxMemZero(mSolverBodyPool.begin(), kinematicCount * sizeof(PxSolverBody));
for (PxU32 i = 0; i < kinematicCount; i+= KinematicCopyTask::NbKinematicsPerTask)
{
const PxU32 nbToProcess = PxMin(KinematicCopyTask::NbKinematicsPerTask, kinematicCount - i);
KinematicCopyTask* copyTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(KinematicCopyTask)), KinematicCopyTask)
(&kinematicIndices[i], nbToProcess, islandSim, &mSolverBodyDataPool[i], mContextID);
copyTask->setContinuation(task);
copyTask->removeReference();
}
}
}
//Resize arrays of solver constraints...
const PxU32 numArticulationConstraints = numArtics* maxArticulationLinks; //Just allocate enough memory to fit worst-case maximum size articulations...
const PxU32 nbActiveContactManagers = islandSim.getNbActiveEdges(IG::Edge::eCONTACT_MANAGER);
const PxU32 nbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT);
const PxU32 totalConstraintCount = nbActiveConstraints + nbActiveContactManagers + numArticulationConstraints;
mSolverConstraintDescPool.forceSize_Unsafe(0);
mSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63));
mSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount);
mOrderedSolverConstraintDescPool.forceSize_Unsafe(0);
mOrderedSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63));
mOrderedSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount);
mTempSolverConstraintDescPool.forceSize_Unsafe(0);
mTempSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63));
mTempSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount);
mContactConstraintBatchHeaders.forceSize_Unsafe(0);
mContactConstraintBatchHeaders.reserve((totalConstraintCount + 63) & (~63));
mContactConstraintBatchHeaders.forceSize_Unsafe(totalConstraintCount);
mContactList.forceSize_Unsafe(0);
mContactList.reserve((nbActiveContactManagers + 63u) & (~63u));
mContactList.forceSize_Unsafe(nbActiveContactManagers);
mMotionVelocityArray.forceSize_Unsafe(0);
mMotionVelocityArray.reserve((bodyCount + 63u) & (~63u));
mMotionVelocityArray.forceSize_Unsafe(bodyCount);
mBodyCoreArray.forceSize_Unsafe(0);
mBodyCoreArray.reserve((bodyCount + 63u) & (~63u));
mBodyCoreArray.forceSize_Unsafe(bodyCount);
mRigidBodyArray.forceSize_Unsafe(0);
mRigidBodyArray.reserve((bodyCount + 63u) & (~63u));
mRigidBodyArray.forceSize_Unsafe(bodyCount);
mArticulationArray.forceSize_Unsafe(0);
mArticulationArray.reserve((numArtics + 63u) & (~63u));
mArticulationArray.forceSize_Unsafe(numArtics);
mNodeIndexArray.forceSize_Unsafe(0);
mNodeIndexArray.reserve((bodyCount + 63u) & (~63u));
mNodeIndexArray.forceSize_Unsafe(bodyCount);
ThresholdStream& stream = getThresholdStream();
stream.forceSize_Unsafe(0);
stream.reserve(PxNextPowerOfTwo(nbActiveContactManagers != 0 ? nbActiveContactManagers - 1 : nbActiveContactManagers));
//flip exceeded force threshold buffer
mCurrentIndex = 1 - mCurrentIndex;
task->removeReference();
}
void DynamicsContext::updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* /*continuation*/, PxBaseTask* lostTouchTask, PxU32 maxLinks)
{
const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim();
const PxU32 islandCount = islandSim.getNbActiveIslands();
PxU32 constraintIndex = 0;
PxU32 solverBatchMax = mSolverBatchSize;
PxU32 articulationBatchMax = mSolverArticBatchSize;
PxU32 minimumConstraintCount = 1;
//create force threshold tasks to produce force change events
PxsForceThresholdTask* forceThresholdTask = PX_PLACEMENT_NEW(getTaskPool().allocate(sizeof(PxsForceThresholdTask)), PxsForceThresholdTask)(*this);
forceThresholdTask->setContinuation(lostTouchTask);
const IG::IslandId*const islandIds = islandSim.getActiveIslands();
PxU32 currentIsland = 0;
PxU32 currentBodyIndex = 0;
PxU32 currentArticulation = 0;
PxU32 currentContact = 0;
//while(start<sentinel)
while(currentIsland < islandCount)
{
SolverIslandObjects objectStarts;
objectStarts.articulations = mArticulationArray.begin()+ currentArticulation;
objectStarts.bodies = mRigidBodyArray.begin() + currentBodyIndex;
objectStarts.contactManagers = mContactList.begin() + currentContact;
objectStarts.constraintDescs = mSolverConstraintDescPool.begin() + constraintIndex;
objectStarts.orderedConstraintDescs = mOrderedSolverConstraintDescPool.begin() + constraintIndex;
objectStarts.tempConstraintDescs = mTempSolverConstraintDescPool.begin() + constraintIndex;
objectStarts.constraintBatchHeaders = mContactConstraintBatchHeaders.begin() + constraintIndex;
objectStarts.motionVelocities = mMotionVelocityArray.begin() + currentBodyIndex;
objectStarts.bodyCoreArray = mBodyCoreArray.begin() + currentBodyIndex;
objectStarts.islandIds = islandIds + currentIsland;
objectStarts.bodyRemapTable = mSolverBodyRemapTable.begin();
objectStarts.nodeIndexArray = mNodeIndexArray.begin() + currentBodyIndex;
PxU32 startIsland = currentIsland;
PxU32 constraintCount = 0;
PxU32 nbArticulations = 0;
PxU32 nbBodies = 0;
PxU32 nbConstraints = 0;
PxU32 nbContactManagers =0;
// islandSim.checkInternalConsistency();
//KS - logic is a bit funky here. We will keep rolling the island together provided currentIsland < islandCount AND either we haven't exceeded the max number of bodies or we have
//zero constraints AND we haven't exceeded articulation batch counts (it's still currently beneficial to keep articulations in separate islands but this is only temporary).
while((currentIsland < islandCount && (nbBodies < solverBatchMax || constraintCount < minimumConstraintCount)) &&
nbArticulations < articulationBatchMax)
{
const IG::Island& island = islandSim.getIsland(islandIds[currentIsland]);
nbBodies += island.mNodeCount[IG::Node::eRIGID_BODY_TYPE];
nbArticulations += island.mNodeCount[IG::Node::eARTICULATION_TYPE];
nbConstraints += island.mEdgeCount[IG::Edge::eCONSTRAINT];
nbContactManagers += island.mEdgeCount[IG::Edge::eCONTACT_MANAGER];
constraintCount = nbConstraints + nbContactManagers;
currentIsland++;
}
objectStarts.numIslands = currentIsland - startIsland;
constraintIndex += nbArticulations* maxLinks;
PxsIslandIndices counts;
counts.articulations = nbArticulations;
counts.bodies = nbBodies;
counts.constraints = nbConstraints;
counts.contactManagers = nbContactManagers;
if(counts.articulations + counts.bodies > 0)
{
createSolverTaskChain(*this, objectStarts, counts,
mKinematicCount + currentBodyIndex, simpleIslandManager, mSolverBodyRemapTable.begin(), mMaterialManager,
forceThresholdTask, mOutputIterator, mUseEnhancedDeterminism);
}
currentBodyIndex += nbBodies;
currentArticulation += nbArticulations;
currentContact += nbContactManagers;
constraintIndex += constraintCount;
}
//kick off forceThresholdTask
forceThresholdTask->removeReference();
}
void DynamicsContext::mergeResults()
{
PX_PROFILE_ZONE("Dynamics.solverMergeResults", mContextID);
//OK. Sum up sim stats here...
#if PX_ENABLE_SIM_STATS
PxcThreadCoherentCacheIterator<ThreadContext, PxcNpMemBlockPool> threadContextIt(mThreadContextPool);
ThreadContext* threadContext = threadContextIt.getNext();
while(threadContext != NULL)
{
ThreadContext::ThreadSimStats& threadStats = threadContext->getSimStats();
addThreadStats(threadStats);
threadStats.clear();
threadContext = threadContextIt.getNext();
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
static void preIntegrationParallel(
PxF32 dt,
PxsBodyCore*const* bodyArray, // INOUT: core body attributes
PxsRigidBody*const* originalBodyArray, // IN: original bodies (LEGACY - DON'T deref the ptrs!!)
PxU32 const* nodeIndexArray, // IN: island node index
PxU32 bodyCount, // IN: body count
PxSolverBodyData* solverBodyDataPool, // IN: solver body data pool (space preallocated)
volatile PxU32* maxSolverPositionIterations,
volatile PxU32* maxSolverVelocityIterations,
const PxVec3& gravity)
{
PxU32 localMaxPosIter = 0;
PxU32 localMaxVelIter = 0;
for(PxU32 a = 1; a < bodyCount; ++a)
{
PxU32 i = a-1;
PxPrefetchLine(bodyArray[a]);
PxPrefetchLine(bodyArray[a],128);
PxPrefetchLine(&solverBodyDataPool[a]);
PxPrefetchLine(&solverBodyDataPool[a],128);
PxsBodyCore& core = *bodyArray[i];
const PxsRigidBody& rBody = *originalBodyArray[i];
const PxU16 iterWord = core.solverIterationCounts;
localMaxPosIter = PxMax<PxU32>(PxU32(iterWord & 0xff), localMaxPosIter);
localMaxVelIter = PxMax<PxU32>(PxU32(iterWord >> 8), localMaxVelIter);
//const Cm::SpatialVector& accel = originalBodyArray[i]->getAccelerationV();
bodyCoreComputeUnconstrainedVelocity(gravity, dt, core.linearDamping, core.angularDamping, rBody.accelScale, core.maxLinearVelocitySq, core.maxAngularVelocitySq,
core.linearVelocity, core.angularVelocity, core.disableGravity!=0);
copyToSolverBodyData(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, nodeIndexArray[i],
core.contactReportThreshold, solverBodyDataPool[i + 1], core.lockFlags, dt, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES);
}
const PxU32 i = bodyCount - 1;
PxsBodyCore& core = *bodyArray[i];
const PxsRigidBody& rBody = *originalBodyArray[i];
PxU16 iterWord = core.solverIterationCounts;
localMaxPosIter = PxMax<PxU32>(PxU32(iterWord & 0xff), localMaxPosIter);
localMaxVelIter = PxMax<PxU32>(PxU32(iterWord >> 8), localMaxVelIter);
bodyCoreComputeUnconstrainedVelocity(gravity, dt, core.linearDamping, core.angularDamping, rBody.accelScale, core.maxLinearVelocitySq, core.maxAngularVelocitySq,
core.linearVelocity, core.angularVelocity, core.disableGravity!=0);
copyToSolverBodyData(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, nodeIndexArray[i],
core.contactReportThreshold, solverBodyDataPool[i + 1], core.lockFlags, dt, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES);
physx::PxAtomicMax(reinterpret_cast<volatile PxI32*>(maxSolverPositionIterations), PxI32(localMaxPosIter));
physx::PxAtomicMax(reinterpret_cast<volatile PxI32*>(maxSolverVelocityIterations), PxI32(localMaxVelIter));
}
void PxsPreIntegrateTask::runInternal()
{
PX_PROFILE_ZONE("PreIntegration", mContext.getContextId());
preIntegrationParallel(mDt, mBodyArray + mStartIndex, mOriginalBodyArray + mStartIndex, mNodeIndexArray + mStartIndex, mNumToIntegrate,
mSolverBodyDataPool + mStartIndex, mMaxSolverPositionIterations, mMaxSolverVelocityIterations, mGravity);
}
void DynamicsContext::preIntegrationParallel(
PxF32 dt,
PxsBodyCore*const* bodyArray, // INOUT: core body attributes
PxsRigidBody*const* originalBodyArray, // IN: original bodies (LEGACY - DON'T deref the ptrs!!)
PxU32 const* nodeIndexArray, // IN: island node index
PxU32 bodyCount, // IN: body count
PxSolverBody* solverBodyPool, // IN: solver body pool (space preallocated)
PxSolverBodyData* solverBodyDataPool, // IN: solver body data pool (space preallocated)
Cm::SpatialVector* /*motionVelocityArray*/, // OUT: motion velocities
PxU32& maxSolverPositionIterations,
PxU32& maxSolverVelocityIterations,
PxBaseTask& task
)
{
//TODO - make this based on some variables so we can try different configurations
const PxU32 IntegrationPerThread = 256;
const PxU32 numTasks = ((bodyCount + IntegrationPerThread-1)/IntegrationPerThread);
const PxU32 taskBatchSize = 64;
for(PxU32 i = 0; i < numTasks; i+=taskBatchSize)
{
const PxU32 nbTasks = PxMin(numTasks - i, taskBatchSize);
PxsPreIntegrateTask* tasks = reinterpret_cast<PxsPreIntegrateTask*>(getTaskPool().allocate(sizeof(PxsPreIntegrateTask)*nbTasks));
for(PxU32 a = 0; a < nbTasks; ++a)
{
PxU32 startIndex = (i+a)*IntegrationPerThread;
PxU32 nbToIntegrate = PxMin((bodyCount-startIndex), IntegrationPerThread);
PxsPreIntegrateTask* pTask = PX_PLACEMENT_NEW(&tasks[a], PxsPreIntegrateTask)(*this, bodyArray,
originalBodyArray, nodeIndexArray, solverBodyDataPool, dt, bodyCount,
&maxSolverPositionIterations, &maxSolverVelocityIterations, startIndex,
nbToIntegrate, mGravity);
pTask->setContinuation(&task);
pTask->removeReference();
}
}
PxMemZero(solverBodyPool, bodyCount * sizeof(PxSolverBody));
}
void solveParallel(SOLVER_PARALLEL_METHOD_ARGS)
{
Dy::ThreadContext& threadContext = *context.getThreadContext();
threadContext.mZVector.forceSize_Unsafe(0);
threadContext.mZVector.reserve(params.mMaxArticulationLinks);
threadContext.mZVector.forceSize_Unsafe(params.mMaxArticulationLinks);
threadContext.mDeltaV.forceSize_Unsafe(0);
threadContext.mDeltaV.reserve(params.mMaxArticulationLinks);
threadContext.mDeltaV.forceSize_Unsafe(params.mMaxArticulationLinks);
context.solveParallel(params, islandSim, threadContext.mZVector.begin(), threadContext.mDeltaV.begin());
context.putThreadContext(&threadContext);
}
void DynamicsContext::solveParallel(SolverIslandParams& params, IG::IslandSim& islandSim, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV)
{
mSolverCore[mFrictionType]->solveVParallelAndWriteBack(params, Z, deltaV);
integrateCoreParallel(params, deltaV, islandSim);
}
void DynamicsContext::integrateCoreParallel(SolverIslandParams& params, Cm::SpatialVectorF* deltaV, IG::IslandSim& islandSim)
{
const PxI32 unrollCount = 128;
PxI32* bodyIntegrationListIndex = ¶ms.bodyIntegrationListIndex;
PxI32 index = physx::PxAtomicAdd(bodyIntegrationListIndex, unrollCount) - unrollCount;
const PxI32 numBodies = PxI32(params.bodyListSize);
const PxI32 numArtics = PxI32(params.articulationListSize);
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
PxsBodyCore*const* bodyArray = params.bodyArray;
PxsRigidBody** PX_RESTRICT rigidBodies = params.rigidBodies;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
PxI32 numIntegrated = 0;
PxI32 bodyRemainder = unrollCount;
while(index < numArtics)
{
const PxI32 remainder = PxMin(numArtics - index, unrollCount);
bodyRemainder -= remainder;
for(PxI32 a = 0; a < remainder; ++a, index++)
{
const PxI32 i = index;
{
//PX_PROFILE_ZONE("Articulations.integrate", mContextID);
ArticulationPImpl::updateBodies(articulationListStart[i], deltaV, mDt);
}
++numIntegrated;
}
if(bodyRemainder == 0)
{
index = physx::PxAtomicAdd(bodyIntegrationListIndex, unrollCount) - unrollCount;
bodyRemainder = unrollCount;
}
}
index -= numArtics;
const PxI32 unrollPlusArtics = unrollCount + numArtics;
PxSolverBody* PX_RESTRICT solverBodies = params.bodyListStart;
PxSolverBodyData* PX_RESTRICT solverBodyData = params.bodyDataList + params.solverBodyOffset+1;
while(index < numBodies)
{
const PxI32 remainder = PxMin(numBodies - index, bodyRemainder);
bodyRemainder -= remainder;
for(PxI32 a = 0; a < remainder; ++a, index++)
{
const PxI32 prefetch = PxMin(index+4, numBodies - 1);
PxPrefetchLine(bodyArray[prefetch]);
PxPrefetchLine(bodyArray[prefetch],128);
PxPrefetchLine(&solverBodies[index],128);
PxPrefetchLine(&motionVelocityArray[index],128);
PxPrefetchLine(&bodyArray[index+32]);
PxPrefetchLine(&rigidBodies[prefetch]);
PxSolverBodyData& data = solverBodyData[index];
PxsRigidBody& rBody = *rigidBodies[index];
PxsBodyCore& core = rBody.getCore();
integrateCore(motionVelocityArray[index].linear, motionVelocityArray[index].angular,
solverBodies[index], data, mDt, core.lockFlags);
rBody.mLastTransform = core.body2World;
core.body2World = data.body2World;
core.linearVelocity = data.linearVelocity;
core.angularVelocity = data.angularVelocity;
const bool hasStaticTouch = islandSim.getIslandStaticTouchCount(PxNodeIndex(data.nodeIndex)) != 0;
sleepCheck(rigidBodies[index], mDt, mEnableStabilization, motionVelocityArray[index], hasStaticTouch);
++numIntegrated;
}
{
index = physx::PxAtomicAdd(bodyIntegrationListIndex, unrollCount) - unrollPlusArtics;
bodyRemainder = unrollCount;
}
}
PxMemoryBarrier();
physx::PxAtomicAdd(¶ms.numObjectsIntegrated, numIntegrated);
}
static PxU32 createFinalizeContacts_Parallel(PxSolverBodyData* solverBodyData, ThreadContext& mThreadContext, DynamicsContext& context,
PxU32 startIndex, PxU32 endIndex, PxsContactManagerOutputIterator& outputs)
{
PX_PROFILE_ZONE("createFinalizeContacts_Parallel", context.getContextId());
const PxFrictionType::Enum frictionType = context.getFrictionType();
const PxReal correlationDist = context.getCorrelationDistance();
const PxReal bounceThreshold = context.getBounceThreshold();
const PxReal frictionOffsetThreshold = context.getFrictionOffsetThreshold();
const PxReal dt = context.getDt();
const PxReal invDt = PxMin(context.getMaxBiasCoefficient(), context.getInvDt());
PxSolverConstraintDesc* contactDescPtr = mThreadContext.orderedContactConstraints;
PxConstraintBatchHeader* headers = mThreadContext.contactConstraintBatchHeaders;
PxI32 axisConstraintCount = 0;
ThreadContext* threadContext = context.getThreadContext();
threadContext->mConstraintBlockStream.reset(); //ensure there's no left-over memory that belonged to another island
threadContext->mZVector.forceSize_Unsafe(0);
threadContext->mZVector.reserve(mThreadContext.mMaxArticulationLinks);
threadContext->mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);
//threadContext->mDeltaV.forceSize_Unsafe(0);
//threadContext->mDeltaV.reserve(mThreadContext.mMaxArticulationLinks);
//threadContext->mDeltaV.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);
Cm::SpatialVectorF* Z = threadContext->mZVector.begin();
const PxTransform idt(PxIdentity);
BlockAllocator blockAllocator(mThreadContext.mConstraintBlockManager, threadContext->mConstraintBlockStream, threadContext->mFrictionPatchStreamPair, threadContext->mConstraintSize);
const PxReal ccdMaxSeparation = context.getCCDSeparationThreshold();
for(PxU32 a = startIndex; a < endIndex; ++a)
{
PxConstraintBatchHeader& header = headers[a];
if(contactDescPtr[header.startIndex].constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT)
{
PxSolverContactDesc blockDescs[4];
PxsContactManagerOutput* cmOutputs[4];
PxsContactManager* cms[4];
for (PxU32 i = 0; i < header.stride; ++i)
{
PxSolverConstraintDesc& desc = contactDescPtr[header.startIndex + i];
PxSolverContactDesc& blockDesc = blockDescs[i];
PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint);
cms[i] = cm;
PxcNpWorkUnit& unit = cm->getWorkUnit();
cmOutputs[i] = &outputs.getContactManager(unit.mNpIndex);
PxSolverBodyData& data0 = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyADataIndex];
PxSolverBodyData& data1 = desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyBDataIndex];
blockDesc.data0 = &data0;
blockDesc.data1 = &data1;
PxU8 flags = unit.rigidCore0->mFlags;
if (unit.rigidCore1)
flags |= PxU8(unit.rigidCore1->mFlags);
blockDesc.bodyFrame0 = unit.rigidCore0->body2World;
blockDesc.bodyFrame1 = unit.rigidCore1 ? unit.rigidCore1->body2World : idt;
blockDesc.shapeInteraction = cm->getShapeInteraction();
blockDesc.contactForces = cmOutputs[i]->contactForces;
blockDesc.desc = &desc;
blockDesc.body0 = desc.bodyA;
blockDesc.body1 = desc.bodyB;
blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION);
blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY;
//second body is articulation
if (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1)
{
//kinematic link
if (desc.linkIndexB == 0xff)
{
blockDesc.bodyState1 = PxSolverContactDesc::eSTATIC_BODY;
}
else
{
blockDesc.bodyState1 = PxSolverContactDesc::eARTICULATION;
}
}
else
{
blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY :
((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY);
}
//blockDesc.flags = unit.flags;
PxReal dominance0 = unit.dominance0 ? 1.f : 0.f;
PxReal dominance1 = unit.dominance1 ? 1.f : 0.f;
blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0;
blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1;
blockDesc.restDistance = unit.restDistance;
blockDesc.frictionPtr = unit.frictionDataPtr;
blockDesc.frictionCount = unit.frictionPatchCount;
blockDesc.maxCCDSeparation = (flags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) ? ccdMaxSeparation : PX_MAX_F32;
blockDesc.offsetSlop = unit.mOffsetSlop;
}
#if DY_BATCH_CONSTRAINTS
SolverConstraintPrepState::Enum state = SolverConstraintPrepState::eUNBATCHABLE;
if(header.stride == 4)
{
//KS - todo - plumb in axisConstraintCount into this method to keep track of the number of axes
state = createFinalizeMethods4[frictionType](cmOutputs, *threadContext,
blockDescs,
invDt,
dt,
bounceThreshold,
frictionOffsetThreshold,
correlationDist,
blockAllocator);
}
if(SolverConstraintPrepState::eSUCCESS != state)
#endif
{
for(PxU32 i = 0; i < header.stride; ++i)
{
PxSolverConstraintDesc& desc = contactDescPtr[header.startIndex+i];
PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint);
PxcNpWorkUnit& n = cm->getWorkUnit();
PxsContactManagerOutput& output = outputs.getContactManager(n.mNpIndex);
createFinalizeMethods[frictionType](blockDescs[i], output, *threadContext,
invDt, dt, bounceThreshold, frictionOffsetThreshold, correlationDist,
blockAllocator, Z);
getContactManagerConstraintDesc(output,*cm,desc);
}
}
for (PxU32 i = 0; i < header.stride; ++i)
{
PxsContactManager* cm = cms[i];
PxcNpWorkUnit& unit = cm->getWorkUnit();
unit.frictionDataPtr = blockDescs[i].frictionPtr;
unit.frictionPatchCount = blockDescs[i].frictionCount;
axisConstraintCount += blockDescs[i].axisConstraintCount;
}
}
else if(contactDescPtr[header.startIndex].constraintLengthOver16 == DY_SC_TYPE_RB_1D)
{
SolverConstraintShaderPrepDesc shaderDescs[4];
PxSolverConstraintPrepDesc descs[4];
for (PxU32 i = 0; i < header.stride; ++i)
{
PxSolverConstraintDesc& desc = contactDescPtr[header.startIndex + i];
const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint);
SolverConstraintShaderPrepDesc& shaderPrepDesc = shaderDescs[i];
PxSolverConstraintPrepDesc& prepDesc = descs[i];
const PxConstraintSolverPrep solverPrep = constraint->solverPrep;
const void* constantBlock = constraint->constantBlock;
const PxU32 constantBlockByteSize = constraint->constantBlockSize;
const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : idt);
const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : idt);
const PxSolverBody* sbody0 = desc.bodyA;
const PxSolverBody* sbody1 = desc.bodyB;
PxSolverBodyData* sbodyData0 = &solverBodyData[desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? desc.bodyADataIndex : 0];
PxSolverBodyData* sbodyData1 = &solverBodyData[desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? desc.bodyBDataIndex : 0];
shaderPrepDesc.constantBlock = constantBlock;
shaderPrepDesc.constantBlockByteSize = constantBlockByteSize;
shaderPrepDesc.constraint = constraint;
shaderPrepDesc.solverPrep = solverPrep;
prepDesc.desc = &desc;
prepDesc.bodyFrame0 = pose0;
prepDesc.bodyFrame1 = pose1;
prepDesc.data0 = sbodyData0;
prepDesc.data1 = sbodyData1;
prepDesc.body0 = sbody0;
prepDesc.body1 = sbody1;
prepDesc.linBreakForce = constraint->linBreakForce;
prepDesc.angBreakForce = constraint->angBreakForce;
prepDesc.writeback = &context.getConstraintWriteBackPool()[constraint->index];
setupConstraintFlags(prepDesc, constraint->flags);
prepDesc.minResponseThreshold = constraint->minResponseThreshold;
}
#if DY_BATCH_CONSTRAINTS && DY_BATCH_1D
SolverConstraintPrepState::Enum state = SolverConstraintPrepState::eUNBATCHABLE;
if(header.stride == 4)
{
PxU32 totalRows;
state = setupSolverConstraint4
(shaderDescs, descs, dt, invDt, totalRows,
blockAllocator);
axisConstraintCount += totalRows;
}
if(state != SolverConstraintPrepState::eSUCCESS)
#endif
{
for(PxU32 i = 0; i < header.stride; ++i)
{
axisConstraintCount += SetupSolverConstraint(shaderDescs[i], descs[i], blockAllocator, dt, invDt, Z);
}
}
}
}
#if PX_ENABLE_SIM_STATS
threadContext->getSimStats().numAxisSolverConstraints += axisConstraintCount;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
context.putThreadContext(threadContext);
return PxU32(axisConstraintCount); //Can't write to mThreadContext as it's shared!!!!
}
class PxsCreateFinalizeContactsTask : public Cm::Task
{
PxsCreateFinalizeContactsTask& operator=(const PxsCreateFinalizeContactsTask&);
public:
PxsCreateFinalizeContactsTask( const PxU32 numConstraints, PxSolverConstraintDesc* descArray, PxSolverBodyData* solverBodyData,
ThreadContext& threadContext, DynamicsContext& context, PxU32 startIndex, PxU32 endIndex, PxsContactManagerOutputIterator& outputs) :
Cm::Task(context.getContextId()),
mNumConstraints(numConstraints), mDescArray(descArray), mSolverBodyData(solverBodyData),
mThreadContext(threadContext), mDynamicsContext(context),
mOutputs(outputs),
mStartIndex(startIndex), mEndIndex(endIndex)
{}
virtual void runInternal()
{
createFinalizeContacts_Parallel(mSolverBodyData, mThreadContext, mDynamicsContext, mStartIndex, mEndIndex, mOutputs);
}
virtual const char* getName() const
{
return "PxsDynamics.createFinalizeContacts";
}
public:
const PxU32 mNumConstraints;
PxSolverConstraintDesc* mDescArray;
PxSolverBodyData* mSolverBodyData;
ThreadContext& mThreadContext;
DynamicsContext& mDynamicsContext;
PxsContactManagerOutputIterator& mOutputs;
PxU32 mStartIndex;
PxU32 mEndIndex;
};
PxU8* BlockAllocator::reserveConstraintData(const PxU32 size)
{
mTotalConstraintByteSize += size;
return mConstraintBlockStream.reserve(size, mConstraintBlockManager);
}
PxU8* BlockAllocator::reserveFrictionData(const PxU32 size)
{
return mFrictionPatchStreamPair.reserve<PxU8>(size);
}
class PxsCreateArticConstraintsTask : public Cm::Task
{
PxsCreateArticConstraintsTask& operator=(const PxsCreateArticConstraintsTask&);
public:
static const PxU32 NbArticsPerTask = 32;
PxsCreateArticConstraintsTask(Dy::FeatherstoneArticulation** articulations, const PxU32 nbArticulations, PxSolverBodyData* solverBodyData, ThreadContext& threadContext, DynamicsContext& context,
PxsContactManagerOutputIterator& outputs) :
Cm::Task(context.getContextId()),
mArticulations(articulations),
mNbArticulations(nbArticulations),
mSolverBodyData(solverBodyData),
mThreadContext(threadContext), mDynamicsContext(context),
mOutputs(outputs)
{}
virtual void runInternal()
{
const PxReal correlationDist = mDynamicsContext.getCorrelationDistance();
const PxReal bounceThreshold = mDynamicsContext.getBounceThreshold();
const PxReal frictionOffsetThreshold = mDynamicsContext.getFrictionOffsetThreshold();
const PxReal dt = mDynamicsContext.getDt();
const PxReal invDt = PxMin(mDynamicsContext.getMaxBiasCoefficient(), mDynamicsContext.getInvDt());
const PxReal ccdMaxSeparation = mDynamicsContext.getCCDSeparationThreshold();
ThreadContext* threadContext = mDynamicsContext.getThreadContext();
threadContext->mConstraintBlockStream.reset(); //ensure there's no left-over memory that belonged to another island
threadContext->mZVector.forceSize_Unsafe(0);
threadContext->mZVector.reserve(mThreadContext.mMaxArticulationLinks);
threadContext->mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);
for (PxU32 i = 0; i < mNbArticulations; ++i)
{
mArticulations[i]->prepareStaticConstraints(dt, invDt, mOutputs, *threadContext, correlationDist, bounceThreshold, frictionOffsetThreshold,
ccdMaxSeparation, mSolverBodyData, mThreadContext.mConstraintBlockManager, mDynamicsContext.getConstraintWriteBackPool().begin());
}
mDynamicsContext.putThreadContext(threadContext);
}
virtual const char* getName() const
{
return "PxsDynamics.createFinalizeContacts";
}
public:
Dy::FeatherstoneArticulation** mArticulations;
PxU32 mNbArticulations;
PxSolverBodyData* mSolverBodyData;
ThreadContext& mThreadContext;
DynamicsContext& mDynamicsContext;
PxsContactManagerOutputIterator& mOutputs;
};
void PxsSolverCreateFinalizeConstraintsTask::runInternal()
{
PX_PROFILE_ZONE("CreateConstraints", mContext.getContextId());
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
PxU32 descCount = mThreadContext.mNumDifferentBodyConstraints;
PxU32 selfConstraintDescCount = mThreadContext.contactDescArraySize - (mThreadContext.mNumDifferentBodyConstraints + mThreadContext.mNumStaticConstraints);
PxArray<PxU32>& accumulatedConstraintsPerPartition = mThreadContext.mConstraintsPerPartition;
PxU32 numHeaders = 0;
PxU32 currentPartition = 0;
PxU32 maxJ = descCount == 0 ? 0 : accumulatedConstraintsPerPartition[0];
const PxU32 maxBatchPartition = 0xFFFFFFFF;
const PxU32 maxBatchSize = mEnhancedDeterminism ? 1u : 4u;
PxU32 headersPerPartition = 0;
for(PxU32 a = 0; a < descCount;)
{
PxU32 loopMax = PxMin(maxJ - a, maxBatchSize);
PxU16 j = 0;
if(loopMax > 0)
{
PxConstraintBatchHeader& header = mThreadContext.contactConstraintBatchHeaders[numHeaders++];
j=1;
PxSolverConstraintDesc& desc = mThreadContext.orderedContactConstraints[a];
if(!isArticulationConstraint(desc) && (desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT ||
desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D) && currentPartition < maxBatchPartition)
{
for(; j < loopMax && desc.constraintLengthOver16 == mThreadContext.orderedContactConstraints[a+j].constraintLengthOver16 &&
!isArticulationConstraint(mThreadContext.orderedContactConstraints[a+j]); ++j);
}
header.startIndex = a;
header.stride = j;
headersPerPartition++;
}
if(maxJ == (a + j) && maxJ != descCount)
{
//Go to next partition!
accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition;
headersPerPartition = 0;
currentPartition++;
maxJ = accumulatedConstraintsPerPartition[currentPartition];
}
a+= j;
}
if(descCount)
accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition;
accumulatedConstraintsPerPartition.forceSize_Unsafe(mThreadContext.mMaxPartitions);
PxU32 numDifferentBodyBatchHeaders = numHeaders;
for(PxU32 a = 0; a < selfConstraintDescCount; ++a)
{
PxConstraintBatchHeader& header = mThreadContext.contactConstraintBatchHeaders[numHeaders++];
header.startIndex = a + descCount;
header.stride = 1;
}
PxU32 numSelfConstraintBatchHeaders = numHeaders - numDifferentBodyBatchHeaders;
mThreadContext.numDifferentBodyBatchHeaders = numDifferentBodyBatchHeaders;
mThreadContext.numSelfConstraintBatchHeaders = numSelfConstraintBatchHeaders;
mThreadContext.numContactConstraintBatches = numHeaders;
{
PxSolverConstraintDesc* descBegin = mThreadContext.orderedContactConstraints;
const PxU32 numThreads = getTaskManager()->getCpuDispatcher()->getWorkerCount();
//Choose an appropriate number of constraint prep tasks. This must be proportionate to the number of constraints to prep and the number
//of worker threads available.
const PxU32 TaskBlockSize = 16;
const PxU32 TaskBlockLargeSize = 64;
const PxU32 BlockAllocationSize = 64;
PxU32 numTasks = (numHeaders+TaskBlockLargeSize-1)/TaskBlockLargeSize;
if(numTasks)
{
if(numTasks < numThreads)
numTasks = PxMax(1u, (numHeaders+TaskBlockSize-1)/TaskBlockSize);
const PxU32 constraintsPerTask = (numHeaders + numTasks-1)/numTasks;
for(PxU32 i = 0; i < numTasks; i+=BlockAllocationSize)
{
PxU32 blockSize = PxMin(numTasks - i, BlockAllocationSize);
PxsCreateFinalizeContactsTask* tasks = reinterpret_cast<PxsCreateFinalizeContactsTask*>(mContext.getTaskPool().allocate(sizeof(PxsCreateFinalizeContactsTask)*blockSize));
for(PxU32 a = 0; a < blockSize; ++a)
{
PxU32 startIndex = (a + i) * constraintsPerTask;
PxU32 endIndex = PxMin(startIndex + constraintsPerTask, numHeaders);
PxsCreateFinalizeContactsTask* pTask = PX_PLACEMENT_NEW(&tasks[a], PxsCreateFinalizeContactsTask( descCount, descBegin, mContext.mSolverBodyDataPool.begin(), mThreadContext, mContext, startIndex, endIndex, mOutputs));
pTask->setContinuation(mCont);
pTask->removeReference();
}
}
}
}
const PxU32 articCount = mIslandContext.mCounts.articulations;
for (PxU32 i = 0; i < articCount; i += PxsCreateArticConstraintsTask::NbArticsPerTask)
{
const PxU32 nbToProcess = PxMin(articCount - i, PxsCreateArticConstraintsTask::NbArticsPerTask);
PxsCreateArticConstraintsTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(PxsCreateArticConstraintsTask)), PxsCreateArticConstraintsTask)
(mThreadContext.mArticulationArray + i, nbToProcess, mContext.mSolverBodyDataPool.begin(), mThreadContext, mContext, mOutputs);
task->setContinuation(mCont);
task->removeReference();
}
}
}
}
| 117,138 | C++ | 37.994341 | 294 | 0.758584 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrepShared.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CONTACT_PREP_SHARED_H
#define DY_CONTACT_PREP_SHARED_H
#include "foundation/PxPreprocessor.h"
#include "PxSceneDesc.h"
#include "foundation/PxVecMath.h"
#include "DyContactPrep.h"
#include "DyCorrelationBuffer.h"
#include "DyArticulationContactPrep.h"
#include "PxsContactManager.h"
#include "PxsContactManagerState.h"
namespace physx
{
namespace Dy
{
template<class PxSolverContactDescT>
PX_FORCE_INLINE Sc::ShapeInteraction* getInteraction(const PxSolverContactDescT& desc)
{
return reinterpret_cast<Sc::ShapeInteraction*>(desc.shapeInteraction);
}
PX_FORCE_INLINE bool pointsAreClose(const PxTransform& body1ToBody0,
const PxVec3& localAnchor0, const PxVec3& localAnchor1,
const PxVec3& axis, float correlDist)
{
const PxVec3 body0PatchPoint1 = body1ToBody0.transform(localAnchor1);
return PxAbs((localAnchor0 - body0PatchPoint1).dot(axis))<correlDist;
}
PX_FORCE_INLINE bool isSeparated(const FrictionPatch& patch, const PxTransform& body1ToBody0, const PxReal correlationDistance)
{
PX_ASSERT(patch.anchorCount <= 2);
for(PxU32 a = 0; a < patch.anchorCount; ++a)
{
if(!pointsAreClose(body1ToBody0, patch.body0Anchors[a], patch.body1Anchors[a], patch.body0Normal, correlationDistance))
return true;
}
return false;
}
inline bool getFrictionPatches(CorrelationBuffer& c,
const PxU8* frictionCookie,
PxU32 frictionPatchCount,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxReal correlationDistance)
{
if(frictionCookie == NULL || frictionPatchCount == 0)
return true;
//KS - this is now DMA'd inside the shader so we don't need to immediate DMA it here
const FrictionPatch* patches = reinterpret_cast<const FrictionPatch*>(frictionCookie);
//Try working out relative transforms! TODO - can we compute this lazily for the first friction patch
bool evaluated = false;
PxTransform body1ToBody0;
while(frictionPatchCount--)
{
PxPrefetchLine(patches,128);
const FrictionPatch& patch = *patches++;
PX_ASSERT (patch.broken == 0 || patch.broken == 1);
if(!patch.broken)
{
// if the eDISABLE_STRONG_FRICTION flag is there we need to blow away the previous frame's friction correlation, so
// that we can associate each friction anchor with a target velocity. So we lose strong friction.
if(patch.anchorCount != 0 && !(patch.materialFlags & PxMaterialFlag::eDISABLE_STRONG_FRICTION))
{
PX_ASSERT(patch.anchorCount <= 2);
if(!evaluated)
{
body1ToBody0 = bodyFrame0.transformInv(bodyFrame1);
evaluated = true;
}
if(patch.body0Normal.dot(body1ToBody0.rotate(patch.body1Normal)) > PXC_SAME_NORMAL)
{
if(!isSeparated(patch, body1ToBody0, correlationDistance))
{
if(c.frictionPatchCount == CorrelationBuffer::MAX_FRICTION_PATCHES)
return false;
{
c.contactID[c.frictionPatchCount][0] = 0xffff;
c.contactID[c.frictionPatchCount][1] = 0xffff;
//Rotate the contact normal into world space
c.frictionPatchWorldNormal[c.frictionPatchCount] = bodyFrame0.rotate(patch.body0Normal);
c.frictionPatchContactCounts[c.frictionPatchCount] = 0;
c.patchBounds[c.frictionPatchCount].setEmpty();
c.correlationListHeads[c.frictionPatchCount] = CorrelationBuffer::LIST_END;
PxMemCopy(&c.frictionPatches[c.frictionPatchCount++], &patch, sizeof(FrictionPatch));
}
}
}
}
}
}
return true;
}
PX_FORCE_INLINE PxU32 extractContacts(PxContactBuffer& buffer, PxsContactManagerOutput& npOutput, bool& hasMaxImpulse, bool& hasTargetVelocity,
PxReal& invMassScale0, PxReal& invMassScale1, PxReal& invInertiaScale0, PxReal& invInertiaScale1, PxReal defaultMaxImpulse)
{
PxContactStreamIterator iter(npOutput.contactPatches, npOutput.contactPoints, npOutput.getInternalFaceIndice(), npOutput.nbPatches, npOutput.nbContacts);
PxU32 numContacts = buffer.count, origContactCount = buffer.count;
if(!iter.forceNoResponse)
{
invMassScale0 = iter.getInvMassScale0();
invMassScale1 = iter.getInvMassScale1();
invInertiaScale0 = iter.getInvInertiaScale0();
invInertiaScale1 = iter.getInvInertiaScale1();
hasMaxImpulse = (iter.patch->internalFlags & PxContactPatch::eHAS_MAX_IMPULSE) != 0;
hasTargetVelocity = (iter.patch->internalFlags & PxContactPatch::eHAS_TARGET_VELOCITY) != 0;
while(iter.hasNextPatch())
{
iter.nextPatch();
while(iter.hasNextContact())
{
iter.nextContact();
PxPrefetchLine(iter.contact, 128);
PxPrefetchLine(&buffer.contacts[numContacts], 128);
PxReal maxImpulse = hasMaxImpulse ? iter.getMaxImpulse() : defaultMaxImpulse;
if(maxImpulse != 0.f)
{
PX_ASSERT(numContacts < PxContactBuffer::MAX_CONTACTS);
buffer.contacts[numContacts].normal = iter.getContactNormal();
PX_ASSERT(PxAbs(buffer.contacts[numContacts].normal.magnitude() - 1) < 1e-3f);
buffer.contacts[numContacts].point = iter.getContactPoint();
buffer.contacts[numContacts].separation = iter.getSeparation();
//KS - we use the face indices to cache the material indices and flags - avoids bloating the PxContact structure
buffer.contacts[numContacts].materialFlags = PxU8(iter.getMaterialFlags());
buffer.contacts[numContacts].maxImpulse = maxImpulse;
buffer.contacts[numContacts].staticFriction = iter.getStaticFriction();
buffer.contacts[numContacts].dynamicFriction = iter.getDynamicFriction();
buffer.contacts[numContacts].restitution = iter.getRestitution();
buffer.contacts[numContacts].damping = iter.getDamping();
const PxVec3& targetVel = iter.getTargetVel();
buffer.contacts[numContacts].targetVel = targetVel;
++numContacts;
}
}
}
}
const PxU32 contactCount = numContacts - origContactCount;
buffer.count = numContacts;
return contactCount;
}
struct CorrelationListIterator
{
CorrelationBuffer& buffer;
PxU32 currPatch;
PxU32 currContact;
CorrelationListIterator(CorrelationBuffer& correlationBuffer, PxU32 startPatch) : buffer(correlationBuffer)
{
//We need to force us to advance the correlation buffer to the first available contact (if one exists)
PxU32 newPatch = startPatch, newContact = 0;
while(newPatch != CorrelationBuffer::LIST_END && newContact == buffer.contactPatches[newPatch].count)
{
newPatch = buffer.contactPatches[newPatch].next;
newContact = 0;
}
currPatch = newPatch;
currContact = newContact;
}
//Returns true if it has another contact pre-loaded. Returns false otherwise
PX_FORCE_INLINE bool hasNextContact() const
{
return (currPatch != CorrelationBuffer::LIST_END && currContact < buffer.contactPatches[currPatch].count);
}
inline void nextContact(PxU32& patch, PxU32& contact)
{
PX_ASSERT(currPatch != CorrelationBuffer::LIST_END);
PX_ASSERT(currContact < buffer.contactPatches[currPatch].count);
patch = currPatch;
contact = currContact;
PxU32 newPatch = currPatch, newContact = currContact + 1;
while(newPatch != CorrelationBuffer::LIST_END && newContact == buffer.contactPatches[newPatch].count)
{
newPatch = buffer.contactPatches[newPatch].next;
newContact = 0;
}
currPatch = newPatch;
currContact = newContact;
}
private:
CorrelationListIterator& operator=(const CorrelationListIterator&);
};
PX_FORCE_INLINE void constructContactConstraint(const Mat33V& invSqrtInertia0, const Mat33V& invSqrtInertia1, const FloatVArg invMassNorLenSq0,
const FloatVArg invMassNorLenSq1, const FloatVArg angD0, const FloatVArg angD1, const Vec3VArg bodyFrame0p, const Vec3VArg bodyFrame1p,
const Vec3VArg normal, const FloatVArg norVel, const VecCrossV& norCross, const Vec3VArg angVel0, const Vec3VArg angVel1,
const FloatVArg invDt, const FloatVArg invDtp8, const FloatVArg dt, const FloatVArg restDistance, const FloatVArg maxPenBias, const FloatVArg restitution,
const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPoint& solverContact,
const FloatVArg ccdMaxSeparation, const Vec3VArg solverOffsetSlop, const FloatVArg damping)
{
const FloatV zero = FZero();
const Vec3V point = V3LoadA(contact.point);
const FloatV separation = FLoad(contact.separation);
const FloatV cTargetVel = V3Dot(normal, V3LoadA(contact.targetVel));
const Vec3V ra = V3Sub(point, bodyFrame0p);
const Vec3V rb = V3Sub(point, bodyFrame1p);
/*ra = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(ra)), V3Zero(), ra);
rb = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rb)), V3Zero(), rb);*/
Vec3V raXn = V3Cross(ra, norCross);
Vec3V rbXn = V3Cross(rb, norCross);
FloatV vRelAng = FSub(V3Dot(raXn, angVel0), V3Dot(rbXn, angVel1));
const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(norVel, zero), FMax(), FDiv(vRelAng, norVel)), FOne()));
raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn);
vRelAng = FSub(V3Dot(raXn, angVel0), V3Dot(rbXn, angVel1));
const FloatV vrel = FAdd(norVel, vRelAng);
const Vec3V raXnSqrtInertia = M33MulV3(invSqrtInertia0, raXn);
const Vec3V rbXnSqrtInertia = M33MulV3(invSqrtInertia1, rbXn);
const FloatV resp0 = FAdd(invMassNorLenSq0, FMul(V3Dot(raXnSqrtInertia, raXnSqrtInertia), angD0));
const FloatV resp1 = FSub(FMul(V3Dot(rbXnSqrtInertia, rbXnSqrtInertia), angD1), invMassNorLenSq1);
const FloatV unitResponse = FAdd(resp0, resp1);
const FloatV penetration = FSub(separation, restDistance);
const FloatV penetrationInvDt = FMul(penetration, invDt);
const FloatV sumVRel(vrel);
const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt));
FloatV targetVelocity = FAdd(cTargetVel, FSel(isGreater2, FMul(FNeg(sumVRel), restitution), zero));
//Note - we add on the initial target velocity
targetVelocity = FSub(targetVelocity, vrel);
FloatV biasedErr, unbiasedErr;
FloatV velMultiplier, impulseMultiplier;
if (FAllGrtr(zero, restitution))
{
const FloatV nrdt = FMul(dt, restitution);
const FloatV a = FMul(dt, FSub(damping, nrdt));
const FloatV b = FMul(dt, FNeg(FMul(restitution, penetration)));
const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne()));
velMultiplier = FMul(x, a);
//FloatV scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier));
const FloatV scaledBias = FMul(x, b);
impulseMultiplier = FSub(FOne(), x);
unbiasedErr = biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias));
}
else
{
velMultiplier = FSel(FIsGrtr(unitResponse, zero), FRecip(unitResponse), zero);
const FloatV penetrationInvDtPt8 = FMax(maxPenBias, FMul(penetration, invDtp8));
FloatV scaledBias = FMul(velMultiplier, penetrationInvDtPt8);
const BoolV ccdSeparationCondition = FIsGrtrOrEq(ccdMaxSeparation, penetration);
scaledBias = FSel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias);
impulseMultiplier = FLoad(1.0f);
biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias));
unbiasedErr = FScaleAdd(targetVelocity, velMultiplier, FSel(isGreater2, zero, FNeg(FMax(scaledBias, zero))));
}
//const FloatV unbiasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(FMax(scaledBias, zero)));
FStore(biasedErr, &solverContact.biasedErr);
FStore(unbiasedErr, &solverContact.unbiasedErr);
FStore(impulseMultiplier, &solverContact.impulseMultiplier);
solverContact.raXn_velMultiplierW = V4SetW(Vec4V_From_Vec3V(raXnSqrtInertia), velMultiplier);
solverContact.rbXn_maxImpulseW = V4SetW(Vec4V_From_Vec3V(rbXnSqrtInertia), FLoad(contact.maxImpulse));
}
}
}
#endif
| 13,346 | C | 38.841791 | 156 | 0.749438 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintPrep.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CONSTRAINT_PREP_H
#define DY_CONSTRAINT_PREP_H
#include "DyConstraint.h"
#include "DySolverConstraintDesc.h"
#include "foundation/PxArray.h"
#include "PxConstraint.h"
namespace physx
{
class PxcConstraintBlockStream;
class PxsConstraintBlockManager;
struct PxSolverBody;
struct PxSolverBodyData;
struct PxSolverConstraintDesc;
namespace Cm
{
struct SpatialVectorF;
}
namespace Dy
{
static const PxU32 MAX_CONSTRAINT_ROWS = 20;
struct SolverConstraintShaderPrepDesc
{
const Constraint* constraint;
PxConstraintSolverPrep solverPrep;
const void* constantBlock;
PxU32 constantBlockByteSize;
};
SolverConstraintPrepState::Enum setupSolverConstraint4
(SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs,
PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator);
SolverConstraintPrepState::Enum setupSolverConstraint4
(PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows);
PxU32 SetupSolverConstraint(SolverConstraintShaderPrepDesc& shaderDesc,
PxSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
PxReal dt, PxReal invdt, Cm::SpatialVectorF* Z);
class ConstraintHelper
{
public:
static PxU32 setupSolverConstraint(
PxSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
PxReal dt, PxReal invdt, Cm::SpatialVectorF* Z);
};
template<class PrepDescT>
PX_FORCE_INLINE void setupConstraintFlags(PrepDescT& prepDesc, PxU16 flags)
{
prepDesc.disablePreprocessing = (flags & PxConstraintFlag::eDISABLE_PREPROCESSING)!=0;
prepDesc.improvedSlerp = (flags & PxConstraintFlag::eIMPROVED_SLERP)!=0;
prepDesc.driveLimitsAreForces = (flags & PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES)!=0;
prepDesc.extendedLimits = (flags & PxConstraintFlag::eENABLE_EXTENDED_LIMITS)!=0;
prepDesc.disableConstraint = (flags & PxConstraintFlag::eDISABLE_CONSTRAINT)!=0;
}
void preprocessRows(Px1DConstraint** sorted,
Px1DConstraint* rows,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
PxU32 rowCount,
const PxMat33& sqrtInvInertia0F32,
const PxMat33& sqrtInvInertia1F32,
const PxReal invMass0,
const PxReal invMass1,
const PxConstraintInvMassScale& ims,
bool disablePreprocessing,
bool diagonalizeDrive);
PX_FORCE_INLINE void setupConstraintRows(Px1DConstraint* PX_RESTRICT rows, PxU32 size)
{
// This is necessary so that there will be sensible defaults and shaders will
// continue to work (albeit with a recompile) if the row format changes.
// It's a bit inefficient because it fills in all constraint rows even if there
// is only going to be one generated. A way around this would be for the shader to
// specify the maximum number of rows it needs, or it could call a subroutine to
// prep the row before it starts filling it it.
PxMemZero(rows, sizeof(Px1DConstraint)*size);
for(PxU32 i=0; i<size; i++)
{
Px1DConstraint& c = rows[i];
//Px1DConstraintInit(c);
c.minImpulse = -PX_MAX_REAL;
c.maxImpulse = PX_MAX_REAL;
}
}
}
}
#endif
| 4,949 | C | 34.611511 | 90 | 0.769246 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverPFConstraints.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DySolverBody.h"
#include "DySolverContact.h"
#include "DySolverContactPF.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "DyThresholdTable.h"
#include "DySolverContext.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
#include "DyThresholdTable.h"
#include "DySolverConstraintsShared.h"
#include "DyFeatherstoneArticulation.h"
#include "DyPGS.h"
namespace physx
{
namespace Dy
{
static void solveContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxSolverBody& b0 = *desc.bodyA;
PxSolverBody& b1 = *desc.bodyB;
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V linVel1 = V3LoadA(b1.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
Vec3V angState1 = V3LoadA(b1.angularState);
SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint);
const PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;//getConstraintLength(desc);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
//const FloatV zero = FZero();
while(currPtr < last)
{
SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader*>(currPtr);
currPtr += sizeof(SolverContactCoulombHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const Vec3V normal = hdr->getNormal();
const FloatV invMassDom0 = FLoad(hdr->dominance0);
const FloatV invMassDom1 = FLoad(hdr->dominance1);
const FloatV angD0 = FLoad(hdr->angDom0);
const FloatV angD1 = FLoad(hdr->angDom1);
SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr);
currPtr += numNormalConstr * sizeof(SolverContactPoint);
PxF32* appliedImpulse = reinterpret_cast<PxF32*> ((reinterpret_cast<PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader));
PxPrefetchLine(appliedImpulse);
solveDynamicContacts(contacts, numNormalConstr, normal, invMassDom0, invMassDom1,
angD0, angD1, linVel0, angState0, linVel1, angState1, appliedImpulse);
}
// Write back
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(linVel1, b1.linearVelocity);
V3StoreA(angState0, b0.angularState);
V3StoreA(angState1, b1.angularState);
PX_ASSERT(currPtr == last);
}
static void solveFriction(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxSolverBody& b0 = *desc.bodyA;
PxSolverBody& b1 = *desc.bodyB;
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V linVel1 = V3LoadA(b1.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
Vec3V angState1 = V3LoadA(b1.angularState);
PxU8* PX_RESTRICT ptr = desc.constraint;
PxU8* PX_RESTRICT currPtr = ptr;
const PxU8* PX_RESTRICT last = ptr + getConstraintLength(desc);
while(currPtr < last)
{
const SolverFrictionHeader* PX_RESTRICT frictionHeader = reinterpret_cast<SolverFrictionHeader*>(currPtr);
currPtr += sizeof(SolverFrictionHeader);
PxF32* appliedImpulse = reinterpret_cast<PxF32*>(currPtr);
currPtr += frictionHeader->getAppliedForcePaddingSize();
SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr);
const PxU32 numFrictionConstr = frictionHeader->numFrictionConstr;
const PxU32 numNormalConstr = frictionHeader->numNormalConstr;
const PxU32 numFrictionPerPoint = numFrictionConstr/numNormalConstr;
currPtr += numFrictionConstr * sizeof(SolverContactFriction);
const FloatV staticFriction = frictionHeader->getStaticFriction();
const FloatV invMass0D0 = FLoad(frictionHeader->invMass0D0);
const FloatV invMass1D1 = FLoad(frictionHeader->invMass1D1);
const FloatV angD0 = FLoad(frictionHeader->angDom0);
const FloatV angD1 = FLoad(frictionHeader->angDom1);
for(PxU32 i=0, j = 0;i<numFrictionConstr;j++)
{
for(PxU32 p = 0; p < numFrictionPerPoint; p++, i++)
{
SolverContactFriction& f = frictions[i];
PxPrefetchLine(&frictions[i], 128);
const Vec3V t0 = Vec3V_From_Vec4V(f.normalXYZ_appliedForceW);
const Vec3V raXt0 = Vec3V_From_Vec4V(f.raXnXYZ_velMultiplierW);
const Vec3V rbXt0 = Vec3V_From_Vec4V(f.rbXnXYZ_biasW);
const FloatV appliedForce = V4GetW(f.normalXYZ_appliedForceW);
const FloatV velMultiplier = V4GetW(f.raXnXYZ_velMultiplierW);
const FloatV targetVel = FLoad(f.targetVel);
const FloatV normalImpulse = FLoad(appliedImpulse[j]);
const FloatV maxFriction = FMul(staticFriction, normalImpulse);
const FloatV nMaxFriction = FNeg(maxFriction);
//Compute the normal velocity of the constraint.
const FloatV t0Vel1 = V3Dot(t0, linVel0);
const FloatV t0Vel2 = V3Dot(raXt0, angState0);
const FloatV t0Vel3 = V3Dot(t0, linVel1);
const FloatV t0Vel4 = V3Dot(rbXt0, angState1);
const FloatV t0Vel = FSub(FAdd(t0Vel1, t0Vel2), FAdd(t0Vel3, t0Vel4));
const Vec3V delLinVel0 = V3Scale(t0, invMass0D0);
const Vec3V delLinVel1 = V3Scale(t0, invMass1D1);
// still lots to do here: using loop pipelining we can interweave this code with the
// above - the code here has a lot of stalls that we would thereby eliminate
const FloatV tmp = FNegScaleSub(targetVel,velMultiplier,appliedForce);
FloatV newForce = FScaleAdd(t0Vel, velMultiplier, tmp);
newForce = FClamp(newForce, nMaxFriction, maxFriction);
FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1);
angState0 = V3ScaleAdd(raXt0, FMul(deltaF, angD0), angState0);
angState1 = V3NegScaleSub(rbXt0, FMul(deltaF, angD1), angState1);
f.setAppliedForce(newForce);
}
}
}
// Write back
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(linVel1, b1.linearVelocity);
V3StoreA(angState0, b0.angularState);
V3StoreA(angState1, b1.angularState);
PX_ASSERT(currPtr == last);
}
static void solveContactCoulomb_BStatic(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxSolverBody& b0 = *desc.bodyA;
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
SolverContactCoulombHeader* firstHeader = reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint);
const PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;//getConstraintLength(desc);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
//const FloatV zero = FZero();
while(currPtr < last)
{
SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader*>(currPtr);
currPtr += sizeof(SolverContactCoulombHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr);
PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPoint);
PxF32* appliedImpulse = reinterpret_cast<PxF32*> ((reinterpret_cast<PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader));
PxPrefetchLine(appliedImpulse);
const Vec3V normal = hdr->getNormal();
const FloatV invMassDom0 = FLoad(hdr->dominance0);
const FloatV angD0 = FLoad(hdr->angDom0);
solveStaticContacts(contacts, numNormalConstr, normal, invMassDom0,
angD0, linVel0, angState0, appliedImpulse);
}
// Write back
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(angState0, b0.angularState);
PX_ASSERT(currPtr == last);
}
static void solveFriction_BStatic(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxSolverBody& b0 = *desc.bodyA;
Vec3V linVel0 = V3LoadA(b0.linearVelocity);
Vec3V angState0 = V3LoadA(b0.angularState);
PxU8* PX_RESTRICT currPtr = desc.constraint;
const PxU8* PX_RESTRICT last = currPtr + getConstraintLength(desc);
while(currPtr < last)
{
const SolverFrictionHeader* PX_RESTRICT frictionHeader = reinterpret_cast<SolverFrictionHeader*>(currPtr);
const PxU32 numFrictionConstr = frictionHeader->numFrictionConstr;
const PxU32 numNormalConstr = frictionHeader->numNormalConstr;
const PxU32 numFrictionPerPoint = numFrictionConstr/numNormalConstr;
currPtr +=sizeof(SolverFrictionHeader);
PxF32* appliedImpulse = reinterpret_cast<PxF32*>(currPtr);
currPtr +=frictionHeader->getAppliedForcePaddingSize();
SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFriction);
const FloatV invMass0 = FLoad(frictionHeader->invMass0D0);
const FloatV angD0 = FLoad(frictionHeader->angDom0);
//const FloatV angD1 = FLoad(frictionHeader->angDom1);
const FloatV staticFriction = frictionHeader->getStaticFriction();
for(PxU32 i=0, j = 0;i<numFrictionConstr;j++)
{
for(PxU32 p = 0; p < numFrictionPerPoint; p++, i++)
{
SolverContactFriction& f = frictions[i];
PxPrefetchLine(&frictions[i+1]);
const Vec3V t0 = Vec3V_From_Vec4V(f.normalXYZ_appliedForceW);
const Vec3V raXt0 = Vec3V_From_Vec4V(f.raXnXYZ_velMultiplierW);
const FloatV appliedForce = V4GetW(f.normalXYZ_appliedForceW);
const FloatV velMultiplier = V4GetW(f.raXnXYZ_velMultiplierW);
const FloatV targetVel = FLoad(f.targetVel);
//const FloatV normalImpulse = contacts[f.contactIndex].getAppliedForce();
const FloatV normalImpulse = FLoad(appliedImpulse[j]);
const FloatV maxFriction = FMul(staticFriction, normalImpulse);
const FloatV nMaxFriction = FNeg(maxFriction);
//Compute the normal velocity of the constraint.
const FloatV t0Vel1 = V3Dot(t0, linVel0);
const FloatV t0Vel2 = V3Dot(raXt0, angState0);
const FloatV t0Vel = FAdd(t0Vel1, t0Vel2);
const Vec3V delangState0 = V3Scale(raXt0, angD0);
const Vec3V delLinVel0 = V3Scale(t0, invMass0);
// still lots to do here: using loop pipelining we can interweave this code with the
// above - the code here has a lot of stalls that we would thereby eliminate
const FloatV tmp = FNegScaleSub(targetVel,velMultiplier,appliedForce);
FloatV newForce = FScaleAdd(t0Vel, velMultiplier, tmp);
newForce = FClamp(newForce, nMaxFriction, maxFriction);
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
angState0 = V3ScaleAdd(delangState0, deltaF, angState0);
f.setAppliedForce(newForce);
}
}
}
// Write back
V3StoreA(linVel0, b0.linearVelocity);
V3StoreA(angState0, b0.angularState);
PX_ASSERT(currPtr == last);
}
static void concludeContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/)
{
PxU8* PX_RESTRICT cPtr = desc.constraint;
const SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr);
PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;//getConstraintLength(desc);
while(cPtr < last)
{
const SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr);
cPtr += sizeof(SolverContactCoulombHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
//if(cPtr < last)
//PxPrefetchLine(cPtr, 512);
PxPrefetchLine(cPtr,128);
PxPrefetchLine(cPtr,256);
PxPrefetchLine(cPtr,384);
const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt)
: sizeof(SolverContactPoint);
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContactPoint *c = reinterpret_cast<SolverContactPoint*>(cPtr);
cPtr += pointStride;
//c->scaledBias = PxMin(c->scaledBias, 0.f);
c->biasedErr = c->unbiasedErr;
}
}
PX_ASSERT(cPtr == last);
}
static void writeBackContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache,
PxSolverBodyData& bd0, PxSolverBodyData& bd1)
{
PxReal normalForce = 0.f;
PxU8* PX_RESTRICT cPtr = desc.constraint;
PxReal* PX_RESTRICT vForceWriteback = reinterpret_cast<PxReal*>(desc.writeBack);
const SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr);
PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;
const PxU32 pointStride = firstHeader->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt)
: sizeof(SolverContactPoint);
bool hasForceThresholds = false;
while(cPtr < last)
{
const SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr);
cPtr += sizeof(SolverContactCoulombHeader);
PxF32* appliedImpulse = reinterpret_cast<PxF32*> (const_cast<PxU8*>((reinterpret_cast<const PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader)));
hasForceThresholds = hdr->flags & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
const PxU32 numNormalConstr = hdr->numNormalConstr;
PxPrefetchLine(cPtr, 256);
PxPrefetchLine(cPtr, 384);
if(vForceWriteback!=NULL)
{
for(PxU32 i=0; i<numNormalConstr; i++)
{
PxF32 imp = appliedImpulse[i];
*vForceWriteback = imp;
vForceWriteback++;
normalForce += imp;
}
}
cPtr += numNormalConstr * pointStride;
}
PX_ASSERT(cPtr == last);
if(hasForceThresholds && desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
normalForce !=0 && (bd0.reportThreshold < PX_MAX_REAL || bd1.reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = normalForce;
elt.threshold = PxMin<float>(bd0.reportThreshold, bd1.reportThreshold);
elt.nodeIndexA = PxNodeIndex(bd0.nodeIndex);
elt.nodeIndexB = PxNodeIndex(bd1.nodeIndex);
elt.shapeInteraction = (reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint))->shapeInteraction;
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
void solveFrictionBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveFriction(desc[a], cache);
}
void solveFrictionBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveFriction(desc[a], cache);
}
void solveFriction_BStaticBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveFriction_BStatic(desc[a], cache);
}
/*void solveFriction_BStaticConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveFriction_BStatic(desc[a], cache);
}*/
void solveFriction_BStaticBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveFriction_BStatic(desc[a], cache);
}
void solveContactCoulombBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveContactCoulomb(desc[a], cache);
}
void solveContactCoulombConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
solveContactCoulomb(desc[a], cache);
concludeContactCoulomb(desc[a], cache);
}
}
void solveContactCoulombBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].bodyBDataIndex];
solveContactCoulomb(desc[a], cache);
writeBackContactCoulomb(desc[a], cache, bd0, bd1);
}
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveContactCoulomb_BStaticBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveContactCoulomb_BStatic(desc[a], cache);
}
void solveContactCoulomb_BStaticConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
solveContactCoulomb_BStatic(desc[a], cache);
concludeContactCoulomb(desc[a], cache);
}
}
void solveContactCoulomb_BStaticBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].bodyADataIndex];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].bodyBDataIndex];
solveContactCoulomb_BStatic(desc[a], cache);
writeBackContactCoulomb(desc[a], cache, bd0, bd1);
}
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Not enough space to write 4 more thresholds back!
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
static void solveExtContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
//We'll need this.
// const FloatV zero = FZero();
// const FloatV one = FOne();
Vec3V linVel0, angVel0, linVel1, angVel1;
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = V3LoadA(desc.bodyA->linearVelocity);
angVel0 = V3LoadA(desc.bodyA->angularState);
}
else
{
//articulation
Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA);
linVel0 = v.linear;
angVel0 = v.angular;
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
linVel1 = V3LoadA(desc.bodyB->linearVelocity);
angVel1 = V3LoadA(desc.bodyB->angularState);
}
else if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
//soft body, need to implement
linVel1 = V3Zero();
angVel1 = V3Zero();
}
else
{
//articulation
Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB);
linVel1 = v.linear;
angVel1 = v.angular;
}
//const PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16*16;
PxU8* PX_RESTRICT currPtr = desc.constraint;
const SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader*>(currPtr);
const PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;
//hopefully pointer aliasing doesn't bite.
Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero();
while (currPtr < last)
{
const SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader*>(currPtr);
currPtr += sizeof(SolverContactCoulombHeader);
const PxU32 numNormalConstr = hdr->numNormalConstr;
PxF32* appliedImpulse = reinterpret_cast<PxF32*>(const_cast<PxU8*>(((reinterpret_cast<const PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader))));
PxPrefetchLine(appliedImpulse);
SolverContactPointExt* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointExt*>(currPtr);
PxPrefetchLine(contacts);
currPtr += numNormalConstr * sizeof(SolverContactPointExt);
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
const Vec3V normal = hdr->getNormal();
solveExtContacts(contacts, numNormalConstr, normal, linVel0, angVel0, linVel1, angVel1, li0, ai0, li1, ai1, appliedImpulse);
linImpulse0 = V3ScaleAdd(li0, FLoad(hdr->dominance0), linImpulse0);
angImpulse0 = V3ScaleAdd(ai0, FLoad(hdr->angDom0), angImpulse0);
linImpulse1 = V3NegScaleSub(li1, FLoad(hdr->dominance1), linImpulse1);
angImpulse1 = V3NegScaleSub(ai1, FLoad(hdr->angDom1), angImpulse1);
}
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel0, desc.bodyA->linearVelocity);
V3StoreA(angVel0, desc.bodyA->angularState);
}
else
{
getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV);
}
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel1, desc.bodyB->linearVelocity);
V3StoreA(angVel1, desc.bodyB->angularState);
}
else
{
getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV);
}
PX_ASSERT(currPtr == last);
}
void solveExtFriction(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
Vec3V linVel0, angVel0, linVel1, angVel1;
if(desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
linVel0 = V3LoadA(desc.bodyA->linearVelocity);
angVel0 = V3LoadA(desc.bodyA->angularState);
}
else
{
Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA);
linVel0 = v.linear;
angVel0 = v.angular;
}
if(desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
linVel1 = V3LoadA(desc.bodyB->linearVelocity);
angVel1 = V3LoadA(desc.bodyB->angularState);
}
else
{
Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB);
linVel1 = v.linear;
angVel1 = v.angular;
}
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc.constraint;
const PxU8* PX_RESTRICT last = currPtr + desc.constraintLengthOver16*16;
Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero();
while(currPtr < last)
{
const SolverFrictionHeader* PX_RESTRICT frictionHeader = reinterpret_cast<SolverFrictionHeader*>(currPtr);
currPtr += sizeof(SolverFrictionHeader);
PxF32* appliedImpulse = reinterpret_cast<PxF32*>(currPtr);
currPtr += frictionHeader->getAppliedForcePaddingSize();
SolverContactFrictionExt* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionExt*>(currPtr);
const PxU32 numFrictionConstr = frictionHeader->numFrictionConstr;
currPtr += numFrictionConstr * sizeof(SolverContactFrictionExt);
const FloatV staticFriction = frictionHeader->getStaticFriction();
Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero();
PxU32 numNormalConstr = frictionHeader->numNormalConstr;
PxU32 nbFrictionsPerPoint = numFrictionConstr/numNormalConstr;
for(PxU32 i = 0, j = 0; i < numFrictionConstr; j++)
{
for(PxU32 p=0;p<nbFrictionsPerPoint;p++, i++)
{
SolverContactFrictionExt& f = frictions[i];
PxPrefetchLine(&frictions[i+1]);
const Vec3V t0 = Vec3V_From_Vec4V(f.normalXYZ_appliedForceW);
const Vec3V raXt0 = Vec3V_From_Vec4V(f.raXnXYZ_velMultiplierW);
const Vec3V rbXt0 = Vec3V_From_Vec4V(f.rbXnXYZ_biasW);
const FloatV appliedForce = V4GetW(f.normalXYZ_appliedForceW);
const FloatV velMultiplier = V4GetW(f.raXnXYZ_velMultiplierW);
const FloatV targetVel = FLoad(f.targetVel);
const FloatV normalImpulse = FLoad(appliedImpulse[j]);//contacts[f.contactIndex].getAppliedForce();
const FloatV maxFriction = FMul(staticFriction, normalImpulse);
const FloatV nMaxFriction = FNeg(maxFriction);
//Compute the normal velocity of the constraint.
Vec3V rVel = V3MulAdd(linVel0, t0, V3Mul(angVel0, raXt0));
rVel = V3Sub(rVel, V3MulAdd(linVel1, t0, V3Mul(angVel1, rbXt0)));
const FloatV t0Vel = FAdd(V3SumElems(rVel), targetVel);
FloatV deltaF = FNeg(FMul(t0Vel, velMultiplier));
FloatV newForce = FAdd(appliedForce, deltaF);
newForce = FClamp(newForce, nMaxFriction, maxFriction);
deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(f.linDeltaVA, deltaF, linVel0);
angVel0 = V3ScaleAdd(f.angDeltaVA, deltaF, angVel0);
linVel1 = V3ScaleAdd(f.linDeltaVB, deltaF, linVel1);
angVel1 = V3ScaleAdd(f.angDeltaVB, deltaF, angVel1);
li0 = V3ScaleAdd(t0, deltaF, li0); ai0 = V3ScaleAdd(raXt0, deltaF, ai0);
li1 = V3ScaleAdd(t0, deltaF, li1); ai1 = V3ScaleAdd(rbXt0, deltaF, ai1);
f.setAppliedForce(newForce);
}
}
linImpulse0 = V3ScaleAdd(li0, FLoad(frictionHeader->invMass0D0), linImpulse0);
angImpulse0 = V3ScaleAdd(ai0, FLoad(frictionHeader->angDom0), angImpulse0);
linImpulse1 = V3NegScaleSub(li1, FLoad(frictionHeader->invMass1D1), linImpulse1);
angImpulse1 = V3NegScaleSub(ai1, FLoad(frictionHeader->angDom1), angImpulse1);
}
if(desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel0, desc.bodyA->linearVelocity);
V3StoreA(angVel0, desc.bodyA->angularState);
}
else
{
getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV);
}
if(desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
{
V3StoreA(linVel1, desc.bodyB->linearVelocity);
V3StoreA(angVel1, desc.bodyB->angularState);
}
else
{
getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV);
}
PX_ASSERT(currPtr == last);
}
void solveExtFrictionBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveExtFriction(desc[a], cache);
}
/*void solveExtFrictionConcludeBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
solveExtFriction(desc[a], cache);
}
}*/
void solveExtFrictionBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveExtFriction(desc[a], cache);
}
/*void solveConcludeExtContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveExtContactCoulomb(desc, cache);
concludeContactCoulomb(desc, cache);
}*/
void solveExtContactCoulombBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
solveExtContactCoulomb(desc[a], cache);
}
void solveExtContactCoulombConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
solveExtContactCoulomb(desc[a], cache);
concludeContactCoulomb(desc[a], cache);
}
}
void solveExtContactCoulombBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
for(PxU32 a = 0; a < constraintCount; ++a)
{
//PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::NO_LINK ? 0 : desc[a].bodyADataIndex];
//PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::NO_LINK ? 0 : desc[a].bodyBDataIndex];
PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? desc[a].bodyADataIndex : 0];
PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? desc[a].bodyBDataIndex : 0];
solveExtContactCoulomb(desc[a], cache);
writeBackContactCoulomb(desc[a], cache, bd0, bd1);
}
if(cache.mThresholdStreamIndex > 0)
{
//Not enough space to write 4 more thresholds back!
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
/*void solveConcludeContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveContactCoulomb(desc, cache);
concludeContactCoulomb(desc, cache);
}
void solveConcludeContactCoulomb_BStatic(const PxSolverConstraintDesc& desc, SolverContext& cache)
{
solveContactCoulomb_BStatic(desc, cache);
concludeContactCoulomb(desc, cache);
}*/
}
}
| 29,185 | C++ | 34.12154 | 163 | 0.748261 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContact4.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONTACT4_H
#define DY_SOLVER_CONTACT4_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "foundation/PxVecMath.h"
#include "DySolverContact.h"
namespace physx
{
namespace Sc
{
class ShapeInteraction;
}
namespace Dy
{
/**
\brief Batched SOA contact data. Note, we don't support batching with extended contacts for the simple reason that handling multiple articulations would be complex.
*/
struct SolverContactHeader4
{
enum
{
eHAS_MAX_IMPULSE = 1 << 0,
eHAS_TARGET_VELOCITY = 1 << 1
};
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 numNormalConstr;
PxU8 numFrictionConstr;
PxU8 flag;
PxU8 flags[4];
//These counts are the max of the 4 sets of data.
//When certain pairs have fewer patches/contacts than others, they are padded with 0s so that no work is performed but
//calculations are still shared (afterall, they're computationally free because we're doing 4 things at a time in SIMD)
//KS - used for write-back only
PxU8 numNormalConstr0, numNormalConstr1, numNormalConstr2, numNormalConstr3;
PxU8 numFrictionConstr0, numFrictionConstr1, numFrictionConstr2, numFrictionConstr3;
Vec4V restitution;
Vec4V staticFriction;
Vec4V dynamicFriction;
//Technically, these mass properties could be pulled out into a new structure and shared. For multi-manifold contacts,
//this would save 64 bytes per-manifold after the cost of the first manifold
Vec4V invMass0D0;
Vec4V invMass1D1;
Vec4V angDom0;
Vec4V angDom1;
//Normal is shared between all contacts in the batch. This will save some memory!
Vec4V normalX;
Vec4V normalY;
Vec4V normalZ;
Sc::ShapeInteraction* shapeInteraction[4]; //192 or 208
};
#if !PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactHeader4) == 192);
#else
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactHeader4) == 208);
#endif
/**
\brief This represents a batch of 4 contacts with static rolled into a single structure
*/
struct SolverContactBatchPointBase4
{
Vec4V raXnX;
Vec4V raXnY;
Vec4V raXnZ;
Vec4V velMultiplier;
Vec4V scaledBias;
Vec4V biasedErr;
Vec4V impulseMultiplier;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactBatchPointBase4) == 112);
/**
\brief Contains the additional data required to represent 4 contacts between 2 dynamic bodies
@see SolverContactBatchPointBase4
*/
struct SolverContactBatchPointDynamic4 : public SolverContactBatchPointBase4
{
Vec4V rbXnX;
Vec4V rbXnY;
Vec4V rbXnZ;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactBatchPointDynamic4) == 160);
/**
\brief This represents the shared information of a batch of 4 friction constraints
*/
struct SolverFrictionSharedData4
{
BoolV broken;
PxU8* frictionBrokenWritebackByte[4];
Vec4V normalX[2];
Vec4V normalY[2];
Vec4V normalZ[2];
};
#if !PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(SolverFrictionSharedData4) == 128);
#endif
/**
\brief This represents a batch of 4 friction constraints with static rolled into a single structure
*/
struct SolverContactFrictionBase4
{
Vec4V raXnX;
Vec4V raXnY;
Vec4V raXnZ;
Vec4V scaledBias;
Vec4V velMultiplier;
Vec4V targetVelocity;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactFrictionBase4) == 96);
/**
\brief Contains the additional data required to represent 4 friction constraints between 2 dynamic bodies
@see SolverContactFrictionBase4
*/
struct SolverContactFrictionDynamic4 : public SolverContactFrictionBase4
{
Vec4V rbXnX;
Vec4V rbXnY;
Vec4V rbXnZ;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactFrictionDynamic4) == 144);
}
}
#endif
| 5,310 | C | 30.058479 | 164 | 0.769115 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationPImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_ARTICULATION_INTERFACE_H
#define DY_ARTICULATION_INTERFACE_H
#include "DyArticulationUtils.h"
#include "DyFeatherstoneArticulation.h"
namespace physx
{
namespace Dy
{
struct ArticulationSolverDesc;
class ArticulationPImpl
{
public:
static PxU32 computeUnconstrainedVelocities(const ArticulationSolverDesc& desc,
PxReal dt,
PxU32& acCount,
const PxVec3& gravity,
Cm::SpatialVectorF* Z,
Cm::SpatialVectorF* deltaV,
const PxReal invLengthScale)
{
return FeatherstoneArticulation::computeUnconstrainedVelocities(desc, dt, acCount, gravity, Z, deltaV, invLengthScale);
}
static void updateBodies(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV,
PxReal dt)
{
FeatherstoneArticulation::updateBodies(desc, tempDeltaV, dt);
}
static void updateBodiesTGS(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV,
PxReal dt)
{
FeatherstoneArticulation::updateBodiesTGS(desc, tempDeltaV, dt);
}
static void saveVelocity(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* tempDeltaV)
{
FeatherstoneArticulation::saveVelocity(articulation, tempDeltaV);
}
static void saveVelocityTGS(FeatherstoneArticulation* articulation, PxReal invDtF32)
{
FeatherstoneArticulation::saveVelocityTGS(articulation, invDtF32);
}
static void computeUnconstrainedVelocitiesTGS(const ArticulationSolverDesc& desc,
PxReal dt,
const PxVec3& gravity, PxU64 contextID, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV,
const PxReal invLengthScale)
{
FeatherstoneArticulation::computeUnconstrainedVelocitiesTGS(desc, dt, gravity, contextID, Z, DeltaV, invLengthScale);
}
static void updateDeltaMotion(const ArticulationSolverDesc& desc, const PxReal dt, Cm::SpatialVectorF* DeltaV, const PxReal totalInvDt)
{
FeatherstoneArticulation::recordDeltaMotion(desc, dt, DeltaV, totalInvDt);
}
static void deltaMotionToMotionVel(const ArticulationSolverDesc& desc, const PxReal invDt)
{
FeatherstoneArticulation::deltaMotionToMotionVelocity(desc, invDt);
}
static PxU32 setupSolverInternalConstraintsTGS(const ArticulationSolverDesc& desc,
PxReal dt,
PxReal invDt,
PxReal totalDt,
PxU32& acCount,
Cm::SpatialVectorF* Z)
{
return FeatherstoneArticulation::setupSolverConstraintsTGS(desc, dt, invDt, totalDt, acCount, Z);
}
};
}
}
#endif
| 4,093 | C | 35.553571 | 136 | 0.770584 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactReduction.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CONTACT_REDUCTION_H
#define DY_CONTACT_REDUCTION_H
#include "geomutils/PxContactPoint.h"
#include "PxsMaterialManager.h"
namespace physx
{
namespace Dy
{
//KS - might be OK with 4 but 5 guarantees the deepest + 4 contacts that contribute to largest surface area
#define CONTACT_REDUCTION_MAX_CONTACTS 6
#define CONTACT_REDUCTION_MAX_PATCHES 32
#define PXS_NORMAL_TOLERANCE 0.995f
#define PXS_SEPARATION_TOLERANCE 0.001f
//A patch contains a normal, pair of material indices and a list of indices. These indices are
//used to index into the PxContact array that's passed by the user
struct ReducedContactPatch
{
PxU32 numContactPoints;
PxU32 contactPoints[CONTACT_REDUCTION_MAX_CONTACTS];
};
struct ContactPatch
{
PxVec3 rootNormal;
ContactPatch* mNextPatch;
PxReal maxPenetration;
PxU16 startIndex;
PxU16 stride;
PxU16 rootIndex;
PxU16 index;
};
struct SortBoundsPredicateManifold
{
bool operator()(const ContactPatch* idx1, const ContactPatch* idx2) const
{
return idx1->maxPenetration < idx2->maxPenetration;
}
};
template <PxU32 MaxPatches>
class ContactReduction
{
public:
ReducedContactPatch mPatches[MaxPatches];
PxU32 mNumPatches;
ContactPatch mIntermediatePatches[CONTACT_REDUCTION_MAX_PATCHES];
ContactPatch* mIntermediatePatchesPtrs[CONTACT_REDUCTION_MAX_PATCHES];
PxU32 mNumIntermediatePatches;
PxContactPoint* PX_RESTRICT mOriginalContacts;
PxsMaterialInfo* PX_RESTRICT mMaterialInfo;
PxU32 mNumOriginalContacts;
ContactReduction(PxContactPoint* PX_RESTRICT originalContacts, PxsMaterialInfo* PX_RESTRICT materialInfo, PxU32 numContacts) :
mNumPatches(0), mNumIntermediatePatches(0), mOriginalContacts(originalContacts), mMaterialInfo(materialInfo), mNumOriginalContacts(numContacts)
{
}
void reduceContacts()
{
//First pass, break up into contact patches, storing the start and stride of the patches
//We will need to have contact patches and then coallesce them
mIntermediatePatches[0].rootNormal = mOriginalContacts[0].normal;
mIntermediatePatches[0].mNextPatch = NULL;
mIntermediatePatches[0].startIndex = 0;
mIntermediatePatches[0].rootIndex = 0;
mIntermediatePatches[0].maxPenetration = mOriginalContacts[0].separation;
mIntermediatePatches[0].index = 0;
PxU16 numPatches = 1;
//PxU32 startIndex = 0;
PxU32 numUniquePatches = 1;
PxU16 m = 1;
for(; m < mNumOriginalContacts; ++m)
{
PxI32 index = -1;
for(PxU32 b = numPatches; b > 0; --b)
{
ContactPatch& patch = mIntermediatePatches[b-1];
if(mMaterialInfo[patch.startIndex].mMaterialIndex0 == mMaterialInfo[m].mMaterialIndex0 && mMaterialInfo[patch.startIndex].mMaterialIndex1 == mMaterialInfo[m].mMaterialIndex1 &&
patch.rootNormal.dot(mOriginalContacts[m].normal) >= PXS_NORMAL_TOLERANCE)
{
index = PxI32(b-1);
break;
}
}
if(index != numPatches - 1)
{
mIntermediatePatches[numPatches-1].stride = PxU16(m - mIntermediatePatches[numPatches - 1].startIndex);
//Create a new patch...
if(numPatches == CONTACT_REDUCTION_MAX_PATCHES)
{
break;
}
mIntermediatePatches[numPatches].startIndex = m;
mIntermediatePatches[numPatches].mNextPatch = NULL;
if(index == -1)
{
mIntermediatePatches[numPatches].rootIndex = numPatches;
mIntermediatePatches[numPatches].rootNormal = mOriginalContacts[m].normal;
mIntermediatePatches[numPatches].maxPenetration = mOriginalContacts[m].separation;
mIntermediatePatches[numPatches].index = numPatches;
++numUniquePatches;
}
else
{
//Find last element in the link
PxU16 rootIndex = mIntermediatePatches[index].rootIndex;
mIntermediatePatches[index].mNextPatch = &mIntermediatePatches[numPatches];
mIntermediatePatches[numPatches].rootNormal = mIntermediatePatches[index].rootNormal;
mIntermediatePatches[rootIndex].maxPenetration = mIntermediatePatches[numPatches].maxPenetration = PxMin(mIntermediatePatches[rootIndex].maxPenetration, mOriginalContacts[m].separation);
mIntermediatePatches[numPatches].rootIndex = rootIndex;
mIntermediatePatches[numPatches].index = numPatches;
}
++numPatches;
}
}
mIntermediatePatches[numPatches-1].stride = PxU16(m - mIntermediatePatches[numPatches-1].startIndex);
//OK, we have a list of contact patches so that we can start contact reduction per-patch
//OK, now we can go and reduce the contacts on a per-patch basis...
for(PxU32 a = 0; a < numPatches; ++a)
{
mIntermediatePatchesPtrs[a] = &mIntermediatePatches[a];
}
SortBoundsPredicateManifold predicate;
PxSort(mIntermediatePatchesPtrs, numPatches, predicate);
PxU32 numReducedPatches = 0;
for(PxU32 a = 0; a < numPatches; ++a)
{
if(mIntermediatePatchesPtrs[a]->rootIndex == mIntermediatePatchesPtrs[a]->index)
{
//Reduce this patch...
if(numReducedPatches == MaxPatches)
break;
ReducedContactPatch& reducedPatch = mPatches[numReducedPatches++];
//OK, now we need to work out if we have to reduce patches...
PxU32 contactCount = 0;
{
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
contactCount += tmpPatch->stride;
tmpPatch = tmpPatch->mNextPatch;
}
}
if(contactCount <= CONTACT_REDUCTION_MAX_CONTACTS)
{
//Just add the contacts...
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
PxU32 ind = 0;
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
reducedPatch.contactPoints[ind++] = tmpPatch->startIndex + b;
}
tmpPatch = tmpPatch->mNextPatch;
}
reducedPatch.numContactPoints = contactCount;
}
else
{
//Iterate through and find the most extreme point
PxU32 ind = 0;
{
PxReal dist = 0.f;
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
PxReal magSq = mOriginalContacts[tmpPatch->startIndex + b].point.magnitudeSquared();
if(dist < magSq)
{
ind = tmpPatch->startIndex + b;
dist = magSq;
}
}
tmpPatch = tmpPatch->mNextPatch;
}
}
reducedPatch.contactPoints[0] = ind;
const PxVec3 p0 = mOriginalContacts[ind].point;
//Now find the point farthest from this point...
{
PxReal maxDist = 0.f;
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
PxReal magSq = (p0 - mOriginalContacts[tmpPatch->startIndex + b].point).magnitudeSquared();
if(magSq > maxDist)
{
ind = tmpPatch->startIndex + b;
maxDist = magSq;
}
}
tmpPatch = tmpPatch->mNextPatch;
}
}
reducedPatch.contactPoints[1] = ind;
const PxVec3 p1 = mOriginalContacts[ind].point;
//Now find the point farthest from the segment
PxVec3 n = (p0 - p1).cross(mIntermediatePatchesPtrs[a]->rootNormal);
//PxReal tVal = 0.f;
{
PxReal maxDist = 0.f;
//PxReal tmpTVal;
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
//PxReal magSq = tmpDistancePointSegmentSquared(p0, p1, mOriginalContacts[tmpPatch->startIndex + b].point, tmpTVal);
PxReal magSq = (mOriginalContacts[tmpPatch->startIndex + b].point - p0).dot(n);
if(magSq > maxDist)
{
ind = tmpPatch->startIndex + b;
//tVal = tmpTVal;
maxDist = magSq;
}
}
tmpPatch = tmpPatch->mNextPatch;
}
}
reducedPatch.contactPoints[2] = ind;
//const PxVec3 closest = (p0 + (p1 - p0) * tVal);
const PxVec3 dir = -n;//closest - p3;
{
PxReal maxDist = 0.f;
//PxReal tVal = 0.f;
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
PxReal magSq = (mOriginalContacts[tmpPatch->startIndex + b].point - p0).dot(dir);
if(magSq > maxDist)
{
ind = tmpPatch->startIndex + b;
maxDist = magSq;
}
}
tmpPatch = tmpPatch->mNextPatch;
}
}
reducedPatch.contactPoints[3] = ind;
//Now, we iterate through all the points, and cluster the points. From this, we establish the deepest point that's within a
//tolerance of this point and keep that point
PxReal separation[CONTACT_REDUCTION_MAX_CONTACTS];
PxU32 deepestInd[CONTACT_REDUCTION_MAX_CONTACTS];
for(PxU32 i = 0; i < 4; ++i)
{
PxU32 index = reducedPatch.contactPoints[i];
separation[i] = mOriginalContacts[index].separation - PXS_SEPARATION_TOLERANCE;
deepestInd[i] = index;
}
ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
PxContactPoint& point = mOriginalContacts[tmpPatch->startIndex + b];
PxReal distance = PX_MAX_REAL;
PxU32 index = 0;
for(PxU32 c = 0; c < 4; ++c)
{
PxVec3 dif = mOriginalContacts[reducedPatch.contactPoints[c]].point - point.point;
PxReal d = dif.magnitudeSquared();
if(distance > d)
{
distance = d;
index = c;
}
}
if(separation[index] > point.separation)
{
deepestInd[index] = tmpPatch->startIndex+b;
separation[index] = point.separation;
}
}
tmpPatch = tmpPatch->mNextPatch;
}
bool chosen[64];
PxMemZero(chosen, sizeof(chosen));
for(PxU32 i = 0; i < 4; ++i)
{
reducedPatch.contactPoints[i] = deepestInd[i];
chosen[deepestInd[i]] = true;
}
for(PxU32 i = 4; i < CONTACT_REDUCTION_MAX_CONTACTS; ++i)
{
separation[i] = PX_MAX_REAL;
deepestInd[i] = 0;
}
tmpPatch = mIntermediatePatchesPtrs[a];
while(tmpPatch)
{
for(PxU32 b = 0; b < tmpPatch->stride; ++b)
{
if(!chosen[tmpPatch->startIndex+b])
{
PxContactPoint& point = mOriginalContacts[tmpPatch->startIndex + b];
for(PxU32 j = 4; j < CONTACT_REDUCTION_MAX_CONTACTS; ++j)
{
if(point.separation < separation[j])
{
for(PxU32 k = CONTACT_REDUCTION_MAX_CONTACTS-1; k > j; --k)
{
separation[k] = separation[k-1];
deepestInd[k] = deepestInd[k-1];
}
separation[j] = point.separation;
deepestInd[j] = tmpPatch->startIndex+b;
break;
}
}
}
}
tmpPatch = tmpPatch->mNextPatch;
}
for(PxU32 i = 4; i < CONTACT_REDUCTION_MAX_CONTACTS; ++i)
{
reducedPatch.contactPoints[i] = deepestInd[i];
}
reducedPatch.numContactPoints = CONTACT_REDUCTION_MAX_CONTACTS;
}
}
}
mNumPatches = numReducedPatches;
}
};
}
}
#endif
| 13,097 | C | 31.02445 | 192 | 0.647095 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSDynamics.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxTime.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxSIMDHelpers.h"
#include "PxvDynamics.h"
#include "common/PxProfileZone.h"
#include "PxsRigidBody.h"
#include "PxsContactManager.h"
#include "DyTGSDynamics.h"
#include "DyBodyCoreIntegrator.h"
#include "DySolverCore.h"
#include "DySolverControl.h"
#include "DySolverContact.h"
#include "DySolverContactPF.h"
#include "DyArticulationContactPrep.h"
#include "DySolverBody.h"
#include "DyConstraintPrep.h"
#include "DyConstraintPartition.h"
#include "CmFlushPool.h"
#include "DyArticulationPImpl.h"
#include "PxsMaterialManager.h"
#include "DySolverContactPF4.h"
#include "DyContactReduction.h"
#include "PxcNpContactPrepShared.h"
#include "DyContactPrep.h"
#include "DySolverControlPF.h"
#include "PxSceneDesc.h"
#include "PxsSimpleIslandManager.h"
#include "PxvNphaseImplementationContext.h"
#include "PxsContactManagerState.h"
#include "DyContactPrepShared.h"
#include "DySolverContext.h"
#include "DyDynamics.h"
#include "DySolverConstraint1D.h"
#include "PxvSimStats.h"
#include "DyTGSContactPrep.h"
#include "DyFeatherstoneArticulation.h"
#include "DySleep.h"
#include "DyTGS.h"
#define PX_USE_BLOCK_SOLVER 1
#define PX_USE_BLOCK_1D 1
namespace physx
{
namespace Dy
{
static inline void waitForBodyProgress(PxTGSSolverBodyVel& body, PxU32 desiredProgress, PxU32 iteration)
{
const PxI32 target = PxI32(desiredProgress + body.maxDynamicPartition * iteration);
volatile PxI32* progress = reinterpret_cast<PxI32*>(&body.partitionMask);
WAIT_FOR_PROGRESS(progress, target);
}
static inline void incrementBodyProgress(PxTGSSolverBodyVel& body)
{
if (body.maxDynamicPartition != 0)
(*reinterpret_cast<volatile PxU32*>(&body.partitionMask))++;
}
static inline void waitForArticulationProgress(Dy::FeatherstoneArticulation& artic, PxU32 desiredProgress, PxU32 iteration)
{
const PxI32 target = PxI32(desiredProgress + artic.maxSolverFrictionProgress * iteration);
volatile PxI32* progress = reinterpret_cast<PxI32*>(&artic.solverProgress);
WAIT_FOR_PROGRESS(progress, target);
}
static inline void incrementArticulationProgress(Dy::FeatherstoneArticulation& artic)
{
(*reinterpret_cast<volatile PxU32*>(&artic.solverProgress))++;
}
static inline void waitForProgresses(const PxSolverConstraintDesc& desc, PxU32 iteration)
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
waitForBodyProgress(*desc.tgsBodyA, desc.progressA, iteration);
else
waitForArticulationProgress(*getArticulationA(desc), desc.progressA, iteration);
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
waitForBodyProgress(*desc.tgsBodyB, desc.progressB, iteration);
else
waitForArticulationProgress(*getArticulationB(desc), desc.progressB, iteration);
}
static inline void incrementProgress(const PxSolverConstraintDesc& desc)
{
if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY)
{
incrementBodyProgress(*desc.tgsBodyA);
}
else
incrementArticulationProgress(*getArticulationA(desc));
if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY)
incrementBodyProgress(*desc.tgsBodyB);
else if(desc.articulationA != desc.articulationB)
incrementArticulationProgress(*getArticulationB(desc));
}
Context* createTGSDynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool,
PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback,
PxsMaterialManager* materialManager, IG::SimpleIslandManager* islandManager, PxU64 contextID,
bool enableStabilization, bool useEnhancedDeterminism,
PxReal lengthScale)
{
return PX_NEW(DynamicsTGSContext)( memBlockPool, scratchAllocator, taskPool, simStats, taskManager, allocatorCallback, materialManager, islandManager, contextID,
enableStabilization, useEnhancedDeterminism, lengthScale);
}
void DynamicsTGSContext::destroy()
{
this->~DynamicsTGSContext();
PX_FREE_THIS;
}
void DynamicsTGSContext::resetThreadContexts()
{
PxcThreadCoherentCacheIterator<ThreadContext, PxcNpMemBlockPool> threadContextIt(mThreadContextPool);
ThreadContext* threadContext = threadContextIt.getNext();
while (threadContext != NULL)
{
threadContext->reset();
threadContext = threadContextIt.getNext();
}
}
PX_FORCE_INLINE PxVec3 safeRecip(const PxVec3& v)
{
return PxVec3(v.x == 0.f ? 0.f : 1.f/v.x, v.y == 0.f ? 0.f : 1.f/v.y, v.z == 0.f ? 0.f : 1.f/v.z);
}
void copyToSolverBodyDataStep(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold,
PxReal maxAngVelSq, PxU32 lockFlags, bool isKinematic,
PxTGSSolverBodyVel& solverVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData, PxReal dt,
bool gyroscopicForces)
{
const PxMat33Padded rotation(globalPose.q);
const PxVec3 sqrtInvInertia = computeSafeSqrtInertia(invInertia);
const PxVec3 sqrtBodySpaceInertia = safeRecip(sqrtInvInertia);
Cm::transformInertiaTensor(sqrtInvInertia, rotation, solverBodyTxInertia.sqrtInvInertia);
solverBodyTxInertia.deltaBody2World.p = globalPose.p;
solverBodyTxInertia.deltaBody2World.q = PxQuat(PxIdentity);
PxMat33 sqrtInertia;
Cm::transformInertiaTensor(sqrtBodySpaceInertia, rotation, sqrtInertia);
PxVec3 lv = linearVelocity;
PxVec3 av = angularVelocity;
if (gyroscopicForces)
{
const PxVec3 localInertia(
invInertia.x == 0.f ? 0.f : 1.f / invInertia.x,
invInertia.y == 0.f ? 0.f : 1.f / invInertia.y,
invInertia.z == 0.f ? 0.f : 1.f / invInertia.z);
PxVec3 localAngVel = globalPose.q.rotateInv(av);
PxVec3 origMom = localInertia.multiply(localAngVel);
PxVec3 torque = -localAngVel.cross(origMom);
PxVec3 newMom = origMom + torque * dt;
const PxReal denom = newMom.magnitude();
PxReal ratio = denom > 0.f ? origMom.magnitude() / denom : 0.f;
newMom *= ratio;
PxVec3 newDeltaAngVel = globalPose.q.rotate(invInertia.multiply(newMom) - localAngVel);
av += newDeltaAngVel;
}
if (lockFlags)
{
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
lv.x = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
lv.y = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
lv.z = 0.f;
//KS - technically, we can zero the inertia columns and produce stiffer constraints. However, this can cause numerical issues with the
//joint solver, which is fixed by disabling joint preprocessing and setting minResponseThreshold to some reasonable value > 0. However, until
//this is handled automatically, it's probably better not to zero these inertia rows
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
{
av.x = 0.f;
//data.sqrtInvInertia.column0 = PxVec3(0.f);
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
{
av.y = 0.f;
//data.sqrtInvInertia.column1 = PxVec3(0.f);
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
{
av.z = 0.f;
//data.sqrtInvInertia.column2 = PxVec3(0.f);
}
}
solverVel.linearVelocity = lv;
solverVel.angularVelocity = sqrtInertia * av;
solverVel.deltaLinDt = PxVec3(0.f);
solverVel.deltaAngDt = PxVec3(0.f);
solverVel.lockFlags = PxU16(lockFlags);
solverVel.isKinematic = isKinematic;
solverVel.maxAngVel = PxSqrt(maxAngVelSq);
solverVel.partitionMask = 0;
solverBodyData.nodeIndex = nodeIndex;
solverBodyData.invMass = invMass;
solverBodyData.penBiasClamp = maxDepenetrationVelocity;
solverBodyData.maxContactImpulse = maxContactImpulse;
solverBodyData.reportThreshold = reportThreshold;
solverBodyData.originalLinearVelocity = lv;
solverBodyData.originalAngularVelocity = av;
PX_ASSERT(lv.isFinite());
PX_ASSERT(av.isFinite());
}
void copyToSolverBodyDataStepKinematic(const PxVec3& linearVelocity, const PxVec3& angularVelocity, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold, PxReal maxAngVelSq,
PxTGSSolverBodyVel& solverVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData)
{
const PxMat33Padded rotation(globalPose.q);
solverBodyTxInertia.deltaBody2World.p = globalPose.p;
solverBodyTxInertia.deltaBody2World.q = PxQuat(PxIdentity);
solverBodyTxInertia.sqrtInvInertia = PxMat33(PxVec3(0.f), PxVec3(0.f), PxVec3(0.f));
solverVel.linearVelocity = PxVec3(0.f);
solverVel.angularVelocity = PxVec3(0.f);
solverVel.deltaLinDt = PxVec3(0.f);
solverVel.deltaAngDt = PxVec3(0.f);
solverVel.lockFlags = 0;
solverVel.isKinematic = true;
solverVel.maxAngVel = PxSqrt(maxAngVelSq);
solverVel.partitionMask = 0;
solverVel.nbStaticInteractions = 0;
solverVel.maxDynamicPartition = 0;
solverBodyData.nodeIndex = nodeIndex;
solverBodyData.invMass = 0.f;
solverBodyData.penBiasClamp = maxDepenetrationVelocity;
solverBodyData.maxContactImpulse = maxContactImpulse;
solverBodyData.reportThreshold = reportThreshold;
solverBodyData.originalLinearVelocity = linearVelocity;
solverBodyData.originalAngularVelocity = angularVelocity;
}
// =========================== Basic methods
DynamicsTGSContext::DynamicsTGSContext( PxcNpMemBlockPool* memBlockPool,
PxcScratchAllocator& scratchAllocator,
Cm::FlushPool& taskPool,
PxvSimStats& simStats,
PxTaskManager* taskManager,
PxVirtualAllocatorCallback* allocatorCallback,
PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager,
PxU64 contextID,
bool enableStabilization,
bool useEnhancedDeterminism,
PxReal lengthScale) :
Dy::Context (islandManager, allocatorCallback, simStats, enableStabilization, useEnhancedDeterminism, PX_MAX_F32, lengthScale, contextID),
// PT: TODO: would make sense to move all the following members to the base class but include paths get in the way atm
mThreadContextPool (memBlockPool),
mMaterialManager (materialManager),
mScratchAllocator (scratchAllocator),
mTaskPool (taskPool),
mTaskManager (taskManager)
{
createThresholdStream(*allocatorCallback);
createForceChangeThresholdStream(*allocatorCallback);
mExceededForceThresholdStream[0] = PX_NEW(ThresholdStream)(*allocatorCallback);
mExceededForceThresholdStream[1] = PX_NEW(ThresholdStream)(*allocatorCallback);
mThresholdStreamOut = 0;
mCurrentIndex = 0;
PxMemZero(&mWorldSolverBodyVel, sizeof(mWorldSolverBodyVel));
mWorldSolverBodyVel.lockFlags = 0;
mWorldSolverBodyVel.isKinematic = false;
mWorldSolverBodyTxInertia.sqrtInvInertia = PxMat33(PxZero);
mWorldSolverBodyTxInertia.deltaBody2World = PxTransform(PxIdentity);
mWorldSolverBodyData2.penBiasClamp = -PX_MAX_REAL;
mWorldSolverBodyData2.maxContactImpulse = PX_MAX_REAL;
mWorldSolverBodyData2.nodeIndex = PX_INVALID_NODE;
mWorldSolverBodyData2.invMass = 0;
mWorldSolverBodyData2.reportThreshold = PX_MAX_REAL;
mWorldSolverBodyData2.originalLinearVelocity = PxVec3(0.f);
mWorldSolverBodyData2.originalAngularVelocity = PxVec3(0.f);
}
DynamicsTGSContext::~DynamicsTGSContext()
{
PX_DELETE(mExceededForceThresholdStream[1]);
PX_DELETE(mExceededForceThresholdStream[0]);
}
void DynamicsTGSContext::setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim,
const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies)
{
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0);
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1);
const PxU32 offsetMap[] = { solverBodyOffset, 0 };
//const PxU32 offsetMap[] = {mKinematicCount, 0};
if (constraint.indexType0 == PxsIndexedInteraction::eARTICULATION)
{
const PxNodeIndex& nodeIndex0 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation0);
const IG::Node& node0 = islandSim.getNode(nodeIndex0);
desc.articulationA = node0.getArticulation();
desc.linkIndexA = nodeIndex0.articulationLinkId();
desc.bodyADataIndex = 0;
}
else
{
desc.tgsBodyA = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBodyVel
: &solverBodies[PxU32(constraint.solverBody0) + offsetMap[constraint.indexType0] + 1];
desc.bodyADataIndex = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? 0
: PxU32(constraint.solverBody0) + offsetMap[constraint.indexType0] + 1;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
if (constraint.indexType1 == PxsIndexedInteraction::eARTICULATION)
{
const PxNodeIndex& nodeIndex1 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation1);
const IG::Node& node1 = islandSim.getNode(nodeIndex1);
desc.articulationB = node1.getArticulation();
desc.linkIndexB = nodeIndex1.articulationLinkId();// PxTo8(getLinkIndex(constraint.articulation1));
desc.bodyBDataIndex = 0;
}
else
{
desc.tgsBodyB = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBodyVel
: &solverBodies[PxU32(constraint.solverBody1) + offsetMap[constraint.indexType1] + 1];
desc.bodyBDataIndex = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? 0
: PxU32(constraint.solverBody1) + offsetMap[constraint.indexType1] + 1;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
}
void DynamicsTGSContext::setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex, const IG::SimpleIslandManager& islandManager,
PxU32* bodyRemap, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies)
{
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0);
PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1);
const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim();
PxNodeIndex node1 = islandSim.getNodeIndex1(edgeIndex);
if (node1.isStaticBody())
{
desc.tgsBodyA = &mWorldSolverBodyVel;
desc.bodyADataIndex = 0;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
else
{
const IG::Node& node = islandSim.getNode(node1);
if (node.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
PX_ASSERT(node1.isArticulation());
Dy::FeatherstoneArticulation* a = islandSim.getLLArticulation(node1);
PxU8 type;
a->fillIndexType(node1.articulationLinkId(),type);
if (type == PxsIndexedInteraction::eARTICULATION)
{
desc.articulationA = a;
desc.linkIndexA = node1.articulationLinkId();
}
else
{
desc.tgsBodyA = &mWorldSolverBodyVel;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
desc.bodyADataIndex = 0;
}
else
{
PX_ASSERT(!node1.isArticulation());
PxU32 activeIndex = islandSim.getActiveNodeIndex(node1);
PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset;
desc.tgsBodyA = &solverBodies[index + 1];
desc.bodyADataIndex = index + 1;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
}
}
PxNodeIndex node2 = islandSim.getNodeIndex2(edgeIndex);
if (node2.isStaticBody())
{
desc.tgsBodyB = &mWorldSolverBodyVel;
desc.bodyBDataIndex = 0;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
else
{
const IG::Node& node = islandSim.getNode(node2);
if (node.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
PX_ASSERT(node2.isArticulation());
Dy::FeatherstoneArticulation* b = islandSim.getLLArticulation(node2);
PxU8 type;
b->fillIndexType(node2.articulationLinkId(), type);
if (type == PxsIndexedInteraction::eARTICULATION)
{
desc.articulationB = b;
desc.linkIndexB = node2.articulationLinkId();
}
else
{
desc.tgsBodyB = &mWorldSolverBodyVel;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
desc.bodyBDataIndex = 0;
}
else
{
PX_ASSERT(!node2.isArticulation());
PxU32 activeIndex = islandSim.getActiveNodeIndex(node2);
PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset;
desc.tgsBodyB = &solverBodies[index + 1];
desc.bodyBDataIndex = index + 1;
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
}
}
}
namespace
{
class DynamicsMergeTask : public Cm::Task
{
PxBaseTask* mSecondContinuation;
public:
DynamicsMergeTask(PxU64 contextId) : Cm::Task(contextId), mSecondContinuation(NULL)
{
}
void setSecondContinuation(PxBaseTask* task) { task->addReference(); mSecondContinuation = task; }
virtual const char* getName() const { return "MergeTask"; }
virtual void runInternal()
{
}
virtual void release()
{
mSecondContinuation->removeReference();
Cm::Task::release();
}
};
class KinematicCopyTGSTask : public Cm::Task
{
const PxNodeIndex* const mKinematicIndices;
const PxU32 mNbKinematics;
const IG::IslandSim& mIslandSim;
PxTGSSolverBodyVel* mVels;
PxTGSSolverBodyTxInertia* mInertia;
PxTGSSolverBodyData* mBodyData;
PX_NOCOPY(KinematicCopyTGSTask)
public:
static const PxU32 NbKinematicsPerTask = 1024;
KinematicCopyTGSTask(const PxNodeIndex* const kinematicIndices,
PxU32 nbKinematics, const IG::IslandSim& islandSim, PxTGSSolverBodyVel* vels,
PxTGSSolverBodyTxInertia* inertias, PxTGSSolverBodyData* datas, PxU64 contextID) : Cm::Task(contextID),
mKinematicIndices(kinematicIndices), mNbKinematics(nbKinematics),
mIslandSim(islandSim), mVels(vels), mInertia(inertias), mBodyData(datas)
{
}
virtual const char* getName() const { return "KinematicCopyTask"; }
virtual void runInternal()
{
for (PxU32 i = 0; i<mNbKinematics; i++)
{
PxsRigidBody* rigidBody = mIslandSim.getRigidBody(mKinematicIndices[i]);
const PxsBodyCore& core = rigidBody->getCore();
copyToSolverBodyDataStepKinematic(core.linearVelocity, core.angularVelocity, core.body2World, core.maxPenBias,
core.maxContactImpulse, mKinematicIndices[i].index(), core.contactReportThreshold, core.maxAngularVelocitySq,
mVels[i], mInertia[i], mBodyData[i]);
rigidBody->saveLastCCDTransform();
}
}
};
class UpdateContinuationTGSTask : public Cm::Task
{
DynamicsTGSContext& mContext;
IG::SimpleIslandManager& mSimpleIslandManager;
PxBaseTask* mLostTouchTask;
PxU32 mMaxArticulationLinks;
PX_NOCOPY(UpdateContinuationTGSTask)
public:
UpdateContinuationTGSTask(DynamicsTGSContext& context,
IG::SimpleIslandManager& simpleIslandManager,
PxBaseTask* lostTouchTask, PxU64 contextID, PxU32 maxLinks) :
Cm::Task(contextID), mContext(context), mSimpleIslandManager(simpleIslandManager),
mLostTouchTask(lostTouchTask), mMaxArticulationLinks(maxLinks)
{
}
virtual const char* getName() const { return "UpdateContinuationTask";}
virtual void runInternal()
{
mContext.updatePostKinematic(mSimpleIslandManager, mCont, mLostTouchTask, mMaxArticulationLinks);
//Allow lost touch task to run once all tasks have be scheduled
mLostTouchTask->removeReference();
}
};
}
void DynamicsTGSContext::update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask,
PxvNphaseImplementationContext* nphase,
PxU32 /*maxPatchesPerCM*/, PxU32 maxArticulationLinks,
PxReal dt, const PxVec3& gravity, PxBitMapPinned& /*changedHandleMap*/)
{
PX_PROFILE_ZONE("Dynamics.solverQueueTasks", mContextID);
PX_UNUSED(simpleIslandManager);
mOutputIterator = nphase->getContactManagerOutputs();
// PT: TODO: refactor
mDt = dt;
mInvDt = 1.0f / dt;
mGravity = gravity;
const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim();
const PxU32 islandCount = islandSim.getNbActiveIslands();
const PxU32 activatedContactCount = islandSim.getNbActivatedEdges(IG::Edge::eCONTACT_MANAGER);
const IG::EdgeIndex* const activatingEdges = islandSim.getActivatedEdges(IG::Edge::eCONTACT_MANAGER);
for (PxU32 a = 0; a < activatedContactCount; ++a)
{
PxsContactManager* cm = simpleIslandManager.getContactManager(activatingEdges[a]);
if (cm)
cm->getWorkUnit().frictionPatchCount = 0; //KS - zero the friction patch count on any activating edges
}
#if PX_ENABLE_SIM_STATS
if (islandCount > 0)
{
mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics();
mSimStats.mNbActiveDynamicBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE);
mSimStats.mNbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT);
}
else
{
mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics();
mSimStats.mNbActiveDynamicBodies = 0;
mSimStats.mNbActiveConstraints = 0;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
mThresholdStreamOut = 0;
resetThreadContexts();
//If there is no work to do then we can do nothing at all.
if(!islandCount)
return;
//Block to make sure it doesn't run before stage2 of update!
lostTouchTask->addReference();
UpdateContinuationTGSTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(UpdateContinuationTGSTask)), UpdateContinuationTGSTask)
(*this, simpleIslandManager, lostTouchTask, mContextID, maxArticulationLinks);
task->setContinuation(continuation);
//KS - test that world solver body's velocities are finite and 0, then set it to 0.
//Technically, the velocity should always be 0 but can be stomped if a NAN creeps into the simulation.
PX_ASSERT(mWorldSolverBodyVel.linearVelocity == PxVec3(0.f));
PX_ASSERT(mWorldSolverBodyVel.angularVelocity == PxVec3(0.f));
PX_ASSERT(mWorldSolverBodyVel.linearVelocity.isFinite());
PX_ASSERT(mWorldSolverBodyVel.angularVelocity.isFinite());
mWorldSolverBodyVel.linearVelocity = mWorldSolverBodyVel.angularVelocity = PxVec3(0.f);
const PxU32 kinematicCount = islandSim.getNbActiveKinematics();
const PxNodeIndex* const kinematicIndices = islandSim.getActiveKinematics();
mKinematicCount = kinematicCount;
const PxU32 bodyCount = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE);
PxU32 numArtics = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE);
{
if (kinematicCount + bodyCount > mSolverBodyVelPool.capacity())
{
mSolverBodyRemapTable.reserve((kinematicCount + bodyCount + 31 + 1) & ~31);
mSolverBodyVelPool.reserve((kinematicCount + bodyCount +31 + 1) & ~31);
mSolverBodyTxInertiaPool.reserve((kinematicCount + bodyCount +31 + 1) & ~31);
mSolverBodyDataPool2.reserve((kinematicCount + bodyCount +31 + 1) & ~31);
}
{
mSolverBodyVelPool.resize(kinematicCount + bodyCount +1);
mSolverBodyTxInertiaPool.resize(kinematicCount + bodyCount +1);
mSolverBodyDataPool2.resize(kinematicCount + bodyCount +1);
mSolverBodyRemapTable.resize(kinematicCount + bodyCount + 1);
}
// integrate and copy all the kinematics - overkill, since not all kinematics
// need solver bodies
mSolverBodyVelPool[0] = mWorldSolverBodyVel;
mSolverBodyTxInertiaPool[0] = mWorldSolverBodyTxInertia;
mSolverBodyDataPool2[0] = mWorldSolverBodyData2;
if(kinematicCount)
{
PX_PROFILE_ZONE("Dynamics.updateKinematics", mContextID);
// PT: TODO: why no PxMemZero here compared to PGS?
for (PxU32 i = 0; i < kinematicCount; i+= KinematicCopyTGSTask::NbKinematicsPerTask)
{
const PxU32 nbToProcess = PxMin(kinematicCount - i, KinematicCopyTGSTask::NbKinematicsPerTask);
KinematicCopyTGSTask* kinematicTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(KinematicCopyTGSTask)), KinematicCopyTGSTask)
(kinematicIndices + i, nbToProcess, islandSim, &mSolverBodyVelPool[i+1],
&mSolverBodyTxInertiaPool[i + 1], &mSolverBodyDataPool2[i + 1], mContextID);
kinematicTask->setContinuation(task);
kinematicTask->removeReference();
}
}
}
const PxU32 numArticulationConstraints = numArtics* maxArticulationLinks; //Just allocate enough memory to fit worst-case maximum size articulations...
const PxU32 nbActiveContactManagers = islandSim.getNbActiveEdges(IG::Edge::eCONTACT_MANAGER);
const PxU32 nbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT);
const PxU32 totalConstraintCount = nbActiveConstraints + nbActiveContactManagers + numArticulationConstraints;
mSolverConstraintDescPool.forceSize_Unsafe(0);
mSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63));
mSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount);
mOrderedSolverConstraintDescPool.forceSize_Unsafe(0);
mOrderedSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63));
mOrderedSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount);
mContactConstraintBatchHeaders.forceSize_Unsafe(0);
mContactConstraintBatchHeaders.reserve((totalConstraintCount + 63) & (~63));
mContactConstraintBatchHeaders.forceSize_Unsafe(totalConstraintCount);
mTempSolverConstraintDescPool.forceSize_Unsafe(0);
mTempSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63));
mTempSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount);
mContactList.forceSize_Unsafe(0);
mContactList.reserve((nbActiveContactManagers + 63u) & (~63u));
mContactList.forceSize_Unsafe(nbActiveContactManagers);
mMotionVelocityArray.forceSize_Unsafe(0);
mMotionVelocityArray.reserve((bodyCount + 63u) & (~63u));
mMotionVelocityArray.forceSize_Unsafe(bodyCount);
mBodyCoreArray.forceSize_Unsafe(0);
mBodyCoreArray.reserve((bodyCount + 63u) & (~63u));
mBodyCoreArray.forceSize_Unsafe(bodyCount);
mRigidBodyArray.forceSize_Unsafe(0);
mRigidBodyArray.reserve((bodyCount + 63u) & (~63u));
mRigidBodyArray.forceSize_Unsafe(bodyCount);
mArticulationArray.forceSize_Unsafe(0);
mArticulationArray.reserve((numArtics + 63u) & (~63u));
mArticulationArray.forceSize_Unsafe(numArtics);
mNodeIndexArray.forceSize_Unsafe(0);
mNodeIndexArray.reserve((bodyCount + 63u) & (~63u));
mNodeIndexArray.forceSize_Unsafe(bodyCount);
ThresholdStream& stream = getThresholdStream();
stream.forceSize_Unsafe(0);
stream.reserve(PxNextPowerOfTwo(nbActiveContactManagers != 0 ? nbActiveContactManagers - 1 : nbActiveContactManagers));
//flip exceeded force threshold buffer
mCurrentIndex = 1 - mCurrentIndex;
task->removeReference();
}
void DynamicsTGSContext::updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxU32 maxLinks)
{
const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim();
const IG::IslandId*const islandIds = islandSim.getActiveIslands();
DynamicsMergeTask* mergeTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(DynamicsMergeTask)), DynamicsMergeTask)(mContextID);
mergeTask->setContinuation(continuation);
mergeTask->setSecondContinuation(lostTouchTask);
PxU32 currentIsland = 0;
PxU32 currentBodyIndex = 0;
PxU32 currentArticulation = 0;
PxU32 currentContact = 0;
PxU32 constraintIndex = 0;
const PxU32 minIslandSize = mSolverBatchSize;
const PxU32 islandCount = islandSim.getNbActiveIslands();
const PxU32 articulationBatchSize = mSolverArticBatchSize;
//while(start<sentinel)
while (currentIsland < islandCount)
{
SolverIslandObjectsStep objectStarts;
objectStarts.articulations = mArticulationArray.begin() + currentArticulation;
objectStarts.bodies = mRigidBodyArray.begin() + currentBodyIndex;
objectStarts.contactManagers = mContactList.begin() + currentContact;
objectStarts.constraintDescs = mSolverConstraintDescPool.begin() + constraintIndex;
objectStarts.orderedConstraintDescs = mOrderedSolverConstraintDescPool.begin() + constraintIndex;
objectStarts.constraintBatchHeaders = mContactConstraintBatchHeaders.begin() + constraintIndex;
objectStarts.tempConstraintDescs = mTempSolverConstraintDescPool.begin() + constraintIndex;
objectStarts.motionVelocities = mMotionVelocityArray.begin() + currentBodyIndex;
objectStarts.bodyCoreArray = mBodyCoreArray.begin() + currentBodyIndex;
objectStarts.islandIds = islandIds + currentIsland;
objectStarts.bodyRemapTable = mSolverBodyRemapTable.begin();
objectStarts.nodeIndexArray = mNodeIndexArray.begin() + currentBodyIndex;
PxU32 startIsland = currentIsland;
PxU32 constraintCount = 0;
PxU32 nbArticulations = 0;
PxU32 nbBodies = 0;
PxU32 nbConstraints = 0;
PxU32 nbContactManagers = 0;
while (nbBodies < minIslandSize && currentIsland < islandCount && nbArticulations < articulationBatchSize)
{
const IG::Island& island = islandSim.getIsland(islandIds[currentIsland]);
nbBodies += island.mNodeCount[IG::Node::eRIGID_BODY_TYPE];
nbArticulations += island.mNodeCount[IG::Node::eARTICULATION_TYPE];
nbConstraints += island.mEdgeCount[IG::Edge::eCONSTRAINT];
nbContactManagers += island.mEdgeCount[IG::Edge::eCONTACT_MANAGER];
constraintCount = nbConstraints + nbContactManagers;
currentIsland++;
}
objectStarts.numIslands = currentIsland - startIsland;
constraintIndex += nbArticulations* maxLinks;
PxsIslandIndices counts;
counts.articulations = nbArticulations;
counts.bodies = nbBodies;
counts.constraints = nbConstraints;
counts.contactManagers = nbContactManagers;
solveIsland(objectStarts, counts,
mKinematicCount + currentBodyIndex, simpleIslandManager, mSolverBodyRemapTable.begin(), mMaterialManager, mOutputIterator,
mergeTask);
currentBodyIndex += nbBodies;
currentArticulation += nbArticulations;
currentContact += nbContactManagers;
constraintIndex += constraintCount;
}
mergeTask->removeReference();
}
void DynamicsTGSContext::prepareBodiesAndConstraints(const SolverIslandObjectsStep& objects,
IG::SimpleIslandManager& islandManager, IslandContextStep& islandContext)
{
Dy::ThreadContext& mThreadContext = *islandContext.mThreadContext;
mThreadContext.mMaxSolverPositionIterations = 0;
mThreadContext.mMaxSolverVelocityIterations = 0;
mThreadContext.mAxisConstraintCount = 0;
mThreadContext.mContactDescPtr = mThreadContext.contactConstraintDescArray;
mThreadContext.mFrictionDescPtr = mThreadContext.frictionConstraintDescArray.begin();
mThreadContext.mNumDifferentBodyConstraints = 0;
mThreadContext.mNumStaticConstraints = 0;
mThreadContext.mNumSelfConstraints = 0;
mThreadContext.mNumDifferentBodyFrictionConstraints = 0;
mThreadContext.mNumSelfConstraintFrictionBlocks = 0;
mThreadContext.mNumSelfFrictionConstraints = 0;
mThreadContext.numContactConstraintBatches = 0;
mThreadContext.contactDescArraySize = 0;
mThreadContext.motionVelocityArray = objects.motionVelocities;
mThreadContext.mBodyCoreArray = objects.bodyCoreArray;
mThreadContext.mRigidBodyArray = objects.bodies;
mThreadContext.mArticulationArray = objects.articulations;
mThreadContext.bodyRemapTable = objects.bodyRemapTable;
mThreadContext.mNodeIndexArray = objects.nodeIndexArray;
const PxU32 frictionConstraintCount = 0;
mThreadContext.resizeArrays(frictionConstraintCount, islandContext.mCounts.articulations);
PxsBodyCore** PX_RESTRICT bodyArrayPtr = mThreadContext.mBodyCoreArray;
PxsRigidBody** PX_RESTRICT rigidBodyPtr = mThreadContext.mRigidBodyArray;
FeatherstoneArticulation** PX_RESTRICT articulationPtr = mThreadContext.mArticulationArray;
PxU32* PX_RESTRICT bodyRemapTable = mThreadContext.bodyRemapTable;
PxU32* PX_RESTRICT nodeIndexArray = mThreadContext.mNodeIndexArray;
PxU32 nbIslands = objects.numIslands;
const IG::IslandId* const islandIds = objects.islandIds;
const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim();
PxU32 bodyIndex = 0, articIndex = 0;
for (PxU32 i = 0; i < nbIslands; ++i)
{
const IG::Island& island = islandSim.getIsland(islandIds[i]);
PxNodeIndex currentIndex = island.mRootNode;
while (currentIndex.isValid())
{
const IG::Node& node = islandSim.getNode(currentIndex);
if (node.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
articulationPtr[articIndex++] = node.getArticulation();
}
else
{
PxsRigidBody* rigid = node.getRigidBody();
PX_ASSERT(bodyIndex < (islandContext.mCounts.bodies + mKinematicCount + 1));
rigidBodyPtr[bodyIndex] = rigid;
bodyArrayPtr[bodyIndex] = &rigid->getCore();
nodeIndexArray[bodyIndex] = currentIndex.index();
bodyRemapTable[islandSim.getActiveNodeIndex(currentIndex)] = bodyIndex++;
}
currentIndex = node.mNextNode;
}
}
PxsIndexedContactManager* indexedManagers = objects.contactManagers;
PxU32 currentContactIndex = 0;
for (PxU32 i = 0; i < nbIslands; ++i)
{
const IG::Island& island = islandSim.getIsland(islandIds[i]);
IG::EdgeIndex contactEdgeIndex = island.mFirstEdge[IG::Edge::eCONTACT_MANAGER];
while (contactEdgeIndex != IG_INVALID_EDGE)
{
const IG::Edge& edge = islandSim.getEdge(contactEdgeIndex);
PxsContactManager* contactManager = islandManager.getContactManager(contactEdgeIndex);
if (contactManager)
{
const PxNodeIndex nodeIndex1 = islandSim.getNodeIndex1(contactEdgeIndex);
const PxNodeIndex nodeIndex2 = islandSim.getNodeIndex2(contactEdgeIndex);
PxsIndexedContactManager& indexedManager = indexedManagers[currentContactIndex++];
indexedManager.contactManager = contactManager;
PX_ASSERT(!nodeIndex1.isStaticBody());
{
const IG::Node& node1 = islandSim.getNode(nodeIndex1);
//Is it an articulation or not???
if (node1.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
indexedManager.articulation0 = nodeIndex1.getInd();
const PxU32 linkId = nodeIndex1.articulationLinkId();
node1.getArticulation()->fillIndexType(linkId, indexedManager.indexType0);
}
else
{
if (node1.isKinematic())
{
indexedManager.indexType0 = PxsIndexedInteraction::eKINEMATIC;
indexedManager.solverBody0 = islandSim.getActiveNodeIndex(nodeIndex1);
}
else
{
indexedManager.indexType0 = PxsIndexedInteraction::eBODY;
indexedManager.solverBody0 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex1)];
}
PX_ASSERT(indexedManager.solverBody0 < (islandContext.mCounts.bodies + mKinematicCount + 1));
}
}
if (nodeIndex2.isStaticBody())
{
indexedManager.indexType1 = PxsIndexedInteraction::eWORLD;
}
else
{
const IG::Node& node2 = islandSim.getNode(nodeIndex2);
//Is it an articulation or not???
if (node2.getNodeType() == IG::Node::eARTICULATION_TYPE)
{
indexedManager.articulation1 = nodeIndex2.getInd();
const PxU32 linkId = nodeIndex2.articulationLinkId();
node2.getArticulation()->fillIndexType(linkId, indexedManager.indexType1);
}
else
{
if (node2.isKinematic())
{
indexedManager.indexType1 = PxsIndexedInteraction::eKINEMATIC;
indexedManager.solverBody1 = islandSim.getActiveNodeIndex(nodeIndex2);
}
else
{
indexedManager.indexType1 = PxsIndexedInteraction::eBODY;
indexedManager.solverBody1 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex2)];
}
PX_ASSERT(indexedManager.solverBody1 < (islandContext.mCounts.bodies + mKinematicCount + 1));
}
}
}
contactEdgeIndex = edge.mNextIslandEdge;
}
}
islandContext.mCounts.contactManagers = currentContactIndex;
}
struct ConstraintLess
{
bool operator()(const PxSolverConstraintDesc& left, const PxSolverConstraintDesc& right) const
{
return reinterpret_cast<Constraint*>(left.constraint)->index > reinterpret_cast<Constraint*>(right.constraint)->index;
}
};
void DynamicsTGSContext::setupDescs(IslandContextStep& mIslandContext, const SolverIslandObjectsStep& mObjects,
PxU32* mBodyRemapTable, PxU32 mSolverBodyOffset, PxsContactManagerOutputIterator& outputs)
{
PX_UNUSED(outputs);
ThreadContext& mThreadContext = *mIslandContext.mThreadContext;
PxSolverConstraintDesc* contactDescPtr = mObjects.constraintDescs;
//PxU32 constraintCount = mCounts.constraints + mCounts.contactManagers;
PxU32 nbIslands = mObjects.numIslands;
const IG::IslandId* const islandIds = mObjects.islandIds;
const IG::IslandSim& islandSim = mIslandManager->getAccurateIslandSim();
for (PxU32 i = 0; i < nbIslands; ++i)
{
const IG::Island& island = islandSim.getIsland(islandIds[i]);
IG::EdgeIndex edgeId = island.mFirstEdge[IG::Edge::eCONSTRAINT];
while (edgeId != IG_INVALID_EDGE)
{
PxSolverConstraintDesc& desc = *contactDescPtr;
const IG::Edge& edge = islandSim.getEdge(edgeId);
Dy::Constraint* constraint = mIslandManager->getConstraint(edgeId);
setDescFromIndices(desc, edgeId, *mIslandManager, mBodyRemapTable, mSolverBodyOffset,
mSolverBodyVelPool.begin());
desc.constraint = reinterpret_cast<PxU8*>(constraint);
desc.constraintLengthOver16 = DY_SC_TYPE_RB_1D;
contactDescPtr++;
edgeId = edge.mNextIslandEdge;
}
}
PxSort(mObjects.constraintDescs, PxU32(contactDescPtr - mObjects.constraintDescs), ConstraintLess());
if (mIslandContext.mCounts.contactManagers)
{
for (PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a)
{
//PxsContactManagerOutput& output = outputs.getContactManager(mObjects.contactManagers[a].contactManager->getWorkUnit().mNpIndex);
//if (output.nbContacts > 0)
{
PxSolverConstraintDesc& desc = *contactDescPtr;
setDescFromIndices(desc, islandSim, mObjects.contactManagers[a], mSolverBodyOffset, mSolverBodyVelPool.begin());
desc.constraint = reinterpret_cast<PxU8*>(mObjects.contactManagers[a].contactManager);
desc.constraintLengthOver16 = DY_SC_TYPE_RB_CONTACT;
contactDescPtr++;
}
//else
//{
// //Clear friction state!
// mObjects.contactManagers[a].contactManager->getWorkUnit().frictionDataPtr = NULL;
// mObjects.contactManagers[a].contactManager->getWorkUnit().frictionPatchCount = 0;
//}
}
}
mThreadContext.contactDescArraySize = PxU32(contactDescPtr - mObjects.constraintDescs);
}
void DynamicsTGSContext::preIntegrateBodies(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray,
PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2, PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, PxU32 /*iteration*/)
{
PX_PROFILE_ZONE("PreIntegrate", mContextID);
PxU32 localMaxPosIter = 0;
PxU32 localMaxVelIter = 0;
for (PxU32 i = 0; i < bodyCount; ++i)
{
PxsBodyCore& core = *bodyArray[i];
const PxsRigidBody& rBody = *originalBodyArray[i];
const PxU16 iterWord = core.solverIterationCounts;
localMaxPosIter = PxMax<PxU32>(PxU32(iterWord & 0xff), localMaxPosIter);
localMaxVelIter = PxMax<PxU32>(PxU32(iterWord >> 8), localMaxVelIter);
//const Cm::SpatialVector& accel = originalBodyArray[i]->getAccelerationV();
bodyCoreComputeUnconstrainedVelocity(gravity, dt, core.linearDamping, core.angularDamping, rBody.accelScale, core.maxLinearVelocitySq, core.maxAngularVelocitySq,
core.linearVelocity, core.angularVelocity, core.disableGravity!=0);
copyToSolverBodyDataStep(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, nodeIndexArray[i],
core.contactReportThreshold, core.maxAngularVelocitySq, core.lockFlags, false,
solverBodyVelPool[i+1], solverBodyTxInertia[i+1], solverBodyDataPool2[i+1], dt, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES);
}
posIters = localMaxPosIter;
velIters = localMaxVelIter;
}
void DynamicsTGSContext::createSolverConstraints(PxSolverConstraintDesc* contactDescPtr, PxConstraintBatchHeader* headers, PxU32 nbHeaders,
PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& islandThreadContext, Dy::ThreadContext& threadContext, PxReal stepDt, PxReal totalDt, PxReal invStepDt,
const PxReal biasCoefficient, PxI32 velIters)
{
PX_UNUSED(totalDt);
//PX_PROFILE_ZONE("CreateConstraints", 0);
PxTransform idt(PxIdentity);
BlockAllocator blockAllocator(islandThreadContext.mConstraintBlockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize);
PxTGSSolverBodyTxInertia* txInertias = mSolverBodyTxInertiaPool.begin();
PxTGSSolverBodyData* solverBodyDatas = mSolverBodyDataPool2.begin();
const PxReal invTotalDt = 1.f / totalDt;
PxReal denom = (totalDt);
if (velIters)
denom += stepDt;
const PxReal invTotalDtPlusStep = 1.f / denom;
for (PxU32 h = 0; h < nbHeaders; ++h)
{
PxConstraintBatchHeader& hdr = headers[h];
PxU32 startIdx = hdr.startIndex;
PxU32 endIdx = startIdx + hdr.stride;
if (contactDescPtr[startIdx].constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT)
{
PxTGSSolverContactDesc blockDescs[4];
PxsContactManagerOutput* cmOutputs[4];
PxsContactManager* cms[4];
for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++)
{
PxSolverConstraintDesc& desc = contactDescPtr[a];
PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint);
PxTGSSolverContactDesc& blockDesc = blockDescs[i];
cms[i] = cm;
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxsContactManagerOutput* cmOutput = &outputs.getContactManager(unit.mNpIndex);
cmOutputs[i] = cmOutput;
PxTGSSolverBodyVel& b0 = *desc.tgsBodyA;
PxTGSSolverBodyVel& b1 = *desc.tgsBodyB;
PxTGSSolverBodyTxInertia& txI0 = txInertias[desc.bodyADataIndex];
PxTGSSolverBodyTxInertia& txI1 = txInertias[desc.bodyBDataIndex];
PxTGSSolverBodyData& data0 = solverBodyDatas[desc.bodyADataIndex];
PxTGSSolverBodyData& data1 = solverBodyDatas[desc.bodyBDataIndex];
blockDesc.body0 = &b0;
blockDesc.body1 = &b1;
blockDesc.bodyFrame0 = unit.rigidCore0->body2World;
blockDesc.bodyFrame1 = unit.rigidCore1->body2World;
blockDesc.shapeInteraction = cm->getShapeInteraction();
blockDesc.contactForces = cmOutput->contactForces;
blockDesc.desc = &desc;
blockDesc.body0 = &b0;
blockDesc.body1 = &b1;
blockDesc.body0TxI = &txI0;
blockDesc.body1TxI = &txI1;
blockDesc.bodyData0 = &data0;
blockDesc.bodyData1 = &data1;
blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION);
blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY;
if (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1)
{
//kinematic link
if (desc.linkIndexB == 0xff)
{
blockDesc.bodyState1 = PxSolverContactDesc::eSTATIC_BODY;
}
else
{
blockDesc.bodyState1 = PxSolverContactDesc::eARTICULATION;
}
}
else
{
blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY :
((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY);
}
//blockDesc.flags = unit.flags;
PxReal maxImpulse0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? static_cast<const PxsBodyCore*>(unit.rigidCore0)->maxContactImpulse : data0.maxContactImpulse;
PxReal maxImpulse1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? static_cast<const PxsBodyCore*>(unit.rigidCore1)->maxContactImpulse : data1.maxContactImpulse;
PxReal dominance0 = unit.dominance0 ? 1.f : 0.f;
PxReal dominance1 = unit.dominance1 ? 1.f : 0.f;
blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0;
blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1;
blockDesc.restDistance = unit.restDistance;
blockDesc.frictionPtr = unit.frictionDataPtr;
blockDesc.frictionCount = unit.frictionPatchCount;
blockDesc.maxCCDSeparation = PX_MAX_F32;
blockDesc.maxImpulse = PxMin(maxImpulse0, maxImpulse1);
blockDesc.torsionalPatchRadius = unit.mTorsionalPatchRadius;
blockDesc.minTorsionalPatchRadius = unit.mMinTorsionalPatchRadius;
blockDesc.offsetSlop = unit.mOffsetSlop;
}
SolverConstraintPrepState::Enum buildState = SolverConstraintPrepState::eUNBATCHABLE;
#if PX_USE_BLOCK_SOLVER
if (hdr.stride == 4)
{
buildState = createFinalizeSolverContacts4Step(
cmOutputs,
threadContext,
blockDescs,
invStepDt,
totalDt,
invTotalDtPlusStep,
stepDt,
mBounceThreshold,
mFrictionOffsetThreshold,
mCorrelationDistance,
biasCoefficient,
blockAllocator);
}
#endif
if (buildState != SolverConstraintPrepState::eSUCCESS)
{
for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++)
{
PxSolverConstraintDesc& desc = contactDescPtr[a];
PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint);
//PxcNpWorkUnit& n = cm->getWorkUnit();
PxsContactManagerOutput& output = *cmOutputs[i];
//PX_ASSERT(output.nbContacts != 0);
createFinalizeSolverContactsStep(blockDescs[i], output, threadContext,
invStepDt, invTotalDtPlusStep, totalDt, stepDt, mBounceThreshold, mFrictionOffsetThreshold, mCorrelationDistance, biasCoefficient,
blockAllocator);
getContactManagerConstraintDesc(output, *cm, desc);
//PX_ASSERT(desc.constraint != NULL);
}
}
for (PxU32 i = 0; i < hdr.stride; ++i)
{
PxsContactManager* cm = cms[i];
PxcNpWorkUnit& unit = cm->getWorkUnit();
unit.frictionDataPtr = blockDescs[i].frictionPtr;
unit.frictionPatchCount = blockDescs[i].frictionCount;
}
}
else if (contactDescPtr[startIdx].constraintLengthOver16 == DY_SC_TYPE_RB_1D)
{
SolverConstraintShaderPrepDesc shaderPrepDescs[4];
PxTGSSolverConstraintPrepDesc prepDescs[4];
for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++)
{
SolverConstraintShaderPrepDesc& shaderPrepDesc = shaderPrepDescs[i];
PxTGSSolverConstraintPrepDesc& prepDesc = prepDescs[i];
const PxTransform id(PxIdentity);
{
PxSolverConstraintDesc& desc = contactDescPtr[a];
const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint);
const PxConstraintSolverPrep solverPrep = constraint->solverPrep;
const void* constantBlock = constraint->constantBlock;
const PxU32 constantBlockByteSize = constraint->constantBlockSize;
const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : id);
const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : id);
const PxTGSSolverBodyVel* sbody0 = desc.tgsBodyA;
const PxTGSSolverBodyVel* sbody1 = desc.tgsBodyB;
PxTGSSolverBodyTxInertia& txI0 = txInertias[desc.bodyADataIndex];
PxTGSSolverBodyTxInertia& txI1 = txInertias[desc.bodyBDataIndex];
PxTGSSolverBodyData& data0 = solverBodyDatas[desc.bodyADataIndex];
PxTGSSolverBodyData& data1 = solverBodyDatas[desc.bodyBDataIndex];
shaderPrepDesc.constantBlock = constantBlock;
shaderPrepDesc.constantBlockByteSize = constantBlockByteSize;
shaderPrepDesc.constraint = constraint;
shaderPrepDesc.solverPrep = solverPrep;
prepDesc.desc = &desc;
prepDesc.bodyFrame0 = pose0;
prepDesc.bodyFrame1 = pose1;
prepDesc.body0 = sbody0;
prepDesc.body1 = sbody1;
prepDesc.body0TxI = &txI0;
prepDesc.body1TxI = &txI1;
prepDesc.bodyData0 = &data0;
prepDesc.bodyData1 = &data1;
prepDesc.linBreakForce = constraint->linBreakForce;
prepDesc.angBreakForce = constraint->angBreakForce;
prepDesc.writeback = &getConstraintWriteBackPool()[constraint->index];
setupConstraintFlags(prepDesc, constraint->flags);
prepDesc.minResponseThreshold = constraint->minResponseThreshold;
prepDesc.bodyState0 = desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION;
prepDesc.bodyState1 = desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION;
}
}
SolverConstraintPrepState::Enum buildState = SolverConstraintPrepState::eUNBATCHABLE;
#if PX_USE_BLOCK_SOLVER
#if PX_USE_BLOCK_1D
if (hdr.stride == 4)
{
PxU32 totalRows;
buildState = setupSolverConstraintStep4
(shaderPrepDescs, prepDescs, stepDt, totalDt, invStepDt, invTotalDt, totalRows, blockAllocator, mLengthScale, biasCoefficient);
}
#endif
#endif
if (buildState != SolverConstraintPrepState::eSUCCESS)
{
for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++)
{
PxReal clampedInvDt = invStepDt;
SetupSolverConstraintStep(shaderPrepDescs[i], prepDescs[i], blockAllocator, stepDt, totalDt, clampedInvDt, invTotalDt, mLengthScale,
biasCoefficient);
}
}
}
}
}
void solveContactBlock (DY_TGS_SOLVE_METHOD_PARAMS);
void solve1DBlock (DY_TGS_SOLVE_METHOD_PARAMS);
void solveExtContactBlock (DY_TGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlock (DY_TGS_SOLVE_METHOD_PARAMS);
void solveContact4 (DY_TGS_SOLVE_METHOD_PARAMS);
void solve1D4 (DY_TGS_SOLVE_METHOD_PARAMS);
TGSSolveBlockMethod g_SolveTGSMethods[] =
{
0,
solveContactBlock, // DY_SC_TYPE_RB_CONTACT
solve1DBlock, // DY_SC_TYPE_RB_1D
solveExtContactBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlock, // DY_SC_TYPE_EXT_1D
solveContactBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContact4, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContact4, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4, // DY_SC_TYPE_BLOCK_1D,
};
void writeBackContact (DY_TGS_WRITEBACK_METHOD_PARAMS);
void writeBack1D (DY_TGS_WRITEBACK_METHOD_PARAMS);
void writeBackContact4 (DY_TGS_WRITEBACK_METHOD_PARAMS);
void writeBack1D4 (DY_TGS_WRITEBACK_METHOD_PARAMS);
TGSWriteBackMethod g_WritebackTGSMethods[] =
{
0,
writeBackContact, // DY_SC_TYPE_RB_CONTACT
writeBack1D, // DY_SC_TYPE_RB_1D
writeBackContact, // DY_SC_TYPE_EXT_CONTACT
writeBack1D, // DY_SC_TYPE_EXT_1D
writeBackContact, // DY_SC_TYPE_STATIC_CONTACT
writeBackContact, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
writeBackContact4, // DY_SC_TYPE_BLOCK_RB_CONTACT
writeBackContact4, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
writeBack1D4, // DY_SC_TYPE_BLOCK_1D,
};
void solveConclude1DBlock (DY_TGS_CONCLUDE_METHOD_PARAMS);
void solveConcludeContactBlock (DY_TGS_CONCLUDE_METHOD_PARAMS);
void solveConcludeContact4 (DY_TGS_CONCLUDE_METHOD_PARAMS);
void solveConclude1D4 (DY_TGS_CONCLUDE_METHOD_PARAMS);
void solveConcludeContactExtBlock (DY_TGS_CONCLUDE_METHOD_PARAMS);
void solveConclude1DBlockExt (DY_TGS_CONCLUDE_METHOD_PARAMS);
TGSSolveConcludeMethod g_SolveConcludeTGSMethods[] =
{
0,
solveConcludeContactBlock, // DY_SC_TYPE_RB_CONTACT
solveConclude1DBlock, // DY_SC_TYPE_RB_1D
solveConcludeContactExtBlock, // DY_SC_TYPE_EXT_CONTACT
solveConclude1DBlockExt, // DY_SC_TYPE_EXT_1D
solveConcludeContactBlock, // DY_SC_TYPE_STATIC_CONTACT
solveConcludeContactBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveConcludeContact4, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveConcludeContact4, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solveConclude1D4, // DY_SC_TYPE_BLOCK_1D,
};
void DynamicsTGSContext::solveConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders,
PxReal invStepDt, const PxTGSSolverBodyTxInertia* const solverTxInertia, PxReal elapsedTime, PxReal minPenetration, SolverContext& cache)
{
PX_UNUSED(invStepDt);
for (PxU32 h = 0; h < nbHeaders; ++h)
{
const PxConstraintBatchHeader& hdr = batchHeaders[h];
g_SolveTGSMethods[hdr.constraintType](hdr, contactDescPtr, solverTxInertia, minPenetration, elapsedTime, cache);
}
}
template <bool TSync>
void DynamicsTGSContext::parallelSolveConstraints(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders,
PxTGSSolverBodyTxInertia* solverTxInertia, PxReal elapsedTime, PxReal minPenetration,
SolverContext& cache, PxU32 iterCount)
{
for (PxU32 h = 0; h < nbHeaders; ++h)
{
const PxConstraintBatchHeader& hdr = batchHeaders[h];
const PxSolverConstraintDesc& desc = contactDescPtr[hdr.startIndex];
if (TSync)
{
PX_ASSERT(hdr.stride == 1);
waitForProgresses(desc, iterCount);
}
g_SolveTGSMethods[hdr.constraintType](hdr, contactDescPtr, solverTxInertia, minPenetration, elapsedTime, cache);
if (TSync)
{
PxMemoryBarrier();
incrementProgress(desc);
}
}
}
void DynamicsTGSContext::writebackConstraintsIteration(const PxConstraintBatchHeader* const hdrs, const PxSolverConstraintDesc* const contactDescPtr, PxU32 nbHeaders)
{
PX_PROFILE_ZONE("Writeback", mContextID);
for (PxU32 h = 0; h < nbHeaders; ++h)
{
const PxConstraintBatchHeader& hdr = hdrs[h];
g_WritebackTGSMethods[hdr.constraintType](hdr, contactDescPtr, NULL);
}
}
void DynamicsTGSContext::parallelWritebackConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders)
{
for (PxU32 h = 0; h < nbHeaders; ++h)
{
const PxConstraintBatchHeader& hdr = batchHeaders[h];
g_WritebackTGSMethods[hdr.constraintType](hdr, contactDescPtr, NULL);
}
}
template <bool TSync>
void DynamicsTGSContext::solveConcludeConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr,
const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxTGSSolverBodyTxInertia* solverTxInertia,
PxReal elapsedTime, SolverContext& cache, PxU32 iterCount)
{
for (PxU32 h = 0; h < nbHeaders; ++h)
{
const PxConstraintBatchHeader& hdr = batchHeaders[h];
const PxSolverConstraintDesc& desc = contactDescPtr[hdr.startIndex];
if (TSync)
waitForProgresses(desc, iterCount);
g_SolveConcludeTGSMethods[hdr.constraintType](hdr, contactDescPtr, solverTxInertia, elapsedTime, cache);
if (TSync)
{
PxMemoryBarrier();
incrementProgress(desc);
}
}
}
void integrateCoreStep(PxTGSSolverBodyVel& vel, PxTGSSolverBodyTxInertia& txInertia, PxF32 dt)
{
PxU32 lockFlags = vel.lockFlags;
if (lockFlags)
{
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
vel.linearVelocity.x = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
vel.linearVelocity.y = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
vel.linearVelocity.z = 0.f;
//The angular velocity should be 0 because it is now impossible to make it rotate around that axis!
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
vel.angularVelocity.x = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
vel.angularVelocity.y = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
vel.angularVelocity.z = 0.f;
}
PxVec3 linearMotionVel = vel.linearVelocity;
const PxVec3 delta = linearMotionVel * dt;
PxVec3 unmolestedAngVel = vel.angularVelocity;
PxVec3 angularMotionVel = txInertia.sqrtInvInertia * vel.angularVelocity;
PxReal w2 = angularMotionVel.magnitudeSquared();
txInertia.deltaBody2World.p += delta;
PX_ASSERT(txInertia.deltaBody2World.p.isFinite());
// Integrate the rotation using closed form quaternion integrator
if (w2 != 0.0f)
{
PxReal w = PxSqrt(w2);
//KS - we allow a little bit more angular velocity than the default
//maxAngVel member otherwise the simulation feels a little flimsy
/*const PxReal maxW = PxMax(50.f, vel.maxAngVel);
if (w > maxW)
{
PxReal ratio = maxW / w;
vel.angularVelocity *= ratio;
}*/
const PxReal v = dt * w * 0.5f;
PxReal s, q;
PxSinCos(v, s, q);
s /= w;
const PxVec3 pqr = angularMotionVel * s;
const PxQuat quatVel(pqr.x, pqr.y, pqr.z, 0);
PxQuat result = quatVel * txInertia.deltaBody2World.q;
result += txInertia.deltaBody2World.q * q;
txInertia.deltaBody2World.q = result.getNormalized();
PX_ASSERT(txInertia.deltaBody2World.q.isSane());
PX_ASSERT(txInertia.deltaBody2World.q.isFinite());
//Accumulate the angular rotations in a space we can project the angular constraints to
}
vel.deltaAngDt += unmolestedAngVel * dt;
vel.deltaLinDt += delta;
/*solverBodyData.body2World = txInertia.body2World;
solverBodyData.deltaLinDt = vel.deltaLinDt;
solverBodyData.deltaAngDt = vel.deltaAngDt;*/
}
void averageVelocity(PxTGSSolverBodyVel& vel, PxF32 invDt, PxReal ratio)
{
const PxVec3 frameLinVel = vel.deltaLinDt*invDt;
const PxVec3 frameAngVel = vel.deltaAngDt*invDt;
if (frameLinVel.magnitudeSquared() < vel.linearVelocity.magnitudeSquared() || frameAngVel.magnitudeSquared() < vel.angularVelocity.magnitudeSquared())
{
const PxReal otherRatio = 1.f - ratio;
vel.linearVelocity = (vel.linearVelocity*ratio + frameLinVel*otherRatio);
vel.angularVelocity = (vel.angularVelocity*ratio + frameAngVel*otherRatio);
}
}
void DynamicsTGSContext::integrateBodies(const SolverIslandObjectsStep& /*objects*/,
PxU32 count, PxTGSSolverBodyVel* PX_RESTRICT vels, PxTGSSolverBodyTxInertia* PX_RESTRICT txInertias,
const PxTGSSolverBodyData*const PX_RESTRICT /*bodyDatas*/, PxReal dt, PxReal invTotalDt, bool average,
PxReal ratio)
{
for (PxU32 k = 0; k < count; k++)
{
integrateCoreStep(vels[k + 1], txInertias[k + 1], dt);
if (average)
averageVelocity(vels[k + 1], invTotalDt, ratio);
}
}
void DynamicsTGSContext::parallelIntegrateBodies(PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
const PxTGSSolverBodyData* const /*bodyDatas*/, PxU32 count, PxReal dt, PxU32 iteration, PxReal invTotalDt, bool average,
PxReal ratio)
{
PX_UNUSED(iteration);
for (PxU32 k = 0; k < count; k++)
{
PX_ASSERT(vels[k + 1].partitionMask == (iteration * vels[k + 1].maxDynamicPartition));
integrateCoreStep(vels[k + 1], txInertias[k + 1], dt);
if (average)
averageVelocity(vels[k + 1], invTotalDt, ratio);
}
}
void DynamicsTGSContext::copyBackBodies(const SolverIslandObjectsStep& objects,
PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
PxTGSSolverBodyData* solverBodyDatas, PxReal invDt, IG::IslandSim& islandSim,
PxU32 startIdx, PxU32 endIdx)
{
for (PxU32 k = startIdx; k < endIdx; k++)
{
//PxStepSolverBody& solverBodyData = solverBodyData2[k + 1];
PxTGSSolverBodyVel& solverBodyVel = vels[k + 1];
PxTGSSolverBodyTxInertia& solverBodyTxI = txInertias[k + 1];
PxTGSSolverBodyData& solverBodyData = solverBodyDatas[k + 1];
const Cm::SpatialVector motionVel(solverBodyVel.deltaLinDt*invDt, solverBodyTxI.sqrtInvInertia*(solverBodyVel.deltaAngDt*invDt));
PxsRigidBody& rBody = *objects.bodies[k];
PxsBodyCore& core = rBody.getCore();
rBody.mLastTransform = core.body2World;
core.body2World.q = (solverBodyTxI.deltaBody2World.q * core.body2World.q).getNormalized();
core.body2World.p = solverBodyTxI.deltaBody2World.p;
/*core.linearVelocity = (solverBodyVel.linearVelocity);
core.angularVelocity = solverBodyTxI.sqrtInvInertia*(solverBodyVel.angularVelocity);*/
PxVec3 linearVelocity = (solverBodyVel.linearVelocity);
PxVec3 angularVelocity = solverBodyTxI.sqrtInvInertia*(solverBodyVel.angularVelocity);
core.linearVelocity = linearVelocity;
core.angularVelocity = angularVelocity;
const bool hasStaticTouch = islandSim.getIslandStaticTouchCount(PxNodeIndex(solverBodyData.nodeIndex)) != 0;
sleepCheck(&rBody, mDt, mEnableStabilization, motionVel, hasStaticTouch);
}
}
void DynamicsTGSContext::stepArticulations(Dy::ThreadContext& threadContext, const PxsIslandIndices& counts, PxReal dt, PxReal totalInvDt)
{
for (PxU32 a = 0; a < counts.articulations; ++a)
{
ArticulationSolverDesc& d = threadContext.getArticulations()[a];
//if(d.articulation->numTotalConstraints > 0)
//d.articulation->solveInternalConstraints(dt, 1.f / dt, threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), false);
ArticulationPImpl::updateDeltaMotion(d, dt, threadContext.mDeltaV.begin(), totalInvDt);
}
}
void DynamicsTGSContext::updateArticulations(Dy::ThreadContext& threadContext, PxU32 startIdx, PxU32 endIdx, PxReal dt)
{
for (PxU32 a = startIdx; a < endIdx; ++a)
{
ArticulationSolverDesc& d = threadContext.getArticulations()[a];
ArticulationPImpl::updateBodiesTGS(d, threadContext.mDeltaV.begin(), dt);
}
}
namespace
{
class ArticulationTask : public Cm::Task
{
Dy::DynamicsTGSContext& mContext;
ArticulationSolverDesc* mDescs;
PxU32 mNbDescs;
PxVec3 mGravity;
PxReal mDt;
PX_NOCOPY(ArticulationTask)
public:
static const PxU32 MaxNbPerTask = 32;
ArticulationTask(Dy::DynamicsTGSContext& context, ArticulationSolverDesc* descs, PxU32 nbDescs, const PxVec3& gravity,
PxReal dt, PxU64 contextId) : Cm::Task(contextId), mContext(context),
mDescs(descs), mNbDescs(nbDescs), mGravity(gravity), mDt(dt)
{
}
virtual const char* getName() const { return "ArticulationTask"; }
virtual void runInternal()
{
PxU32 maxLinks = 0;
for (PxU32 i = 0; i < mNbDescs; i++)
{
maxLinks = PxMax(maxLinks, PxU32(mDescs[i].linkCount));
}
Dy::ThreadContext& threadContext = *mContext.getThreadContext();
threadContext.mZVector.forceSize_Unsafe(0);
threadContext.mZVector.reserve(maxLinks);
threadContext.mZVector.forceSize_Unsafe(maxLinks);
threadContext.mDeltaV.forceSize_Unsafe(0);
threadContext.mDeltaV.reserve(maxLinks);
threadContext.mDeltaV.forceSize_Unsafe(maxLinks);
const PxReal invLengthScale = 1.f / mContext.getLengthScale();
for (PxU32 a = 0; a < mNbDescs; ++a)
{
ArticulationPImpl::computeUnconstrainedVelocitiesTGS(mDescs[a], mDt,
mGravity, getContextId(), threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), invLengthScale);
}
mContext.putThreadContext(&threadContext);
}
};
}
void DynamicsTGSContext::setupArticulations(IslandContextStep& islandContext, const PxVec3& gravity, PxReal dt, PxU32& posIters,
PxU32& velIters, PxBaseTask* continuation)
{
Dy::FeatherstoneArticulation** articulations = islandContext.mThreadContext->mArticulationArray;
PxU32 nbArticulations = islandContext.mCounts.articulations;
PxU32 maxVelIters = 0;
PxU32 maxPosIters = 0;
//PxU32 startIdx = 0;
for (PxU32 a = 0; a < nbArticulations; a+= ArticulationTask::MaxNbPerTask)
{
const PxU32 endIdx = PxMin(nbArticulations, a + ArticulationTask::MaxNbPerTask);
for (PxU32 b = a; b < endIdx; ++b)
{
ArticulationSolverDesc& desc = islandContext.mThreadContext->getArticulations()[b];
articulations[b]->getSolverDesc(desc);
articulations[b]->mArticulationIndex = PxU16(b);
const PxU16 iterWord = articulations[b]->getIterationCounts();
maxVelIters = PxMax<PxU32>(PxU32(iterWord >> 8), maxVelIters);
maxPosIters = PxMax<PxU32>(PxU32(iterWord & 0xff), maxPosIters);
}
Dy::ThreadContext* threadContext = islandContext.mThreadContext;
ArticulationTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(ArticulationTask)), ArticulationTask)(*this, threadContext->getArticulations().begin() + a,
endIdx - a, gravity, dt, getContextId());
task->setContinuation(continuation);
task->removeReference();
//startIdx += descCount;
}
velIters = PxMax(maxVelIters, velIters);
posIters = PxMax(maxPosIters, posIters);
}
PxU32 DynamicsTGSContext::setupArticulationInternalConstraints(IslandContextStep& islandContext, PxReal dt, PxReal invStepDt)
{
Dy::FeatherstoneArticulation** articulations = islandContext.mThreadContext->mArticulationArray;
PxU32 nbArticulations = islandContext.mCounts.articulations;
ThreadContext* threadContext = getThreadContext();
threadContext->mConstraintBlockStream.reset();
PxU32 totalDescCount = 0;
for (PxU32 a = 0; a < nbArticulations; ++a)
{
ArticulationSolverDesc& desc = islandContext.mThreadContext->getArticulations()[a];
articulations[a]->getSolverDesc(desc);
PxU32 acCount;
PxU32 descCount = ArticulationPImpl::setupSolverInternalConstraintsTGS(desc,
islandContext.mStepDt, invStepDt, dt, acCount, threadContext->mZVector.begin());
desc.numInternalConstraints = PxTo8(descCount);
totalDescCount += descCount;
}
putThreadContext(threadContext);
islandContext.mThreadContext->contactDescArraySize += totalDescCount;
return totalDescCount;
}
class SetupDescsTask : public Cm::Task
{
Dy::IslandContextStep& mIslandContext;
const SolverIslandObjectsStep& mObjects;
PxU32* mBodyRemapTable;
PxU32 mSolverBodyOffset;
PxsContactManagerOutputIterator& mOutputs;
DynamicsTGSContext& mContext;
PX_NOCOPY(SetupDescsTask)
public:
SetupDescsTask(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects,
PxU32* bodyRemapTable, PxU32 solverBodyOffset, PxsContactManagerOutputIterator& outputs, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mObjects(objects), mBodyRemapTable(bodyRemapTable), mSolverBodyOffset(solverBodyOffset),
mOutputs(outputs), mContext(context)
{
}
virtual const char* getName() const { return "SetupDescsTask"; }
virtual void runInternal()
{
mContext.setupDescs(mIslandContext, mObjects, mBodyRemapTable, mSolverBodyOffset, mOutputs);
mIslandContext.mArticulationOffset = mIslandContext.mThreadContext->contactDescArraySize;
}
};
class PreIntegrateParallelTask : public Cm::Task
{
PxsBodyCore** mBodyArray;
PxsRigidBody** mOriginalBodyArray;
PxTGSSolverBodyVel* mSolverBodyVelPool;
PxTGSSolverBodyTxInertia* mSolverBodyTxInertia;
PxTGSSolverBodyData* mSolverBodyDataPool2;
PxU32* mNodeIndexArray;
const PxU32 mBodyCount;
const PxVec3& mGravity;
const PxReal mDt;
PxU32& mPosIters;
PxU32& mVelIters;
DynamicsTGSContext& mContext;
PX_NOCOPY(PreIntegrateParallelTask)
public:
PreIntegrateParallelTask(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray,
PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2,
PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters,
DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mBodyArray(bodyArray), mOriginalBodyArray(originalBodyArray), mSolverBodyVelPool(solverBodyVelPool),
mSolverBodyTxInertia(solverBodyTxInertia), mSolverBodyDataPool2(solverBodyDataPool2), mNodeIndexArray(nodeIndexArray),
mBodyCount(bodyCount), mGravity(gravity), mDt(dt), mPosIters(posIters), mVelIters(velIters), mContext(context)
{
}
virtual const char* getName() const { return "PreIntegrateParallelTask"; }
virtual void runInternal()
{
PxU32 posIters = 0;
PxU32 velIters = 0;
mContext.preIntegrateBodies(mBodyArray, mOriginalBodyArray, mSolverBodyVelPool, mSolverBodyTxInertia, mSolverBodyDataPool2, mNodeIndexArray, mBodyCount, mGravity, mDt, posIters, velIters, 0);
PxAtomicMax(reinterpret_cast<PxI32*>(&mPosIters), PxI32(posIters));
PxAtomicMax(reinterpret_cast<PxI32*>(&mVelIters), PxI32(velIters));
}
};
class PreIntegrateTask : public Cm::Task
{
PxsBodyCore** mBodyArray;
PxsRigidBody** mOriginalBodyArray;
PxTGSSolverBodyVel* mSolverBodyVelPool;
PxTGSSolverBodyTxInertia* mSolverBodyTxInertia;
PxTGSSolverBodyData* mSolverBodyDataPool2;
PxU32* mNodeIndexArray;
const PxU32 mBodyCount;
const PxVec3& mGravity;
const PxReal mDt;
PxU32& mPosIters;
PxU32& mVelIters;
DynamicsTGSContext& mContext;
PX_NOCOPY(PreIntegrateTask)
public:
PreIntegrateTask(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray,
PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2,
PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters,
DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mBodyArray(bodyArray), mOriginalBodyArray(originalBodyArray), mSolverBodyVelPool(solverBodyVelPool),
mSolverBodyTxInertia(solverBodyTxInertia), mSolverBodyDataPool2(solverBodyDataPool2), mNodeIndexArray(nodeIndexArray),
mBodyCount(bodyCount), mGravity(gravity), mDt(dt), mPosIters(posIters), mVelIters(velIters), mContext(context)
{
}
virtual const char* getName() const { return "PreIntegrateTask"; }
virtual void runInternal()
{
const PxU32 BodiesPerTask = 512;
if (mBodyCount <= BodiesPerTask)
{
PxU32 posIters = 0;
PxU32 velIters = 0;
mContext.preIntegrateBodies(mBodyArray, mOriginalBodyArray, mSolverBodyVelPool, mSolverBodyTxInertia, mSolverBodyDataPool2, mNodeIndexArray, mBodyCount, mGravity, mDt, posIters, velIters, 0);
PxAtomicMax(reinterpret_cast<PxI32*>(&mPosIters), PxI32(posIters));
PxAtomicMax(reinterpret_cast<PxI32*>(&mVelIters), PxI32(velIters));
}
else
{
for (PxU32 i = 0; i < mBodyCount; i += BodiesPerTask)
{
const PxU32 nbToProcess = PxMin(mBodyCount - i, BodiesPerTask);
PreIntegrateParallelTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(PreIntegrateParallelTask)), PreIntegrateParallelTask)
(mBodyArray+i, mOriginalBodyArray+i, mSolverBodyVelPool+i, mSolverBodyTxInertia+i, mSolverBodyDataPool2+i,mNodeIndexArray+i,
nbToProcess, mGravity, mDt, mPosIters, mVelIters, mContext);
task->setContinuation(mCont);
task->removeReference();
}
}
}
};
class SetStepperTask : public Cm::Task
{
Dy::IslandContextStep& mIslandContext;
Dy::DynamicsTGSContext& mContext;
PxBaseTask* mAdditionalContinuation;
PX_NOCOPY(SetStepperTask)
public:
SetStepperTask(Dy::IslandContextStep& islandContext,
DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mContext(context),
mAdditionalContinuation(NULL)
{
}
virtual const char* getName() const { return "SetStepperTask"; }
void setAdditionalContinuation(PxBaseTask* cont)
{
mAdditionalContinuation = cont;
cont->addReference();
}
virtual void runInternal()
{
PxReal dt = mContext.getDt();
mIslandContext.mStepDt = dt / PxReal(mIslandContext.mPosIters);
mIslandContext.mInvStepDt = 1.f/mIslandContext.mStepDt;//PxMin(1000.f, 1.f / mIslandContext.mStepDt);
mIslandContext.mBiasCoefficient = 2.f * PxSqrt(1.f/mIslandContext.mPosIters);
}
virtual void release()
{
Cm::Task::release();
mAdditionalContinuation->removeReference();
}
};
class SetupArticulationTask : public Cm::Task
{
IslandContextStep& mIslandContext;
const PxVec3& mGravity;
const PxReal mDt;
PxU32& mPosIters;
PxU32& mVelIters;
DynamicsTGSContext& mContext;
PX_NOCOPY(SetupArticulationTask)
public:
SetupArticulationTask(IslandContextStep& islandContext, const PxVec3& gravity, PxReal dt, PxU32& posIters,
PxU32& velIters, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mGravity(gravity), mDt(dt), mPosIters(posIters), mVelIters(velIters), mContext(context)
{
}
virtual const char* getName() const { return "SetupArticulationTask"; }
virtual void runInternal()
{
PxU32 posIters = 0, velIters = 0;
mContext.setupArticulations(mIslandContext, mGravity, mDt, posIters, velIters, mCont);
PxAtomicMax(reinterpret_cast<PxI32*>(&mPosIters), PxI32(posIters));
PxAtomicMax(reinterpret_cast<PxI32*>(&mVelIters), PxI32(velIters));
}
};
class SetupArticulationInternalConstraintsTask : public Cm::Task
{
IslandContextStep& mIslandContext;
const PxReal mDt;
const PxReal mInvDt;
DynamicsTGSContext& mContext;
PX_NOCOPY(SetupArticulationInternalConstraintsTask)
public:
SetupArticulationInternalConstraintsTask(IslandContextStep& islandContext, PxReal dt, PxReal invDt, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mDt(dt), mInvDt(invDt), mContext(context)
{
}
virtual const char* getName() const { return "SetupArticulationInternalConstraintsTask"; }
virtual void runInternal()
{
mContext.setupArticulationInternalConstraints(mIslandContext, mDt, mIslandContext.mInvStepDt);
}
};
class SetupSolverConstraintsSubTask : public Cm::Task
{
PxSolverConstraintDesc* mContactDescPtr;
PxConstraintBatchHeader* mHeaders;
const PxU32 mNbHeaders;
PxsContactManagerOutputIterator& mOutputs;
PxReal mStepDt;
PxReal mTotalDt;
PxReal mInvStepDt;
PxReal mInvDtTotal;
PxReal mBiasCoefficient;
DynamicsTGSContext& mContext;
ThreadContext& mIslandThreadContext;
PxI32 mVelIters;
PX_NOCOPY(SetupSolverConstraintsSubTask)
public:
static const PxU32 MaxPerTask = 64;
SetupSolverConstraintsSubTask(PxSolverConstraintDesc* contactDescPtr, PxConstraintBatchHeader* headers, PxU32 nbHeaders,
PxsContactManagerOutputIterator& outputs, PxReal stepDt, PxReal totalDt, PxReal invStepDt, PxReal invDtTotal,
PxReal biasCoefficient, ThreadContext& islandThreadContext, DynamicsTGSContext& context, PxI32 velIters) : Cm::Task(context.getContextId()),
mContactDescPtr(contactDescPtr), mHeaders(headers), mNbHeaders(nbHeaders), mOutputs(outputs), mStepDt(stepDt), mTotalDt(totalDt), mInvStepDt(invStepDt),
mInvDtTotal(invDtTotal), mBiasCoefficient(biasCoefficient), mContext(context), mIslandThreadContext(islandThreadContext),
mVelIters(velIters)
{
}
virtual const char* getName() const { return "SetupSolverConstraintsSubTask"; }
virtual void runInternal()
{
ThreadContext* tempContext = mContext.getThreadContext();
tempContext->mConstraintBlockStream.reset();
mContext.createSolverConstraints(mContactDescPtr, mHeaders, mNbHeaders, mOutputs, mIslandThreadContext, *tempContext, mStepDt, mTotalDt, mInvStepDt,
mBiasCoefficient, mVelIters);
mContext.putThreadContext(tempContext);
}
};
class PxsCreateArticConstraintsSubTask : public Cm::Task
{
PxsCreateArticConstraintsSubTask& operator=(const PxsCreateArticConstraintsSubTask&);
public:
static const PxU32 NbArticsPerTask = 64;
PxsCreateArticConstraintsSubTask(Dy::FeatherstoneArticulation** articulations, const PxU32 nbArticulations,
PxTGSSolverBodyData* solverBodyData, PxTGSSolverBodyTxInertia* solverBodyTxInertia,
ThreadContext& threadContext, DynamicsTGSContext& context, PxsContactManagerOutputIterator& outputs,
Dy::IslandContextStep& islandContext) :
Cm::Task(context.getContextId()),
mArticulations(articulations),
mNbArticulations(nbArticulations),
mSolverBodyData(solverBodyData),
mSolverBodyTxInertia(solverBodyTxInertia),
mThreadContext(threadContext), mDynamicsContext(context),
mOutputs(outputs),
mIslandContext(islandContext)
{}
virtual void runInternal()
{
const PxReal correlationDist = mDynamicsContext.getCorrelationDistance();
const PxReal bounceThreshold = mDynamicsContext.getBounceThreshold();
const PxReal frictionOffsetThreshold = mDynamicsContext.getFrictionOffsetThreshold();
const PxReal dt = mDynamicsContext.getDt();
const PxReal invStepDt = PxMin(mDynamicsContext.getMaxBiasCoefficient(), mIslandContext.mInvStepDt);
PxReal denom = dt;
if (mIslandContext.mVelIters)
denom += mIslandContext.mStepDt;
PxReal invDt = 1.f / denom;
ThreadContext* threadContext = mDynamicsContext.getThreadContext();
threadContext->mConstraintBlockStream.reset(); //ensure there's no left-over memory that belonged to another island
/*threadContext->mZVector.forceSize_Unsafe(0);
threadContext->mZVector.reserve(mThreadContext.mMaxArticulationLinks);
threadContext->mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);*/
for (PxU32 i = 0; i < mNbArticulations; ++i)
{
mArticulations[i]->prepareStaticConstraintsTGS(mIslandContext.mStepDt, dt, invStepDt, invDt, mOutputs, *threadContext, correlationDist, bounceThreshold, frictionOffsetThreshold,
mSolverBodyData, mSolverBodyTxInertia, mThreadContext.mConstraintBlockManager, mDynamicsContext.getConstraintWriteBackPool().begin(),
mIslandContext.mBiasCoefficient, mDynamicsContext.getLengthScale());
}
mDynamicsContext.putThreadContext(threadContext);
}
virtual const char* getName() const
{
return "PxsDynamics.PxsCreateArticConstraintsSubTask";
}
public:
Dy::FeatherstoneArticulation** mArticulations;
PxU32 mNbArticulations;
PxTGSSolverBodyData* mSolverBodyData;
PxTGSSolverBodyTxInertia* mSolverBodyTxInertia;
ThreadContext& mThreadContext;
DynamicsTGSContext& mDynamicsContext;
PxsContactManagerOutputIterator& mOutputs;
IslandContextStep& mIslandContext;
};
class SetupSolverConstraintsTask : public Cm::Task
{
IslandContextStep& mIslandContext;
PxSolverConstraintDesc* mContactDescPtr;
PxsContactManagerOutputIterator& mOutputs;
Dy::ThreadContext& mThreadContext;
PxReal mTotalDt;
DynamicsTGSContext& mContext;
PX_NOCOPY(SetupSolverConstraintsTask)
public:
SetupSolverConstraintsTask(IslandContextStep& islandContext, PxSolverConstraintDesc* contactDescPtr,
PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& threadContext, PxReal totalDt, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mContactDescPtr(contactDescPtr), mOutputs(outputs), mThreadContext(threadContext),
mTotalDt(totalDt), mContext(context)
{
}
virtual const char* getName() const { return "SetupSolverConstraintsTask"; }
virtual void runInternal()
{
Dy::ThreadContext& threadContext = *mIslandContext.mThreadContext;
const PxU32 nbBatches = threadContext.numContactConstraintBatches;
PxConstraintBatchHeader* hdr = mIslandContext.mObjects.constraintBatchHeaders;
//for (PxU32 a = 0; a < mIslandContext.mArticulationOffset; a += SetupSolverConstraintsSubTask::MaxPerTask)
for (PxU32 a = 0; a < nbBatches; a += SetupSolverConstraintsSubTask::MaxPerTask)
{
const PxU32 nbConstraints = PxMin(nbBatches - a, SetupSolverConstraintsSubTask::MaxPerTask);
SetupSolverConstraintsSubTask* task = PX_PLACEMENT_NEW(mContext.mTaskPool.allocate(sizeof(SetupSolverConstraintsSubTask)), SetupSolverConstraintsSubTask)
(mContactDescPtr, hdr + a, nbConstraints, mOutputs, mIslandContext.mStepDt, mTotalDt, mIslandContext.mInvStepDt, mContext.mInvDt, mIslandContext.mBiasCoefficient, mThreadContext, mContext,
mIslandContext.mVelIters);
task->setContinuation(mCont);
task->removeReference();
}
const PxU32 articCount = mIslandContext.mCounts.articulations;
for (PxU32 i = 0; i < articCount; i += PxsCreateArticConstraintsSubTask::NbArticsPerTask)
{
const PxU32 nbToProcess = PxMin(articCount - i, PxsCreateArticConstraintsSubTask::NbArticsPerTask);
PxsCreateArticConstraintsSubTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(PxsCreateArticConstraintsSubTask)), PxsCreateArticConstraintsSubTask)
(mThreadContext.mArticulationArray + i, nbToProcess, mContext.mSolverBodyDataPool2.begin(), mContext.mSolverBodyTxInertiaPool.begin(), mThreadContext, mContext, mOutputs,
mIslandContext);
task->setContinuation(mCont);
task->removeReference();
}
}
};
class PartitionTask : public Cm::Task
{
IslandContextStep& mIslandContext;
const PxSolverConstraintDesc* mContactDescPtr;
PxTGSSolverBodyVel* mSolverBodyData;
Dy::ThreadContext& mThreadContext;
DynamicsTGSContext& mContext;
PX_NOCOPY(PartitionTask)
public:
PartitionTask(IslandContextStep& islandContext, PxSolverConstraintDesc* contactDescPtr, PxTGSSolverBodyVel* solverBodyData,
Dy::ThreadContext& threadContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mContactDescPtr(contactDescPtr), mSolverBodyData(solverBodyData), mThreadContext(threadContext),
mContext(context)
{
}
virtual const char* getName() const { return "PartitionTask"; }
virtual void runInternal()
{
const ArticulationSolverDesc* artics = mThreadContext.getArticulations().begin();
PxU32 totalDescCount = mThreadContext.contactDescArraySize;
mThreadContext.mConstraintsPerPartition.forceSize_Unsafe(0);
mThreadContext.mConstraintsPerPartition.resize(1);
mThreadContext.mConstraintsPerPartition[0] = 0;
ConstraintPartitionArgs args;
args.mBodies = reinterpret_cast<PxU8*>(mSolverBodyData);
args.mStride = sizeof(PxTGSSolverBodyVel);
args.mArticulationPtrs = artics;
args.mContactConstraintDescriptors = mContactDescPtr;
args.mNumArticulationPtrs = mThreadContext.getArticulations().size();
args.mNumBodies = mIslandContext.mCounts.bodies;
args.mNumContactConstraintDescriptors = totalDescCount;
args.mOrderedContactConstraintDescriptors = mIslandContext.mObjects.orderedConstraintDescs;
args.mOverflowConstraintDescriptors = mIslandContext.mObjects.tempConstraintDescs;
args.mNumDifferentBodyConstraints = args.mNumSelfConstraints = args.mNumStaticConstraints = 0;
args.mConstraintsPerPartition = &mThreadContext.mConstraintsPerPartition;
args.mNumOverflowConstraints = 0;
//args.mBitField = &mThreadContext.mPartitionNormalizationBitmap; // PT: removed, unused
args.mEnhancedDeterminism = false;
args.mForceStaticConstraintsToSolver = false;
args.mMaxPartitions = 64;
mThreadContext.mMaxPartitions = partitionContactConstraints(args);
mThreadContext.mNumDifferentBodyConstraints = args.mNumDifferentBodyConstraints;
mThreadContext.mNumSelfConstraints = args.mNumSelfConstraints;
mThreadContext.mNumStaticConstraints = args.mNumStaticConstraints;
mThreadContext.mHasOverflowPartitions = args.mNumOverflowConstraints != 0;
{
PxU32 descCount = mThreadContext.mNumDifferentBodyConstraints;
PxU32 selfConstraintDescCount = mThreadContext.contactDescArraySize - (mThreadContext.mNumDifferentBodyConstraints + mThreadContext.mNumStaticConstraints);
PxArray<PxU32>& accumulatedConstraintsPerPartition = mThreadContext.mConstraintsPerPartition;
PxU32 numHeaders = 0;
PxU32 currentPartition = 0;
PxU32 maxJ = descCount == 0 ? 0 : accumulatedConstraintsPerPartition[0];
const PxU32 maxBatchPartition = 0xFFFFFFFF;
const PxU32 maxBatchSize2 = args.mEnhancedDeterminism ? 1u : 4u;
PxConstraintBatchHeader* batchHeaders = mIslandContext.mObjects.constraintBatchHeaders;
PxSolverConstraintDesc* orderedConstraints = mIslandContext.mObjects.orderedConstraintDescs;
PxU32 headersPerPartition = 0;
//KS - if we have overflowed the partition limit, overflow constraints are pushed
//into 0th partition. If that's the case, we need to disallow batching of constraints
//in 0th partition.
PxU32 maxBatchSize = args.mNumOverflowConstraints == 0 ? maxBatchSize2 : 1;
for (PxU32 a = 0; a < descCount;)
{
PxU32 loopMax = PxMin(maxJ - a, maxBatchSize);
PxU16 j = 0;
if (loopMax > 0)
{
PxConstraintBatchHeader& header = batchHeaders[numHeaders++];
j = 1;
PxSolverConstraintDesc& desc = orderedConstraints[a];
if (!isArticulationConstraint(desc) && (desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT ||
desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D) && currentPartition < maxBatchPartition)
{
for (; j < loopMax && desc.constraintLengthOver16 == orderedConstraints[a + j].constraintLengthOver16 &&
!isArticulationConstraint(orderedConstraints[a + j]); ++j);
}
header.startIndex = a;
header.stride = j;
header.constraintType = desc.constraintLengthOver16;
headersPerPartition++;
}
if (maxJ == (a + j) && maxJ != descCount)
{
//Go to next partition!
accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition;
headersPerPartition = 0;
currentPartition++;
maxJ = accumulatedConstraintsPerPartition[currentPartition];
maxBatchSize = maxBatchSize2;
}
a += j;
}
if (descCount)
accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition;
accumulatedConstraintsPerPartition.forceSize_Unsafe(mThreadContext.mMaxPartitions);
PxU32 numDifferentBodyBatchHeaders = numHeaders;
for (PxU32 a = 0; a < selfConstraintDescCount; ++a)
{
PxConstraintBatchHeader& header = batchHeaders[numHeaders++];
header.startIndex = a + descCount;
header.stride = 1;
header.constraintType = DY_SC_TYPE_EXT_1D;
}
PxU32 numSelfConstraintBatchHeaders = numHeaders - numDifferentBodyBatchHeaders;
mThreadContext.numDifferentBodyBatchHeaders = numDifferentBodyBatchHeaders;
mThreadContext.numSelfConstraintBatchHeaders = numSelfConstraintBatchHeaders;
mThreadContext.numContactConstraintBatches = numHeaders;
}
}
};
class ParallelSolveTask : public Cm::Task
{
IslandContextStep& mIslandContext;
const SolverIslandObjectsStep& mObjects;
const PxsIslandIndices& mCounts;
ThreadContext& mThreadContext;
DynamicsTGSContext& mContext;
PX_NOCOPY(ParallelSolveTask)
public:
ParallelSolveTask(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& threadContext,
DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mObjects(objects), mCounts(counts), mThreadContext(threadContext), mContext(context)
{
}
virtual const char* getName() const { return "ParallelSolveTask"; }
virtual void runInternal()
{
mContext.iterativeSolveIslandParallel(mObjects, mCounts, mThreadContext, mIslandContext.mStepDt, mIslandContext.mPosIters, mIslandContext.mVelIters,
&mIslandContext.mSharedSolverIndex, &mIslandContext.mSharedRigidBodyIndex, &mIslandContext.mSharedArticulationIndex,
&mIslandContext.mSolvedCount, &mIslandContext.mRigidBodyIntegratedCount, &mIslandContext.mArticulationIntegratedCount,
4, 128, PxMin(0.5f, mIslandContext.mBiasCoefficient), mIslandContext.mBiasCoefficient);
}
};
class SolveIslandTask : public Cm::Task
{
IslandContextStep& mIslandContext;
const SolverIslandObjectsStep& mObjects;
const PxsIslandIndices& mCounts;
ThreadContext& mThreadContext;
DynamicsTGSContext& mContext;
PX_NOCOPY(SolveIslandTask)
public:
SolveIslandTask(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& threadContext,
DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mIslandContext(islandContext), mObjects(objects), mCounts(counts), mThreadContext(threadContext), mContext(context)
{
}
virtual const char* getName() const { return "SolveIslandTask"; }
virtual void runInternal()
{
PxU32 j = 0, i = 0;
PxU32 numBatches = 0;
PxU32 currIndex = 0;
PxU32 totalCount = 0;
PxSolverConstraintDesc* contactDescBegin = mObjects.orderedConstraintDescs;
PxSolverConstraintDesc* contactDescPtr = contactDescBegin;
PxConstraintBatchHeader* headers = mObjects.constraintBatchHeaders;
PxU32 totalPartitions = 0;
for (PxU32 a = 0; a < mThreadContext.mConstraintsPerPartition.size(); ++a)
{
PxU32 endIndex = currIndex + mThreadContext.mConstraintsPerPartition[a];
PxU32 numBatchesInPartition = 0;
for (PxU32 b = currIndex; b < endIndex; ++b)
{
PxConstraintBatchHeader& _header = headers[b];
PxU16 stride = _header.stride, newStride = _header.stride;
PxU32 startIndex = j;
for (PxU16 c = 0; c < stride; ++c)
{
if (getConstraintLength(contactDescBegin[i]) == 0)
{
newStride--;
i++;
}
else
{
if (i != j)
contactDescBegin[j] = contactDescBegin[i];
i++;
j++;
contactDescPtr++;
}
}
if (newStride != 0)
{
headers[numBatches].startIndex = startIndex;
headers[numBatches].stride = newStride;
PxU8 type = *contactDescBegin[startIndex].constraint;
if (type == DY_SC_TYPE_STATIC_CONTACT)
{
//Check if any block of constraints is classified as type static (single) contact constraint.
//If they are, iterate over all constraints grouped with it and switch to "dynamic" contact constraint
//type if there's a dynamic contact constraint in the group.
for (PxU32 c = 1; c < newStride; ++c)
{
if (*contactDescBegin[startIndex + c].constraint == DY_SC_TYPE_RB_CONTACT)
{
type = DY_SC_TYPE_RB_CONTACT;
}
}
}
headers[numBatches].constraintType = type;
numBatches++;
numBatchesInPartition++;
}
}
currIndex += mThreadContext.mConstraintsPerPartition[a];
mThreadContext.mConstraintsPerPartition[totalPartitions] = numBatchesInPartition;
if (numBatchesInPartition)
totalPartitions++;
else if (a == 0)
mThreadContext.mHasOverflowPartitions = false; //If our first partition is now empty, we have no overflows so clear the overflow flag
totalCount += numBatchesInPartition;
}
currIndex = totalCount;
processOverflowConstraints(reinterpret_cast<PxU8*>(mContext.mSolverBodyVelPool.begin() + mObjects.solverBodyOffset+1), sizeof(PxTGSSolverBodyVel),
mCounts.bodies, mThreadContext.getArticulations().begin(), mThreadContext.getArticulations().size(), contactDescBegin,
mThreadContext.mHasOverflowPartitions ? mThreadContext.mConstraintsPerPartition[0] : 0);
//Decision whether to spawn multi-threaded solver or single-threaded solver...
mThreadContext.mConstraintsPerPartition.forceSize_Unsafe(totalPartitions);
mThreadContext.numContactConstraintBatches = totalCount;
PxU32 maxLinks = 0;
for (PxU32 a = 0; a < mCounts.articulations; ++a)
{
ArticulationSolverDesc& desc = mThreadContext.getArticulations()[a];
maxLinks = PxMax(maxLinks, PxU32(desc.linkCount));
}
mThreadContext.mZVector.forceSize_Unsafe(0);
mThreadContext.mZVector.reserve(maxLinks);
mThreadContext.mZVector.forceSize_Unsafe(maxLinks);
mThreadContext.mDeltaV.forceSize_Unsafe(0);
mThreadContext.mDeltaV.reserve(maxLinks);
mThreadContext.mDeltaV.forceSize_Unsafe(maxLinks);
SolverContext cache;
cache.Z = mThreadContext.mZVector.begin();
cache.deltaV = mThreadContext.mDeltaV.begin();
if (mThreadContext.mConstraintsPerPartition.size())
{
const PxU32 threadCount = this->getTaskManager()->getCpuDispatcher()->getWorkerCount();
PxU32 nbHeadersPerPartition;
if (mThreadContext.mHasOverflowPartitions)
{
// jcarius: mitigating potential divide-by-zero problem. It's unclear whether size originally includes
// the overflow partition or not.
const PxU32 size = mThreadContext.mConstraintsPerPartition.size();
const PxU32 nbPartitionsMinusOverflow = (size > 1) ? (size - 1) : 1;
PxU32 nbConstraintsMinusOverflow = currIndex - mThreadContext.mConstraintsPerPartition[0];
nbHeadersPerPartition = ((nbConstraintsMinusOverflow + nbPartitionsMinusOverflow - 1) / nbPartitionsMinusOverflow);
}
else
nbHeadersPerPartition = ((currIndex + mThreadContext.mConstraintsPerPartition.size() - 1) / mThreadContext.mConstraintsPerPartition.size());
const PxU32 NbBatchesPerThread = 8;
//const PxU32 NbBatchesPerThread = 4;
const PxU32 nbIdealThreads = (nbHeadersPerPartition + NbBatchesPerThread-1) / NbBatchesPerThread;
if (threadCount < 2 || nbIdealThreads < 2)
mContext.iterativeSolveIsland(mObjects, mCounts, mThreadContext, mIslandContext.mStepDt, mIslandContext.mInvStepDt,
mIslandContext.mPosIters, mIslandContext.mVelIters, cache, PxMin(0.5f, mIslandContext.mBiasCoefficient), mIslandContext.mBiasCoefficient);
else
{
mIslandContext.mSharedSolverIndex = 0;
mIslandContext.mSolvedCount = 0;
mIslandContext.mSharedRigidBodyIndex = 0;
mIslandContext.mRigidBodyIntegratedCount = 0;
mIslandContext.mSharedArticulationIndex = 0;
mIslandContext.mArticulationIntegratedCount = 0;
PxU32 nbThreads = PxMin(threadCount, nbIdealThreads);
ParallelSolveTask* tasks = reinterpret_cast<ParallelSolveTask*>(mContext.getTaskPool().allocate(sizeof(ParallelSolveTask)*nbThreads));
for (PxU32 a = 0; a < nbThreads; ++a)
{
PX_PLACEMENT_NEW(&tasks[a], ParallelSolveTask)(mIslandContext, mObjects, mCounts, mThreadContext, mContext);
tasks[a].setContinuation(mCont);
tasks[a].removeReference();
}
}
}
else
{
mContext.iterativeSolveIsland(mObjects, mCounts, mThreadContext, mIslandContext.mStepDt,
mIslandContext.mInvStepDt, mIslandContext.mPosIters, mIslandContext.mVelIters, cache,
PxMin(0.5f, mIslandContext.mBiasCoefficient), mIslandContext.mBiasCoefficient);
}
}
};
class EndIslandTask : public Cm::Task
{
ThreadContext& mThreadContext;
DynamicsTGSContext& mContext;
PX_NOCOPY(EndIslandTask)
public:
EndIslandTask(ThreadContext& threadContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mThreadContext(threadContext), mContext(context)
{
}
virtual const char* getName() const { return "EndIslandTask"; }
virtual void runInternal()
{
mContext.endIsland(mThreadContext);
}
};
class FinishSolveIslandTask : public Cm::Task
{
ThreadContext& mThreadContext;
const SolverIslandObjectsStep& mObjects;
const PxsIslandIndices& mCounts;
IG::SimpleIslandManager& mIslandManager;
DynamicsTGSContext& mContext;
PX_NOCOPY(FinishSolveIslandTask)
public:
FinishSolveIslandTask(ThreadContext& threadContext, const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts, IG::SimpleIslandManager& islandManager, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mThreadContext(threadContext), mObjects(objects), mCounts(counts), mIslandManager(islandManager), mContext(context)
{
}
virtual const char* getName() const { return "FinishSolveIslandTask"; }
virtual void runInternal()
{
mContext.finishSolveIsland(mThreadContext, mObjects, mCounts, mIslandManager, mCont);
}
};
void DynamicsTGSContext::iterativeSolveIsland(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext,
PxReal stepDt, PxReal invStepDt, PxU32 posIters, PxU32 velIters, SolverContext& cache, PxReal ratio, PxReal biasCoefficient)
{
PX_PROFILE_ZONE("Dynamics:solveIsland", mContextID);
PxReal elapsedTime = 0.0f;
const PxReal recipStepDt = 1.0f/stepDt;
const PxU32 bodyOffset = objects.solverBodyOffset;
if (mThreadContext.numContactConstraintBatches == 0)
{
for (PxU32 i = 0; i < counts.articulations; ++i)
{
elapsedTime = 0.0f;
ArticulationSolverDesc& d = mThreadContext.getArticulations()[i];
for (PxU32 a = 0; a < posIters; a++)
{
d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient);
ArticulationPImpl::updateDeltaMotion(d, stepDt, mThreadContext.mDeltaV.begin(), mInvDt);
elapsedTime += stepDt;
}
ArticulationPImpl::saveVelocityTGS(d.articulation, mInvDt);
d.articulation->concludeInternalConstraints(true);
for (PxU32 a = 0; a < velIters; ++a)
{
d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), true, true, elapsedTime, biasCoefficient);
}
d.articulation->writebackInternalConstraints(true);
}
integrateBodies(objects, counts.bodies, mSolverBodyVelPool.begin() + bodyOffset, mSolverBodyTxInertiaPool.begin() + bodyOffset, mSolverBodyDataPool2.begin() + bodyOffset, mDt,
mInvDt, false, ratio);
return;
}
for (PxU32 a = 1; a < posIters; a++)
{
solveConstraintsIteration(objects.orderedConstraintDescs, objects.constraintBatchHeaders, mThreadContext.numContactConstraintBatches, invStepDt,
mSolverBodyTxInertiaPool.begin(), elapsedTime, -PX_MAX_F32, cache);
integrateBodies(objects, counts.bodies, mSolverBodyVelPool.begin() + bodyOffset, mSolverBodyTxInertiaPool.begin() + bodyOffset,
mSolverBodyDataPool2.begin() + bodyOffset, stepDt, mInvDt, false, ratio);
for (PxU32 i = 0; i < counts.articulations; ++i)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[i];
d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient);
}
stepArticulations(mThreadContext, counts, stepDt, mInvDt);
elapsedTime += stepDt;
}
solveConcludeConstraintsIteration<false>(objects.orderedConstraintDescs, objects.constraintBatchHeaders, mThreadContext.numContactConstraintBatches,
mSolverBodyTxInertiaPool.begin(), elapsedTime, cache, 0);
for (PxU32 i = 0; i < counts.articulations; ++i)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[i];
d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient);
d.articulation->concludeInternalConstraints(true);
}
elapsedTime += stepDt;
const PxReal invDt = mInvDt;
integrateBodies(objects, counts.bodies, mSolverBodyVelPool.begin() + bodyOffset, mSolverBodyTxInertiaPool.begin() + bodyOffset,
mSolverBodyDataPool2.begin() + bodyOffset, stepDt, mInvDt, false, ratio);
stepArticulations(mThreadContext, counts, stepDt, mInvDt);
for(PxU32 a = 0; a < counts.articulations; ++a)
{
Dy::ArticulationSolverDesc& desc = mThreadContext.getArticulations()[a];
//ArticulationPImpl::updateDeltaMotion(desc, stepDt, mThreadContext.mDeltaV.begin());
ArticulationPImpl::saveVelocityTGS(desc.articulation, invDt);
}
for (PxU32 a = 0; a < velIters; ++a)
{
solveConstraintsIteration(objects.orderedConstraintDescs, objects.constraintBatchHeaders, mThreadContext.numContactConstraintBatches, invStepDt,
mSolverBodyTxInertiaPool.begin(), elapsedTime, /*-PX_MAX_F32*/0.f, cache);
for (PxU32 i = 0; i < counts.articulations; ++i)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[i];
d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), true, true, elapsedTime, biasCoefficient);
}
}
writebackConstraintsIteration(objects.constraintBatchHeaders, objects.orderedConstraintDescs, mThreadContext.numContactConstraintBatches);
for (PxU32 i = 0; i < counts.articulations; ++i)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[i];
d.articulation->writebackInternalConstraints(true);
}
}
void DynamicsTGSContext::iterativeSolveIslandParallel(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext,
PxReal stepDt, PxU32 posIters, PxU32 velIters, PxI32* solverCounts, PxI32* integrationCounts, PxI32* articulationIntegrationCounts,
PxI32* solverProgressCount, PxI32* integrationProgressCount, PxI32* articulationProgressCount, PxU32 solverUnrollSize, PxU32 integrationUnrollSize,
PxReal ratio, PxReal biasCoefficient)
{
PX_PROFILE_ZONE("Dynamics:solveIslandParallel", mContextID);
Dy::ThreadContext& threadContext = *getThreadContext();
PxU32 startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize;
PxU32 nbSolveRemaining = solverUnrollSize;
PxU32 startIntegrateIdx = PxU32(PxAtomicAdd(integrationCounts, PxI32(integrationUnrollSize))) - integrationUnrollSize;
PxU32 nbIntegrateRemaining = integrationUnrollSize;
//For now, just do articulations 1 at a time. Might need to tweak this later depending on performance
PxU32 startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1;
PxU32 targetSolverProgressCount = 0, targetIntegrationProgressCount = 0, targetArticulationProgressCount = 0;
const PxU32 nbSolverBatches = mThreadContext.numContactConstraintBatches;
const PxU32 nbBodies = counts.bodies;// + mKinematicCount;
const PxU32 nbArticulations = counts.articulations;
PxSolverConstraintDesc* contactDescs = objects.orderedConstraintDescs;
PxConstraintBatchHeader* batchHeaders = objects.constraintBatchHeaders;
PxTGSSolverBodyVel* solverVels = mSolverBodyVelPool.begin();
PxTGSSolverBodyTxInertia* solverTxInertias = mSolverBodyTxInertiaPool.begin();
const PxTGSSolverBodyData*const solverBodyData = mSolverBodyDataPool2.begin();
PxU32* constraintsPerPartitions = mThreadContext.mConstraintsPerPartition.begin();
const PxU32 nbPartitions = mThreadContext.mConstraintsPerPartition.size();
const PxU32 bodyOffset = objects.solverBodyOffset;
threadContext.mZVector.reserve(mThreadContext.mZVector.size());
threadContext.mDeltaV.reserve(mThreadContext.mZVector.size());
SolverContext cache;
cache.Z = threadContext.mZVector.begin();
cache.deltaV = threadContext.mDeltaV.begin();
PxReal elapsedTime = 0.0f;
PxReal invStepDt = 1.0f/ stepDt;
const bool overflow = mThreadContext.mHasOverflowPartitions;
PxU32 iterCount = 0;
const PxU32 maxDynamic0 = contactDescs[0].tgsBodyA->maxDynamicPartition;
PX_UNUSED(maxDynamic0);
for (PxU32 a = 1; a < posIters; ++a, targetIntegrationProgressCount += nbBodies, targetArticulationProgressCount += nbArticulations)
{
WAIT_FOR_PROGRESS(integrationProgressCount, PxI32(targetIntegrationProgressCount));
WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount));
PxU32 offset = 0;
for (PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
//Find the startIdx in the partition to process
PxU32 startIdx = startSolveIdx - targetSolverProgressCount;
const PxU32 nbBatches = constraintsPerPartitions[b];
PxU32 nbSolved = 0;
while (startIdx < nbBatches)
{
PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining);
PX_ASSERT(maxDynamic0 == contactDescs[0].tgsBodyA->maxDynamicPartition);
if (b == 0 && overflow)
parallelSolveConstraints<true>(contactDescs, batchHeaders + startIdx + offset, nbToSolve,
solverTxInertias, elapsedTime, -PX_MAX_F32, cache, iterCount);
else
parallelSolveConstraints<false>(contactDescs, batchHeaders + startIdx + offset, nbToSolve,
solverTxInertias, elapsedTime, -PX_MAX_F32, cache, iterCount);
PX_ASSERT(maxDynamic0 == contactDescs[0].tgsBodyA->maxDynamicPartition);
nbSolveRemaining -= nbToSolve;
startSolveIdx += nbToSolve;
startIdx += nbToSolve;
nbSolved += nbToSolve;
if (nbSolveRemaining == 0)
{
startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize;
nbSolveRemaining = solverUnrollSize;
startIdx = startSolveIdx - targetSolverProgressCount;
}
}
if (nbSolved)
PxAtomicAdd(solverProgressCount, PxI32(nbSolved));
targetSolverProgressCount += nbBatches;
offset += nbBatches;
}
iterCount++;
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
PxU32 integStartIdx = startIntegrateIdx - targetIntegrationProgressCount;
PxU32 nbIntegrated = 0;
while (integStartIdx < nbBodies)
{
PxU32 nbToIntegrate = PxMin(nbBodies - integStartIdx, nbIntegrateRemaining);
parallelIntegrateBodies(solverVels + integStartIdx + bodyOffset, solverTxInertias + integStartIdx + bodyOffset,
solverBodyData + integStartIdx + bodyOffset, nbToIntegrate, stepDt, iterCount, mInvDt, false, ratio);
nbIntegrateRemaining -= nbToIntegrate;
startIntegrateIdx += nbToIntegrate;
integStartIdx += nbToIntegrate;
nbIntegrated += nbToIntegrate;
if (nbIntegrateRemaining == 0)
{
startIntegrateIdx = PxU32(PxAtomicAdd(integrationCounts, PxI32(integrationUnrollSize))) - integrationUnrollSize;
nbIntegrateRemaining = integrationUnrollSize;
integStartIdx = startIntegrateIdx - targetIntegrationProgressCount;
}
}
if (nbIntegrated)
PxAtomicAdd(integrationProgressCount, PxI32(nbIntegrated));
PxU32 artIcStartIdx = startArticulationIdx - targetArticulationProgressCount;
PxU32 nbArticsProcessed = 0;
while (artIcStartIdx < nbArticulations)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[artIcStartIdx];
d.articulation->solveInternalConstraints(stepDt, invStepDt, threadContext.mZVector.begin(),
threadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient);
ArticulationPImpl::updateDeltaMotion(d, stepDt, cache.deltaV, mInvDt);
nbArticsProcessed++;
startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1;
artIcStartIdx = startArticulationIdx - targetArticulationProgressCount;
}
if (nbArticsProcessed)
PxAtomicAdd(articulationProgressCount, PxI32(nbArticsProcessed));
elapsedTime += stepDt;
}
{
WAIT_FOR_PROGRESS(integrationProgressCount, PxI32(targetIntegrationProgressCount));
WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount));
PxU32 offset = 0;
for (PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
//Find the startIdx in the partition to process
PxU32 startIdx = startSolveIdx - targetSolverProgressCount;
const PxU32 nbBatches = constraintsPerPartitions[b];
PxU32 nbSolved = 0;
while (startIdx < nbBatches)
{
PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining);
if (b == 0 && overflow)
solveConcludeConstraintsIteration<true>(contactDescs, batchHeaders + startIdx + offset, nbToSolve,
solverTxInertias, elapsedTime, cache, iterCount);
else
solveConcludeConstraintsIteration<false>(contactDescs, batchHeaders + startIdx + offset, nbToSolve,
solverTxInertias, elapsedTime, cache, iterCount);
nbSolveRemaining -= nbToSolve;
startSolveIdx += nbToSolve;
startIdx += nbToSolve;
nbSolved += nbToSolve;
if (nbSolveRemaining == 0)
{
startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize;
nbSolveRemaining = solverUnrollSize;
startIdx = startSolveIdx - targetSolverProgressCount;
}
}
if (nbSolved)
PxAtomicAdd(solverProgressCount, PxI32(nbSolved));
targetSolverProgressCount += nbBatches;
offset += nbBatches;
}
iterCount++;
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
const PxReal invDt = mInvDt;
//const PxReal invDtPt25 = mInvDt * 0.25f;
PxU32 integStartIdx = startIntegrateIdx - targetIntegrationProgressCount;
PxU32 nbIntegrated = 0;
while (integStartIdx < nbBodies)
{
PxU32 nbToIntegrate = PxMin(nbBodies - integStartIdx, nbIntegrateRemaining);
parallelIntegrateBodies(solverVels + integStartIdx + bodyOffset, solverTxInertias + integStartIdx + bodyOffset,
solverBodyData + integStartIdx + bodyOffset, nbToIntegrate, stepDt, iterCount, mInvDt, false, ratio);
nbIntegrateRemaining -= nbToIntegrate;
startIntegrateIdx += nbToIntegrate;
integStartIdx += nbToIntegrate;
nbIntegrated += nbToIntegrate;
if (nbIntegrateRemaining == 0)
{
startIntegrateIdx = PxU32(PxAtomicAdd(integrationCounts, PxI32(integrationUnrollSize))) - integrationUnrollSize;
nbIntegrateRemaining = integrationUnrollSize;
integStartIdx = startIntegrateIdx - targetIntegrationProgressCount;
}
}
if (nbIntegrated)
PxAtomicAdd(integrationProgressCount, PxI32(nbIntegrated));
PxU32 artIcStartIdx = startArticulationIdx - targetArticulationProgressCount;
PxU32 nbArticsProcessed = 0;
while (artIcStartIdx < nbArticulations)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[artIcStartIdx];
d.articulation->solveInternalConstraints(stepDt, invStepDt, threadContext.mZVector.begin(),
threadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient);
d.articulation->concludeInternalConstraints(true);
ArticulationPImpl::updateDeltaMotion(d, stepDt, cache.deltaV, mInvDt);
ArticulationPImpl::saveVelocityTGS(d.articulation, invDt);
nbArticsProcessed++;
startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1;
artIcStartIdx = startArticulationIdx - targetArticulationProgressCount;
}
if (nbArticsProcessed)
PxAtomicAdd(articulationProgressCount, PxI32(nbArticsProcessed));
elapsedTime += stepDt;
targetIntegrationProgressCount += nbBodies;
targetArticulationProgressCount += nbArticulations;
putThreadContext(&threadContext);
}
//Write back constraints...
WAIT_FOR_PROGRESS(integrationProgressCount, PxI32(targetIntegrationProgressCount));
WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount));
for (PxU32 a = 0; a < velIters; ++a)
{
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
const bool lastIter = (velIters - a) == 1;
PxU32 offset = 0;
for (PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
//Find the startIdx in the partition to process
PxU32 startIdx = startSolveIdx - targetSolverProgressCount;
const PxU32 nbBatches = constraintsPerPartitions[b];
PxU32 nbSolved = 0;
while (startIdx < nbBatches)
{
PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining);
if (b == 0 && overflow)
parallelSolveConstraints<true>(contactDescs, batchHeaders + startIdx + offset, nbToSolve,
solverTxInertias, elapsedTime, 0.f/*-PX_MAX_F32*/, cache, iterCount);
else
parallelSolveConstraints<false>(contactDescs, batchHeaders + startIdx + offset, nbToSolve,
solverTxInertias, elapsedTime, 0.f/*-PX_MAX_F32*/, cache, iterCount);
nbSolveRemaining -= nbToSolve;
startSolveIdx += nbToSolve;
startIdx += nbToSolve;
nbSolved += nbToSolve;
if (nbSolveRemaining == 0)
{
startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize;
nbSolveRemaining = solverUnrollSize;
startIdx = startSolveIdx - targetSolverProgressCount;
}
}
if (nbSolved)
PxAtomicAdd(solverProgressCount, PxI32(nbSolved));
targetSolverProgressCount += nbBatches;
offset += nbBatches;
}
WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount));
PxU32 artIcStartIdx = startArticulationIdx - targetArticulationProgressCount;
PxU32 nbArticsProcessed = 0;
while (artIcStartIdx < nbArticulations)
{
ArticulationSolverDesc& d = mThreadContext.getArticulations()[artIcStartIdx];
d.articulation->solveInternalConstraints(stepDt, invStepDt, threadContext.mZVector.begin(),
threadContext.mDeltaV.begin(), true, true, elapsedTime, biasCoefficient);
if (lastIter)
d.articulation->writebackInternalConstraints(true);
nbArticsProcessed++;
startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1;
artIcStartIdx = startArticulationIdx - targetArticulationProgressCount;
}
if (nbArticsProcessed)
PxAtomicAdd(articulationProgressCount, PxI32(nbArticsProcessed));
targetArticulationProgressCount += nbArticulations;
iterCount++;
WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount));
}
{
{
//Find the startIdx in the partition to process
PxU32 startIdx = startSolveIdx - targetSolverProgressCount;
const PxU32 nbBatches = nbSolverBatches;
PxU32 nbSolved = 0;
while (startIdx < nbBatches)
{
PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining);
parallelWritebackConstraintsIteration(contactDescs, batchHeaders + startIdx, nbToSolve);
nbSolveRemaining -= nbToSolve;
startSolveIdx += nbToSolve;
startIdx += nbToSolve;
nbSolved += nbToSolve;
if (nbSolveRemaining == 0)
{
startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize;
nbSolveRemaining = solverUnrollSize;
startIdx = startSolveIdx - targetSolverProgressCount;
}
}
if (nbSolved)
PxAtomicAdd(solverProgressCount, PxI32(nbSolved));
targetSolverProgressCount += nbBatches;
}
}
}
class CopyBackTask : public Cm::Task
{
const SolverIslandObjectsStep& mObjects;
PxTGSSolverBodyVel* mVels;
PxTGSSolverBodyTxInertia* mTxInertias;
PxTGSSolverBodyData* mSolverBodyDatas;
const PxReal mInvDt;
IG::IslandSim& mIslandSim;
const PxU32 mStartIdx;
const PxU32 mEndIdx;
DynamicsTGSContext& mContext;
PX_NOCOPY(CopyBackTask)
public:
CopyBackTask(const SolverIslandObjectsStep& objects,
PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
PxTGSSolverBodyData* solverBodyDatas, PxReal invDt, IG::IslandSim& islandSim,
PxU32 startIdx, PxU32 endIdx, DynamicsTGSContext& context) : Cm::Task(context.getContextId()),
mObjects(objects), mVels(vels), mTxInertias(txInertias), mSolverBodyDatas(solverBodyDatas), mInvDt(invDt),
mIslandSim(islandSim), mStartIdx(startIdx), mEndIdx(endIdx), mContext(context)
{
}
virtual const char* getName() const { return "CopyBackTask"; }
virtual void runInternal()
{
mContext.copyBackBodies(mObjects, mVels, mTxInertias, mSolverBodyDatas, mInvDt, mIslandSim, mStartIdx, mEndIdx);
}
};
class UpdateArticTask : public Cm::Task
{
Dy::ThreadContext& mThreadContext;
PxU32 mStartIdx;
PxU32 mEndIdx;
PxReal mDt;
DynamicsTGSContext& mContext;
PX_NOCOPY(UpdateArticTask)
public:
UpdateArticTask(Dy::ThreadContext& threadContext, PxU32 startIdx, PxU32 endIdx, PxReal dt, DynamicsTGSContext& context) :
Cm::Task(context.getContextId()),
mThreadContext(threadContext), mStartIdx(startIdx), mEndIdx(endIdx), mDt(dt), mContext(context)
{
}
virtual const char* getName() const { return "UpdateArticTask"; }
virtual void runInternal()
{
mContext.updateArticulations(mThreadContext, mStartIdx, mEndIdx, mDt);
}
};
void DynamicsTGSContext::finishSolveIsland(ThreadContext& mThreadContext, const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts, IG::SimpleIslandManager& islandManager, PxBaseTask* continuation)
{
mThreadContext.mConstraintBlockManager.reset();
mThreadContext.mConstraintBlockStream.reset();
const PxU32 NbBodiesPerTask = 512;
for (PxU32 a = 0; a < counts.bodies; a += NbBodiesPerTask)
{
CopyBackTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(CopyBackTask)), CopyBackTask)
(objects, mSolverBodyVelPool.begin() + objects.solverBodyOffset,
mSolverBodyTxInertiaPool.begin() + objects.solverBodyOffset, mSolverBodyDataPool2.begin() + objects.solverBodyOffset,
mInvDt, islandManager.getAccurateIslandSim(), a, PxMin(a + NbBodiesPerTask, counts.bodies),*this);
task->setContinuation(continuation);
task->removeReference();
}
const PxU32 NbArticsPerTask = 64;
for (PxU32 a = 0; a < counts.articulations; a += NbArticsPerTask)
{
UpdateArticTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(UpdateArticTask)), UpdateArticTask)
(mThreadContext, a, PxMin(counts.articulations, a+NbArticsPerTask), mDt, *this);
task->setContinuation(continuation);
task->removeReference();
}
}
void DynamicsTGSContext::endIsland(ThreadContext& mThreadContext)
{
putThreadContext(&mThreadContext);
}
void DynamicsTGSContext::solveIsland(const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts,
PxU32 solverBodyOffset,
IG::SimpleIslandManager& islandManager,
PxU32* bodyRemapTable, PxsMaterialManager* /*materialManager*/,
PxsContactManagerOutputIterator& iterator,
PxBaseTask* continuation)
{
ThreadContext& mThreadContext = *getThreadContext();
IslandContextStep& islandContext = *reinterpret_cast<IslandContextStep*>(mTaskPool.allocate(sizeof(IslandContextStep)));
islandContext.mThreadContext = &mThreadContext;
islandContext.mCounts = counts;
islandContext.mObjects = objects;
islandContext.mPosIters = 0;
islandContext.mVelIters = 0;
islandContext.mObjects.solverBodyOffset = solverBodyOffset;
prepareBodiesAndConstraints(islandContext.mObjects, islandManager, islandContext);
////Create task chain...
SetupDescsTask* descTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupDescsTask)), SetupDescsTask)(islandContext, islandContext.mObjects,
bodyRemapTable, solverBodyOffset, iterator, *this);
PreIntegrateTask* intTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(PreIntegrateTask)), PreIntegrateTask)(islandContext.mObjects.bodyCoreArray, islandContext.mObjects.bodies,
mSolverBodyVelPool.begin() + solverBodyOffset,
mSolverBodyTxInertiaPool.begin() + solverBodyOffset, mSolverBodyDataPool2.begin() + solverBodyOffset,
mThreadContext.mNodeIndexArray, islandContext.mCounts.bodies, mGravity, mDt, islandContext.mPosIters,
islandContext.mVelIters, *this);
SetupArticulationTask* articTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupArticulationTask)), SetupArticulationTask)(islandContext, mGravity,
mDt, islandContext.mPosIters, islandContext.mVelIters, *this);
SetStepperTask* stepperTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetStepperTask)), SetStepperTask)(islandContext, *this);
SetupArticulationInternalConstraintsTask* articConTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupArticulationInternalConstraintsTask)), SetupArticulationInternalConstraintsTask)
(islandContext, mDt, mInvDt, *this);
PartitionTask* partitionTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(PartitionTask)), PartitionTask)
(islandContext, islandContext.mObjects.constraintDescs, mSolverBodyVelPool.begin()+solverBodyOffset+1, mThreadContext,
*this);
SetupSolverConstraintsTask* constraintTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupSolverConstraintsTask)), SetupSolverConstraintsTask)
(islandContext, islandContext.mObjects.orderedConstraintDescs, iterator, mThreadContext,
mDt, *this);
SolveIslandTask* solveTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SolveIslandTask)), SolveIslandTask)(islandContext, islandContext.mObjects, islandContext.mCounts, mThreadContext, *this);
FinishSolveIslandTask* finishTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(FinishSolveIslandTask)), FinishSolveIslandTask)(mThreadContext, islandContext.mObjects, islandContext.mCounts, islandManager, *this);
EndIslandTask* endTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(EndIslandTask)), EndIslandTask)(mThreadContext, *this);
endTask->setContinuation(continuation);
finishTask->setContinuation(endTask);
solveTask->setContinuation(finishTask);
constraintTask->setContinuation(solveTask);
partitionTask->setContinuation(constraintTask);
articConTask->setContinuation(partitionTask);
//Stepper triggers both articCon and constraintTask
stepperTask->setContinuation(articConTask);
stepperTask->setAdditionalContinuation(constraintTask);
articTask->setContinuation(stepperTask);
intTask->setContinuation(stepperTask);
descTask->setContinuation(stepperTask);
endTask->removeReference();
finishTask->removeReference();
solveTask->removeReference();
constraintTask->removeReference();
partitionTask->removeReference();
articConTask->removeReference();
stepperTask->removeReference();
articTask->removeReference();
intTask->removeReference();
descTask->removeReference();
}
void DynamicsTGSContext::mergeResults()
{
}
}
}
| 119,518 | C++ | 36.025713 | 257 | 0.769934 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyThreadContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_THREAD_CONTEXT_H
#define DY_THREAD_CONTEXT_H
#include "foundation/PxTransform.h"
#include "geomutils/PxContactBuffer.h"
#include "PxvConfig.h"
#include "PxvDynamics.h"
#include "PxcThreadCoherentCache.h"
#include "PxcConstraintBlockStream.h"
#include "foundation/PxBitMap.h"
#include "DyThresholdTable.h"
#include "DyVArticulation.h"
#include "DyFrictionPatchStreamPair.h"
#include "DySolverConstraintDesc.h"
#include "DyCorrelationBuffer.h"
#include "foundation/PxAllocator.h"
namespace physx
{
struct PxsIndexedContactManager;
namespace Dy
{
/*!
Cache information specific to the software implementation(non common).
See PxcgetThreadContext.
Not thread-safe, so remember to have one object per thread!
TODO! refactor this and rename(it is a general per thread cache). Move transform cache into its own class.
*/
class ThreadContext :
public PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool>::EntryBase
{
PX_NOCOPY(ThreadContext)
public:
#if PX_ENABLE_SIM_STATS
struct ThreadSimStats
{
void clear()
{
numActiveConstraints = 0;
numActiveDynamicBodies = 0;
numActiveKinematicBodies = 0;
numAxisSolverConstraints = 0;
}
PxU32 numActiveConstraints;
PxU32 numActiveDynamicBodies;
PxU32 numActiveKinematicBodies;
PxU32 numAxisSolverConstraints;
};
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//TODO: tune cache size based on number of active objects.
ThreadContext(PxcNpMemBlockPool* memBlockPool);
void reset();
void resizeArrays(PxU32 frictionConstraintDescCount, PxU32 articulationCount);
PX_FORCE_INLINE PxArray<ArticulationSolverDesc>& getArticulations() { return mArticulations; }
#if PX_ENABLE_SIM_STATS
PX_FORCE_INLINE ThreadSimStats& getSimStats()
{
return mThreadSimStats;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxContactBuffer mContactBuffer;
// temporary buffer for correlation
PX_ALIGN(16, CorrelationBuffer mCorrelationBuffer);
FrictionPatchStreamPair mFrictionPatchStreamPair; // patch streams
PxsConstraintBlockManager mConstraintBlockManager; // for when this thread context is "lead" on an island
PxcConstraintBlockStream mConstraintBlockStream; // constraint block pool
// this stuff is just used for reformatting the solver data. Hopefully we should have a more
// sane format for this when the dust settles - so it's just temporary. If we keep this around
// here we should move these from public to private
PxU32 mNumDifferentBodyConstraints;
PxU32 mNumDifferentBodyFrictionConstraints;
PxU32 mNumSelfConstraints;
PxU32 mNumStaticConstraints;
PxU32 mNumSelfFrictionConstraints;
PxU32 mNumSelfConstraintFrictionBlocks;
bool mHasOverflowPartitions;
PxArray<PxU32> mConstraintsPerPartition;
PxArray<PxU32> mFrictionConstraintsPerPartition;
PxArray<PxU32> mPartitionNormalizationBitmap;
PxsBodyCore** mBodyCoreArray;
PxsRigidBody** mRigidBodyArray;
FeatherstoneArticulation** mArticulationArray;
Cm::SpatialVector* motionVelocityArray;
PxU32* bodyRemapTable;
PxU32* mNodeIndexArray;
//Constraint info for normal constraint sovler
PxSolverConstraintDesc* contactConstraintDescArray;
PxU32 contactDescArraySize;
PxSolverConstraintDesc* orderedContactConstraints;
PxConstraintBatchHeader* contactConstraintBatchHeaders;
PxU32 numContactConstraintBatches;
//Constraint info for partitioning
PxSolverConstraintDesc* tempConstraintDescArray;
//Additional constraint info for 1d/2d friction model
PxArray<PxSolverConstraintDesc> frictionConstraintDescArray;
PxArray<PxConstraintBatchHeader> frictionConstraintBatchHeaders;
//Info for tracking compound contact managers (temporary data - could use scratch memory!)
PxArray<CompoundContactManager> compoundConstraints;
//Used for sorting constraints. Temporary, could use scratch memory
PxArray<const PxsIndexedContactManager*> orderedContactList;
PxArray<const PxsIndexedContactManager*> tempContactList;
PxArray<PxU32> sortIndexArray;
PxArray<Cm::SpatialVectorF> mZVector;
PxArray<Cm::SpatialVectorF> mDeltaV;
PxU32 numDifferentBodyBatchHeaders;
PxU32 numSelfConstraintBatchHeaders;
PxU32 mOrderedContactDescCount;
PxU32 mOrderedFrictionDescCount;
PxU32 mConstraintSize;
PxU32 mAxisConstraintCount;
SelfConstraintBlock* mSelfConstraintBlocks;
SelfConstraintBlock* mSelfConstraintFrictionBlocks;
PxU32 mMaxPartitions;
PxU32 mMaxFrictionPartitions;
PxU32 mMaxSolverPositionIterations;
PxU32 mMaxSolverVelocityIterations;
PxU32 mMaxArticulationLinks;
PxSolverConstraintDesc* mContactDescPtr;
PxSolverConstraintDesc* mStartContactDescPtr;
PxSolverConstraintDesc* mFrictionDescPtr;
private:
PxArray<ArticulationSolverDesc> mArticulations;
#if PX_ENABLE_SIM_STATS
ThreadSimStats mThreadSimStats;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
public:
};
}
}
#endif
| 6,651 | C | 30.526066 | 107 | 0.78725 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrepPF.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DySolverContact.h"
#include "DySolverContactPF.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
using namespace physx::Gu;
using namespace physx::aos;
namespace physx
{
namespace Dy
{
bool createFinalizeSolverContactsCoulomb(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
PxFrictionType::Enum frictionType,
Cm::SpatialVectorF* Z);
static bool setupFinalizeSolverConstraintsCoulomb(Sc::ShapeInteraction* shapeInteraction,
const PxContactBuffer& buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const PxSolverBodyData& data0,
const PxSolverBodyData& data1,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxU32 frictionPerPointCount,
const bool hasForceThresholds,
const bool staticBody,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
PxReal restDist,
const PxReal maxCCDSeparation,
const PxReal solverOffsetSlopF32)
{
const FloatV ccdMaxSeparation = FLoad(maxCCDSeparation);
const Vec3V solverOffsetSlop = V3Load(solverOffsetSlopF32);
PxU8* PX_RESTRICT ptr = workspace;
const FloatV zero=FZero();
PxU8 flags = PxU8(hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0);
const FloatV restDistance = FLoad(restDist);
const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p);
const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p);
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
const PxU32 frictionPatchCount = c.frictionPatchCount;
const PxU32 pointStride = sizeof(SolverContactPoint);
const PxU32 frictionStride = sizeof(SolverContactFriction);
const PxU8 pointHeaderType = PxTo8(staticBody ? DY_SC_TYPE_STATIC_CONTACT : DY_SC_TYPE_RB_CONTACT);
const PxU8 frictionHeaderType = PxTo8(staticBody ? DY_SC_TYPE_STATIC_FRICTION : DY_SC_TYPE_FRICTION);
const Vec3V linVel0 = V3LoadU(data0.linearVelocity);
const Vec3V linVel1 = V3LoadU(data1.linearVelocity);
const Vec3V angVel0 = V3LoadU(data0.angularVelocity);
const Vec3V angVel1 = V3LoadU(data1.angularVelocity);
const FloatV invMass0 = FLoad(data0.invMass);
const FloatV invMass1 = FLoad(data1.invMass);
const FloatV maxPenBias = FMax(FLoad(data0.penBiasClamp), FLoad(data1.penBiasClamp));
// PT: the matrix is symmetric so we can read it as a PxMat33! Gets rid of 25000+ LHS.
const PxMat33& invIn0 = reinterpret_cast<const PxMat33&>(data0.sqrtInvInertia);
PX_ALIGN(16, const Mat33V invSqrtInertia0)
(
V3LoadU(invIn0.column0),
V3LoadU(invIn0.column1),
V3LoadU(invIn0.column2)
);
const PxMat33& invIn1 = reinterpret_cast<const PxMat33&>(data1.sqrtInvInertia);
PX_ALIGN(16, const Mat33V invSqrtInertia1)
(
V3LoadU(invIn1.column0),
V3LoadU(invIn1.column1),
V3LoadU(invIn1.column2)
);
const FloatV invDt = FLoad(invDtF32);
const FloatV dt = FLoad(dtF32);
const FloatV p8 = FLoad(0.8f);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const FloatV orthoThreshold = FLoad(0.70710678f);
const FloatV eps = FLoad(0.00001f);
const FloatV invDtp8 = FMul(invDt, p8);
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV nDom1fV = FNeg(d1);
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
const FloatV invMass0_dom0fV = FMul(d0, invMass0);
const FloatV invMass1_dom1fV = FMul(nDom1fV, invMass1);
for(PxU32 i=0;i< frictionPatchCount;i++)
{
const PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start;
const Vec3V normal = aos::V3LoadA(contactBase0->normal);
const FloatV normalLenSq = V3LengthSq(normal);
const VecCrossV norCross = V3PrepareCross(normal);
const FloatV restitution = FLoad(contactBase0->restitution);
const FloatV damping = FLoad(contactBase0->damping);
const FloatV norVel = V3SumElems(V3NegMulSub(normal, linVel1, V3Mul(normal, linVel0)));
/*const FloatV norVel0 = V3Dot(normal, linVel0);
const FloatV norVel1 = V3Dot(normal, linVel1);
const FloatV norVel = FSub(norVel0, norVel1);*/
const FloatV invMassNorLenSq0 = FMul(invMass0_dom0fV, normalLenSq);
const FloatV invMassNorLenSq1 = FMul(invMass1_dom1fV, normalLenSq);
SolverContactCoulombHeader* PX_RESTRICT header = reinterpret_cast<SolverContactCoulombHeader*>(ptr);
ptr += sizeof(SolverContactCoulombHeader);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
header->numNormalConstr = PxU8(contactCount);
header->type = pointHeaderType;
//header->setRestitution(n.restitution);
//header->setRestitution(contactBase0->restitution);
header->setDominance0(invMass0_dom0fV);
header->setDominance1(FNeg(invMass1_dom1fV));
FStore(angD0, &header->angDom0);
FStore(angD1, &header->angDom1);
header->setNormal(normal);
header->flags = flags;
header->shapeInteraction = shapeInteraction;
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer.contacts + c.contactPatches[patch].start;
PxU8* p = ptr;
for(PxU32 j=0;j<count;j++)
{
const PxContactPoint& contact = contactBase[j];
SolverContactPoint* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPoint*>(p);
p += pointStride;
constructContactConstraint(invSqrtInertia0, invSqrtInertia1, invMassNorLenSq0,
invMassNorLenSq1, angD0, angD1, bodyFrame0p, bodyFrame1p,
normal, norVel, norCross, angVel0, angVel1,
invDt, invDtp8, dt, restDistance, maxPenBias, restitution,
bounceThreshold, contact, *solverContact, ccdMaxSeparation, solverOffsetSlop, damping);
}
ptr = p;
}
}
//construct all the frictions
PxU8* PX_RESTRICT ptr2 = workspace;
bool hasFriction = false;
for(PxU32 i=0;i< frictionPatchCount;i++)
{
const PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start;
SolverContactCoulombHeader* header = reinterpret_cast<SolverContactCoulombHeader*>(ptr2);
header->frictionOffset = PxU16(ptr - ptr2);// + sizeof(SolverFrictionHeader);
ptr2 += sizeof(SolverContactCoulombHeader) + header->numNormalConstr * pointStride;
const PxReal staticFriction = contactBase0->staticFriction;
const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
const bool haveFriction = (disableStrongFriction == 0);
SolverFrictionHeader* frictionHeader = reinterpret_cast<SolverFrictionHeader*>(ptr);
frictionHeader->numNormalConstr = PxTo8(c.frictionPatchContactCounts[i]);
frictionHeader->numFrictionConstr = PxTo8(haveFriction ? c.frictionPatchContactCounts[i] * frictionPerPointCount : 0);
ptr += sizeof(SolverFrictionHeader);
PxF32* appliedForceBuffer = reinterpret_cast<PxF32*>(ptr);
ptr += frictionHeader->getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]);
PxMemZero(appliedForceBuffer, sizeof(PxF32)*contactCount*frictionPerPointCount);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
const Vec3V normal = V3LoadU(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV normalX = V3GetX(normal);
const FloatV normalY = V3GetY(normal);
const FloatV normalZ = V3GetZ(normal);
const Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY);
const Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero);
const BoolV con = FIsGrtr(orthoThreshold, FAbs(normalX));
const Vec3V tFallback1 = V3Sel(con, t0Fallback1, t0Fallback2);
const Vec3V linVrel = V3Sub(linVel0, linVel1);
const Vec3V t0_ = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel)));
const FloatV sqDist = V3Dot(t0_,t0_);
const BoolV con1 = FIsGrtr(sqDist, eps);
const Vec3V tDir0 = V3Normalize(V3Sel(con1, t0_, tFallback1));
const Vec3V tDir1 = V3Cross(tDir0, normal);
Vec3V tFallback = tDir0;
Vec3V tFallbackAlt = tDir1;
if(haveFriction)
{
//frictionHeader->setStaticFriction(n.staticFriction);
frictionHeader->setStaticFriction(staticFriction);
FStore(invMass0_dom0fV, &frictionHeader->invMass0D0);
FStore(FNeg(invMass1_dom1fV), &frictionHeader->invMass1D1);
FStore(angD0, &frictionHeader->angDom0);
FStore(angD1, &frictionHeader->angDom1);
frictionHeader->type = frictionHeaderType;
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxU32 start = c.contactPatches[patch].start;
const PxContactPoint* contactBase = buffer.contacts + start;
PxU8* p = ptr;
for(PxU32 j =0; j < count; j++)
{
hasFriction = true;
const PxContactPoint& contact = contactBase[j];
const Vec3V point = V3LoadU(contact.point);
Vec3V ra = V3Sub(point, bodyFrame0p);
Vec3V rb = V3Sub(point, bodyFrame1p);
ra = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(ra)), V3Zero(), ra);
rb = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rb)), V3Zero(), rb);
const Vec3V targetVel = V3LoadU(contact.targetVel);
for(PxU32 k = 0; k < frictionPerPointCount; ++k)
{
const Vec3V t0 = tFallback;
tFallback = tFallbackAlt;
tFallbackAlt = t0;
SolverContactFriction* PX_RESTRICT f0 = reinterpret_cast<SolverContactFriction*>(p);
p += frictionStride;
//f0->brokenOrContactIndex = contactId;
const Vec3V raXn = V3Cross(ra, t0);
const Vec3V rbXn = V3Cross(rb, t0);
const Vec3V delAngVel0 = M33MulV3(invSqrtInertia0, raXn);
const Vec3V delAngVel1 = M33MulV3(invSqrtInertia1, rbXn);
const FloatV resp0 = FAdd(invMass0_dom0fV, FMul(angD0, V3Dot(delAngVel0, delAngVel0)));
const FloatV resp1 = FSub(FMul(angD1, V3Dot(delAngVel1, delAngVel1)), invMass1_dom1fV);
const FloatV resp = FAdd(resp0, resp1);
const FloatV velMultiplier = FNeg(FSel(FIsGrtr(resp, zero), FRecip(resp), zero));
const FloatV vrel1 = FAdd(V3Dot(t0, linVel0), V3Dot(raXn, angVel0));
const FloatV vrel2 = FAdd(V3Dot(t0, linVel1), V3Dot(rbXn, angVel1));
const FloatV vrel = FSub(vrel1, vrel2);
f0->normalXYZ_appliedForceW = V4SetW(Vec4V_From_Vec3V(t0), zero);
f0->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(delAngVel0), velMultiplier);
//f0->rbXnXYZ_targetVelocityW = V4SetW(Vec4V_From_Vec3V(delAngVel1), FSub(V3Dot(targetVel, t0), vrel));
f0->rbXnXYZ_biasW = Vec4V_From_Vec3V(delAngVel1);
FStore(FSub(V3Dot(targetVel, t0), vrel), &f0->targetVel);
}
}
ptr = p;
}
}
}
*ptr = 0;
return hasFriction;
}
static void computeBlockStreamByteSizesCoulomb( const CorrelationBuffer& c,
const PxU32 frictionCountPerPoint, PxU32& _solverConstraintByteSize,
PxU32& _axisConstraintCount, bool useExtContacts)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PX_ASSERT(0 == _axisConstraintCount);
// PT: use local vars to remove LHS
PxU32 solverConstraintByteSize = 0;
PxU32 numFrictionPatches = 0;
PxU32 axisConstraintCount = 0;
for(PxU32 i = 0; i < c.frictionPatchCount; i++)
{
//Friction patches.
if(c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0;
//Solver constraint data.
if(c.frictionPatchContactCounts[i]!=0)
{
solverConstraintByteSize += sizeof(SolverContactCoulombHeader);
solverConstraintByteSize += useExtContacts ? c.frictionPatchContactCounts[i] * sizeof(SolverContactPointExt)
: c.frictionPatchContactCounts[i] * sizeof(SolverContactPoint);
axisConstraintCount += c.frictionPatchContactCounts[i];
//We always need the friction headers to write the accumulated
if(haveFriction)
{
//4 bytes
solverConstraintByteSize += sizeof(SolverFrictionHeader);
//buffer to store applied forces in
solverConstraintByteSize += SolverFrictionHeader::getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]);
const PxU32 nbFrictionConstraints = c.frictionPatchContactCounts[i] * frictionCountPerPoint;
solverConstraintByteSize += useExtContacts ? nbFrictionConstraints * sizeof(SolverContactFrictionExt)
: nbFrictionConstraints * sizeof(SolverContactFriction);
axisConstraintCount += c.frictionPatchContactCounts[i];
}
else
{
//reserve buffers for storing accumulated impulses
solverConstraintByteSize += sizeof(SolverFrictionHeader);
solverConstraintByteSize += SolverFrictionHeader::getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]);
}
}
}
_axisConstraintCount = axisConstraintCount;
//16-byte alignment.
_solverConstraintByteSize = ((solverConstraintByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
}
static bool reserveBlockStreamsCoulomb(const CorrelationBuffer& c,
PxU8*& solverConstraint, PxU32 frictionCountPerPoint,
PxU32& solverConstraintByteSize,
PxU32& axisConstraintCount, PxConstraintAllocator& constraintAllocator,
bool useExtContacts)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(0 == solverConstraintByteSize);
PX_ASSERT(0 == axisConstraintCount);
//From constraintBlockStream we need to reserve contact points, contact forces, and a char buffer for the solver constraint data (already have a variable for this).
//From frictionPatchStream we just need to reserve a single buffer.
//Compute the sizes of all the buffers.
computeBlockStreamByteSizesCoulomb(
c,
frictionCountPerPoint, solverConstraintByteSize,
axisConstraintCount, useExtContacts);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if(constraintBlockByteSize > 0)
{
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock)
{
if(0==constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock=NULL;
}
}
}
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if(0==constraintBlockByteSize || constraintBlock)
{
if(solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f));
}
}
//Return true if neither of the two block reservations failed.
return ((0==constraintBlockByteSize || constraintBlock));
}
bool createFinalizeSolverContactsCoulomb1D(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z)
{
return createFinalizeSolverContactsCoulomb(contactDesc, output, threadContext, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance,
constraintAllocator, PxFrictionType::eONE_DIRECTIONAL, Z);
}
bool createFinalizeSolverContactsCoulomb2D(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z)
{
return createFinalizeSolverContactsCoulomb(contactDesc, output, threadContext, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance,
constraintAllocator, PxFrictionType::eTWO_DIRECTIONAL, Z);
}
bool createFinalizeSolverContactsCoulomb(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
PxFrictionType::Enum frictionType,
Cm::SpatialVectorF* Z)
{
PX_UNUSED(frictionOffsetThreshold);
PX_UNUSED(correlationDistance);
PxSolverConstraintDesc& desc = *contactDesc.desc;
desc.constraintLengthOver16 = 0;
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
// We pull the friction patches out of the cache to remove the dependency on how
// the cache is organized. Remember original addrs so we can write them back
// efficiently.
PxPrefetchLine(contactDesc.frictionPtr);
PxReal invMassScale0 = 1.f;
PxReal invMassScale1 = 1.f;
PxReal invInertiaScale0 = 1.f;
PxReal invInertiaScale1 = 1.f;
bool hasMaxImpulse = false, hasTargetVelocity = false;
PxU32 numContacts = extractContacts(buffer, output, hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, PxMin(contactDesc.data0->maxContactImpulse, contactDesc.data1->maxContactImpulse));
if(numContacts == 0)
{
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
return true;
}
PxPrefetchLine(contactDesc.body0);
PxPrefetchLine(contactDesc.body1);
PxPrefetchLine(contactDesc.data0);
PxPrefetchLine(contactDesc.data1);
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
createContactPatches(c, buffer.contacts, buffer.count, PXC_SAME_NORMAL);
PxU32 numFrictionPerPatch = PxU32(frictionType == PxFrictionType::eONE_DIRECTIONAL ? 1 : 2);
bool overflow = correlatePatches(c, buffer.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, PXC_SAME_NORMAL, 0, 0);
PX_UNUSED(overflow);
#if PX_CHECKED
if(overflow)
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL, "Dropping contacts in solver because we exceeded limit of 32 friction patches.");
#endif
//PX_ASSERT(patchCount == c.frictionPatchCount);
PxU8* solverConstraint = NULL;
PxU32 solverConstraintByteSize = 0;
PxU32 axisConstraintCount = 0;
const bool useExtContacts = !!((contactDesc.bodyState0 | contactDesc.bodyState1) & PxSolverContactDesc::eARTICULATION);
const bool successfulReserve = reserveBlockStreamsCoulomb(
c,
solverConstraint, numFrictionPerPatch,
solverConstraintByteSize,
axisConstraintCount,
constraintAllocator,
useExtContacts);
// initialise the work unit's ptrs to the various buffers.
contactDesc.frictionPtr = NULL;
desc.constraint = NULL;
desc.constraintLengthOver16 = 0;
contactDesc.frictionCount = 0;
// patch up the work unit with the reserved buffers and set the reserved buffer data as appropriate.
if(successfulReserve)
{
desc.constraint = solverConstraint;
output.nbContacts = PxTo16(numContacts);
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize/16);
//Initialise solverConstraint buffer.
if(solverConstraint)
{
bool hasFriction = false;
const PxSolverBodyData& data0 = *contactDesc.data0;
const PxSolverBodyData& data1 = *contactDesc.data1;
if(useExtContacts)
{
const SolverExtBody b0(reinterpret_cast<const void*>(contactDesc.body0), reinterpret_cast<const void*>(&data0), desc.linkIndexA);
const SolverExtBody b1(reinterpret_cast<const void*>(contactDesc.body1), reinterpret_cast<const void*>(&data1), desc.linkIndexB);
hasFriction = setupFinalizeExtSolverContactsCoulomb(buffer, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
invDtF32, dtF32, bounceThresholdF32, b0, b1, numFrictionPerPatch,
invMassScale0, invInertiaScale0, invMassScale1, invInertiaScale1, contactDesc.restDistance, contactDesc.maxCCDSeparation, Z,
contactDesc.offsetSlop);
}
else
{
hasFriction = setupFinalizeSolverConstraintsCoulomb(getInteraction(contactDesc), buffer, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
data0, data1, invDtF32, dtF32, bounceThresholdF32, numFrictionPerPatch, contactDesc.hasForceThresholds, contactDesc.bodyState1 == PxSolverContactDesc::eSTATIC_BODY,
invMassScale0, invInertiaScale0, invMassScale1, invInertiaScale1, contactDesc.restDistance, contactDesc.maxCCDSeparation, contactDesc.offsetSlop);
}
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize + 4)) = hasFriction ? 0xFFFFFFFF : 0;
}
}
return successfulReserve;
}
}
}
| 23,559 | C++ | 37 | 169 | 0.75572 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintTypes.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONSTRAINT_TYPES_H
#define DY_SOLVER_CONSTRAINT_TYPES_H
#include "foundation/PxSimpleTypes.h"
#include "PxvConfig.h"
namespace physx
{
enum SolverConstraintType
{
DY_SC_TYPE_NONE = 0,
DY_SC_TYPE_RB_CONTACT, // RB-only contact
DY_SC_TYPE_RB_1D, // RB-only 1D constraint
DY_SC_TYPE_EXT_CONTACT, // contact involving articulations
DY_SC_TYPE_EXT_1D, // 1D constraint involving articulations
DY_SC_TYPE_STATIC_CONTACT, // RB-only contact where body b is static
DY_SC_TYPE_NOFRICTION_RB_CONTACT, //RB-only contact with no friction patch
DY_SC_TYPE_BLOCK_RB_CONTACT,
DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT,
DY_SC_TYPE_BLOCK_1D,
// PT: the following types are only used in the PGS PF solver
DY_SC_TYPE_FRICTION,
DY_SC_TYPE_STATIC_FRICTION,
DY_SC_TYPE_EXT_FRICTION,
DY_SC_TYPE_BLOCK_FRICTION,
DY_SC_TYPE_BLOCK_STATIC_FRICTION,
DY_SC_CONSTRAINT_TYPE_COUNT //Count of the number of different constraint types in the solver
};
enum SolverConstraintFlags
{
DY_SC_FLAG_OUTPUT_FORCE = (1<<1),
DY_SC_FLAG_KEEP_BIAS = (1<<2),
DY_SC_FLAG_ROT_EQ = (1<<3),
DY_SC_FLAG_ORTHO_TARGET = (1<<4),
DY_SC_FLAG_SPRING = (1<<5),
DY_SC_FLAG_INEQUALITY = (1<<6)
};
}
#endif
| 2,910 | C | 38.337837 | 94 | 0.741581 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneInverseDynamic.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 "CmConeLimitHelper.h"
#include "DySolverConstraint1D.h"
#include "DyFeatherstoneArticulation.h"
#include "PxsRigidBody.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
#include "DyDynamics.h"
#include "DyArticulationPImpl.h"
#include "foundation/PxProfiler.h"
#include "extensions/PxContactJoint.h"
#include "DyFeatherstoneArticulationLink.h"
#include "DyFeatherstoneArticulationJointData.h"
#include "DyConstraint.h"
#include "DyConstraintPrep.h"
#include "DySolverContext.h"
namespace physx
{
namespace Dy
{
void PxcFsFlushVelocity(FeatherstoneArticulation& articulation, Cm::SpatialVectorF* deltaV, bool doConstraintForce);
void FeatherstoneArticulation::computeLinkAccelerationInv(ArticulationData& data, ScratchData& scratchData)
{
Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations;
Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors;
PxReal* jointAccelerations = scratchData.jointAccelerations;
motionAccelerations[0] = Cm::SpatialVectorF::Zero();
for (PxU32 linkID = 1; linkID < data.getLinkCount(); ++linkID)
{
ArticulationLink& link = data.getLink(linkID);
Cm::SpatialVectorF pMotionAcceleration = translateSpatialVector(-data.getRw(linkID), motionAccelerations[link.parent]);
Cm::SpatialVectorF motionAcceleration(PxVec3(0.f), PxVec3(0.f));
if (jointAccelerations)
{
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
const PxU32 jointOffset = jointDatum.jointOffset;
const PxReal* jAcceleration = &jointAccelerations[jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
motionAcceleration.top += data.mWorldMotionMatrix[jointOffset + ind].top * jAcceleration[ind];
motionAcceleration.bottom += data.mWorldMotionMatrix[jointOffset + ind].bottom * jAcceleration[ind];
}
}
motionAccelerations[linkID] = pMotionAcceleration + coriolisVectors[linkID] + motionAcceleration;
}
}
//generalized force
void FeatherstoneArticulation::computeGeneralizedForceInv(ArticulationData& data, ScratchData& scratchData)
{
const PxU32 linkCount = data.getLinkCount();
Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors;
PxReal* jointForces = scratchData.jointForces;
for (PxU32 linkID = (linkCount - 1); linkID > 0; --linkID)
{
ArticulationLink& link = data.getLink(linkID);
//joint force
spatialZAForces[link.parent] += translateSpatialVector(data.getRw(linkID), spatialZAForces[linkID]);
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
//compute generalized force
const PxU32 jointOffset = jointDatum.jointOffset;
PxReal* force = &jointForces[jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
force[ind] = data.mWorldMotionMatrix[jointOffset + ind].innerProduct(spatialZAForces[linkID]);
}
}
}
void FeatherstoneArticulation::computeZAForceInv(ArticulationData& data, ScratchData& scratchData)
{
const PxU32 linkCount = data.getLinkCount();
Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations;
Cm::SpatialVectorF* biasForce = scratchData.spatialZAVectors;
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
ArticulationLink& link = data.getLink(linkID);
PxsBodyCore& core = *link.bodyCore;
const PxVec3& ii = core.inverseInertia;
const PxReal m = core.inverseMass == 0.f ? 0.f : 1.0f / core.inverseMass;
const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z));
Cm::SpatialVectorF Ia;
Ia.bottom = core.body2World.rotate(core.body2World.rotateInv(motionAccelerations[linkID].top).multiply(inertiaTensor));
Ia.top = motionAccelerations[linkID].bottom * m;
biasForce[linkID] +=Ia;
}
}
void FeatherstoneArticulation::initCompositeSpatialInertia(ArticulationData& data, Dy::SpatialMatrix* compositeSpatialInertia)
{
const PxU32 linkCount = data.getLinkCount();
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
SpatialMatrix& spatialInertia = compositeSpatialInertia[linkID];
ArticulationLink& link = data.getLink(linkID);
PxsBodyCore& core = *link.bodyCore;
const PxVec3& ii = core.inverseInertia;
const PxReal m = core.inverseMass == 0.f ? 0.f : 1.0f / core.inverseMass;
//construct mass matric
spatialInertia.topLeft = PxMat33(PxZero);
spatialInertia.topRight = PxMat33::createDiagonal(PxVec3(m));
//construct inertia matrix
PxMat33 rot(data.getLink(linkID).bodyCore->body2World.q);
PxMat33& I = spatialInertia.bottomLeft;
const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z));
Cm::transformInertiaTensor(inertiaTensor, rot, I);
}
}
void FeatherstoneArticulation::computeCompositeSpatialInertiaAndZAForceInv(ArticulationData& data, ScratchData& scratchData)
{
ArticulationLink* links = data.getLinks();
const PxU32 linkCount = data.getLinkCount();
const PxU32 startIndex = PxU32(linkCount - 1);
Dy::SpatialMatrix* compositeSpatialInertia = scratchData.compositeSpatialInertias;
Cm::SpatialVectorF* zaForce = scratchData.spatialZAVectors;
initCompositeSpatialInertia(data, compositeSpatialInertia);
for (PxU32 linkID = startIndex; linkID > 0; --linkID)
{
ArticulationLink& link = links[linkID];
Dy::SpatialMatrix cSpatialInertia = compositeSpatialInertia[linkID];
translateInertia(FeatherstoneArticulation::constructSkewSymmetricMatrix(data.getRw(linkID)), cSpatialInertia);
//compute parent's composite spatial inertia
compositeSpatialInertia[link.parent] += cSpatialInertia;
//compute zero acceleration force. This is the force that would be required to support the
//motion of all the bodies in childen set if root node acceleration happened to be zero
zaForce[link.parent] += translateSpatialVector(data.getRw(linkID), zaForce[linkID]);
}
}
void FeatherstoneArticulation::computeRelativeGeneralizedForceInv(ArticulationData& data, ScratchData& scratchData)
{
Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations;
Dy::SpatialMatrix* compositeSpatialInertia = scratchData.compositeSpatialInertias;
Cm::SpatialVectorF* zaForce = scratchData.spatialZAVectors;
PxReal* jointForces = scratchData.jointForces;
Dy::SpatialMatrix invInertia = compositeSpatialInertia[0].invertInertia();
motionAccelerations[0] = -(invInertia * zaForce[0]);
const PxU32 linkCount = data.getLinkCount();
ArticulationLink* links = data.getLinks();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
ArticulationLink& link = links[linkID];
//const SpatialTransform p2c = data.mChildToParent[linkID].getTranspose();
motionAccelerations[linkID] = translateSpatialVector(-data.getRw(linkID), motionAccelerations[link.parent]);
zaForce[linkID] = compositeSpatialInertia[linkID] * motionAccelerations[linkID] + zaForce[linkID];
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
//compute generalized force
const PxU32 jointOffset = jointDatum.jointOffset;
PxReal* jForce = &jointForces[jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
jForce[ind] = data.mWorldMotionMatrix[jointOffset+ind].innerProduct(zaForce[linkID]);
}
}
}
void FeatherstoneArticulation::inverseDynamic(ArticulationData& data, const PxVec3& gravity,
ScratchData& scratchData, bool computeCoriolis)
{
//pass 1
computeLinkVelocities(data, scratchData);
if(computeCoriolis)
computeC(data, scratchData);
else
PxMemZero(scratchData.coriolisVectors, sizeof(Cm::SpatialVectorF)*data.getLinkCount());
computeZ(data, gravity, scratchData);
computeLinkAccelerationInv(data, scratchData);
computeZAForceInv(data, scratchData);
//pass 2
computeGeneralizedForceInv(data, scratchData);
}
void FeatherstoneArticulation::inverseDynamicFloatingBase(ArticulationData& data, const PxVec3& gravity,
ScratchData& scratchData, bool computeCoriolis)
{
//pass 1
computeLinkVelocities(data, scratchData);
if(computeCoriolis)
computeC(data, scratchData);
else
PxMemZero(scratchData.coriolisVectors, sizeof(Cm::SpatialVectorF)*data.getLinkCount());
computeZ(data, gravity, scratchData);
//no gravity, no external accelerations because we have turned those in force in
//computeZ
computeLinkAccelerationInv(data, scratchData);
computeZAForceInv(data, scratchData);
//pass 2
computeCompositeSpatialInertiaAndZAForceInv(data, scratchData);
//pass 3
computeRelativeGeneralizedForceInv(data, scratchData);
}
bool FeatherstoneArticulation::applyCacheToDest(ArticulationData& data, PxArticulationCache& cache,
PxReal* jVelocities, PxReal* jPositions, PxReal* jointForces, PxReal* jointTargetPositions, PxReal* jointTargetVelocities,
const PxArticulationCacheFlags flag, bool& shouldWake)
{
bool needsScheduling = !mGPUDirtyFlags;
bool localShouldWake = false;
if (flag & PxArticulationCacheFlag::eVELOCITY)
{
const PxU32 dofCount = data.getDofs();
for (PxU32 i = 0; i < dofCount; ++i)
{
const PxReal jv = cache.jointVelocity[i];
localShouldWake = localShouldWake || jv != 0.f;
jVelocities[i] = jv;
}
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_VELOCITIES;
}
if (flag & PxArticulationCacheFlag::eROOT_TRANSFORM)
{
ArticulationLink& rLink = mArticulationData.getLink(0);
// PT:: tag: scalar transform*transform
rLink.bodyCore->body2World = cache.rootLinkData->transform * rLink.bodyCore->getBody2Actor();
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_TRANSFORM;
}
if(flag & PxArticulationCacheFlag::eROOT_VELOCITIES)
{
ArticulationLink& rLink = mArticulationData.getLink(0);
rLink.bodyCore->linearVelocity = cache.rootLinkData->worldLinVel;
rLink.bodyCore->angularVelocity = cache.rootLinkData->worldAngVel;
localShouldWake = localShouldWake || (!cache.rootLinkData->worldLinVel.isZero()) || (!cache.rootLinkData->worldAngVel.isZero());
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_VELOCITIES;
}
if (flag & PxArticulationCacheFlag::ePOSITION)
{
copyJointData(data, jPositions, cache.jointPosition);
//When we update the joint positions, we also have to update the link state, so need to make links
//dirty!
mGPUDirtyFlags |= (ArticulationDirtyFlag::eDIRTY_POSITIONS);
}
if (flag & PxArticulationCacheFlag::eFORCE)
{
const PxU32 dofCount = data.getDofs();
for (PxU32 i = 0; i < dofCount; ++i)
{
const PxReal jf = cache.jointForce[i];
localShouldWake = localShouldWake || jf != 0.f;
jointForces[i] = jf;
}
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_FORCES;
}
if (flag & PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS)
{
const PxU32 dofCount = data.getDofs();
for (PxU32 i = 0; i < dofCount; ++i)
{
const PxReal jt = cache.jointTargetPositions[i];
localShouldWake = localShouldWake || jt != jPositions[i];
jointTargetPositions[i] = jt;
}
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_POS;
}
if (flag & PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES)
{
const PxU32 dofCount = data.getDofs();
for (PxU32 i = 0; i < dofCount; ++i)
{
const PxReal jv = cache.jointTargetVelocities[i];
localShouldWake = localShouldWake || jv != jVelocities[i];
jointTargetVelocities[i] = jv;
}
mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_VEL;
}
// the updateKinematic functions rely on updated joint frames.
if (mJcalcDirty)
{
jcalc(data);
}
mJcalcDirty = false;
if (flag & (PxArticulationCacheFlag::ePOSITION | PxArticulationCacheFlag::eROOT_TRANSFORM))
{
//update link's position based on the joint position
teleportLinks(data);
}
if (flag & (PxArticulationCacheFlag::eVELOCITY | PxArticulationCacheFlag::ePOSITION | PxArticulationCacheFlag::eROOT_VELOCITIES | PxArticulationCacheFlag::eROOT_TRANSFORM))
{
computeLinkVelocities(data);
}
shouldWake = localShouldWake;
return needsScheduling;
}
void FeatherstoneArticulation::packJointData(const PxReal* maximum, PxReal* reduced)
{
const PxU32 linkCount = mArticulationData.getLinkCount();
for (PxU32 linkID = 1; linkID < linkCount; linkID++)
{
ArticulationLink& linkDatum = mArticulationData.getLink(linkID);
ArticulationJointCore* joint = linkDatum.inboundJoint;
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
const PxReal* maxJointData = &maximum[(linkID - 1) * DY_MAX_DOF];
PxReal* reducedJointData = &reduced[jointDatum.jointOffset];
PxU32 count = 0;
for (PxU32 j = 0; j < DY_MAX_DOF; ++j)
{
PxArticulationMotions motion = PxArticulationMotions(joint->motion[j]);
if (motion != PxArticulationMotion::eLOCKED)
{
reducedJointData[count] = maxJointData[j];
count++;
}
}
PX_ASSERT(count == jointDatum.dof);
}
}
void FeatherstoneArticulation::unpackJointData(const PxReal* reduced, PxReal* maximum)
{
const PxU32 linkCount = mArticulationData.getLinkCount();
for (PxU32 linkID = 1; linkID < linkCount; linkID++)
{
ArticulationLink& linkDatum = mArticulationData.getLink(linkID);
ArticulationJointCore* joint = linkDatum.inboundJoint;
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
PxReal* maxJointData = &maximum[(linkID - 1) * DY_MAX_DOF];
const PxReal* reducedJointData = &reduced[jointDatum.jointOffset];
PxU32 count = 0;
for (PxU32 j = 0; j < DY_MAX_DOF; ++j)
{
PxArticulationMotions motion = PxArticulationMotions(joint->motion[j]);
if (motion != PxArticulationMotion::eLOCKED)
{
maxJointData[j] = reducedJointData[count];
count++;
}
else
{
maxJointData[j] = 0.f;
}
}
PX_ASSERT(count == jointDatum.dof);
}
}
void FeatherstoneArticulation::initializeCommonData()
{
if (mJcalcDirty)
{
jcalc(mArticulationData);
mJcalcDirty = false;
}
{
//constants
const ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
const ArticulationJointCoreData* jointCoreDatas = mArticulationData.getJointData();
const Cm::UnAlignedSpatialVector* motionMatrices = mArticulationData.getMotionMatrix();
//outputs
PxTransform* accumulatedPoses = mArticulationData.getAccumulatedPoses();
PxVec3* rws = mArticulationData.getRw();
Cm::UnAlignedSpatialVector* motionMatricesW = mArticulationData.getWorldMotionMatrix();
computeRelativeTransformC2P(
links, linkCount, jointCoreDatas, motionMatrices,
accumulatedPoses, rws, motionMatricesW);
}
computeRelativeTransformC2B(mArticulationData);
computeSpatialInertia(mArticulationData);
mArticulationData.setDataDirty(false);
}
void FeatherstoneArticulation::getGeneralizedGravityForce(const PxVec3& gravity, PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getGeneralisedGravityForce() commonInit need to be called first to initialize data!");
return;
}
#if FEATHERSTONE_DEBUG
PxReal* jointForce = reinterpret_cast<PxReal*>(PX_ALLOC(sizeof(PxReal) * mArticulationData.getDofs(), "jointForce"));
{
const PxU32 linkCount = mArticulationData.getLinkCount();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
scratchData.jointVelocities = NULL;
scratchData.jointAccelerations = NULL;
scratchData.jointForces = jointForce;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
if (fixBase)
inverseDynamic(mArticulationData, gravity, scratchData, false);
else
inverseDynamicFloatingBase(mArticulationData, gravity, scratchData, false);
allocator->free(tempMemory);
}
#endif
const PxVec3 tGravity = -gravity;
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
const PxU32 linkCount = mArticulationData.getLinkCount();
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
if (fixBase)
{
Cm::SpatialVectorF* spatialZAForces = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * linkCount));
for (PxU32 linkID = 0; linkID < linkCount; ++linkID)
{
ArticulationLink& link = mArticulationData.getLink(linkID);
PxsBodyCore& core = *link.bodyCore;
const PxReal m = 1.0f / core.inverseMass;
const PxVec3 linkGravity = tGravity;
spatialZAForces[linkID].top = m*linkGravity;
spatialZAForces[linkID].bottom = PxVec3(0.f);
}
ScratchData scratchData;
scratchData.spatialZAVectors = spatialZAForces;
scratchData.jointForces = cache.jointForce;
computeGeneralizedForceInv(mArticulationData, scratchData);
//release spatialZA vectors
allocator->free(spatialZAForces);
}
else
{
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
scratchData.jointVelocities = NULL;
scratchData.jointAccelerations = NULL;
scratchData.jointForces = cache.jointForce;
scratchData.externalAccels = NULL;
inverseDynamicFloatingBase(mArticulationData, tGravity, scratchData, false);
allocator->free(tempMemory);
}
#if FEATHERSTONE_DEBUG
//compare joint force
const PxU32 totalDofs = mArticulationData.getDofs();
for (PxU32 i = 0; i < totalDofs; ++i)
{
const PxReal dif = jointForce[i] - cache.jointForce[i];
PX_ASSERT(PxAbs(dif) < 5e-3f);
}
PX_FREE(jointForce);
#endif
}
//gravity, acceleration and external force(external acceleration) are zero
void FeatherstoneArticulation::getCoriolisAndCentrifugalForce(PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getCoriolisAndCentrifugalForce() commonInit need to be called first to initialize data!");
return;
}
const PxU32 linkCount = mArticulationData.getLinkCount();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
scratchData.jointVelocities = cache.jointVelocity;
scratchData.jointAccelerations = NULL;
scratchData.jointForces = cache.jointForce;
scratchData.externalAccels = NULL;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
if (fixBase)
inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, true);
else
inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, true);
allocator->free(tempMemory);
}
//gravity, joint acceleration and joint velocity are zero
void FeatherstoneArticulation::getGeneralizedExternalForce(PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getCoriolisAndCentrifugalForce() commonInit need to be called first to initialize data!");
return;
}
const PxU32 linkCount = mArticulationData.getLinkCount();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
scratchData.jointVelocities = NULL;
scratchData.jointAccelerations = NULL;
scratchData.jointForces = cache.jointForce;
Cm::SpatialVector* accels = reinterpret_cast<Cm::SpatialVector*>(allocator->alloc(sizeof(Cm::SpatialVector) * linkCount));
//turn external forces to external accels
for (PxU32 i = 0; i < linkCount; ++i)
{
ArticulationLink& link = mArticulationData.getLink(i);
PxsBodyCore& core = *link.bodyCore;
const PxSpatialForce& force = cache.externalForces[i];
Cm::SpatialVector& accel = accels[i];
accel.linear = force.force * core.inverseMass;
PxMat33 inverseInertiaWorldSpace;
Cm::transformInertiaTensor(core.inverseInertia, PxMat33(core.body2World.q), inverseInertiaWorldSpace);
accel.angular = inverseInertiaWorldSpace * force.torque;
}
scratchData.externalAccels = accels;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
if (fixBase)
inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false);
else
inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false);
allocator->free(tempMemory);
allocator->free(accels);
}
//provided joint acceleration, calculate joint force
void FeatherstoneArticulation::getJointForce(PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getJointForce() commonInit need to be called first to initialize data!");
return;
}
//const PxU32 size = sizeof(PxReal) * mArticulationData.getDofs();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
//PxReal* jointVelocities = reinterpret_cast<PxReal*>(allocator->alloc(size));
ScratchData scratchData;
scratchData.jointVelocities = NULL;//jont velocity will be zero
scratchData.jointAccelerations = cache.jointAcceleration; //input
scratchData.jointForces = cache.jointForce; //output
scratchData.externalAccels = NULL;
PxU8* tempMemory = allocateScratchSpatialData(allocator, mArticulationData.getLinkCount(), scratchData);
//make sure joint velocity be zero
//PxMemZero(jointVelocities, sizeof(PxReal) * mArticulationData.getDofs());
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
if (fixBase)
inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false);
else
inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false);
//allocator->free(jointVelocities);
allocator->free(tempMemory);
}
void FeatherstoneArticulation::jcalcLoopJointSubspace(ArticulationJointCore* joint,
ArticulationJointCoreData& jointDatum, SpatialSubspaceMatrix& T,
const Cm::UnAlignedSpatialVector* jointAxis)
{
PX_UNUSED(jointDatum);
const PxVec3 childOffset = -joint->childPose.p;
const PxVec3 zero(0.f);
//if the column is free, we put zero for it, this is for computing K(coefficient matrix)
T.setNumColumns(6);
//transpose(Tc)*S = 0
//transpose(Ta)*S = 1
switch (joint->jointType)
{
case PxArticulationJointType::ePRISMATIC:
{
PX_ASSERT(jointDatum.dof == 1);
const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized();
const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized();
const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized();
//joint->activeForceSubspace.setNumColumns(1);
if (jointAxis[0][3] == 1.f)
{
//x is the free translation axis
T.setColumn(0, rx, zero);
T.setColumn(1, ry, zero);
T.setColumn(2, rz, zero);
T.setColumn(3, zero, zero);
T.setColumn(4, zero, ry);
T.setColumn(5, zero, rz);
//joint->activeForceSubspace.setColumn(0, PxVec3(0.f), rx);
}
else if (jointAxis[0][4] == 1.f)
{
//y is the free translation axis
T.setColumn(0, rx, zero);
T.setColumn(1, ry, zero);
T.setColumn(2, rz, zero);
T.setColumn(3, zero, rx);
T.setColumn(4, zero, zero);
T.setColumn(5, zero, rz);
//joint->activeForceSubspace.setColumn(0, PxVec3(0.f), ry);
}
else if (jointAxis[0][5] == 1.f)
{
//z is the free translation axis
T.setColumn(0, rx, zero);
T.setColumn(1, ry, zero);
T.setColumn(2, rx, zero);
T.setColumn(3, zero, rx);
T.setColumn(4, zero, ry);
T.setColumn(5, zero, zero);
//joint->activeForceSubspace.setColumn(0, PxVec3(0.f), rz);
}
break;
}
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
//joint->activeForceSubspace.setNumColumns(1);
const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized();
const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized();
const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized();
const PxVec3 rxXd = rx.cross(childOffset);
const PxVec3 ryXd = ry.cross(childOffset);
const PxVec3 rzXd = rz.cross(childOffset);
if (jointAxis[0][0] == 1.f)
{
//x is the free rotation axis
T.setColumn(0, zero, zero);
T.setColumn(1, ry, zero);
T.setColumn(2, rz, zero);
//joint->activeForceSubspace.setColumn(0, rx, PxVec3(0.f));
}
else if (jointAxis[0][1] == 1.f)
{
//y is the free rotation axis
T.setColumn(0, rx, zero);
T.setColumn(1, zero, zero);
T.setColumn(2, rz, zero);
//joint->activeForceSubspace.setColumn(0, ry, PxVec3(0.f));
}
else if (jointAxis[0][2] == 1.f)
{
//z is the rotation axis
T.setColumn(0, rx, zero);
T.setColumn(1, ry, zero);
T.setColumn(2, zero, zero);
//joint->activeForceSubspace.setColumn(0, rz, PxVec3(0.f));
}
T.setColumn(3, rxXd, rx);
T.setColumn(4, ryXd, ry);
T.setColumn(5, rzXd, rz);
break;
}
case PxArticulationJointType::eSPHERICAL:
{
//joint->activeForceSubspace.setNumColumns(3);
const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized();
const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized();
const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized();
const PxVec3 rxXd = rx.cross(childOffset);
const PxVec3 ryXd = ry.cross(childOffset);
const PxVec3 rzXd = rz.cross(childOffset);
T.setColumn(0, zero, zero);
T.setColumn(1, zero, zero);
T.setColumn(2, zero, zero);
T.setColumn(3, rxXd, rx);
T.setColumn(4, ryXd, ry);
T.setColumn(5, rzXd, rz);
//need to implement constraint force subspace matrix and active force subspace matrix
break;
}
case PxArticulationJointType::eFIX:
{
//joint->activeForceSubspace.setNumColumns(0);
//T.setNumColumns(6);
/* const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized();
const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized();
const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized();
T.setColumn(0, rx, PxVec3(0.f));
T.setColumn(1, ry, PxVec3(0.f));
T.setColumn(2, rz, PxVec3(0.f));
T.setColumn(3, PxVec3(0.f), rx);
T.setColumn(4, PxVec3(0.f), ry);
T.setColumn(5, PxVec3(0.f), rz);
*/
T.setColumn(0, PxVec3(1.f, 0.f, 0.f), zero);
T.setColumn(1, PxVec3(0.f, 1.f, 0.f), zero);
T.setColumn(2, PxVec3(0.f, 0.f, 1.f), zero);
T.setColumn(3, zero, PxVec3(1.f, 0.f, 0.f));
T.setColumn(4, zero, PxVec3(0.f, 1.f, 0.f));
T.setColumn(5, zero, PxVec3(0.f, 0.f, 1.f));
PX_ASSERT(jointDatum.dof == 0);
break;
}
default:
break;
}
}
//This method supports just one loopJoint
void FeatherstoneArticulation::getKMatrix(ArticulationJointCore* loopJoint, const PxU32 parentIndex, const PxU32 childIndex, PxArticulationCache& cache)
{
PX_UNUSED(loopJoint);
PX_UNUSED(parentIndex);
PX_UNUSED(childIndex);
PX_UNUSED(cache);
////initialize all tree links motion subspace matrix
//jcalc(mArticulationData);
////linkID is the parent link, ground is the child link so child link is the fix base
//ArticulationLinkData& pLinkDatum = mArticulationData.getLinkData(parentIndex);
//ArticulationLink& cLink = mArticulationData.getLink(childIndex);
//ArticulationLinkData& cLinkDatum = mArticulationData.getLinkData(childIndex);
//
//ArticulationJointCoreData loopJointDatum;
//loopJointDatum.computeJointDof(loopJoint);
////this is constraintForceSubspace in child body space(T)
//SpatialSubspaceMatrix T;
////loop joint constraint subspace matrix(T)
//jcalcLoopJointSubspace(loopJoint, loopJointDatum, T);
//const PxU32 linkCount = mArticulationData.getLinkCount();
////set Jacobian matrix to be zero
//PxMemZero(cache.jacobian, sizeof(PxKinematicJacobian) * linkCount);
////transform T to world space
//PxTransform& body2World = cLink.bodyCore->body2World;
//for (PxU32 ind = 0; ind < T.getNumColumns(); ++ind)
//{
// Cm::SpatialVectorF& column = T[ind];
// T.setColumn(ind, body2World.rotate(column.top), body2World.rotate(column.bottom));
//}
//const Cm::SpatialVectorF& pAccel = pLinkDatum.motionAcceleration;
//const Cm::SpatialVectorF& cAccel = cLinkDatum.motionAcceleration;
//const Cm::SpatialVectorF& pVel = pLinkDatum.motionVelocity;
//const Cm::SpatialVectorF& cVel = cLinkDatum.motionVelocity;
//Cm::SpatialVectorF k = (pAccel - cAccel) + pVel.cross(cVel);
//k = T.transposeMultiply(k);
//k = -k;
//PxU32 i = childIndex;
//PxU32 j = parentIndex;
//PxU32* index = NULL;
//while (i != j)
//{
// if (i > j)
// index = &i;
// else
// index = &j;
// const PxU32 linkIndex = *index;
// PxKinematicJacobian* K = cache.jacobian + linkIndex;
// ArticulationLink& link = mArticulationData.getLink(linkIndex);
// ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkIndex);
// SpatialSubspaceMatrix& S = jointDatum.motionMatrix;
// PxTransform& tBody2World = link.bodyCore->body2World;
// Cm::SpatialVectorF res;
// for (PxU32 ind = 0; ind < S.getNumColumns(); ++ind)
// {
// Cm::SpatialVectorF& sCol = S[ind];
// //transform spatial axis into world space
// sCol.top = tBody2World.rotate(sCol.top);
// sCol.bottom = tBody2World.rotate(sCol.bottom);
// res = T.transposeMultiply(sCol);
// res = -res;
// PxReal* kSubMatrix = K->j[ind];
// kSubMatrix[0] = res.top.x; kSubMatrix[1] = res.top.y; kSubMatrix[2] = res.top.z;
// kSubMatrix[3] = res.bottom.x; kSubMatrix[4] = res.bottom.y; kSubMatrix[5] = res.bottom.z;
// }
// //overwrite either i or j to its parent index
// *index = link.parent;
//}
}
void FeatherstoneArticulation::getCoefficientMatrix(const PxReal dt, const PxU32 linkID, const PxContactJoint* contactJoints, const PxU32 nbContacts, PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getCoefficientMatrix() commonInit need to be called first to initialize data!");
return;
}
computeArticulatedSpatialInertia(mArticulationData);
ArticulationLink* links = mArticulationData.getLinks();
const PxU32 linkCount = mArticulationData.getLinkCount();
PxReal* coefficientMatrix = cache.coefficientMatrix;
const PxU32 elementCount = mArticulationData.getDofs();
//zero coefficient matrix
PxMemZero(coefficientMatrix, sizeof(PxReal) * elementCount * nbContacts);
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
for (PxU32 a = 0; a < nbContacts; ++a)
{
PxJacobianRow row;
contactJoints[a].computeJacobians(&row);
//impulse lin is contact normal, and ang is raxn. R is body2World, R(t) is world2Body
//| R(t), 0 |
//| R(t)*r, R(t)|
//r is the vector from center of mass to contact point
//p(impluse) = |n|
// |0|
//transform p(impluse) from work space to the local space of link
ArticulationLink& link = links[linkID];
PxTransform& body2World = link.bodyCore->body2World;
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
Cm::SpatialVectorF* Z = scratchData.spatialZAVectors;
//make sure all links' spatial zero acceleration impulse are zero
PxMemZero(Z, sizeof(Cm::SpatialVectorF) * linkCount);
const Cm::SpatialVectorF impl(body2World.rotateInv(row.linear0), body2World.rotateInv(row.angular0));
getZ(linkID, mArticulationData, Z, impl);
const PxU32 totalDofs = mArticulationData.getDofs();
const PxU32 size = sizeof(PxReal) * totalDofs;
PxU8* tData = reinterpret_cast<PxU8*>(allocator->alloc(size * 2));
PxReal* jointVelocities = reinterpret_cast<PxReal*>(tData);
PxReal* jointAccelerations = reinterpret_cast<PxReal*>(tData + size);
//zero joint Velocites
PxMemZero(jointVelocities, size);
getDeltaVWithDeltaJV(fixBase, linkID, mArticulationData, Z, jointVelocities);
const PxReal invDt = 1.f / dt;
//calculate joint acceleration due to velocity change
for (PxU32 i = 0; i < totalDofs; ++i)
{
jointAccelerations[i] = jointVelocities[i] * invDt;
}
//compute individual link's spatial inertia tensor. This is very important
computeSpatialInertia(mArticulationData);
PxReal* coeCol = &coefficientMatrix[elementCount * a];
//this means the joint force calculated by the inverse dynamic
//will be just influenced by joint acceleration change
scratchData.jointVelocities = NULL;
scratchData.externalAccels = NULL;
//Input
scratchData.jointAccelerations = jointAccelerations;
//a column of the coefficient matrix is the joint force
scratchData.jointForces = coeCol;
if (fixBase)
{
inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false);
}
else
{
inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false);
}
allocator->free(tData);
allocator->free(tempMemory);
}
}
void FeatherstoneArticulation::getImpulseResponseSlowInv(Dy::ArticulationLink* links,
const ArticulationData& data,
PxU32 linkID0_,
const Cm::SpatialVector& impulse0,
Cm::SpatialVector& deltaV0,
PxU32 linkID1_,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV1,
PxReal* jointVelocities,
Cm::SpatialVectorF* Z)
{
PX_UNUSED(jointVelocities);
const PxU32 numLinks = data.getLinkCount();
PX_ALLOCA(_stack, PxU32, numLinks);
PxU32* stack = _stack;
PxU32 i0, i1, ic;
PxU32 linkID0 = linkID0_;
PxU32 linkID1 = linkID1_;
for (i0 = linkID0, i1 = linkID1; i0 != i1;) // find common path
{
if (i0<i1)
i1 = links[i1].parent;
else
i0 = links[i0].parent;
}
PxU32 common = i0;
Cm::SpatialVectorF Z0(-impulse0.linear, -impulse0.angular);
Cm::SpatialVectorF Z1(-impulse1.linear, -impulse1.angular);
Z[linkID0] = Z0;
Z[linkID1] = Z1;
//for (i0 = linkID0; i0 != common; i0 = links[i0].parent)
for (i0 = 0; linkID0 != common; linkID0 = links[linkID0].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(linkID0).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(linkID0).dof;
Z0 = FeatherstoneArticulation::propagateImpulseW(
data.getRw(linkID0),
Z0,
&data.getWorldIsInvD(jointOffset), &data.getWorldMotionMatrix(jointOffset),dofCount);
Z[links[linkID0].parent] = Z0;
stack[i0++] = linkID0;
}
for (i1 = i0; linkID1 != common; linkID1 = links[linkID1].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(linkID1).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(linkID1).dof;
Z1 = FeatherstoneArticulation::propagateImpulseW(
data.getRw(linkID1),
Z1,
&data.getWorldIsInvD(jointOffset), &data.getWorldMotionMatrix(jointOffset), dofCount);
Z[links[linkID1].parent] = Z1;
stack[i1++] = linkID1;
}
//KS - we can replace the following section of code with the impulse response matrix - until next comment!
Cm::SpatialVectorF ZZ = Z0 + Z1;
Z[common] = ZZ;
for (ic = i1; common; common = links[common].parent)
{
const PxU32 jointOffset = mArticulationData.getJointData(common).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(common).dof;
Z[links[common].parent] = FeatherstoneArticulation::propagateImpulseW(
data.getRw(common),
Z[common],
&data.getWorldIsInvD(jointOffset), &data.getMotionMatrix(jointOffset), dofCount);
stack[ic++] = common;
}
if(data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE)
Z[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
//SpatialMatrix inverseArticulatedInertia = data.getLinkData(0).spatialArticulatedInertia.getInverse();
const SpatialMatrix& inverseArticulatedInertia = data.getBaseInvSpatialArticulatedInertiaW();
Cm::SpatialVectorF v = inverseArticulatedInertia * (-Z[0]);
for (PxU32 index = ic; (index--) > i1;)
{
const PxU32 id = stack[index];
const PxU32 jointOffset = mArticulationData.getJointData(id).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(id).dof;
v = FeatherstoneArticulation::propagateVelocityW(data.getRw(id), data.mWorldSpatialArticulatedInertia[id],
data.mInvStIs[id], &data.getWorldMotionMatrix(jointOffset), Z[id], jointVelocities, v, dofCount);
}
//Replace everything to here with the impulse response matrix multiply
Cm::SpatialVectorF dv1 = v;
for (PxU32 index = i1; (index--) > i0;)
{
const PxU32 id = stack[index];
const PxU32 jointOffset = mArticulationData.getJointData(id).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(id).dof;
dv1 = FeatherstoneArticulation::propagateVelocityW(data.getRw(id), data.mWorldSpatialArticulatedInertia[id],
data.mInvStIs[id], &data.getWorldMotionMatrix(jointOffset), Z[id], jointVelocities, v, dofCount);
}
Cm::SpatialVectorF dv0 = v;
for (PxU32 index = i0; (index--) > 0;)
{
const PxU32 id = stack[index];
const PxU32 jointOffset = mArticulationData.getJointData(id).jointOffset;
const PxU32 dofCount = mArticulationData.getJointData(id).dof;
dv0 = FeatherstoneArticulation::propagateVelocityW(data.getRw(id), data.mWorldSpatialArticulatedInertia[id],
data.mInvStIs[id], &data.getWorldMotionMatrix(jointOffset), Z[id], jointVelocities, v, dofCount);
}
deltaV0.linear = dv0.bottom;
deltaV0.angular = dv0.top;
deltaV1.linear = dv1.bottom;
deltaV1.angular = dv1.top;
}
void FeatherstoneArticulation::getImpulseSelfResponseInv(const bool fixBase,
PxU32 linkID0,
PxU32 linkID1,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse0,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV0,
Cm::SpatialVector& deltaV1,
PxReal* jointVelocities)
{
ArticulationLink* links = mArticulationData.getLinks();
//transform p(impluse) from work space to the local space of link
ArticulationLink& link = links[linkID1];
//ArticulationLinkData& linkDatum = mArticulationData.getLinkData(linkID1);
if (link.parent == linkID0)
{
PX_ASSERT(linkID0 == link.parent);
PX_ASSERT(linkID0 < linkID1);
//impulse is in world space
const Cm::SpatialVector& imp1 = impulse1;
const Cm::SpatialVector& imp0 = impulse0;
Cm::SpatialVectorF pImpulse(imp0.linear, imp0.angular);
PX_ASSERT(linkID0 == link.parent);
const PxU32 jointOffset = mArticulationData.getJointData(linkID1).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(linkID1).dof;
//initialize child link spatial zero acceleration impulse
Cm::SpatialVectorF Z1(-imp1.linear, -imp1.angular);
//this calculate parent link spatial zero acceleration impulse
Cm::SpatialVectorF Z0 = FeatherstoneArticulation::propagateImpulseW(
mArticulationData.getRw(linkID1),
Z1,
&mArticulationData.mISInvStIS[jointOffset], &mArticulationData.mWorldMotionMatrix[jointOffset], dofCount);
//in parent space
const Cm::SpatialVectorF impulseDif = pImpulse - Z0;
Cm::SpatialVectorF delV0(PxVec3(0.f), PxVec3(0.f));
Cm::SpatialVectorF delV1(PxVec3(0.f), PxVec3(0.f));
//calculate velocity change start from the parent link to the root
delV0 = FeatherstoneArticulation::getImpulseResponseWithJ(linkID0, fixBase, mArticulationData, Z, impulseDif, jointVelocities);
//calculate velocity change for child link
delV1 = FeatherstoneArticulation::propagateVelocityW(mArticulationData.getRw(linkID1),
mArticulationData.mWorldSpatialArticulatedInertia[linkID1], mArticulationData.mInvStIs[linkID1],
&mArticulationData.mWorldMotionMatrix[jointOffset], Z1, jointVelocities, delV0, dofCount);
//translate delV0 and delV1 into world space again
deltaV0.linear = delV0.bottom;
deltaV0.angular = delV0.top;
deltaV1.linear = delV1.bottom;
deltaV1.angular = delV1.top;
}
else
{
getImpulseResponseSlowInv(links, mArticulationData, linkID0, impulse0, deltaV0, linkID1,impulse1, deltaV1, jointVelocities, Z);
}
}
Cm::SpatialVectorF FeatherstoneArticulation::getImpulseResponseInv(
const bool fixBase, const PxU32 linkID,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse,
PxReal* jointVelocities)
{
//impulse lin is contact normal, and ang is raxn. R is body2World, R(t) is world2Body
//| R(t), 0 |
//| R(t)*r, R(t)|
//r is the vector from center of mass to contact point
//p(impluse) = |n|
// |0|
ArticulationLink* links = mArticulationData.getLinks();
//ArticulationLinkData* linkData = mArticulationData.getLinkData();
ArticulationJointCoreData* jointData = mArticulationData.getJointData();
const PxU32 linkCount = mArticulationData.getLinkCount();
//make sure all links' spatial zero acceleration impulse are zero
PxMemZero(Z, sizeof(Cm::SpatialVectorF) * linkCount);
Z[linkID] = Cm::SpatialVectorF(-impulse.linear, -impulse.angular);
for (PxU32 i = linkID; i; i = links[i].parent)
{
ArticulationLink& tLink = links[i];
const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset;
const PxU8 dofCount = mArticulationData.getJointData(i).dof;
//ArticulationLinkData& tLinkDatum = linkData[i];
Z[tLink.parent] = propagateImpulseW(
mArticulationData.getRw(i),
Z[i],
&mArticulationData.mISInvStIS[jointOffset], &mArticulationData.mWorldMotionMatrix[jointOffset], dofCount);
}
//set velocity change of the root link to be zero
Cm::SpatialVectorF deltaV = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f));
if (!fixBase)
deltaV = mArticulationData.mBaseInvSpatialArticulatedInertiaW * (-Z[0]);
const PxU32 startIndex = links[linkID].mPathToRootStartIndex;
const PxU32 numElems = links[linkID].mPathToRootCount;
const PxU32* pathToRoot = &mArticulationData.mPathToRootElements[startIndex];
for(PxU32 i = 0; i < numElems; ++i)
{
const PxU32 index = pathToRoot[i];
PX_ASSERT(links[index].parent < index);
ArticulationJointCoreData& tJointDatum = jointData[index];
PxReal* jVelocity = &jointVelocities[tJointDatum.jointOffset];
deltaV = propagateVelocityW(mArticulationData.getRw(index), mArticulationData.mWorldSpatialArticulatedInertia[index],
mArticulationData.mInvStIs[index], &mArticulationData.mWorldMotionMatrix[tJointDatum.jointOffset], Z[index], jVelocity, deltaV, tJointDatum.dof);
}
return deltaV;
}
void FeatherstoneArticulation::getCoefficientMatrixWithLoopJoints(ArticulationLoopConstraint* lConstraints, const PxU32 nbConstraints, PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getCoefficientMatrix() commonInit need to be called first to initialize data!");
return;
}
computeArticulatedSpatialInertia(mArticulationData);
const PxU32 linkCount = mArticulationData.getLinkCount();
PxReal* coefficientMatrix = cache.coefficientMatrix;
const PxU32 elementCount = mArticulationData.getDofs();
//zero coefficient matrix
PxMemZero(coefficientMatrix, sizeof(PxReal) * elementCount * nbConstraints);
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
Cm::SpatialVectorF* Z = scratchData.spatialZAVectors;
const PxU32 totalDofs = mArticulationData.getDofs();
const PxU32 size = sizeof(PxReal) * totalDofs;
PxU8* tData = reinterpret_cast<PxU8*>(allocator->alloc(size * 2));
const PxReal invDt = 1.f / mArticulationData.getDt();
PxReal* jointVelocities = reinterpret_cast<PxReal*>(tData);
PxReal* jointAccelerations = reinterpret_cast<PxReal*>(tData + size);
for (PxU32 a = 0; a < nbConstraints; ++a)
{
ArticulationLoopConstraint& lConstraint = lConstraints[a];
Constraint* aConstraint = lConstraint.constraint;
Px1DConstraint rows[MAX_CONSTRAINT_ROWS];
setupConstraintRows(rows, MAX_CONSTRAINT_ROWS);
const PxTransform idt(PxIdentity);
const PxTransform& body2World0 = aConstraint->body0 ? aConstraint->bodyCore0->body2World : idt;
const PxTransform& body2World1 = aConstraint->body1 ? aConstraint->bodyCore1->body2World : idt;
PxVec3p unused_body0WorldOffset(0.0f);
PxVec3p unused_ra, unused_rb;
PxConstraintInvMassScale unused_invMassScales;
//TAG:solverprepcall
PxU32 constraintCount = (*aConstraint->solverPrep)(rows,
unused_body0WorldOffset,
MAX_CONSTRAINT_ROWS,
unused_invMassScales,
aConstraint->constantBlock,
body2World0, body2World1, !!(aConstraint->flags & PxConstraintFlag::eENABLE_EXTENDED_LIMITS), unused_ra, unused_rb);
const PxU32 linkIndex0 = lConstraint.linkIndex0;
const PxU32 linkIndex1 = lConstraint.linkIndex1;
//zero joint Velocites
PxMemZero(jointVelocities, size);
for (PxU32 j = 0; j < constraintCount; ++j)
{
Px1DConstraint& row = rows[j];
if (linkIndex0 != 0x80000000 && linkIndex1 != 0x80000000)
{
const bool flip = linkIndex0 > linkIndex1;
Cm::SpatialVector impulse0(row.linear0, row.angular0);
Cm::SpatialVector impulse1(row.linear1, row.angular1);
Cm::SpatialVector deltaV0, deltaV1;
if (flip)
{
getImpulseSelfResponseInv(fixBase, linkIndex1, linkIndex0, Z, impulse1, impulse0,
deltaV1, deltaV0, jointVelocities);
}
else
{
getImpulseSelfResponseInv(fixBase, linkIndex0, linkIndex1, Z, impulse0, impulse1,
deltaV0, deltaV1, jointVelocities);
}
}
else
{
if (linkIndex0 == 0x80000000)
{
Cm::SpatialVector impulse1(row.linear1, row.angular1);
getImpulseResponseInv(fixBase, linkIndex1, Z, impulse1, jointVelocities);
}
else
{
Cm::SpatialVector impulse0(row.linear0, row.angular0);
getImpulseResponseInv(fixBase, linkIndex0, Z, impulse0, jointVelocities);
}
}
}
//calculate joint acceleration due to velocity change
for (PxU32 i = 0; i < totalDofs; ++i)
{
jointAccelerations[i] = jointVelocities[i] * invDt;
}
//reset spatial inertia
computeSpatialInertia(mArticulationData);
PxReal* coeCol = &coefficientMatrix[elementCount * a];
//this means the joint force calculated by the inverse dynamic
//will be just influenced by joint acceleration change
scratchData.jointVelocities = NULL;
scratchData.externalAccels = NULL;
//Input
scratchData.jointAccelerations = jointAccelerations;
//a column of the coefficient matrix is the joint force
scratchData.jointForces = coeCol;
if (fixBase)
{
inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false);
}
else
{
inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false);
}
allocator->free(tData);
allocator->free(tempMemory);
}
}
void FeatherstoneArticulation::constraintPrep(ArticulationLoopConstraint* lConstraints,
const PxU32 nbJoints, Cm::SpatialVectorF* Z, PxSolverConstraintPrepDesc& prepDesc,
PxSolverBody& sBody, PxSolverBodyData& sBodyData, PxSolverConstraintDesc* descs,
PxConstraintAllocator& allocator)
{
const PxReal dt = mArticulationData.getDt();
const PxReal invDt = 1.f / dt;
//constraint prep
for (PxU32 a = 0; a < nbJoints; ++a)
{
ArticulationLoopConstraint& lConstraint = lConstraints[a];
Constraint* aConstraint = lConstraint.constraint;
PxSolverConstraintDesc& desc = descs[a];
prepDesc.desc = &desc;
prepDesc.linBreakForce = aConstraint->linBreakForce;
prepDesc.angBreakForce = aConstraint->angBreakForce;
prepDesc.writeback = &mContext->getConstraintWriteBackPool()[aConstraint->index];
setupConstraintFlags(prepDesc, aConstraint->flags);
prepDesc.minResponseThreshold = aConstraint->minResponseThreshold;
Px1DConstraint rows[MAX_CONSTRAINT_ROWS];
setupConstraintRows(rows, MAX_CONSTRAINT_ROWS);
prepDesc.invMassScales.linear0 = prepDesc.invMassScales.linear1 = prepDesc.invMassScales.angular0 = prepDesc.invMassScales.angular1 = 1.0f;
prepDesc.body0WorldOffset = PxVec3(0.0f);
const PxTransform idt(PxIdentity);
const PxTransform& body2World0 = aConstraint->body0 ? aConstraint->bodyCore0->body2World : idt;
const PxTransform& body2World1 = aConstraint->body1 ? aConstraint->bodyCore1->body2World : idt;
PxVec3p unused_ra, unused_rb;
PxConstraintInvMassScale unused_invMassScales;
//TAG:solverprepcall
prepDesc.numRows = (*aConstraint->solverPrep)(rows,
prepDesc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
unused_invMassScales,
aConstraint->constantBlock,
body2World0, body2World1, !!(aConstraint->flags & PxConstraintFlag::eENABLE_EXTENDED_LIMITS),
unused_ra, unused_rb);
prepDesc.bodyFrame0 = body2World0;
prepDesc.bodyFrame1 = body2World1;
prepDesc.rows = rows;
const PxU32 linkIndex0 = lConstraint.linkIndex0;
const PxU32 linkIndex1 = lConstraint.linkIndex1;
if (linkIndex0 != 0x80000000 && linkIndex1 != 0x80000000)
{
desc.articulationA = this;
desc.articulationB = this;
desc.linkIndexA = PxTo8(linkIndex0);
desc.linkIndexB = PxTo8(linkIndex1);
desc.bodyA = reinterpret_cast<PxSolverBody*>(this);
desc.bodyB = reinterpret_cast<PxSolverBody*>(this);
prepDesc.bodyState0 = PxSolverConstraintPrepDescBase::eARTICULATION;
prepDesc.bodyState1 = PxSolverConstraintPrepDescBase::eARTICULATION;
}
else if (linkIndex0 == 0x80000000)
{
desc.articulationA = NULL;
desc.articulationB = this;
desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY;
desc.linkIndexB = PxTo8(linkIndex1);
desc.bodyA = &sBody;
desc.bodyB = reinterpret_cast<PxSolverBody*>(this);
prepDesc.bodyState0 = PxSolverConstraintPrepDescBase::eSTATIC_BODY;
prepDesc.bodyState1 = PxSolverConstraintPrepDescBase::eARTICULATION;
}
else if (linkIndex1 == 0x80000000)
{
desc.articulationA = this;
desc.articulationB = NULL;
desc.linkIndexA = PxTo8(linkIndex0);
desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY;
desc.bodyA = reinterpret_cast<PxSolverBody*>(this);
desc.bodyB = &sBody;
prepDesc.bodyState0 = PxSolverConstraintPrepDescBase::eARTICULATION;
prepDesc.bodyState1 = PxSolverConstraintPrepDescBase::eSTATIC_BODY;
}
prepDesc.body0 = desc.bodyA;
prepDesc.body1 = desc.bodyB;
prepDesc.data0 = &sBodyData;
prepDesc.data1 = &sBodyData;
ConstraintHelper::setupSolverConstraint(prepDesc, allocator, dt, invDt, Z);
}
}
class BlockBasedAllocator
{
struct AllocationPage
{
static const PxU32 PageSize = 32 * 1024;
PxU8 mPage[PageSize];
PxU32 currentIndex;
AllocationPage() : currentIndex(0) {}
PxU8* allocate(const PxU32 size)
{
PxU32 alignedSize = (size + 15)&(~15);
if ((currentIndex + alignedSize) < PageSize)
{
PxU8* ret = &mPage[currentIndex];
currentIndex += alignedSize;
return ret;
}
return NULL;
}
};
AllocationPage* currentPage;
physx::PxArray<AllocationPage*> mAllocatedBlocks;
PxU32 mCurrentIndex;
public:
BlockBasedAllocator() : currentPage(NULL), mCurrentIndex(0)
{
}
virtual PxU8* allocate(const PxU32 byteSize)
{
if (currentPage)
{
PxU8* data = currentPage->allocate(byteSize);
if (data)
return data;
}
if (mCurrentIndex < mAllocatedBlocks.size())
{
currentPage = mAllocatedBlocks[mCurrentIndex++];
currentPage->currentIndex = 0;
return currentPage->allocate(byteSize);
}
currentPage = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(AllocationPage), "AllocationPage"), AllocationPage)();
mAllocatedBlocks.pushBack(currentPage);
mCurrentIndex = mAllocatedBlocks.size();
return currentPage->allocate(byteSize);
}
void release() { for (PxU32 a = 0; a < mAllocatedBlocks.size(); ++a) PX_FREE(mAllocatedBlocks[a]); mAllocatedBlocks.clear(); currentPage = NULL; mCurrentIndex = 0; }
void reset() { currentPage = NULL; mCurrentIndex = 0; }
virtual ~BlockBasedAllocator()
{
release();
}
};
class ArticulationBlockAllocator : public PxConstraintAllocator
{
BlockBasedAllocator mConstraintAllocator;
BlockBasedAllocator mFrictionAllocator[2];
PxU32 currIdx;
public:
ArticulationBlockAllocator() : currIdx(0)
{
}
virtual ~ArticulationBlockAllocator() {}
virtual PxU8* reserveConstraintData(const PxU32 size)
{
return reinterpret_cast<PxU8*>(mConstraintAllocator.allocate(size));
}
virtual PxU8* reserveFrictionData(const PxU32 byteSize)
{
return reinterpret_cast<PxU8*>(mFrictionAllocator[currIdx].allocate(byteSize));
}
void release() { currIdx = 1 - currIdx; mConstraintAllocator.release(); mFrictionAllocator[currIdx].release(); }
PX_NOCOPY(ArticulationBlockAllocator)
};
void solveExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache);
void writeBack1D(const PxSolverConstraintDesc& desc, SolverContext&, PxSolverBodyData&, PxSolverBodyData&);
void conclude1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/);
void clearExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache);
bool FeatherstoneArticulation::getLambda(ArticulationLoopConstraint* lConstraints, const PxU32 nbJoints,
PxArticulationCache& cache, PxArticulationCache& initialState,
const PxReal* jointTorque, const PxVec3& gravity, const PxU32 maxIter, const PxReal invLengthScale)
{
const PxReal dt = mArticulationData.getDt();
const PxReal invDt = 1.f / dt;
const PxU32 totalDofs = mArticulationData.getDofs();
const PxU32 linkCount = mArticulationData.getLinkCount();
ArticulationBlockAllocator bAlloc;
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * linkCount, true));
Cm::SpatialVectorF* deltaV = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * linkCount, true));
PxReal* prevoiusLambdas =reinterpret_cast<PxReal*>(allocator->alloc(sizeof(PxReal)*nbJoints * 2, true));
PxReal* lambdas = cache.lambda;
//this is the joint force changed caused by contact force based on impulse strength is 1
PxReal* J = cache.coefficientMatrix;
PxSolverBody staticSolverBody;
PxMemZero(&staticSolverBody, sizeof(PxSolverBody));
PxSolverBodyData staticSolverBodyData;
PxMemZero(&staticSolverBodyData, sizeof(PxSolverBodyData));
staticSolverBodyData.maxContactImpulse = PX_MAX_F32;
staticSolverBodyData.penBiasClamp = -PX_MAX_F32;
staticSolverBodyData.body2World = PxTransform(PxIdentity);
Dy::SolverContext context;
context.Z = Z;
context.deltaV = deltaV;
context.doFriction = false;
PxSolverConstraintDesc* desc = reinterpret_cast<PxSolverConstraintDesc*>(allocator->alloc(sizeof(PxSolverConstraintDesc) * nbJoints, true));
ArticulationSolverDesc artiDesc;
PxSolverConstraintDesc* constraintDescs = reinterpret_cast<PxSolverConstraintDesc*>(allocator->alloc(sizeof(PxSolverConstraintDesc) * mArticulationData.getLinkCount()-1, true));
//run forward dynamic to calculate the lamba
artiDesc.articulation = this;
PxU32 acCount = 0;
computeUnconstrainedVelocities(artiDesc, dt, acCount,
gravity, Z, deltaV, invLengthScale);
ScratchData scratchData;
scratchData.motionVelocities = mArticulationData.getMotionVelocities();
scratchData.motionAccelerations = mArticulationData.getMotionAccelerations();
scratchData.coriolisVectors = mArticulationData.getCorioliseVectors();
scratchData.spatialZAVectors = mArticulationData.getSpatialZAVectors();
scratchData.jointAccelerations = mArticulationData.getJointAccelerations();
scratchData.jointVelocities = mArticulationData.getJointVelocities();
scratchData.jointPositions = mArticulationData.getJointPositions();
scratchData.jointForces = mArticulationData.getJointForces();
scratchData.externalAccels = mArticulationData.getExternalAccelerations();
//prepare constraint data
PxSolverConstraintPrepDesc prepDesc;
constraintPrep(lConstraints, nbJoints, Z, prepDesc, staticSolverBody,
staticSolverBodyData, desc, bAlloc);
for (PxU32 i = 0; i < nbJoints; ++i)
{
prevoiusLambdas[i] = PX_MAX_F32;
}
bool found = true;
for (PxU32 iter = 0; iter < maxIter; ++iter)
{
found = true;
for (PxU32 i = 0; i < nbJoints; ++i)
{
clearExt1D(desc[i], context);
}
//solve
for (PxU32 itr = 0; itr < 4; itr++)
{
for (PxU32 i = 0; i < nbJoints; ++i)
{
solveExt1D(desc[i], context);
}
}
for (PxU32 i = 0; i < nbJoints; ++i)
{
conclude1D(desc[i], context);
}
PxcFsFlushVelocity(*this, deltaV, false);
for (PxU32 i = 0; i < nbJoints; ++i)
{
solveExt1D(desc[i], context);
writeBack1D(desc[i], context, staticSolverBodyData, staticSolverBodyData);
}
PxReal eps = 1e-5f;
for (PxU32 i = 0; i < nbJoints; ++i)
{
Dy::Constraint* constraint = lConstraints->constraint;
Dy::ConstraintWriteback& solverOutput = mContext->getConstraintWriteBackPool()[constraint->index];
PxVec3 linearForce = solverOutput.linearImpulse * invDt;
//linear force is normalize so lambda is the magnitude of linear force
lambdas[i] = linearForce.magnitude() * dt;
const PxReal dif = PxAbs(prevoiusLambdas[i] - lambdas[i]);
if (dif > eps)
found = false;
prevoiusLambdas[i] = lambdas[i];
}
if (found)
break;
//joint force
PxReal* jf3 = cache.jointForce;
//zero the joint force buffer
PxMemZero(jf3, sizeof(PxReal)*totalDofs);
for (PxU32 colInd = 0; colInd < nbJoints; ++colInd)
{
PxReal* col = &J[colInd * totalDofs];
for (PxU32 j = 0; j < totalDofs; ++j)
{
jf3[j] += col[j] * lambdas[colInd];
}
}
//jointTorque is M(q)*qddot + C(q,qdot)t - g(q)
//jointTorque - J*lambda.
for (PxU32 j = 0; j < totalDofs; ++j)
{
jf3[j] = jointTorque[j] - jf3[j];
}
bool shouldWake = false;
//reset all joint velocities/
applyCache(initialState, PxArticulationCacheFlag::eALL, shouldWake);
//copy constraint torque to internal data
applyCache(cache, PxArticulationCacheFlag::eFORCE, shouldWake);
mArticulationData.init();
computeLinkVelocities(mArticulationData, scratchData);
computeZ(mArticulationData, gravity, scratchData);
computeArticulatedSpatialZ(mArticulationData, scratchData);
{
//Constant terms.
const bool doIC = true;
const PxArticulationFlags articulationFlags = mArticulationData.getArticulationFlags();
const ArticulationLink* links = mArticulationData.getLinks();
const ArticulationJointCoreData* jointDatas = mArticulationData.getJointData();
const Cm::SpatialVectorF* linkSpatialZAExtForces = scratchData.spatialZAVectors;
const Cm::SpatialVectorF* linkCoriolisForces = scratchData.coriolisVectors;
const PxVec3* linkRws = mArticulationData.getRw();
const Cm::UnAlignedSpatialVector* jointDofMotionMatrices = mArticulationData.getWorldMotionMatrix();
const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW();
//Cached constant terms.
const InvStIs* linkInvStIs = mArticulationData.getInvStIS();
const Cm::SpatialVectorF* jointDofIsWs = mArticulationData.getIsW();
const PxReal* jointDofQstZics = mArticulationData.getQstZIc();
//Output
Cm::SpatialVectorF* linkMotionVelocities = scratchData.motionVelocities;
Cm::SpatialVectorF* linkMotionAccelerations = scratchData.motionAccelerations;
PxReal* jointAccelerations = scratchData.jointAccelerations;
PxReal* jointVelocities = scratchData.jointVelocities;
PxReal* jointNewVelocities = mArticulationData.getJointNewVelocities();
computeLinkAcceleration(
doIC, dt,
articulationFlags,
links, linkCount, jointDatas,
linkSpatialZAExtForces, linkCoriolisForces, linkRws,
jointDofMotionMatrices, baseInvSpatialArticulatedInertiaW,
linkInvStIs, jointDofIsWs, jointDofQstZics,
linkMotionAccelerations, linkMotionVelocities,
jointAccelerations, jointVelocities, jointNewVelocities);
}
//zero zero acceleration vector in the articulation data so that we can use this buffer to accumulated
//impulse for the contacts/constraints in the PGS/TGS solvers
PxMemZero(mArticulationData.getSpatialZAVectors(), sizeof(Cm::SpatialVectorF) * linkCount);
PxMemZero(mArticulationData.getSolverSpatialForces(), sizeof(Cm::SpatialVectorF) * linkCount);
}
allocator->free(constraintDescs);
allocator->free(prevoiusLambdas);
allocator->free(Z);
allocator->free(deltaV);
allocator->free(desc);
bAlloc.release();
bool shouldWake = false;
//roll back to the current stage
applyCache(initialState, PxArticulationCacheFlag::eALL, shouldWake);
return found;
}
//i is the current link ID, we need to compute the row/column related to the joint i with all the other joints
PxU32 computeHi(ArticulationData& data, const PxU32 linkID, PxReal* massMatrix, Cm::SpatialVectorF* f)
{
ArticulationLink* links = data.getLinks();
ArticulationJointCoreData& jointDatum = data.getJointData(linkID);
const PxU32 totalDofs = data.getDofs();
//Hii
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
const PxU32 row = (jointDatum.jointOffset + ind)* totalDofs;
const Cm::SpatialVectorF& tf = f[ind];
for (PxU32 ind2 = 0; ind2 < jointDatum.dof; ++ind2)
{
const PxU32 col = jointDatum.jointOffset + ind2;
const Cm::UnAlignedSpatialVector& sa = data.getWorldMotionMatrix(jointDatum.jointOffset + ind2);
massMatrix[row + col] = sa.innerProduct(tf);
}
}
PxU32 j = linkID;
ArticulationLink* jLink = &links[j];
while (jLink->parent != 0)
{
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
//f[ind] = data.getChildToParent(j) * f[ind];
f[ind] = FeatherstoneArticulation::translateSpatialVector(data.getRw(j), f[ind]);
}
//assign j to the parent link
j = jLink->parent;
jLink = &links[j];
//Hij
ArticulationJointCoreData& pJointDatum = data.getJointData(j);
for (PxU32 ind = 0; ind < pJointDatum.dof; ++ind)
{
const Cm::UnAlignedSpatialVector& sa = data.getWorldMotionMatrix(pJointDatum.jointOffset + ind);
const PxU32 col = pJointDatum.jointOffset + ind;
for (PxU32 ind2 = 0; ind2 < jointDatum.dof; ++ind2)
{
const PxU32 row = (jointDatum.jointOffset + ind2)* totalDofs;
Cm::SpatialVectorF& fcol = f[ind2];
massMatrix[row + col] = sa.innerProduct(fcol);
}
}
//Hji = transpose(Hij)
{
for (PxU32 ind = 0; ind < pJointDatum.dof; ++ind)
{
const PxU32 pRow = (pJointDatum.jointOffset + ind)* totalDofs;
const PxU32 col = pJointDatum.jointOffset + ind;
for (PxU32 ind2 = 0; ind2 < jointDatum.dof; ++ind2)
{
const PxU32 pCol = jointDatum.jointOffset + ind2;
const PxU32 row = (jointDatum.jointOffset + ind2) * totalDofs;
massMatrix[pRow + pCol] = massMatrix[row + col];
}
}
}
}
return j;
}
void FeatherstoneArticulation::calculateHFixBase(PxArticulationCache& cache)
{
const PxU32 elementCount = mArticulationData.getDofs();
PxReal* massMatrix = cache.massMatrix;
PxMemZero(massMatrix, sizeof(PxReal) * elementCount * elementCount);
const PxU32 linkCount = mArticulationData.getLinkCount();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ArticulationLink* links = mArticulationData.getLinks();
const PxU32 startIndex = PxU32(linkCount - 1);
Dy::SpatialMatrix* compositeSpatialInertia = reinterpret_cast<Dy::SpatialMatrix*>(allocator->alloc(sizeof(Dy::SpatialMatrix) * linkCount));
//initialize composite spatial inertial
initCompositeSpatialInertia(mArticulationData, compositeSpatialInertia);
Cm::SpatialVectorF F[6];
for (PxU32 i = startIndex; i > 0; --i)
{
ArticulationLink& link = links[i];
Dy::SpatialMatrix cSpatialInertia = compositeSpatialInertia[i];
//transform current link's spatial inertia to parent's space
PxVec3 rw = link.bodyCore->body2World.p - links[link.parent].bodyCore->body2World.p;
FeatherstoneArticulation::translateInertia(FeatherstoneArticulation::constructSkewSymmetricMatrix(rw), cSpatialInertia);
//compute parent's composite spatial inertia
compositeSpatialInertia[link.parent] += cSpatialInertia;
Dy::SpatialMatrix& tSpatialInertia = compositeSpatialInertia[i];
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(i);
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
Cm::UnAlignedSpatialVector& sa = mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind];
Cm::UnAlignedSpatialVector tmp = tSpatialInertia* sa;
F[ind].top = tmp.top;
F[ind].bottom = tmp.bottom;
}
//Hii, Hij, Hji
computeHi(mArticulationData, i, massMatrix, F);
}
allocator->free(compositeSpatialInertia);
}
void FeatherstoneArticulation::calculateHFloatingBase(PxArticulationCache& cache)
{
const PxU32 elementCount = mArticulationData.getDofs();
PxReal* massMatrix = cache.massMatrix;
PxMemZero(massMatrix, sizeof(PxReal) * elementCount * elementCount);
const PxU32 linkCount = mArticulationData.getLinkCount();
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ArticulationLink* links = mArticulationData.getLinks();
//ArticulationLinkData* linkData = mArticulationData.getLinkData();
const PxU32 startIndex = PxU32(linkCount - 1);
Dy::SpatialMatrix* compositeSpatialInertia = reinterpret_cast<Dy::SpatialMatrix*>(allocator->alloc(sizeof(Dy::SpatialMatrix) * linkCount));
Cm::SpatialVectorF* F = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * elementCount));
//initialize composite spatial inertial
initCompositeSpatialInertia(mArticulationData, compositeSpatialInertia);
for (PxU32 i = startIndex; i > 0; --i)
{
ArticulationLink& link = links[i];
Dy::SpatialMatrix cSpatialInertia = compositeSpatialInertia[i];
//transform current link's spatial inertia to parent's space
PxVec3 rw = link.bodyCore->body2World.p - links[link.parent].bodyCore->body2World.p;
FeatherstoneArticulation::translateInertia(FeatherstoneArticulation::constructSkewSymmetricMatrix(rw), cSpatialInertia);
//compute parent's composite spatial inertia
compositeSpatialInertia[link.parent] += cSpatialInertia;
Dy::SpatialMatrix& tSpatialInertia = compositeSpatialInertia[i];
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(i);
Cm::SpatialVectorF* f = &F[jointDatum.jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
Cm::UnAlignedSpatialVector& sa = mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind];
Cm::UnAlignedSpatialVector tmp = tSpatialInertia* sa;
f[ind].top = tmp.top;
f[ind].bottom = tmp.bottom;
}
//Hii, Hij, Hji
const PxU32 j = computeHi(mArticulationData, i, massMatrix, f);
//transform F to the base link space
//ArticulationLinkData& fDatum = linkData[j];
PxVec3 brw = links[j].bodyCore->body2World.p - links[0].bodyCore->body2World.p;
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
f[ind] = translateSpatialVector(brw, f[ind]);
}
}
//Ib = base link composite inertia tensor
//compute transpose(F) * inv(Ib) *F
Dy::SpatialMatrix invI0 = compositeSpatialInertia[0].invertInertia();
//H - transpose(F) * inv(Ib) * F;
for (PxU32 row = 0; row < elementCount; ++row)
{
const Cm::SpatialVectorF& f = F[row];
for (PxU32 col = 0; col < elementCount; ++col)
{
const Cm::SpatialVectorF invIf = invI0 * F[col];
const PxReal v = f.innerProduct(invIf);
const PxU32 index = row * elementCount + col;
massMatrix[index] = massMatrix[index] - v;
}
}
allocator->free(compositeSpatialInertia);
allocator->free(F);
}
//calculate a single column of H, jointForce is equal to a single column of H
void FeatherstoneArticulation::calculateMassMatrixColInv(ScratchData& scratchData)
{
const PxU32 linkCount = mArticulationData.getLinkCount();
Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations;
Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors;
//Input
PxReal* jointAccelerations = scratchData.jointAccelerations;
//set base link motion acceleration to be zero because H should
//be just affected by joint position/link position
motionAccelerations[0] = Cm::SpatialVectorF::Zero();
spatialZAForces[0] = Cm::SpatialVectorF::Zero();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
ArticulationLink& link = mArticulationData.getLink(linkID);
ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID);
//parent motion accelerations into child space
Cm::SpatialVectorF accel = translateSpatialVector(-mArticulationData.getRw(linkID), motionAccelerations[link.parent]);
const PxReal* jAcceleration = &jointAccelerations[jointDatum.jointOffset];
for (PxU32 ind = 0; ind < jointDatum.dof; ++ind)
{
accel.top += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].top * jAcceleration[ind];
accel.bottom += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].bottom * jAcceleration[ind];
}
motionAccelerations[linkID] = accel;
spatialZAForces[linkID] = mArticulationData.mWorldSpatialArticulatedInertia[linkID] * accel;
}
computeGeneralizedForceInv(mArticulationData, scratchData);
}
void FeatherstoneArticulation::getGeneralizedMassMatrixCRB(PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getGeneralizedMassMatrix() commonInit need to be called first to initialize data!");
return;
}
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
if (fixBase)
{
calculateHFixBase(cache);
}
else
{
calculateHFloatingBase(cache);
}
}
void FeatherstoneArticulation::getGeneralizedMassMatrix( PxArticulationCache& cache)
{
if (mArticulationData.getDataDirty())
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getGeneralizedMassMatrix() commonInit need to be called first to initialize data!");
return;
}
//calculate each column for mass matrix
PxReal* massMatrix = cache.massMatrix;
const PxU32 linkCount = mArticulationData.getLinkCount();
const PxU32 elementCount = mArticulationData.getDofs();
const PxU32 size = sizeof(PxReal) * elementCount;
PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
ScratchData scratchData;
PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData);
PxReal* jointAccelerations = reinterpret_cast<PxReal*>(allocator->alloc(size));
scratchData.jointAccelerations = jointAccelerations;
scratchData.jointVelocities = NULL;
scratchData.externalAccels = NULL;
const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE;
//initialize jointAcceleration to be zero
PxMemZero(jointAccelerations, size);
for (PxU32 colInd = 0; colInd < elementCount; ++colInd)
{
PxReal* col = &massMatrix[colInd * elementCount];
scratchData.jointForces = col;
//set joint acceleration 1 in the col + 1 and zero elsewhere
jointAccelerations[colInd] = 1;
if (fixBase)
{
//jointAcceleration is Q, HQ = ID(model, qdot, Q).
calculateMassMatrixColInv(scratchData);
}
else
{
inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false);
}
//reset joint acceleration to be zero
jointAccelerations[colInd] = 0;
}
allocator->free(jointAccelerations);
allocator->free(tempMemory);
}
} //namespace Dy
}
| 74,561 | C++ | 32.738462 | 179 | 0.730529 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySleep.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 "DySleep.h"
using namespace physx;
// PT: TODO: refactor this, parts of the two codepaths are very similar
static PX_FORCE_INLINE PxReal updateWakeCounter(PxsRigidBody* originalBody, PxReal dt, bool enableStabilization, const Cm::SpatialVector& motionVelocity, bool hasStaticTouch)
{
PxsBodyCore& bodyCore = originalBody->getCore();
// update the body's sleep state and
const PxReal wakeCounterResetTime = 20.0f*0.02f;
PxReal wc = bodyCore.wakeCounter;
if (enableStabilization)
{
const PxTransform& body2World = bodyCore.body2World;
// calculate normalized energy: kinetic energy divided by mass
const PxVec3& t = bodyCore.inverseInertia;
const PxVec3 inertia( t.x > 0.0f ? 1.0f / t.x : 1.0f,
t.y > 0.0f ? 1.0f / t.y : 1.0f,
t.z > 0.0f ? 1.0f / t.z : 1.0f);
const PxVec3& sleepLinVelAcc = motionVelocity.linear;
const PxVec3 sleepAngVelAcc = body2World.q.rotateInv(motionVelocity.angular);
// scale threshold by cluster factor (more contacts => higher sleep threshold)
//const PxReal clusterFactor = PxReal(1u + getNumUniqueInteractions());
PxReal invMass = bodyCore.inverseMass;
if (invMass == 0.0f)
invMass = 1.0f;
const PxReal angular = sleepAngVelAcc.multiply(sleepAngVelAcc).dot(inertia) * invMass;
const PxReal linear = sleepLinVelAcc.magnitudeSquared();
const PxReal frameNormalizedEnergy = 0.5f * (angular + linear);
const PxReal cf = hasStaticTouch ? PxReal(PxMin(10u, bodyCore.numCountedInteractions)) : 0.0f;
const PxReal freezeThresh = cf*bodyCore.freezeThreshold;
originalBody->freezeCount = PxMax(originalBody->freezeCount - dt, 0.0f);
bool settled = true;
PxReal accelScale = PxMin(1.0f, originalBody->accelScale + dt);
if (frameNormalizedEnergy >= freezeThresh)
{
settled = false;
originalBody->freezeCount = PXD_FREEZE_INTERVAL;
}
if (!hasStaticTouch)
{
accelScale = 1.0f;
settled = false;
}
bool freeze = false;
if (settled)
{
//Dampen bodies that are just about to go to sleep
if (cf > 1.0f)
{
const PxReal sleepDamping = PXD_SLEEP_DAMPING;
const PxReal sleepDampingTimesDT = sleepDamping*dt;
const PxReal d = 1.0f - sleepDampingTimesDT;
bodyCore.linearVelocity = bodyCore.linearVelocity * d;
bodyCore.angularVelocity = bodyCore.angularVelocity * d;
accelScale = accelScale * 0.75f + 0.25f*PXD_FREEZE_SCALE;
}
freeze = originalBody->freezeCount == 0.0f && frameNormalizedEnergy < (bodyCore.freezeThreshold * PXD_FREEZE_TOLERANCE);
}
originalBody->accelScale = accelScale;
const PxU32 wasFrozen = originalBody->mInternalFlags & PxsRigidBody::eFROZEN;
PxU16 flags;
if(freeze)
{
//current flag isn't frozen but freeze flag raise so we need to raise the frozen flag in this frame
flags = PxU16(PxsRigidBody::eFROZEN);
if(!wasFrozen)
flags |= PxsRigidBody::eFREEZE_THIS_FRAME;
bodyCore.body2World = originalBody->getLastCCDTransform();
}
else
{
flags = 0;
if(wasFrozen)
flags |= PxsRigidBody::eUNFREEZE_THIS_FRAME;
}
originalBody->mInternalFlags = flags;
/*KS: New algorithm for sleeping when using stabilization:
* Energy *this frame* must be higher than sleep threshold and accumulated energy over previous frames
* must be higher than clusterFactor*energyThreshold.
*/
if (wc < wakeCounterResetTime * 0.5f || wc < dt)
{
//Accumulate energy
originalBody->sleepLinVelAcc += sleepLinVelAcc;
originalBody->sleepAngVelAcc += sleepAngVelAcc;
//If energy this frame is high
if (frameNormalizedEnergy >= bodyCore.sleepThreshold)
{
//Compute energy over sleep preparation time
const PxReal sleepAngular = originalBody->sleepAngVelAcc.multiply(originalBody->sleepAngVelAcc).dot(inertia) * invMass;
const PxReal sleepLinear = originalBody->sleepLinVelAcc.magnitudeSquared();
const PxReal normalizedEnergy = 0.5f * (sleepAngular + sleepLinear);
const PxReal sleepClusterFactor = PxReal(1u + bodyCore.numCountedInteractions);
// scale threshold by cluster factor (more contacts => higher sleep threshold)
const PxReal threshold = sleepClusterFactor*bodyCore.sleepThreshold;
//If energy over sleep preparation time is high
if (normalizedEnergy >= threshold)
{
//Wake up
//PX_ASSERT(isActive());
originalBody->resetSleepFilter();
const float factor = bodyCore.sleepThreshold == 0.0f ? 2.0f : PxMin(normalizedEnergy / threshold, 2.0f);
PxReal oldWc = wc;
wc = factor * 0.5f * wakeCounterResetTime + dt * (sleepClusterFactor - 1.0f);
bodyCore.solverWakeCounter = wc;
//if (oldWc == 0.0f) // for the case where a sleeping body got activated by the system (not the user) AND got processed by the solver as well
// notifyNotReadyForSleeping(bodyCore.nodeIndex);
if (oldWc == 0.0f)
originalBody->mInternalFlags |= PxsRigidBody::eACTIVATE_THIS_FRAME;
return wc;
}
}
}
}
else
{
if (wc < wakeCounterResetTime * 0.5f || wc < dt)
{
const PxTransform& body2World = bodyCore.body2World;
// calculate normalized energy: kinetic energy divided by mass
const PxVec3& t = bodyCore.inverseInertia;
const PxVec3 inertia( t.x > 0.0f ? 1.0f / t.x : 1.0f,
t.y > 0.0f ? 1.0f / t.y : 1.0f,
t.z > 0.0f ? 1.0f / t.z : 1.0f);
const PxVec3& sleepLinVelAcc = motionVelocity.linear;
const PxVec3 sleepAngVelAcc = body2World.q.rotateInv(motionVelocity.angular);
originalBody->sleepLinVelAcc += sleepLinVelAcc;
originalBody->sleepAngVelAcc += sleepAngVelAcc;
PxReal invMass = bodyCore.inverseMass;
if (invMass == 0.0f)
invMass = 1.0f;
const PxReal angular = originalBody->sleepAngVelAcc.multiply(originalBody->sleepAngVelAcc).dot(inertia) * invMass;
const PxReal linear = originalBody->sleepLinVelAcc.magnitudeSquared();
const PxReal normalizedEnergy = 0.5f * (angular + linear);
// scale threshold by cluster factor (more contacts => higher sleep threshold)
const PxReal clusterFactor = PxReal(1 + bodyCore.numCountedInteractions);
const PxReal threshold = clusterFactor*bodyCore.sleepThreshold;
if (normalizedEnergy >= threshold)
{
//PX_ASSERT(isActive());
originalBody->resetSleepFilter();
const float factor = threshold == 0.0f ? 2.0f : PxMin(normalizedEnergy / threshold, 2.0f);
PxReal oldWc = wc;
wc = factor * 0.5f * wakeCounterResetTime + dt * (clusterFactor - 1.0f);
bodyCore.solverWakeCounter = wc;
PxU16 flags = 0;
if (oldWc == 0.0f) // for the case where a sleeping body got activated by the system (not the user) AND got processed by the solver as well
{
flags |= PxsRigidBody::eACTIVATE_THIS_FRAME;
//notifyNotReadyForSleeping(bodyCore.nodeIndex);
}
originalBody->mInternalFlags = flags;
return wc;
}
}
}
wc = PxMax(wc - dt, 0.0f);
bodyCore.solverWakeCounter = wc;
return wc;
}
void Dy::sleepCheck(PxsRigidBody* originalBody, PxReal dt, bool enableStabilization, const Cm::SpatialVector& motionVelocity, bool hasStaticTouch)
{
const PxReal wc = updateWakeCounter(originalBody, dt, enableStabilization, motionVelocity, hasStaticTouch);
if(wc == 0.0f)
{
//PxsBodyCore& bodyCore = originalBody->getCore();
originalBody->mInternalFlags |= PxsRigidBody::eDEACTIVATE_THIS_FRAME;
// notifyReadyForSleeping(bodyCore.nodeIndex);
originalBody->resetSleepFilter();
}
}
| 9,071 | C++ | 37.278481 | 174 | 0.722192 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintPartition.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CONSTRAINT_PARTITION_H
#define DY_CONSTRAINT_PARTITION_H
#include "DyDynamics.h"
namespace physx
{
namespace Dy
{
#define MAX_NUM_PARTITIONS 32u
// PT: introduced base classes to start sharing code between the SDK's and the immediate mode's versions.
class RigidBodyClassificationBase
{
PX_NOCOPY(RigidBodyClassificationBase)
PxU8* const mBodies;
const PxU32 mBodySize;
const PxU32 mBodyStride;
const PxU32 mBodyCount;
public:
RigidBodyClassificationBase(PxU8* bodies, PxU32 bodyCount, PxU32 bodyStride) :
mBodies (bodies),
mBodySize (bodyCount*bodyStride),
mBodyStride (bodyStride),
mBodyCount (bodyCount)
{
}
//Returns true if it is a dynamic-dynamic constraint; false if it is a dynamic-static or dynamic-kinematic constraint
PX_FORCE_INLINE bool classifyConstraint(const PxSolverConstraintDesc& desc, uintptr_t& indexA, uintptr_t& indexB,
bool& activeA, bool& activeB, PxU32& bodyAProgress, PxU32& bodyBProgress) const
{
indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mBodyStride;
indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mBodyStride;
activeA = indexA < mBodyCount;
activeB = indexB < mBodyCount;
bodyAProgress = desc.bodyA->solverProgress;
bodyBProgress = desc.bodyB->solverProgress;
return activeA && activeB;
}
PX_FORCE_INLINE PxU32 getStaticContactWriteIndex(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const
{
if(activeA)
return PxU32(desc.bodyA->maxSolverNormalProgress + desc.bodyA->maxSolverFrictionProgress++);
else if(activeB)
return PxU32(desc.bodyB->maxSolverNormalProgress + desc.bodyB->maxSolverFrictionProgress++);
return 0xffffffff;
}
PX_FORCE_INLINE void recordStaticConstraint(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const
{
if(activeA)
desc.bodyA->maxSolverFrictionProgress++;
if(activeB)
desc.bodyB->maxSolverFrictionProgress++;
}
PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress)
{
desc.bodyA->solverProgress = bodyAProgress;
desc.bodyB->solverProgress = bodyBProgress;
}
PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress, PxU16 availablePartition)
{
desc.bodyA->solverProgress = bodyAProgress;
desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, availablePartition);
desc.bodyB->solverProgress = bodyBProgress;
desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, availablePartition);
}
};
class ExtendedRigidBodyClassificationBase
{
PX_NOCOPY(ExtendedRigidBodyClassificationBase)
PxU8* const mBodies;
const PxU32 mBodyCount;
const PxU32 mBodySize;
const PxU32 mStride;
Dy::FeatherstoneArticulation** mArticulations;
const PxU32 mNumArticulations;
public:
ExtendedRigidBodyClassificationBase(PxU8* bodies, PxU32 numBodies, PxU32 stride, Dy::FeatherstoneArticulation** articulations, PxU32 numArticulations) :
mBodies (bodies),
mBodyCount (numBodies),
mBodySize (numBodies*stride),
mStride (stride),
mArticulations (articulations),
mNumArticulations (numArticulations)
{
}
};
struct ConstraintPartitionArgs
{
//Input
PxU8* mBodies;
PxU32 mNumBodies;
PxU32 mStride;
const ArticulationSolverDesc* mArticulationPtrs;
PxU32 mNumArticulationPtrs;
const PxSolverConstraintDesc* mContactConstraintDescriptors;
PxU32 mNumContactConstraintDescriptors;
//output
PxSolverConstraintDesc* mOrderedContactConstraintDescriptors;
PxSolverConstraintDesc* mOverflowConstraintDescriptors;
PxU32 mNumDifferentBodyConstraints;
PxU32 mNumSelfConstraints;
PxU32 mNumStaticConstraints;
PxU32 mNumOverflowConstraints;
PxArray<PxU32>* mConstraintsPerPartition;
//PxArray<PxU32>* mBitField; // PT: removed, unused
PxU32 mMaxPartitions;
bool mEnhancedDeterminism;
bool mForceStaticConstraintsToSolver;
};
PxU32 partitionContactConstraints(ConstraintPartitionArgs& args);
void processOverflowConstraints(PxU8* bodies, PxU32 bodyStride, PxU32 numBodies, ArticulationSolverDesc* articulations, PxU32 numArticulations,
PxSolverConstraintDesc* constraints, PxU32 numConstraints);
} // namespace physx
}
#endif
| 6,032 | C | 35.125748 | 153 | 0.775696 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverExt.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_EXT_H
#define DY_SOLVER_EXT_H
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "CmSpatialVector.h"
#include "foundation/PxVecMath.h"
namespace physx
{
class PxsRigidBody;
struct PxsBodyCore;
struct PxSolverBody;
struct PxSolverBodyData;
namespace Dy
{
class FeatherstoneArticulation;
struct SolverConstraint1D;
class SolverExtBody
{
public:
union
{
const FeatherstoneArticulation* mArticulation;
const PxSolverBody* mBody;
};
const PxSolverBodyData* mBodyData;
PxU32 mLinkIndex;
SolverExtBody(const void* bodyOrArticulationOrSoftBody, const void* bodyData, PxU32 linkIndex):
mBody(reinterpret_cast<const PxSolverBody*>(bodyOrArticulationOrSoftBody)),
mBodyData(reinterpret_cast<const PxSolverBodyData*>(bodyData)),
mLinkIndex(linkIndex)
{}
void getResponse(const PxVec3& linImpulse, const PxVec3& angImpulse,
PxVec3& linDeltaV, PxVec3& angDeltaV, PxReal dominance) const;
void getResponse(const aos::Vec3V& linImpulse, const aos::Vec3V& angImpulse,
aos::Vec3V& linDeltaV, aos::Vec3V& angDeltaV, aos::FloatV dominance) const;
PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const;
aos::FloatV projectVelocity(const aos::Vec3V& linear, const aos::Vec3V& angular) const;
PxVec3 getLinVel() const;
PxVec3 getAngVel() const;
aos::Vec3V getLinVelV() const;
aos::Vec3V getAngVelV() const;
Cm::SpatialVectorV getVelocity() const;
PxReal getCFM() const;
};
}
}
#endif
| 3,206 | C | 33.117021 | 97 | 0.761697 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationContactPrepPF.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DyCorrelationBuffer.h"
#include "DySolverConstraintExtShared.h"
#include "DyFeatherstoneArticulation.h"
using namespace physx;
using namespace Gu;
// constraint-gen only, since these use getVelocityFast methods
// which aren't valid during the solver phase
namespace physx
{
namespace Dy
{
bool setupFinalizeExtSolverContactsCoulomb(
const PxContactBuffer& buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
PxReal invDt,
PxReal dtF32,
PxReal bounceThresholdF32,
const SolverExtBody& b0,
const SolverExtBody& b1,
PxU32 frictionCountPerPoint,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
PxReal restDist,
PxReal ccdMaxDistance,
Cm::SpatialVectorF* Z,
const PxReal solverOffsetSlop)
{
// NOTE II: the friction patches are sparse (some of them have no contact patches, and
// therefore did not get written back to the cache) but the patch addresses are dense,
// corresponding to valid patches
const FloatV ccdMaxSeparation = FLoad(ccdMaxDistance);
const Vec3V offsetSlop = V3Load(solverOffsetSlop);
PxU8* PX_RESTRICT ptr = workspace;
//KS - TODO - this should all be done in SIMD to avoid LHS
PxF32 maxPenBias0 = b0.mBodyData->penBiasClamp;
PxF32 maxPenBias1 = b1.mBodyData->penBiasClamp;
if (b0.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY)
{
maxPenBias0 = b0.mArticulation->getLinkMaxPenBias(b0.mLinkIndex);
}
if (b1.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY)
{
maxPenBias1 = b1.mArticulation->getLinkMaxPenBias(b1.mLinkIndex);
}
const FloatV maxPenBias = FLoad(PxMax(maxPenBias0, maxPenBias1)/invDt);
const FloatV restDistance = FLoad(restDist);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const Cm::SpatialVectorV vel0 = b0.getVelocity();
const Cm::SpatialVectorV vel1 = b1.getVelocity();
const FloatV invDtV = FLoad(invDt);
const FloatV pt8 = FLoad(0.8f);
const FloatV invDtp8 = FMul(invDtV, pt8);
const FloatV dt = FLoad(dtF32);
const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p);
const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p);
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
const PxU32 frictionPatchCount = c.frictionPatchCount;
const PxU32 pointStride = sizeof(SolverContactPointExt);
const PxU32 frictionStride = sizeof(SolverContactFrictionExt);
const PxU8 pointHeaderType = DY_SC_TYPE_EXT_CONTACT;
const PxU8 frictionHeaderType = DY_SC_TYPE_EXT_FRICTION;
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
PxU8 flags = 0;
const FloatV cfm = FLoad(PxMax(b0.getCFM(), b1.getCFM()));
for(PxU32 i=0;i< frictionPatchCount;i++)
{
const PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start;
const Vec3V normalV = aos::V3LoadA(contactBase0->normal);
const Vec3V normal = V3LoadA(contactBase0->normal);
const PxReal combinedRestitution = contactBase0->restitution;
SolverContactCoulombHeader* PX_RESTRICT header = reinterpret_cast<SolverContactCoulombHeader*>(ptr);
ptr += sizeof(SolverContactCoulombHeader);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
const FloatV restitution = FLoad(combinedRestitution);
const FloatV damping = FLoad(contactBase0->damping);
header->numNormalConstr = PxU8(contactCount);
header->type = pointHeaderType;
//header->setRestitution(combinedRestitution);
header->setDominance0(d0);
header->setDominance1(d1);
header->angDom0 = invInertiaScale0;
header->angDom1 = invInertiaScale1;
header->flags = flags;
header->setNormal(normalV);
const FloatV norVel0 = V3Dot(normalV, vel0.linear);
const FloatV norVel1 = V3Dot(normalV, vel1.linear);
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer.contacts + c.contactPatches[patch].start;
PxU8* p = ptr;
for(PxU32 j=0;j<count;j++)
{
const PxContactPoint& contact = contactBase[j];
SolverContactPointExt* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointExt*>(p);
p += pointStride;
setupExtSolverContact(b0, b1, d0, d1, angD0, angD1, bodyFrame0p, bodyFrame1p, normal, invDtV, invDtp8, dt, restDistance, maxPenBias, restitution,
bounceThreshold, contact, *solverContact, ccdMaxSeparation, Z, vel0, vel1, cfm, offsetSlop,
norVel0, norVel1, damping);
}
ptr = p;
}
}
//construct all the frictions
PxU8* PX_RESTRICT ptr2 = workspace;
const PxF32 orthoThreshold = 0.70710678f;
const PxF32 eps = 0.00001f;
bool hasFriction = false;
for(PxU32 i=0;i< frictionPatchCount;i++)
{
const PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
SolverContactCoulombHeader* header = reinterpret_cast<SolverContactCoulombHeader*>(ptr2);
header->frictionOffset = PxU16(ptr - ptr2);
ptr2 += sizeof(SolverContactCoulombHeader) + header->numNormalConstr * pointStride;
const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start;
PxVec3 normal = contactBase0->normal;
const PxReal staticFriction = contactBase0->staticFriction;
const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
const bool haveFriction = (disableStrongFriction == 0);
SolverFrictionHeader* frictionHeader = reinterpret_cast<SolverFrictionHeader*>(ptr);
frictionHeader->numNormalConstr = PxTo8(c.frictionPatchContactCounts[i]);
frictionHeader->numFrictionConstr = PxTo8(haveFriction ? c.frictionPatchContactCounts[i] * frictionCountPerPoint : 0);
frictionHeader->flags = flags;
ptr += sizeof(SolverFrictionHeader);
PxF32* forceBuffer = reinterpret_cast<PxF32*>(ptr);
ptr += frictionHeader->getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]);
PxMemZero(forceBuffer, sizeof(PxF32) * c.frictionPatchContactCounts[i]);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
const PxVec3 t0Fallback1(0.f, -normal.z, normal.y);
const PxVec3 t0Fallback2(-normal.y, normal.x, 0.f);
const PxVec3 tFallback1 = orthoThreshold > PxAbs(normal.x) ? t0Fallback1 : t0Fallback2;
const PxVec3 vrel = b0.getLinVel() - b1.getLinVel();
const PxVec3 t0_ = vrel - normal * (normal.dot(vrel));
const PxReal sqDist = t0_.dot(t0_);
const PxVec3 tDir0 = (sqDist > eps ? t0_: tFallback1).getNormalized();
const PxVec3 tDir1 = tDir0.cross(normal);
PxVec3 tFallback[2] = {tDir0, tDir1};
PxU32 ind = 0;
if(haveFriction)
{
hasFriction = true;
frictionHeader->setStaticFriction(staticFriction);
frictionHeader->invMass0D0 = invMassScale0;
frictionHeader->invMass1D1 = invMassScale1;
frictionHeader->angDom0 = invInertiaScale0;
frictionHeader->angDom1 = invInertiaScale1;
frictionHeader->type = frictionHeaderType;
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxU32 start = c.contactPatches[patch].start;
const PxContactPoint* contactBase = buffer.contacts + start;
PxU8* p = ptr;
for(PxU32 j =0; j < count; j++)
{
const PxContactPoint& contact = contactBase[j];
const Vec3V ra = V3Sub(V3LoadA(contact.point), bodyFrame0p);
const Vec3V rb = V3Sub(V3LoadA(contact.point), bodyFrame1p);
const Vec3V targetVel = V3LoadA(contact.targetVel);
const Vec3V pVRa = V3Add(vel0.linear, V3Cross(vel0.angular, ra));
const Vec3V pVRb = V3Add(vel1.linear, V3Cross(vel1.angular, rb));
//const PxVec3 vrel = pVRa - pVRb;
for(PxU32 k = 0; k < frictionCountPerPoint; ++k)
{
SolverContactFrictionExt* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionExt*>(p);
p += frictionStride;
Vec3V t0 = V3LoadU(tFallback[ind]);
ind = 1 - ind;
const Vec3V raXn = V3Cross(ra, t0);
const Vec3V rbXn = V3Cross(rb, t0);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t0, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t0), V3Neg(rbXn), b1);
FloatV unitResponse = getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(Z));
FloatV tv = V3Dot(targetVel, t0);
if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
tv = FAdd(tv, V3Dot(pVRa, t0));
else if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
tv = FSub(tv, V3Dot(pVRb, t0));
const FloatV recipResponse = FSel(FIsGrtr(unitResponse, FZero()), FRecip(unitResponse), FZero());
f0->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), recipResponse);
f0->rbXnXYZ_biasW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), FZero());
f0->normalXYZ_appliedForceW = V4SetW(Vec4V_From_Vec3V(t0), FZero());
FStore(tv, &f0->targetVel);
f0->linDeltaVA = deltaV0.linear;
f0->angDeltaVA = deltaV0.angular;
f0->linDeltaVB = deltaV1.linear;
f0->angDeltaVB = deltaV1.angular;
}
}
ptr = p;
}
}
}
//PX_ASSERT(ptr - workspace == n.solverConstraintSize);
return hasFriction;
}
}
}
| 11,579 | C++ | 35.30094 | 149 | 0.727783 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraint1DStep.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONSTRAINT_1D_STEP_H
#define DY_SOLVER_CONSTRAINT_1D_STEP_H
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "DyArticulationUtils.h"
#include "DySolverConstraintTypes.h"
#include "DySolverBody.h"
#include "PxConstraintDesc.h"
#include "DySolverConstraintDesc.h"
namespace physx
{
namespace Dy
{
struct SolverContactHeaderStep
{
enum DySolverContactFlags
{
eHAS_FORCE_THRESHOLDS = 0x1
};
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 flags;
PxU8 numNormalConstr;
PxU8 numFrictionConstr; //4
PxReal angDom0; //8
PxReal angDom1; //12
PxReal invMass0; //16
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W; //32
PxVec3 normal; //48
PxReal maxPenBias; //52
PxReal invMass1; //56
PxReal minNormalForce; //60
PxU32 broken; //64
PxU8* frictionBrokenWritebackByte; //68 72
Sc::ShapeInteraction* shapeInteraction; //72 80
#if !PX_P64_FAMILY
PxU32 pad[2]; //80
#endif
PX_FORCE_INLINE FloatV getStaticFriction() const { return V4GetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE FloatV getDynamicFriction() const { return V4GetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE FloatV getDominance0() const { return V4GetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE FloatV getDominance1() const { return V4GetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
};
struct SolverContactPointStep
{
PxVec3 raXnI;
PxF32 separation;
PxVec3 rbXnI;
PxF32 velMultiplier;
PxF32 targetVelocity;
PxF32 biasCoefficient;
PxF32 recipResponse;
PxF32 maxImpulse;
};
struct SolverContactPointStepExt : public SolverContactPointStep
{
Vec3V linDeltaVA;
Vec3V linDeltaVB;
Vec3V angDeltaVA;
Vec3V angDeltaVB;
};
struct SolverContactFrictionStep
{
Vec4V normalXYZ_ErrorW; //16
Vec4V raXnI_targetVelW;
Vec4V rbXnI_velMultiplierW;
PxReal biasScale;
PxReal appliedForce;
PxReal frictionScale;
PxU32 pad[1];
PX_FORCE_INLINE void setAppliedForce(const FloatV f) { FStore(f, &appliedForce); }
};
struct SolverContactFrictionStepExt : public SolverContactFrictionStep
{
Vec3V linDeltaVA;
Vec3V linDeltaVB;
Vec3V angDeltaVA;
Vec3V angDeltaVB;
};
struct SolverConstraint1DHeaderStep
{
PxU8 type; // enum SolverConstraintType - must be first byte
PxU8 count; // count of following 1D constraints
PxU8 dominance;
PxU8 breakable; // indicate whether this constraint is breakable or not
PxReal linBreakImpulse;
PxReal angBreakImpulse;
PxReal invMass0D0;
PxVec3 body0WorldOffset;
PxReal invMass1D1;
PxVec3 rAWorld;
PxReal linearInvMassScale0; // only used by articulations
PxVec3 rBWorld;
PxReal angularInvMassScale0;
PxReal linearInvMassScale1; // only used by articulations
PxReal angularInvMassScale1;
PxU32 pad[2];
//Ortho axes for body 0, recipResponse in W component
PxVec4 angOrthoAxis0_recipResponseW[3];
//Ortho axes for body 1, error of body in W component
PxVec4 angOrthoAxis1_Error[3];
};
PX_FORCE_INLINE void init(SolverConstraint1DHeaderStep& h,
PxU8 count,
bool isExtended,
const PxConstraintInvMassScale& ims)
{
h.type = PxU8(isExtended ? DY_SC_TYPE_EXT_1D : DY_SC_TYPE_RB_1D);
h.count = count;
h.dominance = 0;
h.linearInvMassScale0 = ims.linear0;
h.angularInvMassScale0 = ims.angular0;
h.linearInvMassScale1 = -ims.linear1;
h.angularInvMassScale1 = -ims.angular1;
}
PX_ALIGN_PREFIX(16)
struct SolverConstraint1DStep
{
public:
PxVec3 lin0; //!< linear velocity projection (body 0)
PxReal error; //!< constraint error term - must be scaled by biasScale. Can be adjusted at run-time
PxVec3 lin1; //!< linear velocity projection (body 1)
PxReal biasScale; //!< constraint constant bias scale. Constant
PxVec3 ang0; //!< angular velocity projection (body 0)
PxReal velMultiplier; //!< constraint velocity multiplier
PxVec3 ang1; //!< angular velocity projection (body 1)
PxReal velTarget; //!< Scaled target velocity of the constraint drive
PxReal minImpulse; //!< Lower bound on impulse magnitude
PxReal maxImpulse; //!< Upper bound on impulse magnitude
PxReal appliedForce; //!< applied force to correct velocity+bias
PxReal maxBias;
PxU32 flags;
PxReal recipResponse; //Constant. Only used for articulations;
PxReal angularErrorScale; //Constant
PxU32 pad;
} PX_ALIGN_SUFFIX(16);
struct SolverConstraint1DExtStep : public SolverConstraint1DStep
{
public:
Cm::SpatialVectorV deltaVA;
Cm::SpatialVectorV deltaVB;
};
PX_FORCE_INLINE void init(SolverConstraint1DStep& c,
const PxVec3& _linear0, const PxVec3& _linear1,
const PxVec3& _angular0, const PxVec3& _angular1,
PxReal _minImpulse, PxReal _maxImpulse)
{
PX_ASSERT(_linear0.isFinite());
PX_ASSERT(_linear1.isFinite());
c.lin0 = _linear0;
c.lin1 = _linear1;
c.ang0 = _angular0;
c.ang1 = _angular1;
c.minImpulse = _minImpulse;
c.maxImpulse = _maxImpulse;
c.flags = 0;
c.appliedForce = 0;
c.angularErrorScale = 1.f;
}
}//namespace Dy
}
#endif
| 7,199 | C | 31.432432 | 129 | 0.714266 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraint1D4.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONSTRAINT_1D4_H
#define DY_SOLVER_CONSTRAINT_1D4_H
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "DyArticulationUtils.h"
#include "DySolverConstraint1D.h"
namespace physx
{
namespace Dy
{
struct SolverConstraint1DHeader4
{
PxU8 type; // enum SolverConstraintType - must be first byte
PxU8 pad0[3];
//These counts are the max of the 4 sets of data.
//When certain pairs have fewer constraints than others, they are padded with 0s so that no work is performed but
//calculations are still shared (afterall, they're computationally free because we're doing 4 things at a time in SIMD)
PxU32 count;
PxU8 count0, count1, count2, count3;
PxU8 break0, break1, break2, break3;
Vec4V linBreakImpulse;
Vec4V angBreakImpulse;
Vec4V invMass0D0;
Vec4V invMass1D1;
Vec4V angD0;
Vec4V angD1;
Vec4V body0WorkOffsetX;
Vec4V body0WorkOffsetY;
Vec4V body0WorkOffsetZ;
};
struct SolverConstraint1DBase4
{
public:
Vec4V lin0X;
Vec4V lin0Y;
Vec4V lin0Z;
Vec4V ang0X;
Vec4V ang0Y;
Vec4V ang0Z;
Vec4V ang0WritebackX;
Vec4V ang0WritebackY;
Vec4V ang0WritebackZ;
Vec4V constant;
Vec4V unbiasedConstant;
Vec4V velMultiplier;
Vec4V impulseMultiplier;
Vec4V minImpulse;
Vec4V maxImpulse;
Vec4V appliedForce;
PxU32 flags[4];
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DBase4) == 272);
struct SolverConstraint1DDynamic4 : public SolverConstraint1DBase4
{
Vec4V lin1X;
Vec4V lin1Y;
Vec4V lin1Z;
Vec4V ang1X;
Vec4V ang1Y;
Vec4V ang1Z;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DDynamic4) == 368);
}
}
#endif
| 3,304 | C | 30.179245 | 120 | 0.763015 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFrictionPatch.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_FRICTION_PATCH_H
#define DY_FRICTION_PATCH_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
namespace physx
{
namespace Dy
{
struct FrictionPatch
{
PxU8 broken; // PT: must be first byte of struct, see "frictionBrokenWritebackByte"
PxU8 materialFlags;
PxU16 anchorCount;
PxReal restitution;
PxReal staticFriction;
PxReal dynamicFriction;
PxVec3 body0Normal;
PxVec3 body1Normal;
PxVec3 body0Anchors[2];
PxVec3 body1Anchors[2];
PxQuat relativeQuat;
PX_FORCE_INLINE void operator = (const FrictionPatch& other)
{
broken = other.broken;
materialFlags = other.materialFlags;
anchorCount = other.anchorCount;
body0Normal = other.body0Normal;
body1Normal = other.body1Normal;
body0Anchors[0] = other.body0Anchors[0];
body0Anchors[1] = other.body0Anchors[1];
body1Anchors[0] = other.body1Anchors[0];
body1Anchors[1] = other.body1Anchors[1];
relativeQuat = other.relativeQuat;
restitution = other.restitution;
staticFriction = other.staticFriction;
dynamicFriction = other.dynamicFriction;
}
};
//PX_COMPILE_TIME_ASSERT(sizeof(FrictionPatch)==80);
}
}
#endif
| 2,894 | C | 34.74074 | 90 | 0.752246 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraint1D.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONSTRAINT_1D_H
#define DY_SOLVER_CONSTRAINT_1D_H
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "DyArticulationUtils.h"
#include "DySolverConstraintTypes.h"
#include "DySolverBody.h"
#include "PxConstraintDesc.h"
#include "DySolverConstraintDesc.h"
namespace physx
{
namespace Dy
{
// dsequeira: we should probably fork these structures for constraints and extended constraints,
// since there's a few things that are used for one but not the other
struct SolverConstraint1DHeader
{
PxU8 type; // enum SolverConstraintType - must be first byte
PxU8 count; // count of following 1D constraints
PxU8 dominance;
PxU8 breakable; // indicate whether this constraint is breakable or not
PxReal linBreakImpulse;
PxReal angBreakImpulse;
PxReal invMass0D0;
PxVec3 body0WorldOffset;
PxReal invMass1D1;
PxReal linearInvMassScale0; // only used by articulations
PxReal angularInvMassScale0; // only used by articulations
PxReal linearInvMassScale1; // only used by articulations
PxReal angularInvMassScale1; // only used by articulations
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DHeader) == 48);
PX_ALIGN_PREFIX(16)
struct SolverConstraint1D
{
public:
PxVec3 lin0; //!< linear velocity projection (body 0)
PxReal constant; //!< constraint constant term
PxVec3 lin1; //!< linear velocity projection (body 1)
PxReal unbiasedConstant; //!< constraint constant term without bias
PxVec3 ang0; //!< angular velocity projection (body 0)
PxReal velMultiplier; //!< constraint velocity multiplier
PxVec3 ang1; //!< angular velocity projection (body 1)
PxReal impulseMultiplier; //!< constraint impulse multiplier
PxVec3 ang0Writeback; //!< unscaled angular velocity projection (body 0)
PxU32 pad;
PxReal minImpulse; //!< Lower bound on impulse magnitude
PxReal maxImpulse; //!< Upper bound on impulse magnitude
PxReal appliedForce; //!< applied force to correct velocity+bias
PxU32 flags;
} PX_ALIGN_SUFFIX(16);
PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1D) == 96);
struct SolverConstraint1DExt : public SolverConstraint1D
{
public:
Cm::SpatialVectorV deltaVA;
Cm::SpatialVectorV deltaVB;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DExt) == 160);
PX_FORCE_INLINE void init(SolverConstraint1DHeader& h,
PxU8 count,
bool isExtended,
const PxConstraintInvMassScale& ims)
{
h.type = PxU8(isExtended ? DY_SC_TYPE_EXT_1D : DY_SC_TYPE_RB_1D);
h.count = count;
h.dominance = 0;
h.linearInvMassScale0 = ims.linear0;
h.angularInvMassScale0 = ims.angular0;
h.linearInvMassScale1 = -ims.linear1;
h.angularInvMassScale1 = -ims.angular1;
}
PX_FORCE_INLINE void init(SolverConstraint1D& c,
const PxVec3& _linear0, const PxVec3& _linear1,
const PxVec3& _angular0, const PxVec3& _angular1,
PxReal _minImpulse, PxReal _maxImpulse)
{
PX_ASSERT(_linear0.isFinite());
PX_ASSERT(_linear1.isFinite());
c.lin0 = _linear0;
c.lin1 = _linear1;
c.ang0 = _angular0;
c.ang1 = _angular1;
c.minImpulse = _minImpulse;
c.maxImpulse = _maxImpulse;
c.flags = 0;
c.appliedForce = 0;
}
PX_FORCE_INLINE bool needsNormalVel(const Px1DConstraint &c)
{
return c.flags & Px1DConstraintFlag::eRESTITUTION
|| (c.flags & Px1DConstraintFlag::eSPRING && c.flags & Px1DConstraintFlag::eACCELERATION_SPRING);
}
PX_FORCE_INLINE void setSolverConstants(PxReal& constant,
PxReal& unbiasedConstant,
PxReal& velMultiplier,
PxReal& impulseMultiplier,
const Px1DConstraint& c,
PxReal normalVel,
PxReal unitResponse,
PxReal minRowResponse,
PxReal erp,
PxReal dt,
PxReal recipdt)
{
PX_ASSERT(PxIsFinite(unitResponse));
PxReal recipResponse = unitResponse <= minRowResponse ? 0 : 1.0f/unitResponse;
if(c.flags & Px1DConstraintFlag::eSPRING)
{
PxReal a = dt * dt * c.mods.spring.stiffness + dt * c.mods.spring.damping;
PxReal b = dt * (c.mods.spring.damping * c.velocityTarget - c.mods.spring.stiffness * c.geometricError);
if(c.flags & Px1DConstraintFlag::eACCELERATION_SPRING)
{
PxReal x = 1.0f/(1.0f+a);
constant = unbiasedConstant = x * recipResponse * b;
velMultiplier = -x * recipResponse * a;
impulseMultiplier = 1.0f-x;
}
else
{
PxReal x = unitResponse == 0.f ? 0.f : 1.0f/(1.0f+a*unitResponse);
constant = unbiasedConstant = x * b;
velMultiplier = -x*a;
impulseMultiplier = 1.0f-x;
}
}
else
{
PxReal geomError = c.geometricError * erp;
velMultiplier = -recipResponse;
impulseMultiplier = 1.0f;
if(c.flags & Px1DConstraintFlag::eRESTITUTION && -normalVel>c.mods.bounce.velocityThreshold)
{
unbiasedConstant = constant = recipResponse * c.mods.bounce.restitution*-normalVel;
}
else
{
// see usage of 'for internal use' in preprocessRows()
constant = recipResponse * (c.velocityTarget - geomError*recipdt);
unbiasedConstant = recipResponse * (c.velocityTarget - c.forInternalUse*recipdt);
}
}
}
}
}
#endif
| 6,791 | C | 32.294117 | 106 | 0.722721 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationCpuGpu.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_ARTICULATION_CPUGPU_H
#define DY_ARTICULATION_CPUGPU_H
#include "foundation/PxSimpleTypes.h"
#include "PxArticulationJointReducedCoordinate.h"
#include "DyFeatherstoneArticulation.h"
#define DY_ARTICULATION_MIN_RESPONSE 1e-5f
#define DY_ARTICULATION_CFM 2e-4f
#define DY_ARTICULATION_PGS_BIAS_COEFFICIENT 0.8f
namespace physx
{
namespace Dy
{
PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc computeImplicitDriveParamsForceDrive
(const PxReal stiffness, const PxReal damping, const PxReal dt,
const PxReal unitResponse, const PxReal geomError, const PxReal targetVelocity, const bool isTGSSolver)
{
ArticulationImplicitDriveDesc driveDesc(PxZero);
const PxReal a = dt * (dt*stiffness + damping);
const PxReal b = dt * (damping * targetVelocity);
const PxReal x = unitResponse > 0.f ? 1.0f / (1.0f + a*unitResponse) : 0.f;
const PxReal driveBiasCoefficient = stiffness * x * dt;
driveDesc.driveTargetVelPlusInitialBias = (x * b) + (geomError * driveBiasCoefficient);
driveDesc.driveVelMultiplier = -x * a;
driveDesc.driveBiasCoefficient = driveBiasCoefficient;
driveDesc.driveImpulseMultiplier = isTGSSolver ? 1.f : 1.0f - x;
return driveDesc;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc computeImplicitDriveParamsAccelerationDrive
(const PxReal stiffness, const PxReal damping, const PxReal dt,
const PxReal recipUnitResponse, const PxReal geomError, const PxReal targetVelocity, const bool isTGSSolver)
{
ArticulationImplicitDriveDesc driveDesc(PxZero);
const PxReal a = dt * (dt*stiffness + damping);
const PxReal b = dt * (damping * targetVelocity);
const PxReal x = 1.0f / (1.0f + a);
const PxReal driveBiasCoefficient = stiffness * x * recipUnitResponse * dt;
driveDesc.driveTargetVelPlusInitialBias = (x * b * recipUnitResponse) + (geomError * driveBiasCoefficient);
driveDesc.driveVelMultiplier = -x * a * recipUnitResponse;
driveDesc.driveBiasCoefficient = driveBiasCoefficient;
driveDesc.driveImpulseMultiplier = isTGSSolver ? 1.f : 1.0f - x;
return driveDesc;
}
/**
\brief Compute the parameters for an implicitly integrated spring.
\param[in] driveType is the type of drive.
\param[in] stiffness is the drive stiffness (force per unit position bias)
\param[in] damping is the drive damping (force per unit velocity bias)
\param[in] dt is the timestep that will be used to forward integrate the spring position bias.
\param[in] unitResponse is the multiplier that converts impulse to velocity change.
\param[in] recipUnitResponse is the reciprocal of unitResponse
\param[in] geomError is the position bias with value (targetPos - currentPos)
\param[in] targetVelocity is the target velocity of the drive.
\param[in] isTGSSolver should be set true when computing implicit spring params for TGS and false for PGS.
\return The implicit spring parameters.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc computeImplicitDriveParams
(const PxArticulationDriveType::Enum driveType, const PxReal stiffness, const PxReal damping, const PxReal dt,
const PxReal unitResponse, const PxReal recipUnitResponse, const PxReal geomError, const PxReal targetVelocity, const bool isTGSSolver)
{
ArticulationImplicitDriveDesc driveDesc(PxZero);
switch (driveType)
{
case PxArticulationDriveType::eFORCE:
{
driveDesc = computeImplicitDriveParamsForceDrive(stiffness, damping, dt, unitResponse, geomError, targetVelocity, isTGSSolver);
}
break;
case PxArticulationDriveType::eACCELERATION:
{
driveDesc = computeImplicitDriveParamsAccelerationDrive(stiffness, damping, dt, recipUnitResponse, geomError, targetVelocity, isTGSSolver);
}
break;
case PxArticulationDriveType::eTARGET:
{
driveDesc = computeImplicitDriveParamsForceDrive(1e+25f, 0.0f, dt, unitResponse, geomError, targetVelocity, isTGSSolver);
}
break;
case PxArticulationDriveType::eVELOCITY:
{
driveDesc = computeImplicitDriveParamsForceDrive(0.0f, 1e+25f, dt, unitResponse, geomError, targetVelocity, isTGSSolver);
}
break;
case PxArticulationDriveType::eNONE:
{
PX_ASSERT(false);
}
break;
}
return driveDesc;
}
/**
\brief Compute the drive impulse for an implicitly integrated spring.
\param[in] accumulatedDriveImpulse is the drive impulse that has accumulated since the the solver started on the current simulation step.
\param[in] jointVel is the current velocity of the joint.
\param[in] jointDeltaPos is the change in joint position that has accumulated since the the solver started on the current simulation step.
\param[in] driveDesc is the implicit spring params.
\return The impulse for the implicitly integrated spring.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal computeDriveImpulse
(const PxReal accumulatedDriveImpulse, const PxReal jointVel, const PxReal jointDeltaPos, const ArticulationImplicitDriveDesc& driveDesc)
{
const PxReal unclampedForce =
accumulatedDriveImpulse * driveDesc.driveImpulseMultiplier
+ jointVel * driveDesc.driveVelMultiplier
+ driveDesc.driveTargetVelPlusInitialBias
- jointDeltaPos * driveDesc.driveBiasCoefficient;
return unclampedForce;
}
} //namespace Dy
} //namespace physx
#endif //DY_ARTICULATION_CPUGPU_H
| 6,854 | C | 45.006711 | 141 | 0.788882 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContactPF.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONTACT_PF_H
#define DY_SOLVER_CONTACT_PF_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
using namespace aos;
namespace Dy
{
struct SolverContactCoulombHeader
{
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 numNormalConstr;
PxU16 frictionOffset; //4
//PxF32 restitution;
PxF32 angDom0; //8
PxF32 dominance0; //12
PxF32 dominance1; //16
PX_ALIGN(16, PxVec3 normalXYZ); //28
PxF32 angDom1; //32
Sc::ShapeInteraction* shapeInteraction; //36 40
PxU8 flags; //37 41
PxU8 pad0[3]; //40 44
#if !PX_P64_FAMILY
PxU32 pad1[2]; //48
#else
PxU32 pad1; // 48
#endif
PX_FORCE_INLINE void setDominance0(const FloatV f) {FStore(f, &dominance0);}
PX_FORCE_INLINE void setDominance1(const FloatV f) {FStore(f, &dominance1);}
PX_FORCE_INLINE void setNormal(const Vec3V n) {V3StoreA(n, normalXYZ);}
PX_FORCE_INLINE FloatV getDominance0() const {return FLoad(dominance0);}
PX_FORCE_INLINE FloatV getDominance1() const {return FLoad(dominance1);}
//PX_FORCE_INLINE FloatV getRestitution() const {return FLoad(restitution);}
PX_FORCE_INLINE Vec3V getNormal()const {return V3LoadA(normalXYZ);}
PX_FORCE_INLINE void setDominance0(PxF32 f) { dominance0 = f; }
PX_FORCE_INLINE void setDominance1(PxF32 f) { dominance1 = f;}
//PX_FORCE_INLINE void setRestitution(PxF32 f) { restitution = f;}
PX_FORCE_INLINE PxF32 getDominance0PxF32() const {return dominance0;}
PX_FORCE_INLINE PxF32 getDominance1PxF32() const {return dominance1;}
//PX_FORCE_INLINE PxF32 getRestitutionPxF32() const {return restitution;}
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactCoulombHeader) == 48);
struct SolverFrictionHeader
{
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 numNormalConstr;
PxU8 numFrictionConstr;
PxU8 flags;
PxF32 staticFriction;
PxF32 invMass0D0;
PxF32 invMass1D1;
PxF32 angDom0;
PxF32 angDom1;
PxU32 pad2[2];
PX_FORCE_INLINE void setStaticFriction(const FloatV f) {FStore(f, &staticFriction);}
PX_FORCE_INLINE FloatV getStaticFriction() const {return FLoad(staticFriction);}
PX_FORCE_INLINE void setStaticFriction(PxF32 f) {staticFriction = f;}
PX_FORCE_INLINE PxF32 getStaticFrictionPxF32() const {return staticFriction;}
PX_FORCE_INLINE PxU32 getAppliedForcePaddingSize() const {return sizeof(PxU32)*((4 * ((numNormalConstr + 3)/4)));}
static PX_FORCE_INLINE PxU32 getAppliedForcePaddingSize(const PxU32 numConstr) {return sizeof(PxU32)*((4 * ((numConstr + 3)/4)));}
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverFrictionHeader) == 32);
}
}
#endif
| 4,499 | C | 36.190082 | 131 | 0.738831 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 DY_SOLVER_BODY_H
#define DY_SOLVER_BODY_H
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMat33.h"
#include "CmSpatialVector.h"
#include "solver/PxSolverDefs.h"
namespace physx
{
class PxsRigidBody;
struct PxsBodyCore;
namespace Dy
{
// PT: TODO: make sure this is still needed / replace with V4sqrt
//This method returns values of 0 when the inertia is 0. This is a bit of a hack but allows us to
//represent kinematic objects' velocities in our new format
PX_FORCE_INLINE PxVec3 computeSafeSqrtInertia(const PxVec3& v)
{
return PxVec3( v.x == 0.0f ? 0.0f : PxSqrt(v.x),
v.y == 0.0f ? 0.0f : PxSqrt(v.y),
v.z == 0.0f ? 0.0f : PxSqrt(v.z));
}
void copyToSolverBodyData(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold, PxSolverBodyData& solverBodyData, PxU32 lockFlags,
PxReal dt, bool gyroscopicForces);
// PT: TODO: using PxsBodyCore in the interface makes us write less data to the stack for passing arguments, and we can take advantage of the class layout
// (we know what is aligned or not, we know if it is safe to V4Load vectors, etc). Note that this is what we previously had, which is why PxsBodyCore was still
// forward-referenced above.
//void copyToSolverBodyData(PxSolverBodyData& solverBodyData, const PxsBodyCore& core, const PxU32 nodeIndex);
}
}
#endif
| 3,092 | C | 43.826086 | 159 | 0.765201 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverControl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONTROL_H
#define DY_SOLVER_CONTROL_H
#include "DySolverCore.h"
#include "DySolverConstraintDesc.h"
namespace physx
{
namespace Dy
{
class BatchIterator
{
PX_NOCOPY(BatchIterator)
public:
PxConstraintBatchHeader* constraintBatchHeaders;
PxU32 mSize;
PxU32 mCurrentIndex;
BatchIterator(PxConstraintBatchHeader* _constraintBatchHeaders, PxU32 size) : constraintBatchHeaders(_constraintBatchHeaders),
mSize(size), mCurrentIndex(0)
{
}
PX_FORCE_INLINE const PxConstraintBatchHeader& GetCurrentHeader(const PxU32 constraintIndex)
{
PxU32 currentIndex = mCurrentIndex;
while((constraintIndex - constraintBatchHeaders[currentIndex].startIndex) >= constraintBatchHeaders[currentIndex].stride)
currentIndex = (currentIndex + 1)%mSize;
PxPrefetchLine(&constraintBatchHeaders[currentIndex], 128);
mCurrentIndex = currentIndex;
return constraintBatchHeaders[currentIndex];
}
};
inline void SolveBlockParallel( PxSolverConstraintDesc* PX_RESTRICT constraintList, const PxI32 batchCount, const PxI32 index,
const PxI32 headerCount, SolverContext& cache, BatchIterator& iterator,
SolveBlockMethod solveTable[],
const PxI32 iteration)
{
const PxI32 indA = index - (iteration * headerCount);
const PxConstraintBatchHeader* PX_RESTRICT headers = iterator.constraintBatchHeaders;
const PxI32 endIndex = indA + batchCount;
for(PxI32 i = indA; i < endIndex; ++i)
{
PX_ASSERT(i < PxI32(iterator.mSize));
const PxConstraintBatchHeader& header = headers[i];
const PxI32 numToGrab = header.stride;
PxSolverConstraintDesc* PX_RESTRICT block = &constraintList[header.startIndex];
// PT: TODO: revisit this one
PxPrefetch(block[0].constraint, 384);
for(PxI32 b = 0; b < numToGrab; ++b)
{
PxPrefetchLine(block[b].bodyA);
PxPrefetchLine(block[b].bodyB);
}
//OK. We have a number of constraints to run...
solveTable[header.constraintType](block, PxU32(numToGrab), cache);
}
}
// PT: TODO: these "solver core" classes are mostly stateless, at this point they could just be function pointers like the solve methods.
class SolverCoreGeneral : public SolverCore
{
public:
bool mFrictionEveryIteration;
SolverCoreGeneral(bool fricEveryIteration) : mFrictionEveryIteration(fricEveryIteration) {}
// SolverCore
virtual void solveVParallelAndWriteBack
(SolverIslandParams& params, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const PX_OVERRIDE PX_FINAL;
virtual void solveV_Blocks
(SolverIslandParams& params) const PX_OVERRIDE PX_FINAL;
//~SolverCore
};
// PT: TODO: we use "extern" instead of functions for TGS. Unify.
SolveBlockMethod* getSolveBlockTable();
SolveBlockMethod* getSolverConcludeBlockTable();
SolveWriteBackBlockMethod* getSolveWritebackBlockTable();
}
}
#endif
| 4,478 | C | 36.016529 | 137 | 0.7682 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContact.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_SOLVER_CONTACT_H
#define DY_SOLVER_CONTACT_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxvConfig.h"
#include "foundation/PxVecMath.h"
namespace physx
{
using namespace aos;
namespace Sc
{
class ShapeInteraction;
}
/**
\brief A header to represent a friction patch for the solver.
*/
namespace Dy
{
struct SolverContactHeader
{
enum DySolverContactFlags
{
eHAS_FORCE_THRESHOLDS = 0x1
};
PxU8 type; //Note: mType should be first as the solver expects a type in the first byte.
PxU8 flags;
PxU8 numNormalConstr;
PxU8 numFrictionConstr; //4
PxReal angDom0; //8
PxReal angDom1; //12
PxReal invMass0; //16
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W; //32
//KS - minAppliedImpulseForFrictionW is non-zero only for articulations. This is a workaround for a case in articulations where
//the impulse is propagated such that many links do not apply friction because their normal forces were corrected by the solver in a previous
//link. This results in some links sliding unnaturally. This occurs with prismatic or revolute joints where the impulse propagation one one link
//resolves the normal constraint on all links
Vec4V normal_minAppliedImpulseForFrictionW; //48
PxReal invMass1; //52
PxU32 broken; //56
PxU8* frictionBrokenWritebackByte; //60 64
Sc::ShapeInteraction* shapeInteraction; //64 72
#if PX_P64_FAMILY
PxU32 pad[2]; //64 80
#endif // PX_X64
PX_FORCE_INLINE void setStaticFriction(const FloatV f) { staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE void setDynamicFriction(const FloatV f) { staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE void setDominance0(const FloatV f) { staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE void setDominance1(const FloatV f) { staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE FloatV getStaticFriction() const { return V4GetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE FloatV getDynamicFriction() const { return V4GetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE FloatV getDominance0() const { return V4GetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE FloatV getDominance1() const { return V4GetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE void setStaticFriction(PxF32 f) { V4WriteX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE void setDynamicFriction(PxF32 f) { V4WriteY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE void setDominance0(PxF32 f) { V4WriteZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE void setDominance1(PxF32 f) { V4WriteW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, f); }
PX_FORCE_INLINE PxF32 getStaticFrictionPxF32() const { return V4ReadX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE PxF32 getDynamicFrictionPxF32() const { return V4ReadY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE PxF32 getDominance0PxF32() const { return V4ReadZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
PX_FORCE_INLINE PxF32 getDominance1PxF32() const { return V4ReadW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); }
};
#if !PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactHeader) == 64);
#else
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactHeader) == 80);
#endif
/**
\brief A single rigid body contact point for the solver.
*/
struct SolverContactPoint
{
Vec4V raXn_velMultiplierW;
Vec4V rbXn_maxImpulseW;
PxF32 biasedErr;
PxF32 unbiasedErr;
PxF32 impulseMultiplier;
PxU32 pad;
PX_FORCE_INLINE FloatV getVelMultiplier() const { return V4GetW(raXn_velMultiplierW); }
PX_FORCE_INLINE FloatV getImpulseMultiplier() const { return FLoad(impulseMultiplier); }
PX_FORCE_INLINE FloatV getBiasedErr() const { return FLoad(biasedErr); }
PX_FORCE_INLINE FloatV getMaxImpulse() const { return V4GetW(rbXn_maxImpulseW); }
PX_FORCE_INLINE Vec3V getRaXn() const { return Vec3V_From_Vec4V(raXn_velMultiplierW); }
PX_FORCE_INLINE Vec3V getRbXn() const { return Vec3V_From_Vec4V(rbXn_maxImpulseW); }
/*PX_FORCE_INLINE void setRaXn(const PxVec3& v) {V4WriteXYZ(raXn_velMultiplierW, v);}
PX_FORCE_INLINE void setRbXn(const PxVec3& v) {V4WriteXYZ(rbXn_maxImpulseW, v);}
PX_FORCE_INLINE void setVelMultiplier(PxF32 f) {V4WriteW(raXn_velMultiplierW, f);}
PX_FORCE_INLINE void setBiasedErr(PxF32 f) {biasedErr = f;}
PX_FORCE_INLINE void setUnbiasedErr(PxF32 f) {unbiasedErr = f;}
PX_FORCE_INLINE PxF32 getVelMultiplierPxF32() const {return V4ReadW(raXn_velMultiplierW);}
PX_FORCE_INLINE const PxVec3& getRaXnPxVec3() const {return V3ReadXYZ(raXn);}
PX_FORCE_INLINE const PxVec3& getRbXnPxVec3() const {return V3ReadXYZ(rbXn);}
PX_FORCE_INLINE PxF32 getBiasedErrPxF32() const {return biasedErr;}*/
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactPoint) == 48);
/**
\brief A single extended articulation contact point for the solver.
*/
struct SolverContactPointExt : public SolverContactPoint
{
Vec3V linDeltaVA;
Vec3V angDeltaVA;
Vec3V linDeltaVB;
Vec3V angDeltaVB;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactPointExt) == 112);
/**
\brief A single friction constraint for the solver.
*/
struct SolverContactFriction
{
Vec4V normalXYZ_appliedForceW; //16
Vec4V raXnXYZ_velMultiplierW; //32
Vec4V rbXnXYZ_biasW; //48
PxReal targetVel; //52
PxU32 mPad[3]; //64
PX_FORCE_INLINE void setAppliedForce(const FloatV f) {normalXYZ_appliedForceW=V4SetW(normalXYZ_appliedForceW,f);}
PX_FORCE_INLINE void setVelMultiplier(const FloatV f) {raXnXYZ_velMultiplierW=V4SetW(raXnXYZ_velMultiplierW,f);}
PX_FORCE_INLINE void setBias(const FloatV f) {rbXnXYZ_biasW=V4SetW(rbXnXYZ_biasW,f);}
PX_FORCE_INLINE FloatV getAppliedForce() const {return V4GetW(normalXYZ_appliedForceW);}
PX_FORCE_INLINE FloatV getVelMultiplier() const {return V4GetW(raXnXYZ_velMultiplierW);}
PX_FORCE_INLINE FloatV getBias() const {return V4GetW(rbXnXYZ_biasW);}
PX_FORCE_INLINE Vec3V getNormal() const {return Vec3V_From_Vec4V(normalXYZ_appliedForceW);}
PX_FORCE_INLINE Vec3V getRaXn() const {return Vec3V_From_Vec4V(raXnXYZ_velMultiplierW);}
PX_FORCE_INLINE Vec3V getRbXn() const {return Vec3V_From_Vec4V(rbXnXYZ_biasW);}
PX_FORCE_INLINE void setNormal(const PxVec3& v) {V4WriteXYZ(normalXYZ_appliedForceW, v);}
PX_FORCE_INLINE void setRaXn(const PxVec3& v) {V4WriteXYZ(raXnXYZ_velMultiplierW, v);}
PX_FORCE_INLINE void setRbXn(const PxVec3& v) {V4WriteXYZ(rbXnXYZ_biasW, v);}
PX_FORCE_INLINE const PxVec3& getNormalPxVec3() const {return V4ReadXYZ(normalXYZ_appliedForceW);}
PX_FORCE_INLINE const PxVec3& getRaXnPxVec3() const {return V4ReadXYZ(raXnXYZ_velMultiplierW);}
PX_FORCE_INLINE const PxVec3& getRbXnPxVec3() const {return V4ReadXYZ(rbXnXYZ_biasW);}
PX_FORCE_INLINE void setAppliedForce(PxF32 f) {V4WriteW(normalXYZ_appliedForceW, f);}
PX_FORCE_INLINE void setVelMultiplier(PxF32 f) {V4WriteW(raXnXYZ_velMultiplierW, f);}
PX_FORCE_INLINE void setBias(PxF32 f) {V4WriteW(rbXnXYZ_biasW, f);}
PX_FORCE_INLINE PxF32 getAppliedForcePxF32() const {return V4ReadW(normalXYZ_appliedForceW);}
PX_FORCE_INLINE PxF32 getVelMultiplierPxF32() const {return V4ReadW(raXnXYZ_velMultiplierW);}
PX_FORCE_INLINE PxF32 getBiasPxF32() const {return V4ReadW(rbXnXYZ_biasW);}
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactFriction) == 64);
/**
\brief A single extended articulation friction constraint for the solver.
*/
struct SolverContactFrictionExt : public SolverContactFriction
{
Vec3V linDeltaVA;
Vec3V angDeltaVA;
Vec3V linDeltaVB;
Vec3V angDeltaVB;
};
PX_COMPILE_TIME_ASSERT(sizeof(SolverContactFrictionExt) == 128);
}
}
#endif
| 10,079 | C | 44.405405 | 188 | 0.767437 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyFeatherstoneArticulation.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_FEATHERSTONE_ARTICULATION_H
#define DY_FEATHERSTONE_ARTICULATION_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxVecMath.h"
#include "CmUtils.h"
#include "DyVArticulation.h"
#include "DyFeatherstoneArticulationUtils.h"
#include "DyFeatherstoneArticulationJointData.h"
#include "solver/PxSolverDefs.h"
#include "DyArticulationTendon.h"
#include "CmSpatialVector.h"
#ifndef FEATHERSTONE_DEBUG
#define FEATHERSTONE_DEBUG 0
#endif
#define DY_STATIC_CONTACTS_IN_INTERNAL_SOLVER true
namespace physx
{
class PxContactJoint;
class PxcConstraintBlockStream;
class PxcScratchAllocator;
class PxsConstraintBlockManager;
struct SolverConstraint1DExtStep;
struct PxSolverConstraintPrepDesc;
struct PxSolverBody;
struct PxSolverBodyData;
class PxConstraintAllocator;
class PxsContactManagerOutputIterator;
struct PxSolverConstraintDesc;
namespace Dy
{
//#if PX_VC
//#pragma warning(push)
//#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
//#endif
class ArticulationLinkData;
struct SpatialSubspaceMatrix;
struct SolverConstraint1DExt;
struct SolverConstraint1DStep;
class FeatherstoneArticulation;
struct SpatialMatrix;
struct SpatialTransform;
struct Constraint;
class ThreadContext;
struct ArticulationInternalTendonConstraint
{
Cm::UnAlignedSpatialVector row0; //24 24
Cm::UnAlignedSpatialVector row1; //24 48
Cm::UnAlignedSpatialVector deltaVB; //24 72
PxU32 linkID0; //4 74
PxU32 linkID1; //4 78
PxReal accumulatedLength; //4 82 //accumulate distance for spatial tendon, accumualate joint pose for fixed tendon
PxReal biasCoefficient; //4 94
PxReal velMultiplier; //4 98
PxReal impulseMultiplier; //4 102
PxReal appliedForce; //4 106
PxReal recipResponse; //4 110
PxReal deltaVA; //4 114
PxReal limitBiasCoefficient;
PxReal limitImpulseMultiplier;
PxReal limitAppliedForce;
PxReal restDistance;
PxReal lowLimit;
PxReal highLimit;
PxReal velImpulseMultiplier;
PxReal limitVelImpulseMultiplier;
};
struct ArticulationInternalConstraintBase
{
//Common/shared directional info between, frictions and drives
Cm::UnAlignedSpatialVector row0; //24 24
Cm::UnAlignedSpatialVector row1; //24 48
Cm::UnAlignedSpatialVector deltaVA; //24 72
Cm::UnAlignedSpatialVector deltaVB; //24 96
//Response information
PxReal recipResponse; //4 100
PxReal response; //4 104
};
struct ArticulationInternalLimit
{
// Initial error for high and low limits. Negative means limit is violated.
PxReal errorLow;
PxReal errorHigh;
// Impulses are updated during solver iterations.
PxReal lowImpulse;
PxReal highImpulse;
};
struct ArticulationImplicitDriveDesc
{
PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc(PxZERO)
: driveTargetVelPlusInitialBias(0.0f),
driveBiasCoefficient(0.0f),
driveVelMultiplier(0.0f),
driveImpulseMultiplier(0.0f)
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc
(const PxReal targetVelPlusInitialBias, const PxReal biasCoefficient, const PxReal velMultiplier, const PxReal impulseMultiplier)
: driveTargetVelPlusInitialBias(targetVelPlusInitialBias),
driveBiasCoefficient(biasCoefficient),
driveVelMultiplier(velMultiplier),
driveImpulseMultiplier(impulseMultiplier)
{
}
PxReal driveTargetVelPlusInitialBias;
PxReal driveBiasCoefficient;
PxReal driveVelMultiplier;
PxReal driveImpulseMultiplier;
};
struct ArticulationInternalConstraint : public ArticulationInternalConstraintBase
{
ArticulationImplicitDriveDesc implicitDriveDesc;
PxReal driveMaxForce;
PxReal driveForce;
PxReal frictionForceCoefficient;
PxReal frictionMaxForce;
PxReal frictionForce;
bool isLinearConstraint;
void setImplicitDriveDesc(const ArticulationImplicitDriveDesc& driveDesc)
{
implicitDriveDesc = driveDesc;
}
const ArticulationImplicitDriveDesc& getImplicitDriveDesc() const
{
return implicitDriveDesc;
}
};
PX_COMPILE_TIME_ASSERT(0 == (sizeof(ArticulationInternalConstraint) & 0x0f));
//linkID can be PxU32. However, each thread is going to read 16 bytes so we just keep ArticulationSensor 16 byte align.
//if not, newArticulationsLaunch kernel will fail to read the sensor data correctly
struct ArticulationSensor
{
PxTransform mRelativePose; //28 28
PxU16 mLinkID; //02 30
PxU16 mFlags; //02 32
};
struct PX_ALIGN_PREFIX(16) JointSpaceSpatialZ
{
PxReal mVals [6][4];
PxReal dot(Cm::SpatialVectorF& v, PxU32 id)
{
return v.top.x * mVals[0][id] + v.top.y * mVals[1][id] + v.top.z * mVals[2][id]
+ v.bottom.x * mVals[3][id] + v.bottom.y * mVals[4][id] + v.bottom.z * mVals[5][id];
}
}
PX_ALIGN_SUFFIX(16);
class ArticulationData
{
public:
ArticulationData() :
mPathToRootElements(NULL), mNumPathToRootElements(0), mLinksData(NULL), mJointData(NULL),
mSpatialTendons(NULL), mNumSpatialTendons(0), mNumTotalAttachments(0),
mFixedTendons(NULL), mNumFixedTendons(0), mSensors(NULL), mSensorForces(NULL),
mNbSensors(0), mDt(0.f), mDofs(0xffffffff),
mDataDirty(true)
{
mRootPreMotionVelocity = Cm::SpatialVectorF::Zero();
}
~ArticulationData();
PX_FORCE_INLINE void init();
void resizeLinkData(const PxU32 linkCount);
void resizeJointData(const PxU32 dofs);
PX_FORCE_INLINE PxReal* getJointAccelerations() { return mJointAcceleration.begin(); }
PX_FORCE_INLINE const PxReal* getJointAccelerations() const { return mJointAcceleration.begin(); }
PX_FORCE_INLINE PxReal* getJointVelocities() { return mJointVelocity.begin(); }
PX_FORCE_INLINE const PxReal* getJointVelocities() const { return mJointVelocity.begin(); }
PX_FORCE_INLINE PxReal* getJointNewVelocities() { return mJointNewVelocity.begin(); }
PX_FORCE_INLINE const PxReal* getJointNewVelocities() const { return mJointNewVelocity.begin(); }
PX_FORCE_INLINE PxReal* getJointPositions() { return mJointPosition.begin(); }
PX_FORCE_INLINE const PxReal* getJointPositions() const { return mJointPosition.begin(); }
PX_FORCE_INLINE PxReal* getJointForces() { return mJointForce.begin(); }
PX_FORCE_INLINE const PxReal* getJointForces() const { return mJointForce.begin(); }
PX_FORCE_INLINE PxReal* getJointConstraintForces() { return mJointConstraintForces.begin(); }
PX_FORCE_INLINE const PxReal* getJointConstraintForces() const { return mJointConstraintForces.begin(); }
PX_FORCE_INLINE PxReal* getJointTargetPositions() { return mJointTargetPositions.begin(); }
PX_FORCE_INLINE const PxReal* getJointTargetPositions() const { return mJointTargetPositions.begin(); }
PX_FORCE_INLINE PxReal* getJointTargetVelocities() { return mJointTargetVelocities.begin(); }
PX_FORCE_INLINE const PxReal* getJointTargetVelocities() const { return mJointTargetVelocities.begin(); }
PX_FORCE_INLINE ArticulationInternalConstraint& getInternalConstraint(const PxU32 dofId) { return mInternalConstraints[dofId]; }
PX_FORCE_INLINE const ArticulationInternalConstraint& getInternalConstraint(const PxU32 dofId) const { return mInternalConstraints[dofId]; }
PX_FORCE_INLINE Cm::SpatialVectorF* getMotionVelocities() { return mMotionVelocities.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getMotionAccelerations() { return mMotionAccelerations.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF* getMotionAccelerations() const { return mMotionAccelerations.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getLinkIncomingJointForces() { return mLinkIncomingJointForces.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getCorioliseVectors() { return mCorioliseVectors.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getSpatialZAVectors() { return mZAForces.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getSpatialZAInternalVectors() { return mZAInternalForces.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getTransmittedForces() { return mJointTransmittedForce.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getPosIterMotionVelocities() { return mPosIterMotionVelocities.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF* getPosIterMotionVelocities() const { return mPosIterMotionVelocities.begin(); }
PX_FORCE_INLINE PxReal* getPosIterJointVelocities() { return mPosIterJointVelocities.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF& getPosIterMotionVelocity(const PxU32 index) { return mPosIterMotionVelocities[index]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getMotionVelocity(const PxU32 index) const { return mMotionVelocities[index]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getMotionAcceleration(const PxU32 index) const { return mMotionAccelerations[index]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getCorioliseVector(const PxU32 index) const { return mCorioliseVectors[index]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getSpatialZAVector(const PxU32 index) const { return mZAForces[index]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getTransmittedForce(const PxU32 index) const { return mJointTransmittedForce[index]; }
PX_FORCE_INLINE Cm::SpatialVectorF& getMotionVelocity(const PxU32 index) { return mMotionVelocities[index]; }
PX_FORCE_INLINE Cm::SpatialVectorF& getMotionAcceleration(const PxU32 index) { return mMotionAccelerations[index]; }
PX_FORCE_INLINE Cm::SpatialVectorF& getCorioliseVector(const PxU32 index) { return mCorioliseVectors[index]; }
PX_FORCE_INLINE Cm::SpatialVectorF& getSpatialZAVector(const PxU32 index) { return mZAForces[index]; }
PX_FORCE_INLINE Cm::SpatialVectorF& getTransmittedForce(const PxU32 index) { return mJointTransmittedForce[index]; }
//PX_FORCE_INLINE Dy::SpatialMatrix* getTempSpatialMatrix() { mTempSpatialMatrix.begin(); }
PX_FORCE_INLINE PxTransform& getPreTransform(const PxU32 index) { return mPreTransform[index]; }
PX_FORCE_INLINE const PxTransform& getPreTransform(const PxU32 index) const { return mPreTransform[index]; }
// PX_FORCE_INLINE void setPreTransform(const PxU32 index, const PxTransform& t){ mPreTransform[index] = t; }
PX_FORCE_INLINE PxTransform* getPreTransform() { return mPreTransform.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF& getDeltaMotionVector(const PxU32 index) const { return mDeltaMotionVector[index]; }
PX_FORCE_INLINE void setDeltaMotionVector(const PxU32 index, const Cm::SpatialVectorF& vec) { mDeltaMotionVector[index] = vec; }
PX_FORCE_INLINE Cm::SpatialVectorF* getDeltaMotionVector() { return mDeltaMotionVector.begin(); }
PX_FORCE_INLINE ArticulationLink* getLinks() const { return mLinks; }
PX_FORCE_INLINE PxU32 getLinkCount() const { return mLinkCount; }
PX_FORCE_INLINE ArticulationLink& getLink(PxU32 index) const { return mLinks[index]; }
PX_FORCE_INLINE ArticulationSpatialTendon** getSpatialTendons() const { return mSpatialTendons; }
PX_FORCE_INLINE PxU32 getSpatialTendonCount() const { return mNumSpatialTendons; }
PX_FORCE_INLINE ArticulationSpatialTendon* getSpatialTendon(PxU32 index) const { return mSpatialTendons[index]; }
PX_FORCE_INLINE ArticulationFixedTendon** getFixedTendons() const { return mFixedTendons; }
PX_FORCE_INLINE PxU32 getFixedTendonCount() const { return mNumFixedTendons; }
PX_FORCE_INLINE ArticulationFixedTendon* getFixedTendon(PxU32 index) const { return mFixedTendons[index]; }
PX_FORCE_INLINE ArticulationSensor** getSensors() const { return mSensors; }
PX_FORCE_INLINE PxU32 getSensorCount() const { return mNbSensors; }
PX_FORCE_INLINE ArticulationLinkData* getLinkData() const { return mLinksData; }
ArticulationLinkData& getLinkData(PxU32 index) const;
PX_FORCE_INLINE ArticulationJointCoreData* getJointData() const { return mJointData; }
PX_FORCE_INLINE ArticulationJointCoreData& getJointData(PxU32 index) const { return mJointData[index]; }
// PT: PX-1399
PX_FORCE_INLINE PxArticulationFlags getArticulationFlags() const { return *mFlags; }
PX_FORCE_INLINE Cm::SpatialVector* getExternalAccelerations() { return mExternalAcceleration; }
PX_FORCE_INLINE Cm::SpatialVector& getExternalAcceleration(const PxU32 linkID) { return mExternalAcceleration[linkID]; }
PX_FORCE_INLINE const Cm::SpatialVector& getExternalAcceleration(const PxU32 linkID) const { return mExternalAcceleration[linkID]; }
PX_FORCE_INLINE PxReal getDt() const { return mDt; }
PX_FORCE_INLINE void setDt(const PxReal dt) { mDt = dt; }
PX_FORCE_INLINE bool getDataDirty() const { return mDataDirty; }
PX_FORCE_INLINE void setDataDirty(const bool dirty) { mDataDirty = dirty; }
PX_FORCE_INLINE PxU32 getDofs() const { return mDofs; }
PX_FORCE_INLINE void setDofs(const PxU32 dof) { mDofs = dof; }
PX_FORCE_INLINE FeatherstoneArticulation* getArticulation() { return mArticulation; }
PX_FORCE_INLINE void setArticulation(FeatherstoneArticulation* articulation) { mArticulation = articulation; }
PX_FORCE_INLINE const SpatialMatrix& getBaseInvSpatialArticulatedInertiaW() const { return mBaseInvSpatialArticulatedInertiaW; }
PX_FORCE_INLINE SpatialMatrix& getBaseInvSpatialArticulatedInertiaW() { return mBaseInvSpatialArticulatedInertiaW; }
PX_FORCE_INLINE PxTransform* getAccumulatedPoses() { return mAccumulatedPoses.begin(); }
PX_FORCE_INLINE const PxTransform* getAccumulatedPoses() const { return mAccumulatedPoses.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getJointSpaceJacobians() { return mJointSpaceJacobians.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF* getJointSpaceJacobians() const { return mJointSpaceJacobians.begin(); }
PX_FORCE_INLINE JointSpaceSpatialZ* getJointSpaceDeltaV() { return mJointSpaceDeltaVMatrix.begin(); }
PX_FORCE_INLINE const JointSpaceSpatialZ* getJointSpaceDeltaV() const { return mJointSpaceDeltaVMatrix.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getJointSpaceResponse() { return mJointSpaceResponseMatrix.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF* getJointSpaceResponse() const { return mJointSpaceResponseMatrix.begin(); }
PX_FORCE_INLINE SpatialImpulseResponseMatrix* getRootResponseMatrix() { return mRootResponseMatrix.begin(); }
PX_FORCE_INLINE const SpatialImpulseResponseMatrix* getRootResponseMatrix() const { return mRootResponseMatrix.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF& getRootDeferredZ() const { return mRootDeferredZ; }
PX_FORCE_INLINE Cm::SpatialVectorF& getRootDeferredZ() { return mRootDeferredZ; }
PX_FORCE_INLINE const SpatialMatrix* getWorldSpatialArticulatedInertia() const { return mWorldSpatialArticulatedInertia.begin(); }
PX_FORCE_INLINE SpatialMatrix* getWorldSpatialArticulatedInertia() { return mWorldSpatialArticulatedInertia.begin(); }
PX_FORCE_INLINE const Cm::UnAlignedSpatialVector* getWorldMotionMatrix() const { return mWorldMotionMatrix.begin(); }
PX_FORCE_INLINE Cm::UnAlignedSpatialVector* getWorldMotionMatrix() { return mWorldMotionMatrix.begin(); }
PX_FORCE_INLINE const Cm::UnAlignedSpatialVector* getMotionMatrix() const { return mMotionMatrix.begin(); }
PX_FORCE_INLINE Cm::UnAlignedSpatialVector* getMotionMatrix() { return mMotionMatrix.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF* getIsW() const { return mIsW.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getIsW() { return mIsW.begin(); }
PX_FORCE_INLINE const PxVec3* getRw() const { return mRw.begin(); }
PX_FORCE_INLINE PxVec3* getRw() { return mRw.begin(); }
PX_FORCE_INLINE const PxReal* getMinusStZExt() const { return qstZIc.begin(); }
PX_FORCE_INLINE PxReal* getMinusStZExt() { return qstZIc.begin(); }
PX_FORCE_INLINE const PxReal* getQstZIc() const { return qstZIc.begin(); }
PX_FORCE_INLINE PxReal* getQstZIc() { return qstZIc.begin(); }
PX_FORCE_INLINE const PxReal* getQStZIntIc() const { return qstZIntIc.begin();}
PX_FORCE_INLINE PxReal* getQStZIntIc() { return qstZIntIc.begin();}
PX_FORCE_INLINE const InvStIs* getInvStIS() const { return mInvStIs.begin(); }
PX_FORCE_INLINE InvStIs* getInvStIS() { return mInvStIs.begin(); }
PX_FORCE_INLINE const Cm::SpatialVectorF* getISInvStIS() const { return mISInvStIS.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF* getISInvStIS() { return mISInvStIS.begin(); }
PX_FORCE_INLINE SpatialImpulseResponseMatrix* getImpulseResponseMatrixWorld() { return mResponseMatrixW.begin(); }
PX_FORCE_INLINE const SpatialImpulseResponseMatrix* getImpulseResponseMatrixWorld() const { return mResponseMatrixW.begin(); }
PX_FORCE_INLINE const SpatialMatrix& getWorldSpatialArticulatedInertia(const PxU32 linkID) const { return mWorldSpatialArticulatedInertia[linkID]; }
PX_FORCE_INLINE const InvStIs& getInvStIs(const PxU32 linkID) const { return mInvStIs[linkID]; }
PX_FORCE_INLINE const Cm::UnAlignedSpatialVector& getMotionMatrix(const PxU32 dofId) const { return mMotionMatrix[dofId]; }
PX_FORCE_INLINE const Cm::UnAlignedSpatialVector& getWorldMotionMatrix(const PxU32 dofId) const { return mWorldMotionMatrix[dofId]; }
PX_FORCE_INLINE Cm::UnAlignedSpatialVector& getJointAxis(const PxU32 dofId) { return mJointAxis[dofId]; }
PX_FORCE_INLINE const Cm::UnAlignedSpatialVector& getJointAxis(const PxU32 dofId) const { return mJointAxis[dofId]; }
PX_FORCE_INLINE const PxVec3& getRw(const PxU32 linkID) const { return mRw[linkID]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getIsW(const PxU32 dofId) const { return mIsW[dofId]; }
PX_FORCE_INLINE const Cm::SpatialVectorF& getWorldIsInvD(const PxU32 dofId) const { return mISInvStIS[dofId]; }
PX_FORCE_INLINE PxReal* getDeferredQstZ() { return mDeferredQstZ.begin(); }
PX_FORCE_INLINE Cm::SpatialVectorF& getSolverSpatialForce(const PxU32 linkID) { return mSolverLinkSpatialForces[linkID]; }
PX_FORCE_INLINE PxSpatialForce* getSensorForces() { return mSensorForces; }
PX_FORCE_INLINE void setRootPreMotionVelocity(const Cm::UnAlignedSpatialVector& vel) { mRootPreMotionVelocity.top = vel.top; mRootPreMotionVelocity.bottom = vel.bottom; }
PX_FORCE_INLINE PxU32* getPathToRootElements() const { return mPathToRootElements; }
PX_FORCE_INLINE PxU32 getPathToRootElementCount() const { return mNumPathToRootElements; }
PX_FORCE_INLINE const Cm::SpatialVectorF* getSolverSpatialForces() const {return mSolverLinkSpatialForces.begin();}
PX_FORCE_INLINE Cm::SpatialVectorF* getSolverSpatialForces() {return mSolverLinkSpatialForces.begin();}
PX_FORCE_INLINE void incrementSolverSpatialDeltaVel(const PxU32 linkID, const Cm::SpatialVectorF& deltaV) {mSolverLinkSpatialDeltaVels[linkID] += deltaV;}
private:
Cm::SpatialVectorF mRootPreMotionVelocity;
Cm::SpatialVectorF mRootDeferredZ;
PxArray<PxReal> mJointAcceleration; // joint acceleration
PxArray<PxReal> mJointInternalAcceleration; //joint internal force acceleration
PxArray<PxReal> mJointVelocity; // joint velocity
PxArray<PxReal> mJointNewVelocity; // joint velocity due to contacts
PxArray<PxReal> mJointPosition; // joint position
PxArray<PxReal> mJointForce; // joint force
PxArray<PxReal> mJointTargetPositions; // joint target positions
PxArray<PxReal> mJointTargetVelocities; // joint target velocities
PxArray<PxReal> mPosIterJointVelocities; //joint delta velocity after postion iternation before velocity iteration
PxArray<Cm::SpatialVectorF> mPosIterMotionVelocities; //link motion velocites after position iteration before velocity iteration
PxArray<Cm::SpatialVectorF> mMotionVelocities; //link motion velocites
PxArray<Cm::SpatialVectorF> mSolverLinkSpatialDeltaVels; //link DeltaVels arising from solver
PxArray<Cm::SpatialVectorF> mSolverLinkSpatialImpulses; //link impulses arising from solver.
PxArray<Cm::SpatialVectorF> mSolverLinkSpatialForces;
PxArray<Cm::SpatialVectorF> mMotionAccelerations; //link motion accelerations
PxArray<Cm::SpatialVectorF> mLinkIncomingJointForces;
PxArray<Cm::SpatialVectorF> mMotionAccelerationsInternal; //link motion accelerations
PxArray<Cm::SpatialVectorF> mCorioliseVectors; //link coriolise vector
PxArray<Cm::SpatialVectorF> mZAInternalForces; //link internal spatial forces
PxArray<Cm::SpatialVectorF> mZAForces; //link spatial zero acceleration force/ spatial articulated force
PxArray<Cm::SpatialVectorF> mJointTransmittedForce;
PxArray<ArticulationInternalConstraint> mInternalConstraints;
PxArray<ArticulationInternalLimit> mInternalLimits;
PxArray<ArticulationInternalTendonConstraint> mInternalSpatialTendonConstraints;
PxArray<ArticulationInternalTendonConstraint> mInternalFixedTendonConstraints;
PxArray<PxReal> mDeferredQstZ;
PxArray<PxReal> mJointConstraintForces;
PxArray<Cm::SpatialVectorF> mDeltaMotionVector; //this is for TGS solver
PxArray<PxTransform> mPreTransform; //this is the previous transform list for links
PxArray<SpatialImpulseResponseMatrix> mResponseMatrixW;
PxArray<Cm::SpatialVectorF> mJointSpaceJacobians;
PxArray<JointSpaceSpatialZ> mJointSpaceDeltaVMatrix;
PxArray<Cm::SpatialVectorF> mJointSpaceResponseMatrix;
PxArray<Cm::SpatialVectorF> mPropagationAccelerator;
PxArray<SpatialImpulseResponseMatrix> mRootResponseMatrix;
PxArray<SpatialMatrix> mWorldSpatialArticulatedInertia;
PxArray<PxMat33> mWorldIsolatedSpatialArticulatedInertia;
PxArray<PxReal> mMasses;
PxArray<InvStIs> mInvStIs;
PxArray<Cm::SpatialVectorF> mIsW;
PxArray<PxReal> qstZIc;//jointForce - stZIc
PxArray<PxReal> qstZIntIc;
PxArray<Cm::UnAlignedSpatialVector> mJointAxis;
PxArray<Cm::UnAlignedSpatialVector> mMotionMatrix;
PxArray<Cm::UnAlignedSpatialVector> mWorldMotionMatrix;
PxArray<Cm::SpatialVectorF> mISInvStIS;
PxArray<PxVec3> mRw;
PxArray<PxU32> mNbStatic1DConstraints;
PxArray<PxU32> mNbStaticContactConstraints;
PxArray<PxU32> mStatic1DConstraintStartIndex;
PxArray<PxU32> mStaticContactConstraintStartIndex;
PxArray<PxQuat> mRelativeQuat;
ArticulationLink* mLinks;
PxU32 mLinkCount;
PxU32* mPathToRootElements;
PxU32 mNumPathToRootElements;
ArticulationLinkData* mLinksData;
ArticulationJointCoreData* mJointData;
ArticulationSpatialTendon** mSpatialTendons;
PxU32 mNumSpatialTendons;
PxU32 mNumTotalAttachments;
ArticulationFixedTendon** mFixedTendons;
PxU32 mNumFixedTendons;
ArticulationSensor** mSensors;
PxSpatialForce* mSensorForces;
PxU32 mNbSensors;
PxReal mDt;
PxU32 mDofs;
const PxArticulationFlags* mFlags; // PT: PX-1399
Cm::SpatialVector* mExternalAcceleration;
bool mDataDirty; //this means we need to call commonInit()
bool mJointDirty; //this means joint delta velocity has been changed by contacts so we need to update joint velocity/joint acceleration
FeatherstoneArticulation* mArticulation;
PxArray<PxTransform> mAccumulatedPoses;
PxArray<PxQuat> mDeltaQ;
SpatialMatrix mBaseInvSpatialArticulatedInertiaW;
PxReal mInvSumMass;
PxVec3 mCOM;
friend class FeatherstoneArticulation;
};
void ArticulationData::init()
{
//zero delta motion vector for TGS solver
PxMemZero(getDeltaMotionVector(), sizeof(Cm::SpatialVectorF) * mLinkCount);
PxMemZero(getPosIterMotionVelocities(), sizeof(Cm::SpatialVectorF) * mLinkCount);
mJointDirty = false;
}
struct ScratchData
{
public:
ScratchData()
{
motionVelocities = NULL;
motionAccelerations = NULL;
coriolisVectors = NULL;
spatialZAVectors = NULL;
externalAccels = NULL;
compositeSpatialInertias = NULL;
jointVelocities = NULL;
jointAccelerations = NULL;
jointForces = NULL;
jointPositions = NULL;
jointFrictionForces = NULL;
}
Cm::SpatialVectorF* motionVelocities;
Cm::SpatialVectorF* motionAccelerations;
Cm::SpatialVectorF* coriolisVectors;
Cm::SpatialVectorF* spatialZAVectors;
Cm::SpatialVector* externalAccels;
Dy::SpatialMatrix* compositeSpatialInertias;
PxReal* jointVelocities;
PxReal* jointAccelerations;
PxReal* jointForces;
PxReal* jointPositions;
PxReal* jointFrictionForces;
};
struct InternalConstraintSolverData
{
const PxReal dt;
const PxReal invDt;
const PxReal elapsedTime;
const PxReal erp;
Cm::SpatialVectorF* impulses;
Cm::SpatialVectorF* deltaV;
const bool isVelIter;
const bool isTGS;
PxU32 dofId;
PxU32 complexId;
PxU32 limitId;
PxU32 articId;
InternalConstraintSolverData(const PxReal dt_, const PxReal invDt_, const PxReal elapsedTime_,
const PxReal erp_, Cm::SpatialVectorF* impulses_, Cm::SpatialVectorF* deltaV_,
bool velocityIteration_, bool isTGS_) : dt(dt_), invDt(invDt_), elapsedTime(elapsedTime_),
erp(erp_), impulses(impulses_), deltaV(deltaV_), isVelIter(velocityIteration_),
isTGS(isTGS_), dofId(0), complexId(0), limitId(0)
{
}
PX_NOCOPY(InternalConstraintSolverData)
};
struct FixedTendonSolveData
{
ArticulationLink* links;
ArticulationTendonJoint* tendonJoints;
PxReal rootVel;
PxReal rootImp;
PxReal erp;
PxReal error;
PxReal limitError;
};
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
//Articulation dirty flag - used to tag which properties of the articulation are dirty. Used only to transfer selected data to the GPU...
struct ArticulationDirtyFlag
{
enum Enum
{
eDIRTY_JOINTS = 1 << 0,
eDIRTY_POSITIONS = 1 << 1,
eDIRTY_VELOCITIES = 1 << 2,
eDIRTY_FORCES = 1 << 3,
eDIRTY_ROOT_TRANSFORM = 1 << 4,
eDIRTY_ROOT_VELOCITIES = 1 << 5,
eDIRTY_LINKS = 1 << 6,
eIN_DIRTY_LIST = 1 << 7,
eDIRTY_WAKECOUNTER = 1 << 8,
eDIRTY_EXT_ACCEL = 1 << 9,
eDIRTY_LINK_FORCE = 1 << 10,
eDIRTY_LINK_TORQUE = 1 << 11,
eDIRTY_JOINT_TARGET_VEL = 1 << 12,
eDIRTY_JOINT_TARGET_POS = 1 << 13,
eDIRTY_SPATIAL_TENDON = 1 << 14,
eDIRTY_SPATIAL_TENDON_ATTACHMENT = 1 << 15,
eDIRTY_FIXED_TENDON = 1 << 16,
eDIRTY_FIXED_TENDON_JOINT = 1 << 17,
eDIRTY_SENSOR = 1 << 18,
eDIRTY_VELOCITY_LIMITS = 1 << 19,
eDIRTY_USER_FLAGS = 1 << 20,
eNEEDS_KINEMATIC_UPDATE = 1 << 21,
eALL = (1<<22)-1
};
};
PX_INLINE PX_CUDA_CALLABLE void computeArticJacobianAxes(PxVec3 row[3], const PxQuat& qa, const PxQuat& qb)
{
// Compute jacobian matrix for (qa* qb) [[* means conjugate in this expr]]
// d/dt (qa* qb) = 1/2 L(qa*) R(qb) (omega_b - omega_a)
// result is L(qa*) R(qb), where L(q) and R(q) are left/right q multiply matrix
const PxReal wa = qa.w, wb = qb.w;
const PxVec3 va(qa.x, qa.y, qa.z), vb(qb.x, qb.y, qb.z);
const PxVec3 c = vb*wa + va*wb;
const PxReal d0 = wa*wb;
const PxReal d1 = va.dot(vb);
const PxReal d = d0 - d1;
row[0] = (va * vb.x + vb * va.x + PxVec3(d, c.z, -c.y)) * 0.5f;
row[1] = (va * vb.y + vb * va.y + PxVec3(-c.z, d, c.x)) * 0.5f;
row[2] = (va * vb.z + vb * va.z + PxVec3(c.y, -c.x, d)) * 0.5f;
if ((d0 + d1) != 0.0f) // check if relative rotation is 180 degrees which can lead to singular matrix
return;
else
{
row[0].x += PX_EPS_F32;
row[1].y += PX_EPS_F32;
row[2].z += PX_EPS_F32;
}
}
PX_CUDA_CALLABLE PX_FORCE_INLINE float compAng(PxReal swingYZ, PxReal swingW)
{
return 4.0f * PxAtan2(swingYZ, 1.0f + swingW); // tan (t/2) = sin(t)/(1+cos t), so this is the quarter angle
}
PX_ALIGN_PREFIX(64)
class FeatherstoneArticulation
{
PX_NOCOPY(FeatherstoneArticulation)
public:
// public interface
explicit FeatherstoneArticulation(void*);
~FeatherstoneArticulation();
// get data sizes for allocation at higher levels
void getDataSizes(PxU32 linkCount, PxU32& solverDataSize, PxU32& totalSize, PxU32& scratchSize);
bool resize(const PxU32 linkCount);
void assignTendons(const PxU32 /*nbTendons*/, Dy::ArticulationSpatialTendon** /*tendons*/);
void assignTendons(const PxU32 /*nbTendons*/, Dy::ArticulationFixedTendon** /*tendons*/);
void assignSensors(const PxU32 nbSensors, Dy::ArticulationSensor** sensors, PxSpatialForce* sensorForces);
PxU32 getDofs() const;
PxU32 getDof(const PxU32 linkID);
bool applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, bool& shouldWake);
void copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled);
static PxU32 getCacheDataSize(PxU32 totalDofs, PxU32 linkCount, PxU32 sensorCount);
static PxArticulationCache* createCache(PxU32 totalDofs, PxU32 linkCount, PxU32 sensorCount);
void packJointData(const PxReal* maximum, PxReal* reduced);
void unpackJointData(const PxReal* reduced, PxReal* maximum);
void initializeCommonData();
//gravity as input, joint force as output
void getGeneralizedGravityForce(const PxVec3& gravity, PxArticulationCache& cache);
//joint velocity as input, generalised force(coriolis and centrigugal force) as output
void getCoriolisAndCentrifugalForce(PxArticulationCache& cache);
//external force as input, joint force as output
void getGeneralizedExternalForce(PxArticulationCache& /*cache*/);
//joint force as input, joint acceleration as output
void getJointAcceleration(const PxVec3& gravity, PxArticulationCache& cache);
//joint acceleration as input, joint force as out
void getJointForce(PxArticulationCache& cache);
void getDenseJacobian(PxArticulationCache& cache, PxU32 & nRows, PxU32 & nCols);
//These two functions are for closed loop system
void getKMatrix(ArticulationJointCore* loopJoint, const PxU32 parentIndex, const PxU32 childIndex, PxArticulationCache& cache);
void getCoefficientMatrix(const PxReal dt, const PxU32 linkID, const PxContactJoint* contactJoints, const PxU32 nbContacts, PxArticulationCache& cache);
void getCoefficientMatrixWithLoopJoints(ArticulationLoopConstraint* lConstraints, const PxU32 nbJoints, PxArticulationCache& cache);
bool getLambda(ArticulationLoopConstraint* lConstraints, const PxU32 nbJoints, PxArticulationCache& cache, PxArticulationCache& rollBackCache,
const PxReal* jointTorque, const PxVec3& gravity, const PxU32 maxIter, const PxReal invLengthScale);
void getGeneralizedMassMatrix(PxArticulationCache& cache);
void getGeneralizedMassMatrixCRB(PxArticulationCache& cache);
bool storeStaticConstraint(const PxSolverConstraintDesc& desc);
bool willStoreStaticConstraint() { return DY_STATIC_CONTACTS_IN_INTERNAL_SOLVER; }
void setRootLinearVelocity(const PxVec3& velocity);
void setRootAngularVelocity(const PxVec3& velocity);
void teleportRootLink();
void getImpulseResponse(
PxU32 linkID,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse,
Cm::SpatialVector& deltaV) const;
void getImpulseResponse(
PxU32 linkID,
Cm::SpatialVectorV* /*Z*/,
const Cm::SpatialVectorV& impulse,
Cm::SpatialVectorV& deltaV) const;
void getImpulseSelfResponse(
PxU32 linkID0,
PxU32 linkID1,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse0,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV0,
Cm::SpatialVector& deltaV1) const;
Cm::SpatialVectorV getLinkVelocity(const PxU32 linkID) const;
Cm::SpatialVector getLinkScalarVelocity(const PxU32 linkID) const;
Cm::SpatialVectorV getLinkMotionVector(const PxU32 linkID) const;
//this is called by island gen to determine whether the articulation should be awake or sleep
Cm::SpatialVector getMotionVelocity(const PxU32 linkID) const;
Cm::SpatialVector getMotionAcceleration(const PxU32 linkID, const bool isGpuSimEnabled) const;
void fillIndexType(const PxU32 linkId, PxU8& indexType);
PxReal getLinkMaxPenBias(const PxU32 linkID) const;
PxReal getCfm(const PxU32 linkID) const;
static PxU32 computeUnconstrainedVelocities(
const ArticulationSolverDesc& desc,
PxReal dt,
PxU32& acCount,
const PxVec3& gravity,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV, const PxReal invLengthScale);
static void computeUnconstrainedVelocitiesTGS(
const ArticulationSolverDesc& desc,
PxReal dt, const PxVec3& gravity,
PxU64 contextID, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV,
const PxReal invLengthScale);
static PxU32 setupSolverConstraintsTGS(const ArticulationSolverDesc& articDesc,
PxReal dt,
PxReal invDt,
PxReal totalDt,
PxU32& acCount,
Cm::SpatialVectorF* Z);
static void saveVelocity(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* deltaV);
static void saveVelocityTGS(FeatherstoneArticulation* articulation, PxReal invDtF32);
static void updateBodies(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt);
static void updateBodiesTGS(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt);
static void updateBodies(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* tempDeltaV, PxReal dt, bool integrateJointPosition);
static void recordDeltaMotion(const ArticulationSolverDesc& desc, const PxReal dt, Cm::SpatialVectorF* deltaV, const PxReal totalInvDt);
static void deltaMotionToMotionVelocity(const ArticulationSolverDesc& desc, PxReal invDt);
void pxcFsApplyImpulse(PxU32 linkID, aos::Vec3V linear,
aos::Vec3V angular, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV);
void pxcFsApplyImpulses(PxU32 linkID, const aos::Vec3V& linear,
const aos::Vec3V& angular, PxU32 linkID2, const aos::Vec3V& linear2,
const aos::Vec3V& angular2, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV);
void pxcFsApplyImpulses(Cm::SpatialVectorF* Z);
Cm::SpatialVectorV pxcFsGetVelocity(PxU32 linkID);
void pxcFsGetVelocities(PxU32 linkID, PxU32 linkID1, Cm::SpatialVectorV& v0, Cm::SpatialVectorV& v1);
Cm::SpatialVectorV pxcFsGetVelocityTGS(PxU32 linkID);
const PxTransform& getCurrentTransform(PxU32 linkID) const;
const PxQuat& getDeltaQ(PxU32 linkID) const;
//Applies a set of N impulses, all in local space and updates the links' motion and joint velocities
void applyImpulses(Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV);
void getDeltaV(Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV);
//This method calculate the velocity change due to collision/constraint impulse, record joint velocity and acceleration
static Cm::SpatialVectorF propagateVelocityW(const PxVec3& c2p, const Dy::SpatialMatrix& spatialInertia,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& Z,
PxReal* jointVelocity, const Cm::SpatialVectorF& hDeltaV, const PxU32 dofCount);
static Cm::SpatialVectorF propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix,
PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration, const PxU32 dofCount, const Cm::SpatialVectorF* IsW, PxReal* qstZIc);
static void propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration,
const PxU32 dofCount, const Cm::SpatialVectorF* IsW);
static Cm::SpatialVectorF propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix,
const Cm::SpatialVectorF& pAcceleration, const PxU32 dofCount, const Cm::SpatialVectorF* IsW, PxReal* qstZIc);
static Cm::SpatialVectorF propagateAccelerationW(const PxVec3& c2p,
const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix,
PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration, Cm::SpatialVectorF& Z, const PxU32 dofCount, const Cm::SpatialVectorF* IsW);
//This method calculate the velocity change due to collision/constraint impulse
static Cm::SpatialVectorF propagateVelocityTestImpulseW(const PxVec3& c2p, const Dy::SpatialMatrix& spatialInertia, const InvStIs& invStIs,
const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& Z, const Cm::SpatialVectorF& hDeltaV,
const PxU32 dofCount);
/**
\brief Propagate a spatial impulse applied to a child link to its parent link.
The Mirtich equivalent is the equation for Y in Figure 5.7, page 141.
Optionally accumulate -s^T*Y for each dof of the child link's incoming joint.
Y = translateChildToParent{[ 1 - [(I * s) / (s^T * I * s)] * s^T] * Y}
\param[in] childToParent is the vector from child link to parent link
\param[in] linkYW is the impulse to apply to the child link.
\param[in] jointDofISInvStISW is (I * s) / (s^T * I * s) with one entry for each dof of the child link's incoming joint.
\param[in] jointDofMotionMatrixW is the motion matrix s with one entry for each dof of the child link's incoming joint.
\param[in] dofCount is the number of dofs of the child link's incoming joint.
\param[in,out] jointDofQStY accumulates -s^T*Y for each dof of the child link's incoming joint.
\note jointDofQStY may be NULL if there is no need to accumulate and record -s^T*Y for each dof of the child link's incoming joint.
\return The propagated spatial impulse.
*/
static Cm::SpatialVectorF propagateImpulseW(
const PxVec3& childToParent,
const Cm::SpatialVectorF& linkYW,
const Cm::SpatialVectorF* jointDofISInvStISW, const Cm::UnAlignedSpatialVector* jointDofMotionMatrixW, const PxU8 dofCount,
PxReal* jointDofQStY = NULL);
bool applyCacheToDest(ArticulationData& data, PxArticulationCache& cache,
PxReal* jVelocities, PxReal* jPosition, PxReal* jointForce,
PxReal* jTargetPositions, PxReal* jTargetVelocities,
const PxArticulationCacheFlags flag, bool& shouldWake);
PX_FORCE_INLINE ArticulationData& getArticulationData() { return mArticulationData; }
PX_FORCE_INLINE const ArticulationData& getArticulationData() const { return mArticulationData; }
PX_FORCE_INLINE void setGpuDirtyFlag(ArticulationDirtyFlag::Enum flag)
{
mGPUDirtyFlags |= flag;
}
//void setGpuRemapId(const PxU32 id) { mGpuRemapId = id; }
//PxU32 getGpuRemapId() { return mGpuRemapId; }
static PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF translateSpatialVector(const PxVec3& offset, const Cm::SpatialVectorF& vec)
{
return Cm::SpatialVectorF(vec.top, vec.bottom + offset.cross(vec.top));
}
static PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::UnAlignedSpatialVector translateSpatialVector(const PxVec3& offset, const Cm::UnAlignedSpatialVector& vec)
{
return Cm::UnAlignedSpatialVector(vec.top, vec.bottom + offset.cross(vec.top));
}
static PX_FORCE_INLINE PxMat33 constructSkewSymmetricMatrix(const PxVec3 r)
{
return PxMat33(PxVec3(0.0f, r.z, -r.y),
PxVec3(-r.z, 0.0f, r.x),
PxVec3(r.y, -r.x, 0.0f));
}
bool raiseGPUDirtyFlag(ArticulationDirtyFlag::Enum flag)
{
bool nothingRaised = !(mGPUDirtyFlags);
mGPUDirtyFlags |= flag;
return nothingRaised;
}
void clearGPUDirtyFlags()
{
mGPUDirtyFlags = 0;
}
public:
void constraintPrep(ArticulationLoopConstraint* lConstraints, const PxU32 nbJoints,
Cm::SpatialVectorF* Z, PxSolverConstraintPrepDesc& prepDesc, PxSolverBody& sBody,
PxSolverBodyData& sBodyData, PxSolverConstraintDesc* desc, PxConstraintAllocator& allocator);
void updateArticulation(const PxVec3& gravity, const PxReal invLengthScale);
void computeUnconstrainedVelocitiesInternal(
const PxVec3& gravity,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV, const PxReal invLengthScale);
//copy joint data from fromJointData to toJointData
void copyJointData(const ArticulationData& data, PxReal* toJointData, const PxReal* fromJointData);
PxU32 computeDofs();
//this function calculates motion subspace matrix(s) for all tree joint
template<bool immediateMode = false>
void jcalc(ArticulationData& data);
//this function calculates loop joint constraint subspace matrix(s) and active force
//subspace matrix
void jcalcLoopJointSubspace(ArticulationJointCore* joint, ArticulationJointCoreData& jointDatum, SpatialSubspaceMatrix& T,
const Cm::UnAlignedSpatialVector* jointAxis);
void computeSpatialInertia(ArticulationData& data);
//compute zero acceleration force
void computeZ(const ArticulationData& data, const PxVec3& gravity, ScratchData& scratchData);
void computeZD(const ArticulationData& data, const PxVec3& gravity, ScratchData& scratchData);
void solveInternalConstraints(const PxReal dt, const PxReal invDt, Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV,
bool velocityIteration, bool isTGS, const PxReal elapsedTime, const PxReal biasCoefficient);
void solveInternalJointConstraints(const PxReal dt, const PxReal invDt, Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV,
bool velocityIteration, bool isTGS, const PxReal elapsedTime, const PxReal biasCoefficient);
Cm::SpatialVectorF solveInternalJointConstraintRecursive(InternalConstraintSolverData& data, const PxU32 linkID,
const Cm::SpatialVectorF& parentDeltaV, const bool isTGS, const bool isVelIter);
void solveInternalSpatialTendonConstraints(bool isTGS);
void solveInternalFixedTendonConstraints(bool isTGS);
void writebackInternalConstraints(bool isTGS);
void concludeInternalConstraints(bool isTGS);
//compute coriolis force
void computeC(ArticulationData& data, ScratchData& scratchData);
//compute relative transform child to parent
/**
\brief a) copy the latest link pose to a handy array
b) update the link separation vectors using the latest link poses.
c) update the motion matrices in the world frame using the latest link poses.
\param[in] links is an array of articulation links that contain the latest link poses.
\param[in] linkCount is the number of links in the articulation
\param[in] jointCoreDatas is an array of joint descriptions
\param[in] jointDofMotionMatrices is an array of motion matrices in the joint frame.
\param[out] linkAccumulatedPoses is an array used to store the latest link poses taken from ArticulationLink::PxsBodyCore.
\param[out] linkRws is an array of link separations.
\param[out] jointDofmotionMatricesW is an array of motion matrices in the world frame.
*/
static void computeRelativeTransformC2P(
const ArticulationLink* links, const PxU32 linkCount, const ArticulationJointCoreData* jointCoreDatas,
const Cm::UnAlignedSpatialVector* jointDofMotionMatrices,
PxTransform* linkAccumulatedPoses, PxVec3* linkRws, Cm::UnAlignedSpatialVector* jointDofmotionMatricesW);
//compute relative transform child to base
void computeRelativeTransformC2B(ArticulationData& data);
void computeLinkVelocities(ArticulationData& data, ScratchData& scratchData);
/**
/brief Prepare links for the next timestep.
\param[in] dt is the timestep of the current simulation step that will advance sim from t to t+dt.
\param[in] invLengthScale is the reciprocal of the lengthscale used by the simulation.
\param[in] gravity is the gravitational acceleration to apply to all links.
\param[in] fixBase determines whether the root link is to be fixed to the world (true) or will move freely (false).
\param[in] linkCount is the total number of links in the articulation
\param[in] linkAccumulatedPosesW is the pose of each link, specified in the world frame.
\param[in] linkExternalAccelsW is the external acceleration to apply to each link, specified in the world frame.
\param[in] linkRsW is the vector from each parent link to each child link, specified in the world frame.
\param[in] jointDofMotionMatricesW is the motion matrix of each dof, specified in the world frame.
\param[in] jointCoreData is the ArticulationJointCoreData instance of each link in the articulation.
\param[in,out] linkData is the ArticulationLinkData instance of each link in the articulation.
\param[in,out] links is the ArticulationLink instance of each link in the articulation.
\param[in,out] jointDofMotionAccelerations is the acceleration of each link, specified in the world frame.
\param[out] jointDofMotionVelocities is velocity of each link computed from the parent link velocity and joint velocity of the inbound joint. Specified in the world frame.
\param[out] linkZAForcesExtW is the computed spatial zero acceleration force of each link, accounting for only external forces applied to the links. Specified in the world frame.
\param[out] linkZAForcesIntW is the computed spatial zero acceleration force of each link, accounting for only internal forces applied to the links. Specified in the world frame.
\param[out] linkCoriolisVectorsW is the computed coriolis vector of each link. Specified in the world frame.
\param[out] linkIsolatedArticulatedInertiasW is the inertia tensor (I) for the trivial sub-chain of each link. Specified in the world frame.
\param[out] linkMasses is the mass of each link.
\param[out] linkSpatialArticulatedInertiasW is the spatial matrix containing the inertia tensor I and the mass matrix M for the trivial sub-chain of each link. Specified in the world frame.
\param[out] jointDofCount is the number of degrees of freedom for the entire articulation.
\param[in,out] jointDofVelocities is the velocity of each degree of freedom.
\param[out] rootPreMotionVelocityW is assigned the spatial velocity of the root link.
\param[out] comW is the centre of mass of the assembly of links, specified in the world frame.
\param[out] invSumMass is the reciprocal of the total mass of all links.
\note invLengthScale should have value 1/100 for centimetres scale and 1/1 for metres scale.
\note If fixBase is true, the root link is assigned zero velocity. If false, the root link inherits the velocity of the associated body core.
\note If fixBase is true, the root link is assigned zero acceleration. If false, the acceleration is propagated from the previous simulation step. The acceleration
of all other links is left unchanged.
\note If fix base is true, the root link is assigned a zero coriolis vector.
\note ArticulationLinkData::maxPenBias of each link inherits the value of the associated PxsBodyCore::maxPenBias.
\note ArticulationLink::cfm of each link is assigned the value PxsBodyCore::cfmScale*invLengthScale, except for the root link. The root link is
assigned a value of 0 if it is fixed to the world ie fixBase == true.
\note The spatial zero acceleration force accounts for the external acceleration; the damping force arising from the velocity and from the velocity
that will accumulate from the external acceleration; the scaling force that will bring velocity back to the maximum allowed velocity if velocity exceeds the maximum allowed.
\note If the velocity of any degree of freedom exceeds the maximum velocity of the associated joint, the velocity of each degree of freedom will be scaled so that none exceeds the maximum.
*/
static void computeLinkStates(
const PxF32 dt, const PxReal invLengthScale, const PxVec3& gravity,
const bool fixBase,
const PxU32 linkCount,
const PxTransform* linkAccumulatedPosesW, const Cm::SpatialVector* linkExternalAccelsW, const PxVec3* linkRsW, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const Dy::ArticulationJointCoreData* jointCoreData,
Dy::ArticulationLinkData *linkData, Dy::ArticulationLink* links,
Cm::SpatialVectorF* jointDofMotionAccelerations, Cm::SpatialVectorF* jointDofMotionVelocities,
Cm::SpatialVectorF* linkZAForcesExtW, Cm::SpatialVectorF* linkZAForcesIntW, Cm::SpatialVectorF* linkCoriolisVectorsW,
PxMat33* linkIsolatedArticulatedInertiasW, PxF32* linkMasses, Dy::SpatialMatrix* linkSpatialArticulatedInertiasW,
const PxU32 jointDofCount,
PxReal* jointDofVelocities,
Cm::SpatialVectorF& rootPreMotionVelocityW, PxVec3& comW, PxF32& invSumMass);
/**
\brief Propagate articulated z.a. spatial force and articulated spatial inertia from parent link to child link.
Repeated calls to computePropagateSpatialInertia_ZA_ZIc allow z.a. spatial force and articulated spatial inertia
to be propagated from tip to root.
The computation proceeds by considering a link/joint pair composed of a child link and its
incoming joint.
The articulated z.a. spatial force is split into an internal and external part. Gravity is added to the external
part, while user-applied external joint forces are added to the internal part.
\note Reference maths can be found in Eq 4.29 in Mirtich thesis.
\note Mirtich works in the joint frame while every quantity here is in the world frame.
\note linkArticulatedInertia has equivalent I_i^A in Mirtich
\note jointMotionMatrix has equivalent s_i and its transpose is s_i^T.
\param[in] jointType is the type of joint
\param[in] nbJointDofs is the number of dofs supported by the joint.
\param[in] jointMotionMatricesW is an array of motion matrices with one entry per dof.
\param[in] jointISW is a cached term linkArticulatedInertia*jointDofMotionMatrix with one entry per dof.
\param[in] jointTargetArmatures is an array of armature values with one entry per dof.
\param[in] jointExternalForces is an array of user-applied external forces applied to the joint wtih one entry per dof.
\param[in] linkArticulatedInertiaW is the articulated inertia of the link.
\param[in] linkZExtW is the external articulated z.a. force of the link.
\param[in] linkZIntIcW is the sum of the internal z.a force of the link and linkArticulatedInertia*coriolisForce
\param[out] linkInvStISW will be computed as 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[out] jointDofISInvStISW will be computed as linkArticulatedInertia*jointMotionMatrix^T/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[out] jointDofMinusStZExtW will be computed as [-jointMotionMatrix^T * ZExt]
\param[out] jointDofQStZIntIcW will be computed as [jointForce - jointMotionMatrix^T *ZIntIc]
\param[out] deltaZAExtParent is a term that is to be translated to parent link and added to the ZExt value of the parent link.
\param[out] deltaZAIntIcParent is a term that is to be translated to parent link and added to the ZInt value of the parent link.
\return A term to be translated to parent link and added to the articulated inertia of the parent.
*/
static SpatialMatrix computePropagateSpatialInertia_ZA_ZIc
(const PxArticulationJointType::Enum jointType, const PxU8 nbJointDofs,
const Cm::UnAlignedSpatialVector* jointMotionMatricesW, const Cm::SpatialVectorF* jointISW,
const PxReal* jointTargetArmatures, const PxReal* jointExternalForces,
const SpatialMatrix& linkArticulatedInertiaW,
const Cm::SpatialVectorF& linkZExtW, const Cm::SpatialVectorF& linkZIntIcW,
InvStIs& linkInvStISW, Cm::SpatialVectorF* jointDofISInvStISW,
PxReal* jointDofMinusStZExtW, PxReal* jointDofQStZIntIcW,
Cm::SpatialVectorF& deltaZAExtParent, Cm::SpatialVectorF& deltaZAIntIcParent);
/**
\brief Propagate articulated z.a. spatial force and articulated spatial inertia from child link to parent link.
Repeated calls to computePropagateSpatialInertia_ZA_ZIc allow z.a. spatial force and articulated spatial inertia
to be propagated from tip to root.
The computation proceeds by considering a link/joint pair composed of a child link and its incoming joint.
\note Reference maths can be found in Eq 4.29 in Mirtich thesis.
\note Mirtich works in the joint frame while every quantity here is in the world frame.
\note linkArticulatedInertia has equivalent I_i^A in Mirtich
\note jointMotionMatrix has equivalent s_i
\param[in] jointType is the type of joint
\param[in] nbJointDofs is the number of dofs supported by the joint.
\param[in] jointMotionMatrices is an array of motion matrices with one entry per dof.
\param[in] jointIs is a cached term linkArticulatedInertia*jointDofMotionMatrix with one entry per dof.
\param[in] jointTargetArmatures is an array of armature values with one entry per dof.
\param[in] jointExternalForces is an array of user-applied external forces applied to the joint with one entry per dof.
\param[in] linkArticulatedInertia is the articulated inertia of the link.
\param[in] ZIc is the sum of the z.a force of the link and linkArticulatedInertia*coriolisForce.
\param[out] invStIs will be computed as 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[out] isInvD will be computed as linkArticulatedInertia*jointMotionMatrix^T/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[out] qstZIc will be computed as [jointForce - jointMotionMatrix^T *ZIc]/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[out] deltaZParent is a term that is to be translated to parent link and added to the articulated z.a force of the parent link.
\return A term to be translated to parent link and added to the articulated inertia of the parent.
*/
static SpatialMatrix computePropagateSpatialInertia_ZA_ZIc_NonSeparated
(const PxArticulationJointType::Enum jointType, const PxU8 nbJointDofs,
const Cm::UnAlignedSpatialVector* jointMotionMatrices, const Cm::SpatialVectorF* jointIs,
const PxReal* jointTargetArmatures, const PxReal* jointExternalForces,
const SpatialMatrix& linkArticulatedInertia,
const Cm::SpatialVectorF& ZIc,
InvStIs& invStIs, Cm::SpatialVectorF* isInvD,
PxReal* qstZIc,
Cm::SpatialVectorF& deltaZParent);
/*
\brief Propagate articulated spatial inertia (but not the articulated z.a. spatial force) from child link to parent link.
Repeated calls to computePropagateSpatialInertia allow the articulated spatial inertia
to be propagated from tip to root.
The computation proceeds by considering a link/joint pair composed of a child link and its
incoming joint.
\param[in] jointType is the type of joint
\param[in] nbJointDofs is the number of dofs supported by the joint.
\param[in] linkArticulatedInertia is the articulated inertia of the link.
\param[in] jointMotionMatrices is an array of motion matrices with one entry per dof.
\param[in] jointIs is a cached term linkArticulatedInertia*jointDofMotionMatrix with one entry per dof.
\param[out] invStIs will be computed as 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[out] isInvD will be computed as linkArticulatedInertia*jointMotionMatrix^T/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\return A term to be translated to parent link and added to the articulated inertia of the parent.
*/
static SpatialMatrix computePropagateSpatialInertia(
const PxArticulationJointType::Enum jointType, const PxU8 nbDofs,
const SpatialMatrix& linkArticulatedInertia, const Cm::UnAlignedSpatialVector* jointMotionMatrices,
const Cm::SpatialVectorF* jointIs,
InvStIs& invStIs, Cm::SpatialVectorF* isInvD);
static void transformInertia(const SpatialTransform& sTod, SpatialMatrix& inertia);
static void translateInertia(const PxMat33& offset, SpatialMatrix& inertia);
static PxMat33 translateInertia(const PxMat33& inertia, const PxReal mass, const PxVec3& t);
/*
\brief Propagate articulated spatial inertia and articulated z.a. spatial force from tip to root.
\param[in] links is an array of articulation links with size denoted by linkCount.
\param[in] linkCount is the number of articulation links.
\param[in] linkRsW is an array of link separations in the world frame with one entry per link.
\param[in] jointData is an array of joint descriptions with one entry per joint.
\param[in] jointDofMotionMatricesW ins an array of motion matrices in the world frame with one entry per dof.
\param[in] linkCoriolisVectorsW is an array fo coriolis terms with one entry per link.
\param[in] jointForces is an array forces to be applied to joints with one entry per dof.
\param[out] jointDofIsW is a cached term linkArticulatedInertia*jointDofMotionMatrix to be computed with one entry per dof.
\param[out] linkInvStIsW will be computed as 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix] with one entry per link.
\param[out] jointDofISInvStIS will be computed as linkArticulatedInertia*jointMotionMatrix^T/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix] with one entry per dof.
\param[out] joIntDofMinusStZExtW will be computed as [-jointMotionMatrix^T * ZExt] with one entry per dof.
\param[out] jointDofQStZIntIcW will be computed as [jointForce - jointMotionMatrix^T *ZIntIc] with one entry per dof.
\param[in,out] linkZAExtForcsW is the articulated z.a spatial force of each link arising from external forces.
\param[in,out] linkZAIntForcesW is the articulated z.a spatial force of each link arising from internal forces.
\param[in,out] linkSpatialArticulatedInertiaW is the articulated spatial inertia of each link.
\param[out] baseInvSpatialArticulatedInertiaW is the inverse of the articulated spatial inertia of the root link.
*/
static void computeArticulatedSpatialInertiaAndZ
(const ArticulationLink* links, const PxU32 linkCount, const PxVec3* linkRsW,
const ArticulationJointCoreData* jointData,
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const Cm::SpatialVectorF* linkCoriolisVectorsW, const PxReal* jointDofForces,
Cm::SpatialVectorF* jointDofIsW, InvStIs* linkInvStIsW, Cm::SpatialVectorF* jointDofISInvStIS, PxReal* joIntDofMinusStZExtW, PxReal* jointDofQStZIntIcW,
Cm::SpatialVectorF* linkZAExtForcesW, Cm::SpatialVectorF* linkZAIntForcesW, SpatialMatrix* linkSpatialArticulatedInertiaW,
SpatialMatrix& baseInvSpatialArticulatedInertiaW);
void computeArticulatedSpatialInertiaAndZ_NonSeparated(ArticulationData& data, ScratchData& scratchData);
void computeArticulatedSpatialInertia(ArticulationData& data);
/*
\brief Compute the response matrix of each link of an articulation.
\param[in] articulationFlags describes whether the articulation has a fixed base.
\param[in] linkCount is the number of links in the articulation.
\param[in] jointData is an array of joint descriptions with one entry per joint.
\param[in] baseInvSpatialArticulatedInertiaW is the inverse of the articulated spatial inertia of the root link.
\param[in] linkRsW is an array of link separations in the world frame with one entry per link.
\param[in] jointDofMotionMatricesW is an array of motion matrices with one entry per dof.
\param[in] jointDofISW is a cached term linkArticulatedInertia*jointDofMotionMatrix to be computed with one entry per dof.
\param[in] linkInvStISW will be computed as 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix] with one entry per link.
\param[in] jointDofIsInvDW will be computed as linkArticulatedInertia*jointMotionMatrix^T/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix] with one entry per dof.
\param[out] links is an array of articulation links with one entry per link. The cfm value of each link will be updated.
\param[out] linkResponsesW if an array of link responses with one entry per link.
*/
static void computeArticulatedResponseMatrix
(const PxArticulationFlags& articulationFlags, const PxU32 linkCount,
const ArticulationJointCoreData* jointData,
const SpatialMatrix& baseInvArticulatedInertiaW,
const PxVec3* linkRsW, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const Cm::SpatialVectorF* jointDofISW, const InvStIs* linkInvStISW, const Cm::SpatialVectorF* jointDofIsInvDW,
ArticulationLink* links, SpatialImpulseResponseMatrix* linkResponsesW);
void computeJointSpaceJacobians(ArticulationData& data);
void computeArticulatedSpatialZ(ArticulationData& data, ScratchData& scratchData);
/*void computeJointAcceleration(ArticulationLinkData& linkDatum, ArticulationJointCoreData& jointDatum,
const Cm::SpatialVectorF& pMotionAcceleration, PxReal* jointAcceleration, const PxU32 linkID);*/
/**
\brief Compute the joint acceleration
\note Reference maths found in Eq 4.27 of Mirtich thesis.
\param[in] pMotionAcceleration is the acceleration of the parent link already transformed into the (child) link frame.
\param[in] jointDofISW is an array of cached terms linkArticulatedInertia*jointDofMotionMatrix with one entry per dof.
\param[in] linkInvStISW is a cached term equivalent to 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix]
\param[in] jointDofQStZIcW is an array of cached terms equivlaent to
[jointExternalForce - jointDofMotionMatrix^T * (zeroAccelSpatialForce + spatialInertia*coriolisForce] with one entry per dof.
\param[out] jointAcceleration is an array of output joint dof accelerations equivalent to Eq 4.27 in Mirtich thesis.
*/
static void computeJointAccelerationW(const PxU8 nbJointDofs,
const Cm::SpatialVectorF& pMotionAcceleration, const Cm::SpatialVectorF* jointDofISW, const InvStIs& linkInvStISW,
const PxReal* jointDofQStZIcW, PxReal* jointAcceleration);
//compute joint acceleration, joint velocity and link acceleration, velocity based
//on spatial force and spatial articulated inertia tensor
/**
\brief Compute joint and link accelerations.
Accelerations are computed by iterating from root to tip using the formulae in Mirtich Figure 4.8 to compute first
the joint dof acceleration and then the link acceleration.
The accelerations are used to forward integrate the link and joint velocities.
This function may be used to determine either the effect of external forces only or the effect of the external and internal forces combined.
The function may not be used to determine the effect of internal forces. For internal forces only use computeLinkInternalAcceleration().
If external forces only are to be considered then set doIC to false to avoid adding the Coriolis vector to the link acceleration. This is important
because Coriolis forces are accounted as part of the update arising from internal forces.
\param[in] doIC determines whether the link Coriolis force is added to the link acceleration.
Set to false if considering external forces only and true if considering the combination of internal and external forces.
\param[in] dt is the timestep used to accumulate joint/link velocities from joint/link accelerations.
\param[in] fixBase describes whether the root of the articulation is fixed or free to rotate and translate.
\param[in] links is an array of articulation links with one entry for each link.
\param[in] linkCount is the number of links in the articulation.
\param[in] jointDatas is an array of joint descriptions with one entry per joint.
\param[in] linkSpatialZAForcesW is an array of spatial z.a. forces arising from the forces acting on each link with one entry for each link.
linkSpatialZAForces will either be internal z.a forces or the sum of internal and external forces.
\param[in] linkCoriolisForcesW is an array of coriolis forces with one entry for each link.
\param[in] linkRsW is an array of link separations with one entry for each link.
\param[in] jointDofMotionMatricesW is an array of motion matrices with one entry per joint dof.
\param[in] baseInvSpatialArticulatedInertiaW is the inverse of the articulated spatial inertia of the root link.
\param[in] linkInvStISW is 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix] with one entry per link.
\param[in] jointDofISW linkArticulatedInertia*jointMotionMatrix^T/ with one entry per joint dof.
\param[in] jointDofQStZIcW has one of two forms:
a) [-jointDofMotionMatrix^T * linkSpatialZAForceExternal]
b) [jointDofForce - jointDofMotionMatrix^T*(linkSpatialZAForceTotal + linkSpatialInertia*linkCoriolisForce)]
with one entry for each joint dof.
\param[out] linkMotionAccelerationsW is an array of link accelerations with one entry per link. The link accelerations are computed
using the formula in Figure 4.8 of the Mirtich thesis.
\param[in,out] linkMotionVelocitiesW is an array of link velocities that are forward integrated by dt using the link accelerations.
\param[out] jointDofAccelerations is an array of joint dof accelerations with one entry per link. The joint dof accelerations are computed
using the formula in Figure 4.8 of the Mirtich thesis.
\param[in,out] jointDofVelocities is an array of joint dof velocities that are forward integrated by dt using the joint dof accelerations.
\param[out] jointDofNewVelocities is another array of joint dof velocities that are forward integrated by dt using the joint dof accelerations.
\note If doIC is false then linkSpatialZAForces must be the external z.a. forces and jointDofQstZics must be [-jointDofMotionMatrix^T * linkSpatialZAForceExternal]
\note If doIC is true then linkSpatialZAForces must be the internal z.a. forces and jointDofQstZics must be [jointDofForce - jointDofMotionMatrix^T*(linkSpatialZAForceTotal + linkSpatialInertia*linkCoriolisForce)]
*/
static void computeLinkAcceleration
(const bool doIC, const PxReal dt,
const bool fixBase,
const ArticulationLink* links, const PxU32 linkCount, const ArticulationJointCoreData* jointDatas,
const Cm::SpatialVectorF* linkSpatialZAForcesW, const Cm::SpatialVectorF* linkCoriolisForcesW, const PxVec3* linkRsW,
const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const SpatialMatrix& baseInvSpatialArticulatedInertiaW,
const InvStIs* linkInvStISW,
const Cm::SpatialVectorF* jointDofISW, const PxReal* jointDofQStZIcW,
Cm::SpatialVectorF* linkMotionAccelerationsW, Cm::SpatialVectorF* linkMotionVelocitiesW,
PxReal* jointDofAccelerations, PxReal* jointDofVelocities, PxReal* jointDofNewVelocities);
/**
\brief Compute joint and link accelerations arising from internal z.a. forces.
Accelerations are computed by iterating from root to tip using the formulae in Mirtich Figure 4.8 to compute first
the joint dof acceleration and then the link acceleration.
The accelerations are used to forward integrate the link and joint velocities.
The resulting link velocities are rescaled if any link violates the maximum allowed linear or angular velocity.
\param[in] dt is the timestep used to accumulate joint/link velocities from joint/link accelerations.
\param[in] fixBase describes whether the root of the articulation is fixed or free to rotate and translate.
\param[in] comW is the centre of mass of the ensemble of links in the articulation. com is used only to enforce the max linear and angular velocity.
\param[in] invSumMass is the inverse of the mass sum of the ensemble of links in the articulation. invSumMass is used only to enforce the max linear and angular velocity.
\param[in] linkMaxLinearVelocity is the maximum allowed linear velocity of any link. The link linear velocities are rescaled to ensure none breaches the limit.
\param[in] linkMaxAngularVelocity is the maximum allowed angular velocity of any link. The link angular velocities are rescaled to ensure none breaches the limit.
\param[in] linkIsolatedSpatialArticulatedInertiasW is an array of link inertias. The link inertias are used only to enforce the max linear and angular velocity.
\param[in] baseInvSpatialArticulatedInertiaW is the inverse of the articulated spatial inertia of the root link.
\param[in] links is an array of articulation links with one entry for each link.
\param[in] linkCount is the number of links in the articulation.
\param[in] linkMasses is an array of link masses with one entry per link.
\param[in] linkRsW is an array of link separations with one entry per link.
\param[in] linkAccumulatedPosesW is an array of link poses with one entry per link.
\param[in] linkSpatialZAIntForcesW is an array of spatial z.a. forces arising from internal forces only with one netry per link.
\param[in] linkCoriolisVectorsW is an array of link Coriolis forces with one entry per link.
\param[in] jointDatas is an array of joint descriptions with one entry per joint.
\param[in] jointDofMotionMatricesW is an array of motion matrices with one entry per dof.
\param[in] linkInvStISW is 1/[jointMotionMatrix^T * linkArticulatedInertia * jointMotionMatrix] with one entry per link.
\param[in] jointDofISW linkArticulatedInertia*jointMotionMatrix^T with one entry per joint dof.
\param[in] jointDoQStZIntIcW has form: [jointDofForce - jointDofMotionMatrix^T*(linkSpatialZAForceInternal + linkSpatialInertia*linkCoriolisForce)]
with one entry for each joint dof.
\param[in,out] linkMotionAccelerationsW accumulates with the computed acceleration arising from internal forces.
\param[out] linkMotionAccelerationIntsW is the computed acceleration arising from internal forces.
\param[in,out] jointDofVelocities is an array of joint dof velocities that are forward integrated by dt using the joint dof accelerations arising from internal forces.
\param[out] jointDofNewVelocities is another array of joint dof velocities that are forward integrated by dt using the joint dof accelerations arising from internal forces.
\note computeLinkInternalAcceleration must be called after computeLinkAcceleration to allow the effect of internal forces to be accumulated on top of external forces.
*/
static void computeLinkInternalAcceleration
(const PxReal dt,
const bool fixBase,
const PxVec3& comW, const PxReal invSumMass, const PxReal linkMaxLinearVelocity, const PxReal linkMaxAngularVelocity, const PxMat33* linkIsolatedSpatialArticulatedInertiasW,
const SpatialMatrix& baseInvSpatialArticulatedInertiaW,
const ArticulationLink* links, const PxU32 linkCount,
const PxReal* linkMasses, const PxVec3* linkRsW, const PxTransform* linkAccumulatedPosesW,
const Cm::SpatialVectorF* linkSpatialZAIntForcesW, const Cm::SpatialVectorF* linkCoriolisVectorsW,
const ArticulationJointCoreData* jointDatas, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW,
const InvStIs* linkInvStISW, const Cm::SpatialVectorF* jointDofISW, const PxReal* jointDoQStZIntIcW,
Cm::SpatialVectorF* linkMotionAccelerationsW, Cm::SpatialVectorF* linkMotionAccelerationIntsW, Cm::SpatialVectorF* linkMotionVelocitiesW,
PxReal* jointDofAccelerations, PxReal* jointDofInternalAccelerations, PxReal* jointDofVelocities, PxReal* jointDofNewVelocities);
/**
\brief For each link compute the incoming joint force in the joint frame.
\param[in] linkCount is the number of links in the articulation
\param[in] linkZAForcesExtW are the external spatial zero acceleration forces in the world frame with one entry per link.
\param[in] linkZAForcesIntW are the internal spatial zero acceleration forces in the world frame with one entry per link.
\param[in] linkMotionAccelerationsW are the spatial accelerations ion the world framewith one entry per link.
\param[in] linkSpatialInertiasW are the spatial articulated inertias in the world frame with one entry per link.
\param[out] linkIncomingJointForces are the incoming joint forces specified in the joint frame that are applied to each link.
*/
static void computeLinkIncomingJointForce(
const PxU32 linkCount,
const Cm::SpatialVectorF* linkZAForcesExtW, const Cm::SpatialVectorF* linkZAForcesIntW,
const Cm::SpatialVectorF* linkMotionAccelerationsW, const SpatialMatrix* linkSpatialInertiasW,
Cm::SpatialVectorF* linkIncomingJointForces);
//void computeTempLinkAcceleration(ArticulationData& data, ScratchData& scratchData);
void computeJointTransmittedFrictionForce(ArticulationData& data, ScratchData& scratchData,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV);
static Cm::SpatialVectorF getDeltaVWithDeltaJV(const bool fixBase, const PxU32 linkID,
const ArticulationData& data, Cm::SpatialVectorF* Z,
PxReal* jointVelocities);
//impulse need to be in the linkID space
static void getZ(const PxU32 linkID, const ArticulationData& data,
Cm::SpatialVectorF* Z, const Cm::SpatialVectorF& impulse);
//This method use in impulse self response. The input impulse is in the link space
static Cm::SpatialVectorF getImpulseResponseW(
const PxU32 linkID,
const ArticulationData& data,
const Cm::SpatialVectorF& impulse);
//This method use in impulse self response. The input impulse is in the link space
static Cm::SpatialVectorF getImpulseResponseWithJ(
const PxU32 linkID,
const bool fixBase,
const ArticulationData& data,
Cm::SpatialVectorF* Z,
const Cm::SpatialVectorF& impulse,
PxReal* jointVelocities);
void getImpulseSelfResponseInv(const bool fixBase,
PxU32 linkID0,
PxU32 linkID1,
Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse0,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV0,
Cm::SpatialVector& deltaV1,
PxReal* jointVelocities);
void getImpulseResponseSlowInv(Dy::ArticulationLink* links,
const ArticulationData& data,
PxU32 linkID0_,
const Cm::SpatialVector& impulse0,
Cm::SpatialVector& deltaV0,
PxU32 linkID1_,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV1,
PxReal* jointVelocities,
Cm::SpatialVectorF* Z);
Cm::SpatialVectorF getImpulseResponseInv(const bool fixBase,
const PxU32 linkID, Cm::SpatialVectorF* Z,
const Cm::SpatialVector& impulse,
PxReal* jointVelocites);
void inverseDynamic(ArticulationData& data, const PxVec3& gravity,
ScratchData& scratchData, bool computeCoriolis);
void inverseDynamicFloatingBase(ArticulationData& data, const PxVec3& gravity,
ScratchData& scratchData, bool computeCoriolis);
//compute link body force with motion velocity and acceleration
void computeZAForceInv(ArticulationData& data, ScratchData& scratchData);
void initCompositeSpatialInertia(ArticulationData& data, Dy::SpatialMatrix* compositeSpatialInertia);
void computeCompositeSpatialInertiaAndZAForceInv(ArticulationData& data, ScratchData& scratchData);
void computeRelativeGeneralizedForceInv(ArticulationData& data, ScratchData& scratchData);
//provided joint velocity and joint acceleartion, compute link acceleration
void computeLinkAccelerationInv(ArticulationData& data, ScratchData& scratchData);
void computeGeneralizedForceInv(ArticulationData& data, ScratchData& scratchData);
void calculateMassMatrixColInv(ScratchData& scratchData);
void calculateHFixBase(PxArticulationCache& cache);
void calculateHFloatingBase(PxArticulationCache& cache);
//joint limits
void enforcePrismaticLimits(PxReal& jPosition, ArticulationJointCore* joint);
public:
PX_FORCE_INLINE void addBody()
{
mAcceleration.pushBack(Cm::SpatialVector(PxVec3(0.f), PxVec3(0.f)));
mUpdateSolverData = true;
}
PX_FORCE_INLINE void removeBody()
{
mUpdateSolverData = true;
}
PX_FORCE_INLINE bool updateSolverData() { return mUpdateSolverData; }
PX_FORCE_INLINE PxU32 getMaxDepth() const { return mMaxDepth; }
PX_FORCE_INLINE void setMaxDepth(const PxU32 depth) { mMaxDepth = depth; }
// solver methods
PX_FORCE_INLINE PxU32 getBodyCount() const { return mSolverDesc.linkCount; }
PX_FORCE_INLINE void getSolverDesc(ArticulationSolverDesc& d) const { d = mSolverDesc; }
PX_FORCE_INLINE ArticulationSolverDesc& getSolverDesc() { return mSolverDesc; }
PX_FORCE_INLINE ArticulationCore* getCore() { return mSolverDesc.core; }
PX_FORCE_INLINE PxU16 getIterationCounts() const { return mSolverDesc.core->solverIterationCounts; }
PX_FORCE_INLINE void* getUserData() const { return mUserData; }
PX_FORCE_INLINE void setDyContext(Dy::Context* context) { mContext = context; }
void setupLinks(PxU32 nbLinks, Dy::ArticulationLink* links);
void allocatePathToRootElements(const PxU32 totalPathToRootElements);
void initPathToRoot();
static void getImpulseSelfResponse(ArticulationLink* links,
Cm::SpatialVectorF* Z,
ArticulationData& data,
PxU32 linkID0,
const Cm::SpatialVectorV& impulse0,
Cm::SpatialVectorV& deltaV0,
PxU32 linkID1,
const Cm::SpatialVectorV& impulse1,
Cm::SpatialVectorV& deltaV1);
static void getImpulseResponseSlow(Dy::ArticulationLink* links,
ArticulationData& data,
PxU32 linkID0_,
const Cm::SpatialVector& impulse0,
Cm::SpatialVector& deltaV0,
PxU32 linkID1_,
const Cm::SpatialVector& impulse1,
Cm::SpatialVector& deltaV1,
Cm::SpatialVectorF* Z);
PxU32 setupSolverConstraints(
ArticulationLink* links,
const PxU32 linkCount,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
PxU32& acCount);
void setupInternalConstraints(
ArticulationLink* links,
const PxU32 linkCount,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
PxReal stepDt,
PxReal dt,
PxReal invDt,
bool isTGSSolver);
void setupInternalConstraintsRecursive(
ArticulationLink* links,
const PxU32 linkCount,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
const PxReal stepDt,
const PxReal dt,
const PxReal invDt,
const bool isTGSSolver,
const PxU32 linkID,
const PxReal maxForceScale);
void setupInternalSpatialTendonConstraintsRecursive(
ArticulationLink* links,
ArticulationAttachment* attachments,
const PxU32 attachmentCount,
const PxVec3& parentAttachmentPoint,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
const PxReal stepDt,
const bool isTGSSolver,
const PxU32 attachmentID,
const PxReal stiffness,
const PxReal damping,
const PxReal limitStiffness,
const PxReal err,
const PxU32 startLink,
const PxVec3& startAxis,
const PxVec3& startRaXn);
void setupInternalFixedTendonConstraintsRecursive(
ArticulationLink* links,
ArticulationTendonJoint* tendonJoints,
const bool fixBase,
ArticulationData& data,
Cm::SpatialVectorF* Z,
const PxReal stepDt,
const bool isTGSSolver,
const PxU32 tendonJointID,
const PxReal stiffness,
const PxReal damping,
const PxReal limitStiffness,
const PxU32 startLink,
const PxVec3& startAxis,
const PxVec3& startRaXn);
void updateSpatialTendonConstraintsRecursive(ArticulationAttachment* attachments, ArticulationData& data, const PxU32 attachmentID, const PxReal accumErr,
const PxVec3& parentAttachmentPoint);
//void updateFixedTendonConstraintsRecursive(ArticulationLink* links, ArticulationTendonJoint* tendonJoint, ArticulationData& data, const PxU32 tendonJointID, const PxReal accumErr);
PxVec3 calculateFixedTendonVelocityAndPositionRecursive(FixedTendonSolveData& solveData,
const Cm::SpatialVectorF& parentV, const Cm::SpatialVectorF& parentDeltaV, const PxU32 tendonJointID);
Cm::SpatialVectorF solveFixedTendonConstraintsRecursive(FixedTendonSolveData& solveData,
const PxU32 tendonJointID);
void prepareStaticConstraints(const PxReal dt, const PxReal invDt, PxsContactManagerOutputIterator& outputs,
Dy::ThreadContext& threadContext, PxReal correlationDist, PxReal bounceThreshold, PxReal frictionOffsetThreshold,
PxReal ccdMaxSeparation, PxSolverBodyData* solverBodyData, PxsConstraintBlockManager& blockManager,
Dy::ConstraintWriteback* constraintWritebackPool);
void prepareStaticConstraintsTGS(const PxReal stepDt, const PxReal totalDt, const PxReal invStepDt, const PxReal invTotalDt,
PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& threadContext, PxReal correlationDist, PxReal bounceThreshold,
PxReal frictionOffsetThreshold, PxTGSSolverBodyData* solverBodyData,
PxTGSSolverBodyTxInertia* txInertia, PxsConstraintBlockManager& blockManager, Dy::ConstraintWriteback* constraintWritebackPool,
const PxReal biasCoefficient, const PxReal lengthScale);
//integration
void propagateLinksDown(ArticulationData& data, PxReal* jointVelocities, PxReal* jointPositions,
Cm::SpatialVectorF* motionVelocities);
void updateJointProperties(
PxReal* jointNewVelocities,
PxReal* jointVelocities,
PxReal* jointAccelerations);
void computeAndEnforceJointPositions(ArticulationData& data);
//update link position based on joint position provided by the cache
void teleportLinks(ArticulationData& data);
void computeLinkVelocities(ArticulationData& data);
PxU8* allocateScratchSpatialData(PxcScratchAllocator* allocator,
const PxU32 linkCount, ScratchData& scratchData, bool fallBackToHeap = false);
//This method calculate the velocity change from parent to child using parent current motion velocity
PxTransform propagateTransform(const PxU32 linkID, ArticulationLink* links, ArticulationJointCoreData& jointDatum,
Cm::SpatialVectorF* motionVelocities, const PxReal dt, const PxTransform& pBody2World, const PxTransform& currentTransform,
PxReal* jointVelocity, PxReal* jointPosition, const Cm::UnAlignedSpatialVector* motionMatrix,
const Cm::UnAlignedSpatialVector* worldMotionMatrix);
static void updateRootBody(const Cm::SpatialVectorF& motionVelocity,
const PxTransform& preTransform, ArticulationData& data, const PxReal dt);
//These variables are used in the constraint partition
PxU16 maxSolverFrictionProgress;
PxU16 maxSolverNormalProgress;
PxU32 solverProgress;
PxU16 mArticulationIndex;
PxU8 numTotalConstraints;
void* mUserData;
Dy::Context* mContext;
ArticulationSolverDesc mSolverDesc;
PxArray<Cm::SpatialVector> mAcceleration; // supplied by Sc-layer to feed into articulations
bool mUpdateSolverData;
PxU32 mMaxDepth;
ArticulationData mArticulationData;
PxArray<PxSolverConstraintDesc> mStaticContactConstraints;
PxArray<PxSolverConstraintDesc> mStatic1DConstraints;
PxU32 mGPUDirtyFlags;
bool mJcalcDirty;
} PX_ALIGN_SUFFIX(64);
#if PX_VC
#pragma warning(pop)
#endif
} //namespace Dy
}
#endif
| 85,250 | C | 51.786997 | 216 | 0.762545 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyHairSystem.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 DY_HAIR_SYSTEM_H
#define DY_HAIR_SYSTEM_H
#include "DyHairSystemCore.h"
#include "PxvGeometry.h"
namespace physx
{
namespace Sc
{
class HairSystemSim;
}
namespace Dy
{
typedef size_t HairSystemHandle;
// forward-declarations
class Context;
class HairSystem;
struct HairSystemDirtyFlag
{
enum Enum
{
// Changes are processed from highest (most fundamental) to lowest to ensure correct dependencies
eNONE = 0, //!> default, everything up-to-date
ePARAMETERS = 1 << 0, //!> Parameters were changed
eGRID_SIZE = 1 << 1 | ePARAMETERS, //!> Grid size was changed. sets ePARAMETERS because settings are stored there
eRIGID_ATTACHMENTS = 1 << 2, //!> Rigid attachment was changed
eSOFTBODY_ATTACHMENTS = 1 << 3, //!> Softbody attachments added or removed
ePOSITIONS_VELOCITIES_MASS = 1 << 4, //!> Positions, velocities or masses changed
eLOD_SWITCH = 1 << 5, //!> Level of detail was changed, update lodX pos/vel from lod0
eLOD_DATA = 1 << 6 | eLOD_SWITCH, //!> Definition of detail levels changed . Must come after setting any kind of rest positions. Triggers one-off initialization of levels
eBENDING_REST_ANGLES = 1 << 7 | eLOD_DATA, //!> Bending rest angles were changed
eTWISTING_REST_POSITIONS = 1 << 8 | eLOD_DATA, //!> Twisting rest positions were changed
eREST_POSITIONS = 1 << 9 | eLOD_DATA, //!> Rest positions changed
eSHAPE_MATCHING_SIZES = 1 << 10 | ePARAMETERS | eLOD_DATA, //!> Shape matching group size or overlap changed. sets ePARAMETERS because settings are stored there
eSTRAND_LENGTHS = 1 << 11 | eLOD_DATA | eSHAPE_MATCHING_SIZES | eBENDING_REST_ANGLES | eTWISTING_REST_POSITIONS, //!> Topology of vertex arrangement was changed
eNUM_STRANDS_OR_VERTS = 1 << 12 | eSHAPE_MATCHING_SIZES
| ePOSITIONS_VELOCITIES_MASS | eBENDING_REST_ANGLES | eTWISTING_REST_POSITIONS
| eREST_POSITIONS | eLOD_DATA | eSTRAND_LENGTHS, //!> Number of strands or vertices changed
eALL = (1 << 13) - 1 //!> everything needs updating
};
};
struct HairSystemSolverDesc
{
HairSystem* hairSystem;
};
class HairSystem
{
PX_NOCOPY(HairSystem)
public:
HairSystem(Sc::HairSystemSim* sim, Dy::HairSystemCore& core) :
mSim(sim)
, mCore(core)
, mShapeCore(NULL)
, mElementId(0xffFFffFF)
, mGpuRemapId(0xffFFffFF)
{
mCore.mDirtyFlags = HairSystemDirtyFlag::eALL;
}
~HairSystem() {}
PX_FORCE_INLINE void setShapeCore(PxsShapeCore* shapeCore)
{
mShapeCore = shapeCore;
}
PX_FORCE_INLINE PxU32 getGpuRemapId() const { return mGpuRemapId; }
PX_FORCE_INLINE void setGpuRemapId(PxU32 remapId)
{
mGpuRemapId = remapId;
PxHairSystemGeometryLL& geom = mShapeCore->mGeometry.get<PxHairSystemGeometryLL>();
geom.gpuRemapId = remapId;
}
PX_FORCE_INLINE PxU32 getElementId() const { return mElementId; }
PX_FORCE_INLINE void setElementId(const PxU32 elementId) { mElementId = elementId; }
PX_FORCE_INLINE Sc::HairSystemSim* getHairSystemSim() const { return mSim; }
PX_FORCE_INLINE const HairSystemCore& getCore() const { return mCore; }
PX_FORCE_INLINE HairSystemCore& getCore() { return mCore; }
PX_FORCE_INLINE PxsShapeCore& getShapeCore() { return *mShapeCore; }
PX_FORCE_INLINE PxU16 getIterationCounts() { return mCore.mSolverIterationCounts; }
private: // variables
Sc::HairSystemSim* mSim;
HairSystemCore& mCore;
PxsShapeCore* mShapeCore;
PxU32 mElementId; //this is used for the bound array
PxU32 mGpuRemapId;
};
PX_FORCE_INLINE HairSystem* getHairSystem(HairSystemHandle handle)
{
return reinterpret_cast<HairSystem*>(handle);
}
}
}
#endif
| 5,346 | C | 37.192857 | 180 | 0.708754 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyHairSystemCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 DY_HAIR_SYSTEM_CORE_H
#define DY_HAIR_SYSTEM_CORE_H
#include "PxAttachment.h"
#include "PxHairSystemFlag.h"
#include "PxNodeIndex.h"
#include "foundation/PxArray.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec2.h"
#include "foundation/PxVec4.h"
namespace physx
{
namespace Dy
{
// These parameters are needed on GPU for simulation and are grouped in a struct
// to reduce the number of assignments in update user data.
struct HairSystemSimParameters
{
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getCellSize() const { return mSegmentLength + 2.0f * mSegmentRadius; }
PX_CUDA_CALLABLE PX_FORCE_INLINE int getGridSize() const { return mGridSize[0] * mGridSize[1] * mGridSize[2]; }
PxHairSystemFlags::InternalType mFlags;
PxReal mSegmentLength;
PxReal mSegmentRadius;
PxReal mInterHairRepulsion; // strength of the repulsion field
PxReal mInterHairVelocityDamping; // friction based on interpolated vel field
PxReal mFrictionCoeff; // coulomb friction coefficient for collisions (internal and external)
PxReal mMaxDepenetrationVelocity; // max velocity delta coming out of collision responses
PxReal mAeroDrag; // the aerodynamic drag coefficient
PxReal mAeroLift; // the aerodynamic lift coefficient
PxReal mBendingCompliance;
PxReal mTwistingCompliance;
int mGridSize[3]; // number of cells in x,y,z directions
PxVec2 mShapeCompliance; // compliance for shape matching
PxReal mSelfCollisionContactDist; // contact distance for self collisions expressed as a multiple of the segment
// radius
PxReal mSelfCollisionRelaxation;
PxReal mLraRelaxation;
PxReal mShapeMatchingCompliance;
PxReal mShapeMatchingBeta; // balance between rigid rotation and linear stretching
PxU16 mShapeMatchingNumVertsPerGroup;
PxU16 mShapeMatchingNumVertsOverlap;
PxU32 mRestPositionTransformNumVertsPerStrand; // how many vertices of each strand to use for computing the rest
// position targets for global shape preservation
HairSystemSimParameters()
: mFlags(0)
, mSegmentLength(0.1f)
, mSegmentRadius(0.02f)
, mInterHairRepulsion(0.0f)
, mInterHairVelocityDamping(0.03f)
, mFrictionCoeff(0.0f)
, mMaxDepenetrationVelocity(PX_MAX_F32)
, mAeroDrag(0.0f)
, mAeroLift(0.0f)
, mBendingCompliance(-1.0f)
, mTwistingCompliance(-1.0f)
, mShapeCompliance(-1.0f)
, mSelfCollisionContactDist(1.5f)
, mSelfCollisionRelaxation(0.7f)
, mLraRelaxation(1.0f)
, mShapeMatchingCompliance(-1.0f)
, mShapeMatchingBeta(0.0f)
, mShapeMatchingNumVertsPerGroup(10)
, mShapeMatchingNumVertsOverlap(5)
, mRestPositionTransformNumVertsPerStrand(2)
{
// grid size must be powers of two
mGridSize[0] = 32;
mGridSize[1] = 64;
mGridSize[0] = 32;
}
};
PX_ALIGN_PREFIX(16)
struct SoftbodyHairAttachment
{
PxVec4 tetBarycentric; // must be aligned, is being loaded as float4
PxU32 tetId;
PxU32 softbodyNodeIdx;
PxU32 hairVtxIdx;
PxReal constraintOffset;
PxVec4 low_high_angle;
PxVec4 attachmentBarycentric;
}
PX_ALIGN_SUFFIX(16);
PX_COMPILE_TIME_ASSERT(sizeof(SoftbodyHairAttachment) % 16 == 0);
struct HairSystemCore
{
public:
PxU32 mDirtyFlags;
PxHairSystemDataFlags mReadRequests;
PxU32 mNumVertices;
PxU32 mNumStrands;
// Parameters
HairSystemSimParameters mParams;
PxU16 mSolverIterationCounts;
PxVec4 mWind;
// Topology data
const PxU32* mStrandPastEndIndices;
const PxReal* mBendingRestAngles;
PxArray<PxU16> mMaterialhandles;
// Buffers for simulation (device or pinned host mirrors)
PxVec4* mPositionInvMass;
PxVec4* mVelocity;
// pointers to PxgHairSystemCore buffers that are exposed to the user
PxU32* mStrandPastEndIndicesGpuSim;
PxVec4* mPositionInvMassGpuSim;
PxReal* mTwistingRestPositionsGpuSim;
// rest positions
PxVec4* mRestPositionsD; // Gpu buffer
// Attachments to rigids
PxParticleRigidAttachment* mRigidAttachments; // Gpu buffer
PxU32 mNumRigidAttachments;
// Attachments to softbodies
SoftbodyHairAttachment* mSoftbodyAttachments;
PxU32 mNumSoftbodyAttachments;
// LOD data
PxU32 mLodLevel; // the selected level, zero by default meaning full detail
PxU32 mLodNumLevels; // number of levels excluding level zero
const PxReal* mLodProportionOfStrands;
const PxReal* mLodProportionOfVertices;
// sleeping
PxReal mSleepThreshold;
PxReal mWakeCounter;
void setMaterial(PxU16 materialhandle) { mMaterialhandles.pushBack(materialhandle); }
void clearMaterials() { mMaterialhandles.clear(); }
HairSystemCore()
: mDirtyFlags(PX_MAX_U32)
, mNumVertices(0)
, mNumStrands(0)
, mSolverIterationCounts(8)
, mWind(0.0f)
, mStrandPastEndIndices(NULL)
, mBendingRestAngles(NULL)
, mPositionInvMass(NULL)
, mVelocity(NULL)
, mStrandPastEndIndicesGpuSim(NULL)
, mPositionInvMassGpuSim(NULL)
, mTwistingRestPositionsGpuSim(NULL)
, mRestPositionsD(NULL)
, mRigidAttachments(NULL)
, mNumRigidAttachments(0)
, mSoftbodyAttachments(NULL)
, mNumSoftbodyAttachments(0)
, mLodLevel(0)
, mLodNumLevels(0)
, mLodProportionOfStrands(NULL)
, mLodProportionOfVertices(NULL)
, mSleepThreshold(0.1f)
, mWakeCounter(1.0f)
{
}
};
} // namespace Dy
} // namespace physx
#endif
| 6,817 | C | 32.258536 | 113 | 0.761185 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyThresholdTable.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_THRESHOLD_TABLE_H
#define DY_THRESHOLD_TABLE_H
#include "foundation/PxPinnedArray.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxHash.h"
#include "foundation/PxMemory.h"
#include "PxNodeIndex.h"
namespace physx
{
class PxsRigidBody;
namespace Sc
{
class ShapeInteraction;
}
namespace Dy
{
struct ThresholdStreamElement
{
Sc::ShapeInteraction* shapeInteraction; //4/8 4/8
PxReal normalForce; //4 8/12
PxReal threshold; //4 12/16
PxNodeIndex nodeIndexA; //8 24 This is the unique node index in island gen which corresonding to that body and it is persistent 16 20
PxNodeIndex nodeIndexB; //8 32 This is the unique node index in island gen which corresonding to that body and it is persistent 20 24
PxReal accumulatedForce; //4 36
PxU32 pad; //4 40
PX_CUDA_CALLABLE bool operator <= (const ThresholdStreamElement& otherPair) const
{
return ((nodeIndexA < otherPair.nodeIndexA) ||(nodeIndexA == otherPair.nodeIndexA && nodeIndexB <= otherPair.nodeIndexB));
}
PX_CUDA_CALLABLE bool operator < (const ThresholdStreamElement& otherPair) const
{
return ((nodeIndexA < otherPair.nodeIndexA) || (nodeIndexA == otherPair.nodeIndexA && nodeIndexB < otherPair.nodeIndexB));
}
PX_CUDA_CALLABLE bool operator == (const ThresholdStreamElement& otherPair) const
{
return ((nodeIndexA == otherPair.nodeIndexA && nodeIndexB == otherPair.nodeIndexB));
}
};
typedef PxPinnedArray<ThresholdStreamElement> ThresholdArray;
class ThresholdStream : public ThresholdArray, public PxUserAllocated
{
public:
ThresholdStream(PxVirtualAllocatorCallback& allocatorCallback) : ThresholdArray(PxVirtualAllocator(&allocatorCallback))
{
}
};
class ThresholdTable
{
public:
ThresholdTable()
: mBuffer(NULL),
mHash(NULL),
mHashSize(0),
mHashCapactiy(0),
mPairs(NULL),
mNexts(NULL),
mPairsSize(0),
mPairsCapacity(0)
{
}
~ThresholdTable()
{
PX_FREE(mBuffer);
}
void build(const ThresholdStream& stream);
bool check(const ThresholdStream& stream, const PxU32 nodexIndexA, const PxU32 nodexIndexB, PxReal dt);
bool check(const ThresholdStream& stream, const ThresholdStreamElement& elem, PxU32& thresholdIndex);
//private:
static const PxU32 NO_INDEX = 0xffffffff;
struct Pair
{
PxU32 thresholdStreamIndex;
PxReal accumulatedForce;
//PxU32 next; // hash key & next ptr
};
PxU8* mBuffer;
PxU32* mHash;
PxU32 mHashSize;
PxU32 mHashCapactiy;
Pair* mPairs;
PxU32* mNexts;
PxU32 mPairsSize;
PxU32 mPairsCapacity;
};
namespace
{
static PX_FORCE_INLINE PxU32 computeHashKey(const PxU32 nodeIndexA, const PxU32 nodeIndexB, const PxU32 hashCapacity)
{
return (PxComputeHash(PxU64(nodeIndexA)<<32 | PxU64(nodeIndexB)) % hashCapacity);
}
}
inline bool ThresholdTable::check(const ThresholdStream& stream, const ThresholdStreamElement& elem, PxU32& thresholdIndex)
{
PxU32* PX_RESTRICT hashes = mHash;
PxU32* PX_RESTRICT nextIndices = mNexts;
Pair* PX_RESTRICT pairs = mPairs;
PX_ASSERT(elem.nodeIndexA < elem.nodeIndexB);
PxU32 hashKey = computeHashKey(elem.nodeIndexA.index(), elem.nodeIndexB.index(), mHashSize);
PxU32 pairIndex = hashes[hashKey];
while(NO_INDEX != pairIndex)
{
Pair& pair = pairs[pairIndex];
const PxU32 thresholdStreamIndex = pair.thresholdStreamIndex;
PX_ASSERT(thresholdStreamIndex < stream.size());
const ThresholdStreamElement& otherElement = stream[thresholdStreamIndex];
if(otherElement.nodeIndexA==elem.nodeIndexA && otherElement.nodeIndexB==elem.nodeIndexB && otherElement.shapeInteraction == elem.shapeInteraction)
{
thresholdIndex = thresholdStreamIndex;
return true;
}
pairIndex = nextIndices[pairIndex];
}
thresholdIndex = NO_INDEX;
return false;
}
inline void ThresholdTable::build(const ThresholdStream& stream)
{
//Handle the case of an empty stream.
if(0==stream.size())
{
mPairsSize=0;
mPairsCapacity=0;
mHashSize=0;
mHashCapactiy=0;
PX_FREE(mBuffer);
return;
}
//Realloc/resize if necessary.
const PxU32 pairsCapacity = stream.size();
const PxU32 hashCapacity = pairsCapacity*2+1;
if((pairsCapacity > mPairsCapacity) || (pairsCapacity < (mPairsCapacity >> 2)))
{
PX_FREE(mBuffer);
const PxU32 pairsByteSize = sizeof(Pair)*pairsCapacity;
const PxU32 nextsByteSize = sizeof(PxU32)*pairsCapacity;
const PxU32 hashByteSize = sizeof(PxU32)*hashCapacity;
const PxU32 totalByteSize = pairsByteSize + nextsByteSize + hashByteSize;
mBuffer = reinterpret_cast<PxU8*>(PX_ALLOC(totalByteSize, "PxThresholdStream"));
PxU32 offset = 0;
mPairs = reinterpret_cast<Pair*>(mBuffer + offset);
offset += pairsByteSize;
mNexts = reinterpret_cast<PxU32*>(mBuffer + offset);
offset += nextsByteSize;
mHash = reinterpret_cast<PxU32*>(mBuffer + offset);
offset += hashByteSize;
PX_ASSERT(totalByteSize == offset);
mPairsCapacity = pairsCapacity;
mHashCapactiy = hashCapacity;
}
//Set each entry of the hash table to 0xffffffff
PxMemSet(mHash, 0xff, sizeof(PxU32)*hashCapacity);
//Init the sizes of the pairs array and hash array.
mPairsSize = 0;
mHashSize = hashCapacity;
PxU32* PX_RESTRICT hashes = mHash;
PxU32* PX_RESTRICT nextIndices = mNexts;
Pair* PX_RESTRICT pairs = mPairs;
//Add all the pairs from the stream.
PxU32 pairsSize = 0;
for(PxU32 i = 0; i < pairsCapacity; i++)
{
const ThresholdStreamElement& element = stream[i];
const PxNodeIndex nodeIndexA = element.nodeIndexA;
const PxNodeIndex nodeIndexB = element.nodeIndexB;
const PxF32 force = element.normalForce;
PX_ASSERT(nodeIndexA < nodeIndexB);
const PxU32 hashKey = computeHashKey(nodeIndexA.index(), nodeIndexB.index(), hashCapacity);
//Get the index of the first pair found that resulted in a hash that matched hashKey.
PxU32 prevPairIndex = hashKey;
PxU32 pairIndex = hashes[hashKey];
//Search through all pairs found that resulted in a hash that matched hashKey.
//Search until the exact same body pair is found.
//Increment the accumulated force if the exact same body pair is found.
while(NO_INDEX != pairIndex)
{
Pair& pair = pairs[pairIndex];
const PxU32 thresholdStreamIndex = pair.thresholdStreamIndex;
PX_ASSERT(thresholdStreamIndex < stream.size());
const ThresholdStreamElement& otherElement = stream[thresholdStreamIndex];
if(nodeIndexA == otherElement.nodeIndexA && nodeIndexB==otherElement.nodeIndexB)
{
pair.accumulatedForce += force;
prevPairIndex = NO_INDEX;
pairIndex = NO_INDEX;
break;
}
prevPairIndex = pairIndex;
pairIndex = nextIndices[pairIndex];
}
if(NO_INDEX != prevPairIndex)
{
nextIndices[pairsSize] = hashes[hashKey];
hashes[hashKey] = pairsSize;
Pair& newPair = pairs[pairsSize];
newPair.thresholdStreamIndex = i;
newPair.accumulatedForce = force;
pairsSize++;
}
}
mPairsSize = pairsSize;
}
}
}
#endif
| 8,602 | C | 29.399293 | 149 | 0.740293 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyFeatherstoneArticulationJointData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_FEATHERSTONE_ARTICULATION_JOINT_DATA_H
#define DY_FEATHERSTONE_ARTICULATION_JOINT_DATA_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxVecMath.h"
#include "CmUtils.h"
#include "CmSpatialVector.h"
#include "DyVArticulation.h"
#include "DyFeatherstoneArticulationUtils.h"
#include "DyArticulationJointCore.h"
#include <stdio.h>
namespace physx
{
namespace Dy
{
class ArticulationJointCoreData
{
public:
ArticulationJointCoreData() : jointOffset(0xffffffff), dofInternalConstraintMask(0)
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 computeJointDofs(ArticulationJointCore* joint) const
{
PxU8 tDof = 0;
for (PxU32 i = 0; i < DY_MAX_DOF; ++i)
{
if (joint->motion[i] != PxArticulationMotion::eLOCKED)
{
tDof++;
}
}
return tDof;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void computeJointAxis(const ArticulationJointCore* joint, Cm::UnAlignedSpatialVector* jointAxis)
{
for (PxU32 i = 0; i < dof; ++i)
{
PxU32 ind = joint->dofIds[i];
Cm::UnAlignedSpatialVector axis = Cm::UnAlignedSpatialVector::Zero();
//axis is in the local space of joint
axis[ind] = 1.f;
jointAxis[i] = axis;
}
}
PX_FORCE_INLINE PxU32 computeJointDof(ArticulationJointCore* joint, Cm::UnAlignedSpatialVector* jointAxis)
{
if (joint->jointDirtyFlag & ArticulationJointCoreDirtyFlag::eMOTION)
{
dof = 0;
limitMask = 0;
//KS - no need to zero memory here.
//PxMemZero(jointAxis, sizeof(jointAxis));
for (PxU8 i = 0; i < DY_MAX_DOF; ++i)
{
if (joint->motion[i] != PxArticulationMotion::eLOCKED)
{
Cm::UnAlignedSpatialVector axis = Cm::UnAlignedSpatialVector::Zero();
//axis is in the local space of joint
axis[i] = 1.f;
jointAxis[dof] = axis;
joint->invDofIds[i] = dof;
joint->dofIds[dof] = i;
if (joint->motion[i] == PxArticulationMotion::eLIMITED)
limitMask |= 1 << dof;
dof++;
}
}
}
return dof;
}
PX_FORCE_INLINE void setArmature(ArticulationJointCore* joint)
{
if (joint->jointDirtyFlag & ArticulationJointCoreDirtyFlag::eARMATURE)
{
for (PxU32 i = 0; i < dof; ++i)
{
PxU32 ind = joint->dofIds[i];
armature[i] = joint->armature[ind];
}
joint->jointDirtyFlag &= ~ArticulationJointCoreDirtyFlag::eARMATURE;
}
}
PxU32 jointOffset; //4
PxReal armature[3]; // indexed by internal dof id.
//degree of freedom
PxU8 dof; //1
PxU8 dofInternalConstraintMask; //1
PxU8 limitMask; //1
};
}//namespace Dy
}
#endif
| 4,452 | C | 29.087838 | 132 | 0.68239 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyArticulationTendon.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 PXD_ARTICULATION_TENDON_H
#define PXD_ARTICULATION_TENDON_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxUtilities.h"
#include "CmUtils.h"
#include "CmIDPool.h"
#include "solver/PxSolverDefs.h"
namespace physx
{
namespace Dy
{
typedef PxU64 ArticulationAttachmentBitField;
#define DY_ARTICULATION_ATTACHMENT_NONE 0xffffffff
struct ArticulationAttachment
{
PxVec3 relativeOffset; //relative offset to the link
PxReal lowLimit;
PxReal highLimit;
PxReal restLength;
PxReal coefficient;
PxU32 parent; //parent index
PxU32 myInd;
PxU32 mConstraintInd;
PxU16 linkInd;
PxU16 childCount;
ArticulationAttachmentBitField children;
};
class ArticulationTendon
{
public:
ArticulationTendon() : mStiffness(0.f), mDamping(0.f), mOffset(0.f), mLimitStiffness(0.f)
{
}
PxReal mStiffness;
PxReal mDamping;
PxReal mOffset;
PxReal mLimitStiffness;
};
class ArticulationSpatialTendon : public ArticulationTendon
{
public:
ArticulationSpatialTendon()
{
mAttachments.reserve(64);
mAttachments.forceSize_Unsafe(64);
}
PX_FORCE_INLINE ArticulationAttachment* getAttachments() { return mAttachments.begin(); }
PX_FORCE_INLINE ArticulationAttachment& getAttachment(const PxU32 index) { return mAttachments[index]; }
PX_FORCE_INLINE PxU32 getNumAttachments() { return mIDPool.getNumUsedID(); }
PX_FORCE_INLINE PxU32 getNewID()
{
const PxU32 index = mIDPool.getNewID();
if (mAttachments.capacity() <= index)
{
mAttachments.resize(index * 2 + 1);
}
return index;
}
PX_FORCE_INLINE void freeID(const PxU32 index)
{
mIDPool.freeID(index);
}
PX_FORCE_INLINE PxU32 getTendonIndex() { return mIndex; }
PX_FORCE_INLINE void setTendonIndex(const PxU32 index) { mIndex = index; }
private:
PxArray<ArticulationAttachment> mAttachments;
Cm::IDPool mIDPool;
PxU32 mIndex;
};
class ArticulationTendonJoint
{
public:
PxU16 axis;
PxU16 startJointOffset;
PxReal coefficient;
PxReal recipCoefficient;
PxU32 mConstraintInd;
PxU32 parent; //parent index
PxU16 linkInd;
PxU16 childCount;
ArticulationAttachmentBitField children;
};
class ArticulationFixedTendon : public ArticulationTendon
{
public:
ArticulationFixedTendon() :mLowLimit(PX_MAX_F32), mHighLimit(-PX_MAX_F32), mRestLength(0.f)
{
mTendonJoints.reserve(64);
mTendonJoints.forceSize_Unsafe(64);
}
PX_FORCE_INLINE ArticulationTendonJoint* getTendonJoints() { return mTendonJoints.begin(); }
PX_FORCE_INLINE ArticulationTendonJoint& getTendonJoint(const PxU32 index) { return mTendonJoints[index]; }
PX_FORCE_INLINE PxU32 getNumJoints() { return mIDPool.getNumUsedID(); }
PX_FORCE_INLINE PxU32 getNewID()
{
const PxU32 index = mIDPool.getNewID();
if (mTendonJoints.capacity() <= index)
{
mTendonJoints.resize(index * 2 + 1);
}
return index;
}
PX_FORCE_INLINE void freeID(const PxU32 index)
{
mIDPool.freeID(index);
}
PX_FORCE_INLINE PxU32 getTendonIndex() { return mIndex; }
PX_FORCE_INLINE void setTendonIndex(const PxU32 index) { mIndex = index; }
PxReal mLowLimit;
PxReal mHighLimit;
PxReal mRestLength;
PxReal mError;
private:
PxArray<ArticulationTendonJoint> mTendonJoints;
Cm::IDPool mIDPool;
PxU32 mIndex;
};
}//namespace Dy
}//namespace physx
#endif
| 5,281 | C | 26.367876 | 109 | 0.723727 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyArticulationCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_ARTICULATION_CORE_H
#define DY_ARTICULATION_CORE_H
#include "PxArticulationReducedCoordinate.h"
namespace physx
{
namespace Dy
{
struct ArticulationCore
{
// PX_SERIALIZATION
ArticulationCore(const PxEMPTY) : flags(PxEmpty) {}
ArticulationCore() {}
//~PX_SERIALIZATION
PxU16 solverIterationCounts; //KS - made a U16 so that it matches PxsRigidCore
PxArticulationFlags flags;
PxReal sleepThreshold;
PxReal freezeThreshold;
PxReal wakeCounter;
PxU32 gpuRemapIndex;
PxReal maxLinearVelocity;
PxReal maxAngularVelocity;
};
struct ArticulationJointCoreDirtyFlag
{
enum Enum
{
eNONE = 0,
eMOTION = 1 << 0,
eFRAME = 1 << 1,
eTARGETPOSE = 1 << 2,
eTARGETVELOCITY = 1 << 3,
eARMATURE = 1 << 4,
eALL = eMOTION | eFRAME | eTARGETPOSE | eTARGETVELOCITY | eARMATURE
};
};
typedef PxFlags<ArticulationJointCoreDirtyFlag::Enum, PxU8> ArticulationJointCoreDirtyFlags;
PX_FLAGS_OPERATORS(ArticulationJointCoreDirtyFlag::Enum, PxU8)
}
}
#endif
| 2,757 | C | 35.289473 | 94 | 0.738121 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_CONTEXT_H
#define DY_CONTEXT_H
#include "PxSceneDesc.h"
#include "DyThresholdTable.h"
#include "PxcNpThreadContext.h"
#include "PxsSimulationController.h"
#include "DyConstraintWriteBack.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
class PxcNpMemBlockPool;
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
}
class PxcScratchAllocator;
struct PxvSimStats;
class PxTaskManager;
class PxsContactManager;
struct PxsContactManagerOutputCounts;
class PxvNphaseImplementationContext;
namespace Dy
{
class Context : public PxUserAllocated
{
PX_NOCOPY(Context)
public:
// PT: TODO: consider making all of these public at this point
// PT: please avoid useless comments like "returns Blah" for a function called "getBlah".
PX_FORCE_INLINE PxReal getMaxBiasCoefficient() const { return mMaxBiasCoefficient; }
PX_FORCE_INLINE void setMaxBiasCoefficient(PxReal coeff) { mMaxBiasCoefficient = coeff; }
PX_FORCE_INLINE PxReal getCorrelationDistance() const { return mCorrelationDistance; }
PX_FORCE_INLINE void setCorrelationDistance(PxReal f) { mCorrelationDistance = f; }
PX_FORCE_INLINE PxReal getBounceThreshold() const { return mBounceThreshold; }
PX_FORCE_INLINE void setBounceThreshold(PxReal f) { mBounceThreshold = f; }
PX_FORCE_INLINE PxReal getFrictionOffsetThreshold() const { return mFrictionOffsetThreshold; }
PX_FORCE_INLINE void setFrictionOffsetThreshold(PxReal offset) { mFrictionOffsetThreshold = offset; }
PX_FORCE_INLINE PxReal getCCDSeparationThreshold() const { return mCCDSeparationThreshold; }
PX_FORCE_INLINE void setCCDSeparationThreshold(PxReal offset) { mCCDSeparationThreshold = offset; }
PX_FORCE_INLINE PxU32 getSolverBatchSize() const { return mSolverBatchSize; }
PX_FORCE_INLINE void setSolverBatchSize(PxU32 f) { mSolverBatchSize = f; }
PX_FORCE_INLINE PxU32 getSolverArticBatchSize() const { return mSolverArticBatchSize; }
PX_FORCE_INLINE void setSolverArticBatchSize(PxU32 f) { mSolverArticBatchSize = f; }
PX_FORCE_INLINE PxFrictionType::Enum getFrictionType() const { return mFrictionType; }
PX_FORCE_INLINE void setFrictionType(PxFrictionType::Enum f) { mFrictionType = f; }
PX_FORCE_INLINE PxReal getDt() const { return mDt; }
PX_FORCE_INLINE void setDt(const PxReal dt) { mDt = dt; }
// PT: TODO: we have a setDt function but it doesn't set the inverse dt, what's the story here?
PX_FORCE_INLINE PxReal getInvDt() const { return mInvDt; }
//Forces any cached body state to be updated!
PX_FORCE_INLINE void setStateDirty(bool dirty) { mBodyStateDirty = dirty; }
PX_FORCE_INLINE bool isStateDirty() const { return mBodyStateDirty; }
// Returns the maximum solver constraint size in this island in bytes.
PX_FORCE_INLINE PxU32 getMaxSolverConstraintSize() const { return mMaxSolverConstraintSize; }
PX_FORCE_INLINE PxReal getLengthScale() const { return mLengthScale; }
PX_FORCE_INLINE const PxVec3& getGravity() const { return mGravity; }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
PX_FORCE_INLINE ThresholdStream& getThresholdStream() { return *mThresholdStream; }
PX_FORCE_INLINE ThresholdStream& getForceChangedThresholdStream() { return *mForceChangedThresholdStream; }
PX_FORCE_INLINE ThresholdTable& getThresholdTable() { return mThresholdTable; }
void createThresholdStream(PxVirtualAllocatorCallback& callback) { PX_ASSERT(!mThresholdStream); mThresholdStream = PX_NEW(ThresholdStream)(callback); }
void createForceChangeThresholdStream(PxVirtualAllocatorCallback& callback) { PX_ASSERT(!mForceChangedThresholdStream); mForceChangedThresholdStream = PX_NEW(ThresholdStream)(callback); }
PX_FORCE_INLINE PxcDataStreamPool& getContactStreamPool() { return mContactStreamPool; }
PX_FORCE_INLINE PxcDataStreamPool& getPatchStreamPool() { return mPatchStreamPool; }
PX_FORCE_INLINE PxcDataStreamPool& getForceStreamPool() { return mForceStreamPool; }
PX_FORCE_INLINE PxPinnedArray<Dy::ConstraintWriteback>& getConstraintWriteBackPool() { return mConstraintWriteBackPool; }
/**
\brief Destroys this dynamics context
*/
virtual void destroy() = 0;
/**
\brief The entry point for the constraint solver.
\param[in] dt The simulation time-step
\param[in] continuation The continuation task for the solver
\param[in] processLostTouchTask The task that processes lost touches
This method is called after the island generation has completed. Its main responsibilities are:
(1) Reserving the solver body pools
(2) Initializing the static and kinematic solver bodies, which are shared resources between islands.
(3) Construct the solver task chains for each island
Each island is solved as an independent solver task chain. In addition, large islands may be solved using multiple parallel tasks.
Island solving is asynchronous. Once all islands have been solved, the continuation task will be called.
*/
virtual void update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* processLostTouchTask,
PxvNphaseImplementationContext* nPhaseContext, PxU32 maxPatchesPerCM, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& changedHandleMap) = 0;
virtual void processLostPatches(IG::SimpleIslandManager& /*simpleIslandManager*/, PxsContactManager** /*lostPatchManagers*/, PxU32 /*nbLostPatchManagers*/, PxsContactManagerOutputCounts* /*outCounts*/) {}
virtual void processFoundPatches(IG::SimpleIslandManager& /*simpleIslandManager*/, PxsContactManager** /*foundPatchManagers*/, PxU32 /*nbFoundPatchManagers*/, PxsContactManagerOutputCounts* /*outCounts*/) {}
/**
\brief This method copy gpu solver body data to cpu body core
*/
virtual void updateBodyCore(PxBaseTask* /*continuation*/) {}
/**
\brief Called after update's task chain has completed. This collects the results of the solver together.
This method combines the results of several islands, e.g. constructing scene-level simulation statistics and merging together threshold streams for contact notification.
*/
virtual void mergeResults() = 0;
virtual void setSimulationController(PxsSimulationController* simulationController) = 0;
virtual void getDataStreamBase(void*& /*contactStreamBase*/, void*& /*patchStreamBase*/, void*& /*forceAndIndicesStreamBase*/) {}
virtual PxSolverType::Enum getSolverType() const = 0;
protected:
Context(IG::SimpleIslandManager* islandManager, PxVirtualAllocatorCallback* allocatorCallback,
PxvSimStats& simStats, bool enableStabilization, bool useEnhancedDeterminism,
PxReal maxBiasCoefficient, PxReal lengthScale, PxU64 contextID) :
mThresholdStream (NULL),
mForceChangedThresholdStream(NULL),
mIslandManager (islandManager),
mDt (1.0f),
mInvDt (1.0f),
mMaxBiasCoefficient (maxBiasCoefficient),
mEnableStabilization (enableStabilization),
mUseEnhancedDeterminism (useEnhancedDeterminism),
mBounceThreshold (-2.0f),
mLengthScale (lengthScale),
mSolverBatchSize (32),
mConstraintWriteBackPool (PxVirtualAllocator(allocatorCallback)),
mSimStats (simStats),
mContextID (contextID),
mBodyStateDirty (false)
{
}
virtual ~Context()
{
PX_DELETE(mThresholdStream);
PX_DELETE(mForceChangedThresholdStream);
}
ThresholdStream* mThresholdStream;
ThresholdStream* mForceChangedThresholdStream;
ThresholdTable mThresholdTable;
IG::SimpleIslandManager* mIslandManager;
PxsSimulationController* mSimulationController;
/**
\brief Time-step.
*/
PxReal mDt;
/**
\brief 1/time-step.
*/
PxReal mInvDt;
PxReal mMaxBiasCoefficient;
const bool mEnableStabilization;
const bool mUseEnhancedDeterminism;
PxVec3 mGravity;
/**
\brief max solver constraint size
*/
PxU32 mMaxSolverConstraintSize;
/**
\brief Threshold controlling the relative velocity at which the solver transitions between restitution and bias for solving normal contact constraint.
*/
PxReal mBounceThreshold;
/**
\brief Threshold controlling whether friction anchors are constructed or not. If the separation is above mFrictionOffsetThreshold, the contact will not be considered to become a friction anchor
*/
PxReal mFrictionOffsetThreshold;
/**
\brief Threshold controlling whether distant contacts are processed using bias, restitution or a combination of the two. This only has effect on pairs involving bodies that have enabled speculative CCD simulation mode.
*/
PxReal mCCDSeparationThreshold;
/**
\brief Threshold for controlling friction correlation
*/
PxReal mCorrelationDistance;
/**
\brief The length scale from PxTolerancesScale::length.
*/
PxReal mLengthScale;
/**
\brief The minimum size of an island to generate a solver task chain.
*/
PxU32 mSolverBatchSize;
/**
\brief The minimum number of articulations required to generate a solver task chain.
*/
PxU32 mSolverArticBatchSize;
/**
\brief The current friction model being used
*/
PxFrictionType::Enum mFrictionType;
/**
\brief Structure to encapsulate contact stream allocations. Used by GPU solver to reference pre-allocated pinned host memory
*/
PxcDataStreamPool mContactStreamPool;
/**
\brief Struct to encapsulate the contact patch stream allocations. Used by GPU solver to reference pre-allocated pinned host memory
*/
PxcDataStreamPool mPatchStreamPool;
/**
\brief Structure to encapsulate force stream allocations. Used by GPU solver to reference pre-allocated pinned host memory for force reports.
*/
PxcDataStreamPool mForceStreamPool;
/**
\brief Structure to encapsulate constraint write back allocations. Used by GPU/CPU solver to reference pre-allocated pinned host memory for breakable joint reports.
*/
PxPinnedArray<Dy::ConstraintWriteback> mConstraintWriteBackPool;
PxvSimStats& mSimStats;
const PxU64 mContextID;
bool mBodyStateDirty;
};
Context* createDynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool,
PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback, PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager, PxU64 contextID, bool enableStabilization, bool useEnhancedDeterminism,
PxReal maxBiasCoefficient, bool frictionEveryIteration, PxReal lengthScale);
Context* createTGSDynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool,
PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback, PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager, PxU64 contextID, bool enableStabilization, bool useEnhancedDeterminism, PxReal lengthScale);
}
}
#endif
| 12,823 | C | 41.18421 | 219 | 0.763394 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyFEMClothCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 PXDV_FEMCLOTH_CORE_H
#define PXDV_FEMCLOTH_CORE_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxTransform.h"
#include "foundation/PxArray.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#endif
#include "PxFEMParameter.h"
#include "PxFEMClothFlags.h"
#include "PxsFEMClothMaterialCore.h"
namespace physx
{
namespace Dy
{
struct FEMClothCore
{
public:
PxFEMParameters parameters;
PxU16 solverIterationCounts;
bool dirty;
PxReal wakeCounter;
PxFEMClothFlags mFlags;
PxFEMClothDataFlags mDirtyFlags;
PxArray<PxU16> mMaterialHandles;
// device pointers
PxVec4* mPositionInvMass;
PxVec4* mVelocity;
PxVec4* mRestPosition;
// multimaterial bending effects
PxArray<PxReal> mBendingScales;
PxReal maxVelocity;
PxReal maxDepenetrationVelocity;
// negative values mean no activation angle: apply bending force toward rest bending angle
PxReal mBendingActivationAngle;
// number of collision pair updates per timestep. Collision pair is updated at least once per timestep and increasing the frequency provides better collision pairs.
PxU32 nbCollisionPairUpdatesPerTimestep;
// number of collision substeps in each sub-timestep. Collision constraints can be applied multiple times in each sub-timestep.
PxU32 nbCollisionSubsteps;
FEMClothCore()
{
maxVelocity = 0.f;
maxDepenetrationVelocity = 0.f;
mBendingActivationAngle = -1.f;
nbCollisionPairUpdatesPerTimestep = 1;
nbCollisionSubsteps = 1;
dirty = 0;
mDirtyFlags = PxFEMClothDataFlags(0);
}
void setMaterial(const PxU16 materialHandle)
{
mMaterialHandles.pushBack(materialHandle);
}
void clearMaterials() { mMaterialHandles.clear(); }
};
}
}
#endif
| 3,471 | C | 33.039215 | 167 | 0.730625 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DySoftBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 DY_SOFTBODY_H
#define DY_SOFTBODY_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxPinnedArray.h"
#include "DySoftBodyCore.h"
#include "PxvGeometry.h"
namespace physx
{
namespace Sc
{
class SoftBodySim;
}
namespace Dy
{
typedef size_t SoftBodyHandle;
struct SoftBodyCore;
typedef PxPinnedArray<PxU64> SoftBodyFilterArray;
class SoftBody
{
PX_NOCOPY(SoftBody)
public:
SoftBody(Sc::SoftBodySim* sim, Dy::SoftBodyCore& core) :
mSoftBodySoftBodyFilterPairs(NULL), mSim(sim), mCore(core), mElementId(0xffffffff), mGpuRemapId(0xffffffff)
{
mFilterDirty = false;
mFilterInDirtyList = false;
mDirtySoftBodyForFilterPairs = NULL;
mSoftBodySoftBodyFilterPairs = NULL;
}
~SoftBody()
{
if (mDirtySoftBodyForFilterPairs)
{
Dy::SoftBody** dirtySoftBodies = mDirtySoftBodyForFilterPairs->begin();
const PxU32 size = mDirtySoftBodyForFilterPairs->size();
for (PxU32 i = 0; i < size; ++i)
{
if (dirtySoftBodies[i] == this)
{
dirtySoftBodies[i] = NULL;
}
}
if (mSoftBodySoftBodyFilterPairs)
PX_FREE(mSoftBodySoftBodyFilterPairs);
}
}
PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; }
PX_FORCE_INLINE Sc::SoftBodySim* getSoftBodySim() const { return mSim; }
PX_FORCE_INLINE void setGpuRemapId(const PxU32 remapId)
{
mGpuRemapId = remapId;
PxTetrahedronMeshGeometryLL& geom = mShapeCore->mGeometry.get<PxTetrahedronMeshGeometryLL>();
geom.materialsLL.gpuRemapId = remapId;
}
PX_FORCE_INLINE PxU32 getGpuRemapId() { return mGpuRemapId; }
PX_FORCE_INLINE void setElementId(const PxU32 elementId) { mElementId = elementId; }
PX_FORCE_INLINE PxU32 getElementId() { return mElementId; }
PX_FORCE_INLINE PxsShapeCore& getShapeCore() { return *mShapeCore; }
PX_FORCE_INLINE void setShapeCore(PxsShapeCore* shapeCore) { mShapeCore = shapeCore; }
PX_FORCE_INLINE void setSimShapeCore(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState)
{
mSimulationMesh = simulationMesh;
mSoftBodyAuxData = simulationState;
}
PX_FORCE_INLINE const PxTetrahedronMesh* getCollisionMesh() const { return mShapeCore->mGeometry.get<PxTetrahedronMeshGeometryLL>().tetrahedronMesh; }
PX_FORCE_INLINE PxTetrahedronMesh* getCollisionMesh() { return mShapeCore->mGeometry.get<PxTetrahedronMeshGeometryLL>().tetrahedronMesh; }
PX_FORCE_INLINE const PxTetrahedronMesh* getSimulationMesh() const { return mSimulationMesh; }
PX_FORCE_INLINE PxTetrahedronMesh* getSimulationMesh() { return mSimulationMesh; }
PX_FORCE_INLINE const PxSoftBodyAuxData* getSoftBodyAuxData() const { return mSoftBodyAuxData; }
PX_FORCE_INLINE PxSoftBodyAuxData* getSoftBodyAuxData() { return mSoftBodyAuxData; }
PX_FORCE_INLINE const SoftBodyCore& getCore() const { return mCore; }
PX_FORCE_INLINE SoftBodyCore& getCore() { return mCore; }
PX_FORCE_INLINE PxU16 getIterationCounts() const { return mCore.solverIterationCounts; }
PX_FORCE_INLINE PxU32 getGpuSoftBodyIndex() const { return mGpuRemapId; }
//These variables are used in the constraint partition
PxU16 maxSolverFrictionProgress;
PxU16 maxSolverNormalProgress;
PxU32 solverProgress;
PxU8 numTotalConstraints;
PxArray<PxU32> mParticleSoftBodyAttachments;
PxArray<PxU32> mRigidSoftBodyAttachments;
PxArray<PxU32> mClothSoftBodyAttachments;
PxArray<PxU32> mSoftSoftBodyAttachments;
SoftBodyFilterArray* mSoftBodySoftBodyFilterPairs;
PxArray <Dy::SoftBody*>* mDirtySoftBodyForFilterPairs; //pointer to the array of mDirtySoftBodyForFilterPairs in PxgSimulationController.cpp
PxArray<PxU32> mSoftBodySoftBodyAttachmentIdReferences;
bool mFilterDirty;
bool mFilterInDirtyList;
private:
Sc::SoftBodySim* mSim;
SoftBodyCore& mCore;
PxsShapeCore* mShapeCore;
PxTetrahedronMesh* mSimulationMesh;
PxSoftBodyAuxData* mSoftBodyAuxData;
PxU32 mElementId; //this is used for the bound array, contactDist
PxU32 mGpuRemapId;
};
PX_FORCE_INLINE SoftBody* getSoftBody(SoftBodyHandle handle)
{
return reinterpret_cast<SoftBody*>(handle);
}
}
}
#endif
| 5,824 | C | 33.880239 | 153 | 0.747596 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DySoftBodyCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 DY_SOFTBODY_CORE_H
#define DY_SOFTBODY_CORE_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxTransform.h"
#include "PxSoftBody.h"
#include "PxSoftBodyFlag.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "foundation/PxArray.h"
namespace physx
{
namespace Dy
{
struct SoftBodyCore
{
public:
PxQuat initialRotation;
PxFEMParameters parameters;
PxReal sleepThreshold;
PxReal freezeThreshold;
PxReal wakeCounter;
PxReal maxPenBias;
PxU16 solverIterationCounts; //vel iters are in low word and pos iters in high word.
bool dirty;
PxSoftBodyFlags mFlags;
PxSoftBodyDataFlags mDirtyFlags;
void setMaterial(const PxU16 materialHandle)
{
mMaterialHandles.pushBack(materialHandle);
}
void clearMaterials() { mMaterialHandles.clear(); }
PxArray<PxU16> mMaterialHandles;
//device - managed by PhysX
PxVec4* mPositionInvMass; // collision mesh positions, alloc on attachShape(), dealloc detachShape()
PxVec4* mRestPosition; // collision mesh rest positions, alloc on attachShape(), dealloc detachShape()
PxVec4* mSimPositionInvMass; // simulation mesh positions, alloc on attachSimulationMesh(), dealloc detachSimulationMesh()
PxVec4* mSimVelocity; // simulation mesh velocities, alloc on attachSimulationMesh(), dealloc detachSimulationMesh()
// device - just the pointer, user responsible.
const PxVec4* mKinematicTarget;
};
}
}
#endif
| 3,086 | C | 37.111111 | 131 | 0.741737 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyParticleSystemCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 DY_PARTICLESYSTEM_CORE_H
#define DY_PARTICLESYSTEM_CORE_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxTransform.h"
#include "foundation/PxArray.h"
#include "foundation/PxMemory.h"
#include "PxParticleSystem.h"
#include "PxParticleBuffer.h"
#include "CmIDPool.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFLIPParticleSystem.h"
#include "PxMPMParticleSystem.h"
#endif
#include "PxParticleSolverType.h"
#include "PxSparseGridParams.h"
namespace physx
{
namespace Dy
{
class ParticleSystemCore
{
public:
PxReal sleepThreshold;
PxReal freezeThreshold;
PxReal wakeCounter;
PxU32 gridSizeX;
PxU32 gridSizeY;
PxU32 gridSizeZ;
PxParticleSolverType::Enum solverType;
bool enableCCD;
PxU16 solverIterationCounts;
PxSparseGridParams sparseGridParams;
PxReal restOffset;
PxReal particleContactOffset;
PxReal particleContactOffset_prev;
PxReal solidRestOffset;
PxReal fluidRestOffset;
PxReal fluidRestOffset_prev;
PxReal fluidBoundaryDensityScale;
PxReal maxDepenetrationVelocity;
PxReal maxVelocity;
PxParticleFlags mFlags;
PxVec3 mWind;
PxU32 mMaxNeighborhood;
PxArray<PxU16> mPhaseGroupToMaterialHandle;
PxArray<PxU16> mUniqueMaterialHandles; //just for reporting
void addParticleBuffer(PxParticleBuffer* particleBuffer)
{
if (particleBuffer->bufferIndex == 0xffffffff)
{
switch (particleBuffer->getConcreteType())
{
case (PxConcreteType::ePARTICLE_BUFFER):
{
particleBuffer->bufferIndex = mParticleBuffers.size();
mParticleBuffers.pushBack(particleBuffer);
mParticleBufferUpdate = true;
particleBuffer->setInternalData(this);
return;
}
case (PxConcreteType::ePARTICLE_DIFFUSE_BUFFER):
{
particleBuffer->bufferIndex = mParticleAndDiffuseBuffers.size();
mParticleAndDiffuseBuffers.pushBack(reinterpret_cast<PxParticleAndDiffuseBuffer*>(particleBuffer));
mParticleAndDiffuseBufferUpdate = true;
particleBuffer->setInternalData(this);
return;
}
case (PxConcreteType::ePARTICLE_CLOTH_BUFFER):
{
particleBuffer->bufferIndex = mClothBuffers.size();
mClothBuffers.pushBack(reinterpret_cast<PxParticleClothBuffer*>(particleBuffer));
mClothBufferUpdate = true;
particleBuffer->setInternalData(this);
return;
}
case (PxConcreteType::ePARTICLE_RIGID_BUFFER):
{
particleBuffer->bufferIndex = mRigidBuffers.size();
mRigidBuffers.pushBack(reinterpret_cast<PxParticleRigidBuffer*>(particleBuffer));
mRigidBufferUpdate = true;
particleBuffer->setInternalData(this);
return;
}
default:
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "addParticleBuffer : Error, this buffer does not have a valid type!");
return;
}
}
}
else
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "addParticleBuffer : Error, this buffer cannot be added to multiple particle systems!");
}
}
void removeParticleBuffer(PxParticleBuffer* particleBuffer)
{
const PxU32 index = particleBuffer->bufferIndex;
switch (particleBuffer->getConcreteType())
{
case (PxConcreteType::ePARTICLE_BUFFER):
{
if (index < mParticleBuffers.size())
{
mParticleBuffers.replaceWithLast(particleBuffer->bufferIndex);
if (mParticleBuffers.size() > index)
mParticleBuffers[index]->bufferIndex = index;
mParticleBufferUpdate = true;
particleBuffer->bufferIndex = 0xffffffff;
particleBuffer->onParticleSystemDestroy();
}
return;
}
case (PxConcreteType::ePARTICLE_DIFFUSE_BUFFER):
{
if (index < mParticleAndDiffuseBuffers.size())
{
mParticleAndDiffuseBuffers.replaceWithLast(particleBuffer->bufferIndex);
if (mParticleAndDiffuseBuffers.size() > index)
mParticleAndDiffuseBuffers[index]->bufferIndex = index;
mParticleAndDiffuseBufferUpdate = true;
particleBuffer->bufferIndex = 0xffffffff;
particleBuffer->onParticleSystemDestroy();
}
return;
}
case (PxConcreteType::ePARTICLE_CLOTH_BUFFER):
{
if (index < mClothBuffers.size())
{
mClothBuffers.replaceWithLast(particleBuffer->bufferIndex);
if (mClothBuffers.size() > index)
mClothBuffers[index]->bufferIndex = index;
mClothBufferUpdate = true;
particleBuffer->bufferIndex = 0xffffffff;
particleBuffer->onParticleSystemDestroy();
}
return;
}
case (PxConcreteType::ePARTICLE_RIGID_BUFFER):
{
if (index < mParticleBuffers.size())
{
mRigidBuffers.replaceWithLast(particleBuffer->bufferIndex);
if (mRigidBuffers.size() > index)
mRigidBuffers[index]->bufferIndex = index;
mRigidBufferUpdate = true;
particleBuffer->bufferIndex = 0xffffffff;
particleBuffer->onParticleSystemDestroy();
}
return;
}
default:
{
PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "removeParticleBuffer : Error, this buffer does not have a valid type!");
return;
}
}
}
PxU32 getNumUserBuffers() const { return mParticleBuffers.size() + mClothBuffers.size() + mRigidBuffers.size() + mParticleAndDiffuseBuffers.size(); }
//device
PxArray<PxParticleBuffer*> mParticleBuffers;
PxArray<PxParticleClothBuffer*> mClothBuffers;
PxArray<PxParticleRigidBuffer*> mRigidBuffers;
PxArray<PxParticleAndDiffuseBuffer*> mParticleAndDiffuseBuffers;
bool mParticleBufferUpdate;
bool mClothBufferUpdate;
bool mRigidBufferUpdate;
bool mParticleAndDiffuseBufferUpdate;
PxParticleSystemCallback* mCallback;
ParticleSystemCore()
{
PxMemSet(this, 0, sizeof(*this));
mParticleBufferUpdate = false;
mClothBufferUpdate = false;
mRigidBufferUpdate = false;
mParticleAndDiffuseBufferUpdate = false;
}
~ParticleSystemCore()
{
for(PxU32 i = 0; i < mParticleBuffers.size(); ++i)
{
mParticleBuffers[i]->onParticleSystemDestroy();
}
for (PxU32 i = 0; i < mClothBuffers.size(); ++i)
{
mClothBuffers[i]->onParticleSystemDestroy();
}
for (PxU32 i = 0; i < mRigidBuffers.size(); ++i)
{
mRigidBuffers[i]->onParticleSystemDestroy();
}
for (PxU32 i = 0; i < mParticleAndDiffuseBuffers.size(); ++i)
{
mParticleAndDiffuseBuffers[i]->onParticleSystemDestroy();
}
}
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
//Leave these members at the end to remain binary compatible with public builds
PxFLIPParams flipParams;
PxMPMParams mpmParams;
#endif
};
} // namespace Dy
} // namespace physx
#endif
| 8,152 | C | 28.327338 | 155 | 0.727797 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyFEMCloth.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 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 PXD_FEMCLOTH_H
#define PXD_FEMCLOTH_H
#include "foundation/PxSimpleTypes.h"
#include "DyFEMClothCore.h"
#include "PxvGeometry.h"
namespace physx
{
namespace Sc
{
class FEMClothSim;
}
namespace Dy
{
typedef size_t FEMClothHandle;
struct FEMClothCore;
class FEMCloth
{
PX_NOCOPY(FEMCloth)
public:
FEMCloth(Sc::FEMClothSim* sim, Dy::FEMClothCore& core) :
mSim(sim), mCore(core), mElementId(0xffffffff), mGpuRemapId(0xffffffff)
{}
~FEMCloth() {}
//PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; }
PX_FORCE_INLINE Sc::FEMClothSim* getFEMClothSim() const { return mSim; }
PX_FORCE_INLINE void setGpuRemapId(const PxU32 remapId)
{
mGpuRemapId = remapId;
PxTriangleMeshGeometryLL& geom = mShapeCore->mGeometry.get<PxTriangleMeshGeometryLL>();
geom.materialsLL.gpuRemapId = remapId;
}
PX_FORCE_INLINE PxTriangleMesh* getTriangleMesh()
{
PxTriangleMeshGeometryLL& geom = mShapeCore->mGeometry.get<PxTriangleMeshGeometryLL>();
return geom.triangleMesh;
}
PX_FORCE_INLINE PxU32 getGpuRemapId() { return mGpuRemapId; }
PX_FORCE_INLINE void setElementId(const PxU32 elementId) { mElementId = elementId; }
PX_FORCE_INLINE PxU32 getElementId() { return mElementId; }
PX_FORCE_INLINE PxsShapeCore& getShapeCore() { return *mShapeCore; }
PX_FORCE_INLINE void setShapeCore(PxsShapeCore* shapeCore) { mShapeCore = shapeCore; }
PX_FORCE_INLINE const FEMClothCore& getCore() const { return mCore; }
PX_FORCE_INLINE FEMClothCore& getCore() { return mCore; }
PX_FORCE_INLINE PxU16 getIterationCounts() const { return mCore.solverIterationCounts; }
void addAttachmentHandle(PxU32 handle);
void removeAttachmentHandle(PxU32 handle);
//These variables are used in the constraint partition
PxU16 maxSolverFrictionProgress;
PxU16 maxSolverNormalProgress;
PxU32 solverProgress;
PxU8 numTotalConstraints;
PxArray<PxU32> mAttachmentHandles;
PxArray<PxU32> mClothClothAttachments;
private:
Sc::FEMClothSim* mSim;
FEMClothCore& mCore;
PxsShapeCore* mShapeCore;
PxU32 mElementId; //this is used for the bound array, contactDist
PxU32 mGpuRemapId;
};
struct FEMClothSolverDesc
{
FEMCloth* femCloth;
};
PX_FORCE_INLINE FEMCloth* getFEMCloth(FEMClothHandle handle)
{
return reinterpret_cast<FEMCloth*>(handle);
}
PX_FORCE_INLINE void FEMCloth::addAttachmentHandle(PxU32 handle)
{
mAttachmentHandles.pushBack(handle);
}
PX_FORCE_INLINE void FEMCloth::removeAttachmentHandle(PxU32 handle)
{
for (PxU32 i = 0; i < mAttachmentHandles.size(); ++i)
{
if (mAttachmentHandles[i] == handle)
{
mAttachmentHandles.replaceWithLast(i);
}
}
}
}
}
#endif | 4,411 | C | 30.971014 | 95 | 0.728406 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyVArticulation.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_V_ARTICULATION_H
#define DY_V_ARTICULATION_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxUtilities.h"
#include "CmUtils.h"
#include "CmSpatialVector.h"
#include "foundation/PxMemory.h"
#include "DyArticulationCore.h"
#include "DyArticulationJointCore.h"
namespace physx
{
struct PxsBodyCore;
class PxsConstraintBlockManager;
class PxsContactManagerOutputIterator;
struct PxSolverConstraintDesc;
struct PxSolverBodyData;
class PxContactJoint;
struct PxTGSSolverBodyData;
struct PxTGSSolverBodyTxInertia;
struct PxSolverConstraintDesc;
namespace Dy
{
struct SpatialSubspaceMatrix;
struct ConstraintWriteback;
class ThreadContext;
static const size_t DY_ARTICULATION_TENDON_MAX_SIZE = 64;
struct Constraint;
class Context;
class ArticulationSpatialTendon;
class ArticulationFixedTendon;
class ArticulationTendonJoint;
struct ArticulationSensor;
struct ArticulationLoopConstraint
{
public:
PxU32 linkIndex0;
PxU32 linkIndex1;
Dy::Constraint* constraint;
};
#define DY_ARTICULATION_LINK_NONE 0xffffffff
typedef PxU64 ArticulationBitField;
struct ArticulationLink
{
ArticulationBitField children; // child bitmap
ArticulationBitField pathToRoot; // path to root, including link and root
PxU32 mPathToRootStartIndex;
PxU32 mChildrenStartIndex;
PxU16 mPathToRootCount;
PxU16 mNumChildren;
PxsBodyCore* bodyCore;
ArticulationJointCore* inboundJoint;
PxU32 parent;
PxReal cfm;
};
class FeatherstoneArticulation;
struct ArticulationSolverDesc
{
void initData(ArticulationCore* core_, const PxArticulationFlags* flags_)
{
articulation = NULL;
links = NULL;
motionVelocity = NULL;
acceleration = NULL;
poses = NULL;
deltaQ = NULL;
core = core_;
flags = flags_;
linkCount = 0;
numInternalConstraints = 0;
}
FeatherstoneArticulation* articulation;
ArticulationLink* links;
Cm::SpatialVectorV* motionVelocity;
Cm::SpatialVector* acceleration;
PxTransform* poses;
PxQuat* deltaQ;
ArticulationCore* core;
const PxArticulationFlags* flags; // PT: PX-1399
PxU8 linkCount;
PxU8 numInternalConstraints;
};
}
}
#endif
| 4,119 | C | 28.640288 | 78 | 0.738772 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyArticulationJointCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_ARTICULATION_JOINT_CORE_H
#define DY_ARTICULATION_JOINT_CORE_H
#include "DyArticulationCore.h"
#include "solver/PxSolverDefs.h"
#include "PxArticulationJointReducedCoordinate.h"
#include "CmSpatialVector.h"
namespace physx
{
namespace Dy
{
class ArticulationJointCoreData;
PX_ALIGN_PREFIX(16)
struct ArticulationJointCore
{
public:
// PX_SERIALIZATION
ArticulationJointCore(const PxEMPTY&) : jointDirtyFlag(PxEmpty)
{
PX_COMPILE_TIME_ASSERT(sizeof(PxArticulationMotions) == sizeof(PxU8));
}
//~PX_SERIALIZATION
ArticulationJointCore(const PxTransform& parentFrame, const PxTransform& childFrame)
{
//PxMarkSerializedMemory(this, sizeof(ArticulationJointCore));
init(parentFrame, childFrame);
}
// PT: these ones don't update the dirty flags
PX_FORCE_INLINE void initLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit) { limits[axis] = limit; }
PX_FORCE_INLINE void initDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) { drives[axis] = drive; }
PX_FORCE_INLINE void initJointType(PxArticulationJointType::Enum type) { jointType = PxU8(type); }
PX_FORCE_INLINE void initMaxJointVelocity(const PxReal maxJointV) { maxJointVelocity = maxJointV; }
PX_FORCE_INLINE void initFrictionCoefficient(const PxReal coefficient) { frictionCoefficient = coefficient; }
void init(const PxTransform& parentFrame, const PxTransform& childFrame)
{
PX_ASSERT(parentFrame.isValid());
PX_ASSERT(childFrame.isValid());
parentPose = parentFrame;
childPose = childFrame;
jointOffset = 0;
// PT: TODO: don't we need ArticulationJointCoreDirtyFlag::eFRAME here?
jointDirtyFlag = ArticulationJointCoreDirtyFlag::eMOTION;
initFrictionCoefficient(0.05f);
initMaxJointVelocity(100.0f);
initJointType(PxArticulationJointType::eUNDEFINED);
for(PxU32 i=0; i<PxArticulationAxis::eCOUNT; i++)
{
initLimit(PxArticulationAxis::Enum(i), PxArticulationLimit(0.0f, 0.0f));
initDrive(PxArticulationAxis::Enum(i), PxArticulationDrive(0.0f, 0.0f, 0.0f, PxArticulationDriveType::eNONE));
targetP[i] = 0.0f;
targetV[i] = 0.0f;
armature[i] = 0.0f;
jointPos[i] = 0.0f;
jointVel[i] = 0.0f;
dofIds[i] = 0xff;
invDofIds[i] = 0xff;
motion[i] = PxArticulationMotion::eLOCKED;
}
}
PX_CUDA_CALLABLE void setJointFrame(Cm::UnAlignedSpatialVector* motionMatrix,
const Cm::UnAlignedSpatialVector* jointAxis,
PxQuat& relativeQuat,
const PxU32 dofs)
{
if (jointDirtyFlag & ArticulationJointCoreDirtyFlag::eFRAME)
{
relativeQuat = (childPose.q * (parentPose.q.getConjugate())).getNormalized();
computeMotionMatrix(motionMatrix, jointAxis, dofs);
jointDirtyFlag &= ~ArticulationJointCoreDirtyFlag::eFRAME;
}
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void computeMotionMatrix(Cm::UnAlignedSpatialVector* motionMatrix,
const Cm::UnAlignedSpatialVector* jointAxis,
const PxU32 dofs)
{
const PxVec3 childOffset = -childPose.p;
switch (jointType)
{
case PxArticulationJointType::ePRISMATIC:
{
const Cm::UnAlignedSpatialVector& jJointAxis = jointAxis[0];
const PxVec3 u = (childPose.rotate(jJointAxis.bottom)).getNormalized();
motionMatrix[0] = Cm::UnAlignedSpatialVector(PxVec3(0.f), u);
PX_ASSERT(dofs == 1);
break;
}
case PxArticulationJointType::eREVOLUTE:
case PxArticulationJointType::eREVOLUTE_UNWRAPPED:
{
const Cm::UnAlignedSpatialVector& jJointAxis = jointAxis[0];
const PxVec3 u = (childPose.rotate(jJointAxis.top)).getNormalized();
const PxVec3 uXd = u.cross(childOffset);
motionMatrix[0] = Cm::UnAlignedSpatialVector(u, uXd);
break;
}
case PxArticulationJointType::eSPHERICAL:
{
for (PxU32 ind = 0; ind < dofs; ++ind)
{
const Cm::UnAlignedSpatialVector& jJointAxis = jointAxis[ind];
const PxVec3 u = (childPose.rotate(jJointAxis.top)).getNormalized();
const PxVec3 uXd = u.cross(childOffset);
motionMatrix[ind] = Cm::UnAlignedSpatialVector(u, uXd);
}
break;
}
case PxArticulationJointType::eFIX:
{
PX_ASSERT(dofs == 0);
break;
}
default:
break;
}
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator=(ArticulationJointCore& other)
{
parentPose = other.parentPose;
childPose = other.childPose;
//KS - temp place to put reduced coordinate limit and drive values
for(PxU32 i=0; i<PxArticulationAxis::eCOUNT; i++)
{
limits[i] = other.limits[i];
drives[i] = other.drives[i];
targetP[i] = other.targetP[i];
targetV[i] = other.targetV[i];
armature[i] = other.armature[i];
jointPos[i] = other.jointPos[i];
jointVel[i] = other.jointVel[i];
dofIds[i] = other.dofIds[i];
invDofIds[i] = other.invDofIds[i];
motion[i] = other.motion[i];
}
frictionCoefficient = other.frictionCoefficient;
maxJointVelocity = other.maxJointVelocity;
jointOffset = other.jointOffset;
jointDirtyFlag = other.jointDirtyFlag;
jointType = other.jointType;
}
PX_FORCE_INLINE void setParentPose(const PxTransform& t) { parentPose = t; jointDirtyFlag |= ArticulationJointCoreDirtyFlag::eFRAME; }
PX_FORCE_INLINE void setChildPose(const PxTransform& t) { childPose = t; jointDirtyFlag |= ArticulationJointCoreDirtyFlag::eFRAME; }
PX_FORCE_INLINE void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum m) { motion[axis] = PxU8(m); jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eMOTION; }
PX_FORCE_INLINE void setTargetP(PxArticulationAxis::Enum axis, PxReal value) { targetP[axis] = value; jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eTARGETPOSE; }
PX_FORCE_INLINE void setTargetV(PxArticulationAxis::Enum axis, PxReal value) { targetV[axis] = value; jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eTARGETVELOCITY; }
PX_FORCE_INLINE void setArmature(PxArticulationAxis::Enum axis, PxReal value) { armature[axis] = value; jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eARMATURE; }
// attachment points, don't change the order, otherwise it will break GPU code
PxTransform parentPose; //28 28
PxTransform childPose; //28 56
//KS - temp place to put reduced coordinate limit and drive values
PxArticulationLimit limits[PxArticulationAxis::eCOUNT]; //48 104
PxArticulationDrive drives[PxArticulationAxis::eCOUNT]; //96 200
PxReal targetP[PxArticulationAxis::eCOUNT]; //24 224
PxReal targetV[PxArticulationAxis::eCOUNT]; //24 248
PxReal armature[PxArticulationAxis::eCOUNT]; //24 272
PxReal jointPos[PxArticulationAxis::eCOUNT]; //24 296
PxReal jointVel[PxArticulationAxis::eCOUNT]; //24 320
PxReal frictionCoefficient; //4 324
PxReal maxJointVelocity; //4 328
//this is the dof offset for the joint in the cache.
PxU32 jointOffset; //4 332
PxU8 dofIds[PxArticulationAxis::eCOUNT]; //6 338
PxU8 motion[PxArticulationAxis::eCOUNT]; //6 344
PxU8 invDofIds[PxArticulationAxis::eCOUNT]; //6 350
ArticulationJointCoreDirtyFlags jointDirtyFlag; //1 351
PxU8 jointType; //1 352
}PX_ALIGN_SUFFIX(16);
}
}
#endif
| 9,319 | C | 38.491525 | 187 | 0.693744 |
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/include/DyFeatherstoneArticulationUtils.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 DY_FEATHERSTONE_ARTICULATION_UTIL_H
#define DY_FEATHERSTONE_ARTICULATION_UTIL_H
#include "foundation/PxVecMath.h"
#include "CmSpatialVector.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxMemory.h"
namespace physx
{
namespace Dy
{
static const size_t DY_MAX_DOF = 6;
struct SpatialSubspaceMatrix
{
static const PxU32 MaxColumns = 3;
public:
#ifndef __CUDACC__
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialSubspaceMatrix() :numColumns(0)
{
//PxMemZero(columns, sizeof(Cm::SpatialVectorF) * 6);
PxMemSet(columns, 0, sizeof(Cm::UnAlignedSpatialVector) * MaxColumns);
}
#endif
PX_CUDA_CALLABLE PX_FORCE_INLINE void setNumColumns(const PxU32 nc)
{
numColumns = nc;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getNumColumns() const
{
return numColumns;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF transposeMultiply(Cm::SpatialVectorF& v) const
{
PxReal result[6];
for (PxU32 i = 0; i < numColumns; ++i)
{
const Cm::UnAlignedSpatialVector& row = columns[i];
result[i] = row.dot(v);
}
Cm::SpatialVectorF res;
res.top.x = result[0]; res.top.y = result[1]; res.top.z = result[2];
res.bottom.x = result[3]; res.bottom.y = result[4]; res.bottom.z = result[5];
return res;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void setColumn(const PxU32 index, const PxVec3& top, const PxVec3& bottom)
{
PX_ASSERT(index < MaxColumns);
columns[index] = Cm::SpatialVectorF(top, bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::UnAlignedSpatialVector& operator[](unsigned int num)
{
PX_ASSERT(num < MaxColumns);
return columns[num];
}
PX_CUDA_CALLABLE PX_FORCE_INLINE const Cm::UnAlignedSpatialVector& operator[](unsigned int num) const
{
PX_ASSERT(num < MaxColumns);
return columns[num];
}
PX_CUDA_CALLABLE PX_FORCE_INLINE const Cm::UnAlignedSpatialVector* getColumns() const
{
return columns;
}
//private:
Cm::UnAlignedSpatialVector columns[MaxColumns]; //3x24 = 72
PxU32 numColumns; //76
PxU32 padding; //80
};
//this should be 6x6 matrix
//|R, 0|
//|-R*rX, R|
struct SpatialTransform
{
PxMat33 R;
PxQuat q;
PxMat33 T;
public:
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialTransform() : R(PxZero), T(PxZero)
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialTransform(const PxMat33& R_, const PxMat33& T_) : R(R_), T(T_)
{
q = PxQuat(R_);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialTransform(const PxQuat& q_, const PxMat33& T_) : q(q_), T(T_)
{
R = PxMat33(q_);
}
//This assume angular is the top vector and linear is the bottom vector
/*PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVector operator *(const Cm::SpatialVector& s) const
{
const PxVec3 angular = R * s.angular;
const PxVec3 linear = T * s.angular + R * s.linear;
return Cm::SpatialVector(linear, angular);
}*/
////This assume angular is the top vector and linear is the bottom vector
//PX_FORCE_INLINE Cm::SpatialVectorF operator *(Cm::SpatialVectorF& s) const
//{
// const PxVec3 top = R * s.top;
// const PxVec3 bottom = T * s.top + R * s.bottom;
// const PxVec3 top1 = q.rotate(s.top);
// const PxVec3 bottom1 = T * s.top + q.rotate(s.bottom);
///* const PxVec3 tDif = (top - top1).abs();
// const PxVec3 bDif = (bottom - bottom1).abs();
// const PxReal eps = 0.001f;
// PX_ASSERT(tDif.x < eps && tDif.y < eps && tDif.z < eps);
// PX_ASSERT(bDif.x < eps && bDif.y < eps && bDif.z < eps);*/
// return Cm::SpatialVectorF(top1, bottom1);
//}
//This assume angular is the top vector and linear is the bottom vector
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF operator *(const Cm::SpatialVectorF& s) const
{
//const PxVec3 top = R * s.top;
//const PxVec3 bottom = T * s.top + R * s.bottom;
const PxVec3 top1 = q.rotate(s.top);
const PxVec3 bottom1 = T * s.top + q.rotate(s.bottom);
return Cm::SpatialVectorF(top1, bottom1);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::UnAlignedSpatialVector operator *(const Cm::UnAlignedSpatialVector& s) const
{
//const PxVec3 top = R * s.top;
//const PxVec3 bottom = T * s.top + R * s.bottom;
const PxVec3 top1 = q.rotate(s.top);
const PxVec3 bottom1 = T * s.top + q.rotate(s.bottom);
return Cm::UnAlignedSpatialVector(top1, bottom1);
}
//transpose is the same as inverse, R(inverse) = R(transpose)
//|R(t), 0 |
//|rXR(t), R(t)|
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialTransform getTranspose() const
{
SpatialTransform ret;
ret.q = q.getConjugate();
ret.R = R.getTranspose();
ret.T = T.getTranspose();
return ret;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF transposeTransform(const Cm::SpatialVectorF& s) const
{
const PxVec3 top1 = q.rotateInv(s.top);
const PxVec3 bottom1 = T.transformTranspose(s.top) + q.rotateInv(s.bottom);
return Cm::SpatialVectorF(top1, bottom1);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::UnAlignedSpatialVector transposeTransform(const Cm::UnAlignedSpatialVector& s) const
{
const PxVec3 top1 = q.rotateInv(s.top);
const PxVec3 bottom1 = T.transformTranspose(s.top) + q.rotateInv(s.bottom);
return Cm::UnAlignedSpatialVector(top1, bottom1);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator =(SpatialTransform& other)
{
R = other.R;
q = other.q;
T = other.T;
}
};
struct InvStIs
{
PxReal invStIs[3][3];
};
//this should be 6x6 matrix and initialize to
//|0, M|
//|I, 0|
//this should be 6x6 matrix but bottomRight is the transpose of topLeft
//so we can get rid of bottomRight
struct SpatialMatrix
{
PxMat33 topLeft; // intialize to 0
PxMat33 topRight; // initialize to mass matrix
PxMat33 bottomLeft; // initialize to inertia
PxU32 padding; //4 112
public:
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix()
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix(PxZERO r) : topLeft(PxZero), topRight(PxZero),
bottomLeft(PxZero)
{
PX_UNUSED(r);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix(const PxMat33& topLeft_, const PxMat33& topRight_, const PxMat33& bottomLeft_)
{
topLeft = topLeft_;
topRight = topRight_;
bottomLeft = bottomLeft_;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33 getBottomRight() const
{
return topLeft.getTranspose();
}
PX_FORCE_INLINE PX_CUDA_CALLABLE void setZero()
{
topLeft = PxMat33(0.f);
topRight = PxMat33(0.f);
bottomLeft = PxMat33(0.f);
}
//This assume angular is the top vector and linear is the bottom vector
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVector operator *(const Cm::SpatialVector& s) const
{
const PxVec3 angular = topLeft * s.angular + topRight * s.linear;
const PxVec3 linear = bottomLeft * s.angular + topLeft.transformTranspose(s.linear);
return Cm::SpatialVector(linear, angular);
}
//This assume angular is the top vector and linear is the bottom vector
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF operator *(const Cm::SpatialVectorF& s) const
{
const PxVec3 top = topLeft * s.top + topRight * s.bottom;
const PxVec3 bottom = bottomLeft * s.top + topLeft.transformTranspose(s.bottom);
return Cm::SpatialVectorF(top, bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::UnAlignedSpatialVector operator *(const Cm::UnAlignedSpatialVector& s) const
{
const PxVec3 top = topLeft * s.top + topRight * s.bottom;
const PxVec3 bottom = bottomLeft * s.top + topLeft.transformTranspose(s.bottom);
return Cm::UnAlignedSpatialVector(top, bottom);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix operator *(const PxReal& s) const
{
const PxMat33 newTopLeft = topLeft * s;
const PxMat33 newTopRight = topRight * s;
const PxMat33 newBottomLeft = bottomLeft * s;
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix operator -(const SpatialMatrix& s) const
{
const PxMat33 newTopLeft = topLeft - s.topLeft;
const PxMat33 newTopRight = topRight - s.topRight;
const PxMat33 newBottomLeft = bottomLeft - s.bottomLeft;
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix operator +(const SpatialMatrix& s) const
{
const PxMat33 newTopLeft = topLeft + s.topLeft;
const PxMat33 newTopRight = topRight + s.topRight;
const PxMat33 newBottomLeft = bottomLeft + s.bottomLeft;
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix operator-()
{
const PxMat33 newTopLeft = -topLeft;
const PxMat33 newTopRight = -topRight;
const PxMat33 newBottomLeft = -bottomLeft;
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void operator +=(const SpatialMatrix& s)
{
topLeft += s.topLeft;
topRight += s.topRight;
bottomLeft += s.bottomLeft;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix operator *(const SpatialMatrix& s)
{
const PxMat33 sBottomRight = s.topLeft.getTranspose();
const PxMat33 bottomRight = topLeft.getTranspose();
const PxMat33 newTopLeft = topLeft * s.topLeft + topRight * s.bottomLeft;
const PxMat33 newTopRight = topLeft * s.topRight + topRight * sBottomRight;
const PxMat33 newBottomLeft = bottomLeft * s.topLeft + bottomRight * s.bottomLeft;
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);
}
static SpatialMatrix constructSpatialMatrix(const Cm::SpatialVector& Is, const Cm::SpatialVector& stI)
{
//construct top left
const PxVec3 tLeftC0 = Is.angular * stI.angular.x;
const PxVec3 tLeftC1 = Is.angular * stI.angular.y;
const PxVec3 tLeftC2 = Is.angular * stI.angular.z;
const PxMat33 topLeft(tLeftC0, tLeftC1, tLeftC2);
//construct top right
const PxVec3 tRightC0 = Is.angular * stI.linear.x;
const PxVec3 tRightC1 = Is.angular * stI.linear.y;
const PxVec3 tRightC2 = Is.angular * stI.linear.z;
const PxMat33 topRight(tRightC0, tRightC1, tRightC2);
//construct bottom left
const PxVec3 bLeftC0 = Is.linear * stI.angular.x;
const PxVec3 bLeftC1 = Is.linear * stI.angular.y;
const PxVec3 bLeftC2 = Is.linear * stI.angular.z;
const PxMat33 bottomLeft(bLeftC0, bLeftC1, bLeftC2);
return SpatialMatrix(topLeft, topRight, bottomLeft);
}
static PX_CUDA_CALLABLE SpatialMatrix constructSpatialMatrix(const Cm::SpatialVectorF& Is, const Cm::SpatialVectorF& stI)
{
//construct top left
const PxVec3 tLeftC0 = Is.top * stI.top.x;
const PxVec3 tLeftC1 = Is.top * stI.top.y;
const PxVec3 tLeftC2 = Is.top * stI.top.z;
const PxMat33 topLeft(tLeftC0, tLeftC1, tLeftC2);
//construct top right
const PxVec3 tRightC0 = Is.top * stI.bottom.x;
const PxVec3 tRightC1 = Is.top * stI.bottom.y;
const PxVec3 tRightC2 = Is.top * stI.bottom.z;
const PxMat33 topRight(tRightC0, tRightC1, tRightC2);
//construct bottom left
const PxVec3 bLeftC0 = Is.bottom * stI.top.x;
const PxVec3 bLeftC1 = Is.bottom * stI.top.y;
const PxVec3 bLeftC2 = Is.bottom * stI.top.z;
const PxMat33 bottomLeft(bLeftC0, bLeftC1, bLeftC2);
return SpatialMatrix(topLeft, topRight, bottomLeft);
}
template <typename SpatialVector>
static PX_CUDA_CALLABLE SpatialMatrix constructSpatialMatrix(const SpatialVector* columns)
{
const PxMat33 topLeft(columns[0].top, columns[1].top, columns[2].top);
const PxMat33 bottomLeft(columns[0].bottom, columns[1].bottom, columns[2].bottom);
const PxMat33 topRight(columns[3].top, columns[4].top, columns[5].top);
return SpatialMatrix(topLeft, topRight, bottomLeft);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix getTranspose()
{
const PxMat33 newTopLeft = topLeft.getTranspose();
const PxMat33 newTopRight = bottomLeft.getTranspose();
const PxMat33 newBottomLeft = topRight.getTranspose();
//const PxMat33 newBottomRight = bottomRight.getTranspose();
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);// , newBottomRight);
}
//static bool isTranspose(const PxMat33& a, const PxMat33& b)
//{
// PxReal eps = 0.01f;
// //test bottomRight is the transpose of topLeft
// for (PxU32 i = 0; i <3; ++i)
// {
// for (PxU32 j = 0; j <3; ++j)
// {
// if (PxAbs(a[i][j] - b[j][i]) > eps)
// return false;
// }
// }
// return true;
//}
PX_FORCE_INLINE bool isIdentity(const PxMat33& matrix)
{
const PxReal eps = 0.00001f;
const float x = PxAbs(1.f - matrix.column0.x);
const float y = PxAbs(1.f - matrix.column1.y);
const float z = PxAbs(1.f - matrix.column2.z);
const bool identity = ((x < eps) && PxAbs(matrix.column0.y - 0.f) < eps && PxAbs(matrix.column0.z - 0.f) < eps) &&
(PxAbs(matrix.column1.x - 0.f) < eps && (y < eps) && PxAbs(matrix.column1.z - 0.f) < eps) &&
(PxAbs(matrix.column2.x - 0.f) < eps && PxAbs(matrix.column2.y - 0.f) < eps && (z < eps));
return identity;
}
PX_FORCE_INLINE bool isZero(const PxMat33& matrix)
{
const PxReal eps = 0.0001f;
for (PxU32 i = 0; i < 3; ++i)
{
for (PxU32 j = 0; j < 3; ++j)
{
if (PxAbs(matrix[i][j]) > eps)
return false;
}
}
return true;
}
PX_FORCE_INLINE bool isIdentity()
{
const bool topLeftIsIdentity = isIdentity(topLeft);
const bool topRightIsZero = isZero(topRight);
const bool bottomLeftIsZero = isZero(bottomLeft);
return topLeftIsIdentity && topRightIsZero && bottomLeftIsZero;
}
static bool isEqual(const PxMat33& s0, const PxMat33& s1)
{
const PxReal eps = 0.00001f;
for (PxU32 i = 0; i < 3; ++i)
{
for (PxU32 j = 0; j < 3; ++j)
{
const PxReal t = s0[i][j] - s1[i][j];
if (PxAbs(t) > eps)
return false;
}
}
return true;
}
PX_FORCE_INLINE bool isEqual(const SpatialMatrix& s)
{
const bool topLeftEqual = isEqual(topLeft, s.topLeft);
const bool topRightEqual = isEqual(topRight, s.topRight);
const bool bottomLeftEqual = isEqual(bottomLeft, s.bottomLeft);
return topLeftEqual && topRightEqual && bottomLeftEqual;
}
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxMat33 invertSym33(const PxMat33& in)
{
const PxVec3 v0 = in[1].cross(in[2]);
const PxVec3 v1 = in[2].cross(in[0]);
const PxVec3 v2 = in[0].cross(in[1]);
const PxReal det = v0.dot(in[0]);
if (det != 0)
{
const PxReal recipDet = 1.0f / det;
return PxMat33(v0 * recipDet,
PxVec3(v0.y, v1.y, v1.z) * recipDet,
PxVec3(v0.z, v1.z, v2.z) * recipDet);
}
else
{
return PxMat33(PxIdentity);
}
}
static PX_FORCE_INLINE aos::Mat33V invertSym33(const aos::Mat33V& in)
{
using namespace aos;
const Vec3V v0 = V3Cross(in.col1, in.col2);
const Vec3V v1 = V3Cross(in.col2, in.col0);
const Vec3V v2 = V3Cross(in.col0, in.col1);
const FloatV det = V3Dot(v0, in.col0);
const FloatV recipDet = FRecip(det);
if (!FAllEq(det, FZero()))
{
return Mat33V(V3Scale(v0, recipDet),
V3Scale(V3Merge(V3GetY(v0), V3GetY(v1), V3GetZ(v1)), recipDet),
V3Scale(V3Merge(V3GetZ(v0), V3GetZ(v1), V3GetZ(v2)), recipDet));
}
else
{
return Mat33V(V3UnitX(), V3UnitY(), V3UnitZ());
}
//return M33Inverse(in);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE SpatialMatrix invertInertia()
{
PxMat33 aa = bottomLeft, ll = topRight, la = topLeft;
aa = (aa + aa.getTranspose())*0.5f;
ll = (ll + ll.getTranspose())*0.5f;
const PxMat33 AAInv = invertSym33(aa);
const PxMat33 z = -la * AAInv;
const PxMat33 S = ll + z * la.getTranspose(); // Schur complement of mAA
const PxMat33 LL = invertSym33(S);
const PxMat33 LA = LL * z;
const PxMat33 AA = AAInv + z.getTranspose() * LA;
const SpatialMatrix result(LA.getTranspose(), AA, LL);// , LA);
return result;
}
PX_FORCE_INLINE void M33Store(const aos::Mat33V& src, PxMat33& dest)
{
aos::V3StoreU(src.col0, dest.column0);
aos::V3StoreU(src.col1, dest.column1);
aos::V3StoreU(src.col2, dest.column2);
}
PX_FORCE_INLINE void invertInertiaV(SpatialMatrix& result)
{
using namespace aos;
Mat33V aa = M33Load(bottomLeft), ll = M33Load(topRight), la = M33Load(topLeft);
aa = M33Scale(M33Add(aa, M33Trnsps(aa)), FHalf());
ll = M33Scale(M33Add(ll, M33Trnsps(ll)), FHalf());
const Mat33V AAInv = invertSym33(aa);
const Mat33V z = M33MulM33(M33Neg(la), AAInv);
const Mat33V S = M33Add(ll, M33MulM33(z, M33Trnsps(la))); // Schur complement of mAA
const Mat33V LL = invertSym33(S);
const Mat33V LA = M33MulM33(LL, z);
const Mat33V AA = M33Add(AAInv, M33MulM33(M33Trnsps(z), LA));
M33Store(M33Trnsps(LA), result.topLeft);
M33Store(AA, result.topRight);
M33Store(LL, result.bottomLeft);
}
SpatialMatrix getInverse()
{
const PxMat33 bottomRight = topLeft.getTranspose();
const PxMat33 blInverse = bottomLeft.getInverse();
const PxMat33 lComp0 = blInverse * (-bottomRight);
const PxMat33 lComp1 = topLeft * lComp0 + topRight;
//This can be simplified
const PxMat33 newBottomLeft = lComp1.getInverse();
const PxMat33 newTopLeft = lComp0 * newBottomLeft;
const PxMat33 trInverse = topRight.getInverse();
const PxMat33 rComp0 = trInverse * (-topLeft);
const PxMat33 rComp1 = bottomLeft + bottomRight * rComp0;
const PxMat33 newTopRight = rComp1.getInverse();
return SpatialMatrix(newTopLeft, newTopRight, newBottomLeft);
}
void zero()
{
topLeft = PxMat33(PxZero);
topRight = PxMat33(PxZero);
bottomLeft = PxMat33(PxZero);
}
};
struct SpatialImpulseResponseMatrix
{
Cm::SpatialVectorF rows[6];
Cm::SpatialVectorF getResponse(const Cm::SpatialVectorF& impulse) const
{
/*return rows[0] * impulse.top.x + rows[1] * impulse.top.y + rows[2] * impulse.top.z
+ rows[3] * impulse.bottom.x + rows[4] * impulse.bottom.y + rows[5] * impulse.bottom.z;*/
using namespace aos;
const Cm::SpatialVectorV row0(V3LoadA(&rows[0].top.x), V3LoadA(&rows[0].bottom.x));
const Cm::SpatialVectorV row1(V3LoadA(&rows[1].top.x), V3LoadA(&rows[1].bottom.x));
const Cm::SpatialVectorV row2(V3LoadA(&rows[2].top.x), V3LoadA(&rows[2].bottom.x));
const Cm::SpatialVectorV row3(V3LoadA(&rows[3].top.x), V3LoadA(&rows[3].bottom.x));
const Cm::SpatialVectorV row4(V3LoadA(&rows[4].top.x), V3LoadA(&rows[4].bottom.x));
const Cm::SpatialVectorV row5(V3LoadA(&rows[5].top.x), V3LoadA(&rows[5].bottom.x));
const Vec4V top = V4LoadA(&impulse.top.x);
const Vec4V bottom = V4LoadA(&impulse.bottom.x);
const FloatV ix = V4GetX(top);
const FloatV iy = V4GetY(top);
const FloatV iz = V4GetZ(top);
const FloatV ia = V4GetX(bottom);
const FloatV ib = V4GetY(bottom);
const FloatV ic = V4GetZ(bottom);
Cm::SpatialVectorV res = row0 * ix + row1 * iy + row2 * iz + row3 * ia + row4 * ib + row5 * ic;
Cm::SpatialVectorF returnVal;
V4StoreA(Vec4V_From_Vec3V(res.linear), &returnVal.top.x);
V4StoreA(Vec4V_From_Vec3V(res.angular), &returnVal.bottom.x);
return returnVal;
}
Cm::SpatialVectorV getResponse(const Cm::SpatialVectorV& impulse) const
{
using namespace aos;
const Cm::SpatialVectorV row0(V3LoadA(&rows[0].top.x), V3LoadA(&rows[0].bottom.x));
const Cm::SpatialVectorV row1(V3LoadA(&rows[1].top.x), V3LoadA(&rows[1].bottom.x));
const Cm::SpatialVectorV row2(V3LoadA(&rows[2].top.x), V3LoadA(&rows[2].bottom.x));
const Cm::SpatialVectorV row3(V3LoadA(&rows[3].top.x), V3LoadA(&rows[3].bottom.x));
const Cm::SpatialVectorV row4(V3LoadA(&rows[4].top.x), V3LoadA(&rows[4].bottom.x));
const Cm::SpatialVectorV row5(V3LoadA(&rows[5].top.x), V3LoadA(&rows[5].bottom.x));
const Vec3V top = impulse.linear;
const Vec3V bottom = impulse.angular;
const FloatV ix = V3GetX(top);
const FloatV iy = V3GetY(top);
const FloatV iz = V3GetZ(top);
const FloatV ia = V3GetX(bottom);
const FloatV ib = V3GetY(bottom);
const FloatV ic = V3GetZ(bottom);
Cm::SpatialVectorV res = row0 * ix + row1 * iy + row2 * iz + row3 * ia + row4 * ib + row5 * ic;
return res;
}
};
struct Temp6x6Matrix;
struct Temp6x3Matrix
{
PxReal column[3][6];
public:
Temp6x3Matrix()
{
}
Temp6x3Matrix(const Cm::SpatialVectorF* spatialAxis)
{
constructColumn(column[0], spatialAxis[0]);
constructColumn(column[1], spatialAxis[1]);
constructColumn(column[2], spatialAxis[2]);
}
void constructColumn(PxReal* dest, const Cm::SpatialVectorF& v)
{
dest[0] = v.top.x;
dest[1] = v.top.y;
dest[2] = v.top.z;
dest[3] = v.bottom.x;
dest[4] = v.bottom.y;
dest[5] = v.bottom.z;
}
Temp6x6Matrix operator * (PxReal s[6][3]);
////s is 3x6 matrix
//PX_FORCE_INLINE Temp6x6Matrix operator * (PxReal s[6][3])
//{
// Temp6x6Matrix temp;
// for (PxU32 i = 0; i < 6; ++i)
// {
// PxReal* tc = temp.column[i];
// for (PxU32 j = 0; j < 6; ++j)
// {
// tc[j] = 0.f;
// for (PxU32 k = 0; k < 3; ++k)
// {
// tc[j] += column[k][j] * s[i][k];
// }
// }
// }
// return temp;
//}
PX_FORCE_INLINE Temp6x3Matrix operator * (const PxMat33& s)
{
Temp6x3Matrix temp;
for (PxU32 i = 0; i < 3; ++i)
{
PxReal* tc = temp.column[i];
const PxVec3 sc = s[i];
for (PxU32 j = 0; j < 6; ++j)
{
tc[j] = 0.f;
for (PxU32 k = 0; k < 3; ++k)
{
tc[j] += column[k][j] * sc[k];
}
}
}
return temp;
}
PX_FORCE_INLINE bool isColumnEqual(const PxU32 ind, const Cm::SpatialVectorF& col)
{
PxReal temp[6];
constructColumn(temp, col);
const PxReal eps = 0.00001f;
for (PxU32 i = 0; i < 6; ++i)
{
const PxReal dif = column[ind][i] - temp[i];
if (PxAbs(dif) > eps)
return false;
}
return true;
}
};
struct Temp6x6Matrix
{
PxReal column[6][6];
public:
Temp6x6Matrix()
{
}
Temp6x6Matrix(const SpatialMatrix& spatialMatrix)
{
constructColumn(column[0], spatialMatrix.topLeft.column0, spatialMatrix.bottomLeft.column0);
constructColumn(column[1], spatialMatrix.topLeft.column1, spatialMatrix.bottomLeft.column1);
constructColumn(column[2], spatialMatrix.topLeft.column2, spatialMatrix.bottomLeft.column2);
const PxMat33 bottomRight = spatialMatrix.getBottomRight();
constructColumn(column[3], spatialMatrix.topRight.column0, bottomRight.column0);
constructColumn(column[4], spatialMatrix.topRight.column1, bottomRight.column1);
constructColumn(column[5], spatialMatrix.topRight.column2, bottomRight.column2);
}
void constructColumn(const PxU32 ind, const PxReal* const values)
{
for (PxU32 i = 0; i < 6; ++i)
{
column[ind][i] = values[i];
}
}
void constructColumn(PxReal* dest, const PxVec3& top, const PxVec3& bottom)
{
dest[0] = top.x;
dest[1] = top.y;
dest[2] = top.z;
dest[3] = bottom.x;
dest[4] = bottom.y;
dest[5] = bottom.z;
}
Temp6x6Matrix getTranspose() const
{
Temp6x6Matrix temp;
for (PxU32 i = 0; i < 6; ++i)
{
for (PxU32 j = 0; j < 6; ++j)
{
temp.column[i][j] = column[j][i];
}
}
return temp;
}
PX_FORCE_INLINE Cm::SpatialVector operator * (const Cm::SpatialVector& s) const
{
Temp6x6Matrix tempMatrix = getTranspose();
PxReal st[6];
st[0] = s.angular.x; st[1] = s.angular.y; st[2] = s.angular.z;
st[3] = s.linear.x; st[4] = s.linear.y; st[5] = s.linear.z;
PxReal result[6];
for (PxU32 i = 0; i < 6; i++)
{
result[i] = 0;
for (PxU32 j = 0; j < 6; ++j)
{
result[i] += tempMatrix.column[i][j] * st[j];
}
}
Cm::SpatialVector temp;
temp.angular.x = result[0]; temp.angular.y = result[1]; temp.angular.z = result[2];
temp.linear.x = result[3]; temp.linear.y = result[4]; temp.linear.z = result[5];
return temp;
}
PX_FORCE_INLINE Cm::SpatialVectorF operator * (const Cm::SpatialVectorF& s) const
{
PxReal st[6];
st[0] = s.top.x; st[1] = s.top.y; st[2] = s.top.z;
st[3] = s.bottom.x; st[4] = s.bottom.y; st[5] = s.bottom.z;
PxReal result[6];
for (PxU32 i = 0; i < 6; ++i)
{
result[i] = 0.f;
for (PxU32 j = 0; j < 6; ++j)
{
result[i] += column[j][i] * st[j];
}
}
Cm::SpatialVectorF temp;
temp.top.x = result[0]; temp.top.y = result[1]; temp.top.z = result[2];
temp.bottom.x = result[3]; temp.bottom.y = result[4]; temp.bottom.z = result[5];
return temp;
}
PX_FORCE_INLINE Temp6x3Matrix operator * (const Temp6x3Matrix& s) const
{
Temp6x3Matrix temp;
for (PxU32 i = 0; i < 3; ++i)
{
PxReal* result = temp.column[i];
const PxReal* input = s.column[i];
for (PxU32 j = 0; j < 6; ++j)
{
result[j] = 0.f;
for (PxU32 k = 0; k < 6; ++k)
{
result[j] += column[k][j] * input[k];
}
}
}
return temp;
}
PX_FORCE_INLINE Cm::SpatialVector spatialVectorMul(const Cm::SpatialVector& s)
{
PxReal st[6];
st[0] = s.angular.x; st[1] = s.angular.y; st[2] = s.angular.z;
st[3] = s.linear.x; st[4] = s.linear.y; st[5] = s.linear.z;
PxReal result[6];
for (PxU32 i = 0; i < 6; ++i)
{
result[i] = 0.f;
for (PxU32 j = 0; j < 6; j++)
{
result[i] += column[i][j] * st[j];
}
}
Cm::SpatialVector temp;
temp.angular.x = result[0]; temp.angular.y = result[1]; temp.angular.z = result[2];
temp.linear.x = result[3]; temp.linear.y = result[4]; temp.linear.z = result[5];
return temp;
}
PX_FORCE_INLINE bool isEqual(const Cm::SpatialVectorF* m)
{
PxReal temp[6];
const PxReal eps = 0.00001f;
for (PxU32 i = 0; i < 6; ++i)
{
temp[0] = m[i].top.x; temp[1] = m[i].top.y; temp[2] = m[i].top.z;
temp[3] = m[i].bottom.x; temp[4] = m[i].bottom.y; temp[5] = m[i].bottom.z;
for (PxU32 j = 0; j < 6; ++j)
{
const PxReal dif = column[i][j] - temp[j];
if (PxAbs(dif) > eps)
return false;
}
}
return true;
}
};
//s is 3x6 matrix
PX_FORCE_INLINE Temp6x6Matrix Temp6x3Matrix::operator * (PxReal s[6][3])
{
Temp6x6Matrix temp;
for (PxU32 i = 0; i < 6; ++i)
{
PxReal* tc = temp.column[i];
for (PxU32 j = 0; j < 6; ++j)
{
tc[j] = 0.f;
for (PxU32 k = 0; k < 3; ++k)
{
tc[j] += column[k][j] * s[i][k];
}
}
}
return temp;
}
PX_FORCE_INLINE void calculateNewVelocity(const PxTransform& newTransform, const PxTransform& oldTransform,
const PxReal dt, PxVec3& linear, PxVec3& angular)
{
//calculate the new velocity
linear = (newTransform.p - oldTransform.p) / dt;
PxQuat quat = newTransform.q * oldTransform.q.getConjugate();
if (quat.w < 0) //shortest angle.
quat = -quat;
PxReal angle;
PxVec3 axis;
quat.toRadiansAndUnitAxis(angle, axis);
angular = (axis * angle) / dt;
}
// generates a pair of quaternions (swing, twist) such that in = swing * twist, with
// swing.x = 0
// twist.y = twist.z = 0, and twist is a unit quat
PX_CUDA_CALLABLE PX_FORCE_INLINE void separateSwingTwist(const PxQuat& q, PxQuat& twist, PxQuat& swing1, PxQuat& swing2)
{
twist = q.x != 0.0f ? PxQuat(q.x, 0, 0, q.w).getNormalized() : PxQuat(PxIdentity);
PxQuat swing = q * twist.getConjugate();
swing1 = swing.y != 0.f ? PxQuat(0.f, swing.y, 0.f, swing.w).getNormalized() : PxQuat(PxIdentity);
swing = swing * swing1.getConjugate();
swing2 = swing.z != 0.f ? PxQuat(0.f, 0.f, swing.z, swing.w).getNormalized() : PxQuat(PxIdentity);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE void separateSwingTwist2(const PxQuat& q, PxQuat& twist, PxQuat& swing1, PxQuat& swing2)
{
swing2 = q.z != 0.0f ? PxQuat(0.f, 0.f, q.z, q.w).getNormalized() : PxQuat(PxIdentity);
PxQuat swing = q * swing2.getConjugate();
swing1 = swing.y != 0.f ? PxQuat(0.f, swing.y, 0.f, swing.w).getNormalized() : PxQuat(PxIdentity);
swing = swing * swing1.getConjugate();
twist = swing.x != 0.f ? PxQuat(swing.x, 0.f, 0.f, swing.w).getNormalized() : PxQuat(PxIdentity);
}
} //namespace Dy
}
#endif
| 29,576 | C | 27.997059 | 127 | 0.658811 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseShared.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef BP_BROADPHASE_SHARED_H
#define BP_BROADPHASE_SHARED_H
#include "BpBroadPhaseIntegerAABB.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxHash.h"
#include "foundation/PxVecMath.h"
namespace physx
{
namespace Bp
{
#define INVALID_ID 0xffffffff
#define INVALID_USER_ID 0xffffffff
struct InternalPair : public PxUserAllocated
{
PX_FORCE_INLINE PxU32 getId0() const { return id0_isNew & ~PX_SIGN_BITMASK; }
PX_FORCE_INLINE PxU32 getId1() const { return id1_isUpdated & ~PX_SIGN_BITMASK; }
PX_FORCE_INLINE PxU32 isNew() const { return id0_isNew & PX_SIGN_BITMASK; }
PX_FORCE_INLINE PxU32 isUpdated() const { return id1_isUpdated & PX_SIGN_BITMASK; }
PX_FORCE_INLINE void setNewPair(PxU32 id0, PxU32 id1)
{
PX_ASSERT(!(id0 & PX_SIGN_BITMASK));
PX_ASSERT(!(id1 & PX_SIGN_BITMASK));
id0_isNew = id0 | PX_SIGN_BITMASK;
id1_isUpdated = id1;
}
PX_FORCE_INLINE void setNewPair2(PxU32 id0, PxU32 id1)
{
PX_ASSERT(!(id0 & PX_SIGN_BITMASK));
PX_ASSERT(!(id1 & PX_SIGN_BITMASK));
id0_isNew = id0;
id1_isUpdated = id1;
}
PX_FORCE_INLINE void setUpdated() { id1_isUpdated |= PX_SIGN_BITMASK; }
PX_FORCE_INLINE void clearUpdated() { id1_isUpdated &= ~PX_SIGN_BITMASK; }
PX_FORCE_INLINE void clearNew() { id0_isNew &= ~PX_SIGN_BITMASK; }
protected:
PxU32 id0_isNew;
PxU32 id1_isUpdated;
};
PX_FORCE_INLINE bool differentPair(const InternalPair& p, PxU32 id0, PxU32 id1) { return (id0!=p.getId0()) || (id1!=p.getId1()); }
PX_FORCE_INLINE PxU32 hash(PxU32 id0, PxU32 id1) { return PxComputeHash( (id0&0xffff)|(id1<<16)); }
//PX_FORCE_INLINE PxU32 hash(PxU32 id0, PxU32 id1) { return PxComputeHash(PxU64(id0)|(PxU64(id1)<<32)) ; }
PX_FORCE_INLINE void sort(PxU32& id0, PxU32& id1) { if(id0>id1) PxSwap(id0, id1); }
class PairManagerData
{
public:
PairManagerData();
~PairManagerData();
PX_FORCE_INLINE PxU32 getPairIndex(const InternalPair* pair) const
{
return (PxU32((size_t(pair) - size_t(mActivePairs)))/sizeof(InternalPair));
}
// Internal version saving hash computation
PX_FORCE_INLINE InternalPair* findPair(PxU32 id0, PxU32 id1, PxU32 hashValue) const
{
if(!mHashTable)
return NULL; // Nothing has been allocated yet
InternalPair* PX_RESTRICT activePairs = mActivePairs;
const PxU32* PX_RESTRICT next = mNext;
// Look for it in the table
PxU32 offset = mHashTable[hashValue];
while(offset!=INVALID_ID && differentPair(activePairs[offset], id0, id1))
{
PX_ASSERT(activePairs[offset].getId0()!=INVALID_USER_ID);
offset = next[offset]; // Better to have a separate array for this
}
if(offset==INVALID_ID)
return NULL;
PX_ASSERT(offset<mNbActivePairs);
// Match mActivePairs[offset] => the pair is persistent
return &activePairs[offset];
}
PX_FORCE_INLINE InternalPair* addPairInternal(PxU32 id0, PxU32 id1)
{
// Order the ids
sort(id0, id1);
const PxU32 fullHashValue = hash(id0, id1);
PxU32 hashValue = fullHashValue & mMask;
{
InternalPair* PX_RESTRICT p = findPair(id0, id1, hashValue);
if(p)
{
p->setUpdated();
return p; // Persistent pair
}
}
// This is a new pair
if(mNbActivePairs >= mHashSize)
hashValue = growPairs(fullHashValue);
const PxU32 pairIndex = mNbActivePairs++;
InternalPair* PX_RESTRICT p = &mActivePairs[pairIndex];
p->setNewPair(id0, id1);
mNext[pairIndex] = mHashTable[hashValue];
mHashTable[hashValue] = pairIndex;
return p;
}
PxU32 mHashSize;
PxU32 mMask;
PxU32 mNbActivePairs;
PxU32* mHashTable;
PxU32* mNext;
InternalPair* mActivePairs;
PxU32 mReservedMemory;
void purge();
void reallocPairs();
void shrinkMemory();
void reserveMemory(PxU32 memSize);
PX_NOINLINE PxU32 growPairs(PxU32 fullHashValue);
void removePair(PxU32 id0, PxU32 id1, PxU32 hashValue, PxU32 pairIndex);
};
struct AABB_Xi
{
PX_FORCE_INLINE AABB_Xi() {}
PX_FORCE_INLINE ~AABB_Xi() {}
PX_FORCE_INLINE void initFromFloats(const void* PX_RESTRICT minX, const void* PX_RESTRICT maxX)
{
mMinX = encodeFloat(*reinterpret_cast<const PxU32*>(minX));
mMaxX = encodeFloat(*reinterpret_cast<const PxU32*>(maxX));
}
PX_FORCE_INLINE void initFromPxVec4(const PxVec4& min, const PxVec4& max)
{
initFromFloats(&min.x, &max.x);
}
PX_FORCE_INLINE void operator = (const AABB_Xi& box)
{
mMinX = box.mMinX;
mMaxX = box.mMaxX;
}
PX_FORCE_INLINE void initSentinel()
{
mMinX = 0xffffffff;
}
PX_FORCE_INLINE bool isSentinel() const
{
return mMinX == 0xffffffff;
}
PxU32 mMinX;
PxU32 mMaxX;
};
struct AABB_YZn
{
PX_FORCE_INLINE AABB_YZn() {}
PX_FORCE_INLINE ~AABB_YZn() {}
PX_FORCE_INLINE void initFromPxVec4(const PxVec4& min, const PxVec4& max)
{
mMinY = -min.y;
mMinZ = -min.z;
mMaxY = max.y;
mMaxZ = max.z;
}
PX_FORCE_INLINE void operator = (const AABB_YZn& box)
{
using namespace physx::aos;
V4StoreA(V4LoadA(&box.mMinY), &mMinY);
}
float mMinY;
float mMinZ;
float mMaxY;
float mMaxZ;
};
struct AABB_YZr
{
PX_FORCE_INLINE AABB_YZr() {}
PX_FORCE_INLINE ~AABB_YZr() {}
PX_FORCE_INLINE void initFromPxVec4(const PxVec4& min, const PxVec4& max)
{
mMinY = min.y;
mMinZ = min.z;
mMaxY = max.y;
mMaxZ = max.z;
}
PX_FORCE_INLINE void operator = (const AABB_YZr& box)
{
using namespace physx::aos;
V4StoreA(V4LoadA(&box.mMinY), &mMinY);
}
float mMinY;
float mMinZ;
float mMaxY;
float mMaxZ;
};
} //namespace Bp
} //namespace physx
#endif // BP_BROADPHASE_SHARED_H
| 7,760 | C | 29.675889 | 131 | 0.655026 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseIntegerAABB.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef BP_BROADPHASE_INTEGER_AABB_H
#define BP_BROADPHASE_INTEGER_AABB_H
#include "BpFiltering.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxUnionCast.h"
namespace physx
{
namespace Bp
{
/*
\brief Encode a single float value with lossless encoding to integer
*/
PX_FORCE_INLINE PxU32 encodeFloat(PxU32 ir)
{
//we may need to check on -0 and 0
//But it should make no practical difference.
if(ir & PX_SIGN_BITMASK) //negative?
return ~ir;//reverse sequence of negative numbers
else
return ir | PX_SIGN_BITMASK; // flip sign
}
/*
\brief Encode a single float value with lossless encoding to integer
*/
PX_FORCE_INLINE PxU32 decodeFloat(PxU32 ir)
{
if(ir & PX_SIGN_BITMASK) //positive?
return ir & ~PX_SIGN_BITMASK; //flip sign
else
return ~ir; //undo reversal
}
/**
\brief Integer representation of PxBounds3 used by BroadPhase
@see BroadPhaseUpdateData
*/
typedef PxU32 ValType;
class IntegerAABB
{
public:
enum
{
MIN_X = 0,
MIN_Y,
MIN_Z,
MAX_X,
MAX_Y,
MAX_Z
};
IntegerAABB(const PxBounds3& b, PxReal contactDistance)
{
const PxVec3 dist(contactDistance);
encode(PxBounds3(b.minimum - dist, b.maximum + dist));
}
/*
\brief Return the minimum along a specified axis
\param[in] i is the axis
*/
PX_FORCE_INLINE ValType getMin(PxU32 i) const { return (mMinMax)[MIN_X+i]; }
/*
\brief Return the maximum along a specified axis
\param[in] i is the axis
*/
PX_FORCE_INLINE ValType getMax(PxU32 i) const { return (mMinMax)[MAX_X+i]; }
/*
\brief Return one of the six min/max values of the bound
\param[in] isMax determines whether a min or max value is returned
\param[in] index is the axis
*/
PX_FORCE_INLINE ValType getExtent(PxU32 isMax, PxU32 index) const
{
PX_ASSERT(isMax<=1);
return (mMinMax)[3*isMax+index];
}
/*
\brief Return the minimum on the x axis
*/
PX_FORCE_INLINE ValType getMinX() const { return mMinMax[MIN_X]; }
/*
\brief Return the minimum on the y axis
*/
PX_FORCE_INLINE ValType getMinY() const { return mMinMax[MIN_Y]; }
/*
\brief Return the minimum on the z axis
*/
PX_FORCE_INLINE ValType getMinZ() const { return mMinMax[MIN_Z]; }
/*
\brief Return the maximum on the x axis
*/
PX_FORCE_INLINE ValType getMaxX() const { return mMinMax[MAX_X]; }
/*
\brief Return the maximum on the y axis
*/
PX_FORCE_INLINE ValType getMaxY() const { return mMinMax[MAX_Y]; }
/*
\brief Return the maximum on the z axis
*/
PX_FORCE_INLINE ValType getMaxZ() const { return mMinMax[MAX_Z]; }
/*
\brief Encode float bounds so they are stored as integer bounds
\param[in] bounds is the bounds to be encoded
\note The integer values of minima are always even, while the integer values of maxima are always odd
\note The encoding process masks off the last four bits for minima and masks on the last four bits for maxima.
This keeps the bounds constant when its shape is subjected to small global pose perturbations. In turn, this helps
reduce computational effort in the broadphase update by reducing the amount of sorting required on near-stationary
bodies that are aligned along one or more axis.
@see decode
*/
PX_FORCE_INLINE void encode(const PxBounds3& bounds)
{
const PxU32* PX_RESTRICT min = PxUnionCast<const PxU32*, const PxF32*>(&bounds.minimum.x);
const PxU32* PX_RESTRICT max = PxUnionCast<const PxU32*, const PxF32*>(&bounds.maximum.x);
//Avoid min=max by enforcing the rule that mins are even and maxs are odd.
mMinMax[MIN_X] = encodeFloatMin(min[0]);
mMinMax[MIN_Y] = encodeFloatMin(min[1]);
mMinMax[MIN_Z] = encodeFloatMin(min[2]);
mMinMax[MAX_X] = encodeFloatMax(max[0]) | (1<<2);
mMinMax[MAX_Y] = encodeFloatMax(max[1]) | (1<<2);
mMinMax[MAX_Z] = encodeFloatMax(max[2]) | (1<<2);
}
/*
\brief Decode from integer bounds to float bounds
\param[out] bounds is the decoded float bounds
\note Encode followed by decode will produce a float bound larger than the original
due to the masking in encode.
@see encode
*/
PX_FORCE_INLINE void decode(PxBounds3& bounds) const
{
PxU32* PX_RESTRICT min = PxUnionCast<PxU32*, PxF32*>(&bounds.minimum.x);
PxU32* PX_RESTRICT max = PxUnionCast<PxU32*, PxF32*>(&bounds.maximum.x);
min[0] = decodeFloat(mMinMax[MIN_X]);
min[1] = decodeFloat(mMinMax[MIN_Y]);
min[2] = decodeFloat(mMinMax[MIN_Z]);
max[0] = decodeFloat(mMinMax[MAX_X]);
max[1] = decodeFloat(mMinMax[MAX_Y]);
max[2] = decodeFloat(mMinMax[MAX_Z]);
}
/*
\brief Encode a single minimum value from integer bounds to float bounds
\note The encoding process masks off the last four bits for minima
@see encode
*/
static PX_FORCE_INLINE ValType encodeFloatMin(PxU32 source)
{
return ((encodeFloat(source) >> eGRID_SNAP_VAL) - 1) << eGRID_SNAP_VAL;
}
/*
\brief Encode a single maximum value from integer bounds to float bounds
\note The encoding process masks on the last four bits for maxima
@see encode
*/
static PX_FORCE_INLINE ValType encodeFloatMax(PxU32 source)
{
return ((encodeFloat(source) >> eGRID_SNAP_VAL) + 1) << eGRID_SNAP_VAL;
}
/*
\brief Shift the encoded bounds by a specified vector
\param[in] shift is the vector used to shift the bounds
*/
PX_FORCE_INLINE void shift(const PxVec3& shift)
{
::physx::PxBounds3 elemBounds;
decode(elemBounds);
elemBounds.minimum -= shift;
elemBounds.maximum -= shift;
encode(elemBounds);
}
/*
\brief Test if this aabb lies entirely inside another aabb
\param[in] box is the other box
\return True if this aabb lies entirely inside box
*/
PX_INLINE bool isInside(const IntegerAABB& box) const
{
if(box.mMinMax[MIN_X]>mMinMax[MIN_X]) return false;
if(box.mMinMax[MIN_Y]>mMinMax[MIN_Y]) return false;
if(box.mMinMax[MIN_Z]>mMinMax[MIN_Z]) return false;
if(box.mMinMax[MAX_X]<mMinMax[MAX_X]) return false;
if(box.mMinMax[MAX_Y]<mMinMax[MAX_Y]) return false;
if(box.mMinMax[MAX_Z]<mMinMax[MAX_Z]) return false;
return true;
}
/*
\brief Test if this aabb and another intersect
\param[in] b is the other box
\return True if this aabb and b intersect
*/
PX_FORCE_INLINE bool intersects(const IntegerAABB& b) const
{
return !(b.mMinMax[MIN_X] > mMinMax[MAX_X] || mMinMax[MIN_X] > b.mMinMax[MAX_X] ||
b.mMinMax[MIN_Y] > mMinMax[MAX_Y] || mMinMax[MIN_Y] > b.mMinMax[MAX_Y] ||
b.mMinMax[MIN_Z] > mMinMax[MAX_Z] || mMinMax[MIN_Z] > b.mMinMax[MAX_Z]);
}
PX_FORCE_INLINE bool intersects1D(const IntegerAABB& b, const PxU32 axis) const
{
const PxU32 maxAxis = axis + 3;
return !(b.mMinMax[axis] > mMinMax[maxAxis] || mMinMax[axis] > b.mMinMax[maxAxis]);
}
/*
\brief Expand bounds to include another
\note This is used to compute the aggregate bounds of multiple shape bounds
\param[in] b is the bounds to be included
*/
PX_FORCE_INLINE void include(const IntegerAABB& b)
{
mMinMax[MIN_X] = PxMin(mMinMax[MIN_X], b.mMinMax[MIN_X]);
mMinMax[MIN_Y] = PxMin(mMinMax[MIN_Y], b.mMinMax[MIN_Y]);
mMinMax[MIN_Z] = PxMin(mMinMax[MIN_Z], b.mMinMax[MIN_Z]);
mMinMax[MAX_X] = PxMax(mMinMax[MAX_X], b.mMinMax[MAX_X]);
mMinMax[MAX_Y] = PxMax(mMinMax[MAX_Y], b.mMinMax[MAX_Y]);
mMinMax[MAX_Z] = PxMax(mMinMax[MAX_Z], b.mMinMax[MAX_Z]);
}
/*
\brief Set the bounds to (max, max, max), (min, min, min)
*/
PX_INLINE void setEmpty()
{
mMinMax[MIN_X] = mMinMax[MIN_Y] = mMinMax[MIN_Z] = 0xff7fffff; //PX_IR(PX_MAX_F32);
mMinMax[MAX_X] = mMinMax[MAX_Y] = mMinMax[MAX_Z] = 0x00800000; ///PX_IR(0.0f);
}
ValType mMinMax[6];
private:
enum
{
eGRID_SNAP_VAL = 4
};
};
PX_FORCE_INLINE ValType encodeMin(const PxBounds3& bounds, PxU32 axis, PxReal contactDistance)
{
const PxReal val = bounds.minimum[axis] - contactDistance;
const PxU32 min = PxUnionCast<PxU32, PxF32>(val);
const PxU32 m = IntegerAABB::encodeFloatMin(min);
return m;
}
PX_FORCE_INLINE ValType encodeMax(const PxBounds3& bounds, PxU32 axis, PxReal contactDistance)
{
const PxReal val = bounds.maximum[axis] + contactDistance;
const PxU32 max = PxUnionCast<PxU32, PxF32>(val);
const PxU32 m = IntegerAABB::encodeFloatMax(max) | (1<<2);
return m;
}
} //namespace Bp
} //namespace physx
#endif
| 9,809 | C | 30.543408 | 117 | 0.713223 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpFiltering.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 "BpFiltering.h"
using namespace physx;
using namespace Bp;
BpFilter::BpFilter(bool discardKineKine, bool discardStaticKine)
{
for(int j = 0; j < Bp::FilterType::COUNT; j++)
for(int i = 0; i < Bp::FilterType::COUNT; i++)
mLUT[j][i] = false;
mLUT[Bp::FilterType::STATIC][Bp::FilterType::DYNAMIC] = mLUT[Bp::FilterType::DYNAMIC][Bp::FilterType::STATIC] = true;
mLUT[Bp::FilterType::STATIC][Bp::FilterType::KINEMATIC] = mLUT[Bp::FilterType::KINEMATIC][Bp::FilterType::STATIC] = !discardStaticKine;
mLUT[Bp::FilterType::DYNAMIC][Bp::FilterType::KINEMATIC] = mLUT[Bp::FilterType::KINEMATIC][Bp::FilterType::DYNAMIC] = true;
mLUT[Bp::FilterType::DYNAMIC][Bp::FilterType::DYNAMIC] = true;
mLUT[Bp::FilterType::KINEMATIC][Bp::FilterType::KINEMATIC] = !discardKineKine;
mLUT[Bp::FilterType::STATIC][Bp::FilterType::AGGREGATE] = mLUT[Bp::FilterType::AGGREGATE][Bp::FilterType::STATIC] = true;
mLUT[Bp::FilterType::KINEMATIC][Bp::FilterType::AGGREGATE] = mLUT[Bp::FilterType::AGGREGATE][Bp::FilterType::KINEMATIC] = true;
mLUT[Bp::FilterType::DYNAMIC][Bp::FilterType::AGGREGATE] = mLUT[Bp::FilterType::AGGREGATE][Bp::FilterType::DYNAMIC] = true;
mLUT[Bp::FilterType::AGGREGATE][Bp::FilterType::AGGREGATE] = true;
//Enable soft body interactions
mLUT[Bp::FilterType::SOFTBODY][Bp::FilterType::DYNAMIC] = mLUT[Bp::FilterType::DYNAMIC][Bp::FilterType::SOFTBODY] = true;
mLUT[Bp::FilterType::SOFTBODY][Bp::FilterType::STATIC] = mLUT[Bp::FilterType::STATIC][Bp::FilterType::SOFTBODY] = true;
mLUT[Bp::FilterType::SOFTBODY][Bp::FilterType::KINEMATIC] = mLUT[Bp::FilterType::KINEMATIC][Bp::FilterType::SOFTBODY] = true;
mLUT[Bp::FilterType::SOFTBODY][Bp::FilterType::SOFTBODY] = true;
//Enable particle system interactions
mLUT[Bp::FilterType::PARTICLESYSTEM][Bp::FilterType::DYNAMIC] = mLUT[Bp::FilterType::DYNAMIC][Bp::FilterType::PARTICLESYSTEM] = true;
mLUT[Bp::FilterType::PARTICLESYSTEM][Bp::FilterType::STATIC] = mLUT[Bp::FilterType::STATIC][Bp::FilterType::PARTICLESYSTEM] = true;
mLUT[Bp::FilterType::PARTICLESYSTEM][Bp::FilterType::KINEMATIC] = mLUT[Bp::FilterType::KINEMATIC][Bp::FilterType::PARTICLESYSTEM] = true;
mLUT[Bp::FilterType::PARTICLESYSTEM][Bp::FilterType::PARTICLESYSTEM] = true;
}
BpFilter::~BpFilter()
{
}
| 3,954 | C++ | 56.31884 | 138 | 0.747092 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseUpdate.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 "BpBroadPhase.h"
#include "common/PxProfileZone.h"
#include "foundation/PxBitMap.h"
using namespace physx;
using namespace Bp;
#if PX_CHECKED
bool BroadPhaseUpdateData::isValid(const BroadPhaseUpdateData& updateData, const BroadPhase& bp, const bool skipBoundValidation, PxU64 contextID)
{
PX_PROFILE_ZONE("BroadPhaseUpdateData::isValid", contextID);
return (updateData.isValid(skipBoundValidation) && bp.isValid(updateData));
}
static bool testHandles(PxU32 size, const BpHandle* handles, const PxU32 capacity, const Bp::FilterGroup::Enum* groups, const PxBounds3* bounds, PxBitMap& bitmap)
{
if(!handles && size)
return false;
/* ValType minVal=0;
ValType maxVal=0xffffffff;*/
for(PxU32 i=0;i<size;i++)
{
const BpHandle h = handles[i];
if(h>=capacity)
return false;
// Array in ascending order of id.
if(i>0 && (h < handles[i-1]))
return false;
if(groups && groups[h]==FilterGroup::eINVALID)
return false;
bitmap.set(h);
if(bounds)
{
if(!bounds[h].isFinite())
return false;
for(PxU32 j=0;j<3;j++)
{
//Max must be greater than min.
if(bounds[h].minimum[j]>bounds[h].maximum[j])
return false;
#if 0
//Bounds have an upper limit.
if(bounds[created[i]].getMax(j)>=maxVal)
return false;
//Bounds have a lower limit.
if(bounds[created[i]].getMin(j)<=minVal)
return false;
//Max must be odd.
if(4 != (bounds[created[i]].getMax(j) & 4))
return false;
//Min must be even.
if(0 != (bounds[created[i]].getMin(j) & 4))
return false;
#endif
}
}
}
return true;
}
static bool testBitmap(const PxBitMap& bitmap, PxU32 size, const BpHandle* handles)
{
while(size--)
{
const BpHandle h = *handles++;
if(bitmap.test(h))
return false;
}
return true;
}
bool BroadPhaseUpdateData::isValid(const bool skipBoundValidation) const
{
const PxBounds3* bounds = skipBoundValidation ? NULL : getAABBs();
const PxU32 boxesCapacity = getCapacity();
const Bp::FilterGroup::Enum* groups = getGroups();
PxBitMap createdBitmap; createdBitmap.resizeAndClear(boxesCapacity);
PxBitMap updatedBitmap; updatedBitmap.resizeAndClear(boxesCapacity);
PxBitMap removedBitmap; removedBitmap.resizeAndClear(boxesCapacity);
if(!testHandles(getNumCreatedHandles(), getCreatedHandles(), boxesCapacity, groups, bounds, createdBitmap))
return false;
if(!testHandles(getNumUpdatedHandles(), getUpdatedHandles(), boxesCapacity, groups, bounds, updatedBitmap))
return false;
if(!testHandles(getNumRemovedHandles(), getRemovedHandles(), boxesCapacity, NULL, NULL, removedBitmap))
return false;
if(1)
{
// Created/updated
if(!testBitmap(createdBitmap, getNumUpdatedHandles(), getUpdatedHandles()))
return false;
// Created/removed
if(!testBitmap(createdBitmap, getNumRemovedHandles(), getRemovedHandles()))
return false;
// Updated/removed
if(!testBitmap(updatedBitmap, getNumRemovedHandles(), getRemovedHandles()))
return false;
}
return true;
}
#endif
| 4,695 | C++ | 31.611111 | 162 | 0.732055 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseSap.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef BP_BROADPHASE_SAP_H
#define BP_BROADPHASE_SAP_H
#include "BpBroadPhase.h"
#include "BpBroadPhaseSapAux.h"
#include "CmPool.h"
#include "CmTask.h"
namespace physx
{
class PxcScratchAllocator;
namespace Gu
{
class Axes;
}
namespace Bp
{
class SapEndPoint;
class IntegerAABB;
class BroadPhaseBatchUpdateWorkTask: public Cm::Task
{
public:
BroadPhaseBatchUpdateWorkTask(PxU64 contextId=0) :
Cm::Task (contextId),
mSap (NULL),
mAxis (0xffffffff),
mPairs (NULL),
mPairsSize (0),
mPairsCapacity (0)
{
}
virtual void runInternal();
virtual const char* getName() const { return "BpBroadphaseSap.batchUpdate"; }
void set(class BroadPhaseSap* sap, const PxU32 axis) {mSap = sap; mAxis = axis;}
BroadPhasePair* getPairs() const {return mPairs;}
PxU32 getPairsSize() const {return mPairsSize;}
PxU32 getPairsCapacity() const {return mPairsCapacity;}
void setPairs(BroadPhasePair* pairs, const PxU32 pairsCapacity) {mPairs = pairs; mPairsCapacity = pairsCapacity;}
void setNumPairs(const PxU32 pairsSize) {mPairsSize=pairsSize;}
private:
class BroadPhaseSap* mSap;
PxU32 mAxis;
BroadPhasePair* mPairs;
PxU32 mPairsSize;
PxU32 mPairsCapacity;
};
//KS - TODO, this could be reduced to U16 in smaller scenes
struct BroadPhaseActivityPocket
{
PxU32 mStartIndex;
PxU32 mEndIndex;
};
class BroadPhaseSap : public BroadPhase
{
PX_NOCOPY(BroadPhaseSap)
public:
friend class BroadPhaseBatchUpdateWorkTask;
friend class SapUpdateWorkTask;
friend class SapPostUpdateWorkTask;
BroadPhaseSap(const PxU32 maxNbBroadPhaseOverlaps, const PxU32 maxNbStaticShapes, const PxU32 maxNbDynamicShapes, PxU64 contextID);
virtual ~BroadPhaseSap();
// BroadPhase
virtual PxBroadPhaseType::Enum getType() const PX_OVERRIDE { return PxBroadPhaseType::eSAP; }
virtual void release() PX_OVERRIDE;
virtual void update(PxcScratchAllocator* scratchAllocator, const BroadPhaseUpdateData& updateData, physx::PxBaseTask* continuation) PX_OVERRIDE;
virtual void preBroadPhase(const Bp::BroadPhaseUpdateData&) PX_OVERRIDE {}
virtual void fetchBroadPhaseResults() PX_OVERRIDE {}
virtual const BroadPhasePair* getCreatedPairs(PxU32& nbCreatedPairs) const PX_OVERRIDE { nbCreatedPairs = mCreatedPairsSize; return mCreatedPairsArray; }
virtual const BroadPhasePair* getDeletedPairs(PxU32& nbDeletedPairs) const PX_OVERRIDE { nbDeletedPairs = mDeletedPairsSize; return mDeletedPairsArray; }
virtual void freeBuffers() PX_OVERRIDE;
virtual void shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances) PX_OVERRIDE;
#if PX_CHECKED
virtual bool isValid(const BroadPhaseUpdateData& updateData) const PX_OVERRIDE;
#endif
//~BroadPhase
private:
void resizeBuffers();
PxcScratchAllocator* mScratchAllocator;
//Data passed in from updateV.
const BpHandle* mCreated;
PxU32 mCreatedSize;
const BpHandle* mRemoved;
PxU32 mRemovedSize;
const BpHandle* mUpdated;
PxU32 mUpdatedSize;
const PxBounds3* mBoxBoundsMinMax;
const Bp::FilterGroup::Enum*mBoxGroups;
const BpFilter* mFilter;
const PxReal* mContactDistance;
PxU32 mBoxesCapacity;
//Boxes.
SapBox1D* mBoxEndPts[3]; //Position of box min/max in sorted arrays of end pts (needs to have mBoxesCapacity).
//End pts (endpts of boxes sorted along each axis).
ValType* mEndPointValues[3]; //Sorted arrays of min and max box coords
BpHandle* mEndPointDatas[3]; //Corresponding owner id and isMin/isMax for each entry in the sorted arrays of min and max box coords.
PxU8* mBoxesUpdated;
BpHandle* mSortedUpdateElements;
BroadPhaseActivityPocket* mActivityPockets;
BpHandle* mListNext;
BpHandle* mListPrev;
PxU32 mBoxesSize; //Number of sorted boxes + number of unsorted (new) boxes
PxU32 mBoxesSizePrev; //Number of sorted boxes
PxU32 mEndPointsCapacity; //Capacity of sorted arrays.
//Default maximum number of overlap pairs
PxU32 mDefaultPairsCapacity;
//Box-box overlap pairs created or removed each update.
BpHandle* mData;
PxU32 mDataSize;
PxU32 mDataCapacity;
//All current box-box overlap pairs.
SapPairManager mPairs;
//Created and deleted overlap pairs reported back through api.
BroadPhasePair* mCreatedPairsArray;
PxU32 mCreatedPairsSize;
PxU32 mCreatedPairsCapacity;
BroadPhasePair* mDeletedPairsArray;
PxU32 mDeletedPairsSize;
PxU32 mDeletedPairsCapacity;
PxU32 mActualDeletedPairSize;
bool setUpdateData(const BroadPhaseUpdateData& updateData);
void update();
void postUpdate();
//Batch create/remove/update.
void batchCreate();
void batchRemove();
void batchUpdate();
void batchUpdate(const PxU32 Axis, BroadPhasePair*& pairs, PxU32& pairsSize, PxU32& pairsCapacity);
void batchUpdateFewUpdates(const PxU32 Axis, BroadPhasePair*& pairs, PxU32& pairsSize, PxU32& pairsCapacity);
void ComputeSortedLists( //const PxVec4& globalMin, const PxVec4& globalMax,
BpHandle* PX_RESTRICT newBoxIndicesSorted, PxU32& newBoxIndicesCount, BpHandle* PX_RESTRICT oldBoxIndicesSorted, PxU32& oldBoxIndicesCount,
bool& allNewBoxesStatics, bool& allOldBoxesStatics);
BroadPhaseBatchUpdateWorkTask mBatchUpdateTasks[3];
const PxU64 mContextID;
#if PX_DEBUG
bool isSelfOrdered() const;
bool isSelfConsistent() const;
#endif
};
} //namespace Bp
} //namespace physx
#endif //BP_BROADPHASE_SAP_H
| 7,399 | C | 33.90566 | 155 | 0.73537 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseMBP.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 "BpBroadPhaseMBP.h"
#include "BpBroadPhaseShared.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxMemory.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxHashSet.h"
#include "common/PxProfileZone.h"
#include "CmRadixSort.h"
#include "CmUtils.h"
using namespace physx::aos;
//#define CHECK_NB_OVERLAPS
#define USE_FULLY_INSIDE_FLAG
//#define MBP_USE_NO_CMP_OVERLAP_3D // Seems slower
//HWSCAN: reverse bits in fully-inside-flag bitmaps because the code gives us indices for which bits are set (and we want the opposite)
#define HWSCAN
using namespace physx;
using namespace Bp;
using namespace Cm;
static PX_FORCE_INLINE MBP_Handle encodeHandle(MBP_ObjectIndex objectIndex, PxU32 flipFlop, bool isStatic)
{
/* objectIndex += objectIndex;
objectIndex |= flipFlop;
return objectIndex;*/
return (objectIndex<<2)|(flipFlop<<1)|PxU32(isStatic);
}
static PX_FORCE_INLINE MBP_ObjectIndex decodeHandle_Index(MBP_Handle handle)
{
// return handle>>1;
return handle>>2;
}
static PX_FORCE_INLINE PxU32 decodeHandle_IsStatic(MBP_Handle handle)
{
return handle&1;
}
#define MBP_ALLOC(x) PX_ALLOC(x, "MBP")
#define MBP_ALLOC_TMP(x) PX_ALLOC(x, "MBP_TMP")
#define MBP_FREE(x) PX_FREE(x)
#define INVALID_ID 0xffffffff
typedef MBP_Index* MBP_Mapping;
/* PX_FORCE_INLINE PxU32 encodeFloat(const float val)
{
// We may need to check on -0 and 0
// But it should make no practical difference.
PxU32 ir = IR(val);
if(ir & 0x80000000) //negative?
ir = ~ir;//reverse sequence of negative numbers
else
ir |= 0x80000000; // flip sign
return ir;
}*/
namespace internalMBP
{
struct RegionHandle : public PxUserAllocated
{
PxU16 mHandle; // Handle from region
PxU16 mInternalBPHandle; // Index of region data within mRegions
};
enum MBPFlags
{
MBP_FLIP_FLOP = (1<<1),
MBP_REMOVED = (1<<2) // ### added for TA24714, not needed otherwise
};
// We have one of those for each of the "200K" objects so we should optimize this size as much as possible
struct MBP_Object : public PxUserAllocated
{
BpHandle mUserID; // Handle sent to us by the AABB manager
PxU16 mNbHandles; // Number of regions the object is part of
PxU16 mFlags; // MBPFlags ### only 1 bit used in the end
PX_FORCE_INLINE bool getFlipFlop() const { return (mFlags & MBP_FLIP_FLOP)==0; }
union
{
RegionHandle mHandle;
PxU32 mHandlesIndex;
};
};
// This one is used in each Region
struct MBPEntry : public PxUserAllocated
{
PX_FORCE_INLINE MBPEntry()
{
mMBPHandle = INVALID_ID;
}
// ### mIndex could be PxU16 but beware, we store mFirstFree there
PxU32 mIndex; // Out-to-in, maps user handle to internal array. mIndex indexes either the static or dynamic array.
MBP_Handle mMBPHandle; // MBP-level handle (the one returned to users)
#if PX_DEBUG
bool mUpdated;
#endif
PX_FORCE_INLINE PxU32 isStatic() const
{
return decodeHandle_IsStatic(mMBPHandle);
}
};
///////////////////////////////////////////////////////////////////////////////
//#define BIT_ARRAY_STACK 512
static PX_FORCE_INLINE PxU32 bitsToDwords(PxU32 nbBits)
{
return (nbBits>>5) + ((nbBits&31) ? 1 : 0);
}
// Use that one instead of an array of bools. Takes less ram, nearly as fast [no bounds checkings and so on].
class BitArray
{
public:
BitArray();
BitArray(PxU32 nbBits);
~BitArray();
bool init(PxU32 nbBits);
void empty();
void resize(PxU32 nbBits);
PX_FORCE_INLINE void setBitChecked(PxU32 bitNumber)
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
resize(bitNumber);
mBits[index] |= 1<<(bitNumber&31);
}
PX_FORCE_INLINE void clearBitChecked(PxU32 bitNumber)
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
resize(bitNumber);
mBits[index] &= ~(1<<(bitNumber&31));
}
// Data management
PX_FORCE_INLINE void setBit(PxU32 bitNumber) { mBits[bitNumber>>5] |= 1<<(bitNumber&31); }
PX_FORCE_INLINE void clearBit(PxU32 bitNumber) { mBits[bitNumber>>5] &= ~(1<<(bitNumber&31)); }
PX_FORCE_INLINE void toggleBit(PxU32 bitNumber) { mBits[bitNumber>>5] ^= 1<<(bitNumber&31); }
PX_FORCE_INLINE void clearAll() { PxMemZero(mBits, mSize*4); }
PX_FORCE_INLINE void setAll() { PxMemSet(mBits, 0xff, mSize*4); }
// Data access
PX_FORCE_INLINE PxIntBool isSet(PxU32 bitNumber) const { return PxIntBool(mBits[bitNumber>>5] & (1<<(bitNumber&31))); }
PX_FORCE_INLINE PxIntBool isSetChecked(PxU32 bitNumber) const
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
return 0;
return PxIntBool(mBits[index] & (1<<(bitNumber&31)));
}
PX_FORCE_INLINE const PxU32* getBits() const { return mBits; }
PX_FORCE_INLINE PxU32 getSize() const { return mSize; }
// PT: replicate PxBitMap stuff for temp testing
PxU32 findLast() const
{
for(PxU32 i = mSize; i-- > 0;)
{
if(mBits[i])
return (i<<5)+PxHighestSetBit(mBits[i]);
}
return PxU32(0);
}
protected:
PxU32* mBits; //!< Array of bits
PxU32 mSize; //!< Size of the array in dwords
#ifdef BIT_ARRAY_STACK
PxU32 mStack[BIT_ARRAY_STACK];
#endif
};
///////////////////////////////////////////////////////////////////////////////
BitArray::BitArray() : mBits(NULL), mSize(0)
{
}
BitArray::BitArray(PxU32 nbBits) : mBits(NULL), mSize(0)
{
init(nbBits);
}
BitArray::~BitArray()
{
empty();
}
void BitArray::empty()
{
#ifdef BIT_ARRAY_STACK
if(mBits!=mStack)
#endif
MBP_FREE(mBits);
mBits = NULL;
mSize = 0;
}
bool BitArray::init(PxU32 nbBits)
{
mSize = bitsToDwords(nbBits);
// Get ram for n bits
#ifdef BIT_ARRAY_STACK
if(mBits!=mStack)
#endif
MBP_FREE(mBits);
#ifdef BIT_ARRAY_STACK
if(mSize>BIT_ARRAY_STACK)
#endif
mBits = reinterpret_cast<PxU32*>(MBP_ALLOC(sizeof(PxU32)*mSize));
#ifdef BIT_ARRAY_STACK
else
mBits = mStack;
#endif
// Set all bits to 0
clearAll();
return true;
}
void BitArray::resize(PxU32 nbBits)
{
const PxU32 newSize = bitsToDwords(nbBits+128);
PxU32* newBits = NULL;
#ifdef BIT_ARRAY_STACK
if(newSize>BIT_ARRAY_STACK)
#endif
{
// Old buffer was stack or allocated, new buffer is allocated
newBits = reinterpret_cast<PxU32*>(MBP_ALLOC(sizeof(PxU32)*newSize));
if(mSize)
PxMemCopy(newBits, mBits, sizeof(PxU32)*mSize);
}
#ifdef BIT_ARRAY_STACK
else
{
newBits = mStack;
if(mSize>BIT_ARRAY_STACK)
{
// Old buffer was allocated, new buffer is stack => copy to stack, shrink
CopyMemory(newBits, mBits, sizeof(PxU32)*BIT_ARRAY_STACK);
}
else
{
// Old buffer was stack, new buffer is stack => keep working on the same stack buffer, nothing to do
}
}
#endif
const PxU32 remain = newSize - mSize;
if(remain)
PxMemZero(newBits + mSize, remain*sizeof(PxU32));
#ifdef BIT_ARRAY_STACK
if(mBits!=mStack)
#endif
MBP_FREE(mBits);
mBits = newBits;
mSize = newSize;
}
#ifdef USE_FULLY_INSIDE_FLAG
static PX_FORCE_INLINE void setBit(BitArray& bitmap, MBP_ObjectIndex objectIndex)
{
#ifdef HWSCAN
bitmap.clearBitChecked(objectIndex); //HWSCAN
#else
bitmap.setBitChecked(objectIndex);
#endif
}
static PX_FORCE_INLINE void clearBit(BitArray& bitmap, MBP_ObjectIndex objectIndex)
{
#ifdef HWSCAN
bitmap.setBitChecked(objectIndex); // HWSCAN
#else
bitmap.clearBitChecked(objectIndex);
#endif
}
#endif
///////////////////////////////////////////////////////////////////////////////
#ifdef MBP_SIMD_OVERLAP
typedef SIMD_AABB MBP_AABB;
#else
typedef IAABB MBP_AABB;
#endif
struct MBPEntry;
struct RegionHandle;
struct MBP_Object;
class MBP_PairManager : public PairManagerData
{
public:
MBP_PairManager();
~MBP_PairManager();
InternalPair* addPair (PxU32 id0, PxU32 id1);
// bool removePair (PxU32 id0, PxU32 id1);
bool computeCreatedDeletedPairs (const MBP_Object* objects, BroadPhaseMBP* mbp, const BitArray& updated, const BitArray& removed);
const Bp::FilterGroup::Enum* mGroups;
const MBP_Object* mObjects;
const bool* mLUT;
};
///////////////////////////////////////////////////////////////////////////
#define STACK_BUFFER_SIZE 256
struct MBPOS_TmpBuffers
{
MBPOS_TmpBuffers();
~MBPOS_TmpBuffers();
void allocateSleeping(PxU32 nbSleeping, PxU32 nbSentinels);
void allocateUpdated(PxU32 nbUpdated, PxU32 nbSentinels);
// PT: wtf, why doesn't the 128 version compile?
// MBP_AABB PX_ALIGN(128, mSleepingDynamicBoxes_Stack[STACK_BUFFER_SIZE]);
// MBP_AABB PX_ALIGN(128, mUpdatedDynamicBoxes_Stack[STACK_BUFFER_SIZE]);
MBP_AABB PX_ALIGN(16, mSleepingDynamicBoxes_Stack[STACK_BUFFER_SIZE]);
MBP_AABB PX_ALIGN(16, mUpdatedDynamicBoxes_Stack[STACK_BUFFER_SIZE]);
MBP_Index mInToOut_Dynamic_Sleeping_Stack[STACK_BUFFER_SIZE];
PxU32 mNbSleeping;
PxU32 mNbUpdated;
MBP_Index* mInToOut_Dynamic_Sleeping;
MBP_AABB* mSleepingDynamicBoxes;
MBP_AABB* mUpdatedDynamicBoxes;
};
struct BIP_Input
{
BIP_Input() :
mObjects (NULL),
mNbUpdatedBoxes (0),
mNbStaticBoxes (0),
mDynamicBoxes (NULL),
mStaticBoxes (NULL),
mInToOut_Static (NULL),
mInToOut_Dynamic(NULL),
mNeeded (false)
{
}
const MBPEntry* mObjects;
PxU32 mNbUpdatedBoxes;
PxU32 mNbStaticBoxes;
const MBP_AABB* mDynamicBoxes;
const MBP_AABB* mStaticBoxes;
const MBP_Index* mInToOut_Static;
const MBP_Index* mInToOut_Dynamic;
bool mNeeded;
};
struct BoxPruning_Input
{
BoxPruning_Input() :
mObjects (NULL),
mUpdatedDynamicBoxes (NULL),
mSleepingDynamicBoxes (NULL),
mInToOut_Dynamic (NULL),
mInToOut_Dynamic_Sleeping (NULL),
mNbUpdated (0),
mNbNonUpdated (0),
mNeeded (false)
{
}
const MBPEntry* mObjects;
const MBP_AABB* mUpdatedDynamicBoxes;
const MBP_AABB* mSleepingDynamicBoxes;
const MBP_Index* mInToOut_Dynamic;
const MBP_Index* mInToOut_Dynamic_Sleeping;
PxU32 mNbUpdated;
PxU32 mNbNonUpdated;
bool mNeeded;
BIP_Input mBIPInput;
};
class Region : public PxUserAllocated
{
PX_NOCOPY(Region)
public:
Region();
~Region();
void updateObject(const MBP_AABB& bounds, MBP_Index handle);
MBP_Index addObject(const MBP_AABB& bounds, MBP_Handle mbpHandle, bool isStatic);
void removeObject(MBP_Index handle);
MBP_Handle retrieveBounds(MBP_AABB& bounds, MBP_Index handle) const;
void setBounds(MBP_Index handle, const MBP_AABB& bounds);
void prepareOverlaps();
void findOverlaps(MBP_PairManager& pairManager);
// private:
BoxPruning_Input PX_ALIGN(16, mInput);
PxU32 mNbObjects;
PxU32 mMaxNbObjects;
PxU32 mFirstFree;
MBPEntry* mObjects; // All objects, indexed by user handle
PxU32 mMaxNbStaticBoxes;
PxU32 mNbStaticBoxes;
PxU32 mMaxNbDynamicBoxes;
PxU32 mNbDynamicBoxes;
MBP_AABB* mStaticBoxes;
MBP_AABB* mDynamicBoxes;
MBP_Mapping mInToOut_Static; // Maps static boxes to mObjects
MBP_Mapping mInToOut_Dynamic; // Maps dynamic boxes to mObjects
PxU32* mPosList;
PxU32 mNbUpdatedBoxes;
PxU32 mPrevNbUpdatedBoxes;
BitArray mStaticBits;
RadixSortBuffered mRS;
bool mNeedsSorting;
bool mNeedsSortingSleeping;
MBPOS_TmpBuffers mTmpBuffers;
void optimizeMemory();
void resizeObjects();
void staticSort();
void preparePruning(MBPOS_TmpBuffers& buffers);
void prepareBIPPruning(const MBPOS_TmpBuffers& buffers);
};
///////////////////////////////////////////////////////////////////////////
// We have one of those for each Region within the MBP
struct RegionData : public PxUserAllocated
{
MBP_AABB mBox; // Volume of space controlled by this Region
Region* mBP; // Pointer to Region itself
PxIntBool mOverlap; // True if overlaps other regions
void* mUserData; // Region identifier, reused to contain "first free ID"
};
#define MAX_NB_MBP 256
// #define MAX_NB_MBP 16
class MBP : public PxUserAllocated
{
public:
MBP();
~MBP();
void preallocate(PxU32 nbRegions, PxU32 nbObjects, PxU32 maxNbOverlaps);
void reset();
void freeBuffers();
PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const PxReal* contactDistance);
bool removeRegion(PxU32 handle);
const Region* getRegion(PxU32 i) const;
PX_FORCE_INLINE PxU32 getNbRegions() const { return mNbRegions; }
MBP_Handle addObject(const MBP_AABB& box, BpHandle userID, bool isStatic);
bool removeObject(MBP_Handle handle);
bool updateObject(MBP_Handle handle, const MBP_AABB& box);
bool updateObjectAfterRegionRemoval(MBP_Handle handle, Region* removedRegion);
bool updateObjectAfterNewRegionAdded(MBP_Handle handle, const MBP_AABB& box, Region* addedRegion, PxU32 regionIndex);
void prepareOverlaps();
void findOverlaps(const Bp::FilterGroup::Enum* PX_RESTRICT groups, const bool* PX_RESTRICT lut);
PxU32 finalize(BroadPhaseMBP* mbp);
void shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances);
// private:
PxU32 mNbRegions;
MBP_ObjectIndex mFirstFreeIndex; // First free recycled index for mMBP_Objects
PxU32 mFirstFreeIndexBP; // First free recycled index for mRegions
PxArray<RegionData> mRegions;
PxArray<MBP_Object> mMBP_Objects;
MBP_PairManager mPairManager;
BitArray mUpdatedObjects; // Indexed by MBP_ObjectIndex
BitArray mRemoved; // Indexed by MBP_ObjectIndex
PxArray<PxU32> mHandles[MAX_NB_MBP+1];
PxU32 mFirstFree[MAX_NB_MBP+1];
PX_FORCE_INLINE RegionHandle* getHandles(MBP_Object& currentObject, PxU32 nbHandles);
void purgeHandles(MBP_Object* PX_RESTRICT object, PxU32 nbHandles);
void storeHandles(MBP_Object* PX_RESTRICT object, PxU32 nbHandles, const RegionHandle* PX_RESTRICT handles);
PxArray<PxU32> mOutOfBoundsObjects; // These are BpHandle but the BP interface expects PxU32s
void addToOutOfBoundsArray(BpHandle id);
#ifdef USE_FULLY_INSIDE_FLAG
BitArray mFullyInsideBitmap; // Indexed by MBP_ObjectIndex
#endif
void populateNewRegion(const MBP_AABB& box, Region* addedRegion, PxU32 regionIndex, const PxBounds3* boundsArray, const PxReal* contactDistance);
#ifdef MBP_REGION_BOX_PRUNING
void buildRegionData();
MBP_AABB mSortedRegionBoxes[MAX_NB_MBP];
PxU32 mSortedRegionIndices[MAX_NB_MBP];
PxU32 mNbActiveRegions;
bool mDirtyRegions;
#endif
};
#ifdef MBP_SIMD_OVERLAP
#define MBP_OVERLAP_TEST(x) SIMD_OVERLAP_TEST(x)
#else
#define MBP_OVERLAP_TEST(x) if(intersect2D(box0, x))
#endif
#define DEFAULT_NB_ENTRIES 128
#ifdef MBP_SIMD_OVERLAP
static PX_FORCE_INLINE void initSentinel(SIMD_AABB& box)
{
// box.mMinX = encodeFloat(FLT_MAX)>>1;
box.mMinX = 0xffffffff;
}
#if PX_DEBUG
static PX_FORCE_INLINE bool isSentinel(const SIMD_AABB& box)
{
return box.mMinX == 0xffffffff;
}
#endif
#else
static PX_FORCE_INLINE void initSentinel(MBP_AABB& box)
{
// box.mMinX = encodeFloat(FLT_MAX)>>1;
box.mMinX = 0xffffffff;
}
#if PX_DEBUG
static PX_FORCE_INLINE bool isSentinel(const MBP_AABB& box)
{
return box.mMinX == 0xffffffff;
}
#endif
#endif
}
using namespace internalMBP;
///////////////////////////////////////////////////////////////////////////////
MBP_PairManager::MBP_PairManager() :
mGroups (NULL),
mObjects (NULL),
mLUT (NULL)
{
}
///////////////////////////////////////////////////////////////////////////////
MBP_PairManager::~MBP_PairManager()
{
}
///////////////////////////////////////////////////////////////////////////////
InternalPair* MBP_PairManager::addPair(PxU32 id0, PxU32 id1)
{
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
PX_ASSERT(mGroups);
PX_ASSERT(mObjects);
{
const MBP_ObjectIndex index0 = decodeHandle_Index(id0);
const MBP_ObjectIndex index1 = decodeHandle_Index(id1);
const BpHandle object0 = mObjects[index0].mUserID;
const BpHandle object1 = mObjects[index1].mUserID;
if(!groupFiltering(mGroups[object0], mGroups[object1], mLUT))
return NULL;
}
return addPairInternal(id0, id1);
}
///////////////////////////////////////////////////////////////////////////////
/*bool MBP_PairManager::removePair(PxU32 id0, PxU32 id1)
{
// Order the ids
sort(id0, id1);
const PxU32 hashValue = hash(id0, id1) & mMask;
const InternalPair* p = findPair(id0, id1, hashValue);
if(!p)
return false;
PX_ASSERT(p->getId0()==id0);
PX_ASSERT(p->getId1()==id1);
PairManagerData::removePair(id0, id1, hashValue, getPairIndex(p));
shrinkMemory();
return true;
}*/
///////////////////////////////////////////////////////////////////////////////
#ifdef MBP_SIMD_OVERLAP
#define SIMD_OVERLAP_PRELOAD_BOX0 \
__m128i b = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&box0.mMinY)); \
b = _mm_shuffle_epi32(b, 78);
// PT: technically we don't need the 16 bits from _mm_movemask_epi8, we only
// need the 4 bits from _mm_movemask_ps. Would it be faster? In any case this
// works thanks to the _mm_cmpgt_epi32 which puts the same values in each byte
// of each separate 32bits components.
#define SIMD_OVERLAP_TEST(x) \
const __m128i a = _mm_loadu_si128(reinterpret_cast<const __m128i*>(&x.mMinY)); \
const __m128i d = _mm_cmpgt_epi32(a, b); \
const int mask = _mm_movemask_epi8(d); \
if(mask==0x0000ff00)
#else
#define SIMD_OVERLAP_PRELOAD_BOX0
#endif
#ifdef MBP_USE_NO_CMP_OVERLAP
/*static PX_FORCE_INLINE void initBox(IAABB& box, const PxBounds3& src)
{
box.initFrom2(src);
}*/
#else
static PX_FORCE_INLINE void initBox(IAABB& box, const PxBounds3& src)
{
box.initFrom(src);
}
#endif
Region::Region() :
mNbObjects (0),
mMaxNbObjects (0),
mFirstFree (INVALID_ID),
mObjects (NULL),
mMaxNbStaticBoxes (0),
mNbStaticBoxes (0),
mMaxNbDynamicBoxes (0),
mNbDynamicBoxes (0),
mStaticBoxes (NULL),
mDynamicBoxes (NULL),
mInToOut_Static (NULL),
mInToOut_Dynamic (NULL),
mPosList (NULL),
mNbUpdatedBoxes (0),
mPrevNbUpdatedBoxes (0),
mNeedsSorting (false),
mNeedsSortingSleeping (true)
{
}
Region::~Region()
{
PX_DELETE_ARRAY(mObjects);
MBP_FREE(mPosList);
MBP_FREE(mInToOut_Dynamic);
MBP_FREE(mInToOut_Static);
PX_DELETE_ARRAY(mDynamicBoxes);
PX_DELETE_ARRAY(mStaticBoxes);
}
// Pre-sort static boxes
#define STACK_BUFFER_SIZE_STATIC_SORT 8192
#define DEFAULT_NUM_DYNAMIC_BOXES 1024
void Region::staticSort()
{
// For now this version is only compatible with:
// MBP_USE_WORDS
// MBP_USE_SENTINELS
mNeedsSorting = false;
const PxU32 nbStaticBoxes = mNbStaticBoxes;
if(!nbStaticBoxes)
{
mStaticBits.empty();
return;
}
// PxU32 Time;
// StartProfile(Time);
// Roadmap:
// - gather updated/modified static boxes
// - sort those, and those only
// - merge sorted set with previously existing (and previously sorted set)
// Separate things-to-sort and things-already-sorted
const PxU32 totalSize = sizeof(PxU32)*nbStaticBoxes*4;
PxU8 stackBuffer[STACK_BUFFER_SIZE_STATIC_SORT];
PxU8* tempMemory = totalSize<=STACK_BUFFER_SIZE_STATIC_SORT ? stackBuffer : reinterpret_cast<PxU8*>(MBP_ALLOC_TMP(totalSize));
PxU32* minPosList_ToSort = reinterpret_cast<PxU32*>(tempMemory);
PxU32* minPosList_Sorted = reinterpret_cast<PxU32*>(tempMemory + sizeof(PxU32)*nbStaticBoxes);
PxU32* boxIndices_ToSort = reinterpret_cast<PxU32*>(tempMemory + sizeof(PxU32)*nbStaticBoxes*2);
PxU32* boxIndices_Sorted = reinterpret_cast<PxU32*>(tempMemory + sizeof(PxU32)*nbStaticBoxes*3);
PxU32 nbToSort = 0;
PxU32 nbSorted = 0;
for(PxU32 i=0;i<nbStaticBoxes;i++)
{
if(mStaticBits.isSetChecked(i)) // ### optimize check in that thing
{
minPosList_ToSort[nbToSort] = mStaticBoxes[i].mMinX;
boxIndices_ToSort[nbToSort] = i;
nbToSort++;
}
else
{
minPosList_Sorted[nbSorted] = mStaticBoxes[i].mMinX;
boxIndices_Sorted[nbSorted] = i;
PX_ASSERT(nbSorted==0 || minPosList_Sorted[nbSorted-1]<=minPosList_Sorted[nbSorted]);
nbSorted++;
}
}
PX_ASSERT(nbSorted+nbToSort==nbStaticBoxes);
// EndProfile(Time);
// printf("Part1: %d\n", Time);
// StartProfile(Time);
// Sort things that need sorting
const PxU32* sorted;
RadixSortBuffered RS;
if(nbToSort<DEFAULT_NUM_DYNAMIC_BOXES)
{
sorted = mRS.Sort(minPosList_ToSort, nbToSort, RADIX_UNSIGNED).GetRanks();
}
else
{
sorted = RS.Sort(minPosList_ToSort, nbToSort, RADIX_UNSIGNED).GetRanks();
}
// EndProfile(Time);
// printf("Part2: %d\n", Time);
// StartProfile(Time);
// Allocate final buffers that wil contain the 2 (merged) streams
MBP_Index* newMapping = reinterpret_cast<MBP_Index*>(MBP_ALLOC(sizeof(MBP_Index)*mMaxNbStaticBoxes));
const PxU32 nbStaticSentinels = 2;
MBP_AABB* sortedBoxes = PX_NEW(MBP_AABB)[mMaxNbStaticBoxes+nbStaticSentinels];
initSentinel(sortedBoxes[nbStaticBoxes]);
initSentinel(sortedBoxes[nbStaticBoxes+1]);
// EndProfile(Time);
// printf("Part2b: %d\n", Time);
// StartProfile(Time);
// Merge streams to final buffers
PxU32 offsetSorted = 0;
PxU32 offsetNonSorted = 0;
PxU32 nextCandidateNonSorted = offsetNonSorted<nbToSort ? minPosList_ToSort[sorted[offsetNonSorted]] : 0xffffffff;
PxU32 nextCandidateSorted = offsetSorted<nbSorted ? minPosList_Sorted[offsetSorted] : 0xffffffff;
for(PxU32 i=0;i<nbStaticBoxes;i++)
{
PxU32 boxIndex;
{
// minPosList_Sorted[offsetSorted] = mStaticBoxes[boxIndices_Sorted[offsetSorted]].mMinX;
if(nextCandidateNonSorted<nextCandidateSorted)
{
boxIndex = boxIndices_ToSort[sorted[offsetNonSorted]];
offsetNonSorted++;
nextCandidateNonSorted = offsetNonSorted<nbToSort ? minPosList_ToSort[sorted[offsetNonSorted]] : 0xffffffff;
}
else
{
boxIndex = boxIndices_Sorted[offsetSorted];
offsetSorted++;
nextCandidateSorted = offsetSorted<nbSorted ? minPosList_Sorted[offsetSorted] : 0xffffffff;
}
}
const MBP_Index OwnerIndex = mInToOut_Static[boxIndex];
sortedBoxes[i] = mStaticBoxes[boxIndex];
newMapping[i] = OwnerIndex;
PX_ASSERT(mObjects[OwnerIndex].mIndex==boxIndex);
PX_ASSERT(mObjects[OwnerIndex].isStatic());
mObjects[OwnerIndex].mIndex = i;
}
PX_ASSERT(offsetSorted+offsetNonSorted==nbStaticBoxes);
// EndProfile(Time);
// printf("Part3: %d\n", Time);
// StartProfile(Time);
if(tempMemory!=stackBuffer)
MBP_FREE(tempMemory);
PX_DELETE_ARRAY(mStaticBoxes);
mStaticBoxes = sortedBoxes;
MBP_FREE(mInToOut_Static);
mInToOut_Static = newMapping;
mStaticBits.empty();
// EndProfile(Time);
// printf("Part4: %d\n", Time);
}
void Region::optimizeMemory()
{
// TODO: resize static boxes/mapping, dynamic boxes/mapping, object array
}
void Region::resizeObjects()
{
const PxU32 newMaxNbOjects = mMaxNbObjects ? mMaxNbObjects + DEFAULT_NB_ENTRIES : DEFAULT_NB_ENTRIES;
// const PxU32 newMaxNbOjects = mMaxNbObjects ? mMaxNbObjects*2 : DEFAULT_NB_ENTRIES;
MBPEntry* newObjects = PX_NEW(MBPEntry)[newMaxNbOjects];
if(mNbObjects)
PxMemCopy(newObjects, mObjects, mNbObjects*sizeof(MBPEntry));
#if PX_DEBUG
for(PxU32 i=mNbObjects;i<newMaxNbOjects;i++)
newObjects[i].mUpdated = false;
#endif
PX_DELETE_ARRAY(mObjects);
mObjects = newObjects;
mMaxNbObjects = newMaxNbOjects;
}
static MBP_AABB* resizeBoxes(PxU32 oldNbBoxes, PxU32 newNbBoxes, const MBP_AABB* boxes)
{
MBP_AABB* newBoxes = PX_NEW(MBP_AABB)[newNbBoxes];
if(oldNbBoxes)
PxMemCopy(newBoxes, boxes, oldNbBoxes*sizeof(MBP_AABB));
PX_DELETE_ARRAY(boxes);
return newBoxes;
}
static MBP_Index* resizeMapping(PxU32 oldNbBoxes, PxU32 newNbBoxes, MBP_Index* mapping)
{
MBP_Index* newMapping = reinterpret_cast<MBP_Index*>(MBP_ALLOC(sizeof(MBP_Index)*newNbBoxes));
if(oldNbBoxes)
PxMemCopy(newMapping, mapping, oldNbBoxes*sizeof(MBP_Index));
MBP_FREE(mapping);
return newMapping;
}
static PX_FORCE_INLINE void MTF(MBP_AABB* PX_RESTRICT dynamicBoxes, MBP_Index* PX_RESTRICT inToOut_Dynamic, MBPEntry* PX_RESTRICT objects, const MBP_AABB& bounds, PxU32 frontIndex, MBPEntry& updatedObject)
{
const PxU32 updatedIndex = updatedObject.mIndex;
if(frontIndex!=updatedIndex)
{
const MBP_AABB box0 = dynamicBoxes[frontIndex];
dynamicBoxes[frontIndex] = bounds;
dynamicBoxes[updatedIndex] = box0;
const MBP_Index index0 = inToOut_Dynamic[frontIndex];
inToOut_Dynamic[frontIndex] = inToOut_Dynamic[updatedIndex];
inToOut_Dynamic[updatedIndex] = index0;
objects[index0].mIndex = updatedIndex;
updatedObject.mIndex = frontIndex;
}
else
{
dynamicBoxes[frontIndex] = bounds;
}
}
MBP_Index Region::addObject(const MBP_AABB& bounds, MBP_Handle mbpHandle, bool isStatic)
{
#ifdef MBP_USE_WORDS
PX_ASSERT(mNbObjects<0xffff);
#endif
PX_ASSERT((decodeHandle_IsStatic(mbpHandle) && isStatic) || (!decodeHandle_IsStatic(mbpHandle) && !isStatic));
MBP_Index handle;
if(mFirstFree!=INVALID_ID)
{
handle = MBP_Index(mFirstFree);
mFirstFree = mObjects[handle].mIndex;
}
else
{
if(mMaxNbObjects==mNbObjects)
resizeObjects();
handle = MBP_Index(mNbObjects);
}
mNbObjects++;
///
PxU32 boxIndex;
if(isStatic)
{
if(mMaxNbStaticBoxes==mNbStaticBoxes)
{
const PxU32 newMaxNbBoxes = mMaxNbStaticBoxes ? mMaxNbStaticBoxes + DEFAULT_NB_ENTRIES : DEFAULT_NB_ENTRIES;
// const PxU32 newMaxNbBoxes = mMaxNbStaticBoxes ? mMaxNbStaticBoxes*2 : DEFAULT_NB_ENTRIES;
mStaticBoxes = resizeBoxes(mNbStaticBoxes, newMaxNbBoxes, mStaticBoxes);
mInToOut_Static = resizeMapping(mNbStaticBoxes, newMaxNbBoxes, mInToOut_Static);
mMaxNbStaticBoxes = newMaxNbBoxes;
}
boxIndex = mNbStaticBoxes++;
mStaticBoxes[boxIndex] = bounds;
mInToOut_Static[boxIndex] = handle;
mNeedsSorting = true;
mStaticBits.setBitChecked(boxIndex);
}
else
{
if(mMaxNbDynamicBoxes==mNbDynamicBoxes)
{
const PxU32 newMaxNbBoxes = mMaxNbDynamicBoxes ? mMaxNbDynamicBoxes + DEFAULT_NB_ENTRIES : DEFAULT_NB_ENTRIES;
// const PxU32 newMaxNbBoxes = mMaxNbDynamicBoxes ? mMaxNbDynamicBoxes*2 : DEFAULT_NB_ENTRIES;
mDynamicBoxes = resizeBoxes(mNbDynamicBoxes, newMaxNbBoxes, mDynamicBoxes);
mInToOut_Dynamic = resizeMapping(mNbDynamicBoxes, newMaxNbBoxes, mInToOut_Dynamic);
mMaxNbDynamicBoxes = newMaxNbBoxes;
MBP_FREE(mPosList);
mPosList = reinterpret_cast<PxU32*>(MBP_ALLOC((newMaxNbBoxes+1)*sizeof(PxU32)));
}
boxIndex = mNbDynamicBoxes++;
mDynamicBoxes[boxIndex] = bounds;
mInToOut_Dynamic[boxIndex] = handle;
}
mObjects[handle].mIndex = boxIndex;
mObjects[handle].mMBPHandle = mbpHandle;
#if PX_DEBUG
mObjects[handle].mUpdated = !isStatic;
#endif
if(!isStatic)
{
MTF(mDynamicBoxes, mInToOut_Dynamic, mObjects, bounds, mNbUpdatedBoxes, mObjects[handle]);
mNbUpdatedBoxes++;
mPrevNbUpdatedBoxes = 0;
mNeedsSortingSleeping = true;
PX_ASSERT(mNbUpdatedBoxes<=mNbDynamicBoxes);
}
return handle;
}
// Moves box 'lastIndex' to location 'removedBoxIndex'
static PX_FORCE_INLINE void remove(MBPEntry* PX_RESTRICT objects, MBP_Index* PX_RESTRICT mapping, MBP_AABB* PX_RESTRICT boxes, PxU32 removedBoxIndex, PxU32 lastIndex)
{
const PxU32 movedBoxHandle = mapping[lastIndex];
boxes[removedBoxIndex] = boxes[lastIndex]; // Relocate box data
mapping[removedBoxIndex] = MBP_Index(movedBoxHandle); // Relocate mapping data
MBPEntry& movedObject = objects[movedBoxHandle];
PX_ASSERT(movedObject.mIndex==lastIndex); // Checks index of moved box was indeed its old location
movedObject.mIndex = removedBoxIndex; // Adjust index of moved box to reflect its new location
}
void Region::removeObject(MBP_Index handle)
{
PX_ASSERT(handle<mMaxNbObjects);
MBPEntry& object = mObjects[handle];
/*const*/ PxU32 removedBoxIndex = object.mIndex;
MBP_Index* PX_RESTRICT mapping;
MBP_AABB* PX_RESTRICT boxes;
PxU32 lastIndex;
if(!object.isStatic())
{
mPrevNbUpdatedBoxes = 0;
mNeedsSortingSleeping = true;
PX_ASSERT(mInToOut_Dynamic[removedBoxIndex]==handle);
const bool isUpdated = removedBoxIndex<mNbUpdatedBoxes;
PX_ASSERT(isUpdated==object.mUpdated);
if(isUpdated)
{
PX_ASSERT(mNbUpdatedBoxes);
if(mNbUpdatedBoxes!=mNbDynamicBoxes)
{
// Removing the object will create this pattern, which is wrong:
// UUUUUUUUUUUNNNNNNNNN......... original
// UUUUUU.UUUUNNNNNNNNN......... remove U
// UUUUUUNUUUUNNNNNNNN.......... move N
//
// What we want instead is:
// UUUUUUUUUUUNNNNNNNNN......... original
// UUUUUU.UUUUNNNNNNNNN......... remove U
// UUUUUUUUUU.NNNNNNNNN......... move U
// UUUUUUUUUUNNNNNNNNN.......... move N
const PxU32 lastUpdatedIndex = mNbUpdatedBoxes-1;
remove(mObjects, mInToOut_Dynamic, mDynamicBoxes, removedBoxIndex, lastUpdatedIndex); // Move last U to removed U
//Remove(mObjects, mInToOut_Dynamic, mDynamicBoxes, lastUpdatedIndex, --mNbDynamicBoxes); // Move last N to last U
removedBoxIndex = lastUpdatedIndex;
}
mNbUpdatedBoxes--;
}
// remove(mObjects, mInToOut_Dynamic, mDynamicBoxes, removedBoxIndex, --mNbDynamicBoxes);
mapping = mInToOut_Dynamic;
boxes = mDynamicBoxes;
lastIndex = --mNbDynamicBoxes;
// ### adjust size of mPosList ?
}
else
{
PX_ASSERT(mInToOut_Static[removedBoxIndex]==handle);
mNeedsSorting = true;
mStaticBits.setBitChecked(removedBoxIndex);
// remove(mObjects, mInToOut_Static, mStaticBoxes, removedBoxIndex, --mNbStaticBoxes);
mapping = mInToOut_Static;
boxes = mStaticBoxes;
lastIndex = --mNbStaticBoxes;
}
remove(mObjects, mapping, boxes, removedBoxIndex, lastIndex);
object.mIndex = mFirstFree;
object.mMBPHandle = INVALID_ID;
// printf("Invalid: %d\n", handle);
mFirstFree = handle;
mNbObjects--;
#if PX_DEBUG
object.mUpdated = false;
#endif
}
void Region::updateObject(const MBP_AABB& bounds, MBP_Index handle)
{
PX_ASSERT(handle<mMaxNbObjects);
MBPEntry& object = mObjects[handle];
if(!object.isStatic())
{
// MTF on updated box
const bool isContinuouslyUpdated = object.mIndex<mPrevNbUpdatedBoxes;
if(!isContinuouslyUpdated)
mNeedsSortingSleeping = true;
// printf("%d: %d\n", handle, isContinuouslyUpdated);
const bool isUpdated = object.mIndex<mNbUpdatedBoxes;
PX_ASSERT(isUpdated==object.mUpdated);
if(!isUpdated)
{
#if PX_DEBUG
object.mUpdated = true;
#endif
MTF(mDynamicBoxes, mInToOut_Dynamic, mObjects, bounds, mNbUpdatedBoxes, object);
mNbUpdatedBoxes++;
PX_ASSERT(mNbUpdatedBoxes<=mNbDynamicBoxes);
}
else
{
mDynamicBoxes[object.mIndex] = bounds;
}
}
else
{
mStaticBoxes[object.mIndex] = bounds;
mNeedsSorting = true; // ### not always!
mStaticBits.setBitChecked(object.mIndex);
}
}
MBP_Handle Region::retrieveBounds(MBP_AABB& bounds, MBP_Index handle) const
{
PX_ASSERT(handle<mMaxNbObjects);
const MBPEntry& object = mObjects[handle];
if(!object.isStatic())
bounds = mDynamicBoxes[object.mIndex];
else
bounds = mStaticBoxes[object.mIndex];
return object.mMBPHandle;
}
void Region::setBounds(MBP_Index handle, const MBP_AABB& bounds)
{
PX_ASSERT(handle<mMaxNbObjects);
const MBPEntry& object = mObjects[handle];
if(!object.isStatic())
{
PX_ASSERT(object.mIndex < mNbDynamicBoxes);
mDynamicBoxes[object.mIndex] = bounds;
}
else
{
PX_ASSERT(object.mIndex < mNbStaticBoxes);
mStaticBoxes[object.mIndex] = bounds;
}
}
#ifndef MBP_SIMD_OVERLAP
static PX_FORCE_INLINE PxIntBool intersect2D(const MBP_AABB& a, const MBP_AABB& b)
{
#ifdef MBP_USE_NO_CMP_OVERLAP
// PT: warning, only valid with the special encoding in InitFrom2
const PxU32 bits0 = (b.mMaxY - a.mMinY)&0x80000000;
const PxU32 bits1 = (b.mMaxZ - a.mMinZ)&0x80000000;
const PxU32 bits2 = (a.mMaxY - b.mMinY)&0x80000000;
const PxU32 bits3 = (a.mMaxZ - b.mMinZ)&0x80000000;
const PxU32 mask = bits0|(bits1>>1)|(bits2>>2)|(bits3>>3);
return !mask;
/* const PxU32 d0 = (b.mMaxY<<16)|a.mMaxY;
const PxU32 d0b = (b.mMaxZ<<16)|a.mMaxZ;
const PxU32 d1 = (a.mMinY<<16)|b.mMinY;
const PxU32 d1b = (a.mMinZ<<16)|b.mMinZ;
const PxU32 mask = (d0 - d1) | (d0b - d1b);
return !(mask & 0x80008000);*/
#else
if(//mMaxX < a.mMinX || a.mMaxX < mMinX
// ||
b.mMaxY < a.mMinY || a.mMaxY < b.mMinY
||
b.mMaxZ < a.mMinZ || a.mMaxZ < b.mMinZ
)
return FALSE;
return TRUE;
#endif
}
#endif
#ifdef MBP_USE_NO_CMP_OVERLAP_3D
static PX_FORCE_INLINE bool intersect3D(const MBP_AABB& a, const MBP_AABB& b)
{
// PT: warning, only valid with the special encoding in InitFrom2
const PxU32 bits0 = (b.mMaxY - a.mMinY)&0x80000000;
const PxU32 bits1 = (b.mMaxZ - a.mMinZ)&0x80000000;
const PxU32 bits2 = (a.mMaxY - b.mMinY)&0x80000000;
const PxU32 bits3 = (a.mMaxZ - b.mMinZ)&0x80000000;
const PxU32 bits4 = (b.mMaxX - a.mMinX)&0x80000000;
const PxU32 bits5 = (a.mMaxX - b.mMinX)&0x80000000;
const PxU32 mask = bits0|(bits1>>1)|(bits2>>2)|(bits3>>3)|(bits4>>4)|(bits5>>5);
return !mask;
}
#endif
#ifdef CHECK_NB_OVERLAPS
static PxU32 gNbOverlaps = 0;
#endif
static PX_FORCE_INLINE void outputPair( MBP_PairManager& pairManager,
PxU32 index0, PxU32 index1,
const MBP_Index* PX_RESTRICT inToOut0, const MBP_Index* PX_RESTRICT inToOut1,
const MBPEntry* PX_RESTRICT objects)
{
#ifdef CHECK_NB_OVERLAPS
gNbOverlaps++;
#endif
const MBP_Index objectIndex0 = inToOut0[index0];
const MBP_Index objectIndex1 = inToOut1[index1];
PX_ASSERT(objectIndex0!=objectIndex1);
const MBP_Handle id0 = objects[objectIndex0].mMBPHandle;
const MBP_Handle id1 = objects[objectIndex1].mMBPHandle;
// printf("2: %d %d\n", index0, index1);
// printf("3: %d %d\n", objectIndex0, objectIndex1);
pairManager.addPair(id0, id1);
}
MBPOS_TmpBuffers::MBPOS_TmpBuffers() :
mNbSleeping (0),
mNbUpdated (0),
mInToOut_Dynamic_Sleeping (NULL),
mSleepingDynamicBoxes (NULL),
mUpdatedDynamicBoxes (NULL)
{
}
MBPOS_TmpBuffers::~MBPOS_TmpBuffers()
{
// printf("mNbSleeping: %d\n", mNbSleeping);
if(mInToOut_Dynamic_Sleeping!=mInToOut_Dynamic_Sleeping_Stack)
MBP_FREE(mInToOut_Dynamic_Sleeping);
if(mSleepingDynamicBoxes!=mSleepingDynamicBoxes_Stack)
PX_DELETE_ARRAY(mSleepingDynamicBoxes);
if(mUpdatedDynamicBoxes!=mUpdatedDynamicBoxes_Stack)
PX_DELETE_ARRAY(mUpdatedDynamicBoxes);
mNbSleeping = 0;
mNbUpdated = 0;
}
void MBPOS_TmpBuffers::allocateSleeping(PxU32 nbSleeping, PxU32 nbSentinels)
{
if(nbSleeping>mNbSleeping)
{
if(mInToOut_Dynamic_Sleeping!=mInToOut_Dynamic_Sleeping_Stack)
MBP_FREE(mInToOut_Dynamic_Sleeping);
if(mSleepingDynamicBoxes!=mSleepingDynamicBoxes_Stack)
PX_DELETE_ARRAY(mSleepingDynamicBoxes);
if(nbSleeping+nbSentinels<=STACK_BUFFER_SIZE)
{
mSleepingDynamicBoxes = mSleepingDynamicBoxes_Stack;
mInToOut_Dynamic_Sleeping = mInToOut_Dynamic_Sleeping_Stack;
}
else
{
mSleepingDynamicBoxes = PX_NEW(MBP_AABB)[nbSleeping+nbSentinels];
mInToOut_Dynamic_Sleeping = reinterpret_cast<MBP_Index*>(MBP_ALLOC(sizeof(MBP_Index)*nbSleeping));
}
mNbSleeping = nbSleeping;
}
}
void MBPOS_TmpBuffers::allocateUpdated(PxU32 nbUpdated, PxU32 nbSentinels)
{
if(nbUpdated>mNbUpdated)
{
if(mUpdatedDynamicBoxes!=mUpdatedDynamicBoxes_Stack)
PX_DELETE_ARRAY(mUpdatedDynamicBoxes);
if(nbUpdated+nbSentinels<=STACK_BUFFER_SIZE)
mUpdatedDynamicBoxes = mUpdatedDynamicBoxes_Stack;
else
mUpdatedDynamicBoxes = PX_NEW(MBP_AABB)[nbUpdated+nbSentinels];
mNbUpdated = nbUpdated;
}
}
void Region::preparePruning(MBPOS_TmpBuffers& buffers)
{
PxU32 _saved = mNbUpdatedBoxes;
mNbUpdatedBoxes = 0;
if(mPrevNbUpdatedBoxes!=_saved)
mNeedsSortingSleeping = true;
PxU32 nb = mNbDynamicBoxes;
if(!nb)
{
mInput.mNeeded = false;
mPrevNbUpdatedBoxes = 0;
mNeedsSortingSleeping = true;
return;
}
const MBP_AABB* PX_RESTRICT dynamicBoxes = mDynamicBoxes;
PxU32* PX_RESTRICT posList = mPosList;
#if PX_DEBUG
PxU32 verifyNbUpdated = 0;
for(PxU32 i=0;i<mMaxNbObjects;i++)
{
if(mObjects[i].mUpdated)
verifyNbUpdated++;
}
PX_ASSERT(verifyNbUpdated==_saved);
#endif
// Build main list using the primary axis
PxU32 nbUpdated = 0;
PxU32 nbNonUpdated = 0;
{
nbUpdated = _saved;
nbNonUpdated = nb - _saved;
for(PxU32 i=0;i<nbUpdated;i++)
{
#if PX_DEBUG
const PxU32 objectIndex = mInToOut_Dynamic[i];
PX_ASSERT(mObjects[objectIndex].mUpdated);
mObjects[objectIndex].mUpdated = false;
#endif
posList[i] = dynamicBoxes[i].mMinX;
}
if(mNeedsSortingSleeping)
{
for(PxU32 i=0;i<nbNonUpdated;i++)
{
#if PX_DEBUG
const PxU32 objectIndex = mInToOut_Dynamic[i];
PX_ASSERT(!mObjects[objectIndex].mUpdated);
#endif
PxU32 j = i + nbUpdated;
posList[j] = dynamicBoxes[j].mMinX;
}
}
#if PX_DEBUG
else
{
for(PxU32 i=0;i<nbNonUpdated;i++)
{
const PxU32 objectIndex = mInToOut_Dynamic[i];
PX_ASSERT(!mObjects[objectIndex].mUpdated);
PxU32 j = i + nbUpdated;
PX_ASSERT(posList[j] == dynamicBoxes[j].mMinX);
}
}
#endif
}
PX_ASSERT(nbUpdated==verifyNbUpdated);
PX_ASSERT(nbUpdated+nbNonUpdated==nb);
mNbUpdatedBoxes = nbUpdated;
if(!nbUpdated)
{
mInput.mNeeded = false;
mPrevNbUpdatedBoxes = 0;
mNeedsSortingSleeping = true;
return;
}
mPrevNbUpdatedBoxes = mNbUpdatedBoxes;
///////
// ### TODO: no need to recreate those buffers each frame!
MBP_Index* PX_RESTRICT inToOut_Dynamic_Sleeping = NULL;
MBP_AABB* PX_RESTRICT sleepingDynamicBoxes = NULL;
if(nbNonUpdated)
{
if(mNeedsSortingSleeping)
{
const PxU32* PX_RESTRICT sorted = mRS.Sort(posList+nbUpdated, nbNonUpdated, RADIX_UNSIGNED).GetRanks();
const PxU32 nbSentinels = 2;
buffers.allocateSleeping(nbNonUpdated, nbSentinels);
sleepingDynamicBoxes = buffers.mSleepingDynamicBoxes;
inToOut_Dynamic_Sleeping = buffers.mInToOut_Dynamic_Sleeping;
for(PxU32 i=0;i<nbNonUpdated;i++)
{
const PxU32 sortedIndex = nbUpdated+sorted[i];
sleepingDynamicBoxes[i] = dynamicBoxes[sortedIndex];
inToOut_Dynamic_Sleeping[i] = mInToOut_Dynamic[sortedIndex];
}
initSentinel(sleepingDynamicBoxes[nbNonUpdated]);
initSentinel(sleepingDynamicBoxes[nbNonUpdated+1]);
mNeedsSortingSleeping = false;
}
else
{
sleepingDynamicBoxes = buffers.mSleepingDynamicBoxes;
inToOut_Dynamic_Sleeping = buffers.mInToOut_Dynamic_Sleeping;
#if PX_DEBUG
for(PxU32 i=0;i<nbNonUpdated-1;i++)
PX_ASSERT(sleepingDynamicBoxes[i].mMinX<=sleepingDynamicBoxes[i+1].mMinX);
#endif
}
}
else
{
mNeedsSortingSleeping = true;
}
///////
// posList[nbUpdated] = MAX_PxU32;
// nb = nbUpdated;
// Sort the list
// const PxU32* PX_RESTRICT sorted = mRS.Sort(posList, nbUpdated+1, RADIX_UNSIGNED).GetRanks();
const PxU32* PX_RESTRICT sorted = mRS.Sort(posList, nbUpdated, RADIX_UNSIGNED).GetRanks();
const PxU32 nbSentinels = 2;
buffers.allocateUpdated(nbUpdated, nbSentinels);
MBP_AABB* PX_RESTRICT updatedDynamicBoxes = buffers.mUpdatedDynamicBoxes;
MBP_Index* PX_RESTRICT inToOut_Dynamic = reinterpret_cast<MBP_Index*>(mRS.GetRecyclable());
for(PxU32 i=0;i<nbUpdated;i++)
{
const PxU32 sortedIndex = sorted[i];
updatedDynamicBoxes[i] = dynamicBoxes[sortedIndex];
inToOut_Dynamic[i] = mInToOut_Dynamic[sortedIndex];
}
initSentinel(updatedDynamicBoxes[nbUpdated]);
initSentinel(updatedDynamicBoxes[nbUpdated+1]);
dynamicBoxes = updatedDynamicBoxes;
mInput.mObjects = mObjects; // Can be shared (1)
mInput.mUpdatedDynamicBoxes = updatedDynamicBoxes; // Can be shared (2) => buffers.mUpdatedDynamicBoxes;
mInput.mSleepingDynamicBoxes = sleepingDynamicBoxes;
mInput.mInToOut_Dynamic = inToOut_Dynamic; // Can be shared (3) => (MBP_Index*)mRS.GetRecyclable();
mInput.mInToOut_Dynamic_Sleeping = inToOut_Dynamic_Sleeping;
mInput.mNbUpdated = nbUpdated; // Can be shared (4)
mInput.mNbNonUpdated = nbNonUpdated;
mInput.mNeeded = true;
}
void Region::prepareBIPPruning(const MBPOS_TmpBuffers& buffers)
{
if(!mNbUpdatedBoxes || !mNbStaticBoxes)
{
mInput.mBIPInput.mNeeded = false;
return;
}
mInput.mBIPInput.mObjects = mObjects; // Can be shared (1)
mInput.mBIPInput.mNbUpdatedBoxes = mNbUpdatedBoxes; // Can be shared (4)
mInput.mBIPInput.mNbStaticBoxes = mNbStaticBoxes;
// mInput.mBIPInput.mDynamicBoxes = mDynamicBoxes;
mInput.mBIPInput.mDynamicBoxes = buffers.mUpdatedDynamicBoxes; // Can be shared (2)
mInput.mBIPInput.mStaticBoxes = mStaticBoxes;
mInput.mBIPInput.mInToOut_Static = mInToOut_Static;
mInput.mBIPInput.mInToOut_Dynamic = reinterpret_cast<const MBP_Index*>(mRS.GetRecyclable()); // Can be shared (3)
mInput.mBIPInput.mNeeded = true;
}
static void doCompleteBoxPruning(MBP_PairManager* PX_RESTRICT pairManager, const BoxPruning_Input& input)
{
const MBPEntry* PX_RESTRICT objects = input.mObjects;
const MBP_AABB* PX_RESTRICT updatedDynamicBoxes = input.mUpdatedDynamicBoxes;
const MBP_AABB* PX_RESTRICT sleepingDynamicBoxes = input.mSleepingDynamicBoxes;
const MBP_Index* PX_RESTRICT inToOut_Dynamic = input.mInToOut_Dynamic;
const MBP_Index* PX_RESTRICT inToOut_Dynamic_Sleeping = input.mInToOut_Dynamic_Sleeping;
const PxU32 nbUpdated = input.mNbUpdated;
const PxU32 nbNonUpdated = input.mNbNonUpdated;
//
// PT: find sleeping-dynamics-vs-active-dynamics overlaps
if(nbNonUpdated)
{
const PxU32 nb0 = nbUpdated;
const PxU32 nb1 = nbNonUpdated;
//
PxU32 index0 = 0;
PxU32 runningIndex1 = 0;
while(runningIndex1<nb1 && index0<nb0)
{
const MBP_AABB& box0 = updatedDynamicBoxes[index0];
const PxU32 limit = box0.mMaxX;
SIMD_OVERLAP_PRELOAD_BOX0
const PxU32 l = box0.mMinX;
while(sleepingDynamicBoxes[runningIndex1].mMinX<l)
runningIndex1++;
PxU32 index1 = runningIndex1;
while(sleepingDynamicBoxes[index1].mMinX<=limit)
{
MBP_OVERLAP_TEST(sleepingDynamicBoxes[index1])
{
outputPair(*pairManager, index0, index1, inToOut_Dynamic, inToOut_Dynamic_Sleeping, objects);
}
index1++;
}
index0++;
}
////
index0 = 0;
PxU32 runningIndex0 = 0;
while(runningIndex0<nb0 && index0<nb1)
{
const MBP_AABB& box0 = sleepingDynamicBoxes[index0];
const PxU32 limit = box0.mMaxX;
SIMD_OVERLAP_PRELOAD_BOX0
const PxU32 l = box0.mMinX;
while(updatedDynamicBoxes[runningIndex0].mMinX<=l)
runningIndex0++;
PxU32 index1 = runningIndex0;
while(updatedDynamicBoxes[index1].mMinX<=limit)
{
MBP_OVERLAP_TEST(updatedDynamicBoxes[index1])
{
outputPair(*pairManager, index1, index0, inToOut_Dynamic, inToOut_Dynamic_Sleeping, objects);
}
index1++;
}
index0++;
}
}
///////
// PT: find active-dynamics-vs-active-dynamics overlaps
PxU32 index0 = 0;
PxU32 runningIndex = 0;
while(runningIndex<nbUpdated && index0<nbUpdated)
{
const MBP_AABB& box0 = updatedDynamicBoxes[index0];
const PxU32 limit = box0.mMaxX;
SIMD_OVERLAP_PRELOAD_BOX0
const PxU32 l = box0.mMinX;
while(updatedDynamicBoxes[runningIndex++].mMinX<l);
if(runningIndex<nbUpdated)
{
PxU32 index1 = runningIndex;
while(updatedDynamicBoxes[index1].mMinX<=limit)
{
MBP_OVERLAP_TEST(updatedDynamicBoxes[index1])
{
outputPair(*pairManager, index0, index1, inToOut_Dynamic, inToOut_Dynamic, objects);
}
index1++;
}
}
index0++;
}
}
static void doBipartiteBoxPruning(MBP_PairManager* PX_RESTRICT pairManager, const BIP_Input& input)
{
// ### crashes because the code expects the dynamic array to be sorted, but mDynamicBoxes is not
// ### we should instead modify mNbUpdatedBoxes so that mNbUpdatedBoxes == mNbDynamicBoxes, and
// ### then the proper sorting happens in CompleteBoxPruning (right?)
const PxU32 nb0 = input.mNbUpdatedBoxes;
const PxU32 nb1 = input.mNbStaticBoxes;
const MBPEntry* PX_RESTRICT mObjects = input.mObjects;
const MBP_AABB* PX_RESTRICT dynamicBoxes = input.mDynamicBoxes;
const MBP_AABB* PX_RESTRICT staticBoxes = input.mStaticBoxes;
const MBP_Index* PX_RESTRICT inToOut_Static = input.mInToOut_Static;
const MBP_Index* PX_RESTRICT inToOut_Dynamic = input.mInToOut_Dynamic;
PX_ASSERT(isSentinel(staticBoxes[nb1]));
PX_ASSERT(isSentinel(staticBoxes[nb1+1]));
// const MBP_AABB Saved = staticBoxes[nb1];
// const MBP_AABB Saved1 = staticBoxes[nb1+1];
// initSentinel(((MBP_AABB* PX_RESTRICT)staticBoxes)[nb1]);
// initSentinel(((MBP_AABB* PX_RESTRICT)staticBoxes)[nb1+1]);
//
PxU32 index0 = 0;
PxU32 runningIndex1 = 0;
while(runningIndex1<nb1 && index0<nb0)
{
const MBP_AABB& box0 = dynamicBoxes[index0];
const PxU32 limit = box0.mMaxX;
SIMD_OVERLAP_PRELOAD_BOX0
const PxU32 l = box0.mMinX;
while(staticBoxes[runningIndex1].mMinX<l)
runningIndex1++;
PxU32 index1 = runningIndex1;
while(staticBoxes[index1].mMinX<=limit)
{
MBP_OVERLAP_TEST(staticBoxes[index1])
{
outputPair(*pairManager, index0, index1, inToOut_Dynamic, inToOut_Static, mObjects);
}
index1++;
}
index0++;
}
////
index0 = 0;
PxU32 runningIndex0 = 0;
while(runningIndex0<nb0 && index0<nb1)
{
const MBP_AABB& box0 = staticBoxes[index0];
const PxU32 limit = box0.mMaxX;
SIMD_OVERLAP_PRELOAD_BOX0
const PxU32 l = box0.mMinX;
while(dynamicBoxes[runningIndex0].mMinX<=l)
runningIndex0++;
PxU32 index1 = runningIndex0;
while(dynamicBoxes[index1].mMinX<=limit)
{
MBP_OVERLAP_TEST(dynamicBoxes[index1])
{
outputPair(*pairManager, index1, index0, inToOut_Dynamic, inToOut_Static, mObjects);
}
index1++;
}
index0++;
}
// MBP_FREE(inToOut_Dynamic);
// ((MBP_AABB* PX_RESTRICT)staticBoxes)[nb1] = Saved;
// ((MBP_AABB* PX_RESTRICT)staticBoxes)[nb1+1] = Saved1;
}
void Region::prepareOverlaps()
{
if(!mNbUpdatedBoxes && !mNeedsSorting)
return;
if(mNeedsSorting)
{
staticSort();
// PT: when a static object is added/removed/updated we need to compute the overlaps again
// even if no dynamic box has been updated. The line below forces all dynamic boxes to be
// sorted in PreparePruning() and tested for overlaps in BipartiteBoxPruning(). It would be
// more efficient to:
// a) skip the actual pruning in PreparePruning() (we only need to re-sort)
// b) do BipartiteBoxPruning() with the new/modified boxes, not all of them
// Well, not done yet.
mNbUpdatedBoxes = mNbDynamicBoxes;
mPrevNbUpdatedBoxes = 0;
mNeedsSortingSleeping = true;
#if PX_DEBUG
for(PxU32 i=0;i<mNbDynamicBoxes;i++)
{
const PxU32 objectIndex = mInToOut_Dynamic[i];
mObjects[objectIndex].mUpdated = true;
}
#endif
}
preparePruning(mTmpBuffers);
prepareBIPPruning(mTmpBuffers);
}
void Region::findOverlaps(MBP_PairManager& pairManager)
{
PX_ASSERT(!mNeedsSorting);
if(!mNbUpdatedBoxes)
return;
if(mInput.mNeeded)
doCompleteBoxPruning(&pairManager, mInput);
if(mInput.mBIPInput.mNeeded)
doBipartiteBoxPruning(&pairManager, mInput.mBIPInput);
mNbUpdatedBoxes = 0;
}
///////////////////////////////////////////////////////////////////////////
MBP::MBP() :
mNbRegions (0),
mFirstFreeIndex (INVALID_ID),
mFirstFreeIndexBP (INVALID_ID)
#ifdef MBP_REGION_BOX_PRUNING
,mNbActiveRegions (0),
mDirtyRegions (true)
#endif
{
for(PxU32 i=0;i<MAX_NB_MBP+1;i++)
mFirstFree[i] = INVALID_ID;
}
MBP::~MBP()
{
/* for(PxU32 i=1;i<MAX_NB_MBP;i++)
{
if(mHandles[i].GetNbEntries())
{
const PxU32 SizeOfBundle = sizeof(RegionHandle)*i;
// printf("Handles %d: %d\n", i, mHandles[i].GetNbEntries()*sizeof(PxU32)/SizeOfBundle);
}
}*/
reset();
}
void MBP::freeBuffers()
{
mRemoved.empty();
mOutOfBoundsObjects.clear();
}
void MBP::preallocate(PxU32 nbRegions, PxU32 nbObjects, PxU32 maxNbOverlaps)
{
if(nbRegions)
{
mRegions.clear();
mRegions.reserve(nbRegions);
}
if(nbObjects)
{
mMBP_Objects.clear();
mMBP_Objects.reserve(nbObjects);
#ifdef USE_FULLY_INSIDE_FLAG
mFullyInsideBitmap.init(nbObjects);
mFullyInsideBitmap.clearAll();
#endif
}
mPairManager.reserveMemory(maxNbOverlaps);
}
PX_COMPILE_TIME_ASSERT(sizeof(BpHandle)<=sizeof(PxU32));
void MBP::addToOutOfBoundsArray(BpHandle id)
{
PX_ASSERT(mOutOfBoundsObjects.find(PxU32(id)) == mOutOfBoundsObjects.end());
mOutOfBoundsObjects.pushBack(PxU32(id));
}
static void setupOverlapFlags(PxU32 nbRegions, RegionData* PX_RESTRICT regions)
{
for(PxU32 i=0;i<nbRegions;i++)
regions[i].mOverlap = false;
for(PxU32 i=0;i<nbRegions;i++)
{
if(!regions[i].mBP)
continue;
for(PxU32 j=i+1;j<nbRegions;j++)
{
if(!regions[j].mBP)
continue;
if(regions[i].mBox.intersectNoTouch(regions[j].mBox))
{
regions[i].mOverlap = true;
regions[j].mOverlap = true;
}
}
}
}
//#define PRINT_STATS
#ifdef PRINT_STATS
#include <stdio.h>
#endif
// PT: TODO:
// - We could try to keep bounds around all objects (for each region), and then test the new region's bounds against these instead of
// testing all objects one by one. These new bounds (around all objects of a given region) would be delicate to maintain though.
// - Just store these "fully inside flags" (i.e. objects) in a separate list? Or can we do MTF on objects? (probably not, else we
// wouldn't have holes in the array due to removed objects)
// PT: automatically populate new region with overlapping objects.
// Brute-force version checking all existing objects, potentially optimized using "fully inside" flags.
//#define FIRST_VERSION
#ifdef FIRST_VERSION
void MBP::populateNewRegion(const MBP_AABB& box, Region* addedRegion, PxU32 regionIndex)
{
const RegionData* PX_RESTRICT regions = mRegions.begin();
const PxU32 nbObjects = mMBP_Objects.size();
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
#ifdef PRINT_STATS
PxU32 nbObjectsFound = 0;
PxU32 nbObjectsTested = 0;
#endif
#ifdef USE_FULLY_INSIDE_FLAG
const PxU32* fullyInsideFlags = mFullyInsideBitmap.getBits();
#endif
PxU32 j=0;
while(j<nbObjects)
{
#ifdef USE_FULLY_INSIDE_FLAG
const PxU32 blockFlags = fullyInsideFlags[j>>5];
#ifdef HWSCAN
if(blockFlags==0) //HWSCAN
#else
if(blockFlags==0xffffffff)
#endif
{
j+=32;
continue;
}
PxU32 nbToGo = PxMin(nbObjects - j, PxU32(32));
PxU32 mask = 1;
while(nbToGo--)
{
MBP_Object& currentObject = objects[j];
// PT: if an object A is fully contained inside all the regions S it overlaps, we don't need to test it against the new region R.
// The rationale is that even if R does overlap A, any new object B must touch S to overlap with A. So B would be added to S and
// the (A,B) overlap would be detected in S, even if it's not detected in R.
const PxU32 res = blockFlags & mask;
PX_ASSERT((mFullyInsideBitmap.isSet(j) && res) || (!mFullyInsideBitmap.isSet(j) && !res));
mask+=mask;
j++;
#ifdef HWSCAN
if(!res) //HWSCAN
#else
if(res)
#endif
continue;
PX_ASSERT(!(currentObject.mFlags & MBP_REMOVED));
#else
MBP_Object& currentObject = objects[j++];
if(currentObject.mFlags & MBP_REMOVED)
continue; // PT: object is in the free list
#endif
#ifdef PRINT_STATS
nbObjectsTested++;
#endif
MBP_AABB bounds;
MBP_Handle mbpHandle;
const PxU32 nbHandles = currentObject.mNbHandles;
if(nbHandles)
{
RegionHandle* PX_RESTRICT handles = getHandles(currentObject, nbHandles);
// PT: no need to test all regions since they should contain the same info. Just retrieve bounds from the first one.
PxU32 i=0; // for(PxU32 i=0;i<nbHandles;i++)
{
const RegionHandle& h = handles[i];
const RegionData& currentRegion = regions[h.mInternalBPHandle];
PX_ASSERT(currentRegion.mBP);
mbpHandle = currentRegion.mBP->retrieveBounds(bounds, h.mHandle);
}
}
else
{
PX_ASSERT(mManager);
// PT: if the object is out-of-bounds, we're out-of-luck. We don't have the object bounds, so we need to retrieve them
// from the AABB manager - and then re-encode them. This is not very elegant or efficient, but it should rarely happen
// so this is good enough for now.
const PxBounds3 decodedBounds = mManager->getBPBounds(currentObject.mUserID);
bounds.initFrom2(decodedBounds);
mbpHandle = currentObject.mHandlesIndex;
}
if(bounds.intersect(box))
{
// updateObject(mbpHandle, bounds);
updateObjectAfterNewRegionAdded(mbpHandle, bounds, addedRegion, regionIndex);
#ifdef PRINT_STATS
nbObjectsFound++;
#endif
}
#ifdef USE_FULLY_INSIDE_FLAG
}
#endif
}
#ifdef PRINT_STATS
printf("Populating new region with %d objects (tested %d/%d object)\n", nbObjectsFound, nbObjectsTested, nbObjects);
#endif
}
#endif
// PT: version using lowestSetBit
#define SECOND_VERSION
#ifdef SECOND_VERSION
/* PX_FORCE_INLINE PxU32 lowestSetBitUnsafe64(PxU64 v)
{
unsigned long retval;
_BitScanForward64(&retval, v);
return retval;
}*/
void MBP::populateNewRegion(const MBP_AABB& box, Region* addedRegion, PxU32 regionIndex, const PxBounds3* boundsArray, const PxReal* contactDistance)
{
const RegionData* PX_RESTRICT regions = mRegions.begin();
const PxU32 nbObjects = mMBP_Objects.size();
PX_UNUSED(nbObjects);
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
const PxU32* fullyInsideFlags = mFullyInsideBitmap.getBits();
// const PxU64* fullyInsideFlags = (const PxU64*)mFullyInsideBitmap.getBits();
if(!fullyInsideFlags)
return;
const PxU32 lastSetBit = mFullyInsideBitmap.findLast();
// const PxU64 lastSetBit = mFullyInsideBitmap.findLast();
#ifdef PRINT_STATS
PxU32 nbObjectsFound = 0;
PxU32 nbObjectsTested = 0;
#endif
// PT: ### bitmap iterator pattern
for(PxU32 w = 0; w <= lastSetBit >> 5; ++w)
// for(PxU64 w = 0; w <= lastSetBit >> 6; ++w)
{
for(PxU32 b = fullyInsideFlags[w]; b; b &= b-1)
// for(PxU64 b = fullyInsideFlags[w]; b; b &= b-1)
{
const PxU32 index = PxU32(w<<5|PxLowestSetBit(b));
// const PxU64 index = (PxU64)(w<<6|::lowestSetBitUnsafe64(b));
PX_ASSERT(index<nbObjects);
MBP_Object& currentObject = objects[index];
// PT: if an object A is fully contained inside all the regions S it overlaps, we don't need to test it against the new region R.
// The rationale is that even if R does overlap A, any new object B must touch S to overlap with A. So B would be added to S and
// the (A,B) overlap would be detected in S, even if it's not detected in R.
PX_ASSERT(!(currentObject.mFlags & MBP_REMOVED));
#ifdef HWSCAN
PX_ASSERT(mFullyInsideBitmap.isSet(index));
#else
PX_ASSERT(!mFullyInsideBitmap.isSet(index));
#endif
#ifdef PRINT_STATS
nbObjectsTested++;
#endif
MBP_AABB bounds;
MBP_Handle mbpHandle;
const PxU32 nbHandles = currentObject.mNbHandles;
if(nbHandles)
{
RegionHandle* PX_RESTRICT handles = getHandles(currentObject, nbHandles);
// PT: no need to test all regions since they should contain the same info. Just retrieve bounds from the first one.
PxU32 i=0; // for(PxU32 i=0;i<nbHandles;i++)
{
const RegionHandle& h = handles[i];
const RegionData& currentRegion = regions[h.mInternalBPHandle];
PX_ASSERT(currentRegion.mBP);
mbpHandle = currentRegion.mBP->retrieveBounds(bounds, h.mHandle);
}
}
else
{
// PT: if the object is out-of-bounds, we're out-of-luck. We don't have the object bounds, so we need to retrieve them
// from the AABB manager - and then re-encode them. This is not very elegant or efficient, but it should rarely happen
// so this is good enough for now.
const PxBounds3 rawBounds = boundsArray[currentObject.mUserID];
PxVec3 c(contactDistance[currentObject.mUserID]);
const PxBounds3 decodedBounds(rawBounds.minimum - c, rawBounds.maximum + c);
bounds.initFrom2(decodedBounds);
mbpHandle = currentObject.mHandlesIndex;
}
if(bounds.intersects(box))
{
// updateObject(mbpHandle, bounds);
updateObjectAfterNewRegionAdded(mbpHandle, bounds, addedRegion, regionIndex);
#ifdef PRINT_STATS
nbObjectsFound++;
#endif
}
}
}
#ifdef PRINT_STATS
printf("Populating new region with %d objects (tested %d/%d object)\n", nbObjectsFound, nbObjectsTested, nbObjects);
#endif
}
#endif
//#define THIRD_VERSION
#ifdef THIRD_VERSION
void MBP::populateNewRegion(const MBP_AABB& box, Region* addedRegion, PxU32 regionIndex)
{
const RegionData* PX_RESTRICT regions = mRegions.begin();
const PxU32 nbObjects = mMBP_Objects.size();
PX_UNUSED(nbObjects);
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
const PxU32* fullyInsideFlags = mFullyInsideBitmap.getBits();
if(!fullyInsideFlags)
return;
#ifdef PRINT_STATS
PxU32 nbObjectsFound = 0;
PxU32 nbObjectsTested = 0;
#endif
PxBitMap bm;
bm.importData(mFullyInsideBitmap.getSize(), (PxU32*)fullyInsideFlags);
PxBitMap::Iterator it(bm);
PxU32 index = it.getNext();
while(index != PxBitMap::Iterator::DONE)
{
PX_ASSERT(index<nbObjects);
MBP_Object& currentObject = objects[index];
// PT: if an object A is fully contained inside all the regions S it overlaps, we don't need to test it against the new region R.
// The rationale is that even if R does overlap A, any new object B must touch S to overlap with A. So B would be added to S and
// the (A,B) overlap would be detected in S, even if it's not detected in R.
PX_ASSERT(!(currentObject.mFlags & MBP_REMOVED));
#ifdef PRINT_STATS
nbObjectsTested++;
#endif
MBP_AABB bounds;
MBP_Handle mbpHandle;
const PxU32 nbHandles = currentObject.mNbHandles;
if(nbHandles)
{
RegionHandle* PX_RESTRICT handles = getHandles(currentObject, nbHandles);
// PT: no need to test all regions since they should contain the same info. Just retrieve bounds from the first one.
PxU32 i=0; // for(PxU32 i=0;i<nbHandles;i++)
{
const RegionHandle& h = handles[i];
const RegionData& currentRegion = regions[h.mInternalBPHandle];
PX_ASSERT(currentRegion.mBP);
mbpHandle = currentRegion.mBP->retrieveBounds(bounds, h.mHandle);
}
}
else
{
PX_ASSERT(mManager);
// PT: if the object is out-of-bounds, we're out-of-luck. We don't have the object bounds, so we need to retrieve them
// from the AABB manager - and then re-encode them. This is not very elegant or efficient, but it should rarely happen
// so this is good enough for now.
const PxBounds3 decodedBounds = mManager->getBPBounds(currentObject.mUserID);
bounds.initFrom2(decodedBounds);
mbpHandle = currentObject.mHandlesIndex;
}
if(bounds.intersect(box))
{
// updateObject(mbpHandle, bounds);
updateObjectAfterNewRegionAdded(mbpHandle, bounds, addedRegion, regionIndex);
#ifdef PRINT_STATS
nbObjectsFound++;
#endif
}
index = it.getNext();
}
#ifdef PRINT_STATS
printf("Populating new region with %d objects (tested %d/%d object)\n", nbObjectsFound, nbObjectsTested, nbObjects);
#endif
}
#endif
PxU32 MBP::addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const PxReal* contactDistance)
{
PxU32 regionHandle;
RegionData* PX_RESTRICT buffer;
if(mFirstFreeIndexBP!=INVALID_ID)
{
regionHandle = mFirstFreeIndexBP;
buffer = mRegions.begin();
buffer += regionHandle;
mFirstFreeIndexBP = PxU32(size_t(buffer->mUserData)); // PT: this is safe, we previously stored a PxU32 in there
}
else
{
if(mNbRegions>=MAX_NB_MBP)
{
PxGetFoundation().error(PxErrorCode::eOUT_OF_MEMORY, PX_FL, "MBP::addRegion: max number of regions reached.");
return INVALID_ID;
}
regionHandle = mNbRegions++;
buffer = reserveContainerMemory<RegionData>(mRegions, 1);
}
Region* newRegion = PX_NEW(Region);
buffer->mBox.initFrom2(region.mBounds);
buffer->mBP = newRegion;
buffer->mUserData = region.mUserData;
setupOverlapFlags(mNbRegions, mRegions.begin());
// PT: automatically populate new region with overlapping objects
if(populateRegion)
populateNewRegion(buffer->mBox, newRegion, regionHandle, boundsArray, contactDistance);
#ifdef MBP_REGION_BOX_PRUNING
mDirtyRegions = true;
#endif
return regionHandle;
}
// ### TODO: recycle regions, make sure objects are properly deleted/transferred, etc
// ### TODO: what happens if we delete a zone then immediately add it back? Do objects get deleted?
// ### TODO: in fact if we remove a zone but we keep the objects, what happens to their current overlaps? Are they kept or discarded?
bool MBP::removeRegion(PxU32 handle)
{
if(handle>=mNbRegions)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "MBP::removeRegion: invalid handle.");
return false;
}
RegionData* PX_RESTRICT region = mRegions.begin();
region += handle;
Region* bp = region->mBP;
if(!bp)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "MBP::removeRegion: invalid handle.");
return false;
}
PxBounds3 empty;
empty.setEmpty();
region->mBox.initFrom2(empty);
{
// We are going to remove the region but it can still contain objects. We need to update
// those objects so that their handles and out-of-bounds status are modified.
//
// Unfortunately there is no way to iterate over active objects in a region, so we need
// to iterate over the max amount of objects. ### TODO: optimize this
const PxU32 maxNbObjects = bp->mMaxNbObjects;
MBPEntry* PX_RESTRICT objects = bp->mObjects;
for(PxU32 j=0;j<maxNbObjects;j++)
{
// The handle is INVALID_ID for non-active entries
if(objects[j].mMBPHandle!=INVALID_ID)
{
// printf("Object to update!\n");
updateObjectAfterRegionRemoval(objects[j].mMBPHandle, bp);
}
}
}
PX_DELETE(bp);
region->mBP = NULL;
region->mUserData = reinterpret_cast<void*>(size_t(mFirstFreeIndexBP));
mFirstFreeIndexBP = handle;
#ifdef MBP_REGION_BOX_PRUNING
mDirtyRegions = true;
#endif
// A region has been removed so we need to update the overlap flags for all remaining regions
// ### TODO: optimize this
setupOverlapFlags(mNbRegions, mRegions.begin());
return true;
}
const Region* MBP::getRegion(PxU32 i) const
{
if(i>=mNbRegions)
return NULL;
const RegionData* PX_RESTRICT regions = mRegions.begin();
return regions[i].mBP;
}
#ifdef MBP_REGION_BOX_PRUNING
void MBP::buildRegionData()
{
const PxU32 size = mNbRegions;
PxU32 nbValidRegions = 0;
if(size)
{
const RegionData* PX_RESTRICT regions = mRegions.begin();
// Gather valid regions
PxU32 minPosList[MAX_NB_MBP];
for(PxU32 i=0;i<size;i++)
{
if(regions[i].mBP)
minPosList[nbValidRegions++] = regions[i].mBox.mMinX;
}
// Sort them
RadixSortBuffered RS;
const PxU32* sorted = RS.Sort(minPosList, nbValidRegions, RADIX_UNSIGNED).GetRanks();
// Store sorted
for(PxU32 i=0;i<nbValidRegions;i++)
{
const PxU32 sortedIndex = *sorted++;
mSortedRegionBoxes[i] = regions[sortedIndex].mBox;
mSortedRegionIndices[i] = sortedIndex;
}
}
mNbActiveRegions = nbValidRegions;
mDirtyRegions = false;
}
#endif
PX_FORCE_INLINE RegionHandle* MBP::getHandles(MBP_Object& currentObject, PxU32 nbHandles)
{
RegionHandle* handles;
if(nbHandles==1)
handles = ¤tObject.mHandle;
else
{
const PxU32 handlesIndex = currentObject.mHandlesIndex;
PxArray<PxU32>& c = mHandles[nbHandles];
handles = reinterpret_cast<RegionHandle*>(c.begin()+handlesIndex);
}
return handles;
}
void MBP::purgeHandles(MBP_Object* PX_RESTRICT object, PxU32 nbHandles)
{
if(nbHandles>1)
{
const PxU32 handlesIndex = object->mHandlesIndex;
PxArray<PxU32>& c = mHandles[nbHandles];
PxU32* recycled = c.begin() + handlesIndex;
*recycled = mFirstFree[nbHandles];
mFirstFree[nbHandles] = handlesIndex;
}
}
void MBP::storeHandles(MBP_Object* PX_RESTRICT object, PxU32 nbHandles, const RegionHandle* PX_RESTRICT handles)
{
if(nbHandles==1)
{
object->mHandle = handles[0];
}
else if(nbHandles)
{
PxArray<PxU32>& c = mHandles[nbHandles];
const PxU32 firstFree = mFirstFree[nbHandles];
PxU32* handlesMemory;
if(firstFree!=INVALID_ID)
{
object->mHandlesIndex = firstFree;
handlesMemory = c.begin() + firstFree;
mFirstFree[nbHandles] = *handlesMemory;
}
else
{
const PxU32 handlesIndex = c.size();
object->mHandlesIndex = handlesIndex;
handlesMemory = reserveContainerMemory<PxU32>(c, sizeof(RegionHandle)*nbHandles/sizeof(PxU32));
}
PxMemCopy(handlesMemory, handles, sizeof(RegionHandle)*nbHandles);
}
}
MBP_Handle MBP::addObject(const MBP_AABB& box, BpHandle userID, bool isStatic)
{
MBP_ObjectIndex objectIndex;
MBP_Object* objectMemory;
PxU32 flipFlop;
if(1)
{
if(mFirstFreeIndex!=INVALID_ID)
{
objectIndex = mFirstFreeIndex;
MBP_Object* objects = mMBP_Objects.begin();
objectMemory = &objects[objectIndex];
PX_ASSERT(!objectMemory->mNbHandles);
mFirstFreeIndex = objectMemory->mHandlesIndex;
flipFlop = PxU32(objectMemory->getFlipFlop());
}
else
{
objectIndex = mMBP_Objects.size();
objectMemory = reserveContainerMemory<MBP_Object>(mMBP_Objects, 1);
flipFlop = 0;
}
}
else
{
// PT: must be possible to use the AABB-manager's ID directly. Something like this:
objectIndex = userID;
if(mMBP_Objects.capacity()<userID+1)
{
PxU32 newCap = mMBP_Objects.capacity() ? mMBP_Objects.capacity()*2 : 128;
if(newCap<userID+1)
newCap = userID+1;
mMBP_Objects.reserve(newCap);
}
mMBP_Objects.forceSize_Unsafe(userID+1);
objectMemory = &mMBP_Objects[userID];
flipFlop = 0;
}
const MBP_Handle MBPObjectHandle = encodeHandle(objectIndex, flipFlop, isStatic);
// mMBP_Objects.Shrink();
PxU32 nbHandles = 0;
#ifdef USE_FULLY_INSIDE_FLAG
bool newObjectIsFullyInsideRegions = true;
#endif
const PxU32 nb = mNbRegions;
const RegionData* PX_RESTRICT regions = mRegions.begin();
RegionHandle tmpHandles[MAX_NB_MBP+1];
for(PxU32 i=0;i<nb;i++)
{
#ifdef MBP_USE_NO_CMP_OVERLAP_3D
if(intersect3D(regions[i].mBox, box))
#else
if(regions[i].mBox.intersects(box))
#endif
{
#ifdef USE_FULLY_INSIDE_FLAG
if(!box.isInside(regions[i].mBox))
newObjectIsFullyInsideRegions = false;
#endif
#ifdef MBP_USE_WORDS
if(regions[i].mBP->mNbObjects==0xffff)
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "MBP::addObject: 64K objects in single region reached. Some collisions might be lost.");
else
#endif
{
RegionHandle& h = tmpHandles[nbHandles++];
h.mHandle = regions[i].mBP->addObject(box, MBPObjectHandle, isStatic);
h.mInternalBPHandle = PxTo16(i);
}
}
}
storeHandles(objectMemory, nbHandles, tmpHandles);
objectMemory->mNbHandles = PxTo16(nbHandles);
PxU16 flags = 0;
if(flipFlop)
flags |= MBP_FLIP_FLOP;
#ifdef USE_FULLY_INSIDE_FLAG
if(nbHandles && newObjectIsFullyInsideRegions)
setBit(mFullyInsideBitmap, objectIndex);
else
clearBit(mFullyInsideBitmap, objectIndex);
#endif
if(!nbHandles)
{
objectMemory->mHandlesIndex = MBPObjectHandle;
addToOutOfBoundsArray(userID);
}
if(!isStatic)
mUpdatedObjects.setBitChecked(objectIndex);
// objectMemory->mUpdated = !isStatic;
objectMemory->mFlags = flags;
objectMemory->mUserID = userID;
return MBPObjectHandle;
}
bool MBP::removeObject(MBP_Handle handle)
{
const MBP_ObjectIndex objectIndex = decodeHandle_Index(handle);
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
MBP_Object& currentObject = objects[objectIndex];
const RegionData* PX_RESTRICT regions = mRegions.begin();
// Parse previously overlapping regions. If still overlapping, update object. Else remove from region.
const PxU32 nbHandles = currentObject.mNbHandles;
if(nbHandles)
{
RegionHandle* handles = getHandles(currentObject, nbHandles);
for(PxU32 i=0;i<nbHandles;i++)
{
const RegionHandle& h = handles[i];
const RegionData& currentRegion = regions[h.mInternalBPHandle];
// if(currentRegion.mBP)
PX_ASSERT(currentRegion.mBP);
currentRegion.mBP->removeObject(h.mHandle);
}
purgeHandles(¤tObject, nbHandles);
}
currentObject.mNbHandles = 0;
currentObject.mFlags |= MBP_REMOVED;
currentObject.mHandlesIndex = mFirstFreeIndex;
// if(!decodeHandle_IsStatic(handle))
// if(!currentObject.IsStatic())
mUpdatedObjects.setBitChecked(objectIndex);
mFirstFreeIndex = objectIndex;
mRemoved.setBitChecked(objectIndex); // PT: this is cleared each frame so it's not a replacement for the MBP_REMOVED flag
#ifdef USE_FULLY_INSIDE_FLAG
// PT: when removing an object we mark it as "fully inside" so that it is automatically
// discarded in the "populateNewRegion" function, without the need for MBP_REMOVED.
setBit(mFullyInsideBitmap, objectIndex);
#endif
return true;
}
static PX_FORCE_INLINE bool stillIntersects(PxU32 handle, PxU32& _nb, PxU32* PX_RESTRICT currentOverlaps)
{
const PxU32 nb = _nb;
for(PxU32 i=0;i<nb;i++)
{
if(currentOverlaps[i]==handle)
{
_nb = nb-1;
currentOverlaps[i] = currentOverlaps[nb-1];
return true;
}
}
return false;
}
bool MBP::updateObject(MBP_Handle handle, const MBP_AABB& box)
{
const MBP_ObjectIndex objectIndex = decodeHandle_Index(handle);
const PxU32 isStatic = decodeHandle_IsStatic(handle);
const PxU32 nbRegions = mNbRegions;
const RegionData* PX_RESTRICT regions = mRegions.begin();
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
MBP_Object& currentObject = objects[objectIndex];
// if(!isStatic) // ### removed for PhysX integration (bugfix)
// if(!currentObject.IsStatic())
{
mUpdatedObjects.setBitChecked(objectIndex);
}
// PT: fast path which should happen quite frequently. If:
// - the object was touching a single region
// - that region doesn't overlap other regions
// - the object's new bounds is fully inside the region
// then we know that the object can't touch another region, and we can use this fast-path that simply
// updates one region and avoids iterating over/testing all the other ones.
const PxU32 nbHandles = currentObject.mNbHandles;
if(nbHandles==1)
{
const RegionHandle& h = currentObject.mHandle;
const RegionData& currentRegion = regions[h.mInternalBPHandle];
if(!currentRegion.mOverlap && box.isInside(currentRegion.mBox))
{
#ifdef USE_FULLY_INSIDE_FLAG
// PT: it is possible that this flag is not set already when reaching this place:
// - object touches 2 regions
// - then in one frame:
// - object moves fully inside one region
// - the other region is removed
// => nbHandles changes from 2 to 1 while MBP_FULLY_INSIDE is not set
setBit(mFullyInsideBitmap, objectIndex);
#endif
currentRegion.mBP->updateObject(box, h.mHandle);
return true;
}
}
// Find regions overlapping object's new position
#ifdef USE_FULLY_INSIDE_FLAG
bool objectIsFullyInsideRegions = true;
#endif
PxU32 nbCurrentOverlaps = 0;
PxU32 currentOverlaps[MAX_NB_MBP+1];
// PT: here, we may still parse regions which have been removed. But their boxes have been set to empty,
// so nothing will happen.
for(PxU32 i=0;i<nbRegions;i++)
{
#ifdef MBP_USE_NO_CMP_OVERLAP_3D
if(intersect3D(regions[i].mBox, box))
#else
if(regions[i].mBox.intersects(box))
#endif
{
#ifdef USE_FULLY_INSIDE_FLAG
if(!box.isInside(regions[i].mBox))
objectIsFullyInsideRegions = false;
#endif
PX_ASSERT(nbCurrentOverlaps<MAX_NB_MBP);
currentOverlaps[nbCurrentOverlaps++] = i;
}
}
// New data for this frame
PxU32 nbNewHandles = 0;
RegionHandle newHandles[MAX_NB_MBP+1];
// Parse previously overlapping regions. If still overlapping, update object. Else remove from region.
RegionHandle* handles = getHandles(currentObject, nbHandles);
for(PxU32 i=0;i<nbHandles;i++)
{
const RegionHandle& h = handles[i];
PX_ASSERT(h.mInternalBPHandle<nbRegions);
const RegionData& currentRegion = regions[h.mInternalBPHandle];
// We need to update object even if it then gets removed, as the removal
// doesn't actually report lost pairs - and we need this.
// currentRegion.mBP->UpdateObject(box, h.mHandle);
if(stillIntersects(h.mInternalBPHandle, nbCurrentOverlaps, currentOverlaps))
{
currentRegion.mBP->updateObject(box, h.mHandle);
// Still collides => keep handle for this frame
newHandles[nbNewHandles++] = h;
}
else
{
PX_ASSERT(!currentRegion.mBox.intersects(box));
// if(currentRegion.mBP)
PX_ASSERT(currentRegion.mBP);
currentRegion.mBP->removeObject(h.mHandle);
}
}
// Add to new regions if needed
for(PxU32 i=0;i<nbCurrentOverlaps;i++)
{
// if(currentOverlaps[i]==INVALID_ID)
// continue;
const PxU32 regionIndex = currentOverlaps[i];
const MBP_Index BPHandle = regions[regionIndex].mBP->addObject(box, handle, isStatic!=0);
newHandles[nbNewHandles].mHandle = PxTo16(BPHandle);
newHandles[nbNewHandles].mInternalBPHandle = PxTo16(regionIndex);
nbNewHandles++;
}
if(nbHandles==nbNewHandles)
{
for(PxU32 i=0;i<nbNewHandles;i++)
handles[i] = newHandles[i];
}
else
{
purgeHandles(¤tObject, nbHandles);
storeHandles(¤tObject, nbNewHandles, newHandles);
}
currentObject.mNbHandles = PxTo16(nbNewHandles);
if(!nbNewHandles && nbHandles)
{
currentObject.mHandlesIndex = handle;
addToOutOfBoundsArray(currentObject.mUserID);
}
// for(PxU32 i=0;i<nbNewHandles;i++)
// currentObject.mHandles[i] = newHandles[i];
#ifdef USE_FULLY_INSIDE_FLAG
if(objectIsFullyInsideRegions && nbNewHandles)
setBit(mFullyInsideBitmap, objectIndex);
else
clearBit(mFullyInsideBitmap, objectIndex);
#endif
return true;
}
bool MBP::updateObjectAfterRegionRemoval(MBP_Handle handle, Region* removedRegion)
{
PX_ASSERT(removedRegion);
const MBP_ObjectIndex objectIndex = decodeHandle_Index(handle);
const PxU32 nbRegions = mNbRegions;
PX_UNUSED(nbRegions);
const RegionData* PX_RESTRICT regions = mRegions.begin();
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
MBP_Object& currentObject = objects[objectIndex];
// Mark the object as updated so that its pairs are considered for removal. If we don't do this an out-of-bounds object
// resting on another non-out-of-bounds object still collides with that object and the memory associated with that pair
// is not released. If we mark it as updated the pair is lost, and the out-of-bounds object falls through.
//
// However if we do this any pair involving the object will be marked as lost, even the ones involving other regions.
// Typically the pair will then get lost one frame and get recreated the next frame.
// mUpdatedObjects.setBitChecked(objectIndex);
const PxU32 nbHandles = currentObject.mNbHandles;
PX_ASSERT(nbHandles);
// New handles
PxU32 nbNewHandles = 0;
RegionHandle newHandles[MAX_NB_MBP+1];
// Parse previously overlapping regions. Keep all of them except removed one.
RegionHandle* handles = getHandles(currentObject, nbHandles);
for(PxU32 i=0;i<nbHandles;i++)
{
const RegionHandle& h = handles[i];
PX_ASSERT(h.mInternalBPHandle<nbRegions);
if(regions[h.mInternalBPHandle].mBP!=removedRegion)
newHandles[nbNewHandles++] = h;
}
#ifdef USE_FULLY_INSIDE_FLAG
// PT: in theory we should update the inside flag here but we don't do that for perf reasons.
// - If the flag is set, it means the object was fully inside all its regions. Removing one of them does not invalidate the flag.
// - If the flag is not set, removing one region might allow us to set the flag now. However not doing so simply makes the
// populateNewRegion() function run a bit slower, it does not produce wrong results. This is only until concerned objects are
// updated again anyway, so we live with this.
#endif
PX_ASSERT(nbNewHandles==nbHandles-1);
purgeHandles(¤tObject, nbHandles);
storeHandles(¤tObject, nbNewHandles, newHandles);
currentObject.mNbHandles = PxTo16(nbNewHandles);
if(!nbNewHandles)
{
currentObject.mHandlesIndex = handle;
addToOutOfBoundsArray(currentObject.mUserID);
#ifdef USE_FULLY_INSIDE_FLAG
clearBit(mFullyInsideBitmap, objectIndex);
#endif
}
return true;
}
bool MBP::updateObjectAfterNewRegionAdded(MBP_Handle handle, const MBP_AABB& box, Region* addedRegion, PxU32 regionIndex)
{
PX_ASSERT(addedRegion);
const MBP_ObjectIndex objectIndex = decodeHandle_Index(handle);
const PxU32 isStatic = decodeHandle_IsStatic(handle);
MBP_Object* PX_RESTRICT objects = mMBP_Objects.begin();
MBP_Object& currentObject = objects[objectIndex];
// if(!isStatic) // ### removed for PhysX integration (bugfix)
// if(!currentObject.IsStatic())
{
mUpdatedObjects.setBitChecked(objectIndex);
}
// PT: here we know that we're touching one more region than before and we'll need to update the handles.
// So there is no "fast path" in this case - well the whole function is a fast path if you want.
//
// We don't need to "find regions overlapping object's new position": we know it's going to be the
// same as before, plus the newly added region ("addedRegion").
#ifdef USE_FULLY_INSIDE_FLAG
// PT: we know that the object is not marked as "fully inside", otherwise this function would not have been called.
#ifdef HWSCAN
PX_ASSERT(mFullyInsideBitmap.isSet(objectIndex)); //HWSCAN
#else
PX_ASSERT(!mFullyInsideBitmap.isSet(objectIndex));
#endif
#endif
const PxU32 nbHandles = currentObject.mNbHandles;
PxU32 nbNewHandles = 0;
RegionHandle newHandles[MAX_NB_MBP+1];
// PT: get previously overlapping regions. We didn't actually move so we're still overlapping as before.
// We just need to get the handles here.
RegionHandle* handles = getHandles(currentObject, nbHandles);
for(PxU32 i=0;i<nbHandles;i++)
newHandles[nbNewHandles++] = handles[i];
// Add to new region
{
#if PX_DEBUG
const RegionData* PX_RESTRICT regions = mRegions.begin();
const RegionData& currentRegion = regions[regionIndex];
PX_ASSERT(currentRegion.mBox.intersects(box));
#endif
const MBP_Index BPHandle = addedRegion->addObject(box, handle, isStatic!=0);
newHandles[nbNewHandles].mHandle = PxTo16(BPHandle);
newHandles[nbNewHandles].mInternalBPHandle = PxTo16(regionIndex);
nbNewHandles++;
}
// PT: we know that we have one more handle than before, no need to test
purgeHandles(¤tObject, nbHandles);
storeHandles(¤tObject, nbNewHandles, newHandles);
currentObject.mNbHandles = PxTo16(nbNewHandles);
// PT: we know that we have at least one handle (from the newly added region), so we can't be "out of bounds" here.
PX_ASSERT(nbNewHandles);
#ifdef USE_FULLY_INSIDE_FLAG
// PT: we know that the object was not "fully inside" before, so even if it is fully inside the new region, it
// will not be fully inside all of them => no need to change its fully inside flag
// TODO: an exception to this would be the case where the object was out-of-bounds, and it's now fully inside the new region
// => we could set the flag in that case.
#endif
return true;
}
bool MBP_PairManager::computeCreatedDeletedPairs(const MBP_Object* objects, BroadPhaseMBP* mbp, const BitArray& updated, const BitArray& removed)
{
// PT: parse all currently active pairs. The goal here is to generate the found/lost pairs, compared to previous frame.
PxU32 i=0;
PxU32 nbActivePairs = mNbActivePairs;
while(i<nbActivePairs)
{
InternalPair& p = mActivePairs[i];
if(p.isNew())
{
// New pair
// PT: 'isNew' is set to true in the 'addPair' function. In this case the pair did not previously
// exist in the structure, and thus we must report the new pair to the client code.
//
// PT: group-based filtering is not needed here, since it has already been done in 'addPair'
const PxU32 id0 = p.getId0();
const PxU32 id1 = p.getId1();
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
const MBP_ObjectIndex index0 = decodeHandle_Index(id0);
const MBP_ObjectIndex index1 = decodeHandle_Index(id1);
const BpHandle object0 = objects[index0].mUserID;
const BpHandle object1 = objects[index1].mUserID;
mbp->mCreated.pushBack(BroadPhasePair(object0, object1));
p.clearNew();
p.clearUpdated();
i++;
}
else if(p.isUpdated())
{
// Persistent pair
// PT: this pair already existed in the structure, and has been found again this frame. Since
// MBP reports "all pairs" each frame (as opposed to SAP), this happens quite often, for each
// active persistent pair.
p.clearUpdated();
i++;
}
else
{
// Lost pair
// PT: if the pair is not new and not 'updated', it might be a lost (separated) pair. But this
// is not always the case since we now handle "sleeping" objects directly within MBP. A pair
// of sleeping objects does not generate an 'addPair' call, so it ends up in this codepath.
// Nonetheless the sleeping pair should not be deleted. We can only delete pairs involving
// objects that have been actually moved during the frame. This is the only case in which
// a pair can indeed become 'lost'.
const PxU32 id0 = p.getId0();
const PxU32 id1 = p.getId1();
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
const MBP_ObjectIndex index0 = decodeHandle_Index(id0);
const MBP_ObjectIndex index1 = decodeHandle_Index(id1);
// PT: if none of the involved objects have been updated, the pair is just sleeping: keep it and skip it.
if(updated.isSetChecked(index0) || updated.isSetChecked(index1))
{
// PT: by design (for better or worse) we do not report pairs to the client when
// one of the involved objects has been deleted. The pair must still be deleted
// from the MBP structure though.
if(!removed.isSetChecked(index0) && !removed.isSetChecked(index1))
{
// PT: doing the group-based filtering here is useless. The pair should not have
// been added in the first place.
const BpHandle object0 = objects[index0].mUserID;
const BpHandle object1 = objects[index1].mUserID;
mbp->mDeleted.pushBack(BroadPhasePair(object0, object1));
}
const PxU32 hashValue = hash(id0, id1) & mMask;
PairManagerData::removePair(id0, id1, hashValue, i);
nbActivePairs--;
}
else i++;
}
}
shrinkMemory();
return true;
}
void MBP::prepareOverlaps()
{
const PxU32 nb = mNbRegions;
const RegionData* PX_RESTRICT regions = mRegions.begin();
for(PxU32 i=0;i<nb;i++)
{
if(regions[i].mBP)
regions[i].mBP->prepareOverlaps();
}
}
void MBP::findOverlaps(const Bp::FilterGroup::Enum* PX_RESTRICT groups, const bool* PX_RESTRICT lut)
{
PxU32 nb = mNbRegions;
const RegionData* PX_RESTRICT regions = mRegions.begin();
const MBP_Object* objects = mMBP_Objects.begin();
mPairManager.mObjects = objects;
mPairManager.mGroups = groups;
mPairManager.mLUT = lut;
for(PxU32 i=0;i<nb;i++)
{
if(regions[i].mBP)
regions[i].mBP->findOverlaps(mPairManager);
}
}
PxU32 MBP::finalize(BroadPhaseMBP* mbp)
{
const MBP_Object* objects = mMBP_Objects.begin();
mPairManager.computeCreatedDeletedPairs(objects, mbp, mUpdatedObjects, mRemoved);
mUpdatedObjects.clearAll();
return mPairManager.mNbActivePairs;
}
void MBP::reset()
{
PxU32 nb = mNbRegions;
RegionData* PX_RESTRICT regions = mRegions.begin();
while(nb--)
{
// printf("%d objects in region\n", regions->mBP->mNbObjects);
PX_DELETE(regions->mBP);
regions++;
}
mNbRegions = 0;
mFirstFreeIndex = INVALID_ID;
mFirstFreeIndexBP = INVALID_ID;
for(PxU32 i=0;i<MAX_NB_MBP+1;i++)
{
mHandles[i].clear();
mFirstFree[i] = INVALID_ID;
}
mRegions.clear();
mMBP_Objects.clear();
mPairManager.purge();
mUpdatedObjects.empty();
mRemoved.empty();
mOutOfBoundsObjects.clear();
#ifdef USE_FULLY_INSIDE_FLAG
mFullyInsideBitmap.empty();
#endif
}
void MBP::shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances)
{
const PxU32 size = mNbRegions;
RegionData* PX_RESTRICT regions = mRegions.begin();
//
// regions
//
for(PxU32 i=0; i < size; i++)
{
if(regions[i].mBP)
{
MBP_AABB& box = regions[i].mBox;
PxBounds3 bounds;
box.decode(bounds);
bounds.minimum -= shift;
bounds.maximum -= shift;
box.initFrom2(bounds);
}
}
//
// object bounds
//
const PxU32 nbObjects = mMBP_Objects.size();
MBP_Object* objects = mMBP_Objects.begin();
for(PxU32 i=0; i < nbObjects; i++)
{
MBP_Object& obj = objects[i];
const PxU32 nbHandles = obj.mNbHandles;
if(nbHandles)
{
MBP_AABB bounds;
const PxBounds3 rawBounds = boundsArray[obj.mUserID];
PxVec3 c(contactDistances[obj.mUserID]);
const PxBounds3 decodedBounds(rawBounds.minimum - c, rawBounds.maximum + c);
bounds.initFrom2(decodedBounds);
RegionHandle* PX_RESTRICT handles = getHandles(obj, nbHandles);
for(PxU32 j=0; j < nbHandles; j++)
{
const RegionHandle& h = handles[j];
const RegionData& currentRegion = regions[h.mInternalBPHandle];
PX_ASSERT(currentRegion.mBP);
currentRegion.mBP->setBounds(h.mHandle, bounds);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Below is the PhysX wrapper = link between AABBManager and MBP
#define DEFAULT_CREATED_DELETED_PAIRS_CAPACITY 1024
BroadPhaseMBP::BroadPhaseMBP( PxU32 maxNbRegions,
PxU32 maxNbBroadPhaseOverlaps,
PxU32 maxNbStaticShapes,
PxU32 maxNbDynamicShapes,
PxU64 contextID) :
mMapping (NULL),
mCapacity (0),
mGroups (NULL),
mFilter (NULL),
mContextID (contextID)
{
mMBP = PX_NEW(MBP);
const PxU32 nbObjects = maxNbStaticShapes + maxNbDynamicShapes;
mMBP->preallocate(maxNbRegions, nbObjects, maxNbBroadPhaseOverlaps);
if(nbObjects)
allocateMappingArray(nbObjects);
mCreated.reserve(DEFAULT_CREATED_DELETED_PAIRS_CAPACITY);
mDeleted.reserve(DEFAULT_CREATED_DELETED_PAIRS_CAPACITY);
}
BroadPhaseMBP::~BroadPhaseMBP()
{
PX_DELETE(mMBP);
PX_FREE(mMapping);
}
void BroadPhaseMBP::allocateMappingArray(PxU32 newCapacity)
{
PX_ASSERT(newCapacity>mCapacity);
MBP_Handle* newMapping = reinterpret_cast<MBP_Handle*>(PX_ALLOC(sizeof(MBP_Handle)*newCapacity, "MBP"));
if(mCapacity)
PxMemCopy(newMapping, mMapping, mCapacity*sizeof(MBP_Handle));
for(PxU32 i=mCapacity;i<newCapacity;i++)
newMapping[i] = PX_INVALID_U32;
PX_FREE(mMapping);
mMapping = newMapping;
mCapacity = newCapacity;
}
void BroadPhaseMBP::getCaps(PxBroadPhaseCaps& caps) const
{
caps.mMaxNbRegions = 256;
}
PxU32 BroadPhaseMBP::getNbRegions() const
{
// PT: we need to count active regions here, as we only keep track of the total number of
// allocated regions internally - and some of which might have been removed.
const PxU32 size = mMBP->mNbRegions;
/* const RegionData* PX_RESTRICT regions = (const RegionData*)mMBP->mRegions.GetEntries();
PxU32 nbActiveRegions = 0;
for(PxU32 i=0;i<size;i++)
{
if(regions[i].mBP)
nbActiveRegions++;
}
return nbActiveRegions;*/
return size;
}
PxU32 BroadPhaseMBP::getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
const PxU32 size = mMBP->mNbRegions;
const RegionData* PX_RESTRICT regions = mMBP->mRegions.begin();
regions += startIndex;
const PxU32 writeCount = PxMin(size, bufferSize);
for(PxU32 i=0;i<writeCount;i++)
{
const MBP_AABB& box = regions[i].mBox;
box.decode(userBuffer[i].mRegion.mBounds);
if(regions[i].mBP)
{
PX_ASSERT(userBuffer[i].mRegion.mBounds.isValid());
userBuffer[i].mRegion.mUserData = regions[i].mUserData;
userBuffer[i].mActive = true;
userBuffer[i].mOverlap = regions[i].mOverlap!=0;
userBuffer[i].mNbStaticObjects = regions[i].mBP->mNbStaticBoxes;
userBuffer[i].mNbDynamicObjects = regions[i].mBP->mNbDynamicBoxes;
}
else
{
userBuffer[i].mRegion.mBounds.setEmpty();
userBuffer[i].mRegion.mUserData = NULL;
userBuffer[i].mActive = false;
userBuffer[i].mOverlap = false;
userBuffer[i].mNbStaticObjects = 0;
userBuffer[i].mNbDynamicObjects = 0;
}
}
return writeCount;
}
PxU32 BroadPhaseMBP::addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const PxReal* contactDistance)
{
return mMBP->addRegion(region, populateRegion, boundsArray, contactDistance);
}
bool BroadPhaseMBP::removeRegion(PxU32 handle)
{
return mMBP->removeRegion(handle);
}
void BroadPhaseMBP::update(PxcScratchAllocator* scratchAllocator, const BroadPhaseUpdateData& updateData, physx::PxBaseTask* /*continuation*/)
{
PX_CHECK_AND_RETURN(scratchAllocator, "BroadPhaseMBP::update - scratchAllocator must be non-NULL \n");
PX_UNUSED(scratchAllocator);
setUpdateData(updateData);
update();
postUpdate();
}
static PX_FORCE_INLINE void computeMBPBounds(MBP_AABB& aabb, const PxBounds3* PX_RESTRICT boundsXYZ, const PxReal* PX_RESTRICT contactDistances, const BpHandle index)
{
const PxBounds3& b = boundsXYZ[index];
const Vec4V contactDistanceV = V4Load(contactDistances[index]);
const Vec4V inflatedMinV = V4Sub(V4LoadU(&b.minimum.x), contactDistanceV);
const Vec4V inflatedMaxV = V4Add(V4LoadU(&b.maximum.x), contactDistanceV); // PT: this one is safe because we allocated one more box in the array (in BoundsArray::initEntry)
PX_ALIGN(16, PxVec4) boxMin;
PX_ALIGN(16, PxVec4) boxMax;
V4StoreA(inflatedMinV, &boxMin.x);
V4StoreA(inflatedMaxV, &boxMax.x);
const PxU32* PX_RESTRICT min = PxUnionCast<const PxU32*, const PxF32*>(&boxMin.x);
const PxU32* PX_RESTRICT max = PxUnionCast<const PxU32*, const PxF32*>(&boxMax.x);
//Avoid min=max by enforcing the rule that mins are even and maxs are odd.
aabb.mMinX = IntegerAABB::encodeFloatMin(min[0])>>1;
aabb.mMinY = IntegerAABB::encodeFloatMin(min[1])>>1;
aabb.mMinZ = IntegerAABB::encodeFloatMin(min[2])>>1;
aabb.mMaxX = (IntegerAABB::encodeFloatMax(max[0]) | (1<<2))>>1;
aabb.mMaxY = (IntegerAABB::encodeFloatMax(max[1]) | (1<<2))>>1;
aabb.mMaxZ = (IntegerAABB::encodeFloatMax(max[2]) | (1<<2))>>1;
/* const IntegerAABB bounds(boundsXYZ[index], contactDistances[index]);
aabb.mMinX = bounds.mMinMax[IntegerAABB::MIN_X]>>1;
aabb.mMinY = bounds.mMinMax[IntegerAABB::MIN_Y]>>1;
aabb.mMinZ = bounds.mMinMax[IntegerAABB::MIN_Z]>>1;
aabb.mMaxX = bounds.mMinMax[IntegerAABB::MAX_X]>>1;
aabb.mMaxY = bounds.mMinMax[IntegerAABB::MAX_Y]>>1;
aabb.mMaxZ = bounds.mMinMax[IntegerAABB::MAX_Z]>>1;*/
/*
aabb.mMinX &= ~1;
aabb.mMinY &= ~1;
aabb.mMinZ &= ~1;
aabb.mMaxX |= 1;
aabb.mMaxY |= 1;
aabb.mMaxZ |= 1;
*/
/*#if PX_DEBUG
PxBounds3 decodedBox;
PxU32* bin = reinterpret_cast<PxU32*>(&decodedBox.minimum.x);
bin[0] = decodeFloat(bounds.mMinMax[IntegerAABB::MIN_X]);
bin[1] = decodeFloat(bounds.mMinMax[IntegerAABB::MIN_Y]);
bin[2] = decodeFloat(bounds.mMinMax[IntegerAABB::MIN_Z]);
bin[3] = decodeFloat(bounds.mMinMax[IntegerAABB::MAX_X]);
bin[4] = decodeFloat(bounds.mMinMax[IntegerAABB::MAX_Y]);
bin[5] = decodeFloat(bounds.mMinMax[IntegerAABB::MAX_Z]);
MBP_AABB PrunerBox;
PrunerBox.initFrom2(decodedBox);
PX_ASSERT(PrunerBox.mMinX==aabb.mMinX);
PX_ASSERT(PrunerBox.mMinY==aabb.mMinY);
PX_ASSERT(PrunerBox.mMinZ==aabb.mMinZ);
PX_ASSERT(PrunerBox.mMaxX==aabb.mMaxX);
PX_ASSERT(PrunerBox.mMaxY==aabb.mMaxY);
PX_ASSERT(PrunerBox.mMaxZ==aabb.mMaxZ);
#endif*/
}
void BroadPhaseMBP::removeObjects(const BroadPhaseUpdateData& updateData)
{
const BpHandle* PX_RESTRICT removed = updateData.getRemovedHandles();
if(removed)
{
PxU32 nbToGo = updateData.getNumRemovedHandles();
while(nbToGo--)
{
const BpHandle index = *removed++;
PX_ASSERT(index+1<mCapacity); // PT: we allocated one more box on purpose
const bool status = mMBP->removeObject(mMapping[index]);
PX_ASSERT(status);
PX_UNUSED(status);
mMapping[index] = PX_INVALID_U32;
}
}
}
void BroadPhaseMBP::updateObjects(const BroadPhaseUpdateData& updateData)
{
const BpHandle* PX_RESTRICT updated = updateData.getUpdatedHandles();
if(updated)
{
const PxBounds3* PX_RESTRICT boundsXYZ = updateData.getAABBs();
PxU32 nbToGo = updateData.getNumUpdatedHandles();
while(nbToGo--)
{
const BpHandle index = *updated++;
PX_ASSERT(index+1<mCapacity); // PT: we allocated one more box on purpose
MBP_AABB aabb;
computeMBPBounds(aabb, boundsXYZ, updateData.getContactDistance(), index);
const bool status = mMBP->updateObject(mMapping[index], aabb);
PX_ASSERT(status);
PX_UNUSED(status);
}
}
}
void BroadPhaseMBP::addObjects(const BroadPhaseUpdateData& updateData)
{
const BpHandle* PX_RESTRICT created = updateData.getCreatedHandles();
if(created)
{
const PxBounds3* PX_RESTRICT boundsXYZ = updateData.getAABBs();
const Bp::FilterGroup::Enum* PX_RESTRICT groups = updateData.getGroups();
PxU32 nbToGo = updateData.getNumCreatedHandles();
while(nbToGo--)
{
const BpHandle index = *created++;
PX_ASSERT(index+1<mCapacity); // PT: we allocated one more box on purpose
MBP_AABB aabb;
computeMBPBounds(aabb, boundsXYZ, updateData.getContactDistance(), index);
const PxU32 group = groups[index];
const bool isStatic = group==FilterGroup::eSTATICS;
mMapping[index] = mMBP->addObject(aabb, index, isStatic);
}
}
}
void BroadPhaseMBP::setUpdateData(const BroadPhaseUpdateData& updateData)
{
PX_PROFILE_ZONE("BroadPhaseMBP::setUpdateData", mContextID);
// mMBP->setTransientBounds(updateData.getAABBs(), updateData.getContactDistance());
const PxU32 newCapacity = updateData.getCapacity();
if(newCapacity>mCapacity)
allocateMappingArray(newCapacity);
#if PX_CHECKED
// PT: WARNING: this must be done after the allocateMappingArray call
if(!BroadPhaseUpdateData::isValid(updateData, *this, false, mContextID))
{
PX_CHECK_MSG(false, "Illegal BroadPhaseUpdateData \n");
return;
}
#endif
mGroups = updateData.getGroups();
mFilter = &updateData.getFilter();
// ### TODO: handle groups inside MBP
// ### TODO: get rid of AABB conversions
removeObjects(updateData);
addObjects(updateData);
updateObjects(updateData);
PX_ASSERT(!mCreated.size());
PX_ASSERT(!mDeleted.size());
mMBP->prepareOverlaps();
}
void BroadPhaseMBP::update()
{
#ifdef CHECK_NB_OVERLAPS
gNbOverlaps = 0;
#endif
mMBP->findOverlaps(mGroups, mFilter->getLUT());
#ifdef CHECK_NB_OVERLAPS
printf("PPU: %d overlaps\n", gNbOverlaps);
#endif
}
void BroadPhaseMBP::postUpdate()
{
{
PxU32 Nb = mMBP->mNbRegions;
const RegionData* PX_RESTRICT regions = mMBP->mRegions.begin();
for(PxU32 i=0;i<Nb;i++)
{
if(regions[i].mBP)
regions[i].mBP->mNbUpdatedBoxes = 0;
}
}
mMBP->finalize(this);
}
const BroadPhasePair* BroadPhaseMBP::getCreatedPairs(PxU32& nbCreatedPairs) const
{
nbCreatedPairs = mCreated.size();
return mCreated.begin();
}
const BroadPhasePair* BroadPhaseMBP::getDeletedPairs(PxU32& nbDeletedPairs) const
{
nbDeletedPairs = mDeleted.size();
return mDeleted.begin();
}
PxU32 BroadPhaseMBP::getNbOutOfBoundsObjects() const
{
return mMBP->mOutOfBoundsObjects.size();
}
const PxU32* BroadPhaseMBP::getOutOfBoundsObjects() const
{
return mMBP->mOutOfBoundsObjects.begin();
}
static void freeBuffer(PxArray<BroadPhasePair>& buffer)
{
const PxU32 size = buffer.size();
if(size>DEFAULT_CREATED_DELETED_PAIRS_CAPACITY)
{
buffer.reset();
buffer.reserve(DEFAULT_CREATED_DELETED_PAIRS_CAPACITY);
}
else
{
buffer.clear();
}
}
void BroadPhaseMBP::freeBuffers()
{
mMBP->freeBuffers();
freeBuffer(mCreated);
freeBuffer(mDeleted);
}
#if PX_CHECKED
bool BroadPhaseMBP::isValid(const BroadPhaseUpdateData& updateData) const
{
const BpHandle* created = updateData.getCreatedHandles();
if(created)
{
PxHashSet<BpHandle> set;
PxU32 nbObjects = mMBP->mMBP_Objects.size();
const MBP_Object* PX_RESTRICT objects = mMBP->mMBP_Objects.begin();
while(nbObjects--)
{
if(!(objects->mFlags & MBP_REMOVED))
set.insert(objects->mUserID);
objects++;
}
PxU32 nbToGo = updateData.getNumCreatedHandles();
while(nbToGo--)
{
const BpHandle index = *created++;
PX_ASSERT(index<mCapacity);
if(set.contains(index))
return false; // This object has been added already
}
}
const BpHandle* updated = updateData.getUpdatedHandles();
if(updated)
{
PxU32 nbToGo = updateData.getNumUpdatedHandles();
while(nbToGo--)
{
const BpHandle index = *updated++;
PX_ASSERT(index<mCapacity);
if(mMapping[index]==PX_INVALID_U32)
return false; // This object has been removed already, or never been added
}
}
const BpHandle* removed = updateData.getRemovedHandles();
if(removed)
{
PxU32 nbToGo = updateData.getNumRemovedHandles();
while(nbToGo--)
{
const BpHandle index = *removed++;
PX_ASSERT(index<mCapacity);
if(mMapping[index]==PX_INVALID_U32)
return false; // This object has been removed already, or never been added
}
}
return true;
}
#endif
void BroadPhaseMBP::shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances)
{
mMBP->shiftOrigin(shift, boundsArray, contactDistances);
}
PxU32 BroadPhaseMBP::getCurrentNbPairs() const
{
return mMBP->mPairManager.mNbActivePairs;
}
| 98,031 | C++ | 28.263284 | 205 | 0.711204 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseMBP.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef BP_BROADPHASE_MBP_H
#define BP_BROADPHASE_MBP_H
#include "BpBroadPhase.h"
#include "BpBroadPhaseMBPCommon.h"
#include "foundation/PxArray.h"
namespace internalMBP
{
class MBP;
}
namespace physx
{
namespace Bp
{
class BroadPhaseMBP : public BroadPhase
{
PX_NOCOPY(BroadPhaseMBP)
public:
BroadPhaseMBP( PxU32 maxNbRegions,
PxU32 maxNbBroadPhaseOverlaps,
PxU32 maxNbStaticShapes,
PxU32 maxNbDynamicShapes,
PxU64 contextID);
virtual ~BroadPhaseMBP();
// BroadPhaseBase
virtual void getCaps(PxBroadPhaseCaps& caps) const;
virtual PxU32 getNbRegions() const;
virtual PxU32 getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const;
virtual PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const PxReal* contactDistance);
virtual bool removeRegion(PxU32 handle);
virtual PxU32 getNbOutOfBoundsObjects() const;
virtual const PxU32* getOutOfBoundsObjects() const;
//~BroadPhaseBase
// BroadPhase
virtual PxBroadPhaseType::Enum getType() const PX_OVERRIDE { return PxBroadPhaseType::eMBP; }
virtual void release() PX_OVERRIDE { PX_DELETE_THIS; }
virtual void update(PxcScratchAllocator* scratchAllocator, const BroadPhaseUpdateData& updateData, physx::PxBaseTask* continuation) PX_OVERRIDE;
virtual void preBroadPhase(const Bp::BroadPhaseUpdateData&) PX_OVERRIDE {}
virtual void fetchBroadPhaseResults() PX_OVERRIDE {}
virtual const BroadPhasePair* getCreatedPairs(PxU32&) const PX_OVERRIDE;
virtual const BroadPhasePair* getDeletedPairs(PxU32&) const PX_OVERRIDE;
virtual void freeBuffers() PX_OVERRIDE;
virtual void shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances) PX_OVERRIDE;
#if PX_CHECKED
virtual bool isValid(const BroadPhaseUpdateData& updateData) const PX_OVERRIDE;
#endif
//~BroadPhase
internalMBP::MBP* mMBP; // PT: TODO: aggregate
MBP_Handle* mMapping;
PxU32 mCapacity;
PxArray<BroadPhasePair> mCreated;
PxArray<BroadPhasePair> mDeleted;
const Bp::FilterGroup::Enum*mGroups;
const BpFilter* mFilter;
const PxU64 mContextID;
void setUpdateData(const BroadPhaseUpdateData& updateData);
void addObjects(const BroadPhaseUpdateData& updateData);
void removeObjects(const BroadPhaseUpdateData& updateData);
void updateObjects(const BroadPhaseUpdateData& updateData);
void update();
void postUpdate();
void allocateMappingArray(PxU32 newCapacity);
PxU32 getCurrentNbPairs() const;
};
} //namespace Bp
} //namespace physx
#endif // BP_BROADPHASE_MBP_H
| 4,579 | C | 40.636363 | 151 | 0.727233 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseSap.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMath.h"
#include "common/PxProfileZone.h"
#include "CmRadixSort.h"
#include "PxcScratchAllocator.h"
#include "PxSceneDesc.h"
#include "BpBroadPhaseSap.h"
#include "BpBroadPhaseSapAux.h"
#include "foundation/PxAllocator.h"
//#include <stdio.h>
// PT: reactivated this. Ran UTs with SAP as default BP and nothing broke.
#define TEST_DELETED_PAIRS
namespace physx
{
namespace Bp
{
#define DEFAULT_DATA_ARRAY_CAPACITY 1024
#define DEFAULT_CREATEDDELETED_PAIR_ARRAY_CAPACITY 64
#define DEFAULT_CREATEDDELETED1AXIS_CAPACITY 8192
template<typename T, PxU32 stackLimit>
class TmpMem
{
public:
PX_FORCE_INLINE TmpMem(PxU32 size):
mPtr(size<=stackLimit?mStackBuf : PX_ALLOCATE(T, size, "char"))
{
}
PX_FORCE_INLINE ~TmpMem()
{
if(mPtr!=mStackBuf)
PX_FREE(mPtr);
}
PX_FORCE_INLINE T& operator*() const
{
return *mPtr;
}
PX_FORCE_INLINE T* operator->() const
{
return mPtr;
}
PX_FORCE_INLINE T& operator[](PxU32 index)
{
return mPtr[index];
}
T* getBase()
{
return mPtr;
}
private:
T mStackBuf[stackLimit];
T* mPtr;
};
BroadPhaseSap::BroadPhaseSap(
const PxU32 maxNbBroadPhaseOverlaps,
const PxU32 maxNbStaticShapes,
const PxU32 maxNbDynamicShapes,
PxU64 contextID) :
mScratchAllocator (NULL),
mContextID (contextID)
{
for(PxU32 i=0;i<3;i++)
mBatchUpdateTasks[i].setContextId(contextID);
//Boxes
mBoxesSize=0;
mBoxesSizePrev=0;
mBoxesCapacity = (((maxNbStaticShapes + maxNbDynamicShapes) + 31) & ~31);
mBoxEndPts[0] = reinterpret_cast<SapBox1D*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(SapBox1D)*mBoxesCapacity)), "SapBox1D"));
mBoxEndPts[1] = reinterpret_cast<SapBox1D*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(SapBox1D)*mBoxesCapacity)), "SapBox1D"));
mBoxEndPts[2] = reinterpret_cast<SapBox1D*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(SapBox1D)*mBoxesCapacity)), "SapBox1D"));
for(PxU32 i=0; i<mBoxesCapacity;i++)
{
mBoxEndPts[0][i].mMinMax[0]=BP_INVALID_BP_HANDLE;
mBoxEndPts[0][i].mMinMax[1]=BP_INVALID_BP_HANDLE;
mBoxEndPts[1][i].mMinMax[0]=BP_INVALID_BP_HANDLE;
mBoxEndPts[1][i].mMinMax[1]=BP_INVALID_BP_HANDLE;
mBoxEndPts[2][i].mMinMax[0]=BP_INVALID_BP_HANDLE;
mBoxEndPts[2][i].mMinMax[1]=BP_INVALID_BP_HANDLE;
}
//End points
mEndPointsCapacity = mBoxesCapacity*2 + NUM_SENTINELS;
mBoxesUpdated = reinterpret_cast<PxU8*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(PxU8)*mBoxesCapacity)), "BoxesUpdated"));
mSortedUpdateElements = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*mEndPointsCapacity)), "SortedUpdateElements"));
mActivityPockets = reinterpret_cast<BroadPhaseActivityPocket*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BroadPhaseActivityPocket)*mEndPointsCapacity)), "BroadPhaseActivityPocket"));
mEndPointValues[0] = reinterpret_cast<ValType*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(ValType)*(mEndPointsCapacity))), "ValType"));
mEndPointValues[1] = reinterpret_cast<ValType*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(ValType)*(mEndPointsCapacity))), "ValType"));
mEndPointValues[2] = reinterpret_cast<ValType*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(ValType)*(mEndPointsCapacity))), "ValType"));
mEndPointDatas[0] = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*(mEndPointsCapacity))), "BpHandle"));
mEndPointDatas[1] = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*(mEndPointsCapacity))), "BpHandle"));
mEndPointDatas[2]= reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*(mEndPointsCapacity))), "BpHandle"));
// Initialize sentinels
setMinSentinel(mEndPointValues[0][0],mEndPointDatas[0][0]);
setMaxSentinel(mEndPointValues[0][1],mEndPointDatas[0][1]);
setMinSentinel(mEndPointValues[1][0],mEndPointDatas[1][0]);
setMaxSentinel(mEndPointValues[1][1],mEndPointDatas[1][1]);
setMinSentinel(mEndPointValues[2][0],mEndPointDatas[2][0]);
setMaxSentinel(mEndPointValues[2][1],mEndPointDatas[2][1]);
mListNext = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*mEndPointsCapacity)), "NextList"));
mListPrev = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*mEndPointsCapacity)), "PrevList"));
for(PxU32 a = 1; a < mEndPointsCapacity; ++a)
{
mListNext[a-1] = BpHandle(a);
mListPrev[a] = BpHandle(a-1);
}
mListNext[mEndPointsCapacity-1] = BpHandle(mEndPointsCapacity-1);
mListPrev[0] = 0;
mDefaultPairsCapacity = PxMax(maxNbBroadPhaseOverlaps, PxU32(DEFAULT_CREATEDDELETED_PAIR_ARRAY_CAPACITY));
mPairs.init(mDefaultPairsCapacity);
mBatchUpdateTasks[2].set(this,2);
mBatchUpdateTasks[1].set(this,1);
mBatchUpdateTasks[0].set(this,0);
mBatchUpdateTasks[2].setPairs(NULL, 0);
mBatchUpdateTasks[1].setPairs(NULL, 0);
mBatchUpdateTasks[0].setPairs(NULL, 0);
//Initialise data array.
mData = NULL;
mDataSize = 0;
mDataCapacity = 0;
//Initialise pairs arrays.
mCreatedPairsArray = NULL;
mCreatedPairsCapacity = 0;
mCreatedPairsSize = 0;
mDeletedPairsArray = NULL;
mDeletedPairsCapacity = 0;
mDeletedPairsSize = 0;
mActualDeletedPairSize = 0;
mFilter = NULL;
}
BroadPhaseSap::~BroadPhaseSap()
{
PX_FREE(mBoxEndPts[0]);
PX_FREE(mBoxEndPts[1]);
PX_FREE(mBoxEndPts[2]);
PX_FREE(mEndPointValues[0]);
PX_FREE(mEndPointValues[1]);
PX_FREE(mEndPointValues[2]);
PX_FREE(mEndPointDatas[0]);
PX_FREE(mEndPointDatas[1]);
PX_FREE(mEndPointDatas[2]);
PX_FREE(mListNext);
PX_FREE(mListPrev);
PX_FREE(mSortedUpdateElements);
PX_FREE(mActivityPockets);
PX_FREE(mBoxesUpdated);
mPairs.release();
mBatchUpdateTasks[0].setPairs(NULL, 0);
mBatchUpdateTasks[1].setPairs(NULL, 0);
mBatchUpdateTasks[2].setPairs(NULL, 0);
mData = NULL;
mCreatedPairsArray = NULL;
mDeletedPairsArray = NULL;
}
void BroadPhaseSap::release()
{
this->~BroadPhaseSap();
PX_FREE_THIS;
}
void BroadPhaseSap::resizeBuffers()
{
const PxU32 defaultPairsCapacity = mDefaultPairsCapacity;
mCreatedPairsArray = reinterpret_cast<BroadPhasePair*>(mScratchAllocator->alloc(sizeof(BroadPhasePair)*defaultPairsCapacity, true));
mCreatedPairsCapacity = defaultPairsCapacity;
mCreatedPairsSize = 0;
mDeletedPairsArray = reinterpret_cast<BroadPhasePair*>(mScratchAllocator->alloc(sizeof(BroadPhasePair)*defaultPairsCapacity, true));
mDeletedPairsCapacity = defaultPairsCapacity;
mDeletedPairsSize = 0;
mData = reinterpret_cast<BpHandle*>(mScratchAllocator->alloc(sizeof(BpHandle)*defaultPairsCapacity, true));
mDataCapacity = defaultPairsCapacity;
mDataSize = 0;
mBatchUpdateTasks[0].setPairs(reinterpret_cast<BroadPhasePair*>(mScratchAllocator->alloc(sizeof(BroadPhasePair)*defaultPairsCapacity, true)), defaultPairsCapacity);
mBatchUpdateTasks[0].setNumPairs(0);
mBatchUpdateTasks[1].setPairs(reinterpret_cast<BroadPhasePair*>(mScratchAllocator->alloc(sizeof(BroadPhasePair)*defaultPairsCapacity, true)), defaultPairsCapacity);
mBatchUpdateTasks[1].setNumPairs(0);
mBatchUpdateTasks[2].setPairs(reinterpret_cast<BroadPhasePair*>(mScratchAllocator->alloc(sizeof(BroadPhasePair)*defaultPairsCapacity, true)), defaultPairsCapacity);
mBatchUpdateTasks[2].setNumPairs(0);
}
static void DeletePairsLists(const PxU32 numActualDeletedPairs, const BroadPhasePair* deletedPairsList, SapPairManager& pairManager)
{
// #### try batch removal here
for(PxU32 i=0;i<numActualDeletedPairs;i++)
{
const BpHandle id0 = deletedPairsList[i].mVolA;
const BpHandle id1 = deletedPairsList[i].mVolB;
#if PX_DEBUG
const bool Status = pairManager.RemovePair(id0, id1);
PX_ASSERT(Status);
#else
pairManager.RemovePair(id0, id1);
#endif
}
}
void BroadPhaseSap::freeBuffers()
{
// PT: was: void BroadPhaseSap::deletePairs()
#ifndef TEST_DELETED_PAIRS
DeletePairsLists(mActualDeletedPairSize, mDeletedPairsArray, mPairs);
#endif
if(mCreatedPairsArray) mScratchAllocator->free(mCreatedPairsArray);
mCreatedPairsArray = NULL;
mCreatedPairsSize = 0;
mCreatedPairsCapacity = 0;
if(mDeletedPairsArray) mScratchAllocator->free(mDeletedPairsArray);
mDeletedPairsArray = NULL;
mDeletedPairsSize = 0;
mDeletedPairsCapacity = 0;
mActualDeletedPairSize = 0;
if(mData) mScratchAllocator->free(mData);
mData = NULL;
mDataSize = 0;
mDataCapacity = 0;
if(mBatchUpdateTasks[0].getPairs()) mScratchAllocator->free(mBatchUpdateTasks[0].getPairs());
mBatchUpdateTasks[0].setPairs(NULL, 0);
mBatchUpdateTasks[0].setNumPairs(0);
if(mBatchUpdateTasks[1].getPairs()) mScratchAllocator->free(mBatchUpdateTasks[1].getPairs());
mBatchUpdateTasks[1].setPairs(NULL, 0);
mBatchUpdateTasks[1].setNumPairs(0);
if(mBatchUpdateTasks[2].getPairs()) mScratchAllocator->free(mBatchUpdateTasks[2].getPairs());
mBatchUpdateTasks[2].setPairs(NULL, 0);
mBatchUpdateTasks[2].setNumPairs(0);
//Shrink pair manager buffers it they are larger than needed but only let them shrink to a minimum size.
mPairs.shrinkMemory();
}
PX_FORCE_INLINE static void shiftCoord3(const ValType val0, const BpHandle handle0,
const ValType val1, const BpHandle handle1,
const ValType val2, const BpHandle handle2,
const PxF32* shift, ValType& oVal0, ValType& oVal1, ValType& oVal2)
{
PX_ASSERT(!isSentinel(handle0));
PX_ASSERT(!isSentinel(handle1));
PX_ASSERT(!isSentinel(handle2));
PxF32 fl0, fl1, fl2;
ValType* PX_RESTRICT bpVal0 = PxUnionCast<ValType*, PxF32*>(&fl0);
ValType* PX_RESTRICT bpVal1 = PxUnionCast<ValType*, PxF32*>(&fl1);
ValType* PX_RESTRICT bpVal2 = PxUnionCast<ValType*, PxF32*>(&fl2);
*bpVal0 = decodeFloat(val0);
*bpVal1 = decodeFloat(val1);
*bpVal2 = decodeFloat(val2);
fl0 -= shift[0];
fl1 -= shift[1];
fl2 -= shift[2];
oVal0 = (isMax(handle0)) ? (IntegerAABB::encodeFloatMax(*bpVal0) | 1) : ((IntegerAABB::encodeFloatMin(*bpVal0) + 1) & ~1);
oVal1 = (isMax(handle1)) ? (IntegerAABB::encodeFloatMax(*bpVal1) | 1) : ((IntegerAABB::encodeFloatMin(*bpVal1) + 1) & ~1);
oVal2 = (isMax(handle2)) ? (IntegerAABB::encodeFloatMax(*bpVal2) | 1) : ((IntegerAABB::encodeFloatMin(*bpVal2) + 1) & ~1);
}
PX_FORCE_INLINE static void testPostShiftOrder(const ValType prevVal, ValType& currVal, const BpHandle prevIsMax, const BpHandle currIsMax)
{
if(currVal < prevVal)
{
//The order has been broken by the lossy shift.
//Correct currVal so that it is greater than prevVal.
//If currVal is a box max then ensure that the box is of finite extent.
const ValType shiftCorrection = (prevIsMax==currIsMax) ? ValType(0) : ValType(1);
currVal = prevVal + shiftCorrection;
}
}
void BroadPhaseSap::shiftOrigin(const PxVec3& shift, const PxBounds3* /*boundsArray*/, const PxReal* /*contactDistances*/)
{
//
// Note: shifting the bounds does not necessarily preserve the order of the broadphase interval endpoints. The encoding of the float bounds is a lossy
// operation, thus it is not possible to get the original float values back and shift them. The only goal of this method is to shift the endpoints
// such that the order is preserved. The new intervals might no reflect the correct bounds! Since all bounds have been marked dirty, they will get
// recomputed in the next frame anyway. This method makes sure that the next frame update can start from a valid configuration that is close to
// the correct one and does not require too many swaps.
//
if(0==mBoxesSize)
{
return;
}
//
// Note: processing all the axis at once improved performance on XBox 360 and PS3 because it allows to compensate for stalls
//
const PxF32 shiftAxis[3] = { shift.x, shift.y, shift.z };
const BpHandle* PX_RESTRICT epData0 = mEndPointDatas[0];
ValType* PX_RESTRICT epValues0 = mEndPointValues[0];
const BpHandle* PX_RESTRICT epData1 = mEndPointDatas[1];
ValType* PX_RESTRICT epValues1 = mEndPointValues[1];
const BpHandle* PX_RESTRICT epData2 = mEndPointDatas[2];
ValType* PX_RESTRICT epValues2 = mEndPointValues[2];
//Shift the first value in the array of sorted values.
{
//Shifted min (first element must be a min by definition).
shiftCoord3(epValues0[1], epData0[1], epValues1[1], epData1[1], epValues2[1], epData2[1], shiftAxis, epValues0[1], epValues1[1], epValues2[1]);
PX_ASSERT(!isMax(epData0[1]));
PX_ASSERT(!isMax(epData1[1]));
PX_ASSERT(!isMax(epData2[1]));
}
//Shift the remainder.
ValType prevVal0 = epValues0[1];
BpHandle prevIsMax0 = isMax(epData0[1]);
ValType prevVal1 = epValues1[1];
BpHandle prevIsMax1 = isMax(epData1[1]);
ValType prevVal2 = epValues2[1];
BpHandle prevIsMax2 = isMax(epData2[1]);
for(PxU32 i=2; i <= mBoxesSize*2; i++)
{
const BpHandle handle0 = epData0[i];
const BpHandle handle1 = epData1[i];
const BpHandle handle2 = epData2[i];
PX_ASSERT(!isSentinel(handle0));
PX_ASSERT(!isSentinel(handle1));
PX_ASSERT(!isSentinel(handle2));
//Get the relevant prev and curr values after the shift.
const BpHandle currIsMax0 = isMax(epData0[i]);
const BpHandle currIsMax1 = isMax(epData1[i]);
const BpHandle currIsMax2 = isMax(epData2[i]);
ValType currVal0, currVal1, currVal2;
shiftCoord3(epValues0[i], handle0, epValues1[i], handle1, epValues2[i], handle2, shiftAxis, currVal0, currVal1, currVal2);
//Test if the order has been preserved by the lossy shift.
testPostShiftOrder(prevVal0, currVal0, prevIsMax0, currIsMax0);
testPostShiftOrder(prevVal1, currVal1, prevIsMax1, currIsMax1);
testPostShiftOrder(prevVal2, currVal2, prevIsMax2, currIsMax2);
prevIsMax0 = currIsMax0;
prevVal0 = currVal0;
prevIsMax1 = currIsMax1;
prevVal1 = currVal1;
prevIsMax2 = currIsMax2;
prevVal2 = currVal2;
epValues0[i] = currVal0;
epValues1[i] = currVal1;
epValues2[i] = currVal2;
}
PX_ASSERT(isSelfOrdered());
}
#if PX_CHECKED
bool BroadPhaseSap::isValid(const BroadPhaseUpdateData& updateData) const
{
//Test that the created bounds haven't been added already (without first being removed).
const BpHandle* created=updateData.getCreatedHandles();
const PxU32 numCreated=updateData.getNumCreatedHandles();
for(PxU32 i=0;i<numCreated;i++)
{
const BpHandle id=created[i];
//If id >=mBoxesCapacity then we need to resize to add this id, meaning that the id must be new.
if(id<mBoxesCapacity)
{
for(PxU32 j=0;j<3;j++)
{
const SapBox1D& box1d=mBoxEndPts[j][id];
if(box1d.mMinMax[0] != BP_INVALID_BP_HANDLE && box1d.mMinMax[0] != PX_REMOVED_BP_HANDLE)
return false; //This box has been added already but without being removed.
if(box1d.mMinMax[1] != BP_INVALID_BP_HANDLE && box1d.mMinMax[1] != PX_REMOVED_BP_HANDLE)
return false; //This box has been added already but without being removed.
}
}
}
//Test that the updated bounds have valid ids.
const BpHandle* updated=updateData.getUpdatedHandles();
const PxU32 numUpdated=updateData.getNumUpdatedHandles();
for(PxU32 i=0;i<numUpdated;i++)
{
const BpHandle id = updated[i];
if(id >= mBoxesCapacity)
return false;
}
//Test that the updated bounds have been been added without being removed.
for(PxU32 i=0;i<numUpdated;i++)
{
const BpHandle id = updated[i];
for(PxU32 j=0;j<3;j++)
{
const SapBox1D& box1d=mBoxEndPts[j][id];
if(BP_INVALID_BP_HANDLE == box1d.mMinMax[0] || PX_REMOVED_BP_HANDLE == box1d.mMinMax[0])
return false; //This box has either not been added or has been removed
if(BP_INVALID_BP_HANDLE == box1d.mMinMax[1] || PX_REMOVED_BP_HANDLE == box1d.mMinMax[1])
return false; //This box has either not been added or has been removed
}
}
//Test that the removed bounds have valid ids.
const BpHandle* removed=updateData.getRemovedHandles();
const PxU32 numRemoved=updateData.getNumRemovedHandles();
for(PxU32 i=0;i<numRemoved;i++)
{
const BpHandle id = removed[i];
if(id >= mBoxesCapacity)
return false;
}
//Test that the removed bounds have already been added and haven't been removed.
for(PxU32 i=0;i<numRemoved;i++)
{
const BpHandle id = removed[i];
for(PxU32 j=0;j<3;j++)
{
const SapBox1D& box1d=mBoxEndPts[j][id];
if(BP_INVALID_BP_HANDLE == box1d.mMinMax[0] || PX_REMOVED_BP_HANDLE == box1d.mMinMax[0])
return false; //This box has either not been added or has been removed
if(BP_INVALID_BP_HANDLE == box1d.mMinMax[1] || PX_REMOVED_BP_HANDLE == box1d.mMinMax[1])
return false; //This box has either not been added or has been removed
}
}
return true;
}
#endif
void BroadPhaseSap::update(PxcScratchAllocator* scratchAllocator, const BroadPhaseUpdateData& updateData, PxBaseTask* /*continuation*/)
{
PX_CHECK_AND_RETURN(scratchAllocator, "BroadPhaseSap::update - scratchAllocator must be non-NULL \n");
if(setUpdateData(updateData))
{
mScratchAllocator = scratchAllocator;
resizeBuffers();
update();
postUpdate();
}
}
bool BroadPhaseSap::setUpdateData(const BroadPhaseUpdateData& updateData)
{
PX_PROFILE_ZONE("BroadPhaseSap::setUpdateData", mContextID);
PX_ASSERT(0==mCreatedPairsSize);
PX_ASSERT(0==mDeletedPairsSize);
#if PX_CHECKED
if(!BroadPhaseUpdateData::isValid(updateData, *this, false, mContextID))
{
PX_CHECK_MSG(false, "Illegal BroadPhaseUpdateData \n");
mCreated = NULL;
mCreatedSize = 0;
mUpdated = NULL;
mUpdatedSize = 0;
mRemoved = NULL;
mRemovedSize = 0;
mBoxBoundsMinMax = updateData.getAABBs();
mBoxGroups = updateData.getGroups();
return false;
}
#endif
//Copy across the data ptrs and sizes.
mCreated = updateData.getCreatedHandles();
mCreatedSize = updateData.getNumCreatedHandles();
mUpdated = updateData.getUpdatedHandles();
mUpdatedSize = updateData.getNumUpdatedHandles();
mRemoved = updateData.getRemovedHandles();
mRemovedSize = updateData.getNumRemovedHandles();
mBoxBoundsMinMax = updateData.getAABBs();
mBoxGroups = updateData.getGroups();
mFilter = &updateData.getFilter();
mContactDistance = updateData.getContactDistance();
//Do we need more memory to store the positions of each box min/max in the arrays of sorted boxes min/max?
if(updateData.getCapacity() > mBoxesCapacity)
{
const PxU32 oldBoxesCapacity=mBoxesCapacity;
const PxU32 newBoxesCapacity=updateData.getCapacity();
SapBox1D* newBoxEndPts0 = reinterpret_cast<SapBox1D*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(SapBox1D)*newBoxesCapacity)), "SapBox1D"));
SapBox1D* newBoxEndPts1 = reinterpret_cast<SapBox1D*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(SapBox1D)*newBoxesCapacity)), "SapBox1D"));
SapBox1D* newBoxEndPts2 = reinterpret_cast<SapBox1D*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(SapBox1D)*newBoxesCapacity)), "SapBox1D"));
PxMemCopy(newBoxEndPts0, mBoxEndPts[0], sizeof(SapBox1D)*oldBoxesCapacity);
PxMemCopy(newBoxEndPts1, mBoxEndPts[1], sizeof(SapBox1D)*oldBoxesCapacity);
PxMemCopy(newBoxEndPts2, mBoxEndPts[2], sizeof(SapBox1D)*oldBoxesCapacity);
for(PxU32 i=oldBoxesCapacity;i<newBoxesCapacity;i++)
{
newBoxEndPts0[i].mMinMax[0]=BP_INVALID_BP_HANDLE;
newBoxEndPts0[i].mMinMax[1]=BP_INVALID_BP_HANDLE;
newBoxEndPts1[i].mMinMax[0]=BP_INVALID_BP_HANDLE;
newBoxEndPts1[i].mMinMax[1]=BP_INVALID_BP_HANDLE;
newBoxEndPts2[i].mMinMax[0]=BP_INVALID_BP_HANDLE;
newBoxEndPts2[i].mMinMax[1]=BP_INVALID_BP_HANDLE;
}
PX_FREE(mBoxEndPts[0]);
PX_FREE(mBoxEndPts[1]);
PX_FREE(mBoxEndPts[2]);
mBoxEndPts[0] = newBoxEndPts0;
mBoxEndPts[1] = newBoxEndPts1;
mBoxEndPts[2] = newBoxEndPts2;
mBoxesCapacity = newBoxesCapacity;
PX_FREE(mBoxesUpdated);
mBoxesUpdated = reinterpret_cast<PxU8*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(PxU8))*newBoxesCapacity), "Updated Boxes"));
}
//Do we need more memory for the array of sorted boxes?
if(2*(mBoxesSize + mCreatedSize) + NUM_SENTINELS > mEndPointsCapacity)
{
const PxU32 newEndPointsCapacity = 2*(mBoxesSize + mCreatedSize) + NUM_SENTINELS;
ValType* newEndPointValuesX = reinterpret_cast<ValType*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(ValType)*(newEndPointsCapacity))), "BPValType"));
ValType* newEndPointValuesY = reinterpret_cast<ValType*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(ValType)*(newEndPointsCapacity))), "BPValType"));
ValType* newEndPointValuesZ = reinterpret_cast<ValType*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(ValType)*(newEndPointsCapacity))), "BPValType"));
BpHandle* newEndPointDatasX = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*(newEndPointsCapacity))), "BpHandle"));
BpHandle* newEndPointDatasY = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*(newEndPointsCapacity))), "BpHandle"));
BpHandle* newEndPointDatasZ = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*(newEndPointsCapacity))), "BpHandle"));
PX_FREE(mListNext);
PX_FREE(mListPrev);
mListNext = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*newEndPointsCapacity)), "NextList"));
mListPrev = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*newEndPointsCapacity)), "Prev"));
for(PxU32 a = 1; a < newEndPointsCapacity; ++a)
{
mListNext[a-1] = BpHandle(a);
mListPrev[a] = BpHandle(a-1);
}
mListNext[newEndPointsCapacity-1] = BpHandle(newEndPointsCapacity-1);
mListPrev[0] = 0;
PxMemCopy(newEndPointValuesX, mEndPointValues[0], sizeof(ValType)*(mBoxesSize*2+NUM_SENTINELS));
PxMemCopy(newEndPointValuesY, mEndPointValues[1], sizeof(ValType)*(mBoxesSize*2+NUM_SENTINELS));
PxMemCopy(newEndPointValuesZ, mEndPointValues[2], sizeof(ValType)*(mBoxesSize*2+NUM_SENTINELS));
PxMemCopy(newEndPointDatasX, mEndPointDatas[0], sizeof(BpHandle)*(mBoxesSize*2+NUM_SENTINELS));
PxMemCopy(newEndPointDatasY, mEndPointDatas[1], sizeof(BpHandle)*(mBoxesSize*2+NUM_SENTINELS));
PxMemCopy(newEndPointDatasZ, mEndPointDatas[2], sizeof(BpHandle)*(mBoxesSize*2+NUM_SENTINELS));
PX_FREE(mEndPointValues[0]);
PX_FREE(mEndPointValues[1]);
PX_FREE(mEndPointValues[2]);
PX_FREE(mEndPointDatas[0]);
PX_FREE(mEndPointDatas[1]);
PX_FREE(mEndPointDatas[2]);
mEndPointValues[0] = newEndPointValuesX;
mEndPointValues[1] = newEndPointValuesY;
mEndPointValues[2] = newEndPointValuesZ;
mEndPointDatas[0] = newEndPointDatasX;
mEndPointDatas[1] = newEndPointDatasY;
mEndPointDatas[2] = newEndPointDatasZ;
mEndPointsCapacity = newEndPointsCapacity;
PX_FREE(mSortedUpdateElements);
PX_FREE(mActivityPockets);
mSortedUpdateElements = reinterpret_cast<BpHandle*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BpHandle)*newEndPointsCapacity)), "SortedUpdateElements"));
mActivityPockets = reinterpret_cast<BroadPhaseActivityPocket*>(PX_ALLOC(ALIGN_SIZE_16((sizeof(BroadPhaseActivityPocket)*newEndPointsCapacity)), "BroadPhaseActivityPocket"));
}
PxMemZero(mBoxesUpdated, sizeof(PxU8) * (mBoxesCapacity));
for(PxU32 a=0;a<mUpdatedSize;a++)
{
const PxU32 handle=mUpdated[a];
mBoxesUpdated[handle] = 1;
}
//Update the size of the sorted boxes arrays.
PX_ASSERT(mBoxesSize==mBoxesSizePrev);
mBoxesSize += mCreatedSize;
PX_ASSERT(2*mBoxesSize+NUM_SENTINELS <= mEndPointsCapacity);
return true;
}
void BroadPhaseSap::postUpdate()
{
PX_PROFILE_ZONE("BroadPhase.SapPostUpdate", mContextID);
DataArray da(mData, mDataSize, mDataCapacity);
for(PxU32 i=0;i<3;i++)
{
const PxU32 numPairs=mBatchUpdateTasks[i].getPairsSize();
const BroadPhasePair* PX_RESTRICT pairs=mBatchUpdateTasks[i].getPairs();
for(PxU32 j=0;j<numPairs;j++)
{
const BroadPhasePair& pair=pairs[j];
const BpHandle volA=pair.mVolA;
const BpHandle volB=pair.mVolB;
if(volA > volB)
addPair(volA, volB, mScratchAllocator, mPairs, da);
else
removePair(volA, volB, mScratchAllocator, mPairs, da);
}
}
mData = da.mData;
mDataSize = da.mSize;
mDataCapacity = da.mCapacity;
batchCreate();
//Compute the lists of created and deleted overlap pairs.
ComputeCreatedDeletedPairsLists(
mBoxGroups,
mData,mDataSize,
mScratchAllocator,
mCreatedPairsArray,mCreatedPairsSize,mCreatedPairsCapacity,
mDeletedPairsArray,mDeletedPairsSize,mDeletedPairsCapacity,
mActualDeletedPairSize,
mPairs);
#ifdef TEST_DELETED_PAIRS
// PT: TODO: why did we move this to another place?
DeletePairsLists(mActualDeletedPairSize, mDeletedPairsArray, mPairs);
#endif
PX_ASSERT(isSelfConsistent());
mBoxesSizePrev=mBoxesSize;
}
void BroadPhaseBatchUpdateWorkTask::runInternal()
{
mPairsSize=0;
mSap->batchUpdate(mAxis, mPairs, mPairsSize, mPairsCapacity);
}
void BroadPhaseSap::update()
{
PX_PROFILE_ZONE("BroadPhase.SapUpdate", mContextID);
batchRemove();
//Check that the overlap pairs per axis have been reset.
PX_ASSERT(0==mBatchUpdateTasks[0].getPairsSize());
PX_ASSERT(0==mBatchUpdateTasks[1].getPairsSize());
PX_ASSERT(0==mBatchUpdateTasks[2].getPairsSize());
mBatchUpdateTasks[0].runInternal();
mBatchUpdateTasks[1].runInternal();
mBatchUpdateTasks[2].runInternal();
}
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE void InsertEndPoints(const ValType* PX_RESTRICT newEndPointValues, const BpHandle* PX_RESTRICT newEndPointDatas, PxU32 numNewEndPoints,
ValType* PX_RESTRICT endPointValues, BpHandle* PX_RESTRICT endPointDatas, const PxU32 numEndPoints, SapBox1D* PX_RESTRICT boxes)
{
ValType* const BaseEPValue = endPointValues;
BpHandle* const BaseEPData = endPointDatas;
const PxU32 OldSize = numEndPoints-NUM_SENTINELS;
const PxU32 NewSize = numEndPoints-NUM_SENTINELS+numNewEndPoints;
BaseEPValue[NewSize + 1] = BaseEPValue[OldSize + 1];
BaseEPData[NewSize + 1] = BaseEPData[OldSize + 1];
PxI32 WriteIdx = PxI32(NewSize);
PxU32 CurrInsIdx = 0;
//const SapValType* FirstValue = &BaseEPValue[0];
const BpHandle* FirstData = &BaseEPData[0];
const ValType* CurrentValue = &BaseEPValue[OldSize];
const BpHandle* CurrentData = &BaseEPData[OldSize];
while(CurrentData>=FirstData)
{
const ValType& SrcValue = *CurrentValue;
const BpHandle& SrcData = *CurrentData;
const ValType& InsValue = newEndPointValues[CurrInsIdx];
const BpHandle& InsData = newEndPointDatas[CurrInsIdx];
// We need to make sure we insert maxs before mins to handle exactly equal endpoints correctly
const bool ShouldInsert = isMax(InsData) ? (SrcValue <= InsValue) : (SrcValue < InsValue);
const ValType& MovedValue = ShouldInsert ? InsValue : SrcValue;
const BpHandle& MovedData = ShouldInsert ? InsData : SrcData;
BaseEPValue[WriteIdx] = MovedValue;
BaseEPData[WriteIdx] = MovedData;
boxes[getOwner(MovedData)].mMinMax[isMax(MovedData)] = BpHandle(WriteIdx--);
if(ShouldInsert)
{
CurrInsIdx++;
if(CurrInsIdx >= numNewEndPoints)
break;//we just inserted the last endpoint
}
else
{
CurrentValue--;
CurrentData--;
}
}
}
static PX_FORCE_INLINE bool Intersect3D(const ValType bDir1Min, const ValType bDir1Max, const ValType bDir2Min, const ValType bDir2Max, const ValType bDir3Min, const ValType bDir3Max,
const ValType cDir1Min, const ValType cDir1Max, const ValType cDir2Min, const ValType cDir2Max, const ValType cDir3Min, const ValType cDir3Max)
{
return (bDir1Max >= cDir1Min && cDir1Max >= bDir1Min &&
bDir2Max >= cDir2Min && cDir2Max >= bDir2Min &&
bDir3Max >= cDir3Min && cDir3Max >= bDir3Min);
}
void BroadPhaseSap::ComputeSortedLists( //const PxVec4& globalMin, const PxVec4& /*globalMax*/,
BpHandle* PX_RESTRICT newBoxIndicesSorted, PxU32& newBoxIndicesCount, BpHandle* PX_RESTRICT oldBoxIndicesSorted, PxU32& oldBoxIndicesCount,
bool& allNewBoxesStatics, bool& allOldBoxesStatics)
{
//To help us gather the two lists of sorted boxes we are going to use a bitmap and our knowledge of the indices of the new boxes
const PxU32 bitmapWordCount = ((mBoxesCapacity*2 + 31) & ~31)/32;
TmpMem<PxU32, 8> bitMapMem(bitmapWordCount);
PxU32* bitMapWords = bitMapMem.getBase();
PxMemSet(bitMapWords, 0, sizeof(PxU32)*bitmapWordCount);
PxBitMap bitmap;
bitmap.setWords(bitMapWords, bitmapWordCount);
const PxU32 axis0 = 0;
const PxU32 axis1 = 2;
const PxU32 axis2 = 1;
const PxU32 insertAABBStart = 0;
const PxU32 insertAABBEnd = mCreatedSize;
const BpHandle* PX_RESTRICT createdAABBs = mCreated;
SapBox1D** PX_RESTRICT asapBoxes = mBoxEndPts;
const Bp::FilterGroup::Enum* PX_RESTRICT asapBoxGroupIds = mBoxGroups;
BpHandle* PX_RESTRICT asapEndPointDatas = mEndPointDatas[axis0];
const PxU32 numSortedEndPoints = mBoxesSize*2 + NUM_SENTINELS;
//Set the bitmap for new box ids and compute the aabb (of the sorted handles/indices and not of the values) that bounds all new boxes.
PxU32 globalAABBMinX = PX_MAX_U32;
PxU32 globalAABBMinY = PX_MAX_U32;
PxU32 globalAABBMinZ = PX_MAX_U32;
PxU32 globalAABBMaxX = 0;
PxU32 globalAABBMaxY = 0;
PxU32 globalAABBMaxZ = 0;
// PT: TODO: compute the global bounds from the initial data, more cache/SIMD-friendly
// => maybe doesn't work, we're dealing with indices here not actual float values IIRC
for(PxU32 i=insertAABBStart;i<insertAABBEnd;i++)
{
const PxU32 boxId = createdAABBs[i];
bitmap.set(boxId);
globalAABBMinX = PxMin(globalAABBMinX, PxU32(asapBoxes[axis0][boxId].mMinMax[0]));
globalAABBMaxX = PxMax(globalAABBMaxX, PxU32(asapBoxes[axis0][boxId].mMinMax[1]));
globalAABBMinY = PxMin(globalAABBMinY, PxU32(asapBoxes[axis1][boxId].mMinMax[0]));
globalAABBMaxY = PxMax(globalAABBMaxY, PxU32(asapBoxes[axis1][boxId].mMinMax[1]));
globalAABBMinZ = PxMin(globalAABBMinZ, PxU32(asapBoxes[axis2][boxId].mMinMax[0]));
globalAABBMaxZ = PxMax(globalAABBMaxZ, PxU32(asapBoxes[axis2][boxId].mMinMax[1]));
}
/* PxU32 _globalAABBMinX = IntegerAABB::encodeFloatMin(PxUnionCast<PxU32, PxF32>(globalMin.x));
PxU32 _globalAABBMinY = IntegerAABB::encodeFloatMin(PxUnionCast<PxU32, PxF32>(globalMin.y));
PxU32 _globalAABBMinZ = IntegerAABB::encodeFloatMin(PxUnionCast<PxU32, PxF32>(globalMin.z));
PxU32 _globalAABBMaxX = IntegerAABB::encodeFloatMin(PxUnionCast<PxU32, PxF32>(globalMax.x));
PxU32 _globalAABBMaxY = IntegerAABB::encodeFloatMin(PxUnionCast<PxU32, PxF32>(globalMax.y));
PxU32 _globalAABBMaxZ = IntegerAABB::encodeFloatMin(PxUnionCast<PxU32, PxF32>(globalMax.z));
(void)_globalAABBMinX;*/
PxU32 oldStaticCount=0;
PxU32 newStaticCount=0;
//Assign the sorted end pts to the appropriate arrays.
// PT: TODO: we could just do this loop before inserting the new endpts, i.e. no need for a bitmap etc
// => but we need to insert the pts first to have valid mMinMax data in the above loop.
// => but why do we iterate over endpoints and then skip the mins? Why not iterate directly over boxes? ====> probably to get sorted results
// => we could then just use the regular bounds data etc
for(PxU32 i=1;i<numSortedEndPoints-1;i++)
{
//Make sure we haven't encountered a sentinel -
//they should only be at each end of the array.
PX_ASSERT(!isSentinel(asapEndPointDatas[i]));
PX_ASSERT(!isSentinel(asapEndPointDatas[i]));
PX_ASSERT(!isSentinel(asapEndPointDatas[i]));
if(!isMax(asapEndPointDatas[i]))
{
const BpHandle boxId = BpHandle(getOwner(asapEndPointDatas[i]));
if(!bitmap.test(boxId))
{
if(Intersect3D(
globalAABBMinX, globalAABBMaxX, globalAABBMinY, globalAABBMaxY, globalAABBMinZ, globalAABBMaxZ,
asapBoxes[axis0][boxId].mMinMax[0],
asapBoxes[axis0][boxId].mMinMax[1],
asapBoxes[axis1][boxId].mMinMax[0],
asapBoxes[axis1][boxId].mMinMax[1],
asapBoxes[axis2][boxId].mMinMax[0],
asapBoxes[axis2][boxId].mMinMax[1]))
{
oldBoxIndicesSorted[oldBoxIndicesCount++] = boxId;
oldStaticCount += asapBoxGroupIds[boxId]==FilterGroup::eSTATICS ? 0 : 1;
}
}
else
{
newBoxIndicesSorted[newBoxIndicesCount++] = boxId;
newStaticCount += asapBoxGroupIds[boxId]==FilterGroup::eSTATICS ? 0 : 1;
}
}
}
allOldBoxesStatics = oldStaticCount ? false : true;
allNewBoxesStatics = newStaticCount ? false : true;
//Make sure that we've found the correct number of boxes.
PX_ASSERT(newBoxIndicesCount==(insertAABBEnd-insertAABBStart));
PX_ASSERT(oldBoxIndicesCount<=((numSortedEndPoints-NUM_SENTINELS)/2));
}
//#include "foundation/PxVecMath.h"
//using namespace aos;
void BroadPhaseSap::batchCreate()
{
if(!mCreatedSize)
return; // Early-exit if no object has been created
// PxVec4 globalMin, globalMax;
{
//Number of newly-created boxes (still to be sorted) and number of old boxes (already sorted).
const PxU32 numNewBoxes = mCreatedSize;
//const PxU32 numOldBoxes = mBoxesSize - mCreatedSize;
//Array of newly-created box indices.
const BpHandle* PX_RESTRICT created = mCreated;
//Arrays of min and max coords for each box for each axis.
const PxBounds3* PX_RESTRICT minMax = mBoxBoundsMinMax;
/* {
PxU32 nbToGo = numNewBoxes-1;
const PxU32 lastBoxId = created[nbToGo];
const PxVec3 lastMin = minMax[lastBoxId].minimum;
const PxVec3 lastMax = minMax[lastBoxId].maximum;
PxVec4 minI(lastMin.x, lastMin.y, lastMin.z, 0.0f);
PxVec4 maxI(lastMax.x, lastMax.y, lastMax.z, 0.0f);
const Vec4V dist4 = V4Load(mContactDistance[lastBoxId]);
Vec4V resultMinV = V4Sub(V4LoadU(&lastMin.x), dist4);
Vec4V resultMaxV = V4Add(V4LoadU(&lastMax.x), dist4);
const BpHandle* src = created;
while(nbToGo--)
{
const PxU32 boxId = *src++;
const Vec4V d4 = V4Load(mContactDistance[boxId]);
resultMinV = V4Min(resultMinV, V4Sub(V4LoadU(&minMax[boxId].minimum.x), d4));
resultMaxV = V4Max(resultMaxV, V4Add(V4LoadU(&minMax[boxId].maximum.x), d4));
}
V4StoreU(resultMinV, &globalMin.x);
V4StoreU(resultMaxV, &globalMax.x);
}*/
//Insert new boxes into sorted endpoints lists.
{
const PxU32 numEndPoints = numNewBoxes*2;
TmpMem<ValType, 32> nepsv(numEndPoints), bv(numEndPoints);
ValType* newEPSortedValues = nepsv.getBase();
ValType* bufferValues = bv.getBase();
// PT: TODO: use the scratch allocator
Cm::RadixSortBuffered RS;
for(PxU32 Axis=0;Axis<3;Axis++)
{
for(PxU32 i=0;i<numNewBoxes;i++)
{
const PxU32 boxIndex = PxU32(created[i]);
PX_ASSERT(mBoxEndPts[Axis][boxIndex].mMinMax[0]==BP_INVALID_BP_HANDLE || mBoxEndPts[Axis][boxIndex].mMinMax[0]==PX_REMOVED_BP_HANDLE);
PX_ASSERT(mBoxEndPts[Axis][boxIndex].mMinMax[1]==BP_INVALID_BP_HANDLE || mBoxEndPts[Axis][boxIndex].mMinMax[1]==PX_REMOVED_BP_HANDLE);
// const ValType minValue = minMax[boxIndex].getMin(Axis);
// const ValType maxValue = minMax[boxIndex].getMax(Axis);
const PxReal contactDistance = mContactDistance[boxIndex];
newEPSortedValues[i*2+0] = encodeMin(minMax[boxIndex], Axis, contactDistance);
newEPSortedValues[i*2+1] = encodeMax(minMax[boxIndex], Axis, contactDistance);
}
// Sort endpoints backwards
BpHandle* bufferDatas;
{
RS.invalidateRanks(); // PT: there's no coherence between axes
const PxU32* Sorted = RS.Sort(newEPSortedValues, numEndPoints, Cm::RADIX_UNSIGNED).GetRanks();
bufferDatas = RS.GetRecyclable();
// PT: TODO: with two passes here we could reuse the "newEPSortedValues" buffer and drop "bufferValues"
for(PxU32 i=0;i<numEndPoints;i++)
{
const PxU32 sortedIndex = Sorted[numEndPoints-1-i];
bufferValues[i] = newEPSortedValues[sortedIndex];
// PT: compute buffer data on-the-fly, store in recyclable buffer
const PxU32 boxIndex = PxU32(created[sortedIndex>>1]);
bufferDatas[i] = setData(boxIndex, (sortedIndex&1)!=0);
}
}
InsertEndPoints(bufferValues, bufferDatas, numEndPoints, mEndPointValues[Axis], mEndPointDatas[Axis], 2*(mBoxesSize-mCreatedSize)+NUM_SENTINELS, mBoxEndPts[Axis]);
}
}
//Some debug tests.
#if PX_DEBUG
{
for(PxU32 i=0;i<numNewBoxes;i++)
{
PxU32 BoxIndex = PxU32(created[i]);
PX_ASSERT(mBoxEndPts[0][BoxIndex].mMinMax[0]!=BP_INVALID_BP_HANDLE && mBoxEndPts[0][BoxIndex].mMinMax[0]!=PX_REMOVED_BP_HANDLE);
PX_ASSERT(mBoxEndPts[0][BoxIndex].mMinMax[1]!=BP_INVALID_BP_HANDLE && mBoxEndPts[0][BoxIndex].mMinMax[1]!=PX_REMOVED_BP_HANDLE);
PX_ASSERT(mBoxEndPts[1][BoxIndex].mMinMax[0]!=BP_INVALID_BP_HANDLE && mBoxEndPts[1][BoxIndex].mMinMax[0]!=PX_REMOVED_BP_HANDLE);
PX_ASSERT(mBoxEndPts[1][BoxIndex].mMinMax[1]!=BP_INVALID_BP_HANDLE && mBoxEndPts[1][BoxIndex].mMinMax[1]!=PX_REMOVED_BP_HANDLE);
PX_ASSERT(mBoxEndPts[2][BoxIndex].mMinMax[0]!=BP_INVALID_BP_HANDLE && mBoxEndPts[2][BoxIndex].mMinMax[0]!=PX_REMOVED_BP_HANDLE);
PX_ASSERT(mBoxEndPts[2][BoxIndex].mMinMax[1]!=BP_INVALID_BP_HANDLE && mBoxEndPts[2][BoxIndex].mMinMax[1]!=PX_REMOVED_BP_HANDLE);
}
for(PxU32 i=0;i<mBoxesSize*2+1;i++)
{
PX_ASSERT(mEndPointValues[0][i] <= mEndPointValues[0][i+1]);
PX_ASSERT(mEndPointValues[1][i] <= mEndPointValues[1][i+1]);
PX_ASSERT(mEndPointValues[2][i] <= mEndPointValues[2][i+1]);
}
}
#endif
}
// Perform box-pruning
{
// PT: TODO: use the scratch allocator in TmpMem
//Number of newly-created boxes (still to be sorted) and number of old boxes (already sorted).
const PxU32 numNewBoxes = mCreatedSize;
const PxU32 numOldBoxes = mBoxesSize - mCreatedSize;
//Gather two list of sorted boxes along the preferred axis direction:
//one list for new boxes and one list for existing boxes.
//Only gather the existing boxes that overlap the bounding box of
//all new boxes.
TmpMem<BpHandle, 8> oldBoxesIndicesSortedMem(numOldBoxes);
TmpMem<BpHandle, 8> newBoxesIndicesSortedMem(numNewBoxes);
BpHandle* oldBoxesIndicesSorted = oldBoxesIndicesSortedMem.getBase();
BpHandle* newBoxesIndicesSorted = newBoxesIndicesSortedMem.getBase();
PxU32 oldBoxCount = 0;
PxU32 newBoxCount = 0;
bool allNewBoxesStatics = false;
bool allOldBoxesStatics = false;
// PT: TODO: separate static/dynamic to speed things up, compute "minPosList" etc at the same time
// PT: TODO: isn't "newBoxesIndicesSorted" the same as what we already computed in batchCreate() ?
//Ready to gather the two lists now.
ComputeSortedLists(/*globalMin, globalMax,*/ newBoxesIndicesSorted, newBoxCount, oldBoxesIndicesSorted, oldBoxCount, allNewBoxesStatics, allOldBoxesStatics);
//Intersect new boxes with new boxes and new boxes with existing boxes.
if(!allNewBoxesStatics || !allOldBoxesStatics)
{
const AuxData data0(newBoxCount, mBoxEndPts, newBoxesIndicesSorted, mBoxGroups);
if(!allNewBoxesStatics)
performBoxPruningNewNew(&data0, mScratchAllocator, mFilter->getLUT(), mPairs, mData, mDataSize, mDataCapacity);
// the old boxes are not the first ones in the array
if(numOldBoxes)
{
if(oldBoxCount)
{
const AuxData data1(oldBoxCount, mBoxEndPts, oldBoxesIndicesSorted, mBoxGroups);
performBoxPruningNewOld(&data0, &data1, mScratchAllocator, mFilter->getLUT(), mPairs, mData, mDataSize, mDataCapacity);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
void BroadPhaseSap::batchRemove()
{
if(!mRemovedSize) return; // Early-exit if no object has been removed
//The box count is incremented when boxes are added to the create list but these boxes
//haven't yet been added to the pair manager or the sorted axis lists. We need to
//pretend that the box count is the value it was when the bp was last updated.
//Then, at the end, we need to set the box count to the number that includes the boxes
//in the create list and subtract off the boxes that have been removed.
PxU32 currBoxesSize=mBoxesSize;
mBoxesSize=mBoxesSizePrev;
for(PxU32 Axis=0;Axis<3;Axis++)
{
ValType* const BaseEPValue = mEndPointValues[Axis];
BpHandle* const BaseEPData = mEndPointDatas[Axis];
PxU32 MinMinIndex = PX_MAX_U32;
for(PxU32 i=0;i<mRemovedSize;i++)
{
PX_ASSERT(mRemoved[i]<mBoxesCapacity);
const PxU32 MinIndex = mBoxEndPts[Axis][mRemoved[i]].mMinMax[0];
PX_ASSERT(MinIndex<mBoxesCapacity*2+2);
PX_ASSERT(getOwner(BaseEPData[MinIndex])==mRemoved[i]);
const PxU32 MaxIndex = mBoxEndPts[Axis][mRemoved[i]].mMinMax[1];
PX_ASSERT(MaxIndex<mBoxesCapacity*2+2);
PX_ASSERT(getOwner(BaseEPData[MaxIndex])==mRemoved[i]);
PX_ASSERT(MinIndex<MaxIndex);
BaseEPData[MinIndex] = PX_REMOVED_BP_HANDLE;
BaseEPData[MaxIndex] = PX_REMOVED_BP_HANDLE;
if(MinIndex<MinMinIndex)
MinMinIndex = MinIndex;
}
PxU32 ReadIndex = MinMinIndex;
PxU32 DestIndex = MinMinIndex;
const PxU32 Limit = mBoxesSize*2+NUM_SENTINELS;
while(ReadIndex!=Limit)
{
PxPrefetchLine(&BaseEPData[ReadIndex],128);
while(ReadIndex!=Limit && BaseEPData[ReadIndex] == PX_REMOVED_BP_HANDLE)
{
PxPrefetchLine(&BaseEPData[ReadIndex],128);
ReadIndex++;
}
if(ReadIndex!=Limit)
{
if(ReadIndex!=DestIndex)
{
BaseEPValue[DestIndex] = BaseEPValue[ReadIndex];
BaseEPData[DestIndex] = BaseEPData[ReadIndex];
PX_ASSERT(BaseEPData[DestIndex] != PX_REMOVED_BP_HANDLE);
if(!isSentinel(BaseEPData[DestIndex]))
{
BpHandle BoxOwner = getOwner(BaseEPData[DestIndex]);
PX_ASSERT(BoxOwner<mBoxesCapacity);
mBoxEndPts[Axis][BoxOwner].mMinMax[isMax(BaseEPData[DestIndex])] = BpHandle(DestIndex);
}
}
DestIndex++;
ReadIndex++;
}
}
}
for(PxU32 i=0;i<mRemovedSize;i++)
{
const PxU32 handle=mRemoved[i];
mBoxEndPts[0][handle].mMinMax[0]=PX_REMOVED_BP_HANDLE;
mBoxEndPts[0][handle].mMinMax[1]=PX_REMOVED_BP_HANDLE;
mBoxEndPts[1][handle].mMinMax[0]=PX_REMOVED_BP_HANDLE;
mBoxEndPts[1][handle].mMinMax[1]=PX_REMOVED_BP_HANDLE;
mBoxEndPts[2][handle].mMinMax[0]=PX_REMOVED_BP_HANDLE;
mBoxEndPts[2][handle].mMinMax[1]=PX_REMOVED_BP_HANDLE;
}
const PxU32 bitmapWordCount=1+(mBoxesCapacity>>5);
TmpMem<PxU32, 128> bitmapWords(bitmapWordCount);
PxMemZero(bitmapWords.getBase(),sizeof(PxU32)*bitmapWordCount);
PxBitMap bitmap;
bitmap.setWords(bitmapWords.getBase(),bitmapWordCount);
for(PxU32 i=0;i<mRemovedSize;i++)
{
PxU32 Index = mRemoved[i];
PX_ASSERT(Index<mBoxesCapacity);
PX_ASSERT(0==bitmap.test(Index));
bitmap.set(Index);
}
mPairs.RemovePairs(bitmap);
mBoxesSize=currBoxesSize;
mBoxesSize-=mRemovedSize;
mBoxesSizePrev=mBoxesSize-mCreatedSize;
}
static BroadPhasePair* resizeBroadPhasePairArray(const PxU32 oldMaxNb, const PxU32 newMaxNb, PxcScratchAllocator* scratchAllocator, BroadPhasePair* elements)
{
PX_ASSERT(newMaxNb > oldMaxNb);
PX_ASSERT(newMaxNb > 0);
PX_ASSERT(0==((newMaxNb*sizeof(BroadPhasePair)) & 15));
BroadPhasePair* newElements = reinterpret_cast<BroadPhasePair*>(scratchAllocator->alloc(sizeof(BroadPhasePair)*newMaxNb, true));
PX_ASSERT(0==(uintptr_t(newElements) & 0x0f));
PxMemCopy(newElements, elements, oldMaxNb*sizeof(BroadPhasePair));
scratchAllocator->free(elements);
return newElements;
}
#define PERFORM_COMPARISONS 1
void BroadPhaseSap::batchUpdate
(const PxU32 Axis, BroadPhasePair*& pairs, PxU32& pairsSize, PxU32& pairsCapacity)
{
//Nothin updated so don't do anything
if(mUpdatedSize == 0)
return;
//If number updated is sufficiently fewer than number of boxes (say less than 20%)
if((mUpdatedSize*5) < mBoxesSize)
{
batchUpdateFewUpdates(Axis, pairs, pairsSize, pairsCapacity);
return;
}
PxU32 numPairs=0;
PxU32 maxNumPairs=pairsCapacity;
const PxBounds3* PX_RESTRICT boxMinMax3D = mBoxBoundsMinMax;
SapBox1D* boxMinMax2D[6]={mBoxEndPts[1],mBoxEndPts[2],mBoxEndPts[2],mBoxEndPts[0],mBoxEndPts[0],mBoxEndPts[1]};
const SapBox1D* PX_RESTRICT boxMinMax0=boxMinMax2D[2*Axis+0];
const SapBox1D* PX_RESTRICT boxMinMax1=boxMinMax2D[2*Axis+1];
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
const Bp::FilterGroup::Enum* PX_RESTRICT asapBoxGroupIds=mBoxGroups;
#endif
SapBox1D* PX_RESTRICT asapBoxes=mBoxEndPts[Axis];
ValType* PX_RESTRICT asapEndPointValues=mEndPointValues[Axis];
BpHandle* PX_RESTRICT asapEndPointDatas=mEndPointDatas[Axis];
ValType* const PX_RESTRICT BaseEPValues = asapEndPointValues;
BpHandle* const PX_RESTRICT BaseEPDatas = asapEndPointDatas;
PxU8* PX_RESTRICT updated = mBoxesUpdated;
//KS - can we lazy create these inside the loop? Might benefit us
//There are no extents, jus the sentinels, so exit early.
if(isSentinel(BaseEPDatas[1]))
return;
//We are going to skip the 1st element in the array (the sublist will be sorted)
//but we must first update its value if it has moved
//const PxU32 startIsMax = isMax(BaseEPDatas[1]);
PX_ASSERT(!isMax(BaseEPDatas[1]));
const BpHandle startHandle = getOwner(BaseEPDatas[1]);
//KS - in theory, we should just be able to grab the min element but there's some issue where a body's max < min (i.e. an invalid extents) that
//appears in a unit test
// ValType ThisValue_ = boxMinMax3D[startHandle].getMin(Axis);
ValType ThisValue_ = encodeMin(boxMinMax3D[startHandle], Axis, mContactDistance[startHandle]);
BaseEPValues[1] = ThisValue_;
PxU32 updateCounter = mUpdatedSize*2;
updateCounter -= updated[startHandle];
//We'll never overlap with this sentinel but it just ensures that we don't need to branch to see if
//there's a pocket that we need to test against
BroadPhaseActivityPocket* PX_RESTRICT currentPocket = mActivityPockets;
currentPocket->mEndIndex = 0;
currentPocket->mStartIndex = 0;
BpHandle ind = 2;
PxU8 wasUpdated = updated[startHandle];
for(; !isSentinel(BaseEPDatas[ind]); ++ind)
{
BpHandle ThisData = BaseEPDatas[ind];
const BpHandle handle = getOwner(ThisData);
if(updated[handle] || wasUpdated)
{
wasUpdated = updated[handle];
updateCounter -= wasUpdated;
BpHandle ThisIndex = ind;
const BpHandle startIsMax = isMax(ThisData);
//Access and write back the updated values. TODO - can we avoid this when we're walking through inactive nodes?
//BPValType ThisValue = boxMinMax1D[Axis][twoHandle+startIsMax];
//BPValType ThisValue = startIsMax ? boxMinMax3D[handle].getMax(Axis) : boxMinMax3D[handle].getMin(Axis);
//ValType ThisValue = boxMinMax3D[handle].getExtent(startIsMax, Axis);
ValType ThisValue = startIsMax ? encodeMax(boxMinMax3D[handle], Axis, mContactDistance[handle])
: encodeMin(boxMinMax3D[handle], Axis, mContactDistance[handle]);
BaseEPValues[ThisIndex] = ThisValue;
PX_ASSERT(handle!=BP_INVALID_BP_HANDLE);
//We always iterate back through the list...
BpHandle CurrentIndex = mListPrev[ThisIndex];
ValType CurrentValue = BaseEPValues[CurrentIndex];
//PxBpHandle CurrentData = BaseEPDatas[CurrentIndex];
if(CurrentValue > ThisValue)
{
wasUpdated = 1;
//Get the bounds of the curr aabb.
//Get the box1d of the curr aabb.
/*const SapBox1D* PX_RESTRICT Object=&asapBoxes[handle];
PX_ASSERT(Object->mMinMax[0]!=BP_INVALID_BP_HANDLE);
PX_ASSERT(Object->mMinMax[1]!=BP_INVALID_BP_HANDLE);*/
// const ValType boxMax=boxMinMax3D[handle].getMax(Axis);
const ValType boxMax=encodeMax(boxMinMax3D[handle], Axis, mContactDistance[handle]);
PxU32 endIndex = ind;
PxU32 startIndex = ind;
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
const Bp::FilterGroup::Enum group = asapBoxGroupIds[handle];
#endif
if(!isMax(ThisData))
{
do
{
BpHandle CurrentData = BaseEPDatas[CurrentIndex];
const BpHandle IsMax = isMax(CurrentData);
#if PERFORM_COMPARISONS
if(IsMax)
{
const BpHandle ownerId=getOwner(CurrentData);
SapBox1D* PX_RESTRICT id1 = asapBoxes + ownerId;
// Our min passed a max => start overlap
if(
BaseEPValues[id1->mMinMax[0]] < boxMax &&
//2D intersection test using up-to-date values
Intersect2D_Handle(boxMinMax0[handle].mMinMax[0], boxMinMax0[handle].mMinMax[1], boxMinMax1[handle].mMinMax[0], boxMinMax1[handle].mMinMax[1],
boxMinMax0[ownerId].mMinMax[0],boxMinMax0[ownerId].mMinMax[1],boxMinMax1[ownerId].mMinMax[0],boxMinMax1[ownerId].mMinMax[1])
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
&& groupFiltering(group, asapBoxGroupIds[ownerId], mFilter->getLUT())
#else
&& handle!=ownerId
#endif
)
{
if(numPairs==maxNumPairs)
{
const PxU32 newMaxNumPairs=maxNumPairs*2;
pairs = reinterpret_cast<BroadPhasePair*>(resizeBroadPhasePairArray(maxNumPairs, newMaxNumPairs, mScratchAllocator, pairs));
maxNumPairs=newMaxNumPairs;
}
PX_ASSERT(numPairs<maxNumPairs);
pairs[numPairs].mVolA=BpHandle(PxMax(handle, ownerId));
pairs[numPairs].mVolB=BpHandle(PxMin(handle, ownerId));
numPairs++;
//AddPair(handle, getOwner(*CurrentMinData), mPairs, mData, mDataSize, mDataCapacity);
}
}
#endif
startIndex--;
CurrentIndex = mListPrev[CurrentIndex];
CurrentValue = BaseEPValues[CurrentIndex];
}
while(ThisValue < CurrentValue);
}
else
{
// Max is moving left:
do
{
BpHandle CurrentData = BaseEPDatas[CurrentIndex];
const BpHandle IsMax = isMax(CurrentData);
#if PERFORM_COMPARISONS
if(!IsMax)
{
// Our max passed a min => stop overlap
const BpHandle ownerId=getOwner(CurrentData);
#if 1
if(
#if BP_SAP_USE_OVERLAP_TEST_ON_REMOVES
Intersect2D_Handle(boxMinMax0[handle].mMinMax[0], boxMinMax0[handle].mMinMax[1], boxMinMax1[handle].mMinMax[0], boxMinMax1[handle].mMinMax[1],
boxMinMax0[ownerId].mMinMax[0],boxMinMax0[ownerId].mMinMax[1],boxMinMax1[ownerId].mMinMax[0],boxMinMax1[ownerId].mMinMax[1])
#endif
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
&& groupFiltering(group, asapBoxGroupIds[ownerId], mFilter->getLUT())
#else
&& handle!=ownerId
#endif
)
#endif
{
if(numPairs==maxNumPairs)
{
const PxU32 newMaxNumPairs=maxNumPairs*2;
pairs = reinterpret_cast<BroadPhasePair*>(resizeBroadPhasePairArray(maxNumPairs, newMaxNumPairs, mScratchAllocator, pairs));
maxNumPairs=newMaxNumPairs;
}
PX_ASSERT(numPairs<maxNumPairs);
pairs[numPairs].mVolA=BpHandle(PxMin(handle, ownerId));
pairs[numPairs].mVolB=BpHandle(PxMax(handle, ownerId));
numPairs++;
//RemovePair(handle, getOwner(*CurrentMaxData), mPairs, mData, mDataSize, mDataCapacity);
}
}
#endif
startIndex--;
CurrentIndex = mListPrev[CurrentIndex];
CurrentValue = BaseEPValues[CurrentIndex];
}
while(ThisValue < CurrentValue);
}
//This test is unnecessary. If we entered the outer loop, we're doing the swap in here
{
//Unlink from old position and re-link to new position
BpHandle oldNextIndex = mListNext[ThisIndex];
BpHandle oldPrevIndex = mListPrev[ThisIndex];
BpHandle newNextIndex = mListNext[CurrentIndex];
BpHandle newPrevIndex = CurrentIndex;
//Unlink this node
mListNext[oldPrevIndex] = oldNextIndex;
mListPrev[oldNextIndex] = oldPrevIndex;
//Link it to it's new place in the list
mListNext[ThisIndex] = newNextIndex;
mListPrev[ThisIndex] = newPrevIndex;
mListPrev[newNextIndex] = ThisIndex;
mListNext[newPrevIndex] = ThisIndex;
}
//There is a sentinel with 0 index, so we don't need
//to worry about walking off the array
while(startIndex < currentPocket->mStartIndex)
{
currentPocket--;
}
//If our start index > currentPocket->mEndIndex, then we don't overlap so create a new pocket
if(currentPocket == mActivityPockets || startIndex > (currentPocket->mEndIndex+1))
{
currentPocket++;
currentPocket->mStartIndex = startIndex;
}
currentPocket->mEndIndex = endIndex;
}// update max
//ind++;
}
else if (updateCounter == 0) //We've updated all the bodies and neither this nor the previous body was updated, so we're done
break;
}// updated aabbs
pairsSize=numPairs;
pairsCapacity=maxNumPairs;
BroadPhaseActivityPocket* pocket = mActivityPockets+1;
while(pocket <= currentPocket)
{
for(PxU32 a = pocket->mStartIndex; a <= pocket->mEndIndex; ++a)
{
mListPrev[a] = BpHandle(a);
}
//Now copy all the data to the array, updating the remap table
PxU32 CurrIndex = pocket->mStartIndex-1;
for(PxU32 a = pocket->mStartIndex; a <= pocket->mEndIndex; ++a)
{
CurrIndex = mListNext[CurrIndex];
PxU32 origIndex = CurrIndex;
BpHandle remappedIndex = mListPrev[origIndex];
if(origIndex != a)
{
const BpHandle ownerId=getOwner(BaseEPDatas[remappedIndex]);
const BpHandle IsMax = isMax(BaseEPDatas[remappedIndex]);
ValType tmp = BaseEPValues[a];
BpHandle tmpHandle = BaseEPDatas[a];
BaseEPValues[a] = BaseEPValues[remappedIndex];
BaseEPDatas[a] = BaseEPDatas[remappedIndex];
BaseEPValues[remappedIndex] = tmp;
BaseEPDatas[remappedIndex] = tmpHandle;
mListPrev[remappedIndex] = mListPrev[a];
//Write back remap index (should be an immediate jump to original index)
mListPrev[mListPrev[a]] = remappedIndex;
asapBoxes[ownerId].mMinMax[IsMax] = BpHandle(a);
}
}
////Reset next and prev ptrs back
for(PxU32 a = pocket->mStartIndex-1; a <= pocket->mEndIndex; ++a)
{
mListPrev[a+1] = BpHandle(a);
mListNext[a] = BpHandle(a+1);
}
pocket++;
}
mListPrev[0] = 0;
}
void BroadPhaseSap::batchUpdateFewUpdates(const PxU32 Axis, BroadPhasePair*& pairs, PxU32& pairsSize, PxU32& pairsCapacity)
{
PxU32 numPairs=0;
PxU32 maxNumPairs=pairsCapacity;
const PxBounds3* PX_RESTRICT boxMinMax3D = mBoxBoundsMinMax;
SapBox1D* boxMinMax2D[6]={mBoxEndPts[1],mBoxEndPts[2],mBoxEndPts[2],mBoxEndPts[0],mBoxEndPts[0],mBoxEndPts[1]};
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
const Bp::FilterGroup::Enum* PX_RESTRICT asapBoxGroupIds=mBoxGroups;
#endif
SapBox1D* PX_RESTRICT asapBoxes=mBoxEndPts[Axis];
/*const BPValType* PX_RESTRICT boxMinMax0=boxMinMax2D[2*Axis];
const BPValType* PX_RESTRICT boxMinMax1=boxMinMax2D[2*Axis+1];*/
ValType* PX_RESTRICT asapEndPointValues=mEndPointValues[Axis];
BpHandle* PX_RESTRICT asapEndPointDatas=mEndPointDatas[Axis];
ValType* const PX_RESTRICT BaseEPValues = asapEndPointValues;
BpHandle* const PX_RESTRICT BaseEPDatas = asapEndPointDatas;
const SapBox1D* PX_RESTRICT boxMinMax0=boxMinMax2D[2*Axis+0];
const SapBox1D* PX_RESTRICT boxMinMax1=boxMinMax2D[2*Axis+1];
PxU8* PX_RESTRICT updated = mBoxesUpdated;
const PxU32 endPointSize = mBoxesSize*2 + 1;
//There are no extents, just the sentinels, so exit early.
if(isSentinel(BaseEPDatas[1]))
return;
PxU32 ind_ = 0;
PxU32 index = 1;
if(mUpdatedSize < 512)
{
//The array of updated elements is small, so use qsort to sort them
for(PxU32 a = 0; a < mUpdatedSize; ++a)
{
const PxU32 handle=mUpdated[a];
const SapBox1D* Object=&asapBoxes[handle];
PX_ASSERT(Object->mMinMax[0]!=BP_INVALID_BP_HANDLE);
PX_ASSERT(Object->mMinMax[1]!=BP_INVALID_BP_HANDLE);
//Get the bounds of the curr aabb.
// const ValType boxMin=boxMinMax3D[handle].getMin(Axis);
// const ValType boxMax=boxMinMax3D[handle].getMax(Axis);
const ValType boxMin = encodeMin(boxMinMax3D[handle], Axis, mContactDistance[handle]);
const ValType boxMax = encodeMax(boxMinMax3D[handle], Axis, mContactDistance[handle]);
BaseEPValues[Object->mMinMax[0]] = boxMin;
BaseEPValues[Object->mMinMax[1]] = boxMax;
mSortedUpdateElements[ind_++] = Object->mMinMax[0];
mSortedUpdateElements[ind_++] = Object->mMinMax[1];
}
PxSort(mSortedUpdateElements, ind_);
}
else
{
//The array of updated elements is large so use a bucket sort to sort them
for(; index < endPointSize; ++index)
{
if(isSentinel( BaseEPDatas[index] ))
break;
BpHandle ThisData = BaseEPDatas[index];
BpHandle owner = BpHandle(getOwner(ThisData));
if(updated[owner])
{
//BPValType ThisValue = isMax(ThisData) ? boxMinMax3D[owner].getMax(Axis) : boxMinMax3D[owner].getMin(Axis);
ValType ThisValue = isMax(ThisData) ? encodeMax(boxMinMax3D[owner], Axis, mContactDistance[owner])
: encodeMin(boxMinMax3D[owner], Axis, mContactDistance[owner]);
BaseEPValues[index] = ThisValue;
mSortedUpdateElements[ind_++] = BpHandle(index);
}
}
}
const PxU32 updateCounter = ind_;
//We'll never overlap with this sentinel but it just ensures that we don't need to branch to see if
//there's a pocket that we need to test against
BroadPhaseActivityPocket* PX_RESTRICT currentPocket = mActivityPockets;
currentPocket->mEndIndex = 0;
currentPocket->mStartIndex = 0;
for(PxU32 a = 0; a < updateCounter; ++a)
{
BpHandle ind = mSortedUpdateElements[a];
BpHandle NextData;
BpHandle PrevData;
do
{
BpHandle ThisData = BaseEPDatas[ind];
const BpHandle handle = getOwner(ThisData);
BpHandle ThisIndex = ind;
ValType ThisValue = BaseEPValues[ThisIndex];
//Get the box1d of the curr aabb.
const SapBox1D* PX_RESTRICT Object=&asapBoxes[handle];
PX_ASSERT(handle!=BP_INVALID_BP_HANDLE);
PX_ASSERT(Object->mMinMax[0]!=BP_INVALID_BP_HANDLE);
PX_ASSERT(Object->mMinMax[1]!=BP_INVALID_BP_HANDLE);
PX_UNUSED(Object);
//Get the bounds of the curr aabb.
//const PxU32 twoHandle = 2*handle;
const ValType boxMax=encodeMax(boxMinMax3D[handle], Axis, mContactDistance[handle]);
//We always iterate back through the list...
BpHandle CurrentIndex = mListPrev[ThisIndex];
ValType CurrentValue = BaseEPValues[CurrentIndex];
if(CurrentValue > ThisValue)
{
//We're performing some swaps so we need an activity pocket here. This structure allows us to keep track of the range of
//modifications in the sorted lists. Doesn't help when everything's moving but makes a really big difference to reconstituting the
//list when only a small number of things are moving
PxU32 endIndex = ind;
PxU32 startIndex = ind;
//const BPValType* PX_RESTRICT box0MinMax0 = &boxMinMax0[twoHandle];
//const BPValType* PX_RESTRICT box0MinMax1 = &boxMinMax1[twoHandle];
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
const Bp::FilterGroup::Enum group = asapBoxGroupIds[handle];
#endif
if(!isMax(ThisData))
{
do
{
BpHandle CurrentData = BaseEPDatas[CurrentIndex];
const BpHandle IsMax = isMax(CurrentData);
#if PERFORM_COMPARISONS
if(IsMax)
{
const BpHandle ownerId=getOwner(CurrentData);
SapBox1D* PX_RESTRICT id1 = asapBoxes + ownerId;
// Our min passed a max => start overlap
if(
BaseEPValues[id1->mMinMax[0]] < boxMax &&
//2D intersection test using up-to-date values
Intersect2D_Handle(boxMinMax0[handle].mMinMax[0], boxMinMax0[handle].mMinMax[1], boxMinMax1[handle].mMinMax[0], boxMinMax1[handle].mMinMax[1],
boxMinMax0[ownerId].mMinMax[0],boxMinMax0[ownerId].mMinMax[1],boxMinMax1[ownerId].mMinMax[0],boxMinMax1[ownerId].mMinMax[1])
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
&& groupFiltering(group, asapBoxGroupIds[ownerId], mFilter->getLUT())
#else
&& Object!=id1
#endif
)
{
if(numPairs==maxNumPairs)
{
const PxU32 newMaxNumPairs=maxNumPairs*2;
pairs = reinterpret_cast<BroadPhasePair*>(resizeBroadPhasePairArray(maxNumPairs, newMaxNumPairs, mScratchAllocator, pairs));
maxNumPairs=newMaxNumPairs;
}
PX_ASSERT(numPairs<maxNumPairs);
pairs[numPairs].mVolA=BpHandle(PxMax(handle, ownerId));
pairs[numPairs].mVolB=BpHandle(PxMin(handle, ownerId));
numPairs++;
//AddPair(handle, getOwner(*CurrentMinData), mPairs, mData, mDataSize, mDataCapacity);
}
}
#endif
startIndex--;
CurrentIndex = mListPrev[CurrentIndex];
CurrentValue = BaseEPValues[CurrentIndex];
}
while(ThisValue < CurrentValue);
}
else
{
// Max is moving left:
do
{
BpHandle CurrentData = BaseEPDatas[CurrentIndex];
const BpHandle IsMax = isMax(CurrentData);
#if PERFORM_COMPARISONS
if(!IsMax)
{
// Our max passed a min => stop overlap
const BpHandle ownerId=getOwner(CurrentData);
#if 1
if(
#if BP_SAP_USE_OVERLAP_TEST_ON_REMOVES
Intersect2D_Handle(boxMinMax0[handle].mMinMax[0], boxMinMax0[handle].mMinMax[1], boxMinMax1[handle].mMinMax[0], boxMinMax1[handle].mMinMax[1],
boxMinMax0[ownerId].mMinMax[0],boxMinMax0[ownerId].mMinMax[1],boxMinMax1[ownerId].mMinMax[0],boxMinMax1[ownerId].mMinMax[1])
#endif
#if BP_SAP_TEST_GROUP_ID_CREATEUPDATE
&& groupFiltering(group, asapBoxGroupIds[ownerId], mFilter->getLUT())
#else
&& Object!=id1
#endif
)
#endif
{
if(numPairs==maxNumPairs)
{
const PxU32 newMaxNumPairs=maxNumPairs*2;
pairs = reinterpret_cast<BroadPhasePair*>(resizeBroadPhasePairArray(maxNumPairs, newMaxNumPairs, mScratchAllocator, pairs));
maxNumPairs=newMaxNumPairs;
}
PX_ASSERT(numPairs<maxNumPairs);
pairs[numPairs].mVolA=BpHandle(PxMin(handle, ownerId));
pairs[numPairs].mVolB=BpHandle(PxMax(handle, ownerId));
numPairs++;
//RemovePair(handle, getOwner(*CurrentMaxData), mPairs, mData, mDataSize, mDataCapacity);
}
}
#endif
startIndex--;
CurrentIndex = mListPrev[CurrentIndex];
CurrentValue = BaseEPValues[CurrentIndex];
}
while(ThisValue < CurrentValue);
}
//This test is unnecessary. If we entered the outer loop, we're doing the swap in here
{
//Unlink from old position and re-link to new position
BpHandle oldNextIndex = mListNext[ThisIndex];
BpHandle oldPrevIndex = mListPrev[ThisIndex];
BpHandle newNextIndex = mListNext[CurrentIndex];
BpHandle newPrevIndex = CurrentIndex;
//Unlink this node
mListNext[oldPrevIndex] = oldNextIndex;
mListPrev[oldNextIndex] = oldPrevIndex;
//Link it to it's new place in the list
mListNext[ThisIndex] = newNextIndex;
mListPrev[ThisIndex] = newPrevIndex;
mListPrev[newNextIndex] = ThisIndex;
mListNext[newPrevIndex] = ThisIndex;
}
//Loop over the activity pocket stack to make sure this set of shuffles didn't
//interfere with the previous set. If it did, we roll this pocket into the previous
//pockets. If everything in the scene is moving, we should result in just 1 pocket
while(startIndex < currentPocket->mStartIndex)
{
currentPocket--;
}
//If our start index > currentPocket->mEndIndex, then we don't overlap so create a new pocket
if(currentPocket == mActivityPockets || startIndex > (currentPocket->mEndIndex+1))
{
currentPocket++;
currentPocket->mStartIndex = startIndex;
}
currentPocket->mEndIndex = endIndex;
}// update max
//Get prev and next ptr...
NextData = BaseEPDatas[++ind];
PrevData = BaseEPDatas[mListPrev[ind]];
}while(!isSentinel(NextData) && !updated[getOwner(NextData)] && updated[getOwner(PrevData)]);
}// updated aabbs
pairsSize=numPairs;
pairsCapacity=maxNumPairs;
BroadPhaseActivityPocket* pocket = mActivityPockets+1;
while(pocket <= currentPocket)
{
//PxU32 CurrIndex = mListPrev[pocket->mStartIndex];
for(PxU32 a = pocket->mStartIndex; a <= pocket->mEndIndex; ++a)
{
mListPrev[a] = BpHandle(a);
}
//Now copy all the data to the array, updating the remap table
PxU32 CurrIndex = pocket->mStartIndex-1;
for(PxU32 a = pocket->mStartIndex; a <= pocket->mEndIndex; ++a)
{
CurrIndex = mListNext[CurrIndex];
PxU32 origIndex = CurrIndex;
BpHandle remappedIndex = mListPrev[origIndex];
if(origIndex != a)
{
const BpHandle ownerId=getOwner(BaseEPDatas[remappedIndex]);
const BpHandle IsMax = isMax(BaseEPDatas[remappedIndex]);
ValType tmp = BaseEPValues[a];
BpHandle tmpHandle = BaseEPDatas[a];
BaseEPValues[a] = BaseEPValues[remappedIndex];
BaseEPDatas[a] = BaseEPDatas[remappedIndex];
BaseEPValues[remappedIndex] = tmp;
BaseEPDatas[remappedIndex] = tmpHandle;
mListPrev[remappedIndex] = mListPrev[a];
//Write back remap index (should be an immediate jump to original index)
mListPrev[mListPrev[a]] = remappedIndex;
asapBoxes[ownerId].mMinMax[IsMax] = BpHandle(a);
}
}
for(PxU32 a = pocket->mStartIndex-1; a <= pocket->mEndIndex; ++a)
{
mListPrev[a+1] = BpHandle(a);
mListNext[a] = BpHandle(a+1);
}
pocket++;
}
}
#if PX_DEBUG
bool BroadPhaseSap::isSelfOrdered() const
{
if(0==mBoxesSize)
return true;
for(PxU32 Axis=0;Axis<3;Axis++)
{
PxU32 it=1;
PX_ASSERT(mEndPointDatas[Axis]);
while(!isSentinel(mEndPointDatas[Axis][it]))
{
//Test the array is sorted.
const ValType prevVal=mEndPointValues[Axis][it-1];
const ValType currVal=mEndPointValues[Axis][it];
if(currVal<prevVal)
return false;
//Test the end point array is consistent.
const BpHandle ismax=isMax(mEndPointDatas[Axis][it]);
const BpHandle ownerId=getOwner(mEndPointDatas[Axis][it]);
if(mBoxEndPts[Axis][ownerId].mMinMax[ismax]!=it)
return false;
//Test the mins are even, the maxes are odd, and the extents are finite.
const ValType boxMin = mEndPointValues[Axis][mBoxEndPts[Axis][ownerId].mMinMax[0]];
const ValType boxMax = mEndPointValues[Axis][mBoxEndPts[Axis][ownerId].mMinMax[1]];
if(boxMin & 1)
return false;
if(0==(boxMax & 1))
return false;
if(boxMax<=boxMin)
return false;
it++;
}
}
return true;
}
bool BroadPhaseSap::isSelfConsistent() const
{
if(0==mBoxesSize)
return true;
for(PxU32 Axis=0;Axis<3;Axis++)
{
PxU32 it=1;
ValType prevVal=0;
const PxBounds3* PX_RESTRICT boxMinMax = mBoxBoundsMinMax;
const PxReal* PX_RESTRICT contactDistance = mContactDistance;
PX_ASSERT(mEndPointDatas[Axis]);
while(!isSentinel(mEndPointDatas[Axis][it]))
{
const BpHandle ownerId=getOwner(mEndPointDatas[Axis][it]);
const BpHandle ismax=isMax(mEndPointDatas[Axis][it]);
const ValType boxMinMaxs[2] = { encodeMin(boxMinMax[ownerId], Axis, contactDistance[ownerId]),
encodeMax(boxMinMax[ownerId], Axis, contactDistance[ownerId]) };
// const ValType boxMinMaxs[2] = { boxMinMax[ownerId].getMin(Axis), boxMinMax[ownerId].getMax(Axis) };
const ValType test1=boxMinMaxs[ismax];
const ValType test2=mEndPointValues[Axis][it];
if(test1!=test2)
return false;
if(test2<prevVal)
return false;
prevVal=test2;
if(mBoxEndPts[Axis][ownerId].mMinMax[ismax]!=it)
return false;
it++;
}
}
for(PxU32 i=0;i<mCreatedPairsSize;i++)
{
const PxU32 a=mCreatedPairsArray[i].mVolA;
const PxU32 b=mCreatedPairsArray[i].mVolB;
IntegerAABB aabb0(mBoxBoundsMinMax[a], mContactDistance[a]);
IntegerAABB aabb1(mBoxBoundsMinMax[b], mContactDistance[b]);
if(!aabb0.intersects(aabb1))
return false;
}
for(PxU32 i=0;i<mDeletedPairsSize;i++)
{
const PxU32 a=mDeletedPairsArray[i].mVolA;
const PxU32 b=mDeletedPairsArray[i].mVolB;
bool isDeleted=false;
for(PxU32 j=0;j<mRemovedSize;j++)
{
if(a==mRemoved[j] || b==mRemoved[j])
isDeleted=true;
}
if(!isDeleted)
{
IntegerAABB aabb0(mBoxBoundsMinMax[a], mContactDistance[a]);
IntegerAABB aabb1(mBoxBoundsMinMax[b], mContactDistance[b]);
if(aabb0.intersects(aabb1))
{
// with the past refactors this should have become illegal
return false;
}
}
}
return true;
}
#endif
} //namespace Bp
} //namespace physx
| 68,288 | C++ | 34.697334 | 183 | 0.722733 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseMBPCommon.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef BP_BROADPHASE_MBP_COMMON_H
#define BP_BROADPHASE_MBP_COMMON_H
#include "PxPhysXConfig.h"
#include "BpBroadPhaseIntegerAABB.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
namespace Bp
{
#define MBP_USE_WORDS
#define MBP_USE_NO_CMP_OVERLAP
#if PX_INTEL_FAMILY && !defined(PX_SIMD_DISABLED)
#define MBP_SIMD_OVERLAP
#endif
#ifdef MBP_USE_WORDS
typedef PxU16 MBP_Index;
#else
typedef PxU32 MBP_Index;
#endif
typedef PxU32 MBP_ObjectIndex; // PT: index in mMBP_Objects
typedef PxU32 MBP_Handle; // PT: returned to MBP users, combination of index/flip-flop/static-bit
struct IAABB : public PxUserAllocated
{
PX_FORCE_INLINE bool isInside(const IAABB& box) const
{
if(box.mMinX>mMinX) return false;
if(box.mMinY>mMinY) return false;
if(box.mMinZ>mMinZ) return false;
if(box.mMaxX<mMaxX) return false;
if(box.mMaxY<mMaxY) return false;
if(box.mMaxZ<mMaxZ) return false;
return true;
}
PX_FORCE_INLINE PxIntBool intersects(const IAABB& a) const
{
if(mMaxX < a.mMinX || a.mMaxX < mMinX
|| mMaxY < a.mMinY || a.mMaxY < mMinY
|| mMaxZ < a.mMinZ || a.mMaxZ < mMinZ
)
return PxIntFalse;
return PxIntTrue;
}
PX_FORCE_INLINE PxIntBool intersectNoTouch(const IAABB& a) const
{
if(mMaxX <= a.mMinX || a.mMaxX <= mMinX
|| mMaxY <= a.mMinY || a.mMaxY <= mMinY
|| mMaxZ <= a.mMinZ || a.mMaxZ <= mMinZ
)
return PxIntFalse;
return PxIntTrue;
}
PX_FORCE_INLINE void initFrom2(const PxBounds3& box)
{
const PxU32* PX_RESTRICT binary = reinterpret_cast<const PxU32*>(&box.minimum.x);
mMinX = encodeFloat(binary[0])>>1;
mMinY = encodeFloat(binary[1])>>1;
mMinZ = encodeFloat(binary[2])>>1;
mMaxX = encodeFloat(binary[3])>>1;
mMaxY = encodeFloat(binary[4])>>1;
mMaxZ = encodeFloat(binary[5])>>1;
}
PX_FORCE_INLINE void decode(PxBounds3& box) const
{
PxU32* PX_RESTRICT binary = reinterpret_cast<PxU32*>(&box.minimum.x);
binary[0] = decodeFloat(mMinX<<1);
binary[1] = decodeFloat(mMinY<<1);
binary[2] = decodeFloat(mMinZ<<1);
binary[3] = decodeFloat(mMaxX<<1);
binary[4] = decodeFloat(mMaxY<<1);
binary[5] = decodeFloat(mMaxZ<<1);
}
PX_FORCE_INLINE PxU32 getMin(PxU32 i) const { return (&mMinX)[i]; }
PX_FORCE_INLINE PxU32 getMax(PxU32 i) const { return (&mMaxX)[i]; }
PxU32 mMinX;
PxU32 mMinY;
PxU32 mMinZ;
PxU32 mMaxX;
PxU32 mMaxY;
PxU32 mMaxZ;
};
struct SIMD_AABB : public PxUserAllocated
{
PX_FORCE_INLINE void initFrom(const PxBounds3& box)
{
const PxU32* PX_RESTRICT binary = reinterpret_cast<const PxU32*>(&box.minimum.x);
mMinX = encodeFloat(binary[0]);
mMinY = encodeFloat(binary[1]);
mMinZ = encodeFloat(binary[2]);
mMaxX = encodeFloat(binary[3]);
mMaxY = encodeFloat(binary[4]);
mMaxZ = encodeFloat(binary[5]);
}
PX_FORCE_INLINE void initFrom2(const PxBounds3& box)
{
const PxU32* PX_RESTRICT binary = reinterpret_cast<const PxU32*>(&box.minimum.x);
mMinX = encodeFloat(binary[0])>>1;
mMinY = encodeFloat(binary[1])>>1;
mMinZ = encodeFloat(binary[2])>>1;
mMaxX = encodeFloat(binary[3])>>1;
mMaxY = encodeFloat(binary[4])>>1;
mMaxZ = encodeFloat(binary[5])>>1;
}
PX_FORCE_INLINE void decode(PxBounds3& box) const
{
PxU32* PX_RESTRICT binary = reinterpret_cast<PxU32*>(&box.minimum.x);
binary[0] = decodeFloat(mMinX<<1);
binary[1] = decodeFloat(mMinY<<1);
binary[2] = decodeFloat(mMinZ<<1);
binary[3] = decodeFloat(mMaxX<<1);
binary[4] = decodeFloat(mMaxY<<1);
binary[5] = decodeFloat(mMaxZ<<1);
}
PX_FORCE_INLINE bool isInside(const SIMD_AABB& box) const
{
if(box.mMinX>mMinX) return false;
if(box.mMinY>mMinY) return false;
if(box.mMinZ>mMinZ) return false;
if(box.mMaxX<mMaxX) return false;
if(box.mMaxY<mMaxY) return false;
if(box.mMaxZ<mMaxZ) return false;
return true;
}
PX_FORCE_INLINE PxIntBool intersects(const SIMD_AABB& a) const
{
if(mMaxX < a.mMinX || a.mMaxX < mMinX
|| mMaxY < a.mMinY || a.mMaxY < mMinY
|| mMaxZ < a.mMinZ || a.mMaxZ < mMinZ
)
return PxIntFalse;
return PxIntTrue;
}
PX_FORCE_INLINE PxIntBool intersectNoTouch(const SIMD_AABB& a) const
{
if(mMaxX <= a.mMinX || a.mMaxX <= mMinX
|| mMaxY <= a.mMinY || a.mMaxY <= mMinY
|| mMaxZ <= a.mMinZ || a.mMaxZ <= mMinZ
)
return PxIntFalse;
return PxIntTrue;
}
PxU32 mMinX;
PxU32 mMaxX;
PxU32 mMinY;
PxU32 mMinZ;
PxU32 mMaxY;
PxU32 mMaxZ;
};
}
} // namespace physx
#endif // BP_BROADPHASE_MBP_COMMON_H
| 6,232 | C | 30.321608 | 100 | 0.692715 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpBroadPhaseABP.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxProfiler.h"
#include "foundation/PxMemory.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxFPU.h"
#include "BpBroadPhaseABP.h"
#include "BpBroadPhaseShared.h"
#include "foundation/PxVecMath.h"
#include "PxcScratchAllocator.h"
#include "common/PxProfileZone.h"
#include "CmRadixSort.h"
#include "CmUtils.h"
#include "GuBounds.h"
#include "foundation/PxThread.h"
#include "foundation/PxSync.h"
#include "task/PxTask.h"
using namespace physx::aos;
using namespace physx;
using namespace Bp;
using namespace Cm;
/*
PT: to try:
- prepare data: sort & compute bounds in parallel? or just MT the last loop?
- switch post update & add delayed pairs?
- MT computeCreatedDeletedPairs
- why do we set the update flag for added/removed objects?
- use timestamps instead of bits?
*/
#define ABP_MT
#define CHECKPOINT(x)
//#include <stdio.h>
//#define CHECKPOINT(x) printf(x);
//#pragma warning (disable : 4702)
#define CODEALIGN16 //_asm align 16
#if PX_INTEL_FAMILY && !defined(PX_SIMD_DISABLED)
#define ABP_SIMD_OVERLAP
#endif
//#define ABP_BATCHING 128
#define ABP_BATCHING 256
//#define USE_ABP_BUCKETS 5000 // PT: don't use buckets below that number...
#define USE_ABP_BUCKETS 512 // PT: don't use buckets below that number...
//#define USE_ABP_BUCKETS 64 // PT: don't use buckets below that number...
#ifdef USE_ABP_BUCKETS
#define NB_BUCKETS 5
// Regular version: 5 buckets a la bucket pruner (4 + cross bucket)
// Alternative version: 4 buckets + dup objects a la MBP regions
// #define USE_ALTERNATIVE_VERSION
#define ABP_USE_INTEGER_XS2 // Works but questionable speedups
#else
#define ABP_USE_INTEGER_XS
#endif
#define NB_SENTINELS 6
//#define RECURSE_LIMIT 20000
typedef PxU32 ABP_Index;
static const bool gPrepareOverlapsFlag = true;
#ifdef ABP_SIMD_OVERLAP
static const bool gUseRegularBPKernel = false; // false to use "version 13" in box pruning series
static const bool gUnrollLoop = true; // true to use "version 14" in box pruning series
#else
// PT: tested on Switch, for some reason the regular version is fastest there
static const bool gUseRegularBPKernel = true; // false to use "version 13" in box pruning series
static const bool gUnrollLoop = false; // true to use "version 14" in box pruning series
//ABP_SIMD_OVERLAP
//MBP.Add64KObjects 13982 ( +0.0%) 4757795 ( +0.0%) FAIL
//MBP.AddBroadPhaseRegion 0 ( +0.0%) 3213795 ( +0.0%) FAIL
//MBP.FinalizeOverlaps64KObjects 507 ( +0.0%) 5650723 ( +0.0%) FAIL
//MBP.FindOverlaps64KMixedObjects 59258 ( +0.0%) 5170179 ( +0.0%) FAIL
//MBP.FindOverlaps64KObjects 31351 ( +0.0%) 7122019 ( +0.0%) FAIL
//MBP.Remove64KObjects 4993 ( +0.0%) 5281683 ( +0.0%) FAIL
//MBP.Update64KObjects 13711 ( +0.0%) 5521699 ( +0.0%) FAIL
//gUseRegularBPKernel:
//MBP.Add64KObjects 14406 ( +0.0%) 4757795 ( +0.0%) FAIL
//MBP.AddBroadPhaseRegion 0 ( +0.0%) 3213795 ( +0.0%) FAIL
//MBP.FinalizeOverlaps64KObjects 504 ( +0.0%) 5650723 ( +0.0%) FAIL
//MBP.FindOverlaps64KMixedObjects 48929 ( +0.0%) 5170179 ( +0.0%) FAIL
//MBP.FindOverlaps64KObjects 25636 ( +0.0%) 7122019 ( +0.0%) FAIL
//MBP.Remove64KObjects 4878 ( +0.0%) 5281683 ( +0.0%) FAIL
//MBP.Update64KObjects 13932 ( +0.0%) 5521699 ( +0.0%) FAIL
// false/true
//MBP.Add64KObjects 14278 ( +0.0%) 4757795 ( +0.0%) FAIL
//MBP.AddBroadPhaseRegion 0 ( +0.0%) 3213795 ( +0.0%) FAIL
//MBP.FinalizeOverlaps64KObjects 504 ( +0.0%) 5650723 ( +0.0%) FAIL
//MBP.FindOverlaps64KMixedObjects 60331 ( +0.0%) 5170179 ( +0.0%) FAIL
//MBP.FindOverlaps64KObjects 32064 ( +0.0%) 7122019 ( +0.0%) FAIL
//MBP.Remove64KObjects 4930 ( +0.0%) 5281683 ( +0.0%) FAIL
//MBP.Update64KObjects 13673 ( +0.0%) 5521699 ( +0.0%) FAIL
// false/false
//MBP.Add64KObjects 13960 ( +0.0%) 4757795 ( +0.0%) FAIL
//MBP.AddBroadPhaseRegion 0 ( +0.0%) 3213795 ( +0.0%) FAIL
//MBP.FinalizeOverlaps64KObjects 503 ( +0.0%) 5650723 ( +0.0%) FAIL
//MBP.FindOverlaps64KMixedObjects 48549 ( +0.0%) 5170179 ( +0.0%) FAIL
//MBP.FindOverlaps64KObjects 25598 ( +0.0%) 7122019 ( +0.0%) FAIL
//MBP.Remove64KObjects 4883 ( +0.0%) 5281683 ( +0.0%) FAIL
//MBP.Update64KObjects 13667 ( +0.0%) 5521699 ( +0.0%) FAIL
#endif
#ifdef ABP_USE_INTEGER_XS
typedef PxU32 PosXType;
#define SentinelValue 0xffffffff
#else
typedef float PosXType;
#define SentinelValue FLT_MAX
#endif
#ifdef ABP_USE_INTEGER_XS2
typedef PxU32 PosXType2;
#define SentinelValue2 0xffffffff
#else
#ifdef ABP_USE_INTEGER_XS
typedef PxU32 PosXType2;
#define SentinelValue2 0xffffffff
#else
typedef float PosXType2;
#define SentinelValue2 FLT_MAX
#endif
#endif
namespace internalABP
{
struct SIMD_AABB4 : public PxUserAllocated
{
PX_FORCE_INLINE void initFrom2(const PxBounds3& box)
{
#ifdef ABP_USE_INTEGER_XS
mMinX = encodeFloat(PX_IR(box.minimum.x));
mMaxX = encodeFloat(PX_IR(box.maximum.x));
mMinY = box.minimum.y;
mMinZ = box.minimum.z;
mMaxY = box.maximum.y;
mMaxZ = box.maximum.z;
#else
mMinX = box.minimum.x;
mMinY = box.minimum.y;
mMinZ = box.minimum.z;
mMaxX = box.maximum.x;
mMaxY = box.maximum.y;
mMaxZ = box.maximum.z;
#endif
}
PX_FORCE_INLINE void operator = (const SIMD_AABB4& box)
{
mMinX = box.mMinX;
mMinY = box.mMinY;
mMinZ = box.mMinZ;
mMaxX = box.mMaxX;
mMaxY = box.mMaxY;
mMaxZ = box.mMaxZ;
}
PX_FORCE_INLINE void initSentinel()
{
mMinX = SentinelValue;
}
PX_FORCE_INLINE bool isSentinel() const
{
return mMinX == SentinelValue;
}
#ifdef USE_ABP_BUCKETS
// PT: to be able to compute bounds easily
PosXType mMinX;
float mMinY;
float mMinZ;
PosXType mMaxX;
float mMaxY;
float mMaxZ;
#else
PosXType mMinX;
PosXType mMaxX;
float mMinY;
float mMinZ;
float mMaxY;
float mMaxZ;
#endif
};
#define USE_SHARED_CLASSES
#ifdef USE_SHARED_CLASSES
struct SIMD_AABB_X4 : public AABB_Xi
{
PX_FORCE_INLINE void initFrom(const SIMD_AABB4& box)
{
#ifdef ABP_USE_INTEGER_XS2
initFromFloats(&box.mMinX, &box.mMaxX);
#else
mMinX = box.mMinX;
mMaxX = box.mMaxX;
#endif
}
};
PX_ALIGN_PREFIX(16)
#ifdef ABP_SIMD_OVERLAP
struct SIMD_AABB_YZ4 : AABB_YZn
{
PX_FORCE_INLINE void initFrom(const SIMD_AABB4& box)
{
#ifdef ABP_SIMD_OVERLAP
mMinY = -box.mMinY;
mMinZ = -box.mMinZ;
#else
mMinY = box.mMinY;
mMinZ = box.mMinZ;
#endif
mMaxY = box.mMaxY;
mMaxZ = box.mMaxZ;
}
}
#else
struct SIMD_AABB_YZ4 : AABB_YZr
{
PX_FORCE_INLINE void initFrom(const SIMD_AABB4& box)
{
mMinY = box.mMinY;
mMinZ = box.mMinZ;
mMaxY = box.mMaxY;
mMaxZ = box.mMaxZ;
}
}
#endif
PX_ALIGN_SUFFIX(16);
#else
struct SIMD_AABB_X4 : public PxUserAllocated
{
PX_FORCE_INLINE void initFromFloats(const void* PX_RESTRICT minX, const void* PX_RESTRICT maxX)
{
mMinX = encodeFloat(*reinterpret_cast<const PxU32*>(minX));
mMaxX = encodeFloat(*reinterpret_cast<const PxU32*>(maxX));
}
PX_FORCE_INLINE void initFrom(const SIMD_AABB4& box)
{
#ifdef ABP_USE_INTEGER_XS2
initFromFloats(&box.mMinX, &box.mMaxX);
#else
mMinX = box.mMinX;
mMaxX = box.mMaxX;
#endif
}
PX_FORCE_INLINE void initFromPxVec4(const PxVec4& min, const PxVec4& max)
{
#ifdef ABP_USE_INTEGER_XS2
initFromFloats(&min.x, &max.x);
#else
#ifdef ABP_USE_INTEGER_XS
initFromFloats(&min.x, &max.x);
#else
mMinX = min.x;
mMaxX = max.x;
#endif
#endif
}
PX_FORCE_INLINE void operator = (const SIMD_AABB_X4& box)
{
mMinX = box.mMinX;
mMaxX = box.mMaxX;
}
PX_FORCE_INLINE void initSentinel()
{
mMinX = SentinelValue2;
}
PX_FORCE_INLINE bool isSentinel() const
{
return mMinX == SentinelValue2;
}
PosXType2 mMinX;
PosXType2 mMaxX;
};
struct SIMD_AABB_YZ4 : public PxUserAllocated
{
PX_FORCE_INLINE void initFrom(const SIMD_AABB4& box)
{
#ifdef ABP_SIMD_OVERLAP
mMinY = -box.mMinY;
mMinZ = -box.mMinZ;
#else
mMinY = box.mMinY;
mMinZ = box.mMinZ;
#endif
mMaxY = box.mMaxY;
mMaxZ = box.mMaxZ;
}
PX_FORCE_INLINE void initFromPxVec4(const PxVec4& min, const PxVec4& max)
{
#ifdef ABP_SIMD_OVERLAP
mMinY = -min.y;
mMinZ = -min.z;
#else
mMinY = min.y;
mMinZ = min.z;
#endif
mMaxY = max.y;
mMaxZ = max.z;
}
PX_FORCE_INLINE void operator = (const SIMD_AABB_YZ4& box)
{
V4StoreA(V4LoadA(&box.mMinY), &mMinY);
}
float mMinY;
float mMinZ;
float mMaxY;
float mMaxZ;
};
#endif
#define MBP_ALLOC(x) PX_ALLOC(x, "MBP")
#define MBP_ALLOC_TMP(x) PX_ALLOC(x, "MBP_TMP")
#define MBP_FREE(x) PX_FREE(x)
#define INVALID_ID 0xffffffff
///////////////////////////////////////////////////////////////////////////////
#define DEFAULT_NB_ENTRIES 128
class ABP_MM
{
public:
ABP_MM() : mScratchAllocator(NULL) {}
~ABP_MM() {}
void* frameAlloc(PxU32 size);
void frameFree(void* address);
PxcScratchAllocator* mScratchAllocator;
};
void* ABP_MM::frameAlloc(PxU32 size)
{
if(mScratchAllocator)
return mScratchAllocator->alloc(size, true);
return PX_ALLOC(size, "frameAlloc");
}
void ABP_MM::frameFree(void* address)
{
if(mScratchAllocator)
mScratchAllocator->free(address);
else
PX_FREE(address);
}
template<class T>
static T* resizeBoxesT(PxU32 oldNbBoxes, PxU32 newNbBoxes, T* boxes)
{
T* newBoxes = reinterpret_cast<T*>(MBP_ALLOC(sizeof(T)*newNbBoxes));
if(oldNbBoxes)
PxMemCopy(newBoxes, boxes, oldNbBoxes*sizeof(T));
MBP_FREE(boxes);
return newBoxes;
}
class Boxes
{
public:
Boxes();
~Boxes();
PX_FORCE_INLINE void init(const Boxes& boxes){ mSize = boxes.mSize; mCapacity = boxes.mCapacity; }
PX_FORCE_INLINE PxU32 getSize() const { return mSize; }
PX_FORCE_INLINE PxU32 getCapacity() const { return mCapacity; }
PX_FORCE_INLINE bool isFull() const { return mSize==mCapacity; }
PX_FORCE_INLINE void reset() { mSize = mCapacity = 0; }
PX_FORCE_INLINE PxU32 popBack() { return --mSize; }
// protected:
PxU32 mSize;
PxU32 mCapacity;
};
Boxes::Boxes() :
mSize (0),
mCapacity (0)
{
}
Boxes::~Boxes()
{
reset();
}
class StraightBoxes : public Boxes
{
public:
StraightBoxes();
~StraightBoxes();
void init(PxU32 size, PxU32 capacity, SIMD_AABB4* boxes);
void reset();
PxU32 resize();
PxU32 resize(PxU32 incoming);
bool allocate(PxU32 nb);
PX_FORCE_INLINE const SIMD_AABB4* getBoxes() const { return mBoxes; }
PX_FORCE_INLINE SIMD_AABB4* getBoxes() { return mBoxes; }
PX_FORCE_INLINE void setBounds(PxU32 index, const SIMD_AABB4& box)
{
PX_ASSERT(index<mSize);
mBoxes[index] = box;
}
PX_FORCE_INLINE PxU32 pushBack(const SIMD_AABB4& box)
{
const PxU32 index = mSize++;
setBounds(index, box);
return index;
}
private:
SIMD_AABB4* mBoxes;
};
StraightBoxes::StraightBoxes() :
mBoxes (NULL)
{
}
StraightBoxes::~StraightBoxes()
{
reset();
}
void StraightBoxes::reset()
{
PX_DELETE_ARRAY(mBoxes);
Boxes::reset();
}
void StraightBoxes::init(PxU32 size, PxU32 capacity, SIMD_AABB4* boxes)
{
reset();
mSize = size;
mCapacity = capacity;
mBoxes = boxes;
}
PxU32 StraightBoxes::resize()
{
const PxU32 capacity = mCapacity;
const PxU32 size = mSize;
// const PxU32 newCapacity = capacity ? capacity + DEFAULT_NB_ENTRIES : DEFAULT_NB_ENTRIES;
// const PxU32 newCapacity = capacity ? capacity*2 : DEFAULT_NB_ENTRIES;
const PxU32 newCapacity = capacity ? capacity*2 : DEFAULT_NB_ENTRIES;
// PT: we allocate one extra box for safe SIMD loads
mBoxes = resizeBoxesT(size, newCapacity+1, mBoxes);
mCapacity = newCapacity;
return newCapacity;
}
PxU32 StraightBoxes::resize(PxU32 incoming)
{
const PxU32 capacity = mCapacity;
const PxU32 size = mSize;
const PxU32 minCapacity = size + incoming;
if(minCapacity<capacity)
return capacity;
PxU32 newCapacity = capacity ? capacity*2 : DEFAULT_NB_ENTRIES;
if(newCapacity<minCapacity)
newCapacity=minCapacity;
// PT: we allocate one extra box for safe SIMD loads
mBoxes = resizeBoxesT(size, newCapacity+1, mBoxes);
mCapacity = newCapacity;
return newCapacity;
}
bool StraightBoxes::allocate(PxU32 nb)
{
if(nb<=mSize)
return false;
PX_DELETE_ARRAY(mBoxes);
// PT: we allocate NB_SENTINELS more boxes than necessary here so we don't need to allocate one more for SIMD-load safety
mBoxes = PX_NEW(SIMD_AABB4)[nb+NB_SENTINELS];
mSize = mCapacity = nb;
return true;
}
class SplitBoxes : public Boxes
{
public:
SplitBoxes();
~SplitBoxes();
void init(PxU32 size, PxU32 capacity, SIMD_AABB_X4* boxes_X, SIMD_AABB_YZ4* boxes_YZ);
void init(const SplitBoxes& boxes);
void reset(bool freeMemory = true);
PxU32 resize();
PxU32 resize(PxU32 incoming);
bool allocate(PxU32 nb);
PX_FORCE_INLINE const SIMD_AABB_X4* getBoxes_X() const { return mBoxes_X; }
PX_FORCE_INLINE SIMD_AABB_X4* getBoxes_X() { return mBoxes_X; }
PX_FORCE_INLINE const SIMD_AABB_YZ4* getBoxes_YZ() const { return mBoxes_YZ; }
PX_FORCE_INLINE SIMD_AABB_YZ4* getBoxes_YZ() { return mBoxes_YZ; }
PX_FORCE_INLINE void setBounds(PxU32 index, const PxVec4& min, const PxVec4& max)
{
PX_ASSERT(index<mSize);
mBoxes_X[index].initFromPxVec4(min, max);
mBoxes_YZ[index].initFromPxVec4(min, max);
}
PX_FORCE_INLINE void setBounds(PxU32 index, const SIMD_AABB4& box)
{
PX_ASSERT(index<mSize);
mBoxes_X[index].initFrom(box);
mBoxes_YZ[index].initFrom(box);
}
PX_FORCE_INLINE PxU32 pushBack(const SIMD_AABB4& box)
{
const PxU32 index = mSize++;
setBounds(index, box);
return index;
}
private:
SIMD_AABB_X4* mBoxes_X;
SIMD_AABB_YZ4* mBoxes_YZ;
};
SplitBoxes::SplitBoxes() :
mBoxes_X (NULL),
mBoxes_YZ (NULL)
{
}
SplitBoxes::~SplitBoxes()
{
reset();
}
void SplitBoxes::reset(bool freeMemory)
{
if(freeMemory)
{
MBP_FREE(mBoxes_YZ);
MBP_FREE(mBoxes_X);
}
mBoxes_X = NULL;
mBoxes_YZ = NULL;
Boxes::reset();
}
void SplitBoxes::init(PxU32 size, PxU32 capacity, SIMD_AABB_X4* boxes_X, SIMD_AABB_YZ4* boxes_YZ)
{
reset();
mSize = size;
mCapacity = capacity;
mBoxes_X = boxes_X;
mBoxes_YZ = boxes_YZ;
}
void SplitBoxes::init(const SplitBoxes& boxes)
{
reset();
Boxes::init(boxes);
mBoxes_X = const_cast<SIMD_AABB_X4*>(boxes.getBoxes_X());
mBoxes_YZ = const_cast<SIMD_AABB_YZ4*>(boxes.getBoxes_YZ());
}
PxU32 SplitBoxes::resize()
{
const PxU32 capacity = mCapacity;
const PxU32 size = mSize;
// const PxU32 newCapacity = capacity ? capacity + DEFAULT_NB_ENTRIES : DEFAULT_NB_ENTRIES;
// const PxU32 newCapacity = capacity ? capacity*2 : DEFAULT_NB_ENTRIES;
const PxU32 newCapacity = capacity ? capacity*2 : DEFAULT_NB_ENTRIES;
mBoxes_X = resizeBoxesT(size, newCapacity, mBoxes_X);
mBoxes_YZ = resizeBoxesT(size, newCapacity, mBoxes_YZ);
mCapacity = newCapacity;
return newCapacity;
}
PxU32 SplitBoxes::resize(PxU32 incoming)
{
const PxU32 capacity = mCapacity;
const PxU32 size = mSize;
const PxU32 minCapacity = size + incoming;
if(minCapacity<capacity)
return capacity;
PxU32 newCapacity = capacity ? capacity*2 : DEFAULT_NB_ENTRIES;
if(newCapacity<minCapacity)
newCapacity=minCapacity;
mBoxes_X = resizeBoxesT(size, newCapacity, mBoxes_X);
mBoxes_YZ = resizeBoxesT(size, newCapacity, mBoxes_YZ);
mCapacity = newCapacity;
return newCapacity;
}
bool SplitBoxes::allocate(PxU32 nb)
{
if(nb<=mSize)
return false;
MBP_FREE(mBoxes_YZ);
MBP_FREE(mBoxes_X);
mBoxes_X = reinterpret_cast<SIMD_AABB_X4*>(MBP_ALLOC(sizeof(SIMD_AABB_X4)*(nb+NB_SENTINELS)));
mBoxes_YZ = reinterpret_cast<SIMD_AABB_YZ4*>(MBP_ALLOC(sizeof(SIMD_AABB_YZ4)*nb));
PX_ASSERT(!(size_t(mBoxes_YZ) & 15));
mSize = mCapacity = nb;
return true;
}
typedef SplitBoxes StaticBoxes;
typedef SplitBoxes DynamicBoxes;
///////////////////////////////////////////////////////////////////////////////
struct ABP_Object : public PxUserAllocated
{
PX_FORCE_INLINE ABP_Object() : mIndex(INVALID_ID)
{
#if PX_DEBUG
mUpdated = false;
#endif
}
private:
PxU32 mIndex; // Out-to-in, maps user handle to internal array. mIndex indexes either the static or dynamic array.
// PT: the type won't be available for removed objects so we have to store it there. That uses 2 bits.
// Then the "data" will need one more bit for marking sleeping objects so that leaves 28bits for the actual index.
PX_FORCE_INLINE void setData(PxU32 index, FilterType::Enum type)
{
// mIndex = index;
index <<= 2;
index |= type;
mIndex = index;
}
public:
// PT: TODO: rename "index" to data everywhere
PX_FORCE_INLINE void setActiveIndex(PxU32 index, FilterType::Enum type)
{
const PxU32 boxData = (index+index);
setData(boxData, type);
}
PX_FORCE_INLINE void setSleepingIndex(PxU32 index, FilterType::Enum type)
{
const PxU32 boxData = (index+index)|1;
PX_ASSERT(getType()==type);
setData(boxData, type);
}
PX_FORCE_INLINE FilterType::Enum getType() const
{
return FilterType::Enum(mIndex&3);
}
PX_FORCE_INLINE PxU32 getData() const
{
return mIndex>>2;
}
PX_FORCE_INLINE void invalidateIndex()
{
mIndex = INVALID_ID;
}
PX_FORCE_INLINE bool isValid() const
{
return mIndex != INVALID_ID;
}
#if PX_DEBUG
bool mUpdated;
#endif
};
typedef ABP_Object ABPEntry;
///////////////////////////////////////////////////////////////////////////////
//#define BIT_ARRAY_STACK 512
static PX_FORCE_INLINE PxU32 bitsToDwords(PxU32 nbBits)
{
return (nbBits>>5) + ((nbBits&31) ? 1 : 0);
}
// Use that one instead of an array of bools. Takes less ram, nearly as fast [no bounds checkings and so on].
class BitArray
{
public:
BitArray();
BitArray(PxU32 nbBits);
~BitArray();
bool init(PxU32 nbBits);
void empty();
void resize(PxU32 nbBits);
PX_FORCE_INLINE void checkResize(PxU32 bitNumber)
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
resize(bitNumber);
}
PX_FORCE_INLINE void setBitChecked(PxU32 bitNumber)
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
resize(bitNumber);
mBits[index] |= 1<<(bitNumber&31);
}
PX_FORCE_INLINE void clearBitChecked(PxU32 bitNumber)
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
resize(bitNumber);
mBits[index] &= ~(1<<(bitNumber&31));
}
// Data management
PX_FORCE_INLINE void setBit(PxU32 bitNumber) { mBits[bitNumber>>5] |= 1<<(bitNumber&31); }
PX_FORCE_INLINE void clearBit(PxU32 bitNumber) { mBits[bitNumber>>5] &= ~(1<<(bitNumber&31)); }
PX_FORCE_INLINE void toggleBit(PxU32 bitNumber) { mBits[bitNumber>>5] ^= 1<<(bitNumber&31); }
PX_FORCE_INLINE void clearAll() { PxMemZero(mBits, mSize*4); }
PX_FORCE_INLINE void setAll() { PxMemSet(mBits, 0xff, mSize*4); }
// Data access
PX_FORCE_INLINE PxIntBool isSet(PxU32 bitNumber) const { return PxIntBool(mBits[bitNumber>>5] & (1<<(bitNumber&31))); }
PX_FORCE_INLINE PxIntBool isSetChecked(PxU32 bitNumber) const
{
const PxU32 index = bitNumber>>5;
if(index>=mSize)
return 0;
return PxIntBool(mBits[index] & (1<<(bitNumber&31)));
}
PX_FORCE_INLINE const PxU32* getBits() const { return mBits; }
PX_FORCE_INLINE PxU32 getSize() const { return mSize; }
protected:
PxU32* mBits; //!< Array of bits
PxU32 mSize; //!< Size of the array in dwords
#ifdef BIT_ARRAY_STACK
PxU32 mStack[BIT_ARRAY_STACK];
#endif
};
///////////////////////////////////////////////////////////////////////////////
BitArray::BitArray() : mBits(NULL), mSize(0)
{
}
BitArray::BitArray(PxU32 nbBits) : mBits(NULL), mSize(0)
{
init(nbBits);
}
BitArray::~BitArray()
{
empty();
}
void BitArray::empty()
{
#ifdef BIT_ARRAY_STACK
if(mBits!=mStack)
#endif
MBP_FREE(mBits);
mBits = NULL;
mSize = 0;
}
bool BitArray::init(PxU32 nbBits)
{
mSize = bitsToDwords(nbBits);
// Get ram for n bits
#ifdef BIT_ARRAY_STACK
if(mBits!=mStack)
#endif
MBP_FREE(mBits);
#ifdef BIT_ARRAY_STACK
if(mSize>BIT_ARRAY_STACK)
#endif
mBits = reinterpret_cast<PxU32*>(MBP_ALLOC(sizeof(PxU32)*mSize));
#ifdef BIT_ARRAY_STACK
else
mBits = mStack;
#endif
// Set all bits to 0
clearAll();
return true;
}
void BitArray::resize(PxU32 nbBits)
{
const PxU32 newSize = bitsToDwords(nbBits+128);
PxU32* newBits = NULL;
#ifdef BIT_ARRAY_STACK
if(newSize>BIT_ARRAY_STACK)
#endif
{
// Old buffer was stack or allocated, new buffer is allocated
newBits = reinterpret_cast<PxU32*>(MBP_ALLOC(sizeof(PxU32)*newSize));
if(mSize)
PxMemCopy(newBits, mBits, sizeof(PxU32)*mSize);
}
#ifdef BIT_ARRAY_STACK
else
{
newBits = mStack;
if(mSize>BIT_ARRAY_STACK)
{
// Old buffer was allocated, new buffer is stack => copy to stack, shrink
CopyMemory(newBits, mBits, sizeof(PxU32)*BIT_ARRAY_STACK);
}
else
{
// Old buffer was stack, new buffer is stack => keep working on the same stack buffer, nothing to do
}
}
#endif
const PxU32 remain = newSize - mSize;
if(remain)
PxMemZero(newBits + mSize, remain*sizeof(PxU32));
#ifdef BIT_ARRAY_STACK
if(mBits!=mStack)
#endif
MBP_FREE(mBits);
mBits = newBits;
mSize = newSize;
}
///////////////////////////////////////////////////////////////////////////////
static ABP_Index* resizeMapping(PxU32 oldNbBoxes, PxU32 newNbBoxes, ABP_Index* mapping)
{
ABP_Index* newMapping = reinterpret_cast<ABP_Index*>(MBP_ALLOC(sizeof(ABP_Index)*newNbBoxes));
if(oldNbBoxes)
PxMemCopy(newMapping, mapping, oldNbBoxes*sizeof(ABP_Index));
MBP_FREE(mapping);
return newMapping;
}
struct ABP_Object;
#ifdef ABP_MT
struct DelayedPair
{
PxU32 mID0;
PxU32 mID1;
PxU32 mHash;
};
#endif
class ABP_PairManager : public PairManagerData
{
public:
ABP_PairManager();
~ABP_PairManager();
InternalPair* addPair (PxU32 id0, PxU32 id1);
void computeCreatedDeletedPairs (PxArray<BroadPhasePair>& createdPairs, PxArray<BroadPhasePair>& deletedPairs, const BitArray& updated, const BitArray& removed);
#ifdef ABP_MT
void addDelayedPair (PxArray<DelayedPair>& delayedPairs, const ABP_Index* mInToOut0, const ABP_Index* mInToOut1, PxU32 index0, PxU32 index1) const;
void addDelayedPairs (const PxArray<DelayedPair>& delayedPairs);
void addDelayedPairs2(PxArray<BroadPhasePair>& createdPairs, const PxArray<DelayedPair>& delayedPairs);
void resizeForNewPairs(PxU32 nbDelayedPairs);
#endif
const Bp::FilterGroup::Enum* mGroups;
const ABP_Index* mInToOut0;
const ABP_Index* mInToOut1;
const bool* mLUT;
};
///////////////////////////////////////////////////////////////////////////
struct ABP_SharedData
{
PX_FORCE_INLINE ABP_SharedData() :
mABP_Objects (NULL),
mABP_Objects_Capacity (0)
{
}
void resize(BpHandle userID);
PX_FORCE_INLINE void checkResize(PxU32 maxID)
{
if(mABP_Objects_Capacity<maxID+1)
resize(maxID);
}
ABP_Object* mABP_Objects;
PxU32 mABP_Objects_Capacity;
BitArray mUpdatedObjects; // Indexed by ABP_ObjectIndex
BitArray mRemovedObjects; // Indexed by ABP_ObjectIndex
};
void ABP_SharedData::resize(BpHandle userID)
{
const PxU32 oldCapacity = mABP_Objects_Capacity;
PxU32 newCapacity = mABP_Objects_Capacity ? mABP_Objects_Capacity*2 : 256;
if(newCapacity<userID+1)
newCapacity = userID+1;
ABP_Object* newObjects = PX_NEW(ABP_Object)[newCapacity];
if(mABP_Objects)
PxMemCopy(newObjects, mABP_Objects, oldCapacity*sizeof(ABP_Object));
#if PX_DEBUG
for(PxU32 i=oldCapacity;i<newCapacity;i++)
newObjects[i].mUpdated = false;
#endif
PX_DELETE_ARRAY(mABP_Objects);
mABP_Objects = newObjects;
mABP_Objects_Capacity = newCapacity;
}
class BoxManager
{
public:
BoxManager(FilterType::Enum type);
~BoxManager();
void reset();
void setSourceData(const PxBounds3* bounds, const float* distances)
{
mAABBManagerBounds = bounds;
mAABBManagerDistances = distances;
}
void addObjects(const BpHandle* PX_RESTRICT userIDs, PxU32 nb, ABP_SharedData* PX_RESTRICT sharedData);
void removeObject(ABPEntry& object, BpHandle userID);
void updateObject(ABPEntry& object, BpHandle userID);
void prepareData(RadixSortBuffered& rs, ABP_Object* PX_RESTRICT objects, PxU32 objectsCapacity, ABP_MM& memoryManager, PxU64 contextID);
// PX_FORCE_INLINE PxU32 isThereWorkToDo() const { return mNbUpdated; }
PX_FORCE_INLINE bool isThereWorkToDo() const { return mNbUpdated || mNbRemovedSleeping; } // PT: temp & test, maybe we do that differently in the end
PX_FORCE_INLINE PxU32 getNbUpdatedBoxes() const { return mNbUpdated; }
PX_FORCE_INLINE PxU32 getNbNonUpdatedBoxes() const { return mNbSleeping; }
PX_FORCE_INLINE const DynamicBoxes& getUpdatedBoxes() const { return mUpdatedBoxes; }
PX_FORCE_INLINE const DynamicBoxes& getSleepingBoxes() const { return mSleepingBoxes; }
PX_FORCE_INLINE const ABP_Index* getRemap_Updated() const { return mInToOut_Updated; }
PX_FORCE_INLINE const ABP_Index* getRemap_Sleeping() const { return mInToOut_Sleeping; }
#ifdef USE_ABP_BUCKETS
PX_FORCE_INLINE const PxBounds3& getUpdatedBounds() const { return mUpdatedBounds; }
#endif
private:
FilterType::Enum mType;
// PT: refs to source data (not owned). Currently separate arrays, ideally should be merged.
const PxBounds3* mAABBManagerBounds;
const float* mAABBManagerDistances;
// New & updated objects
#ifdef USE_ABP_BUCKETS
PxBounds3 mUpdatedBounds; // Bounds around updated dynamic objects, computed in prepareData().
#endif
ABP_Index* mInToOut_Updated; // Maps boxes to mABP_Objects
PxU32 mNbUpdated;
PxU32 mMaxNbUpdated;
DynamicBoxes mUpdatedBoxes;
// Sleeping objects
ABP_Index* mInToOut_Sleeping; // Maps boxes to mABP_Objects
PxU32 mNbSleeping;
DynamicBoxes mSleepingBoxes;
// Removed sleeping
PxU32 mNbRemovedSleeping;
void purgeRemovedFromSleeping(ABP_Object* PX_RESTRICT objects, PxU32 objectsCapacity);
};
BoxManager::BoxManager(FilterType::Enum type) :
mType (type),
mAABBManagerBounds (NULL),
mAABBManagerDistances (NULL),
mInToOut_Updated (NULL),
mNbUpdated (0),
mMaxNbUpdated (0),
mInToOut_Sleeping (NULL),
mNbSleeping (0),
mNbRemovedSleeping (0)
{
}
BoxManager::~BoxManager()
{
reset();
}
void BoxManager::reset()
{
mMaxNbUpdated = mNbUpdated = mNbSleeping = 0;
PX_FREE(mInToOut_Updated);
PX_FREE(mInToOut_Sleeping);
mUpdatedBoxes.reset();
mSleepingBoxes.reset();
}
static PX_FORCE_INLINE PxU32 isNewOrUpdated(PxU32 data)
{
return data & PX_SIGN_BITMASK;
}
static PX_FORCE_INLINE PxU32 markAsNewOrUpdated(PxU32 data)
{
return data | PX_SIGN_BITMASK;
}
static PX_FORCE_INLINE PxU32 removeNewOrUpdatedMark(PxU32 data)
{
return data & ~PX_SIGN_BITMASK;
}
// BpHandle = index in main/shared arrays like mAABBManagerBounds / mAABBManagerDistances
PX_COMPILE_TIME_ASSERT(sizeof(BpHandle)==sizeof(ABP_Index));
void BoxManager::addObjects(const BpHandle* PX_RESTRICT userIDs, PxU32 nb, ABP_SharedData* PX_RESTRICT sharedData)
{
// PT: we're called for each batch.
// PT: TODO: fix the BpHandle/ABP_Index mix
const PxU32 currentSize = mNbUpdated;
const PxU32 currentCapacity = mMaxNbUpdated;
const PxU32 newSize = currentSize + nb;
ABP_Index* remap;
if(newSize>currentCapacity)
{
const PxU32 minCapacity = PxMax(newSize, 1024u);
const PxU32 newCapacity = PxMax(minCapacity, currentCapacity*2);
PX_ASSERT(newCapacity>=newSize);
mMaxNbUpdated = newCapacity;
remap = resizeMapping(currentSize, newCapacity, mInToOut_Updated);
}
else
{
remap = mInToOut_Updated;
}
mInToOut_Updated = remap;
mNbUpdated = newSize;
// PT: we only copy the new handles for now. The bounds will be computed later in "prepareData".
// PT: TODO: do we even need to copy them? Can't we just reuse the source ptr directly?
{
PX_ASSERT(currentSize+nb<=mMaxNbUpdated);
remap += currentSize;
PxU32 nbToGo = nb;
while(nbToGo--)
{
const BpHandle userID = *userIDs++;
PX_ASSERT(!isNewOrUpdated(userID));
*remap++ = markAsNewOrUpdated(userID);
if(sharedData)
sharedData->mUpdatedObjects.setBit(userID);
}
}
}
// PT: TODO: inline this again
void BoxManager::removeObject(ABPEntry& object, BpHandle userID)
{
PX_UNUSED(userID);
const PxU32 boxData = object.getData();
const PxU32 boxIndex = boxData>>1;
if(boxData&1)
{
// Sleeping object.
PX_ASSERT(boxIndex<mNbSleeping);
PX_ASSERT(mInToOut_Sleeping[boxIndex]==userID);
PX_ASSERT(mInToOut_Sleeping[boxIndex] != INVALID_ID); // PT: can that happen if we update and remove an object in the same frame or does the AABB take care of it?
mInToOut_Sleeping[boxIndex] = INVALID_ID;
mNbRemovedSleeping++;
PX_ASSERT(mNbRemovedSleeping<=mNbSleeping);
}
else
{
// PT: remove active object, i.e. one that was previously in "updated" arrays.
PX_ASSERT(boxIndex<mNbUpdated);
PX_ASSERT(boxIndex<mMaxNbUpdated);
PX_ASSERT(mInToOut_Updated[boxIndex]==userID);
PX_ASSERT(mInToOut_Updated[boxIndex] != INVALID_ID);
// PT: TODO: do we need this at all? We could use 'userID' to access the removed bitmap...
mInToOut_Updated[boxIndex] = INVALID_ID;
}
}
// PT: TODO: inline this again
void BoxManager::updateObject(ABPEntry& object, BpHandle userID)
{
PX_UNUSED(userID);
const PxU32 boxData = object.getData();
const PxU32 boxIndex = boxData>>1;
if(boxData&1)
{
// PT: benchmark for this codepath: MBP.UpdateSleeping
// Sleeping object. We must reactivate it, i.e:
// - remove it from the array of sleeping objects
// - add it to the array of active/updated objects
// First we remove:
{
PX_ASSERT(boxIndex<mNbSleeping);
PX_ASSERT(mInToOut_Sleeping[boxIndex]==userID);
PX_ASSERT(mInToOut_Sleeping[boxIndex] != INVALID_ID);
mInToOut_Sleeping[boxIndex] = INVALID_ID;
mNbRemovedSleeping++;
PX_ASSERT(mNbRemovedSleeping<=mNbSleeping);
}
// Then we add
// PT: TODO: revisit / improve this maybe
addObjects(&userID, 1, NULL); // Don't pass sharedData because the bitmap has already been updated by the calling code
}
else
{
// Active object, i.e. it was updated in previous frame and it's already in mInToOut_Updated array
PX_ASSERT(boxIndex<mNbUpdated);
PX_ASSERT(boxIndex<mMaxNbUpdated);
PX_ASSERT(mInToOut_Updated[boxIndex]==userID);
mInToOut_Updated[boxIndex] = markAsNewOrUpdated(mInToOut_Updated[boxIndex]);
}
}
#if PX_DEBUG
static PX_FORCE_INLINE void computeMBPBounds_Check(SIMD_AABB4& aabb, const PxBounds3* PX_RESTRICT boundsXYZ, const PxReal* PX_RESTRICT contactDistances, const BpHandle index)
{
const PxBounds3& b = boundsXYZ[index];
const Vec4V contactDistanceV = V4Load(contactDistances[index]);
const Vec4V inflatedMinV = V4Sub(V4LoadU(&b.minimum.x), contactDistanceV);
const Vec4V inflatedMaxV = V4Add(V4LoadU(&b.maximum.x), contactDistanceV); // PT: this one is safe because we allocated one more box in the array (in BoundsArray::initEntry)
PX_ALIGN(16, PxVec4) boxMin;
PX_ALIGN(16, PxVec4) boxMax;
V4StoreA(inflatedMinV, &boxMin.x);
V4StoreA(inflatedMaxV, &boxMax.x);
aabb.mMinX = boxMin[0];
aabb.mMinY = boxMin[1];
aabb.mMinZ = boxMin[2];
aabb.mMaxX = boxMax[0];
aabb.mMaxY = boxMax[1];
aabb.mMaxZ = boxMax[2];
}
#endif
static PX_FORCE_INLINE void initSentinels(SIMD_AABB_X4* PX_RESTRICT boxesX, const PxU32 size)
{
for(PxU32 i=0;i<NB_SENTINELS;i++)
boxesX[size+i].initSentinel();
}
void BoxManager::purgeRemovedFromSleeping(ABP_Object* PX_RESTRICT objects, PxU32 objectsCapacity)
{
CHECKPOINT("purgeRemovedFromSleeping\n");
PX_UNUSED(objectsCapacity);
PX_ASSERT(mNbRemovedSleeping);
PX_ASSERT(mNbSleeping);
// PT: TODO: do we need to allocate separate buffers here?
// PT: we reach this codepath when:
// - no object has been added or updated
// - sleeping objects have been removed
// So we have to purge the removed objects from the sleeping array. We cannot entirely ignore the removals since we compute collisions
// between sleeping arrays and active arrays for bipartite cases. So we either have to remove the invalid entries immediately, or make
// sure they don't report collisions. We could ignore collisions when the remapped ID is "INVALID_ID" but that would be an additional
// test for each potential pair, i.e. it's a constant cost. We cannot tweak the removed bounding boxes (e.g. mark them as empty) because
// they are sorted, and the tweak would break the sorting and the collision loop. Keeping all removed objects in the array also means
// there is more data to parse all the time, i.e. there is a performance cost again. So for now we just remove all deleted entries here.
// ==> also tweaking the sleeping boxes might break the "merge sleeping" array code
PX_ASSERT(mNbRemovedSleeping<=mNbSleeping);
if(mNbRemovedSleeping==mNbSleeping)
{
// PT: remove everything
mSleepingBoxes.reset();
PX_FREE(mInToOut_Sleeping);
mNbSleeping = mNbRemovedSleeping = 0;
return;
}
const PxU32 expectedTotal = mNbSleeping - mNbRemovedSleeping;
PxU32 nbRemovedFound = 0;
PxU32 nbSleepingLeft = 0;
const PxU32 sleepCapacity = mSleepingBoxes.getCapacity();
if(expectedTotal>=sleepCapacity/2)
{
// PT: remove holes, keep same data buffers
SIMD_AABB_X4* boxesX = mSleepingBoxes.getBoxes_X();
SIMD_AABB_YZ4* boxesYZ = mSleepingBoxes.getBoxes_YZ();
ABP_Index* remap = mInToOut_Sleeping;
for(PxU32 i=0;i<mNbSleeping;i++)
{
const PxU32 boxIndex = remap[i];
if(boxIndex==INVALID_ID)
{
nbRemovedFound++;
}
else
{
PX_ASSERT(nbSleepingLeft<expectedTotal);
if(i!=nbSleepingLeft)
{
remap[nbSleepingLeft] = boxIndex;
boxesX[nbSleepingLeft] = boxesX[i];
boxesYZ[nbSleepingLeft] = boxesYZ[i];
}
{
PX_ASSERT(boxIndex<objectsCapacity);
objects[boxIndex].setSleepingIndex(nbSleepingLeft, mType);
}
nbSleepingLeft++;
}
}
PX_ASSERT(nbSleepingLeft==expectedTotal);
PX_ASSERT(nbSleepingLeft+nbRemovedFound==mNbSleeping);
initSentinels(boxesX, expectedTotal);
mSleepingBoxes.mSize = expectedTotal;
}
else
{
// PT: remove holes, get fresh memory buffers
SIMD_AABB_X4* dstBoxesX = reinterpret_cast<SIMD_AABB_X4*>(MBP_ALLOC(sizeof(SIMD_AABB_X4)*(expectedTotal+NB_SENTINELS)));
SIMD_AABB_YZ4* dstBoxesYZ = reinterpret_cast<SIMD_AABB_YZ4*>(MBP_ALLOC(sizeof(SIMD_AABB_YZ4)*(expectedTotal+NB_SENTINELS)));
initSentinels(dstBoxesX, expectedTotal);
BpHandle* PX_RESTRICT dstRemap = reinterpret_cast<BpHandle*>(PX_ALLOC(expectedTotal*sizeof(BpHandle), "tmp"));
const SIMD_AABB_X4* PX_RESTRICT srcDataX = mSleepingBoxes.getBoxes_X();
const SIMD_AABB_YZ4* PX_RESTRICT srcDataYZ = mSleepingBoxes.getBoxes_YZ();
const ABP_Index* PX_RESTRICT srcRemap = mInToOut_Sleeping;
for(PxU32 i=0;i<mNbSleeping;i++)
{
const PxU32 boxIndex = srcRemap[i];
if(boxIndex==INVALID_ID)
{
nbRemovedFound++;
}
else
{
PX_ASSERT(nbSleepingLeft<expectedTotal);
dstRemap[nbSleepingLeft] = boxIndex;
dstBoxesX[nbSleepingLeft] = srcDataX[i];
dstBoxesYZ[nbSleepingLeft] = srcDataYZ[i];
{
PX_ASSERT(boxIndex<objectsCapacity);
objects[boxIndex].setSleepingIndex(nbSleepingLeft, mType);
}
nbSleepingLeft++;
}
}
PX_ASSERT(nbSleepingLeft==expectedTotal);
PX_ASSERT(nbSleepingLeft+nbRemovedFound==mNbSleeping);
// PT: TODO: double check all this
mSleepingBoxes.init(expectedTotal, expectedTotal, dstBoxesX, dstBoxesYZ);
PX_FREE(mInToOut_Sleeping);
mInToOut_Sleeping = dstRemap;
}
mNbSleeping = expectedTotal;
mNbRemovedSleeping = 0;
}
static PX_FORCE_INLINE PosXType2 getNextCandidateSorted(PxU32 offsetSorted, const PxU32 nbSorted, const SIMD_AABB_X4* PX_RESTRICT sortedDataX, const PxU32* PX_RESTRICT sleepingIndices)
{
return offsetSorted<nbSorted ? sortedDataX[sleepingIndices[offsetSorted]].mMinX : SentinelValue2;
}
static PX_FORCE_INLINE PosXType2 getNextCandidateNonSorted(PxU32 offsetNonSorted, const PxU32 nbToSort, const SIMD_AABB_X4* PX_RESTRICT toSortDataX)
{
return offsetNonSorted<nbToSort ? toSortDataX[offsetNonSorted].mMinX : SentinelValue2;
}
PX_COMPILE_TIME_ASSERT(sizeof(BpHandle)==sizeof(float));
void BoxManager::prepareData(RadixSortBuffered& /*rs*/, ABP_Object* PX_RESTRICT objects, PxU32 objectsCapacity, ABP_MM& memoryManager, PxU64 contextID)
{
PX_UNUSED(contextID);
// PT: mNbUpdated = number of objects in the updated buffer, could have been updated this frame or previous frame
const PxU32 size = mNbUpdated;
if(!size)
{
if(mNbRemovedSleeping)
{
// PT: benchmark for this codepath: MBP.RemoveHalfSleeping
purgeRemovedFromSleeping(objects, objectsCapacity);
}
return;
}
PX_ASSERT(mAABBManagerBounds);
PX_ASSERT(mAABBManagerDistances);
PX_ASSERT(mInToOut_Updated);
// Prepare new/updated objects
const ABP_Index* PX_RESTRICT remap = mInToOut_Updated;
const PxBounds3* PX_RESTRICT bounds = mAABBManagerBounds;
const float* PX_RESTRICT distances = mAABBManagerDistances;
float* PX_RESTRICT keys = NULL;
// newOrUpdatedIDs: *userIDs* of objects that have been added or updated this frame.
// sleepingIndices: *indices* (not userIDs) of non-updated objects within mInToOut_Updated
PxU32* tempBuffer = NULL;
PxU32* newOrUpdatedIDs = tempBuffer;
PxU32* sleepingIndices = tempBuffer;
// PT: mNbUpdated / mInToOut_Updated contains:
// 1) objects added this frame (from addObject(s))
// 2) objects updated this frame (from updateObject(s))
// 3) objects updated the frame before, not updated this frame, i.e. they are now "sleeping"
// 4) objects updated the frame before, then removed (from removeObject(s))
//
// We split the current array into separate groups:
// - 1) & 2) go to "temp", count is "nbUpdated"
// - 3) go to "temp2", count is "nbSleeping"
// - 4) are filtered out. No special processing is needed because the updated data is always parsed/recreated here anyway.
// So if we don't actively add removed objects to the new buffers, they get removed as a side-effect.
PxU32 nbUpdated = 0; // PT: number of objects updated this frame
PxU32 nbSleeping = 0;
PxU32 nbRemoved = 0; // PT: number of removed objects that were previously located in the udpated array
// PT: TODO: could we do the work within mInToOut_Updated?
// - updated objects have invalidated bounds so we don't need to preserve their order
// - we need to preserve the order of sleeping objects to avoid re-sorting them
// - we cannot use MTF since it breaks the order
// - parse backward and move sleeping objects to the back? but then we might have to move the sleeping boxes at the same time
for(PxU32 i=0;i<size;i++)
{
PX_ASSERT(i<mMaxNbUpdated);
const PxU32 index = remap[i];
if(index==INVALID_ID)
{
nbRemoved++;
}
else
{
if(!tempBuffer)
{
tempBuffer = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(size*sizeof(PxU32)));
newOrUpdatedIDs = tempBuffer;
sleepingIndices = tempBuffer;
}
if(isNewOrUpdated(index))
{
// PT: new or updated object
if(!keys)
keys = reinterpret_cast<float*>(PX_ALLOC(size*sizeof(float), "tmp"));
// PT: in this version we compute the key on-the-fly, i.e. it will be computed twice overall. We could make this
// faster by merging bounds and distances inside the AABB manager.
const BpHandle userID = removeNewOrUpdatedMark(index);
keys[nbUpdated] = bounds[userID].minimum.x - distances[userID];
newOrUpdatedIDs[size - 1 - nbUpdated] = userID;
#if PX_DEBUG
SIMD_AABB4 aabb;
computeMBPBounds_Check(aabb, bounds, distances, userID);
PX_ASSERT(aabb.mMinX==keys[nbUpdated]);
#endif
nbUpdated++;
}
else
{
// PT: sleeping object
sleepingIndices[nbSleeping++] = i;
}
}
}
PX_ASSERT(nbRemoved + nbUpdated + nbSleeping == size);
// PT: we must process the sleeping objects first, because the bounds of new sleeping objects are located in the existing updated buffers.
// PT: TODO: *HOWEVER* we could sort things right now and then reuse the "keys" buffer?
if(nbSleeping)
{
// PT: must merge these guys to current sleeping array
// They should already be in sorted order and we should already have the boxes.
#if PX_DEBUG
const SIMD_AABB_YZ4* boxesYZ = mUpdatedBoxes.getBoxes_YZ();
float prevKey = -FLT_MAX;
for(PxU32 ii=0;ii<nbSleeping;ii++)
{
const PxU32 i = sleepingIndices[ii]; // PT: TODO: remove this indirection
const PxU32 index = remap[i];
PX_ASSERT(index!=INVALID_ID);
PX_ASSERT(!(index & PX_SIGN_BITMASK));
const BpHandle userID = index;
const float key = bounds[userID].minimum.x - distances[userID];
PX_ASSERT(key>=prevKey);
prevKey = key;
SIMD_AABB4 aabb;
computeMBPBounds_Check(aabb, bounds, distances, userID);
PX_ASSERT(aabb.mMinX==key);
#ifdef ABP_SIMD_OVERLAP
PX_ASSERT(boxesYZ[i].mMinY==-aabb.mMinY);
PX_ASSERT(boxesYZ[i].mMinZ==-aabb.mMinZ);
#else
PX_ASSERT(boxesYZ[i].mMinY==aabb.mMinY);
PX_ASSERT(boxesYZ[i].mMinZ==aabb.mMinZ);
#endif
PX_ASSERT(boxesYZ[i].mMaxY==aabb.mMaxY);
PX_ASSERT(boxesYZ[i].mMaxZ==aabb.mMaxZ);
}
#endif
if(mNbSleeping)
{
// PT: benchmark for this codepath: MBP.MergeSleeping
CHECKPOINT("Merging sleeping objects\n");
// PT: here, we need to merge two arrays of sleeping objects together:
// - the ones already contained inside mSleepingBoxes
// - the new sleeping objects currently contained in mUpdatedBoxes
// Both of them should already be sorted.
// PT: TODO: super subtle stuff going on there, to revisit
// PT: TODO: revisit names
PxU32 offsetSorted = 0;
const PxU32 nbSorted = nbSleeping;
const SIMD_AABB_X4* PX_RESTRICT sortedDataX = mUpdatedBoxes.getBoxes_X();
const SIMD_AABB_YZ4* PX_RESTRICT sortedDataYZ = mUpdatedBoxes.getBoxes_YZ();
const ABP_Index* PX_RESTRICT sortedRemap = mInToOut_Updated;
PxU32 offsetNonSorted = 0;
const PxU32 nbToSort = mNbSleeping;
const SIMD_AABB_X4* PX_RESTRICT toSortDataX = mSleepingBoxes.getBoxes_X();
const SIMD_AABB_YZ4* PX_RESTRICT toSortDataYZ = mSleepingBoxes.getBoxes_YZ();
const ABP_Index* PX_RESTRICT toSortRemap = mInToOut_Sleeping;
PX_ASSERT(mNbRemovedSleeping<=mNbSleeping);
#if PX_DEBUG
{
PxU32 nbRemovedFound=0;
for(PxU32 i=0;i<mNbSleeping;i++)
{
if(toSortRemap[i]==INVALID_ID)
nbRemovedFound++;
}
PX_ASSERT(nbRemovedFound==mNbRemovedSleeping);
}
#endif
PosXType2 nextCandidateNonSorted = getNextCandidateNonSorted(offsetNonSorted, nbToSort, toSortDataX);
PosXType2 nextCandidateSorted = getNextCandidateSorted(offsetSorted, nbSorted, sortedDataX, sleepingIndices);
const PxU32 nbTotal = nbSorted + nbToSort - mNbRemovedSleeping;
SIMD_AABB_X4* dstBoxesX = reinterpret_cast<SIMD_AABB_X4*>(MBP_ALLOC(sizeof(SIMD_AABB_X4)*(nbTotal+NB_SENTINELS)));
SIMD_AABB_YZ4* dstBoxesYZ = reinterpret_cast<SIMD_AABB_YZ4*>(MBP_ALLOC(sizeof(SIMD_AABB_YZ4)*(nbTotal+NB_SENTINELS)));
initSentinels(dstBoxesX, nbTotal);
BpHandle* PX_RESTRICT dstRemap = reinterpret_cast<BpHandle*>(PX_ALLOC(nbTotal*sizeof(BpHandle), "tmp"));
PxU32 i=0;
PxU32 nbRemovedFound=0;
PxU32 nbToGo = nbSorted + nbToSort;
while(nbToGo--)
{
PxU32 boxIndex;
{
if(nextCandidateNonSorted<nextCandidateSorted)
{
boxIndex = toSortRemap[offsetNonSorted];
if(boxIndex!=INVALID_ID)
{
dstRemap[i] = boxIndex;
dstBoxesX[i] = toSortDataX[offsetNonSorted];
dstBoxesYZ[i] = toSortDataYZ[offsetNonSorted];
}
else
nbRemovedFound++;
offsetNonSorted++;
nextCandidateNonSorted = getNextCandidateNonSorted(offsetNonSorted, nbToSort, toSortDataX);
}
else
{
const PxU32 j = sleepingIndices[offsetSorted];
PX_ASSERT(j<size);
boxIndex = sortedRemap[j];
PX_ASSERT(boxIndex!=INVALID_ID);
dstRemap[i] = boxIndex;
dstBoxesX[i] = sortedDataX[j];
dstBoxesYZ[i] = sortedDataYZ[j];
offsetSorted++;
nextCandidateSorted = getNextCandidateSorted(offsetSorted, nbSorted, sortedDataX, sleepingIndices);
}
}
if(boxIndex!=INVALID_ID)
{
PX_ASSERT(boxIndex<objectsCapacity);
objects[boxIndex].setSleepingIndex(i, mType);
i++;
}
}
PX_ASSERT(i==nbTotal);
PX_ASSERT(offsetSorted+offsetNonSorted==nbSorted+nbToSort);
#if PX_DEBUG
{
PosXType2 prevSorted = dstBoxesX[0].mMinX;
for(PxU32 i2=1;i2<nbTotal;i2++)
{
PosXType2 v = dstBoxesX[i2].mMinX;
PX_ASSERT(prevSorted<=v);
prevSorted = v;
}
}
#endif
// PT: TODO: double check all this
mSleepingBoxes.init(nbTotal, nbTotal, dstBoxesX, dstBoxesYZ);
PX_FREE(mInToOut_Sleeping);
mInToOut_Sleeping = dstRemap;
mNbSleeping = nbTotal;
mNbRemovedSleeping = 0;
}
else
{
// PT: benchmark for this codepath: MBP.ActiveToSleeping
CHECKPOINT("Active objects become sleeping objects\n");
// PT: TODO: optimize allocs
BpHandle* inToOut_Sleeping;
if(mSleepingBoxes.allocate(nbSleeping))
{
inToOut_Sleeping = reinterpret_cast<BpHandle*>(PX_ALLOC(nbSleeping*sizeof(BpHandle), "tmp"));
PX_FREE(mInToOut_Sleeping);
mInToOut_Sleeping = inToOut_Sleeping;
}
else
{
inToOut_Sleeping = mInToOut_Sleeping;
}
const SIMD_AABB_X4* srcBoxesX = mUpdatedBoxes.getBoxes_X();
const SIMD_AABB_YZ4* srcBoxesYZ = mUpdatedBoxes.getBoxes_YZ();
SIMD_AABB_X4* dstBoxesX = mSleepingBoxes.getBoxes_X();
SIMD_AABB_YZ4* dstBoxesYZ = mSleepingBoxes.getBoxes_YZ();
initSentinels(dstBoxesX, nbSleeping);
for(PxU32 ii=0;ii<nbSleeping;ii++)
{
const PxU32 i = sleepingIndices[ii]; // PT: TODO: remove this indirection
const PxU32 index = remap[i];
PX_ASSERT(index!=INVALID_ID);
inToOut_Sleeping[ii] = index;
dstBoxesX[ii] = srcBoxesX[i];
dstBoxesYZ[ii] = srcBoxesYZ[i];
{
PX_ASSERT(index<objectsCapacity);
objects[index].setSleepingIndex(ii, mType);
}
}
mNbSleeping = nbSleeping;
}
}
else
{
// PT: no sleeping objects in updated buffer
if(mNbSleeping)
{
if(mNbRemovedSleeping)
{
// PT: benchmark for this codepath: MBP.UpdateSleeping
purgeRemovedFromSleeping(objects, objectsCapacity);
}
}
else
{
PX_ASSERT(!mNbRemovedSleeping);
}
}
if(nbUpdated)
{
// PT: benchmark for this codepath: MBP.Update64KObjects
CHECKPOINT("Create updated objects\n");
// PT: we need to sort here because we reuse the "keys" buffer just afterwards
PxU32* ranks0 = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(sizeof(PxU32)*nbUpdated));
PxU32* ranks1 = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(sizeof(PxU32)*nbUpdated));
StackRadixSort(rs, ranks0, ranks1);
const PxU32* sorted;
{
PX_PROFILE_ZONE("Sort", contextID);
sorted = rs.Sort(keys, nbUpdated).GetRanks();
}
// PT:
// - shuffle the remap table, store it in sorted order (we can probably use the "recyclable" array here again)
// - compute bounds on-the-fly, store them in sorted order
// PT: TODO: the "keys" array can be much bigger than stricly necessary here
BpHandle* inToOut_Updated_Sorted;
if(mUpdatedBoxes.allocate(nbUpdated))
{
inToOut_Updated_Sorted = reinterpret_cast<BpHandle*>(keys);
PX_FREE(mInToOut_Updated);
mInToOut_Updated = inToOut_Updated_Sorted;
}
else
{
PX_FREE(keys);
inToOut_Updated_Sorted = mInToOut_Updated;
}
SIMD_AABB_X4* PX_RESTRICT dstBoxesX = mUpdatedBoxes.getBoxes_X();
initSentinels(dstBoxesX, nbUpdated);
#ifdef USE_ABP_BUCKETS
Vec4V minV = V4Load(FLT_MAX);
Vec4V maxV = V4Load(-FLT_MAX);
#endif
// PT: TODO: parallel? Everything indexed by i should be fine, things indexed by userID might have some false sharing
for(PxU32 i=0;i<nbUpdated;i++)
{
const PxU32 sortedIndex = *sorted++;
const BpHandle userID = newOrUpdatedIDs[size - 1 - sortedIndex];
PX_ASSERT(i<size);
inToOut_Updated_Sorted[i] = userID;
{
PX_ASSERT(userID<objectsCapacity);
objects[userID].setActiveIndex(i, mType);
#if PX_DEBUG
objects[userID].mUpdated = false;
#endif
}
// PT: TODO: refactor with computeMBPBounds?
{
const PxBounds3& b = bounds[userID];
const Vec4V contactDistanceV = V4Load(distances[userID]);
const Vec4V inflatedMinV = V4Sub(V4LoadU(&b.minimum.x), contactDistanceV);
const Vec4V inflatedMaxV = V4Add(V4LoadU(&b.maximum.x), contactDistanceV); // PT: this one is safe because we allocated one more box in the array (in BoundsArray::initEntry)
#ifdef USE_ABP_BUCKETS
minV = V4Min(minV, inflatedMinV);
maxV = V4Max(maxV, inflatedMaxV);
#endif
// PT: TODO better
PX_ALIGN(16, PxVec4) boxMin;
PX_ALIGN(16, PxVec4) boxMax;
V4StoreA(inflatedMinV, &boxMin.x);
V4StoreA(inflatedMaxV, &boxMax.x);
mUpdatedBoxes.setBounds(i, boxMin, boxMax);
}
}
#ifdef USE_ABP_BUCKETS
StoreBounds(mUpdatedBounds, minV, maxV)
#endif
#ifndef TEST_PERSISTENT_MEMORY
memoryManager.frameFree(ranks1);
memoryManager.frameFree(ranks0);
#endif
}
else
{
// PT: benchmark for this codepath: MBP.MergeSleeping / MBP.Remove64KObjects
CHECKPOINT("Free updated objects\n");
PX_FREE(keys);
mUpdatedBoxes.reset();
PX_FREE(mInToOut_Updated);
}
mNbUpdated = mMaxNbUpdated = nbUpdated;
if(tempBuffer)
memoryManager.frameFree(tempBuffer);
}
#ifdef ABP_MT
namespace
{
struct PairManagerMT
{
const ABP_PairManager* mSharedPM;
PxArray<DelayedPair> mDelayedPairs;
const ABP_Index* mInToOut0;
const ABP_Index* mInToOut1;
//char mBuffer[256];
};
}
static PX_FORCE_INLINE void outputPair(PairManagerMT& pairManager, PxU32 index0, PxU32 index1)
{
pairManager.mSharedPM->addDelayedPair(pairManager.mDelayedPairs, pairManager.mInToOut0, pairManager.mInToOut1, index0, index1);
}
#endif
#ifdef ABP_MT2
#define NB_BIP_TASKS 15
enum ABP_TaskID
{
ABP_TASK_0,
ABP_TASK_1,
};
class ABP_InternalTask : public PxLightCpuTask
{
public:
ABP_InternalTask(ABP_TaskID id) : mBP(NULL), mID(id) {}
virtual const char* getName() const PX_OVERRIDE
{
return "ABP_InternalTask";
}
virtual void run() PX_OVERRIDE;
BroadPhaseABP* mBP;
ABP_TaskID mID;
};
class ABP_CompleteBoxPruningStartTask;
class ABP_CompleteBoxPruningTask : public PxLightCpuTask
{
public:
ABP_CompleteBoxPruningTask() :
mStartTask(NULL),
mType(0),
mID(0)
{
}
virtual const char* getName() const PX_OVERRIDE
{
return "ABP_CompleteBoxPruningTask";
}
virtual void run() PX_OVERRIDE;
ABP_CompleteBoxPruningStartTask* mStartTask;
PxU16 mType;
PxU16 mID;
PxU32 mCounter;
const SIMD_AABB_X4* mBoxListX;
const SIMD_AABB_YZ4* mBoxListYZ;
const PxU32* mRemap;
PxU32 mCounter4;
const SIMD_AABB_X4* mBoxListX4;
const SIMD_AABB_YZ4* mBoxListYZ4;
const PxU32* mRemap4;
PairManagerMT mPairs;
PX_FORCE_INLINE bool isThereWorkToDo() const
{
if(!mCounter)
return false;
if(mType)
return mCounter4!=0;
return true;
}
};
class ABP_CompleteBoxPruningEndTask : public PxLightCpuTask
{
public:
ABP_CompleteBoxPruningEndTask() : mStartTask(NULL) {}
virtual const char* getName() const PX_OVERRIDE
{
return "ABP_CompleteBoxPruningEndTask";
}
virtual void run() PX_OVERRIDE;
ABP_CompleteBoxPruningStartTask* mStartTask;
};
class ABP_CompleteBoxPruningStartTask : public PxLightCpuTask
{
public:
ABP_CompleteBoxPruningStartTask();
virtual const char* getName() const PX_OVERRIDE
{
return "ABP_CompleteBoxPruningStartTask";
}
void setup(
//ABP_MM& memoryManager,
const PxBounds3& updatedBounds,
ABP_PairManager* PX_RESTRICT pairManager,
PxU32 nb,
const SIMD_AABB_X4* PX_RESTRICT listX,
const SIMD_AABB_YZ4* PX_RESTRICT listYZ,
const ABP_Index* PX_RESTRICT inputRemap,
PxU64 contextID);
void addDelayedPairs();
void addDelayedPairs2(PxArray<BroadPhasePair>& createdPairs);
virtual void run() PX_OVERRIDE;
const SIMD_AABB_X4* mListX;
const SIMD_AABB_YZ4* mListYZ;
const ABP_Index* mInputRemap;
ABP_PairManager* mPairManager;
PxU32* mRemap;
SIMD_AABB_X4* mBoxListXBuffer;
SIMD_AABB_YZ4* mBoxListYZBuffer;
PxU32 mCounters[NB_BUCKETS];
SIMD_AABB_X4* mBoxListX[NB_BUCKETS];
SIMD_AABB_YZ4* mBoxListYZ[NB_BUCKETS];
PxU32* mRemapBase[NB_BUCKETS];
PxBounds3 mBounds;
PxU32 mNb;
ABP_CompleteBoxPruningTask mTasks[9];
ABP_CompleteBoxPruningEndTask mEndTask;
};
#endif
typedef BoxManager DynamicManager;
typedef BoxManager StaticManager;
class ABP : public PxUserAllocated
{
PX_NOCOPY(ABP)
public:
ABP(PxU64 contextID);
~ABP();
void preallocate(PxU32 nbObjects, PxU32 maxNbOverlaps);
void reset();
void freeBuffers();
void addStaticObjects(const BpHandle* userIDs, PxU32 nb, PxU32 maxID);
void addDynamicObjects(const BpHandle* userIDs, PxU32 nb, PxU32 maxID);
void addKinematicObjects(const BpHandle* userIDs, PxU32 nb, PxU32 maxID);
void removeObject(BpHandle userID);
void updateObject(BpHandle userID);
void findOverlaps(PxBaseTask* continuation, const Bp::FilterGroup::Enum* PX_RESTRICT groups, const bool* PX_RESTRICT lut);
PxU32 finalize(PxArray<BroadPhasePair>& createdPairs, PxArray<BroadPhasePair>& deletedPairs);
void shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances);
void setTransientData(const PxBounds3* bounds, const PxReal* contactDistance);
void Region_prepareOverlaps();
ABP_MM mMM;
BoxManager mSBM;
DynamicManager mDBM;
RadixSortBuffered mRS;
DynamicManager mKBM;
ABP_SharedData mShared;
ABP_PairManager mPairManager;
const PxU64 mContextID;
#ifdef ABP_MT2
ABP_InternalTask mTask0;
ABP_InternalTask mTask1;
ABP_CompleteBoxPruningStartTask mCompleteBoxPruningTask0;
ABP_CompleteBoxPruningStartTask mCompleteBoxPruningTask1;
ABP_CompleteBoxPruningTask mBipTasks[NB_BIP_TASKS];
void addDelayedPairs();
void addDelayedPairs2(PxArray<BroadPhasePair>& createdPairs);
#endif
};
#ifdef ABP_SIMD_OVERLAP
#define ABP_OVERLAP_TEST(x) SIMD_OVERLAP_TEST(x)
#else
#define ABP_OVERLAP_TEST(x) if(intersect2D(box0, x))
#endif
///////////////////////////////////////////////////////////////////////////////
ABP_PairManager::ABP_PairManager() :
mGroups (NULL),
mInToOut0 (NULL),
mInToOut1 (NULL),
mLUT (NULL)
{
}
///////////////////////////////////////////////////////////////////////////////
ABP_PairManager::~ABP_PairManager()
{
}
///////////////////////////////////////////////////////////////////////////////
InternalPair* ABP_PairManager::addPair(PxU32 index0, PxU32 index1)
{
const PxU32 id0 = mInToOut0[index0];
const PxU32 id1 = mInToOut1[index1];
PX_ASSERT(id0!=id1);
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
PX_ASSERT(mGroups);
{
if(!groupFiltering(mGroups[id0], mGroups[id1], mLUT))
return NULL;
}
return addPairInternal(id0, id1);
}
#ifdef ABP_MT
void ABP_PairManager::addDelayedPair(PxArray<DelayedPair>& delayedPairs, const ABP_Index* inToOut0, const ABP_Index* inToOut1, PxU32 index0, PxU32 index1) const
{
/*const*/ PxU32 id0 = inToOut0[index0];
/*const*/ PxU32 id1 = inToOut1[index1];
PX_ASSERT(id0!=id1);
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
PX_ASSERT(mGroups);
{
if(!groupFiltering(mGroups[id0], mGroups[id1], mLUT))
return;
}
if(1)
{
// Order the ids
sort(id0, id1);
const PxU32 fullHashValue = hash(id0, id1);
PxU32 hashValue = fullHashValue & mMask;
{
InternalPair* /*PX_RESTRICT*/ p = findPair(id0, id1, hashValue);
if(p)
{
p->setUpdated(); // ### PT: potential false sharing here
//return p; // Persistent pair
return; // Persistent pair
}
}
{
/*// This is a new pair
if(mNbActivePairs >= mHashSize)
hashValue = growPairs(fullHashValue);
const PxU32 pairIndex = mNbActivePairs++;
InternalPair* PX_RESTRICT p = &mActivePairs[pairIndex];
p->setNewPair(id0, id1);
mNext[pairIndex] = mHashTable[hashValue];
mHashTable[hashValue] = pairIndex;
return p;*/
DelayedPair* newPair = Cm::reserveContainerMemory(delayedPairs, 1);
newPair->mID0 = id0;
newPair->mID1 = id1;
newPair->mHash = fullHashValue;
}
}
}
void ABP_PairManager::resizeForNewPairs(PxU32 nbDelayedPairs)
{
PxU32 currentNbPairs = mNbActivePairs;
const PxU32 newNbPairs = currentNbPairs + nbDelayedPairs;
// Get more entries
mHashSize = PxNextPowerOfTwo(newNbPairs+1);
mMask = mHashSize-1;
//reallocPairs();
{
MBP_FREE(mHashTable);
mHashTable = reinterpret_cast<PxU32*>(MBP_ALLOC(mHashSize*sizeof(PxU32)));
//storeDwords(mHashTable, mHashSize, INVALID_ID);
if(0)
{
PxU32 nb = mHashSize;
PxU32* dest = mHashTable;
while(nb--)
*dest++ = INVALID_ID;
}
else
PxMemSet(mHashTable, 0xff, mHashSize*sizeof(PxU32));
// Get some bytes for new entries
InternalPair* newPairs = reinterpret_cast<InternalPair*>(MBP_ALLOC(mHashSize * sizeof(InternalPair))); PX_ASSERT(newPairs);
PxU32* newNext = reinterpret_cast<PxU32*>(MBP_ALLOC(mHashSize * sizeof(PxU32))); PX_ASSERT(newNext);
// Copy old data if needed
if(currentNbPairs)
PxMemCopy(newPairs, mActivePairs, currentNbPairs*sizeof(InternalPair));
// ### check it's actually needed... probably only for pairs whose hash value was cut by the and
// yeah, since hash(id0, id1) is a constant
// However it might not be needed to recompute them => only less efficient but still ok
for(PxU32 i=0;i<currentNbPairs;i++)
{
const PxU32 hashValue = hash(mActivePairs[i].getId0(), mActivePairs[i].getId1()) & mMask; // New hash value with new mask
newNext[i] = mHashTable[hashValue];
mHashTable[hashValue] = i;
}
// Delete old data
MBP_FREE(mNext);
MBP_FREE(mActivePairs);
// Assign new pointer
mActivePairs = newPairs;
mNext = newNext;
}
}
void ABP_PairManager::addDelayedPairs(const PxArray<DelayedPair>& delayedPairs)
{
if(0)
{
PxU32 nbDelayedPairs = delayedPairs.size();
const DelayedPair* pairs = delayedPairs.begin();
while(nbDelayedPairs--)
{
const DelayedPair& dp = *pairs++;
const PxU32 fullHashValue = dp.mHash;
PxU32 hashValue = fullHashValue & mMask;
if(mNbActivePairs >= mHashSize)
hashValue = growPairs(fullHashValue);
const PxU32 pairIndex = mNbActivePairs++;
InternalPair* PX_RESTRICT p = &mActivePairs[pairIndex];
p->setNewPair(dp.mID0, dp.mID1);
mNext[pairIndex] = mHashTable[hashValue];
mHashTable[hashValue] = pairIndex;
}
}
else
{
PxU32 nbDelayedPairs = delayedPairs.size();
PxU32 currentNbPairs = mNbActivePairs;
//resizeForNewPairs(nbDelayedPairs);
{
const PxU32 mask = mMask;
PxU32* PX_RESTRICT hashTable = mHashTable;
PxU32* PX_RESTRICT next = mNext;
InternalPair* PX_RESTRICT internalPairs = mActivePairs;
const DelayedPair* PX_RESTRICT pairs = delayedPairs.begin();
while(nbDelayedPairs--)
{
const DelayedPair& dp = *pairs++;
const PxU32 fullHashValue = dp.mHash;
const PxU32 hashValue = fullHashValue & mask;
PX_ASSERT(currentNbPairs < mHashSize);
const PxU32 pairIndex = currentNbPairs++;
internalPairs[pairIndex].setNewPair(dp.mID0, dp.mID1);
next[pairIndex] = hashTable[hashValue];
hashTable[hashValue] = pairIndex;
}
mNbActivePairs = currentNbPairs;
}
}
}
void ABP_PairManager::addDelayedPairs2(PxArray<BroadPhasePair>& createdPairs, const PxArray<DelayedPair>& delayedPairs)
{
PxU32 nbDelayedPairs = delayedPairs.size();
PxU32 currentNbPairs = mNbActivePairs;
//resizeForNewPairs(nbDelayedPairs);
BroadPhasePair* newPair = Cm::reserveContainerMemory(createdPairs, nbDelayedPairs);
{
const PxU32 mask = mMask;
PxU32* PX_RESTRICT hashTable = mHashTable;
PxU32* PX_RESTRICT next = mNext;
InternalPair* PX_RESTRICT internalPairs = mActivePairs;
const DelayedPair* PX_RESTRICT pairs = delayedPairs.begin();
while(nbDelayedPairs--)
{
const DelayedPair& dp = *pairs++;
const PxU32 fullHashValue = dp.mHash;
const PxU32 hashValue = fullHashValue & mask;
PX_ASSERT(currentNbPairs < mHashSize);
const PxU32 pairIndex = currentNbPairs++;
internalPairs[pairIndex].setNewPair2(dp.mID0, dp.mID1);
{
newPair->mVolA = dp.mID0;
newPair->mVolB = dp.mID1;
newPair++;
}
next[pairIndex] = hashTable[hashValue];
hashTable[hashValue] = pairIndex;
}
mNbActivePairs = currentNbPairs;
}
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if PX_INTEL_FAMILY
#define SIMD_OVERLAP_TEST_14a(box) _mm_movemask_ps(_mm_cmpngt_ps(b, _mm_load_ps(box)))==15
#define SIMD_OVERLAP_INIT_9c(box) \
__m128 b = _mm_shuffle_ps(_mm_load_ps(&box.mMinY), _mm_load_ps(&box.mMinY), 78);\
const float Coeff = -1.0f;\
b = _mm_mul_ps(b, _mm_load1_ps(&Coeff));
#define SIMD_OVERLAP_TEST_9c(box) \
const __m128 a = _mm_load_ps(&box.mMinY); \
const __m128 d = _mm_cmpge_ps(a, b); \
if(_mm_movemask_ps(d)==15)
#else
#define SIMD_OVERLAP_TEST_14a(box) BAllEqFFFF(V4IsGrtr(b, V4LoadA(box)))
#define SIMD_OVERLAP_INIT_9c(box) \
Vec4V b = V4PermZWXY(V4LoadA(&box.mMinY)); \
b = V4Mul(b, V4Load(-1.0f));
#define SIMD_OVERLAP_TEST_9c(box) \
const Vec4V a = V4LoadA(&box.mMinY); \
const Vec4V d = V4IsGrtrOrEq(a, b); \
if(BAllEqTTTT(d))
#endif
#ifdef ABP_SIMD_OVERLAP
#define SIMD_OVERLAP_PRELOAD_BOX0 SIMD_OVERLAP_INIT_9c(box0)
#define SIMD_OVERLAP_TEST(x) SIMD_OVERLAP_TEST_9c(x)
#else
#define SIMD_OVERLAP_PRELOAD_BOX0
#endif
#ifndef ABP_SIMD_OVERLAP
static PX_FORCE_INLINE int intersect2D(const SIMD_AABB_YZ4& a, const SIMD_AABB_YZ4& b)
{
/* if(
b.mMaxY < a.mMinY || a.mMaxY < b.mMinY
||
b.mMaxZ < a.mMinZ || a.mMaxZ < b.mMinZ
)
return 0;
return 1;*/
const bool b0 = b.mMaxY < a.mMinY;
const bool b1 = a.mMaxY < b.mMinY;
const bool b2 = b.mMaxZ < a.mMinZ;
const bool b3 = a.mMaxZ < b.mMinZ;
// const bool b4 = b0 || b1 || b2 || b3;
const bool b4 = b0 | b1 | b2 | b3;
return !b4;
}
#endif
static PX_FORCE_INLINE void outputPair(ABP_PairManager& pairManager, PxU32 index0, PxU32 index1)
{
pairManager.addPair(index0, index1);
}
template<const int codepath, class ABP_PairManagerT>
static void boxPruningKernel( PxU32 nb0, PxU32 nb1,
const SIMD_AABB_X4* PX_RESTRICT boxes0_X, const SIMD_AABB_X4* PX_RESTRICT boxes1_X,
const SIMD_AABB_YZ4* PX_RESTRICT boxes0_YZ, const SIMD_AABB_YZ4* PX_RESTRICT boxes1_YZ,
const ABP_Index* PX_RESTRICT inToOut0, const ABP_Index* PX_RESTRICT inToOut1,
ABP_PairManagerT* PX_RESTRICT pairManager)
{
pairManager->mInToOut0 = inToOut0;
pairManager->mInToOut1 = inToOut1;
PxU32 index0 = 0;
PxU32 runningIndex1 = 0;
while(runningIndex1<nb1 && index0<nb0)
{
const SIMD_AABB_X4& box0_X = boxes0_X[index0];
const PosXType2 maxLimit = box0_X.mMaxX;
const PosXType2 minLimit = box0_X.mMinX;
if(!codepath)
{
while(boxes1_X[runningIndex1].mMinX<minLimit)
runningIndex1++;
}
else
{
while(boxes1_X[runningIndex1].mMinX<=minLimit)
runningIndex1++;
}
const SIMD_AABB_YZ4& box0 = boxes0_YZ[index0];
SIMD_OVERLAP_PRELOAD_BOX0
if(gUseRegularBPKernel)
{
PxU32 index1 = runningIndex1;
while(boxes1_X[index1].mMinX<=maxLimit)
{
ABP_OVERLAP_TEST(boxes1_YZ[index1])
{
outputPair(*pairManager, index0, index1);
}
index1++;
}
}
else
{
PxU32 Offset = 0;
const char* const CurrentBoxListYZ = reinterpret_cast<const char*>(&boxes1_YZ[runningIndex1]);
const char* const CurrentBoxListX = reinterpret_cast<const char*>(&boxes1_X[runningIndex1]);
if(!gUnrollLoop)
{
while(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset)<=maxLimit)
{
const float* box = reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2);
#ifdef ABP_SIMD_OVERLAP
if(SIMD_OVERLAP_TEST_14a(box))
#else
if(intersect2D(box0, *reinterpret_cast<const SIMD_AABB_YZ4*>(box)))
#endif
{
const PxU32 Index1 = PxU32(CurrentBoxListX + Offset - reinterpret_cast<const char*>(boxes1_X))>>3;
outputPair(*pairManager, index0, Index1);
}
Offset += 8;
}
}
else
{
#define BIP_VERSION4
#ifdef BIP_VERSION4
#ifdef ABP_SIMD_OVERLAP
#define BLOCK4(x, label) {const float* box = reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2 + x*2); \
if(SIMD_OVERLAP_TEST_14a(box)) \
goto label; }
#else
#define BLOCK4(x, label) {const float* box = reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2 + x*2); \
if(intersect2D(box0, *reinterpret_cast<const SIMD_AABB_YZ4*>(box))) \
goto label; }
#endif
goto StartLoop4;
CODEALIGN16
FoundOverlap3:
Offset += 8;
CODEALIGN16
FoundOverlap2:
Offset += 8;
CODEALIGN16
FoundOverlap1:
Offset += 8;
CODEALIGN16
FoundOverlap0:
Offset += 8;
CODEALIGN16
FoundOverlap:
{
const PxU32 Index1 = PxU32(CurrentBoxListX + Offset - 8 - reinterpret_cast<const char*>(boxes1_X))>>3;
outputPair(*pairManager, index0, Index1);
}
CODEALIGN16
StartLoop4:
while(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset + 8*5)<=maxLimit)
{
BLOCK4(0, FoundOverlap0)
BLOCK4(8, FoundOverlap1)
BLOCK4(16, FoundOverlap2)
BLOCK4(24, FoundOverlap3)
Offset += 40;
BLOCK4(-8, FoundOverlap)
}
#undef BLOCK4
#endif
#ifdef ABP_SIMD_OVERLAP
#define BLOCK if(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset)<=maxLimit) \
{if(SIMD_OVERLAP_TEST_14a(reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2))) \
goto OverlapFound; \
Offset += 8;
#else
#define BLOCK if(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset)<=maxLimit) \
{if(intersect2D(box0, *reinterpret_cast<const SIMD_AABB_YZ4*>(CurrentBoxListYZ + Offset*2))) \
goto OverlapFound; \
Offset += 8;
#endif
goto LoopStart;
CODEALIGN16
OverlapFound:
{
const PxU32 Index1 = PxU32(CurrentBoxListX + Offset - reinterpret_cast<const char*>(boxes1_X))>>3;
outputPair(*pairManager, index0, Index1);
}
Offset += 8;
CODEALIGN16
LoopStart:
BLOCK
BLOCK
BLOCK
}
}
goto LoopStart;
}
#undef BLOCK
}
}
index0++;
}
}
template<class ABP_PairManagerT>
static /*PX_FORCE_INLINE*/ void doBipartiteBoxPruning_Leaf(
ABP_PairManagerT* PX_RESTRICT pairManager,
PxU32 nb0,
PxU32 nb1,
const SIMD_AABB_X4* PX_RESTRICT boxes0_X,
const SIMD_AABB_X4* PX_RESTRICT boxes1_X,
const SIMD_AABB_YZ4* PX_RESTRICT boxes0_YZ,
const SIMD_AABB_YZ4* PX_RESTRICT boxes1_YZ,
const ABP_Index* PX_RESTRICT remap0,
const ABP_Index* PX_RESTRICT remap1
)
{
PX_ASSERT(boxes0_X[nb0].isSentinel());
PX_ASSERT(boxes1_X[nb1].isSentinel());
boxPruningKernel<0>(nb0, nb1, boxes0_X, boxes1_X, boxes0_YZ, boxes1_YZ, remap0, remap1, pairManager);
boxPruningKernel<1>(nb1, nb0, boxes1_X, boxes0_X, boxes1_YZ, boxes0_YZ, remap1, remap0, pairManager);
}
template<class ABP_PairManagerT>
static PX_FORCE_INLINE void doBipartiteBoxPruning_Leaf(ABP_PairManagerT* PX_RESTRICT pairManager,
PxU32 nb0, PxU32 nb1, const SplitBoxes& boxes0, const SplitBoxes& boxes1, const ABP_Index* PX_RESTRICT remap0, const ABP_Index* PX_RESTRICT remap1)
{
doBipartiteBoxPruning_Leaf(pairManager, nb0, nb1, boxes0.getBoxes_X(), boxes1.getBoxes_X(), boxes0.getBoxes_YZ(), boxes1.getBoxes_YZ(), remap0, remap1);
}
template<class ABP_PairManagerT>
static void doCompleteBoxPruning_Leaf( ABP_PairManagerT* PX_RESTRICT pairManager, PxU32 nb,
const SIMD_AABB_X4* PX_RESTRICT boxes_X,
const SIMD_AABB_YZ4* PX_RESTRICT boxes_YZ,
const ABP_Index* PX_RESTRICT remap)
{
pairManager->mInToOut0 = remap;
pairManager->mInToOut1 = remap;
PxU32 index0 = 0;
PxU32 runningIndex = 0;
while(runningIndex<nb && index0<nb)
{
const SIMD_AABB_X4& box0_X = boxes_X[index0];
const PosXType2 maxLimit = box0_X.mMaxX;
const PosXType2 minLimit = box0_X.mMinX;
while(boxes_X[runningIndex++].mMinX<minLimit);
const SIMD_AABB_YZ4& box0 = boxes_YZ[index0];
SIMD_OVERLAP_PRELOAD_BOX0
if(gUseRegularBPKernel)
{
PxU32 index1 = runningIndex;
while(boxes_X[index1].mMinX<=maxLimit)
{
ABP_OVERLAP_TEST(boxes_YZ[index1])
{
outputPair(*pairManager, index0, index1);
}
index1++;
}
}
else
{
PxU32 Offset = 0;
const char* const CurrentBoxListYZ = reinterpret_cast<const char*>(&boxes_YZ[runningIndex]);
const char* const CurrentBoxListX = reinterpret_cast<const char*>(&boxes_X[runningIndex]);
if(!gUnrollLoop)
{
while(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset)<=maxLimit)
{
const float* box = reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2);
#ifdef ABP_SIMD_OVERLAP
if(SIMD_OVERLAP_TEST_14a(box))
#else
if(intersect2D(box0, *reinterpret_cast<const SIMD_AABB_YZ4*>(box)))
#endif
{
const PxU32 Index = PxU32(CurrentBoxListX + Offset - reinterpret_cast<const char*>(boxes_X))>>3;
outputPair(*pairManager, index0, Index);
}
Offset += 8;
}
}
else
{
#define VERSION4c
#ifdef VERSION4c
#define VERSION3 // Enable this as our safe loop
#ifdef ABP_SIMD_OVERLAP
#define BLOCK4(x, label) {const float* box = reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2 + x*2); \
if(SIMD_OVERLAP_TEST_14a(box)) \
goto label; }
#else
#define BLOCK4(x, label) {const SIMD_AABB_YZ4* box = reinterpret_cast<const SIMD_AABB_YZ4*>(CurrentBoxListYZ + Offset*2 + x*2); \
if(intersect2D(box0, *box)) \
goto label; }
#endif
goto StartLoop4;
CODEALIGN16
FoundOverlap3:
Offset += 8;
CODEALIGN16
FoundOverlap2:
Offset += 8;
CODEALIGN16
FoundOverlap1:
Offset += 8;
CODEALIGN16
FoundOverlap0:
Offset += 8;
CODEALIGN16
FoundOverlap:
{
const PxU32 Index = PxU32(CurrentBoxListX + Offset - 8 - reinterpret_cast<const char*>(boxes_X))>>3;
outputPair(*pairManager, index0, Index);
}
CODEALIGN16
StartLoop4:
while(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset + 8*5)<=maxLimit)
{
BLOCK4(0, FoundOverlap0)
BLOCK4(8, FoundOverlap1)
BLOCK4(16, FoundOverlap2)
BLOCK4(24, FoundOverlap3)
Offset += 40;
BLOCK4(-8, FoundOverlap)
}
#endif
#define VERSION3
#ifdef VERSION3
#ifdef ABP_SIMD_OVERLAP
#define BLOCK if(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset)<=maxLimit) \
{if(SIMD_OVERLAP_TEST_14a(reinterpret_cast<const float*>(CurrentBoxListYZ + Offset*2))) \
goto BeforeLoop; \
Offset += 8;
#else
#define BLOCK if(*reinterpret_cast<const PosXType2*>(CurrentBoxListX + Offset)<=maxLimit) \
{if(intersect2D(box0, *reinterpret_cast<const SIMD_AABB_YZ4*>(CurrentBoxListYZ + Offset*2))) \
goto BeforeLoop; \
Offset += 8;
#endif
goto StartLoop;
CODEALIGN16
BeforeLoop:
{
const PxU32 Index = PxU32(CurrentBoxListX + Offset - reinterpret_cast<const char*>(boxes_X))>>3;
outputPair(*pairManager, index0, Index);
Offset += 8;
}
CODEALIGN16
StartLoop:
BLOCK
BLOCK
BLOCK
BLOCK
BLOCK
}
}
}
}
goto StartLoop;
}
#endif
}
}
index0++;
}
}
#ifdef USE_ABP_BUCKETS
static const PxU8 gCodes[] = { 4, 4, 4, 255, 4, 3, 2, 255,
4, 1, 0, 255, 255, 255, 255, 255 };
static PX_FORCE_INLINE PxU8 classifyBoxNew(const SIMD_AABB_YZ4& boxYZ, const float limitY, const float limitZ)
{
#ifdef ABP_SIMD_OVERLAP
// PT: mins have been negated for SIMD tests
const bool upperPart = (-boxYZ.mMinZ) > limitZ;
const bool rightPart = (-boxYZ.mMinY) > limitY;
#else
const bool upperPart = boxYZ.mMinZ > limitZ;
const bool rightPart = boxYZ.mMinY > limitY;
#endif
const bool lowerPart = boxYZ.mMaxZ < limitZ;
const bool leftPart = boxYZ.mMaxY < limitY;
// Table-based box classification avoids many branches
const PxU32 Code = PxU32(rightPart)|(PxU32(leftPart)<<1)|(PxU32(upperPart)<<2)|(PxU32(lowerPart)<<3);
PX_ASSERT(gCodes[Code]!=255);
return gCodes[Code];
}
#ifdef RECURSE_LIMIT
static void CompleteBoxPruning_Recursive(
ABP_MM& memoryManager,
ABP_PairManager* PX_RESTRICT pairManager,
PxU32 nb,
const SIMD_AABB_X4* PX_RESTRICT listX,
const SIMD_AABB_YZ4* PX_RESTRICT listYZ,
const ABP_Index* PX_RESTRICT remap,
const ABPEntry* PX_RESTRICT objects)
{
// printf("CompleteBoxPruning_Recursive %d\n", nb);
if(!nb)
return;
/*__declspec(align(16))*/ float mergedMin[4];
/*__declspec(align(16))*/ float mergedMax[4];
{
//#ifdef SAFE_VERSION
Vec4V maxV = V4LoadA(&listYZ[0].mMinY);
for(PxU32 i=1;i<nb;i++)
maxV = V4Max(maxV, V4LoadA(&listYZ[i].mMinY));
PX_ALIGN(16, PxVec4) tmp;
V4StoreA(maxV, &tmp.x);
mergedMin[1] = -tmp.x;
mergedMin[2] = -tmp.y;
mergedMax[1] = tmp.z;
mergedMax[2] = tmp.w;
//#endif
}
const float limitY = (mergedMax[1] + mergedMin[1]) * 0.5f;
const float limitZ = (mergedMax[2] + mergedMin[2]) * 0.5f;
// PT: TODO: revisit allocs
SIMD_AABB_X4* BoxListXBuffer = reinterpret_cast<SIMD_AABB_X4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_X4)*(nb+NB_SENTINELS*NB_BUCKETS)));
SIMD_AABB_YZ4* BoxListYZBuffer = reinterpret_cast<SIMD_AABB_YZ4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_YZ4)*nb));
PxU32 Counters[NB_BUCKETS];
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
PxU32* Remap = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(sizeof(PxU32)*nb));
PxU8* Indices = reinterpret_cast<PxU8*>(memoryManager.frameAlloc(sizeof(PxU8)*nb));
for(PxU32 i=0;i<nb;i++)
{
const PxU8 index = classifyBoxNew(listYZ[i], limitY, limitZ);
Indices[i] = index;
Counters[index]++;
}
SIMD_AABB_X4* BoxListX[NB_BUCKETS];
SIMD_AABB_YZ4* BoxListYZ[NB_BUCKETS];
PxU32* RemapBase[NB_BUCKETS];
{
SIMD_AABB_X4* CurrentBoxListXBuffer = BoxListXBuffer;
SIMD_AABB_YZ4* CurrentBoxListYZBuffer = BoxListYZBuffer;
PxU32* CurrentRemap = Remap;
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
const PxU32 Nb = Counters[i];
BoxListX[i] = CurrentBoxListXBuffer;
BoxListYZ[i] = CurrentBoxListYZBuffer;
RemapBase[i] = CurrentRemap;
CurrentBoxListXBuffer += Nb+NB_SENTINELS;
CurrentBoxListYZBuffer += Nb;
CurrentRemap += Nb;
}
PX_ASSERT(CurrentBoxListXBuffer == BoxListXBuffer + nb + NB_SENTINELS*NB_BUCKETS);
PX_ASSERT(CurrentBoxListYZBuffer == BoxListYZBuffer + nb);
PX_ASSERT(CurrentRemap == Remap + nb);
}
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 SortedIndex = i;
const PxU32 TargetBucket = PxU32(Indices[SortedIndex]);
const PxU32 IndexInTarget = Counters[TargetBucket]++;
SIMD_AABB_X4* TargetBoxListX = BoxListX[TargetBucket];
SIMD_AABB_YZ4* TargetBoxListYZ = BoxListYZ[TargetBucket];
PxU32* TargetRemap = RemapBase[TargetBucket];
TargetRemap[IndexInTarget] = remap[SortedIndex];
TargetBoxListX[IndexInTarget] = listX[SortedIndex];
TargetBoxListYZ[IndexInTarget] = listYZ[SortedIndex];
}
memoryManager.frameFree(Indices);
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
SIMD_AABB_X4* TargetBoxListX = BoxListX[i];
const PxU32 IndexInTarget = Counters[i];
for(PxU32 j=0;j<NB_SENTINELS;j++)
TargetBoxListX[IndexInTarget+j].initSentinel();
}
{
const PxU32 limit = RECURSE_LIMIT;
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
if(Counters[i]<limit || Counters[i]==nb)
doCompleteBoxPruning_Leaf( pairManager,
Counters[i],
BoxListX[i], BoxListYZ[i],
RemapBase[i],
objects);
else
CompleteBoxPruning_Recursive(memoryManager, pairManager,
Counters[i],
BoxListX[i], BoxListYZ[i],
RemapBase[i],
objects);
}
}
{
for(PxU32 i=0;i<NB_BUCKETS-1;i++)
{
doBipartiteBoxPruning_Leaf(pairManager, objects,
Counters[i], Counters[NB_BUCKETS-1],
BoxListX[i], BoxListX[NB_BUCKETS-1], BoxListYZ[i], BoxListYZ[NB_BUCKETS-1],
RemapBase[i], RemapBase[NB_BUCKETS-1]
);
}
}
memoryManager.frameFree(Remap);
memoryManager.frameFree(BoxListYZBuffer);
memoryManager.frameFree(BoxListXBuffer);
}
#endif
#ifdef ABP_MT2
void ABP_CompleteBoxPruningTask::run()
{
// printf("Running ABP_CompleteBoxPruningTask\n");
//printf("ABP_Task_%d - thread ID %d\n", mID, PxU32(PxThread::getId()));
//printf("Count: %d\n", mCounter);
bool runComplete = false;
bool runBipartite = false;
if(mType==0)
runComplete = true;
else
runBipartite = true;
if(runComplete)
doCompleteBoxPruning_Leaf(&mPairs, mCounter, mBoxListX, mBoxListYZ, mRemap);
if(runBipartite)
doBipartiteBoxPruning_Leaf(&mPairs,
mCounter, mCounter4,
mBoxListX, mBoxListX4,
mBoxListYZ, mBoxListYZ4,
mRemap, mRemap4);
}
void ABP_CompleteBoxPruningEndTask::run()
{
// printf("Running ABP_CompleteBoxPruningEndTask\n");
//memoryManager.frameFree(Remap);
//memoryManager.frameFree(BoxListYZBuffer);
//memoryManager.frameFree(BoxListXBuffer);
// PT: TODO: revisit allocs
PX_FREE(mStartTask->mRemap);
PX_FREE(mStartTask->mBoxListYZBuffer);
PX_FREE(mStartTask->mBoxListXBuffer);
}
ABP_CompleteBoxPruningStartTask::ABP_CompleteBoxPruningStartTask() :
mListX (NULL),
mListYZ (NULL),
mInputRemap (NULL),
mPairManager (NULL),
mRemap (NULL),
mBoxListXBuffer (NULL),
mBoxListYZBuffer(NULL),
mNb (0)
{
}
void ABP_CompleteBoxPruningStartTask::setup(
//ABP_MM& memoryManager,
const PxBounds3& updatedBounds,
ABP_PairManager* PX_RESTRICT pairManager,
PxU32 nb,
const SIMD_AABB_X4* PX_RESTRICT listX,
const SIMD_AABB_YZ4* PX_RESTRICT listYZ,
const ABP_Index* PX_RESTRICT inputRemap,
PxU64 contextID)
{
mListX = listX;
mListYZ = listYZ;
mInputRemap = inputRemap;
mPairManager = pairManager;
mBounds = updatedBounds;
mContextID = contextID;
mNb = nb;
// PT: TODO: revisit allocs
//mBoxListXBuffer = reinterpret_cast<SIMD_AABB_X4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_X4)*(nb+NB_SENTINELS*NB_BUCKETS)));
//mBoxListYZBuffer = reinterpret_cast<SIMD_AABB_YZ4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_YZ4)*nb));
mBoxListXBuffer = reinterpret_cast<SIMD_AABB_X4*>(PX_ALLOC(sizeof(SIMD_AABB_X4)*(nb+NB_SENTINELS*NB_BUCKETS), "mBoxListXBuffer"));
mBoxListYZBuffer = reinterpret_cast<SIMD_AABB_YZ4*>(PX_ALLOC(sizeof(SIMD_AABB_YZ4)*nb, "mBoxListYZBuffer"));
//mRemap = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(sizeof(PxU32)*nb));
mRemap = reinterpret_cast<PxU32*>(PX_ALLOC(sizeof(PxU32)*nb, "mRemap"));
mEndTask.mStartTask = this;
for(PxU32 i=0;i<9;i++)
mTasks[i].mStartTask = this;
}
void ABP_CompleteBoxPruningStartTask::run()
{
// printf("Running ABP_CompleteBoxPruningStartTask\n");
const SIMD_AABB_X4* PX_RESTRICT listX = mListX;
const SIMD_AABB_YZ4* PX_RESTRICT listYZ = mListYZ;
const ABP_Index* PX_RESTRICT remap = mInputRemap;
const PxU32 nb = mNb;
PxU32* PX_RESTRICT Remap = mRemap;
SIMD_AABB_X4* PX_RESTRICT BoxListXBuffer = mBoxListXBuffer;
SIMD_AABB_YZ4* PX_RESTRICT BoxListYZBuffer = mBoxListYZBuffer;
PxU32* PX_RESTRICT Counters = mCounters;
SIMD_AABB_X4** PX_RESTRICT BoxListX = mBoxListX;
SIMD_AABB_YZ4** PX_RESTRICT BoxListYZ = mBoxListYZ;
PxU32** PX_RESTRICT RemapBase = mRemapBase;
{
PX_PROFILE_ZONE("ABP_CompleteBoxPruningStartTask - Run", mContextID);
// PT: TODO: revisit allocs
//BoxListXBuffer = reinterpret_cast<SIMD_AABB_X4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_X4)*(nb+NB_SENTINELS*NB_BUCKETS)));
//BoxListYZBuffer = reinterpret_cast<SIMD_AABB_YZ4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_YZ4)*nb));
const PxVec3& mergedMin = mBounds.minimum;
const PxVec3& mergedMax = mBounds.maximum;
const float limitY = (mergedMax[1] + mergedMin[1]) * 0.5f;
const float limitZ = (mergedMax[2] + mergedMin[2]) * 0.5f;
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
//Remap = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(sizeof(PxU32)*nb));
// PT: TODO: revisit allocs
//PxU8* Indices = reinterpret_cast<PxU8*>(memoryManager.frameAlloc(sizeof(PxU8)*nb));
PxU8* Indices = reinterpret_cast<PxU8*>(PX_ALLOC(sizeof(PxU8)*nb, "Indices"));
{
PX_PROFILE_ZONE("BoxPruning - ClassifyBoxes", mContextID);
for(PxU32 i=0;i<nb;i++)
{
const PxU8 index = classifyBoxNew(listYZ[i], limitY, limitZ);
Indices[i] = index;
Counters[index]++;
}
}
{
SIMD_AABB_X4* CurrentBoxListXBuffer = BoxListXBuffer;
SIMD_AABB_YZ4* CurrentBoxListYZBuffer = BoxListYZBuffer;
PxU32* CurrentRemap = Remap;
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
const PxU32 Nb = Counters[i];
BoxListX[i] = CurrentBoxListXBuffer;
BoxListYZ[i] = CurrentBoxListYZBuffer;
RemapBase[i] = CurrentRemap;
CurrentBoxListXBuffer += Nb+NB_SENTINELS;
CurrentBoxListYZBuffer += Nb;
CurrentRemap += Nb;
}
PX_ASSERT(CurrentBoxListXBuffer == BoxListXBuffer + nb + NB_SENTINELS*NB_BUCKETS);
PX_ASSERT(CurrentBoxListYZBuffer == BoxListYZBuffer + nb);
PX_ASSERT(CurrentRemap == Remap + nb);
}
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 SortedIndex = i;
const PxU32 TargetBucket = PxU32(Indices[SortedIndex]);
const PxU32 IndexInTarget = Counters[TargetBucket]++;
SIMD_AABB_X4* TargetBoxListX = BoxListX[TargetBucket];
SIMD_AABB_YZ4* TargetBoxListYZ = BoxListYZ[TargetBucket];
PxU32* TargetRemap = RemapBase[TargetBucket];
TargetRemap[IndexInTarget] = remap[SortedIndex];
TargetBoxListX[IndexInTarget] = listX[SortedIndex];
TargetBoxListYZ[IndexInTarget] = listYZ[SortedIndex];
}
//memoryManager.frameFree(Indices);
PX_FREE(Indices);
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
SIMD_AABB_X4* TargetBoxListX = BoxListX[i];
const PxU32 IndexInTarget = Counters[i];
for(PxU32 j=0;j<NB_SENTINELS;j++)
TargetBoxListX[IndexInTarget+j].initSentinel();
}
}
for(PxU32 i=0;i<8;i++)
{
mTasks[i].mCounter = Counters[i/2];
mTasks[i].mBoxListX = BoxListX[i/2];
mTasks[i].mBoxListYZ = BoxListYZ[i/2];
mTasks[i].mRemap = RemapBase[i/2];
mTasks[i].mType = i&1;
mTasks[i].mCounter4 = Counters[4];
mTasks[i].mBoxListX4 = BoxListX[4];
mTasks[i].mBoxListYZ4 = BoxListYZ[4];
mTasks[i].mRemap4 = RemapBase[4];
mTasks[i].mPairs.mSharedPM = mPairManager;
//mTasks[i].mPairs.mDelayedPairs.reserve(10000);
}
PxU32 i=8;
{
mTasks[i].mCounter = Counters[4];
mTasks[i].mBoxListX = BoxListX[4];
mTasks[i].mBoxListYZ = BoxListYZ[4];
mTasks[i].mRemap = RemapBase[4];
mTasks[i].mType = 0;
mTasks[i].mCounter4 = Counters[4];
mTasks[i].mBoxListX4 = BoxListX[4];
mTasks[i].mBoxListYZ4 = BoxListYZ[4];
mTasks[i].mRemap4 = RemapBase[4];
mTasks[i].mPairs.mSharedPM = mPairManager;
//mTasks[i].mPairs.mDelayedPairs.reserve(10000);
}
for(PxU32 k=0; k<8+1; k++)
{
if(mTasks[k].isThereWorkToDo())
{
mTasks[k].mID = PxU16(k);
mTasks[k].setContinuation(getContinuation());
}
}
for(PxU32 k=0; k<8+1; k++)
{
if(mTasks[k].isThereWorkToDo())
mTasks[k].removeReference();
}
}
void ABP_CompleteBoxPruningStartTask::addDelayedPairs()
{
PX_PROFILE_ZONE("ABP_CompleteBoxPruningStartTask - add delayed pairs", mContextID);
PxU32 nbDelayedPairs = 0;
for(PxU32 k=0; k<9; k++)
nbDelayedPairs += mTasks[k].mPairs.mDelayedPairs.size();
if(nbDelayedPairs)
{
{
PX_PROFILE_ZONE("BroadPhaseABP - resizeForNewPairs", mContextID);
mPairManager->resizeForNewPairs(nbDelayedPairs);
}
for(PxU32 k=0; k<9; k++)
mPairManager->addDelayedPairs(mTasks[k].mPairs.mDelayedPairs);
}
}
void ABP_CompleteBoxPruningStartTask::addDelayedPairs2(PxArray<BroadPhasePair>& createdPairs)
{
PX_PROFILE_ZONE("ABP_CompleteBoxPruningStartTask - add delayed pairs", mContextID);
PxU32 nbDelayedPairs = 0;
for(PxU32 k=0; k<9; k++)
nbDelayedPairs += mTasks[k].mPairs.mDelayedPairs.size();
if(nbDelayedPairs)
{
{
PX_PROFILE_ZONE("BroadPhaseABP - resizeForNewPairs", mContextID);
mPairManager->resizeForNewPairs(nbDelayedPairs);
}
for(PxU32 k=0; k<9; k++)
mPairManager->addDelayedPairs2(createdPairs, mTasks[k].mPairs.mDelayedPairs);
}
}
#endif
#ifndef USE_ALTERNATIVE_VERSION
static void CompleteBoxPruning_Version16(
#ifdef ABP_MT2
ABP_CompleteBoxPruningStartTask& completeBoxPruningTask,
#endif
ABP_MM& memoryManager,
const PxBounds3& updatedBounds,
ABP_PairManager* PX_RESTRICT pairManager,
PxU32 nb,
const SIMD_AABB_X4* PX_RESTRICT listX,
const SIMD_AABB_YZ4* PX_RESTRICT listYZ,
const ABP_Index* PX_RESTRICT remap,
PxBaseTask* continuation, PxU64 contextID)
{
PX_UNUSED(contextID);
PX_UNUSED(continuation);
if(!nb)
return;
#ifdef ABP_MT2
if(continuation)
{
completeBoxPruningTask.setup(updatedBounds, pairManager, nb, listX, listYZ, remap, contextID);
completeBoxPruningTask.mEndTask.setContinuation(continuation);
completeBoxPruningTask.setContinuation(&completeBoxPruningTask.mEndTask);
completeBoxPruningTask.mEndTask.removeReference();
completeBoxPruningTask.removeReference();
return;
}
#endif
PxU32* Remap;
SIMD_AABB_X4* BoxListXBuffer;
SIMD_AABB_YZ4* BoxListYZBuffer;
PxU32 Counters[NB_BUCKETS];
SIMD_AABB_X4* BoxListX[NB_BUCKETS];
SIMD_AABB_YZ4* BoxListYZ[NB_BUCKETS];
PxU32* RemapBase[NB_BUCKETS];
{
PX_PROFILE_ZONE("BoxPruning - PrepareData", contextID);
// PT: TODO: revisit allocs
BoxListXBuffer = reinterpret_cast<SIMD_AABB_X4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_X4)*(nb+NB_SENTINELS*NB_BUCKETS)));
BoxListYZBuffer = reinterpret_cast<SIMD_AABB_YZ4*>(memoryManager.frameAlloc(sizeof(SIMD_AABB_YZ4)*nb));
const PxVec3& mergedMin = updatedBounds.minimum;
const PxVec3& mergedMax = updatedBounds.maximum;
const float limitY = (mergedMax[1] + mergedMin[1]) * 0.5f;
const float limitZ = (mergedMax[2] + mergedMin[2]) * 0.5f;
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
Remap = reinterpret_cast<PxU32*>(memoryManager.frameAlloc(sizeof(PxU32)*nb));
PxU8* Indices = reinterpret_cast<PxU8*>(memoryManager.frameAlloc(sizeof(PxU8)*nb));
{
PX_PROFILE_ZONE("BoxPruning - ClassifyBoxes", contextID);
for(PxU32 i=0;i<nb;i++)
{
const PxU8 index = classifyBoxNew(listYZ[i], limitY, limitZ);
Indices[i] = index;
Counters[index]++;
}
}
{
SIMD_AABB_X4* CurrentBoxListXBuffer = BoxListXBuffer;
SIMD_AABB_YZ4* CurrentBoxListYZBuffer = BoxListYZBuffer;
PxU32* CurrentRemap = Remap;
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
const PxU32 Nb = Counters[i];
BoxListX[i] = CurrentBoxListXBuffer;
BoxListYZ[i] = CurrentBoxListYZBuffer;
RemapBase[i] = CurrentRemap;
CurrentBoxListXBuffer += Nb+NB_SENTINELS;
CurrentBoxListYZBuffer += Nb;
CurrentRemap += Nb;
}
PX_ASSERT(CurrentBoxListXBuffer == BoxListXBuffer + nb + NB_SENTINELS*NB_BUCKETS);
PX_ASSERT(CurrentBoxListYZBuffer == BoxListYZBuffer + nb);
PX_ASSERT(CurrentRemap == Remap + nb);
}
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 SortedIndex = i;
const PxU32 TargetBucket = PxU32(Indices[SortedIndex]);
const PxU32 IndexInTarget = Counters[TargetBucket]++;
SIMD_AABB_X4* TargetBoxListX = BoxListX[TargetBucket];
SIMD_AABB_YZ4* TargetBoxListYZ = BoxListYZ[TargetBucket];
PxU32* TargetRemap = RemapBase[TargetBucket];
TargetRemap[IndexInTarget] = remap[SortedIndex];
TargetBoxListX[IndexInTarget] = listX[SortedIndex];
TargetBoxListYZ[IndexInTarget] = listYZ[SortedIndex];
}
memoryManager.frameFree(Indices);
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
SIMD_AABB_X4* TargetBoxListX = BoxListX[i];
const PxU32 IndexInTarget = Counters[i];
for(PxU32 j=0;j<NB_SENTINELS;j++)
TargetBoxListX[IndexInTarget+j].initSentinel();
}
}
{
for(PxU32 i=0;i<NB_BUCKETS;i++)
{
#ifdef RECURSE_LIMIT
if(Counters[i]<RECURSE_LIMIT || Counters[i]==nb)
#endif
doCompleteBoxPruning_Leaf( pairManager,
Counters[i],
BoxListX[i], BoxListYZ[i],
RemapBase[i]);
#ifdef RECURSE_LIMIT
else
CompleteBoxPruning_Recursive(memoryManager, pairManager,
Counters[i],
BoxListX[i], BoxListYZ[i],
RemapBase[i]);
#endif
}
for(PxU32 i=0;i<NB_BUCKETS-1;i++)
{
doBipartiteBoxPruning_Leaf(pairManager,
Counters[i], Counters[NB_BUCKETS-1],
BoxListX[i], BoxListX[NB_BUCKETS-1], BoxListYZ[i], BoxListYZ[NB_BUCKETS-1],
RemapBase[i], RemapBase[NB_BUCKETS-1]
);
}
}
memoryManager.frameFree(Remap);
memoryManager.frameFree(BoxListYZBuffer);
memoryManager.frameFree(BoxListXBuffer);
}
#endif
#endif
#ifdef USE_ALTERNATIVE_VERSION
// PT: experimental version that adds all cross-bucket objects to all regular buckets
static void CompleteBoxPruning_Version16(
ABP_MM& /*memoryManager*/,
const PxBounds3& updatedBounds,
ABP_PairManager* PX_RESTRICT pairManager,
PxU32 nb,
const SIMD_AABB_X4* PX_RESTRICT listX,
const SIMD_AABB_YZ4* PX_RESTRICT listYZ,
const ABP_Index* PX_RESTRICT remap,
const ABPEntry* PX_RESTRICT objects)
{
if(!nb)
return;
const PxVec3& mergedMin = updatedBounds.minimum;
const PxVec3& mergedMax = updatedBounds.maximum;
const float limitY = (mergedMax[1] + mergedMin[1]) * 0.5f;
const float limitZ = (mergedMax[2] + mergedMin[2]) * 0.5f;
PxU32 Counters[NB_BUCKETS];
for(PxU32 i=0;i<NB_BUCKETS;i++)
Counters[i] = 0;
PxU8* Indices = (PxU8*)PX_ALLOC(sizeof(PxU8)*nb, "temp");
for(PxU32 i=0;i<nb;i++)
{
const PxU8 index = classifyBoxNew(listYZ[i], limitY, limitZ);
Indices[i] = index;
Counters[index]++;
}
PxU32 total = 0;
PxU32 Counters2[4];
for(PxU32 i=0;i<4;i++)
{
Counters2[i] = Counters[i] + Counters[4];
total += Counters2[i];
}
// PT: TODO: revisit allocs
SIMD_AABB_X4* BoxListXBuffer = (SIMD_AABB_X4*)PX_ALLOC(sizeof(SIMD_AABB_X4)*(total+NB_SENTINELS*NB_BUCKETS), "temp");
SIMD_AABB_YZ4* BoxListYZBuffer = (SIMD_AABB_YZ4*)PX_ALLOC(sizeof(SIMD_AABB_YZ4)*total, "temp");
PxU32* Remap = (PxU32*)PX_ALLOC(sizeof(PxU32)*total, "temp");
SIMD_AABB_X4* CurrentBoxListXBuffer = BoxListXBuffer;
SIMD_AABB_YZ4* CurrentBoxListYZBuffer = BoxListYZBuffer;
PxU32* CurrentRemap = Remap;
SIMD_AABB_X4* BoxListX[4];
SIMD_AABB_YZ4* BoxListYZ[4];
PxU32* RemapBase[4];
for(PxU32 i=0;i<4;i++)
{
const PxU32 Nb = Counters2[i];
BoxListX[i] = CurrentBoxListXBuffer;
BoxListYZ[i] = CurrentBoxListYZBuffer;
RemapBase[i] = CurrentRemap;
CurrentBoxListXBuffer += Nb+NB_SENTINELS;
CurrentBoxListYZBuffer += Nb;
CurrentRemap += Nb;
}
PX_ASSERT(CurrentBoxListXBuffer == BoxListXBuffer + total + NB_SENTINELS*NB_BUCKETS);
PX_ASSERT(CurrentBoxListYZBuffer == BoxListYZBuffer + total);
PX_ASSERT(CurrentRemap == Remap + total);
for(PxU32 i=0;i<4;i++)
Counters2[i] = 0;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 SortedIndex = i;
const PxU32 TargetBucket = PxU32(Indices[SortedIndex]);
if(TargetBucket==4)
{
for(PxU32 j=0;j<4;j++)
{
const PxU32 IndexInTarget = Counters2[j]++;
SIMD_AABB_X4* TargetBoxListX = BoxListX[j];
SIMD_AABB_YZ4* TargetBoxListYZ = BoxListYZ[j];
PxU32* TargetRemap = RemapBase[j];
TargetRemap[IndexInTarget] = remap[SortedIndex];
TargetBoxListX[IndexInTarget] = listX[SortedIndex];
TargetBoxListYZ[IndexInTarget] = listYZ[SortedIndex];
}
}
else
{
const PxU32 IndexInTarget = Counters2[TargetBucket]++;
SIMD_AABB_X4* TargetBoxListX = BoxListX[TargetBucket];
SIMD_AABB_YZ4* TargetBoxListYZ = BoxListYZ[TargetBucket];
PxU32* TargetRemap = RemapBase[TargetBucket];
TargetRemap[IndexInTarget] = remap[SortedIndex];
TargetBoxListX[IndexInTarget] = listX[SortedIndex];
TargetBoxListYZ[IndexInTarget] = listYZ[SortedIndex];
}
}
PX_FREE(Indices);
for(PxU32 i=0;i<4;i++)
{
SIMD_AABB_X4* TargetBoxListX = BoxListX[i];
const PxU32 IndexInTarget = Counters2[i];
for(PxU32 j=0;j<NB_SENTINELS;j++)
TargetBoxListX[IndexInTarget+j].initSentinel();
}
{
for(PxU32 i=0;i<4;i++)
{
#ifdef RECURSE_LIMIT
if(Counters2[i]<RECURSE_LIMIT || Counters2[i]==nb)
#endif
doCompleteBoxPruning_Leaf( pairManager,
Counters2[i],
BoxListX[i], BoxListYZ[i],
RemapBase[i],
objects);
#ifdef RECURSE_LIMIT
else
CompleteBoxPruning_Recursive( pairManager,
Counters2[i],
BoxListX[i], BoxListYZ[i],
RemapBase[i],
objects);
#endif
}
}
PX_FREE(Remap);
PX_FREE(BoxListYZBuffer);
PX_FREE(BoxListXBuffer);
}
#endif
static void doCompleteBoxPruning_(
#ifdef ABP_MT2
ABP_CompleteBoxPruningStartTask& completeBoxPruningTask,
ABP_CompleteBoxPruningTask& bipTask0,
ABP_CompleteBoxPruningTask& bipTask1,
#endif
ABP_MM& memoryManager, ABP_PairManager* PX_RESTRICT pairManager, const DynamicManager& mDBM, PxBaseTask* continuation, PxU64 contextID)
{
const PxU32 nbUpdated = mDBM.getNbUpdatedBoxes();
if(!nbUpdated)
return;
const PxU32 nbNonUpdated = mDBM.getNbNonUpdatedBoxes();
const DynamicBoxes& updatedBoxes = mDBM.getUpdatedBoxes();
const SIMD_AABB_X4* PX_RESTRICT updatedDynamicBoxes_X = updatedBoxes.getBoxes_X();
const SIMD_AABB_YZ4* PX_RESTRICT updatedDynamicBoxes_YZ = updatedBoxes.getBoxes_YZ();
// PT: find sleeping-dynamics-vs-active-dynamics overlaps
if(nbNonUpdated)
{
#ifdef ABP_MT2
if(continuation)
{
bipTask0.mCounter = nbUpdated;
bipTask0.mBoxListX = updatedBoxes.getBoxes_X();
bipTask0.mBoxListYZ = updatedBoxes.getBoxes_YZ();
bipTask0.mRemap = mDBM.getRemap_Updated();
bipTask0.mType = 1;
bipTask0.mCounter4 = nbNonUpdated;
bipTask0.mBoxListX4 = mDBM.getSleepingBoxes().getBoxes_X();
bipTask0.mBoxListYZ4 = mDBM.getSleepingBoxes().getBoxes_YZ();
bipTask0.mRemap4 = mDBM.getRemap_Sleeping();
bipTask0.mPairs.mSharedPM = pairManager;
//bipTask0.mPairs.mDelayedPairs.reserve(10000);
if(bipTask0.isThereWorkToDo())
{
bipTask0.mID = 0;
bipTask0.setContinuation(continuation);
bipTask0.removeReference();
}
}
else
#endif
doBipartiteBoxPruning_Leaf( pairManager, nbUpdated, nbNonUpdated,
updatedBoxes, mDBM.getSleepingBoxes(),
mDBM.getRemap_Updated(), mDBM.getRemap_Sleeping());
}
///////
// PT: find active-dynamics-vs-active-dynamics overlaps
if(1)
{
PX_UNUSED(memoryManager);
#ifdef USE_ABP_BUCKETS
if(nbUpdated>USE_ABP_BUCKETS)
CompleteBoxPruning_Version16(
#ifdef ABP_MT2
completeBoxPruningTask,
#endif
memoryManager, mDBM.getUpdatedBounds(), pairManager, nbUpdated,
updatedDynamicBoxes_X, updatedDynamicBoxes_YZ,
mDBM.getRemap_Updated(), continuation, contextID);
else
#endif
{
#ifdef ABP_MT2
if(continuation)
{
bipTask1.mCounter = nbUpdated;
bipTask1.mBoxListX = updatedDynamicBoxes_X;
bipTask1.mBoxListYZ = updatedDynamicBoxes_YZ;
bipTask1.mRemap = mDBM.getRemap_Updated();
bipTask1.mType = 0;
bipTask1.mPairs.mSharedPM = pairManager;
//bipTask1.mPairs.mDelayedPairs.reserve(10000);
if(bipTask1.isThereWorkToDo())
{
bipTask1.mID = 0;
bipTask1.setContinuation(continuation);
bipTask1.removeReference();
}
}
else
#endif
doCompleteBoxPruning_Leaf( pairManager, nbUpdated,
updatedDynamicBoxes_X, updatedDynamicBoxes_YZ,
mDBM.getRemap_Updated());
}
}
}
void ABP::Region_prepareOverlaps()
{
PX_PROFILE_ZONE("ABP - Region_prepareOverlaps", mContextID);
if( !mDBM.isThereWorkToDo()
&& !mKBM.isThereWorkToDo()
&& !mSBM.isThereWorkToDo()
)
return;
if(mSBM.isThereWorkToDo())
mSBM.prepareData(mRS, mShared.mABP_Objects, mShared.mABP_Objects_Capacity, mMM, mContextID);
mDBM.prepareData(mRS, mShared.mABP_Objects, mShared.mABP_Objects_Capacity, mMM, mContextID);
mKBM.prepareData(mRS, mShared.mABP_Objects, mShared.mABP_Objects_Capacity, mMM, mContextID);
mRS.reset();
}
// Finds static-vs-dynamic and dynamic-vs-dynamic overlaps
static void findAllOverlaps(
#ifdef ABP_MT2
ABP_CompleteBoxPruningStartTask& completeBoxPruningTask,
ABP_CompleteBoxPruningTask& bipTask0,
ABP_CompleteBoxPruningTask& bipTask1,
ABP_CompleteBoxPruningTask& bipTask2,
ABP_CompleteBoxPruningTask& bipTask3,
ABP_CompleteBoxPruningTask& bipTask4,
#endif
ABP_MM& memoryManager, ABP_PairManager& pairManager, const StaticManager& mSBM, const DynamicManager& mDBM, bool doComplete, bool doBipartite, PxBaseTask* continuation, PxU64 contextID)
{
const PxU32 nbUpdatedBoxesDynamic = mDBM.getNbUpdatedBoxes();
// PT: find dynamics-vs-dynamics overlaps
if(doComplete)
doCompleteBoxPruning_(
#ifdef ABP_MT2
completeBoxPruningTask,
bipTask3,
bipTask4,
#endif
memoryManager, &pairManager, mDBM, continuation, contextID);
// PT: find dynamics-vs-statics overlaps
if(doBipartite)
{
const PxU32 nbUpdatedBoxesStatic = mSBM.getNbUpdatedBoxes();
const PxU32 nbNonUpdatedBoxesStatic = mSBM.getNbNonUpdatedBoxes();
const PxU32 nbNonUpdatedBoxesDynamic = mDBM.getNbNonUpdatedBoxes();
// PT: in previous versions we did active-dynamics-vs-all-statics here.
if(nbUpdatedBoxesDynamic)
{
if(nbUpdatedBoxesStatic)
{
// PT: active static vs active dynamic
#ifdef ABP_MT2
if(continuation)
{
bipTask0.mCounter = nbUpdatedBoxesDynamic;
bipTask0.mBoxListX = mDBM.getUpdatedBoxes().getBoxes_X();
bipTask0.mBoxListYZ = mDBM.getUpdatedBoxes().getBoxes_YZ();
bipTask0.mRemap = mDBM.getRemap_Updated();
bipTask0.mType = 1;
bipTask0.mCounter4 = nbUpdatedBoxesStatic;
bipTask0.mBoxListX4 = mSBM.getUpdatedBoxes().getBoxes_X();
bipTask0.mBoxListYZ4 = mSBM.getUpdatedBoxes().getBoxes_YZ();
bipTask0.mRemap4 = mSBM.getRemap_Updated();
bipTask0.mPairs.mSharedPM = &pairManager;
//bipTask0.mPairs.mDelayedPairs.reserve(10000);
if(bipTask0.isThereWorkToDo())
{
bipTask0.mID = 0;
bipTask0.setContinuation(continuation);
bipTask0.removeReference();
}
}
else
#endif
doBipartiteBoxPruning_Leaf( &pairManager,
nbUpdatedBoxesDynamic, nbUpdatedBoxesStatic,
mDBM.getUpdatedBoxes(), mSBM.getUpdatedBoxes(),
mDBM.getRemap_Updated(), mSBM.getRemap_Updated());
}
if(nbNonUpdatedBoxesStatic)
{
// PT: sleeping static vs active dynamic
#ifdef ABP_MT2
if(continuation)
{
bipTask1.mCounter = nbUpdatedBoxesDynamic;
bipTask1.mBoxListX = mDBM.getUpdatedBoxes().getBoxes_X();
bipTask1.mBoxListYZ = mDBM.getUpdatedBoxes().getBoxes_YZ();
bipTask1.mRemap = mDBM.getRemap_Updated();
bipTask1.mType = 1;
bipTask1.mCounter4 = nbNonUpdatedBoxesStatic;
bipTask1.mBoxListX4 = mSBM.getSleepingBoxes().getBoxes_X();
bipTask1.mBoxListYZ4 = mSBM.getSleepingBoxes().getBoxes_YZ();
bipTask1.mRemap4 = mSBM.getRemap_Sleeping();
bipTask1.mPairs.mSharedPM = &pairManager;
//bipTask1.mPairs.mDelayedPairs.reserve(10000);
if(bipTask1.isThereWorkToDo())
{
bipTask1.mID = 0;
bipTask1.setContinuation(continuation);
bipTask1.removeReference();
}
}
else
#endif
doBipartiteBoxPruning_Leaf( &pairManager,
nbUpdatedBoxesDynamic, nbNonUpdatedBoxesStatic,
mDBM.getUpdatedBoxes(), mSBM.getSleepingBoxes(),
mDBM.getRemap_Updated(), mSBM.getRemap_Sleeping());
}
}
if(nbUpdatedBoxesStatic && nbNonUpdatedBoxesDynamic)
{
// PT: active static vs sleeping dynamic
#ifdef ABP_MT2
if(continuation)
{
bipTask2.mCounter = nbNonUpdatedBoxesDynamic;
bipTask2.mBoxListX = mDBM.getSleepingBoxes().getBoxes_X();
bipTask2.mBoxListYZ = mDBM.getSleepingBoxes().getBoxes_YZ();
bipTask2.mRemap = mDBM.getRemap_Sleeping();
bipTask2.mType = 1;
bipTask2.mCounter4 = nbUpdatedBoxesStatic;
bipTask2.mBoxListX4 = mSBM.getUpdatedBoxes().getBoxes_X();
bipTask2.mBoxListYZ4 = mSBM.getUpdatedBoxes().getBoxes_YZ();
bipTask2.mRemap4 = mSBM.getRemap_Updated();
bipTask2.mPairs.mSharedPM = &pairManager;
//bipTask2.mPairs.mDelayedPairs.reserve(10000);
if(bipTask2.isThereWorkToDo())
{
bipTask2.mID = 0;
bipTask2.setContinuation(continuation);
bipTask2.removeReference();
}
}
else
#endif
doBipartiteBoxPruning_Leaf( &pairManager,
nbNonUpdatedBoxesDynamic, nbUpdatedBoxesStatic,
mDBM.getSleepingBoxes(), mSBM.getUpdatedBoxes(),
mDBM.getRemap_Sleeping(), mSBM.getRemap_Updated());
}
}
}
///////////////////////////////////////////////////////////////////////////
ABP::ABP(PxU64 contextID) :
mSBM (FilterType::STATIC),
mDBM (FilterType::DYNAMIC),
mKBM (FilterType::KINEMATIC),
mContextID (contextID)
#ifdef ABP_MT2
,mTask0 (ABP_TASK_0)
,mTask1 (ABP_TASK_1)
#endif
{
#ifdef ABP_MT2
mTask0.setContextId(mContextID);
mTask1.setContextId(mContextID);
mCompleteBoxPruningTask0.setContextId(mContextID);
mCompleteBoxPruningTask1.setContextId(mContextID);
for(PxU32 k=0; k<9; k++)
{
mCompleteBoxPruningTask0.mTasks[k].setContextId(mContextID);
mCompleteBoxPruningTask1.mTasks[k].setContextId(mContextID);
}
for(PxU32 k=0; k<NB_BIP_TASKS; k++)
mBipTasks[k].setContextId(mContextID);
#endif
}
ABP::~ABP()
{
reset();
}
void ABP::freeBuffers()
{
mShared.mRemovedObjects.empty();
}
void ABP::preallocate(PxU32 nbObjects, PxU32 maxNbOverlaps)
{
if(nbObjects)
{
PX_DELETE_ARRAY(mShared.mABP_Objects);
ABP_Object* objects = PX_NEW(ABP_Object)[nbObjects];
mShared.mABP_Objects = objects;
mShared.mABP_Objects_Capacity = nbObjects;
#if PX_DEBUG
for(PxU32 i=0;i<nbObjects;i++)
objects[i].mUpdated = false;
#endif
}
// PT: TODO: here we should preallocate the box arrays but we don't know how many of them will be static / dynamic...
mPairManager.reserveMemory(maxNbOverlaps);
}
void ABP::addStaticObjects(const BpHandle* userID_, PxU32 nb, PxU32 maxID)
{
mShared.checkResize(maxID);
mSBM.addObjects(userID_, nb, NULL);
}
void ABP::addDynamicObjects(const BpHandle* userID_, PxU32 nb, PxU32 maxID)
{
mShared.checkResize(maxID);
mShared.mUpdatedObjects.checkResize(maxID);
mDBM.addObjects(userID_, nb, &mShared);
}
void ABP::addKinematicObjects(const BpHandle* userID_, PxU32 nb, PxU32 maxID)
{
mShared.checkResize(maxID);
mShared.mUpdatedObjects.checkResize(maxID);
mKBM.addObjects(userID_, nb, &mShared);
}
void ABP::removeObject(BpHandle userID)
{
mShared.mUpdatedObjects.setBitChecked(userID);
mShared.mRemovedObjects.setBitChecked(userID);
PX_ASSERT(userID<mShared.mABP_Objects_Capacity);
ABPEntry& object = mShared.mABP_Objects[userID];
// PT: TODO better
BoxManager* bm;
const FilterType::Enum objectType = object.getType();
if(objectType==FilterType::STATIC)
{
bm = &mSBM;
}
else if(objectType==FilterType::KINEMATIC)
{
bm = &mKBM;
}
else
{
bm = &mDBM;
}
bm->removeObject(object, userID);
object.invalidateIndex();
#if PX_DEBUG
object.mUpdated = false;
#endif
}
void ABP::updateObject(BpHandle userID)
{
mShared.mUpdatedObjects.setBitChecked(userID);
PX_ASSERT(userID<mShared.mABP_Objects_Capacity);
ABPEntry& object = mShared.mABP_Objects[userID];
// PT: TODO better
BoxManager* bm;
const FilterType::Enum objectType = object.getType();
if(objectType==FilterType::STATIC)
{
bm = &mSBM;
}
else if(objectType==FilterType::KINEMATIC)
{
bm = &mKBM;
}
else
{
bm = &mDBM;
}
bm->updateObject(object, userID);
}
// PT: TODO: replace bits with timestamps?
void ABP_PairManager::computeCreatedDeletedPairs(PxArray<BroadPhasePair>& createdPairs, PxArray<BroadPhasePair>& deletedPairs, const BitArray& updated, const BitArray& removed)
{
// PT: parse all currently active pairs. The goal here is to generate the found/lost pairs, compared to previous frame.
// PT: TODO: MT?
PxU32 i=0;
PxU32 nbActivePairs = mNbActivePairs;
while(i<nbActivePairs)
{
InternalPair& p = mActivePairs[i];
if(p.isNew())
{
// New pair
// PT: 'isNew' is set to true in the 'addPair' function. In this case the pair did not previously
// exist in the structure, and thus we must report the new pair to the client code.
//
// PT: group-based filtering is not needed here, since it has already been done in 'addPair'
const PxU32 id0 = p.getId0();
const PxU32 id1 = p.getId1();
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
//createdPairs.pushBack(BroadPhasePair(id0, id1));
BroadPhasePair* newPair = Cm::reserveContainerMemory(createdPairs, 1);
newPair->mVolA = id0;
newPair->mVolB = id1;
// PT: TODO: replace this with bitmaps?
p.clearNew();
p.clearUpdated();
i++;
}
else if(p.isUpdated())
{
// Persistent pair
// PT: this pair already existed in the structure, and has been found again this frame. Since
// MBP reports "all pairs" each frame (as opposed to SAP), this happens quite often, for each
// active persistent pair.
p.clearUpdated();
i++;
}
else
{
// Lost pair
// PT: if the pair is not new and not 'updated', it might be a lost (separated) pair. But this
// is not always the case since we now handle "sleeping" objects directly within MBP. A pair
// of sleeping objects does not generate an 'addPair' call, so it ends up in this codepath.
// Nonetheless the sleeping pair should not be deleted. We can only delete pairs involving
// objects that have been actually moved during the frame. This is the only case in which
// a pair can indeed become 'lost'.
const PxU32 id0 = p.getId0();
const PxU32 id1 = p.getId1();
PX_ASSERT(id0!=INVALID_ID);
PX_ASSERT(id1!=INVALID_ID);
// PT: if none of the involved objects have been updated, the pair is just sleeping: keep it and skip it.
if(updated.isSetChecked(id0) || updated.isSetChecked(id1))
{
// PT: by design (for better or worse) we do not report pairs to the client when
// one of the involved objects has been deleted. The pair must still be deleted
// from the MBP structure though.
if(!removed.isSetChecked(id0) && !removed.isSetChecked(id1))
{
// PT: doing the group-based filtering here is useless. The pair should not have
// been added in the first place.
//deletedPairs.pushBack(BroadPhasePair(id0, id1));
BroadPhasePair* lostPair = Cm::reserveContainerMemory(deletedPairs, 1);
lostPair->mVolA = id0;
lostPair->mVolB = id1;
}
const PxU32 hashValue = hash(id0, id1) & mMask;
removePair(id0, id1, hashValue, i);
nbActivePairs--;
}
else i++;
}
}
shrinkMemory();
}
void ABP::findOverlaps(PxBaseTask* continuation, const Bp::FilterGroup::Enum* PX_RESTRICT groups, const bool* PX_RESTRICT lut)
{
PX_PROFILE_ZONE("ABP - findOverlaps", mContextID);
mPairManager.mGroups = groups;
mPairManager.mLUT = lut;
if(!gPrepareOverlapsFlag)
Region_prepareOverlaps();
bool doKineKine = true;
bool doStaticKine = true;
{
doStaticKine = lut[Bp::FilterType::KINEMATIC*Bp::FilterType::COUNT + Bp::FilterType::STATIC];
doKineKine = lut[Bp::FilterType::KINEMATIC*Bp::FilterType::COUNT + Bp::FilterType::KINEMATIC];
}
// Static-vs-dynamic (bipartite) and dynamic-vs-dynamic (complete)
findAllOverlaps(
#ifdef ABP_MT2
mCompleteBoxPruningTask0,
mBipTasks[0],
mBipTasks[1],
mBipTasks[2],
mBipTasks[3],
mBipTasks[4],
#endif
mMM, mPairManager, mSBM, mDBM, true, true, continuation, mContextID);
// Static-vs-kinematics (bipartite) and kinematics-vs-kinematics (complete)
findAllOverlaps(
#ifdef ABP_MT2
mCompleteBoxPruningTask1,
mBipTasks[5],
mBipTasks[6],
mBipTasks[7],
mBipTasks[8],
mBipTasks[9],
#endif
mMM, mPairManager, mSBM, mKBM, doKineKine, doStaticKine, continuation, mContextID);
if(1)
{
findAllOverlaps(
#ifdef ABP_MT2
mCompleteBoxPruningTask1,
mBipTasks[10],
mBipTasks[11],
mBipTasks[12],
mBipTasks[13],
mBipTasks[14],
#endif
mMM, mPairManager, mKBM, mDBM, false, true, continuation, mContextID);
}
else
{
const PxU32 nbUpdatedDynamics = mDBM.getNbUpdatedBoxes();
const PxU32 nbNonUpdatedDynamics = mDBM.getNbNonUpdatedBoxes();
const PxU32 nbUpdatedKinematics = mKBM.getNbUpdatedBoxes();
const PxU32 nbNonUpdatedKinematics = mKBM.getNbNonUpdatedBoxes();
if(nbUpdatedDynamics)
{
// Active dynamics vs active kinematics
if(nbUpdatedKinematics)
{
doBipartiteBoxPruning_Leaf( &mPairManager,
nbUpdatedDynamics, nbUpdatedKinematics,
mDBM.getUpdatedBoxes(), mKBM.getUpdatedBoxes(),
mDBM.getRemap_Updated(), mKBM.getRemap_Updated());
}
// Active dynamics vs inactive kinematics
if(nbNonUpdatedKinematics)
{
doBipartiteBoxPruning_Leaf( &mPairManager,
nbUpdatedDynamics, nbNonUpdatedKinematics,
mDBM.getUpdatedBoxes(), mKBM.getSleepingBoxes(),
mDBM.getRemap_Updated(), mKBM.getRemap_Sleeping());
}
}
if(nbUpdatedKinematics && nbNonUpdatedDynamics)
{
// Inactive dynamics vs active kinematics
doBipartiteBoxPruning_Leaf( &mPairManager,
nbNonUpdatedDynamics, nbUpdatedKinematics,
mDBM.getSleepingBoxes(), mKBM.getUpdatedBoxes(),
mDBM.getRemap_Sleeping(), mKBM.getRemap_Updated());
}
}
}
PxU32 ABP::finalize(PxArray<BroadPhasePair>& createdPairs, PxArray<BroadPhasePair>& deletedPairs)
{
PX_PROFILE_ZONE("ABP - finalize", mContextID);
{
PX_PROFILE_ZONE("computeCreatedDeletedPairs", mContextID);
mPairManager.computeCreatedDeletedPairs(createdPairs, deletedPairs, mShared.mUpdatedObjects, mShared.mRemovedObjects);
}
mShared.mUpdatedObjects.clearAll();
return mPairManager.mNbActivePairs;
}
#ifdef ABP_MT2
void ABP::addDelayedPairs()
{
PX_PROFILE_ZONE("ABP - addDelayedPairs", mContextID);
mCompleteBoxPruningTask0.addDelayedPairs();
mCompleteBoxPruningTask1.addDelayedPairs();
PxU32 nbDelayedPairs = 0;
for(PxU32 k=0; k<NB_BIP_TASKS; k++)
nbDelayedPairs += mBipTasks[k].mPairs.mDelayedPairs.size();
if(nbDelayedPairs)
{
{
PX_PROFILE_ZONE("ABP - resizeForNewPairs", mContextID);
mPairManager.resizeForNewPairs(nbDelayedPairs);
}
for(PxU32 k=0; k<NB_BIP_TASKS; k++)
mPairManager.addDelayedPairs(mBipTasks[k].mPairs.mDelayedPairs);
}
}
void ABP::addDelayedPairs2(PxArray<BroadPhasePair>& createdPairs)
{
PX_PROFILE_ZONE("ABP - addDelayedPairs", mContextID);
mCompleteBoxPruningTask0.addDelayedPairs2(createdPairs);
mCompleteBoxPruningTask1.addDelayedPairs2(createdPairs);
PxU32 nbDelayedPairs = 0;
for(PxU32 k=0; k<NB_BIP_TASKS; k++)
nbDelayedPairs += mBipTasks[k].mPairs.mDelayedPairs.size();
if(nbDelayedPairs)
{
{
PX_PROFILE_ZONE("ABP - resizeForNewPairs", mContextID);
mPairManager.resizeForNewPairs(nbDelayedPairs);
}
for(PxU32 k=0; k<NB_BIP_TASKS; k++)
mPairManager.addDelayedPairs2(createdPairs, mBipTasks[k].mPairs.mDelayedPairs);
}
}
#endif
void ABP::reset()
{
mSBM.reset();
mDBM.reset();
mKBM.reset();
PX_DELETE_ARRAY(mShared.mABP_Objects);
mShared.mABP_Objects_Capacity = 0;
mPairManager.purge();
mShared.mUpdatedObjects.empty();
mShared.mRemovedObjects.empty();
}
// PT: TODO: is is really ok to use "transient" data in this function?
void ABP::shiftOrigin(const PxVec3& shift, const PxBounds3* /*boundsArray*/, const PxReal* /*contactDistances*/)
{
PX_UNUSED(shift); // PT: unused because the bounds were pre-shifted before calling this function
// PT: the AABB manager marks all objects as updated when we shift so the stuff below may not be necessary
}
void ABP::setTransientData(const PxBounds3* bounds, const PxReal* contactDistance)
{
mSBM.setSourceData(bounds, contactDistance);
mDBM.setSourceData(bounds, contactDistance);
mKBM.setSourceData(bounds, contactDistance);
}
///////////////////////////////////////////////////////////////////////////////
}
// Below is the PhysX wrapper = link between AABBManager and ABP
using namespace internalABP;
#define DEFAULT_CREATED_DELETED_PAIRS_CAPACITY 1024
BroadPhaseABP::BroadPhaseABP( PxU32 maxNbBroadPhaseOverlaps,
PxU32 maxNbStaticShapes,
PxU32 maxNbDynamicShapes,
PxU64 contextID,
bool enableMT) :
mNbAdded (0),
mNbUpdated (0),
mNbRemoved (0),
mCreatedHandles (NULL),
mUpdatedHandles (NULL),
mRemovedHandles (NULL),
mGroups (NULL),
mFilter (NULL),
mContextID (contextID),
mEnableMT (enableMT)
{
mABP = PX_NEW(ABP)(contextID);
const PxU32 nbObjects = maxNbStaticShapes + maxNbDynamicShapes;
mABP->preallocate(nbObjects, maxNbBroadPhaseOverlaps);
mCreated.reserve(DEFAULT_CREATED_DELETED_PAIRS_CAPACITY);
mDeleted.reserve(DEFAULT_CREATED_DELETED_PAIRS_CAPACITY);
}
BroadPhaseABP::~BroadPhaseABP()
{
PX_DELETE(mABP);
}
void BroadPhaseABP::update(PxcScratchAllocator* scratchAllocator, const BroadPhaseUpdateData& updateData, PxBaseTask* continuation)
{
PX_PROFILE_ZONE("BroadPhaseABP - update", mContextID);
PX_CHECK_AND_RETURN(scratchAllocator, "BroadPhaseABP::update - scratchAllocator must be non-NULL \n");
{
PX_PROFILE_ZONE("BroadPhaseABP - setup", mContextID);
mABP->mMM.mScratchAllocator = scratchAllocator;
mABP->setTransientData(updateData.getAABBs(), updateData.getContactDistance());
const PxU32 newCapacity = updateData.getCapacity();
mABP->mShared.checkResize(newCapacity);
#if PX_CHECKED
// PT: WARNING: this must be done after the allocateMappingArray call
if(!BroadPhaseUpdateData::isValid(updateData, *this, false, mContextID))
{
PX_CHECK_MSG(false, "Illegal BroadPhaseUpdateData \n");
return;
}
#endif
mGroups = updateData.getGroups();
mFilter = &updateData.getFilter();
mNbAdded = updateData.getNumCreatedHandles();
mNbUpdated = updateData.getNumUpdatedHandles();
mNbRemoved = updateData.getNumRemovedHandles();
mCreatedHandles = updateData.getCreatedHandles();
mUpdatedHandles = updateData.getUpdatedHandles();
mRemovedHandles = updateData.getRemovedHandles();
}
// PT: run single-threaded if forced to do so
if(!mEnableMT)
continuation = NULL;
#ifdef ABP_MT2
if(continuation)
{
mABP->mTask1.mBP = this;
mABP->mTask1.setContinuation(continuation);
mABP->mTask0.mBP = this;
mABP->mTask0.setContinuation(&mABP->mTask1);
mABP->mTask1.removeReference();
mABP->mTask0.removeReference();
}
else
#endif
{
{
PX_PROFILE_ZONE("BroadPhaseABP - setUpdateData", mContextID);
removeObjects();
addObjects();
updateObjects();
PX_ASSERT(!mCreated.size());
PX_ASSERT(!mDeleted.size());
if(gPrepareOverlapsFlag)
mABP->Region_prepareOverlaps();
}
{
PX_PROFILE_ZONE("BroadPhaseABP - update", mContextID);
mABP->findOverlaps(continuation, mGroups, mFilter->getLUT());
}
{
PX_PROFILE_ZONE("BroadPhaseABP - postUpdate", mContextID);
mABP->finalize(mCreated, mDeleted);
}
}
}
#ifdef ABP_MT2
void ABP_InternalTask::run()
{
PX_SIMD_GUARD
internalABP::ABP* abp = mBP->mABP;
if(mID==ABP_TASK_0)
{
{
PX_PROFILE_ZONE("ABP_InternalTask - setUpdateData", mContextID);
mBP->removeObjects();
mBP->addObjects();
mBP->updateObjects();
PX_ASSERT(!mBP->mCreated.size());
PX_ASSERT(!mBP->mDeleted.size());
if(gPrepareOverlapsFlag)
abp->Region_prepareOverlaps();
}
{
PX_PROFILE_ZONE("ABP_InternalTask - update", mContextID);
for(PxU32 k=0;k<9;k++)
{
abp->mCompleteBoxPruningTask0.mTasks[k].mPairs.mDelayedPairs.resetOrClear();
abp->mCompleteBoxPruningTask1.mTasks[k].mPairs.mDelayedPairs.resetOrClear();
}
for(PxU32 k=0;k<NB_BIP_TASKS;k++)
abp->mBipTasks[k].mPairs.mDelayedPairs.resetOrClear();
abp->findOverlaps(getContinuation(), mBP->mGroups, mBP->mFilter->getLUT());
}
}
else if(mID==ABP_TASK_1)
{
//abp->addDelayedPairs();
//abp->finalize(mBP->mCreated, mBP->mDeleted);
abp->finalize(mBP->mCreated, mBP->mDeleted);
abp->addDelayedPairs2(mBP->mCreated);
}
}
#endif
void BroadPhaseABP::removeObjects()
{
PX_PROFILE_ZONE("BroadPhaseABP - removeObjects", mContextID);
PxU32 nbRemoved = mNbRemoved;
const BpHandle* removed = mRemovedHandles;
if(!nbRemoved || !removed)
return;
while(nbRemoved--)
{
const BpHandle index = *removed++;
PX_ASSERT(index+1<mABP->mShared.mABP_Objects_Capacity); // PT: we allocated one more box on purpose
mABP->removeObject(index);
}
}
void BroadPhaseABP::updateObjects()
{
PX_PROFILE_ZONE("BroadPhaseABP - updateObjects", mContextID);
PxU32 nbUpdated = mNbUpdated;
const BpHandle* updated = mUpdatedHandles;
if(!nbUpdated || !updated)
return;
while(nbUpdated--)
{
const BpHandle index = *updated++;
PX_ASSERT(index+1<mABP->mShared.mABP_Objects_Capacity); // PT: we allocated one more box on purpose
mABP->updateObject(index);
}
}
void BroadPhaseABP::addObjects()
{
PX_PROFILE_ZONE("BroadPhaseABP - addObjects", mContextID);
PxU32 nbAdded = mNbAdded;
const BpHandle* created = mCreatedHandles;
if(!nbAdded || !created)
return;
const Bp::FilterGroup::Enum* PX_RESTRICT groups = mGroups;
struct Batch
{
PX_FORCE_INLINE Batch() : mNb(0), mMaxIndex(0) {}
PxU32 mNb;
PxU32 mMaxIndex;
BpHandle mIndices[ABP_BATCHING];
PX_FORCE_INLINE void add(const BpHandle index, internalABP::ABP* PX_RESTRICT abp, FilterType::Enum type)
{
PxU32 nb = mNb;
mMaxIndex = PxMax(mMaxIndex, index);
mIndices[nb++] = index;
if(nb==ABP_BATCHING)
{
mNb = 0;
// PT: TODO: we could use a function ptr here
if(type==FilterType::STATIC)
abp->addStaticObjects(mIndices, ABP_BATCHING, mMaxIndex);
else if(type==FilterType::KINEMATIC)
abp->addKinematicObjects(mIndices, ABP_BATCHING, mMaxIndex);
else
{
PX_ASSERT(type==FilterType::DYNAMIC || type==FilterType::AGGREGATE);
abp->addDynamicObjects(mIndices, ABP_BATCHING, mMaxIndex);
}
mMaxIndex = 0;
}
else
mNb = nb;
}
};
Batch statics;
Batch dynamics;
Batch kinematics;
Batch* batches[FilterType::COUNT] = {NULL};
batches[FilterType::STATIC] = &statics;
batches[FilterType::DYNAMIC] = &dynamics;
batches[FilterType::AGGREGATE] = &dynamics;
batches[FilterType::KINEMATIC] = &kinematics;
while(nbAdded--)
{
const BpHandle index = *created++;
PX_ASSERT(index+1<mABP->mShared.mABP_Objects_Capacity); // PT: we allocated one more box on purpose
FilterType::Enum type = FilterType::Enum(groups[index] & BP_FILTERING_TYPE_MASK);
if(!batches[type])
type = FilterType::DYNAMIC;
batches[type]->add(index, mABP, type);
}
if(statics.mNb)
mABP->addStaticObjects(statics.mIndices, statics.mNb, statics.mMaxIndex);
if(kinematics.mNb)
mABP->addKinematicObjects(kinematics.mIndices, kinematics.mNb, kinematics.mMaxIndex);
if(dynamics.mNb)
mABP->addDynamicObjects(dynamics.mIndices, dynamics.mNb, dynamics.mMaxIndex);
}
const BroadPhasePair* BroadPhaseABP::getCreatedPairs(PxU32& nbCreatedPairs) const
{
nbCreatedPairs = mCreated.size();
return mCreated.begin();
}
const BroadPhasePair* BroadPhaseABP::getDeletedPairs(PxU32& nbDeletedPairs) const
{
nbDeletedPairs = mDeleted.size();
return mDeleted.begin();
}
static void freeBuffer(PxArray<BroadPhasePair>& buffer)
{
const PxU32 size = buffer.size();
if(size>DEFAULT_CREATED_DELETED_PAIRS_CAPACITY)
{
buffer.reset();
buffer.reserve(DEFAULT_CREATED_DELETED_PAIRS_CAPACITY);
}
else
{
buffer.clear();
}
}
void BroadPhaseABP::freeBuffers()
{
PX_PROFILE_ZONE("BroadPhaseABP - freeBuffers", mContextID);
mABP->freeBuffers();
freeBuffer(mCreated);
freeBuffer(mDeleted);
}
#if PX_CHECKED
bool BroadPhaseABP::isValid(const BroadPhaseUpdateData& updateData) const
{
const PxU32 nbObjects = mABP->mShared.mABP_Objects_Capacity;
PX_UNUSED(nbObjects);
const ABP_Object* PX_RESTRICT objects = mABP->mShared.mABP_Objects;
const BpHandle* created = updateData.getCreatedHandles();
if(created)
{
PxU32 nbToGo = updateData.getNumCreatedHandles();
while(nbToGo--)
{
const BpHandle index = *created++;
PX_ASSERT(index<nbObjects);
if(objects[index].isValid())
return false; // This object has been added already
}
}
const BpHandle* updated = updateData.getUpdatedHandles();
if(updated)
{
PxU32 nbToGo = updateData.getNumUpdatedHandles();
while(nbToGo--)
{
const BpHandle index = *updated++;
PX_ASSERT(index<nbObjects);
if(!objects[index].isValid())
return false; // This object has been removed already, or never been added
}
}
const BpHandle* removed = updateData.getRemovedHandles();
if(removed)
{
PxU32 nbToGo = updateData.getNumRemovedHandles();
while(nbToGo--)
{
const BpHandle index = *removed++;
PX_ASSERT(index<nbObjects);
if(!objects[index].isValid())
return false; // This object has been removed already, or never been added
}
}
return true;
}
#endif
void BroadPhaseABP::shiftOrigin(const PxVec3& shift, const PxBounds3* boundsArray, const PxReal* contactDistances)
{
mABP->shiftOrigin(shift, boundsArray, contactDistances);
}
| 123,703 | C++ | 27.582255 | 186 | 0.690056 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevelaabb/src/BpAABBManagerBase.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 "BpAABBManagerBase.h"
#include "BpBroadPhase.h"
using namespace physx;
using namespace Bp;
AABBManagerBase::AABBManagerBase( BroadPhase& bp, BoundsArray& boundsArray, PxFloatArrayPinned& contactDistance,
PxU32 maxNbAggregates, PxU32 maxNbShapes, PxVirtualAllocator& allocator, PxU64 contextID,
PxPairFilteringMode::Enum kineKineFilteringMode, PxPairFilteringMode::Enum staticKineFilteringMode) :
mAddedHandleMap (allocator),
mRemovedHandleMap (allocator),
mChangedHandleMap (allocator),
mGroups (allocator),
mContactDistance (contactDistance),
mVolumeData (allocator),
mFilters (kineKineFilteringMode == PxPairFilteringMode::eKILL, staticKineFilteringMode == PxPairFilteringMode::eKILL),
mAddedHandles (allocator),
mUpdatedHandles (allocator),
mRemovedHandles (allocator),
mBroadPhase (bp),
mBoundsArray (boundsArray),
mUsedSize (0),
mNbAggregates (0),
#ifdef BP_USE_AGGREGATE_GROUP_TAIL
mAggregateGroupTide (PxU32(Bp::FilterGroup::eAGGREGATE_BASE)),
#endif
mContextID (contextID),
mOriginShifted (false)
{
PX_UNUSED(maxNbAggregates); // PT: TODO: use it or remove it
reserveShapeSpace(PxMax(maxNbShapes, 1u));
// mCreatedOverlaps.reserve(16000);
}
void AABBManagerBase::reserveShapeSpace(PxU32 nbTotalBounds)
{
nbTotalBounds = PxNextPowerOfTwo(nbTotalBounds);
mGroups.resize(nbTotalBounds, Bp::FilterGroup::eINVALID);
mVolumeData.resize(nbTotalBounds); //KS - must be initialized so that userData is NULL for SQ-only shapes
mContactDistance.resizeUninitialized(nbTotalBounds);
mAddedHandleMap.resize(nbTotalBounds);
mRemovedHandleMap.resize(nbTotalBounds);
}
void AABBManagerBase::reserveSpaceForBounds(BoundsIndex index)
{
if ((index + 1) >= mVolumeData.size())
reserveShapeSpace(index + 1);
resetEntry(index); //KS - make sure this entry is flagged as invalid
}
void AABBManagerBase::freeBuffers()
{
// PT: TODO: investigate if we need more stuff here
mBroadPhase.freeBuffers();
}
void AABBManagerBase::shiftOrigin(const PxVec3& shift)
{
mBroadPhase.shiftOrigin(shift, mBoundsArray.begin(), mContactDistance.begin());
mOriginShifted = true;
}
| 3,855 | C++ | 40.021276 | 122 | 0.769131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.