Optimize Broad-Phase (#159)
Broad-phase optimization ported from Box2D.
This commit is contained in:
parent
954cf879e7
commit
f555ee4208
51 changed files with 3802 additions and 1830 deletions
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,17336.6
|
||||
2,8857.22
|
||||
3,5945.65
|
||||
4,4508.71
|
||||
5,3674.55
|
||||
6,3105.97
|
||||
7,2696.86
|
||||
8,2410.11
|
||||
1,14441.9
|
||||
2,7238.43
|
||||
3,4870.13
|
||||
4,3697.34
|
||||
5,2998.67
|
||||
6,2533.13
|
||||
7,2209.12
|
||||
8,1983.89
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,1586.48
|
||||
2,787.633
|
||||
3,531.491
|
||||
4,401.5
|
||||
5,325.625
|
||||
6,275.095
|
||||
7,238.344
|
||||
8,214.504
|
||||
1,1323.84
|
||||
2,691.063
|
||||
3,463.698
|
||||
4,353.723
|
||||
5,284.09
|
||||
6,240.864
|
||||
7,209.11
|
||||
8,185.953
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,20044.1
|
||||
2,10386.4
|
||||
3,7087.11
|
||||
4,5437.88
|
||||
5,4451.58
|
||||
6,3792.59
|
||||
7,3293.41
|
||||
8,2970.84
|
||||
1,16467.5
|
||||
2,8687.63
|
||||
3,5966.06
|
||||
4,4569.55
|
||||
5,3727.89
|
||||
6,3175.51
|
||||
7,2801.72
|
||||
8,2512.32
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,2071.23
|
||||
2,1143.38
|
||||
3,778.58
|
||||
4,597.287
|
||||
5,487.523
|
||||
6,419.766
|
||||
7,366.281
|
||||
8,333.042
|
||||
1,1993.6
|
||||
2,1049.01
|
||||
3,712.917
|
||||
4,544.335
|
||||
5,443.056
|
||||
6,384.22
|
||||
7,331.626
|
||||
8,297.982
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,10.938
|
||||
2,12.76
|
||||
3,13.5526
|
||||
4,13.9525
|
||||
5,15.3005
|
||||
6,15.6679
|
||||
7,15.4235
|
||||
8,14.7126
|
||||
1,7.6329
|
||||
2,9.7115
|
||||
3,10.7648
|
||||
4,11.2398
|
||||
5,12.029
|
||||
6,12.1204
|
||||
7,12.2289
|
||||
8,12.5125
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,2331.14
|
||||
2,1259.61
|
||||
3,827.118
|
||||
4,616.691
|
||||
5,495.451
|
||||
6,411.55
|
||||
7,355.527
|
||||
8,316.039
|
||||
1,2075.59
|
||||
2,1084.54
|
||||
3,722.057
|
||||
4,549.644
|
||||
5,437.772
|
||||
6,372.242
|
||||
7,319.13
|
||||
8,283.131
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,2434.57
|
||||
2,1325.14
|
||||
3,937.234
|
||||
4,737.677
|
||||
5,615.764
|
||||
6,536.387
|
||||
7,479.755
|
||||
8,444.147
|
||||
1,2102.47
|
||||
2,1147.85
|
||||
3,803.547
|
||||
4,630.96
|
||||
5,524.168
|
||||
6,452.1
|
||||
7,404.499
|
||||
8,370.325
|
||||
|
|
|
|||
|
9
benchmark/amd7950x_sse2/sleep.csv
Normal file
9
benchmark/amd7950x_sse2/sleep.csv
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
threads,ms
|
||||
1,1144.18
|
||||
2,613.407
|
||||
3,423.032
|
||||
4,329.512
|
||||
5,272.901
|
||||
6,239.65
|
||||
7,216.5
|
||||
8,200.217
|
||||
|
9
benchmark/amd7950x_sse2/spinner.csv
Normal file
9
benchmark/amd7950x_sse2/spinner.csv
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
threads,ms
|
||||
1,3173.87
|
||||
2,1841.25
|
||||
3,1325.07
|
||||
4,1061.04
|
||||
5,902.193
|
||||
6,803.715
|
||||
7,734.266
|
||||
8,689.781
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,225.438
|
||||
2,141.14
|
||||
3,115.727
|
||||
4,101.289
|
||||
5,93.6898
|
||||
6,90.61
|
||||
7,86.1046
|
||||
8,86.7291
|
||||
1,170.276
|
||||
2,112.037
|
||||
3,88.2708
|
||||
4,78.4451
|
||||
5,74.3577
|
||||
6,71.868
|
||||
7,70.6687
|
||||
8,69.1284
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,727.276
|
||||
2,433.755
|
||||
3,315.505
|
||||
4,270.352
|
||||
5,246.82
|
||||
6,228.451
|
||||
7,216.217
|
||||
8,210.749
|
||||
1,673.356
|
||||
2,395.07
|
||||
3,291.336
|
||||
4,249.378
|
||||
5,225.709
|
||||
6,211.1
|
||||
7,201.452
|
||||
8,194.379
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,334.365
|
||||
2,191.522
|
||||
3,144.41
|
||||
4,127.041
|
||||
5,119.247
|
||||
6,113.65
|
||||
7,108.433
|
||||
8,105.905
|
||||
1,285.24
|
||||
2,174.635
|
||||
3,132.161
|
||||
4,116.509
|
||||
5,107.948
|
||||
6,102.503
|
||||
7,98.9163
|
||||
8,96.5196
|
||||
|
|
|
|||
|
|
|
@ -1,9 +1,9 @@
|
|||
threads,ms
|
||||
1,27059.6
|
||||
2,14569.2
|
||||
3,10081.7
|
||||
4,7825.43
|
||||
5,6480.34
|
||||
6,5518.81
|
||||
7,4901.6
|
||||
8,4256.68
|
||||
1,21430.4
|
||||
2,11407.7
|
||||
3,7908.09
|
||||
4,6102.55
|
||||
5,5012.68
|
||||
6,4272.59
|
||||
7,3783.33
|
||||
8,3415.5
|
||||
|
|
|
|||
|
|
|
@ -157,12 +157,13 @@ int main( int argc, char** argv )
|
|||
{ "large_world", GetLargeWorldCapacity, CreateLargeWorld, NULL, StepLargeWorld, 500 },
|
||||
{ "many_pyramids", NULL, CreateManyPyramids, NULL, NULL, 100 },
|
||||
{ "rain", GetRainCapacity, CreateRain, DestroyRain, StepRain, 400 },
|
||||
{ "sleep", GetSleepCapacity, CreateSleep, NULL, StepSleep, 300 },
|
||||
{ "spinner", GetSpinnerCapacity, CreateSpinner, DestroySpinner, NULL, 800 },
|
||||
{ "trees100", NULL, CreateTrees100, DestroyTrees, NULL, 500 },
|
||||
{ "trees50", NULL, CreateTrees50, DestroyTrees, NULL, 500 },
|
||||
{ "trees25", NULL, CreateTrees25, DestroyTrees, NULL, 500 },
|
||||
{ "washer", GetWasherCapacity, CreateWasher, NULL, NULL, 1000 },
|
||||
//{ "smash", CreateSmash, NULL, 300 },
|
||||
//{ "spinner", CreateSpinner, StepSpinner, 1400 },
|
||||
//{ "tumbler", CreateTumbler, NULL, 750 },
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -48,8 +48,8 @@ B3_API b3TreeStats b3DynamicTree_Query( const b3DynamicTree* tree, b3AABB aabb,
|
|||
/// point.
|
||||
/// @param tree the dynamic tree to query
|
||||
/// @param point the query point
|
||||
/// @param maskBits nodes are skipped if the bit-wise AND with the node category bits is zero
|
||||
/// @param requireAllBits nodes are skipped if the bit-wise AND with the node category bits does not equal the maskBits
|
||||
/// @param maskBits proxies are skipped if the bit-wise AND with the proxy category bits is zero
|
||||
/// @param requireAllBits proxies are skipped if the bit-wise AND with the proxy category bits does not equal the maskBits
|
||||
/// @param callback a user provided instance of b3TreeQueryClosestCallbackFcn
|
||||
/// @param context a user context object that is provided to the callback
|
||||
/// @param minDistanceSqr the initial and final minimum squared distance. Provide a small initial to restrict the search and
|
||||
|
|
@ -68,8 +68,8 @@ B3_API b3TreeStats b3DynamicTree_QueryClosest( const b3DynamicTree* tree, b3Vec3
|
|||
/// However, this filtering may be approximate, so the user should still apply filtering to results.
|
||||
/// @param tree the dynamic tree to ray cast
|
||||
/// @param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1)
|
||||
/// @param maskBits bit mask test: `bool accept = (maskBits & node->categoryBits) != 0;`
|
||||
/// @param requireAllBits modifies bit mask test: `bool accept = (maskBits & node->categoryBits) == maskBits;`
|
||||
/// @param maskBits bit mask test: `bool accept = (maskBits & proxy->categoryBits) != 0;`
|
||||
/// @param requireAllBits modifies bit mask test: `bool accept = (maskBits & proxy->categoryBits) == maskBits;`
|
||||
/// @param callback a callback function that is called for each proxy that is hit by the ray
|
||||
/// @param context user context that is passed to the callback
|
||||
/// @return performance data
|
||||
|
|
@ -103,8 +103,8 @@ B3_API int b3DynamicTree_GetByteCount( const b3DynamicTree* tree );
|
|||
/// Validate this tree. For testing.
|
||||
B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree );
|
||||
|
||||
/// Validate this tree has no enlarged AABBs. For testing.
|
||||
B3_API void b3DynamicTree_ValidateNoEnlarged( const b3DynamicTree* tree );
|
||||
/// Validate this tree has no moved nodes. For testing.
|
||||
B3_API void b3DynamicTree_ValidateNoMoved( const b3DynamicTree* tree );
|
||||
|
||||
/// Save this tree to a file for debugging
|
||||
B3_API void b3DynamicTree_Save( const b3DynamicTree* tree, const char* fileName );
|
||||
|
|
@ -115,13 +115,13 @@ B3_API b3DynamicTree b3DynamicTree_Load( const char* fileName, float scale );
|
|||
/// Get proxy user data
|
||||
B3_INLINE uint64_t b3DynamicTree_GetUserData( const b3DynamicTree* tree, int proxyId )
|
||||
{
|
||||
return tree->nodes[proxyId].userData;
|
||||
return tree->proxies[proxyId].userData;
|
||||
}
|
||||
|
||||
/// Get the AABB of a proxy
|
||||
B3_INLINE b3AABB b3DynamicTree_GetAABB( const b3DynamicTree* tree, int proxyId )
|
||||
{
|
||||
return tree->nodes[proxyId].aabb;
|
||||
return tree->nodes[tree->proxies[proxyId].node].aabb;
|
||||
}
|
||||
|
||||
/**@}*/ // tree
|
||||
|
|
|
|||
|
|
@ -1683,58 +1683,46 @@ typedef struct b3TOIOutput
|
|||
* @{
|
||||
*/
|
||||
|
||||
/// Flags for tree nodes. For internal usage.
|
||||
typedef enum b3TreeNodeFlags
|
||||
{
|
||||
b3_allocatedNode = 0x0001,
|
||||
b3_enlargedNode = 0x0002,
|
||||
b3_leafNode = 0x0004,
|
||||
} b3TreeNodeFlags;
|
||||
|
||||
/// Tree node child indices. For internal usage.
|
||||
typedef struct b3TreeNodeChildren
|
||||
{
|
||||
int child1; ///< child node index 1
|
||||
int child2; ///< child node index 2
|
||||
} b3TreeNodeChildren;
|
||||
|
||||
/// A node in the dynamic tree. This is private data placed here for performance reasons.
|
||||
/// todo test padding to 64 bytes to avoid straddling cache lines
|
||||
/// A node in the dynamic tree. Siblings sit together at an even index so two nodes fit in
|
||||
/// a 64 byte cache line. The root is at index zero and index one always empty.
|
||||
typedef struct b3TreeNode
|
||||
{
|
||||
/// The node bounding box
|
||||
b3AABB aabb; // 24
|
||||
|
||||
/// Category bits for collision filtering
|
||||
uint64_t categoryBits; // 8
|
||||
/// bit 31 : 1 for leaf node
|
||||
/// bit 30 : 1 for moved flag
|
||||
/// bits 0-29 : index of the sibling pair node or the proxy id for a leaf
|
||||
uint32_t flagIndex; // 4
|
||||
|
||||
union
|
||||
{
|
||||
/// Children (internal node)
|
||||
b3TreeNodeChildren children;
|
||||
/// The height of an internal node. A leaf has zero height.
|
||||
int32_t height;
|
||||
|
||||
/// User data (leaf node)
|
||||
uint64_t userData;
|
||||
}; // 8
|
||||
|
||||
union
|
||||
{
|
||||
/// The node parent index (allocated node)
|
||||
int parent;
|
||||
|
||||
/// The node freelist next index (free node)
|
||||
int next;
|
||||
/// The shape index for a leaf. Truncated from proxy user data.
|
||||
int32_t shapeIndex;
|
||||
}; // 4
|
||||
|
||||
/// Height of the node. Leaves have a height of 0.
|
||||
uint16_t height; // 2
|
||||
|
||||
/// @see b3TreeNodeFlags
|
||||
uint16_t flags; // 2
|
||||
} b3TreeNode;
|
||||
|
||||
/// Separate storage for tree leaves.
|
||||
typedef struct b3TreeProxy
|
||||
{
|
||||
/// User data is an index instead of void* because it is used internally as a shape index.
|
||||
uint64_t userData;
|
||||
|
||||
/// Category bits for collision filtering.
|
||||
uint64_t categoryBits;
|
||||
|
||||
/// The leaf node. B3_NULL_INDEX for a free proxy.
|
||||
int32_t node;
|
||||
|
||||
/// Next free proxy.
|
||||
int32_t next;
|
||||
} b3TreeProxy;
|
||||
|
||||
/// Dynamic tree version for compatibility testing.
|
||||
#define B3_DYNAMIC_TREE_VERSION 0x93EDAF889FD30B4Aull
|
||||
#define B3_DYNAMIC_TREE_VERSION 0x1D6F4C2A73B80E91ull
|
||||
|
||||
/// The dynamic tree structure. This should be considered private data.
|
||||
/// It is placed here for performance reasons.
|
||||
|
|
@ -1744,26 +1732,42 @@ typedef struct b3DynamicTree
|
|||
/// if the tree is serialized.
|
||||
uint64_t version;
|
||||
|
||||
/// The tree nodes
|
||||
/// Array of nodes. The root is at index zero and index 1 is empty.
|
||||
/// Otherwise siblings are paired at even indices. Has holes for free node pairs.
|
||||
b3TreeNode* nodes;
|
||||
|
||||
/// The root index
|
||||
int root;
|
||||
/// Parent index per node. The free list is interweaved.
|
||||
int32_t* parents;
|
||||
|
||||
/// The number of nodes
|
||||
int nodeCount;
|
||||
/// Proxy data split from node array as cold data.
|
||||
b3TreeProxy* proxies;
|
||||
|
||||
/// Every allocated node has a lower index than this.
|
||||
int32_t nodeEnd;
|
||||
|
||||
/// The allocated node space
|
||||
int nodeCapacity;
|
||||
int32_t nodeCapacity;
|
||||
|
||||
/// Free pairs below nodeEnd
|
||||
int32_t pairFreeList;
|
||||
|
||||
/// Number of proxies created
|
||||
int proxyCount;
|
||||
int32_t proxyCount;
|
||||
|
||||
/// Node free list
|
||||
int freeList;
|
||||
/// The allocated proxy space
|
||||
int32_t proxyCapacity;
|
||||
|
||||
/// Proxy free list
|
||||
int32_t proxyFreeList;
|
||||
|
||||
/// Array of nodes for rebuild.
|
||||
b3TreeNode* swapNodes;
|
||||
|
||||
/// Leaf indices for rebuild
|
||||
int* leafIndices;
|
||||
int32_t* leafIndices;
|
||||
|
||||
/// Leaves for the rebuild. May represent a proxy or a retained subtree.
|
||||
b3TreeNode* leafNodes;
|
||||
|
||||
/// Leaf bounding boxes for rebuild
|
||||
b3AABB* leafBoxes;
|
||||
|
|
@ -1772,10 +1776,14 @@ typedef struct b3DynamicTree
|
|||
b3Vec3* leafCenters;
|
||||
|
||||
/// Bins for sorting during rebuild
|
||||
int* binIndices;
|
||||
int32_t* binIndices;
|
||||
|
||||
/// Allocated space for rebuilding
|
||||
int rebuildCapacity;
|
||||
int32_t rebuildCapacity;
|
||||
|
||||
/// Rebuild orders the nodes so the children follow parents. Cache friendly for queries
|
||||
/// and refitting. The order can be disrupted by proxy creation.
|
||||
bool dfsOrdered;
|
||||
} b3DynamicTree;
|
||||
|
||||
/// These are performance results returned by dynamic tree queries.
|
||||
|
|
@ -2488,7 +2496,11 @@ typedef struct b3CompoundData
|
|||
/// Offset of the tree node array in bytes from the struct address.
|
||||
int nodeOffset;
|
||||
|
||||
/// Immutable dynamic tree. The tree node pointer must be fixed up using the node offset
|
||||
/// Offset of the tree proxy array in bytes from the struct address.
|
||||
int proxyOffset;
|
||||
|
||||
/// Immutable dynamic tree. The node and proxy pointers must be fixed up using the offsets
|
||||
/// above. A baked tree is never inserted into, so the parent array stays null.
|
||||
b3DynamicTree tree;
|
||||
|
||||
/// Offset of the material array in bytes from the struct address.
|
||||
|
|
|
|||
|
|
@ -194,10 +194,12 @@ endif()
|
|||
|
||||
# Include root is the samples dir so "gfx/..." and "host/..." prefixes resolve.
|
||||
# The data dir is on the path too so samples can #include recorded dumps
|
||||
# (sample_issues pulls dumps/.../box3d_dump.inl at compile time).
|
||||
# (sample_issues pulls dumps/.../box3d_dump.inl at compile time). src is on the
|
||||
# path so sample_tree.cpp can reach dynamic_tree.h for the node layout helpers.
|
||||
target_include_directories(samples PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../data")
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../data"
|
||||
"${CMAKE_SOURCE_DIR}/src")
|
||||
|
||||
# gfx: the renderer + Draw*/adapter. shared: human, utils (Random*), the
|
||||
# benchmark/determinism helpers the samples lean on.
|
||||
|
|
|
|||
|
|
@ -1439,7 +1439,7 @@ public:
|
|||
|
||||
void Step() override
|
||||
{
|
||||
if ( m_context->pause == false || m_context->singleStep == 0 )
|
||||
if ( m_context->pause == false || m_context->singleStep > 0 )
|
||||
{
|
||||
StepJunkyard( m_worldId, m_stepCount );
|
||||
}
|
||||
|
|
@ -1486,3 +1486,78 @@ public:
|
|||
};
|
||||
|
||||
static int sampleConvexPile = RegisterSample( "Benchmark", "Convex Pile", BenchmarkConvexPile::Create );
|
||||
|
||||
class BenchmarkSpinner : public Sample
|
||||
{
|
||||
public:
|
||||
explicit BenchmarkSpinner( SampleContext* context )
|
||||
: Sample( context )
|
||||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( 0.0f, 12.0f, 45.0f, { 0.0f, 12.0f, 0.0f } );
|
||||
}
|
||||
|
||||
b3Capacity capacity = {};
|
||||
GetSpinnerCapacity( &capacity );
|
||||
CreateWorld( &capacity );
|
||||
|
||||
CreateSpinner( m_worldId );
|
||||
}
|
||||
|
||||
~BenchmarkSpinner() override
|
||||
{
|
||||
DestroySpinner();
|
||||
}
|
||||
|
||||
void Step() override
|
||||
{
|
||||
Sample::Step();
|
||||
|
||||
DrawTextLine( "spinner angle = %.2f", GetSpinnerAngle() );
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
{
|
||||
return new BenchmarkSpinner( context );
|
||||
}
|
||||
};
|
||||
|
||||
static int benchmarkSpinner = RegisterSample( "Benchmark", "Spinner", BenchmarkSpinner::Create );
|
||||
|
||||
class BenchmarkSleep : public Sample
|
||||
{
|
||||
public:
|
||||
explicit BenchmarkSleep( SampleContext* context )
|
||||
: Sample( context )
|
||||
{
|
||||
if ( m_context->restart == false )
|
||||
{
|
||||
m_camera->SetView( -10.0f, 25.0f, 100.0f, { 0.0f, 3.0f, 0.0f } );
|
||||
}
|
||||
|
||||
b3Capacity capacity = {};
|
||||
GetSleepCapacity( &capacity );
|
||||
CreateWorld( &capacity );
|
||||
|
||||
CreateSleep( m_worldId );
|
||||
SetGroundShape( GetGroundShapeId() );
|
||||
}
|
||||
|
||||
void Step() override
|
||||
{
|
||||
if ( m_context->pause == false || m_context->singleStep > 0 )
|
||||
{
|
||||
StepSleep( m_worldId, m_stepCount );
|
||||
}
|
||||
|
||||
Sample::Step();
|
||||
}
|
||||
|
||||
static Sample* Create( SampleContext* context )
|
||||
{
|
||||
return new BenchmarkSleep( context );
|
||||
}
|
||||
};
|
||||
|
||||
static int benchmarkSleep = RegisterSample( "Benchmark", "Sleep", BenchmarkSleep::Create );
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@
|
|||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include "dynamic_tree.h"
|
||||
|
||||
#include <queue>
|
||||
#include <stdio.h>
|
||||
#include <unordered_map>
|
||||
|
|
@ -88,45 +90,55 @@ public:
|
|||
}
|
||||
|
||||
// Breath-first search to compute node depth values start with 0 at the root.
|
||||
// The tree is walked a sibling pair at a time, so depth is tracked alongside
|
||||
// each queued pair rather than looked up through the parent index.
|
||||
int ComputeDepths()
|
||||
{
|
||||
m_depths.resize( m_tree.nodeCapacity, 0 );
|
||||
|
||||
if ( m_tree.nodes == nullptr || m_tree.nodeCount == 0 || m_tree.root == B3_NULL_INDEX )
|
||||
if ( m_tree.nodes == nullptr || m_tree.proxyCount == 0 )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int* queue = (int*)malloc( m_tree.nodeCount * sizeof( int ) );
|
||||
b3TreeNode* nodes = m_tree.nodes;
|
||||
m_depths[B3_ROOT_NODE] = 0;
|
||||
|
||||
if ( b3IsLeaf( nodes + B3_ROOT_NODE ) )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct QueueItem
|
||||
{
|
||||
int pair;
|
||||
int depth;
|
||||
};
|
||||
|
||||
QueueItem* queue = (QueueItem*)malloc( m_tree.nodeEnd * sizeof( QueueItem ) );
|
||||
int front = 0;
|
||||
int back = 0;
|
||||
|
||||
b3TreeNode* nodes = m_tree.nodes;
|
||||
queue[0] = m_tree.root;
|
||||
back += 1;
|
||||
queue[back++] = { b3GetLeftChild( nodes + B3_ROOT_NODE ), 1 };
|
||||
|
||||
int depth = 0;
|
||||
|
||||
while ( back > front )
|
||||
{
|
||||
int index = queue[front];
|
||||
front += 1;
|
||||
QueueItem item = queue[front++];
|
||||
depth = b3MaxInt( depth, item.depth );
|
||||
|
||||
b3TreeNode* node = nodes + index;
|
||||
if ( node->parent == B3_NULL_INDEX )
|
||||
for ( int i = 0; i < 2; ++i )
|
||||
{
|
||||
m_depths[index] = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_depths[index] = m_depths[node->parent] + 1;
|
||||
depth = b3MaxInt( depth, m_depths[index] );
|
||||
}
|
||||
int index = item.pair + i;
|
||||
b3TreeNode* node = nodes + index;
|
||||
m_depths[index] = item.depth;
|
||||
|
||||
if ( ( node->flags & b3_leafNode ) == 0 )
|
||||
{
|
||||
B3_ASSERT( back < m_tree.nodeCount - 1 );
|
||||
queue[back++] = node->children.child1;
|
||||
queue[back++] = node->children.child2;
|
||||
if ( b3IsLeaf( node ) == false )
|
||||
{
|
||||
B3_ASSERT( back < m_tree.nodeEnd );
|
||||
queue[back++] = { b3GetLeftChild( node ), item.depth + 1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -284,17 +296,15 @@ public:
|
|||
int maxArea = 0.0f;
|
||||
int maxAreaIndex = -1;
|
||||
|
||||
for ( int i = 0; i < m_tree.nodeCapacity; ++i )
|
||||
for ( int i = 0; i < m_tree.nodeEnd; ++i )
|
||||
{
|
||||
b3TreeNode* node = m_tree.nodes + i;
|
||||
|
||||
if ( ( node->flags & b3_leafNode ) == 0 )
|
||||
if ( b3IsLeaf( node ) == false || b3IsEmptyNode( node ) )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
assert( node->flags & b3_allocatedNode );
|
||||
|
||||
Proxy proxy = {};
|
||||
proxy.aabb = node->aabb;
|
||||
|
||||
|
|
@ -305,8 +315,9 @@ public:
|
|||
maxAreaIndex = (int)m_proxies.size();
|
||||
}
|
||||
|
||||
proxy.proxyId = i;
|
||||
m_proxies[node->userData] = proxy;
|
||||
int proxyId = b3GetProxyId( node );
|
||||
proxy.proxyId = proxyId;
|
||||
m_proxies[m_tree.proxies[proxyId].userData] = proxy;
|
||||
}
|
||||
|
||||
printf( "max index = %d\n", maxAreaIndex );
|
||||
|
|
@ -363,7 +374,7 @@ public:
|
|||
{
|
||||
srand( 42 );
|
||||
|
||||
b3AABB bounds = m_tree.nodes[m_tree.root].aabb;
|
||||
b3AABB bounds = m_tree.nodes[B3_ROOT_NODE].aabb;
|
||||
b3Vec3 extents = b3AABB_Extents( bounds );
|
||||
float radius = ( extents.x + extents.y + extents.z ) / 3.0f;
|
||||
|
||||
|
|
@ -509,13 +520,11 @@ public:
|
|||
b3_colorCoral, b3_colorCornflowerBlue, b3_colorCornsilk, b3_colorCrimson, b3_colorCyan,
|
||||
};
|
||||
|
||||
int capacity = m_tree.nodeCapacity;
|
||||
for ( int i = 0; i < capacity; ++i )
|
||||
for ( int i = 0; i < m_tree.nodeEnd; ++i )
|
||||
{
|
||||
b3TreeNode* node = nodes + i;
|
||||
if ( m_depths[i] != m_drawLevel || ( node->flags & b3_allocatedNode ) == 0 )
|
||||
if ( m_depths[i] != m_drawLevel || b3IsEmptyNode( node ) )
|
||||
{
|
||||
// skip internal nodes
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -528,12 +537,13 @@ public:
|
|||
}
|
||||
else
|
||||
{
|
||||
uint16_t requiredFlags = b3_allocatedNode | b3_leafNode;
|
||||
for ( int i = 0; i < m_tree.nodeCapacity; ++i )
|
||||
// Live leaves only. A mark on a leaf says its ancestors still need a refit, the
|
||||
// leaf box itself is already current, so moved leaves still draw.
|
||||
for ( int i = 0; i < m_tree.nodeEnd; ++i )
|
||||
{
|
||||
b3TreeNode* node = nodes + i;
|
||||
|
||||
if ( node->flags != requiredFlags )
|
||||
if ( b3IsEmptyNode( node ) || b3IsLeaf( node ) == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
|
@ -544,7 +554,7 @@ public:
|
|||
continue;
|
||||
}
|
||||
|
||||
Proxy& proxy = m_proxies[node->userData];
|
||||
Proxy& proxy = m_proxies[m_tree.proxies[b3GetProxyId( node )].userData];
|
||||
if ( proxy.queryTimeStamp == m_timeStamp || proxy.rayTimeStamp == m_timeStamp )
|
||||
{
|
||||
DrawBounds( node->aabb, 0.0f, MakeColor( b3_colorLightGray ) );
|
||||
|
|
|
|||
|
|
@ -1000,3 +1000,316 @@ void CreateConvexPile( b3WorldId worldId )
|
|||
|
||||
b3DestroyHull( convex );
|
||||
}
|
||||
|
||||
#define SPINNER_SEGMENT_COUNT 90
|
||||
|
||||
typedef struct
|
||||
{
|
||||
b3MeshData* cylinderMesh;
|
||||
b3JointId spinnerId;
|
||||
} SpinnerData;
|
||||
|
||||
static SpinnerData g_spinnerData;
|
||||
|
||||
// An inward facing cylinder capped on both ends, axis along z. Every triangle is wound so its
|
||||
// normal points at the axis, which is what holds the contents in. The caps do the same job along
|
||||
// the axis that the 2D loop had for free.
|
||||
static b3MeshData* CreateInwardCylinderMesh( float radius, float halfDepth, float yCenter, int segmentCount )
|
||||
{
|
||||
int vertexCount = 2 * segmentCount + 2;
|
||||
int triangleCount = 4 * segmentCount;
|
||||
|
||||
b3Vec3* vertices = malloc( vertexCount * sizeof( b3Vec3 ) );
|
||||
int* indices = malloc( 3 * triangleCount * sizeof( int ) );
|
||||
|
||||
for ( int i = 0; i < segmentCount; ++i )
|
||||
{
|
||||
float angle = 2.0f * B3_PI * (float)i / (float)segmentCount;
|
||||
b3CosSin cs = b3ComputeCosSin( angle );
|
||||
float x = radius * cs.cosine;
|
||||
float y = radius * cs.sine + yCenter;
|
||||
vertices[2 * i + 0] = (b3Vec3){ x, y, -halfDepth };
|
||||
vertices[2 * i + 1] = (b3Vec3){ x, y, halfDepth };
|
||||
}
|
||||
|
||||
int centerNegative = 2 * segmentCount;
|
||||
int centerPositive = 2 * segmentCount + 1;
|
||||
vertices[centerNegative] = (b3Vec3){ 0.0f, yCenter, -halfDepth };
|
||||
vertices[centerPositive] = (b3Vec3){ 0.0f, yCenter, halfDepth };
|
||||
|
||||
int index = 0;
|
||||
for ( int i = 0; i < segmentCount; ++i )
|
||||
{
|
||||
int j = ( i + 1 ) % segmentCount;
|
||||
|
||||
// Wall, normal towards the axis
|
||||
indices[index++] = 2 * i + 0;
|
||||
indices[index++] = 2 * i + 1;
|
||||
indices[index++] = 2 * j + 1;
|
||||
|
||||
indices[index++] = 2 * i + 0;
|
||||
indices[index++] = 2 * j + 1;
|
||||
indices[index++] = 2 * j + 0;
|
||||
|
||||
// Near cap, normal towards positive z
|
||||
indices[index++] = centerNegative;
|
||||
indices[index++] = 2 * i + 0;
|
||||
indices[index++] = 2 * j + 0;
|
||||
|
||||
// Far cap, normal towards negative z
|
||||
indices[index++] = centerPositive;
|
||||
indices[index++] = 2 * j + 1;
|
||||
indices[index++] = 2 * i + 1;
|
||||
}
|
||||
|
||||
assert( index == 3 * triangleCount );
|
||||
|
||||
b3MeshDef meshDef = { 0 };
|
||||
meshDef.vertices = vertices;
|
||||
meshDef.vertexCount = vertexCount;
|
||||
meshDef.indices = indices;
|
||||
meshDef.triangleCount = triangleCount;
|
||||
meshDef.identifyEdges = true;
|
||||
|
||||
b3MeshData* meshData = b3CreateMesh( &meshDef, NULL, 0 );
|
||||
|
||||
free( vertices );
|
||||
free( indices );
|
||||
|
||||
return meshData;
|
||||
}
|
||||
|
||||
void GetSpinnerCapacity( b3Capacity* capacity )
|
||||
{
|
||||
capacity->staticShapeCount = 4;
|
||||
capacity->staticBodyCount = 4;
|
||||
capacity->dynamicShapeCount = 2000;
|
||||
capacity->dynamicBodyCount = 2000;
|
||||
capacity->contactCount = 20000;
|
||||
}
|
||||
|
||||
// A paddle on a motor churning a pile of small shapes inside a closed cylinder. The cylinder axis
|
||||
// is z so the cross section matches the 2D benchmark and the hinge, which turns about the local
|
||||
// frame z axis, lines up with it. The paddle circle is internally tangent to the cylinder at the
|
||||
// bottom, so the tip scrapes the floor.
|
||||
void CreateSpinner( b3WorldId worldId )
|
||||
{
|
||||
g_spinnerData = (SpinnerData){ 0 };
|
||||
|
||||
float radius = 12.0f;
|
||||
float halfDepth = 1.0f;
|
||||
float yCenter = radius;
|
||||
|
||||
b3BodyId groundId;
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
groundId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
g_spinnerData.cylinderMesh = CreateInwardCylinderMesh( radius, halfDepth, yCenter, SPINNER_SEGMENT_COUNT );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 0.1f;
|
||||
b3CreateMeshShape( groundId, &shapeDef, g_spinnerData.cylinderMesh, b3Vec3_one );
|
||||
}
|
||||
|
||||
{
|
||||
float halfLength = 0.5f * radius;
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.position = (b3Pos){ 0.0f, yCenter - halfLength, 0.0f };
|
||||
bodyDef.enableSleep = false;
|
||||
|
||||
b3BodyId spinnerId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
b3BoxHull paddle = b3MakeBoxHull( 0.3f, halfLength + 0.1f, halfDepth + 0.1f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 0.0f;
|
||||
b3CreateHullShape( spinnerId, &shapeDef, &paddle.base );
|
||||
|
||||
b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef();
|
||||
jointDef.base.bodyIdA = groundId;
|
||||
jointDef.base.bodyIdB = spinnerId;
|
||||
jointDef.base.localFrameA.p = (b3Vec3){ 0.0f, yCenter - halfLength, 0.0f };
|
||||
jointDef.enableMotor = true;
|
||||
jointDef.motorSpeed = 8.0f;
|
||||
jointDef.maxMotorTorque = FLT_MAX;
|
||||
|
||||
g_spinnerData.spinnerId = b3CreateRevoluteJoint( worldId, &jointDef );
|
||||
}
|
||||
|
||||
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.2f };
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = 0.1f;
|
||||
shapeDef.baseMaterial.restitution = 0.1f;
|
||||
shapeDef.density = 0.25f;
|
||||
|
||||
int bodyCount = BENCHMARK_DEBUG ? 500 : 1500;
|
||||
|
||||
// The grid starts low where the cylinder is narrow, so the span has to fit the chord there
|
||||
float spacing = 0.55f;
|
||||
float yStart = 2.0f;
|
||||
float chordHalfWidth = sqrtf( radius * radius - ( yCenter - yStart ) * ( yCenter - yStart ) );
|
||||
float xLimit = chordHalfWidth - 2.0f * spacing;
|
||||
float zLimit = halfDepth - 2.0f * sphere.radius;
|
||||
|
||||
float x = -xLimit;
|
||||
float y = yStart;
|
||||
float z = -zLimit;
|
||||
|
||||
for ( int i = 0; i < bodyCount; ++i )
|
||||
{
|
||||
bodyDef.position = (b3Pos){ x, y, z };
|
||||
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
|
||||
|
||||
z += spacing;
|
||||
|
||||
if ( z > zLimit )
|
||||
{
|
||||
z = -zLimit;
|
||||
x += spacing;
|
||||
|
||||
if ( x > xLimit )
|
||||
{
|
||||
x = -xLimit;
|
||||
y += spacing;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DestroySpinner( void )
|
||||
{
|
||||
if ( g_spinnerData.cylinderMesh != NULL )
|
||||
{
|
||||
b3DestroyMesh( g_spinnerData.cylinderMesh );
|
||||
g_spinnerData.cylinderMesh = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
// The motor is unbounded, so a healthy run holds the commanded speed and the angle advances
|
||||
// steadily. A stalling solver shows up here before it shows up in the step time.
|
||||
float GetSpinnerAngle( void )
|
||||
{
|
||||
if ( b3Joint_IsValid( g_spinnerData.spinnerId ) == false )
|
||||
{
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
return b3RevoluteJoint_GetAngle( g_spinnerData.spinnerId );
|
||||
}
|
||||
|
||||
#define SLEEP_PYRAMID_COUNT 10
|
||||
|
||||
typedef struct
|
||||
{
|
||||
b3BodyId bodyIdA[SLEEP_PYRAMID_COUNT];
|
||||
b3BodyId bodyIdB[SLEEP_PYRAMID_COUNT];
|
||||
} SleepData;
|
||||
|
||||
static SleepData g_sleepData;
|
||||
|
||||
// Reports two bodies that are certain to share a touching contact, so the filter joint below
|
||||
// always lands inside one island.
|
||||
static void CreateSleepPyramid( b3WorldId worldId, int baseCount, float extent, float centerX, b3BodyId* bodyIdA,
|
||||
b3BodyId* bodyIdB )
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.sleepThreshold = 1.0f;
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3BoxHull box = b3MakeBoxHull( extent, extent, extent );
|
||||
|
||||
for ( int i = 0; i < baseCount; ++i )
|
||||
{
|
||||
float y = ( 2.0f * i + 1.0f ) * extent;
|
||||
|
||||
for ( int j = i; j < baseCount; ++j )
|
||||
{
|
||||
float x = ( i + 1.0f ) * extent + 2.0f * ( j - i ) * extent + centerX;
|
||||
bodyDef.position = (b3Pos){ x, y, 0.0f };
|
||||
|
||||
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
b3CreateHullShape( bodyId, &shapeDef, &box.base );
|
||||
|
||||
if ( i == 0 && j == 0 )
|
||||
{
|
||||
*bodyIdA = bodyId;
|
||||
}
|
||||
else if ( i == 1 && j == 1 )
|
||||
{
|
||||
// Rests on the base body above, so the pair always has a touching contact
|
||||
*bodyIdB = bodyId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GetSleepCapacity( b3Capacity* capacity )
|
||||
{
|
||||
capacity->staticShapeCount = 4;
|
||||
capacity->staticBodyCount = 4;
|
||||
capacity->dynamicShapeCount = 2200;
|
||||
capacity->dynamicBodyCount = 2200;
|
||||
capacity->contactCount = 12000;
|
||||
}
|
||||
|
||||
// Stress tests waking and sleeping. Each pyramid settles into its own island and the step below
|
||||
// wakes one of them again, so the island splitter never gets to rest.
|
||||
void CreateSleep( b3WorldId worldId )
|
||||
{
|
||||
g_sleepData = (SleepData){ 0 };
|
||||
|
||||
int baseCount = BENCHMARK_DEBUG ? 8 : 20;
|
||||
float extent = 0.5f;
|
||||
|
||||
float baseWidth = 2.0f * extent * baseCount;
|
||||
float pitch = baseWidth + 8.0f * extent;
|
||||
float span = pitch * ( SLEEP_PYRAMID_COUNT - 1 );
|
||||
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.position = (b3Pos){ 0.0f, -1.0f, 0.0f };
|
||||
b3BodyId groundId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 0.5f * span + baseWidth, 1.0f, 4.0f );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
g_groundShapeId = b3CreateHullShape( groundId, &shapeDef, &box.base );
|
||||
}
|
||||
|
||||
for ( int i = 0; i < SLEEP_PYRAMID_COUNT; ++i )
|
||||
{
|
||||
float centerX = -0.5f * span + i * pitch - 0.5f * baseWidth;
|
||||
CreateSleepPyramid( worldId, baseCount, extent, centerX, g_sleepData.bodyIdA + i, g_sleepData.bodyIdB + i );
|
||||
}
|
||||
}
|
||||
|
||||
void StepSleep( b3WorldId worldId, int stepCount )
|
||||
{
|
||||
(void)stepCount;
|
||||
|
||||
for ( int i = 0; i < SLEEP_PYRAMID_COUNT; ++i )
|
||||
{
|
||||
if ( b3Body_IsAwake( g_sleepData.bodyIdA[i] ) == false )
|
||||
{
|
||||
// Creating and destroying a joint engages the island splitter
|
||||
b3FilterJointDef jointDef = b3DefaultFilterJointDef();
|
||||
jointDef.base.bodyIdA = g_sleepData.bodyIdA[i];
|
||||
jointDef.base.bodyIdB = g_sleepData.bodyIdB[i];
|
||||
b3JointId jointId = b3CreateFilterJoint( worldId, &jointDef );
|
||||
|
||||
// This wakes the island
|
||||
b3DestroyJoint( jointId, true );
|
||||
|
||||
// Only one per step
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,9 +42,14 @@ void GetWasherCapacity( b3Capacity* capacity );
|
|||
void CreateWasher( b3WorldId worldId );
|
||||
void CreateConvexPile( b3WorldId worldId );
|
||||
void GetConvexPileCapacity( b3Capacity* capacity );
|
||||
void GetSpinnerCapacity( b3Capacity* capacity );
|
||||
void CreateSpinner( b3WorldId worldId );
|
||||
void DestroySpinner( void );
|
||||
float GetSpinnerAngle( void );
|
||||
void GetSleepCapacity( b3Capacity* capacity );
|
||||
void CreateSleep( b3WorldId worldId );
|
||||
void StepSleep( b3WorldId worldId, int stepCount );
|
||||
|
||||
// void CreateSpinner( b3WorldId worldId );
|
||||
// float StepSpinner( b3WorldId worldId, int stepCount );
|
||||
// void CreateSmash( b3WorldId worldId );
|
||||
// void CreateTumbler( b3WorldId worldId );
|
||||
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ set(BOX3D_SOURCE_FILES
|
|||
distance.c
|
||||
distance_joint.c
|
||||
dynamic_tree.c
|
||||
dynamic_tree.h
|
||||
height_field.c
|
||||
hull.c
|
||||
hull.h
|
||||
|
|
|
|||
|
|
@ -375,6 +375,12 @@ void b3DestroyBody( b3BodyId bodyId )
|
|||
{
|
||||
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
|
||||
|
||||
if ( shape->type == b3_compoundShape )
|
||||
{
|
||||
B3_ASSERT( world->compoundShapeCount > 0 );
|
||||
world->compoundShapeCount -= 1;
|
||||
}
|
||||
|
||||
if ( shape->sensorIndex != B3_NULL_INDEX )
|
||||
{
|
||||
b3DestroySensor( world, shape );
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -3,16 +3,13 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include "bitset.h"
|
||||
#include "container.h"
|
||||
#include "dynamic_tree.h"
|
||||
#include "table.h"
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "box3d/types.h"
|
||||
|
||||
typedef struct b3Shape b3Shape;
|
||||
typedef struct b3MovePair b3MovePair;
|
||||
typedef struct b3MoveResult b3MoveResult;
|
||||
typedef struct b3Stack b3Stack;
|
||||
typedef struct b3World b3World;
|
||||
|
||||
|
|
@ -26,20 +23,11 @@ typedef struct b3World b3World;
|
|||
/// It is up to the client to consume the new pairs and to track subsequent overlap.
|
||||
typedef struct b3BroadPhase
|
||||
{
|
||||
// One tree for each body type.
|
||||
b3DynamicTree trees[b3_bodyTypeCount];
|
||||
|
||||
// Per body-type bit sets indexed by proxyId, marking proxies moved this step.
|
||||
// Paired with moveArray which preserves deterministic insertion order for pair queries.
|
||||
b3BitSet movedProxies[b3_bodyTypeCount];
|
||||
b3Array( int ) moveArray;
|
||||
|
||||
// These are the results from the pair query and are used to create new contacts
|
||||
// in deterministic order.
|
||||
// todo these could be in the step context
|
||||
b3MoveResult* moveResults;
|
||||
b3MovePair* movePairs;
|
||||
int movePairCapacity;
|
||||
b3AtomicInt movePairIndex;
|
||||
// The moved siblings gathered from the dynamic body tree.
|
||||
int* movedSiblings;
|
||||
|
||||
// Tracks shape pairs that have a b3Contact
|
||||
// todo pairSet can grow quite large on the first time step and remain large
|
||||
|
|
@ -54,7 +42,6 @@ int b3BroadPhase_CreateProxy( b3BroadPhase* bp, b3BodyType proxyType, b3AABB aab
|
|||
void b3BroadPhase_DestroyProxy( b3BroadPhase* bp, int proxyKey );
|
||||
|
||||
void b3BroadPhase_MoveProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb );
|
||||
void b3BroadPhase_EnlargeProxy( b3BroadPhase* bp, int proxyKey, b3AABB aabb );
|
||||
|
||||
int b3BroadPhase_GetShapeIndex( b3BroadPhase* bp, int proxyKey );
|
||||
|
||||
|
|
@ -62,18 +49,18 @@ void b3UpdateBroadPhasePairs( b3World* world );
|
|||
bool b3BroadPhase_TestOverlap( const b3BroadPhase* bp, int proxyKeyA, int proxyKeyB );
|
||||
|
||||
void b3ValidateBroadPhase( const b3BroadPhase* bp );
|
||||
void b3ValidateNoEnlarged( const b3BroadPhase* bp );
|
||||
void b3ValidateNoMoved( const b3BroadPhase* bp );
|
||||
|
||||
// This is what triggers new contact pairs to be created
|
||||
// Warning: this must be called in deterministic order
|
||||
static inline void b3BufferMove( b3BroadPhase* bp, int queryProxy )
|
||||
static inline void b3BroadPhase_MarkProxyMovedSerial( b3BroadPhase* bp, int proxyKey )
|
||||
{
|
||||
b3BodyType proxyType = B3_PROXY_TYPE( queryProxy );
|
||||
int proxyId = B3_PROXY_ID( queryProxy );
|
||||
b3BitSet* set = &bp->movedProxies[proxyType];
|
||||
if ( b3GetBit( set, proxyId ) == false )
|
||||
{
|
||||
b3SetBitGrow( set, proxyId );
|
||||
b3Array_Push( bp->moveArray, queryProxy );
|
||||
}
|
||||
b3BodyType proxyType = B3_PROXY_TYPE( proxyKey );
|
||||
int proxyId = B3_PROXY_ID( proxyKey );
|
||||
b3DynamicTree_MarkProxyMovedSerial( bp->trees + proxyType, proxyId );
|
||||
}
|
||||
|
||||
static inline void b3BroadPhase_MarkProxyMoved( b3BroadPhase* bp, int proxyKey, b3AABB aabb )
|
||||
{
|
||||
b3BodyType proxyType = B3_PROXY_TYPE( proxyKey );
|
||||
int proxyId = B3_PROXY_ID( proxyKey );
|
||||
b3DynamicTree_MarkProxyMoved( bp->trees + proxyType, proxyId, aabb );
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
|
||||
#include "compound.h"
|
||||
|
||||
#include "dynamic_tree.h"
|
||||
#include "hull.h"
|
||||
#include "math_internal.h"
|
||||
#include "shape.h"
|
||||
|
|
@ -52,6 +53,16 @@ static inline b3TreeNode* b3GetCompoundNodes( b3CompoundData* compound )
|
|||
return (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset );
|
||||
}
|
||||
|
||||
static inline b3TreeProxy* b3GetCompoundProxies( b3CompoundData* compound )
|
||||
{
|
||||
if ( compound->proxyOffset == 0 )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return (b3TreeProxy*)( (intptr_t)compound + compound->proxyOffset );
|
||||
}
|
||||
|
||||
const b3SurfaceMaterial* b3GetCompoundMaterials( const b3CompoundData* compound )
|
||||
{
|
||||
if ( compound->materialOffset == 0 )
|
||||
|
|
@ -274,13 +285,13 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
|
||||
// Instances
|
||||
int capsuleCount = def->capsuleCount;
|
||||
b3CompoundCapsule* capsuleInstances = b3AllocZeroed( capsuleCount * sizeof( b3CompoundCapsule ) );
|
||||
b3CompoundCapsule* capsuleInstances = b3AllocZero( capsuleCount * sizeof( b3CompoundCapsule ) );
|
||||
int hullCount = def->hullCount;
|
||||
b3HullInstance* hullInstances = b3AllocZeroed( hullCount * sizeof( b3HullInstance ) );
|
||||
b3HullInstance* hullInstances = b3AllocZero( hullCount * sizeof( b3HullInstance ) );
|
||||
int meshCount = def->meshCount;
|
||||
b3MeshInstance* meshInstances = b3AllocZeroed( meshCount * sizeof( b3MeshInstance ) );
|
||||
b3MeshInstance* meshInstances = b3AllocZero( meshCount * sizeof( b3MeshInstance ) );
|
||||
int sphereCount = def->sphereCount;
|
||||
b3CompoundSphere* sphereInstances = b3AllocZeroed( sphereCount * sizeof( b3CompoundSphere ) );
|
||||
b3CompoundSphere* sphereInstances = b3AllocZero( sphereCount * sizeof( b3CompoundSphere ) );
|
||||
|
||||
// Determine material capacity.
|
||||
int materialCapacity = convexCount;
|
||||
|
|
@ -294,7 +305,7 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
b3MaterialMap materialMap;
|
||||
b3MaterialMap_init( &materialMap );
|
||||
b3MaterialMap_reserve( &materialMap, materialCapacity );
|
||||
b3SurfaceMaterial* materials = b3AllocZeroed( materialCapacity * sizeof( b3SurfaceMaterial ) );
|
||||
b3SurfaceMaterial* materials = b3AllocZero( materialCapacity * sizeof( b3SurfaceMaterial ) );
|
||||
int materialCount = 0;
|
||||
|
||||
for ( int i = 0; i < def->capsuleCount; ++i )
|
||||
|
|
@ -322,7 +333,7 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
}
|
||||
|
||||
// Hulls
|
||||
b3SharedHull* sharedHulls = b3AllocZeroed( hullCount * sizeof( b3SharedHull ) );
|
||||
b3SharedHull* sharedHulls = b3AllocZero( hullCount * sizeof( b3SharedHull ) );
|
||||
int sharedHullCount = 0;
|
||||
|
||||
if ( hullCount > 0 )
|
||||
|
|
@ -378,7 +389,7 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
}
|
||||
|
||||
// Meshes
|
||||
b3SharedMesh* sharedMeshes = b3AllocZeroed( meshCount * sizeof( b3SharedMesh ) );
|
||||
b3SharedMesh* sharedMeshes = b3AllocZero( meshCount * sizeof( b3SharedMesh ) );
|
||||
int sharedMeshCount = 0;
|
||||
|
||||
if ( meshCount > 0 )
|
||||
|
|
@ -471,14 +482,16 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
}
|
||||
|
||||
B3_ASSERT( materialCount <= materialCapacity );
|
||||
B3_ASSERT( tree.nodeCount > 0 );
|
||||
B3_ASSERT( tree.proxyCount > 0 );
|
||||
|
||||
b3DynamicTree_Rebuild( &tree, true );
|
||||
|
||||
// Tree nodes
|
||||
// Tree nodes and proxies. The rebuild is dense, so only the live nodes travel.
|
||||
size_t byteCount = b3AlignUp8( sizeof( b3CompoundData ) );
|
||||
int nodeOffset = (int)byteCount;
|
||||
byteCount += b3AlignUp8( tree.nodeCapacity * sizeof( b3TreeNode ) );
|
||||
byteCount += b3AlignUp8( tree.nodeEnd * sizeof( b3TreeNode ) );
|
||||
int proxyOffset = (int)byteCount;
|
||||
byteCount += b3AlignUp8( tree.proxyCount * sizeof( b3TreeProxy ) );
|
||||
int materialOffset = (int)byteCount;
|
||||
byteCount += b3AlignUp8( materialCount * sizeof( b3SurfaceMaterial ) );
|
||||
int capsuleOffset = (int)byteCount;
|
||||
|
|
@ -525,17 +538,25 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
compound->version = B3_COMPOUND_VERSION;
|
||||
compound->byteCount = (int)byteCount;
|
||||
compound->nodeOffset = nodeOffset;
|
||||
compound->proxyOffset = proxyOffset;
|
||||
memcpy( &compound->tree, &tree, sizeof( b3DynamicTree ) );
|
||||
|
||||
// todo clean up this mess
|
||||
compound->tree.freeList = 0;
|
||||
compound->tree.nodeCapacity = tree.nodeEnd;
|
||||
compound->tree.pairFreeList = B3_NULL_INDEX;
|
||||
compound->tree.proxyCapacity = tree.proxyCount;
|
||||
compound->tree.proxyFreeList = B3_NULL_INDEX;
|
||||
compound->tree.swapNodes = NULL;
|
||||
compound->tree.leafIndices = NULL;
|
||||
compound->tree.leafNodes = NULL;
|
||||
compound->tree.leafBoxes = NULL;
|
||||
compound->tree.leafCenters = NULL;
|
||||
compound->tree.binIndices = NULL;
|
||||
compound->tree.rebuildCapacity = 0;
|
||||
|
||||
compound->tree.nodes = NULL;
|
||||
compound->tree.parents = NULL;
|
||||
compound->tree.proxies = NULL;
|
||||
compound->materialOffset = materialOffset;
|
||||
compound->materialCount = materialCount;
|
||||
compound->capsuleOffset = capsuleOffset;
|
||||
|
|
@ -547,11 +568,15 @@ b3CompoundData* b3CreateCompound( const b3CompoundDef* def )
|
|||
compound->sphereOffset = sphereOffset;
|
||||
compound->sphereCount = sphereCount;
|
||||
|
||||
// Tree nodes
|
||||
// Tree nodes and proxies
|
||||
b3TreeNode* nodes = b3GetCompoundNodes( compound );
|
||||
memcpy( nodes, tree.nodes, tree.nodeCapacity * sizeof( b3TreeNode ) );
|
||||
memcpy( nodes, tree.nodes, tree.nodeEnd * sizeof( b3TreeNode ) );
|
||||
compound->tree.nodes = nodes;
|
||||
|
||||
b3TreeProxy* proxies = b3GetCompoundProxies( compound );
|
||||
memcpy( proxies, tree.proxies, tree.proxyCount * sizeof( b3TreeProxy ) );
|
||||
compound->tree.proxies = proxies;
|
||||
|
||||
// Materials
|
||||
B3_ASSERT( materialCount > 0 );
|
||||
b3SurfaceMaterial* destinationMaterials = (b3SurfaceMaterial*)( (intptr_t)compound + compound->materialOffset );
|
||||
|
|
@ -638,8 +663,9 @@ void b3DestroyCompound( b3CompoundData* compound )
|
|||
|
||||
uint8_t* b3ConvertCompoundToBytes( b3CompoundData* compound )
|
||||
{
|
||||
// scrub this pointer before serialization
|
||||
// scrub these pointers before serialization
|
||||
compound->tree.nodes = NULL;
|
||||
compound->tree.proxies = NULL;
|
||||
return (uint8_t*)compound;
|
||||
}
|
||||
|
||||
|
|
@ -661,13 +687,14 @@ b3CompoundData* b3ConvertBytesToCompound( uint8_t* bytes, int byteCount )
|
|||
return NULL;
|
||||
}
|
||||
|
||||
if ( compound->nodeOffset <= 0 )
|
||||
if ( compound->nodeOffset <= 0 || compound->proxyOffset <= 0 )
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// this mutates the input bytes
|
||||
compound->tree.nodes = (b3TreeNode*)( (intptr_t)compound + compound->nodeOffset );
|
||||
compound->tree.proxies = (b3TreeProxy*)( (intptr_t)compound + compound->proxyOffset );
|
||||
return compound;
|
||||
}
|
||||
|
||||
|
|
@ -676,8 +703,7 @@ b3AABB b3ComputeCompoundAABB( const b3CompoundData* shape, b3Transform transform
|
|||
B3_ASSERT( shape->nodeOffset > 0 );
|
||||
|
||||
const b3TreeNode* nodes = (const b3TreeNode*)( (intptr_t)shape + shape->nodeOffset );
|
||||
int root = shape->tree.root;
|
||||
b3AABB aabb = nodes[root].aabb;
|
||||
b3AABB aabb = nodes[B3_ROOT_NODE].aabb;
|
||||
return b3AABB_Transform( transform, aabb );
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -182,3 +182,4 @@ B3_INLINE int b3RemoveHelper( void* data, int* count, int index, int elementSize
|
|||
#define b3Array_ByteCount( a ) ( ( a ).capacity * (int)sizeof( *( a ).data ) )
|
||||
|
||||
b3DeclareArrayNative( int );
|
||||
b3DeclareArrayNative( uint64_t );
|
||||
|
|
|
|||
|
|
@ -230,12 +230,19 @@ void* b3GrowAlloc( void* oldMem, int oldSize, int newSize )
|
|||
return newMem;
|
||||
}
|
||||
|
||||
void* b3GrowAllocZeroed( void* oldMem, int oldSize, int newSize )
|
||||
{
|
||||
void* newMem = b3GrowAlloc( oldMem, oldSize, newSize );
|
||||
memset( (char*)newMem + oldSize, 0, (size_t)( newSize - oldSize ) );
|
||||
return newMem;
|
||||
}
|
||||
|
||||
int b3GetByteCount( void )
|
||||
{
|
||||
return b3AtomicLoadInt( &b3_byteCount );
|
||||
}
|
||||
|
||||
void* b3AllocZeroed( size_t size )
|
||||
void* b3AllocZero( size_t size )
|
||||
{
|
||||
void* mem = b3Alloc( size );
|
||||
memset( mem, 0, size );
|
||||
|
|
|
|||
|
|
@ -133,9 +133,13 @@ typedef struct b3AtomicU32
|
|||
#define B3_FREE( M, T, N ) b3Free( M, N * sizeof( T ) );
|
||||
|
||||
void* b3Alloc( size_t size );
|
||||
void* b3AllocZeroed( size_t size );
|
||||
void* b3AllocZero( size_t size );
|
||||
void b3Free( void* mem, size_t size );
|
||||
void* b3GrowAlloc( void* oldMem, int oldSize, int newSize );
|
||||
void* b3GrowAllocZeroed( void* oldMem, int oldSize, int newSize );
|
||||
|
||||
#define B3_GROW( A, N, M ) b3GrowAlloc( ( A ), (int)( ( N ) * sizeof( *( A ) ) ), (int)( ( M ) * sizeof( *( A ) ) ) )
|
||||
#define B3_GROW_ZERO( A, N, M ) b3GrowAllocZeroed( ( A ), (int)( ( N ) * sizeof( *( A ) ) ), (int)( ( M ) * sizeof( *( A ) ) ) )
|
||||
|
||||
B3_PRINTF_FORMAT( 1, 2 )
|
||||
void b3Log( const char* format, ... );
|
||||
|
|
|
|||
2384
src/dynamic_tree.c
2384
src/dynamic_tree.c
File diff suppressed because it is too large
Load diff
89
src/dynamic_tree.h
Normal file
89
src/dynamic_tree.h
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "box3d/math_functions.h"
|
||||
|
||||
#define B3_TREE_STACK_SIZE 512
|
||||
|
||||
// Used to mark a node as being moved such that pairs need to be generated and the tree
|
||||
// may need to be rebuilt. This mark comes from a few sources:
|
||||
// - updating the transform and AABB in the solver from movement
|
||||
// - a joint disabling collision
|
||||
// - creating a proxy
|
||||
// - setting the transform on a body
|
||||
|
||||
#define B3_MOVED_NODE ( 1u << 30 )
|
||||
#define B3_LEAF_NODE ( 1u << 31 )
|
||||
#define B3_NODE_INDEX_MASK ( 0xFFFFFFFFu & ~( B3_MOVED_NODE | B3_LEAF_NODE ) )
|
||||
|
||||
// Used to indicate empty nodes. It also passes as a leaf so that internal node
|
||||
// processing will naturally skip it.
|
||||
#define B3_EMPTY_NODE ( B3_NODE_INDEX_MASK | B3_LEAF_NODE )
|
||||
|
||||
#define B3_ROOT_NODE 0
|
||||
|
||||
B3_FORCE_INLINE bool b3IsLeaf( const b3TreeNode* node )
|
||||
{
|
||||
return ( node->flagIndex & B3_LEAF_NODE ) == B3_LEAF_NODE;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3IsNodeMoved( const b3TreeNode* node )
|
||||
{
|
||||
return ( node->flagIndex & B3_MOVED_NODE ) == B3_MOVED_NODE;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3IsEmptyNode( const b3TreeNode* node )
|
||||
{
|
||||
return node->flagIndex == B3_EMPTY_NODE;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE int b3GetLeftChild( const b3TreeNode* node )
|
||||
{
|
||||
return (int)( node->flagIndex & B3_NODE_INDEX_MASK );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE int b3GetProxyId( const b3TreeNode* node )
|
||||
{
|
||||
return (int)( node->flagIndex & B3_NODE_INDEX_MASK );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE int b3GetRootPair( const b3TreeNode* nodes )
|
||||
{
|
||||
const b3TreeNode* root = nodes + B3_ROOT_NODE;
|
||||
return b3IsLeaf( root ) ? B3_ROOT_NODE : b3GetLeftChild( root );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3TreeNode b3MakeEmptyNode( void )
|
||||
{
|
||||
return B3_LITERAL( b3TreeNode ){
|
||||
.aabb =
|
||||
{
|
||||
.lowerBound = { INFINITY, INFINITY, INFINITY },
|
||||
.upperBound = { -INFINITY, -INFINITY, -INFINITY },
|
||||
},
|
||||
.flagIndex = B3_EMPTY_NODE,
|
||||
.height = 0,
|
||||
};
|
||||
}
|
||||
|
||||
static inline bool b3HasTreeMoved( const b3DynamicTree* tree )
|
||||
{
|
||||
return b3IsNodeMoved( tree->nodes + B3_ROOT_NODE );
|
||||
}
|
||||
|
||||
static inline bool b3NeedsRebuild( const b3DynamicTree* tree )
|
||||
{
|
||||
return b3IsNodeMoved( tree->nodes + B3_ROOT_NODE ) || tree->dfsOrdered == false;
|
||||
}
|
||||
|
||||
int b3CreateTreeProxyInternal( b3DynamicTree* tree, b3AABB aabb, uint64_t categoryBits, uint64_t userData, bool markMoved );
|
||||
void b3DynamicTree_MoveProxyInternal( b3DynamicTree* tree, int proxyId, b3AABB aabb, bool markMoved );
|
||||
|
||||
void b3DynamicTree_MarkProxyMovedSerial( b3DynamicTree* tree, int proxyId );
|
||||
void b3DynamicTree_MarkProxyMoved( b3DynamicTree* tree, int proxyId, b3AABB aabb );
|
||||
void b3DynamicTree_ClearMoved( b3DynamicTree* tree );
|
||||
int b3DynamicTree_GatherMovedProxies( const b3DynamicTree* tree, int* proxyIds );
|
||||
void b3DynamicTree_Refit( b3DynamicTree* tree );
|
||||
|
|
@ -953,7 +953,7 @@ void b3Joint_SetCollideConnected( b3JointId jointId, bool shouldCollide )
|
|||
|
||||
if ( shape->proxyKey != B3_NULL_INDEX )
|
||||
{
|
||||
b3BufferMove( &world->broadPhase, shape->proxyKey );
|
||||
b3BroadPhase_MarkProxyMovedSerial( &world->broadPhase, shape->proxyKey );
|
||||
}
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
|
|
|
|||
|
|
@ -78,6 +78,8 @@ void b3ParallelFor( b3World* world, b3ParallelForCallback* callback, int itemCou
|
|||
// block size grows once items exceed maxBlockCount * minRange
|
||||
// so the block count stays bounded and per-block sync overhead stays low.
|
||||
// Benchmarking shows 32 is optimal for the convex pile benchmark and others.
|
||||
// This is a lot different than Box2D because the 3D narrow phase cost
|
||||
// varies a lot.
|
||||
int blocksPerWorker = 32;
|
||||
int maxBlockCount = blocksPerWorker * workerCount;
|
||||
|
||||
|
|
|
|||
|
|
@ -175,11 +175,11 @@ static void b3CreateWorkerContexts( b3World* world )
|
|||
{
|
||||
world->taskContexts.data[i].arena = b3CreateArena( 128 * 1024 );
|
||||
b3Array_Reserve( world->taskContexts.data[i].sensorHits, 8 );
|
||||
b3Array_Reserve( world->taskContexts.data[i].pairKeys, 64 );
|
||||
world->taskContexts.data[i].contactStateBitSet = b3CreateBitSet( 1024 );
|
||||
world->taskContexts.data[i].hitEventBitSet = b3CreateBitSet( 1024 );
|
||||
world->taskContexts.data[i].hasHitEvents = false;
|
||||
world->taskContexts.data[i].jointStateBitSet = b3CreateBitSet( 1024 );
|
||||
world->taskContexts.data[i].enlargedSimBitSet = b3CreateBitSet( 256 );
|
||||
world->taskContexts.data[i].awakeIslandBitSet = b3CreateBitSet( 256 );
|
||||
world->taskContexts.data[i].splitIslandId = B3_NULL_INDEX;
|
||||
|
||||
|
|
@ -193,10 +193,10 @@ static void b3DestroyWorkerContexts( b3World* world )
|
|||
{
|
||||
b3DestroyArena( &world->taskContexts.data[i].arena );
|
||||
b3Array_Destroy( world->taskContexts.data[i].sensorHits );
|
||||
b3Array_Destroy( world->taskContexts.data[i].pairKeys );
|
||||
b3DestroyBitSet( &world->taskContexts.data[i].contactStateBitSet );
|
||||
b3DestroyBitSet( &world->taskContexts.data[i].hitEventBitSet );
|
||||
b3DestroyBitSet( &world->taskContexts.data[i].jointStateBitSet );
|
||||
b3DestroyBitSet( &world->taskContexts.data[i].enlargedSimBitSet );
|
||||
b3DestroyBitSet( &world->taskContexts.data[i].awakeIslandBitSet );
|
||||
|
||||
b3DestroyBitSet( &world->sensorTaskContexts.data[i].eventBits );
|
||||
|
|
@ -1148,7 +1148,7 @@ void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount )
|
|||
world->finishTaskFcn( world->userTreeTask, world->userTaskContext );
|
||||
world->userTreeTask = NULL;
|
||||
world->activeTaskCount -= 1;
|
||||
b3ValidateNoEnlarged( &world->broadPhase );
|
||||
b3ValidateNoMoved( &world->broadPhase );
|
||||
}
|
||||
|
||||
// Update sensors
|
||||
|
|
@ -2419,22 +2419,14 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
|
|||
int staticTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody );
|
||||
int kinematicTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_kinematicBody );
|
||||
int dynamicTreeBytes = b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_dynamicBody );
|
||||
int movedBytes = 0;
|
||||
for ( int i = 0; i < b3_bodyTypeCount; ++i )
|
||||
{
|
||||
movedBytes += b3GetBitSetBytes( &world->broadPhase.movedProxies[i] );
|
||||
}
|
||||
int moveArrayBytes = b3Array_ByteCount( world->broadPhase.moveArray );
|
||||
b3HashSet* pairSet = &world->broadPhase.pairSet;
|
||||
int pairSetBytes = b3GetHashSetBytes( pairSet );
|
||||
total += (uint64_t)staticTreeBytes + kinematicTreeBytes + dynamicTreeBytes + movedBytes + moveArrayBytes + pairSetBytes;
|
||||
total += (uint64_t)staticTreeBytes + kinematicTreeBytes + dynamicTreeBytes + pairSetBytes;
|
||||
|
||||
b3Log( "broad-phase" );
|
||||
b3Log( "static tree: %d", staticTreeBytes );
|
||||
b3Log( "kinematic tree: %d", kinematicTreeBytes );
|
||||
b3Log( "dynamic tree: %d", dynamicTreeBytes );
|
||||
b3Log( "movedProxies: %d", movedBytes );
|
||||
b3Log( "moveArray: %d", moveArrayBytes );
|
||||
b3Log( "pairSet: %d (%d, %d)", pairSetBytes, pairSet->count, pairSet->capacity );
|
||||
|
||||
// Manifold block allocators, one per manifold point count
|
||||
|
|
@ -2512,10 +2504,10 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
|
|||
{
|
||||
b3TaskContext* taskContext = world->taskContexts.data + i;
|
||||
taskContextBytes += b3Array_ByteCount( taskContext->sensorHits );
|
||||
taskContextBytes += b3Array_ByteCount( taskContext->pairKeys );
|
||||
taskContextBytes += b3GetBitSetBytes( &taskContext->contactStateBitSet );
|
||||
taskContextBytes += b3GetBitSetBytes( &taskContext->jointStateBitSet );
|
||||
taskContextBytes += b3GetBitSetBytes( &taskContext->hitEventBitSet );
|
||||
taskContextBytes += b3GetBitSetBytes( &taskContext->enlargedSimBitSet );
|
||||
taskContextBytes += b3GetBitSetBytes( &taskContext->awakeIslandBitSet );
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,6 +76,9 @@ typedef struct b3TaskContext
|
|||
// Collect per thread sensor continuous hit events.
|
||||
b3Array( b3SensorHit ) sensorHits;
|
||||
|
||||
// Broad-phase pairs.
|
||||
b3Array( uint64_t ) pairKeys;
|
||||
|
||||
// These bits align with the b3ConstraintGraph::contactBlocks and signal a change in contact status
|
||||
b3BitSet contactStateBitSet;
|
||||
|
||||
|
|
@ -88,10 +91,6 @@ typedef struct b3TaskContext
|
|||
// Fast-path flag: true when this worker set at least one bit in hitEventBitSet this step.
|
||||
bool hasHitEvents;
|
||||
|
||||
// Used to track bodies with shapes that have enlarged AABBs. This avoids having a bit array
|
||||
// that is very large when there are many static shapes.
|
||||
b3BitSet enlargedSimBitSet;
|
||||
|
||||
// Used to put islands to sleep
|
||||
b3BitSet awakeIslandBitSet;
|
||||
|
||||
|
|
@ -177,6 +176,10 @@ typedef struct b3World
|
|||
// These are sparse arrays that point into the pools above
|
||||
b3Array( b3Shape ) shapes;
|
||||
|
||||
// Compound shapes are static only, so only the broad-phase static pass can meet one. This
|
||||
// lets a world without compounds skip the shape type read in the pair batch.
|
||||
int compoundShapeCount;
|
||||
|
||||
// Reference counted store of shared hull data keyed by content. Shapes hold a
|
||||
// pointer to the hull stored in the db. Type erased to avoid leaking the verstable map
|
||||
// type into this header.
|
||||
|
|
|
|||
|
|
@ -12,6 +12,11 @@
|
|||
#include <intrin.h>
|
||||
#elif defined( _MSC_VER )
|
||||
#include <intrin0.h>
|
||||
// _MM_HINT_T0 lives here. Prefetch is a platform intrinsic, not part of the SIMD kernel
|
||||
// selection, so it has to survive a BOX3D_DISABLE_SIMD build.
|
||||
#if defined( _M_X64 ) || defined( _M_IX86 )
|
||||
#include <xmmintrin.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined( _MSC_VER )
|
||||
|
|
@ -104,3 +109,26 @@ static inline uint32_t b3AtomicLoadU32( b3AtomicU32* a )
|
|||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
// Relaxed load on a plain word. Lets a racing reader peek before paying for a read modify write.
|
||||
static inline uint32_t b3AtomicLoadU32Raw( uint32_t* a )
|
||||
{
|
||||
#if defined( _MSC_VER ) && !defined( __clang__ )
|
||||
return (uint32_t)__iso_volatile_load32( (volatile __int32*)a );
|
||||
#elif defined( __GNUC__ ) || defined( __clang__ )
|
||||
return __atomic_load_n( a, __ATOMIC_RELAXED );
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline uint32_t b3AtomicFetchOrU32( uint32_t* a, uint32_t mask )
|
||||
{
|
||||
#if defined( _MSC_VER )
|
||||
return (uint32_t)_InterlockedOr( (long*)a, (long)mask );
|
||||
#elif defined( __GNUC__ ) || defined( __clang__ )
|
||||
return __atomic_fetch_or( a, mask, __ATOMIC_SEQ_CST );
|
||||
#else
|
||||
#error "Unsupported platform"
|
||||
#endif
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,8 +51,8 @@ typedef struct b3World b3World;
|
|||
#define B3_REC_VERSION_MAJOR 6
|
||||
|
||||
// Minor tracks op-stream additions that keep the 48 byte header shape.
|
||||
// Minor version 4 added b3Shape_SetMeshMaterial, b3Shape_SetHull, b3Shape_SetMesh
|
||||
#define B3_REC_VERSION_MINOR 4
|
||||
// Minor version 6 moved the broad phase to the tree against tree pair traversal
|
||||
#define B3_REC_VERSION_MINOR 6
|
||||
|
||||
// File header, fixed 48 bytes. Contains the registry locator so the player
|
||||
// can load geometry before replaying any ops.
|
||||
|
|
|
|||
|
|
@ -192,6 +192,8 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
|
|||
|
||||
if ( shape->type == b3_compoundShape )
|
||||
{
|
||||
world->compoundShapeCount += 1;
|
||||
|
||||
// Own a copy of the compound materials so every shape frees its array the same way. Compounds
|
||||
// are few, so the copy is cheap and avoids aliasing the geometry blob.
|
||||
int materialCount = shape->compound->materialCount;
|
||||
|
|
@ -481,6 +483,12 @@ static void b3DestroyShapeInternal( b3World* world, b3Shape* shape, b3Body* body
|
|||
{
|
||||
int shapeId = shape->id;
|
||||
|
||||
if ( shape->type == b3_compoundShape )
|
||||
{
|
||||
B3_ASSERT( world->compoundShapeCount > 0 );
|
||||
world->compoundShapeCount -= 1;
|
||||
}
|
||||
|
||||
// Remove the shape from the body's doubly linked list.
|
||||
if ( shape->prevShapeId != B3_NULL_INDEX )
|
||||
{
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ typedef enum b3ShapeFlags
|
|||
b3_enableCustomFiltering = 0x04,
|
||||
b3_enableHitEvents = 0x08,
|
||||
b3_enablePreSolveEvents = 0x10,
|
||||
b3_enlargedAABB = 0x20,
|
||||
// 0x20 is free, it was the enlarged AABB flag before the broad-phase marked the tree
|
||||
b3_enableSpeculative = 0x40,
|
||||
} b3ShapeFlags;
|
||||
|
||||
|
|
|
|||
184
src/simd.h
184
src/simd.h
|
|
@ -5,6 +5,9 @@
|
|||
|
||||
#include "core.h"
|
||||
|
||||
#include "box3d/math_functions.h"
|
||||
#include "box3d/types.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#if defined( B3_SIMD_NEON )
|
||||
|
|
@ -921,3 +924,184 @@ static inline int b3MinIndexW( b3FloatW a, int bitCount )
|
|||
}
|
||||
|
||||
#endif
|
||||
|
||||
#if defined( B3_SIMD_NEON )
|
||||
|
||||
typedef struct b3AABBV
|
||||
{
|
||||
float32x4_t lower;
|
||||
float32x4_t upper;
|
||||
} b3AABBV;
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3LoadAABBV( const b3AABB* aabb )
|
||||
{
|
||||
const float* base = &aabb->lowerBound.x;
|
||||
|
||||
// Offset to avoid reading off the end (avoid UB).
|
||||
// [lz ux uy uz]
|
||||
float32x4_t v1 = vld1q_f32( base + 2 );
|
||||
b3AABBV result;
|
||||
// [lx ly lz -]
|
||||
result.lower = vld1q_f32( base );
|
||||
// [ux uy uz -]
|
||||
result.upper = vextq_f32( v1, v1, 1 );
|
||||
return result;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapAABBV( b3AABBV a, b3AABBV b )
|
||||
{
|
||||
static const uint32_t laneMask[4] = { 0, 0, 0, 0xFFFFFFFFu };
|
||||
uint32x4_t test = vandq_u32( vcleq_f32( a.lower, b.upper ), vcleq_f32( b.lower, a.upper ) );
|
||||
return vminvq_u32( vorrq_u32( test, vld1q_u32( laneMask ) ) ) != 0;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapNode( b3AABBV av, const b3TreeNode* node )
|
||||
{
|
||||
return b3OverlapAABBV( av, b3LoadAABBV( &node->aabb ) );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapV( const b3AABB* a, const b3AABB* b )
|
||||
{
|
||||
return b3OverlapAABBV( b3LoadAABBV( a ), b3LoadAABBV( b ) );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3UnionAABBV( b3AABBV a, b3AABBV b )
|
||||
{
|
||||
b3AABBV result;
|
||||
result.lower = vminq_f32( a.lower, b.lower );
|
||||
result.upper = vmaxq_f32( a.upper, b.upper );
|
||||
return result;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3UnionPairV( const b3TreeNode* pair )
|
||||
{
|
||||
return b3UnionAABBV( b3LoadAABBV( &pair[0].aabb ), b3LoadAABBV( &pair[1].aabb ) );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE void b3StoreAABBV( b3AABB* aabb, b3AABBV value, bool condition )
|
||||
{
|
||||
float32x4_t raw0 = vsetq_lane_f32( vgetq_lane_f32( value.upper, 0 ), value.lower, 3 );
|
||||
float32x4_t rotated = vextq_f32( value.upper, value.upper, 1 );
|
||||
float32x4_t raw1 = vcombine_f32( vget_high_f32( raw0 ), vget_low_f32( rotated ) );
|
||||
|
||||
float* base = &aabb->lowerBound.x;
|
||||
uint32x4_t mask = vdupq_n_u32( condition ? 0xFFFFFFFFu : 0u );
|
||||
vst1q_f32( base, vbslq_f32( mask, raw0, vld1q_f32( base ) ) );
|
||||
vst1q_f32( base + 2, vbslq_f32( mask, raw1, vld1q_f32( base + 2 ) ) );
|
||||
}
|
||||
|
||||
#elif defined( B3_SIMD_SSE2 )
|
||||
|
||||
typedef struct b3AABBV
|
||||
{
|
||||
__m128 lower;
|
||||
__m128 upper;
|
||||
} b3AABBV;
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3LoadAABBV( const b3AABB* aabb )
|
||||
{
|
||||
const float* base = &aabb->lowerBound.x;
|
||||
// Same offset as Neon to avoid UB.
|
||||
__m128 v1 = _mm_loadu_ps( base + 2 );
|
||||
b3AABBV result;
|
||||
result.lower = _mm_loadu_ps( base );
|
||||
result.upper = _mm_shuffle_ps( v1, v1, _MM_SHUFFLE( 3, 3, 2, 1 ) );
|
||||
return result;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapAABBV( b3AABBV a, b3AABBV b )
|
||||
{
|
||||
__m128 test = _mm_and_ps( _mm_cmple_ps( a.lower, b.upper ), _mm_cmple_ps( b.lower, a.upper ) );
|
||||
return ( _mm_movemask_ps( test ) & 0x7 ) == 0x7;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapNode( b3AABBV av, const b3TreeNode* node )
|
||||
{
|
||||
return b3OverlapAABBV( av, b3LoadAABBV( &node->aabb ) );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapV( const b3AABB* a, const b3AABB* b )
|
||||
{
|
||||
return b3OverlapAABBV( b3LoadAABBV( a ), b3LoadAABBV( b ) );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3UnionAABBV( b3AABBV a, b3AABBV b )
|
||||
{
|
||||
b3AABBV result;
|
||||
result.lower = _mm_min_ps( a.lower, b.lower );
|
||||
result.upper = _mm_max_ps( a.upper, b.upper );
|
||||
return result;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3UnionPairV( const b3TreeNode* pair )
|
||||
{
|
||||
return b3UnionAABBV( b3LoadAABBV( &pair[0].aabb ), b3LoadAABBV( &pair[1].aabb ) );
|
||||
}
|
||||
|
||||
// Conditionally store an AABB. Avoids a branch.
|
||||
B3_FORCE_INLINE void b3StoreAABBV( b3AABB* aabb, b3AABBV value, bool condition )
|
||||
{
|
||||
__m128 lane3 = _mm_castsi128_ps( _mm_set_epi32( -1, 0, 0, 0 ) );
|
||||
__m128 uxSplat = _mm_shuffle_ps( value.upper, value.upper, _MM_SHUFFLE( 0, 0, 0, 0 ) );
|
||||
__m128 raw0 = _mm_or_ps( _mm_andnot_ps( lane3, value.lower ), _mm_and_ps( lane3, uxSplat ) );
|
||||
__m128 raw1 = _mm_shuffle_ps( raw0, value.upper, _MM_SHUFFLE( 2, 1, 3, 2 ) );
|
||||
|
||||
float* base = &aabb->lowerBound.x;
|
||||
__m128 mask = _mm_castsi128_ps( _mm_set1_epi32( condition ? -1 : 0 ) );
|
||||
__m128 old0 = _mm_loadu_ps( base );
|
||||
__m128 old1 = _mm_loadu_ps( base + 2 );
|
||||
_mm_storeu_ps( base, _mm_or_ps( _mm_and_ps( mask, raw0 ), _mm_andnot_ps( mask, old0 ) ) );
|
||||
_mm_storeu_ps( base + 2, _mm_or_ps( _mm_and_ps( mask, raw1 ), _mm_andnot_ps( mask, old1 ) ) );
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
typedef b3AABB b3AABBV;
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3LoadAABBV( const b3AABB* aabb )
|
||||
{
|
||||
return *aabb;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapAABBV( b3AABBV a, b3AABBV b )
|
||||
{
|
||||
return a.lowerBound.x <= b.upperBound.x && a.lowerBound.y <= b.upperBound.y && a.lowerBound.z <= b.upperBound.z &&
|
||||
b.lowerBound.x <= a.upperBound.x && b.lowerBound.y <= a.upperBound.y && b.lowerBound.z <= a.upperBound.z;
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapNode( b3AABBV av, const b3TreeNode* node )
|
||||
{
|
||||
return b3OverlapAABBV( av, node->aabb );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE bool b3OverlapV( const b3AABB* a, const b3AABB* b )
|
||||
{
|
||||
return b3OverlapAABBV( *a, *b );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3UnionAABBV( b3AABBV a, b3AABBV b )
|
||||
{
|
||||
return b3AABB_Union( a, b );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE b3AABBV b3UnionPairV( const b3TreeNode* pair )
|
||||
{
|
||||
return b3AABB_Union( pair[0].aabb, pair[1].aabb );
|
||||
}
|
||||
|
||||
B3_FORCE_INLINE void b3StoreAABBV( b3AABB* aabb, b3AABBV value, bool condition )
|
||||
{
|
||||
if ( condition )
|
||||
{
|
||||
*aabb = value;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
B3_FORCE_INLINE b3AABB b3UnionV( b3AABB a, b3AABB b )
|
||||
{
|
||||
b3AABB result;
|
||||
b3StoreAABBV( &result, b3UnionAABBV( b3LoadAABBV( &a ), b3LoadAABBV( &b ) ), true );
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
166
src/solver.c
166
src/solver.c
|
|
@ -589,8 +589,14 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
|
|||
b3Vec3 aabbMargin = { marginScalar, marginScalar, marginScalar };
|
||||
shape->fatAABB = (b3AABB){ b3Sub( aabb.lowerBound, aabbMargin ), b3Add( aabb.upperBound, aabbMargin ) };
|
||||
|
||||
shape->flags |= b3_enlargedAABB;
|
||||
fastBodySim->flags |= b3_enlargeBounds;
|
||||
|
||||
// Regular bodies mark the hierarchy as moved using atomic operations.
|
||||
// Bullets are handled separately at a later stage.
|
||||
if ( isBullet == false )
|
||||
{
|
||||
b3BroadPhase_MarkProxyMoved( &world->broadPhase, shape->proxyKey, shape->fatAABB );
|
||||
}
|
||||
}
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
|
|
@ -621,8 +627,12 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
|
|||
.upperBound = b3Add( shape->aabb.upperBound, aabbMargin ),
|
||||
};
|
||||
|
||||
shape->flags |= b3_enlargedAABB;
|
||||
fastBodySim->flags |= b3_enlargeBounds;
|
||||
|
||||
if ( isBullet == false )
|
||||
{
|
||||
b3BroadPhase_MarkProxyMoved( &world->broadPhase, shape->proxyKey, shape->fatAABB );
|
||||
}
|
||||
}
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
|
|
@ -680,7 +690,6 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
|
|||
b3BodyMoveEvent* moveEvents = world->bodyMoveEvents.data;
|
||||
|
||||
b3TaskContext* taskContext = world->taskContexts.data + workerIndex;
|
||||
b3BitSet* enlargedSimBitSet = &taskContext->enlargedSimBitSet;
|
||||
b3BitSet* awakeIslandBitSet = &taskContext->awakeIslandBitSet;
|
||||
|
||||
const float speculativeScalar = B3_SPECULATIVE_DISTANCE;
|
||||
|
|
@ -817,42 +826,31 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
|
|||
}
|
||||
|
||||
// Update shapes AABBs
|
||||
b3WorldTransform transform = sim->transform;
|
||||
bool isFast = ( sim->flags & b3_isFast ) != 0;
|
||||
int shapeId = body->headShapeId;
|
||||
while ( shapeId != B3_NULL_INDEX )
|
||||
// For fast non-bullet bodies the AABB has already been updated in b3SolveContinuous
|
||||
// For fast bullet bodies the AABB will be updated at a later stage
|
||||
if ( ( sim->flags & b3_isFast ) == 0 )
|
||||
{
|
||||
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
|
||||
|
||||
if ( isFast )
|
||||
b3WorldTransform transform = sim->transform;
|
||||
int shapeId = body->headShapeId;
|
||||
while ( shapeId != B3_NULL_INDEX )
|
||||
{
|
||||
// For fast non-bullet bodies the AABB has already been updated in b3SolveContinuous
|
||||
// For fast bullet bodies the AABB will be updated at a later stage
|
||||
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
|
||||
|
||||
// Add to enlarged shapes regardless of AABB changes.
|
||||
// Bit-set to keep the move array sorted
|
||||
b3SetBit( enlargedSimBitSet, simIndex );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeScalar );
|
||||
shape->aabb = aabb;
|
||||
|
||||
B3_ASSERT( ( shape->flags & b3_enlargedAABB ) == 0 );
|
||||
|
||||
if ( b3AABB_Contains( shape->fatAABB, aabb ) == false )
|
||||
{
|
||||
float marginScalar = shape->aabbMargin;
|
||||
b3Vec3 aabbMargin = { marginScalar, marginScalar, marginScalar };
|
||||
shape->fatAABB = (b3AABB){ b3Sub( aabb.lowerBound, aabbMargin ), b3Add( aabb.upperBound, aabbMargin ) };
|
||||
shape->flags |= b3_enlargedAABB;
|
||||
|
||||
// Bit-set to keep the move array sorted
|
||||
b3SetBit( enlargedSimBitSet, simIndex );
|
||||
// Mark the hierarchy as moved using atomic operations.
|
||||
b3BroadPhase_MarkProxyMoved( &world->broadPhase, shape->proxyKey, shape->fatAABB );
|
||||
}
|
||||
}
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
shapeId = shape->nextShapeId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1870,18 +1868,28 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
|
|||
b3TracyCZoneNC( update_transforms, "Update Transforms", b3_colorMediumSeaGreen, true );
|
||||
uint64_t transformTicks = b3GetTicks();
|
||||
|
||||
// Prepare contact, enlarged body, and island bit sets used in body finalization.
|
||||
// Prepare the island bit set used in body finalization.
|
||||
int awakeIslandCount = awakeSet->islandSims.count;
|
||||
for ( int i = 0; i < world->workerCount; ++i )
|
||||
{
|
||||
b3TaskContext* taskContext = world->taskContexts.data + i;
|
||||
b3Array_Clear( taskContext->sensorHits );
|
||||
b3SetBitCountAndClear( &taskContext->enlargedSimBitSet, awakeBodyCount );
|
||||
b3SetBitCountAndClear( &taskContext->awakeIslandBitSet, awakeIslandCount );
|
||||
taskContext->splitIslandId = B3_NULL_INDEX;
|
||||
taskContext->splitSleepTime = 0.0f;
|
||||
}
|
||||
|
||||
// Finish the user tree task that was queued earlier in the time step. This must be complete before touching the
|
||||
// broad-phase.
|
||||
if ( world->userTreeTask != NULL )
|
||||
{
|
||||
world->finishTaskFcn( world->userTreeTask, world->userTaskContext );
|
||||
world->userTreeTask = NULL;
|
||||
world->activeTaskCount -= 1;
|
||||
}
|
||||
|
||||
b3ValidateNoMoved( &world->broadPhase );
|
||||
|
||||
// Finalize bodies. Must happen after the constraint solver and after island splitting.
|
||||
b3ParallelFor( world, &b3FinalizeBodiesTask, awakeBodyCount, 16, stepContext, "ccd" );
|
||||
|
||||
|
|
@ -2073,90 +2081,8 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
|
|||
b3TracyCZoneNC( refit_bvh, "Refit BVH", b3_colorFireBrick, true );
|
||||
uint64_t refitTicks = b3GetTicks();
|
||||
|
||||
// Finish the user tree task that was queued earlier in the time step. This must be complete before touching the
|
||||
// broad-phase.
|
||||
if ( world->userTreeTask != NULL )
|
||||
{
|
||||
world->finishTaskFcn( world->userTreeTask, world->userTaskContext );
|
||||
world->userTreeTask = NULL;
|
||||
world->activeTaskCount -= 1;
|
||||
}
|
||||
|
||||
b3ValidateNoEnlarged( &world->broadPhase );
|
||||
|
||||
// Gather bits for all sim bodies that have enlarged AABBs
|
||||
b3BitSet* enlargedBodyBitSet = &world->taskContexts.data[0].enlargedSimBitSet;
|
||||
for ( int i = 1; i < world->workerCount; ++i )
|
||||
{
|
||||
b3InPlaceUnion( enlargedBodyBitSet, &world->taskContexts.data[i].enlargedSimBitSet );
|
||||
}
|
||||
|
||||
// Enlarge broad-phase proxies and build move array
|
||||
// Apply shape AABB changes to broad-phase. This also create the move array which must be
|
||||
// in deterministic order. I'm tracking sim bodies because the number of shape ids can be huge.
|
||||
// This has to happen before bullets are processed.
|
||||
{
|
||||
b3BroadPhase* broadPhase = &world->broadPhase;
|
||||
uint32_t wordCount = enlargedBodyBitSet->blockCount;
|
||||
uint64_t* bits = enlargedBodyBitSet->bits;
|
||||
|
||||
// Fast array access is important here
|
||||
b3Body* bodyArray = world->bodies.data;
|
||||
b3BodySim* bodySimArray = awakeSet->bodySims.data;
|
||||
b3Shape* shapeArray = world->shapes.data;
|
||||
|
||||
for ( uint32_t k = 0; k < wordCount; ++k )
|
||||
{
|
||||
uint64_t word = bits[k];
|
||||
while ( word != 0 )
|
||||
{
|
||||
uint32_t ctz = b3CTZ64( word );
|
||||
uint32_t bodySimIndex = 64 * k + ctz;
|
||||
|
||||
b3BodySim* bodySim = bodySimArray + bodySimIndex;
|
||||
|
||||
b3Body* body = bodyArray + bodySim->bodyId;
|
||||
|
||||
int shapeId = body->headShapeId;
|
||||
if ( ( bodySim->flags & ( b3_isBullet | b3_isFast ) ) == ( b3_isBullet | b3_isFast ) )
|
||||
{
|
||||
// Fast bullet bodies don't have their final AABB yet
|
||||
while ( shapeId != B3_NULL_INDEX )
|
||||
{
|
||||
b3Shape* shape = shapeArray + shapeId;
|
||||
|
||||
// Shape is fast. It's aabb will be enlarged in continuous collision.
|
||||
// Update the move array here for determinism because bullets are processed
|
||||
// below in non-deterministic order.
|
||||
b3BufferMove( broadPhase, shape->proxyKey );
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while ( shapeId != B3_NULL_INDEX )
|
||||
{
|
||||
b3Shape* shape = shapeArray + shapeId;
|
||||
|
||||
// The AABB may not have been enlarged, despite the body being flagged as enlarged.
|
||||
// For example, a body with multiple shapes may have not have all shapes enlarged.
|
||||
// A fast body may have been flagged as enlarged despite having no shapes enlarged.
|
||||
if ( shape->flags & b3_enlargedAABB )
|
||||
{
|
||||
b3BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB );
|
||||
shape->flags &= ~b3_enlargedAABB;
|
||||
}
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the smallest set bit
|
||||
word = word & ( word - 1 );
|
||||
}
|
||||
}
|
||||
}
|
||||
b3DynamicTree_Refit( world->broadPhase.trees + b3_kinematicBody );
|
||||
b3DynamicTree_Refit( world->broadPhase.trees + b3_dynamicBody );
|
||||
|
||||
b3ValidateBroadPhase( &world->broadPhase );
|
||||
|
||||
|
|
@ -2207,23 +2133,17 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
|
|||
while ( shapeId != B3_NULL_INDEX )
|
||||
{
|
||||
b3Shape* shape = shapeArray + shapeId;
|
||||
if ( ( shape->flags & b3_enlargedAABB ) == 0 )
|
||||
{
|
||||
shapeId = shape->nextShapeId;
|
||||
continue;
|
||||
}
|
||||
|
||||
// clear flag
|
||||
shape->flags &= ~b3_enlargedAABB;
|
||||
|
||||
int proxyKey = shape->proxyKey;
|
||||
int proxyId = B3_PROXY_ID( proxyKey );
|
||||
B3_ASSERT( B3_PROXY_TYPE( proxyKey ) == b3_dynamicBody );
|
||||
B3_VALIDATE( B3_PROXY_TYPE( proxyKey ) == b3_dynamicBody );
|
||||
|
||||
// all fast bullet shapes should already be in the move buffer
|
||||
B3_ASSERT( b3GetBit( &broadPhase->movedProxies[b3_dynamicBody], proxyId ) );
|
||||
b3AABB treeAABB = b3DynamicTree_GetAABB( dynamicTree, proxyId );
|
||||
|
||||
b3DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB );
|
||||
if ( b3AABB_Contains( treeAABB, shape->fatAABB ) == false )
|
||||
{
|
||||
b3DynamicTree_EnlargeProxy( dynamicTree, proxyId, shape->fatAABB );
|
||||
}
|
||||
|
||||
shapeId = shape->nextShapeId;
|
||||
}
|
||||
|
|
|
|||
28
src/table.c
28
src/table.c
|
|
@ -52,25 +52,6 @@ void b3ClearSet( b3HashSet* set )
|
|||
memset( set->items, 0, set->capacity * sizeof( b3SetItem ) );
|
||||
}
|
||||
|
||||
// I need a good hash because the keys are built from pairs of increasing integers.
|
||||
// A simple hash like hash = (integer1 XOR integer2) has many collisions.
|
||||
// https://lemire.me/blog/2018/08/15/fast-strongly-universal-64-bit-hashing-everywhere/
|
||||
// https://preshing.com/20130107/this-hash-set-is-faster-than-a-judy-array/
|
||||
// todo try: https://www.jandrewrogers.com/2019/02/12/fast-perfect-hashing/
|
||||
// todo try:
|
||||
// https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
|
||||
static inline uint32_t b3KeyHash( uint64_t key )
|
||||
{
|
||||
uint64_t h = key;
|
||||
h ^= h >> 33;
|
||||
h *= 0xff51afd7ed558ccdL;
|
||||
h ^= h >> 33;
|
||||
h *= 0xc4ceb9fe1a85ec53L;
|
||||
h ^= h >> 33;
|
||||
|
||||
return (uint32_t)h;
|
||||
}
|
||||
|
||||
static int32_t b3FindSlot( const b3HashSet* set, uint64_t key, uint32_t hash )
|
||||
{
|
||||
uint32_t capacity = set->capacity;
|
||||
|
|
@ -139,6 +120,15 @@ bool b3ContainsKey( const b3HashSet* set, uint64_t key )
|
|||
return set->items[index].key == key;
|
||||
}
|
||||
|
||||
// The caller already has the hash, which lets a batch prefetch the slots before probing them.
|
||||
bool b3ContainsHashedKey( const b3HashSet* set, uint64_t key, uint32_t hash )
|
||||
{
|
||||
B3_ASSERT( key != 0 );
|
||||
B3_ASSERT( hash == b3KeyHash( key ) );
|
||||
int32_t index = b3FindSlot( set, key, hash );
|
||||
return set->items[index].key == key;
|
||||
}
|
||||
|
||||
int b3GetHashSetBytes( b3HashSet* set )
|
||||
{
|
||||
return set->capacity * (int)sizeof( b3SetItem );
|
||||
|
|
|
|||
21
src/table.h
21
src/table.h
|
|
@ -3,11 +3,31 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include "box3d/base.h"
|
||||
#include "box3d/constants.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// I need a good hash because the keys are built from pairs of increasing integers.
|
||||
// A simple hash like hash = (integer1 XOR integer2) has many collisions.
|
||||
// https://lemire.me/blog/2018/08/15/fast-strongly-universal-64-bit-hashing-everywhere/
|
||||
// https://preshing.com/20130107/this-hash-set-is-faster-than-a-judy-array/
|
||||
// todo try: https://www.jandrewrogers.com/2019/02/12/fast-perfect-hashing/
|
||||
// todo try:
|
||||
// https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
|
||||
B3_FORCE_INLINE uint32_t b3KeyHash( uint64_t key )
|
||||
{
|
||||
uint64_t h = key;
|
||||
h ^= h >> 33;
|
||||
h *= 0xff51afd7ed558ccdL;
|
||||
h ^= h >> 33;
|
||||
h *= 0xc4ceb9fe1a85ec53L;
|
||||
h ^= h >> 33;
|
||||
|
||||
return (uint32_t)h;
|
||||
}
|
||||
|
||||
typedef struct b3SetItem
|
||||
{
|
||||
uint64_t key;
|
||||
|
|
@ -49,5 +69,6 @@ bool b3AddKey( b3HashSet* set, uint64_t key );
|
|||
bool b3RemoveKey( b3HashSet* set, uint64_t key );
|
||||
|
||||
bool b3ContainsKey( const b3HashSet* set, uint64_t key );
|
||||
bool b3ContainsHashedKey( const b3HashSet* set, uint64_t key, uint32_t hash );
|
||||
|
||||
int b3GetHashSetBytes( b3HashSet* set );
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@
|
|||
|
||||
// Snapshot image magic 'BNS3' and version
|
||||
#define B3_SNAP_MAGIC 0x33534E42u
|
||||
#define B3_SNAP_VERSION 3u // added b3Body::safetyFactor
|
||||
#define B3_SNAP_VERSION 5u // broad-phase pair traversal, move buffer removed
|
||||
|
||||
#define B3_SNAP_FLAG_VALIDATION 0x1u
|
||||
#define B3_SNAP_FLAG_DOUBLE_PRECISION 0x2u
|
||||
|
|
@ -64,6 +64,7 @@ static uint32_t b3ComputeLayoutHash( void )
|
|||
MIX( sizeof( b3GraphColor ) )
|
||||
MIX( sizeof( b3DynamicTree ) )
|
||||
MIX( sizeof( b3TreeNode ) )
|
||||
MIX( sizeof( b3TreeProxy ) )
|
||||
MIX( sizeof( b3SetItem ) )
|
||||
MIX( sizeof( b3IdPool ) )
|
||||
MIX( sizeof( b3SurfaceMaterial ) )
|
||||
|
|
@ -277,18 +278,26 @@ static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs )
|
|||
}
|
||||
}
|
||||
|
||||
// DynamicTree: version, scalars, full nodeCapacity nodes (rebuild scratch excluded)
|
||||
// DynamicTree: version, scalars, then nodes and parents to nodeEnd and proxies at capacity.
|
||||
// The empty node and the free pairs are sentinels below the end and travel as they are. Only the
|
||||
// stale tail above the end, the spare array and the rebuild scratch are skipped.
|
||||
static void b3SerTree( b3RecBuffer* buf, const b3DynamicTree* tree )
|
||||
{
|
||||
b3SnapW_Bytes( buf, &tree->version, sizeof( uint64_t ) );
|
||||
b3SnapW_I32( buf, tree->root );
|
||||
b3SnapW_I32( buf, tree->nodeCount );
|
||||
b3SnapW_I32( buf, tree->nodeCapacity );
|
||||
b3SnapW_I32( buf, tree->freeList );
|
||||
b3SnapW_I32( buf, tree->nodeEnd );
|
||||
b3SnapW_I32( buf, tree->pairFreeList );
|
||||
b3SnapW_I32( buf, tree->proxyCount );
|
||||
if ( tree->nodeCapacity > 0 )
|
||||
b3SnapW_I32( buf, tree->proxyCapacity );
|
||||
b3SnapW_I32( buf, tree->proxyFreeList );
|
||||
b3SnapW_I32( buf, tree->dfsOrdered ? 1 : 0 );
|
||||
if ( tree->nodeEnd > 0 )
|
||||
{
|
||||
b3SnapW_Bytes( buf, tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
|
||||
b3SnapW_Bytes( buf, tree->nodes, tree->nodeEnd * (int)sizeof( b3TreeNode ) );
|
||||
b3SnapW_Bytes( buf, tree->parents, tree->nodeEnd * (int)sizeof( int32_t ) );
|
||||
}
|
||||
if ( tree->proxyCapacity > 0 )
|
||||
{
|
||||
b3SnapW_Bytes( buf, tree->proxies, tree->proxyCapacity * (int)sizeof( b3TreeProxy ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -296,29 +305,50 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
|
|||
{
|
||||
uint64_t version;
|
||||
b3SnapR_Bytes( r, &version, sizeof( uint64_t ) );
|
||||
int root = b3SnapR_I32( r );
|
||||
int nodeCount = b3SnapR_I32( r );
|
||||
int nodeCapacity = b3SnapR_I32( r );
|
||||
int freeList = b3SnapR_I32( r );
|
||||
int nodeEnd = b3SnapR_I32( r );
|
||||
int pairFreeList = b3SnapR_I32( r );
|
||||
int proxyCount = b3SnapR_I32( r );
|
||||
int proxyCapacity = b3SnapR_I32( r );
|
||||
int proxyFreeList = b3SnapR_I32( r );
|
||||
bool dfsOrdered = b3SnapR_I32( r ) != 0;
|
||||
|
||||
if ( r->ok && b3SnapCheckCount( r, nodeCapacity, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false )
|
||||
if ( r->ok && b3SnapCheckCount( r, nodeEnd, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false )
|
||||
{
|
||||
r->ok = false;
|
||||
}
|
||||
|
||||
// Free existing allocation including any rebuild scratch
|
||||
if ( r->ok && b3SnapCheckCount( r, proxyCapacity, (int)sizeof( b3TreeProxy ), (int)sizeof( b3TreeProxy ) ) == false )
|
||||
{
|
||||
r->ok = false;
|
||||
}
|
||||
|
||||
if ( r->ok && ( nodeEnd < 2 || ( nodeEnd & 1 ) != 0 || proxyCapacity < 1 ) )
|
||||
{
|
||||
r->ok = false;
|
||||
}
|
||||
|
||||
// Free existing allocation including the spare array and any rebuild scratch
|
||||
b3Free( tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
|
||||
b3Free( tree->parents, tree->nodeCapacity * (int)sizeof( int32_t ) );
|
||||
b3Free( tree->proxies, tree->proxyCapacity * (int)sizeof( b3TreeProxy ) );
|
||||
b3Free( tree->swapNodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
|
||||
b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) );
|
||||
b3Free( tree->leafNodes, tree->rebuildCapacity * (int)sizeof( b3TreeNode ) );
|
||||
b3Free( tree->leafBoxes, tree->rebuildCapacity * (int)sizeof( b3AABB ) );
|
||||
b3Free( tree->leafCenters, tree->rebuildCapacity * (int)sizeof( b3Vec3 ) );
|
||||
b3Free( tree->binIndices, tree->rebuildCapacity * (int)sizeof( int ) );
|
||||
tree->nodes = NULL;
|
||||
tree->parents = NULL;
|
||||
tree->proxies = NULL;
|
||||
tree->swapNodes = NULL;
|
||||
tree->leafIndices = NULL;
|
||||
tree->leafNodes = NULL;
|
||||
tree->leafBoxes = NULL;
|
||||
tree->leafCenters = NULL;
|
||||
tree->binIndices = NULL;
|
||||
tree->nodeEnd = 0;
|
||||
tree->nodeCapacity = 0;
|
||||
tree->proxyCapacity = 0;
|
||||
tree->rebuildCapacity = 0;
|
||||
|
||||
if ( !r->ok )
|
||||
|
|
@ -327,17 +357,21 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
|
|||
}
|
||||
|
||||
tree->version = version;
|
||||
tree->root = root;
|
||||
tree->nodeCount = nodeCount;
|
||||
tree->nodeCapacity = nodeCapacity;
|
||||
tree->freeList = freeList;
|
||||
tree->nodeEnd = nodeEnd;
|
||||
tree->nodeCapacity = nodeEnd;
|
||||
tree->pairFreeList = pairFreeList;
|
||||
tree->proxyCount = proxyCount;
|
||||
tree->proxyCapacity = proxyCapacity;
|
||||
tree->proxyFreeList = proxyFreeList;
|
||||
tree->dfsOrdered = dfsOrdered;
|
||||
|
||||
if ( nodeCapacity > 0 )
|
||||
{
|
||||
tree->nodes = (b3TreeNode*)b3Alloc( nodeCapacity * (int)sizeof( b3TreeNode ) );
|
||||
b3SnapR_Bytes( r, tree->nodes, nodeCapacity * (int)sizeof( b3TreeNode ) );
|
||||
}
|
||||
tree->nodes = (b3TreeNode*)b3Alloc( nodeEnd * (int)sizeof( b3TreeNode ) );
|
||||
tree->parents = (int32_t*)b3Alloc( nodeEnd * (int)sizeof( int32_t ) );
|
||||
b3SnapR_Bytes( r, tree->nodes, nodeEnd * (int)sizeof( b3TreeNode ) );
|
||||
b3SnapR_Bytes( r, tree->parents, nodeEnd * (int)sizeof( int32_t ) );
|
||||
|
||||
tree->proxies = (b3TreeProxy*)b3Alloc( proxyCapacity * (int)sizeof( b3TreeProxy ) );
|
||||
b3SnapR_Bytes( r, tree->proxies, proxyCapacity * (int)sizeof( b3TreeProxy ) );
|
||||
}
|
||||
|
||||
// Solver set: setIndex + 4 arrays (note: contactIndices is int array, not contactSims)
|
||||
|
|
@ -446,6 +480,7 @@ static void b3SerWorldConfig( b3RecBuffer* buf, const b3World* world )
|
|||
b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) );
|
||||
b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) );
|
||||
b3SnapW_I32( buf, world->endEventArrayIndex );
|
||||
b3SnapW_I32( buf, world->compoundShapeCount );
|
||||
b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) );
|
||||
uint8_t flags = 0;
|
||||
flags |= world->enableSleep ? 0x01u : 0u;
|
||||
|
|
@ -470,6 +505,7 @@ static void b3DesWorldConfig( b3SnapReader* r, b3World* world )
|
|||
b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) );
|
||||
b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) );
|
||||
world->endEventArrayIndex = b3SnapR_I32( r );
|
||||
world->compoundShapeCount = b3SnapR_I32( r );
|
||||
b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) );
|
||||
uint8_t flags = 0;
|
||||
b3SnapR_Bytes( r, &flags, 1 );
|
||||
|
|
@ -1078,11 +1114,6 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
|
|||
{
|
||||
b3SerTree( buf, &bp->trees[t] );
|
||||
}
|
||||
for ( int t = 0; t < b3_bodyTypeCount; ++t )
|
||||
{
|
||||
b3SerBitSet( buf, &bp->movedProxies[t] );
|
||||
}
|
||||
b3SerPodArray( buf, bp->moveArray );
|
||||
b3SerHashSet( buf, &bp->pairSet );
|
||||
|
||||
// Constraint graph
|
||||
|
|
@ -1307,17 +1338,8 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
|
|||
{
|
||||
b3DesTree( r, &bp->trees[t] );
|
||||
}
|
||||
for ( int t = 0; t < b3_bodyTypeCount; ++t )
|
||||
{
|
||||
b3DesBitSet( r, &bp->movedProxies[t] );
|
||||
}
|
||||
|
||||
b3Array_Destroy( bp->moveArray );
|
||||
b3Array_Create( bp->moveArray );
|
||||
b3DesPodArray( r, bp->moveArray );
|
||||
|
||||
b3DesHashSet( r, &bp->pairSet );
|
||||
// Transient moveResults/movePairs stay at shell's NULL/0
|
||||
// The gathered moved siblings are per step scratch and stay at the shell's NULL
|
||||
}
|
||||
|
||||
// 11. Constraint graph
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ set(BOX3D_TEST_FILES
|
|||
test_container.c
|
||||
test_determinism.c
|
||||
test_distance.c
|
||||
test_dynamic_tree.c
|
||||
test_hash.c
|
||||
test_height_field.c
|
||||
test_hull.c
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ extern int CompoundTest( void );
|
|||
extern int ContainerTest( void );
|
||||
extern int DeterminismTest( void );
|
||||
extern int DistanceTest( void );
|
||||
extern int DynamicTreeTest( void );
|
||||
extern int HashTest( void );
|
||||
extern int HeightFieldTest( void );
|
||||
extern int HullTest( void );
|
||||
|
|
@ -109,6 +110,7 @@ int main( int argc, char** argv )
|
|||
MAYBE_RUN_TEST( ContainerTest );
|
||||
MAYBE_RUN_TEST( DeterminismTest );
|
||||
MAYBE_RUN_TEST( DistanceTest );
|
||||
MAYBE_RUN_TEST( DynamicTreeTest );
|
||||
MAYBE_RUN_TEST( HashTest );
|
||||
MAYBE_RUN_TEST( HeightFieldTest );
|
||||
MAYBE_RUN_TEST( HullTest );
|
||||
|
|
|
|||
|
|
@ -76,8 +76,10 @@ static int CompoundCreateMixed( void )
|
|||
ENSURE( compound->sharedHullCount == 1 );
|
||||
ENSURE( compound->sharedMeshCount == 1 );
|
||||
|
||||
ENSURE( compound->tree.nodeCount > 0 );
|
||||
ENSURE( compound->tree.nodeEnd >= 2 );
|
||||
ENSURE( compound->tree.proxyCount > 0 );
|
||||
ENSURE( compound->tree.nodes != NULL );
|
||||
ENSURE( compound->tree.proxies != NULL );
|
||||
|
||||
b3DestroyCompound( compound );
|
||||
b3DestroyMesh( meshData );
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
|
||||
b3DeclareArrayNative( uint64_t );
|
||||
// uint64_t is already declared in container.h for the broad-phase pair keys
|
||||
b3DeclareArrayNative( int16_t );
|
||||
b3DeclareArrayNative( uint8_t );
|
||||
|
||||
|
|
|
|||
|
|
@ -18,25 +18,25 @@
|
|||
// Double precision accumulates body positions in double, so the settle/sleep step and the
|
||||
// state hash differ from the float build. Both modes are internally deterministic.
|
||||
#if defined( BOX3D_DOUBLE_PRECISION )
|
||||
#define RAGDOLL_SLEEP_STEP 272
|
||||
#define RAGDOLL_HASH 0xBF43ECD7
|
||||
#define WAVE_PILE_SLEEP_STEP 291
|
||||
#define WAVE_PILE_HASH 0x8B6E2CD2
|
||||
#define RAGDOLL_SLEEP_STEP 277
|
||||
#define RAGDOLL_HASH 0xF7B5B2D1
|
||||
#define WAVE_PILE_SLEEP_STEP 323
|
||||
#define WAVE_PILE_HASH 0x2200A547
|
||||
#define QUERY_SPAWN_SLEEP_STEP 242
|
||||
#define QUERY_SPAWN_HASH 0x1737F5BC
|
||||
#define QUERY_SPAWN_HIT_COUNT 59
|
||||
#define QUERY_SPAWN_QUERY_HASH 0x31F090DC
|
||||
#define QUERY_SPAWN_QUERY_HASH 0x5B4429DC
|
||||
#define MESH_DROP_SLEEP_STEP 251
|
||||
#define MESH_DROP_HASH 0x465381C5
|
||||
#else
|
||||
#define RAGDOLL_SLEEP_STEP 286
|
||||
#define RAGDOLL_HASH 0x0211682A
|
||||
#define WAVE_PILE_SLEEP_STEP 282
|
||||
#define WAVE_PILE_HASH 0xFC161D3D
|
||||
#define RAGDOLL_SLEEP_STEP 272
|
||||
#define RAGDOLL_HASH 0xF4992B41
|
||||
#define WAVE_PILE_SLEEP_STEP 316
|
||||
#define WAVE_PILE_HASH 0xAA7D15A7
|
||||
#define QUERY_SPAWN_SLEEP_STEP 242
|
||||
#define QUERY_SPAWN_HASH 0xB9F993A5
|
||||
#define QUERY_SPAWN_HIT_COUNT 59
|
||||
#define QUERY_SPAWN_QUERY_HASH 0xB9D3863D
|
||||
#define QUERY_SPAWN_QUERY_HASH 0xE3271F3D
|
||||
#define MESH_DROP_SLEEP_STEP 251
|
||||
#define MESH_DROP_HASH 0xE58C7240
|
||||
#endif
|
||||
|
|
|
|||
713
test/test_dynamic_tree.c
Normal file
713
test/test_dynamic_tree.c
Normal file
|
|
@ -0,0 +1,713 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "aabb.h"
|
||||
#include "dynamic_tree.h"
|
||||
#include "test_macros.h"
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "box3d/constants.h"
|
||||
#include "box3d/math_functions.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define PROXY_COUNT 300
|
||||
|
||||
static uint32_t s_seed = 12345;
|
||||
|
||||
static uint32_t NextRandom( void )
|
||||
{
|
||||
s_seed = 1664525u * s_seed + 1013904223u;
|
||||
return s_seed;
|
||||
}
|
||||
|
||||
static float RandomFloat( float lo, float hi )
|
||||
{
|
||||
float t = (float)( NextRandom() >> 8 ) / (float)( 1 << 24 );
|
||||
return lo + t * ( hi - lo );
|
||||
}
|
||||
|
||||
static b3AABB RandomBox( float extent, float size )
|
||||
{
|
||||
b3Vec3 center = { RandomFloat( -extent, extent ), RandomFloat( -extent, extent ), RandomFloat( -extent, extent ) };
|
||||
b3Vec3 half = { RandomFloat( 0.1f, size ), RandomFloat( 0.1f, size ), RandomFloat( 0.1f, size ) };
|
||||
return (b3AABB){ b3Sub( center, half ), b3Add( center, half ) };
|
||||
}
|
||||
|
||||
typedef struct HitSet
|
||||
{
|
||||
int ids[PROXY_COUNT];
|
||||
int count;
|
||||
bool bad;
|
||||
} HitSet;
|
||||
|
||||
// Every test seeds user data with the index of the box it created the proxy from, so the sets
|
||||
// are keyed on user data. Proxy ids recycle, box indices do not.
|
||||
// A callback cannot fail the test directly, so bad news rides back on the context.
|
||||
static bool CollectCallback( int proxyId, uint64_t userData, void* context )
|
||||
{
|
||||
HitSet* set = context;
|
||||
if ( set->count >= PROXY_COUNT || (int)userData < 0 || (int)userData >= PROXY_COUNT )
|
||||
{
|
||||
set->bad = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
(void)proxyId;
|
||||
set->ids[set->count] = (int)userData;
|
||||
set->count += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
static int CompareInt( const void* a, const void* b )
|
||||
{
|
||||
int x = *(const int*)a;
|
||||
int y = *(const int*)b;
|
||||
return x < y ? -1 : ( x > y ? 1 : 0 );
|
||||
}
|
||||
|
||||
static int SameSet( HitSet* a, HitSet* b )
|
||||
{
|
||||
ENSURE( a->bad == false );
|
||||
ENSURE( b->bad == false );
|
||||
ENSURE( a->count == b->count );
|
||||
qsort( a->ids, (size_t)a->count, sizeof( int ), CompareInt );
|
||||
qsort( b->ids, (size_t)b->count, sizeof( int ), CompareInt );
|
||||
for ( int i = 0; i < a->count; ++i )
|
||||
{
|
||||
ENSURE( a->ids[i] == b->ids[i] );
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The tree must agree with a linear scan over the stored boxes. This is the gate on the
|
||||
// SIMD box helpers, which have three separate lane layouts.
|
||||
static int TreeQueryBruteForce( void )
|
||||
{
|
||||
s_seed = 12345;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
int proxies[PROXY_COUNT];
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 6.0f, 1.5f );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
ENSURE( proxies[i] == i );
|
||||
}
|
||||
|
||||
b3DynamicTree_Validate( &tree );
|
||||
ENSURE( b3DynamicTree_GetProxyCount( &tree ) == PROXY_COUNT );
|
||||
|
||||
int totalHits = 0;
|
||||
for ( int round = 0; round < 200; ++round )
|
||||
{
|
||||
b3AABB queryBox = RandomBox( 7.0f, 3.0f );
|
||||
|
||||
HitSet treeHits = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, B3_DEFAULT_MASK_BITS, false, CollectCallback, &treeHits );
|
||||
|
||||
HitSet bruteHits = { 0 };
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
if ( b3AABB_Overlaps( boxes[i], queryBox ) )
|
||||
{
|
||||
bruteHits.ids[bruteHits.count] = i;
|
||||
bruteHits.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
ENSURE( SameSet( &treeHits, &bruteHits ) == 0 );
|
||||
totalHits += treeHits.count;
|
||||
}
|
||||
|
||||
// Guard against the comparison above agreeing on nothing
|
||||
ENSURE( totalHits > 1000 );
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Moving and enlarging every proxy exercises remove, insert, the ordered flag, the sweep refit
|
||||
// and the partial rebuild, then the query has to still agree with the scan.
|
||||
static int TreeMoveRefitRebuild( void )
|
||||
{
|
||||
s_seed = 777;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
int proxies[PROXY_COUNT];
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 6.0f, 1.0f );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
}
|
||||
|
||||
b3DynamicTree_Rebuild( &tree, true );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
ENSURE( tree.dfsOrdered );
|
||||
|
||||
int totalHits = 0;
|
||||
for ( int round = 0; round < 8; ++round )
|
||||
{
|
||||
// Half the proxies move, half grow in place
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
if ( ( i & 1 ) == 0 )
|
||||
{
|
||||
boxes[i] = RandomBox( 6.0f, 1.0f );
|
||||
b3DynamicTree_MoveProxy( &tree, proxies[i], boxes[i] );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3AABB grown = b3AABB_Inflate( boxes[i], 0.35f );
|
||||
boxes[i] = grown;
|
||||
b3DynamicTree_EnlargeProxy( &tree, proxies[i], grown );
|
||||
}
|
||||
}
|
||||
|
||||
b3DynamicTree_Refit( &tree );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
|
||||
b3DynamicTree_Rebuild( &tree, false );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
b3DynamicTree_ValidateNoMoved( &tree );
|
||||
ENSURE( tree.dfsOrdered );
|
||||
|
||||
// Every stored box must still be inside its leaf and inside the root
|
||||
b3AABB rootBounds = b3DynamicTree_GetRootBounds( &tree );
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
ENSURE( b3AABB_Contains( b3DynamicTree_GetAABB( &tree, proxies[i] ), boxes[i] ) );
|
||||
ENSURE( b3AABB_Contains( rootBounds, boxes[i] ) );
|
||||
ENSURE( (int)b3DynamicTree_GetUserData( &tree, proxies[i] ) == i );
|
||||
}
|
||||
|
||||
b3AABB queryBox = RandomBox( 7.0f, 3.0f );
|
||||
|
||||
HitSet treeHits = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, B3_DEFAULT_MASK_BITS, false, CollectCallback, &treeHits );
|
||||
|
||||
HitSet bruteHits = { 0 };
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
if ( b3AABB_Overlaps( boxes[i], queryBox ) )
|
||||
{
|
||||
bruteHits.ids[bruteHits.count] = i;
|
||||
bruteHits.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
ENSURE( SameSet( &treeHits, &bruteHits ) == 0 );
|
||||
totalHits += treeHits.count;
|
||||
}
|
||||
|
||||
// Guard against the comparison above agreeing on nothing
|
||||
ENSURE( totalHits > 50 );
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Destroying proxies in a scrambled order recycles sibling pairs through the free list and
|
||||
// leaves the array unordered, which is the path the fallback refit has to handle.
|
||||
static int TreeDestroyScrambled( void )
|
||||
{
|
||||
s_seed = 4242;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
int proxies[PROXY_COUNT];
|
||||
bool alive[PROXY_COUNT];
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 10.0f, 0.8f );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
alive[i] = true;
|
||||
}
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; i += 3 )
|
||||
{
|
||||
b3DynamicTree_DestroyProxy( &tree, proxies[i] );
|
||||
alive[i] = false;
|
||||
}
|
||||
|
||||
b3DynamicTree_Validate( &tree );
|
||||
|
||||
// Re-create into the holes
|
||||
for ( int i = 0; i < PROXY_COUNT; i += 3 )
|
||||
{
|
||||
boxes[i] = RandomBox( 10.0f, 0.8f );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
alive[i] = true;
|
||||
}
|
||||
|
||||
b3DynamicTree_Validate( &tree );
|
||||
ENSURE( b3DynamicTree_GetProxyCount( &tree ) == PROXY_COUNT );
|
||||
|
||||
// The user data has to have followed each proxy through the churn
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
ENSURE( alive[i] );
|
||||
ENSURE( (int)b3DynamicTree_GetUserData( &tree, proxies[i] ) == i );
|
||||
ENSURE( b3AABB_Contains( b3DynamicTree_GetAABB( &tree, proxies[i] ), boxes[i] ) );
|
||||
}
|
||||
|
||||
b3AABB queryBox = { { -10.0f, -10.0f, -10.0f }, { 10.0f, 10.0f, 10.0f } };
|
||||
HitSet treeHits = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, B3_DEFAULT_MASK_BITS, false, CollectCallback, &treeHits );
|
||||
|
||||
HitSet bruteHits = { 0 };
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
if ( b3AABB_Overlaps( boxes[i], queryBox ) )
|
||||
{
|
||||
bruteHits.ids[bruteHits.count] = i;
|
||||
bruteHits.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
ENSURE( SameSet( &treeHits, &bruteHits ) == 0 );
|
||||
ENSURE( treeHits.count == PROXY_COUNT );
|
||||
|
||||
// Empty the tree
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
b3DynamicTree_DestroyProxy( &tree, proxies[i] );
|
||||
}
|
||||
|
||||
b3DynamicTree_Validate( &tree );
|
||||
ENSURE( b3DynamicTree_GetProxyCount( &tree ) == 0 );
|
||||
ENSURE( b3DynamicTree_GetHeight( &tree ) == 0 );
|
||||
|
||||
// Queries on an empty tree must be silent
|
||||
HitSet emptyHits = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, B3_DEFAULT_MASK_BITS, false, CollectCallback, &emptyHits );
|
||||
ENSURE( emptyHits.count == 0 );
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
typedef struct LeafRootHit
|
||||
{
|
||||
int count;
|
||||
int proxyId;
|
||||
uint64_t userData;
|
||||
} LeafRootHit;
|
||||
|
||||
static bool LeafRootCallback( int proxyId, uint64_t userData, void* context )
|
||||
{
|
||||
LeafRootHit* hit = context;
|
||||
hit->count += 1;
|
||||
hit->proxyId = proxyId;
|
||||
hit->userData = userData;
|
||||
return true;
|
||||
}
|
||||
|
||||
// A one proxy tree is a leaf at the root with an empty node beside it, which every traversal
|
||||
// has to survive.
|
||||
static int TreeLeafRoot( void )
|
||||
{
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB box = { { -1.0f, -1.0f, -1.0f }, { 1.0f, 1.0f, 1.0f } };
|
||||
int proxyId = b3DynamicTree_CreateProxy( &tree, box, B3_DEFAULT_CATEGORY_BITS, 7 );
|
||||
|
||||
b3DynamicTree_Validate( &tree );
|
||||
ENSURE( b3DynamicTree_GetProxyCount( &tree ) == 1 );
|
||||
ENSURE( b3DynamicTree_GetHeight( &tree ) == 0 );
|
||||
ENSURE( b3DynamicTree_GetAreaRatio( &tree ) == 0.0f );
|
||||
ENSURE( b3DynamicTree_GetUserData( &tree, proxyId ) == 7 );
|
||||
|
||||
LeafRootHit hit = { 0 };
|
||||
b3AABB hitBox = { { 0.5f, 0.5f, 0.5f }, { 2.0f, 2.0f, 2.0f } };
|
||||
b3DynamicTree_Query( &tree, hitBox, B3_DEFAULT_MASK_BITS, false, LeafRootCallback, &hit );
|
||||
ENSURE( hit.count == 1 );
|
||||
ENSURE( hit.proxyId == proxyId );
|
||||
ENSURE( hit.userData == 7 );
|
||||
|
||||
hit.count = 0;
|
||||
b3AABB missBox = { { 4.0f, 4.0f, 4.0f }, { 5.0f, 5.0f, 5.0f } };
|
||||
b3DynamicTree_Query( &tree, missBox, B3_DEFAULT_MASK_BITS, false, LeafRootCallback, &hit );
|
||||
ENSURE( hit.count == 0 );
|
||||
|
||||
// The rebuild has one build leaf and the refit has nothing above it
|
||||
b3DynamicTree_Rebuild( &tree, true );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
b3DynamicTree_Refit( &tree );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
ENSURE( b3DynamicTree_GetProxyCount( &tree ) == 1 );
|
||||
|
||||
b3AABB grown = b3AABB_Inflate( box, 1.0f );
|
||||
b3DynamicTree_EnlargeProxy( &tree, proxyId, grown );
|
||||
ENSURE( b3AABB_Contains( b3DynamicTree_GetAABB( &tree, proxyId ), grown ) );
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Category bits live on the proxy now, so the filter has to bite at the leaf.
|
||||
static int TreeCategoryFilter( void )
|
||||
{
|
||||
s_seed = 99;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
uint64_t bits[PROXY_COUNT];
|
||||
int proxies[PROXY_COUNT];
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 8.0f, 0.6f );
|
||||
bits[i] = 1ull << ( i % 3 );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], bits[i], (uint64_t)i );
|
||||
ENSURE( b3DynamicTree_GetCategoryBits( &tree, proxies[i] ) == bits[i] );
|
||||
}
|
||||
|
||||
b3AABB queryBox = { { -8.0f, -8.0f, -8.0f }, { 8.0f, 8.0f, 8.0f } };
|
||||
|
||||
// A single bit mask makes requireAll equivalent to the any-bit test, so the last pass is
|
||||
// the one that proves requireAll accepts rather than just rejects
|
||||
static const uint64_t masks[3] = { 0x1ull, 0x3ull, 0x2ull };
|
||||
static const bool requireAlls[3] = { false, false, true };
|
||||
|
||||
for ( int pass = 0; pass < 3; ++pass )
|
||||
{
|
||||
uint64_t mask = masks[pass];
|
||||
bool requireAll = requireAlls[pass];
|
||||
|
||||
HitSet treeHits = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, mask, requireAll, CollectCallback, &treeHits );
|
||||
|
||||
HitSet bruteHits = { 0 };
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
bool accept = requireAll ? ( bits[i] & mask ) == mask : ( bits[i] & mask ) != 0;
|
||||
if ( accept && b3AABB_Overlaps( boxes[i], queryBox ) )
|
||||
{
|
||||
bruteHits.ids[bruteHits.count] = i;
|
||||
bruteHits.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
ENSURE( SameSet( &treeHits, &bruteHits ) == 0 );
|
||||
ENSURE( treeHits.count > PROXY_COUNT / 4 );
|
||||
}
|
||||
|
||||
// requireAll with two bits can never match a single bit proxy
|
||||
HitSet noHits = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, 0x5ull, true, CollectCallback, &noHits );
|
||||
ENSURE( noHits.count == 0 );
|
||||
|
||||
// Changing the bits has to change the filter without touching the structure
|
||||
b3DynamicTree_SetCategoryBits( &tree, proxies[0], 0x8ull );
|
||||
ENSURE( b3DynamicTree_GetCategoryBits( &tree, proxies[0] ) == 0x8ull );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
|
||||
HitSet oneHit = { 0 };
|
||||
b3DynamicTree_Query( &tree, queryBox, 0x8ull, false, CollectCallback, &oneHit );
|
||||
ENSURE( oneHit.count == 1 );
|
||||
ENSURE( oneHit.ids[0] == 0 );
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Returning -1 skips the proxy without shrinking the fraction, so the traversal keeps going
|
||||
// and reports every proxy whose node box the segment crosses.
|
||||
static float RayCastCollectCallback( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context )
|
||||
{
|
||||
(void)input;
|
||||
(void)proxyId;
|
||||
HitSet* set = context;
|
||||
if ( set->count >= PROXY_COUNT || (int)userData < 0 || (int)userData >= PROXY_COUNT )
|
||||
{
|
||||
set->bad = true;
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
set->ids[set->count] = (int)userData;
|
||||
set->count += 1;
|
||||
return -1.0f;
|
||||
}
|
||||
|
||||
static float BoxCastCollectCallback( const b3BoxCastInput* input, int proxyId, uint64_t userData, void* context )
|
||||
{
|
||||
(void)input;
|
||||
(void)proxyId;
|
||||
HitSet* set = context;
|
||||
if ( set->count >= PROXY_COUNT || (int)userData < 0 || (int)userData >= PROXY_COUNT )
|
||||
{
|
||||
set->bad = true;
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
set->ids[set->count] = (int)userData;
|
||||
set->count += 1;
|
||||
return -1.0f;
|
||||
}
|
||||
|
||||
// The casts pop a pair, test both nodes and order the survivors. A ray that skips every hit
|
||||
// must still reach every proxy its segment crosses.
|
||||
static int TreeCastBruteForce( void )
|
||||
{
|
||||
s_seed = 31337;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
int proxies[PROXY_COUNT];
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 6.0f, 1.0f );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
}
|
||||
|
||||
b3DynamicTree_Rebuild( &tree, true );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
|
||||
int totalCrossings = 0;
|
||||
for ( int round = 0; round < 100; ++round )
|
||||
{
|
||||
b3Vec3 origin = { RandomFloat( -8.0f, 8.0f ), RandomFloat( -8.0f, 8.0f ), RandomFloat( -8.0f, 8.0f ) };
|
||||
b3Vec3 translation = { RandomFloat( -16.0f, 16.0f ), RandomFloat( -16.0f, 16.0f ), RandomFloat( -16.0f, 16.0f ) };
|
||||
|
||||
b3RayCastInput rayInput = { .origin = origin, .translation = translation, .maxFraction = 1.0f };
|
||||
|
||||
HitSet treeHits = { 0 };
|
||||
b3DynamicTree_RayCast( &tree, &rayInput, B3_DEFAULT_MASK_BITS, false, RayCastCollectCallback, &treeHits );
|
||||
ENSURE( treeHits.bad == false );
|
||||
|
||||
// The tree may report a superset because it tests the node box, not the shape. Every
|
||||
// proxy the segment actually crosses has to be in there.
|
||||
b3Vec3 p2 = b3MulAdd( origin, 1.0f, translation );
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
float minFraction = 0.0f;
|
||||
float maxFraction = 1.0f;
|
||||
if ( b3RayCastAABB( boxes[i], origin, p2, &minFraction, &maxFraction ) == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
for ( int j = 0; j < treeHits.count; ++j )
|
||||
{
|
||||
if ( treeHits.ids[j] == i )
|
||||
{
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ENSURE( found );
|
||||
totalCrossings += 1;
|
||||
}
|
||||
|
||||
// Every reported proxy has to at least overlap the segment box
|
||||
b3AABB segmentBox = { b3Min( origin, p2 ), b3Max( origin, p2 ) };
|
||||
for ( int j = 0; j < treeHits.count; ++j )
|
||||
{
|
||||
ENSURE( b3AABB_Overlaps( boxes[treeHits.ids[j]], segmentBox ) );
|
||||
}
|
||||
|
||||
// A zero extent box cast has to reach the same proxies as the ray
|
||||
b3AABB castBox = { origin, origin };
|
||||
b3BoxCastInput boxInput = { .box = castBox, .translation = translation, .maxFraction = 1.0f };
|
||||
|
||||
HitSet boxHits = { 0 };
|
||||
b3DynamicTree_BoxCast( &tree, &boxInput, B3_DEFAULT_MASK_BITS, false, BoxCastCollectCallback, &boxHits );
|
||||
ENSURE( boxHits.bad == false );
|
||||
|
||||
for ( int j = 0; j < treeHits.count; ++j )
|
||||
{
|
||||
bool found = false;
|
||||
for ( int k = 0; k < boxHits.count; ++k )
|
||||
{
|
||||
if ( boxHits.ids[k] == treeHits.ids[j] )
|
||||
{
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ENSURE( found );
|
||||
}
|
||||
}
|
||||
|
||||
// Guard against the comparisons above agreeing on nothing
|
||||
ENSURE( totalCrossings > 100 );
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
typedef struct ClosestResult
|
||||
{
|
||||
const b3AABB* boxes;
|
||||
b3Vec3 point;
|
||||
bool bad;
|
||||
} ClosestResult;
|
||||
|
||||
static float DistanceToBoxSqr( b3Vec3 point, b3AABB box )
|
||||
{
|
||||
b3Vec3 r = b3Sub( point, b3Clamp( point, box.lowerBound, box.upperBound ) );
|
||||
return b3Dot( r, r );
|
||||
}
|
||||
|
||||
static float ClosestCollectCallback( float distanceSqrMin, int proxyId, uint64_t userData, void* context )
|
||||
{
|
||||
ClosestResult* result = context;
|
||||
if ( (int)userData != proxyId )
|
||||
{
|
||||
result->bad = true;
|
||||
return distanceSqrMin;
|
||||
}
|
||||
|
||||
float d = DistanceToBoxSqr( result->point, result->boxes[proxyId] );
|
||||
return d < distanceSqrMin ? d : distanceSqrMin;
|
||||
}
|
||||
|
||||
// The closest query orders by distance and prunes on the running minimum, so seeding it from
|
||||
// the root pair has to be right or it prunes away a whole half of the tree.
|
||||
static int TreeQueryClosest( void )
|
||||
{
|
||||
s_seed = 5150;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 6.0f, 0.9f );
|
||||
int proxyId = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
ENSURE( proxyId == i );
|
||||
}
|
||||
|
||||
for ( int round = 0; round < 100; ++round )
|
||||
{
|
||||
b3Vec3 point = { RandomFloat( -8.0f, 8.0f ), RandomFloat( -8.0f, 8.0f ), RandomFloat( -8.0f, 8.0f ) };
|
||||
|
||||
float bruteBest = FLT_MAX;
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
float d = DistanceToBoxSqr( point, boxes[i] );
|
||||
if ( d < bruteBest )
|
||||
{
|
||||
bruteBest = d;
|
||||
}
|
||||
}
|
||||
|
||||
// The callback reports the exact box distance, so the pruned search has to land on the
|
||||
// same minimum as the scan. Same arithmetic both ways, so this is an exact compare.
|
||||
ClosestResult result = { .boxes = boxes, .point = point };
|
||||
float minDistanceSqr = FLT_MAX;
|
||||
b3DynamicTree_QueryClosest( &tree, point, B3_DEFAULT_MASK_BITS, false, ClosestCollectCallback, &result,
|
||||
&minDistanceSqr );
|
||||
|
||||
ENSURE( result.bad == false );
|
||||
ENSURE( minDistanceSqr == bruteBest );
|
||||
}
|
||||
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// A saved tree carries only its live node range. A baked compound tree has no parent array, so
|
||||
// saving one has to bail out rather than write from a null pointer.
|
||||
static int TreeSaveLoadRoundtrip( void )
|
||||
{
|
||||
s_seed = 4242;
|
||||
|
||||
b3DynamicTree tree = b3DynamicTree_Create( 16 );
|
||||
|
||||
b3AABB boxes[PROXY_COUNT];
|
||||
int proxies[PROXY_COUNT];
|
||||
|
||||
for ( int i = 0; i < PROXY_COUNT; ++i )
|
||||
{
|
||||
boxes[i] = RandomBox( 6.0f, 1.0f );
|
||||
proxies[i] = b3DynamicTree_CreateProxy( &tree, boxes[i], B3_DEFAULT_CATEGORY_BITS, (uint64_t)i );
|
||||
}
|
||||
|
||||
// Destroy a few so the pair free list is populated and the node tail is stale
|
||||
for ( int i = 0; i < PROXY_COUNT; i += 37 )
|
||||
{
|
||||
b3DynamicTree_DestroyProxy( &tree, proxies[i] );
|
||||
}
|
||||
|
||||
b3DynamicTree_Rebuild( &tree, true );
|
||||
b3DynamicTree_Validate( &tree );
|
||||
|
||||
const char* treePath = "test_dynamic_tree_roundtrip.dat";
|
||||
b3DynamicTree_Save( &tree, treePath );
|
||||
|
||||
b3DynamicTree loaded = b3DynamicTree_Load( treePath, 1.0f );
|
||||
remove( treePath );
|
||||
|
||||
ENSURE( loaded.nodes != NULL );
|
||||
ENSURE( loaded.nodeEnd == tree.nodeEnd );
|
||||
ENSURE( loaded.nodeCapacity == tree.nodeEnd );
|
||||
ENSURE( b3DynamicTree_GetProxyCount( &loaded ) == b3DynamicTree_GetProxyCount( &tree ) );
|
||||
ENSURE( memcmp( loaded.nodes, tree.nodes, (size_t)tree.nodeEnd * sizeof( b3TreeNode ) ) == 0 );
|
||||
ENSURE( memcmp( loaded.parents, tree.parents, (size_t)tree.nodeEnd * sizeof( int32_t ) ) == 0 );
|
||||
b3DynamicTree_Validate( &loaded );
|
||||
|
||||
b3DynamicTree_Destroy( &loaded );
|
||||
b3DynamicTree_Destroy( &tree );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
|
||||
|
||||
b3CompoundHullDef hulls[2];
|
||||
hulls[0].hull = &box.base;
|
||||
hulls[0].transform = (b3Transform){ { -1.0f, 0.0f, 0.0f }, b3Quat_identity };
|
||||
hulls[0].material = b3DefaultSurfaceMaterial();
|
||||
hulls[1].hull = &box.base;
|
||||
hulls[1].transform = (b3Transform){ { 1.0f, 0.0f, 0.0f }, b3Quat_identity };
|
||||
hulls[1].material = b3DefaultSurfaceMaterial();
|
||||
|
||||
b3CompoundDef compoundDef = { 0 };
|
||||
compoundDef.hulls = hulls;
|
||||
compoundDef.hullCount = 2;
|
||||
b3CompoundData* compound = b3CreateCompound( &compoundDef );
|
||||
ENSURE( compound != NULL );
|
||||
ENSURE( compound->tree.parents == NULL );
|
||||
ENSURE( compound->tree.proxyCapacity == compound->tree.proxyCount );
|
||||
|
||||
const char* compoundPath = "test_dynamic_tree_compound.dat";
|
||||
remove( compoundPath );
|
||||
b3DynamicTree_Save( &compound->tree, compoundPath );
|
||||
|
||||
b3DynamicTree noTree = b3DynamicTree_Load( compoundPath, 1.0f );
|
||||
remove( compoundPath );
|
||||
ENSURE( noTree.nodes == NULL );
|
||||
|
||||
b3DestroyCompound( compound );
|
||||
return 0;
|
||||
}
|
||||
|
||||
int DynamicTreeTest( void )
|
||||
{
|
||||
RUN_SUBTEST( TreeLeafRoot );
|
||||
RUN_SUBTEST( TreeQueryBruteForce );
|
||||
RUN_SUBTEST( TreeCategoryFilter );
|
||||
RUN_SUBTEST( TreeMoveRefitRebuild );
|
||||
RUN_SUBTEST( TreeDestroyScrambled );
|
||||
RUN_SUBTEST( TreeCastBruteForce );
|
||||
RUN_SUBTEST( TreeQueryClosest );
|
||||
RUN_SUBTEST( TreeSaveLoadRoundtrip );
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "benchmarks.h"
|
||||
#include "dynamic_tree.h"
|
||||
#include "overflow_color.h"
|
||||
#include "physics_world.h"
|
||||
#include "test_macros.h"
|
||||
|
|
@ -971,13 +972,13 @@ static int EnableContactRecyclingTest( void )
|
|||
return 0;
|
||||
}
|
||||
|
||||
static int CountEnlargedNodes( const b3DynamicTree* tree )
|
||||
static int CountMovedNodes( const b3DynamicTree* tree )
|
||||
{
|
||||
int count = 0;
|
||||
for ( int i = 0; i < tree->nodeCapacity; ++i )
|
||||
for ( int i = 0; i < tree->nodeEnd; ++i )
|
||||
{
|
||||
const b3TreeNode* node = tree->nodes + i;
|
||||
if ( ( node->flags & b3_allocatedNode ) != 0 && ( node->flags & b3_enlargedNode ) != 0 )
|
||||
if ( b3IsEmptyNode( node ) == false && b3IsNodeMoved( node ) )
|
||||
{
|
||||
count += 1;
|
||||
}
|
||||
|
|
@ -1020,22 +1021,73 @@ static int TestEnlargedProxyDestroyed( void )
|
|||
float timeStep = 1.0f / 60.0f;
|
||||
b3World_Step( worldId, timeStep, 4 );
|
||||
|
||||
ENSURE( CountEnlargedNodes( tree ) > 0 );
|
||||
ENSURE( CountMovedNodes( tree ) > 0 );
|
||||
|
||||
b3DestroyBody( moverId );
|
||||
|
||||
// The mover was the only proxy in the move buffer
|
||||
ENSURE( world->broadPhase.moveArray.count == 0 );
|
||||
ENSURE( CountEnlargedNodes( tree ) > 0 );
|
||||
// Removing the leaf re-derives the marks along its path, so the tree is already consistent
|
||||
// here and nothing is left marked to drive a rebuild. What the destroy can still leave
|
||||
// stale is the DFS order the sweep refit needs, so the step has to rebuild regardless.
|
||||
b3DynamicTree_Validate( tree );
|
||||
ENSURE( CountMovedNodes( tree ) == 0 );
|
||||
|
||||
b3World_Step( worldId, timeStep, 4 );
|
||||
|
||||
ENSURE( CountEnlargedNodes( tree ) == 0 );
|
||||
ENSURE( CountMovedNodes( tree ) == 0 );
|
||||
ENSURE( tree->dfsOrdered );
|
||||
|
||||
b3DestroyWorld( worldId );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// b3DestroyBody tears shapes down inline instead of going through the shape destroy path, so it
|
||||
// needs its own compound census decrement. A leaked count pins the broad-phase on the slow
|
||||
// per-candidate compound path for the life of the world and rides along into snapshots.
|
||||
static int TestCompoundShapeCount( void )
|
||||
{
|
||||
b3WorldDef worldDef = b3DefaultWorldDef();
|
||||
b3WorldId worldId = b3CreateWorld( &worldDef );
|
||||
|
||||
b3World* world = b3GetWorldFromId( worldId );
|
||||
ENSURE( world->compoundShapeCount == 0 );
|
||||
|
||||
b3BoxHull box = b3MakeBoxHull( 1.0f, 1.0f, 1.0f );
|
||||
|
||||
b3CompoundHullDef hull;
|
||||
hull.hull = &box.base;
|
||||
hull.transform = (b3Transform){ b3Vec3_zero, b3Quat_identity };
|
||||
hull.material = b3DefaultSurfaceMaterial();
|
||||
|
||||
b3CompoundDef compoundDef = { 0 };
|
||||
compoundDef.hulls = &hull;
|
||||
compoundDef.hullCount = 1;
|
||||
b3CompoundData* compound = b3CreateCompound( &compoundDef );
|
||||
ENSURE( compound != NULL );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_staticBody;
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
|
||||
// Shape destroyed on its own
|
||||
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
b3ShapeId shapeId = b3CreateBakedCompoundShape( bodyId, &shapeDef, compound );
|
||||
ENSURE( world->compoundShapeCount == 1 );
|
||||
b3DestroyShape( shapeId, true );
|
||||
ENSURE( world->compoundShapeCount == 0 );
|
||||
b3DestroyBody( bodyId );
|
||||
|
||||
// Shape carried away by its body
|
||||
bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
b3CreateBakedCompoundShape( bodyId, &shapeDef, compound );
|
||||
ENSURE( world->compoundShapeCount == 1 );
|
||||
b3DestroyBody( bodyId );
|
||||
ENSURE( world->compoundShapeCount == 0 );
|
||||
|
||||
b3DestroyWorld( worldId );
|
||||
b3DestroyCompound( compound );
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Identical hull data is shared through a reference counted world database.
|
||||
static int TestHullDatabase( void )
|
||||
{
|
||||
|
|
@ -1247,6 +1299,7 @@ int WorldTest( void )
|
|||
RUN_SUBTEST( TestSetWorkerCount );
|
||||
RUN_SUBTEST( TestHullDatabase );
|
||||
RUN_SUBTEST( TestEnlargedProxyDestroyed );
|
||||
RUN_SUBTEST( TestCompoundShapeCount );
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue