Hull sharing (#13)

Save memory when there are many duplicate hulls. Can improve performance
in some cases.

For consistency with b3MeshData, b3Hull is renamed to b3HullData.
This commit is contained in:
Erin Catto 2026-06-11 22:39:26 -07:00 • committed by GitHub
commit a252f03b19
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
66 changed files with 881 additions and 549 deletions

View file

@ -51,7 +51,7 @@ b3DeclareArray( b3OverflowBlock );
// across copies -- hence this pointer-shared block.
typedef struct b3ArenaSharedState
{
b3ArrayC( b3OverflowBlock ) overflows;
b3Array( b3OverflowBlock ) overflows;
int maxIndex; // high water mark of the bump pointer this step
int overflowBytes; // total bytes in overflow blocks this step
int peakDemand; // all-time peak of (maxIndex + overflowBytes), survives sync

View file

@ -19,7 +19,7 @@ b3DeclareArray( b3Block );
typedef struct b3BlockAllocator
{
b3ArrayC( b3Block ) blocks;
b3Array( b3Block ) blocks;
void* freeList;
int elementSize;
int nextIndex;

View file

@ -31,7 +31,7 @@ typedef struct b3BroadPhase
// 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];
b3ArrayC( int ) moveArray;
b3Array( int ) moveArray;
// These are the results from the pair query and are used to create new contacts
// in deterministic order.

View file

@ -269,8 +269,8 @@ int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, con
{
float totalRadius = mover->radius + shape->radius;
b3ClosestApproachResult approach =
b3ClosestApproachSegments( shape->center1, shape->center2, mover->center1, mover->center2 );
b3SegmentDistanceResult approach =
b3SegmentDistance( shape->center1, shape->center2, mover->center1, mover->center2 );
// The normal points from the shape toward the mover.
float distance;

View file

@ -3,6 +3,7 @@
#include "compound.h"
#include "hull_map.h"
#include "math_internal.h"
#include "shape.h"
@ -16,7 +17,7 @@
typedef struct b3SharedHull
{
const b3Hull* hull;
const b3HullData* hull;
int hullOffset;
} b3SharedHull;
@ -88,7 +89,7 @@ b3CompoundHull b3GetCompoundHull( const b3Compound* compound, int index )
const b3HullInstance* hullInstances = (const b3HullInstance*)( (intptr_t)compound + compound->hullOffset );
uint32_t hullOffset = hullInstances[index].hullOffset;
B3_ASSERT( hullOffset >= compound->hullOffset + compound->hullCount * sizeof( b3HullInstance ) );
result.hull = (const b3Hull*)( (intptr_t)compound + hullOffset );
result.hull = (const b3HullData*)( (intptr_t)compound + hullOffset );
result.transform = hullInstances[index].transform;
result.materialIndex = hullInstances[index].materialIndex;
return result;
@ -195,36 +196,6 @@ b3ChildShape b3GetCompoundChild( const b3Compound* compound, int childIndex )
static inline size_t vt_wyhash( const void* key, size_t len );
static inline uint64_t b3HashHull( const b3Hull* hull )
{
return vt_wyhash( hull, hull->byteCount );
}
static bool b3CompareHulls( const b3Hull* hull1, const b3Hull* hull2 )
{
if ( hull1 == hull2 )
{
return true;
}
if ( hull1->byteCount != hull2->byteCount )
{
return false;
}
int result = memcmp( hull1, hull2, hull1->byteCount );
return result == 0;
}
#define NAME b3HullMap
#define KEY_TY const b3Hull*
#define VAL_TY int
#define HASH_FN b3HashHull
#define CMPR_FN b3CompareHulls
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#include "verstable.h"
static inline uint64_t b3HashMesh( const b3MeshData* mesh )
{
return vt_wyhash( mesh, mesh->byteCount );
@ -357,7 +328,7 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
for ( int i = 0; i < hullCount; ++i )
{
const b3CompoundHullDef* hullDef = def->hulls + i;
const b3Hull* hull = hullDef->hull;
const b3HullData* hull = hullDef->hull;
b3AABB aabb = b3ComputeHullAABB( hull, hullDef->transform );
b3DynamicTree_CreateProxy( &tree, aabb, ~0ull, childIndex );
childIndex += 1;
@ -607,7 +578,7 @@ b3Compound* b3CreateCompound( const b3CompoundDef* def )
for ( int i = 0; i < sharedHullCount; ++i )
{
int offset = sharedHulls[i].hullOffset;
b3Hull* destinationHull = (b3Hull*)( (intptr_t)compound + offset );
b3HullData* destinationHull = (b3HullData*)( (intptr_t)compound + offset );
memcpy( destinationHull, sharedHulls[i].hull, sharedHulls[i].hull->byteCount );
}

View file

@ -44,10 +44,10 @@ typedef struct b3GraphColor
b3BitSet bodySet;
// cache friendly arrays
b3ArrayC( b3JointSim ) jointSims;
b3Array( b3JointSim ) jointSims;
b3ArrayC( int ) convexContacts;
b3ArrayC( b3ContactSpec ) contacts;
b3Array( int ) convexContacts;
b3Array( b3ContactSpec ) contacts;
// These are used for convex contacts
struct b3ContactConstraintWide* wideConstraints;

View file

@ -83,8 +83,7 @@ typedef struct b3ContactEdge
typedef struct b3MeshContact
{
// todo use block allocator for this for faster shutdown
b3ArrayC( b3TriangleCache ) triangleCache;
b3Array( b3TriangleCache ) triangleCache;
b3AABB queryBounds;
} b3MeshContact;

View file

@ -12,12 +12,12 @@
#define b3DeclareArray( T ) \
typedef struct b3DynamicArray_##T \
{ \
struct T* data; \
struct T* data; \
int count; \
int capacity; \
} b3DynamicArray_##T
#define b3DeclareArrayNative( T ) \
#define b3DeclareArrayNative( T ) \
typedef struct b3DynamicArray_##T \
{ \
T* data; \
@ -27,8 +27,8 @@
// Define an array.
// It may be zero initialized:
// b3ArrayC(int) myArray = { 0 };
#define b3ArrayC( T ) b3DynamicArray_##T
// b3Array(int) myArray = { 0 };
#define b3Array( T ) b3DynamicArray_##T
// Alternative to zero initialization
#define b3Array_Create( a ) \
@ -110,22 +110,22 @@
#define b3Array_AddIndex( a ) \
( b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ), ( a ).count - 1 )
// Append a contiguous run of values.
// Append a contiguous run of values. _n is used to cache the input count while avoiding naming conflicts.
#define b3Array_Append( a, src, n ) \
do \
{ \
int b3_n = ( n ); \
if ( ( a ).count + b3_n > ( a ).capacity ) \
int _n = ( n ); \
if ( ( a ).count + _n > ( a ).capacity ) \
{ \
int req = ( a ).count + b3_n; \
int req = ( a ).count + _n; \
int newCapacity = req > 2 ? req + ( req >> 1 ) : 8; \
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newSize = newCapacity * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = newCapacity; \
} \
memcpy( ( a ).data + ( a ).count, ( src ), b3_n * sizeof( *( a ).data ) ); \
( a ).count += b3_n; \
memcpy( ( a ).data + ( a ).count, ( src ), _n * sizeof( *( a ).data ) ); \
( a ).count += _n; \
} \
while ( 0 )

View file

@ -69,7 +69,7 @@ static int b3ClipSegment( b3ClipVertex segment[2], b3Plane plane )
return vertexCount;
}
static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3Hull* hull, int refFace )
static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3HullData* hull, int refFace )
{
const b3HullFace* faces = b3GetHullFaces( hull );
const b3Plane* planes = b3GetHullPlanes( hull );
@ -106,7 +106,7 @@ static int b3ClipSegmentToHullFace( b3ClipVertex segment[2], const b3Hull* hull,
return 2;
}
static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3Hull* hull, const b3Capsule* capsule,
static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3HullData* hull, const b3Capsule* capsule,
b3Transform capsuleTransform )
{
int maxFaceIndex = -1;
@ -141,7 +141,7 @@ static b3FaceQuery b3QueryFaceDirectionHullAndCapsule( const b3Hull* hull, const
};
}
static b3FaceQuery b3QueryFaceDirections( const b3Hull* hullA, const b3Hull* hullB, b3Transform relativeTransform )
static b3FaceQuery b3QueryFaceDirections( const b3HullData* hullA, const b3HullData* hullB, b3Transform relativeTransform )
{
// We perform all computations in local space of the second hull
b3Transform transform = b3InvertTransform( relativeTransform );
@ -174,7 +174,7 @@ static b3FaceQuery b3QueryFaceDirections( const b3Hull* hullA, const b3Hull* hul
};
}
static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3Hull* hull, const b3Capsule* capsule,
static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3HullData* hull, const b3Capsule* capsule,
b3Transform capsuleTransform )
{
// Find axis of minimum penetration
@ -230,7 +230,7 @@ static b3EdgeQuery b3QueryEdgeDirectionHullAndCapsule( const b3Hull* hull, const
};
}
static b3EdgeQuery b3QueryEdgeDirections( const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA )
static b3EdgeQuery b3QueryEdgeDirections( const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA )
{
// Find axis of minimum penetration
float maxSeparation = -FLT_MAX;
@ -535,7 +535,7 @@ void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b
float totalRadius = sphereB->radius + capsuleA->radius;
b3Vec3 closestPoint = b3ClosestPointOnSegment( center1, center2, center );
b3Vec3 closestPoint = b3PointToSegmentDistance( center1, center2, center );
b3Vec3 offset = b3Sub( center, closestPoint );
float distanceSq = b3LengthSquared( offset );
@ -567,7 +567,7 @@ void b3CollideCapsuleAndSphere( b3LocalManifold* manifold, int capacity, const b
pt->pair = b3FeaturePair_single;
}
void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Sphere* sphereB,
void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Sphere* sphereB,
b3Transform transformBtoA, b3SimplexCache* cache )
{
manifold->pointCount = 0;
@ -685,7 +685,7 @@ void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule
float radius = capsuleA->radius + capsuleB->radius;
float maxDistance = radius + B3_SPECULATIVE_DISTANCE;
b3ClosestApproachResult result = b3ClosestApproachSegments( centerA1, centerA2, centerB1, centerB2 );
b3SegmentDistanceResult result = b3SegmentDistance( centerA1, centerA2, centerB1, centerB2 );
b3Vec3 offset = b3Sub( result.point2, result.point1 );
float distanceSquared = b3LengthSquared( offset );
float linearSlop = B3_LINEAR_SLOP;
@ -748,8 +748,8 @@ void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule
if ( pointCount == 2 )
{
// Closest points on A to the clipped points on B.
b3Vec3 closestPoint1 = b3ClosestPointOnSegment( centerA1, centerA2, verticesB[0].position );
b3Vec3 closestPoint2 = b3ClosestPointOnSegment( centerA1, centerA2, verticesB[1].position );
b3Vec3 closestPoint1 = b3PointToSegmentDistance( centerA1, centerA2, verticesB[0].position );
b3Vec3 closestPoint2 = b3PointToSegmentDistance( centerA1, centerA2, verticesB[1].position );
float distance1 = b3Distance( closestPoint1, verticesB[0].position );
float distance2 = b3Distance( closestPoint2, verticesB[1].position );
@ -810,7 +810,7 @@ void b3CollideCapsules( b3LocalManifold* manifold, int capacity, const b3Capsule
pt->pair = b3FeaturePair_single;
}
static bool b3BuildHullFaceAndCapsuleContact( b3LocalManifold* manifold, const b3Hull* hullA, const b3Capsule* capsuleB,
static bool b3BuildHullFaceAndCapsuleContact( b3LocalManifold* manifold, const b3HullData* hullA, const b3Capsule* capsuleB,
b3Transform transformBtoA, b3FaceQuery query )
{
// Work in shapeA coordinates
@ -877,7 +877,7 @@ static inline float b3DeepestPointSeparation( const b3LocalManifold* manifold )
return minSeparation;
}
static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA,
static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA,
const b3Capsule* capsuleB, b3Transform transformBtoA, b3EdgeQuery query )
{
if ( capacity < 1 )
@ -910,7 +910,7 @@ static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int cap
normal = b3Neg( normal );
}
b3ClosestApproachResult result = b3ClosestApproachLines( ph, eh, pc, ec );
b3SegmentDistanceResult result = b3LineDistance( ph, eh, pc, ec );
if ( b3IsWithinSegments( &result ) == false )
{
@ -934,7 +934,7 @@ static bool b3BuildHullAndCapsuleEdgeContact( b3LocalManifold* manifold, int cap
return true;
}
void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Capsule* capsuleB,
void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3Capsule* capsuleB,
b3Transform transformBtoA, b3SimplexCache* cache )
{
manifold->pointCount = 0;
@ -1071,7 +1071,7 @@ void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3H
}
}
static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3Hull* hull, int incFace, b3Plane refPlane )
static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3HullData* hull, int incFace, b3Plane refPlane )
{
const b3HullFace* faces = b3GetHullFaces( hull );
const b3HullHalfEdge* edges = b3GetHullEdges( hull );
@ -1109,7 +1109,7 @@ static int b3BuildPolygon( b3ClipVertex* out, b3Transform transform, const b3Hul
return outCount;
}
static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB,
static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB,
b3Transform transformBtoA, b3FaceQuery query, b3SATCache* cache )
{
const b3HullFace* facesA = b3GetHullFaces( hullA );
@ -1206,7 +1206,7 @@ static bool b3BuildFaceAContact( b3LocalManifold* manifold, int capacity, const
return true;
}
static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB,
static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB,
b3Transform transformBtoA, b3FaceQuery query, b3SATCache* cache )
{
b3Transform transformAtoB = b3InvertTransform( transformBtoA );
@ -1237,7 +1237,7 @@ static bool b3BuildFaceBContact( b3LocalManifold* manifold, int capacity, const
return true;
}
static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA,
static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA,
b3EdgeQuery query, b3SATCache* cache )
{
// Work in shapeA coordinates
@ -1270,7 +1270,7 @@ static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA,
normal = b3Neg( normal );
}
b3ClosestApproachResult result = b3ClosestApproachLines( pA, eA, pB, eB );
b3SegmentDistanceResult result = b3LineDistance( pA, eA, pB, eB );
if ( b3IsWithinSegments( &result ) == false )
{
@ -1304,7 +1304,7 @@ static bool b3BuildEdgeContact( b3LocalManifold* manifold, const b3Hull* hullA,
return true;
}
void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, const b3Hull* hullB, b3Transform transformBtoA,
void b3CollideHulls( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, const b3HullData* hullB, b3Transform transformBtoA,
b3SATCache* cache )
{
manifold->pointCount = 0;

View file

@ -131,6 +131,12 @@ void* b3GrowAlloc( void* oldMem, int oldSize, int newSize );
void b3Log( const char* format, ... );
// Geometry content hashes reserve zero to mean unhashed
static inline uint32_t b3NonZeroHash( uint32_t hash )
{
return hash != 0 ? hash : 1;
}
typedef struct b3Mutex b3Mutex;
b3Mutex* b3CreateMutex( void );
void b3DestroyMutex( b3Mutex* m );

View file

@ -3,6 +3,9 @@
#pragma once
#include "box3d/base.h"
#include <stdbool.h>
#include <stdint.h>
#if defined( _MSC_VER ) && !defined( __clang__ )
@ -11,7 +14,7 @@
// https://en.wikipedia.org/wiki/Find_first_set
B3_INLINE uint32_t b3CTZ32( uint32_t block )
static inline uint32_t b3CTZ32( uint32_t block )
{
unsigned long index;
_BitScanForward( &index, block );
@ -19,7 +22,7 @@ B3_INLINE uint32_t b3CTZ32( uint32_t block )
}
// This function doesn't need to be fast, so using the Ivy Bridge fallback.
B3_INLINE uint32_t b3CLZ32( uint32_t value )
static inline uint32_t b3CLZ32( uint32_t value )
{
#if 0
@ -45,7 +48,7 @@ B3_INLINE uint32_t b3CLZ32( uint32_t value )
#endif
}
B3_INLINE uint32_t b3CTZ64( uint64_t block )
static inline uint32_t b3CTZ64( uint64_t block )
{
unsigned long index;
@ -67,41 +70,41 @@ B3_INLINE uint32_t b3CTZ64( uint64_t block )
return index;
}
B3_INLINE int b3PopCount64( uint64_t block )
static inline int b3PopCount64( uint64_t block )
{
return (int)__popcnt64( block );
}
#else
B3_INLINE uint32_t b3CTZ32( uint32_t block )
static inline uint32_t b3CTZ32( uint32_t block )
{
return __builtin_ctz( block );
}
B3_INLINE uint32_t b3CLZ32( uint32_t value )
static inline uint32_t b3CLZ32( uint32_t value )
{
return __builtin_clz( value );
}
B3_INLINE uint32_t b3CTZ64( uint64_t block )
static inline uint32_t b3CTZ64( uint64_t block )
{
return __builtin_ctzll( block );
}
B3_INLINE int b3PopCount64( uint64_t block )
static inline int b3PopCount64( uint64_t block )
{
return __builtin_popcountll( block );
}
#endif
B3_INLINE bool b3IsPowerOf2( int x )
static inline bool b3IsPowerOf2( int x )
{
return ( x & ( x - 1 ) ) == 0;
}
B3_INLINE int b3BoundingPowerOf2( int x )
static inline int b3BoundingPowerOf2( int x )
{
if ( x <= 1 )
{
@ -111,7 +114,7 @@ B3_INLINE int b3BoundingPowerOf2( int x )
return 32 - (int)b3CLZ32( (uint32_t)x - 1 );
}
B3_INLINE int b3RoundUpPowerOf2( int x )
static inline int b3RoundUpPowerOf2( int x )
{
if ( x <= 1 )
{
@ -121,7 +124,7 @@ B3_INLINE int b3RoundUpPowerOf2( int x )
return 1 << ( 32 - (int)b3CLZ32( (uint32_t)x - 1 ) );
}
B3_INLINE int b3LowerPowerOf2Exponent( int x )
static inline int b3LowerPowerOf2Exponent( int x )
{
B3_ASSERT( x > 0 );
int clz = (int)b3CLZ32( (uint32_t)x );

View file

@ -465,7 +465,7 @@ b3HeightField* b3CreateHeightField( const b3HeightFieldDef* data )
h = b3Hash( h, (const uint8_t*)hf->materialIndices, cellCount * (int)sizeof( uint8_t ) );
h = b3Hash( h, (const uint8_t*)hf->flags, triangleCount * (int)sizeof( uint8_t ) );
h = b3Hash( h, (const uint8_t*)&hf->aabb, (int)( sizeof( b3HeightField ) - offsetof( b3HeightField, aabb ) ) );
hf->hash = h;
hf->hash = b3NonZeroHash( h );
return hf;
}

View file

@ -4,6 +4,7 @@
// Dirk Gregorius contributed portions of this code
#include "algorithm.h"
#include "hull_map.h"
#include "math_internal.h"
#include "shape.h"
@ -1570,7 +1571,7 @@ static void b3HullBuilder_Init( b3HullBuilder* b, char* mem, const b3HullWorkSiz
b->horizonStackCapacity = s->horizonStackCapacity;
}
static b3Vec3* b3GetHullPointsWrite( b3Hull* hull )
static b3Vec3* b3GetHullPointsWrite( b3HullData* hull )
{
if ( hull->pointOffset == 0 )
{
@ -1579,7 +1580,7 @@ static b3Vec3* b3GetHullPointsWrite( b3Hull* hull )
return (b3Vec3*)( (intptr_t)hull + hull->pointOffset );
}
static b3Plane* b3GetHullPlanesWrite( b3Hull* hull )
static b3Plane* b3GetHullPlanesWrite( b3HullData* hull )
{
if ( hull->planeOffset == 0 )
{
@ -1588,7 +1589,7 @@ static b3Plane* b3GetHullPlanesWrite( b3Hull* hull )
return (b3Plane*)( (intptr_t)hull + hull->planeOffset );
}
static b3HullVertex* b3GetHullVerticesWrite( b3Hull* hull )
static b3HullVertex* b3GetHullVerticesWrite( b3HullData* hull )
{
if ( hull->vertexOffset == 0 )
{
@ -1597,7 +1598,7 @@ static b3HullVertex* b3GetHullVerticesWrite( b3Hull* hull )
return (b3HullVertex*)( (intptr_t)hull + hull->vertexOffset );
}
static b3HullHalfEdge* b3GetHullEdgesWrite( b3Hull* hull )
static b3HullHalfEdge* b3GetHullEdgesWrite( b3HullData* hull )
{
if ( hull->edgeOffset == 0 )
{
@ -1606,7 +1607,7 @@ static b3HullHalfEdge* b3GetHullEdgesWrite( b3Hull* hull )
return (b3HullHalfEdge*)( (intptr_t)hull + hull->edgeOffset );
}
int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction )
int b3FindHullSupportVertex( const b3HullData* hull, b3Vec3 direction )
{
int bestIndex = B3_NULL_INDEX;
float bestDot = -FLT_MAX;
@ -1628,7 +1629,7 @@ int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction )
return bestIndex;
}
int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction )
int b3FindHullSupportFace( const b3HullData* hull, b3Vec3 direction )
{
int bestIndex = B3_NULL_INDEX;
float bestDot = -FLT_MAX;
@ -1652,7 +1653,7 @@ int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction )
#if B3_ENABLE_VALIDATION
bool b3IsValidHull( const b3Hull* hull )
bool b3IsValidHull( const b3HullData* hull )
{
if ( hull->version != B3_HULL_VERSION )
{
@ -1759,7 +1760,7 @@ bool b3IsValidHull( const b3Hull* hull )
#else
bool b3IsValidHull( const b3Hull* hull )
bool b3IsValidHull( const b3HullData* hull )
{
B3_UNUSED( hull );
return true;
@ -1767,7 +1768,7 @@ bool b3IsValidHull( const b3Hull* hull )
#endif
b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides )
b3HullData* b3CreateCylinder( float height, float radius, float yOffset, int sides )
{
B3_ASSERT( height > 0.0f );
B3_ASSERT( radius > 0.0f );
@ -1791,7 +1792,7 @@ b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides )
alpha += deltaAlpha;
}
b3Hull* hull = b3CreateHull( points, pointCount, pointCount );
b3HullData* hull = b3CreateHull( points, pointCount, pointCount );
B3_ASSERT( hull->vertexCount == pointCount );
B3_ASSERT( hull->edgeCount == 6 * sides );
B3_ASSERT( hull->faceCount == sides + 2 );
@ -1801,7 +1802,7 @@ b3Hull* b3CreateCylinder( float height, float radius, float yOffset, int sides )
return hull;
}
b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices )
b3HullData* b3CreateCone( float height, float radius1, float radius2, int slices )
{
B3_ASSERT( height > 0.0f );
B3_ASSERT( radius1 > 0.0f );
@ -1826,7 +1827,7 @@ b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices )
alpha += deltaAlpha;
}
b3Hull* hull = b3CreateHull( points, pointCount, pointCount );
b3HullData* hull = b3CreateHull( points, pointCount, pointCount );
B3_ASSERT( hull->vertexCount == pointCount );
B3_ASSERT( hull->edgeCount == 6 * slices );
B3_ASSERT( hull->faceCount == slices + 2 );
@ -1836,7 +1837,7 @@ b3Hull* b3CreateCone( float height, float radius1, float radius2, int slices )
return hull;
}
static void b3UpdateHullBounds( b3Hull* hull )
static void b3UpdateHullBounds( b3HullData* hull )
{
const b3Vec3* points = b3GetHullPoints( hull );
int vertexCount = hull->vertexCount;
@ -1857,7 +1858,7 @@ static void b3UpdateHullBounds( b3Hull* hull )
}
// M. Kallay - "Computing the Moment of Inertia of a Solid Defined by a Triangle Mesh"
static bool b3UpdateHullBulkProperties( b3Hull* hull )
static bool b3UpdateHullBulkProperties( b3HullData* hull )
{
const b3Vec3* points = b3GetHullPoints( hull );
const b3HullFace* faces = b3GetHullFaces( hull );
@ -1984,7 +1985,7 @@ static bool b3UpdateHullBulkProperties( b3Hull* hull )
return true;
}
b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
{
if ( pointCount < 4 )
{
@ -2077,7 +2078,7 @@ b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
}
// Allocate the hull. Arrays hang off the end.
size_t byteCount = b3AlignUp8( sizeof( b3Hull ) );
size_t byteCount = b3AlignUp8( sizeof( b3HullData ) );
int vertexOffset = (int)byteCount;
byteCount += b3AlignUp8( vertexCount * (int)sizeof( b3HullVertex ) );
int pointOffset = (int)byteCount;
@ -2089,7 +2090,7 @@ b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
int planeOffset = (int)byteCount;
byteCount += b3AlignUp8( faceCount * (int)sizeof( b3Plane ) );
b3Hull* hull = b3Alloc( byteCount );
b3HullData* hull = b3Alloc( byteCount );
memset( hull, 0, byteCount );
hull->version = B3_HULL_VERSION;
@ -2160,32 +2161,80 @@ b3Hull* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount )
}
hull->hash = 0;
hull->hash = b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount );
hull->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ) );
return hull;
}
b3Hull* b3CloneHull( const b3Hull* hull )
b3HullData* b3CloneHull( const b3HullData* hull )
{
if ( hull == NULL || b3IsValidHull( hull ) == false )
{
return NULL;
}
b3Hull* clone = (b3Hull*)b3Alloc( hull->byteCount );
b3HullData* clone = (b3HullData*)b3Alloc( hull->byteCount );
memcpy( clone, hull, hull->byteCount );
return clone;
}
b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform, b3Vec3 scale )
uint64_t b3HashHullData( const b3HullData* hull )
{
// The baked content hash already covers byteCount. Spread the 32 bits across 64 so the table
// can use the high bits for its fast reject fragment.
return (uint64_t)hull->hash * 0x9E3779B97F4A7C15ull;
}
bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 )
{
if ( hull1 == hull2 )
{
return true;
}
if ( hull1->byteCount != hull2->byteCount )
{
return false;
}
return memcmp( hull1, hull2, hull1->byteCount ) == 0;
}
// Hull identity covers every byte, so the structs carry explicit padding. These lock
// the layout, re-audit padding if a size changes.
_Static_assert( sizeof( b3HullData ) == 136, "unexpected hull data size" );
_Static_assert( sizeof( b3BoxHull ) == 440, "unexpected box hull size" );
#define NAME b3HullMap
#define KEY_TY const b3HullData*
#define VAL_TY int
#define HASH_FN b3HashHullData
#define CMPR_FN b3CompareHullData
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#define IMPLEMENTATION_MODE
#include "verstable.h"
size_t b3HullMapByteCount( b3HullMap* map )
{
// The map owns a combined bucket and metadata allocation, valid only when buckets exist
size_t byteCount = sizeof( b3HullMap );
if ( b3HullMap_bucket_count( map ) > 0 )
{
byteCount += b3HullMap_total_alloc_size( map );
}
return byteCount;
}
b3HullData* b3CloneAndTransformHull( const b3HullData* original, b3Transform transform, b3Vec3 scale )
{
if ( original == NULL || b3IsValidHull( original ) == false )
{
return NULL;
}
b3Hull* hull = (b3Hull*)b3Alloc( original->byteCount );
b3HullData* hull = (b3HullData*)b3Alloc( original->byteCount );
memcpy( hull, original, original->byteCount );
b3Vec3 safeScale = b3SafeScale( scale );
@ -2317,19 +2366,19 @@ b3Hull* b3CloneAndTransformHull( const b3Hull* original, b3Transform transform,
}
hull->hash = 0;
hull->hash = b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount );
hull->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)hull, hull->byteCount ) );
B3_VALIDATE( b3IsValidHull( hull ) );
return hull;
}
void b3DestroyHull( b3Hull* hull )
void b3DestroyHull( b3HullData* hull )
{
b3Free( hull, hull->byteCount );
}
b3MassData b3ComputeHullMass( const b3Hull* shape, float density )
b3MassData b3ComputeHullMass( const b3HullData* shape, float density )
{
b3MassData out;
out.mass = density * shape->volume;
@ -2340,19 +2389,19 @@ b3MassData b3ComputeHullMass( const b3Hull* shape, float density )
return out;
}
b3AABB b3ComputeHullAABB( const b3Hull* shape, b3Transform transform )
b3AABB b3ComputeHullAABB( const b3HullData* shape, b3Transform transform )
{
return b3AABB_Transform( transform, shape->aabb );
}
b3AABB b3ComputeSweptHullAABB( const b3Hull* shape, b3Transform xf1, b3Transform xf2 )
b3AABB b3ComputeSweptHullAABB( const b3HullData* shape, b3Transform xf1, b3Transform xf2 )
{
b3AABB aabb1 = b3AABB_Transform( xf1, shape->aabb );
b3AABB aabb2 = b3AABB_Transform( xf2, shape->aabb );
return b3AABB_Union( aabb1, aabb2 );
}
bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
bool b3OverlapHull( const b3HullData* shape, b3Transform shapeTransform, const b3ShapeProxy* proxy )
{
const b3Vec3* points = b3GetHullPoints( shape );
@ -2368,7 +2417,7 @@ bool b3OverlapHull( const b3Hull* shape, b3Transform shapeTransform, const b3Sha
return output.distance < B3_OVERLAP_SLOP;
}
b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input )
b3CastOutput b3RayCastHull( const b3HullData* shape, const b3RayCastInput* input )
{
B3_ASSERT( b3IsValidRay( input ) );
b3CastOutput output = { 0 };
@ -2436,7 +2485,7 @@ b3CastOutput b3RayCastHull( const b3Hull* shape, const b3RayCastInput* input )
return output;
}
b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input )
b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastInput* input )
{
const b3Vec3* points = b3GetHullPoints( shape );
@ -2453,7 +2502,7 @@ b3CastOutput b3ShapeCastHull( const b3Hull* shape, const b3ShapeCastInput* input
return output;
}
int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3Capsule* mover )
int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const b3Capsule* mover )
{
const b3Vec3* points = b3GetHullPoints( shape );
b3DistanceInput distanceInput;
@ -2487,7 +2536,7 @@ int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3C
return 0;
}
b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin )
b3ShapeExtent b3ComputeHullExtent( const b3HullData* hull, b3Vec3 origin )
{
const b3Vec3* points = b3GetHullPoints( hull );
@ -2503,7 +2552,7 @@ b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin )
return extent;
}
float b3ComputeHullProjectedArea( const b3Hull* hull, b3Vec3 direction )
float b3ComputeHullProjectedArea( const b3HullData* hull, b3Vec3 direction )
{
float area = 0.0f;
@ -2630,7 +2679,7 @@ b3BoxHull b3MakeTransformedBoxHull( float hx, float hy, float hz, b3Transform tr
boxHull.boxPoints[7] = b3TransformPoint( transform, (b3Vec3){ h.x, -h.y, -h.z } );
boxHull.base.hash = 0;
boxHull.base.hash = b3Hash( B3_HASH_INIT, (uint8_t*)&boxHull, sizeof( b3BoxHull ) );
boxHull.base.hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)&boxHull, sizeof( b3BoxHull ) ) );
return boxHull;
}

