diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt index c3e21cb..629dfb9 100644 --- a/benchmark/CMakeLists.txt +++ b/benchmark/CMakeLists.txt @@ -18,4 +18,21 @@ endif() target_link_libraries(benchmark PRIVATE box3d shared) -source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX3D_BENCHMARK_FILES}) \ No newline at end of file +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX3D_BENCHMARK_FILES}) +# Mesh drop soak. Uses internal threads, so it needs the static library. +if (NOT BUILD_SHARED_LIBS) + add_executable(mesh_soak mesh_soak.c) + + set_target_properties(mesh_soak PROPERTIES + C_STANDARD 17 + C_STANDARD_REQUIRED YES + C_EXTENSIONS NO + ) + + if (BOX3D_COMPILE_WARNING_AS_ERROR) + set_target_properties(mesh_soak PROPERTIES COMPILE_WARNING_AS_ERROR ON) + endif() + + target_include_directories(mesh_soak PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../src) + target_link_libraries(mesh_soak PRIVATE box3d) +endif() diff --git a/benchmark/mesh_soak.c b/benchmark/mesh_soak.c new file mode 100644 index 0000000..ca06128 --- /dev/null +++ b/benchmark/mesh_soak.c @@ -0,0 +1,452 @@ +// SPDX-FileCopyrightText: 2026 Erin Catto +// SPDX-License-Identifier: MIT + +// Headless soak of the Continuous / Mesh Drop sample. Each generation drops 1024 small bodies on a +// wave mesh and steps until every body sleeps. A generation fails if a body falls through the mesh +// or the pile is still awake at the step limit. Generations run in parallel, one single threaded +// world per thread. The printed seed reproduces a generation in the sample. + +#include "core.h" + +#include "box3d/box3d.h" +#include "box3d/collision.h" +#include "box3d/math_functions.h" + +#include +#include +#include + +#define GRID_COUNT 32 +#define BODY_COUNT ( GRID_COUNT * GRID_COUNT ) +#define MAX_REPORTED_FAILURES 32 +#define MAX_THREADS 64 + +typedef enum ShapeType +{ + e_box, + e_capsule, + e_cylinder, + e_sphere, + e_shapeCount, +} ShapeType; + +static const char* s_shapeNames[e_shapeCount] = { "box", "capsule", "cylinder", "sphere" }; + +typedef enum FailureKind +{ + e_tunnel, + e_awake, +} FailureKind; + +typedef struct Failure +{ + FailureKind kind; + ShapeType shapeType; + int generation; + uint32_t seed; + int step; + int index1; + int index2; + b3Pos position; +} Failure; + +typedef struct Soak +{ + b3Mutex* mutex; + b3MeshData* groundMesh; + b3HullData* cylinder; + uint32_t baseSeed; + int generationCount; + int nextGeneration; + int shapeType; + bool fixedSeed; + + int completedCount; + int failureCount; + int tunnelCount; + int awakeCount; + long long totalSteps; + int maxSteps; + Failure failures[MAX_REPORTED_FAILURES]; +} Soak; + +// Same XorShift32 and mapping as the samples, so a seed replays there +static float RandomFloatRange( uint32_t* seed, float lo, float hi ) +{ + uint32_t x = *seed; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + *seed = x; + + int i = (int)( x % 32768 ); + float r = (float)( i & 32767 ) / 32767.0f; + return ( hi - lo ) * r + lo; +} + +static b3Vec3 RandomVec3Uniform( uint32_t* seed, float lo, float hi ) +{ + b3Vec3 v; + v.x = RandomFloatRange( seed, lo, hi ); + v.y = RandomFloatRange( seed, lo, hi ); + v.z = RandomFloatRange( seed, lo, hi ); + return v; +} + +static uint32_t HashSeed( uint32_t x ) +{ + x ^= x >> 16; + x *= 0x7feb352du; + x ^= x >> 15; + x *= 0x846ca68bu; + x ^= x >> 16; + return x != 0 ? x : 1; +} + +static void CreateGround( b3WorldId worldId, const b3MeshData* mesh ) +{ + b3BodyDef bodyDef = b3DefaultBodyDef(); + b3BodyId groundId = b3CreateBody( worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.filter.categoryBits = 1; + b3CreateMeshShape( groundId, &shapeDef, mesh, b3Vec3_one ); + + float extent = 20.0f; + float halfHeight = 1.0f; + + b3Transform transforms[4] = { + { { 0.0f, halfHeight, -extent }, b3Quat_identity }, + { { 0.0f, halfHeight, extent }, b3Quat_identity }, + { { -extent, halfHeight, 0.0f }, b3Quat_identity }, + { { extent, halfHeight, 0.0f }, b3Quat_identity }, + }; + + for ( int i = 0; i < 4; ++i ) + { + float hx = i < 2 ? extent : 0.1f; + float hz = i < 2 ? 0.1f : extent; + b3BoxHull wallBox = b3MakeTransformedBoxHull( hx, halfHeight, hz, transforms[i] ); + b3CreateHullShape( groundId, &shapeDef, &wallBox.base ); + } +} + +static void RecordFailure( Soak* soak, const Failure* failure ) +{ + b3LockMutex( soak->mutex ); + if ( soak->failureCount < MAX_REPORTED_FAILURES ) + { + soak->failures[soak->failureCount] = *failure; + } + soak->failureCount += 1; + if ( failure->kind == e_tunnel ) + { + soak->tunnelCount += 1; + } + else + { + soak->awakeCount += 1; + } + b3UnlockMutex( soak->mutex ); + + const char* kind = failure->kind == e_tunnel ? "TUNNEL" : "AWAKE"; + printf( "%s: generation %d, %s, seed %u, step %d, body (%d, %d) at (%.2f, %.2f, %.2f)\n", kind, failure->generation, + s_shapeNames[failure->shapeType], failure->seed, failure->step, failure->index1, failure->index2, + (float)failure->position.x, (float)failure->position.y, (float)failure->position.z ); +} + +// Mirrors MeshDrop::Generate and the auto generate step loop +static int RunGeneration( Soak* soak, int generation, uint32_t seed, ShapeType shapeType, b3BodyId* bodies ) +{ + b3WorldDef worldDef = b3DefaultWorldDef(); + worldDef.workerCount = 1; + + // The world registry is global and not thread safe + b3LockMutex( soak->mutex ); + b3WorldId worldId = b3CreateWorld( &worldDef ); + b3UnlockMutex( soak->mutex ); + + CreateGround( worldId, soak->groundMesh ); + + b3BoxHull box = b3MakeBoxHull( 0.02f, 0.2f, 0.04f ); + b3Capsule capsule = { { 0.0f, -0.2f, 0.0f }, { 0.0f, 0.2f, 0.0f }, 0.05f }; + b3Sphere sphere = { b3Vec3_zero, 0.05f }; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.rollingResistance = shapeType == e_capsule || shapeType == e_sphere ? 0.4f : 0.1f; + + // Isolate mesh collision + shapeDef.filter.categoryBits = 2; + shapeDef.filter.maskBits = 1; + + uint32_t random = seed; + int bodyIndex = 0; + for ( int i = 0; i < GRID_COUNT; ++i ) + { + for ( int j = 0; j < GRID_COUNT; ++j ) + { + b3Vec3 linearVelocity = RandomVec3Uniform( &random, -1.0f, 1.0f ); + b3Vec3 angularVelocity = RandomVec3Uniform( &random, -5.0f, 5.0f ); + + bodyDef.position = (b3Pos){ 0.5f * ( i - 0.5f * GRID_COUNT ), 5.0f, 0.5f * ( j - 0.5f * GRID_COUNT ) }; + bodyDef.linearVelocity = linearVelocity; + bodyDef.angularVelocity = angularVelocity; + b3BodyId bodyId = b3CreateBody( worldId, &bodyDef ); + + switch ( shapeType ) + { + case e_box: + b3CreateHullShape( bodyId, &shapeDef, &box.base ); + break; + case e_capsule: + b3CreateCapsuleShape( bodyId, &shapeDef, &capsule ); + break; + case e_cylinder: + b3CreateHullShape( bodyId, &shapeDef, soak->cylinder ); + break; + default: + b3CreateSphereShape( bodyId, &shapeDef, &sphere ); + break; + } + + bodies[bodyIndex++] = bodyId; + } + } + + float timeStep = 1.0f / 60.0f; + int subStepCount = 4; + int maxSteps = shapeType == e_capsule ? 3000 : 1000; + int step = 0; + bool failed = false; + + while ( failed == false ) + { + b3World_Step( worldId, timeStep, subStepCount ); + step += 1; + + for ( int i = 0; i < BODY_COUNT; ++i ) + { + b3Pos center = b3Body_GetWorldCenter( bodies[i] ); + if ( center.y < -2.0f ) + { + Failure failure = { e_tunnel, shapeType, generation, seed, step, i / GRID_COUNT, i % GRID_COUNT, center }; + RecordFailure( soak, &failure ); + failed = true; + break; + } + } + + if ( b3World_GetBodyEvents( worldId ).moveCount == 0 ) + { + break; + } + + if ( failed == false && step > maxSteps ) + { + int awakeIndex = 0; + for ( int i = 0; i < BODY_COUNT; ++i ) + { + if ( b3Body_IsAwake( bodies[i] ) ) + { + awakeIndex = i; + break; + } + } + + b3Pos center = b3Body_GetWorldCenter( bodies[awakeIndex] ); + Failure failure = { e_awake, shapeType, generation, seed, step, awakeIndex / GRID_COUNT, awakeIndex % GRID_COUNT, center }; + RecordFailure( soak, &failure ); + failed = true; + } + } + + b3LockMutex( soak->mutex ); + b3DestroyWorld( worldId ); + b3UnlockMutex( soak->mutex ); + + return step; +} + +static void SoakWorker( void* context ) +{ + Soak* soak = context; + b3BodyId* bodies = malloc( BODY_COUNT * sizeof( b3BodyId ) ); + + while ( true ) + { + b3LockMutex( soak->mutex ); + int generation = soak->nextGeneration; + soak->nextGeneration += 1; + b3UnlockMutex( soak->mutex ); + + if ( generation >= soak->generationCount ) + { + break; + } + + uint32_t seed = soak->fixedSeed ? soak->baseSeed : HashSeed( soak->baseSeed + (uint32_t)generation ); + ShapeType shapeType = soak->shapeType >= 0 ? (ShapeType)soak->shapeType : (ShapeType)( generation % e_shapeCount ); + + int steps = RunGeneration( soak, generation, seed, shapeType, bodies ); + + b3LockMutex( soak->mutex ); + soak->completedCount += 1; + soak->totalSteps += steps; + soak->maxSteps = b3MaxInt( soak->maxSteps, steps ); + int completed = soak->completedCount; + b3UnlockMutex( soak->mutex ); + + if ( completed % 100 == 0 ) + { + printf( "%d generations, %d bodies\n", completed, completed * BODY_COUNT ); + fflush( stdout ); + } + } + + free( bodies ); +} + +static const char* MatchValue( const char* arg, const char* shortName, const char* longName ) +{ + size_t shortLength = strlen( shortName ); + if ( strncmp( arg, shortName, shortLength ) == 0 ) + { + return arg + shortLength; + } + + size_t longLength = strlen( longName ); + if ( strncmp( arg, longName, longLength ) == 0 ) + { + return arg + longLength; + } + + return NULL; +} + +int main( int argc, char** argv ) +{ + int generationCount = 1000; + int threadCount = 8; + int shapeType = e_box; + uint32_t seed = (uint32_t)b3GetTicks(); + bool fixedSeed = false; + float amplitude = 0.5f; + + for ( int i = 1; i < argc; ++i ) + { + const char* arg = argv[i]; + const char* value; + + if ( ( value = MatchValue( arg, "-g=", "--generations=" ) ) != NULL ) + { + generationCount = atoi( value ); + } + else if ( ( value = MatchValue( arg, "-t=", "--threads=" ) ) != NULL ) + { + threadCount = b3ClampInt( atoi( value ), 1, MAX_THREADS ); + } + else if ( ( value = MatchValue( arg, "-s=", "--shape=" ) ) != NULL ) + { + shapeType = -2; + for ( int k = 0; k < e_shapeCount; ++k ) + { + if ( strcmp( value, s_shapeNames[k] ) == 0 ) + { + shapeType = k; + } + } + + if ( strcmp( value, "all" ) == 0 ) + { + shapeType = -1; + } + + if ( shapeType == -2 ) + { + printf( "unknown shape: %s\n", value ); + return 2; + } + } + else if ( ( value = MatchValue( arg, "-seed=", "--seed=" ) ) != NULL ) + { + seed = (uint32_t)strtoul( value, NULL, 10 ); + fixedSeed = true; + } + else if ( ( value = MatchValue( arg, "-b=", "--base-seed=" ) ) != NULL ) + { + seed = (uint32_t)strtoul( value, NULL, 10 ); + } + else if ( ( value = MatchValue( arg, "-a=", "--amplitude=" ) ) != NULL ) + { + amplitude = (float)atof( value ); + } + else + { + printf( "Usage: mesh_soak [options]\n" + "Drops %d bodies per generation on the Mesh Drop wave mesh until they sleep.\n" + "Fails on a body below y = -2 (tunnel) or a pile awake past the step limit.\n" + " -g, --generations= generation count (default 1000)\n" + " -t, --threads= worker threads, one world each (default 8)\n" + " -s, --shape= box, capsule, cylinder, sphere or all (default box)\n" + " -b, --base-seed= base seed, each generation hashes its own seed from it\n" + " --seed= run every generation with this exact seed (replay)\n" + " -a, --amplitude= wave amplitude (default 0.5)\n" + "Exit code is 0 when every generation passes, 1 otherwise.\n", + BODY_COUNT ); + return 2; + } + } + + Soak soak = { 0 }; + soak.mutex = b3CreateMutex(); + soak.groundMesh = b3CreateWaveMesh( 40, 40, 1.0f, amplitude, 0.1f, 0.2f ); + soak.cylinder = b3CreateCylinder( 0.4f, 0.05f, 0.0f, 6 ); + soak.baseSeed = seed; + soak.fixedSeed = fixedSeed; + soak.generationCount = generationCount; + soak.shapeType = shapeType; + + const char* shapeName = shapeType >= 0 ? s_shapeNames[shapeType] : "all"; + printf( "mesh soak: %d generations, %d threads, shape %s, %s seed %u\n", generationCount, threadCount, shapeName, + fixedSeed ? "fixed" : "base", seed ); + fflush( stdout ); + + uint64_t ticks = b3GetTicks(); + + b3Thread* threads[MAX_THREADS]; + for ( int i = 0; i < threadCount; ++i ) + { + threads[i] = b3CreateThread( SoakWorker, &soak, "soak" ); + } + + for ( int i = 0; i < threadCount; ++i ) + { + b3JoinThread( threads[i] ); + } + + float seconds = 0.001f * b3GetMilliseconds( ticks ); + double averageSteps = soak.completedCount > 0 ? (double)soak.totalSteps / soak.completedCount : 0.0; + + printf( "generations: %d, bodies: %d, tunnels: %d, awake: %d\n", soak.completedCount, soak.completedCount * BODY_COUNT, + soak.tunnelCount, soak.awakeCount ); + printf( "steps to sleep: average %.0f, max %d, time %.1f s\n", averageSteps, soak.maxSteps, seconds ); + + int reported = b3MinInt( soak.failureCount, MAX_REPORTED_FAILURES ); + for ( int i = 0; i < reported; ++i ) + { + Failure* f = soak.failures + i; + printf( " %s %s seed %u body (%d, %d)\n", f->kind == e_tunnel ? "tunnel" : "awake", s_shapeNames[f->shapeType], f->seed, + f->index1, f->index2 ); + } + + printf( soak.failureCount == 0 ? "PASS\n" : "FAIL\n" ); + + b3DestroyHull( soak.cylinder ); + b3DestroyMesh( soak.groundMesh ); + b3DestroyMutex( soak.mutex ); + + return soak.failureCount == 0 ? 0 : 1; +} diff --git a/samples/sample_continuous.cpp b/samples/sample_continuous.cpp index 6ff45dd..31c94dc 100644 --- a/samples/sample_continuous.cpp +++ b/samples/sample_continuous.cpp @@ -441,7 +441,7 @@ public: m_runCount = 0; m_failure = false; m_autoGenerate = false; - m_collide = true; + m_collide = false; m_stepWhilePaused = true; Generate(); @@ -544,7 +544,14 @@ public: bodyDef.type = b3_dynamicBody; b3ShapeDef shapeDef = b3DefaultShapeDef(); - shapeDef.baseMaterial.rollingResistance = m_shapeType == e_capsule ? 0.4f : 0.1f; + if (m_shapeType == e_capsule || m_shapeType == e_sphere) + { + shapeDef.baseMaterial.rollingResistance = 0.4f; + } + else + { + shapeDef.baseMaterial.rollingResistance = 0.1f; + } // Don't allow shapes to collide with each other. This // makes isolating failures easier. @@ -554,10 +561,11 @@ public: shapeDef.filter.maskBits = 1; } - g_randomSeed = (uint32_t)b3GetTicks(); + // A non-zero seed replays a generation reported by the mesh_soak tool + g_randomSeed = m_replaySeed != 0 ? m_replaySeed : (uint32_t)b3GetTicks(); bool simulateAll = true; - // g_randomSeed = 1910133196; + //g_randomSeed = 2772533094; m_runCount += 1; m_stepCount = 0; @@ -570,7 +578,7 @@ public: b3Vec3 linearVelocity = RandomVec3Uniform( -1.0f, 1.0f ); b3Vec3 angularVelocity = RandomVec3Uniform( -5.0f, 5.0f ); - if ( simulateAll || ( i == 19 && j == 20 ) ) + if ( simulateAll || ( i == 9 && j == 3 ) ) { bodyDef.position = { 0.5f * ( i - 0.5f * m_gridCount ), 5.0f, 0.5f * ( j - 0.5f * m_gridCount ) }; bodyDef.linearVelocity = linearVelocity; @@ -631,6 +639,8 @@ public: Generate(); } + ImGui::InputScalar( "Seed", ImGuiDataType_U32, &m_replaySeed ); + if ( ImGui::Button( "Generate" ) ) { Generate(); @@ -743,6 +753,7 @@ public: bool m_failure; bool m_autoGenerate; bool m_collide; + uint32_t m_replaySeed = 0; }; static int sampleMeshDrop = RegisterSample( "Continuous", "Mesh Drop", MeshDrop::Create ); diff --git a/samples/sample_mesh.cpp b/samples/sample_mesh.cpp index 9438735..1a76391 100644 --- a/samples/sample_mesh.cpp +++ b/samples/sample_mesh.cpp @@ -1621,3 +1621,627 @@ public: }; static int sampleHollowBox = RegisterSample( "Mesh", "Hollow Box", HollowBox::Create ); + +// Ghost collision scenes. Each ground is a profile in the xy-plane extruded along z and finely +// tessellated, so a sliding body crosses many internal edges. A manifold that pushes on the body +// is a ghost when its normal points outside the span of face normals under the body. Those are the +// ones that block or launch a body. +class GhostCollisions : public Sample +{ +public: + enum Scene + { + e_flat, + e_concaveRamp, + e_cliff, + e_crest, + e_bumps, + e_tJunction, + e_shapeSeam, + e_internalEdges, + e_sceneCount + }; + + enum BodyType + { + e_box, + e_capsule, + e_uprightCapsule, + e_sphere, + e_cylinder, + e_bodyTypeCount + }; + + // Mesh variants of the PEEL InternalEdges presets + struct PeelPreset + { + int columnCount; + float scaleX; + float startZ; + }; + + static constexpr PeelPreset m_peelPresets[] = { + { 4, 0.1f, -55.0f }, + { 4, 0.1f, -54.0f }, + { 4, 0.01f, -55.0f }, + { 16, 0.01f, -54.0f }, + }; + + static constexpr float m_halfLength = 20.0f; + static constexpr float m_halfWidth = 3.0f; + static constexpr float m_startX = -16.0f; + static constexpr int m_markerCapacity = 256; + + explicit GhostCollisions( SampleContext* context ) + : Sample( context ) + { + if ( m_context->restart == false ) + { + m_camera->SetView( 90.0f, 20.0f, 30.0f, { 0.0f, 1.0f, 0.0f } ); + } + + m_cylinder = b3CreateCylinder( 0.4f, 0.4f, -0.2f, 16 ); + m_peelCylinder = b3CreateCylinder( 2.0f, 1.0f, -1.0f, 16 ); + m_groundId = b3_nullBodyId; + m_bodyId = b3_nullBodyId; + m_shapeId = b3_nullShapeId; + + CreateGround(); + Launch(); + } + + ~GhostCollisions() override + { + DestroyMeshes(); + b3DestroyHull( m_cylinder ); + b3DestroyHull( m_peelCylinder ); + } + + void DestroyMeshes() + { + for ( int i = 0; i < m_meshCount; ++i ) + { + b3DestroyMesh( m_meshes[i] ); + m_meshes[i] = nullptr; + } + m_meshCount = 0; + } + + // The profile runs in +x with the solid below it. The mirror flips x in the data and the mesh + // scale flips it back, so the world geometry is the same either way. + void AddStrip( std::vector& vertices, std::vector& indices, const b3Vec2* profile, int count, + float zCell ) const + { + std::vector points; + points.push_back( profile[0] ); + for ( int k = 0; k + 1 < count; ++k ) + { + b3Vec2 a = profile[k]; + b3Vec2 b = profile[k + 1]; + float length = sqrtf( ( b.x - a.x ) * ( b.x - a.x ) + ( b.y - a.y ) * ( b.y - a.y ) ); + int n = b3MaxInt( 1, (int)ceilf( length / m_cellSize - 0.01f ) ); + for ( int s = 1; s <= n; ++s ) + { + float t = (float)s / (float)n; + points.push_back( { a.x + t * ( b.x - a.x ), a.y + t * ( b.y - a.y ) } ); + } + } + + int zCount = b3MaxInt( 1, (int)ceilf( 2.0f * m_halfWidth / zCell - 0.01f ) ); + AddGrid( vertices, indices, points, m_halfWidth, zCount, true ); + } + + void AddGrid( std::vector& vertices, std::vector& indices, const std::vector& points, + float halfWidth, int zCount, bool alternate ) const + { + float sign = m_mirror ? -1.0f : 1.0f; + int stride = zCount + 1; + int base = (int)vertices.size(); + + for ( b3Vec2 p : points ) + { + for ( int j = 0; j <= zCount; ++j ) + { + float z = -halfWidth + 2.0f * halfWidth * (float)j / (float)zCount; + vertices.push_back( { sign * p.x, p.y, z } ); + } + } + + bool mirror = m_mirror; + auto emit = [&]( int i1, int i2, int i3 ) { + indices.push_back( i1 ); + indices.push_back( mirror ? i3 : i2 ); + indices.push_back( mirror ? i2 : i3 ); + }; + + int pointCount = (int)points.size(); + for ( int i = 0; i + 1 < pointCount; ++i ) + { + for ( int j = 0; j < zCount; ++j ) + { + int a = base + i * stride + j; + int b = a + 1; + int c = a + stride + 1; + int d = a + stride; + + // Alternate the diagonal like cooked level geometry + if ( alternate && ( ( i + j ) & 1 ) ) + { + emit( a, b, d ); + emit( b, c, d ); + } + else + { + emit( a, b, c ); + emit( c, d, a ); + } + } + } + } + + void AddMesh( std::vector& vertices, std::vector& indices, bool frictionless = false ) + { + b3MeshDef meshDef = {}; + meshDef.vertices = vertices.data(); + meshDef.indices = indices.data(); + meshDef.vertexCount = (int)vertices.size(); + meshDef.triangleCount = (int)( indices.size() / 3 ); + meshDef.weldVertices = true; + meshDef.weldTolerance = 0.001f; + meshDef.identifyEdges = true; + + b3MeshData* mesh = b3CreateMesh( &meshDef, nullptr, 0 ); + m_meshes[m_meshCount++] = mesh; + + b3Vec3 scale = m_mirror ? b3Vec3{ -1.0f, 1.0f, 1.0f } : b3Vec3_one; + b3ShapeDef shapeDef = b3DefaultShapeDef(); + if ( frictionless ) + { + shapeDef.baseMaterial.friction = 0.0f; + } + b3CreateMeshShape( m_groundId, &shapeDef, mesh, scale ); + } + + void CreateGround() + { + if ( B3_IS_NON_NULL( m_groundId ) ) + { + b3DestroyBody( m_groundId ); + } + DestroyMeshes(); + + b3BodyDef bodyDef = b3DefaultBodyDef(); + m_groundId = b3CreateBody( m_worldId, &bodyDef ); + + float h = m_halfLength; + m_profile.clear(); + + switch ( m_scene ) + { + case e_concaveRamp: + { + float slope = 8.0f * B3_PI / 180.0f; + m_profile = { { -h, h * tanf( slope ) }, { 0.0f, 0.0f }, { h, 0.0f } }; + } + break; + + case e_cliff: + m_profile = { { -h, 3.0f }, { 0.0f, 3.0f }, { 0.0f, 0.0f }, { h, 0.0f } }; + break; + + case e_crest: + m_profile = { { -h, 0.0f }, { -10.0f, 0.0f }, { 0.0f, 1.0f }, { 10.0f, 0.0f }, { h, 0.0f } }; + break; + + case e_bumps: + // Gentle folds of a few degrees, the range that only flat edge suppression misses + for ( int i = 0; i <= 80; ++i ) + { + float x = -h + 0.5f * (float)i; + float y = x < -10.0f ? 0.0f : 0.05f * ( 1.0f - cosf( B3_PI * x ) ); + m_profile.push_back( { x, y } ); + } + break; + + case e_internalEdges: + // PEEL's curved mesh: 32 rows 4 m apart, each step up 1.25 times the last, sliding toward +x + for ( int i = 31; i >= 0; --i ) + { + m_profile.push_back( { 62.0f - 4.0f * (float)i, 1.0f + 0.1f * powf( 1.25f, (float)i ) } ); + } + break; + + default: + m_profile = { { -h, 0.0f }, { h, 0.0f } }; + break; + } + + std::vector vertices; + std::vector indices; + b3Vec2 left[2] = { { -h, 0.0f }, { 0.0f, 0.0f } }; + b3Vec2 right[2] = { { 0.0f, 0.0f }, { h, 0.0f } }; + + if ( m_scene == e_tJunction ) + { + // Fine and coarse strips share only every other vertex along x = 0 + AddStrip( vertices, indices, left, 2, 0.5f * m_cellSize ); + AddStrip( vertices, indices, right, 2, m_cellSize ); + AddMesh( vertices, indices ); + } + else if ( m_scene == e_shapeSeam ) + { + // Two mesh shapes meeting at x = 0, so the seam spans two contacts + AddStrip( vertices, indices, left, 2, m_cellSize ); + AddMesh( vertices, indices ); + + vertices.clear(); + indices.clear(); + AddStrip( vertices, indices, right, 2, m_cellSize ); + AddMesh( vertices, indices ); + } + else if ( m_scene == e_internalEdges ) + { + // The mesh has no friction and the ground plane under it does, as in PEEL + const PeelPreset& preset = m_peelPresets[m_peelPreset]; + int zCount = preset.columnCount - 1; + float halfWidth = 20.0f * preset.scaleX * (float)zCount; + AddGrid( vertices, indices, m_profile, halfWidth, zCount, false ); + AddMesh( vertices, indices, true ); + + b3BoxHull box = b3MakeOffsetBoxHull( 140.0f, 1.0f, 30.0f, { 65.0f, -1.0f, 0.0f } ); + b3ShapeDef shapeDef = b3DefaultShapeDef(); + b3CreateHullShape( m_groundId, &shapeDef, &box.base ); + } + else + { + AddStrip( vertices, indices, m_profile.data(), (int)m_profile.size(), m_cellSize ); + AddMesh( vertices, indices ); + } + } + + void Launch() + { + if ( B3_IS_NON_NULL( m_bodyId ) ) + { + b3DestroyBody( m_bodyId ); + } + + // PEEL drops its bodies from rest, sized in meters rather than tenths + bool peel = m_scene == e_internalEdges; + float boxHalf = peel ? 1.0f : 0.2f; + float capsuleRadius = peel ? 1.0f : 0.2f; + float capsuleHalf = peel ? 2.0f : 0.4f; + float sphereRadius = peel ? 1.0f : 0.25f; + + b3BodyDef bodyDef = b3DefaultBodyDef(); + bodyDef.type = b3_dynamicBody; + b3Quat yaw = b3MakeQuatFromAxisAngle( b3Vec3_axisY, m_yaw * B3_PI / 180.0f ); + + if ( peel ) + { + bodyDef.position = { m_peelPresets[m_peelPreset].startZ, 80.0f, 0.0f }; + bodyDef.rotation = yaw; + } + else + { + int segment = 0; + for ( int k = 0; k + 1 < (int)m_profile.size(); ++k ) + { + if ( m_profile[k].x <= m_startX && m_startX < m_profile[k + 1].x ) + { + segment = k; + break; + } + } + + b3Vec2 a = m_profile[segment]; + b3Vec2 b = m_profile[segment + 1]; + float length = sqrtf( ( b.x - a.x ) * ( b.x - a.x ) + ( b.y - a.y ) * ( b.y - a.y ) ); + b3Vec2 d = { ( b.x - a.x ) / length, ( b.y - a.y ) / length }; + b3Vec2 n = { -d.y, d.x }; + float y = a.y + ( m_startX - a.x ) * d.y / d.x; + + float lift = boxHalf; + if ( m_bodyType == e_sphere ) + { + lift = sphereRadius; + } + else if ( m_bodyType == e_uprightCapsule ) + { + lift = capsuleHalf + capsuleRadius; + } + lift += 0.01f; + + bodyDef.position = { m_startX + lift * n.x, y + lift * n.y, 0.0f }; + b3Quat slope = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, atan2f( d.y, d.x ) ); + bodyDef.rotation = b3MulQuat( slope, yaw ); + bodyDef.linearVelocity = { m_speed * d.x, m_speed * d.y, 0.0f }; + } + + bodyDef.motionLocks.angularX = m_fixedRotation; + bodyDef.motionLocks.angularY = m_fixedRotation; + bodyDef.motionLocks.angularZ = m_fixedRotation; + bodyDef.enableSleep = false; + bodyDef.name = "slider"; + m_bodyId = b3CreateBody( m_worldId, &bodyDef ); + + b3ShapeDef shapeDef = b3DefaultShapeDef(); + shapeDef.baseMaterial.friction = m_friction; + shapeDef.enableSpeculativeContact = m_speculative; + + switch ( m_bodyType ) + { + case e_box: + { + b3BoxHull box = peel ? b3MakeBoxHull( 1.0f, 1.0f, 1.0f ) : b3MakeBoxHull( 0.4f, 0.2f, 0.4f ); + m_shapeId = b3CreateHullShape( m_bodyId, &shapeDef, &box.base ); + } + break; + + case e_capsule: + { + b3Capsule capsule = { { 0.0f, 0.0f, -capsuleHalf }, { 0.0f, 0.0f, capsuleHalf }, capsuleRadius }; + m_shapeId = b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } + break; + + case e_uprightCapsule: + { + b3Capsule capsule = { { 0.0f, -capsuleHalf, 0.0f }, { 0.0f, capsuleHalf, 0.0f }, capsuleRadius }; + m_shapeId = b3CreateCapsuleShape( m_bodyId, &shapeDef, &capsule ); + } + break; + + case e_sphere: + { + b3Sphere sphere = { b3Vec3_zero, sphereRadius }; + m_shapeId = b3CreateSphereShape( m_bodyId, &shapeDef, &sphere ); + } + break; + + default: + m_shapeId = b3CreateHullShape( m_bodyId, &shapeDef, peel ? m_peelCylinder : m_cylinder ); + break; + } + + m_runGhostCount = 0; + m_runSteps = 0; + } + + float SegmentAngle( int k ) const + { + b3Vec2 a = m_profile[k]; + b3Vec2 b = m_profile[k + 1]; + return atan2f( b.x - a.x, a.y - b.y ); + } + + // The normal points from the ground to the body. A hull face can be the reference face, so any + // normal within the span of face normals under the body is valid. + bool IsGhost( b3Vec3 normal, float xMin, float xMax ) const + { + float tolerance = 5.0f * B3_PI / 180.0f; + if ( b3AbsFloat( normal.z ) > sinf( tolerance ) ) + { + return true; + } + + float lower = B3_PI; + float upper = -B3_PI; + int segmentCount = (int)m_profile.size() - 1; + for ( int k = 0; k < segmentCount; ++k ) + { + float x0 = b3MinFloat( m_profile[k].x, m_profile[k + 1].x ); + float x1 = b3MaxFloat( m_profile[k].x, m_profile[k + 1].x ); + if ( x1 < xMin || xMax < x0 ) + { + continue; + } + + float angle = SegmentAngle( k ); + lower = b3MinFloat( lower, angle ); + upper = b3MaxFloat( upper, angle ); + } + + float angle = atan2f( normal.y, normal.x ); + return angle < lower - tolerance || upper + tolerance < angle; + } + + void Step() override + { + Sample::Step(); + + b3Pos center = b3Body_GetWorldCenter( m_bodyId ); + bool done = center.x > m_halfLength - 1.0f || center.y < -3.0f; + if ( m_scene == e_internalEdges ) + { + // Run out onto the ground plane, or give up on a body knocked off the side + done = center.x > 100.0f || center.y < -3.0f || m_runSteps > 900; + } + + if ( done ) + { + m_runCount += 1; + Launch(); + center = b3Body_GetWorldCenter( m_bodyId ); + } + + if ( m_didStep ) + { + m_runSteps += 1; + + b3AABB bounds = b3Shape_GetAABB( m_shapeId ); + float xMin = (float)bounds.lowerBound.x - 0.1f; + float xMax = (float)bounds.upperBound.x + 0.1f; + + b3ContactData contacts[8]; + int contactCount = b3Body_GetContactData( m_bodyId, contacts, 8 ); + for ( int i = 0; i < contactCount; ++i ) + { + bool bodyIsA = B3_ID_EQUALS( contacts[i].shapeIdA, m_shapeId ); + b3ShapeId otherId = bodyIsA ? contacts[i].shapeIdB : contacts[i].shapeIdA; + if ( b3Shape_GetType( otherId ) != b3_meshShape ) + { + continue; + } + + for ( int j = 0; j < contacts[i].manifoldCount; ++j ) + { + const b3Manifold* manifold = contacts[i].manifolds + j; + + // Speculative points that never pushed are harmless + float impulse = 0.0f; + for ( int k = 0; k < manifold->pointCount; ++k ) + { + impulse += manifold->points[k].totalNormalImpulse; + } + + if ( manifold->pointCount == 0 || impulse <= 0.0f ) + { + continue; + } + + b3Vec3 normal = bodyIsA ? b3Neg( manifold->normal ) : manifold->normal; + if ( IsGhost( normal, xMin, xMax ) == false ) + { + continue; + } + + m_ghostCount += 1; + m_runGhostCount += 1; + + b3Vec3 anchor = bodyIsA ? manifold->points[0].anchorA : manifold->points[0].anchorB; + m_markers[m_markerIndex] = { center + anchor, normal }; + m_markerIndex = ( m_markerIndex + 1 ) % m_markerCapacity; + m_markerCount = b3MinInt( m_markerCount + 1, m_markerCapacity ); + } + } + } + + for ( int i = 0; i < m_markerCount; ++i ) + { + b3Pos p = m_markers[i].point; + DrawPoint( p, 8.0f, MakeColor( b3_colorRed ) ); + DrawLine( p, p + 0.5f * m_markers[i].normal, MakeColor( b3_colorRed ) ); + } + + b3Vec3 velocity = b3Body_GetLinearVelocity( m_bodyId ); + DrawTextLine( "ghost manifolds: %d this run, %d total over %d runs", m_runGhostCount, m_ghostCount, m_runCount + 1 ); + DrawTextLine( "speed: %.2f m/s, vertical velocity: %.2f m/s", b3Length( velocity ), velocity.y ); + } + + bool DrawControls() override + { + const char* sceneNames[] = { "Flat", "Concave Ramp", "Cliff", "Crest", "Bumps", "T-Junction", "Shape Seam", + "PEEL Internal Edges" }; + static_assert( IM_ARRAYSIZE( sceneNames ) == e_sceneCount ); + const char* bodyNames[] = { "Box", "Capsule", "Upright Capsule", "Sphere", "Cylinder" }; + static_assert( IM_ARRAYSIZE( bodyNames ) == e_bodyTypeCount ); + const char* presetNames[] = { "4 x 0.1, start -55", "4 x 0.1, start -54", "4 x 0.01, start -55", + "16 x 0.01, start -54" }; + static_assert( IM_ARRAYSIZE( presetNames ) == IM_ARRAYSIZE( m_peelPresets ) ); + + bool rebuild = false; + bool relaunch = false; + + int scene = (int)m_scene; + if ( ImGui::Combo( "Scene", &scene, sceneNames, IM_ARRAYSIZE( sceneNames ) ) ) + { + m_scene = (Scene)scene; + rebuild = true; + + if ( m_scene == e_internalEdges ) + { + m_camera->SetView( 60.0f, 20.0f, 160.0f, { 0.0f, 30.0f, 0.0f } ); + } + else + { + m_camera->SetView( 90.0f, 20.0f, 30.0f, { 0.0f, 1.0f, 0.0f } ); + } + } + + if ( m_scene == e_internalEdges ) + { + rebuild |= ImGui::Combo( "Preset", &m_peelPreset, presetNames, IM_ARRAYSIZE( presetNames ) ); + } + + int bodyType = (int)m_bodyType; + if ( ImGui::Combo( "Body", &bodyType, bodyNames, IM_ARRAYSIZE( bodyNames ) ) ) + { + m_bodyType = (BodyType)bodyType; + relaunch = true; + } + + rebuild |= ImGui::Checkbox( "Mirror Mesh", &m_mirror ); + rebuild |= ImGui::SliderFloat( "Cell Size", &m_cellSize, 0.1f, 1.0f, "%.2f m" ); + relaunch |= ImGui::SliderFloat( "Speed", &m_speed, 0.0f, 15.0f, "%.1f m/s" ); + relaunch |= ImGui::SliderFloat( "Yaw", &m_yaw, 0.0f, 45.0f, "%.0f deg" ); + relaunch |= ImGui::SliderFloat( "Friction", &m_friction, 0.0f, 1.0f, "%.2f" ); + relaunch |= ImGui::Checkbox( "Fixed Rotation", &m_fixedRotation ); + relaunch |= ImGui::Checkbox( "Speculative", &m_speculative ); + relaunch |= ImGui::Button( "Launch" ); + + if ( ImGui::Button( "Reset Counters" ) ) + { + m_ghostCount = 0; + m_runGhostCount = 0; + m_runCount = 0; + m_markerCount = 0; + m_markerIndex = 0; + } + + if ( rebuild ) + { + CreateGround(); + m_markerCount = 0; + m_markerIndex = 0; + } + + if ( rebuild || relaunch ) + { + Launch(); + } + + return true; + } + + static Sample* Create( SampleContext* context ) + { + return new GhostCollisions( context ); + } + + struct Marker + { + b3Pos point; + b3Vec3 normal; + }; + + b3MeshData* m_meshes[2] = {}; + int m_meshCount = 0; + std::vector m_profile; + b3HullData* m_cylinder; + b3HullData* m_peelCylinder; + b3BodyId m_groundId; + b3BodyId m_bodyId; + b3ShapeId m_shapeId; + + Scene m_scene = e_flat; + BodyType m_bodyType = e_box; + bool m_mirror = false; + float m_cellSize = 0.25f; + float m_speed = 6.0f; + float m_yaw = 0.0f; + float m_friction = 0.0f; + bool m_fixedRotation = false; + bool m_speculative = true; + int m_peelPreset = 0; + int m_runSteps = 0; + + int m_ghostCount = 0; + int m_runGhostCount = 0; + int m_runCount = 0; + Marker m_markers[m_markerCapacity]; + int m_markerCount = 0; + int m_markerIndex = 0; +}; + +static int sampleGhostCollisions = RegisterSample( "Mesh", "Ghost Collisions", GhostCollisions::Create );