improve mesh drop soak

This commit is contained in:
Erin Catto 2026-10-31 10:12:52 -07:00
commit 4a1bb35160
7 changed files with 921 additions and 368 deletions

View file

@ -34,7 +34,7 @@ if (NOT BUILD_SHARED_LIBS)
endif()
target_include_directories(mesh_soak PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../src)
target_link_libraries(mesh_soak PRIVATE box3d)
target_link_libraries(mesh_soak PRIVATE box3d shared)
endif()
# Headless Ghost Collisions sample. Counts ghost manifolds per scene and body.

View file

@ -3,34 +3,30 @@
// 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.
// or the pile is still awake at the step limit. Tunnels are rare, so the soak also counts bodies that
// sink into the wave past a few depth levels and can compare those counts against a baseline.
// Generations run in parallel, one single threaded world per thread. The printed seed reproduces a
// generation in the sample.
#define _CRT_SECURE_NO_WARNINGS
#include "core.h"
#include "mesh_drop.h"
#include "box3d/box3d.h"
#include "box3d/collision.h"
#include "box3d/math_functions.h"
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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" };
#define MAX_BASELINE_ROWS 64
#define BASELINE_ROW_SIZE 512
typedef enum FailureKind
{
@ -41,96 +37,51 @@ typedef enum FailureKind
typedef struct Failure
{
FailureKind kind;
ShapeType shapeType;
MeshDropShape shape;
int generation;
uint32_t seed;
int step;
int index1;
int index2;
int index;
b3Pos position;
} Failure;
typedef struct ShapeStats
{
int generationCount;
int tunnelCount;
int awakeCount;
int depthCounts[MESH_DROP_DEPTH_LEVEL_COUNT];
float maxDepth;
uint32_t maxSeed;
int maxGeneration;
int maxIndex;
int maxStep;
} ShapeStats;
typedef struct Soak
{
b3Mutex* mutex;
b3MeshData* groundMesh;
b3HullData* cylinder;
MeshDropSettings settings;
uint32_t baseSeed;
int generationCount;
int nextGeneration;
int shapeType;
// -1 rotates through the shapes
int shapeFilter;
bool fixedSeed;
int completedCount;
int failureCount;
int tunnelCount;
int awakeCount;
long long totalSteps;
int maxSteps;
ShapeStats stats[e_meshDropShapeCount];
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 );
@ -139,24 +90,18 @@ static void RecordFailure( Soak* soak, const Failure* failure )
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 );
g_meshDropShapeNames[failure->shape], failure->seed, failure->step, failure->index / MESH_DROP_GRID_COUNT,
failure->index % MESH_DROP_GRID_COUNT, (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 )
// Mirrors MeshDrop::Generate and the auto generate step loop. Returns the step count.
static int RunGeneration( Soak* soak, int generation, uint32_t seed, MeshDropShape shape, b3BodyId* bodies,
MeshDropDepth* depth, int* failureKind )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.workerCount = 1;
@ -166,74 +111,34 @@ static int RunGeneration( Soak* soak, int generation, uint32_t seed, ShapeType s
b3WorldId worldId = b3CreateWorld( &worldDef );
b3UnlockMutex( soak->mutex );
CreateGround( worldId, soak->groundMesh );
CreateMeshDropGround( 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;
}
}
MeshDropSettings settings = soak->settings;
settings.shape = shape;
CreateMeshDropBodies( worldId, settings, seed, soak->cylinder, bodies );
ResetMeshDropDepth( depth, settings, soak->cylinder );
float timeStep = 1.0f / 60.0f;
int subStepCount = 4;
int maxSteps = shapeType == e_capsule ? 3000 : 1000;
int maxSteps = GetMeshDropStepLimit( shape );
float tunnelHeight = GetMeshDropTunnelHeight();
int step = 0;
bool failed = false;
while ( failed == false )
{
b3World_Step( worldId, timeStep, subStepCount );
UpdateMeshDropDepth( worldId, depth );
step += 1;
for ( int i = 0; i < BODY_COUNT; ++i )
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
b3Pos center = b3Body_GetWorldCenter( bodies[i] );
if ( center.y < -2.0f )
if ( center.y < tunnelHeight )
{
Failure failure = { e_tunnel, shapeType, generation, seed, step, i / GRID_COUNT, i % GRID_COUNT, center };
Failure failure = { e_tunnel, shape, generation, seed, step, i, center };
RecordFailure( soak, &failure );
*failureKind = e_tunnel;
failed = true;
break;
}
@ -247,7 +152,7 @@ static int RunGeneration( Soak* soak, int generation, uint32_t seed, ShapeType s
if ( failed == false && step > maxSteps )
{
int awakeIndex = 0;
for ( int i = 0; i < BODY_COUNT; ++i )
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
if ( b3Body_IsAwake( bodies[i] ) )
{
@ -257,8 +162,9 @@ static int RunGeneration( Soak* soak, int generation, uint32_t seed, ShapeType s
}
b3Pos center = b3Body_GetWorldCenter( bodies[awakeIndex] );
Failure failure = { e_awake, shapeType, generation, seed, step, awakeIndex / GRID_COUNT, awakeIndex % GRID_COUNT, center };
Failure failure = { e_awake, shape, generation, seed, step, awakeIndex, center };
RecordFailure( soak, &failure );
*failureKind = e_awake;
failed = true;
}
}
@ -273,7 +179,8 @@ static int RunGeneration( Soak* soak, int generation, uint32_t seed, ShapeType s
static void SoakWorker( void* context )
{
Soak* soak = context;
b3BodyId* bodies = malloc( BODY_COUNT * sizeof( b3BodyId ) );
b3BodyId* bodies = malloc( MESH_DROP_BODY_COUNT * sizeof( b3BodyId ) );
MeshDropDepth* depth = malloc( sizeof( MeshDropDepth ) );
while ( true )
{
@ -287,28 +194,247 @@ static void SoakWorker( void* context )
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 );
uint32_t seed = soak->fixedSeed ? soak->baseSeed : GetMeshDropSeed( soak->baseSeed, generation );
MeshDropShape shape =
soak->shapeFilter >= 0 ? (MeshDropShape)soak->shapeFilter : (MeshDropShape)( generation % e_meshDropShapeCount );
int steps = RunGeneration( soak, generation, seed, shapeType, bodies );
int failureKind = -1;
int steps = RunGeneration( soak, generation, seed, shape, bodies, depth, &failureKind );
int depthCounts[MESH_DROP_DEPTH_LEVEL_COUNT];
GetMeshDropDepthCounts( depth, depthCounts );
b3LockMutex( soak->mutex );
soak->completedCount += 1;
soak->totalSteps += steps;
soak->maxSteps = b3MaxInt( soak->maxSteps, steps );
ShapeStats* stats = soak->stats + shape;
stats->generationCount += 1;
stats->tunnelCount += failureKind == e_tunnel ? 1 : 0;
stats->awakeCount += failureKind == e_awake ? 1 : 0;
for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
stats->depthCounts[i] += depthCounts[i];
}
// Ties go to the earlier generation so the report does not depend on thread timing
if ( depth->maxDepth > stats->maxDepth ||
( depth->maxDepth == stats->maxDepth && generation < stats->maxGeneration ) )
{
stats->maxDepth = depth->maxDepth;
stats->maxSeed = seed;
stats->maxGeneration = generation;
stats->maxIndex = depth->maxIndex;
stats->maxStep = depth->maxStep;
}
int completed = soak->completedCount;
b3UnlockMutex( soak->mutex );
if ( completed % 100 == 0 )
if ( completed % b3MaxInt( 100, soak->generationCount / 10 ) == 0 )
{
printf( "%d generations, %d bodies\n", completed, completed * BODY_COUNT );
printf( "%d generations, %d bodies\n", completed, completed * MESH_DROP_BODY_COUNT );
fflush( stdout );
}
}
free( depth );
free( bodies );
}
static const char* GetFilterName( int shapeFilter )
{
return shapeFilter >= 0 ? g_meshDropShapeNames[shapeFilter] : "all";
}
// A baseline row starts with the run that made it, so one file can hold several runs
static void GetBaselineKey( const Soak* soak, char* key, int size )
{
snprintf( key, size, "%s,%u,%d,", GetFilterName( soak->shapeFilter ), soak->baseSeed, soak->generationCount );
}
// Replaces the rows of this run and keeps the rest
static void WriteBaseline( const Soak* soak, const char* path )
{
char key[64];
GetBaselineKey( soak, key, sizeof( key ) );
size_t keyLength = strlen( key );
char* rows = malloc( MAX_BASELINE_ROWS * BASELINE_ROW_SIZE );
int rowCount = 0;
FILE* file = fopen( path, "r" );
if ( file != NULL )
{
char line[BASELINE_ROW_SIZE];
bool header = true;
while ( fgets( line, sizeof( line ), file ) != NULL )
{
if ( header == false && strncmp( line, key, keyLength ) != 0 && rowCount < MAX_BASELINE_ROWS )
{
snprintf( rows + rowCount * BASELINE_ROW_SIZE, BASELINE_ROW_SIZE, "%s", line );
rowCount += 1;
}
header = false;
}
fclose( file );
}
file = fopen( path, "w" );
if ( file == NULL )
{
printf( "cannot write %s\n", path );
free( rows );
return;
}
fprintf( file, "filter,base,generations,shape,tunnels,awake" );
for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
fprintf( file, ",depth%g", g_meshDropDepthLevels[i] );
}
fprintf( file, "\n" );
for ( int i = 0; i < rowCount; ++i )
{
fputs( rows + i * BASELINE_ROW_SIZE, file );
}
free( rows );
for ( int shape = 0; shape < e_meshDropShapeCount; ++shape )
{
const ShapeStats* stats = soak->stats + shape;
if ( stats->generationCount == 0 )
{
continue;
}
fprintf( file, "%s,%u,%d,%s,%d,%d", GetFilterName( soak->shapeFilter ), soak->baseSeed, soak->generationCount,
g_meshDropShapeNames[shape], stats->tunnelCount, stats->awakeCount );
for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
fprintf( file, ",%d", stats->depthCounts[i] );
}
fprintf( file, "\n" );
}
fclose( file );
printf( "wrote %s\n", path );
}
// Returns 0 when no count grew past its noise band, 1 when one did, 2 when the baseline has no rows for this run
static int CompareBaseline( const Soak* soak, const char* path )
{
FILE* file = fopen( path, "r" );
if ( file == NULL )
{
printf( "cannot read %s\n", path );
return 2;
}
char line[512];
if ( fgets( line, sizeof( line ), file ) == NULL )
{
fclose( file );
printf( "empty baseline %s\n", path );
return 2;
}
int result = 0;
int changedCount = 0;
int matchedCount = 0;
while ( fgets( line, sizeof( line ), file ) != NULL )
{
char filter[32];
char shapeName[32];
unsigned int base;
int generations;
int counts[2 + MESH_DROP_DEPTH_LEVEL_COUNT];
_Static_assert( MESH_DROP_DEPTH_LEVEL_COUNT == 4, "update the baseline row format" );
int fieldCount = sscanf( line, "%31[^,],%u,%d,%31[^,],%d,%d,%d,%d,%d,%d", filter, &base, &generations, shapeName,
counts + 0, counts + 1, counts + 2, counts + 3, counts + 4, counts + 5 );
if ( fieldCount != 10 )
{
continue;
}
if ( strcmp( filter, GetFilterName( soak->shapeFilter ) ) != 0 || base != soak->baseSeed ||
generations != soak->generationCount )
{
continue;
}
int shape = -1;
for ( int i = 0; i < e_meshDropShapeCount; ++i )
{
if ( strcmp( shapeName, g_meshDropShapeNames[i] ) == 0 )
{
shape = i;
}
}
if ( shape < 0 )
{
continue;
}
matchedCount += 1;
const ShapeStats* stats = soak->stats + shape;
int current[2 + MESH_DROP_DEPTH_LEVEL_COUNT] = { stats->tunnelCount, stats->awakeCount };
for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
current[2 + i] = stats->depthCounts[i];
}
for ( int i = 0; i < 2 + MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
if ( current[i] == counts[i] )
{
continue;
}
// Any collision change reshuffles the chaotic pile, so a count moves by about its square root
// even when nothing got worse. Flag growth past three of those. A count that was zero flags on any
// growth, since a good build never sinks that deep.
float band = 3.0f * sqrtf( (float)counts[i] );
bool regressed = i < 2 ? current[i] > counts[i] : current[i] > counts[i] + band;
char column[32];
if ( i < 2 )
{
snprintf( column, sizeof( column ), i == 0 ? "tunnels" : "awake" );
}
else
{
snprintf( column, sizeof( column ), "> %g slop", g_meshDropDepthLevels[i - 2] );
}
printf( " %-9s %-11s %d>%d%s\n", shapeName, column, counts[i], current[i], regressed ? " GREW" : "" );
changedCount += 1;
result = regressed ? 1 : result;
}
}
fclose( file );
if ( matchedCount == 0 )
{
printf( "%s has no rows for -s=%s -b=%u -g=%d\n", path, GetFilterName( soak->shapeFilter ), soak->baseSeed,
soak->generationCount );
return 2;
}
printf( "compared with %s: %d changed, %s\n", path, changedCount, result == 0 ? "none grew past noise" : "GREW" );
return result;
}
static const char* MatchValue( const char* arg, const char* shortName, const char* longName )
{
size_t shortLength = strlen( shortName );
@ -330,10 +456,12 @@ int main( int argc, char** argv )
{
int generationCount = 1000;
int threadCount = 8;
int shapeType = e_box;
int shapeFilter = e_meshDropBox;
uint32_t seed = (uint32_t)b3GetTicks();
bool fixedSeed = false;
float amplitude = 0.5f;
const char* writePath = NULL;
const char* comparePath = NULL;
MeshDropSettings settings = GetDefaultMeshDropSettings();
for ( int i = 1; i < argc; ++i )
{
@ -350,21 +478,21 @@ int main( int argc, char** argv )
}
else if ( ( value = MatchValue( arg, "-s=", "--shape=" ) ) != NULL )
{
shapeType = -2;
for ( int k = 0; k < e_shapeCount; ++k )
shapeFilter = -2;
for ( int k = 0; k < e_meshDropShapeCount; ++k )
{
if ( strcmp( value, s_shapeNames[k] ) == 0 )
if ( strcmp( value, g_meshDropShapeNames[k] ) == 0 )
{
shapeType = k;
shapeFilter = k;
}
}
if ( strcmp( value, "all" ) == 0 )
{
shapeType = -1;
shapeFilter = -1;
}
if ( shapeType == -2 )
if ( shapeFilter == -2 )
{
printf( "unknown shape: %s\n", value );
return 2;
@ -381,37 +509,61 @@ int main( int argc, char** argv )
}
else if ( ( value = MatchValue( arg, "-a=", "--amplitude=" ) ) != NULL )
{
amplitude = (float)atof( value );
settings.amplitude = (float)atof( value );
}
else if ( ( value = MatchValue( arg, "-w=", "--write=" ) ) != NULL )
{
writePath = value;
}
else if ( ( value = MatchValue( arg, "-c=", "--compare=" ) ) != NULL )
{
comparePath = 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"
"Counts bodies that sink into the wave deeper than each depth level.\n"
" -g, --generations=<int> generation count (default 1000)\n"
" -t, --threads=<int> worker threads, one world each (default 8)\n"
" -s, --shape=<name> box, capsule, cylinder, sphere or all (default box)\n"
" -b, --base-seed=<uint> base seed, each generation hashes its own seed from it\n"
" -b, --base-seed=<uint> base seed, each generation hashes its own seed from it (default random)\n"
" --seed=<uint> run every generation with this exact seed (replay)\n"
" -a, --amplitude=<float> wave amplitude (default 0.5)\n"
"Exit code is 0 when every generation passes, 1 otherwise.\n",
BODY_COUNT );
" -w, --write=<csv> write the counts as a baseline, replacing only the rows of this run\n"
" -c, --compare=<csv> compare the counts with the baseline rows from the same -s, -b and -g\n"
"Exit code is 0 when every generation passes and no count grew past noise, 1 otherwise,\n"
"2 for bad arguments or a baseline from a different run.\n",
MESH_DROP_BODY_COUNT );
return 2;
}
}
if ( fixedSeed && ( writePath != NULL || comparePath != NULL ) )
{
printf( "a baseline needs a base seed, not --seed\n" );
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.settings = settings;
soak.groundMesh = CreateMeshDropMesh( settings.amplitude );
soak.cylinder = CreateMeshDropCylinder();
soak.baseSeed = seed;
soak.fixedSeed = fixedSeed;
soak.generationCount = generationCount;
soak.shapeType = shapeType;
soak.shapeFilter = shapeFilter;
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 );
for ( int i = 0; i < e_meshDropShapeCount; ++i )
{
soak.stats[i].maxDepth = -FLT_MAX;
soak.stats[i].maxGeneration = INT32_MAX;
}
printf( "mesh soak: %d generations, %d threads, shape %s, %s seed %u\n", generationCount, threadCount,
GetFilterName( shapeFilter ), fixedSeed ? "fixed" : "base", seed );
fflush( stdout );
uint64_t ticks = b3GetTicks();
@ -429,24 +581,71 @@ int main( int argc, char** argv )
float seconds = 0.001f * b3GetMilliseconds( ticks );
double averageSteps = soak.completedCount > 0 ? (double)soak.totalSteps / soak.completedCount : 0.0;
float slop = B3_LINEAR_SLOP;
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 );
printf( "\n%-9s %8s %8s %6s", "shape", "bodies", "tunnels", "awake" );
for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
char label[32];
snprintf( label, sizeof( label ), "> %g slop", g_meshDropDepthLevels[i] );
printf( " %10s", label );
}
printf( " deepest\n" );
for ( int shape = 0; shape < e_meshDropShapeCount; ++shape )
{
const ShapeStats* stats = soak.stats + shape;
if ( stats->generationCount == 0 )
{
continue;
}
printf( "%-9s %8d %8d %6d", g_meshDropShapeNames[shape], stats->generationCount * MESH_DROP_BODY_COUNT,
stats->tunnelCount, stats->awakeCount );
for ( int i = 0; i < MESH_DROP_DEPTH_LEVEL_COUNT; ++i )
{
printf( " %10d", stats->depthCounts[i] );
}
if ( stats->maxIndex >= 0 )
{
printf( " %.1f slop, seed %u body (%d, %d) step %d\n", stats->maxDepth / slop, stats->maxSeed,
stats->maxIndex / MESH_DROP_GRID_COUNT, stats->maxIndex % MESH_DROP_GRID_COUNT, stats->maxStep );
}
else
{
printf( "\n" );
}
}
printf( "\nsteps 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( " %s %s seed %u body (%d, %d)\n", f->kind == e_tunnel ? "tunnel" : "awake", g_meshDropShapeNames[f->shape],
f->seed, f->index / MESH_DROP_GRID_COUNT, f->index % MESH_DROP_GRID_COUNT );
}
printf( soak.failureCount == 0 ? "PASS\n" : "FAIL\n" );
int exitCode = soak.failureCount == 0 ? 0 : 1;
if ( writePath != NULL )
{
WriteBaseline( &soak, writePath );
}
if ( comparePath != NULL )
{
int compareResult = CompareBaseline( &soak, comparePath );
exitCode = b3MaxInt( exitCode, compareResult );
}
printf( exitCode == 0 ? "PASS\n" : "FAIL\n" );
b3DestroyHull( soak.cylinder );
b3DestroyMesh( soak.groundMesh );
b3DestroyMutex( soak.mutex );
return soak.failureCount == 0 ? 0 : 1;
return exitCode;
}