24
src/hull_map.h Normal file
View file

@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/types.h"
#include <stddef.h>
// Content hash and equality over the whole baked hull. Shared by every hull
// de-duplication map so they agree on identity.
uint64_t b3HashHullData( const b3HullData* hull );
bool b3CompareHullData( const b3HullData* hull1, const b3HullData* hull2 );
// Map keyed by hull content. The world hull database stores a reference count,
// compound baking stores a byte offset. Implementation lives in hull.c.
#define NAME b3HullMap
#define KEY_TY const b3HullData*
#define VAL_TY int
#define HEADER_MODE
#include "verstable.h"
// Total map allocation in bytes, excluding the stored hull data
size_t b3HullMapByteCount( b3HullMap* map );

View file

@ -7,7 +7,7 @@
typedef struct b3IdPool
{
b3ArrayC( int ) freeArray;
b3Array( int ) freeArray;
int nextIndex;
} b3IdPool;

View file

@ -63,14 +63,14 @@ typedef struct b3Island
// I tried using a stack array for this but the data pointer goes out of
// sync when the world island array grows.
b3ArrayC( int ) bodies;
b3Array( int ) bodies;
// Contacts and joints that belong to this island. May connect to static
// bodies not in the island.
// Each link has the two body ids so that b3SplitIsland's union-find pass
// never needs to touch b3Contact/b3Joint.
b3ArrayC( b3ContactLink ) contacts;
b3ArrayC( b3JointLink ) joints;
b3Array( b3ContactLink ) contacts;
b3Array( b3JointLink ) joints;
} b3Island;

