Fixes 01 (#26)

Fix #25 
Fix replay mover colors
Update README
Added unit test for CCD move events
Avoid Linux crash when OpenGL 4.5 is not present
This commit is contained in:
Erin Catto 2026-07-01 23:19:23 -07:00 • committed by GitHub
commit 1c5ac42c37
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 126 additions and 150 deletions

1
.gitignore vendored
View file

@ -11,5 +11,4 @@ CMakeUserPresets.json
.claude/
.tmp/
.fetchcontent-cache/
build-dp/
*.b3rec

View file

@ -4,6 +4,8 @@
Box3D is a 3D physics engine for games.
[![Introducing Box3D](https://img.youtube.com/vi/jr_Fzl2XwKU/maxresdefault.jpg)](https://www.youtube.com/watch?v=jr_Fzl2XwKU)
## Build status
[![Build Status](https://github.com/erincatto/box3d/actions/workflows/build.yml/badge.svg)](https://github.com/erincatto/box3d/actions)
@ -19,13 +21,14 @@ Box3D is a 3D physics engine for games.
- Collision filtering
- Ray casts, shape casts, and overlap queries
- Sensor system
- Character mover
### Physics
- Robust _Soft Step_ rigid body solver
- Continuous physics for fast translations and rotations
- Island based sleep
- Revolute, prismatic, distance, mouse joint, weld, and wheel joints
- Revolute, prismatic, distance, motor, weld, and wheel joints
- Joint limits, motors, springs, and friction
- Joint and contact forces
- Body movement events and sleep notification
@ -36,12 +39,14 @@ Box3D is a 3D physics engine for games.
- Written in portable C17
- Extensive multithreading and SIMD
- Optimized for large piles of bodies
- Cross platform determinism
- Recording and replay
### Samples
- Uses sokol to run with D3D11 on Window, Metal on macOS, and OpenGL 4.3 on Linux
- Graphical user interface with imgui
- Many samples to demonstrate features and performance
- Uses sokol to run with D3D11 on Windows, Metal on macOS, and OpenGL 4.5 on Linux.
- Graphical user interface with imgui.
- Many samples to demonstrate features and performance.
## Building all platforms
@ -51,7 +56,7 @@ Box3D is a 3D physics engine for games.
## Building with CMake presets (recommended)
The presets in `CMakePresets.json` give one build flow on every platform and are picked up automatically by Visual Studio, VS Code, and CLion (open the folder and choose a preset). From the command line:
This uses the presets in `CMakePresets.json`.
- Windows: `cmake --preset windows` then `cmake --build --preset windows-release`
- Linux: `cmake --preset linux-release` then `cmake --build --preset linux-release`
@ -94,10 +99,9 @@ Run the samples app (must be in the Box3D directory).
## Using Box3D in your project
The core library has no dependencies beyond the C runtime (and `libm` on Unix). Linking it
gives you the `box3d::box3d` target. When Box3D is consumed as a subproject it builds the
library only; samples, tests, and benchmarks are skipped.
gives you the `box3d::box3d` target.
The recommended path is FetchContent, which pins a tag and needs no separate install step:
I recommend to use FetchContent:
```cmake
include(FetchContent)
@ -147,7 +151,7 @@ The user manual lives in [`docs/`](docs/) and is built with Doxygen. Enable the
## Contributing
Please do not submit pull requests. Instead, please file an issue for bugs or feature requests. For support, please visit the Discord server.
Pull requests are currently disabled. Instead, please file an issue for bugs or feature requests. For support, please visit the Discord server.
## Giving feedback
@ -162,3 +166,16 @@ Box3D is developed by Erin Catto and uses the [MIT license](https://en.wikipedia
Support development of Box3D through [Github Sponsors](https://github.com/sponsors/erincatto).
Please consider starring this repository and subscribing to my [YouTube channel](https://www.youtube.com/@erin_catto).
## LLM Usage
LLMs are used in the following areas:
- unit tests
- samples app
- migrating code between Box2D and Box3D
- build configuration
- code reviews
- benchmarking
Elsewhere all code is developed and written by me. I take responsibility for every line of code in Box2D/3D.

View file

@ -451,6 +451,25 @@ static void OnCleanup( void )
exit( errors == 0 ? 0 : 1 );
}
static void OnAppLog( const char* tag, uint32_t logLevel, uint32_t logItemId, const char* message, uint32_t lineNumber,
const char* filename, void* userData )
{
(void)tag;
(void)logItemId;
(void)filename;
(void)userData;
(void)lineNumber;
const char* level = ( logLevel == 0 ) ? "panic" : ( logLevel == 1 ) ? "error" : ( logLevel == 2 ) ? "warn" : "info";
fprintf( stderr, "sokol(level %s) %s\n", level, message ? message : "(no message)" );
if ( logLevel == 0 )
{
fprintf( stderr, "Ensure you have OpenGL 4.5 if on Linux" );
exit( 1 );
}
}
sapp_desc sokol_main( int argc, char** argv )
{
for ( int i = 1; i < argc; ++i )
@ -470,6 +489,7 @@ sapp_desc sokol_main( int argc, char** argv )
desc.frame_cb = OnFrame;
desc.event_cb = OnEvent;
desc.cleanup_cb = OnCleanup;
desc.logger.func = OnAppLog;
// GL 4.5 for glClipControl (reverse-Z). Ignored on D3D11 / Metal.
desc.gl.major_version = 4;

View file

@ -42,106 +42,6 @@ struct Ray
b3Vec3 origin, translation;
};
#ifdef _WIN32
#include <immintrin.h>
// Warning: this code has not been validated
void ClosestPointAVX2( const float* aabbMinX, const float* aabbMinY, const float* aabbMinZ, const float* aabbMaxX,
const float* aabbMaxY, const float* aabbMaxZ, int proxyCount, b3Vec3 point, b3Vec3* outClosestPoint,
float* outMinDistSq )
{
const __m256 px = _mm256_set1_ps( point.x );
const __m256 py = _mm256_set1_ps( point.y );
const __m256 pz = _mm256_set1_ps( point.z );
__m256 bestDistSq = _mm256_set1_ps( FLT_MAX );
__m256i bestIndex = _mm256_set1_epi32( -1 );
int j = 0;
for ( ; j + 8 <= proxyCount; j += 8 )
{
// Load AABB bounds for 8 proxies
__m256 minX = _mm256_loadu_ps( aabbMinX + j );
__m256 minY = _mm256_loadu_ps( aabbMinY + j );
__m256 minZ = _mm256_loadu_ps( aabbMinZ + j );
__m256 maxX = _mm256_loadu_ps( aabbMaxX + j );
__m256 maxY = _mm256_loadu_ps( aabbMaxY + j );
__m256 maxZ = _mm256_loadu_ps( aabbMaxZ + j );
// Closest point on AABB to point: clamp each coordinate
__m256 cx = _mm256_min_ps( _mm256_max_ps( px, minX ), maxX );
__m256 cy = _mm256_min_ps( _mm256_max_ps( py, minY ), maxY );
__m256 cz = _mm256_min_ps( _mm256_max_ps( pz, minZ ), maxZ );
// d = point - closest
__m256 dx = _mm256_sub_ps( px, cx );
__m256 dy = _mm256_sub_ps( py, cy );
__m256 dz = _mm256_sub_ps( pz, cz );
__m256 dx2 = _mm256_mul_ps( dx, dx );
__m256 dy2 = _mm256_mul_ps( dy, dy );
__m256 dz2 = _mm256_mul_ps( dz, dz );
__m256 distSq = _mm256_add_ps( _mm256_add_ps( dx2, dy2 ), dz2 );
// Compare to current best
__m256 mask = _mm256_cmp_ps( distSq, bestDistSq, _CMP_LT_OQ );
bestDistSq = _mm256_blendv_ps( bestDistSq, distSq, mask );
__m256i indices = _mm256_set_epi32( j + 7, j + 6, j + 5, j + 4, j + 3, j + 2, j + 1, j + 0 );
// Tracks the 8 best indices
bestIndex =
_mm256_castps_si256( _mm256_blendv_ps( _mm256_castsi256_ps( bestIndex ), _mm256_castsi256_ps( indices ), mask ) );
}
// Now find the best index among the best 8.
alignas( 32 ) float distBuf[8];
alignas( 32 ) int indexBuf[8];
_mm256_store_ps( distBuf, bestDistSq );
_mm256_store_si256( (__m256i*)indexBuf, bestIndex );
float minDist = distBuf[0];
int minIdx = indexBuf[0];
for ( int k = 1; k < 8; ++k )
{
if ( distBuf[k] < minDist )
{
minDist = distBuf[k];
minIdx = indexBuf[k];
}
}
// Remainder
for ( ; j < proxyCount; ++j )
{
float cx = b3MinFloat( b3MaxFloat( point.x, aabbMinX[j] ), aabbMaxX[j] );
float cy = b3MinFloat( b3MaxFloat( point.y, aabbMinY[j] ), aabbMaxY[j] );
float cz = b3MinFloat( b3MaxFloat( point.z, aabbMinZ[j] ), aabbMaxZ[j] );
float dx = point.x - cx;
float dy = point.y - cy;
float dz = point.z - cz;
float d2 = dx * dx + dy * dy + dz * dz;
if ( d2 < minDist )
{
minDist = d2;
minIdx = j;
}
}
b3Vec3 cp;
cp.x = b3MinFloat( b3MaxFloat( point.x, aabbMinX[minIdx] ), aabbMaxX[minIdx] );
cp.y = b3MinFloat( b3MaxFloat( point.y, aabbMinY[minIdx] ), aabbMaxY[minIdx] );
cp.z = b3MinFloat( b3MaxFloat( point.z, aabbMinZ[minIdx] ), aabbMaxZ[minIdx] );
*outClosestPoint = cp;
*outMinDistSq = minDist;
}
#endif
class TreeBenchmark : public Sample
{
public:
@ -565,42 +465,6 @@ public:
}
m_overlapTime = b3GetMilliseconds( ticks );
#if 0 && defined( _WIN32 )
// brute force avx2
int proxyCount = (int)m_proxies.size();
for ( int i = 0; i < m_testCount; ++i )
{
b3Vec3 point = m_closestPointQueries[i].center;
float minDistSq;
b3Vec3 closest;
ClosestPointAVX2( m_aabbMinX, m_aabbMinY, m_aabbMinZ, m_aabbMaxX, m_aabbMaxY, m_aabbMaxZ, proxyCount, point, &closest,
&minDistSq );
m_closestPoint = closest;
m_haveClosest = true;
}
#elif 0
// Brute force
int proxyCount = (int)m_proxies.size();
for ( int i = 0; i < m_testCount; ++i )
{
b3Vec3 point = m_closestPointQueries[i].center;
float minDistanceSquared = FLT_MAX;
m_haveClosest = false;
for ( int j = 0; j < proxyCount; ++j )
{
b3Vec3 closestPoint = b3ClosestPointToAABB( point, m_proxies[j].aabb );
float d = b3DistanceSquared( point, closestPoint );
if ( d < minDistanceSquared )
{
m_closestPoint = closestPoint;
m_haveClosest = true;
minDistanceSquared = d;
}
}
}
#else
for ( int i = 0; i < m_testCount; ++i )
{
b3Vec3 point = m_closestPointQueries[i].center;
@ -611,7 +475,7 @@ public:
b3DynamicTree_QueryClosest( &m_tree, point, B3_DEFAULT_MASK_BITS, false, ClosetPointCallback, this,
&distanceSquared );
}
#endif
m_closestTime = b3GetMilliseconds( ticks );
}

View file

@ -3315,7 +3315,7 @@ void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int q
{
b3Pos c1 = b3OffsetPos( q->origin, q->mover.center1 );
b3Pos c2 = b3OffsetPos( q->origin, q->mover.center2 );
b3HexColor c = q->kind == b3_colorLightSkyBlue;
b3HexColor c = b3_colorLightSkyBlue;
if ( draw->DrawCapsuleFcn )
{
draw->DrawCapsuleFcn( c1, c2, q->mover.radius, b3RecQuerySelColor( selected, c ), 0.6f, draw->context );
@ -3335,7 +3335,7 @@ void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int q
{
b3Pos c1 = b3OffsetPos( q->origin, q->mover.center1 );
b3Pos c2 = b3OffsetPos( q->origin, q->mover.center2 );
b3HexColor c = q->kind == b3_colorTan;
b3HexColor c = b3_colorTan;
if ( draw->DrawCapsuleFcn )
{
draw->DrawCapsuleFcn( c1, c2, q->mover.radius, b3RecQuerySelColor( selected, c ), 0.6f, draw->context );

View file

@ -563,6 +563,10 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
fastBodySim->rotation0 = q;
fastBodySim->center0 = center;
// The move event was written before CCD, so correct it with the impact pose
b3BodyMoveEvent* event = b3Array_Get( world->bodyMoveEvents, bodySimIndex );
event->transform = fastBodySim->transform;
// Prepare AABBs for broad-phase.
// Even though a body is fast, it may not move much. So the AABB may not need enlargement.

View file

@ -681,7 +681,7 @@ static int TestMeshDrop( void )
b3World_Step( worldId, timeStep, subStepCount );
b3BodyEvents events = b3World_GetBodyEvents( worldId );
if (events.moveCount == 0)
if ( events.moveCount == 0 )
{
// All bodies sleeping
break;
@ -995,6 +995,77 @@ static int TestExplosion( void )
return 0;
}
// Ensure correct move events from bodies involved in CCD.
static int TestContinuousMoveEvent( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_EnableContinuous( worldId, true );
// Thin static wall, near face at x = 0.1
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_staticBody;
bodyDef.position = (b3Pos){ 0.0f, 0.0f, 0.0f };
b3BodyId wallId = b3CreateBody( worldId, &bodyDef );
b3BoxHull wallBox = b3MakeBoxHull( 0.1f, 5.0f, 5.0f );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateHullShape( wallId, &shapeDef, &wallBox.base );
// Fast dynamic sphere fired at the wall.
bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.gravityScale = 0.0f;
bodyDef.position = (b3Pos){ 3.0f, 0.0f, 0.0f };
bodyDef.linearVelocity = (b3Vec3){ -30.0f, 0.0f, 0.0f };
b3BodyId ballId = b3CreateBody( worldId, &bodyDef );
shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
b3Sphere sphere = { { 0.0f, 0.0f, 0.0f }, 0.25f };
b3CreateSphereShape( ballId, &shapeDef, &sphere );
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
bool haveMove = false;
for ( int step = 0; step < 30; ++step )
{
b3World_Step( worldId, timeStep, subStepCount );
b3WorldTransform xf = b3Body_GetTransform( ballId );
b3BodyEvents events = b3World_GetBodyEvents( worldId );
for ( int i = 0; i < events.moveCount; ++i )
{
b3BodyMoveEvent* event = events.moveEvents + i;
if ( B3_ID_EQUALS( event->bodyId, ballId ) == false )
{
continue;
}
haveMove = true;
// The move event must carry the same pose the body reports, CCD rewind included
ENSURE( event->transform.p.x == xf.p.x );
ENSURE( event->transform.p.y == xf.p.y );
ENSURE( event->transform.p.z == xf.p.z );
ENSURE( event->transform.q.v.x == xf.q.v.x );
ENSURE( event->transform.q.v.y == xf.q.v.y );
ENSURE( event->transform.q.v.z == xf.q.v.z );
ENSURE( event->transform.q.s == xf.q.s );
}
}
ENSURE( haveMove == true );
// Tunnel check
b3Pos finalPos = b3Body_GetPosition( ballId );
ENSURE( 0.2f < finalPos.x && finalPos.x < 0.8f );
b3DestroyWorld( worldId );
return 0;
}
int WorldTest( void )
{
RUN_SUBTEST( HelloWorld );
@ -1005,6 +1076,7 @@ int WorldTest( void )
RUN_SUBTEST( TestWorldCoverage );
RUN_SUBTEST( TestExplosion );
RUN_SUBTEST( TestSensor );
RUN_SUBTEST( TestContinuousMoveEvent );
RUN_SUBTEST( TestContactEvents );
RUN_SUBTEST( TestHitEvents );
RUN_SUBTEST( TestCompoundHitEvents );