View file

@ -0,0 +1,9 @@
filter,base,generations,shape,tunnels,awake,depth4,depth8,depth16,depth32
all,12345,1000,box,0,0,1386,213,2,0
all,12345,1000,capsule,0,0,14474,3477,28,0
all,12345,1000,cylinder,0,0,10741,2305,35,0
all,12345,1000,sphere,0,0,56,0,0,0
all,12345,16000,box,0,0,21423,3126,42,0
all,12345,16000,capsule,0,0,231138,54408,513,0
all,12345,16000,cylinder,0,0,172961,36766,453,0
all,12345,16000,sphere,0,0,989,0,0,0
1 filter base generations shape tunnels awake depth4 depth8 depth16 depth32
2 all 12345 1000 box 0 0 1386 213 2 0
3 all 12345 1000 capsule 0 0 14474 3477 28 0
4 all 12345 1000 cylinder 0 0 10741 2305 35 0
5 all 12345 1000 sphere 0 0 56 0 0 0
6 all 12345 16000 box 0 0 21423 3126 42 0
7 all 12345 16000 capsule 0 0 231138 54408 513 0
8 all 12345 16000 cylinder 0 0 172961 36766 453 0
9 all 12345 16000 sphere 0 0 989 0 0 0

View file

@ -4,6 +4,7 @@
#include "gfx/debug_adapter.h"
#include "gfx/draw.h"
#include "imgui.h"
#include "mesh_drop.h"
#include "sample.h"
#include "utils.h"
@ -387,38 +388,9 @@ public:
static int sampleNeedleMesh = RegisterSample( "Continuous", "Needle Mesh", NeedleMesh::Create );
struct IndexPair
{
int index1;
int index2;
};
static inline IndexPair ConvertToPair( void* userData )
{
static_assert( sizeof( intptr_t ) >= 8 && sizeof( int ) == 4 );
intptr_t value = (intptr_t)userData;
int index1 = (int)value;
int index2 = (int)( value >> 32 );
return { index1, index2 };
}
static inline void* ConvertToUserData( IndexPair pair )
{
intptr_t value = (intptr_t)pair.index2 << 32 | (intptr_t)pair.index1;
return (void*)value;
}
class MeshDrop : public Sample
{
public:
enum ShapeType
{
e_box,
e_capsule,
e_cylinder,
e_sphere,
};
explicit MeshDrop( SampleContext* context )
: Sample( context )
{
@ -428,20 +400,21 @@ public:
GetGuiDraw()->forceScale = 0.1f;
}
m_settings = GetDefaultMeshDropSettings();
m_groundId = b3_nullBodyId;
m_groundMesh = nullptr;
m_groundAmplitude = 0.5f;
CreateGround();
m_bodies = new b3BodyId[m_bodyCount];
memset( m_bodies, 0, m_bodyCount * sizeof( b3BodyId ) );
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
m_bodies[i] = b3_nullBodyId;
}
m_cylinder = b3CreateCylinder( 0.4f, 0.05f, 0.0f, 6 );
m_shapeType = e_box;
m_cylinder = CreateMeshDropCylinder();
m_seed = 0;
m_runCount = 0;
m_failure = false;
m_autoGenerate = false;
m_collide = false;
m_stepWhilePaused = true;
Generate();
@ -449,7 +422,6 @@ public:
~MeshDrop() override
{
delete[] m_bodies;
b3DestroyHull( m_cylinder );
b3DestroyMesh( m_groundMesh );
}
@ -468,58 +440,13 @@ public:
m_groundMesh = nullptr;
}
b3BodyDef bodyDef = b3DefaultBodyDef();
m_groundId = b3CreateBody( m_worldId, &bodyDef );
int gridCount = 40;
float cellWidth = 1.0f;
float rowHz = 0.1f;
float columnHz = 0.2f;
m_groundMesh = b3CreateWaveMesh( gridCount, gridCount, cellWidth, m_groundAmplitude, rowHz, columnHz );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.filter.categoryBits = 1;
b3CreateMeshShape( m_groundId, &shapeDef, m_groundMesh, b3Vec3_one );
float extent = 0.5f * gridCount * cellWidth;
float halfHeight = 1.0f;
{
b3Transform transform;
transform.p = { 0.0f, halfHeight, -extent };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( extent, halfHeight, 0.1f, transform );
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
{
b3Transform transform;
transform.p = { 0.0f, halfHeight, extent };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( extent, halfHeight, 0.1f, transform );
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
{
b3Transform transform;
transform.p = { -extent, halfHeight, 0.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, halfHeight, extent, transform );
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
{
b3Transform transform;
transform.p = { extent, halfHeight, 0.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, halfHeight, extent, transform );
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
m_groundMesh = CreateMeshDropMesh( m_settings.amplitude );
m_groundId = CreateMeshDropGround( m_worldId, m_groundMesh );
}
void Generate()
{
for ( int i = 0; i < m_bodyCount; ++i )
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
if ( B3_IS_NULL( m_bodies[i] ) )
{
@ -530,117 +457,53 @@ public:
m_bodies[i] = b3_nullBodyId;
}
// The soft contact solver cannot always resolve this small shape at 4 sub-steps.
// Also this small shape has trouble moving advancing in the time of impact code
// because the size is very close to the tolerances used.
// b3BoxHull box = b3MakeBoxHull( 0.01f, 0.1f, 0.02f );
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 };
int bodyIndex = 0;
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3ShapeDef shapeDef = b3DefaultShapeDef();
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.
if ( m_collide == false )
{
shapeDef.filter.categoryBits = 2;
shapeDef.filter.maskBits = 1;
}
// 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 = false;
g_randomSeed = 2256131175;
m_seed = m_replaySeed != 0 ? m_replaySeed : (uint32_t)b3GetTicks();
m_runCount += 1;
m_stepCount = 0;
printf( "run %d seed %u\n", m_runCount, g_randomSeed );
printf( "run %d seed %u\n", m_runCount, m_seed );
for ( int i = 0; i < m_gridCount; ++i )
MeshDropSettings settings = m_settings;
if ( m_solo[0] >= 0 && m_solo[1] >= 0 )
{
for ( int j = 0; j < m_gridCount; ++j )
{
b3Vec3 linearVelocity = RandomVec3Uniform( -1.0f, 1.0f );
b3Vec3 angularVelocity = RandomVec3Uniform( -5.0f, 5.0f );
if ( simulateAll || ( i == 31 && j == 20 ) )
{
bodyDef.position = { 0.5f * ( i - 0.5f * m_gridCount ), 5.0f, 0.5f * ( j - 0.5f * m_gridCount ) };
bodyDef.linearVelocity = linearVelocity;
bodyDef.angularVelocity = angularVelocity;
// bodyDef.angularDamping = 0.1f;
bodyDef.userData = ConvertToUserData( { i, j } );
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
if ( m_shapeType == e_box )
{
b3CreateHullShape( bodyId, &shapeDef, &box.base );
}
else if ( m_shapeType == e_capsule )
{
b3CreateCapsuleShape( bodyId, &shapeDef, &capsule );
}
else if ( m_shapeType == e_cylinder )
{
b3CreateHullShape( bodyId, &shapeDef, m_cylinder );
}
else
{
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
}
m_bodies[bodyIndex] = bodyId;
}
else
{
m_bodies[bodyIndex] = b3_nullBodyId;
}
bodyIndex += 1;
}
settings.soloIndex = MESH_DROP_GRID_COUNT * m_solo[0] + m_solo[1];
}
assert( bodyIndex == m_bodyCount );
CreateMeshDropBodies( m_worldId, settings, m_seed, m_cylinder, m_bodies );
ResetMeshDropDepth( &m_depth, settings, m_cylinder );
}
bool DrawControls() override
{
const char* shapeTypes[] = { "box", "capsule", "cylinder", "sphere" };
int shapeType = (int)m_shapeType;
if ( ImGui::Combo( "Type", &shapeType, shapeTypes, IM_ARRAYSIZE( shapeTypes ) ) )
int shapeType = (int)m_settings.shape;
if ( ImGui::Combo( "Type", &shapeType, g_meshDropShapeNames, e_meshDropShapeCount ) )
{
m_stepCount = 0;
m_shapeType = ShapeType( shapeType );
m_settings.shape = MeshDropShape( shapeType );
Generate();
}
if ( ImGui::SliderFloat( "Amplitude", &m_groundAmplitude, 0.0f, 1.0f ) )
if ( ImGui::SliderFloat( "Amplitude", &m_settings.amplitude, 0.0f, 1.0f ) )
{
CreateGround();
Generate();
}
if ( ImGui::Checkbox( "Collide", &m_collide ) )
if ( ImGui::Checkbox( "Collide", &m_settings.collide ) )
{
Generate();
}
ImGui::InputScalar( "Seed", ImGuiDataType_U32, &m_replaySeed );
// Drop only the body at these indices, -1 for all
if ( ImGui::InputInt2( "Solo", m_solo ) )
{
m_solo[0] = b3ClampInt( m_solo[0], -1, MESH_DROP_GRID_COUNT - 1 );
m_solo[1] = b3ClampInt( m_solo[1], -1, MESH_DROP_GRID_COUNT - 1 );
}
if ( ImGui::Button( "Generate" ) )
{
Generate();
@ -657,8 +520,14 @@ public:
void Step() override
{
int stepCount = m_stepCount;
Sample::Step();
if ( m_stepCount != stepCount )
{
UpdateMeshDropDepth( m_worldId, &m_depth );
}
{
PickRay pickRay = m_camera->BuildPickRay( m_context->mouseX, m_context->mouseY );
@ -667,13 +536,25 @@ public:
if ( result.hit )
{
b3BodyId bodyId = b3Shape_GetBody( result.shapeId );
void* userData = b3Body_GetUserData( bodyId );
IndexPair pair = ConvertToPair( userData );
DrawTextLine( "indices: (%d, %d)\n", pair.index1, pair.index2 );
int index = GetMeshDropBodyIndex( b3Body_GetUserData( bodyId ) );
if ( index >= 0 )
{
DrawTextLine( "indices: (%d, %d)", index / MESH_DROP_GRID_COUNT, index % MESH_DROP_GRID_COUNT );
}
}
}
for ( int i = 0; i < m_bodyCount && m_failure == false; i += 1 )
DrawTextLine( "seed %u", m_seed );
if ( m_depth.maxIndex >= 0 )
{
int index = m_depth.maxIndex;
DrawTextLine( "deepest: (%d, %d) %.1f slop at step %d", index / MESH_DROP_GRID_COUNT, index % MESH_DROP_GRID_COUNT,
m_depth.maxDepth / B3_LINEAR_SLOP, m_depth.maxStep );
}
float tunnelHeight = GetMeshDropTunnelHeight();
for ( int i = 0; i < MESH_DROP_BODY_COUNT && m_failure == false; i += 1 )
{
b3BodyId bodyId = m_bodies[i];
if ( B3_IS_NULL( bodyId ) )
@ -682,19 +563,14 @@ public:
}
b3Pos massCenter = b3Body_GetWorldCenter( bodyId );
if ( massCenter.y < -2.0f )
if ( massCenter.y < tunnelHeight )
{
IndexPair pair = ConvertToPair( b3Body_GetUserData( bodyId ) );
printf( "index1: %d - index2: %d\n", pair.index1, pair.index2 );
printf( "index1: %d - index2: %d\n", i / MESH_DROP_GRID_COUNT, i % MESH_DROP_GRID_COUNT );
printf( "(%6.2f, %6.2f, %6.2f)\n", massCenter.x, massCenter.y, massCenter.z );
m_context->pause = true;
m_failure = true;
m_autoGenerate = false;
}
// This is for debugging the fallback inner sphere
// b3Sphere sphere = {massCenter, 0.015f};
// DrawSphere( m_scene, b3Transform_identity, sphere, b3_colorLightGray );
}
if ( m_autoGenerate )
@ -719,13 +595,13 @@ public:
for ( int i = 0; i < n; ++i )
{
b3World_Step( m_worldId, timeStep, m_context->subStepCount );
UpdateMeshDropDepth( m_worldId, &m_depth );
}
m_stepCount += n;
}
int maxSteps = m_shapeType == e_capsule ? 3000 : 1000;
if ( m_stepCount > maxSteps )
if ( m_stepCount > GetMeshDropStepLimit( m_settings.shape ) )
{
m_context->pause = true;
m_failure = true;
@ -739,21 +615,18 @@ public:
return new MeshDrop( context );
}
static constexpr int m_gridCount = 32;
// static constexpr int m_gridCount = 3;
static constexpr int m_bodyCount = m_gridCount * m_gridCount;
MeshDropSettings m_settings;
MeshDropDepth m_depth;
b3MeshData* m_groundMesh;
float m_groundAmplitude;
b3BodyId m_groundId;
b3HullData* m_cylinder;
b3BodyId* m_bodies;
ShapeType m_shapeType;
b3BodyId m_bodies[MESH_DROP_BODY_COUNT];
uint32_t m_seed;
int m_runCount;
bool m_failure;
bool m_autoGenerate;
bool m_collide;
uint32_t m_replaySeed = 0;
int m_solo[2] = { -1, -1 };
};
static int sampleMeshDrop = RegisterSample( "Continuous", "Mesh Drop", MeshDrop::Create );

View file

@ -9,6 +9,8 @@ set(BOX3D_SHARED_FILES
ghost_collisions.h
human.c
human.h
mesh_drop.c
mesh_drop.h
overflow_color.c
overflow_color.h
stability.c

355
shared/mesh_drop.c Normal file
View file

@ -0,0 +1,355 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "mesh_drop.h"
#include "box3d/box3d.h"
#include <float.h>
#include <math.h>
#define WAVE_CELL_WIDTH 1.0f
#define WAVE_ROW_FREQUENCY 0.1f
#define WAVE_COLUMN_FREQUENCY 0.2f
#define DROP_SPACING 0.5f
#define DROP_HEIGHT 5.0f
#define BODY_RADIUS 0.05f
#define CAPSULE_HALF_LENGTH 0.2f
const char* g_meshDropShapeNames[e_meshDropShapeCount] = { "box", "capsule", "cylinder", "sphere" };
const float g_meshDropDepthLevels[MESH_DROP_DEPTH_LEVEL_COUNT] = { 4.0f, 8.0f, 16.0f, 32.0f };
// Same XorShift32 and mapping as the samples, but with local state so worlds can run on many threads
static float RandomFloatRange( uint32_t* state, float lo, float hi )
{
uint32_t x = *state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
*state = x;
int i = (int)( x % 32768 );
float r = (float)( i & 32767 ) / 32767.0f;
return ( hi - lo ) * r + lo;
}
static b3Vec3 RandomVec3Uniform( uint32_t* state, float lo, float hi )
{
b3Vec3 v;
v.x = RandomFloatRange( state, lo, hi );
v.y = RandomFloatRange( state, lo, hi );
v.z = RandomFloatRange( state, 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 b3BoxHull MakeDropBox( void )
{
// The soft contact solver cannot always resolve a smaller box at 4 sub-steps, and its size gets
// close to the time of impact tolerances
return b3MakeBoxHull( 0.02f, 0.2f, 0.04f );
}
MeshDropSettings GetDefaultMeshDropSettings( void )
{
MeshDropSettings settings = {
.shape = e_meshDropBox,
.amplitude = 0.5f,
.collide = false,
.soloIndex = -1,
};
return settings;
}
uint32_t GetMeshDropSeed( uint32_t baseSeed, int generation )
{
return HashSeed( HashSeed( baseSeed ) + (uint32_t)generation );
}
int GetMeshDropStepLimit( MeshDropShape shape )
{
return shape == e_meshDropCapsule ? 3000 : 1000;
}
float GetMeshDropTunnelHeight( void )
{
return -2.0f;
}
b3MeshData* CreateMeshDropMesh( float amplitude )
{
return b3CreateWaveMesh( MESH_DROP_WAVE_COUNT, MESH_DROP_WAVE_COUNT, WAVE_CELL_WIDTH, amplitude, WAVE_ROW_FREQUENCY,
WAVE_COLUMN_FREQUENCY );
}
b3HullData* CreateMeshDropCylinder( void )
{
return b3CreateCylinder( 0.4f, BODY_RADIUS, 0.0f, 6 );
}
b3BodyId CreateMeshDropGround( 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 = 0.5f * MESH_DROP_WAVE_COUNT * WAVE_CELL_WIDTH;
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 );
}
return groundId;
}
void CreateMeshDropBodies( b3WorldId worldId, MeshDropSettings settings, uint32_t seed, const b3HullData* cylinder,
b3BodyId* bodies )
{
b3BoxHull box = MakeDropBox();
b3Capsule capsule = { { 0.0f, -CAPSULE_HALF_LENGTH, 0.0f }, { 0.0f, CAPSULE_HALF_LENGTH, 0.0f }, BODY_RADIUS };
b3Sphere sphere = { b3Vec3_zero, BODY_RADIUS };
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3ShapeDef shapeDef = b3DefaultShapeDef();
bool round = settings.shape == e_meshDropCapsule || settings.shape == e_meshDropSphere;
shapeDef.baseMaterial.rollingResistance = round ? 0.4f : 0.1f;
if ( settings.collide == false )
{
shapeDef.filter.categoryBits = 2;
shapeDef.filter.maskBits = 1;
}
uint32_t state = seed;
int index = 0;
for ( int i = 0; i < MESH_DROP_GRID_COUNT; ++i )
{
for ( int j = 0; j < MESH_DROP_GRID_COUNT; ++j )
{
// Draw for every body so a solo body gets the same velocity it has in the full drop
b3Vec3 linearVelocity = RandomVec3Uniform( &state, -1.0f, 1.0f );
b3Vec3 angularVelocity = RandomVec3Uniform( &state, -5.0f, 5.0f );
if ( settings.soloIndex >= 0 && settings.soloIndex != index )
{
bodies[index] = b3_nullBodyId;
index += 1;
continue;
}
bodyDef.position = (b3Pos){ DROP_SPACING * ( i - 0.5f * MESH_DROP_GRID_COUNT ), DROP_HEIGHT,
DROP_SPACING * ( j - 0.5f * MESH_DROP_GRID_COUNT ) };
bodyDef.linearVelocity = linearVelocity;
bodyDef.angularVelocity = angularVelocity;
bodyDef.userData = (void*)(intptr_t)( index + 1 );
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
switch ( settings.shape )
{
case e_meshDropBox:
b3CreateHullShape( bodyId, &shapeDef, &box.base );
break;
case e_meshDropCapsule:
b3CreateCapsuleShape( bodyId, &shapeDef, &capsule );
break;
case e_meshDropCylinder:
b3CreateHullShape( bodyId, &shapeDef, cylinder );
break;
default:
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
break;
}
bodies[index] = bodyId;
index += 1;
}
}
}
int GetMeshDropBodyIndex( void* userData )
{
intptr_t value = (intptr_t)userData;
return 1 <= value && value <= MESH_DROP_BODY_COUNT ? (int)value - 1 : -1;
}
void ResetMeshDropDepth( MeshDropDepth* depth, MeshDropSettings settings, const b3HullData* cylinder )
{
// Same heights as b3CreateWaveMesh
float omegaZ = 2.0f * B3_PI * WAVE_ROW_FREQUENCY * WAVE_CELL_WIDTH;
float omegaX = 2.0f * B3_PI * WAVE_COLUMN_FREQUENCY * WAVE_CELL_WIDTH;
int index = 0;
for ( int ix = 0; ix <= MESH_DROP_WAVE_COUNT; ++ix )
{
float rowHeight = b3ComputeCosSin( omegaX * ix ).sine;
for ( int iz = 0; iz <= MESH_DROP_WAVE_COUNT; ++iz )
{
float columnHeight = b3ComputeCosSin( omegaZ * iz ).sine;
depth->heights[index++] = settings.amplitude * rowHeight * columnHeight;
}
}
depth->amplitude = fabsf( settings.amplitude );
depth->probeCount = 0;
depth->radius = 0.0f;
switch ( settings.shape )
{
case e_meshDropBox:
case e_meshDropCylinder:
{
b3BoxHull box = MakeDropBox();
const b3HullData* hull = settings.shape == e_meshDropBox ? &box.base : cylinder;
const b3Vec3* points = b3GetHullPoints( hull );
int count = hull->vertexCount < MESH_DROP_MAX_PROBES ? hull->vertexCount : MESH_DROP_MAX_PROBES;
for ( int i = 0; i < count; ++i )
{
depth->probes[i] = points[i];
}
depth->probeCount = count;
}
break;
case e_meshDropCapsule:
depth->probes[0] = (b3Vec3){ 0.0f, -CAPSULE_HALF_LENGTH, 0.0f };
depth->probes[1] = (b3Vec3){ 0.0f, CAPSULE_HALF_LENGTH, 0.0f };
depth->probeCount = 2;
depth->radius = BODY_RADIUS;
break;
default:
depth->probes[0] = b3Vec3_zero;
depth->probeCount = 1;
depth->radius = BODY_RADIUS;
break;
}
float maxLength = 0.0f;
for ( int i = 0; i < depth->probeCount; ++i )
{
maxLength = fmaxf( maxLength, b3Length( depth->probes[i] ) );
}
depth->boundingRadius = maxLength + depth->radius;
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
depth->bodyDepths[i] = -FLT_MAX;
}
depth->maxDepth = -FLT_MAX;
depth->maxIndex = -1;
depth->maxStep = 0;
depth->stepCount = 0;
}
// Signed distance to the plane of the wave triangle under the point. Exact away from the folds, where
// it reads a little deep on a crest and shallow in a valley.
static float GetWaveDistance( const MeshDropDepth* depth, b3Vec3 p )
{
float origin = -0.5f * MESH_DROP_WAVE_COUNT * WAVE_CELL_WIDTH;
float u = ( p.x - origin ) / WAVE_CELL_WIDTH;
float v = ( p.z - origin ) / WAVE_CELL_WIDTH;
int ix = b3ClampInt( (int)floorf( u ), 0, MESH_DROP_WAVE_COUNT - 1 );
int iz = b3ClampInt( (int)floorf( v ), 0, MESH_DROP_WAVE_COUNT - 1 );
int stride = MESH_DROP_WAVE_COUNT + 1;
float ha = depth->heights[ix * stride + iz];
float hb = depth->heights[ix * stride + iz + 1];
float hc = depth->heights[( ix + 1 ) * stride + iz + 1];
float hd = depth->heights[( ix + 1 ) * stride + iz];
// The cell diagonal runs from a to c, matching b3CreateWaveMesh
float w = WAVE_CELL_WIDTH;
b3Vec3 a = { origin + ix * w, ha, origin + iz * w };
b3Vec3 ac = { w, hc - ha, w };
b3Vec3 side = v - iz >= u - ix ? (b3Vec3){ 0.0f, hb - ha, w } : (b3Vec3){ w, hd - ha, 0.0f };
b3Vec3 normal = b3Normalize( b3Cross( side, ac ) );
if ( normal.y < 0.0f )
{
normal = b3Neg( normal );
}
return b3Dot( normal, b3Sub( p, a ) );
}
void UpdateMeshDropDepth( b3WorldId worldId, MeshDropDepth* depth )
{
depth->stepCount += 1;
b3BodyEvents events = b3World_GetBodyEvents( worldId );
for ( int i = 0; i < events.moveCount; ++i )
{
const b3BodyMoveEvent* event = events.moveEvents + i;
int index = GetMeshDropBodyIndex( event->userData );
if ( index < 0 )
{
continue;
}
b3WorldTransform transform = event->transform;
if ( (float)transform.p.y - depth->boundingRadius > depth->amplitude )
{
continue;
}
float sink = -FLT_MAX;
for ( int j = 0; j < depth->probeCount; ++j )
{
b3Pos point = b3TransformWorldPoint( transform, depth->probes[j] );
b3Vec3 p = { (float)point.x, (float)point.y, (float)point.z };
sink = fmaxf( sink, depth->radius - GetWaveDistance( depth, p ) );
}
if ( sink > depth->bodyDepths[index] )
{
depth->bodyDepths[index] = sink;
}
if ( sink > depth->maxDepth )
{
depth->maxDepth = sink;
depth->maxIndex = index;
depth->maxStep = depth->stepCount;
}
}
}
void GetMeshDropDepthCounts( const MeshDropDepth* depth, int counts[MESH_DROP_DEPTH_LEVEL_COUNT] )
{
for ( int level = 0; level < MESH_DROP_DEPTH_LEVEL_COUNT; ++level )
{
float threshold = g_meshDropDepthLevels[level] * B3_LINEAR_SLOP;
int count = 0;
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
count += depth->bodyDepths[i] > threshold ? 1 : 0;
}
counts[level] = count;
}
}

115
shared/mesh_drop.h Normal file
View file

@ -0,0 +1,115 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/collision.h"
#include "box3d/id.h"
#include "box3d/math_functions.h"
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C"
{
#endif
// Mesh Drop scene, shared by the Continuous / Mesh Drop sample and the headless mesh soak. A generation
// drops a grid of small bodies with random velocities on a wave mesh and steps until they sleep. A body
// that falls out of the world tunneled. The depth tracker measures how far each body sinks into the
// wave, which flags contact trouble far more often than tunnels do.
typedef enum MeshDropShape
{
e_meshDropBox,
e_meshDropCapsule,
e_meshDropCylinder,
e_meshDropSphere,
e_meshDropShapeCount
} MeshDropShape;
#define MESH_DROP_GRID_COUNT 32
#define MESH_DROP_BODY_COUNT ( MESH_DROP_GRID_COUNT * MESH_DROP_GRID_COUNT )
#define MESH_DROP_DEPTH_LEVEL_COUNT 4
// Wave mesh cells along x and z
#define MESH_DROP_WAVE_COUNT 40
// Enough for the cylinder hull
#define MESH_DROP_MAX_PROBES 16
extern const char* g_meshDropShapeNames[e_meshDropShapeCount];
// Sink depth thresholds in linear slop
extern const float g_meshDropDepthLevels[MESH_DROP_DEPTH_LEVEL_COUNT];
typedef struct MeshDropSettings
{
MeshDropShape shape;
float amplitude;
// Let the bodies collide with each other. Off isolates mesh collision.
bool collide;
// Create only this grid index, or -1 for all. Without body collision a body moves the same alone.
int soloIndex;
} MeshDropSettings;
MeshDropSettings GetDefaultMeshDropSettings( void );
// Hashes the base before adding the generation, so nearby base seeds share no generations
uint32_t GetMeshDropSeed( uint32_t baseSeed, int generation );
// Steps a generation may take to fall asleep
int GetMeshDropStepLimit( MeshDropShape shape );
// A body below this height tunneled
float GetMeshDropTunnelHeight( void );
b3MeshData* CreateMeshDropMesh( float amplitude );
b3HullData* CreateMeshDropCylinder( void );
// Creates a static body with the wave mesh and four walls
b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh );
// Creates the bodies of one generation in grid order. Bodies left out by the solo index are null. The
// body user data encodes the grid index, see GetMeshDropBodyIndex.
void CreateMeshDropBodies( b3WorldId worldId, MeshDropSettings settings, uint32_t seed, const b3HullData* cylinder,
b3BodyId* bodies );
// Grid index from body user data, or -1 if the body is not part of the drop
int GetMeshDropBodyIndex( void* userData );
typedef struct MeshDropDepth
{
// Wave heights at the mesh vertices
float heights[( MESH_DROP_WAVE_COUNT + 1 ) * ( MESH_DROP_WAVE_COUNT + 1 )];
// Collision points in the body frame, rounded by the radius
b3Vec3 probes[MESH_DROP_MAX_PROBES];
int probeCount;
float radius;
float boundingRadius;
float amplitude;
// Deepest sink of each body so far, positive when inside the wave
float bodyDepths[MESH_DROP_BODY_COUNT];
float maxDepth;
int maxIndex;
int maxStep;
int stepCount;
} MeshDropDepth;
// Starts tracking a new generation
void ResetMeshDropDepth( MeshDropDepth* depth, MeshDropSettings settings, const b3HullData* cylinder );
// Call after each world step
void UpdateMeshDropDepth( b3WorldId worldId, MeshDropDepth* depth );
// Number of bodies that sank deeper than each depth level
void GetMeshDropDepthCounts( const MeshDropDepth* depth, int counts[MESH_DROP_DEPTH_LEVEL_COUNT] );
#ifdef __cplusplus
}
#endif