View file

@ -67,7 +67,7 @@ float b3EdgeEdgeSeparation( b3Vec3 p1, b3Vec3 e1, b3Vec3 c1, b3Vec3 p2, b3Vec3 e
// Then we look for all edges coming out of that vertex and look for the edge that is
// most perpendicular to the reference normal.
// Then from that edge, we select the adjacent face that is most anti-parallel to the reference normal.
int b3FindIncidentFace( const b3Hull* hull, b3Vec3 refNormal, int vertexIndex )
int b3FindIncidentFace( const b3HullData* hull, b3Vec3 refNormal, int vertexIndex )
{
const b3HullVertex* vertices = b3GetHullVertices( hull );
const b3HullHalfEdge* edges = b3GetHullEdges( hull );

View file

@ -36,7 +36,7 @@ typedef enum b3FeatureOwner
} b3FeatureOwner;
float b3EdgeEdgeSeparation( b3Vec3 p1, b3Vec3 e1, b3Vec3 c1, b3Vec3 p2, b3Vec3 e2, b3Vec3 c2 );
int b3FindIncidentFace( const b3Hull* hull, b3Vec3 refNormal, int vertexIndex );
int b3FindIncidentFace( const b3HullData* hull, b3Vec3 refNormal, int vertexIndex );
b3FeaturePair b3MakeFeaturePair( b3FeatureOwner owner1, int index1, b3FeatureOwner owner2, int index2 );
b3FeaturePair b3FlipPair( b3FeaturePair pair );

View file

@ -315,9 +315,9 @@ b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 )
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 )
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 )
{
b3ClosestApproachResult result;
b3SegmentDistanceResult result;
// Solve A*x = b
float a11 = b3Dot( d1, d1 );
@ -355,9 +355,9 @@ b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2,
}
//--------------------------------------------------------------------------------------------------
b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 )
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 )
{
b3ClosestApproachResult result;
b3SegmentDistanceResult result;
b3Vec3 d1 = b3Sub( q1, p1 );
b3Vec3 d2 = b3Sub( q2, p2 );
@ -432,7 +432,7 @@ b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3
return result;
}
b3Vec3 b3ClosestPointOnSegment( b3Vec3 a, b3Vec3 b, b3Vec3 q )
b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q )
{
b3Vec3 ab = b3Sub( b, a );
b3Vec3 aq = b3Sub( q, a );

View file

@ -31,7 +31,7 @@ typedef struct b3Triangle
int flags;
} b3Triangle;
typedef struct
typedef struct b3TrianglePoint
{
b3Vec3 point;
b3TriangleFeature feature;
@ -46,22 +46,22 @@ typedef struct b3ShapeExtent
b3TrianglePoint b3ClosestPointOnTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 q );
// The closest points between to segments or infinite lines.
typedef struct b3ClosestApproachResult
typedef struct b3SegmentDistanceResult
{
b3Vec3 point1;
float fraction1;
b3Vec3 point2;
float fraction2;
} b3ClosestApproachResult;
} b3SegmentDistanceResult;
// Compute the closest point on the segment a-b to the target q
b3Vec3 b3ClosestPointOnSegment( b3Vec3 a, b3Vec3 b, b3Vec3 q );
b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q );
// Compute the closest points on two infinite lines
b3ClosestApproachResult b3ClosestApproachLines( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
// Compute the closest points on two line segments
b3ClosestApproachResult b3ClosestApproachSegments( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
float b3IntersectSegmentTriangle( b3Vec3 p, b3Vec3 q, b3Vec3 a, b3Vec3 b, b3Vec3 c );
float b3IntersectSegmentSphere( b3Vec3 p, b3Vec3 q, b3Vec3 c, float r );
@ -470,7 +470,7 @@ static inline float b3SignedVolume( b3Vec3 v1, b3Vec3 v2, b3Vec3 v3, b3Vec3 p )
}
// todo eliminate this
static inline bool b3IsWithinSegments( const b3ClosestApproachResult* result )
static inline bool b3IsWithinSegments( const b3SegmentDistanceResult* result )
{
return ( 0.0f <= result->fraction1 && result->fraction1 <= 1.0f ) &&
( 0.0f <= result->fraction2 && result->fraction2 <= 1.0f );

View file

@ -347,7 +347,7 @@ typedef struct b3VertexNode
typedef struct b3SpatialHash
{
b3ArrayC( b3VertexNode ) nodes;
b3Array( b3VertexNode ) nodes;
const b3Vec3* vertices;
int vertexCount;
b3VertexMap vertexMap;
@ -491,7 +491,7 @@ static int b3WeldVertices( b3WeldData* data, float tolerance )
// Create spatial hash and find duplicates
b3SpatialHash spatialHash;
b3SpatialHash_Create( &spatialHash, data->srcVertices, vertexCount, tolerance );
b3ArrayC( int ) vertexMapping = { 0 };
b3Array( int ) vertexMapping = { 0 };
b3Array_Resize( vertexMapping, vertexCount );
for ( int i = 0; i < vertexCount; ++i )
@ -870,7 +870,7 @@ static bool b3ValidateSplit( int count, b3Primitive* primitives, const b3Split*
#endif
static int b3BuildRecursive( b3ArrayC( b3MeshNode ) * nodes, int count, b3Primitive* primitives, b3Primitive* base,
static int b3BuildRecursive( b3Array( b3MeshNode ) * nodes, int count, b3Primitive* primitives, b3Primitive* base,
bool useMedianSplit, int* height )
{
if ( count > B3_DESIRED_TRIANGLES_PER_LEAF )
@ -955,10 +955,10 @@ static bool b3SortMeshTriangles( b3MeshData* mesh )
// Sort triangles in depth-first-order
int offset = 0;
b3ArrayC( b3MeshTriangle ) tempTriangles;
b3Array( b3MeshTriangle ) tempTriangles;
b3Array_CreateN( tempTriangles, mesh->triangleCount );
b3ArrayC( uint8_t ) tempMaterialIndices;
b3Array( uint8_t ) tempMaterialIndices;
b3Array_CreateN( tempMaterialIndices, mesh->triangleCount );
int count = 0;
@ -1220,7 +1220,7 @@ b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int mater
// Create vertices
int vertexCount = ( xCount + 1 ) * ( zCount + 1 );
b3ArrayC( b3Vec3 ) vertices = { 0 };
b3Array( b3Vec3 ) vertices = { 0 };
b3Array_Resize( vertices, vertexCount );
int index = 0;
@ -1244,10 +1244,10 @@ b3MeshData* b3CreateGridMesh( int xCount, int zCount, float cellWidth, int mater
// Triangles
int triangleCount = 2 * xCount * zCount;
b3ArrayC( int ) indices = { 0 };
b3Array( int ) indices = { 0 };
b3Array_Resize( indices, 3 * triangleCount );
b3ArrayC( uint8_t ) materialIndices = { 0 };
b3Array( uint8_t ) materialIndices = { 0 };
b3Array_Resize( materialIndices, triangleCount );
int materialIndex = 0;
@ -1310,7 +1310,7 @@ b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amp
// Create vertices
int vertexCount = ( xCount + 1 ) * ( zCount + 1 );
b3ArrayC( b3Vec3 ) vertices = { 0 };
b3Array( b3Vec3 ) vertices = { 0 };
b3Array_Resize( vertices, vertexCount );
int index = 0;
@ -1342,7 +1342,7 @@ b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amp
// Triangles
int triangleCount = 2 * xCount * zCount;
b3ArrayC( int ) indices = { 0 };
b3Array( int ) indices = { 0 };
b3Array_Resize( indices, 3 * triangleCount );
index = 0;
@ -1392,7 +1392,7 @@ b3MeshData* b3CreateWaveMesh( int xCount, int zCount, float cellWidth, float amp
b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, float radius, float thickness )
{
// Create vertices
b3ArrayC( b3Vec3 ) vertices = { 0 };
b3Array( b3Vec3 ) vertices = { 0 };
for ( int radialIndex = 0; radialIndex < radialResolution; radialIndex++ )
{
@ -1411,7 +1411,7 @@ b3MeshData* b3CreateTorusMesh( int radialResolution, int tubularResolution, floa
}
// Triangles
b3ArrayC( int ) indices = { 0 };
b3Array( int ) indices = { 0 };
for ( int radialIndex1 = 0; radialIndex1 < radialResolution; radialIndex1++ )
{
int radialIndex2 = ( radialIndex1 + 1 ) % radialResolution;
@ -1570,10 +1570,10 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3AABB meshBounds = B3_BOUNDS3_EMPTY;
// Clone indices and vertices to support welding
b3ArrayC( int ) indices;
b3Array( int ) indices;
b3Array_CreateN( indices, 3 * triangleCount );
b3ArrayC( b3Vec3 ) vertices;
b3Array( b3Vec3 ) vertices;
b3Array_CreateN( vertices, vertexCount );
if ( def->weldVertices && def->weldTolerance > 0.0f )
@ -1598,7 +1598,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3Array_Append( indices, def->indices, 3 * triangleCount );
}
b3ArrayC( b3Primitive ) primitives;
b3Array( b3Primitive ) primitives;
b3Array_CreateN( primitives, triangleCount );
int degenerateCount = 0;
float minArea = 0.01f * B3_LINEAR_SLOP * B3_LINEAR_SLOP;
@ -1668,7 +1668,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
}
// Build the tree (this reorders the builder triangles)
b3ArrayC( b3MeshNode ) tempNodes;
b3Array( b3MeshNode ) tempNodes;
b3Array_CreateN( tempNodes, 2 * triangleCount - 1 );
int treeHeight = 0;
@ -1758,7 +1758,7 @@ b3MeshData* b3CreateMesh( const b3MeshDef* def, int* degenerateTriangleIndices,
b3Array_Destroy( vertices );
mesh->hash = 0;
mesh->hash = b3Hash( B3_HASH_INIT, (uint8_t*)mesh, mesh->byteCount );
mesh->hash = b3NonZeroHash( b3Hash( B3_HASH_INIT, (uint8_t*)mesh, mesh->byteCount ) );
return mesh;
}

View file

@ -571,6 +571,8 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
b3TriangleCache* triangleCaches = meshContact->triangleCache.data;
const b3HullData* hullB = shapeB->type == b3_hullShape ? shapeB->hull : NULL;
for ( int index = 0; index < triangleCount && totalPointCount + 3 < pointBufferCapacity; ++index )
{
int triangleIndex = triangleCaches[index].triangleIndex;
@ -614,7 +616,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
cache->satCache = (b3SATCache){ 0 };
}
b3CollideHullAndTriangle( manifold, pointCapacity, shapeB->hull, vertices[0], vertices[1], vertices[2],
b3CollideHullAndTriangle( manifold, pointCapacity, hullB, vertices[0], vertices[1], vertices[2],
triangle.flags, &cache->satCache );
context->satCallCount += 1;
context->satCacheHitCount += cache->satCache.hit;

View file

@ -12,6 +12,7 @@
#include "contact.h"
#include "core.h"
#include "ctz.h"
#include "hull_map.h"
#include "island.h"
#include "joint.h"
#include "parallel_for.h"
@ -35,6 +36,57 @@ b3World b3_worlds[B3_MAX_WORLDS];
b3AtomicInt b3_worldCount;
int b3_maxWorldCount;
const b3HullData* b3AddHullToDatabase( b3World* world, const b3HullData* src )
{
b3HullMap* database = world->hullDatabase;
// Compare by content so an unowned query hull finds the shared copy.
b3HullMap_itr itr = b3HullMap_get( database, src );
if ( b3HullMap_is_end( itr ) == false )
{
itr.data->val += 1;
return itr.data->key;
}
b3HullData* owned = b3CloneHull( src );
B3_ASSERT( owned != NULL );
b3HullMap_insert( database, owned, 1 );
return owned;
}
const b3HullData* b3AddOwnedHullToDatabase( b3World* world, b3HullData* owned )
{
b3HullMap* database = world->hullDatabase;
b3HullMap_itr itr = b3HullMap_get( database, owned );
if ( b3HullMap_is_end( itr ) == false )
{
itr.data->val += 1;
b3DestroyHull( owned );
return itr.data->key;
}
// Take ownership of input hull.
b3HullMap_insert( database, owned, 1 );
return owned;
}
void b3RemoveHullFromDatabase( b3World* world, const b3HullData* data )
{
b3HullMap* database = world->hullDatabase;
b3HullMap_itr itr = b3HullMap_get( database, data );
B3_ASSERT( b3HullMap_is_end( itr ) == false );
if ( --itr.data->val == 0 )
{
// Erase through the iterator we already have so the lookup runs once.
b3HullData* owned = (b3HullData*)itr.data->key;
b3HullMap_erase_itr( database, itr );
b3DestroyHull( owned );
}
}
b3World* b3GetUnlockedWorldFromId( b3WorldId id )
{
B3_ASSERT( 1 <= id.index1 && id.index1 <= B3_MAX_WORLDS );
@ -235,6 +287,9 @@ b3WorldId b3CreateWorld( const b3WorldDef* def )
int shapeCapacity = b3MaxInt( 16, def->capacity.staticShapeCount + def->capacity.dynamicShapeCount );
b3Array_Reserve( world->shapes, shapeCapacity );
world->hullDatabase = b3Alloc( sizeof( b3HullMap ) );
b3HullMap_init( world->hullDatabase );
world->contactIdPool = b3CreateIdPool();
b3Array_Reserve( world->contacts, b3MaxInt( 16, def->capacity.contactCount ) );
@ -409,6 +464,12 @@ void b3DestroyWorld( b3WorldId worldId )
}
}
// Destroying every shape above released all hull references, so the database is empty.
B3_ASSERT( b3HullMap_size( (b3HullMap*)world->hullDatabase ) == 0 );
b3HullMap_cleanup( world->hullDatabase );
b3Free( world->hullDatabase, sizeof( b3HullMap ) );
world->hullDatabase = NULL;
b3Array_Destroy( world->shapes );
b3Array_Destroy( world->contacts );
b3Array_Destroy( world->joints );
@ -2145,47 +2206,125 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
return;
}
FILE* file = b3OpenFile( "box3d_memory.txt" );
if ( file == NULL )
{
return;
}
// Large worlds can exceed 2GB, sum in 64 bits
uint64_t total = 0;
// id pools
fprintf( file, "id pools\n" );
fprintf( file, "body ids: %d\n", b3GetIdBytes( &world->bodyIdPool ) );
fprintf( file, "solver set ids: %d\n", b3GetIdBytes( &world->solverSetIdPool ) );
fprintf( file, "joint ids: %d\n", b3GetIdBytes( &world->jointIdPool ) );
fprintf( file, "contact ids: %d\n", b3GetIdBytes( &world->contactIdPool ) );
fprintf( file, "island ids: %d\n", b3GetIdBytes( &world->islandIdPool ) );
fprintf( file, "shape ids: %d\n", b3GetIdBytes( &world->shapeIdPool ) );
fprintf( file, "\n" );
int bodyIdBytes = b3GetIdBytes( &world->bodyIdPool );
int solverSetIdBytes = b3GetIdBytes( &world->solverSetIdPool );
int jointIdBytes = b3GetIdBytes( &world->jointIdPool );
int contactIdBytes = b3GetIdBytes( &world->contactIdPool );
int islandIdBytes = b3GetIdBytes( &world->islandIdPool );
int shapeIdBytes = b3GetIdBytes( &world->shapeIdPool );
total += (uint64_t)bodyIdBytes + solverSetIdBytes + jointIdBytes + contactIdBytes + islandIdBytes + shapeIdBytes;
b3Log( "id pools" );
b3Log( "body ids: %d", bodyIdBytes );
b3Log( "solver set ids: %d", solverSetIdBytes );
b3Log( "joint ids: %d", jointIdBytes );
b3Log( "contact ids: %d", contactIdBytes );
b3Log( "island ids: %d", islandIdBytes );
b3Log( "shape ids: %d", shapeIdBytes );
// Islands own per-island body/contact/joint link arrays
int islandLinkBytes = 0;
for ( int i = 0; i < world->islands.count; ++i )
{
b3Island* island = world->islands.data + i;
islandLinkBytes += b3Array_ByteCount( island->bodies );
islandLinkBytes += b3Array_ByteCount( island->contacts );
islandLinkBytes += b3Array_ByteCount( island->joints );
}
// world arrays
fprintf( file, "world arrays\n" );
fprintf( file, "bodies: %d\n", b3Array_ByteCount( world->bodies ) );
fprintf( file, "solver sets: %d\n", b3Array_ByteCount( world->solverSets ) );
fprintf( file, "joints: %d\n", b3Array_ByteCount( world->joints ) );
fprintf( file, "contacts: %d\n", b3Array_ByteCount( world->contacts ) );
fprintf( file, "islands: %d\n", b3Array_ByteCount( world->islands ) );
fprintf( file, "shapes: %d\n", b3Array_ByteCount( world->shapes ) );
fprintf( file, "\n" );
int bodyArrayBytes = b3Array_ByteCount( world->bodies );
int solverSetArrayBytes = b3Array_ByteCount( world->solverSets );
int jointArrayBytes = b3Array_ByteCount( world->joints );
int contactArrayBytes = b3Array_ByteCount( world->contacts );
int islandArrayBytes = b3Array_ByteCount( world->islands );
int shapeArrayBytes = b3Array_ByteCount( world->shapes );
int sensorArrayBytes = b3Array_ByteCount( world->sensors );
total += (uint64_t)bodyArrayBytes + solverSetArrayBytes + jointArrayBytes + contactArrayBytes + islandArrayBytes +
islandLinkBytes + shapeArrayBytes + sensorArrayBytes;
b3Log( "world arrays" );
b3Log( "bodies: %d", bodyArrayBytes );
b3Log( "solver sets: %d", solverSetArrayBytes );
b3Log( "joints: %d", jointArrayBytes );
b3Log( "contacts: %d", contactArrayBytes );
b3Log( "islands: %d", islandArrayBytes );
b3Log( "island links: %d", islandLinkBytes );
b3Log( "shapes: %d", shapeArrayBytes );
b3Log( "sensors: %d", sensorArrayBytes );
// Sensors own overlap tracking arrays. The sensor array is dense.
int sensorOverlapBytes = 0;
for ( int i = 0; i < world->sensors.count; ++i )
{
b3Sensor* sensor = world->sensors.data + i;
sensorOverlapBytes += b3Array_ByteCount( sensor->hits );
sensorOverlapBytes += b3Array_ByteCount( sensor->overlaps1 );
sensorOverlapBytes += b3Array_ByteCount( sensor->overlaps2 );
}
total += sensorOverlapBytes;
b3Log( "owned arrays" );
b3Log( "sensor overlaps: %d", sensorOverlapBytes );
// Shared hull database. The map owns a combined bucket and metadata allocation
// plus the small map struct. Each stored key is an owned clone sized by byteCount.
b3HullMap* hullDatabase = world->hullDatabase;
int hullCount = (int)b3HullMap_size( hullDatabase );
int hullBucketCount = (int)b3HullMap_bucket_count( hullDatabase );
uint64_t hullMapBytes = b3HullMapByteCount( hullDatabase );
uint64_t hullDataBytes = 0;
for ( b3HullMap_itr itr = b3HullMap_first( hullDatabase ); b3HullMap_is_end( itr ) == false;
itr = b3HullMap_next( itr ) )
{
hullDataBytes += itr.data->key->byteCount;
}
total += hullMapBytes + hullDataBytes;
b3Log( "hulls" );
b3Log( "database: %llu (%d, %d)", (unsigned long long)hullMapBytes, hullCount, hullBucketCount );
b3Log( "hull data: %llu", (unsigned long long)hullDataBytes );
// broad-phase
fprintf( file, "broad-phase\n" );
fprintf( file, "static tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_staticBody ) );
fprintf( file, "kinematic tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_kinematicBody ) );
fprintf( file, "dynamic tree: %d\n", b3DynamicTree_GetByteCount( world->broadPhase.trees + b3_dynamicBody ) );
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] );
}
fprintf( file, "movedProxies: %d\n", movedBytes );
fprintf( file, "moveArray: %d\n", b3Array_ByteCount( world->broadPhase.moveArray ) );
int moveArrayBytes = b3Array_ByteCount( world->broadPhase.moveArray );
b3HashSet* pairSet = &world->broadPhase.pairSet;
fprintf( file, "pairSet: %d (%d, %d)\n", b3GetHashSetBytes( pairSet ), pairSet->count, pairSet->capacity );
fprintf( file, "\n" );
int pairSetBytes = b3GetHashSetBytes( pairSet );
total += (uint64_t)staticTreeBytes + kinematicTreeBytes + dynamicTreeBytes + movedBytes + moveArrayBytes + 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
int manifoldArrayBytes = b3Array_ByteCount( world->manifoldAllocators );
int manifoldBlockBytes = 0;
for ( int i = 0; i < world->manifoldAllocators.count; ++i )
{
b3BlockAllocator* allocator = world->manifoldAllocators.data + i;
manifoldBlockBytes += b3Array_ByteCount( allocator->blocks );
manifoldBlockBytes += allocator->blocks.count * B3_BLOCK_SIZE * allocator->elementSize;
}
total += (uint64_t)manifoldArrayBytes + manifoldBlockBytes;
b3Log( "manifold allocators" );
b3Log( "allocator array: %d", manifoldArrayBytes );
b3Log( "blocks: %d", manifoldBlockBytes );
// solver sets
int bodySimCapacity = 0;
@ -2209,36 +2348,93 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
islandSimCapacity += set->islandSims.capacity;
}
fprintf( file, "solver sets\n" );
fprintf( file, "body sim: %d\n", bodySimCapacity * (int)sizeof( b3BodySim ) );
fprintf( file, "body state: %d\n", bodyStateCapacity * (int)sizeof( b3BodyState ) );
fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b3JointSim ) );
fprintf( file, "contact sim: %d\n", contactIndexCapacity * (int)sizeof( int ) );
fprintf( file, "island sim: %d\n", islandSimCapacity * (int)sizeof( islandSimCapacity ) );
fprintf( file, "\n" );
int setBodySimBytes = bodySimCapacity * (int)sizeof( b3BodySim );
int setBodyStateBytes = bodyStateCapacity * (int)sizeof( b3BodyState );
int setJointSimBytes = jointSimCapacity * (int)sizeof( b3JointSim );
int setContactSimBytes = contactIndexCapacity * (int)sizeof( int );
int setIslandSimBytes = islandSimCapacity * (int)sizeof( b3IslandSim );
total += (uint64_t)setBodySimBytes + setBodyStateBytes + setJointSimBytes + setContactSimBytes + setIslandSimBytes;
b3Log( "solver sets" );
b3Log( "body sim: %d", setBodySimBytes );
b3Log( "body state: %d", setBodyStateBytes );
b3Log( "joint sim: %d", setJointSimBytes );
b3Log( "contact sim: %d", setContactSimBytes );
b3Log( "island sim: %d", setIslandSimBytes );
// constraint graph
int bodyBitSetBytes = 0;
int contactSpecCapacity = 0;
jointSimCapacity = 0;
int graphContactBytes = 0;
int graphJointSimBytes = 0;
for ( int i = 0; i < B3_GRAPH_COLOR_COUNT; ++i )
{
b3GraphColor* c = world->constraintGraph.colors + i;
bodyBitSetBytes += b3GetBitSetBytes( &c->bodySet );
contactSpecCapacity += c->convexContacts.capacity + c->contacts.capacity;
jointSimCapacity += c->jointSims.capacity;
graphContactBytes += b3Array_ByteCount( c->convexContacts ) + b3Array_ByteCount( c->contacts );
graphJointSimBytes += b3Array_ByteCount( c->jointSims );
}
total += (uint64_t)bodyBitSetBytes + graphJointSimBytes + graphContactBytes;
b3Log( "constraint graph" );
b3Log( "body bit sets: %d", bodyBitSetBytes );
b3Log( "joint sim: %d", graphJointSimBytes );
b3Log( "contact sim: %d", graphContactBytes );
// Per worker task storage and its bit sets
int taskContextBytes = b3Array_ByteCount( world->taskContexts );
for ( int i = 0; i < world->taskContexts.count; ++i )
{
b3TaskContext* taskContext = world->taskContexts.data + i;
taskContextBytes += b3Array_ByteCount( taskContext->sensorHits );
taskContextBytes += b3GetBitSetBytes( &taskContext->contactStateBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->jointStateBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->hitEventBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->enlargedSimBitSet );
taskContextBytes += b3GetBitSetBytes( &taskContext->awakeIslandBitSet );
}
fprintf( file, "constraint graph\n" );
fprintf( file, "body bit sets: %d\n", bodyBitSetBytes );
fprintf( file, "joint sim: %d\n", jointSimCapacity * (int)sizeof( b3JointSim ) );
fprintf( file, "contact sim: %d\n", contactSpecCapacity * (int)sizeof( int ) );
fprintf( file, "\n" );
int sensorTaskContextBytes = b3Array_ByteCount( world->sensorTaskContexts );
for ( int i = 0; i < world->sensorTaskContexts.count; ++i )
{
b3SensorTaskContext* taskContext = world->sensorTaskContexts.data + i;
sensorTaskContextBytes += b3GetBitSetBytes( &taskContext->eventBits );
}
total += (uint64_t)taskContextBytes + sensorTaskContextBytes;
b3Log( "task contexts" );
b3Log( "worker: %d", taskContextBytes );
b3Log( "sensor: %d", sensorTaskContextBytes );
// Double buffered event arrays
int eventBytes = 0;
eventBytes += b3Array_ByteCount( world->bodyMoveEvents );
eventBytes += b3Array_ByteCount( world->sensorBeginEvents );
eventBytes += b3Array_ByteCount( world->contactBeginEvents );
eventBytes += b3Array_ByteCount( world->sensorEndEvents[0] );
eventBytes += b3Array_ByteCount( world->sensorEndEvents[1] );
eventBytes += b3Array_ByteCount( world->contactEndEvents[0] );
eventBytes += b3Array_ByteCount( world->contactEndEvents[1] );
eventBytes += b3Array_ByteCount( world->contactHitEvents );
eventBytes += b3Array_ByteCount( world->jointEvents );
total += eventBytes;
b3Log( "events: %d", eventBytes );
// Debug draw bit sets
int debugBytes = 0;
debugBytes += b3GetBitSetBytes( &world->debugBodySet );
debugBytes += b3GetBitSetBytes( &world->debugJointSet );
debugBytes += b3GetBitSetBytes( &world->debugContactSet );
debugBytes += b3GetBitSetBytes( &world->debugIslandSet );
total += debugBytes;
b3Log( "debug draw: %d", debugBytes );
// stack allocator
fprintf( file, "stack allocator: %d\n\n", world->stack.capacity );
total += world->stack.capacity;
b3Log( "stack allocator: %d", world->stack.capacity );
fclose( file );
b3Log( "total: %llu", (unsigned long long)total );
}
void b3World_DumpShapeBounds( b3WorldId worldId, b3BodyType type )

View file

@ -72,7 +72,7 @@ typedef struct b3TaskContext
b3Arena arena;
// Collect per thread sensor continuous hit events.
b3ArrayC( b3SensorHit ) sensorHits;
b3Array( b3SensorHit ) sensorHits;
// These bits align with the b3ConstraintGraph::contactBlocks and signal a change in contact status
b3BitSet contactStateBitSet;
@ -129,7 +129,7 @@ typedef struct b3World
b3ConstraintGraph constraintGraph;
// Manifold allocators have one allocator for each manifold count.
b3ArrayC( b3BlockAllocator ) manifoldAllocators;
b3Array( b3BlockAllocator ) manifoldAllocators;
b3Mutex* manifoldAllocatorMutex;
// The body id pool is used to allocate and recycle body ids. Body ids
@ -140,7 +140,7 @@ typedef struct b3World
// This is a sparse array that maps body ids to the body data
// stored in solver sets. As sims move within a set or across set.
// Indices come from id pool.
b3ArrayC( b3Body ) bodies;
b3Array( b3Body ) bodies;
// Provides free list for solver sets.
b3IdPool solverSetIdPool;
@ -148,51 +148,56 @@ typedef struct b3World
// Solvers sets allow sims to be stored in contiguous arrays. The first
// set is all static sims. The second set is active sims. The third set is disabled
// sims. The remaining sets are sleeping islands.
b3ArrayC( b3SolverSet ) solverSets;
b3Array( b3SolverSet ) solverSets;
// Used to create stable ids for joints
b3IdPool jointIdPool;
// This is a sparse array that maps joint ids to the joint data stored in the constraint graph
// or in the solver sets.
b3ArrayC( b3Joint ) joints;
b3Array( b3Joint ) joints;
// Used to create stable ids for contacts
b3IdPool contactIdPool;
// This is a sparse array that maps contact ids to the contact data stored in the constraint graph
// or in the solver sets.
b3ArrayC( b3Contact ) contacts;
b3Array( b3Contact ) contacts;
// Used to create stable ids for islands
b3IdPool islandIdPool;
// This is a sparse array that maps island ids to the island data stored in the solver sets.
b3ArrayC( b3Island ) islands;
b3Array( b3Island ) islands;
b3IdPool shapeIdPool;
// These are sparse arrays that point into the pools above
b3ArrayC( b3Shape ) shapes;
b3Array( b3Shape ) shapes;
// Reference counted store of shared hull data keyed by content. Shapes hold a
// pointer to the owned copy here. Opaque to avoid leaking the verstable map
// type into this header.
void* hullDatabase;
// This is a dense array of sensor data.
b3ArrayC( b3Sensor ) sensors;
b3Array( b3Sensor ) sensors;
// Per thread storage
b3ArrayC( b3TaskContext ) taskContexts;
b3ArrayC( b3SensorTaskContext ) sensorTaskContexts;
b3Array( b3TaskContext ) taskContexts;
b3Array( b3SensorTaskContext ) sensorTaskContexts;
b3ArrayC( b3BodyMoveEvent ) bodyMoveEvents;
b3ArrayC( b3SensorBeginTouchEvent ) sensorBeginEvents;
b3ArrayC( b3ContactBeginTouchEvent ) contactBeginEvents;
b3Array( b3BodyMoveEvent ) bodyMoveEvents;
b3Array( b3SensorBeginTouchEvent ) sensorBeginEvents;
b3Array( b3ContactBeginTouchEvent ) contactBeginEvents;
// End events are double buffered so that the user doesn't need to flush events
b3ArrayC( b3SensorEndTouchEvent ) sensorEndEvents[2];
b3ArrayC( b3ContactEndTouchEvent ) contactEndEvents[2];
b3Array( b3SensorEndTouchEvent ) sensorEndEvents[2];
b3Array( b3ContactEndTouchEvent ) contactEndEvents[2];
int endEventArrayIndex;
b3ArrayC( b3ContactHitEvent ) contactHitEvents;
b3ArrayC( b3JointEvent ) jointEvents;
b3Array( b3ContactHitEvent ) contactHitEvents;
b3Array( b3JointEvent ) jointEvents;
// Used to track debug draw
b3BitSet debugBodySet;
@ -285,6 +290,17 @@ void b3ValidateConnectivity( b3World* world );
void b3ValidateSolverSets( b3World* world );
void b3ValidateContacts( b3World* world );
// Register a hull in the world database, returning the owned shared copy. Identical hulls
// share one copy with a reference count. The input may be freed after this call.
const b3HullData* b3AddHullToDatabase( b3World* world, const b3HullData* src );
// Like b3AddHullToDatabase but takes ownership of a heap hull: inserted directly on a miss,
// freed on a hit. Avoids cloning data the caller already allocated.
const b3HullData* b3AddOwnedHullToDatabase( b3World* world, b3HullData* owned );
// Release a reference to a shared hull. The owned copy is freed when the count reaches zero.
void b3RemoveHullFromDatabase( b3World* world, const b3HullData* data );
static inline b3Manifold* b3AllocateManifolds( b3World* world, int count )
{
if ( count == 0 )

View file

@ -195,7 +195,7 @@ static void b3SensorTask( int startIndex, int endIndex, int workerIndex, void* c
b3Shape* sensorShape = b3Array_Get( world->shapes, sensor->shapeId );
// Swap overlap arrays
b3ArrayC( b3Visitor ) temp = sensor->overlaps1;
b3Array( b3Visitor ) temp = sensor->overlaps1;
sensor->overlaps1 = sensor->overlaps2;
sensor->overlaps2 = temp;
b3Array_Clear( sensor->overlaps2 );

View file

@ -26,9 +26,9 @@ b3DeclareArray( b3Visitor );
typedef struct b3Sensor
{
b3ArrayC( b3Visitor ) hits;
b3ArrayC( b3Visitor ) overlaps1;
b3ArrayC( b3Visitor ) overlaps2;
b3Array( b3Visitor ) hits;
b3Array( b3Visitor ) overlaps1;
b3Array( b3Visitor ) overlaps2;
int shapeId;
} b3Sensor;

View file

@ -46,7 +46,7 @@ static float b3ComputeShapeMargin( b3Shape* shape )
case b3_hullShape:
{
const b3Hull* hull = shape->hull;
const b3HullData* hull = shape->hull;
const b3Vec3* points = b3GetHullPoints( hull );
float maxExtentSqr = 0.0f;
int count = hull->vertexCount;
@ -143,18 +143,21 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3Transform
case b3_hullShape:
if ( haveShapeTransform )
{
shape->hull = b3CloneAndTransformHull( (b3Hull*)geometry, shapeTransform, scale );
if ( shape->hull == NULL )
// The transform and non-uniform scale are baked into fresh data, then shared.
b3HullData* baked = b3CloneAndTransformHull( (b3HullData*)geometry, shapeTransform, scale );
if ( baked == NULL )
{
// This can fail to produce a valid hull in extreme cases
b3FreeId( &world->shapeIdPool, shapeId );
shape->id = B3_NULL_INDEX;
return NULL;
}
shape->hull = b3AddOwnedHullToDatabase( world, baked );
}
else
{
shape->hull = b3CloneHull( (b3Hull*)geometry );
shape->hull = b3AddHullToDatabase( world, (const b3HullData*)geometry );
}
break;
@ -336,14 +339,14 @@ b3ShapeId b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3
return b3CreateShape( bodyId, def, capsule, b3_capsuleShape, b3Transform_identity, b3Vec3_one, false );
}
b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull )
b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull )
{
B3_VALIDATE( b3IsValidHull( hull ) );
B3_VALIDATE( hull->hash != 0 );
return b3CreateShape( bodyId, def, hull, b3_hullShape, b3Transform_identity, b3Vec3_one, false );
}
b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Hull* hull, b3Transform transform,
b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull, b3Transform transform,
b3Vec3 scale )
{
B3_VALIDATE( b3IsValidHull( hull ) );
@ -918,7 +921,7 @@ static void b3DestroyShapeAllocationForShapeChange( b3World* world, b3Shape* sha
switch ( type )
{
case b3_hullShape:
b3DestroyHull( (b3Hull*)shape->hull );
b3RemoveHullFromDatabase( world, shape->hull );
shape->hull = NULL;
break;
@ -966,8 +969,9 @@ b3ShapeProxy b3MakeShapeProxy( const b3Shape* shape )
case b3_hullShape:
{
const b3Vec3* points = b3GetHullPoints( shape->hull );
return (b3ShapeProxy){ points, shape->hull->vertexCount, 0.0f };
const b3HullData* hull = shape->hull;
const b3Vec3* points = b3GetHullPoints( hull );
return (b3ShapeProxy){ points, hull->vertexCount, 0.0f };
}
default:
@ -1437,7 +1441,7 @@ b3Capsule b3Shape_GetCapsule( b3ShapeId shapeId )
return shape->capsule;
}
const b3Hull* b3Shape_GetHull( b3ShapeId shapeId )
const b3HullData* b3Shape_GetHull( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
@ -1513,8 +1517,11 @@ void b3Shape_SetCapsule( b3ShapeId shapeId, const b3Capsule* capsule )
world->locked = false;
}
void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull )
void b3Shape_SetHull( b3ShapeId shapeId, const b3HullData* hull )
{
B3_VALIDATE( b3IsValidHull( hull ) );
B3_VALIDATE( hull->hash != 0 );
b3World* world = b3GetUnlockedWorld( shapeId.world0 );
if ( world == NULL )
{
@ -1525,9 +1532,21 @@ void b3Shape_SetHull( b3ShapeId shapeId, const b3Hull* hull )
b3Shape* shape = b3GetShape( world, shapeId );
// Acquire the new hull before releasing the old so the input may safely alias
// the shape's current shared data.
const b3HullData* data = b3AddHullToDatabase( world, hull );
// Same shared hull, avoid destroying contacts and recreating the proxy
if ( shape->type == b3_hullShape && data == shape->hull )
{
b3RemoveHullFromDatabase( world, data );
world->locked = false;
return;
}
b3DestroyShapeAllocationForShapeChange( world, shape );
shape->hull = b3CloneHull( hull );
shape->hull = data;
shape->type = b3_hullShape;
shape->aabbMargin = b3ComputeShapeMargin( shape );
@ -2344,7 +2363,7 @@ void b3DumpShape( b3World* world, int shapeIndex )
case b3_hullShape:
{
const b3Hull* s = shape->hull;
const b3HullData* s = shape->hull;
int vertexCount = s->vertexCount;
const b3Vec3* vs = b3GetHullPoints( s );
b3Dump( " b3Vec3 vs[%d];\n", vertexCount );
@ -2352,9 +2371,9 @@ void b3DumpShape( b3World* world, int shapeIndex )
{
b3Dump( " vs[%d] = {%.9g, %.9g, %.9g};\n", i, vs[i].x, vs[i].y, vs[i].z );
}
b3Dump( " b3Hull* hull = b3CreateHull(vs, %d);\n", vertexCount );
b3Dump( " b3CreateHullShape(bodyId, &sd, hull);\n" );
b3Dump( " b3DestroyHull(hull);\n" );
b3Dump( " b3HullData* hullData = b3CreateHull(vs, %d, %d);\n", vertexCount, vertexCount );
b3Dump( " b3CreateHullShape(bodyId, &sd, hullData);\n" );
b3Dump( " b3DestroyHull(hullData);\n" );
}
break;

View file

@ -49,7 +49,7 @@ typedef struct b3Shape
{
b3Capsule capsule;
b3Sphere sphere;
const b3Hull* hull;
const b3HullData* hull;
b3Mesh mesh;
const b3HeightField* heightField;
const b3Compound* compound;
@ -89,19 +89,19 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover );
int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, const b3Capsule* mover );
int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3Capsule* mover );
int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const b3Capsule* mover );
int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* shape, const b3Capsule* mover );
int b3CollideMoverAndHeightField( b3PlaneResult* results, int capacity, const b3HeightField* shape, const b3Capsule* mover );
int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* shape, b3Transform transform,
const b3Capsule* mover );
// Hull
int b3FindHullSupportVertex( const b3Hull* hull, b3Vec3 direction );
int b3FindHullSupportFace( const b3Hull* hull, b3Vec3 direction );
bool b3IsValidHull( const b3Hull* hull );
b3AABB b3ComputeSweptHullAABB( const b3Hull* shape, b3Transform xf1, b3Transform xf2 );
b3ShapeExtent b3ComputeHullExtent( const b3Hull* hull, b3Vec3 origin );
float b3ComputeHullProjectedArea( const b3Hull* hull, b3Vec3 direction );
int b3FindHullSupportVertex( const b3HullData* hull, b3Vec3 direction );
int b3FindHullSupportFace( const b3HullData* hull, b3Vec3 direction );
bool b3IsValidHull( const b3HullData* hull );
b3AABB b3ComputeSweptHullAABB( const b3HullData* shape, b3Transform xf1, b3Transform xf2 );
b3ShapeExtent b3ComputeHullExtent( const b3HullData* hull, b3Vec3 origin );
float b3ComputeHullProjectedArea( const b3HullData* hull, b3Vec3 direction );
// Height field
b3Triangle b3GetHeightFieldTriangle( const b3HeightField* heightField, int triangleIndex );

