From 37e8d26bd5d01b1302638921f731cc1df7751843 Mon Sep 17 00:00:00 2001 From: Erin Catto Date: Sat, 23 May 2026 12:04:16 -0700 Subject: [PATCH] Fix for deep mover overlap on hulls (#8) Get world bounds Update build.yml --- .github/workflows/build.yml | 18 ++-- README.md | 32 ++++-- include/box3d/box3d.h | 4 + samples/sample_character.cpp | 170 ++++++++++++++++++++++++++++++ src/capsule.c | 36 ++++--- src/hull.c | 9 ++ src/physics_world.c | 34 ++++++ src/sphere.c | 34 +++--- test/test_mover.c | 195 +++++++++++++++++++++++++++++++++++ 9 files changed, 487 insertions(+), 45 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 66f5418..1ff8b02 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,7 +14,7 @@ jobs: if: github.event_name == 'push' || github.event.pull_request.draft == false timeout-minutes: 4 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON @@ -32,7 +32,7 @@ jobs: if: github.event_name == 'push' || github.event.pull_request.draft == false timeout-minutes: 4 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang-18 -DCMAKE_C_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=thread" -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON @@ -47,10 +47,10 @@ jobs: build-ubuntu-clang-msan: name: ubuntu-clang-msan runs-on: ubuntu-latest - if: github.event_name == 'push' || github.event.pull_request.draft == false + if: false # todo re-enable once repo is public timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_CXX_COMPILER=clang++-18 -DCMAKE_C_COMPILER=clang-18 -DCMAKE_C_FLAGS="-fsanitize=memory -fsanitize-memory-track-origins=1 -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=memory -fsanitize-memory-track-origins=1 -fno-omit-frame-pointer" -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=memory" -DBOX3D_SAMPLES=OFF -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON @@ -70,7 +70,7 @@ jobs: if: github.event_name == 'push' || github.event.pull_request.draft == false timeout-minutes: 4 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBOX3D_SANITIZE=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON @@ -88,7 +88,7 @@ jobs: if: github.event_name == 'push' || github.event.pull_request.draft == false timeout-minutes: 4 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBOX3D_SAMPLES=OFF -DBOX3D_VALIDATE=ON -DCMAKE_COMPILE_WARNING_AS_ERROR=ON @@ -107,10 +107,10 @@ jobs: timeout-minutes: 6 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Setup MSVC dev command prompt - uses: TheMrMilchmann/setup-msvc-dev@v3 + uses: TheMrMilchmann/setup-msvc-dev@v4 with: arch: x64 @@ -126,7 +126,7 @@ jobs: if: github.event_name == 'push' || github.event.pull_request.draft == false timeout-minutes: 6 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=Release -DBOX3D_SAMPLES=ON -DBUILD_SHARED_LIBS=OFF -DBOX3D_UNIT_TESTS=OFF diff --git a/README.md b/README.md index 62bbc3c..03141e7 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,27 @@ +# Box3D + ![Box3D Logo](https://box2d.org/images/logo.svg) -# Build Status -[![Build Status](https://github.com/erincatto/box3d/actions/workflows/build.yml/badge.svg)](https://github.com/erincatto/box3d/actions) - -# Box3D Box3D is a 3D physics engine for games. -[![Box3D Version 3.0 Release Demo](https://img.youtube.com/vi/dAoM-xjOWtA/0.jpg)](https://www.youtube.com/watch?v=dAoM-xjOWtA) +## Build Status + +[![Build Status](https://github.com/erincatto/box3d/actions/workflows/build.yml/badge.svg)](https://github.com/erincatto/box3d/actions) ## Features ### Collision + - Continuous collision detection - Contact events -- Convex polygons, capsules, circles, rounded polygons, segments, and chains +- Convex hulls, capsules, spheres, triangle meshes, and height fields - Multiple shapes per body - Collision filtering - Ray casts, shape casts, and overlap queries - Sensor system ### Physics + - Robust _Soft Step_ rigid body solver - Continuous physics for fast translations and rotations - Island based sleep @@ -29,31 +31,37 @@ Box3D is a 3D physics engine for games. - Body movement events and sleep notification ### System + - Data-oriented design - Written in portable C17 - Extensive multithreading and SIMD - Optimized for large piles of bodies ### Samples -- OpenGL with GLFW + +- 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 ## Building All Platforms + - Install [CMake](https://cmake.org/) - Install [git](https://git-scm.com/) - Ensure these run from the command line ## Building for Visual Studio + - Install [Visual Studio](https://visualstudio.microsoft.com/) - Run `build_vs2026.bat` - Open and build `build/box3d.slnx` ## Building for Linux + - Run `build.sh` from a bash shell - Results are in the build sub-folder ## Building for Xcode + - mkdir build - cd build - cmake -G Xcode .. @@ -62,6 +70,7 @@ Box3D is a 3D physics engine for games. - Build and run the samples ## Building and installing + - mkdir build - cd build - cmake .. @@ -69,6 +78,7 @@ Box3D is a 3D physics engine for games. - cmake --install . (might need sudo) ## Compatibility + The Box3D library and samples build and run on Windows, Linux, and Mac. You will need a compiler that supports C17 to build the Box3D library. @@ -78,21 +88,27 @@ You will need a compiler that supports C++20 to build the samples. Box3D uses SSE2 and Neon SIMD math to improve performance. This can be disabled by defining `BOX3D_DISABLE_SIMD`. ## Documentation + - [Manual](https://box2d.org/documentation/) ## Community + - [Discord](https://discord.gg/NKYgCBP) ## Contributing + Please do not submit pull requests. Instead, please file an issue for bugs or feature requests. For support, please visit the Discord server. -# Giving Feedback +## Giving Feedback + Please file an issue or start a chat on discord. You can also use [GitHub Discussions](https://github.com/erincatto/box3d/discussions). ## License + Box3D is developed by Erin Catto and uses the [MIT license](https://en.wikipedia.org/wiki/MIT_License). ## Sponsorship + 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). diff --git a/include/box3d/box3d.h b/include/box3d/box3d.h index 8f369f3..a5c06c4 100644 --- a/include/box3d/box3d.h +++ b/include/box3d/box3d.h @@ -48,6 +48,10 @@ B3_API void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount ); /// Call this to draw shapes and other debug draw data B3_API void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits ); +/// Get the worlds bounds. This is the bounding box that covers the current simulation. May have a small +/// amount of padding. +B3_API b3AABB b3World_GetBounds( b3WorldId worldId ); + /// Get the body events for the current time step. The event data is transient. Do not store a reference to this data. B3_API b3BodyEvents b3World_GetBodyEvents( b3WorldId worldId ); diff --git a/samples/sample_character.cpp b/samples/sample_character.cpp index b47c868..c660fe3 100644 --- a/samples/sample_character.cpp +++ b/samples/sample_character.cpp @@ -152,6 +152,176 @@ public: static int sampleCapsulePlane = SampleManager::Register( "Character", "CapsulePlane", CapsulePlane::Create ); +// Exercises the deep-overlap path of b3World_CollideMover against each primitive +// shape type: drag the mover capsule (yellow) into the static sphere, capsule, +// and box hull and watch the returned planes (lime arrows) and the solved +// push-out position (cyan). The HUD reports the count of planes and the count +// of degenerate (zero) normals; the latter must stay at 0 even when the mover +// is buried inside a shape. +class MoverOverlap : public Sample +{ +public: + static Sample* Create( SampleContext* context ) + { + return new MoverOverlap( context ); + } + + explicit MoverOverlap( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 120.0f, 25.0f, 10.0f, { 0.0f, 1.0f, 0.0f } ); + } + + m_capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.35f }; + m_transform = { { 0.0f, 3.5f, 0.0f }, b3Quat_identity }; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + + // Static sphere + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { -3.0f, 1.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3Sphere sphere = { b3Vec3_zero, 0.6f }; + b3CreateSphereShape( body, &shapeDef, &sphere ); + } + + // Static capsule + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 0.0f, 1.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3Capsule capsule = { { 0.0f, 0.0f, -0.7f }, { 0.0f, 0.0f, 0.7f }, 0.4f }; + b3CreateCapsuleShape( body, &shapeDef, &capsule ); + } + + // Static box hull + { + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.position = { 3.0f, 1.0f, 0.0f }; + b3BodyId body = b3CreateBody( m_worldId, &bodyDef ); + b3BoxHull box = b3MakeBoxHull( 0.6f, 0.6f, 0.6f ); + b3CreateHullShape( body, &shapeDef, &box.base ); + } + + m_baseTranslation = b3Vec3_zero; + m_origin = b3Vec3_zero; + m_tracking = false; + m_planeCount = 0; + m_zeroNormalCount = 0; + } + + void Render() override + { + Sample::Render(); + DrawGrid( m_scene, 12 ); + } + + static bool PlaneResultFcn( b3ShapeId /*shape*/, const b3PlaneResult* results, int planeCount, void* context ) + { + MoverOverlap* self = static_cast( context ); + for ( int i = 0; i < planeCount && self->m_planeCount < m_planeCapacity; ++i ) + { + self->m_results[self->m_planeCount] = results[i]; + self->m_planeCount += 1; + } + return true; + } + + void MouseDown( b3Vec2 p, int button, int modifiers ) override + { + if ( button == 0 && ( modifiers & GLFW_MOD_ALT ) == 0 ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + m_origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_baseTranslation = m_transform.p; + m_tracking = true; + } + } + + void MouseUp( b3Vec2 /*p*/, int /*button*/ ) override + { + m_tracking = false; + } + + void MouseMove( b3Vec2 p ) override + { + if ( m_tracking ) + { + PickRay pickRay = m_camera->BuildPickRay( p.x, p.y ); + b3Vec3 origin = pickRay.origin + 10.0f * b3Normalize( pickRay.translation ); + m_transform.p = m_baseTranslation + origin - m_origin; + } + } + + void Step() override + { + // Build the mover in world space and query all overlapping shapes. + b3Capsule worldMover = { m_capsule.center1 + m_transform.p, m_capsule.center2 + m_transform.p, m_capsule.radius }; + + m_planeCount = 0; + m_zeroNormalCount = 0; + b3QueryFilter filter = b3DefaultQueryFilter(); + b3World_CollideMover( m_worldId, &worldMover, filter, PlaneResultFcn, this ); + + // Mover at the queried position. + DrawCapsule( m_scene, m_transform, m_capsule, b3_colorYellow ); + + // One arrow per returned plane, drawn from the contact point along the + // normal. A degenerate (zero) normal is drawn red to surface the bug. + b3CollisionPlane solverPlanes[m_planeCapacity]; + for ( int i = 0; i < m_planeCount; ++i ) + { + b3PlaneResult r = m_results[i]; + bool valid = b3IsNormalized( r.plane.normal ); + b3HexColor color = valid ? b3_colorLimeGreen : b3_colorRed; + DrawPoint( m_scene, r.point, 6.0f, color ); + DrawArrow( m_scene, r.point, r.point + 0.5f * r.plane.normal, 0.05f, color ); + if ( valid == false ) + { + m_zeroNormalCount += 1; + } + solverPlanes[i] = { r.plane, FLT_MAX, 0.0f, true }; + } + + // Solve the planes and show the pushed-out capsule pose. + b3PlaneSolverResult solved = b3SolvePlanes( b3Vec3_zero, solverPlanes, m_planeCount ); + b3Transform pushed = { m_transform.p + solved.delta, m_transform.q }; + DrawCapsule( m_scene, pushed, m_capsule, b3_colorCyan ); + + DrawTextLine( "drag the capsule with the left mouse to push it into the shapes" ); + DrawTextLine( "yellow = queried pose, cyan = solved push-out, lime = valid plane normals" ); + DrawTextLine( "planes: %d degenerate normals: %d", m_planeCount, m_zeroNormalCount ); + } + + void UpdateUI() override + { + float fontSize = ImGui::GetFontSize(); + ImGui::SetNextWindowPos( ImVec2( 10.0f, 600.0f ), ImGuiCond_Once ); + ImGui::SetNextWindowSize( ImVec2( 18.0f * fontSize, 5.0f * fontSize ) ); + ImGui::Begin( "Mover Overlap", nullptr, ImGuiWindowFlags_NoResize ); + ImGui::Text( "planes: %d", m_planeCount ); + ImGui::Text( "degenerate normals: %d", m_zeroNormalCount ); + ImGui::End(); + } + + static constexpr int m_planeCapacity = 32; + + b3Transform m_transform; + b3Capsule m_capsule; + b3PlaneResult m_results[m_planeCapacity] = {}; + int m_planeCount; + int m_zeroNormalCount; + + b3Vec3 m_baseTranslation; + b3Vec3 m_origin; + bool m_tracking; +}; + +static int sampleMoverOverlap = SampleManager::Register( "Character", "MoverOverlap", MoverOverlap::Create ); + class BasicMover : public Sample { public: diff --git a/src/capsule.c b/src/capsule.c index ea6c457..9ab7ebc 100644 --- a/src/capsule.c +++ b/src/capsule.c @@ -267,24 +267,32 @@ b3CastOutput b3ShapeCastCapsule( const b3Capsule* capsule, const b3ShapeCastInpu int b3CollideMoverAndCapsule( b3PlaneResult* result, const b3Capsule* shape, const b3Capsule* mover ) { - b3DistanceInput distanceInput; - distanceInput.proxyA = (b3ShapeProxy){ &shape->center1, 2, 0.0f }; - distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, mover->radius }; - distanceInput.transformA = b3Transform_identity; - distanceInput.transformB = b3Transform_identity; - distanceInput.useRadii = false; - float totalRadius = mover->radius + shape->radius; - b3SimplexCache cache = { 0 }; - b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + b3ClosestApproachResult approach = + b3ClosestApproachSegments( shape->center1, shape->center2, mover->center1, mover->center2 ); - if ( distanceOutput.distance <= totalRadius ) + // The normal points from the shape toward the mover. + float distance; + b3Vec3 normal = b3GetLengthAndNormalize( &distance, b3Sub( approach.point2, approach.point1 ) ); + + if ( distance > totalRadius ) { - b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; - *result = (b3PlaneResult){ plane, distanceOutput.pointA }; - return 1; + return 0; } - return 0; + float linearSlop = B3_LINEAR_SLOP; + if ( distance < linearSlop ) + { + // Deep overlap: the core segments intersect. Pick an arbitrary direction perpendicular + // the to capsule axis. + float moverLength; + b3Vec3 moverAxis = b3GetLengthAndNormalize( &moverLength, b3Sub( mover->center2, mover->center1 ) ); + normal = moverLength > linearSlop ? b3Perp( moverAxis ) : b3Vec3_axisY; + distance = 0.0f; + } + + b3Plane plane = { normal, totalRadius - distance }; + *result = (b3PlaneResult){ plane, approach.point1 }; + return 1; } diff --git a/src/hull.c b/src/hull.c index bd4716b..03e2765 100644 --- a/src/hull.c +++ b/src/hull.c @@ -2471,6 +2471,15 @@ int b3CollideMoverAndHull( b3PlaneResult* result, const b3Hull* shape, const b3C b3SimplexCache cache = { 0 }; b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + if ( distanceOutput.distance == 0.0f ) + { + // I could handle deep overlap on hulls, but there is no reasonable solution for + // deep overlap on meshes. So if someone converted a hull to a mesh there would be + // different behavior. So I think there is not a good reason to handle deep overlap + // on hulls. + return 0; + } + if ( distanceOutput.distance <= totalRadius ) { b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; diff --git a/src/physics_world.c b/src/physics_world.c index 23c268f..89d7f9c 100644 --- a/src/physics_world.c +++ b/src/physics_world.c @@ -1549,6 +1549,40 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits ) } } +b3AABB b3World_GetBounds( b3WorldId worldId ) +{ + b3World* world = b3GetUnlockedWorldFromId( worldId ); + if ( world == NULL ) + { + return (b3AABB){ 0 }; + } + + b3AABB worldBounds = { 0 }; + bool haveBounds = false; + + for ( int i = 0; i < b3_bodyTypeCount; ++i ) + { + b3DynamicTree* tree = world->broadPhase.trees + i; + if ( b3DynamicTree_GetProxyCount( tree ) == 0 ) + { + continue; + } + + b3AABB bounds = b3DynamicTree_GetRootBounds( world->broadPhase.trees + i ); + + if ( haveBounds ) + { + worldBounds = b3AABB_Union( worldBounds, bounds ); + } + else + { + worldBounds = bounds; + } + } + + return worldBounds; +} + b3BodyEvents b3World_GetBodyEvents( b3WorldId worldId ) { b3World* world = b3GetUnlockedWorldFromId( worldId ); diff --git a/src/sphere.c b/src/sphere.c index 5b659ef..8f2e59c 100644 --- a/src/sphere.c +++ b/src/sphere.c @@ -218,24 +218,30 @@ b3CastOutput b3ShapeCastSphere( const b3Sphere* sphere, const b3ShapeCastInput* int b3CollideMoverAndSphere( b3PlaneResult* result, const b3Sphere* shape, const b3Capsule* mover ) { - b3DistanceInput distanceInput; - distanceInput.proxyA = ( b3ShapeProxy ){ &shape->center, 1, 0.0f }; - distanceInput.proxyB = ( b3ShapeProxy ){ &mover->center1, 2, mover->radius }; - distanceInput.transformA = b3Transform_identity; - distanceInput.transformB = b3Transform_identity; - distanceInput.useRadii = false; - float totalRadius = mover->radius + shape->radius; + b3Vec3 closest = b3ClosestPointOnSegment( mover->center1, mover->center2, shape->center ); - b3SimplexCache cache = { 0 }; - b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 ); + // The normal points from the sphere toward the mover. + float distance; + b3Vec3 normal = b3GetLengthAndNormalize( &distance, b3Sub( closest, shape->center ) ); - if ( distanceOutput.distance <= totalRadius ) + if ( distance > totalRadius ) { - b3Plane plane = { distanceOutput.normal, totalRadius - distanceOutput.distance }; - *result = ( b3PlaneResult ){ plane, distanceOutput.pointA }; - return 1; + return 0; } - return 0; + float linearSlop = B3_LINEAR_SLOP; + if ( distance < linearSlop ) + { + // Deep overlap: the mover axis passes through the sphere center, so no + // direction is preferred. Push perpendicular to the mover axis. + float length; + b3Vec3 axis = b3GetLengthAndNormalize( &length, b3Sub( mover->center2, mover->center1 ) ); + normal = length > linearSlop ? b3Perp( axis ) : b3Vec3_axisY; + distance = 0.0f; + } + + b3Plane plane = { normal, totalRadius - distance }; + *result = ( b3PlaneResult ){ plane, shape->center }; + return 1; } diff --git a/test/test_mover.c b/test/test_mover.c index 2844ae3..89e16ca 100644 --- a/test/test_mover.c +++ b/test/test_mover.c @@ -3,6 +3,9 @@ #include "test_macros.h" +// b3CollideMoverAndSphere / Capsule / Hull are internal +#include "shape.h" + #include "box3d/collision.h" static int ParallelPlanes( void ) @@ -51,10 +54,202 @@ static int GamePlanes( void ) return 0; } +// --------------------------------------------------------------------------- +// Mover-collide overlap handling +// +// b3CollideMoverAndSphere / Capsule / Hull must never emit a plane with a +// degenerate (zero) normal, even when the mover deeply penetrates the shape. +// On deep overlap the GJK path returns a {0,0,0} normal; these tests guard the +// fix that replaces it with an analytic (sphere/capsule) or dropped (hull) result. +// --------------------------------------------------------------------------- + +static int MoverSphereSeparated( void ) +{ + b3Sphere shape = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + b3Capsule mover = { { 4.0f, 3.0f, 0.0f }, { 6.0f, 3.0f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndSphere( &result, &shape, &mover ); + ENSURE( count == 0 ); + + return 0; +} + +static int MoverSphereTouching( void ) +{ + b3Sphere shape = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + + // Mover core segment runs along X at y = 0.6, leaving it 0.1 inside the + // 0.7 combined radius. + b3Capsule mover = { { -1.0f, 0.6f, 0.0f }, { 1.0f, 0.6f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndSphere( &result, &shape, &mover ); + ENSURE( count == 1 ); + ENSURE( b3IsNormalized( result.plane.normal ) ); + + // Push-out points from the sphere straight up toward the mover. + ENSURE( result.plane.normal.y > 0.99f ); + ENSURE_SMALL( result.plane.offset - 0.1f, 1e-5f ); + + return 0; +} + +static int MoverSphereDeepOverlap( void ) +{ + b3Sphere shape = { { 0.0f, 0.0f, 0.0f }, 0.5f }; + + // Mover axis runs straight through the sphere center: the bug case where + // GJK reports a zero normal. + b3Capsule mover = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndSphere( &result, &shape, &mover ); + ENSURE( count == 1 ); + + // The normal must still be a valid unit vector. + ENSURE( b3IsNormalized( result.plane.normal ) ); + + // The fallback axis is perpendicular to the mover axis (X). + ENSURE_SMALL( result.plane.normal.x, 1e-5f ); + + // Deepest possible penetration: the full combined radius. + ENSURE_SMALL( result.plane.offset - 0.7f, 1e-5f ); + + return 0; +} + +static int MoverCapsuleSeparated( void ) +{ + b3Capsule shape = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.3f }; + b3Capsule mover = { { -1.0f, 5.0f, 0.0f }, { 1.0f, 5.0f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndCapsule( &result, &shape, &mover ); + ENSURE( count == 0 ); + + return 0; +} + +static int MoverCapsuleTouching( void ) +{ + b3Capsule shape = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.3f }; + + // Parallel mover 0.4 above, leaving it 0.1 inside the 0.5 combined radius. + b3Capsule mover = { { -1.0f, 0.4f, 0.0f }, { 1.0f, 0.4f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndCapsule( &result, &shape, &mover ); + ENSURE( count == 1 ); + ENSURE( b3IsNormalized( result.plane.normal ) ); + ENSURE( result.plane.normal.y > 0.99f ); + ENSURE_SMALL( result.plane.offset - 0.1f, 1e-5f ); + + return 0; +} + +static int MoverCapsuleDeepOverlap( void ) +{ + // Shape capsule along X, mover capsule along Z; their core segments cross + // exactly at the origin, so GJK reports a zero normal. + b3Capsule shape = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.3f }; + b3Capsule mover = { { 0.0f, 0.0f, -1.0f }, { 0.0f, 0.0f, 1.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndCapsule( &result, &shape, &mover ); + ENSURE( count == 1 ); + ENSURE( b3IsNormalized( result.plane.normal ) ); + + // The separating axis of two crossing segments is perpendicular to both. + ENSURE_SMALL( result.plane.normal.x, 1e-5f ); + ENSURE_SMALL( result.plane.normal.z, 1e-5f ); + ENSURE_SMALL( result.plane.offset - 0.5f, 1e-5f ); + + return 0; +} + +static int MoverCapsuleParallelOverlap( void ) +{ + // Mover core segment coincides with the shape core segment: the cross-product + // axis degenerates, so a perpendicular of the mover axis is used instead. + b3Capsule shape = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.3f }; + b3Capsule mover = { { -1.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndCapsule( &result, &shape, &mover ); + ENSURE( count == 1 ); + ENSURE( b3IsNormalized( result.plane.normal ) ); + + // The fallback axis is perpendicular to the mover axis (X). + ENSURE_SMALL( result.plane.normal.x, 1e-5f ); + ENSURE_SMALL( result.plane.offset - 0.5f, 1e-5f ); + + return 0; +} + +static int MoverHullSeparated( void ) +{ + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + b3Capsule mover = { { -0.3f, 5.0f, 0.0f }, { 0.3f, 5.0f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndHull( &result, &box.base, &mover ); + ENSURE( count == 0 ); + + return 0; +} + +static int MoverHullTouching( void ) +{ + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + // Mover core segment above the +Y face; the 0.2 radius reaches 0.1 into it. + b3Capsule mover = { { -0.3f, 0.6f, 0.0f }, { 0.3f, 0.6f, 0.0f }, 0.2f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndHull( &result, &box.base, &mover ); + ENSURE( count == 1 ); + ENSURE( b3IsNormalized( result.plane.normal ) ); + ENSURE( result.plane.normal.y > 0.99f ); + ENSURE_SMALL( result.plane.offset - 0.1f, 1e-4f ); + + return 0; +} + +static int MoverHullDeepOverlap( void ) +{ + b3BoxHull box = b3MakeBoxHull( 0.5f, 0.5f, 0.5f ); + + // Mover core segment lies entirely inside the box, so GJK reports overlap. + b3Capsule mover = { { -0.2f, 0.0f, 0.0f }, { 0.2f, 0.0f, 0.0f }, 0.1f }; + + b3PlaneResult result = { 0 }; + int count = b3CollideMoverAndHull( &result, &box.base, &mover ); + + // The overlap guard drops the plane rather than emit a zero normal. + // todo replace with SAT once b3CollideMoverAndHull resolves overlaps. + ENSURE( count == 0 ); + + return 0; +} + int MoverTest( void ) { RUN_SUBTEST( GamePlanes ); RUN_SUBTEST( ParallelPlanes ); + RUN_SUBTEST( MoverSphereSeparated ); + RUN_SUBTEST( MoverSphereTouching ); + RUN_SUBTEST( MoverSphereDeepOverlap ); + + RUN_SUBTEST( MoverCapsuleSeparated ); + RUN_SUBTEST( MoverCapsuleTouching ); + RUN_SUBTEST( MoverCapsuleDeepOverlap ); + RUN_SUBTEST( MoverCapsuleParallelOverlap ); + + RUN_SUBTEST( MoverHullSeparated ); + RUN_SUBTEST( MoverHullTouching ); + RUN_SUBTEST( MoverHullDeepOverlap ); + return 0; }