Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/StreamWrapper.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/StreamIn.h>
#include <Jolt/Core/StreamOut.h>
JPH_SUPPRESS_WARNINGS_STD_BEGIN
#include <ostream>
JPH_SUPPRESS_WARNINGS_STD_END
JPH_NAMESPACE_BEGIN
/// Wrapper around std::ostream
class StreamOutWrapper : public StreamOut
{
public:
/// Constructor
StreamOutWrapper(ostream &ioWrapped) : mWrapped(ioWrapped) { }
/// Write a string of bytes to the binary stream
virtual void WriteBytes(const void *inData, size_t inNumBytes) override { mWrapped.write((const char *)inData, inNumBytes); }
/// Returns true if there was an IO failure
virtual bool IsFailed() const override { return mWrapped.fail(); }
private:
ostream & mWrapped;
};
/// Wrapper around std::istream
class StreamInWrapper : public StreamIn
{
public:
/// Constructor
StreamInWrapper(istream &ioWrapped) : mWrapped(ioWrapped) { }
/// Write a string of bytes to the binary stream
virtual void ReadBytes(void *outData, size_t inNumBytes) override { mWrapped.read((char *)outData, inNumBytes); }
/// Returns true when an attempt has been made to read past the end of the file
virtual bool IsEOF() const override { return mWrapped.eof(); }
/// Returns true if there was an IO failure
virtual bool IsFailed() const override { return mWrapped.fail(); }
private:
istream & mWrapped;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/JobSystemWithBarrier.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2023 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/JobSystem.h>
#include <Jolt/Core/Semaphore.h>
JPH_NAMESPACE_BEGIN
/// Implementation of the Barrier class for a JobSystem
///
/// This class can be used to make it easier to create a new JobSystem implementation that integrates with your own job system.
/// It will implement all functionality relating to barriers, so the only functions that are left to be implemented are:
///
/// * JobSystem::GetMaxConcurrency
/// * JobSystem::CreateJob
/// * JobSystem::FreeJob
/// * JobSystem::QueueJob/QueueJobs
///
/// See instructions in JobSystem for more information on how to implement these.
class JobSystemWithBarrier : public JobSystem
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructs barriers
/// @see JobSystemWithBarrier::Init
explicit JobSystemWithBarrier(uint inMaxBarriers);
JobSystemWithBarrier() = default;
virtual ~JobSystemWithBarrier() override;
/// Initialize the barriers
/// @param inMaxBarriers Max number of barriers that can be allocated at any time
void Init(uint inMaxBarriers);
// See JobSystem
virtual Barrier * CreateBarrier() override;
virtual void DestroyBarrier(Barrier *inBarrier) override;
virtual void WaitForJobs(Barrier *inBarrier) override;
private:
class BarrierImpl : public Barrier
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
BarrierImpl();
virtual ~BarrierImpl() override;
// See Barrier
virtual void AddJob(const JobHandle &inJob) override;
virtual void AddJobs(const JobHandle *inHandles, uint inNumHandles) override;
/// Check if there are any jobs in the job barrier
inline bool IsEmpty() const { return mJobReadIndex == mJobWriteIndex; }
/// Wait for all jobs in this job barrier, while waiting, execute jobs that are part of this barrier on the current thread
void Wait();
/// Flag to indicate if a barrier has been handed out
atomic<bool> mInUse { false };
protected:
/// Called by a Job to mark that it is finished
virtual void OnJobFinished(Job *inJob) override;
/// Jobs queue for the barrier
static constexpr uint cMaxJobs = 2048;
static_assert(IsPowerOf2(cMaxJobs)); // We do bit operations and require max jobs to be a power of 2
atomic<Job *> mJobs[cMaxJobs]; ///< List of jobs that are part of this barrier, nullptrs for empty slots
alignas(JPH_CACHE_LINE_SIZE) atomic<uint> mJobReadIndex { 0 }; ///< First job that could be valid (modulo cMaxJobs), can be nullptr if other thread is still working on adding the job
alignas(JPH_CACHE_LINE_SIZE) atomic<uint> mJobWriteIndex { 0 }; ///< First job that can be written (modulo cMaxJobs)
atomic<int> mNumToAcquire { 0 }; ///< Number of times the semaphore has been released, the barrier should acquire the semaphore this many times (written at the same time as mJobWriteIndex so ok to put in same cache line)
Semaphore mSemaphore; ///< Semaphore used by finishing jobs to signal the barrier that they're done
};
/// Array of barriers (we keep them constructed all the time since constructing a semaphore/mutex is not cheap)
uint mMaxBarriers = 0; ///< Max amount of barriers
BarrierImpl * mBarriers = nullptr; ///< List of the actual barriers
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/ByteBuffer.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/STLAlignedAllocator.h>
JPH_NAMESPACE_BEGIN
/// Underlying data type for ByteBuffer
using ByteBufferVector = std::vector<uint8, STLAlignedAllocator<uint8, JPH_CACHE_LINE_SIZE>>;
/// Simple byte buffer, aligned to a cache line
class ByteBuffer : public ByteBufferVector
{
public:
/// Align the size to a multiple of inSize, returns the length after alignment
size_t Align(size_t inSize)
{
// Assert power of 2
JPH_ASSERT(IsPowerOf2(inSize));
// Calculate new size and resize buffer
size_t s = AlignUp(size(), inSize);
resize(s);
return s;
}
/// Allocate block of data of inSize elements and return the pointer
template <class Type>
Type * Allocate(size_t inSize = 1)
{
// Reserve space
size_t s = size();
resize(s + inSize * sizeof(Type));
// Get data pointer
Type *data = reinterpret_cast<Type *>(&at(s));
// Construct elements
for (Type *d = data, *d_end = data + inSize; d < d_end; ++d)
::new (d) Type;
// Return pointer
return data;
}
/// Append inData to the buffer
template <class Type>
void AppendVector(const Array<Type> &inData)
{
size_t size = inData.size() * sizeof(Type);
uint8 *data = Allocate<uint8>(size);
memcpy(data, &inData[0], size);
}
/// Get object at inPosition (an offset in bytes)
template <class Type>
const Type * Get(size_t inPosition) const
{
return reinterpret_cast<const Type *>(&at(inPosition));
}
/// Get object at inPosition (an offset in bytes)
template <class Type>
Type * Get(size_t inPosition)
{
return reinterpret_cast<Type *>(&at(inPosition));
}
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/HashCombine.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Implements the FNV-1a hash algorithm
/// @see https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
/// @param inData Data block of bytes
/// @param inSize Number of bytes
/// @param inSeed Seed of the hash (can be used to pass in the hash of a previous operation, otherwise leave default)
/// @return Hash
inline uint64 HashBytes(const void *inData, uint inSize, uint64 inSeed = 0xcbf29ce484222325UL)
{
uint64 hash = inSeed;
for (const uint8 *data = reinterpret_cast<const uint8 *>(inData); data < reinterpret_cast<const uint8 *>(inData) + inSize; ++data)
{
hash = hash ^ uint64(*data);
hash = hash * 0x100000001b3UL;
}
return hash;
}
/// A 64 bit hash function by Thomas Wang, Jan 1997
/// See: http://web.archive.org/web/20071223173210/http://www.concentric.net/~Ttwang/tech/inthash.htm
/// @param inValue Value to hash
/// @return Hash
inline uint64 Hash64(uint64 inValue)
{
uint64 hash = inValue;
hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
hash = hash ^ (hash >> 24);
hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
hash = hash ^ (hash >> 14);
hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
hash = hash ^ (hash >> 28);
hash = hash + (hash << 31);
return hash;
}
/// @brief Helper function that hashes a single value into ioSeed
/// Taken from: https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x
template <typename T>
inline void HashCombineHelper(size_t &ioSeed, const T &inValue)
{
std::hash<T> hasher;
ioSeed ^= hasher(inValue) + 0x9e3779b9 + (ioSeed << 6) + (ioSeed >> 2);
}
/// Hash combiner to use a custom struct in an unordered map or set
///
/// Usage:
///
/// struct SomeHashKey
/// {
/// std::string key1;
/// std::string key2;
/// bool key3;
/// };
///
/// JPH_MAKE_HASHABLE(SomeHashKey, t.key1, t.key2, t.key3)
template <typename... Values>
inline void HashCombine(std::size_t &ioSeed, Values... inValues)
{
// Hash all values together using a fold expression
(HashCombineHelper(ioSeed, inValues), ...);
}
JPH_NAMESPACE_END
JPH_SUPPRESS_WARNING_PUSH
JPH_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic")
#define JPH_MAKE_HASH_STRUCT(type, name, ...) \
struct [[nodiscard]] name \
{ \
std::size_t operator()(const type &t) const \
{ \
std::size_t ret = 0; \
::JPH::HashCombine(ret, __VA_ARGS__); \
return ret; \
} \
};
#define JPH_MAKE_HASHABLE(type, ...) \
JPH_SUPPRESS_WARNING_PUSH \
JPH_SUPPRESS_WARNINGS \
namespace std \
{ \
template<> \
JPH_MAKE_HASH_STRUCT(type, hash<type>, __VA_ARGS__) \
} \
JPH_SUPPRESS_WARNING_POP
JPH_SUPPRESS_WARNING_POP
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/InsertionSort.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2022 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Implementation of the insertion sort algorithm.
template <typename Iterator, typename Compare>
inline void InsertionSort(Iterator inBegin, Iterator inEnd, Compare inCompare)
{
// Empty arrays don't need to be sorted
if (inBegin != inEnd)
{
// Start at the second element
for (Iterator i = inBegin + 1; i != inEnd; ++i)
{
// Move this element to a temporary value
auto x = std::move(*i);
// Check if the element goes before inBegin (we can't decrement the iterator before inBegin so this needs to be a separate branch)
if (inCompare(x, *inBegin))
{
// Move all elements to the right to make space for x
Iterator prev;
for (Iterator j = i; j != inBegin; j = prev)
{
prev = j - 1;
*j = *prev;
}
// Move x to the first place
*inBegin = std::move(x);
}
else
{
// Move elements to the right as long as they are bigger than x
Iterator j = i;
for (Iterator prev = j - 1; inCompare(x, *prev); j = prev, --prev)
*j = std::move(*prev);
// Move x into place
*j = std::move(x);
}
}
}
}
/// Implementation of insertion sort algorithm without comparator.
template <typename Iterator>
inline void InsertionSort(Iterator inBegin, Iterator inEnd)
{
std::less<> compare;
InsertionSort(inBegin, inEnd, compare);
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/TempAllocator.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/NonCopyable.h>
JPH_NAMESPACE_BEGIN
/// Allocator for temporary allocations.
/// This allocator works as a stack: The blocks must always be freed in the reverse order as they are allocated.
/// Note that allocations and frees can take place from different threads, but the order is guaranteed though
/// job dependencies, so it is not needed to use any form of locking.
class TempAllocator : public NonCopyable
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Destructor
virtual ~TempAllocator() = default;
/// Allocates inSize bytes of memory, returned memory address must be JPH_RVECTOR_ALIGNMENT byte aligned
virtual void * Allocate(uint inSize) = 0;
/// Frees inSize bytes of memory located at inAddress
virtual void Free(void *inAddress, uint inSize) = 0;
};
/// Default implementation of the temp allocator that allocates a large block through malloc upfront
class TempAllocatorImpl final : public TempAllocator
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructs the allocator with a maximum allocatable size of inSize
explicit TempAllocatorImpl(uint inSize) :
mBase(static_cast<uint8 *>(AlignedAllocate(inSize, JPH_RVECTOR_ALIGNMENT))),
mSize(inSize)
{
}
/// Destructor, frees the block
virtual ~TempAllocatorImpl() override
{
JPH_ASSERT(mTop == 0);
AlignedFree(mBase);
}
// See: TempAllocator
virtual void * Allocate(uint inSize) override
{
if (inSize == 0)
{
return nullptr;
}
else
{
uint new_top = mTop + AlignUp(inSize, JPH_RVECTOR_ALIGNMENT);
if (new_top > mSize)
JPH_CRASH; // Out of memory
void *address = mBase + mTop;
mTop = new_top;
return address;
}
}
// See: TempAllocator
virtual void Free(void *inAddress, uint inSize) override
{
if (inAddress == nullptr)
{
JPH_ASSERT(inSize == 0);
}
else
{
mTop -= AlignUp(inSize, JPH_RVECTOR_ALIGNMENT);
if (mBase + mTop != inAddress)
JPH_CRASH; // Freeing in the wrong order
}
}
// Check if no allocations have been made
bool IsEmpty() const
{
return mTop == 0;
}
private:
uint8 * mBase; ///< Base address of the memory block
uint mSize; ///< Size of the memory block
uint mTop = 0; ///< Current top of the stack
};
/// Implementation of the TempAllocator that just falls back to malloc/free
/// Note: This can be quite slow when running in the debugger as large memory blocks need to be initialized with 0xcd
class TempAllocatorMalloc final : public TempAllocator
{
public:
JPH_OVERRIDE_NEW_DELETE
// See: TempAllocator
virtual void * Allocate(uint inSize) override
{
return AlignedAllocate(inSize, JPH_RVECTOR_ALIGNMENT);
}
// See: TempAllocator
virtual void Free(void *inAddress, uint inSize) override
{
AlignedFree(inAddress);
}
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/Result.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
// GCC doesn't properly detect that mState is used to ensure that mResult is initialized
JPH_GCC_SUPPRESS_WARNING("-Wmaybe-uninitialized")
/// Helper class that either contains a valid result or an error
template <class Type>
class Result
{
public:
/// Default constructor
Result() { }
/// Copy constructor
Result(const Result<Type> &inRHS) :
mState(inRHS.mState)
{
switch (inRHS.mState)
{
case EState::Valid:
::new (&mResult) Type (inRHS.mResult);
break;
case EState::Error:
::new (&mError) String(inRHS.mError);
break;
case EState::Invalid:
break;
}
}
/// Move constructor
Result(Result<Type> &&inRHS) noexcept :
mState(inRHS.mState)
{
switch (inRHS.mState)
{
case EState::Valid:
::new (&mResult) Type (std::move(inRHS.mResult));
break;
case EState::Error:
::new (&mError) String(std::move(inRHS.mError));
break;
case EState::Invalid:
break;
}
inRHS.mState = EState::Invalid;
}
/// Destructor
~Result() { Clear(); }
/// Copy assignment
Result<Type> & operator = (const Result<Type> &inRHS)
{
Clear();
mState = inRHS.mState;
switch (inRHS.mState)
{
case EState::Valid:
::new (&mResult) Type (inRHS.mResult);
break;
case EState::Error:
::new (&mError) String(inRHS.mError);
break;
case EState::Invalid:
break;
}
return *this;
}
/// Move assignment
Result<Type> & operator = (Result<Type> &&inRHS) noexcept
{
Clear();
mState = inRHS.mState;
switch (inRHS.mState)
{
case EState::Valid:
::new (&mResult) Type (std::move(inRHS.mResult));
break;
case EState::Error:
::new (&mError) String(std::move(inRHS.mError));
break;
case EState::Invalid:
break;
}
inRHS.mState = EState::Invalid;
return *this;
}
/// Clear result or error
void Clear()
{
switch (mState)
{
case EState::Valid:
mResult.~Type();
break;
case EState::Error:
mError.~String();
break;
case EState::Invalid:
break;
}
mState = EState::Invalid;
}
/// Checks if the result is still uninitialized
bool IsEmpty() const { return mState == EState::Invalid; }
/// Checks if the result is valid
bool IsValid() const { return mState == EState::Valid; }
/// Get the result value
const Type & Get() const { JPH_ASSERT(IsValid()); return mResult; }
/// Set the result value
void Set(const Type &inResult) { Clear(); ::new (&mResult) Type(inResult); mState = EState::Valid; }
/// Set the result value (move value)
void Set(const Type &&inResult) { Clear(); ::new (&mResult) Type(std::move(inResult)); mState = EState::Valid; }
/// Check if we had an error
bool HasError() const { return mState == EState::Error; }
/// Get the error value
const String & GetError() const { JPH_ASSERT(HasError()); return mError; }
/// Set an error value
void SetError(const char *inError) { Clear(); ::new (&mError) String(inError); mState = EState::Error; }
void SetError(const string_view &inError) { Clear(); ::new (&mError) String(inError); mState = EState::Error; }
void SetError(String &&inError) { Clear(); ::new (&mError) String(std::move(inError)); mState = EState::Error; }
private:
union
{
Type mResult; ///< The actual result object
String mError; ///< The error description if the result failed
};
/// State of the result
enum class EState : uint8
{
Invalid,
Valid,
Error
};
EState mState = EState::Invalid;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/StringTools.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Create a formatted text string for debugging purposes.
/// Note that this function has an internal buffer of 1024 characters, so long strings will be trimmed.
String StringFormat(const char *inFMT, ...);
/// Convert type to string
template<typename T>
String ConvertToString(const T &inValue)
{
using OStringStream = std::basic_ostringstream<char, std::char_traits<char>, STLAllocator<char>>;
OStringStream oss;
oss << inValue;
return oss.str();
}
/// Calculate the FNV-1a hash of inString.
/// @see https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
constexpr uint64 HashString(const char *inString)
{
uint64 hash = 14695981039346656037UL;
for (const char *c = inString; *c != 0; ++c)
{
hash ^= *c;
hash = hash * 1099511628211UL;
}
return hash;
}
/// Replace substring with other string
void StringReplace(String &ioString, const string_view &inSearch, const string_view &inReplace);
/// Convert a delimited string to an array of strings
void StringToVector(const string_view &inString, Array<String> &outVector, const string_view &inDelimiter = ",", bool inClearVector = true);
/// Convert an array strings to a delimited string
void VectorToString(const Array<String> &inVector, String &outString, const string_view &inDelimiter = ",");
/// Convert a string to lower case
String ToLower(const string_view &inString);
/// Converts the lower 4 bits of inNibble to a string that represents the number in binary format
const char *NibbleToBinary(uint32 inNibble);
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/RTTI.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Reference.h>
#include <Jolt/Core/StaticArray.h>
#include <Jolt/ObjectStream/SerializableAttribute.h>
JPH_NAMESPACE_BEGIN
//////////////////////////////////////////////////////////////////////////////////////////
// RTTI
//////////////////////////////////////////////////////////////////////////////////////////
/// Light weight runtime type information system. This way we don't need to turn
/// on the default RTTI system of the compiler (introducing a possible overhead for every
/// class)
///
/// Notes:
/// - An extra virtual member function is added. This adds 8 bytes to the size of
/// an instance of the class (unless you are already using virtual functions).
///
/// To use RTTI on a specific class use:
///
/// Header file:
///
/// class Foo
/// {
/// JPH_DECLARE_RTTI_VIRTUAL_BASE(Foo)
/// }
///
/// class Bar : public Foo
/// {
/// JPH_DECLARE_RTTI_VIRTUAL(Bar)
/// };
///
/// Implementation file:
///
/// JPH_IMPLEMENT_RTTI_VIRTUAL_BASE(Foo)
/// {
/// }
///
/// JPH_IMPLEMENT_RTTI_VIRTUAL(Bar)
/// {
/// JPH_ADD_BASE_CLASS(Bar, Foo) // Multiple inheritance is allowed, just do JPH_ADD_BASE_CLASS for every base class
/// }
///
/// For abstract classes use:
///
/// Header file:
///
/// class Foo
/// {
/// JPH_DECLARE_RTTI_ABSTRACT_BASE(Foo)
///
/// public:
/// virtual void AbstractFunction() = 0;
/// }
///
/// class Bar : public Foo
/// {
/// JPH_DECLARE_RTTI_VIRTUAL(Bar)
///
/// public:
/// virtual void AbstractFunction() { } // Function is now implemented so this class is no longer abstract
/// };
///
/// Implementation file:
///
/// JPH_IMPLEMENT_RTTI_ABSTRACT_BASE(Foo)
/// {
/// }
///
/// JPH_IMPLEMENT_RTTI_VIRTUAL(Bar)
/// {
/// JPH_ADD_BASE_CLASS(Bar, Foo)
/// }
///
/// Example of usage in a program:
///
/// Foo *foo_ptr = new Foo;
/// Foo *bar_ptr = new Bar;
///
/// IsType(foo_ptr, RTTI(Bar)) returns false
/// IsType(bar_ptr, RTTI(Bar)) returns true
///
/// IsKindOf(foo_ptr, RTTI(Bar)) returns false
/// IsKindOf(bar_ptr, RTTI(Foo)) returns true
/// IsKindOf(bar_ptr, RTTI(Bar)) returns true
///
/// StaticCast<Bar>(foo_ptr) asserts and returns foo_ptr casted to pBar
/// StaticCast<Bar>(bar_ptr) returns bar_ptr casted to pBar
///
/// DynamicCast<Bar>(foo_ptr) returns nullptr
/// DynamicCast<Bar>(bar_ptr) returns bar_ptr casted to pBar
///
/// Other feature of DynamicCast:
///
/// class A { int data[5]; };
/// class B { int data[7]; };
/// class C : public A, public B { int data[9]; };
///
/// C *c = new C;
/// A *a = c;
///
/// Note that:
///
/// B *b = (B *)a;
///
/// generates an invalid pointer,
///
/// B *b = StaticCast<B>(a);
///
/// doesn't compile, and
///
/// B *b = DynamicCast<B>(a);
///
/// does the correct cast
class RTTI
{
public:
/// Function to create an object
using pCreateObjectFunction = void *(*)();
/// Function to destroy an object
using pDestructObjectFunction = void (*)(void *inObject);
/// Function to initialize the runtime type info structure
using pCreateRTTIFunction = void (*)(RTTI &inRTTI);
/// Constructor
RTTI(const char *inName, int inSize, pCreateObjectFunction inCreateObject, pDestructObjectFunction inDestructObject);
RTTI(const char *inName, int inSize, pCreateObjectFunction inCreateObject, pDestructObjectFunction inDestructObject, pCreateRTTIFunction inCreateRTTI);
// Properties
inline const char * GetName() const { return mName; }
void SetName(const char *inName) { mName = inName; }
inline int GetSize() const { return mSize; }
bool IsAbstract() const { return mCreate == nullptr || mDestruct == nullptr; }
int GetBaseClassCount() const;
const RTTI * GetBaseClass(int inIdx) const;
uint32 GetHash() const;
/// Create an object of this type (returns nullptr if the object is abstract)
void * CreateObject() const;
/// Destruct object of this type (does nothing if the object is abstract)
void DestructObject(void *inObject) const;
/// Add base class
void AddBaseClass(const RTTI *inRTTI, int inOffset);
/// Equality operators
bool operator == (const RTTI &inRHS) const;
bool operator != (const RTTI &inRHS) const { return !(*this == inRHS); }
/// Test if this class is derived from class of type inRTTI
bool IsKindOf(const RTTI *inRTTI) const;
/// Cast inObject of this type to object of type inRTTI, returns nullptr if the cast is unsuccessful
const void * CastTo(const void *inObject, const RTTI *inRTTI) const;
/// Attribute access
void AddAttribute(const SerializableAttribute &inAttribute);
int GetAttributeCount() const;
const SerializableAttribute & GetAttribute(int inIdx) const;
protected:
/// Base class information
struct BaseClass
{
const RTTI * mRTTI;
int mOffset;
};
const char * mName; ///< Class name
int mSize; ///< Class size
StaticArray<BaseClass, 4> mBaseClasses; ///< Names of base classes
pCreateObjectFunction mCreate; ///< Pointer to a function that will create a new instance of this class
pDestructObjectFunction mDestruct; ///< Pointer to a function that will destruct an object of this class
StaticArray<SerializableAttribute, 32> mAttributes; ///< All attributes of this class
};
//////////////////////////////////////////////////////////////////////////////////////////
// Add run time type info to types that don't have virtual functions
//////////////////////////////////////////////////////////////////////////////////////////
// JPH_DECLARE_RTTI_NON_VIRTUAL
#define JPH_DECLARE_RTTI_NON_VIRTUAL(class_name) \
public: \
JPH_OVERRIDE_NEW_DELETE \
friend RTTI * GetRTTIOfType(class_name *); \
friend inline const RTTI * GetRTTI(const class_name *inObject) { return GetRTTIOfType((class_name *)nullptr); }\
static void sCreateRTTI(RTTI &inRTTI); \
// JPH_IMPLEMENT_RTTI_NON_VIRTUAL
#define JPH_IMPLEMENT_RTTI_NON_VIRTUAL(class_name) \
RTTI * GetRTTIOfType(class_name *) \
{ \
static RTTI rtti(#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \
return &rtti; \
} \
void class_name::sCreateRTTI(RTTI &inRTTI) \
//////////////////////////////////////////////////////////////////////////////////////////
// Same as above, but when you cannot insert the declaration in the class
// itself, for example for templates and third party classes
//////////////////////////////////////////////////////////////////////////////////////////
// JPH_DECLARE_RTTI_OUTSIDE_CLASS
#define JPH_DECLARE_RTTI_OUTSIDE_CLASS(class_name) \
RTTI * GetRTTIOfType(class_name *); \
inline const RTTI * GetRTTI(const class_name *inObject) { return GetRTTIOfType((class_name *)nullptr); }\
void CreateRTTI##class_name(RTTI &inRTTI); \
// JPH_IMPLEMENT_RTTI_OUTSIDE_CLASS
#define JPH_IMPLEMENT_RTTI_OUTSIDE_CLASS(class_name) \
RTTI * GetRTTIOfType(class_name *) \
{ \
static RTTI rtti((const char *)#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &CreateRTTI##class_name); \
return &rtti; \
} \
void CreateRTTI##class_name(RTTI &inRTTI)
//////////////////////////////////////////////////////////////////////////////////////////
// Same as above, but for classes that have virtual functions
//////////////////////////////////////////////////////////////////////////////////////////
#define JPH_DECLARE_RTTI_HELPER(class_name, modifier) \
public: \
JPH_OVERRIDE_NEW_DELETE \
friend RTTI * GetRTTIOfType(class_name *); \
friend inline const RTTI * GetRTTI(const class_name *inObject) { return inObject->GetRTTI(); } \
virtual const RTTI * GetRTTI() const modifier; \
virtual const void * CastTo(const RTTI *inRTTI) const modifier; \
static void sCreateRTTI(RTTI &inRTTI); \
// JPH_DECLARE_RTTI_VIRTUAL - for derived classes with RTTI
#define JPH_DECLARE_RTTI_VIRTUAL(class_name) \
JPH_DECLARE_RTTI_HELPER(class_name, override)
// JPH_IMPLEMENT_RTTI_VIRTUAL
#define JPH_IMPLEMENT_RTTI_VIRTUAL(class_name) \
RTTI * GetRTTIOfType(class_name *) \
{ \
static RTTI rtti(#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \
return &rtti; \
} \
const RTTI * class_name::GetRTTI() const \
{ \
return JPH_RTTI(class_name); \
} \
const void * class_name::CastTo(const RTTI *inRTTI) const \
{ \
return JPH_RTTI(class_name)->CastTo((const void *)this, inRTTI); \
} \
void class_name::sCreateRTTI(RTTI &inRTTI) \
// JPH_DECLARE_RTTI_VIRTUAL_BASE - for concrete base class that has RTTI
#define JPH_DECLARE_RTTI_VIRTUAL_BASE(class_name) \
JPH_DECLARE_RTTI_HELPER(class_name, )
// JPH_IMPLEMENT_RTTI_VIRTUAL_BASE
#define JPH_IMPLEMENT_RTTI_VIRTUAL_BASE(class_name) \
JPH_IMPLEMENT_RTTI_VIRTUAL(class_name)
// JPH_DECLARE_RTTI_ABSTRACT - for derived abstract class that have RTTI
#define JPH_DECLARE_RTTI_ABSTRACT(class_name) \
JPH_DECLARE_RTTI_HELPER(class_name, override)
// JPH_IMPLEMENT_RTTI_ABSTRACT
#define JPH_IMPLEMENT_RTTI_ABSTRACT(class_name) \
RTTI * GetRTTIOfType(class_name *) \
{ \
static RTTI rtti(#class_name, sizeof(class_name), nullptr, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \
return &rtti; \
} \
const RTTI * class_name::GetRTTI() const \
{ \
return JPH_RTTI(class_name); \
} \
const void * class_name::CastTo(const RTTI *inRTTI) const \
{ \
return JPH_RTTI(class_name)->CastTo((const void *)this, inRTTI); \
} \
void class_name::sCreateRTTI(RTTI &inRTTI) \
// JPH_DECLARE_RTTI_ABSTRACT_BASE - for abstract base class that has RTTI
#define JPH_DECLARE_RTTI_ABSTRACT_BASE(class_name) \
JPH_DECLARE_RTTI_HELPER(class_name, )
// JPH_IMPLEMENT_RTTI_ABSTRACT_BASE
#define JPH_IMPLEMENT_RTTI_ABSTRACT_BASE(class_name) \
JPH_IMPLEMENT_RTTI_ABSTRACT(class_name)
//////////////////////////////////////////////////////////////////////////////////////////
// Declare an RTTI class for registering with the factory
//////////////////////////////////////////////////////////////////////////////////////////
#define JPH_DECLARE_RTTI_FOR_FACTORY(class_name) \
RTTI * GetRTTIOfType(class class_name *);
#define JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(name_space, class_name) \
namespace name_space { \
class class_name; \
RTTI * GetRTTIOfType(class class_name *); \
}
//////////////////////////////////////////////////////////////////////////////////////////
// Find the RTTI of a class
//////////////////////////////////////////////////////////////////////////////////////////
#define JPH_RTTI(class_name) GetRTTIOfType((class_name *)nullptr)
//////////////////////////////////////////////////////////////////////////////////////////
// Macro to rename a class, useful for embedded classes:
//
// class A { class B { }; }
//
// Now use JPH_RENAME_CLASS(B, A::B) to avoid conflicts with other classes named B
//////////////////////////////////////////////////////////////////////////////////////////
// JPH_RENAME_CLASS
#define JPH_RENAME_CLASS(class_name, new_name) \
inRTTI.SetName(#new_name);
//////////////////////////////////////////////////////////////////////////////////////////
// Macro to add base classes
//////////////////////////////////////////////////////////////////////////////////////////
/// Define very dirty macro to get the offset of a baseclass into a class
#define JPH_BASE_CLASS_OFFSET(inClass, inBaseClass) ((int(uint64((inBaseClass *)((inClass *)0x10000))))-0x10000)
// JPH_ADD_BASE_CLASS
#define JPH_ADD_BASE_CLASS(class_name, base_class_name) \
inRTTI.AddBaseClass(JPH_RTTI(base_class_name), JPH_BASE_CLASS_OFFSET(class_name, base_class_name));
//////////////////////////////////////////////////////////////////////////////////////////
// Macros and templates to identify a class
//////////////////////////////////////////////////////////////////////////////////////////
/// Check if inObject is of DstType
template <class Type>
inline bool IsType(const Type *inObject, const RTTI *inRTTI)
{
return inObject == nullptr || *inObject->GetRTTI() == *inRTTI;
}
template <class Type>
inline bool IsType(const RefConst<Type> &inObject, const RTTI *inRTTI)
{
return inObject == nullptr || *inObject->GetRTTI() == *inRTTI;
}
template <class Type>
inline bool IsType(const Ref<Type> &inObject, const RTTI *inRTTI)
{
return inObject == nullptr || *inObject->GetRTTI() == *inRTTI;
}
/// Check if inObject is or is derived from DstType
template <class Type>
inline bool IsKindOf(const Type *inObject, const RTTI *inRTTI)
{
return inObject == nullptr || inObject->GetRTTI()->IsKindOf(inRTTI);
}
template <class Type>
inline bool IsKindOf(const RefConst<Type> &inObject, const RTTI *inRTTI)
{
return inObject == nullptr || inObject->GetRTTI()->IsKindOf(inRTTI);
}
template <class Type>
inline bool IsKindOf(const Ref<Type> &inObject, const RTTI *inRTTI)
{
return inObject == nullptr || inObject->GetRTTI()->IsKindOf(inRTTI);
}
/// Cast inObject to DstType, asserts on failure
template <class DstType, class SrcType>
inline const DstType *StaticCast(const SrcType *inObject)
{
JPH_ASSERT(IsKindOf(inObject, JPH_RTTI(DstType)), "Invalid cast");
return static_cast<const DstType *>(inObject);
}
template <class DstType, class SrcType>
inline DstType *StaticCast(SrcType *inObject)
{
JPH_ASSERT(IsKindOf(inObject, JPH_RTTI(DstType)), "Invalid cast");
return static_cast<DstType *>(inObject);
}
template <class DstType, class SrcType>
inline RefConst<DstType> StaticCast(RefConst<SrcType> &inObject)
{
JPH_ASSERT(IsKindOf(inObject, JPH_RTTI(DstType)), "Invalid cast");
return static_cast<const DstType *>(inObject.GetPtr());
}
template <class DstType, class SrcType>
inline Ref<DstType> StaticCast(Ref<SrcType> &inObject)
{
JPH_ASSERT(IsKindOf(inObject, JPH_RTTI(DstType)), "Invalid cast");
return static_cast<DstType *>(inObject.GetPtr());
}
/// Cast inObject to DstType, returns nullptr on failure
template <class DstType, class SrcType>
inline const DstType *DynamicCast(const SrcType *inObject)
{
return inObject != nullptr? reinterpret_cast<const DstType *>(inObject->CastTo(JPH_RTTI(DstType))) : nullptr;
}
template <class DstType, class SrcType>
inline DstType *DynamicCast(SrcType *inObject)
{
return inObject != nullptr? const_cast<DstType *>(reinterpret_cast<const DstType *>(inObject->CastTo(JPH_RTTI(DstType)))) : nullptr;
}
template <class DstType, class SrcType>
inline RefConst<DstType> DynamicCast(RefConst<SrcType> &inObject)
{
return inObject != nullptr? reinterpret_cast<const DstType *>(inObject->CastTo(JPH_RTTI(DstType))) : nullptr;
}
template <class DstType, class SrcType>
inline Ref<DstType> DynamicCast(Ref<SrcType> &inObject)
{
return inObject != nullptr? const_cast<DstType *>(reinterpret_cast<const DstType *>(inObject->CastTo(JPH_RTTI(DstType)))) : nullptr;
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/Mutex.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Profiler.h>
#include <Jolt/Core/NonCopyable.h>
JPH_SUPPRESS_WARNINGS_STD_BEGIN
#include <mutex>
#include <shared_mutex>
#include <thread>
JPH_SUPPRESS_WARNINGS_STD_END
JPH_NAMESPACE_BEGIN
// Things we're using from STL
using std::mutex;
using std::shared_mutex;
using std::thread;
using std::lock_guard;
using std::shared_lock;
using std::unique_lock;
#ifdef JPH_PLATFORM_BLUE
// On Platform Blue the mutex class is not very fast so we implement it using the official APIs
class MutexBase : public NonCopyable
{
public:
MutexBase()
{
JPH_PLATFORM_BLUE_MUTEX_INIT(mMutex);
}
~MutexBase()
{
JPH_PLATFORM_BLUE_MUTEX_DESTROY(mMutex);
}
inline bool try_lock()
{
return JPH_PLATFORM_BLUE_MUTEX_TRYLOCK(mMutex);
}
inline void lock()
{
JPH_PLATFORM_BLUE_MUTEX_LOCK(mMutex);
}
inline void unlock()
{
JPH_PLATFORM_BLUE_MUTEX_UNLOCK(mMutex);
}
private:
JPH_PLATFORM_BLUE_MUTEX mMutex;
};
// On Platform Blue the shared_mutex class is not very fast so we implement it using the official APIs
class SharedMutexBase : public NonCopyable
{
public:
SharedMutexBase()
{
JPH_PLATFORM_BLUE_RWLOCK_INIT(mRWLock);
}
~SharedMutexBase()
{
JPH_PLATFORM_BLUE_RWLOCK_DESTROY(mRWLock);
}
inline bool try_lock()
{
return JPH_PLATFORM_BLUE_RWLOCK_TRYWLOCK(mRWLock);
}
inline bool try_lock_shared()
{
return JPH_PLATFORM_BLUE_RWLOCK_TRYRLOCK(mRWLock);
}
inline void lock()
{
JPH_PLATFORM_BLUE_RWLOCK_WLOCK(mRWLock);
}
inline void unlock()
{
JPH_PLATFORM_BLUE_RWLOCK_WUNLOCK(mRWLock);
}
inline void lock_shared()
{
JPH_PLATFORM_BLUE_RWLOCK_RLOCK(mRWLock);
}
inline void unlock_shared()
{
JPH_PLATFORM_BLUE_RWLOCK_RUNLOCK(mRWLock);
}
private:
JPH_PLATFORM_BLUE_RWLOCK mRWLock;
};
#else
// On other platforms just use the STL implementation
using MutexBase = mutex;
using SharedMutexBase = shared_mutex;
#endif // JPH_PLATFORM_BLUE
#if defined(JPH_ENABLE_ASSERTS) || defined(JPH_PROFILE_ENABLED) || defined(JPH_EXTERNAL_PROFILE)
/// Very simple wrapper around MutexBase which tracks lock contention in the profiler
/// and asserts that locks/unlocks take place on the same thread
class Mutex : public MutexBase
{
public:
inline bool try_lock()
{
JPH_ASSERT(mLockedThreadID != std::this_thread::get_id());
if (MutexBase::try_lock())
{
JPH_IF_ENABLE_ASSERTS(mLockedThreadID = std::this_thread::get_id();)
return true;
}
return false;
}
inline void lock()
{
if (!try_lock())
{
JPH_PROFILE("Lock", 0xff00ffff);
MutexBase::lock();
JPH_IF_ENABLE_ASSERTS(mLockedThreadID = std::this_thread::get_id();)
}
}
inline void unlock()
{
JPH_ASSERT(mLockedThreadID == std::this_thread::get_id());
JPH_IF_ENABLE_ASSERTS(mLockedThreadID = thread::id();)
MutexBase::unlock();
}
#ifdef JPH_ENABLE_ASSERTS
inline bool is_locked()
{
return mLockedThreadID != thread::id();
}
#endif // JPH_ENABLE_ASSERTS
private:
JPH_IF_ENABLE_ASSERTS(thread::id mLockedThreadID;)
};
/// Very simple wrapper around SharedMutexBase which tracks lock contention in the profiler
/// and asserts that locks/unlocks take place on the same thread
class SharedMutex : public SharedMutexBase
{
public:
inline bool try_lock()
{
JPH_ASSERT(mLockedThreadID != std::this_thread::get_id());
if (SharedMutexBase::try_lock())
{
JPH_IF_ENABLE_ASSERTS(mLockedThreadID = std::this_thread::get_id();)
return true;
}
return false;
}
inline void lock()
{
if (!try_lock())
{
JPH_PROFILE("WLock", 0xff00ffff);
SharedMutexBase::lock();
JPH_IF_ENABLE_ASSERTS(mLockedThreadID = std::this_thread::get_id();)
}
}
inline void unlock()
{
JPH_ASSERT(mLockedThreadID == std::this_thread::get_id());
JPH_IF_ENABLE_ASSERTS(mLockedThreadID = thread::id();)
SharedMutexBase::unlock();
}
#ifdef JPH_ENABLE_ASSERTS
inline bool is_locked()
{
return mLockedThreadID != thread::id();
}
#endif // JPH_ENABLE_ASSERTS
inline void lock_shared()
{
if (!try_lock_shared())
{
JPH_PROFILE("RLock", 0xff00ffff);
SharedMutexBase::lock_shared();
}
}
private:
JPH_IF_ENABLE_ASSERTS(thread::id mLockedThreadID;)
};
#else
using Mutex = MutexBase;
using SharedMutex = SharedMutexBase;
#endif
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/JobSystemThreadPool.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/JobSystemWithBarrier.h>
#include <Jolt/Core/FixedSizeFreeList.h>
#include <Jolt/Core/Semaphore.h>
JPH_SUPPRESS_WARNINGS_STD_BEGIN
#include <thread>
JPH_SUPPRESS_WARNINGS_STD_END
JPH_NAMESPACE_BEGIN
// Things we're using from STL
using std::thread;
/// Implementation of a JobSystem using a thread pool
///
/// Note that this is considered an example implementation. It is expected that when you integrate
/// the physics engine into your own project that you'll provide your own implementation of the
/// JobSystem built on top of whatever job system your project uses.
class JobSystemThreadPool final : public JobSystemWithBarrier
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Creates a thread pool.
/// @see JobSystemThreadPool::Init
JobSystemThreadPool(uint inMaxJobs, uint inMaxBarriers, int inNumThreads = -1);
JobSystemThreadPool() = default;
virtual ~JobSystemThreadPool() override;
/// Initialize the thread pool
/// @param inMaxJobs Max number of jobs that can be allocated at any time
/// @param inMaxBarriers Max number of barriers that can be allocated at any time
/// @param inNumThreads Number of threads to start (the number of concurrent jobs is 1 more because the main thread will also run jobs while waiting for a barrier to complete). Use -1 to autodetect the amount of CPU's.
void Init(uint inMaxJobs, uint inMaxBarriers, int inNumThreads = -1);
// See JobSystem
virtual int GetMaxConcurrency() const override { return int(mThreads.size()) + 1; }
virtual JobHandle CreateJob(const char *inName, ColorArg inColor, const JobFunction &inJobFunction, uint32 inNumDependencies = 0) override;
/// Change the max concurrency after initialization
void SetNumThreads(int inNumThreads) { StopThreads(); StartThreads(inNumThreads); }
protected:
// See JobSystem
virtual void QueueJob(Job *inJob) override;
virtual void QueueJobs(Job **inJobs, uint inNumJobs) override;
virtual void FreeJob(Job *inJob) override;
private:
/// Start/stop the worker threads
void StartThreads(int inNumThreads);
void StopThreads();
/// Entry point for a thread
void ThreadMain(int inThreadIndex);
/// Get the head of the thread that has processed the least amount of jobs
inline uint GetHead() const;
/// Internal helper function to queue a job
inline void QueueJobInternal(Job *inJob);
/// Array of jobs (fixed size)
using AvailableJobs = FixedSizeFreeList<Job>;
AvailableJobs mJobs;
/// Threads running jobs
Array<thread> mThreads;
// The job queue
static constexpr uint32 cQueueLength = 1024;
static_assert(IsPowerOf2(cQueueLength)); // We do bit operations and require queue length to be a power of 2
atomic<Job *> mQueue[cQueueLength];
// Head and tail of the queue, do this value modulo cQueueLength - 1 to get the element in the mQueue array
atomic<uint> * mHeads = nullptr; ///< Per executing thread the head of the current queue
alignas(JPH_CACHE_LINE_SIZE) atomic<uint> mTail = 0; ///< Tail (write end) of the queue
// Semaphore used to signal worker threads that there is new work
Semaphore mSemaphore;
/// Boolean to indicate that we want to stop the job system
atomic<bool> mQuit = false;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/STLTempAllocator.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/TempAllocator.h>
JPH_NAMESPACE_BEGIN
/// STL allocator that wraps around TempAllocator
template <typename T>
class STLTempAllocator
{
public:
using value_type = T;
/// Pointer to type
using pointer = T *;
using const_pointer = const T *;
/// Reference to type.
/// Can be removed in C++20.
using reference = T &;
using const_reference = const T &;
using size_type = size_t;
using difference_type = ptrdiff_t;
/// Constructor
inline STLTempAllocator(TempAllocator &inAllocator) : mAllocator(inAllocator) { }
/// Constructor from other allocator
template <typename T2>
inline explicit STLTempAllocator(const STLTempAllocator<T2> &inRHS) : mAllocator(inRHS.GetAllocator()) { }
/// Allocate memory
inline pointer allocate(size_type inN)
{
return (pointer)mAllocator.Allocate(uint(inN * sizeof(value_type)));
}
/// Free memory
inline void deallocate(pointer inPointer, size_type inN)
{
mAllocator.Free(inPointer, uint(inN * sizeof(value_type)));
}
/// Allocators are stateless so assumed to be equal
inline bool operator == (const STLTempAllocator<T> &) const
{
return true;
}
inline bool operator != (const STLTempAllocator<T> &) const
{
return false;
}
/// Converting to allocator for other type
template <typename T2>
struct rebind
{
using other = STLTempAllocator<T2>;
};
/// Get our temp allocator
TempAllocator & GetAllocator() const
{
return mAllocator;
}
private:
TempAllocator & mAllocator;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/STLAllocator.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
#ifndef JPH_DISABLE_CUSTOM_ALLOCATOR
/// STL allocator that forwards to our allocation functions
template <typename T>
class STLAllocator
{
public:
using value_type = T;
/// Pointer to type
using pointer = T *;
using const_pointer = const T *;
/// Reference to type.
/// Can be removed in C++20.
using reference = T &;
using const_reference = const T &;
using size_type = size_t;
using difference_type = ptrdiff_t;
/// Constructor
inline STLAllocator() = default;
/// Constructor from other allocator
template <typename T2>
inline STLAllocator(const STLAllocator<T2> &) { }
/// Allocate memory
inline pointer allocate(size_type inN)
{
if constexpr (alignof(T) > (JPH_CPU_ADDRESS_BITS == 32? 8 : 16))
return (pointer)AlignedAllocate(inN * sizeof(value_type), alignof(T));
else
return (pointer)Allocate(inN * sizeof(value_type));
}
/// Free memory
inline void deallocate(pointer inPointer, size_type)
{
if constexpr (alignof(T) > (JPH_CPU_ADDRESS_BITS == 32? 8 : 16))
AlignedFree(inPointer);
else
Free(inPointer);
}
/// Allocators are stateless so assumed to be equal
inline bool operator == (const STLAllocator<T> &) const
{
return true;
}
inline bool operator != (const STLAllocator<T> &) const
{
return false;
}
/// Converting to allocator for other type
template <typename T2>
struct rebind
{
using other = STLAllocator<T2>;
};
};
#else
template <typename T> using STLAllocator = std::allocator<T>;
#endif // !JPH_DISABLE_CUSTOM_ALLOCATOR
// Declare STL containers that use our allocator
template <class T> using Array = std::vector<T, STLAllocator<T>>;
using String = std::basic_string<char, std::char_traits<char>, STLAllocator<char>>;
using IStringStream = std::basic_istringstream<char, std::char_traits<char>, STLAllocator<char>>;
JPH_NAMESPACE_END
#if (!defined(JPH_PLATFORM_WINDOWS) || defined(JPH_COMPILER_MINGW)) && !defined(JPH_DISABLE_CUSTOM_ALLOCATOR)
namespace std
{
/// Declare std::hash for String, for some reason on Linux based platforms template deduction takes the wrong variant
template <>
struct hash<JPH::String>
{
inline size_t operator () (const JPH::String &inRHS) const
{
return hash<string_view> { } (inRHS);
}
};
}
#endif // (!JPH_PLATFORM_WINDOWS || JPH_COMPILER_MINGW) && !JPH_DISABLE_CUSTOM_ALLOCATOR
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/STLAlignedAllocator.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// STL allocator that takes care that memory is aligned to N bytes
template <typename T, size_t N>
class STLAlignedAllocator
{
public:
using value_type = T;
/// Pointer to type
using pointer = T *;
using const_pointer = const T *;
/// Reference to type.
/// Can be removed in C++20.
using reference = T &;
using const_reference = const T &;
using size_type = size_t;
using difference_type = ptrdiff_t;
/// Constructor
inline STLAlignedAllocator() = default;
/// Constructor from other allocator
template <typename T2>
inline explicit STLAlignedAllocator(const STLAlignedAllocator<T2, N> &) { }
/// Allocate memory
inline pointer allocate(size_type inN)
{
return (pointer)AlignedAllocate(inN * sizeof(value_type), N);
}
/// Free memory
inline void deallocate(pointer inPointer, size_type)
{
AlignedFree(inPointer);
}
/// Allocators are stateless so assumed to be equal
inline bool operator == (const STLAlignedAllocator<T, N> &) const
{
return true;
}
inline bool operator != (const STLAlignedAllocator<T, N> &) const
{
return false;
}
/// Converting to allocator for other type
template <typename T2>
struct rebind
{
using other = STLAlignedAllocator<T2, N>;
};
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/LinearCurve.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/ObjectStream/SerializableObject.h>
#include <Jolt/Core/QuickSort.h>
JPH_NAMESPACE_BEGIN
class StreamOut;
class StreamIn;
// A set of points (x, y) that form a linear curve
class LinearCurve
{
public:
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(LinearCurve)
/// A point on the curve
class Point
{
public:
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(Point)
float mX = 0.0f;
float mY = 0.0f;
};
/// Remove all points
void Clear() { mPoints.clear(); }
/// Reserve memory for inNumPoints points
void Reserve(uint inNumPoints) { mPoints.reserve(inNumPoints); }
/// Add a point to the curve. Points must be inserted in ascending X or Sort() needs to be called when all points have been added.
/// @param inX X value
/// @param inY Y value
void AddPoint(float inX, float inY) { mPoints.push_back({ inX, inY }); }
/// Sort the points on X ascending
void Sort() { QuickSort(mPoints.begin(), mPoints.end(), [](const Point &inLHS, const Point &inRHS) { return inLHS.mX < inRHS.mX; }); }
/// Get the lowest X value
float GetMinX() const { return mPoints.empty()? 0.0f : mPoints.front().mX; }
/// Get the highest X value
float GetMaxX() const { return mPoints.empty()? 0.0f : mPoints.back().mX; }
/// Sample value on the curve
/// @param inX X value to sample at
/// @return Interpolated Y value
float GetValue(float inX) const;
/// Saves the state of this object in binary form to inStream.
void SaveBinaryState(StreamOut &inStream) const;
/// Restore the state of this object from inStream.
void RestoreBinaryState(StreamIn &inStream);
/// The points on the curve, should be sorted ascending by x
using Points = Array<Point>;
Points mPoints;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/StreamIn.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Simple binary input stream
class StreamIn
{
public:
/// Virtual destructor
virtual ~StreamIn() = default;
/// Read a string of bytes from the binary stream
virtual void ReadBytes(void *outData, size_t inNumBytes) = 0;
/// Returns true when an attempt has been made to read past the end of the file
virtual bool IsEOF() const = 0;
/// Returns true if there was an IO failure
virtual bool IsFailed() const = 0;
/// Read a primitive (e.g. float, int, etc.) from the binary stream
template <class T>
void Read(T &outT)
{
ReadBytes(&outT, sizeof(outT));
}
/// Read a vector of primitives from the binary stream
template <class T, class A>
void Read(std::vector<T, A> &outT)
{
typename Array<T>::size_type len = outT.size(); // Initialize to previous array size, this is used for validation in the StateRecorder class
Read(len);
if (!IsEOF() && !IsFailed())
{
outT.resize(len);
for (typename Array<T>::size_type i = 0; i < len; ++i)
Read(outT[i]);
}
else
outT.clear();
}
/// Read a string from the binary stream (reads the number of characters and then the characters)
template <class Type, class Traits, class Allocator>
void Read(std::basic_string<Type, Traits, Allocator> &outString)
{
typename std::basic_string<Type, Traits, Allocator>::size_type len = 0;
Read(len);
if (!IsEOF() && !IsFailed())
{
outString.resize(len);
ReadBytes(outString.data(), len * sizeof(Type));
}
else
outString.clear();
}
/// Read a Vec3 (don't read W)
void Read(Vec3 &outVec)
{
ReadBytes(&outVec, 3 * sizeof(float));
outVec = Vec3::sFixW(outVec.mValue);
}
/// Read a DVec3 (don't read W)
void Read(DVec3 &outVec)
{
ReadBytes(&outVec, 3 * sizeof(double));
outVec = DVec3::sFixW(outVec.mValue);
}
/// Read a DMat44 (don't read W component of translation)
void Read(DMat44 &outVec)
{
Vec4 x, y, z;
Read(x);
Read(y);
Read(z);
DVec3 t;
Read(t);
outVec = DMat44(x, y, z, t);
}
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/Profiler.inl | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
JPH_NAMESPACE_BEGIN
//////////////////////////////////////////////////////////////////////////////////////////
// ProfileThread
//////////////////////////////////////////////////////////////////////////////////////////
ProfileThread::ProfileThread(const string_view &inThreadName) :
mThreadName(inThreadName)
{
Profiler::sInstance->AddThread(this);
}
ProfileThread::~ProfileThread()
{
Profiler::sInstance->RemoveThread(this);
}
//////////////////////////////////////////////////////////////////////////////////////////
// ProfileMeasurement
//////////////////////////////////////////////////////////////////////////////////////////
ProfileMeasurement::ProfileMeasurement(const char *inName, uint32 inColor)
{
if (ProfileThread::sInstance == nullptr)
{
// Thread not instrumented
mSample = nullptr;
}
else if (ProfileThread::sInstance->mCurrentSample < ProfileThread::cMaxSamples)
{
// Get pointer to write data to
mSample = &ProfileThread::sInstance->mSamples[ProfileThread::sInstance->mCurrentSample++];
// Start constructing sample (will end up on stack)
mTemp.mName = inName;
mTemp.mColor = inColor;
// Collect start sample last
mTemp.mStartCycle = GetProcessorTickCount();
}
else
{
// Out of samples
if (!sOutOfSamplesReported)
{
Trace("ProfileMeasurement: Too many samples, some data will be lost!");
sOutOfSamplesReported = true;
}
mSample = nullptr;
}
}
ProfileMeasurement::~ProfileMeasurement()
{
if (mSample != nullptr)
{
// Finalize sample
mTemp.mEndCycle = GetProcessorTickCount();
// Write it to the memory buffer bypassing the cache
static_assert(sizeof(ProfileSample) == 32, "Assume 32 bytes");
static_assert(alignof(ProfileSample) == 16, "Assume 16 byte alignment");
#if defined(JPH_USE_SSE)
const __m128i *src = reinterpret_cast<const __m128i *>(&mTemp);
__m128i *dst = reinterpret_cast<__m128i *>(mSample);
__m128i val = _mm_loadu_si128(src);
_mm_stream_si128(dst, val);
val = _mm_loadu_si128(src + 1);
_mm_stream_si128(dst + 1, val);
#elif defined(JPH_USE_NEON)
const int *src = reinterpret_cast<const int *>(&mTemp);
int *dst = reinterpret_cast<int *>(mSample);
int32x4_t val = vld1q_s32(src);
vst1q_s32(dst, val);
val = vld1q_s32(src + 4);
vst1q_s32(dst + 4, val);
#else
memcpy(mSample, &mTemp, sizeof(ProfileSample));
#endif
mSample = nullptr;
}
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/IssueReporting.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Trace function, needs to be overridden by application. This should output a line of text to the log / TTY.
using TraceFunction = void (*)(const char *inFMT, ...);
extern TraceFunction Trace;
// Always turn on asserts in Debug mode
#if defined(_DEBUG) && !defined(JPH_ENABLE_ASSERTS)
#define JPH_ENABLE_ASSERTS
#endif
#ifdef JPH_ENABLE_ASSERTS
/// Function called when an assertion fails. This function should return true if a breakpoint needs to be triggered
using AssertFailedFunction = bool(*)(const char *inExpression, const char *inMessage, const char *inFile, uint inLine);
extern AssertFailedFunction AssertFailed;
// Helper functions to pass message on to failed function
struct AssertLastParam { };
inline bool AssertFailedParamHelper(const char *inExpression, const char *inFile, uint inLine, AssertLastParam) { return AssertFailed(inExpression, nullptr, inFile, inLine); }
inline bool AssertFailedParamHelper(const char *inExpression, const char *inFile, uint inLine, const char *inMessage, AssertLastParam) { return AssertFailed(inExpression, inMessage, inFile, inLine); }
/// Main assert macro, usage: JPH_ASSERT(condition, message) or JPH_ASSERT(condition)
#define JPH_ASSERT(inExpression, ...) do { if (!(inExpression) && AssertFailedParamHelper(#inExpression, __FILE__, uint(__LINE__), ##__VA_ARGS__, AssertLastParam())) JPH_BREAKPOINT; } while (false)
#define JPH_IF_ENABLE_ASSERTS(...) __VA_ARGS__
#else
#define JPH_ASSERT(...) ((void)0)
#define JPH_IF_ENABLE_ASSERTS(...)
#endif // JPH_ENABLE_ASSERTS
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/Reference.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Atomics.h>
JPH_NAMESPACE_BEGIN
// Forward declares
template <class T> class Ref;
template <class T> class RefConst;
/// Simple class to facilitate reference counting / releasing
/// Derive your class from RefTarget and you can reference it by using Ref<classname> or RefConst<classname>
///
/// Reference counting classes keep an integer which indicates how many references
/// to the object are active. Reference counting objects are derived from RefTarget
/// and staT & their life with a reference count of zero. They can then be assigned
/// to equivalents of pointers (Ref) which will increase the reference count immediately.
/// If the destructor of Ref is called or another object is assigned to the reference
/// counting pointer it will decrease the reference count of the object again. If this
/// reference count becomes zero, the object is destroyed.
///
/// This provides a very powerful mechanism to prevent memory leaks, but also gives
/// some responsibility to the programmer. The most notable point is that you cannot
/// have one object reference another and have the other reference the first one
/// back, because this way the reference count of both objects will never become
/// lower than 1, resulting in a memory leak. By carefully designing your classses
/// (and particularly identifying who owns who in the class hierarchy) you can avoid
/// these problems.
template <class T>
class RefTarget
{
public:
/// Constructor
inline RefTarget() = default;
inline RefTarget(const RefTarget &) { /* Do not copy refcount */ }
inline ~RefTarget() { JPH_IF_ENABLE_ASSERTS(uint32 value = mRefCount.load(memory_order_relaxed);) JPH_ASSERT(value == 0 || value == cEmbedded); } ///< assert no one is referencing us
/// Mark this class as embedded, this means the type can be used in a compound or constructed on the stack.
/// The Release function will never destruct the object, it is assumed the destructor will be called by whoever allocated
/// the object and at that point in time it is checked that no references are left to the structure.
inline void SetEmbedded() const { JPH_IF_ENABLE_ASSERTS(uint32 old = ) mRefCount.fetch_add(cEmbedded, memory_order_relaxed); JPH_ASSERT(old < cEmbedded); }
/// Assignment operator
inline RefTarget & operator = (const RefTarget &) { /* Don't copy refcount */ return *this; }
/// Get current refcount of this object
uint32 GetRefCount() const { return mRefCount.load(memory_order_relaxed); }
/// Add or release a reference to this object
inline void AddRef() const
{
// Adding a reference can use relaxed memory ordering
mRefCount.fetch_add(1, memory_order_relaxed);
}
inline void Release() const
{
// Releasing a reference must use release semantics...
if (mRefCount.fetch_sub(1, memory_order_release) == 1)
{
// ... so that we can use aquire to ensure that we see any updates from other threads that released a ref before deleting the object
atomic_thread_fence(memory_order_acquire);
delete static_cast<const T *>(this);
}
}
/// INTERNAL HELPER FUNCTION USED BY SERIALIZATION
static int sInternalGetRefCountOffset() { return offsetof(T, mRefCount); }
protected:
static constexpr uint32 cEmbedded = 0x0ebedded; ///< A large value that gets added to the refcount to mark the object as embedded
mutable atomic<uint32> mRefCount = 0; ///< Current reference count
};
/// Pure virtual version of RefTarget
class RefTargetVirtual
{
public:
/// Virtual destructor
virtual ~RefTargetVirtual() = default;
/// Virtual add reference
virtual void AddRef() = 0;
/// Virtual release reference
virtual void Release() = 0;
};
/// Class for automatic referencing, this is the equivalent of a pointer to type T
/// if you assign a value to this class it will increment the reference count by one
/// of this object, and if you assign something else it will decrease the reference
/// count of the first object again. If it reaches a reference count of zero it will
/// be deleted
template <class T>
class Ref
{
public:
/// Constructor
inline Ref() : mPtr(nullptr) { }
inline Ref(T *inRHS) : mPtr(inRHS) { AddRef(); }
inline Ref(const Ref<T> &inRHS) : mPtr(inRHS.mPtr) { AddRef(); }
inline Ref(Ref<T> &&inRHS) noexcept : mPtr(inRHS.mPtr) { inRHS.mPtr = nullptr; }
inline ~Ref() { Release(); }
/// Assignment operators
inline Ref<T> & operator = (T *inRHS) { if (mPtr != inRHS) { Release(); mPtr = inRHS; AddRef(); } return *this; }
inline Ref<T> & operator = (const Ref<T> &inRHS) { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; AddRef(); } return *this; }
inline Ref<T> & operator = (Ref<T> &&inRHS) noexcept { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; inRHS.mPtr = nullptr; } return *this; }
/// Casting operators
inline operator T * const () const { return mPtr; }
inline operator T *() { return mPtr; }
/// Access like a normal pointer
inline T * const operator -> () const { return mPtr; }
inline T * operator -> () { return mPtr; }
inline T & operator * () const { return *mPtr; }
/// Comparison
inline bool operator == (const T * inRHS) const { return mPtr == inRHS; }
inline bool operator == (const Ref<T> &inRHS) const { return mPtr == inRHS.mPtr; }
inline bool operator != (const T * inRHS) const { return mPtr != inRHS; }
inline bool operator != (const Ref<T> &inRHS) const { return mPtr != inRHS.mPtr; }
/// Get pointer
inline T * GetPtr() const { return mPtr; }
inline T * GetPtr() { return mPtr; }
/// INTERNAL HELPER FUNCTION USED BY SERIALIZATION
void ** InternalGetPointer() { return reinterpret_cast<void **>(&mPtr); }
private:
template <class T2> friend class RefConst;
/// Use "variable = nullptr;" to release an object, do not call these functions
inline void AddRef() { if (mPtr != nullptr) mPtr->AddRef(); }
inline void Release() { if (mPtr != nullptr) mPtr->Release(); }
T * mPtr; ///< Pointer to object that we are reference counting
};
/// Class for automatic referencing, this is the equivalent of a CONST pointer to type T
/// if you assign a value to this class it will increment the reference count by one
/// of this object, and if you assign something else it will decrease the reference
/// count of the first object again. If it reaches a reference count of zero it will
/// be deleted
template <class T>
class RefConst
{
public:
/// Constructor
inline RefConst() : mPtr(nullptr) { }
inline RefConst(const T * inRHS) : mPtr(inRHS) { AddRef(); }
inline RefConst(const RefConst<T> &inRHS) : mPtr(inRHS.mPtr) { AddRef(); }
inline RefConst(RefConst<T> &&inRHS) noexcept : mPtr(inRHS.mPtr) { inRHS.mPtr = nullptr; }
inline RefConst(const Ref<T> &inRHS) : mPtr(inRHS.mPtr) { AddRef(); }
inline RefConst(Ref<T> &&inRHS) noexcept : mPtr(inRHS.mPtr) { inRHS.mPtr = nullptr; }
inline ~RefConst() { Release(); }
/// Assignment operators
inline RefConst<T> & operator = (const T * inRHS) { if (mPtr != inRHS) { Release(); mPtr = inRHS; AddRef(); } return *this; }
inline RefConst<T> & operator = (const RefConst<T> &inRHS) { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; AddRef(); } return *this; }
inline RefConst<T> & operator = (RefConst<T> &&inRHS) noexcept { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; inRHS.mPtr = nullptr; } return *this; }
inline RefConst<T> & operator = (const Ref<T> &inRHS) { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; AddRef(); } return *this; }
inline RefConst<T> & operator = (Ref<T> &&inRHS) noexcept { if (mPtr != inRHS.mPtr) { Release(); mPtr = inRHS.mPtr; inRHS.mPtr = nullptr; } return *this; }
/// Casting operators
inline operator const T * () const { return mPtr; }
/// Access like a normal pointer
inline const T * operator -> () const { return mPtr; }
inline const T & operator * () const { return *mPtr; }
/// Comparison
inline bool operator == (const T * inRHS) const { return mPtr == inRHS; }
inline bool operator == (const RefConst<T> &inRHS) const { return mPtr == inRHS.mPtr; }
inline bool operator == (const Ref<T> &inRHS) const { return mPtr == inRHS.mPtr; }
inline bool operator != (const T * inRHS) const { return mPtr != inRHS; }
inline bool operator != (const RefConst<T> &inRHS) const { return mPtr != inRHS.mPtr; }
inline bool operator != (const Ref<T> &inRHS) const { return mPtr != inRHS.mPtr; }
/// Get pointer
inline const T * GetPtr() const { return mPtr; }
/// INTERNAL HELPER FUNCTION USED BY SERIALIZATION
void ** InternalGetPointer() { return const_cast<void **>(reinterpret_cast<const void **>(&mPtr)); }
private:
/// Use "variable = nullptr;" to release an object, do not call these functions
inline void AddRef() { if (mPtr != nullptr) mPtr->AddRef(); }
inline void Release() { if (mPtr != nullptr) mPtr->Release(); }
const T * mPtr; ///< Pointer to object that we are reference counting
};
JPH_NAMESPACE_END
JPH_SUPPRESS_WARNING_PUSH
JPH_CLANG_SUPPRESS_WARNING("-Wc++98-compat")
namespace std
{
/// Declare std::hash for Ref
template <class T>
struct hash<JPH::Ref<T>>
{
size_t operator () (const JPH::Ref<T> &inRHS) const
{
return hash<T *> { }(inRHS.GetPtr());
}
};
/// Declare std::hash for RefConst
template <class T>
struct hash<JPH::RefConst<T>>
{
size_t operator () (const JPH::RefConst<T> &inRHS) const
{
return hash<const T *> { }(inRHS.GetPtr());
}
};
}
JPH_SUPPRESS_WARNING_POP
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/ARMNeon.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2022 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#ifdef JPH_USE_NEON
#ifdef JPH_COMPILER_MSVC
JPH_NAMESPACE_BEGIN
// Constructing NEON values
#define JPH_NEON_INT32x4(v1, v2, v3, v4) { int64_t(v1) + (int64_t(v2) << 32), int64_t(v3) + (int64_t(v4) << 32) }
#define JPH_NEON_UINT32x4(v1, v2, v3, v4) { uint64_t(v1) + (uint64_t(v2) << 32), uint64_t(v3) + (uint64_t(v4) << 32) }
#define JPH_NEON_INT8x16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { int64_t(v1) + (int64_t(v2) << 8) + (int64_t(v3) << 16) + (int64_t(v4) << 24) + (int64_t(v5) << 32) + (int64_t(v6) << 40) + (int64_t(v7) << 48) + (int64_t(v8) << 56), int64_t(v9) + (int64_t(v10) << 8) + (int64_t(v11) << 16) + (int64_t(v12) << 24) + (int64_t(v13) << 32) + (int64_t(v14) << 40) + (int64_t(v15) << 48) + (int64_t(v16) << 56) }
// Generic shuffle vector template
template <unsigned I1, unsigned I2, unsigned I3, unsigned I4>
JPH_INLINE float32x4_t NeonShuffleFloat32x4(float32x4_t inV1, float32x4_t inV2)
{
float32x4_t ret;
ret = vmovq_n_f32(vgetq_lane_f32(I1 >= 4? inV2 : inV1, I1 & 0b11));
ret = vsetq_lane_f32(vgetq_lane_f32(I2 >= 4? inV2 : inV1, I2 & 0b11), ret, 1);
ret = vsetq_lane_f32(vgetq_lane_f32(I3 >= 4? inV2 : inV1, I3 & 0b11), ret, 2);
ret = vsetq_lane_f32(vgetq_lane_f32(I4 >= 4? inV2 : inV1, I4 & 0b11), ret, 3);
return ret;
}
// Specializations
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 2, 2>(float32x4_t inV1, float32x4_t inV2)
{
return vcombine_f32(vget_low_f32(inV1), vdup_lane_s32(vget_high_f32(inV1), 0));
}
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 3, 3>(float32x4_t inV1, float32x4_t inV2)
{
return vcombine_f32(vget_low_f32(inV1), vdup_lane_s32(vget_high_f32(inV1), 1));
}
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 2, 3>(float32x4_t inV1, float32x4_t inV2)
{
return inV1;
}
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 0, 3, 2>(float32x4_t inV1, float32x4_t inV2)
{
return vcombine_f32(vrev64_f32(vget_low_f32(inV1)), vrev64_f32(vget_high_f32(inV1)));
}
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 2, 1, 0>(float32x4_t inV1, float32x4_t inV2)
{
return vcombine_f32(vdup_lane_s32(vget_high_f32(inV1), 0), vrev64_f32(vget_low_f32(inV1)));
}
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 3, 0, 1>(float32x4_t inV1, float32x4_t inV2)
{
return vcombine_f32(vget_high_f32(inV1), vget_low_f32(inV1));
}
// Used extensively by cross product
template <>
JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 0, 0>(float32x4_t inV1, float32x4_t inV2)
{
static int8x16_t table = JPH_NEON_INT8x16(0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03);
return vreinterpretq_f32_u8(vqtbl1q_u8(vreinterpretq_u8_f32(inV1), table));
}
// Shuffle a vector
#define JPH_NEON_SHUFFLE_F32x4(vec1, vec2, index1, index2, index3, index4) NeonShuffleFloat32x4<index1, index2, index3, index4>(vec1, vec2)
JPH_NAMESPACE_END
#else
// Constructing NEON values
#define JPH_NEON_INT32x4(v1, v2, v3, v4) { v1, v2, v3, v4 }
#define JPH_NEON_UINT32x4(v1, v2, v3, v4) { v1, v2, v3, v4 }
#define JPH_NEON_INT8x16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16 }
// Shuffle a vector
#define JPH_NEON_SHUFFLE_F32x4(vec1, vec2, index1, index2, index3, index4) __builtin_shufflevector(vec1, vec2, index1, index2, index3, index4)
#endif
#endif // JPH_USE_NEON
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/NonCopyable.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Class that makes another class non-copyable. Usage: Inherit from NonCopyable.
class NonCopyable
{
public:
NonCopyable() = default;
NonCopyable(const NonCopyable &) = delete;
void operator = (const NonCopyable &) = delete;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/FixedSizeFreeList.inl | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
JPH_NAMESPACE_BEGIN
template <typename Object>
FixedSizeFreeList<Object>::~FixedSizeFreeList()
{
// Check if we got our Init call
if (mPages != nullptr)
{
// Ensure everything is freed before the freelist is destructed
JPH_ASSERT(mNumFreeObjects.load(memory_order_relaxed) == mNumPages * mPageSize);
// Free memory for pages
uint32 num_pages = mNumObjectsAllocated / mPageSize;
for (uint32 page = 0; page < num_pages; ++page)
AlignedFree(mPages[page]);
Free(mPages);
}
}
template <typename Object>
void FixedSizeFreeList<Object>::Init(uint inMaxObjects, uint inPageSize)
{
// Check sanity
JPH_ASSERT(inPageSize > 0 && IsPowerOf2(inPageSize));
JPH_ASSERT(mPages == nullptr);
// Store configuration parameters
mNumPages = (inMaxObjects + inPageSize - 1) / inPageSize;
mPageSize = inPageSize;
mPageShift = CountTrailingZeros(inPageSize);
mObjectMask = inPageSize - 1;
JPH_IF_ENABLE_ASSERTS(mNumFreeObjects = mNumPages * inPageSize;)
// Allocate page table
mPages = reinterpret_cast<ObjectStorage **>(Allocate(mNumPages * sizeof(ObjectStorage *)));
// We didn't yet use any objects of any page
mNumObjectsAllocated = 0;
mFirstFreeObjectInNewPage = 0;
// Start with 1 as the first tag
mAllocationTag = 1;
// Set first free object (with tag 0)
mFirstFreeObjectAndTag = cInvalidObjectIndex;
}
template <typename Object>
template <typename... Parameters>
uint32 FixedSizeFreeList<Object>::ConstructObject(Parameters &&... inParameters)
{
for (;;)
{
// Get first object from the linked list
uint64 first_free_object_and_tag = mFirstFreeObjectAndTag.load(memory_order_acquire);
uint32 first_free = uint32(first_free_object_and_tag);
if (first_free == cInvalidObjectIndex)
{
// The free list is empty, we take an object from the page that has never been used before
first_free = mFirstFreeObjectInNewPage.fetch_add(1, memory_order_relaxed);
if (first_free >= mNumObjectsAllocated)
{
// Allocate new page
lock_guard lock(mPageMutex);
while (first_free >= mNumObjectsAllocated)
{
uint32 next_page = mNumObjectsAllocated / mPageSize;
if (next_page == mNumPages)
return cInvalidObjectIndex; // Out of space!
mPages[next_page] = reinterpret_cast<ObjectStorage *>(AlignedAllocate(mPageSize * sizeof(ObjectStorage), max<size_t>(alignof(ObjectStorage), JPH_CACHE_LINE_SIZE)));
mNumObjectsAllocated += mPageSize;
}
}
// Allocation successful
JPH_IF_ENABLE_ASSERTS(mNumFreeObjects.fetch_sub(1, memory_order_relaxed);)
ObjectStorage &storage = GetStorage(first_free);
::new (&storage.mObject) Object(std::forward<Parameters>(inParameters)...);
storage.mNextFreeObject.store(first_free, memory_order_release);
return first_free;
}
else
{
// Load next pointer
uint32 new_first_free = GetStorage(first_free).mNextFreeObject.load(memory_order_acquire);
// Construct a new first free object tag
uint64 new_first_free_object_and_tag = uint64(new_first_free) + (uint64(mAllocationTag.fetch_add(1, memory_order_relaxed)) << 32);
// Compare and swap
if (mFirstFreeObjectAndTag.compare_exchange_weak(first_free_object_and_tag, new_first_free_object_and_tag, memory_order_release))
{
// Allocation successful
JPH_IF_ENABLE_ASSERTS(mNumFreeObjects.fetch_sub(1, memory_order_relaxed);)
ObjectStorage &storage = GetStorage(first_free);
::new (&storage.mObject) Object(std::forward<Parameters>(inParameters)...);
storage.mNextFreeObject.store(first_free, memory_order_release);
return first_free;
}
}
}
}
template <typename Object>
void FixedSizeFreeList<Object>::AddObjectToBatch(Batch &ioBatch, uint32 inObjectIndex)
{
JPH_ASSERT(GetStorage(inObjectIndex).mNextFreeObject.load(memory_order_relaxed) == inObjectIndex, "Trying to add a object to the batch that is already in a free list");
JPH_ASSERT(ioBatch.mNumObjects != uint32(-1), "Trying to reuse a batch that has already been freed");
// Link object in batch to free
if (ioBatch.mFirstObjectIndex == cInvalidObjectIndex)
ioBatch.mFirstObjectIndex = inObjectIndex;
else
GetStorage(ioBatch.mLastObjectIndex).mNextFreeObject.store(inObjectIndex, memory_order_release);
ioBatch.mLastObjectIndex = inObjectIndex;
ioBatch.mNumObjects++;
}
template <typename Object>
void FixedSizeFreeList<Object>::DestructObjectBatch(Batch &ioBatch)
{
if (ioBatch.mFirstObjectIndex != cInvalidObjectIndex)
{
// Call destructors
if constexpr (!is_trivially_destructible<Object>())
{
uint32 object_idx = ioBatch.mFirstObjectIndex;
do
{
ObjectStorage &storage = GetStorage(object_idx);
storage.mObject.~Object();
object_idx = storage.mNextFreeObject.load(memory_order_relaxed);
}
while (object_idx != cInvalidObjectIndex);
}
// Add to objects free list
ObjectStorage &storage = GetStorage(ioBatch.mLastObjectIndex);
for (;;)
{
// Get first object from the list
uint64 first_free_object_and_tag = mFirstFreeObjectAndTag.load(memory_order_acquire);
uint32 first_free = uint32(first_free_object_and_tag);
// Make it the next pointer of the last object in the batch that is to be freed
storage.mNextFreeObject.store(first_free, memory_order_release);
// Construct a new first free object tag
uint64 new_first_free_object_and_tag = uint64(ioBatch.mFirstObjectIndex) + (uint64(mAllocationTag.fetch_add(1, memory_order_relaxed)) << 32);
// Compare and swap
if (mFirstFreeObjectAndTag.compare_exchange_weak(first_free_object_and_tag, new_first_free_object_and_tag, memory_order_release))
{
// Free successful
JPH_IF_ENABLE_ASSERTS(mNumFreeObjects.fetch_add(ioBatch.mNumObjects, memory_order_relaxed);)
// Mark the batch as freed
#ifdef JPH_ENABLE_ASSERTS
ioBatch.mNumObjects = uint32(-1);
#endif
return;
}
}
}
}
template <typename Object>
void FixedSizeFreeList<Object>::DestructObject(uint32 inObjectIndex)
{
JPH_ASSERT(inObjectIndex != cInvalidObjectIndex);
// Call destructor
ObjectStorage &storage = GetStorage(inObjectIndex);
storage.mObject.~Object();
// Add to object free list
for (;;)
{
// Get first object from the list
uint64 first_free_object_and_tag = mFirstFreeObjectAndTag.load(memory_order_acquire);
uint32 first_free = uint32(first_free_object_and_tag);
// Make it the next pointer of the last object in the batch that is to be freed
storage.mNextFreeObject.store(first_free, memory_order_release);
// Construct a new first free object tag
uint64 new_first_free_object_and_tag = uint64(inObjectIndex) + (uint64(mAllocationTag.fetch_add(1, memory_order_relaxed)) << 32);
// Compare and swap
if (mFirstFreeObjectAndTag.compare_exchange_weak(first_free_object_and_tag, new_first_free_object_and_tag, memory_order_release))
{
// Free successful
JPH_IF_ENABLE_ASSERTS(mNumFreeObjects.fetch_add(1, memory_order_relaxed);)
return;
}
}
}
template<typename Object>
inline void FixedSizeFreeList<Object>::DestructObject(Object *inObject)
{
uint32 index = reinterpret_cast<ObjectStorage *>(inObject)->mNextFreeObject.load(memory_order_relaxed);
JPH_ASSERT(index < mNumObjectsAllocated);
DestructObject(index);
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/FixedSizeFreeList.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/NonCopyable.h>
#include <Jolt/Core/Mutex.h>
#include <Jolt/Core/Atomics.h>
JPH_NAMESPACE_BEGIN
/// Class that allows lock free creation / destruction of objects (unless a new page of objects needs to be allocated)
/// It contains a fixed pool of objects and also allows batching up a lot of objects to be destroyed
/// and doing the actual free in a single atomic operation
template <typename Object>
class FixedSizeFreeList : public NonCopyable
{
private:
/// Storage type for an Object
struct ObjectStorage
{
/// The object we're storing
Object mObject;
/// When the object is freed (or in the process of being freed as a batch) this will contain the next free object
/// When an object is in use it will contain the object's index in the free list
atomic<uint32> mNextFreeObject;
};
static_assert(alignof(ObjectStorage) == alignof(Object), "Object not properly aligned");
/// Access the object storage given the object index
const ObjectStorage & GetStorage(uint32 inObjectIndex) const { return mPages[inObjectIndex >> mPageShift][inObjectIndex & mObjectMask]; }
ObjectStorage & GetStorage(uint32 inObjectIndex) { return mPages[inObjectIndex >> mPageShift][inObjectIndex & mObjectMask]; }
/// Number of objects that we currently have in the free list / new pages
#ifdef JPH_ENABLE_ASSERTS
atomic<uint32> mNumFreeObjects;
#endif // JPH_ENABLE_ASSERTS
/// Simple counter that makes the first free object pointer update with every CAS so that we don't suffer from the ABA problem
atomic<uint32> mAllocationTag;
/// Index of first free object, the first 32 bits of an object are used to point to the next free object
atomic<uint64> mFirstFreeObjectAndTag;
/// Size (in objects) of a single page
uint32 mPageSize;
/// Number of bits to shift an object index to the right to get the page number
uint32 mPageShift;
/// Mask to and an object index with to get the page number
uint32 mObjectMask;
/// Total number of pages that are usable
uint32 mNumPages;
/// Total number of objects that have been allocated
uint32 mNumObjectsAllocated;
/// The first free object to use when the free list is empty (may need to allocate a new page)
atomic<uint32> mFirstFreeObjectInNewPage;
/// Array of pages of objects
ObjectStorage ** mPages = nullptr;
/// Mutex that is used to allocate a new page if the storage runs out
Mutex mPageMutex;
public:
/// Invalid index
static const uint32 cInvalidObjectIndex = 0xffffffff;
/// Size of an object + bookkeeping for the freelist
static const int ObjectStorageSize = sizeof(ObjectStorage);
/// Destructor
inline ~FixedSizeFreeList();
/// Initialize the free list, up to inMaxObjects can be allocated
inline void Init(uint inMaxObjects, uint inPageSize);
/// Lockless construct a new object, inParameters are passed on to the constructor
template <typename... Parameters>
inline uint32 ConstructObject(Parameters &&... inParameters);
/// Lockless destruct an object and return it to the free pool
inline void DestructObject(uint32 inObjectIndex);
/// Lockless destruct an object and return it to the free pool
inline void DestructObject(Object *inObject);
/// A batch of objects that can be destructed
struct Batch
{
uint32 mFirstObjectIndex = cInvalidObjectIndex;
uint32 mLastObjectIndex = cInvalidObjectIndex;
uint32 mNumObjects = 0;
};
/// Add a object to an existing batch to be destructed.
/// Adding objects to a batch does not destroy or modify the objects, this will merely link them
/// so that the entire batch can be returned to the free list in a single atomic operation
inline void AddObjectToBatch(Batch &ioBatch, uint32 inObjectIndex);
/// Lockless destruct batch of objects
inline void DestructObjectBatch(Batch &ioBatch);
/// Access an object by index.
inline Object & Get(uint32 inObjectIndex) { return GetStorage(inObjectIndex).mObject; }
/// Access an object by index.
inline const Object & Get(uint32 inObjectIndex) const { return GetStorage(inObjectIndex).mObject; }
};
JPH_NAMESPACE_END
#include "FixedSizeFreeList.inl"
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/QuickSort.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2022 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/InsertionSort.h>
JPH_NAMESPACE_BEGIN
/// Helper function for QuickSort, will move the pivot element to inMiddle.
template <typename Iterator, typename Compare>
inline void QuickSortMedianOfThree(Iterator inFirst, Iterator inMiddle, Iterator inLast, Compare inCompare)
{
// This should be guaranteed because we switch over to insertion sort when there's 32 or less elements
JPH_ASSERT(inFirst != inMiddle && inMiddle != inLast);
if (inCompare(*inMiddle, *inFirst))
swap(*inFirst, *inMiddle);
if (inCompare(*inLast, *inFirst))
swap(*inFirst, *inLast);
if (inCompare(*inLast, *inMiddle))
swap(*inMiddle, *inLast);
}
/// Helper function for QuickSort using the Ninther method, will move the pivot element to inMiddle.
template <typename Iterator, typename Compare>
inline void QuickSortNinther(Iterator inFirst, Iterator inMiddle, Iterator inLast, Compare inCompare)
{
// Divide the range in 8 equal parts (this means there are 9 points)
auto diff = (inLast - inFirst) >> 3;
auto two_diff = diff << 1;
// Median of first 3 points
Iterator mid1 = inFirst + diff;
QuickSortMedianOfThree(inFirst, mid1, inFirst + two_diff, inCompare);
// Median of second 3 points
QuickSortMedianOfThree(inMiddle - diff, inMiddle, inMiddle + diff, inCompare);
// Median of third 3 points
Iterator mid3 = inLast - diff;
QuickSortMedianOfThree(inLast - two_diff, mid3, inLast, inCompare);
// Determine the median of the 3 medians
QuickSortMedianOfThree(mid1, inMiddle, mid3, inCompare);
}
/// Implementation of the quick sort algorithm. The STL version implementation is not consistent across platforms.
template <typename Iterator, typename Compare>
inline void QuickSort(Iterator inBegin, Iterator inEnd, Compare inCompare)
{
// Implementation based on https://en.wikipedia.org/wiki/Quicksort using Hoare's partition scheme
// Loop so that we only need to do 1 recursive call instead of 2.
for (;;)
{
// If there's less than 2 elements we're done
auto num_elements = inEnd - inBegin;
if (num_elements < 2)
return;
// Fall back to insertion sort if there are too few elements
if (num_elements <= 32)
{
InsertionSort(inBegin, inEnd, inCompare);
return;
}
// Determine pivot
Iterator pivot_iterator = inBegin + ((num_elements - 1) >> 1);
QuickSortNinther(inBegin, pivot_iterator, inEnd - 1, inCompare);
auto pivot = *pivot_iterator;
// Left and right iterators
Iterator i = inBegin;
Iterator j = inEnd;
for (;;)
{
// Find the first element that is bigger than the pivot
while (inCompare(*i, pivot))
i++;
// Find the last element that is smaller than the pivot
do
--j;
while (inCompare(pivot, *j));
// If the two iterators crossed, we're done
if (i >= j)
break;
// Swap the elements
swap(*i, *j);
// Note that the first while loop in this function should
// have been do i++ while (...) but since we cannot decrement
// the iterator from inBegin we left that out, so we need to do
// it here.
++i;
}
// Include the middle element on the left side
j++;
// Check which partition is smaller
if (j - inBegin < inEnd - j)
{
// Left side is smaller, recurse to left first
QuickSort(inBegin, j, inCompare);
// Loop again with the right side to avoid a call
inBegin = j;
}
else
{
// Right side is smaller, recurse to right first
QuickSort(j, inEnd, inCompare);
// Loop again with the left side to avoid a call
inEnd = j;
}
}
}
/// Implementation of quick sort algorithm without comparator.
template <typename Iterator>
inline void QuickSort(Iterator inBegin, Iterator inEnd)
{
std::less<> compare;
QuickSort(inBegin, inEnd, compare);
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/Atomics.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_SUPPRESS_WARNINGS_STD_BEGIN
#include <atomic>
JPH_SUPPRESS_WARNINGS_STD_END
JPH_NAMESPACE_BEGIN
// Things we're using from STL
using std::atomic;
using std::memory_order;
using std::memory_order_relaxed;
using std::memory_order_acquire;
using std::memory_order_release;
using std::memory_order_acq_rel;
using std::memory_order_seq_cst;
/// Atomically compute the min(ioAtomic, inValue) and store it in ioAtomic, returns true if value was updated
template <class T>
bool AtomicMin(atomic<T> &ioAtomic, const T inValue, const memory_order inMemoryOrder = memory_order_seq_cst)
{
T cur_value = ioAtomic.load(memory_order_relaxed);
while (cur_value > inValue)
if (ioAtomic.compare_exchange_weak(cur_value, inValue, inMemoryOrder))
return true;
return false;
}
/// Atomically compute the max(ioAtomic, inValue) and store it in ioAtomic, returns true if value was updated
template <class T>
bool AtomicMax(atomic<T> &ioAtomic, const T inValue, const memory_order inMemoryOrder = memory_order_seq_cst)
{
T cur_value = ioAtomic.load(memory_order_relaxed);
while (cur_value < inValue)
if (ioAtomic.compare_exchange_weak(cur_value, inValue, inMemoryOrder))
return true;
return false;
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Core/JobSystem.inl | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
JPH_NAMESPACE_BEGIN
void JobSystem::Job::AddDependency(int inCount)
{
JPH_IF_ENABLE_ASSERTS(uint32 old_value =) mNumDependencies.fetch_add(inCount, memory_order_relaxed);
JPH_ASSERT(old_value > 0 && old_value != cExecutingState && old_value != cDoneState, "Job is queued, running or done, it is not allowed to add a dependency to a running job");
}
bool JobSystem::Job::RemoveDependency(int inCount)
{
uint32 old_value = mNumDependencies.fetch_sub(inCount, memory_order_release);
JPH_ASSERT(old_value != cExecutingState && old_value != cDoneState, "Job is running or done, it is not allowed to add a dependency to a running job");
uint32 new_value = old_value - inCount;
JPH_ASSERT(old_value > new_value, "Test wrap around, this is a logic error");
return new_value == 0;
}
void JobSystem::Job::RemoveDependencyAndQueue(int inCount)
{
if (RemoveDependency(inCount))
mJobSystem->QueueJob(this);
}
void JobSystem::JobHandle::sRemoveDependencies(JobHandle *inHandles, uint inNumHandles, int inCount)
{
JPH_PROFILE_FUNCTION();
JPH_ASSERT(inNumHandles > 0);
// Get the job system, all jobs should be part of the same job system
JobSystem *job_system = inHandles->GetPtr()->GetJobSystem();
// Allocate a buffer to store the jobs that need to be queued
Job **jobs_to_queue = (Job **)JPH_STACK_ALLOC(inNumHandles * sizeof(Job *));
Job **next_job = jobs_to_queue;
// Remove the dependencies on all jobs
for (const JobHandle *handle = inHandles, *handle_end = inHandles + inNumHandles; handle < handle_end; ++handle)
{
Job *job = handle->GetPtr();
JPH_ASSERT(job->GetJobSystem() == job_system); // All jobs should belong to the same job system
if (job->RemoveDependency(inCount))
*(next_job++) = job;
}
// If any jobs need to be scheduled, schedule them as a batch
uint num_jobs_to_queue = uint(next_job - jobs_to_queue);
if (num_jobs_to_queue != 0)
job_system->QueueJobs(jobs_to_queue, num_jobs_to_queue);
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/TriangleSplitter/TriangleSplitterFixedLeafSize.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/TriangleSplitter/TriangleSplitter.h>
#include <Jolt/Geometry/AABox.h>
JPH_NAMESPACE_BEGIN
/// Same as TriangleSplitterBinning, but ensuring that leaves have a fixed amount of triangles
/// The resulting tree should be suitable for processing on GPU where we want all threads to process an equal amount of triangles
class TriangleSplitterFixedLeafSize : public TriangleSplitter
{
public:
/// Constructor
TriangleSplitterFixedLeafSize(const VertexList &inVertices, const IndexedTriangleList &inTriangles, uint inLeafSize, uint inMinNumBins = 8, uint inMaxNumBins = 128, uint inNumTrianglesPerBin = 6);
// See TriangleSplitter::GetStats
virtual void GetStats(Stats &outStats) const override
{
outStats.mSplitterName = "TriangleSplitterFixedLeafSize";
outStats.mLeafSize = mLeafSize;
}
// See TriangleSplitter::Split
virtual bool Split(const Range &inTriangles, Range &outLeft, Range &outRight) override;
private:
/// Get centroid for group
Vec3 GetCentroidForGroup(uint inFirstTriangleInGroup);
// Configuration
const uint mLeafSize;
const uint mMinNumBins;
const uint mMaxNumBins;
const uint mNumTrianglesPerBin;
struct Bin
{
// Properties of this bin
AABox mBounds;
float mMinCentroid;
uint mNumTriangles;
// Accumulated data from left most / right most bin to current (including this bin)
AABox mBoundsAccumulatedLeft;
AABox mBoundsAccumulatedRight;
uint mNumTrianglesAccumulatedLeft;
uint mNumTrianglesAccumulatedRight;
};
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/TriangleSplitter/TriangleSplitterBinning.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/TriangleSplitter/TriangleSplitter.h>
#include <Jolt/Geometry/AABox.h>
JPH_NAMESPACE_BEGIN
/// Binning splitter approach taken from: Realtime Ray Tracing on GPU with BVH-based Packet Traversal by Johannes Gunther et al.
class TriangleSplitterBinning : public TriangleSplitter
{
public:
/// Constructor
TriangleSplitterBinning(const VertexList &inVertices, const IndexedTriangleList &inTriangles, uint inMinNumBins = 8, uint inMaxNumBins = 128, uint inNumTrianglesPerBin = 6);
// See TriangleSplitter::GetStats
virtual void GetStats(Stats &outStats) const override
{
outStats.mSplitterName = "TriangleSplitterBinning";
}
// See TriangleSplitter::Split
virtual bool Split(const Range &inTriangles, Range &outLeft, Range &outRight) override;
private:
// Configuration
const uint mMinNumBins;
const uint mMaxNumBins;
const uint mNumTrianglesPerBin;
struct Bin
{
// Properties of this bin
AABox mBounds;
float mMinCentroid;
uint mNumTriangles;
// Accumulated data from left most / right most bin to current (including this bin)
AABox mBoundsAccumulatedLeft;
AABox mBoundsAccumulatedRight;
uint mNumTrianglesAccumulatedLeft;
uint mNumTrianglesAccumulatedRight;
};
// Scratch area to store the bins
Array<Bin> mBins;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/TriangleSplitter/TriangleSplitterMean.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/TriangleSplitter/TriangleSplitter.h>
JPH_NAMESPACE_BEGIN
/// Splitter using mean of axis with biggest centroid deviation
class TriangleSplitterMean : public TriangleSplitter
{
public:
/// Constructor
TriangleSplitterMean(const VertexList &inVertices, const IndexedTriangleList &inTriangles);
// See TriangleSplitter::GetStats
virtual void GetStats(Stats &outStats) const override
{
outStats.mSplitterName = "TriangleSplitterMean";
}
// See TriangleSplitter::Split
virtual bool Split(const Range &inTriangles, Range &outLeft, Range &outRight) override;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/TriangleSplitter/TriangleSplitter.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Geometry/IndexedTriangle.h>
JPH_NAMESPACE_BEGIN
/// A class that splits a triangle list into two parts for building a tree
class TriangleSplitter
{
public:
/// Constructor
TriangleSplitter(const VertexList &inVertices, const IndexedTriangleList &inTriangles);
/// Virtual destructor
virtual ~TriangleSplitter() = default;
struct Stats
{
const char * mSplitterName = nullptr;
int mLeafSize = 0;
};
/// Get stats of splitter
virtual void GetStats(Stats &outStats) const = 0;
/// Helper struct to indicate triangle range before and after the split
struct Range
{
/// Constructor
Range() = default;
Range(uint inBegin, uint inEnd) : mBegin(inBegin), mEnd(inEnd) { }
/// Get number of triangles in range
uint Count() const
{
return mEnd - mBegin;
}
/// Start and end index (end = 1 beyond end)
uint mBegin;
uint mEnd;
};
/// Range of triangles to start with
Range GetInitialRange() const
{
return Range(0, (uint)mSortedTriangleIdx.size());
}
/// Split triangles into two groups left and right, returns false if no split could be made
/// @param inTriangles The range of triangles (in mSortedTriangleIdx) to process
/// @param outLeft On return this will contain the ranges for the left subpart. mSortedTriangleIdx may have been shuffled.
/// @param outRight On return this will contain the ranges for the right subpart. mSortedTriangleIdx may have been shuffled.
/// @return Returns true when a split was found
virtual bool Split(const Range &inTriangles, Range &outLeft, Range &outRight) = 0;
/// Get the list of vertices
const VertexList & GetVertices() const
{
return mVertices;
}
/// Get triangle by index
const IndexedTriangle & GetTriangle(uint inIdx) const
{
return mTriangles[mSortedTriangleIdx[inIdx]];
}
protected:
/// Helper function to split triangles based on dimension and split value
bool SplitInternal(const Range &inTriangles, uint inDimension, float inSplit, Range &outLeft, Range &outRight);
const VertexList & mVertices; ///< Vertices of the indexed triangles
const IndexedTriangleList & mTriangles; ///< Unsorted triangles
Array<Float3> mCentroids; ///< Unsorted centroids of triangles
Array<uint> mSortedTriangleIdx; ///< Indices to sort triangles
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/TriangleSplitter/TriangleSplitterMorton.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/TriangleSplitter/TriangleSplitter.h>
JPH_NAMESPACE_BEGIN
/// Splitter using Morton codes, see: http://devblogs.nvidia.com/parallelforall/thinking-parallel-part-iii-tree-construction-gpu/
class TriangleSplitterMorton : public TriangleSplitter
{
public:
/// Constructor
TriangleSplitterMorton(const VertexList &inVertices, const IndexedTriangleList &inTriangles);
// See TriangleSplitter::GetStats
virtual void GetStats(Stats &outStats) const override
{
outStats.mSplitterName = "TriangleSplitterMorton";
}
// See TriangleSplitter::Split
virtual bool Split(const Range &inTriangles, Range &outLeft, Range &outRight) override;
private:
// Precalculated Morton codes
Array<uint32> mMortonCodes;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/TriangleSplitter/TriangleSplitterLongestAxis.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/TriangleSplitter/TriangleSplitter.h>
JPH_NAMESPACE_BEGIN
/// Splitter using center of bounding box with longest axis
class TriangleSplitterLongestAxis : public TriangleSplitter
{
public:
/// Constructor
TriangleSplitterLongestAxis(const VertexList &inVertices, const IndexedTriangleList &inTriangles);
// See TriangleSplitter::GetStats
virtual void GetStats(Stats &outStats) const override
{
outStats.mSplitterName = "TriangleSplitterLongestAxis";
}
// See TriangleSplitter::Split
virtual bool Split(const Range &inTriangles, Range &outLeft, Range &outRight) override;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/LargeIslandSplitter.h | // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/NonCopyable.h>
#include <Jolt/Core/Atomics.h>
JPH_NAMESPACE_BEGIN
class Body;
class BodyID;
class IslandBuilder;
class TempAllocator;
class Constraint;
class BodyManager;
class ContactConstraintManager;
/// Assigns bodies in large islands to multiple groups that can run in parallel
///
/// This basically implements what is described in: High-Performance Physical Simulations on Next-Generation Architecture with Many Cores by Chen et al.
/// See: http://web.eecs.umich.edu/~msmelyan/papers/physsim_onmanycore_itj.pdf section "PARALLELIZATION METHODOLOGY"
class LargeIslandSplitter : public NonCopyable
{
private:
using SplitMask = uint32;
public:
static constexpr uint cNumSplits = sizeof(SplitMask) * 8;
static constexpr uint cNonParallelSplitIdx = cNumSplits - 1;
static constexpr uint cLargeIslandTreshold = 128; ///< If the number of constraints + contacts in an island is larger than this, we will try to split the island
/// Status code for retrieving a batch
enum class EStatus
{
WaitingForBatch, ///< Work is expected to be available later
BatchRetrieved, ///< Work is being returned
AllBatchesDone, ///< No further work is expected from this
};
/// Describes a split of constraints and contacts
struct Split
{
inline uint GetNumContacts() const { return mContactBufferEnd - mContactBufferBegin; }
inline uint GetNumConstraints() const { return mConstraintBufferEnd - mConstraintBufferBegin; }
inline uint GetNumItems() const { return GetNumContacts() + GetNumConstraints(); }
uint32 mContactBufferBegin; ///< Begin of the contact buffer (offset relative to mContactAndConstraintIndices)
uint32 mContactBufferEnd; ///< End of the contact buffer
uint32 mConstraintBufferBegin; ///< Begin of the constraint buffer (offset relative to mContactAndConstraintIndices)
uint32 mConstraintBufferEnd; ///< End of the constraint buffer
};
/// Structure that describes the resulting splits from the large island splitter
class Splits
{
public:
inline uint GetNumSplits() const
{
return mNumSplits;
}
inline void GetConstraintsInSplit(uint inSplitIndex, uint32 &outConstraintsBegin, uint32 &outConstraintsEnd) const
{
const Split &split = mSplits[inSplitIndex];
outConstraintsBegin = split.mConstraintBufferBegin;
outConstraintsEnd = split.mConstraintBufferEnd;
}
inline void GetContactsInSplit(uint inSplitIndex, uint32 &outContactsBegin, uint32 &outContactsEnd) const
{
const Split &split = mSplits[inSplitIndex];
outContactsBegin = split.mContactBufferBegin;
outContactsEnd = split.mContactBufferEnd;
}
/// Reset current status so that no work can be picked up from this split
inline void ResetStatus()
{
mStatus.store(StatusItemMask, memory_order_relaxed);
}
/// Make the first batch available to other threads
inline void StartFirstBatch()
{
uint split_index = mNumSplits > 0? 0 : cNonParallelSplitIdx;
mStatus.store(uint64(split_index) << StatusSplitShift, memory_order_release);
}
/// Fetch the next batch to process
EStatus FetchNextBatch(uint32 &outConstraintsBegin, uint32 &outConstraintsEnd, uint32 &outContactsBegin, uint32 &outContactsEnd, bool &outFirstIteration);
/// Mark a batch as processed
void MarkBatchProcessed(uint inNumProcessed, bool &outLastIteration, bool &outFinalBatch);
enum EIterationStatus : uint64
{
StatusIterationMask = 0xffff000000000000,
StatusIterationShift = 48,
StatusSplitMask = 0x0000ffff00000000,
StatusSplitShift = 32,
StatusItemMask = 0x00000000ffffffff,
};
static inline int sGetIteration(uint64 inStatus)
{
return int((inStatus & StatusIterationMask) >> StatusIterationShift);
}
static inline uint sGetSplit(uint64 inStatus)
{
return uint((inStatus & StatusSplitMask) >> StatusSplitShift);
}
static inline uint sGetItem(uint64 inStatus)
{
return uint(inStatus & StatusItemMask);
}
Split mSplits[cNumSplits]; ///< Data per split
uint32 mIslandIndex; ///< Index of the island that was split
uint mNumSplits; ///< Number of splits that were created (excluding the non-parallel split)
int mNumIterations; ///< Number of iterations to do
int mNumVelocitySteps; ///< Number of velocity steps to do (cached for 2nd sub step)
int mNumPositionSteps; ///< Number of position steps to do
atomic<uint64> mStatus; ///< Status of the split, see EIterationStatus
atomic<uint> mItemsProcessed; ///< Number of items that have been marked as processed
};
public:
/// Destructor
~LargeIslandSplitter();
/// Prepare the island splitter by allocating memory
void Prepare(const IslandBuilder &inIslandBuilder, uint32 inNumActiveBodies, TempAllocator *inTempAllocator);
/// Assign two bodies to a split. Returns the split index.
uint AssignSplit(const Body *inBody1, const Body *inBody2);
/// Force a body to be in a non parallel split. Returns the split index.
uint AssignToNonParallelSplit(const Body *inBody);
/// Splits up an island, the created splits will be added to the list of batches and can be fetched with FetchNextBatch. Returns false if the island did not need splitting.
bool SplitIsland(uint32 inIslandIndex, const IslandBuilder &inIslandBuilder, const BodyManager &inBodyManager, const ContactConstraintManager &inContactManager, Constraint **inActiveConstraints, int inNumVelocitySteps, int inNumPositionSteps);
/// Fetch the next batch to process, returns a handle in outSplitIslandIndex that must be provided to MarkBatchProcessed when complete
EStatus FetchNextBatch(uint &outSplitIslandIndex, uint32 *&outConstraintsBegin, uint32 *&outConstraintsEnd, uint32 *&outContactsBegin, uint32 *&outContactsEnd, bool &outFirstIteration);
/// Mark a batch as processed
void MarkBatchProcessed(uint inSplitIslandIndex, const uint32 *inConstraintsBegin, const uint32 *inConstraintsEnd, const uint32 *inContactsBegin, const uint32 *inContactsEnd, bool &outLastIteration, bool &outFinalBatch);
/// Get the island index of the island that was split for a particular split island index
inline uint32 GetIslandIndex(uint inSplitIslandIndex) const
{
JPH_ASSERT(inSplitIslandIndex < mNumSplitIslands);
return mSplitIslands[inSplitIslandIndex].mIslandIndex;
}
/// Prepare the island splitter for iterating over the split islands again for position solving. Marks all batches as startable.
void PrepareForSolvePositions();
/// Reset the island splitter
void Reset(TempAllocator *inTempAllocator);
private:
static constexpr uint cSplitCombineTreshold = 32; ///< If the number of constraints + contacts in a split is lower than this, we will merge this split into the 'non-parallel split'
static constexpr uint cBatchSize = 16; ///< Number of items to process in a constraint batch
uint32 mNumActiveBodies = 0; ///< Cached number of active bodies
SplitMask * mSplitMasks = nullptr; ///< Bits that indicate for each body in the BodyManager::mActiveBodies list which split they already belong to
uint32 * mContactAndConstaintsSplitIdx = nullptr; ///< Buffer to store the split index per constraint or contact
uint32 * mContactAndConstraintIndices = nullptr; ///< Buffer to store the ordered constraint indices per split
uint mContactAndConstraintsSize = 0; ///< Total size of mContactAndConstraintsSplitIdx and mContactAndConstraintIndices
atomic<uint> mContactAndConstraintsNextFree { 0 }; ///< Next element that is free in both buffers
uint mNumSplitIslands = 0; ///< Total number of islands that required splitting
Splits * mSplitIslands = nullptr; ///< List of islands that required splitting
atomic<uint> mNextSplitIsland = 0; ///< Next split island to pick from mSplitIslands
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/PhysicsUpdateContext.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyPair.h>
#include <Jolt/Physics/Collision/ContactListener.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
#include <Jolt/Core/StaticArray.h>
#include <Jolt/Core/JobSystem.h>
#include <Jolt/Core/STLTempAllocator.h>
JPH_NAMESPACE_BEGIN
class PhysicsSystem;
class IslandBuilder;
class Constraint;
class TempAllocator;
/// Information used during the Update call
class PhysicsUpdateContext : public NonCopyable
{
public:
/// Destructor
explicit PhysicsUpdateContext(TempAllocator &inTempAllocator);
~PhysicsUpdateContext();
static constexpr int cMaxConcurrency = 32; ///< Maximum supported amount of concurrent jobs
static constexpr int cMaxSubSteps = 4; ///< Maximum supported amount of integration sub steps
using JobHandleArray = StaticArray<JobHandle, cMaxConcurrency>;
struct Step;
/// Structure that contains job handles for each integration sub step
struct SubStep
{
Step * mStep; ///< Step that this substeb belongs to
bool mIsFirst; ///< If this is the first substep in the step
bool mIsLast; ///< If this is the last substep in the step
bool mIsFirstOfAll; ///< If this is the first substep of the first step
bool mIsLastOfAll; ///< If this is the last substep in the last step
atomic<uint32> mSolveVelocityConstraintsNextIsland { 0 }; ///< Next island that needs to be processed for the solve velocity constraints step (doesn't need own cache line since position jobs don't run at same time)
atomic<uint32> mSolvePositionConstraintsNextIsland { 0 }; ///< Next island that needs to be processed for the solve position constraints step (doesn't need own cache line since velocity jobs don't run at same time)
/// Contains the information needed to cast a body through the scene to do continuous collision detection
struct CCDBody
{
CCDBody(BodyID inBodyID1, Vec3Arg inDeltaPosition, float inLinearCastThresholdSq, float inMaxPenetration) : mDeltaPosition(inDeltaPosition), mBodyID1(inBodyID1), mLinearCastThresholdSq(inLinearCastThresholdSq), mMaxPenetration(inMaxPenetration) { }
Vec3 mDeltaPosition; ///< Desired rotation step
Vec3 mContactNormal; ///< World space normal of closest hit (only valid if mFractionPlusSlop < 1)
RVec3 mContactPointOn2; ///< World space contact point on body 2 of closest hit (only valid if mFractionPlusSlop < 1)
BodyID mBodyID1; ///< Body 1 (the body that is performing collision detection)
BodyID mBodyID2; ///< Body 2 (the body of the closest hit, only valid if mFractionPlusSlop < 1)
float mFraction = 1.0f; ///< Fraction at which the hit occurred
float mFractionPlusSlop = 1.0f; ///< Fraction at which the hit occurred + extra delta to allow body to penetrate by mMaxPenetration
float mLinearCastThresholdSq; ///< Maximum allowed squared movement before doing a linear cast (determined by inner radius of shape)
float mMaxPenetration; ///< Maximum allowed penetration (determined by inner radius of shape)
ContactSettings mContactSettings; ///< The contact settings for this contact
};
atomic<uint32> mIntegrateVelocityReadIdx { 0 }; ///< Next active body index to take when integrating velocities
CCDBody * mCCDBodies = nullptr; ///< List of bodies that need to do continuous collision detection
uint32 mCCDBodiesCapacity = 0; ///< Capacity of the mCCDBodies list
atomic<uint32> mNumCCDBodies = 0; ///< Number of CCD bodies in mCCDBodies
atomic<uint32> mNextCCDBody { 0 }; ///< Next unprocessed body index in mCCDBodies
int * mActiveBodyToCCDBody = nullptr; ///< A mapping between an index in BodyManager::mActiveBodies and the index in mCCDBodies
uint32 mNumActiveBodyToCCDBody = 0; ///< Number of indices in mActiveBodyToCCDBody
JobHandleArray mSolveVelocityConstraints; ///< Solve the constraints in the velocity domain
JobHandle mPreIntegrateVelocity; ///< Setup integration of all body positions
JobHandleArray mIntegrateVelocity; ///< Integrate all body positions
JobHandle mPostIntegrateVelocity; ///< Finalize integration of all body positions
JobHandle mResolveCCDContacts; ///< Updates the positions and velocities for all bodies that need continuous collision detection
JobHandleArray mSolvePositionConstraints; ///< Solve all constraints in the position domain
JobHandle mStartNextSubStep; ///< Trampoline job that either kicks the next sub step or the next step
};
using SubSteps = StaticArray<SubStep, cMaxSubSteps>;
struct BodyPairQueue
{
atomic<uint32> mWriteIdx { 0 }; ///< Next index to write in mBodyPair array (need to add thread index * mMaxBodyPairsPerQueue and modulo mMaxBodyPairsPerQueue)
uint8 mPadding1[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Moved to own cache line to avoid conflicts with consumer jobs
atomic<uint32> mReadIdx { 0 }; ///< Next index to read in mBodyPair array (need to add thread index * mMaxBodyPairsPerQueue and modulo mMaxBodyPairsPerQueue)
uint8 mPadding2[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Moved to own cache line to avoid conflicts with producer/consumer jobs
};
using BodyPairQueues = StaticArray<BodyPairQueue, cMaxConcurrency>;
using JobMask = uint32; ///< A mask that has as many bits as we can have concurrent jobs
static_assert(sizeof(JobMask) * 8 >= cMaxConcurrency);
/// Structure that contains data needed for each collision step.
struct Step
{
Step() = default;
Step(const Step &) { JPH_ASSERT(false); } // vector needs a copy constructor, but we're never going to call it
PhysicsUpdateContext *mContext; ///< The physics update context
BroadPhase::UpdateState mBroadPhaseUpdateState; ///< Handle returned by Broadphase::UpdatePrepare
uint32 mNumActiveBodiesAtStepStart; ///< Number of bodies that were active at the start of the physics update step. Only these bodies will receive gravity (they are the first N in the active body list).
atomic<uint32> mConstraintReadIdx { 0 }; ///< Next constraint for determine active constraints
uint8 mPadding1[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic
atomic<uint32> mNumActiveConstraints { 0 }; ///< Number of constraints in the mActiveConstraints array
uint8 mPadding2[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic
atomic<uint32> mStepListenerReadIdx { 0 }; ///< Next step listener to call
uint8 mPadding3[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic
atomic<uint32> mApplyGravityReadIdx { 0 }; ///< Next body to apply gravity to
uint8 mPadding4[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic
atomic<uint32> mActiveBodyReadIdx { 0 }; ///< Index of fist active body that has not yet been processed by the broadphase
uint8 mPadding5[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic
BodyPairQueues mBodyPairQueues; ///< Queues in which to put body pairs that need to be tested by the narrowphase
uint32 mMaxBodyPairsPerQueue; ///< Amount of body pairs that we can queue per queue
atomic<JobMask> mActiveFindCollisionJobs; ///< A bitmask that indicates which jobs are still active
atomic<uint> mNumBodyPairs { 0 }; ///< The number of body pairs found in this step (used to size the contact cache in the next step)
atomic<uint> mNumManifolds { 0 }; ///< The number of manifolds found in this step (used to size the contact cache in the next step)
// Jobs in order of execution (some run in parallel)
JobHandle mBroadPhasePrepare; ///< Prepares the new tree in the background
JobHandleArray mStepListeners; ///< Listeners to notify of the beginning of a physics step
JobHandleArray mDetermineActiveConstraints; ///< Determine which constraints will be active during this step
JobHandleArray mApplyGravity; ///< Update velocities of bodies with gravity
JobHandleArray mFindCollisions; ///< Find all collisions between active bodies an the world
JobHandle mUpdateBroadphaseFinalize; ///< Swap the newly built tree with the current tree
JobHandle mSetupVelocityConstraints; ///< Calculate properties for all constraints in the constraint manager
JobHandle mBuildIslandsFromConstraints; ///< Go over all constraints and assign the bodies they're attached to to an island
JobHandle mFinalizeIslands; ///< Finalize calculation simulation islands
JobHandle mBodySetIslandIndex; ///< Set the current island index on each body (not used by the simulation, only for drawing purposes)
SubSteps mSubSteps; ///< Integration sub steps
JobHandle mContactRemovedCallbacks; ///< Calls the contact removed callbacks
JobHandle mStartNextStep; ///< Job that kicks the next step (empty for the last step)
};
using Steps = std::vector<Step, STLTempAllocator<Step>>;
/// Maximum amount of concurrent jobs on this machine
int GetMaxConcurrency() const { const int max_concurrency = PhysicsUpdateContext::cMaxConcurrency; return min(max_concurrency, mJobSystem->GetMaxConcurrency()); } ///< Need to put max concurrency in temp var as min requires a reference
PhysicsSystem * mPhysicsSystem; ///< The physics system we belong to
TempAllocator * mTempAllocator; ///< Temporary allocator used during the update
JobSystem * mJobSystem; ///< Job system that processes jobs
JobSystem::Barrier * mBarrier; ///< Barrier used to wait for all physics jobs to complete
float mStepDeltaTime; ///< Delta time for a simulation step (collision step)
float mSubStepDeltaTime; ///< Delta time for a simulation sub step (integration step)
float mWarmStartImpulseRatio; ///< Ratio of this step delta time vs last step
bool mUseLargeIslandSplitter; ///< If true, use large island splitting
atomic<uint32> mErrors { 0 }; ///< Errors that occurred during the update, actual type is EPhysicsUpdateError
Constraint ** mActiveConstraints = nullptr; ///< Constraints that were active at the start of the physics update step (activating bodies can activate constraints and we need a consistent snapshot). Only these constraints will be resolved.
BodyPair * mBodyPairs = nullptr; ///< A list of body pairs found by the broadphase
IslandBuilder * mIslandBuilder; ///< Keeps track of connected bodies and builds islands for multithreaded velocity/position update
Steps mSteps;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/StateRecorder.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/StreamIn.h>
#include <Jolt/Core/StreamOut.h>
JPH_NAMESPACE_BEGIN
/// Class that records the state of a physics system. Can be used to check if the simulation is deterministic by putting the recorder in validation mode.
/// Can be used to restore the state to an earlier point in time.
class StateRecorder : public StreamIn, public StreamOut
{
public:
/// Constructor
StateRecorder() = default;
StateRecorder(const StateRecorder &inRHS) : mIsValidating(inRHS.mIsValidating) { }
/// Sets the stream in validation mode. In this case the physics system ensures that before it calls ReadBytes that it will
/// ensure that those bytes contain the current state. This makes it possible to step and save the state, restore to the previous
/// step and step again and when the recorded state is not the same it can restore the expected state and any byte that changes
/// due to a ReadBytes function can be caught to find out which part of the simulation is not deterministic
void SetValidating(bool inValidating) { mIsValidating = inValidating; }
bool IsValidating() const { return mIsValidating; }
private:
bool mIsValidating = false;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/PhysicsLock.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Mutex.h>
JPH_NAMESPACE_BEGIN
#ifdef JPH_ENABLE_ASSERTS
/// This is the list of locks used by the physics engine, they need to be locked in a particular order (from top of the list to bottom of the list) in order to prevent deadlocks
enum class EPhysicsLockTypes
{
BroadPhaseQuery = 1 << 0,
PerBody = 1 << 1,
BodiesList = 1 << 2,
BroadPhaseUpdate = 1 << 3,
ConstraintsList = 1 << 4,
ActiveBodiesList = 1 << 5,
};
/// A token that indicates the context of a lock (we use 1 per physics system and we use the body manager pointer because it's convenient)
class BodyManager;
using PhysicsLockContext = const BodyManager *;
#endif // !JPH_ENABLE_ASSERTS
/// Helpers to safely lock the different mutexes that are part of the physics system while preventing deadlock
/// Class that keeps track per thread which lock are taken and if the order of locking is correct
class PhysicsLock
{
public:
#ifdef JPH_ENABLE_ASSERTS
/// Call before taking the lock
static inline void sCheckLock(PhysicsLockContext inContext, EPhysicsLockTypes inType)
{
uint32 &mutexes = sGetLockedMutexes(inContext);
JPH_ASSERT((uint32)inType > mutexes, "A lock of same or higher priority was already taken, this can create a deadlock!");
mutexes = mutexes | (uint32)inType;
}
/// Call after releasing the lock
static inline void sCheckUnlock(PhysicsLockContext inContext, EPhysicsLockTypes inType)
{
uint32 &mutexes = sGetLockedMutexes(inContext);
JPH_ASSERT((mutexes & (uint32)inType) != 0, "Mutex was not locked!");
mutexes = mutexes & ~(uint32)inType;
}
#endif // !JPH_ENABLE_ASSERTS
template <class LockType>
static inline void sLock(LockType &inMutex JPH_IF_ENABLE_ASSERTS(, PhysicsLockContext inContext, EPhysicsLockTypes inType))
{
JPH_IF_ENABLE_ASSERTS(sCheckLock(inContext, inType);)
inMutex.lock();
}
template <class LockType>
static inline void sUnlock(LockType &inMutex JPH_IF_ENABLE_ASSERTS(, PhysicsLockContext inContext, EPhysicsLockTypes inType))
{
JPH_IF_ENABLE_ASSERTS(sCheckUnlock(inContext, inType);)
inMutex.unlock();
}
template <class LockType>
static inline void sLockShared(LockType &inMutex JPH_IF_ENABLE_ASSERTS(, PhysicsLockContext inContext, EPhysicsLockTypes inType))
{
JPH_IF_ENABLE_ASSERTS(sCheckLock(inContext, inType);)
inMutex.lock_shared();
}
template <class LockType>
static inline void sUnlockShared(LockType &inMutex JPH_IF_ENABLE_ASSERTS(, PhysicsLockContext inContext, EPhysicsLockTypes inType))
{
JPH_IF_ENABLE_ASSERTS(sCheckUnlock(inContext, inType);)
inMutex.unlock_shared();
}
#ifdef JPH_ENABLE_ASSERTS
private:
struct LockData
{
uint32 mLockedMutexes = 0;
PhysicsLockContext mContext = nullptr;
};
static thread_local LockData sLocks[4];
// Helper function to find the locked mutexes for a particular context
static uint32 & sGetLockedMutexes(PhysicsLockContext inContext)
{
// If we find a matching context we can use it
for (LockData &l : sLocks)
if (l.mContext == inContext)
return l.mLockedMutexes;
// Otherwise we look for an entry that is not in use
for (LockData &l : sLocks)
if (l.mLockedMutexes == 0)
{
l.mContext = inContext;
return l.mLockedMutexes;
}
JPH_ASSERT(false, "Too many physics systems locked at the same time!");
return sLocks[0].mLockedMutexes;
}
#endif // !JPH_ENABLE_ASSERTS
};
/// Helper class that is similar to std::unique_lock
template <class LockType>
class UniqueLock : public NonCopyable
{
public:
explicit UniqueLock(LockType &inLock JPH_IF_ENABLE_ASSERTS(, PhysicsLockContext inContext, EPhysicsLockTypes inType)) :
mLock(inLock)
#ifdef JPH_ENABLE_ASSERTS
, mContext(inContext),
mType(inType)
#endif // JPH_ENABLE_ASSERTS
{
PhysicsLock::sLock(mLock JPH_IF_ENABLE_ASSERTS(, mContext, mType));
}
~UniqueLock()
{
PhysicsLock::sUnlock(mLock JPH_IF_ENABLE_ASSERTS(, mContext, mType));
}
private:
LockType & mLock;
#ifdef JPH_ENABLE_ASSERTS
PhysicsLockContext mContext;
EPhysicsLockTypes mType;
#endif // JPH_ENABLE_ASSERTS
};
/// Helper class that is similar to std::shared_lock
template <class LockType>
class SharedLock : public NonCopyable
{
public:
explicit SharedLock(LockType &inLock JPH_IF_ENABLE_ASSERTS(, PhysicsLockContext inContext, EPhysicsLockTypes inType)) :
mLock(inLock)
#ifdef JPH_ENABLE_ASSERTS
, mContext(inContext)
, mType(inType)
#endif // JPH_ENABLE_ASSERTS
{
PhysicsLock::sLockShared(mLock JPH_IF_ENABLE_ASSERTS(, mContext, mType));
}
~SharedLock()
{
PhysicsLock::sUnlockShared(mLock JPH_IF_ENABLE_ASSERTS(, mContext, mType));
}
private:
LockType & mLock;
#ifdef JPH_ENABLE_ASSERTS
PhysicsLockContext mContext;
EPhysicsLockTypes mType;
#endif // JPH_ENABLE_ASSERTS
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/DeterminismLog.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2022 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
//#define JPH_ENABLE_DETERMINISM_LOG
#ifdef JPH_ENABLE_DETERMINISM_LOG
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
JPH_SUPPRESS_WARNINGS_STD_BEGIN
#include <iomanip>
#include <fstream>
JPH_SUPPRESS_WARNINGS_STD_END
JPH_NAMESPACE_BEGIN
/// A simple class that logs the state of the simulation. The resulting text file can be used to diff between platforms and find issues in determinism.
class DeterminismLog
{
private:
JPH_INLINE uint32 Convert(float inValue) const
{
return *(uint32 *)&inValue;
}
JPH_INLINE uint64 Convert(double inValue) const
{
return *(uint64 *)&inValue;
}
public:
DeterminismLog()
{
mLog.open("detlog.txt", std::ios::out | std::ios::trunc | std::ios::binary); // Binary because we don't want a difference between Unix and Windows line endings.
mLog.fill('0');
}
DeterminismLog & operator << (char inValue)
{
mLog << inValue;
return *this;
}
DeterminismLog & operator << (const char *inValue)
{
mLog << std::dec << inValue;
return *this;
}
DeterminismLog & operator << (const string &inValue)
{
mLog << std::dec << inValue;
return *this;
}
DeterminismLog & operator << (const BodyID &inValue)
{
mLog << std::hex << std::setw(8) << inValue.GetIndexAndSequenceNumber();
return *this;
}
DeterminismLog & operator << (const SubShapeID &inValue)
{
mLog << std::hex << std::setw(8) << inValue.GetValue();
return *this;
}
DeterminismLog & operator << (float inValue)
{
mLog << std::hex << std::setw(8) << Convert(inValue);
return *this;
}
DeterminismLog & operator << (int inValue)
{
mLog << inValue;
return *this;
}
DeterminismLog & operator << (uint32 inValue)
{
mLog << std::hex << std::setw(8) << inValue;
return *this;
}
DeterminismLog & operator << (uint64 inValue)
{
mLog << std::hex << std::setw(16) << inValue;
return *this;
}
DeterminismLog & operator << (Vec3Arg inValue)
{
mLog << std::hex << std::setw(8) << Convert(inValue.GetX()) << " " << std::setw(8) << Convert(inValue.GetY()) << " " << std::setw(8) << Convert(inValue.GetZ());
return *this;
}
DeterminismLog & operator << (DVec3Arg inValue)
{
mLog << std::hex << std::setw(16) << Convert(inValue.GetX()) << " " << std::setw(16) << Convert(inValue.GetY()) << " " << std::setw(16) << Convert(inValue.GetZ());
return *this;
}
DeterminismLog & operator << (Vec4Arg inValue)
{
mLog << std::hex << std::setw(8) << Convert(inValue.GetX()) << " " << std::setw(8) << Convert(inValue.GetY()) << " " << std::setw(8) << Convert(inValue.GetZ()) << " " << std::setw(8) << Convert(inValue.GetW());
return *this;
}
DeterminismLog & operator << (const Float3 &inValue)
{
mLog << std::hex << std::setw(8) << Convert(inValue.x) << " " << std::setw(8) << Convert(inValue.y) << " " << std::setw(8) << Convert(inValue.z);
return *this;
}
DeterminismLog & operator << (Mat44Arg inValue)
{
*this << inValue.GetColumn4(0) << " " << inValue.GetColumn4(1) << " " << inValue.GetColumn4(2) << " " << inValue.GetColumn4(3);
return *this;
}
DeterminismLog & operator << (DMat44Arg inValue)
{
*this << inValue.GetColumn4(0) << " " << inValue.GetColumn4(1) << " " << inValue.GetColumn4(2) << " " << inValue.GetTranslation();
return *this;
}
DeterminismLog & operator << (QuatArg inValue)
{
*this << inValue.GetXYZW();
return *this;
}
// Singleton instance
static DeterminismLog sLog;
private:
std::ofstream mLog;
};
/// Will log something to the determinism log, usage: JPH_DET_LOG("label " << value);
#define JPH_DET_LOG(...) DeterminismLog::sLog << __VA_ARGS__ << '\n'
JPH_NAMESPACE_END
#else
JPH_SUPPRESS_WARNING_PUSH
JPH_SUPPRESS_WARNINGS
/// By default we log nothing
#define JPH_DET_LOG(...)
JPH_SUPPRESS_WARNING_POP
#endif // JPH_ENABLE_DETERMINISM_LOG
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/EPhysicsUpdateError.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2023 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Enum used by PhysicsSystem to report error conditions during the PhysicsSystem::Update call. This is a bit field, multiple errors can trigger in the same update.
enum class EPhysicsUpdateError : uint32
{
None = 0, ///< No errors
ManifoldCacheFull = 1 << 0, ///< The manifold cache is full, this means that the total number of contacts between bodies is too high. Some contacts were ignored. Increase inMaxContactConstraints in PhysicsSystem::Init.
BodyPairCacheFull = 1 << 1, ///< The body pair cache is full, this means that too many bodies contacted. Some contacts were ignored. Increase inMaxBodyPairs in PhysicsSystem::Init.
ContactConstraintsFull = 1 << 2, ///< The contact constraints buffer is full. Some contacts were ignored. Increase inMaxContactConstraints in PhysicsSystem::Init.
};
/// OR operator for EPhysicsUpdateError
inline EPhysicsUpdateError operator | (EPhysicsUpdateError inA, EPhysicsUpdateError inB)
{
return static_cast<EPhysicsUpdateError>(static_cast<uint32>(inA) | static_cast<uint32>(inB));
}
/// OR operator for EPhysicsUpdateError
inline EPhysicsUpdateError operator |= (EPhysicsUpdateError &ioA, EPhysicsUpdateError inB)
{
ioA = ioA | inB;
return ioA;
}
/// AND operator for EPhysicsUpdateError
inline EPhysicsUpdateError operator & (EPhysicsUpdateError inA, EPhysicsUpdateError inB)
{
return static_cast<EPhysicsUpdateError>(static_cast<uint32>(inA) & static_cast<uint32>(inB));
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/PhysicsSystem.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyInterface.h>
#include <Jolt/Physics/Collision/NarrowPhaseQuery.h>
#include <Jolt/Physics/Collision/ContactListener.h>
#include <Jolt/Physics/Constraints/ContactConstraintManager.h>
#include <Jolt/Physics/Constraints/ConstraintManager.h>
#include <Jolt/Physics/IslandBuilder.h>
#include <Jolt/Physics/LargeIslandSplitter.h>
#include <Jolt/Physics/PhysicsUpdateContext.h>
#include <Jolt/Physics/PhysicsSettings.h>
JPH_NAMESPACE_BEGIN
class JobSystem;
class StateRecorder;
class TempAllocator;
class PhysicsStepListener;
/// The main class for the physics system. It contains all rigid bodies and simulates them.
///
/// The main simulation is performed by the Update() call on multiple threads (if the JobSystem is configured to use them). Please refer to the general architecture overview in the Docs folder for more information.
class PhysicsSystem : public NonCopyable
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor / Destructor
PhysicsSystem() : mContactManager(mPhysicsSettings) JPH_IF_ENABLE_ASSERTS(, mConstraintManager(&mBodyManager)) { }
~PhysicsSystem();
/// Initialize the system.
/// @param inMaxBodies Maximum number of bodies to support.
/// @param inNumBodyMutexes Number of body mutexes to use. Should be a power of 2 in the range [1, 64], use 0 to auto detect.
/// @param inMaxBodyPairs Maximum amount of body pairs to process (anything else will fall through the world), this number should generally be much higher than the max amount of contact points as there will be lots of bodies close that are not actually touching.
/// @param inMaxContactConstraints Maximum amount of contact constraints to process (anything else will fall through the world).
/// @param inBroadPhaseLayerInterface Information on the mapping of object layers to broad phase layers. Since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem.
/// @param inObjectVsBroadPhaseLayerFilter Filter callback function that is used to determine if an object layer collides with a broad phase layer. Since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem.
/// @param inObjectLayerPairFilter Filter callback function that is used to determine if two object layers collide. Since this is a virtual interface, the instance needs to stay alive during the lifetime of the PhysicsSystem.
void Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter);
/// Listener that is notified whenever a body is activated/deactivated
void SetBodyActivationListener(BodyActivationListener *inListener) { mBodyManager.SetBodyActivationListener(inListener); }
BodyActivationListener * GetBodyActivationListener() const { return mBodyManager.GetBodyActivationListener(); }
/// Listener that is notified whenever a contact point between two bodies is added/updated/removed
void SetContactListener(ContactListener *inListener) { mContactManager.SetContactListener(inListener); }
ContactListener * GetContactListener() const { return mContactManager.GetContactListener(); }
/// Set the function that combines the friction of two bodies and returns it
/// Default method is the geometric mean: sqrt(friction1 * friction2).
void SetCombineFriction(ContactConstraintManager::CombineFunction inCombineFriction) { mContactManager.SetCombineFriction(inCombineFriction); }
/// Set the function that combines the restitution of two bodies and returns it
/// Default method is max(restitution1, restitution1)
void SetCombineRestitution(ContactConstraintManager::CombineFunction inCombineRestition) { mContactManager.SetCombineRestitution(inCombineRestition); }
/// Control the main constants of the physics simulation
void SetPhysicsSettings(const PhysicsSettings &inSettings) { mPhysicsSettings = inSettings; }
const PhysicsSettings & GetPhysicsSettings() const { return mPhysicsSettings; }
/// Access to the body interface. This interface allows to to create / remove bodies and to change their properties.
const BodyInterface & GetBodyInterface() const { return mBodyInterfaceLocking; }
BodyInterface & GetBodyInterface() { return mBodyInterfaceLocking; }
const BodyInterface & GetBodyInterfaceNoLock() const { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
BodyInterface & GetBodyInterfaceNoLock() { return mBodyInterfaceNoLock; } ///< Version that does not lock the bodies, use with great care!
/// Access to the broadphase interface that allows coarse collision queries
const BroadPhaseQuery & GetBroadPhaseQuery() const { return *mBroadPhase; }
/// Interface that allows fine collision queries against first the broad phase and then the narrow phase.
const NarrowPhaseQuery & GetNarrowPhaseQuery() const { return mNarrowPhaseQueryLocking; }
const NarrowPhaseQuery & GetNarrowPhaseQueryNoLock() const { return mNarrowPhaseQueryNoLock; } ///< Version that does not lock the bodies, use with great care!
/// Add constraint to the world
void AddConstraint(Constraint *inConstraint) { mConstraintManager.Add(&inConstraint, 1); }
/// Remove constraint from the world
void RemoveConstraint(Constraint *inConstraint) { mConstraintManager.Remove(&inConstraint, 1); }
/// Batch add constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
void AddConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Add(inConstraints, inNumber); }
/// Batch remove constraints. Note that the inConstraints array is allowed to have nullptrs, these will be ignored.
void RemoveConstraints(Constraint **inConstraints, int inNumber) { mConstraintManager.Remove(inConstraints, inNumber); }
/// Get a list of all constraints
Constraints GetConstraints() const { return mConstraintManager.GetConstraints(); }
/// Optimize the broadphase, needed only if you've added many bodies prior to calling Update() for the first time.
void OptimizeBroadPhase();
/// Adds a new step listener
void AddStepListener(PhysicsStepListener *inListener);
/// Removes a step listener
void RemoveStepListener(PhysicsStepListener *inListener);
/// Simulate the system.
/// The world steps for a total of inDeltaTime seconds. This is divided in inCollisionSteps iterations. Each iteration
/// consists of collision detection followed by inIntegrationSubSteps integration steps.
EPhysicsUpdateError Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem);
/// Saving state for replay
void SaveState(StateRecorder &inStream) const;
/// Restoring state for replay. Returns false if failed.
bool RestoreState(StateRecorder &inStream);
#ifdef JPH_DEBUG_RENDERER
// Drawing properties
static bool sDrawMotionQualityLinearCast; ///< Draw debug info for objects that perform continuous collision detection through the linear cast motion quality
/// Draw the state of the bodies (debugging purposes)
void DrawBodies(const BodyManager::DrawSettings &inSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter = nullptr) { mBodyManager.Draw(inSettings, mPhysicsSettings, inRenderer, inBodyFilter); }
/// Draw the constraints only (debugging purposes)
void DrawConstraints(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraints(inRenderer); }
/// Draw the constraint limits only (debugging purposes)
void DrawConstraintLimits(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintLimits(inRenderer); }
/// Draw the constraint reference frames only (debugging purposes)
void DrawConstraintReferenceFrame(DebugRenderer *inRenderer) { mConstraintManager.DrawConstraintReferenceFrame(inRenderer); }
#endif // JPH_DEBUG_RENDERER
/// Set gravity value
void SetGravity(Vec3Arg inGravity) { mGravity = inGravity; }
Vec3 GetGravity() const { return mGravity; }
/// Returns a locking interface that won't actually lock the body. Use with great care!
inline const BodyLockInterfaceNoLock & GetBodyLockInterfaceNoLock() const { return mBodyLockInterfaceNoLock; }
/// Returns a locking interface that locks the body so other threads cannot modify it.
inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }
/// Get an broadphase layer filter that uses the default pair filter and a specified object layer to determine if broadphase layers collide
DefaultBroadPhaseLayerFilter GetDefaultBroadPhaseLayerFilter(ObjectLayer inLayer) const { return DefaultBroadPhaseLayerFilter(*mObjectVsBroadPhaseLayerFilter, inLayer); }
/// Get an object layer filter that uses the default pair filter and a specified layer to determine if layers collide
DefaultObjectLayerFilter GetDefaultLayerFilter(ObjectLayer inLayer) const { return DefaultObjectLayerFilter(*mObjectLayerPairFilter, inLayer); }
/// Gets the current amount of bodies that are in the body manager
uint GetNumBodies() const { return mBodyManager.GetNumBodies(); }
/// Gets the current amount of active bodies that are in the body manager
uint32 GetNumActiveBodies() const { return mBodyManager.GetNumActiveBodies(); }
/// Get the maximum amount of bodies that this physics system supports
uint GetMaxBodies() const { return mBodyManager.GetMaxBodies(); }
/// Helper struct that counts the number of bodies of each type
using BodyStats = BodyManager::BodyStats;
/// Get stats about the bodies in the body manager (slow, iterates through all bodies)
BodyStats GetBodyStats() const { return mBodyManager.GetBodyStats(); }
/// Get copy of the list of all bodies under protection of a lock.
/// @param outBodyIDs On return, this will contain the list of BodyIDs
void GetBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetBodyIDs(outBodyIDs); }
/// Get copy of the list of active bodies under protection of a lock.
/// @param outBodyIDs On return, this will contain the list of BodyIDs
void GetActiveBodies(BodyIDVector &outBodyIDs) const { return mBodyManager.GetActiveBodies(outBodyIDs); }
/// Check if 2 bodies were in contact during the last simulation step. Since contacts are only detected between active bodies, so at least one of the bodies must be active in order for this function to work.
/// It queries the state at the time of the last PhysicsSystem::Update and will return true if the bodies were in contact, even if one of the bodies was moved / removed afterwards.
/// This function can be called from any thread when the PhysicsSystem::Update is not running. During PhysicsSystem::Update this function is only valid during contact callbacks:
/// - During the ContactListener::OnContactAdded callback this function can be used to determine if a different contact pair between the bodies was active in the previous simulation step (function returns true) or if this is the first step that the bodies are touching (function returns false).
/// - During the ContactListener::OnContactRemoved callback this function can be used to determine if this is the last contact pair between the bodies (function returns false) or if there are other contacts still present (function returns true).
bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const { return mContactManager.WereBodiesInContact(inBody1ID, inBody2ID); }
#ifdef JPH_TRACK_BROADPHASE_STATS
/// Trace the accumulated broadphase stats to the TTY
void ReportBroadphaseStats() { mBroadPhase->ReportStats(); }
#endif // JPH_TRACK_BROADPHASE_STATS
private:
using CCDBody = PhysicsUpdateContext::SubStep::CCDBody;
// Various job entry points
void JobStepListeners(PhysicsUpdateContext::Step *ioStep);
void JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const;
void JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
void JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const;
void JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep);
void JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex);
void JobFinalizeIslands(PhysicsUpdateContext *ioContext);
void JobBodySetIslandIndex();
void JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
void JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
void JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
void JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const;
void JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
void JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
void JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep);
void JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep);
/// Tries to spawn a new FindCollisions job if max concurrency hasn't been reached yet
void TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const;
using ContactAllocator = ContactConstraintManager::ContactAllocator;
/// Process narrow phase for a single body pair
void ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair);
/// This helper batches up bodies that need to put to sleep to avoid contention on the activation mutex
class BodiesToSleep;
/// Called at the end of JobSolveVelocityConstraints to check if bodies need to go to sleep and to update their bounding box in the broadphase
void CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::SubStep *ioSubStep, BodiesToSleep &ioBodiesToSleep);
/// Number of constraints to process at once in JobDetermineActiveConstraints
static constexpr int cDetermineActiveConstraintsBatchSize = 64;
/// Number of bodies to process at once in JobApplyGravity
static constexpr int cApplyGravityBatchSize = 64;
/// Number of active bodies to test for collisions per batch
static constexpr int cActiveBodiesBatchSize = 16;
/// Number of active bodies to integrate velocities for
static constexpr int cIntegrateVelocityBatchSize = 64;
/// Number of contacts that need to be queued before another narrow phase job is started
static constexpr int cNarrowPhaseBatchSize = 16;
/// Number of continuous collision shape casts that need to be queued before another job is started
static constexpr int cNumCCDBodiesPerJob = 4;
/// Broadphase layer filter that decides if two objects can collide
const ObjectVsBroadPhaseLayerFilter *mObjectVsBroadPhaseLayerFilter = nullptr;
/// Object layer filter that decides if two objects can collide
const ObjectLayerPairFilter *mObjectLayerPairFilter = nullptr;
/// The body manager keeps track which bodies are in the simulation
BodyManager mBodyManager;
/// Body locking interfaces
BodyLockInterfaceNoLock mBodyLockInterfaceNoLock { mBodyManager };
BodyLockInterfaceLocking mBodyLockInterfaceLocking { mBodyManager };
/// Body interfaces
BodyInterface mBodyInterfaceNoLock;
BodyInterface mBodyInterfaceLocking;
/// Narrow phase query interface
NarrowPhaseQuery mNarrowPhaseQueryNoLock;
NarrowPhaseQuery mNarrowPhaseQueryLocking;
/// The broadphase does quick collision detection between body pairs
BroadPhase * mBroadPhase = nullptr;
/// Simulation settings
PhysicsSettings mPhysicsSettings;
/// The contact manager resolves all contacts during a simulation step
ContactConstraintManager mContactManager;
/// All non-contact constraints
ConstraintManager mConstraintManager;
/// Keeps track of connected bodies and builds islands for multithreaded velocity/position update
IslandBuilder mIslandBuilder;
/// Will split large islands into smaller groups of bodies that can be processed in parallel
LargeIslandSplitter mLargeIslandSplitter;
/// Mutex protecting mStepListeners
Mutex mStepListenersMutex;
/// List of physics step listeners
using StepListeners = Array<PhysicsStepListener *>;
StepListeners mStepListeners;
/// This is the global gravity vector
Vec3 mGravity = Vec3(0, -9.81f, 0);
/// Previous frame's delta time of one sub step to allow scaling previous frame's constraint impulses
float mPreviousSubStepDeltaTime = 0.0f;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/StateRecorderImpl.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/StateRecorder.h>
JPH_NAMESPACE_BEGIN
/// Implementation of the StateRecorder class that uses a stringstream as underlying store and that implements checking if the state doesn't change upon reading
class StateRecorderImpl final : public StateRecorder
{
public:
/// Constructor
StateRecorderImpl() = default;
StateRecorderImpl(StateRecorderImpl &&inRHS) : StateRecorder(inRHS), mStream(std::move(inRHS.mStream)) { }
/// Write a string of bytes to the binary stream
virtual void WriteBytes(const void *inData, size_t inNumBytes) override;
/// Rewind the stream for reading
void Rewind();
/// Read a string of bytes from the binary stream
virtual void ReadBytes(void *outData, size_t inNumBytes) override;
// See StreamIn
virtual bool IsEOF() const override { return mStream.eof(); }
// See StreamIn / StreamOut
virtual bool IsFailed() const override { return mStream.fail(); }
/// Compare this state with a reference state and ensure they are the same
bool IsEqual(StateRecorderImpl &inReference);
/// Convert the binary data to a string
string GetData() const { return mStream.str(); }
private:
std::stringstream mStream;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/PhysicsStepListener.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
class PhysicsSystem;
/// A listener class that receives a callback before every physics simulation step
class PhysicsStepListener
{
public:
/// Ensure virtual destructor
virtual ~PhysicsStepListener() = default;
/// Called before every simulation step (received inCollisionSteps times for every PhysicsSystem::Update(...) call)
/// This is called while all body and constraint mutexes are locked. You can read/write bodies and constraints but not add/remove them.
/// Multiple listeners can be executed in parallel and it is the responsibility of the listener to avoid race conditions.
/// The best way to do this is to have each step listener operate on a subset of the bodies and constraints
/// and making sure that these bodies and constraints are not touched by any other step listener.
/// Note that this function is not called if there aren't any active bodies or when the physics system is updated with 0 delta time.
virtual void OnStep(float inDeltaTime, PhysicsSystem &inPhysicsSystem) = 0;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/EActivation.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Enum used by AddBody to determine if the body needs to be initially active
enum class EActivation
{
Activate, ///< Activate the body, making it part of the simulation
DontActivate ///< Leave activation state as it is (will not deactivate an active body)
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/IslandBuilder.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Core/NonCopyable.h>
#include <Jolt/Core/Atomics.h>
JPH_NAMESPACE_BEGIN
class TempAllocator;
//#define JPH_VALIDATE_ISLAND_BUILDER
/// Keeps track of connected bodies and builds islands for multithreaded velocity/position update
class IslandBuilder : public NonCopyable
{
public:
/// Destructor
~IslandBuilder();
/// Initialize the island builder with the maximum amount of bodies that could be active
void Init(uint32 inMaxActiveBodies);
/// Prepare for simulation step by allocating space for the contact constraints
void PrepareContactConstraints(uint32 inMaxContactConstraints, TempAllocator *inTempAllocator);
/// Prepare for simulation step by allocating space for the non-contact constraints
void PrepareNonContactConstraints(uint32 inNumConstraints, TempAllocator *inTempAllocator);
/// Link two bodies by their index in the BodyManager::mActiveBodies list to form islands
void LinkBodies(uint32 inFirst, uint32 inSecond);
/// Link a constraint to a body by their index in the BodyManager::mActiveBodies
void LinkConstraint(uint32 inConstraintIndex, uint32 inFirst, uint32 inSecond);
/// Link a contact to a body by their index in the BodyManager::mActiveBodies
void LinkContact(uint32 inContactIndex, uint32 inFirst, uint32 inSecond);
/// Finalize the islands after all bodies have been Link()-ed
void Finalize(const BodyID *inActiveBodies, uint32 inNumActiveBodies, uint32 inNumContacts, TempAllocator *inTempAllocator);
/// Get the amount of islands formed
uint32 GetNumIslands() const { return mNumIslands; }
/// Get iterator for a particular island, return false if there are no constraints
void GetBodiesInIsland(uint32 inIslandIndex, BodyID *&outBodiesBegin, BodyID *&outBodiesEnd) const;
bool GetConstraintsInIsland(uint32 inIslandIndex, uint32 *&outConstraintsBegin, uint32 *&outConstraintsEnd) const;
bool GetContactsInIsland(uint32 inIslandIndex, uint32 *&outContactsBegin, uint32 *&outContactsEnd) const;
/// After you're done calling the three functions above, call this function to free associated data
void ResetIslands(TempAllocator *inTempAllocator);
private:
/// Returns the index of the lowest body in the group
uint32 GetLowestBodyIndex(uint32 inActiveBodyIndex) const;
#ifdef JPH_VALIDATE_ISLAND_BUILDER
/// Helper function to validate all islands so far generated
void ValidateIslands(uint32 inNumActiveBodies) const;
#endif
// Helper functions to build various islands
void BuildBodyIslands(const BodyID *inActiveBodies, uint32 inNumActiveBodies, TempAllocator *inTempAllocator);
void BuildConstraintIslands(const uint32 *inConstraintToBody, uint32 inNumConstraints, uint32 *&outConstraints, uint32 *&outConstraintsEnd, TempAllocator *inTempAllocator) const;
/// Sorts the islands so that the islands with most constraints go first
void SortIslands(TempAllocator *inTempAllocator);
/// Intermediate data structure that for each body keeps track what the lowest index of the body is that it is connected to
struct BodyLink
{
JPH_OVERRIDE_NEW_DELETE
atomic<uint32> mLinkedTo; ///< An index in mBodyLinks pointing to another body in this island with a lower index than this body
uint32 mIslandIndex; ///< The island index of this body (filled in during Finalize)
};
// Intermediate data
BodyLink * mBodyLinks = nullptr; ///< Maps bodies to the first body in the island
uint32 * mConstraintLinks = nullptr; ///< Maps constraint index to body index (which maps to island index)
uint32 * mContactLinks = nullptr; ///< Maps contact constraint index to body index (which maps to island index)
// Final data
BodyID * mBodyIslands = nullptr; ///< Bodies ordered by island
uint32 * mBodyIslandEnds = nullptr; ///< End index of each body island
uint32 * mConstraintIslands = nullptr; ///< Constraints ordered by island
uint32 * mConstraintIslandEnds = nullptr; ///< End index of each constraint island
uint32 * mContactIslands = nullptr; ///< Contacts ordered by island
uint32 * mContactIslandEnds = nullptr; ///< End index of each contact island
uint32 * mIslandsSorted = nullptr; ///< A list of island indices in order of most constraints first
// Counters
uint32 mMaxActiveBodies; ///< Maximum size of the active bodies list (see BodyManager::mActiveBodies)
uint32 mNumActiveBodies = 0; ///< Number of active bodies passed to
uint32 mNumConstraints = 0; ///< Size of the constraint list (see ConstraintManager::mConstraints)
uint32 mMaxContacts = 0; ///< Maximum amount of contacts supported
uint32 mNumContacts = 0; ///< Size of the contacts list (see ContactConstraintManager::mNumConstraints)
uint32 mNumIslands = 0; ///< Final number of islands
#ifdef JPH_VALIDATE_ISLAND_BUILDER
/// Structure to keep track of all added links to validate that islands were generated correctly
struct LinkValidation
{
uint32 mFirst;
uint32 mSecond;
};
LinkValidation * mLinkValidation = nullptr;
atomic<uint32> mNumLinkValidation;
#endif
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/PhysicsSettings.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// If objects are closer than this distance, they are considered to be colliding (used for GJK) (unit: meter)
constexpr float cDefaultCollisionTolerance = 1.0e-4f;
/// A factor that determines the accuracy of the penetration depth calculation. If the change of the squared distance is less than tolerance * current_penetration_depth^2 the algorithm will terminate. (unit: dimensionless)
constexpr float cDefaultPenetrationTolerance = 1.0e-4f; ///< Stop when there's less than 1% change
/// How much padding to add around objects
constexpr float cDefaultConvexRadius = 0.05f;
/// Used by (Tapered)CapsuleShape to determine when supporting face is an edge rather than a point (unit: meter)
static constexpr float cCapsuleProjectionSlop = 0.02f;
/// Maximum amount of jobs to allow
constexpr int cMaxPhysicsJobs = 2048;
/// Maximum amount of barriers to allow
constexpr int cMaxPhysicsBarriers = 8;
struct PhysicsSettings
{
JPH_OVERRIDE_NEW_DELETE
/// Size of body pairs array, corresponds to the maximum amount of potential body pairs that can be in flight at any time.
/// Setting this to a low value will use less memory but slow down simulation as threads may run out of narrow phase work.
int mMaxInFlightBodyPairs = 16384;
/// How many PhysicsStepListeners to notify in 1 batch
int mStepListenersBatchSize = 8;
/// How many step listener batches are needed before spawning another job (set to INT_MAX if no parallelism is desired)
int mStepListenerBatchesPerJob = 1;
/// Baumgarte stabilization factor (how much of the position error to 'fix' in 1 update) (unit: dimensionless, 0 = nothing, 1 = 100%)
float mBaumgarte = 0.2f;
/// Radius around objects inside which speculative contact points will be detected. Note that if this is too big
/// you will get ghost collisions as speculative contacts are based on the closest points during the collision detection
/// step which may not be the actual closest points by the time the two objects hit (unit: meters)
float mSpeculativeContactDistance = 0.02f;
/// How much bodies are allowed to sink into eachother (unit: meters)
float mPenetrationSlop = 0.02f;
/// Fraction of its inner radius a body must move per step to enable casting for the LinearCast motion quality
float mLinearCastThreshold = 0.75f;
/// Fraction of its inner radius a body may penetrate another body for the LinearCast motion quality
float mLinearCastMaxPenetration = 0.25f;
/// Max squared distance to use to determine if two points are on the same plane for determining the contact manifold between two shape faces (unit: meter^2)
float mManifoldToleranceSq = 1.0e-6f;
/// Maximum distance to correct in a single iteration when solving position constraints (unit: meters)
float mMaxPenetrationDistance = 0.2f;
/// Maximum relative delta position for body pairs to be able to reuse collision results from last frame (units: meter^2)
float mBodyPairCacheMaxDeltaPositionSq = Square(0.001f); ///< 1 mm
/// Maximum relative delta orientation for body pairs to be able to reuse collision results from last frame, stored as cos(max angle / 2)
float mBodyPairCacheCosMaxDeltaRotationDiv2 = 0.99984769515639123915701155881391f; ///< cos(2 degrees / 2)
/// Maximum angle between normals that allows manifolds between different sub shapes of the same body pair to be combined
float mContactNormalCosMaxDeltaRotation = 0.99619469809174553229501040247389f; ///< cos(5 degree)
/// Maximum allowed distance between old and new contact point to preserve contact forces for warm start (units: meter^2)
float mContactPointPreserveLambdaMaxDistSq = Square(0.01f); ///< 1 cm
/// Number of solver velocity iterations to run
/// Note that this needs to be >= 2 in order for friction to work (friction is applied using the non-penetration impulse from the previous iteration)
int mNumVelocitySteps = 10;
/// Number of solver position iterations to run
int mNumPositionSteps = 2;
/// Minimal velocity needed before a collision can be elastic (unit: m)
float mMinVelocityForRestitution = 1.0f;
/// Time before object is allowed to go to sleep (unit: seconds)
float mTimeBeforeSleep = 0.5f;
/// Velocity of points on bounding box of object below which an object can be considered sleeping (unit: m/s)
float mPointVelocitySleepThreshold = 0.03f;
/// By default the simulation is deterministic, it is possible to turn this off by setting this setting to false. This will make the simulation run faster but it will no longer be deterministic.
bool mDeterministicSimulation = true;
///@name These variables are mainly for debugging purposes, they allow turning on/off certain subsystems. You probably want to leave them alone.
///@{
/// Whether or not to use warm starting for constraints (initially applying previous frames impulses)
bool mConstraintWarmStart = true;
/// Whether or not to use the body pair cache, which removes the need for narrow phase collision detection when orientation between two bodies didn't change
bool mUseBodyPairContactCache = true;
/// Whether or not to reduce manifolds with similar contact normals into one contact manifold
bool mUseManifoldReduction = true;
/// If we split up large islands into smaller parallel batches of work (to improve performance)
bool mUseLargeIslandSplitter = true;
/// If objects can go to sleep or not
bool mAllowSleeping = true;
/// When false, we prevent collision against non-active (shared) edges. Mainly for debugging the algorithm.
bool mCheckActiveEdges = true;
///@}
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include | repos/c2z/use_cases/JoltPhysics/include/Physics/PhysicsScene.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Reference.h>
#include <Jolt/Physics/Body/BodyCreationSettings.h>
#include <Jolt/Physics/Constraints/TwoBodyConstraint.h>
JPH_NAMESPACE_BEGIN
class PhysicsSystem;
/// Contains the creation settings of a set of bodies
class PhysicsScene : public RefTarget<PhysicsScene>
{
public:
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(PhysicsScene)
/// Add a body to the scene
void AddBody(const BodyCreationSettings &inBody);
/// Body constant to use to indicate that the constraint is attached to the fixed world
static constexpr uint32 cFixedToWorld = 0xffffffff;
/// Add a constraint to the scene
/// @param inConstraint Constraint settings
/// @param inBody1 Index in the bodies list of first body to attach constraint to
/// @param inBody2 Index in the bodies list of the second body to attach constraint to
void AddConstraint(const TwoBodyConstraintSettings *inConstraint, uint32 inBody1, uint32 inBody2);
/// Get number of bodies in this scene
size_t GetNumBodies() const { return mBodies.size(); }
/// Access to the body settings for this scene
const Array<BodyCreationSettings> & GetBodies() const { return mBodies; }
Array<BodyCreationSettings> & GetBodies() { return mBodies; }
/// A constraint and how it is connected to the bodies in the scene
class ConnectedConstraint
{
public:
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(ConnectedConstraint)
ConnectedConstraint() = default;
ConnectedConstraint(const TwoBodyConstraintSettings *inSettings, uint inBody1, uint inBody2) : mSettings(inSettings), mBody1(inBody1), mBody2(inBody2) { }
RefConst<TwoBodyConstraintSettings> mSettings; ///< Constraint settings
uint32 mBody1; ///< Index of first body (in mBodies)
uint32 mBody2; ///< Index of second body (in mBodies)
};
/// Get number of constraints in this scene
size_t GetNumConstraints() const { return mConstraints.size(); }
/// Access to the constraints for this scene
const Array<ConnectedConstraint> & GetConstraints() const { return mConstraints; }
Array<ConnectedConstraint> & GetConstraints() { return mConstraints; }
/// Instantiate all bodies, returns false if not all bodies could be created
bool CreateBodies(PhysicsSystem *inSystem) const;
/// Go through all body creation settings and fix shapes that are scaled incorrectly (note this will change the scene a bit).
/// @return False when not all scales could be fixed.
bool FixInvalidScales();
/// Saves the state of this object in binary form to inStream.
/// @param inStream The stream to save the state to
/// @param inSaveShapes If the shapes should be saved as well (these could be shared between physics scenes, in which case the calling application may want to write custom code to restore them)
/// @param inSaveGroupFilter If the group filter should be saved as well (these could be shared)
void SaveBinaryState(StreamOut &inStream, bool inSaveShapes, bool inSaveGroupFilter) const;
using PhysicsSceneResult = Result<Ref<PhysicsScene>>;
/// Restore a saved scene from inStream
static PhysicsSceneResult sRestoreFromBinaryState(StreamIn &inStream);
/// For debugging purposes: Construct a scene from the current state of the physics system
void FromPhysicsSystem(const PhysicsSystem *inSystem);
private:
/// The bodies that are part of this scene
Array<BodyCreationSettings> mBodies;
/// Constraints that are part of this scene
Array<ConnectedConstraint> mConstraints;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Character/CharacterVirtual.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Character/CharacterBase.h>
#include <Jolt/Physics/Body/MotionType.h>
#include <Jolt/Physics/Body/BodyFilter.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
#include <Jolt/Physics/Collision/ObjectLayer.h>
#include <Jolt/Core/STLTempAllocator.h>
JPH_NAMESPACE_BEGIN
class CharacterVirtual;
/// Contains the configuration of a character
class CharacterVirtualSettings : public CharacterBaseSettings
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Character mass (kg). Used to push down objects with gravity when the character is standing on top.
float mMass = 70.0f;
/// Maximum force with which the character can push other bodies (N).
float mMaxStrength = 100.0f;
/// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
Vec3 mShapeOffset = Vec3::sZero();
///@name Movement settings
EBackFaceMode mBackFaceMode = EBackFaceMode::CollideWithBackFaces; ///< When colliding with back faces, the character will not be able to move through back facing triangles. Use this if you have triangles that need to collide on both sides.
float mPredictiveContactDistance = 0.1f; ///< How far to scan outside of the shape for predictive contacts. A value of 0 will most likely cause the character to get stuck as it properly calculate a sliding direction anymore. A value that's too high will cause ghost collisions.
uint mMaxCollisionIterations = 5; ///< Max amount of collision loops
uint mMaxConstraintIterations = 15; ///< How often to try stepping in the constraint solving
float mMinTimeRemaining = 1.0e-4f; ///< Early out condition: If this much time is left to simulate we are done
float mCollisionTolerance = 1.0e-3f; ///< How far we're willing to penetrate geometry
float mCharacterPadding = 0.02f; ///< How far we try to stay away from the geometry, this ensures that the sweep will hit as little as possible lowering the collision cost and reducing the risk of getting stuck
uint mMaxNumHits = 256; ///< Max num hits to collect in order to avoid excess of contact points collection
float mHitReductionCosMaxAngle = 0.999f; ///< Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
float mPenetrationRecoverySpeed = 1.0f; ///< This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
};
/// This class contains settings that allow you to override the behavior of a character's collision response
class CharacterContactSettings
{
public:
bool mCanPushCharacter = true; ///< True when the object can push the virtual character
bool mCanReceiveImpulses = true; ///< True when the virtual character can apply impulses (push) the body
};
/// This class receives callbacks when a virtual character hits something.
class CharacterContactListener
{
public:
/// Destructor
virtual ~CharacterContactListener() = default;
/// Callback to adjust the velocity of a body as seen by the character. Can be adjusted to e.g. implement a conveyor belt or an inertial dampener system of a sci-fi space ship.
/// Note that inBody2 is locked during the callback so you can read its properties freely.
virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }
/// Checks if a character can collide with specified body. Return true if the contact is valid.
virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }
/// Called whenever the character collides with a body. Returns true if the contact can push the character.
/// @param inCharacter Character that is being solved
/// @param inBodyID2 Body ID of body that is being hit
/// @param inSubShapeID2 Sub shape ID of shape that is being hit
/// @param inContactPosition World space contact position
/// @param inContactNormal World space contact normal
/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave
virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
/// Called whenever a contact is being used by the solver. Allows the listener to override the resulting character velocity (e.g. by preventing sliding along certain surfaces).
/// @param inCharacter Character that is being solved
/// @param inBodyID2 Body ID of body that is being hit
/// @param inSubShapeID2 Sub shape ID of shape that is being hit
/// @param inContactPosition World space contact position
/// @param inContactNormal World space contact normal
/// @param inContactVelocity World space velocity of contact point (e.g. for a moving platform)
/// @param inContactMaterial Material of contact point
/// @param inCharacterVelocity World space velocity of the character prior to hitting this contact
/// @param ioNewCharacterVelocity Contains the calculated world space velocity of the character after hitting this contact, this velocity slides along the surface of the contact. Can be modified by the listener to provide an alternative velocity.
virtual void OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) { /* Default do nothing */ }
};
/// Runtime character object.
/// This object usually represents the player. Contrary to the Character class it doesn't use a rigid body but moves doing collision checks only (hence the name virtual).
/// The advantage of this is that you can determine when the character moves in the frame (usually this has to happen at a very particular point in the frame)
/// but the downside is that other objects don't see this virtual character. In order to make this work it is recommended to pair a CharacterVirtual with a Character that
/// moves along. This Character should be keyframed (or at least have no gravity) and move along with the CharacterVirtual so that other rigid bodies can collide with it.
class CharacterVirtual : public CharacterBase
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
/// @param inSettings The settings for the character
/// @param inPosition Initial position for the character
/// @param inRotation Initial rotation for the character (usually only around the up-axis)
/// @param inSystem Physics system that this character will be added to later
CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem);
/// Set the contact listener
void SetListener(CharacterContactListener *inListener) { mListener = inListener; }
/// Get the current contact listener
CharacterContactListener * GetListener() const { return mListener; }
/// Get the linear velocity of the character (m / s)
Vec3 GetLinearVelocity() const { return mLinearVelocity; }
/// Set the linear velocity of the character (m / s)
void SetLinearVelocity(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; }
/// Get the position of the character
RVec3 GetPosition() const { return mPosition; }
/// Set the position of the character
void SetPosition(RVec3Arg inPosition) { mPosition = inPosition; }
/// Get the rotation of the character
Quat GetRotation() const { return mRotation; }
/// Set the rotation of the character
void SetRotation(QuatArg inRotation) { mRotation = inRotation; }
/// Calculate the world transform of the character
RMat44 GetWorldTransform() const { return RMat44::sRotationTranslation(mRotation, mPosition); }
/// Calculates the transform for this character's center of mass
RMat44 GetCenterOfMassTransform() const { return GetCenterOfMassTransform(mPosition, mRotation, mShape); }
/// Character mass (kg)
float GetMass() const { return mMass; }
void SetMass(float inMass) { mMass = inMass; }
/// Maximum force with which the character can push other bodies (N)
float GetMaxStrength() const { return mMaxStrength; }
void SetMaxStrength(float inMaxStrength) { mMaxStrength = inMaxStrength; }
/// This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
float GetPenetrationRecoverySpeed() const { return mPenetrationRecoverySpeed; }
void SetPenetrationRecoverySpeed(float inSpeed) { mPenetrationRecoverySpeed = inSpeed; }
/// Character padding
float GetCharacterPadding() const { return mCharacterPadding; }
/// Max num hits to collect in order to avoid excess of contact points collection
uint GetMaxNumHits() const { return mMaxNumHits; }
void SetMaxNumHits(uint inMaxHits) { mMaxNumHits = inMaxHits; }
/// Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
float GetHitReductionCosMaxAngle() const { return mHitReductionCosMaxAngle; }
void SetHitReductionCosMaxAngle(float inCosMaxAngle) { mHitReductionCosMaxAngle = inCosMaxAngle; }
/// Returns if we exceeded the maximum number of hits during the last collision check and had to discard hits based on distance.
/// This can be used to find areas that have too complex geometry for the character to navigate properly.
/// To solve you can either increase the max number of hits or simplify the geometry. Note that the character simulation will
/// try to do its best to select the most relevant contacts to avoid the character from getting stuck.
bool GetMaxHitsExceeded() const { return mMaxHitsExceeded; }
/// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space. Note that setting it on the fly can cause the shape to teleport into collision.
Vec3 GetShapeOffset() const { return mShapeOffset; }
void SetShapeOffset(Vec3Arg inShapeOffset) { mShapeOffset = inShapeOffset; }
/// This function can be called prior to calling Update() to convert a desired velocity into a velocity that won't make the character move further onto steep slopes.
/// This velocity can then be set on the character using SetLinearVelocity()
/// @param inDesiredVelocity Velocity to clamp against steep walls
/// @return A new velocity vector that won't make the character move up steep slopes
Vec3 CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const;
/// This is the main update function. It moves the character according to its current velocity (the character is similar to a kinematic body in the sense
/// that you set the velocity and the character will follow unless collision is blocking the way). Note it's your own responsibility to apply gravity to the character velocity!
/// Different surface materials (like ice) can be emulated by getting the ground material and adjusting the velocity and/or the max slope angle accordingly every frame.
/// @param inDeltaTime Time step to simulate.
/// @param inGravity Gravity vector (m/s^2). This gravity vector is only used when the character is standing on top of another object to apply downward force.
/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
/// @param inBodyFilter Filter that is used to check if a character collides with a body.
/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
void Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
/// This function will return true if the character has moved into a slope that is too steep (e.g. a vertical wall).
/// You would call WalkStairs to attempt to step up stairs.
/// @param inLinearVelocity The linear velocity that the player desired. This is used to determine if we're pusing into a step.
bool CanWalkStairs(Vec3Arg inLinearVelocity) const;
/// When stair walking is needed, you can call the WalkStairs function to cast up, forward and down again to try to find a valid position
/// @param inDeltaTime Time step to simulate.
/// @param inStepUp The direction and distance to step up (this corresponds to the max step height)
/// @param inStepForward The direction and distance to step forward after the step up
/// @param inStepForwardTest When running at a high frequency, inStepForward can be very small and it's likely that you hit the side of the stairs on the way down. This could produce a normal that violates the max slope angle. If this happens, we test again using this distance from the up position to see if we find a valid slope.
/// @param inStepDownExtra An additional translation that is added when stepping down at the end. Allows you to step further down than up. Set to zero if you don't want this. Should be in the opposite direction of up.
/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
/// @param inBodyFilter Filter that is used to check if a character collides with a body.
/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
/// @return true if the stair walk was successful
bool WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg inStepForward, Vec3Arg inStepForwardTest, Vec3Arg inStepDownExtra, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
/// This function can be used to artificially keep the character to the floor. Normally when a character is on a small step and starts moving horizontally, the character will
/// lose contact with the floor because the initial vertical velocity is zero while the horizontal velocity is quite high. To prevent the character from losing contact with the floor,
/// we do an additional collision check downwards and if we find the floor within a certain distance, we project the character onto the floor.
/// @param inStepDown Max amount to project the character downwards (if no floor is found within this distance, the function will return false)
/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
/// @param inBodyFilter Filter that is used to check if a character collides with a body.
/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
/// @return True if the character was successfully projected onto the floor.
bool StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
/// Settings struct with settings for ExtendedUpdate
struct ExtendedUpdateSettings
{
Vec3 mStickToFloorStepDown { 0, -0.5f, 0 }; ///< See StickToFloor inStepDown parameter. Can be zero to turn off.
Vec3 mWalkStairsStepUp { 0, 0.4f, 0 }; ///< See WalkStairs inStepUp parameter. Can be zero to turn off.
float mWalkStairsMinStepForward { 0.02f }; ///< See WalkStairs inStepForward parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
float mWalkStairsStepForwardTest { 0.15f }; ///< See WalkStairs inStepForwardTest parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
float mWalkStairsCosAngleForwardContact { Cos(DegreesToRadians(75.0f)) }; ///< Cos(angle) where angle is the maximum angle between the ground normal in the horizontal plane and the character forward vector where we're willing to adjust the step forward test towards the contact normal.
Vec3 mWalkStairsStepDownExtra { Vec3::sZero() }; ///< See WalkStairs inStepDownExtra
};
/// This function combines Update, StickToFloor and WalkStairs. This function serves as an example of how these functions could be combined.
/// Before calling, call SetLinearVelocity to update the horizontal/vertical speed of the character, typically this is:
/// - When on OnGround and not moving away from ground: velocity = GetGroundVelocity() + horizontal speed as input by player + optional vertical jump velocity + delta time * gravity
/// - Else: velocity = current vertical velocity + horizontal speed as input by player + delta time * gravity
/// @param inDeltaTime Time step to simulate.
/// @param inGravity Gravity vector (m/s^2). This gravity vector is only used when the character is standing on top of another object to apply downward force.
/// @param inSettings A structure containing settings for the algorithm.
/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
/// @param inBodyFilter Filter that is used to check if a character collides with a body.
/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
void ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
/// This function can be used after a character has teleported to determine the new contacts with the world.
void RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
/// Use the ground body ID to get an updated estimate of the ground velocity. This function can be used if the ground body has moved / changed velocity and you want a new estimate of the ground velocity.
/// It will not perform collision detection, so is less accurate than RefreshContacts but a lot faster.
void UpdateGroundVelocity();
/// Switch the shape of the character (e.g. for stance).
/// @param inShape The shape to switch to.
/// @param inMaxPenetrationDepth When inMaxPenetrationDepth is not FLT_MAX, it checks if the new shape collides before switching shape. This is the max penetration we're willing to accept after the switch.
/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
/// @param inBodyFilter Filter that is used to check if a character collides with a body.
/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
/// @return Returns true if the switch succeeded.
bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
/// @brief Get all contacts for the character at a particular location
/// @param inPosition Position to test, note that this position will be corrected for the character padding.
/// @param inRotation Rotation at which to test the shape.
/// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.
/// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).
/// @param inShape Shape to test collision with.
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. GetPosition() since floats are most accurate near the origin
/// @param ioCollector Collision collector that receives the collision results.
/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
/// @param inBodyFilter Filter that is used to check if a character collides with a body.
/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
void CheckCollision(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inMovementDirection, float inMaxSeparationDistance, const Shape *inShape, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
// Saving / restoring state for replay
virtual void SaveState(StateRecorder &inStream) const override;
virtual void RestoreState(StateRecorder &inStream) override;
#ifdef JPH_DEBUG_RENDERER
static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating them
static inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithm
static inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm
#endif
// Encapsulates a collision contact
struct Contact
{
// Saving / restoring state for replay
void SaveState(StateRecorder &inStream) const;
void RestoreState(StateRecorder &inStream);
RVec3 mPosition; ///< Position where the character makes contact
Vec3 mLinearVelocity; ///< Velocity of the contact point
Vec3 mContactNormal; ///< Contact normal, pointing towards the character
Vec3 mSurfaceNormal; ///< Surface normal of the contact
float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive
float mFraction; ///< Fraction along the path where this contact takes place
BodyID mBodyB; ///< ID of body we're colliding with
SubShapeID mSubShapeIDB; ///< Sub shape ID of body we're colliding with
EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact
uint64 mUserData; ///< User data of B
const PhysicsMaterial * mMaterial; ///< Material of B
bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)
bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact
bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character
};
using TempContactList = std::vector<Contact, STLTempAllocator<Contact>>;
using ContactList = Array<Contact>;
/// Access to the internal list of contacts that the character has found.
const ContactList & GetActiveContacts() const { return mActiveContacts; }
private:
// A contact that needs to be ignored
struct IgnoredContact
{
IgnoredContact() = default;
IgnoredContact(const BodyID &inBodyID, const SubShapeID &inSubShapeID) : mBodyID(inBodyID), mSubShapeID(inSubShapeID) { }
BodyID mBodyID; ///< ID of body we're colliding with
SubShapeID mSubShapeID; ///< Sub shape of body we're colliding with
};
using IgnoredContactList = std::vector<IgnoredContact, STLTempAllocator<IgnoredContact>>;
// A constraint that limits the movement of the character
struct Constraint
{
Contact * mContact; ///< Contact that this constraint was generated from
float mTOI; ///< Calculated time of impact (can be negative if penetrating)
float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)
Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)
Plane mPlane; ///< Plane around the origin that describes how far we can displace (from the origin)
};
using ConstraintList = std::vector<Constraint, STLTempAllocator<Constraint>>;
// Collision collector that collects hits for CollideShape
class ContactCollector : public CollideShapeCollector
{
public:
ContactCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, uint inMaxHits, float inHitReductionCosMaxAngle, Vec3Arg inUp, RVec3Arg inBaseOffset, TempContactList &outContacts) : mBaseOffset(inBaseOffset), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mContacts(outContacts), mMaxHits(inMaxHits), mHitReductionCosMaxAngle(inHitReductionCosMaxAngle) { }
virtual void AddHit(const CollideShapeResult &inResult) override;
RVec3 mBaseOffset;
Vec3 mUp;
PhysicsSystem * mSystem;
const CharacterVirtual * mCharacter;
TempContactList & mContacts;
uint mMaxHits;
float mHitReductionCosMaxAngle;
bool mMaxHitsExceeded = false;
};
// A collision collector that collects hits for CastShape
class ContactCastCollector : public CastShapeCollector
{
public:
ContactCastCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, Vec3Arg inDisplacement, Vec3Arg inUp, const IgnoredContactList &inIgnoredContacts, RVec3Arg inBaseOffset, Contact &outContact) : mBaseOffset(inBaseOffset), mDisplacement(inDisplacement), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mIgnoredContacts(inIgnoredContacts), mContact(outContact) { }
virtual void AddHit(const ShapeCastResult &inResult) override;
RVec3 mBaseOffset;
Vec3 mDisplacement;
Vec3 mUp;
PhysicsSystem * mSystem;
const CharacterVirtual * mCharacter;
const IgnoredContactList & mIgnoredContacts;
Contact & mContact;
};
// Helper function to convert a Jolt collision result into a contact
template <class taCollector>
inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);
// Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometry
void MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator
#ifdef JPH_DEBUG_RENDERER
, bool inDrawConstraints = false
#endif // JPH_DEBUG_RENDERER
) const;
// Ask the callback if inContact is a valid contact point
bool ValidateContact(const Contact &inContact) const;
// Tests the shape for collision around inPosition
void GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
// Remove penetrating contacts with the same body that have conflicting normals, leaving these will make the character mover get stuck
void RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const;
// Convert contacts into constraints. The character is assumed to start at the origin and the constraints are planes around the origin that confine the movement of the character.
void DetermineConstraints(TempContactList &inContacts, ConstraintList &outConstraints) const;
// Use the constraints to solve the displacement of the character. This will slide the character on the planes around the origin for as far as possible.
void SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator
#ifdef JPH_DEBUG_RENDERER
, bool inDrawConstraints = false
#endif // JPH_DEBUG_RENDERER
) const;
// Get the velocity of a body adjusted by the contact listener
void GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const;
// Calculate the ground velocity of the character assuming it's standing on an object with specified linear and angular velocity and with specified center of mass.
// Note that we don't just take the point velocity because a point on an object with angular velocity traces an arc,
// so if you just take point velocity * delta time you get an error that accumulates over time
Vec3 CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass, Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, float inDeltaTime) const;
// Handle contact with physics object that we're colliding against
bool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime) const;
// Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision
bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
// Store contacts so that we have proper ground information
void StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);
// This function will determine which contacts are touching the character and will calculate the one that is supporting us
void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);
/// This function can be called after moving the character to a new colliding position
void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
// This function returns the actual center of mass of the shape, not corrected for the character padding
inline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const
{
return RMat44::sRotationTranslation(inRotation, inPosition).PreTranslated(mShapeOffset + inShape->GetCenterOfMass()).PostTranslated(mCharacterPadding * mUp);
}
// Our main listener for contacts
CharacterContactListener * mListener = nullptr;
// Movement settings
EBackFaceMode mBackFaceMode; // When colliding with back faces, the character will not be able to move through back facing triangles. Use this if you have triangles that need to collide on both sides.
float mPredictiveContactDistance; // How far to scan outside of the shape for predictive contacts. A value of 0 will most likely cause the character to get stuck as it properly calculate a sliding direction anymore. A value that's too high will cause ghost collisions.
uint mMaxCollisionIterations; // Max amount of collision loops
uint mMaxConstraintIterations; // How often to try stepping in the constraint solving
float mMinTimeRemaining; // Early out condition: If this much time is left to simulate we are done
float mCollisionTolerance; // How far we're willing to penetrate geometry
float mCharacterPadding; // How far we try to stay away from the geometry, this ensures that the sweep will hit as little as possible lowering the collision cost and reducing the risk of getting stuck
uint mMaxNumHits; // Max num hits to collect in order to avoid excess of contact points collection
float mHitReductionCosMaxAngle; // Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
float mPenetrationRecoverySpeed; // This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
// Character mass (kg)
float mMass;
// Maximum force with which the character can push other bodies (N)
float mMaxStrength;
// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
Vec3 mShapeOffset = Vec3::sZero();
// Current position (of the base, not the center of mass)
RVec3 mPosition = RVec3::sZero();
// Current rotation (of the base, not of the center of mass)
Quat mRotation = Quat::sIdentity();
// Current linear velocity
Vec3 mLinearVelocity = Vec3::sZero();
// List of contacts that were active in the last frame
ContactList mActiveContacts;
// Remembers the delta time of the last update
float mLastDeltaTime = 1.0f / 60.0f;
// Remember if we exceeded the maximum number of hits and had to remove similar contacts
mutable bool mMaxHitsExceeded = false;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Character/CharacterBase.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Reference.h>
#include <Jolt/Core/NonCopyable.h>
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Physics/Collision/PhysicsMaterial.h>
JPH_NAMESPACE_BEGIN
class PhysicsSystem;
class StateRecorder;
/// Base class for configuration of a character
class CharacterBaseSettings : public RefTarget<CharacterBaseSettings>
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Virtual destructor
virtual ~CharacterBaseSettings() = default;
/// Vector indicating the up direction of the character
Vec3 mUp = Vec3::sAxisY();
/// Plane, defined in local space relative to the character. Every contact behind this plane can support the
/// character, every contact in front of this plane is treated as only colliding with the player.
/// Default: Accept any contact.
Plane mSupportingVolume { Vec3::sAxisY(), -1.0e10f };
/// Maximum angle of slope that character can still walk on (radians).
float mMaxSlopeAngle = DegreesToRadians(50.0f);
/// Initial shape that represents the character's volume.
/// Usually this is a capsule, make sure the shape is made so that the bottom of the shape is at (0, 0, 0).
RefConst<Shape> mShape;
};
/// Base class for character class
class CharacterBase : public RefTarget<CharacterBase>, public NonCopyable
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
CharacterBase(const CharacterBaseSettings *inSettings, PhysicsSystem *inSystem);
/// Destructor
virtual ~CharacterBase() = default;
/// Set the maximum angle of slope that character can still walk on (radians)
void SetMaxSlopeAngle(float inMaxSlopeAngle) { mCosMaxSlopeAngle = Cos(inMaxSlopeAngle); }
float GetCosMaxSlopeAngle() const { return mCosMaxSlopeAngle; }
/// Set the up vector for the character
void SetUp(Vec3Arg inUp) { mUp = inUp; }
Vec3 GetUp() const { return mUp; }
/// Check if the normal of the ground surface is too steep to walk on
bool IsSlopeTooSteep(Vec3Arg inNormal) const
{
// If cos max slope angle is close to one the system is turned off,
// otherwise check the angle between the up and normal vector
return mCosMaxSlopeAngle < cNoMaxSlopeAngle && inNormal.Dot(mUp) < mCosMaxSlopeAngle;
}
/// Get the current shape that the character is using.
const Shape * GetShape() const { return mShape; }
enum class EGroundState
{
OnGround, ///< Character is on the ground and can move freely.
OnSteepGround, ///< Character is on a slope that is too steep and can't climb up any further. The caller should start applying downward velocity if sliding from the slope is desired.
NotSupported, ///< Character is touching an object, but is not supported by it and should fall. The GetGroundXXX functions will return information about the touched object.
InAir, ///< Character is in the air and is not touching anything.
};
///@name Properties of the ground this character is standing on
/// Current ground state
EGroundState GetGroundState() const { return mGroundState; }
/// Returns true if the player is supported by normal or steep ground
bool IsSupported() const { return mGroundState == EGroundState::OnGround || mGroundState == EGroundState::OnSteepGround; }
/// Get the contact point with the ground
RVec3 GetGroundPosition() const { return mGroundPosition; }
/// Get the contact normal with the ground
Vec3 GetGroundNormal() const { return mGroundNormal; }
/// Velocity in world space of ground
Vec3 GetGroundVelocity() const { return mGroundVelocity; }
/// Material that the character is standing on
const PhysicsMaterial * GetGroundMaterial() const { return mGroundMaterial; }
/// BodyID of the object the character is standing on. Note may have been removed!
BodyID GetGroundBodyID() const { return mGroundBodyID; }
/// Sub part of the body that we're standing on.
SubShapeID GetGroundSubShapeID() const { return mGroundBodySubShapeID; }
/// User data value of the body that we're standing on
uint64 GetGroundUserData() const { return mGroundUserData; }
// Saving / restoring state for replay
virtual void SaveState(StateRecorder &inStream) const;
virtual void RestoreState(StateRecorder &inStream);
protected:
// Cached physics system
PhysicsSystem * mSystem;
// The shape that the body currently has
RefConst<Shape> mShape;
// The character's world space up axis
Vec3 mUp;
// Every contact behind this plane can support the character
Plane mSupportingVolume;
// Beyond this value there is no max slope
static constexpr float cNoMaxSlopeAngle = 0.9999f;
// Cosine of the maximum angle of slope that character can still walk on
float mCosMaxSlopeAngle;
// Ground properties
EGroundState mGroundState = EGroundState::InAir;
BodyID mGroundBodyID;
SubShapeID mGroundBodySubShapeID;
RVec3 mGroundPosition = RVec3::sZero();
Vec3 mGroundNormal = Vec3::sZero();
Vec3 mGroundVelocity = Vec3::sZero();
RefConst<PhysicsMaterial> mGroundMaterial = PhysicsMaterial::sDefault;
uint64 mGroundUserData = 0;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Character/Character.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Character/CharacterBase.h>
#include <Jolt/Physics/EActivation.h>
JPH_NAMESPACE_BEGIN
/// Contains the configuration of a character
class CharacterSettings : public CharacterBaseSettings
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Layer that this character will be added to
ObjectLayer mLayer = 0;
/// Mass of the character
float mMass = 80.0f;
/// Friction for the character
float mFriction = 0.2f;
/// Value to multiply gravity with for this character
float mGravityFactor = 1.0f;
};
/// Runtime character object.
/// This object usually represents the player or a humanoid AI. It uses a single rigid body,
/// usually with a capsule shape to simulate movement and collision for the character.
/// The character is a keyframed object, the application controls it by setting the velocity.
class Character : public CharacterBase
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
/// @param inSettings The settings for the character
/// @param inPosition Initial position for the character
/// @param inRotation Initial rotation for the character (usually only around Y)
/// @param inUserData Application specific value
/// @param inSystem Physics system that this character will be added to later
Character(const CharacterSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, uint64 inUserData, PhysicsSystem *inSystem);
/// Destructor
virtual ~Character() override;
/// Add bodies and constraints to the system and optionally activate the bodies
void AddToPhysicsSystem(EActivation inActivationMode = EActivation::Activate, bool inLockBodies = true);
/// Remove bodies and constraints from the system
void RemoveFromPhysicsSystem(bool inLockBodies = true);
/// Wake up the character
void Activate(bool inLockBodies = true);
/// Needs to be called after every PhysicsSystem::Update
/// @param inMaxSeparationDistance Max distance between the floor and the character to still consider the character standing on the floor
/// @param inLockBodies If the collision query should use the locking body interface (true) or the non locking body interface (false)
void PostSimulation(float inMaxSeparationDistance, bool inLockBodies = true);
/// Control the velocity of the character
void SetLinearAndAngularVelocity(Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, bool inLockBodies = true);
/// Get the linear velocity of the character (m / s)
Vec3 GetLinearVelocity(bool inLockBodies = true) const;
/// Set the linear velocity of the character (m / s)
void SetLinearVelocity(Vec3Arg inLinearVelocity, bool inLockBodies = true);
/// Add world space linear velocity to current velocity (m / s)
void AddLinearVelocity(Vec3Arg inLinearVelocity, bool inLockBodies = true);
/// Add impulse to the center of mass of the character
void AddImpulse(Vec3Arg inImpulse, bool inLockBodies = true);
/// Get the body associated with this character
BodyID GetBodyID() const { return mBodyID; }
/// Get position / rotation of the body
void GetPositionAndRotation(RVec3 &outPosition, Quat &outRotation, bool inLockBodies = true) const;
/// Set the position / rotation of the body, optionally activating it.
void SetPositionAndRotation(RVec3Arg inPosition, QuatArg inRotation, EActivation inActivationMode = EActivation::Activate, bool inLockBodies = true) const;
/// Get the position of the character
RVec3 GetPosition(bool inLockBodies = true) const;
/// Set the position of the character, optionally activating it.
void SetPosition(RVec3Arg inPostion, EActivation inActivationMode = EActivation::Activate, bool inLockBodies = true);
/// Get the rotation of the character
Quat GetRotation(bool inLockBodies = true) const;
/// Set the rotation of the character, optionally activating it.
void SetRotation(QuatArg inRotation, EActivation inActivationMode = EActivation::Activate, bool inLockBodies = true);
/// Position of the center of mass of the underlying rigid body
RVec3 GetCenterOfMassPosition(bool inLockBodies = true) const;
/// Calculate the world transform of the character
RMat44 GetWorldTransform(bool inLockBodies = true) const;
/// Update the layer of the character
void SetLayer(ObjectLayer inLayer, bool inLockBodies = true);
/// Switch the shape of the character (e.g. for stance). When inMaxPenetrationDepth is not FLT_MAX, it checks
/// if the new shape collides before switching shape. Returns true if the switch succeeded.
bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, bool inLockBodies = true);
/// @brief Get all contacts for the character at a particular location
/// @param inPosition Position to test.
/// @param inRotation Rotation at which to test the shape.
/// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.
/// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).
/// @param inShape Shape to test collision with.
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. GetPosition() since floats are most accurate near the origin
/// @param ioCollector Collision collector that receives the collision results.
/// @param inLockBodies If the collision query should use the locking body interface (true) or the non locking body interface (false)
void CheckCollision(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inMovementDirection, float inMaxSeparationDistance, const Shape *inShape, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, bool inLockBodies = true) const;
private:
/// Check collisions between inShape and the world using the center of mass transform
void CheckCollision(RMat44Arg inCenterOfMassTransform, Vec3Arg inMovementDirection, float inMaxSeparationDistance, const Shape *inShape, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, bool inLockBodies) const;
/// Check collisions between inShape and the world using the current position / rotation of the character
void CheckCollision(const Shape *inShape, float inMaxSeparationDistance, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, bool inLockBodies) const;
/// The body of this character
BodyID mBodyID;
/// The layer the body is in
ObjectLayer mLayer;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ContactListener.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/SubShapeIDPair.h>
#include <Jolt/Core/StaticArray.h>
JPH_NAMESPACE_BEGIN
class Body;
class CollideShapeResult;
/// Array of contact points
using ContactPoints = StaticArray<Vec3, 64>;
/// Manifold class, describes the contact surface between two bodies
class ContactManifold
{
public:
/// Swaps shape 1 and 2
ContactManifold SwapShapes() const { return { mBaseOffset, -mWorldSpaceNormal, mPenetrationDepth, mSubShapeID2, mSubShapeID1, mRelativeContactPointsOn2, mRelativeContactPointsOn1 }; }
/// Access to the world space contact positions
inline RVec3 GetWorldSpaceContactPointOn1(uint inIndex) const { return mBaseOffset + mRelativeContactPointsOn1[inIndex]; }
inline RVec3 GetWorldSpaceContactPointOn2(uint inIndex) const { return mBaseOffset + mRelativeContactPointsOn2[inIndex]; }
RVec3 mBaseOffset; ///< Offset to which all the contact points are relative
Vec3 mWorldSpaceNormal; ///< Normal for this manifold, direction along which to move body 2 out of collision along the shortest path
float mPenetrationDepth; ///< Penetration depth (move shape 2 by this distance to resolve the collision)
SubShapeID mSubShapeID1; ///< Sub shapes that formed this manifold (note that when multiple manifolds are combined because they're coplanar, we lose some information here because we only keep track of one sub shape pair that we encounter)
SubShapeID mSubShapeID2;
ContactPoints mRelativeContactPointsOn1; ///< Contact points on the surface of shape 1 relative to mBaseOffset.
ContactPoints mRelativeContactPointsOn2; ///< Contact points on the surface of shape 2 relative to mBaseOffset. If there's no penetration, this will be the same as mRelativeContactPointsOn1. If there is penetration they will be different.
};
/// When a contact point is added or persisted, the callback gets a chance to override certain properties of the contact constraint.
/// The values are filled in with their defaults by the system so the callback doesn't need to modify anything, but it can if it wants to.
class ContactSettings
{
public:
float mCombinedFriction; ///< Combined friction for the body pair (usually calculated by sCombineFriction)
float mCombinedRestitution; ///< Combined restitution for the body pair (usually calculated by sCombineRestitution)
bool mIsSensor; ///< If the contact should be treated as a sensor vs body contact (no collision response)
};
/// Return value for the OnContactValidate callback. Determines if the contact is being processed or not.
/// Results are ordered so that the strongest accept has the lowest number and the strongest reject the highest number (which allows for easy combining of results)
enum class ValidateResult
{
AcceptAllContactsForThisBodyPair, ///< Accept this and any further contact points for this body pair
AcceptContact, ///< Accept this contact only (and continue calling this callback for every contact manifold for the same body pair)
RejectContact, ///< Reject this contact only (but process any other contact manifolds for the same body pair)
RejectAllContactsForThisBodyPair ///< Rejects this and any further contact points for this body pair
};
/// A listener class that receives collision contact events events.
/// It can be registered with the ContactConstraintManager (or PhysicsSystem).
/// Note that contact listener callbacks are called from multiple threads at the same time when all bodies are locked, you're only allowed to read from the bodies and you can't change physics state.
class ContactListener
{
public:
/// Ensure virtual destructor
virtual ~ContactListener() = default;
/// Called after detecting a collision between a body pair, but before calling OnContactAdded and before adding the contact constraint.
/// If the function returns false, the contact will not be added and any other contacts between this body pair will not be processed.
/// This function will only be called once per PhysicsSystem::Update per body pair and may not be called again the next update
/// if a contact persists and no new contact pairs between sub shapes are found.
/// This is a rather expensive time to reject a contact point since a lot of the collision detection has happened already, make sure you
/// filter out the majority of undesired body pairs through the ObjectLayerPairFilter that is registered on the PhysicsSystem.
/// Note that this callback is called when all bodies are locked, so don't use any locking functions!
/// The order of body 1 and 2 is undefined, but when one of the two bodies is dynamic it will be body 1.
/// The collision result (inCollisionResult) is reported relative to inBaseOffset.
virtual ValidateResult OnContactValidate(const Body &inBody1, const Body &inBody2, RVec3Arg inBaseOffset, const CollideShapeResult &inCollisionResult) { return ValidateResult::AcceptAllContactsForThisBodyPair; }
/// Called whenever a new contact point is detected.
/// Note that this callback is called when all bodies are locked, so don't use any locking functions!
/// Body 1 and 2 will be sorted such that body 1 ID < body 2 ID, so body 1 may not be dynamic.
/// Note that only active bodies will report contacts, as soon as a body goes to sleep the contacts between that body and all other
/// bodies will receive an OnContactRemoved callback, if this is the case then Body::IsActive() will return false during the callback.
/// When contacts are added, the constraint solver has not run yet, so the collision impulse is unknown at that point.
/// The velocities of inBody1 and inBody2 are the velocities before the contact has been resolved, so you can use this to
/// estimate the collision impulse to e.g. determine the volume of the impact sound to play (see: EstimateCollisionResponse).
virtual void OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings) { /* Do nothing */ }
/// Called whenever a contact is detected that was also detected last update.
/// Note that this callback is called when all bodies are locked, so don't use any locking functions!
/// Body 1 and 2 will be sorted such that body 1 ID < body 2 ID, so body 1 may not be dynamic.
/// If the structure of the shape of a body changes between simulation steps (e.g. by adding/removing a child shape of a compound shape),
/// it is possible that the same sub shape ID used to identify the removed child shape is now reused for a different child shape. The physics
/// system cannot detect this, so may send a 'contact persisted' callback even though the contact is now on a different child shape. You can
/// detect this by keeping the old shape (before adding/removing a part) around until the next PhysicsSystem::Update (when the OnContactPersisted
/// callbacks are triggered) and resolving the sub shape ID against both the old and new shape to see if they still refer to the same child shape.
virtual void OnContactPersisted(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings) { /* Do nothing */ }
/// Called whenever a contact was detected last update but is not detected anymore.
/// Note that this callback is called when all bodies are locked, so don't use any locking functions!
/// Note that we're using BodyID's since the bodies may have been removed at the time of callback.
/// Body 1 and 2 will be sorted such that body 1 ID < body 2 ID, so body 1 may not be dynamic.
/// The sub shape ID were created in the previous simulation step too, so if the structure of a shape changes (e.g. by adding/removing a child shape of a compound shape),
/// the sub shape ID may not be valid / may not point to the same sub shape anymore.
/// If you want to know if this is the last contact between the two bodies, use PhysicsSystem::WereBodiesInContact.
virtual void OnContactRemoved(const SubShapeIDPair &inSubShapePair) { /* Do nothing */ }
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/SortReverseAndStore.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// This function will sort values from high to low and only keep the ones that are less than inMaxValue
/// @param inValues Values to be sorted
/// @param inMaxValue Values need to be less than this to keep them
/// @param ioIdentifiers 4 identifiers that will be sorted in the same way as the values
/// @param outValues The values are stored here from high to low
/// @return The number of values that were kept
JPH_INLINE int SortReverseAndStore(Vec4Arg inValues, float inMaxValue, UVec4 &ioIdentifiers, float *outValues)
{
// Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
Vec4::sSort4Reverse(inValues, ioIdentifiers);
// Count how many results are less than the max value
UVec4 closer = Vec4::sLess(inValues, Vec4::sReplicate(inMaxValue));
int num_results = closer.CountTrues();
// Shift the values so that only the ones that are less than max are kept
inValues = inValues.ReinterpretAsInt().ShiftComponents4Minus(num_results).ReinterpretAsFloat();
ioIdentifiers = ioIdentifiers.ShiftComponents4Minus(num_results);
// Store the values
inValues.StoreFloat4((Float4 *)outValues);
return num_results;
}
/// Shift the elements so that the identifiers that correspond with the trues in inValue come first
/// @param inValue Values to test for true or false
/// @param ioIdentifiers the identifiers that are shifted, on return they are shifted
/// @return The number of trues
JPH_INLINE int CountAndSortTrues(UVec4Arg inValue, UVec4 &ioIdentifiers)
{
// Sort the hits
ioIdentifiers = UVec4::sSort4True(inValue, ioIdentifiers);
// Return the amount of hits
return inValue.CountTrues();
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollisionCollector.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
class Body;
class TransformedShape;
/// Traits to use for CastRay
class CollisionCollectorTraitsCastRay
{
public:
/// For rays the early out fraction is the fraction along the line to order hits.
static constexpr float InitialEarlyOutFraction = 1.0f + FLT_EPSILON; ///< Furthest hit: Fraction is 1 + epsilon
static constexpr float ShouldEarlyOutFraction = 0.0f; ///< Closest hit: Fraction is 0
};
/// Traits to use for CastShape
class CollisionCollectorTraitsCastShape
{
public:
/// For rays the early out fraction is the fraction along the line to order hits.
static constexpr float InitialEarlyOutFraction = 1.0f + FLT_EPSILON; ///< Furthest hit: Fraction is 1 + epsilon
static constexpr float ShouldEarlyOutFraction = -FLT_MAX; ///< Deepest hit: Penetration is infinite
};
/// Traits to use for CollideShape
class CollisionCollectorTraitsCollideShape
{
public:
/// For shape collisions we use -penetration depth to order hits.
static constexpr float InitialEarlyOutFraction = FLT_MAX; ///< Most shallow hit: Separatation is infinite
static constexpr float ShouldEarlyOutFraction = -FLT_MAX; ///< Deepest hit: Penetration is infinite
};
/// Traits to use for CollidePoint
using CollisionCollectorTraitsCollidePoint = CollisionCollectorTraitsCollideShape;
/// Virtual interface that allows collecting multiple collision results
template <class ResultTypeArg, class TraitsType>
class CollisionCollector
{
public:
/// Declare ResultType so that derived classes can use it
using ResultType = ResultTypeArg;
/// Destructor
virtual ~CollisionCollector() = default;
/// If you want to reuse this collector, call Reset()
virtual void Reset() { mEarlyOutFraction = TraitsType::InitialEarlyOutFraction; }
/// When running a query through the NarrowPhaseQuery class, this will be called for every body that is potentially colliding.
/// It allows collecting additional information needed by the collision collector implementation from the body under lock protection
/// before AddHit is called (e.g. the user data pointer or the velocity of the body).
virtual void OnBody(const Body &inBody) { /* Collects nothing by default */ }
/// Set by the collision detection functions to the current TransformedShape that we're colliding against before calling the AddHit function
void SetContext(const TransformedShape *inContext) { mContext = inContext; }
const TransformedShape *GetContext() const { return mContext; }
/// This function will be called for every hit found, it's up to the application to decide how to store the hit
virtual void AddHit(const ResultType &inResult) = 0;
/// Update the early out fraction (should be lower than before)
inline void UpdateEarlyOutFraction(float inFraction) { JPH_ASSERT(inFraction <= mEarlyOutFraction); mEarlyOutFraction = inFraction; }
/// Reset the early out fraction to a specific value
inline void ResetEarlyOutFraction(float inFraction) { mEarlyOutFraction = inFraction; }
/// Force the collision detection algorithm to terminate as soon as possible. Call this from the AddHit function when a satisfying hit is found.
inline void ForceEarlyOut() { mEarlyOutFraction = TraitsType::ShouldEarlyOutFraction; }
/// When true, the collector will no longer accept any additional hits and the collision detection routine should early out as soon as possible
inline bool ShouldEarlyOut() const { return mEarlyOutFraction <= TraitsType::ShouldEarlyOutFraction; }
/// Get the current early out value
inline float GetEarlyOutFraction() const { return mEarlyOutFraction; }
private:
/// The early out fraction determines the fraction below which the collector is still accepting a hit (can be used to reduce the amount of work)
float mEarlyOutFraction = TraitsType::InitialEarlyOutFraction;
/// Set by the collision detection functions to the current TransformedShape of the body that we're colliding against before calling the AddHit function
const TransformedShape *mContext = nullptr;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollisionGroup.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/GroupFilter.h>
#include <Jolt/ObjectStream/SerializableObject.h>
JPH_NAMESPACE_BEGIN
class StreamIn;
class StreamOut;
/// Two objects collide with each other if:
/// - Both don't have a group filter
/// - The first group filter says that the objects can collide
/// - Or if there's no filter for the first object, the second group filter says the objects can collide
class CollisionGroup
{
public:
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(CollisionGroup)
using GroupID = uint32;
using SubGroupID = uint32;
static const GroupID cInvalidGroup = ~GroupID(0);
static const SubGroupID cInvalidSubGroup = ~SubGroupID(0);
/// Default constructor
CollisionGroup() = default;
/// Construct with all properties
CollisionGroup(const GroupFilter *inFilter, GroupID inGroupID, SubGroupID inSubGroupID) : mGroupFilter(inFilter), mGroupID(inGroupID), mSubGroupID(inSubGroupID) { }
/// Set the collision group filter
inline void SetGroupFilter(const GroupFilter *inFilter)
{
mGroupFilter = inFilter;
}
/// Get the collision group filter
inline const GroupFilter *GetGroupFilter() const
{
return mGroupFilter;
}
/// Set the main group id for this object
inline void SetGroupID(GroupID inID)
{
mGroupID = inID;
}
inline GroupID GetGroupID() const
{
return mGroupID;
}
/// Add this object to a sub group
inline void SetSubGroupID(SubGroupID inID)
{
mSubGroupID = inID;
}
inline SubGroupID GetSubGroupID() const
{
return mSubGroupID;
}
/// Check if this object collides with another object
bool CanCollide(const CollisionGroup &inOther) const
{
// Call the CanCollide function of the first group filter that's not null
if (mGroupFilter != nullptr)
return mGroupFilter->CanCollide(*this, inOther);
else if (inOther.mGroupFilter != nullptr)
return inOther.mGroupFilter->CanCollide(inOther, *this);
else
return true;
}
/// Saves the state of this object in binary form to inStream. Does not save group filter.
void SaveBinaryState(StreamOut &inStream) const;
/// Restore the state of this object from inStream. Does not save group filter.
void RestoreBinaryState(StreamIn &inStream);
private:
RefConst<GroupFilter> mGroupFilter;
GroupID mGroupID = cInvalidGroup;
SubGroupID mSubGroupID = cInvalidSubGroup;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/PhysicsMaterial.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Reference.h>
#include <Jolt/Core/Color.h>
#include <Jolt/Core/Result.h>
#include <Jolt/ObjectStream/SerializableObject.h>
JPH_NAMESPACE_BEGIN
class StreamIn;
class StreamOut;
/// This structure describes the surface of (part of) a shape. You should inherit from it to define additional
/// information that is interesting for the simulation. The 2 materials involved in a contact could be used
/// to decide which sound or particle effects to play.
///
/// If you inherit from this material, don't forget to create a suitable default material in sDefault
class PhysicsMaterial : public SerializableObject, public RefTarget<PhysicsMaterial>
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(PhysicsMaterial)
/// Virtual destructor
virtual ~PhysicsMaterial() override = default;
/// Default material that is used when a shape has no materials defined
static RefConst<PhysicsMaterial> sDefault;
// Properties
virtual const char * GetDebugName() const { return "Unknown"; }
virtual Color GetDebugColor() const { return Color::sGrey; }
/// Saves the contents of the material in binary form to inStream.
virtual void SaveBinaryState(StreamOut &inStream) const;
using PhysicsMaterialResult = Result<Ref<PhysicsMaterial>>;
/// Creates a PhysicsMaterial of the correct type and restores its contents from the binary stream inStream.
static PhysicsMaterialResult sRestoreFromBinaryState(StreamIn &inStream);
protected:
/// This function should not be called directly, it is used by sRestoreFromBinaryState.
virtual void RestoreBinaryState(StreamIn &inStream);
};
using PhysicsMaterialList = Array<RefConst<PhysicsMaterial>>;
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollectFacesMode.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// Whether or not to collect faces, used by CastShape and CollideShape
enum class ECollectFacesMode : uint8
{
CollectFaces, ///< mShape1/2Face is desired
NoFaces ///< mShape1/2Face is not desired
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/GroupFilter.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/Result.h>
#include <Jolt/ObjectStream/SerializableObject.h>
JPH_NAMESPACE_BEGIN
class CollisionGroup;
class StreamIn;
class StreamOut;
/// Abstract class that checks if two CollisionGroups collide
class GroupFilter : public SerializableObject, public RefTarget<GroupFilter>
{
public:
JPH_DECLARE_SERIALIZABLE_ABSTRACT(GroupFilter)
/// Virtual destructor
virtual ~GroupFilter() override = default;
/// Check if two groups collide
virtual bool CanCollide(const CollisionGroup &inGroup1, const CollisionGroup &inGroup2) const = 0;
/// Saves the contents of the group filter in binary form to inStream.
virtual void SaveBinaryState(StreamOut &inStream) const;
using GroupFilterResult = Result<Ref<GroupFilter>>;
/// Creates a GroupFilter of the correct type and restores its contents from the binary stream inStream.
static GroupFilterResult sRestoreFromBinaryState(StreamIn &inStream);
protected:
/// This function should not be called directly, it is used by sRestoreFromBinaryState.
virtual void RestoreBinaryState(StreamIn &inStream);
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ShapeCast.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Geometry/AABox.h>
#include <Jolt/Physics/Collision/CollideShape.h>
#include <Jolt/Physics/Collision/Shape/Shape.h>
JPH_NAMESPACE_BEGIN
/// Structure that holds a single shape cast (a shape moving along a linear path in 3d space with no rotation)
template <class Vec, class Mat, class ShapeCastType>
struct ShapeCastT
{
JPH_OVERRIDE_NEW_DELETE
/// Constructor
ShapeCastT(const Shape *inShape, Vec3Arg inScale, typename Mat::ArgType inCenterOfMassStart, Vec3Arg inDirection, const AABox &inWorldSpaceBounds) :
mShape(inShape),
mScale(inScale),
mCenterOfMassStart(inCenterOfMassStart),
mDirection(inDirection),
mShapeWorldBounds(inWorldSpaceBounds)
{
}
/// Constructor
ShapeCastT(const Shape *inShape, Vec3Arg inScale, typename Mat::ArgType inCenterOfMassStart, Vec3Arg inDirection) :
ShapeCastT<Vec, Mat, ShapeCastType>(inShape, inScale, inCenterOfMassStart, inDirection, inShape->GetWorldSpaceBounds(inCenterOfMassStart, inScale))
{
}
/// Construct a shape cast using a world transform for a shape instead of a center of mass transform
static inline ShapeCastType sFromWorldTransform(const Shape *inShape, Vec3Arg inScale, typename Mat::ArgType inWorldTransform, Vec3Arg inDirection)
{
return ShapeCastType(inShape, inScale, inWorldTransform.PreTranslated(inShape->GetCenterOfMass()), inDirection);
}
/// Transform this shape cast using inTransform. Multiply transform on the left left hand side.
ShapeCastType PostTransformed(typename Mat::ArgType inTransform) const
{
Mat44 start = inTransform * mCenterOfMassStart;
Vec3 direction = inTransform.Multiply3x3(mDirection);
return { mShape, mScale, start, direction };
}
/// Translate this shape cast by inTranslation.
ShapeCastType PostTranslated(typename Vec::ArgType inTranslation) const
{
return { mShape, mScale, mCenterOfMassStart.PostTranslated(inTranslation), mDirection };
}
/// Get point with fraction inFraction on ray from mCenterOfMassStart to mCenterOfMassStart + mDirection (0 = start of ray, 1 = end of ray)
inline Vec GetPointOnRay(float inFraction) const
{
return mCenterOfMassStart.GetTranslation() + inFraction * mDirection;
}
const Shape * mShape; ///< Shape that's being cast (cannot be mesh shape). Note that this structure does not assume ownership over the shape for performance reasons.
const Vec3 mScale; ///< Scale in local space of the shape being cast
const Mat mCenterOfMassStart; ///< Start position and orientation of the center of mass of the shape (construct using sFromWorldTransform if you have a world transform for your shape)
const Vec3 mDirection; ///< Direction and length of the cast (anything beyond this length will not be reported as a hit)
const AABox mShapeWorldBounds; ///< Cached shape's world bounds, calculated in constructor
};
struct ShapeCast : public ShapeCastT<Vec3, Mat44, ShapeCast>
{
using ShapeCastT<Vec3, Mat44, ShapeCast>::ShapeCastT;
};
struct RShapeCast : public ShapeCastT<RVec3, RMat44, RShapeCast>
{
using ShapeCastT<RVec3, RMat44, RShapeCast>::ShapeCastT;
/// Convert from ShapeCast, converts single to double precision
explicit RShapeCast(const ShapeCast &inCast) :
RShapeCast(inCast.mShape, inCast.mScale, RMat44(inCast.mCenterOfMassStart), inCast.mDirection, inCast.mShapeWorldBounds)
{
}
/// Convert to ShapeCast, which implies casting from double precision to single precision
explicit operator ShapeCast() const
{
return ShapeCast(mShape, mScale, mCenterOfMassStart.ToMat44(), mDirection, mShapeWorldBounds);
}
};
/// Settings to be passed with a shape cast
class ShapeCastSettings : public CollideSettingsBase
{
public:
JPH_OVERRIDE_NEW_DELETE
/// How backfacing triangles should be treated (should we report moving out of a triangle?)
EBackFaceMode mBackFaceModeTriangles = EBackFaceMode::IgnoreBackFaces;
/// How backfacing convex objects should be treated (should we report starting inside an object and moving out?)
EBackFaceMode mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;
/// Indicates if we want to shrink the shape by the convex radius and then expand it again. This speeds up collision detection and gives a more accurate normal at the cost of a more 'rounded' shape.
bool mUseShrunkenShapeAndConvexRadius = false;
/// When true, and the shape is intersecting at the beginning of the cast (fraction = 0) then this will calculate the deepest penetration point (costing additional CPU time)
bool mReturnDeepestPoint = false;
};
/// Result of a shape cast test
class ShapeCastResult : public CollideShapeResult
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Default constructor
ShapeCastResult() = default;
/// Constructor
/// @param inFraction Fraction at which the cast hit
/// @param inContactPoint1 Contact point on shape 1
/// @param inContactPoint2 Contact point on shape 2
/// @param inContactNormalOrPenetrationDepth Contact normal pointing from shape 1 to 2 or penetration depth vector when the objects are penetrating (also from 1 to 2)
/// @param inBackFaceHit If this hit was a back face hit
/// @param inSubShapeID1 Sub shape id for shape 1
/// @param inSubShapeID2 Sub shape id for shape 2
/// @param inBodyID2 BodyID that was hit
ShapeCastResult(float inFraction, Vec3Arg inContactPoint1, Vec3Arg inContactPoint2, Vec3Arg inContactNormalOrPenetrationDepth, bool inBackFaceHit, const SubShapeID &inSubShapeID1, const SubShapeID &inSubShapeID2, const BodyID &inBodyID2) :
CollideShapeResult(inContactPoint1, inContactPoint2, inContactNormalOrPenetrationDepth, (inContactPoint2 - inContactPoint1).Length(), inSubShapeID1, inSubShapeID2, inBodyID2),
mFraction(inFraction),
mIsBackFaceHit(inBackFaceHit)
{
}
/// Function required by the CollisionCollector. A smaller fraction is considered to be a 'better hit'. For rays/cast shapes we can just use the collision fraction. The fraction and penetration depth are combined in such a way that deeper hits at fraction 0 go first.
inline float GetEarlyOutFraction() const { return mFraction > 0.0f? mFraction : -mPenetrationDepth; }
/// Reverses the hit result, swapping contact point 1 with contact point 2 etc.
/// @param inWorldSpaceCastDirection Direction of the shape cast in world space
ShapeCastResult Reversed(Vec3Arg inWorldSpaceCastDirection) const
{
// Calculate by how much to shift the contact points
Vec3 delta = mFraction * inWorldSpaceCastDirection;
ShapeCastResult result;
result.mContactPointOn2 = mContactPointOn1 - delta;
result.mContactPointOn1 = mContactPointOn2 - delta;
result.mPenetrationAxis = -mPenetrationAxis;
result.mPenetrationDepth = mPenetrationDepth;
result.mSubShapeID2 = mSubShapeID1;
result.mSubShapeID1 = mSubShapeID2;
result.mBodyID2 = mBodyID2;
result.mFraction = mFraction;
result.mIsBackFaceHit = mIsBackFaceHit;
result.mShape2Face.resize(mShape1Face.size());
for (Face::size_type i = 0; i < mShape1Face.size(); ++i)
result.mShape2Face[i] = mShape1Face[i] - delta;
result.mShape1Face.resize(mShape2Face.size());
for (Face::size_type i = 0; i < mShape2Face.size(); ++i)
result.mShape1Face[i] = mShape2Face[i] - delta;
return result;
}
float mFraction; ///< This is the fraction where the shape hit the other shape: CenterOfMassOnHit = Start + value * (End - Start)
bool mIsBackFaceHit; ///< True if the shape was hit from the back side
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CastConvexVsTriangles.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#include <Jolt/Physics/Collision/ShapeCast.h>
JPH_NAMESPACE_BEGIN
/// Collision detection helper that casts a convex object vs one or more triangles
class CastConvexVsTriangles
{
public:
/// Constructor
/// @param inShapeCast The shape to cast against the triangles and its start and direction
/// @param inShapeCastSettings Settings for performing the cast
/// @param inScale Local space scale for the shape to cast against.
/// @param inCenterOfMassTransform2 Is the center of mass transform of shape 2 (excluding scale), this is used to provide a transform to the shape cast result so that local quantities can be transformed into world space.
/// @param inSubShapeIDCreator1 Class that tracks the current sub shape ID for the casting shape
/// @param ioCollector The collector that receives the results.
CastConvexVsTriangles(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, CastShapeCollector &ioCollector);
/// Cast convex object with a single triangle
/// @param inV0 , inV1 , inV2: CCW triangle vertices
/// @param inActiveEdges bit 0 = edge v0..v1 is active, bit 1 = edge v1..v2 is active, bit 2 = edge v2..v0 is active
/// An active edge is an edge that is not connected to another triangle in such a way that it is impossible to collide with the edge
/// @param inSubShapeID2 The sub shape ID for the triangle
void Cast(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2);
protected:
const ShapeCast & mShapeCast;
const ShapeCastSettings & mShapeCastSettings;
const Mat44 & mCenterOfMassTransform2;
Vec3 mScale;
SubShapeIDCreator mSubShapeIDCreator1;
CastShapeCollector & mCollector;
private:
ConvexShape::SupportBuffer mSupportBuffer; ///< Buffer that holds the support function of the cast shape
const ConvexShape::Support * mSupport = nullptr; ///< Support function of the cast shape
float mScaleSign; ///< Sign of the scale, -1 if object is inside out, 1 if not
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollideSphereVsTriangles.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
JPH_NAMESPACE_BEGIN
class CollideShapeSettings;
/// Collision detection helper that collides a sphere vs one or more triangles
class CollideSphereVsTriangles
{
public:
/// Constructor
/// @param inShape1 The sphere to collide against triangles
/// @param inScale1 Local space scale for the sphere
/// @param inScale2 Local space scale for the triangles
/// @param inCenterOfMassTransform1 Transform that takes the center of mass of 1 into world space
/// @param inCenterOfMassTransform2 Transform that takes the center of mass of 2 into world space
/// @param inSubShapeID1 Sub shape ID of the convex object
/// @param inCollideShapeSettings Settings for the collide shape query
/// @param ioCollector The collector that will receive the results
CollideSphereVsTriangles(const SphereShape *inShape1, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeID &inSubShapeID1, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector);
/// Collide sphere with a single triangle
/// @param inV0 , inV1 , inV2: CCW triangle vertices
/// @param inActiveEdges bit 0 = edge v0..v1 is active, bit 1 = edge v1..v2 is active, bit 2 = edge v2..v0 is active
/// An active edge is an edge that is not connected to another triangle in such a way that it is impossible to collide with the edge
/// @param inSubShapeID2 The sub shape ID for the triangle
void Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2);
protected:
const CollideShapeSettings & mCollideShapeSettings; ///< Settings for this collision operation
CollideShapeCollector & mCollector; ///< The collector that will receive the results
const SphereShape * mShape1; ///< The shape that we're colliding with
Vec3 mScale2; ///< The scale of the shape (in shape local space) of the shape we're colliding against
Mat44 mTransform2; ///< Transform of the shape we're colliding against
Vec3 mSphereCenterIn2; ///< The center of the sphere in the space of 2
SubShapeID mSubShapeID1; ///< Sub shape ID of colliding shape
float mScaleSign2; ///< Sign of the scale of object 2, -1 if object is inside out, 1 if not
float mRadius; ///< Radius of the sphere
float mRadiusPlusMaxSeparationSq; ///< (Radius + Max SeparationDistance)^2
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BackFaceMode.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// How collision detection functions will treat back facing triangles
enum class EBackFaceMode : uint8
{
IgnoreBackFaces, ///< Ignore collision with back facing surfaces/triangles
CollideWithBackFaces, ///< Collide with back facing surfaces/triangles
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ManifoldBetweenTwoFaces.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#include <Jolt/Physics/Collision/ContactListener.h>
JPH_NAMESPACE_BEGIN
/// Remove contact points if there are > 4 (no more than 4 are needed for a stable solution)
/// @param inPenetrationAxis is the world space penetration axis (must be normalized)
/// @param ioContactPointsOn1 The contact points on shape 1 relative to inCenterOfMass
/// @param ioContactPointsOn2 The contact points on shape 2 relative to inCenterOfMass
/// On output ioContactPointsOn1/2 are reduced to 4 or less points
#ifdef JPH_DEBUG_RENDERER
/// @param inCenterOfMass Center of mass position of body 1
#endif
void PruneContactPoints(Vec3Arg inPenetrationAxis, ContactPoints &ioContactPointsOn1, ContactPoints &ioContactPointsOn2
#ifdef JPH_DEBUG_RENDERER
, RVec3Arg inCenterOfMass
#endif
);
/// Determine contact points between 2 faces of 2 shapes and return them in outContactPoints 1 & 2
/// @param inContactPoint1 The contact point on shape 1 relative to inCenterOfMass
/// @param inContactPoint2 The contact point on shape 2 relative to inCenterOfMass
/// @param inPenetrationAxis The local space penetration axis in world space
/// @param inSpeculativeContactDistanceSq Squared speculative contact distance, any contact further apart than this distance will be discarded
/// @param inShape1Face The supporting faces on shape 1 relative to inCenterOfMass
/// @param inShape2Face The supporting faces on shape 2 relative to inCenterOfMass
/// @param outContactPoints1 Returns the contact points between the two shapes for shape 1 relative to inCenterOfMass (any existing points in the output array are left as is)
/// @param outContactPoints2 Returns the contact points between the two shapes for shape 2 relative to inCenterOfMass (any existing points in the output array are left as is)
#ifdef JPH_DEBUG_RENDERER
/// @param inCenterOfMass Center of mass position of body 1
#endif
void ManifoldBetweenTwoFaces(Vec3Arg inContactPoint1, Vec3Arg inContactPoint2, Vec3Arg inPenetrationAxis, float inSpeculativeContactDistanceSq, const ConvexShape::SupportingFace &inShape1Face, const ConvexShape::SupportingFace &inShape2Face, ContactPoints &outContactPoints1, ContactPoints &outContactPoints2
#ifdef JPH_DEBUG_RENDERER
, RVec3Arg inCenterOfMass
#endif
);
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/TransformedShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/ObjectLayer.h>
#include <Jolt/Physics/Collision/ShapeFilter.h>
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Physics/Collision/BackFaceMode.h>
#include <Jolt/Physics/Body/BodyID.h>
JPH_NAMESPACE_BEGIN
struct RRayCast;
struct RShapeCast;
class CollideShapeSettings;
class RayCastResult;
/// Temporary data structure that contains a shape and a transform.
/// This structure can be obtained from a body (e.g. after a broad phase query) under lock protection.
/// The lock can then be released and collision detection operations can be safely performed since
/// the class takes a reference on the shape and does not use anything from the body anymore.
class TransformedShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
TransformedShape() = default;
TransformedShape(RVec3Arg inPositionCOM, QuatArg inRotation, const Shape *inShape, const BodyID &inBodyID, const SubShapeIDCreator &inSubShapeIDCreator = SubShapeIDCreator()) : mShapePositionCOM(inPositionCOM), mShapeRotation(inRotation), mShape(inShape), mBodyID(inBodyID), mSubShapeIDCreator(inSubShapeIDCreator) { }
/// Cast a ray and find the closest hit. Returns true if it finds a hit. Hits further than ioHit.mFraction will not be considered and in this case ioHit will remain unmodified (and the function will return false).
/// Convex objects will be treated as solid (meaning if the ray starts inside, you'll get a hit fraction of 0) and back face hits are returned.
/// If you want the surface normal of the hit use GetWorldSpaceSurfaceNormal(ioHit.mSubShapeID2, inRay.GetPointOnRay(ioHit.mFraction)) on this object.
bool CastRay(const RRayCast &inRay, RayCastResult &ioHit) const;
/// Cast a ray, allows collecting multiple hits. Note that this version is more flexible but also slightly slower than the CastRay function that returns only a single hit.
/// If you want the surface normal of the hit use GetWorldSpaceSurfaceNormal(collected sub shape ID, inRay.GetPointOnRay(collected fraction)) on this object.
void CastRay(const RRayCast &inRay, const RayCastSettings &inRayCastSettings, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
/// Check if inPoint is inside any shapes. For this tests all shapes are treated as if they were solid.
/// For a mesh shape, this test will only provide sensible information if the mesh is a closed manifold.
/// For each shape that collides, ioCollector will receive a hit
void CollidePoint(RVec3Arg inPoint, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
/// Collide a shape and report any hits to ioCollector
/// @param inShape Shape to test
/// @param inShapeScale Scale in local space of shape
/// @param inCenterOfMassTransform Center of mass transform for the shape
/// @param inCollideShapeSettings Settings
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. mShapePositionCOM since floats are most accurate near the origin
/// @param ioCollector Collector that receives the hits
/// @param inShapeFilter Filter that allows you to reject collisions
void CollideShape(const Shape *inShape, Vec3Arg inShapeScale, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
/// Cast a shape and report any hits to ioCollector
/// @param inShapeCast The shape cast and its position and direction
/// @param inShapeCastSettings Settings for the shape cast
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. mShapePositionCOM or inShapeCast.mCenterOfMassStart.GetTranslation() since floats are most accurate near the origin
/// @param ioCollector Collector that receives the hits
/// @param inShapeFilter Filter that allows you to reject collisions
void CastShape(const RShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
/// Collect the leaf transformed shapes of all leaf shapes of this shape
/// inBox is the world space axis aligned box which leaf shapes should collide with
void CollectTransformedShapes(const AABox &inBox, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const;
/// Use the context from Shape
using GetTrianglesContext = Shape::GetTrianglesContext;
/// To start iterating over triangles, call this function first.
/// To get the actual triangles call GetTrianglesNext.
/// @param ioContext A temporary buffer and should remain untouched until the last call to GetTrianglesNext.
/// @param inBox The world space bounding in which you want to get the triangles.
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. inBox.GetCenter() since floats are most accurate near the origin
void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, RVec3Arg inBaseOffset) const;
/// Call this repeatedly to get all triangles in the box.
/// outTriangleVertices should be large enough to hold 3 * inMaxTriangleRequested entries
/// outMaterials (if it is not null) should contain inMaxTrianglesRequested entries
/// The function returns the amount of triangles that it found (which will be <= inMaxTrianglesRequested), or 0 if there are no more triangles.
/// Note that the function can return a value < inMaxTrianglesRequested and still have more triangles to process (triangles can be returned in blocks)
/// Note that the function may return triangles outside of the requested box, only coarse culling is performed on the returned triangles
int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const;
/// Get/set the scale of the shape as a Vec3
inline Vec3 GetShapeScale() const { return Vec3::sLoadFloat3Unsafe(mShapeScale); }
inline void SetShapeScale(Vec3Arg inScale) { inScale.StoreFloat3(&mShapeScale); }
/// Calculates the transform for this shapes's center of mass (excluding scale)
inline RMat44 GetCenterOfMassTransform() const { return RMat44::sRotationTranslation(mShapeRotation, mShapePositionCOM); }
/// Calculates the inverse of the transform for this shape's center of mass (excluding scale)
inline RMat44 GetInverseCenterOfMassTransform() const { return RMat44::sInverseRotationTranslation(mShapeRotation, mShapePositionCOM); }
/// Sets the world transform (including scale) of this transformed shape (not from the center of mass but in the space the shape was created)
inline void SetWorldTransform(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inScale)
{
mShapePositionCOM = inPosition + inRotation * (inScale * mShape->GetCenterOfMass());
mShapeRotation = inRotation;
SetShapeScale(inScale);
}
/// Sets the world transform (including scale) of this transformed shape (not from the center of mass but in the space the shape was created)
inline void SetWorldTransform(RMat44Arg inTransform)
{
Vec3 scale;
RMat44 rot_trans = inTransform.Decompose(scale);
SetWorldTransform(rot_trans.GetTranslation(), rot_trans.GetRotation().GetQuaternion(), scale);
}
/// Calculates the world transform including scale of this shape (not from the center of mass but in the space the shape was created)
inline RMat44 GetWorldTransform() const
{
RMat44 transform = RMat44::sRotation(mShapeRotation).PreScaled(GetShapeScale());
transform.SetTranslation(mShapePositionCOM - transform.Multiply3x3(mShape->GetCenterOfMass()));
return transform;
}
/// Get the world space bounding box for this transformed shape
AABox GetWorldSpaceBounds() const { return mShape != nullptr? mShape->GetWorldSpaceBounds(GetCenterOfMassTransform(), GetShapeScale()) : AABox(); }
/// Make inSubShapeID relative to mShape. When mSubShapeIDCreator is not empty, this is needed in order to get the correct path to the sub shape.
inline SubShapeID MakeSubShapeIDRelativeToShape(const SubShapeID &inSubShapeID) const
{
// Take off the sub shape ID part that comes from mSubShapeIDCreator and validate that it is the same
SubShapeID sub_shape_id;
uint num_bits_written = mSubShapeIDCreator.GetNumBitsWritten();
JPH_IF_ENABLE_ASSERTS(uint32 root_id =) inSubShapeID.PopID(num_bits_written, sub_shape_id);
JPH_ASSERT(root_id == (mSubShapeIDCreator.GetID().GetValue() & ((1 << num_bits_written) - 1)));
return sub_shape_id;
}
/// Get surface normal of a particular sub shape and its world space surface position on this body.
/// Note: When you have a CollideShapeResult or ShapeCastResult you should use -mPenetrationAxis.Normalized() as contact normal as GetWorldSpaceSurfaceNormal will only return face normals (and not vertex or edge normals).
inline Vec3 GetWorldSpaceSurfaceNormal(const SubShapeID &inSubShapeID, RVec3Arg inPosition) const
{
RMat44 inv_com = GetInverseCenterOfMassTransform();
Vec3 scale = GetShapeScale(); // See comment at ScaledShape::GetSurfaceNormal for the math behind the scaling of the normal
return inv_com.Multiply3x3Transposed(mShape->GetSurfaceNormal(MakeSubShapeIDRelativeToShape(inSubShapeID), Vec3(inv_com * inPosition) / scale) / scale).Normalized();
}
/// Get the vertices of the face that faces inDirection the most (includes any convex radius). Note that this function can only return faces of
/// convex shapes or triangles, which is why a sub shape ID to get to that leaf must be provided.
/// @param inSubShapeID Sub shape ID of target shape
/// @param inDirection Direction that the face should be facing (in world space)
/// @param inBaseOffset The vertices will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. mShapePositionCOM since floats are most accurate near the origin
/// @param outVertices Resulting face. Note the returned face can have a single point if the shape doesn't have polygons to return (e.g. because it's a sphere). The face will be returned in world space.
void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, RVec3Arg inBaseOffset, Shape::SupportingFace &outVertices) const
{
Mat44 com = GetCenterOfMassTransform().PostTranslated(-inBaseOffset).ToMat44();
mShape->GetSupportingFace(MakeSubShapeIDRelativeToShape(inSubShapeID), com.Multiply3x3Transposed(inDirection), GetShapeScale(), com, outVertices);
}
/// Get material of a particular sub shape
inline const PhysicsMaterial *GetMaterial(const SubShapeID &inSubShapeID) const
{
return mShape->GetMaterial(MakeSubShapeIDRelativeToShape(inSubShapeID));
}
/// Get the user data of a particular sub shape
inline uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const
{
return mShape->GetSubShapeUserData(MakeSubShapeIDRelativeToShape(inSubShapeID));
}
/// Get the direct child sub shape and its transform for a sub shape ID.
/// @param inSubShapeID Sub shape ID that indicates the path to the leaf shape
/// @param outRemainder The remainder of the sub shape ID after removing the sub shape
/// @return Direct child sub shape and its transform, note that the body ID and sub shape ID will be invalid
TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, SubShapeID &outRemainder) const
{
TransformedShape ts = mShape->GetSubShapeTransformedShape(inSubShapeID, Vec3::sZero(), mShapeRotation, GetShapeScale(), outRemainder);
ts.mShapePositionCOM += mShapePositionCOM;
return ts;
}
/// Helper function to return the body id from a transformed shape. If the transformed shape is null an invalid body ID will be returned.
inline static BodyID sGetBodyID(const TransformedShape *inTS) { return inTS != nullptr? inTS->mBodyID : BodyID(); }
RVec3 mShapePositionCOM; ///< Center of mass world position of the shape
Quat mShapeRotation; ///< Rotation of the shape
RefConst<Shape> mShape; ///< The shape itself
Float3 mShapeScale { 1, 1, 1 }; ///< Not stored as Vec3 to get a nicely packed structure
BodyID mBodyID; ///< Optional body ID from which this shape comes
SubShapeIDCreator mSubShapeIDCreator; ///< Optional sub shape ID creator for the shape (can be used when expanding compound shapes into multiple transformed shapes)
};
static_assert(sizeof(TransformedShape) == JPH_IF_SINGLE_PRECISION_ELSE(64, 96), "Not properly packed");
static_assert(alignof(TransformedShape) == JPH_RVECTOR_ALIGNMENT, "Not properly aligned");
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollisionDispatch.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Physics/Collision/ShapeCast.h>
#include <Jolt/Physics/Collision/ShapeFilter.h>
#include <Jolt/Physics/Collision/NarrowPhaseStats.h>
JPH_NAMESPACE_BEGIN
class CollideShapeSettings;
/// Dispatch function, main function to handle collisions between shapes
class CollisionDispatch
{
public:
/// Collide 2 shapes and pass any collision on to ioCollector
/// @param inShape1 The first shape
/// @param inShape2 The second shape
/// @param inScale1 Local space scale of shape 1
/// @param inScale2 Local space scale of shape 2
/// @param inCenterOfMassTransform1 Transform to transform center of mass of shape 1 into world space
/// @param inCenterOfMassTransform2 Transform to transform center of mass of shape 2 into world space
/// @param inSubShapeIDCreator1 Class that tracks the current sub shape ID for shape 1
/// @param inSubShapeIDCreator2 Class that tracks the current sub shape ID for shape 2
/// @param inCollideShapeSettings Options for the CollideShape test
/// @param ioCollector The collector that receives the results.
/// @param inShapeFilter allows selectively disabling collisions between pairs of (sub) shapes.
static inline void sCollideShapeVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter = { })
{
JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseStat track(NarrowPhaseStat::sCollideShape[(int)inShape1->GetSubType()][(int)inShape2->GetSubType()]);)
// Only test shape if it passes the shape filter
if (inShapeFilter.ShouldCollide(inShape1, inSubShapeIDCreator1.GetID(), inShape2, inSubShapeIDCreator2.GetID()))
sCollideShape[(int)inShape1->GetSubType()][(int)inShape2->GetSubType()](inShape1, inShape2, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, inCollideShapeSettings, ioCollector, inShapeFilter);
}
/// Cast a shape againt this shape, passes any hits found to ioCollector.
/// Note: This version takes the shape cast in local space relative to the center of mass of inShape, take a look at sCastShapeVsShapeWorldSpace if you have a shape cast in world space.
/// @param inShapeCastLocal The shape to cast against the other shape and its start and direction.
/// @param inShapeCastSettings Settings for performing the cast
/// @param inShape The shape to cast against.
/// @param inScale Local space scale for the shape to cast against.
/// @param inShapeFilter allows selectively disabling collisions between pairs of (sub) shapes.
/// @param inCenterOfMassTransform2 Is the center of mass transform of shape 2 (excluding scale), this is used to provide a transform to the shape cast result so that local hit result quantities can be transformed into world space.
/// @param inSubShapeIDCreator1 Class that tracks the current sub shape ID for the casting shape
/// @param inSubShapeIDCreator2 Class that tracks the current sub shape ID for the shape we're casting against
/// @param ioCollector The collector that receives the results.
static inline void sCastShapeVsShapeLocalSpace(const ShapeCast &inShapeCastLocal, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
{
JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseStat track(NarrowPhaseStat::sCastShape[(int)inShapeCast.mShape->GetSubType()][(int)inShape->GetSubType()]);)
// Only test shape if it passes the shape filter
if (inShapeFilter.ShouldCollide(inShapeCastLocal.mShape, inSubShapeIDCreator1.GetID(), inShape, inSubShapeIDCreator2.GetID()))
sCastShape[(int)inShapeCastLocal.mShape->GetSubType()][(int)inShape->GetSubType()](inShapeCastLocal, inShapeCastSettings, inShape, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, ioCollector);
}
/// See: sCastShapeVsShapeLocalSpace.
/// The only difference is that the shape cast (inShapeCastWorld) is provided in world space.
/// Note: A shape cast contains the center of mass start of the shape, if you have the world transform of the shape you probably want to construct it using ShapeCast::sFromWorldTransform.
static inline void sCastShapeVsShapeWorldSpace(const ShapeCast &inShapeCastWorld, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
{
ShapeCast local_shape_cast = inShapeCastWorld.PostTransformed(inCenterOfMassTransform2.InversedRotationTranslation());
sCastShapeVsShapeLocalSpace(local_shape_cast, inShapeCastSettings, inShape, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, inSubShapeIDCreator2, ioCollector);
}
/// Function that collides 2 shapes (see sCollideShapeVsShape)
using CollideShape = void (*)(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
/// Function that casts a shape vs another shape (see sCastShapeVsShapeLocalSpace)
using CastShape = void (*)(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
/// Initialize all collision functions with a function that asserts and returns no collision
static void sInit();
/// Register a collide shape function in the collision table
static void sRegisterCollideShape(EShapeSubType inType1, EShapeSubType inType2, CollideShape inFunction) { sCollideShape[(int)inType1][(int)inType2] = inFunction; }
/// Register a cast shape function in the collision table
static void sRegisterCastShape(EShapeSubType inType1, EShapeSubType inType2, CastShape inFunction) { sCastShape[(int)inType1][(int)inType2] = inFunction; }
/// An implementation of CollideShape that swaps inShape1 and inShape2 and swaps the result back, can be registered if the collision function only exists the other way around
static void sReversedCollideShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
/// An implementation of CastShape that swaps inShape1 and inShape2 and swaps the result back, can be registered if the collision function only exists the other way around
static void sReversedCastShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
private:
static CollideShape sCollideShape[NumSubShapeTypes][NumSubShapeTypes];
static CastShape sCastShape[NumSubShapeTypes][NumSubShapeTypes];
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ShapeFilter.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Core/NonCopyable.h>
JPH_NAMESPACE_BEGIN
class Shape;
class SubShapeID;
/// Filter class
class ShapeFilter : public NonCopyable
{
public:
/// Destructor
virtual ~ShapeFilter() = default;
/// Filter function to determine if we should collide with a shape. Returns true if the filter passes.
/// This overload is called when the query doesn't have a source shape (e.g. ray cast / collide point)
/// @param inShape2 Shape we're colliding against
/// @param inSubShapeIDOfShape2 The sub shape ID that will lead from the root shape to inShape2 (i.e. the shape of mBodyID2)
virtual bool ShouldCollide(const Shape *inShape2, const SubShapeID &inSubShapeIDOfShape2) const
{
return true;
}
/// Filter function to determine if two shapes should collide. Returns true if the filter passes.
/// This overload is called when querying a shape vs a shape (e.g. collide object / cast object).
/// It is called at each level of the shape hierarchy, so if you have a compound shape with a box, this function will be called twice.
/// It will not be called on triangles that are part of another shape, i.e a mesh shape will not trigger a callback per triangle. You can filter out individual triangles in the CollisionCollector::AddHit function by their sub shape ID.
/// @param inShape1 1st shape that is colliding
/// @param inSubShapeIDOfShape1 The sub shape ID that will lead from the root shape to inShape1 (i.e. the shape that is used to collide or cast against shape 2)
/// @param inShape2 2nd shape that is colliding
/// @param inSubShapeIDOfShape2 The sub shape ID that will lead from the root shape to inShape2 (i.e. the shape of mBodyID2)
virtual bool ShouldCollide(const Shape *inShape1, const SubShapeID &inSubShapeIDOfShape1, const Shape *inShape2, const SubShapeID &inSubShapeIDOfShape2) const
{
return true;
}
/// Set by the collision detection functions to the body ID of the body that we're colliding against before calling the ShouldCollide function
mutable BodyID mBodyID2;
};
/// Helper class to reverse the order of the shapes in the ShouldCollide function
class ReversedShapeFilter : public ShapeFilter
{
public:
/// Constructor
explicit ReversedShapeFilter(const ShapeFilter &inFilter) : mFilter(inFilter)
{
mBodyID2 = inFilter.mBodyID2;
}
virtual bool ShouldCollide(const Shape *inShape2, const SubShapeID &inSubShapeIDOfShape2) const override
{
return mFilter.ShouldCollide(inShape2, inSubShapeIDOfShape2);
}
virtual bool ShouldCollide(const Shape *inShape1, const SubShapeID &inSubShapeIDOfShape1, const Shape *inShape2, const SubShapeID &inSubShapeIDOfShape2) const override
{
return mFilter.ShouldCollide(inShape2, inSubShapeIDOfShape2, inShape1, inSubShapeIDOfShape1);
}
private:
const ShapeFilter & mFilter;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollideShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/StaticArray.h>
#include <Jolt/Physics/Collision/BackFaceMode.h>
#include <Jolt/Physics/Collision/ActiveEdgeMode.h>
#include <Jolt/Physics/Collision/CollectFacesMode.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Physics/PhysicsSettings.h>
JPH_NAMESPACE_BEGIN
/// Class that contains all information of two colliding shapes
class CollideShapeResult
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Default constructor
CollideShapeResult() = default;
/// Constructor
CollideShapeResult(Vec3Arg inContactPointOn1, Vec3Arg inContactPointOn2, Vec3Arg inPenetrationAxis, float inPenetrationDepth, const SubShapeID &inSubShapeID1, const SubShapeID &inSubShapeID2, const BodyID &inBodyID2) :
mContactPointOn1(inContactPointOn1),
mContactPointOn2(inContactPointOn2),
mPenetrationAxis(inPenetrationAxis),
mPenetrationDepth(inPenetrationDepth),
mSubShapeID1(inSubShapeID1),
mSubShapeID2(inSubShapeID2),
mBodyID2(inBodyID2)
{
}
/// Function required by the CollisionCollector. A smaller fraction is considered to be a 'better hit'. We use -penetration depth to get the hit with the biggest penetration depth
inline float GetEarlyOutFraction() const { return -mPenetrationDepth; }
/// Reverses the hit result, swapping contact point 1 with contact point 2 etc.
inline CollideShapeResult Reversed() const
{
CollideShapeResult result;
result.mContactPointOn2 = mContactPointOn1;
result.mContactPointOn1 = mContactPointOn2;
result.mPenetrationAxis = -mPenetrationAxis;
result.mPenetrationDepth = mPenetrationDepth;
result.mSubShapeID2 = mSubShapeID1;
result.mSubShapeID1 = mSubShapeID2;
result.mBodyID2 = mBodyID2;
result.mShape2Face = mShape1Face;
result.mShape1Face = mShape2Face;
return result;
}
using Face = StaticArray<Vec3, 32>;
Vec3 mContactPointOn1; ///< Contact point on the surface of shape 1 (in world space or relative to base offset)
Vec3 mContactPointOn2; ///< Contact point on the surface of shape 2 (in world space or relative to base offset). If the penetration depth is 0, this will be the same as mContactPointOn1.
Vec3 mPenetrationAxis; ///< Direction to move shape 2 out of collision along the shortest path (magnitude is meaningless, in world space). You can use -mPenetrationAxis.Normalized() as contact normal.
float mPenetrationDepth; ///< Penetration depth (move shape 2 by this distance to resolve the collision)
SubShapeID mSubShapeID1; ///< Sub shape ID that identifies the face on shape 1
SubShapeID mSubShapeID2; ///< Sub shape ID that identifies the face on shape 2
BodyID mBodyID2; ///< BodyID to which shape 2 belongs to
Face mShape1Face; ///< Colliding face on shape 1 (optional result, in world space or relative to base offset)
Face mShape2Face; ///< Colliding face on shape 2 (optional result, in world space or relative to base offset)
};
/// Settings to be passed with a collision query
class CollideSettingsBase
{
public:
JPH_OVERRIDE_NEW_DELETE
/// How active edges (edges that a moving object should bump into) are handled
EActiveEdgeMode mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive;
/// If colliding faces should be collected or only the collision point
ECollectFacesMode mCollectFacesMode = ECollectFacesMode::NoFaces;
/// If objects are closer than this distance, they are considered to be colliding (used for GJK) (unit: meter)
float mCollisionTolerance = cDefaultCollisionTolerance;
/// A factor that determines the accuracy of the penetration depth calculation. If the change of the squared distance is less than tolerance * current_penetration_depth^2 the algorithm will terminate. (unit: dimensionless)
float mPenetrationTolerance = cDefaultPenetrationTolerance;
/// When mActiveEdgeMode is CollideOnlyWithActive a movement direction can be provided. When hitting an inactive edge, the system will select the triangle normal as penetration depth only if it impedes the movement less than with the calculated penetration depth.
Vec3 mActiveEdgeMovementDirection = Vec3::sZero();
};
/// Settings to be passed with a collision query
class CollideShapeSettings : public CollideSettingsBase
{
public:
JPH_OVERRIDE_NEW_DELETE
/// When > 0 contacts in the vicinity of the query shape can be found. All nearest contacts that are not further away than this distance will be found (uint: meter)
float mMaxSeparationDistance = 0.0f;
/// How backfacing triangles should be treated
EBackFaceMode mBackFaceMode = EBackFaceMode::IgnoreBackFaces;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollisionCollectorImpl.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/CollisionCollector.h>
#include <Jolt/Core/QuickSort.h>
JPH_NAMESPACE_BEGIN
/// Simple implementation that collects all hits and optionally sorts them on distance
template <class CollectorType>
class AllHitCollisionCollector : public CollectorType
{
public:
/// Redeclare ResultType
using ResultType = typename CollectorType::ResultType;
// See: CollectorType::Reset
virtual void Reset() override
{
CollectorType::Reset();
mHits.clear();
}
// See: CollectorType::AddHit
virtual void AddHit(const ResultType &inResult) override
{
mHits.push_back(inResult);
}
/// Order hits on closest first
void Sort()
{
QuickSort(mHits.begin(), mHits.end(), [](const ResultType &inLHS, const ResultType &inRHS) { return inLHS.GetEarlyOutFraction() < inRHS.GetEarlyOutFraction(); });
}
/// Check if any hits were collected
inline bool HadHit() const
{
return !mHits.empty();
}
Array<ResultType> mHits;
};
/// Simple implementation that collects the closest / deepest hit
template <class CollectorType>
class ClosestHitCollisionCollector : public CollectorType
{
public:
/// Redeclare ResultType
using ResultType = typename CollectorType::ResultType;
// See: CollectorType::Reset
virtual void Reset() override
{
CollectorType::Reset();
mHadHit = false;
}
// See: CollectorType::AddHit
virtual void AddHit(const ResultType &inResult) override
{
float early_out = inResult.GetEarlyOutFraction();
if (!mHadHit || early_out < mHit.GetEarlyOutFraction())
{
// Update early out fraction
CollectorType::UpdateEarlyOutFraction(early_out);
// Store hit
mHit = inResult;
mHadHit = true;
}
}
/// Check if this collector has had a hit
inline bool HadHit() const
{
return mHadHit;
}
ResultType mHit;
private:
bool mHadHit = false;
};
/// Simple implementation that collects any hit
template <class CollectorType>
class AnyHitCollisionCollector : public CollectorType
{
public:
/// Redeclare ResultType
using ResultType = typename CollectorType::ResultType;
// See: CollectorType::Reset
virtual void Reset() override
{
CollectorType::Reset();
mHadHit = false;
}
// See: CollectorType::AddHit
virtual void AddHit(const ResultType &inResult) override
{
// Test that the collector is not collecting more hits after forcing an early out
JPH_ASSERT(!mHadHit);
// Abort any further testing
CollectorType::ForceEarlyOut();
// Store hit
mHit = inResult;
mHadHit = true;
}
/// Check if this collector has had a hit
inline bool HadHit() const
{
return mHadHit;
}
ResultType mHit;
private:
bool mHadHit = false;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CastSphereVsTriangles.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/ShapeCast.h>
JPH_NAMESPACE_BEGIN
/// Collision detection helper that casts a sphere vs one or more triangles
class CastSphereVsTriangles
{
public:
/// Constructor
/// @param inShapeCast The sphere to cast against the triangles and its start and direction
/// @param inShapeCastSettings Settings for performing the cast
/// @param inScale Local space scale for the shape to cast against.
/// @param inCenterOfMassTransform2 Is the center of mass transform of shape 2 (excluding scale), this is used to provide a transform to the shape cast result so that local quantities can be transformed into world space.
/// @param inSubShapeIDCreator1 Class that tracks the current sub shape ID for the casting shape
/// @param ioCollector The collector that receives the results.
CastSphereVsTriangles(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, CastShapeCollector &ioCollector);
/// Cast sphere with a single triangle
/// @param inV0 , inV1 , inV2: CCW triangle vertices
/// @param inActiveEdges bit 0 = edge v0..v1 is active, bit 1 = edge v1..v2 is active, bit 2 = edge v2..v0 is active
/// An active edge is an edge that is not connected to another triangle in such a way that it is impossible to collide with the edge
/// @param inSubShapeID2 The sub shape ID for the triangle
void Cast(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2);
protected:
Vec3 mStart; ///< Starting location of the sphere
Vec3 mDirection; ///< Direction and length of movement of sphere
float mRadius; ///< Scaled radius of sphere
const ShapeCastSettings & mShapeCastSettings;
const Mat44 & mCenterOfMassTransform2;
Vec3 mScale;
SubShapeIDCreator mSubShapeIDCreator1;
CastShapeCollector & mCollector;
private:
void AddHit(bool inBackFacing, const SubShapeID &inSubShapeID2, float inFraction, Vec3Arg inContactPointA, Vec3Arg inContactPointB, Vec3Arg inContactNormal);
void AddHitWithActiveEdgeDetection(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, bool inBackFacing, Vec3Arg inTriangleNormal, uint8 inActiveEdges, const SubShapeID &inSubShapeID2, float inFraction, Vec3Arg inContactPointA, Vec3Arg inContactPointB, Vec3Arg inContactNormal);
float RayCylinder(Vec3Arg inRayDirection, Vec3Arg inCylinderA, Vec3Arg inCylinderB, float inRadius) const;
float mScaleSign; ///< Sign of the scale, -1 if object is inside out, 1 if not
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CastResult.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
JPH_NAMESPACE_BEGIN
/// Structure that holds a ray cast or other object cast hit
class BroadPhaseCastResult
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Function required by the CollisionCollector. A smaller fraction is considered to be a 'better hit'. For rays/cast shapes we can just use the collision fraction.
inline float GetEarlyOutFraction() const { return mFraction; }
BodyID mBodyID; ///< Body that was hit
float mFraction = 1.0f + FLT_EPSILON; ///< Hit fraction of the ray/object [0, 1], HitPoint = Start + mFraction * (End - Start)
};
/// Specialization of cast result against a shape
class RayCastResult : public BroadPhaseCastResult
{
public:
JPH_OVERRIDE_NEW_DELETE
SubShapeID mSubShapeID2; ///< Sub shape ID of shape that we collided against
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/AABoxCast.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Geometry/AABox.h>
JPH_NAMESPACE_BEGIN
/// Structure that holds AABox moving linearly through 3d space
struct AABoxCast
{
JPH_OVERRIDE_NEW_DELETE
AABox mBox; ///< Axis aligned box at starting location
Vec3 mDirection; ///< Direction and length of the cast (anything beyond this length will not be reported as a hit)
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollidePointResult.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
JPH_NAMESPACE_BEGIN
/// Structure that holds the result of colliding a point against a shape
class CollidePointResult
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Function required by the CollisionCollector. A smaller fraction is considered to be a 'better hit'. For point queries there is no sensible return value.
inline float GetEarlyOutFraction() const { return 0.0f; }
BodyID mBodyID; ///< Body that was hit
SubShapeID mSubShapeID2; ///< Sub shape ID of shape that we collided against
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/RayCast.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/BackFaceMode.h>
JPH_NAMESPACE_BEGIN
/// Structure that holds a single ray cast
template <class Vec, class Mat, class RayCastType>
struct RayCastT
{
JPH_OVERRIDE_NEW_DELETE
/// Constructors
RayCastT() = default; // Allow raycast to be created uninitialized
RayCastT(typename Vec::ArgType inOrigin, Vec3Arg inDirection) : mOrigin(inOrigin), mDirection(inDirection) { }
RayCastT(const RayCastT<Vec, Mat, RayCastType> &) = default;
/// Transform this ray using inTransform
RayCastType Transformed(typename Mat::ArgType inTransform) const
{
Vec ray_origin = inTransform * mOrigin;
Vec3 ray_direction(inTransform * (mOrigin + mDirection) - ray_origin);
return { ray_origin, ray_direction };
}
/// Get point with fraction inFraction on ray (0 = start of ray, 1 = end of ray)
inline Vec GetPointOnRay(float inFraction) const
{
return mOrigin + inFraction * mDirection;
}
Vec mOrigin; ///< Origin of the ray
Vec3 mDirection; ///< Direction and length of the ray (anything beyond this length will not be reported as a hit)
};
struct RayCast : public RayCastT<Vec3, Mat44, RayCast>
{
using RayCastT<Vec3, Mat44, RayCast>::RayCastT;
};
struct RRayCast : public RayCastT<RVec3, RMat44, RRayCast>
{
using RayCastT<RVec3, RMat44, RRayCast>::RayCastT;
/// Convert from RayCast, converts single to double precision
explicit RRayCast(const RayCast &inRay) :
RRayCast(RVec3(inRay.mOrigin), inRay.mDirection)
{
}
/// Convert to RayCast, which implies casting from double precision to single precision
explicit operator RayCast() const
{
return RayCast(Vec3(mOrigin), mDirection);
}
};
/// Settings to be passed with a ray cast
class RayCastSettings
{
public:
JPH_OVERRIDE_NEW_DELETE
/// How backfacing triangles should be treated
EBackFaceMode mBackFaceMode = EBackFaceMode::IgnoreBackFaces;
/// If convex shapes should be treated as solid. When true, a ray starting inside a convex shape will generate a hit at fraction 0.
bool mTreatConvexAsSolid = true;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/EstimateCollisionResponse.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2023 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/ContactListener.h>
JPH_NAMESPACE_BEGIN
/// A structure that contains the estimated contact and friction impulses and the resulting body velocities
struct CollisionEstimationResult
{
Vec3 mLinearVelocity1; ///< The estimated linear velocity of body 1 after collision
Vec3 mAngularVelocity1; ///< The estimated angular velocity of body 1 after collision
Vec3 mLinearVelocity2; ///< The estimated linear velocity of body 2 after collision
Vec3 mAngularVelocity2; ///< The estimated angular velocity of body 2 after collision
Vec3 mTangent1; ///< Normalized tangent of contact normal
Vec3 mTangent2; ///< Second normalized tangent of contact normal (forms a basis with mTangent1 and mWorldSpaceNormal)
struct Impulse
{
float mContactImpulse; ///< Estimated contact impulses (kg m / s)
float mFrictionImpulse1; ///< Estimated friction impulses in the direction of tangent 1 (kg m / s)
float mFrictionImpulse2; ///< Estimated friction impulses in the direction of tangent 2 (kg m / s)
};
using Impulses = StaticArray<Impulse, ContactPoints::Capacity>;
Impulses mImpulses;
};
/// This function estimates the contact impulses and body velocity changes as a result of a collision.
/// It can be used in the ContactListener::OnContactAdded to determine the strength of the collision to e.g. play a sound or trigger a particle system.
/// This function is accurate when two bodies collide but will not be accurate when more than 2 bodies collide at the same time as it does not know about these other collisions.
///
/// @param inBody1 Colliding body 1
/// @param inBody2 Colliding body 2
/// @param inManifold The collision manifold
/// @param outResult A structure that contains the estimated contact and friction impulses and the resulting body velocities
/// @param inCombinedFriction The combined friction of body 1 and body 2 (see ContactSettings::mCombinedFriction)
/// @param inCombinedRestitution The combined restitution of body 1 and body 2 (see ContactSettings::mCombinedRestitution)
/// @param inMinVelocityForRestitution Minimal velocity required for restitution to be applied (see PhysicsSettings::mMinVelocityForRestitution)
/// @param inNumIterations Number of iterations to use for the impulse estimation (see PhysicsSettings::mNumVelocitySteps, note you can probably use a lower number for a decent estimate). If you set the number of iterations to 1 then no friction will be calculated.
void EstimateCollisionResponse(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, CollisionEstimationResult &outResult, float inCombinedFriction, float inCombinedRestitution, float inMinVelocityForRestitution = 1.0f, uint inNumIterations = 10);
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ActiveEdgeMode.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
JPH_NAMESPACE_BEGIN
/// How to treat active/inactive edges.
/// An active edge is an edge that either has no neighbouring edge or if the angle between the two connecting faces is too large, see: ActiveEdges
enum class EActiveEdgeMode : uint8
{
CollideOnlyWithActive, ///< Do not collide with inactive edges. For physics simulation, this gives less ghost collisions.
CollideWithAll, ///< Collide with all edges. Use this when you're interested in all collisions.
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/PhysicsMaterialSimple.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/PhysicsMaterial.h>
JPH_NAMESPACE_BEGIN
/// Sample implementation of PhysicsMaterial that just holds the needed properties directly
class PhysicsMaterialSimple : public PhysicsMaterial
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(PhysicsMaterialSimple)
/// Constructor
PhysicsMaterialSimple() = default;
PhysicsMaterialSimple(const string_view &inName, ColorArg inColor) : mDebugName(inName), mDebugColor(inColor) { }
// Properties
virtual const char * GetDebugName() const override { return mDebugName.c_str(); }
virtual Color GetDebugColor() const override { return mDebugColor; }
// See: PhysicsMaterial::SaveBinaryState
virtual void SaveBinaryState(StreamOut &inStream) const override;
protected:
// See: PhysicsMaterial::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
String mDebugName; ///< Name of the material, used for debugging purposes
Color mDebugColor = Color::sGrey; ///< Color of the material, used to render the shapes
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/GroupFilterTable.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/GroupFilter.h>
#include <Jolt/Physics/Collision/CollisionGroup.h>
JPH_NAMESPACE_BEGIN
/// Implementation of GroupFilter that stores a bit table with one bit per sub shape ID pair to determine if they collide or not
///
/// The collision rules:
/// - If one of the objects is in the cInvalidGroup the objects will collide
/// - If the objects are in different groups they will collide
/// - If they're in the same group but their collision filter is different they will not collide
/// - If they're in the same group and their collision filters match, we'll use the SubGroupID and the table below:
///
/// For N = 6 sub shapes the table will look like:
///
/// group 1 --->
/// group 2 x.....
/// | ox....
/// | oox...
/// V ooox..
/// oooox.
/// ooooox
///
/// x means group 1 == group 2 and we define this to never collide
/// o is a bit that we have to store
/// . is a bit we don't need to store because the table is symmetric, we take care that group 2 > group 1 always by swapping the elements if needed
///
/// The total number of bits we need to store is (N * (N - 1)) / 2
class GroupFilterTable final : public GroupFilter
{
JPH_DECLARE_SERIALIZABLE_VIRTUAL(GroupFilterTable)
private:
using GroupID = CollisionGroup::GroupID;
using SubGroupID = CollisionGroup::SubGroupID;
/// Get which bit corresponds to the pair (inSubGroup1, inSubGroup2)
int GetBit(SubGroupID inSubGroup1, SubGroupID inSubGroup2) const
{
JPH_ASSERT(inSubGroup1 != inSubGroup2);
// We store the lower left half only, so swap the inputs when trying to access the top right half
if (inSubGroup1 > inSubGroup2)
swap(inSubGroup1, inSubGroup2);
JPH_ASSERT(inSubGroup2 < mNumSubGroups);
// Calculate at which bit the entry for this pair resides
// We use the fact that a row always starts at inSubGroup2 * (inSubGroup2 - 1) / 2
// (this is the amount of bits needed to store a table of inSubGroup2 entries)
return (inSubGroup2 * (inSubGroup2 - 1)) / 2 + inSubGroup1;
}
public:
/// Constructs the table with inNumSubGroups subgroups, initially all collision pairs are enabled except when the sub group ID is the same
explicit GroupFilterTable(uint inNumSubGroups = 0) :
mNumSubGroups(inNumSubGroups)
{
// By default everything collides
int table_size = ((inNumSubGroups * (inNumSubGroups - 1)) / 2 + 7) / 8;
mTable.resize(table_size, 0xff);
}
/// Copy constructor
GroupFilterTable(const GroupFilterTable &inRHS) : mNumSubGroups(inRHS.mNumSubGroups), mTable(inRHS.mTable) { }
/// Disable collision between two sub groups
void DisableCollision(SubGroupID inSubGroup1, SubGroupID inSubGroup2)
{
int bit = GetBit(inSubGroup1, inSubGroup2);
mTable[bit >> 3] &= (0xff ^ (1 << (bit & 0b111)));
}
/// Enable collision between two sub groups
void EnableCollision(SubGroupID inSubGroup1, SubGroupID inSubGroup2)
{
int bit = GetBit(inSubGroup1, inSubGroup2);
mTable[bit >> 3] |= 1 << (bit & 0b111);
}
/// Check if the collision between two subgroups is enabled
inline bool IsCollisionEnabled(SubGroupID inSubGroup1, SubGroupID inSubGroup2) const
{
// Test if the bit is set for this group pair
int bit = GetBit(inSubGroup1, inSubGroup2);
return (mTable[bit >> 3] & (1 << (bit & 0b111))) != 0;
}
/// Checks if two CollisionGroups collide
virtual bool CanCollide(const CollisionGroup &inGroup1, const CollisionGroup &inGroup2) const override
{
// If one of the groups is cInvalidGroup the objects will collide (note that the if following this if will ensure that group2 is not cInvalidGroup)
if (inGroup1.GetGroupID() == CollisionGroup::cInvalidGroup)
return true;
// If the objects are in different groups, they collide
if (inGroup1.GetGroupID() != inGroup2.GetGroupID())
return true;
// If the collision filters do not match, but they're in the same group we ignore the collision
if (inGroup1.GetGroupFilter() != inGroup2.GetGroupFilter())
return false;
// If they are in the same sub group, they don't collide
if (inGroup1.GetSubGroupID() == inGroup2.GetSubGroupID())
return false;
// Check the bit table
return IsCollisionEnabled(inGroup1.GetSubGroupID(), inGroup2.GetSubGroupID());
}
// See: GroupFilter::SaveBinaryState
virtual void SaveBinaryState(StreamOut &inStream) const override;
protected:
// See: GroupFilter::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
uint mNumSubGroups; ///< The number of subgroups that this group filter supports
Array<uint8> mTable; ///< The table of bits that indicates which pairs collide
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/NarrowPhaseQuery.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyFilter.h>
#include <Jolt/Physics/Body/BodyLock.h>
#include <Jolt/Physics/Body/BodyLockInterface.h>
#include <Jolt/Physics/Collision/ShapeFilter.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuery.h>
#include <Jolt/Physics/Collision/BackFaceMode.h>
JPH_NAMESPACE_BEGIN
class Shape;
class CollideShapeSettings;
class RayCastResult;
/// Class that provides an interface for doing precise collision detection against the broad and then the narrow phase.
/// Unlike a BroadPhaseQuery, the NarrowPhaseQuery will test against shapes and will return collision information against triangles, spheres etc.
class NarrowPhaseQuery : public NonCopyable
{
public:
/// Initialize the interface (should only be called by PhysicsSystem)
void Init(BodyLockInterface &inBodyLockInterface, BroadPhaseQuery &inBroadPhaseQuery) { mBodyLockInterface = &inBodyLockInterface; mBroadPhaseQuery = &inBroadPhaseQuery; }
/// Cast a ray and find the closest hit. Returns true if it finds a hit. Hits further than ioHit.mFraction will not be considered and in this case ioHit will remain unmodified (and the function will return false).
/// Convex objects will be treated as solid (meaning if the ray starts inside, you'll get a hit fraction of 0) and back face hits against triangles are returned.
/// If you want the surface normal of the hit use Body::GetWorldSpaceSurfaceNormal(ioHit.mSubShapeID2, inRay.GetPointOnRay(ioHit.mFraction)) on body with ID ioHit.mBodyID.
bool CastRay(const RRayCast &inRay, RayCastResult &ioHit, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }, const BodyFilter &inBodyFilter = { }) const;
/// Cast a ray, allows collecting multiple hits. Note that this version is more flexible but also slightly slower than the CastRay function that returns only a single hit.
/// If you want the surface normal of the hit use Body::GetWorldSpaceSurfaceNormal(collected sub shape ID, inRay.GetPointOnRay(collected fraction)) on body with collected body ID.
void CastRay(const RRayCast &inRay, const RayCastSettings &inRayCastSettings, CastRayCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }, const BodyFilter &inBodyFilter = { }, const ShapeFilter &inShapeFilter = { }) const;
/// Check if inPoint is inside any shapes. For this tests all shapes are treated as if they were solid.
/// For a mesh shape, this test will only provide sensible information if the mesh is a closed manifold.
/// For each shape that collides, ioCollector will receive a hit
void CollidePoint(RVec3Arg inPoint, CollidePointCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }, const BodyFilter &inBodyFilter = { }, const ShapeFilter &inShapeFilter = { }) const;
/// Collide a shape with the system
/// @param inShape Shape to test
/// @param inShapeScale Scale in local space of shape
/// @param inCenterOfMassTransform Center of mass transform for the shape
/// @param inCollideShapeSettings Settings
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. inCenterOfMassTransform.GetTranslation() since floats are most accurate near the origin
/// @param ioCollector Collector that receives the hits
/// @param inBroadPhaseLayerFilter Filter that filters at broadphase level
/// @param inObjectLayerFilter Filter that filters at layer level
/// @param inBodyFilter Filter that filters at body level
/// @param inShapeFilter Filter that filters at shape level
void CollideShape(const Shape *inShape, Vec3Arg inShapeScale, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }, const BodyFilter &inBodyFilter = { }, const ShapeFilter &inShapeFilter = { }) const;
/// Cast a shape and report any hits to ioCollector
/// @param inShapeCast The shape cast and its position and direction
/// @param inShapeCastSettings Settings for the shape cast
/// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. inShapeCast.mCenterOfMassStart.GetTranslation() since floats are most accurate near the origin
/// @param ioCollector Collector that receives the hits
/// @param inBroadPhaseLayerFilter Filter that filters at broadphase level
/// @param inObjectLayerFilter Filter that filters at layer level
/// @param inBodyFilter Filter that filters at body level
/// @param inShapeFilter Filter that filters at shape level
void CastShape(const RShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }, const BodyFilter &inBodyFilter = { }, const ShapeFilter &inShapeFilter = { }) const;
/// Collect all leaf transformed shapes that fall inside world space box inBox
void CollectTransformedShapes(const AABox &inBox, TransformedShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }, const BodyFilter &inBodyFilter = { }, const ShapeFilter &inShapeFilter = { }) const;
private:
BodyLockInterface * mBodyLockInterface = nullptr;
BroadPhaseQuery * mBroadPhaseQuery = nullptr;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/CollideConvexVsTriangles.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Geometry/AABox.h>
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
JPH_NAMESPACE_BEGIN
class CollideShapeSettings;
/// Collision detection helper that collides a convex object vs one or more triangles
class CollideConvexVsTriangles
{
public:
/// Constructor
/// @param inShape1 The convex shape to collide against triangles
/// @param inScale1 Local space scale for the convex object
/// @param inScale2 Local space scale for the triangles
/// @param inCenterOfMassTransform1 Transform that takes the center of mass of 1 into world space
/// @param inCenterOfMassTransform2 Transform that takes the center of mass of 2 into world space
/// @param inSubShapeID1 Sub shape ID of the convex object
/// @param inCollideShapeSettings Settings for the collide shape query
/// @param ioCollector The collector that will receive the results
CollideConvexVsTriangles(const ConvexShape *inShape1, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeID &inSubShapeID1, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector);
/// Collide convex object with a single triangle
/// @param inV0 , inV1 , inV2: CCW triangle vertices
/// @param inActiveEdges bit 0 = edge v0..v1 is active, bit 1 = edge v1..v2 is active, bit 2 = edge v2..v0 is active
/// An active edge is an edge that is not connected to another triangle in such a way that it is impossible to collide with the edge
/// @param inSubShapeID2 The sub shape ID for the triangle
void Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8 inActiveEdges, const SubShapeID &inSubShapeID2);
protected:
const CollideShapeSettings & mCollideShapeSettings; ///< Settings for this collision operation
CollideShapeCollector & mCollector; ///< The collector that will receive the results
const ConvexShape * mShape1; ///< The shape that we're colliding with
Vec3 mScale1; ///< The scale of the shape (in shape local space) of the shape we're colliding with
Vec3 mScale2; ///< The scale of the shape (in shape local space) of the shape we're colliding against
Mat44 mTransform1; ///< Transform of the shape we're colliding with
Mat44 mTransform2To1; ///< Transform that takes a point in space of the colliding shape to the shape we're colliding with
AABox mBoundsOf1; ///< Bounds of the colliding shape in local space
AABox mBoundsOf1InSpaceOf2; ///< Bounds of the colliding shape in space of shape we're colliding with
SubShapeID mSubShapeID1; ///< Sub shape ID of colliding shape
float mScaleSign2; ///< Sign of the scale of object 2, -1 if object is inside out, 1 if not
ConvexShape::SupportBuffer mBufferExCvxRadius; ///< Buffer that holds the support function data excluding convex radius
ConvexShape::SupportBuffer mBufferIncCvxRadius; ///< Buffer that holds the support function data including convex radius
const ConvexShape::Support * mShape1ExCvxRadius = nullptr; ///< Actual support function object excluding convex radius
const ConvexShape::Support * mShape1IncCvxRadius = nullptr; ///< Actual support function object including convex radius
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/NarrowPhaseStats.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/TickCounter.h>
#include <Jolt/Physics/Collision/Shape/Shape.h>
JPH_SUPPRESS_WARNING_PUSH
JPH_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic")
// Shorthand function to ifdef out code if narrow phase stats tracking is off
#ifdef JPH_TRACK_NARROWPHASE_STATS
#define JPH_IF_TRACK_NARROWPHASE_STATS(...) __VA_ARGS__
#else
#define JPH_IF_TRACK_NARROWPHASE_STATS(...)
#endif // JPH_TRACK_NARROWPHASE_STATS
JPH_SUPPRESS_WARNING_POP
#ifdef JPH_TRACK_NARROWPHASE_STATS
JPH_NAMESPACE_BEGIN
/// Structure that tracks narrow phase timing information for a particular combination of shapes
class NarrowPhaseStat
{
public:
/// Trace an individual stat in CSV form.
void ReportStats(const char *inName, EShapeSubType inType1, EShapeSubType inType2) const;
/// Trace the collected broadphase stats in CSV form.
/// This report can be used to judge and tweak the efficiency of the broadphase.
static void sReportStats();
atomic<uint64> mNumQueries = 0;
atomic<uint64> mHitsReported = 0;
atomic<uint64> mTotalTicks = 0;
atomic<uint64> mChildTicks = 0;
static NarrowPhaseStat sCollideShape[NumSubShapeTypes][NumSubShapeTypes];
static NarrowPhaseStat sCastShape[NumSubShapeTypes][NumSubShapeTypes];
};
/// Object that tracks the start and end of a narrow phase operation
class TrackNarrowPhaseStat
{
public:
TrackNarrowPhaseStat(NarrowPhaseStat &inStat) :
mStat(inStat),
mParent(sRoot),
mStart(GetProcessorTickCount())
{
// Make this the new root of the chain
sRoot = this;
}
~TrackNarrowPhaseStat()
{
uint64 delta_ticks = GetProcessorTickCount() - mStart;
// Notify parent of time spent in child
if (mParent != nullptr)
mParent->mStat.mChildTicks += delta_ticks;
// Increment stats at this level
mStat.mNumQueries++;
mStat.mTotalTicks += delta_ticks;
// Restore root pointer
JPH_ASSERT(sRoot == this);
sRoot = mParent;
}
NarrowPhaseStat & mStat;
TrackNarrowPhaseStat * mParent;
uint64 mStart;
static thread_local TrackNarrowPhaseStat *sRoot;
};
/// Object that tracks the start and end of a hit being processed by a collision collector
class TrackNarrowPhaseCollector
{
public:
TrackNarrowPhaseCollector() :
mStart(GetProcessorTickCount())
{
}
~TrackNarrowPhaseCollector()
{
// Mark time spent in collector as 'child' time for the parent
uint64 delta_ticks = GetProcessorTickCount() - mStart;
if (TrackNarrowPhaseStat::sRoot != nullptr)
TrackNarrowPhaseStat::sRoot->mStat.mChildTicks += delta_ticks;
// Notify all parents of a hit
for (TrackNarrowPhaseStat *track = TrackNarrowPhaseStat::sRoot; track != nullptr; track = track->mParent)
track->mStat.mHitsReported++;
}
private:
uint64 mStart;
};
JPH_NAMESPACE_END
#endif // JPH_TRACK_NARROWPHASE_STATS
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ActiveEdges.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Geometry/ClosestPoint.h>
JPH_NAMESPACE_BEGIN
/// An active edge is an edge that either has no neighbouring edge or if the angle between the two connecting faces is too large.
namespace ActiveEdges
{
/// Helper function to check if an edge is active or not
/// @param inNormal1 Triangle normal of triangle on the left side of the edge (when looking along the edge from the top)
/// @param inNormal2 Triangle normal of triangle on the right side of the edge
/// @param inEdgeDirection Vector that points along the edge
inline static bool IsEdgeActive(Vec3Arg inNormal1, Vec3Arg inNormal2, Vec3Arg inEdgeDirection)
{
// If normals are opposite the edges are active (the triangles are back to back)
float cos_angle_normals = inNormal1.Dot(inNormal2);
if (cos_angle_normals < -0.99984769515639123915701155881391f) // cos(179 degrees)
return true;
// Check if concave edge, if so we are not active
if (inNormal1.Cross(inNormal2).Dot(inEdgeDirection) < 0.0f)
return false;
// Convex edge, active when angle bigger than threshold
return cos_angle_normals < 0.99619469809174553229501040247389f; // cos(5 degrees)
}
/// Replace normal by triangle normal if a hit is hitting an inactive edge
/// @param inV0 , inV1 , inV2 form the triangle
/// @param inTriangleNormal is the normal of the provided triangle (does not need to be normalized)
/// @param inActiveEdges bit 0 = edge v0..v1 is active, bit 1 = edge v1..v2 is active, bit 2 = edge v2..v0 is active
/// @param inPoint Collision point on the triangle
/// @param inNormal Collision normal on the triangle (does not need to be normalized)
/// @param inMovementDirection Can be zero. This gives an indication of in which direction the motion is to determine if when we hit an inactive edge/triangle we should return the triangle normal.
/// @return Returns inNormal if an active edge was hit, otherwise returns inTriangleNormal
inline static Vec3 FixNormal(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inTriangleNormal, uint8 inActiveEdges, Vec3Arg inPoint, Vec3Arg inNormal, Vec3Arg inMovementDirection)
{
// Check: All of the edges are active, we have the correct normal already. No need to call this function!
JPH_ASSERT(inActiveEdges != 0b111);
// If inNormal would affect movement less than inTriangleNormal use inNormal
// This is done since it is really hard to make a distinction between sliding over a horizontal triangulated grid and hitting an edge (in this case you want to use the triangle normal)
// and sliding over a triangulated grid and grazing a vertical triangle with an inactive edge (in this case using the triangle normal will cause the object to bounce back so we want to use the calculated normal).
// To solve this we take a movement hint to give an indication of what direction our object is moving. If the edge normal results in less motion difference than the triangle normal we use the edge normal.
float normal_length = inNormal.Length();
float triangle_normal_length = inTriangleNormal.Length();
if (inMovementDirection.Dot(inNormal) * triangle_normal_length < inMovementDirection.Dot(inTriangleNormal) * normal_length)
return inNormal;
// Check: None of the edges are active, we need to use the triangle normal
if (inActiveEdges == 0)
return inTriangleNormal;
// Some edges are active.
// If normal is parallel to the triangle normal we don't need to check the active edges.
if (inTriangleNormal.Dot(inNormal) > 0.99619469809174553229501040247389f * normal_length * triangle_normal_length) // cos(5 degrees)
return inNormal;
const float cEpsilon = 1.0e-4f;
const float cOneMinusEpsilon = 1.0f - cEpsilon;
uint colliding_edge;
// Test where the contact point is in the triangle
float u, v, w;
ClosestPoint::GetBaryCentricCoordinates(inV0 - inPoint, inV1 - inPoint, inV2 - inPoint, u, v, w);
if (u > cOneMinusEpsilon)
{
// Colliding with v0, edge 0 or 2 needs to be active
colliding_edge = 0b101;
}
else if (v > cOneMinusEpsilon)
{
// Colliding with v1, edge 0 or 1 needs to be active
colliding_edge = 0b011;
}
else if (w > cOneMinusEpsilon)
{
// Colliding with v2, edge 1 or 2 needs to be active
colliding_edge = 0b110;
}
else if (u < cEpsilon)
{
// Colliding with edge v1, v2, edge 1 needs to be active
colliding_edge = 0b010;
}
else if (v < cEpsilon)
{
// Colliding with edge v0, v2, edge 2 needs to be active
colliding_edge = 0b100;
}
else if (w < cEpsilon)
{
// Colliding with edge v0, v1, edge 0 needs to be active
colliding_edge = 0b001;
}
else
{
// Interior hit
return inTriangleNormal;
}
// If this edge is active, use the provided normal instead of the triangle normal
return (inActiveEdges & colliding_edge) != 0? inNormal : inTriangleNormal;
}
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/ObjectLayer.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/NonCopyable.h>
JPH_NAMESPACE_BEGIN
/// Layer that objects can be in, determines which other objects it can collide with
#ifndef JPH_OBJECT_LAYER_BITS
#define JPH_OBJECT_LAYER_BITS 16
#endif // JPH_OBJECT_LAYER_BITS
#if JPH_OBJECT_LAYER_BITS == 16
using ObjectLayer = uint16;
#elif JPH_OBJECT_LAYER_BITS == 32
using ObjectLayer = uint32;
#else
#error "JPH_OBJECT_LAYER_BITS must be 16 or 32"
#endif
/// Constant value used to indicate an invalid object layer
static constexpr ObjectLayer cObjectLayerInvalid = ObjectLayer(~ObjectLayer(0U));
/// Filter class for object layers
class ObjectLayerFilter : public NonCopyable
{
public:
/// Destructor
virtual ~ObjectLayerFilter() = default;
/// Function to filter out object layers when doing collision query test (return true to allow testing against objects with this layer)
virtual bool ShouldCollide(ObjectLayer inLayer) const
{
return true;
}
#ifdef JPH_TRACK_BROADPHASE_STATS
/// Get a string that describes this filter for stat tracking purposes
virtual String GetDescription() const
{
return "No Description";
}
#endif // JPH_TRACK_BROADPHASE_STATS
};
/// Filter class to test if two objects can collide based on their object layer. Used while finding collision pairs.
class ObjectLayerPairFilter : public NonCopyable
{
public:
/// Destructor
virtual ~ObjectLayerPairFilter() = default;
/// Returns true if two layers can collide
virtual bool ShouldCollide(ObjectLayer inLayer1, ObjectLayer inLayer2) const
{
return true;
}
};
/// Default filter class that uses the pair filter in combination with a specified layer to filter layers
class DefaultObjectLayerFilter : public ObjectLayerFilter
{
public:
/// Constructor
DefaultObjectLayerFilter(const ObjectLayerPairFilter &inObjectLayerPairFilter, ObjectLayer inLayer) :
mObjectLayerPairFilter(inObjectLayerPairFilter),
mLayer(inLayer)
{
}
/// Copy constructor
DefaultObjectLayerFilter(const DefaultObjectLayerFilter &inRHS) :
mObjectLayerPairFilter(inRHS.mObjectLayerPairFilter),
mLayer(inRHS.mLayer)
{
}
// See ObjectLayerFilter::ShouldCollide
virtual bool ShouldCollide(ObjectLayer inLayer) const override
{
return mObjectLayerPairFilter.ShouldCollide(mLayer, inLayer);
}
private:
const ObjectLayerPairFilter & mObjectLayerPairFilter;
ObjectLayer mLayer;
};
/// Allows objects from a specific layer only
class SpecifiedObjectLayerFilter : public ObjectLayerFilter
{
public:
/// Constructor
explicit SpecifiedObjectLayerFilter(ObjectLayer inLayer) :
mLayer(inLayer)
{
}
// See ObjectLayerFilter::ShouldCollide
virtual bool ShouldCollide(ObjectLayer inLayer) const override
{
return mLayer == inLayer;
}
private:
ObjectLayer mLayer;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BroadPhase/BroadPhase.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuery.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
JPH_NAMESPACE_BEGIN
// Shorthand function to ifdef out code if broadphase stats tracking is off
#ifdef JPH_TRACK_BROADPHASE_STATS
#define JPH_IF_TRACK_BROADPHASE_STATS(...) __VA_ARGS__
#else
#define JPH_IF_TRACK_BROADPHASE_STATS(...)
#endif // JPH_TRACK_BROADPHASE_STATS
class BodyManager;
struct BodyPair;
using BodyPairCollector = CollisionCollector<BodyPair, CollisionCollectorTraitsCollideShape>;
/// Used to do coarse collision detection operations to quickly prune out bodies that will not collide.
class BroadPhase : public BroadPhaseQuery
{
public:
/// Initialize the broadphase.
/// @param inBodyManager The body manager singleton
/// @param inLayerInterface Interface that maps object layers to broadphase layers.
/// Note that the broadphase takes a pointer to the data inside inObjectToBroadPhaseLayer so this object should remain static.
virtual void Init(BodyManager *inBodyManager, const BroadPhaseLayerInterface &inLayerInterface);
/// Should be called after many objects have been inserted to make the broadphase more efficient, usually done on startup only
virtual void Optimize() { /* Optionally overridden by implementation */ }
/// Must be called just before updating the broadphase when none of the body mutexes are locked
virtual void FrameSync() { /* Optionally overridden by implementation */ }
/// Must be called before UpdatePrepare to prevent modifications from being made to the tree
virtual void LockModifications() { /* Optionally overridden by implementation */ }
/// Context used during broadphase update
struct UpdateState { void *mData[4]; };
/// Update the broadphase, needs to be called frequently to update the internal state when bodies have been modified.
/// The UpdatePrepare() function can run in a background thread without influencing the broadphase
virtual UpdateState UpdatePrepare() { return UpdateState(); }
/// Finalizing the update will quickly apply the changes
virtual void UpdateFinalize(const UpdateState &inUpdateState) { /* Optionally overridden by implementation */ }
/// Must be called after UpdateFinalize to allow modifications to the broadphase
virtual void UnlockModifications() { /* Optionally overridden by implementation */ }
/// Handle used during adding bodies to the broadphase
using AddState = void *;
/// Prepare adding inNumber bodies at ioBodies to the broadphase, returns a handle that should be used in AddBodiesFinalize/Abort.
/// This can be done on a background thread without influencing the broadphase.
/// ioBodies may be shuffled around by this function and should be kept that way until AddBodiesFinalize/Abort is called.
virtual AddState AddBodiesPrepare(BodyID *ioBodies, int inNumber) { return nullptr; } // By default the broadphase doesn't support this
/// Finalize adding bodies to the broadphase, supply the return value of AddBodiesPrepare in inAddState.
/// Please ensure that the ioBodies array passed to AddBodiesPrepare is unmodified and passed again to this function.
virtual void AddBodiesFinalize(BodyID *ioBodies, int inNumber, AddState inAddState) = 0;
/// Abort adding bodies to the broadphase, supply the return value of AddBodiesPrepare in inAddState.
/// This can be done on a background thread without influencing the broadphase.
/// Please ensure that the ioBodies array passed to AddBodiesPrepare is unmodified and passed again to this function.
virtual void AddBodiesAbort(BodyID *ioBodies, int inNumber, AddState inAddState) { /* By default nothing needs to be done */ }
/// Remove inNumber bodies in ioBodies from the broadphase.
/// ioBodies may be shuffled around by this function.
virtual void RemoveBodies(BodyID *ioBodies, int inNumber) = 0;
/// Call whenever the aabb of a body changes (can change order of ioBodies array)
/// inTakeLock should be false if we're between LockModifications/UnlockModificiations in which case care needs to be taken to not call this between UpdatePrepare/UpdateFinalize
virtual void NotifyBodiesAABBChanged(BodyID *ioBodies, int inNumber, bool inTakeLock = true) = 0;
/// Call whenever the layer (and optionally the aabb as well) of a body changes (can change order of ioBodies array)
virtual void NotifyBodiesLayerChanged(BodyID *ioBodies, int inNumber) = 0;
/// Find all colliding pairs between dynamic bodies
/// Note that this function is very specifically tailored for the PhysicsSystem::Update function, hence it is not part of the BroadPhaseQuery interface.
/// One of the assumptions it can make is that no locking is needed during the query as it will only be called during a very particular part of the update.
/// @param ioActiveBodies is a list of bodies for which we need to find colliding pairs (this function can change the order of the ioActiveBodies array). This can be a subset of the set of active bodies in the system.
/// @param inNumActiveBodies is the size of the ioActiveBodies array.
/// @param inSpeculativeContactDistance Distance at which speculative contact points will be created.
/// @param inObjectVsBroadPhaseLayerFilter is the filter that determines if an object can collide with a broadphase layer.
/// @param inObjectLayerPairFilter is the filter that determines if two objects can collide.
/// @param ioPairCollector receives callbacks for every body pair found.
virtual void FindCollidingPairs(BodyID *ioActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter, BodyPairCollector &ioPairCollector) const = 0;
/// Same as BroadPhaseQuery::CastAABox but can be implemented in a way to take no broad phase locks.
virtual void CastAABoxNoLock(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const = 0;
#ifdef JPH_TRACK_BROADPHASE_STATS
/// Trace the collected broadphase stats in CSV form.
/// This report can be used to judge and tweak the efficiency of the broadphase.
virtual void ReportStats() { /* Can be implemented by derived classes */ }
#endif // JPH_TRACK_BROADPHASE_STATS
protected:
/// Link to the body manager that manages the bodies in this broadphase
BodyManager * mBodyManager = nullptr;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BroadPhase/BroadPhaseLayer.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/NonCopyable.h>
#include <Jolt/Physics/Collision/ObjectLayer.h>
JPH_NAMESPACE_BEGIN
/// An object layer can be mapped to a broadphase layer. Objects with the same broadphase layer will end up in the same sub structure (usually a tree) of the broadphase.
/// When there are many layers, this reduces the total amount of sub structures the broad phase needs to manage. Usually you want objects that don't collide with each other
/// in different broad phase layers, but there could be exceptions if objects layers only contain a minor amount of objects so it is not beneficial to give each layer its
/// own sub structure in the broadphase.
/// Note: This class requires explicit casting from and to Type to avoid confusion with ObjectLayer
class BroadPhaseLayer
{
public:
using Type = uint8;
JPH_INLINE BroadPhaseLayer() = default;
JPH_INLINE explicit constexpr BroadPhaseLayer(Type inValue) : mValue(inValue) { }
JPH_INLINE constexpr BroadPhaseLayer(const BroadPhaseLayer &) = default;
JPH_INLINE BroadPhaseLayer & operator = (const BroadPhaseLayer &) = default;
JPH_INLINE constexpr bool operator == (const BroadPhaseLayer &inRHS) const
{
return mValue == inRHS.mValue;
}
JPH_INLINE constexpr bool operator != (const BroadPhaseLayer &inRHS) const
{
return mValue != inRHS.mValue;
}
JPH_INLINE constexpr bool operator < (const BroadPhaseLayer &inRHS) const
{
return mValue < inRHS.mValue;
}
JPH_INLINE explicit constexpr operator Type() const
{
return mValue;
}
private:
Type mValue;
};
/// Constant value used to indicate an invalid broad phase layer
static constexpr BroadPhaseLayer cBroadPhaseLayerInvalid(0xff);
/// Interface that the application should implement to allow mapping object layers to broadphase layers
class BroadPhaseLayerInterface : public NonCopyable
{
public:
/// Destructor
virtual ~BroadPhaseLayerInterface() = default;
/// Return the number of broadphase layers there are
virtual uint GetNumBroadPhaseLayers() const = 0;
/// Convert an object layer to the corresponding broadphase layer
virtual BroadPhaseLayer GetBroadPhaseLayer(ObjectLayer inLayer) const = 0;
#if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
/// Get the user readable name of a broadphase layer (debugging purposes)
virtual const char * GetBroadPhaseLayerName(BroadPhaseLayer inLayer) const = 0;
#endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
};
/// Class to test if an object can collide with a broadphase layer. Used while finding collision pairs.
class ObjectVsBroadPhaseLayerFilter : public NonCopyable
{
public:
/// Destructor
virtual ~ObjectVsBroadPhaseLayerFilter() = default;
/// Returns true if an object layer should collide with a broadphase layer
virtual bool ShouldCollide(ObjectLayer inLayer1, BroadPhaseLayer inLayer2) const
{
return true;
}
};
/// Filter class for broadphase layers
class BroadPhaseLayerFilter : public NonCopyable
{
public:
/// Destructor
virtual ~BroadPhaseLayerFilter() = default;
/// Function to filter out broadphase layers when doing collision query test (return true to allow testing against objects with this layer)
virtual bool ShouldCollide(BroadPhaseLayer inLayer) const
{
return true;
}
};
/// Default filter class that uses the pair filter in combination with a specified layer to filter layers
class DefaultBroadPhaseLayerFilter : public BroadPhaseLayerFilter
{
public:
/// Constructor
DefaultBroadPhaseLayerFilter(const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, ObjectLayer inLayer) :
mObjectVsBroadPhaseLayerFilter(inObjectVsBroadPhaseLayerFilter),
mLayer(inLayer)
{
}
// See BroadPhaseLayerFilter::ShouldCollide
virtual bool ShouldCollide(BroadPhaseLayer inLayer) const override
{
return mObjectVsBroadPhaseLayerFilter.ShouldCollide(mLayer, inLayer);
}
private:
const ObjectVsBroadPhaseLayerFilter &mObjectVsBroadPhaseLayerFilter;
ObjectLayer mLayer;
};
/// Allows objects from a specific broad phase layer only
class SpecifiedBroadPhaseLayerFilter : public BroadPhaseLayerFilter
{
public:
/// Constructor
explicit SpecifiedBroadPhaseLayerFilter(BroadPhaseLayer inLayer) :
mLayer(inLayer)
{
}
// See BroadPhaseLayerFilter::ShouldCollide
virtual bool ShouldCollide(BroadPhaseLayer inLayer) const override
{
return mLayer == inLayer;
}
private:
BroadPhaseLayer mLayer;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/BroadPhase/QuadTree.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
#include <Jolt/Physics/PhysicsLock.h>
JPH_NAMESPACE_BEGIN
/// Fast SIMD based quad tree BroadPhase that is multithreading aware and tries to do a minimal amount of locking.
class BroadPhaseQuadTree final : public BroadPhase
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Destructor
virtual ~BroadPhaseQuadTree() override;
// Implementing interface of BroadPhase (see BroadPhase for documentation)
virtual void Init(BodyManager *inBodyManager, const BroadPhaseLayerInterface &inLayerInterface) override;
virtual void Optimize() override;
virtual void FrameSync() override;
virtual void LockModifications() override;
virtual UpdateState UpdatePrepare() override;
virtual void UpdateFinalize(const UpdateState &inUpdateState) override;
virtual void UnlockModifications() override;
virtual AddState AddBodiesPrepare(BodyID *ioBodies, int inNumber) override;
virtual void AddBodiesFinalize(BodyID *ioBodies, int inNumber, AddState inAddState) override;
virtual void AddBodiesAbort(BodyID *ioBodies, int inNumber, AddState inAddState) override;
virtual void RemoveBodies(BodyID *ioBodies, int inNumber) override;
virtual void NotifyBodiesAABBChanged(BodyID *ioBodies, int inNumber, bool inTakeLock) override;
virtual void NotifyBodiesLayerChanged(BodyID *ioBodies, int inNumber) override;
virtual void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CastAABoxNoLock(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void FindCollidingPairs(BodyID *ioActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter, BodyPairCollector &ioPairCollector) const override;
#ifdef JPH_TRACK_BROADPHASE_STATS
virtual void ReportStats() override;
#endif // JPH_TRACK_BROADPHASE_STATS
private:
/// Helper struct for AddBodies handle
struct LayerState
{
JPH_OVERRIDE_NEW_DELETE
BodyID * mBodyStart = nullptr;
BodyID * mBodyEnd;
QuadTree::AddState mAddState;
};
using Tracking = QuadTree::Tracking;
using TrackingVector = QuadTree::TrackingVector;
#ifdef JPH_ENABLE_ASSERTS
/// Context used to lock a physics lock
PhysicsLockContext mLockContext = nullptr;
#endif // JPH_ENABLE_ASSERTS
/// Max amount of bodies we support
size_t mMaxBodies = 0;
/// Array that for each BodyID keeps track of where it is located in which tree
TrackingVector mTracking;
/// Node allocator for all trees
QuadTree::Allocator mAllocator;
/// Information about broad phase layers
const BroadPhaseLayerInterface *mBroadPhaseLayerInterface = nullptr;
/// One tree per object layer
QuadTree * mLayers;
uint mNumLayers;
/// UpdateState implementation for this tree used during UpdatePrepare/Finalize()
struct UpdateStateImpl
{
QuadTree * mTree;
QuadTree::UpdateState mUpdateState;
};
static_assert(sizeof(UpdateStateImpl) <= sizeof(UpdateState));
static_assert(alignof(UpdateStateImpl) <= alignof(UpdateState));
/// Mutex that prevents object modification during UpdatePrepare/Finalize()
SharedMutex mUpdateMutex;
/// We double buffer all trees so that we can query while building the next one and we destroy the old tree the next physics update.
/// This structure ensures that we wait for queries that are still using the old tree.
mutable SharedMutex mQueryLocks[2];
/// This index indicates which lock is currently active, it alternates between 0 and 1
atomic<uint32> mQueryLockIdx { 0 };
/// This is the next tree to update in UpdatePrepare()
uint32 mNextLayerToUpdate = 0;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BroadPhase/QuadTree.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Core/FixedSizeFreeList.h>
#include <Jolt/Core/Atomics.h>
#include <Jolt/Core/NonCopyable.h>
#include <Jolt/Physics/Body/BodyManager.h>
#include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
//#define JPH_DUMP_BROADPHASE_TREE
JPH_NAMESPACE_BEGIN
/// Internal tree structure in broadphase, is essentially a quad AABB tree.
/// Tree is lockless (except for UpdatePrepare/Finalize() function), modifying objects in the tree will widen the aabbs of parent nodes to make the node fit.
/// During the UpdatePrepare/Finalize() call the tree is rebuilt to achieve a tight fit again.
class QuadTree : public NonCopyable
{
public:
JPH_OVERRIDE_NEW_DELETE
private:
// Forward declare
class AtomicNodeID;
/// Class that points to either a body or a node in the tree
class NodeID
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Default constructor does not initialize
inline NodeID() = default;
/// Construct a node ID
static inline NodeID sInvalid() { return NodeID(cInvalidNodeIndex); }
static inline NodeID sFromBodyID(BodyID inID) { NodeID node_id(inID.GetIndexAndSequenceNumber()); JPH_ASSERT(node_id.IsBody()); return node_id; }
static inline NodeID sFromNodeIndex(uint32 inIdx) { NodeID node_id(inIdx | cIsNode); JPH_ASSERT(node_id.IsNode()); return node_id; }
/// Check what type of ID it is
inline bool IsValid() const { return mID != cInvalidNodeIndex; }
inline bool IsBody() const { return (mID & cIsNode) == 0; }
inline bool IsNode() const { return (mID & cIsNode) != 0; }
/// Get body or node index
inline BodyID GetBodyID() const { JPH_ASSERT(IsBody()); return BodyID(mID); }
inline uint32 GetNodeIndex() const { JPH_ASSERT(IsNode()); return mID & ~cIsNode; }
/// Comparison
inline bool operator == (const BodyID &inRHS) const { return mID == inRHS.GetIndexAndSequenceNumber(); }
inline bool operator == (const NodeID &inRHS) const { return mID == inRHS.mID; }
private:
friend class AtomicNodeID;
inline explicit NodeID(uint32 inID) : mID(inID) { }
static const uint32 cIsNode = BodyID::cBroadPhaseBit; ///< If this bit is set it means that the ID refers to a node, otherwise it refers to a body
uint32 mID;
};
static_assert(sizeof(NodeID) == sizeof(BodyID), "Body id's should have the same size as NodeIDs");
/// A NodeID that uses atomics to store the value
class AtomicNodeID
{
public:
/// Constructor
AtomicNodeID() = default;
explicit AtomicNodeID(const NodeID &inRHS) : mID(inRHS.mID) { }
/// Assignment
inline void operator = (const NodeID &inRHS) { mID = inRHS.mID; }
/// Getting the value
inline operator NodeID () const { return NodeID(mID); }
/// Check if the ID is valid
inline bool IsValid() const { return mID != cInvalidNodeIndex; }
/// Comparison
inline bool operator == (const BodyID &inRHS) const { return mID == inRHS.GetIndexAndSequenceNumber(); }
inline bool operator == (const NodeID &inRHS) const { return mID == inRHS.mID; }
/// Atomically compare and swap value. Expects inOld value, replaces with inNew value or returns false
inline bool CompareExchange(NodeID inOld, NodeID inNew) { return mID.compare_exchange_strong(inOld.mID, inNew.mID); }
private:
atomic<uint32> mID;
};
/// Class that represents a node in the tree
class Node
{
public:
/// Construct node
explicit Node(bool inIsChanged);
/// Get bounding box encapsulating all children
void GetNodeBounds(AABox &outBounds) const;
/// Get bounding box in a consistent way with the functions below (check outBounds.IsValid() before using the box)
void GetChildBounds(int inChildIndex, AABox &outBounds) const;
/// Set the bounds in such a way that other threads will either see a fully correct bounding box or a bounding box with no volume
void SetChildBounds(int inChildIndex, const AABox &inBounds);
/// Invalidate bounding box in such a way that other threads will not temporarily see a very large bounding box
void InvalidateChildBounds(int inChildIndex);
/// Encapsulate inBounds in node bounds, returns true if there were changes
bool EncapsulateChildBounds(int inChildIndex, const AABox &inBounds);
/// Bounding box for child nodes or bodies (all initially set to invalid so no collision test will ever traverse to the leaf)
atomic<float> mBoundsMinX[4];
atomic<float> mBoundsMinY[4];
atomic<float> mBoundsMinZ[4];
atomic<float> mBoundsMaxX[4];
atomic<float> mBoundsMaxY[4];
atomic<float> mBoundsMaxZ[4];
/// Index of child node or body ID.
AtomicNodeID mChildNodeID[4];
/// Index of the parent node.
/// Note: This value is unreliable during the UpdatePrepare/Finalize() function as a node may be relinked to the newly built tree.
atomic<uint32> mParentNodeIndex = cInvalidNodeIndex;
/// If this part of the tree has changed, if not, we will treat this sub tree as a single body during the UpdatePrepare/Finalize().
/// If any changes are made to an object inside this sub tree then the direct path from the body to the top of the tree will become changed.
atomic<uint32> mIsChanged;
// Padding to align to 124 bytes
uint32 mPadding = 0;
};
// Maximum size of the stack during tree walk
static constexpr int cStackSize = 128;
static_assert(sizeof(atomic<float>) == 4, "Assuming that an atomic doesn't add any additional storage");
static_assert(sizeof(atomic<uint32>) == 4, "Assuming that an atomic doesn't add any additional storage");
static_assert(is_trivially_destructible<Node>(), "Assuming that we don't have a destructor");
public:
/// Class that allocates tree nodes, can be shared between multiple trees
using Allocator = FixedSizeFreeList<Node>;
static_assert(Allocator::ObjectStorageSize == 128, "Node should be 128 bytes");
/// Data to track location of a Body in the tree
struct Tracking
{
/// Constructor to satisfy the vector class
Tracking() = default;
Tracking(const Tracking &inRHS) : mBroadPhaseLayer(inRHS.mBroadPhaseLayer.load()), mObjectLayer(inRHS.mObjectLayer.load()), mBodyLocation(inRHS.mBodyLocation.load()) { }
/// Invalid body location identifier
static const uint32 cInvalidBodyLocation = 0xffffffff;
atomic<BroadPhaseLayer::Type> mBroadPhaseLayer = (BroadPhaseLayer::Type)cBroadPhaseLayerInvalid;
atomic<ObjectLayer> mObjectLayer = cObjectLayerInvalid;
atomic<uint32> mBodyLocation { cInvalidBodyLocation };
};
using TrackingVector = Array<Tracking>;
/// Destructor
~QuadTree();
#if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
/// Name of the tree for debugging purposes
void SetName(const char *inName) { mName = inName; }
inline const char * GetName() const { return mName; }
#endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
/// Check if there is anything in the tree
inline bool HasBodies() const { return mNumBodies != 0; }
/// Check if the tree needs an UpdatePrepare/Finalize()
inline bool IsDirty() const { return mIsDirty; }
/// Check if this tree can get an UpdatePrepare/Finalize() or if it needs a DiscardOldTree() first
inline bool CanBeUpdated() const { return mFreeNodeBatch.mNumObjects == 0; }
/// Initialization
void Init(Allocator &inAllocator);
struct UpdateState
{
NodeID mRootNodeID; ///< This will be the new root node id
};
/// Will throw away the previous frame's nodes so that we can start building a new tree in the background
void DiscardOldTree();
/// Update the broadphase, needs to be called regularly to achieve a tight fit of the tree when bodies have been modified.
/// UpdatePrepare() will build the tree, UpdateFinalize() will lock the root of the tree shortly and swap the trees and afterwards clean up temporary data structures.
void UpdatePrepare(const BodyVector &inBodies, TrackingVector &ioTracking, UpdateState &outUpdateState, bool inFullRebuild);
void UpdateFinalize(const BodyVector &inBodies, const TrackingVector &inTracking, const UpdateState &inUpdateState);
/// Temporary data structure to pass information between AddBodiesPrepare and AddBodiesFinalize/Abort
struct AddState
{
NodeID mLeafID = NodeID::sInvalid();
AABox mLeafBounds;
};
/// Prepare adding inNumber bodies at ioBodyIDs to the quad tree, returns the state in outState that should be used in AddBodiesFinalize.
/// This can be done on a background thread without influencing the broadphase.
/// ioBodyIDs may be shuffled around by this function.
void AddBodiesPrepare(const BodyVector &inBodies, TrackingVector &ioTracking, BodyID *ioBodyIDs, int inNumber, AddState &outState);
/// Finalize adding bodies to the quadtree, supply the same number of bodies as in AddBodiesPrepare.
void AddBodiesFinalize(TrackingVector &ioTracking, int inNumberBodies, const AddState &inState);
/// Abort adding bodies to the quadtree, supply the same bodies and state as in AddBodiesPrepare.
/// This can be done on a background thread without influencing the broadphase.
void AddBodiesAbort(TrackingVector &ioTracking, const AddState &inState);
/// Remove inNumber bodies in ioBodyIDs from the quadtree.
void RemoveBodies(const BodyVector &inBodies, TrackingVector &ioTracking, const BodyID *ioBodyIDs, int inNumber);
/// Call whenever the aabb of a body changes.
void NotifyBodiesAABBChanged(const BodyVector &inBodies, const TrackingVector &inTracking, const BodyID *ioBodyIDs, int inNumber);
/// Cast a ray and get the intersecting bodies in ioCollector.
void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
/// Get bodies intersecting with inBox in ioCollector
void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
/// Get bodies intersecting with a sphere in ioCollector
void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
/// Get bodies intersecting with a point and any hits to ioCollector
void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
/// Get bodies intersecting with an oriented box and any hits to ioCollector
void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
/// Cast a box and get intersecting bodies in ioCollector
void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking) const;
/// Find all colliding pairs between dynamic bodies, calls ioPairCollector for every pair found
void FindCollidingPairs(const BodyVector &inBodies, const BodyID *inActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, BodyPairCollector &ioPairCollector, const ObjectLayerPairFilter &inObjectLayerPairFilter) const;
#ifdef JPH_TRACK_BROADPHASE_STATS
/// Trace the stats of this tree to the TTY
void ReportStats() const;
#endif // JPH_TRACK_BROADPHASE_STATS
private:
/// Constants
static const uint32 cInvalidNodeIndex = 0xffffffff; ///< Value used to indicate node index is invalid
static const float cLargeFloat; ///< A large floating point number that is small enough to not cause any overflows
static const AABox cInvalidBounds; ///< Invalid bounding box using cLargeFloat
/// We alternate between two trees in order to let collision queries complete in parallel to adding/removing objects to the tree
struct RootNode
{
/// Get the ID of the root node
inline NodeID GetNodeID() const { return NodeID::sFromNodeIndex(mIndex); }
/// Index of the root node of the tree (this is always a node, never a body id)
atomic<uint32> mIndex { cInvalidNodeIndex };
};
/// Caches location of body inBodyID in the tracker, body can be found in mNodes[inNodeIdx].mChildNodeID[inChildIdx]
void GetBodyLocation(const TrackingVector &inTracking, BodyID inBodyID, uint32 &outNodeIdx, uint32 &outChildIdx) const;
void SetBodyLocation(TrackingVector &ioTracking, BodyID inBodyID, uint32 inNodeIdx, uint32 inChildIdx) const;
static void sInvalidateBodyLocation(TrackingVector &ioTracking, BodyID inBodyID);
/// Get the current root of the tree
JPH_INLINE const RootNode & GetCurrentRoot() const { return mRootNode[mRootNodeIndex]; }
JPH_INLINE RootNode & GetCurrentRoot() { return mRootNode[mRootNodeIndex]; }
/// Depending on if inNodeID is a body or tree node return the bounding box
inline AABox GetNodeOrBodyBounds(const BodyVector &inBodies, NodeID inNodeID) const;
/// Mark node and all of its parents as changed
inline void MarkNodeAndParentsChanged(uint32 inNodeIndex);
/// Widen parent bounds of node inNodeIndex to encapsulate inNewBounds, also mark node and all of its parents as changed
inline void WidenAndMarkNodeAndParentsChanged(uint32 inNodeIndex, const AABox &inNewBounds);
/// Allocate a new node
inline uint32 AllocateNode(bool inIsChanged);
/// Try to insert a new leaf to the tree at inNodeIndex
inline bool TryInsertLeaf(TrackingVector &ioTracking, int inNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies);
/// Try to replace the existing root with a new root that contains both the existing root and the new leaf
inline bool TryCreateNewRoot(TrackingVector &ioTracking, atomic<uint32> &ioRootNodeIndex, NodeID inLeafID, const AABox &inLeafBounds, int inLeafNumBodies);
/// Build a tree for ioBodyIDs, returns the NodeID of the root (which will be the ID of a single body if inNumber = 1). All tree levels up to inMaxDepthMarkChanged will be marked as 'changed'.
NodeID BuildTree(const BodyVector &inBodies, TrackingVector &ioTracking, NodeID *ioNodeIDs, int inNumber, uint inMaxDepthMarkChanged, AABox &outBounds);
/// Sorts ioNodeIDs spatially into 2 groups. Second groups starts at ioNodeIDs + outMidPoint.
/// After the function returns ioNodeIDs and ioNodeCenters will be shuffled
static void sPartition(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inNumber, int &outMidPoint);
/// Sorts ioNodeIDs from inBegin to (but excluding) inEnd spatially into 4 groups.
/// outSplit needs to be 5 ints long, when the function returns each group runs from outSplit[i] to (but excluding) outSplit[i + 1]
/// After the function returns ioNodeIDs and ioNodeCenters will be shuffled
static void sPartition4(NodeID *ioNodeIDs, Vec3 *ioNodeCenters, int inBegin, int inEnd, int *outSplit);
#ifdef _DEBUG
/// Validate that the tree is consistent.
/// Note: This function only works if the tree is not modified while we're traversing it.
void ValidateTree(const BodyVector &inBodies, const TrackingVector &inTracking, uint32 inNodeIndex, uint32 inNumExpectedBodies) const;
#endif
#ifdef JPH_DUMP_BROADPHASE_TREE
/// Dump the tree in DOT format (see: https://graphviz.org/)
void DumpTree(const NodeID &inRoot, const char *inFileNamePrefix) const;
#endif
#ifdef JPH_TRACK_BROADPHASE_STATS
/// Mutex protecting the various LayerToStats members
mutable Mutex mStatsMutex;
struct Stat
{
uint64 mNumQueries = 0;
uint64 mNodesVisited = 0;
uint64 mBodiesVisited = 0;
uint64 mHitsReported = 0;
uint64 mTotalTicks = 0;
uint64 mCollectorTicks = 0;
};
using LayerToStats = UnorderedMap<String, Stat>;
/// Trace the stats of a single query type to the TTY
void ReportStats(const char *inName, const LayerToStats &inLayer) const;
mutable LayerToStats mCastRayStats;
mutable LayerToStats mCollideAABoxStats;
mutable LayerToStats mCollideSphereStats;
mutable LayerToStats mCollidePointStats;
mutable LayerToStats mCollideOrientedBoxStats;
mutable LayerToStats mCastAABoxStats;
#endif // JPH_TRACK_BROADPHASE_STATS
/// Debug function to get the depth of the tree from node inNodeID
uint GetMaxTreeDepth(const NodeID &inNodeID) const;
/// Walk the node tree calling the Visitor::VisitNodes for each node encountered and Visitor::VisitBody for each body encountered
template <class Visitor>
JPH_INLINE void WalkTree(const ObjectLayerFilter &inObjectLayerFilter, const TrackingVector &inTracking, Visitor &ioVisitor JPH_IF_TRACK_BROADPHASE_STATS(, LayerToStats &ioStats)) const;
#if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
/// Name of this tree for debugging purposes
const char * mName = "Layer";
#endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED
/// Number of bodies currently in the tree
atomic<uint32> mNumBodies { 0 };
/// We alternate between two tree root nodes. When updating, we activate the new tree and we keep the old tree alive.
/// for queries that are in progress until the next time DiscardOldTree() is called.
RootNode mRootNode[2];
atomic<uint32> mRootNodeIndex { 0 };
/// Allocator that controls adding / freeing nodes
Allocator * mAllocator = nullptr;
/// This is a list of nodes that must be deleted after the trees are swapped and the old tree is no longer in use
Allocator::Batch mFreeNodeBatch;
/// Flag to keep track of changes to the broadphase, if false, we don't need to UpdatePrepare/Finalize()
atomic<bool> mIsDirty = false;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BroadPhase/BroadPhaseBruteForce.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>
#include <Jolt/Core/Mutex.h>
JPH_NAMESPACE_BEGIN
/// Test BroadPhase implementation that does not do anything to speed up the operations. Can be used as a reference implementation.
class BroadPhaseBruteForce final : public BroadPhase
{
public:
JPH_OVERRIDE_NEW_DELETE
// Implementing interface of BroadPhase (see BroadPhase for documentation)
virtual void AddBodiesFinalize(BodyID *ioBodies, int inNumber, AddState inAddState) override;
virtual void RemoveBodies(BodyID *ioBodies, int inNumber) override;
virtual void NotifyBodiesAABBChanged(BodyID *ioBodies, int inNumber, bool inTakeLock) override;
virtual void NotifyBodiesLayerChanged(BodyID *ioBodies, int inNumber) override;
virtual void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CastAABoxNoLock(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter) const override;
virtual void FindCollidingPairs(BodyID *ioActiveBodies, int inNumActiveBodies, float inSpeculativeContactDistance, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter, BodyPairCollector &ioPairCollector) const override;
private:
Array<BodyID> mBodyIDs;
mutable SharedMutex mMutex;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/BroadPhase/BroadPhaseQuery.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
#include <Jolt/Physics/Collision/ObjectLayer.h>
#include <Jolt/Physics/Collision/CollisionCollector.h>
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Core/NonCopyable.h>
JPH_NAMESPACE_BEGIN
struct RayCast;
class BroadPhaseCastResult;
class AABox;
class OrientedBox;
struct AABoxCast;
// Various collector configurations
using RayCastBodyCollector = CollisionCollector<BroadPhaseCastResult, CollisionCollectorTraitsCastRay>;
using CastShapeBodyCollector = CollisionCollector<BroadPhaseCastResult, CollisionCollectorTraitsCastShape>;
using CollideShapeBodyCollector = CollisionCollector<BodyID, CollisionCollectorTraitsCollideShape>;
/// Interface to the broadphase that can perform collision queries. These queries will only test the bounding box of the body to quickly determine a potential set of colliding bodies.
/// The shapes of the bodies are not tested, if you want this then you should use the NarrowPhaseQuery interface.
class BroadPhaseQuery : public NonCopyable
{
public:
/// Virtual destructor
virtual ~BroadPhaseQuery() = default;
/// Cast a ray and add any hits to ioCollector
virtual void CastRay(const RayCast &inRay, RayCastBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }) const = 0;
/// Get bodies intersecting with inBox and any hits to ioCollector
virtual void CollideAABox(const AABox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }) const = 0;
/// Get bodies intersecting with a sphere and any hits to ioCollector
virtual void CollideSphere(Vec3Arg inCenter, float inRadius, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }) const = 0;
/// Get bodies intersecting with a point and any hits to ioCollector
virtual void CollidePoint(Vec3Arg inPoint, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }) const = 0;
/// Get bodies intersecting with an oriented box and any hits to ioCollector
virtual void CollideOrientedBox(const OrientedBox &inBox, CollideShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }) const = 0;
/// Cast a box and add any hits to ioCollector
virtual void CastAABox(const AABoxCast &inBox, CastShapeBodyCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter = { }, const ObjectLayerFilter &inObjectLayerFilter = { }) const = 0;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/CompoundShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
JPH_NAMESPACE_BEGIN
class CollideShapeSettings;
class OrientedBox;
/// Base class settings to construct a compound shape
class CompoundShapeSettings : public ShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_ABSTRACT(CompoundShapeSettings)
/// Constructor. Use AddShape to add the parts.
CompoundShapeSettings() = default;
/// Add a shape to the compound.
void AddShape(Vec3Arg inPosition, QuatArg inRotation, const ShapeSettings *inShape, uint32 inUserData = 0);
/// Add a shape to the compound. Variant that uses a concrete shape, which means this object cannot be serialized.
void AddShape(Vec3Arg inPosition, QuatArg inRotation, const Shape *inShape, uint32 inUserData = 0);
struct SubShapeSettings
{
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(SubShapeSettings)
RefConst<ShapeSettings> mShape; ///< Sub shape (either this or mShapePtr needs to be filled up)
RefConst<Shape> mShapePtr; ///< Sub shape (either this or mShape needs to be filled up)
Vec3 mPosition; ///< Position of the sub shape
Quat mRotation; ///< Rotation of the sub shape
uint32 mUserData = 0; ///< User data value (can be used by the application for any purpose)
};
using SubShapes = Array<SubShapeSettings>;
SubShapes mSubShapes;
};
/// Base class for a compound shape
class CompoundShape : public Shape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
explicit CompoundShape(EShapeSubType inSubType) : Shape(EShapeType::Compound, inSubType) { }
CompoundShape(EShapeSubType inSubType, const ShapeSettings &inSettings, ShapeResult &outResult) : Shape(EShapeType::Compound, inSubType, inSettings, outResult) { }
// See Shape::GetCenterOfMass
virtual Vec3 GetCenterOfMass() const override { return mCenterOfMass; }
// See Shape::MustBeStatic
virtual bool MustBeStatic() const override;
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override { return mLocalBounds; }
// See Shape::GetSubShapeIDBitsRecursive
virtual uint GetSubShapeIDBitsRecursive() const override;
// See Shape::GetWorldSpaceBounds
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
using Shape::GetWorldSpaceBounds;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return mInnerRadius; }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetMaterial
virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
// See Shape::GetSubShapeUserData
virtual uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const override;
// See Shape::GetSubShapeTransformedShape
virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See Shape::GetSubmergedVolume
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
// See Shape::DrawGetSupportFunction
virtual void DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const override;
// See Shape::DrawGetSupportingFace
virtual void DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); }
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); return 0; }
/// Get which sub shape's bounding boxes overlap with an axis aligned box
/// @param inBox The axis aligned box to test against (relative to the center of mass of this shape)
/// @param outSubShapeIndices Buffer where to place the indices of the sub shapes that intersect
/// @param inMaxSubShapeIndices How many indices will fit in the buffer (normally you'd provide a buffer of GetNumSubShapes() indices)
/// @return How many indices were placed in outSubShapeIndices
virtual int GetIntersectingSubShapes(const AABox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const = 0;
/// Get which sub shape's bounding boxes overlap with an axis aligned box
/// @param inBox The axis aligned box to test against (relative to the center of mass of this shape)
/// @param outSubShapeIndices Buffer where to place the indices of the sub shapes that intersect
/// @param inMaxSubShapeIndices How many indices will fit in the buffer (normally you'd provide a buffer of GetNumSubShapes() indices)
/// @return How many indices were placed in outSubShapeIndices
virtual int GetIntersectingSubShapes(const OrientedBox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const = 0;
struct SubShape
{
/// Initialize sub shape from sub shape settings
/// @param inSettings Settings object
/// @param outResult Result object, only used in case of error
/// @return True on success, false on failure
bool FromSettings(const CompoundShapeSettings::SubShapeSettings &inSettings, ShapeResult &outResult)
{
if (inSettings.mShapePtr != nullptr)
{
// Use provided shape
mShape = inSettings.mShapePtr;
}
else
{
// Create child shape
ShapeResult child_result = inSettings.mShape->Create();
if (!child_result.IsValid())
{
outResult = child_result;
return false;
}
mShape = child_result.Get();
}
// Copy user data
mUserData = inSettings.mUserData;
SetTransform(inSettings.mPosition, inSettings.mRotation, Vec3::sZero() /* Center of mass not yet calculated */);
return true;
}
/// Update the transform of this sub shape
/// @param inPosition New position
/// @param inRotation New orientation
/// @param inCenterOfMass The center of mass of the compound shape
JPH_INLINE void SetTransform(Vec3Arg inPosition, QuatArg inRotation, Vec3Arg inCenterOfMass)
{
SetPositionCOM(inPosition - inCenterOfMass + inRotation * mShape->GetCenterOfMass());
mIsRotationIdentity = inRotation.IsClose(Quat::sIdentity()) || inRotation.IsClose(-Quat::sIdentity());
SetRotation(mIsRotationIdentity? Quat::sIdentity() : inRotation);
}
/// Get the local transform for this shape given the scale of the child shape
/// The total transform of the child shape will be GetLocalTransformNoScale(inScale) * Mat44::sScaling(TransformScale(inScale))
/// @param inScale The scale of the child shape (in local space of this shape)
JPH_INLINE Mat44 GetLocalTransformNoScale(Vec3Arg inScale) const
{
JPH_ASSERT(IsValidScale(inScale));
return Mat44::sRotationTranslation(GetRotation(), inScale * GetPositionCOM());
}
/// Test if inScale is valid for this sub shape
inline bool IsValidScale(Vec3Arg inScale) const
{
// We can always handle uniform scale or identity rotations
if (mIsRotationIdentity || ScaleHelpers::IsUniformScale(inScale))
return true;
return ScaleHelpers::CanScaleBeRotated(GetRotation(), inScale);
}
/// Transform the scale to the local space of the child shape
inline Vec3 TransformScale(Vec3Arg inScale) const
{
// We don't need to transform uniform scale or if the rotation is identity
if (mIsRotationIdentity || ScaleHelpers::IsUniformScale(inScale))
return inScale;
return ScaleHelpers::RotateScale(GetRotation(), inScale);
}
/// Compress the center of mass position
JPH_INLINE void SetPositionCOM(Vec3Arg inPositionCOM)
{
inPositionCOM.StoreFloat3(&mPositionCOM);
}
/// Uncompress the center of mass position
JPH_INLINE Vec3 GetPositionCOM() const
{
return Vec3::sLoadFloat3Unsafe(mPositionCOM);
}
/// Compress the rotation
JPH_INLINE void SetRotation(QuatArg inRotation)
{
inRotation.StoreFloat3(&mRotation);
}
/// Uncompress the rotation
JPH_INLINE Quat GetRotation() const
{
return mIsRotationIdentity? Quat::sIdentity() : Quat::sLoadFloat3Unsafe(mRotation);
}
RefConst<Shape> mShape;
Float3 mPositionCOM; ///< Note: Position of center of mass of sub shape!
Float3 mRotation; ///< Note: X, Y, Z of rotation quaternion - note we read 4 bytes beyond this so make sure there's something there
uint32 mUserData; ///< User data value (put here because it falls in padding bytes)
bool mIsRotationIdentity; ///< If mRotation is close to identity (put here because it falls in padding bytes)
// 3 padding bytes left
};
static_assert(sizeof(SubShape) == (JPH_CPU_ADDRESS_BITS == 64? 40 : 36), "Compiler added unexpected padding");
using SubShapes = Array<SubShape>;
/// Access to the sub shapes of this compound
const SubShapes & GetSubShapes() const { return mSubShapes; }
/// Get the total number of sub shapes
uint GetNumSubShapes() const { return (uint)mSubShapes.size(); }
/// Access to a particular sub shape
const SubShape & GetSubShape(uint inIdx) const { return mSubShapes[inIdx]; }
/// Get the user data associated with a shape in this compound
uint32 GetCompoundUserData(uint inIdx) const { return mSubShapes[inIdx].mUserData; }
/// Set the user data associated with a shape in this compound
void SetCompoundUserData(uint inIdx, uint32 inUserData) { mSubShapes[inIdx].mUserData = inUserData; }
/// Check if a sub shape ID is still valid for this shape
/// @param inSubShapeID Sub shape id that indicates the leaf shape relative to this shape
/// @return True if the ID is valid, false if not
inline bool IsSubShapeIDValid(SubShapeID inSubShapeID) const
{
SubShapeID remainder;
return inSubShapeID.PopID(GetSubShapeIDBits(), remainder) < mSubShapes.size();
}
/// Convert SubShapeID to sub shape index
/// @param inSubShapeID Sub shape id that indicates the leaf shape relative to this shape
/// @param outRemainder This is the sub shape ID for the sub shape of the compound after popping off the index
/// @return The index of the sub shape of this compound
inline uint32 GetSubShapeIndexFromID(SubShapeID inSubShapeID, SubShapeID &outRemainder) const
{
uint32 idx = inSubShapeID.PopID(GetSubShapeIDBits(), outRemainder);
JPH_ASSERT(idx < mSubShapes.size(), "Invalid SubShapeID");
return idx;
}
/// @brief Convert a sub shape index to a sub shape ID
/// @param inIdx Index of the sub shape of this compound
/// @param inParentSubShapeID Parent SubShapeID (describing the path to the compound shape)
/// @return A sub shape ID creator that contains the full path to the sub shape with index inIdx
inline SubShapeIDCreator GetSubShapeIDFromIndex(int inIdx, const SubShapeIDCreator &inParentSubShapeID) const
{
return inParentSubShapeID.PushID(inIdx, GetSubShapeIDBits());
}
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
virtual void SaveSubShapeState(ShapeList &outSubShapes) const override;
virtual void RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes) override;
// See Shape::GetStatsRecursive
virtual Stats GetStatsRecursive(VisitedShapes &ioVisitedShapes) const override;
// See Shape::GetVolume
virtual float GetVolume() const override;
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override;
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
// Visitors for collision detection
struct CastRayVisitor;
struct CastRayVisitorCollector;
struct CollidePointVisitor;
struct CastShapeVisitor;
struct CollectTransformedShapesVisitor;
struct CollideCompoundVsShapeVisitor;
struct CollideShapeVsCompoundVisitor;
template <class BoxType> struct GetIntersectingSubShapesVisitor;
/// Determine amount of bits needed to encode sub shape id
inline uint GetSubShapeIDBits() const
{
// Ensure we have enough bits to encode our shape [0, n - 1]
uint32 n = (uint32)mSubShapes.size() - 1;
return 32 - CountLeadingZeros(n);
}
/// Determine the inner radius of this shape
inline void CalculateInnerRadius()
{
mInnerRadius = FLT_MAX;
for (const SubShape &s : mSubShapes)
mInnerRadius = min(mInnerRadius, s.mShape->GetInnerRadius());
}
Vec3 mCenterOfMass { Vec3::sZero() }; ///< Center of mass of the compound
AABox mLocalBounds;
SubShapes mSubShapes;
float mInnerRadius = FLT_MAX; ///< Smallest radius of GetInnerRadius() of child shapes
private:
// Helper functions called by CollisionDispatch
static void sCastCompoundVsShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/ConvexHullShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#include <Jolt/Physics/PhysicsSettings.h>
#include <Jolt/Geometry/Plane.h>
#ifdef JPH_DEBUG_RENDERER
#include <Jolt/Renderer/DebugRenderer.h>
#endif // JPH_DEBUG_RENDERER
JPH_NAMESPACE_BEGIN
/// Class that constructs a ConvexHullShape
class ConvexHullShapeSettings final : public ConvexShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(ConvexHullShapeSettings)
/// Default constructor for deserialization
ConvexHullShapeSettings() = default;
/// Create a convex hull from inPoints and maximum convex radius inMaxConvexRadius, the radius is automatically lowered if the hull requires it.
/// (internally this will be subtracted so the total size will not grow with the convex radius).
ConvexHullShapeSettings(const Vec3 *inPoints, int inNumPoints, float inMaxConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShapeSettings(inMaterial), mPoints(inPoints, inPoints + inNumPoints), mMaxConvexRadius(inMaxConvexRadius) { }
ConvexHullShapeSettings(const Array<Vec3> &inPoints, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShapeSettings(inMaterial), mPoints(inPoints), mMaxConvexRadius(inConvexRadius) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
Array<Vec3> mPoints; ///< Points to create the hull from
float mMaxConvexRadius = 0.0f; ///< Convex radius as supplied by the constructor. Note that during hull creation the convex radius can be made smaller if the value is too big for the hull.
float mMaxErrorConvexRadius = 0.05f; ///< Maximum distance between the shrunk hull + convex radius and the actual hull.
float mHullTolerance = 1.0e-3f; ///< Points are allowed this far outside of the hull (increasing this yields a hull with less vertices). Note that the actual used value can be larger if the points of the hull are far apart.
};
/// A convex hull
class ConvexHullShape final : public ConvexShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Maximum amount of points supported in a convex hull. Note that while constructing a hull, interior points are discarded so you can provide more points.
/// The ConvexHullShapeSettings::Create function will return an error when too many points are provided.
static constexpr int cMaxPointsInHull = 256;
/// Constructor
ConvexHullShape() : ConvexShape(EShapeSubType::ConvexHull) { }
ConvexHullShape(const ConvexHullShapeSettings &inSettings, ShapeResult &outResult);
// See Shape::GetCenterOfMass
virtual Vec3 GetCenterOfMass() const override { return mCenterOfMass; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override { return mLocalBounds; }
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return mInnerRadius; }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See ConvexShape::GetSupportFunction
virtual const Support * GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const override;
// See Shape::GetSubmergedVolume
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
/// Debugging helper draw function that draws how all points are moved when a shape is shrunk by the convex radius
void DrawShrunkShape(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override;
// See Shape::GetVolume
virtual float GetVolume() const override { return mVolume; }
/// Get the convex radius of this convex hull
float GetConvexRadius() const { return mConvexRadius; }
/// Get the planes of this convex hull
const Array<Plane> & GetPlanes() const { return mPlanes; }
/// Get the number of vertices in this convex hull
inline uint GetNumPoints() const { return (uint)mPoints.size(); }
/// Get a vertex of this convex hull relative to the center of mass
inline Vec3 GetPoint(uint inIndex) const { return mPoints[inIndex].mPosition; }
/// Get the number of faces in this convex hull
inline uint GetNumFaces() const { return (uint)mFaces.size(); }
/// Get the number of vertices in a face
inline uint GetNumVerticesInFace(uint inFaceIndex) const { return mFaces[inFaceIndex].mNumVertices; }
/// Get the vertices indices of a face
/// @param inFaceIndex Index of the face.
/// @param inMaxVertices Maximum number of vertices to return.
/// @param outVertices Array of vertices indices, must be at least inMaxVertices in size, the vertices are returned in counter clockwise order and the positions can be obtained using GetPoint(index).
/// @return Number of vertices in face, if this is bigger than inMaxVertices, not all vertices were retrieved.
inline uint GetFaceVertices(uint inFaceIndex, uint inMaxVertices, uint *outVertices) const
{
const Face &face = mFaces[inFaceIndex];
const uint8 *first_vertex = mVertexIdx.data() + face.mFirstVertex;
uint num_vertices = min<uint>(face.mNumVertices, inMaxVertices);
for (uint i = 0; i < num_vertices; ++i)
outVertices[i] = first_vertex[i];
return face.mNumVertices;
}
// Register shape functions with the registry
static void sRegister();
#ifdef JPH_DEBUG_RENDERER
/// Draw the outlines of the faces of the convex hull when drawing the shape
inline static bool sDrawFaceOutlines = false;
#endif // JPH_DEBUG_RENDERER
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
/// Helper function that returns the min and max fraction along the ray that hits the convex hull. Returns false if there is no hit.
bool CastRayHelper(const RayCast &inRay, float &outMinFraction, float &outMaxFraction) const;
/// Class for GetTrianglesStart/Next
class CHSGetTrianglesContext;
/// Classes for GetSupportFunction
class HullNoConvex;
class HullWithConvex;
class HullWithConvexScaled;
struct Face
{
uint16 mFirstVertex; ///< First index in mVertexIdx to use
uint16 mNumVertices = 0; ///< Number of vertices in the mVertexIdx to use
};
static_assert(sizeof(Face) == 4, "Unexpected size");
static_assert(alignof(Face) == 2, "Unexpected alignment");
struct Point
{
Vec3 mPosition; ///< Position of vertex
int mNumFaces = 0; ///< Number of faces in the face array below
int mFaces[3] = { -1, -1, -1 }; ///< Indices of 3 neighboring faces with the biggest difference in normal (used to shift vertices for convex radius)
};
static_assert(sizeof(Point) == 32, "Unexpected size");
static_assert(alignof(Point) == JPH_VECTOR_ALIGNMENT, "Unexpected alignment");
Vec3 mCenterOfMass; ///< Center of mass of this convex hull
Mat44 mInertia; ///< Inertia matrix assuming density is 1 (needs to be multiplied by density)
AABox mLocalBounds; ///< Local bounding box for the convex hull
Array<Point> mPoints; ///< Points on the convex hull surface
Array<Face> mFaces; ///< Faces of the convex hull surface
Array<Plane> mPlanes; ///< Planes for the faces (1-on-1 with mFaces array, separate because they need to be 16 byte aligned)
Array<uint8> mVertexIdx; ///< A list of vertex indices (indexing in mPoints) for each of the faces
float mConvexRadius = 0.0f; ///< Convex radius
float mVolume; ///< Total volume of the convex hull
float mInnerRadius = FLT_MAX; ///< Radius of the biggest sphere that fits entirely in the convex hull
#ifdef JPH_DEBUG_RENDERER
mutable DebugRenderer::GeometryRef mGeometry;
#endif // JPH_DEBUG_RENDERER
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/ScaleHelpers.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/PhysicsSettings.h>
JPH_NAMESPACE_BEGIN
/// Helper functions to get properties of a scaling vector
namespace ScaleHelpers
{
/// The tolerance used to check if components of the scale vector are the same
static constexpr float cScaleToleranceSq = 1.0e-8f;
/// Test if a scale is identity
inline bool IsNotScaled(Vec3Arg inScale) { return inScale.IsClose(Vec3::sReplicate(1.0f), cScaleToleranceSq); }
/// Test if a scale is uniform
inline bool IsUniformScale(Vec3Arg inScale) { return inScale.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>().IsClose(inScale, cScaleToleranceSq); }
/// Scale the convex radius of an object
inline float ScaleConvexRadius(float inConvexRadius, Vec3Arg inScale) { return min(inConvexRadius * inScale.Abs().ReduceMin(), cDefaultConvexRadius); }
/// Test if a scale flips an object inside out (which requires flipping all normals and polygon windings)
inline bool IsInsideOut(Vec3Arg inScale) { return (CountBits(Vec3::sLess(inScale, Vec3::sZero()).GetTrues() & 0x7) & 1) != 0; }
/// Get the average scale if inScale, used to make the scale uniform when a shape doesn't support non-uniform scale
inline Vec3 MakeUniformScale(Vec3Arg inScale) { return Vec3::sReplicate((inScale.GetX() + inScale.GetY() + inScale.GetZ()) / 3.0f); }
/// Checks in scale can be rotated to child shape
/// @param inRotation Rotation of child shape
/// @param inScale Scale in local space of parent shape
/// @return True if the scale is valid (no shearing introduced)
inline bool CanScaleBeRotated(QuatArg inRotation, Vec3Arg inScale)
{
// inScale is a scale in local space of the shape, so the transform for the shape (ignoring translation) is: T = Mat44::sScale(inScale) * mRotation.
// when we pass the scale to the child it needs to be local to the child, so we want T = mRotation * Mat44::sScale(ChildScale).
// Solving for ChildScale: ChildScale = mRotation^-1 * Mat44::sScale(inScale) * mRotation = mRotation^T * Mat44::sScale(inScale) * mRotation
// If any of the off diagonal elements are non-zero, it means the scale / rotation is not compatible.
Mat44 r = Mat44::sRotation(inRotation);
Mat44 child_scale = r.Multiply3x3LeftTransposed(r.PostScaled(inScale));
// Get the columns, but zero the diagonal
Vec4 zero = Vec4::sZero();
Vec4 c0 = Vec4::sSelect(child_scale.GetColumn4(0), zero, UVec4(0xffffffff, 0, 0, 0)).Abs();
Vec4 c1 = Vec4::sSelect(child_scale.GetColumn4(1), zero, UVec4(0, 0xffffffff, 0, 0)).Abs();
Vec4 c2 = Vec4::sSelect(child_scale.GetColumn4(2), zero, UVec4(0, 0, 0xffffffff, 0)).Abs();
// Check if all elements are less than epsilon
Vec4 epsilon = Vec4::sReplicate(1.0e-6f);
return UVec4::sAnd(UVec4::sAnd(Vec4::sLess(c0, epsilon), Vec4::sLess(c1, epsilon)), Vec4::sLess(c2, epsilon)).TestAllTrue();
}
/// Adjust scale for rotated child shape
/// @param inRotation Rotation of child shape
/// @param inScale Scale in local space of parent shape
/// @return Rotated scale
inline Vec3 RotateScale(QuatArg inRotation, Vec3Arg inScale)
{
// Get the diagonal of mRotation^T * Mat44::sScale(inScale) * mRotation (see comment at CanScaleBeRotated)
Mat44 r = Mat44::sRotation(inRotation);
return r.Multiply3x3LeftTransposed(r.PostScaled(inScale)).GetDiagonal3();
}
}
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/SubShapeIDPair.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Body/BodyID.h>
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
#include <Jolt/Core/HashCombine.h>
JPH_NAMESPACE_BEGIN
/// A pair of bodies and their sub shape ID's. Can be used as a key in a map to find a contact point.
class SubShapeIDPair
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
SubShapeIDPair() = default;
SubShapeIDPair(const BodyID &inBody1ID, const SubShapeID &inSubShapeID1, const BodyID &inBody2ID, const SubShapeID &inSubShapeID2) : mBody1ID(inBody1ID), mSubShapeID1(inSubShapeID1), mBody2ID(inBody2ID), mSubShapeID2(inSubShapeID2) { }
SubShapeIDPair(const SubShapeIDPair &) = default;
/// Equality operator
inline bool operator == (const SubShapeIDPair &inRHS) const
{
return UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(this)) == UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(&inRHS));
}
/// Less than operator, used to consistently order contact points for a deterministic simulation
inline bool operator < (const SubShapeIDPair &inRHS) const
{
if (mBody1ID != inRHS.mBody1ID)
return mBody1ID < inRHS.mBody1ID;
if (mSubShapeID1.GetValue() != inRHS.mSubShapeID1.GetValue())
return mSubShapeID1.GetValue() < inRHS.mSubShapeID1.GetValue();
if (mBody2ID != inRHS.mBody2ID)
return mBody2ID < inRHS.mBody2ID;
return mSubShapeID2.GetValue() < inRHS.mSubShapeID2.GetValue();
}
const BodyID & GetBody1ID() const { return mBody1ID; }
const SubShapeID & GetSubShapeID1() const { return mSubShapeID1; }
const BodyID & GetBody2ID() const { return mBody2ID; }
const SubShapeID & GetSubShapeID2() const { return mSubShapeID2; }
uint64 GetHash() const { return HashBytes(this, sizeof(SubShapeIDPair)); }
private:
BodyID mBody1ID;
SubShapeID mSubShapeID1;
BodyID mBody2ID;
SubShapeID mSubShapeID2;
};
static_assert(sizeof(SubShapeIDPair) == 16, "Unexpected size");
static_assert(alignof(SubShapeIDPair) == 4, "Assuming 4 byte aligned");
JPH_NAMESPACE_END
JPH_SUPPRESS_WARNINGS_STD_BEGIN
namespace std
{
/// Declare std::hash for SubShapeIDPair, note that std::hash is platform dependent and we need this one to be consistent because we sort on it in the ContactConstraintManager
template <>
struct hash<JPH::SubShapeIDPair>
{
inline size_t operator () (const JPH::SubShapeIDPair &inRHS) const
{
return static_cast<size_t>(inRHS.GetHash());
}
};
}
JPH_SUPPRESS_WARNINGS_STD_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/PolyhedronSubmergedVolumeCalculator.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Geometry/Plane.h>
#ifdef JPH_DEBUG_RENDERER
#include <Jolt/Renderer/DebugRenderer.h>
#endif // JPH_DEBUG_RENDERER
JPH_NAMESPACE_BEGIN
/// This class calculates the intersection between a fluid surface and a polyhedron and returns the submerged volume and its center of buoyancy
/// Construct this class and then one by one add all faces of the polyhedron using the AddFace function. After all faces have been added the result
/// can be gotten through GetResult.
class PolyhedronSubmergedVolumeCalculator
{
private:
// Calculate submerged volume * 6 and center of mass * 4 for a tetrahedron with 4 vertices submerged
// inV1 .. inV4 are submerged
inline static void sTetrahedronVolume4(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, Vec3Arg inV4, float &outVolumeTimes6, Vec3 &outCenterTimes4)
{
// Calculate center of mass and mass of this tetrahedron,
// see: https://en.wikipedia.org/wiki/Tetrahedron#Volume
outVolumeTimes6 = max((inV1 - inV4).Dot((inV2 - inV4).Cross(inV3 - inV4)), 0.0f); // All contributions should be positive because we use a reference point that is on the surface of the hull
outCenterTimes4 = inV1 + inV2 + inV3 + inV4;
}
// Get the intersection point with a plane.
// inV1 is inD1 distance away from the plane, inV2 is inD2 distance away from the plane
inline static Vec3 sGetPlaneIntersection(Vec3Arg inV1, float inD1, Vec3Arg inV2, float inD2)
{
JPH_ASSERT(Sign(inD1) != Sign(inD2), "Assuming both points are on opposite ends of the plane");
float delta = inD1 - inD2;
if (abs(delta) < 1.0e-6f)
return inV1; // Parallel to plane, just pick a point
else
return inV1 + inD1 * (inV2 - inV1) / delta;
}
// Calculate submerged volume * 6 and center of mass * 4 for a tetrahedron with 1 vertex submerged
// inV1 is submerged, inV2 .. inV4 are not
// inD1 .. inD4 are the distances from the points to the plane
inline JPH_IF_NOT_DEBUG_RENDERER(static) void sTetrahedronVolume1(Vec3Arg inV1, float inD1, Vec3Arg inV2, float inD2, Vec3Arg inV3, float inD3, Vec3Arg inV4, float inD4, float &outVolumeTimes6, Vec3 &outCenterTimes4)
{
// A tetrahedron with 1 point submerged is cut along 3 edges forming a new tetrahedron
Vec3 v2 = sGetPlaneIntersection(inV1, inD1, inV2, inD2);
Vec3 v3 = sGetPlaneIntersection(inV1, inD1, inV3, inD3);
Vec3 v4 = sGetPlaneIntersection(inV1, inD1, inV4, inD4);
#ifdef JPH_DEBUG_RENDERER
// Draw intersection between tetrahedron and surface
if (Shape::sDrawSubmergedVolumes)
{
RVec3 v2w = mBaseOffset + v2;
RVec3 v3w = mBaseOffset + v3;
RVec3 v4w = mBaseOffset + v4;
DebugRenderer::sInstance->DrawTriangle(v4w, v3w, v2w, Color::sGreen);
DebugRenderer::sInstance->DrawWireTriangle(v4w, v3w, v2w, Color::sWhite);
}
#endif // JPH_DEBUG_RENDERER
sTetrahedronVolume4(inV1, v2, v3, v4, outVolumeTimes6, outCenterTimes4);
}
// Calculate submerged volume * 6 and center of mass * 4 for a tetrahedron with 2 vertices submerged
// inV1, inV2 are submerged, inV3, inV4 are not
// inD1 .. inD4 are the distances from the points to the plane
inline JPH_IF_NOT_DEBUG_RENDERER(static) void sTetrahedronVolume2(Vec3Arg inV1, float inD1, Vec3Arg inV2, float inD2, Vec3Arg inV3, float inD3, Vec3Arg inV4, float inD4, float &outVolumeTimes6, Vec3 &outCenterTimes4)
{
// A tetrahedron with 2 points submerged is cut along 4 edges forming a quad
Vec3 c = sGetPlaneIntersection(inV1, inD1, inV3, inD3);
Vec3 d = sGetPlaneIntersection(inV1, inD1, inV4, inD4);
Vec3 e = sGetPlaneIntersection(inV2, inD2, inV4, inD4);
Vec3 f = sGetPlaneIntersection(inV2, inD2, inV3, inD3);
#ifdef JPH_DEBUG_RENDERER
// Draw intersection between tetrahedron and surface
if (Shape::sDrawSubmergedVolumes)
{
RVec3 cw = mBaseOffset + c;
RVec3 dw = mBaseOffset + d;
RVec3 ew = mBaseOffset + e;
RVec3 fw = mBaseOffset + f;
DebugRenderer::sInstance->DrawTriangle(cw, ew, dw, Color::sGreen);
DebugRenderer::sInstance->DrawTriangle(cw, fw, ew, Color::sGreen);
DebugRenderer::sInstance->DrawWireTriangle(cw, ew, dw, Color::sWhite);
DebugRenderer::sInstance->DrawWireTriangle(cw, fw, ew, Color::sWhite);
}
#endif // JPH_DEBUG_RENDERER
// We pick point c as reference (which is on the cut off surface)
// This leaves us with three tetrahedrons to sum up (any faces that are in the same plane as c will have zero volume)
Vec3 center1, center2, center3;
float volume1, volume2, volume3;
sTetrahedronVolume4(e, f, inV2, c, volume1, center1);
sTetrahedronVolume4(e, inV1, d, c, volume2, center2);
sTetrahedronVolume4(e, inV2, inV1, c, volume3, center3);
// Tally up the totals
outVolumeTimes6 = volume1 + volume2 + volume3;
outCenterTimes4 = outVolumeTimes6 > 0.0f? (volume1 * center1 + volume2 * center2 + volume3 * center3) / outVolumeTimes6 : Vec3::sZero();
}
// Calculate submerged volume * 6 and center of mass * 4 for a tetrahedron with 3 vertices submerged
// inV1, inV2, inV3 are submerged, inV4 is not
// inD1 .. inD4 are the distances from the points to the plane
inline JPH_IF_NOT_DEBUG_RENDERER(static) void sTetrahedronVolume3(Vec3Arg inV1, float inD1, Vec3Arg inV2, float inD2, Vec3Arg inV3, float inD3, Vec3Arg inV4, float inD4, float &outVolumeTimes6, Vec3 &outCenterTimes4)
{
// A tetrahedron with 1 point above the surface is cut along 3 edges forming a new tetrahedron
Vec3 v1 = sGetPlaneIntersection(inV1, inD1, inV4, inD4);
Vec3 v2 = sGetPlaneIntersection(inV2, inD2, inV4, inD4);
Vec3 v3 = sGetPlaneIntersection(inV3, inD3, inV4, inD4);
#ifdef JPH_DEBUG_RENDERER
// Draw intersection between tetrahedron and surface
if (Shape::sDrawSubmergedVolumes)
{
RVec3 v1w = mBaseOffset + v1;
RVec3 v2w = mBaseOffset + v2;
RVec3 v3w = mBaseOffset + v3;
DebugRenderer::sInstance->DrawTriangle(v3w, v2w, v1w, Color::sGreen);
DebugRenderer::sInstance->DrawWireTriangle(v3w, v2w, v1w, Color::sWhite);
}
#endif // JPH_DEBUG_RENDERER
Vec3 dry_center, total_center;
float dry_volume, total_volume;
// We first calculate the part that is above the surface
sTetrahedronVolume4(v1, v2, v3, inV4, dry_volume, dry_center);
// Calculate the total volume
sTetrahedronVolume4(inV1, inV2, inV3, inV4, total_volume, total_center);
// From this we can calculate the center and volume of the submerged part
outVolumeTimes6 = max(total_volume - dry_volume, 0.0f);
outCenterTimes4 = outVolumeTimes6 > 0.0f? (total_center * total_volume - dry_center * dry_volume) / outVolumeTimes6 : Vec3::sZero();
}
public:
/// A helper class that contains cached information about a polyhedron vertex
class Point
{
public:
Vec3 mPosition; ///< World space position of vertex
float mDistanceToSurface; ///< Signed distance to the surface (> 0 is above, < 0 is below)
bool mAboveSurface; ///< If the point is above the surface (mDistanceToSurface > 0)
};
/// Constructor
/// @param inTransform Transform to transform all incoming points with
/// @param inPoints Array of points that are part of the polyhedron
/// @param inPointStride Amount of bytes between each point (should usually be sizeof(Vec3))
/// @param inNumPoints The amount of points
/// @param inSurface The plane that forms the fluid surface (normal should point up)
/// @param ioBuffer A temporary buffer of Point's that should have inNumPoints entries and should stay alive while this class is alive
#ifdef JPH_DEBUG_RENDERER
/// @param inBaseOffset The offset to transform inTransform to world space (in double precision mode this can be used to shift the whole operation closer to the origin). Only used for debug drawing.
#endif // JPH_DEBUG_RENDERER
PolyhedronSubmergedVolumeCalculator(const Mat44 &inTransform, const Vec3 *inPoints, int inPointStride, int inNumPoints, const Plane &inSurface, Point *ioBuffer
#ifdef JPH_DEBUG_RENDERER // Not using JPH_IF_DEBUG_RENDERER for Doxygen
, RVec3 inBaseOffset
#endif // JPH_DEBUG_RENDERER
) :
mPoints(ioBuffer)
#ifdef JPH_DEBUG_RENDERER
, mBaseOffset(inBaseOffset)
#endif // JPH_DEBUG_RENDERER
{
// Convert the points to world space and determine the distance to the surface
float reference_dist = FLT_MAX;
for (int p = 0; p < inNumPoints; ++p)
{
// Calculate values
Vec3 transformed_point = inTransform * *reinterpret_cast<const Vec3 *>(reinterpret_cast<const uint8 *>(inPoints) + p * inPointStride);
float dist = inSurface.SignedDistance(transformed_point);
bool above = dist >= 0.0f;
// Keep track if all are above or below
mAllAbove &= above;
mAllBelow &= !above;
// Calculate lowest point, we use this to create tetrahedrons out of all faces
if (reference_dist > dist)
{
mReferencePointIdx = p;
reference_dist = dist;
}
// Store values
ioBuffer->mPosition = transformed_point;
ioBuffer->mDistanceToSurface = dist;
ioBuffer->mAboveSurface = above;
++ioBuffer;
}
}
/// Check if all points are above the surface. Should be used as early out.
inline bool AreAllAbove() const
{
return mAllAbove;
}
/// Check if all points are below the surface. Should be used as early out.
inline bool AreAllBelow() const
{
return mAllBelow;
}
/// Get the lowest point of the polyhedron. Used to form the 4th vertex to make a tetrahedron out of a polyhedron face.
inline int GetReferencePointIdx() const
{
return mReferencePointIdx;
}
/// Add a polyhedron face. Supply the indices of the points that form the face (in counter clockwise order).
void AddFace(int inIdx1, int inIdx2, int inIdx3)
{
JPH_ASSERT(inIdx1 != mReferencePointIdx && inIdx2 != mReferencePointIdx && inIdx3 != mReferencePointIdx, "A face using the reference point will not contribute to the volume");
// Find the points
const Point &ref = mPoints[mReferencePointIdx];
const Point &p1 = mPoints[inIdx1];
const Point &p2 = mPoints[inIdx2];
const Point &p3 = mPoints[inIdx3];
// Determine which vertices are submerged
uint code = (p1.mAboveSurface? 0 : 0b001) | (p2.mAboveSurface? 0 : 0b010) | (p3.mAboveSurface? 0 : 0b100);
float volume;
Vec3 center;
switch (code)
{
case 0b000:
// One point submerged
sTetrahedronVolume1(ref.mPosition, ref.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, volume, center);
break;
case 0b001:
// Two points submerged
sTetrahedronVolume2(ref.mPosition, ref.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, volume, center);
break;
case 0b010:
// Two points submerged
sTetrahedronVolume2(ref.mPosition, ref.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, volume, center);
break;
case 0b100:
// Two points submerged
sTetrahedronVolume2(ref.mPosition, ref.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, volume, center);
break;
case 0b011:
// Three points submerged
sTetrahedronVolume3(ref.mPosition, ref.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, volume, center);
break;
case 0b101:
// Three points submerged
sTetrahedronVolume3(ref.mPosition, ref.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, volume, center);
break;
case 0b110:
// Three points submerged
sTetrahedronVolume3(ref.mPosition, ref.mDistanceToSurface, p3.mPosition, p3.mDistanceToSurface, p2.mPosition, p2.mDistanceToSurface, p1.mPosition, p1.mDistanceToSurface, volume, center);
break;
case 0b111:
// Four points submerged
sTetrahedronVolume4(ref.mPosition, p3.mPosition, p2.mPosition, p1.mPosition, volume, center);
break;
default:
// Should not be possible
JPH_ASSERT(false);
volume = 0.0f;
center = Vec3::sZero();
break;
}
mSubmergedVolume += volume;
mCenterOfBuoyancy += volume * center;
}
/// Call after all faces have been added. Returns the submerged volume and the center of buoyancy for the submerged volume.
void GetResult(float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy) const
{
outCenterOfBuoyancy = mSubmergedVolume > 0.0f? mCenterOfBuoyancy / (4.0f * mSubmergedVolume) : Vec3::sZero(); // Do this before dividing submerged volume by 6 to get correct weight factor
outSubmergedVolume = mSubmergedVolume / 6.0f;
}
private:
// The precalculated points for this polyhedron
const Point * mPoints;
// If all points are above/below the surface
bool mAllBelow = true;
bool mAllAbove = true;
// The lowest point
int mReferencePointIdx = 0;
// Aggregator for submerged volume and center of buoyancy
float mSubmergedVolume = 0.0f;
Vec3 mCenterOfBuoyancy = Vec3::sZero();
#ifdef JPH_DEBUG_RENDERER
// Base offset used for drawing
RVec3 mBaseOffset;
#endif
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/CylinderShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#include <Jolt/Physics/PhysicsSettings.h>
JPH_NAMESPACE_BEGIN
/// Class that constructs a CylinderShape
class CylinderShapeSettings final : public ConvexShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(CylinderShapeSettings)
/// Default constructor for deserialization
CylinderShapeSettings() = default;
/// Create a shape centered around the origin with one top at (0, -inHalfHeight, 0) and the other at (0, inHalfHeight, 0) and radius inRadius.
/// (internally the convex radius will be subtracted from the cylinder the total cylinder will not grow with the convex radius, but the edges of the cylinder will be rounded a bit).
CylinderShapeSettings(float inHalfHeight, float inRadius, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShapeSettings(inMaterial), mHalfHeight(inHalfHeight), mRadius(inRadius), mConvexRadius(inConvexRadius) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
float mHalfHeight = 0.0f;
float mRadius = 0.0f;
float mConvexRadius = 0.0f;
};
/// A cylinder
class CylinderShape final : public ConvexShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
CylinderShape() : ConvexShape(EShapeSubType::Cylinder) { }
CylinderShape(const CylinderShapeSettings &inSettings, ShapeResult &outResult);
/// Create a shape centered around the origin with one top at (0, -inHalfHeight, 0) and the other at (0, inHalfHeight, 0) and radius inRadius.
/// (internally the convex radius will be subtracted from the cylinder the total cylinder will not grow with the convex radius, but the edges of the cylinder will be rounded a bit).
CylinderShape(float inHalfHeight, float inRadius, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr);
/// Get half height of cylinder
float GetHalfHeight() const { return mHalfHeight; }
/// Get radius of cylinder
float GetRadius() const { return mRadius; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return min(mHalfHeight, mRadius); }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See ConvexShape::GetSupportFunction
virtual const Support * GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
using ConvexShape::CastRay;
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 0); }
// See Shape::GetVolume
virtual float GetVolume() const override { return 2.0f * JPH_PI * mHalfHeight * Square(mRadius); }
/// Get the convex radius of this cylinder
float GetConvexRadius() const { return mConvexRadius; }
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override;
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Class for GetSupportFunction
class Cylinder;
float mHalfHeight = 0.0f;
float mRadius = 0.0f;
float mConvexRadius = 0.0f;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/GetTrianglesContext.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/Shape.h>
JPH_NAMESPACE_BEGIN
class PhysicsMaterial;
/// Implementation of GetTrianglesStart/Next that uses a fixed list of vertices for the triangles. These are transformed into world space when getting the triangles.
class GetTrianglesContextVertexList
{
public:
/// Constructor, to be called in GetTrianglesStart
GetTrianglesContextVertexList(Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, Mat44Arg inLocalTransform, const Vec3 *inTriangleVertices, size_t inNumTriangleVertices, const PhysicsMaterial *inMaterial) :
mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale) * inLocalTransform),
mTriangleVertices(inTriangleVertices),
mNumTriangleVertices(inNumTriangleVertices),
mMaterial(inMaterial),
mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
{
static_assert(sizeof(GetTrianglesContextVertexList) <= sizeof(Shape::GetTrianglesContext), "GetTrianglesContext too small");
JPH_ASSERT(IsAligned(this, alignof(GetTrianglesContextVertexList)));
JPH_ASSERT(inNumTriangleVertices % 3 == 0);
}
/// @see Shape::GetTrianglesNext
int GetTrianglesNext(int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials)
{
JPH_ASSERT(inMaxTrianglesRequested >= Shape::cGetTrianglesMinTrianglesRequested);
int total_num_vertices = min(inMaxTrianglesRequested * 3, int(mNumTriangleVertices - mCurrentVertex));
if (mIsInsideOut)
{
// Store triangles flipped
for (const Vec3 *v = mTriangleVertices + mCurrentVertex, *v_end = v + total_num_vertices; v < v_end; v += 3)
{
(mLocalToWorld * v[0]).StoreFloat3(outTriangleVertices++);
(mLocalToWorld * v[2]).StoreFloat3(outTriangleVertices++);
(mLocalToWorld * v[1]).StoreFloat3(outTriangleVertices++);
}
}
else
{
// Store triangles
for (const Vec3 *v = mTriangleVertices + mCurrentVertex, *v_end = v + total_num_vertices; v < v_end; v += 3)
{
(mLocalToWorld * v[0]).StoreFloat3(outTriangleVertices++);
(mLocalToWorld * v[1]).StoreFloat3(outTriangleVertices++);
(mLocalToWorld * v[2]).StoreFloat3(outTriangleVertices++);
}
}
// Update the current vertex to point to the next vertex to get
mCurrentVertex += total_num_vertices;
int total_num_triangles = total_num_vertices / 3;
// Store materials
if (outMaterials != nullptr)
for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
*m = mMaterial;
return total_num_triangles;
}
/// Helper function that creates a vertex list of a half unit sphere (top part)
static void sCreateHalfUnitSphereTop(std::vector<Vec3> &ioVertices, int inDetailLevel)
{
sCreateUnitSphereHelper(ioVertices, Vec3::sAxisX(), Vec3::sAxisY(), Vec3::sAxisZ(), inDetailLevel);
sCreateUnitSphereHelper(ioVertices, Vec3::sAxisY(), -Vec3::sAxisX(), Vec3::sAxisZ(), inDetailLevel);
sCreateUnitSphereHelper(ioVertices, Vec3::sAxisY(), Vec3::sAxisX(), -Vec3::sAxisZ(), inDetailLevel);
sCreateUnitSphereHelper(ioVertices, -Vec3::sAxisX(), Vec3::sAxisY(), -Vec3::sAxisZ(), inDetailLevel);
}
/// Helper function that creates a vertex list of a half unit sphere (bottom part)
static void sCreateHalfUnitSphereBottom(std::vector<Vec3> &ioVertices, int inDetailLevel)
{
sCreateUnitSphereHelper(ioVertices, -Vec3::sAxisX(), -Vec3::sAxisY(), Vec3::sAxisZ(), inDetailLevel);
sCreateUnitSphereHelper(ioVertices, -Vec3::sAxisY(), Vec3::sAxisX(), Vec3::sAxisZ(), inDetailLevel);
sCreateUnitSphereHelper(ioVertices, Vec3::sAxisX(), -Vec3::sAxisY(), -Vec3::sAxisZ(), inDetailLevel);
sCreateUnitSphereHelper(ioVertices, -Vec3::sAxisY(), -Vec3::sAxisX(), -Vec3::sAxisZ(), inDetailLevel);
}
/// Helper function that creates an open cyclinder of half height 1 and radius 1
static void sCreateUnitOpenCylinder(std::vector<Vec3> &ioVertices, int inDetailLevel)
{
const Vec3 bottom_offset(0.0f, -2.0f, 0.0f);
int num_verts = 4 * (1 << inDetailLevel);
for (int i = 0; i < num_verts; ++i)
{
float angle1 = 2.0f * JPH_PI * (float(i) / num_verts);
float angle2 = 2.0f * JPH_PI * (float(i + 1) / num_verts);
Vec3 t1(Sin(angle1), 1.0f, Cos(angle1));
Vec3 t2(Sin(angle2), 1.0f, Cos(angle2));
Vec3 b1 = t1 + bottom_offset;
Vec3 b2 = t2 + bottom_offset;
ioVertices.push_back(t1);
ioVertices.push_back(b1);
ioVertices.push_back(t2);
ioVertices.push_back(t2);
ioVertices.push_back(b1);
ioVertices.push_back(b2);
}
}
private:
/// Recursive helper function for creating a sphere
static void sCreateUnitSphereHelper(std::vector<Vec3> &ioVertices, Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, int inLevel)
{
Vec3 center1 = (inV1 + inV2).Normalized();
Vec3 center2 = (inV2 + inV3).Normalized();
Vec3 center3 = (inV3 + inV1).Normalized();
if (inLevel > 0)
{
int new_level = inLevel - 1;
sCreateUnitSphereHelper(ioVertices, inV1, center1, center3, new_level);
sCreateUnitSphereHelper(ioVertices, center1, center2, center3, new_level);
sCreateUnitSphereHelper(ioVertices, center1, inV2, center2, new_level);
sCreateUnitSphereHelper(ioVertices, center3, center2, inV3, new_level);
}
else
{
ioVertices.push_back(inV1);
ioVertices.push_back(inV2);
ioVertices.push_back(inV3);
}
}
Mat44 mLocalToWorld;
const Vec3 * mTriangleVertices;
size_t mNumTriangleVertices;
size_t mCurrentVertex = 0;
const PhysicsMaterial * mMaterial;
bool mIsInsideOut;
};
/// Implementation of GetTrianglesStart/Next that uses a multiple fixed lists of vertices for the triangles. These are transformed into world space when getting the triangles.
class GetTrianglesContextMultiVertexList
{
public:
/// Constructor, to be called in GetTrianglesStart
GetTrianglesContextMultiVertexList(bool inIsInsideOut, const PhysicsMaterial *inMaterial) :
mMaterial(inMaterial),
mIsInsideOut(inIsInsideOut)
{
static_assert(sizeof(GetTrianglesContextMultiVertexList) <= sizeof(Shape::GetTrianglesContext), "GetTrianglesContext too small");
JPH_ASSERT(IsAligned(this, alignof(GetTrianglesContextMultiVertexList)));
}
/// Add a mesh part and its transform
void AddPart(Mat44Arg inLocalToWorld, const Vec3 *inTriangleVertices, size_t inNumTriangleVertices)
{
JPH_ASSERT(inNumTriangleVertices % 3 == 0);
mParts.push_back({ inLocalToWorld, inTriangleVertices, inNumTriangleVertices });
}
/// @see Shape::GetTrianglesNext
int GetTrianglesNext(int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials)
{
JPH_ASSERT(inMaxTrianglesRequested >= Shape::cGetTrianglesMinTrianglesRequested);
int total_num_vertices = 0;
int max_vertices_requested = inMaxTrianglesRequested * 3;
// Loop over parts
for (; mCurrentPart < mParts.size(); ++mCurrentPart)
{
const Part &part = mParts[mCurrentPart];
// Calculate how many vertices to take from this part
int part_num_vertices = min(max_vertices_requested, int(part.mNumTriangleVertices - mCurrentVertex));
if (part_num_vertices == 0)
break;
max_vertices_requested -= part_num_vertices;
total_num_vertices += part_num_vertices;
if (mIsInsideOut)
{
// Store triangles flipped
for (const Vec3 *v = part.mTriangleVertices + mCurrentVertex, *v_end = v + part_num_vertices; v < v_end; v += 3)
{
(part.mLocalToWorld * v[0]).StoreFloat3(outTriangleVertices++);
(part.mLocalToWorld * v[2]).StoreFloat3(outTriangleVertices++);
(part.mLocalToWorld * v[1]).StoreFloat3(outTriangleVertices++);
}
}
else
{
// Store triangles
for (const Vec3 *v = part.mTriangleVertices + mCurrentVertex, *v_end = v + part_num_vertices; v < v_end; v += 3)
{
(part.mLocalToWorld * v[0]).StoreFloat3(outTriangleVertices++);
(part.mLocalToWorld * v[1]).StoreFloat3(outTriangleVertices++);
(part.mLocalToWorld * v[2]).StoreFloat3(outTriangleVertices++);
}
}
// Update the current vertex to point to the next vertex to get
mCurrentVertex += part_num_vertices;
// Check if we completed this part
if (mCurrentVertex < part.mNumTriangleVertices)
break;
// Reset current vertex for the next part
mCurrentVertex = 0;
}
int total_num_triangles = total_num_vertices / 3;
// Store materials
if (outMaterials != nullptr)
for (const PhysicsMaterial **m = outMaterials, **m_end = outMaterials + total_num_triangles; m < m_end; ++m)
*m = mMaterial;
return total_num_triangles;
}
private:
struct Part
{
Mat44 mLocalToWorld;
const Vec3 * mTriangleVertices;
size_t mNumTriangleVertices;
};
StaticArray<Part, 3> mParts;
uint mCurrentPart = 0;
size_t mCurrentVertex = 0;
const PhysicsMaterial * mMaterial;
bool mIsInsideOut;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/OffsetCenterOfMassShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/DecoratedShape.h>
JPH_NAMESPACE_BEGIN
class CollideShapeSettings;
/// Class that constructs an OffsetCenterOfMassShape
class OffsetCenterOfMassShapeSettings final : public DecoratedShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(OffsetCenterOfMassShapeSettings)
/// Constructor
OffsetCenterOfMassShapeSettings() = default;
/// Construct with shape settings, can be serialized.
OffsetCenterOfMassShapeSettings(Vec3Arg inOffset, const ShapeSettings *inShape) : DecoratedShapeSettings(inShape), mOffset(inOffset) { }
/// Variant that uses a concrete shape, which means this object cannot be serialized.
OffsetCenterOfMassShapeSettings(Vec3Arg inOffset, const Shape *inShape): DecoratedShapeSettings(inShape), mOffset(inOffset) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
Vec3 mOffset; ///< Offset to be applied to the center of mass of the child shape
};
/// This shape will shift the center of mass of a child shape, it can e.g. be used to lower the center of mass of an unstable object like a boat to make it stable
class OffsetCenterOfMassShape final : public DecoratedShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
OffsetCenterOfMassShape() : DecoratedShape(EShapeSubType::OffsetCenterOfMass) { }
OffsetCenterOfMassShape(const OffsetCenterOfMassShapeSettings &inSettings, ShapeResult &outResult);
/// Access the offset that is applied to the center of mass
Vec3 GetOffset() const { return mOffset; }
// See Shape::GetCenterOfMass
virtual Vec3 GetCenterOfMass() const override { return mInnerShape->GetCenterOfMass() + mOffset; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetWorldSpaceBounds
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
using Shape::GetWorldSpaceBounds;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return mInnerShape->GetInnerRadius(); }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override
{
MassProperties mp = mInnerShape->GetMassProperties();
mp.Translate(mOffset);
return mp;
}
// See Shape::GetSubShapeTransformedShape
virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See Shape::GetSubmergedVolume
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
// See Shape::DrawGetSupportFunction
virtual void DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const override;
// See Shape::DrawGetSupportingFace
virtual void DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::CollectTransformedShapes
virtual void CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const override;
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); }
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); return 0; }
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 0); }
// See Shape::GetVolume
virtual float GetVolume() const override { return mInnerShape->GetVolume(); }
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override { return mInnerShape->IsValidScale(inScale); }
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Helper functions called by CollisionDispatch
static void sCollideOffsetCenterOfMassVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCollideShapeVsOffsetCenterOfMass(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCastOffsetCenterOfMassVsShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
static void sCastShapeVsOffsetCenterOfMass(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
Vec3 mOffset; ///< Offset of the center of mass
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/DecoratedShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/Shape.h>
JPH_NAMESPACE_BEGIN
/// Class that constructs a DecoratedShape
class DecoratedShapeSettings : public ShapeSettings
{
JPH_DECLARE_SERIALIZABLE_VIRTUAL(DecoratedShapeSettings)
/// Default constructor for deserialization
DecoratedShapeSettings() = default;
/// Constructor that decorates another shape
explicit DecoratedShapeSettings(const ShapeSettings *inShape) : mInnerShape(inShape) { }
explicit DecoratedShapeSettings(const Shape *inShape) : mInnerShapePtr(inShape) { }
RefConst<ShapeSettings> mInnerShape; ///< Sub shape (either this or mShapePtr needs to be filled up)
RefConst<Shape> mInnerShapePtr; ///< Sub shape (either this or mShape needs to be filled up)
};
/// Base class for shapes that decorate another shape with extra functionality (e.g. scale, translation etc.)
class DecoratedShape : public Shape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
explicit DecoratedShape(EShapeSubType inSubType) : Shape(EShapeType::Decorated, inSubType) { }
DecoratedShape(EShapeSubType inSubType, const Shape *inInnerShape) : Shape(EShapeType::Decorated, inSubType), mInnerShape(inInnerShape) { }
DecoratedShape(EShapeSubType inSubType, const DecoratedShapeSettings &inSettings, ShapeResult &outResult);
/// Access to the decorated inner shape
const Shape * GetInnerShape() const { return mInnerShape; }
// See Shape::MustBeStatic
virtual bool MustBeStatic() const override { return mInnerShape->MustBeStatic(); }
// See Shape::GetCenterOfMass
virtual Vec3 GetCenterOfMass() const override { return mInnerShape->GetCenterOfMass(); }
// See Shape::GetSubShapeIDBitsRecursive
virtual uint GetSubShapeIDBitsRecursive() const override { return mInnerShape->GetSubShapeIDBitsRecursive(); }
// See Shape::GetMaterial
virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See Shape::GetSubShapeUserData
virtual uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const override;
// See Shape
virtual void SaveSubShapeState(ShapeList &outSubShapes) const override;
virtual void RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes) override;
// See Shape::GetStatsRecursive
virtual Stats GetStatsRecursive(VisitedShapes &ioVisitedShapes) const override;
protected:
RefConst<Shape> mInnerShape;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/SphereShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
JPH_NAMESPACE_BEGIN
/// Class that constructs a SphereShape
class SphereShapeSettings final : public ConvexShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(SphereShapeSettings)
/// Default constructor for deserialization
SphereShapeSettings() = default;
/// Create a sphere with radius inRadius
SphereShapeSettings(float inRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShapeSettings(inMaterial), mRadius(inRadius) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
float mRadius = 0.0f;
};
/// A sphere, centered around the origin.
/// Note that it is implemented as a point with convex radius.
class SphereShape final : public ConvexShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
SphereShape() : ConvexShape(EShapeSubType::Sphere) { }
SphereShape(const SphereShapeSettings &inSettings, ShapeResult &outResult);
/// Create a sphere with radius inRadius
SphereShape(float inRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShape(EShapeSubType::Sphere, inMaterial), mRadius(inRadius) { JPH_ASSERT(inRadius > 0.0f); }
/// Radius of the sphere
float GetRadius() const { return mRadius; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetWorldSpaceBounds
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
using Shape::GetWorldSpaceBounds;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return mRadius; }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override { /* Hit is always a single point, no point in returning anything */ }
// See ConvexShape::GetSupportFunction
virtual const Support * GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const override;
// See Shape::GetSubmergedVolume
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 0); }
// See Shape::GetVolume
virtual float GetVolume() const override { return 4.0f / 3.0f * JPH_PI * Cubed(mRadius); }
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override;
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Get the radius of this sphere scaled by inScale
inline float GetScaledRadius(Vec3Arg inScale) const;
// Classes for GetSupportFunction
class SphereNoConvex;
class SphereWithConvex;
float mRadius = 0.0f;
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/ScaledShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/DecoratedShape.h>
JPH_NAMESPACE_BEGIN
class SubShapeIDCreator;
class CollideShapeSettings;
/// Class that constructs a ScaledShape
class ScaledShapeSettings final : public DecoratedShapeSettings
{
JPH_DECLARE_SERIALIZABLE_VIRTUAL(ScaledShapeSettings)
/// Default constructor for deserialization
ScaledShapeSettings() = default;
/// Constructor that decorates another shape with a scale
ScaledShapeSettings(const ShapeSettings *inShape, Vec3Arg inScale) : DecoratedShapeSettings(inShape), mScale(inScale) { }
/// Variant that uses a concrete shape, which means this object cannot be serialized.
ScaledShapeSettings(const Shape *inShape, Vec3Arg inScale) : DecoratedShapeSettings(inShape), mScale(inScale) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
Vec3 mScale = Vec3(1, 1, 1);
};
/// A shape that scales a child shape in local space of that shape. The scale can be non-uniform and can even turn it inside out when one or three components of the scale are negative.
class ScaledShape final : public DecoratedShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
ScaledShape() : DecoratedShape(EShapeSubType::Scaled) { }
ScaledShape(const ScaledShapeSettings &inSettings, ShapeResult &outResult);
/// Constructor that decorates another shape with a scale
ScaledShape(const Shape *inShape, Vec3Arg inScale) : DecoratedShape(EShapeSubType::Scaled, inShape), mScale(inScale) { }
/// Get the scale
Vec3 GetScale() const { return mScale; }
// See Shape::GetCenterOfMass
virtual Vec3 GetCenterOfMass() const override { return mScale * mInnerShape->GetCenterOfMass(); }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetWorldSpaceBounds
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
using Shape::GetWorldSpaceBounds;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return mScale.ReduceMin() * mInnerShape->GetInnerRadius(); }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSubShapeTransformedShape
virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See Shape::GetSubmergedVolume
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
// See Shape::DrawGetSupportFunction
virtual void DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const override;
// See Shape::DrawGetSupportingFace
virtual void DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::CollectTransformedShapes
virtual void CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const override;
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); }
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); return 0; }
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 0); }
// See Shape::GetVolume
virtual float GetVolume() const override;
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override;
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Helper functions called by CollisionDispatch
static void sCollideScaledVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCollideShapeVsScaled(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCastScaledVsShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
static void sCastShapeVsScaled(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
Vec3 mScale = Vec3(1, 1, 1);
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/HeightFieldShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/Shape.h>
#include <Jolt/Physics/Collision/PhysicsMaterial.h>
#ifdef JPH_DEBUG_RENDERER
#include <Jolt/Renderer/DebugRenderer.h>
#endif // JPH_DEBUG_RENDERER
JPH_NAMESPACE_BEGIN
class ConvexShape;
class CollideShapeSettings;
/// Constants for HeightFieldShape, this was moved out of the HeightFieldShape because of a linker bug
namespace HeightFieldShapeConstants
{
/// Value used to create gaps in the height field
constexpr float cNoCollisionValue = FLT_MAX;
/// Stack size to use during WalkHeightField
constexpr int cStackSize = 128;
/// A position in the hierarchical grid is defined by a level (which grid), x and y position. We encode this in a single uint32 as: level << 28 | y << 14 | x
constexpr uint cNumBitsXY = 14;
constexpr uint cMaskBitsXY = (1 << cNumBitsXY) - 1;
constexpr uint cLevelShift = 2 * cNumBitsXY;
/// When height samples are converted to 16 bit:
constexpr uint16 cNoCollisionValue16 = 0xffff; ///< This is the magic value for 'no collision'
constexpr uint16 cMaxHeightValue16 = 0xfffe; ///< This is the maximum allowed height value
};
/// Class that constructs a HeightFieldShape
class HeightFieldShapeSettings final : public ShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(HeightFieldShapeSettings)
/// Default constructor for deserialization
HeightFieldShapeSettings() = default;
/// Create a height field shape of inSampleCount * inSampleCount vertices.
/// The height field is a surface defined by: inOffset + inScale * (x, inSamples[y * inSampleCount + x], y).
/// where x and y are integers in the range x and y e [0, inSampleCount - 1].
/// inSampleCount: inSampleCount / mBlockSize must be a power of 2 and minimally 2.
/// inSamples: inSampleCount^2 vertices.
/// inMaterialIndices: (inSampleCount - 1)^2 indices that index into inMaterialList.
HeightFieldShapeSettings(const float *inSamples, Vec3Arg inOffset, Vec3Arg inScale, uint32 inSampleCount, const uint8 *inMaterialIndices = nullptr, const PhysicsMaterialList &inMaterialList = PhysicsMaterialList());
// See: ShapeSettings
virtual ShapeResult Create() const override;
/// Determine the minimal and maximal value of mHeightSamples (will ignore cNoCollisionValue)
/// @param outMinValue The minimal value fo mHeightSamples or FLT_MAX if no samples have collision
/// @param outMaxValue The maximal value fo mHeightSamples or -FLT_MAX if no samples have collision
/// @param outQuantizationScale (value - outMinValue) * outQuantizationScale quantizes a height sample to 16 bits
void DetermineMinAndMaxSample(float &outMinValue, float &outMaxValue, float &outQuantizationScale) const;
/// Given mBlockSize, mSampleCount and mHeightSamples, calculate the amount of bits needed to stay below absolute error inMaxError
/// @param inMaxError Maximum allowed error in mHeightSamples after compression (note that this does not take mScale.Y into account)
/// @return Needed bits per sample in the range [1, 8].
uint32 CalculateBitsPerSampleForError(float inMaxError) const;
/// The height field is a surface defined by: mOffset + mScale * (x, mHeightSamples[y * mSampleCount + x], y).
/// where x and y are integers in the range x and y e [0, mSampleCount - 1].
Vec3 mOffset = Vec3::sZero();
Vec3 mScale = Vec3::sReplicate(1.0f);
uint32 mSampleCount = 0;
/// The heightfield is divided in blocks of mBlockSize * mBlockSize * 2 triangles and the acceleration structure culls blocks only,
/// bigger block sizes reduce memory consumption but also reduce query performance. Sensible values are [2, 8], does not need to be
/// a power of 2. Note that at run-time we'll perform one more grid subdivision, so the effective block size is half of what is provided here.
uint32 mBlockSize = 2;
/// How many bits per sample to use to compress the height field. Can be in the range [1, 8].
/// Note that each sample is compressed relative to the min/max value of its block of mBlockSize * mBlockSize pixels so the effective precision is higher.
/// Also note that increasing mBlockSize saves more memory than reducing the amount of bits per sample.
uint32 mBitsPerSample = 8;
Array<float> mHeightSamples;
Array<uint8> mMaterialIndices;
/// The materials of square at (x, y) is: mMaterials[mMaterialIndices[x + y * (mSampleCount - 1)]]
PhysicsMaterialList mMaterials;
};
/// A height field shape. Cannot be used as a dynamic object.
class HeightFieldShape final : public Shape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
HeightFieldShape() : Shape(EShapeType::HeightField, EShapeSubType::HeightField) { }
HeightFieldShape(const HeightFieldShapeSettings &inSettings, ShapeResult &outResult);
// See Shape::MustBeStatic
virtual bool MustBeStatic() const override { return true; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetSubShapeIDBitsRecursive
virtual uint GetSubShapeIDBitsRecursive() const override { return GetSubShapeIDBits(); }
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return 0.0f; }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetMaterial
virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
/// Overload to get the material at a particular location
const PhysicsMaterial * GetMaterial(uint inX, uint inY) const;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See Shape::GetSubmergedVolume
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override { JPH_ASSERT(false, "Not supported"); }
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
/// Get height field position at sampled location (inX, inY).
/// where inX and inY are integers in the range inX e [0, mSampleCount - 1] and inY e [0, mSampleCount - 1].
Vec3 GetPosition(uint inX, uint inY) const;
/// Check if height field at sampled location (inX, inY) has collision (has a hole or not)
bool IsNoCollision(uint inX, uint inY) const;
/// Projects inLocalPosition (a point in the space of the shape) along the Y axis onto the surface and returns it in outSurfacePosition.
/// When there is no surface position (because of a hole or because the point is outside the heightfield) the function will return false.
bool ProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const override;
virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials) override;
// See Shape::GetStats
virtual Stats GetStats() const override;
// See Shape::GetVolume
virtual float GetVolume() const override { return 0; }
#ifdef JPH_DEBUG_RENDERER
// Settings
static bool sDrawTriangleOutlines;
#endif // JPH_DEBUG_RENDERER
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
class DecodingContext; ///< Context class for walking through all nodes of a heightfield
struct HSGetTrianglesContext; ///< Context class for GetTrianglesStart/Next
/// Calculate commonly used values and store them in the shape
void CacheValues();
/// Calculate bit mask for all active edges in the heightfield
void CalculateActiveEdges();
/// Store material indices in the least amount of bits per index possible
void StoreMaterialIndices(const Array<uint8> &inMaterialIndices);
/// Get the amount of horizontal/vertical blocks
inline uint GetNumBlocks() const { return mSampleCount / mBlockSize; }
/// Get the maximum level (amount of grids) of the tree
static inline uint sGetMaxLevel(uint inNumBlocks) { return CountTrailingZeros(inNumBlocks); }
/// Get the range block offset and stride for GetBlockOffsetAndScale
static inline void sGetRangeBlockOffsetAndStride(uint inNumBlocks, uint inMaxLevel, uint &outRangeBlockOffset, uint &outRangeBlockStride);
/// For block (inBlockX, inBlockY) get the offset and scale needed to decode a uint8 height sample to a uint16
inline void GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const;
/// Get the height sample at position (inX, inY)
inline uint8 GetHeightSample(uint inX, uint inY) const;
/// Faster version of GetPosition when block offset and scale are already known
inline Vec3 GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const;
/// Determine amount of bits needed to encode sub shape id
uint GetSubShapeIDBits() const;
/// En/decode a sub shape ID. inX and inY specify the coordinate of the triangle. inTriangle == 0 is the lower triangle, inTriangle == 1 is the upper triangle.
inline SubShapeID EncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const;
inline void DecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const;
/// Get the edge flags for a triangle
inline uint8 GetEdgeFlags(uint inX, uint inY, uint inTriangle) const;
// Helper functions called by CollisionDispatch
static void sCollideConvexVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCollideSphereVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCastConvexVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
static void sCastSphereVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
/// Visit the entire height field using a visitor pattern
template <class Visitor>
JPH_INLINE void WalkHeightField(Visitor &ioVisitor) const;
/// A block of 2x2 ranges used to form a hierarchical grid, ordered left top, right top, left bottom, right bottom
struct alignas(16) RangeBlock
{
uint16 mMin[4];
uint16 mMax[4];
};
/// Offset of first RangedBlock in grid per level
static const uint sGridOffsets[];
/// The height field is a surface defined by: mOffset + mScale * (x, mHeightSamples[y * mSampleCount + x], y).
/// where x and y are integers in the range x and y e [0, mSampleCount - 1].
Vec3 mOffset = Vec3::sZero();
Vec3 mScale = Vec3::sReplicate(1.0f);
/// Height data
uint32 mSampleCount = 0; ///< See HeightFieldShapeSettings::mSampleCount
uint32 mBlockSize = 2; ///< See HeightFieldShapeSettings::mBlockSize
uint8 mBitsPerSample = 8; ///< See HeightFieldShapeSettings::mBitsPerSample
uint8 mSampleMask = 0xff; ///< All bits set for a sample: (1 << mBitsPerSample) - 1, used to indicate that there's no collision
uint16 mMinSample = HeightFieldShapeConstants::cNoCollisionValue16; ///< Min and max value in mHeightSamples quantized to 16 bit, for calculating bounding box
uint16 mMaxSample = HeightFieldShapeConstants::cNoCollisionValue16;
Array<RangeBlock> mRangeBlocks; ///< Hierarchical grid of range data describing the height variations within 1 block. The grid for level <level> starts at offset sGridOffsets[<level>]
Array<uint8> mHeightSamples; ///< mBitsPerSample-bit height samples. Value [0, mMaxHeightValue] maps to highest detail grid in mRangeBlocks [mMin, mMax]. mNoCollisionValue is reserved to indicate no collision.
Array<uint8> mActiveEdges; ///< (mSampleCount - 1)^2 * 3-bit active edge flags.
/// Materials
PhysicsMaterialList mMaterials; ///< The materials of square at (x, y) is: mMaterials[mMaterialIndices[x + y * (mSampleCount - 1)]]
Array<uint8> mMaterialIndices; ///< Compressed to the minimum amount of bits per material index (mSampleCount - 1) * (mSampleCount - 1) * mNumBitsPerMaterialIndex bits of data
uint32 mNumBitsPerMaterialIndex = 0; ///< Number of bits per material index
#ifdef JPH_DEBUG_RENDERER
/// Temporary rendering data
mutable Array<DebugRenderer::GeometryRef> mGeometry;
mutable bool mCachedUseMaterialColors = false; ///< This is used to regenerate the triangle batch if the drawing settings change
#endif // JPH_DEBUG_RENDERER
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/TaperedCapsuleShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#ifdef JPH_DEBUG_RENDERER
#include <Jolt/Renderer/DebugRenderer.h>
#endif // JPH_DEBUG_RENDERER
JPH_NAMESPACE_BEGIN
/// Class that constructs a TaperedCapsuleShape
class TaperedCapsuleShapeSettings final : public ConvexShapeSettings
{
JPH_DECLARE_SERIALIZABLE_VIRTUAL(TaperedCapsuleShapeSettings)
/// Default constructor for deserialization
TaperedCapsuleShapeSettings() = default;
/// Create a tapered capsule centered around the origin with one sphere cap at (0, -inHalfHeightOfTaperedCylinder, 0) with radius inBottomRadius and the other at (0, inHalfHeightOfTaperedCylinder, 0) with radius inTopRadius
TaperedCapsuleShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, const PhysicsMaterial *inMaterial = nullptr);
/// Check if the settings are valid
bool IsValid() const { return mTopRadius > 0.0f && mBottomRadius > 0.0f && mHalfHeightOfTaperedCylinder >= 0.0f; }
/// Checks if the settings of this tapered capsule make this shape a sphere
bool IsSphere() const;
// See: ShapeSettings
virtual ShapeResult Create() const override;
float mHalfHeightOfTaperedCylinder = 0.0f;
float mTopRadius = 0.0f;
float mBottomRadius = 0.0f;
};
/// A capsule with different top and bottom radii
class TaperedCapsuleShape final : public ConvexShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
TaperedCapsuleShape() : ConvexShape(EShapeSubType::TaperedCapsule) { }
TaperedCapsuleShape(const TaperedCapsuleShapeSettings &inSettings, ShapeResult &outResult);
// See Shape::GetCenterOfMass
virtual Vec3 GetCenterOfMass() const override { return mCenterOfMass; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override;
// See Shape::GetWorldSpaceBounds
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
using Shape::GetWorldSpaceBounds;
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return min(mTopRadius, mBottomRadius); }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See ConvexShape::GetSupportFunction
virtual const Support * GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::TransformShape
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 0); }
// See Shape::GetVolume
virtual float GetVolume() const override { return GetLocalBounds().GetVolume(); } // Volume is approximate!
// See Shape::IsValidScale
virtual bool IsValidScale(Vec3Arg inScale) const override;
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Class for GetSupportFunction
class TaperedCapsule;
/// Returns box that approximates the inertia
AABox GetInertiaApproximation() const;
Vec3 mCenterOfMass = Vec3::sZero();
float mTopRadius = 0.0f;
float mBottomRadius = 0.0f;
float mTopCenter = 0.0f;
float mBottomCenter = 0.0f;
float mConvexRadius = 0.0f;
float mSinAlpha = 0.0f;
float mTanAlpha = 0.0f;
#ifdef JPH_DEBUG_RENDERER
mutable DebugRenderer::GeometryRef mGeometry;
#endif // JPH_DEBUG_RENDERER
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/MutableCompoundShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/CompoundShape.h>
JPH_NAMESPACE_BEGIN
class CollideShapeSettings;
/// Class that constructs a MutableCompoundShape.
class MutableCompoundShapeSettings final : public CompoundShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(MutableCompoundShapeSettings)
// See: ShapeSettings
virtual ShapeResult Create() const override;
};
/// A compound shape, sub shapes can be rotated and translated.
/// This shape is optimized for adding / removing and changing the rotation / translation of sub shapes but is less efficient in querying.
/// Shifts all child objects so that they're centered around the center of mass (which needs to be kept up to date by calling AdjustCenterOfMass).
///
/// Note: If you're using MutableCompoundShapes and are querying data while modifying the shape you'll have a race condition.
/// In this case it is best to create a new MutableCompoundShape and set the new shape on the body using BodyInterface::SetShape. If a
/// query is still working on the old shape, it will have taken a reference and keep the old shape alive until the query finishes.
class MutableCompoundShape final : public CompoundShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
MutableCompoundShape() : CompoundShape(EShapeSubType::MutableCompound) { }
MutableCompoundShape(const MutableCompoundShapeSettings &inSettings, ShapeResult &outResult);
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::CollectTransformedShapes
virtual void CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const override;
// See: CompoundShape::GetIntersectingSubShapes
virtual int GetIntersectingSubShapes(const AABox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const override;
// See: CompoundShape::GetIntersectingSubShapes
virtual int GetIntersectingSubShapes(const OrientedBox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this) + mSubShapes.size() * sizeof(SubShape) + mSubShapeBounds.size() * sizeof(Bounds), 0); }
///@{
/// @name Mutating shapes. Note that this is not thread safe, so you need to ensure that any bodies that use this shape are locked at the time of modification using BodyLockWrite. After modification you need to call BodyInterface::NotifyShapeChanged to update the broadphase and collision caches.
/// Adding a new shape
/// @return The index of the newly added shape
uint AddShape(Vec3Arg inPosition, QuatArg inRotation, const Shape *inShape, uint32 inUserData = 0);
/// Remove a shape by index
void RemoveShape(uint inIndex);
/// Modify the position / orientation of a shape
void ModifyShape(uint inIndex, Vec3Arg inPosition, QuatArg inRotation);
/// Modify the position / orientation and shape at the same time
void ModifyShape(uint inIndex, Vec3Arg inPosition, QuatArg inRotation, const Shape *inShape);
/// @brief Batch set positions / orientations, this avoids duplicate work due to bounding box calculation.
/// @param inStartIndex Index of first shape to update
/// @param inNumber Number of shapes to update
/// @param inPositions A list of positions with arbitrary stride
/// @param inRotations A list of orientations with arbitrary stride
/// @param inPositionStride The position stride (the number of bytes between the first and second element)
/// @param inRotationStride The orientation stride (the number of bytes between the first and second element)
void ModifyShapes(uint inStartIndex, uint inNumber, const Vec3 *inPositions, const Quat *inRotations, uint inPositionStride = sizeof(Vec3), uint inRotationStride = sizeof(Quat));
/// Recalculate the center of mass and shift all objects so they're centered around it
/// (this needs to be done of dynamic bodies and if the center of mass changes significantly due to adding / removing / repositioning sub shapes or else the simulation will look unnatural)
/// Note that after adjusting the center of mass of an object you need to call BodyInterface::NotifyShapeChanged and Constraint::NotifyShapeChanged on the relevant bodies / constraints.
void AdjustCenterOfMass();
///@}
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Visitor for GetIntersectingSubShapes
template <class BoxType>
struct GetIntersectingSubShapesVisitorMC : public GetIntersectingSubShapesVisitor<BoxType>
{
using GetIntersectingSubShapesVisitor<BoxType>::GetIntersectingSubShapesVisitor;
using Result = UVec4;
JPH_INLINE Result TestBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ) const
{
return GetIntersectingSubShapesVisitor<BoxType>::TestBounds(inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
}
JPH_INLINE bool ShouldVisitBlock(UVec4Arg inResult) const
{
return inResult.TestAnyTrue();
}
JPH_INLINE bool ShouldVisitSubShape(UVec4Arg inResult, uint inIndexInBlock) const
{
return inResult[inIndexInBlock] != 0;
}
};
/// Get the number of blocks of 4 bounding boxes
inline uint GetNumBlocks() const { return ((uint)mSubShapes.size() + 3) >> 2; }
/// Ensure that the mSubShapeBounds has enough space to store bounding boxes equivalent to the number of shapes in mSubShapes
void EnsureSubShapeBoundsCapacity();
/// Update mSubShapeBounds
/// @param inStartIdx First sub shape to update
/// @param inNumber Number of shapes to update
void CalculateSubShapeBounds(uint inStartIdx, uint inNumber);
/// Calculate mLocalBounds from mSubShapeBounds
void CalculateLocalBounds();
template <class Visitor>
JPH_INLINE void WalkSubShapes(Visitor &ioVisitor) const; ///< Walk the sub shapes and call Visitor::VisitShape for each sub shape encountered
// Helper functions called by CollisionDispatch
static void sCollideCompoundVsShape(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCollideShapeVsCompound(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
static void sCastShapeVsCompound(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
struct Bounds
{
Vec4 mMinX;
Vec4 mMinY;
Vec4 mMinZ;
Vec4 mMaxX;
Vec4 mMaxY;
Vec4 mMaxZ;
};
Array<Bounds> mSubShapeBounds; ///< Bounding boxes of all sub shapes in SOA format (in blocks of 4 boxes), MinX 0..3, MinY 0..3, MinZ 0..3, MaxX 0..3, MaxY 0..3, MaxZ 0..3, MinX 4..7, MinY 4..7, ...
};
JPH_NAMESPACE_END
|
0 | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision | repos/c2z/use_cases/JoltPhysics/include/Physics/Collision/Shape/BoxShape.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/Physics/Collision/Shape/ConvexShape.h>
#include <Jolt/Physics/PhysicsSettings.h>
JPH_NAMESPACE_BEGIN
/// Class that constructs a BoxShape
class BoxShapeSettings final : public ConvexShapeSettings
{
public:
JPH_DECLARE_SERIALIZABLE_VIRTUAL(BoxShapeSettings)
/// Default constructor for deserialization
BoxShapeSettings() = default;
/// Create a box with half edge length inHalfExtent and convex radius inConvexRadius.
/// (internally the convex radius will be subtracted from the half extent so the total box will not grow with the convex radius).
BoxShapeSettings(Vec3Arg inHalfExtent, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShapeSettings(inMaterial), mHalfExtent(inHalfExtent), mConvexRadius(inConvexRadius) { }
// See: ShapeSettings
virtual ShapeResult Create() const override;
Vec3 mHalfExtent = Vec3::sZero(); ///< Half the size of the box (including convex radius)
float mConvexRadius = 0.0f;
};
/// A box, centered around the origin
class BoxShape final : public ConvexShape
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor
BoxShape() : ConvexShape(EShapeSubType::Box) { }
BoxShape(const BoxShapeSettings &inSettings, ShapeResult &outResult);
/// Create a box with half edge length inHalfExtent and convex radius inConvexRadius.
/// (internally the convex radius will be subtracted from the half extent so the total box will not grow with the convex radius).
BoxShape(Vec3Arg inHalfExtent, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr) : ConvexShape(EShapeSubType::Box, inMaterial), mHalfExtent(inHalfExtent), mConvexRadius(inConvexRadius) { JPH_ASSERT(inConvexRadius >= 0.0f); JPH_ASSERT(inHalfExtent.ReduceMin() >= inConvexRadius); }
/// Get half extent of box
Vec3 GetHalfExtent() const { return mHalfExtent; }
// See Shape::GetLocalBounds
virtual AABox GetLocalBounds() const override { return AABox(-mHalfExtent, mHalfExtent); }
// See Shape::GetInnerRadius
virtual float GetInnerRadius() const override { return mHalfExtent.ReduceMin(); }
// See Shape::GetMassProperties
virtual MassProperties GetMassProperties() const override;
// See Shape::GetSurfaceNormal
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
// See Shape::GetSupportingFace
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
// See ConvexShape::GetSupportFunction
virtual const Support * GetSupportFunction(ESupportMode inMode, SupportBuffer &inBuffer, Vec3Arg inScale) const override;
#ifdef JPH_DEBUG_RENDERER
// See Shape::Draw
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
#endif // JPH_DEBUG_RENDERER
// See Shape::CastRay
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See: Shape::CollidePoint
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
// See Shape::GetTrianglesStart
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
// See Shape::GetTrianglesNext
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
// See Shape
virtual void SaveBinaryState(StreamOut &inStream) const override;
// See Shape::GetStats
virtual Stats GetStats() const override { return Stats(sizeof(*this), 12); }
// See Shape::GetVolume
virtual float GetVolume() const override { return GetLocalBounds().GetVolume(); }
/// Get the convex radius of this box
float GetConvexRadius() const { return mConvexRadius; }
// Register shape functions with the registry
static void sRegister();
protected:
// See: Shape::RestoreBinaryState
virtual void RestoreBinaryState(StreamIn &inStream) override;
private:
// Class for GetSupportFunction
class Box;
Vec3 mHalfExtent = Vec3::sZero(); ///< Half the size of the box (including convex radius)
float mConvexRadius = 0.0f;
};
JPH_NAMESPACE_END
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.