View file

@ -30,25 +30,25 @@ b3DeclareArray( b3IslandSim );
typedef struct b3SolverSet
{
// Body array. Empty for unused set.
b3ArrayC( b3BodySim ) bodySims;
b3Array( b3BodySim ) bodySims;
// Body state only exists for active set
b3ArrayC( b3BodyState ) bodyStates;
b3Array( b3BodyState ) bodyStates;
// This holds sleeping/disabled joints. Empty for static/active set.
b3ArrayC( b3JointSim ) jointSims;
b3Array( b3JointSim ) jointSims;
// This holds all contacts for sleeping sets.
// This holds non-touching contacts for the awake set.
// This should be empty for the static and disabled sets.
b3ArrayC( int ) contactIndices;
b3Array( int ) contactIndices;
// The awake set has an array of islands. Sleeping sets normally have a single islands. However, joints
// created between sleeping sets causes the sets to merge, leaving them with multiple islands. These sleeping
// islands will be naturally merged with the set is woken.
// The static and disabled sets have no islands.
// Islands live in the solver sets to limit the number of islands that need to be considered for sleeping.
b3ArrayC( b3IslandSim ) islandSims;
b3Array( b3IslandSim ) islandSims;
// Aligns with b3World::solverSetIdPool. Used to create a stable id for body/contact/joint/islands.
int setIndex;

View file

@ -219,7 +219,7 @@ b3CastOutput b3ShapeCastSphere( const b3Sphere* sphere, const b3ShapeCastInput*
int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover )
{
float totalRadius = mover->radius + shape->radius;
b3Vec3 closest = b3ClosestPointOnSegment( mover->center1, mover->center2, shape->center );
b3Vec3 closest = b3PointToSegmentDistance( mover->center1, mover->center2, shape->center );
// The normal points from the sphere toward the mover.
float distance;

View file

@ -297,7 +297,7 @@ static void b3BuildTriangleAndCapsuleEdgeContact( b3LocalManifold* manifold, con
normal = b3Neg( normal );
}
b3ClosestApproachResult result = b3ClosestApproachLines( v1, triangleEdge, p1, capsuleEdge );
b3SegmentDistanceResult result = b3LineDistance( v1, triangleEdge, p1, capsuleEdge );
if ( result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f || 1.0f < result.fraction2 )
{
@ -480,7 +480,7 @@ static inline int b3GetTriangleSupport( b3Vec3* points, b3Vec3 direction )
return index;
}
static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3Hull* hull )
static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3HullData* hull )
{
const b3Vec3* hullPoints = b3GetHullPoints( hull );
b3Plane plane = triangle->plane;
@ -495,7 +495,7 @@ static b3FaceQuery b3QueryTriangleFace( const b3TriangleData* triangle, const b3
};
}
static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3Hull* hull )
static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3HullData* hull )
{
const b3Plane* hullPlanes = b3GetHullPlanes( hull );
int faceCount = hull->faceCount;
@ -528,7 +528,7 @@ static b3FaceQuery b3QueryHullFace( const b3TriangleData* triangle, const b3Hull
};
}
static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull* hull )
static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3HullData* hull )
{
b3EdgeQuery result = {
.separation = -FLT_MAX,
@ -596,7 +596,7 @@ static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull
return result;
}
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3Hull* hull,
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3HullData* hull,
b3FaceQuery query, b3SATCache* cache )
{
manifold->pointCount = 0;
@ -701,7 +701,7 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
}
static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle,
const b3Hull* hull, b3FaceQuery query, b3SATCache* cache )
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache )
{
B3_VALIDATE( manifold->pointCount == 0 );
@ -807,7 +807,7 @@ static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity
}
static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capacity, b3Vec3 trianglePoint, b3Vec3 triangleEdge,
b3Vec3 triangleCenter, const b3Hull* hull, b3EdgeQuery query, b3SATCache* cache )
b3Vec3 triangleCenter, const b3HullData* hull, b3EdgeQuery query, b3SATCache* cache )
{
B3_VALIDATE( query.separation <= 2.0f * B3_SPECULATIVE_DISTANCE );
B3_ASSERT( query.indexA < 3 );
@ -851,7 +851,7 @@ static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capaci
}
// Get the closest points between the infinite edge lines
b3ClosestApproachResult result = b3ClosestApproachLines( pA, eA, pB, eB );
b3SegmentDistanceResult result = b3LineDistance( pA, eA, pB, eB );
// Is one of the closest points outside of the associated edge segment?
if ( capacity == 0 || result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f || 1.0f < result.fraction2 )
@ -901,7 +901,7 @@ b3AtomicInt b3_triangleConvexCalls;
b3AtomicInt b3_triangleCacheHits;
// Computes the manifold in the local space of the hull
void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3Hull* hullA, b3Vec3 v1, b3Vec3 v2, b3Vec3 v3,
void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2, b3Vec3 v3,
int triangleFlags, b3SATCache* cache )
{
manifold->pointCount = 0;