Reduce ghosts (#212)

Full ghost collision handling for sphere, capsule, and hull versus a
single mesh or heightfield. This requires mesh to be built with edge
identification.

Optimized mesh builder.

Removed B3_MAX_MESH_CONTACT_TRIANGLES. You will still hit performance
problems for dense meshes. Fixes #184
This commit is contained in:
Erin Catto 2026-11-10 21:53:10 -08:00 • committed by GitHub
commit 38f2ae1e19
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
61 changed files with 17756 additions and 1492 deletions

View file

@ -2,6 +2,8 @@
set(BOX3D_BENCHMARK_FILES
main.c
mesh_benchmark.c
mesh_benchmark.h
)
add_executable(benchmark ${BOX3D_BENCHMARK_FILES})
@ -18,4 +20,36 @@ endif()
target_link_libraries(benchmark PRIVATE box3d shared)
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "" FILES ${BOX3D_BENCHMARK_FILES})
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 shared)
endif()
# Headless Ghost Collisions sample. Counts ghost manifolds per scene and body.
add_executable(ghost_scan ghost_scan.c)
set_target_properties(ghost_scan PROPERTIES
C_STANDARD 17
C_STANDARD_REQUIRED YES
C_EXTENSIONS NO
)
if (BOX3D_COMPILE_WARNING_AS_ERROR)
set_target_properties(ghost_scan PROPERTIES COMPILE_WARNING_AS_ERROR ON)
endif()
target_link_libraries(ghost_scan PRIVATE box3d shared)

View file

@ -0,0 +1,105 @@
scene,preset,mirror,body,ghosts,runs
flat,0,0,box,0,2
flat,0,0,capsule,0,2
flat,0,0,upright,0,2
flat,0,0,sphere,0,2
flat,0,0,cylinder,0,2
flat,0,1,box,0,2
flat,0,1,capsule,0,2
flat,0,1,upright,0,2
flat,0,1,sphere,0,2
flat,0,1,cylinder,0,2
ramp,0,0,box,0,3
ramp,0,0,capsule,0,3
ramp,0,0,upright,0,3
ramp,0,0,sphere,0,3
ramp,0,0,cylinder,0,3
ramp,0,1,box,0,3
ramp,0,1,capsule,0,3
ramp,0,1,upright,0,3
ramp,0,1,sphere,0,3
ramp,0,1,cylinder,0,3
cliff,0,0,box,0,2
cliff,0,0,capsule,0,2
cliff,0,0,upright,0,2
cliff,0,0,sphere,0,2
cliff,0,0,cylinder,0,2
cliff,0,1,box,0,2
cliff,0,1,capsule,0,2
cliff,0,1,upright,0,2
cliff,0,1,sphere,0,2
cliff,0,1,cylinder,0,2
crest,0,0,box,0,2
crest,0,0,capsule,0,2
crest,0,0,upright,0,2
crest,0,0,sphere,0,2
crest,0,0,cylinder,0,2
crest,0,1,box,0,2
crest,0,1,capsule,0,2
crest,0,1,upright,0,2
crest,0,1,sphere,0,2
crest,0,1,cylinder,0,2
bumps,0,0,box,0,1
bumps,0,0,capsule,0,1
bumps,0,0,upright,0,1
bumps,0,0,sphere,0,1
bumps,0,0,cylinder,0,1
bumps,0,1,box,0,1
bumps,0,1,capsule,0,1
bumps,0,1,upright,0,1
bumps,0,1,sphere,0,1
bumps,0,1,cylinder,0,1
peel,0,0,box,0,2
peel,0,0,capsule,0,2
peel,0,0,upright,0,2
peel,0,0,sphere,0,2
peel,0,0,cylinder,0,2
peel,0,1,box,0,2
peel,0,1,capsule,0,2
peel,0,1,upright,0,2
peel,0,1,sphere,0,2
peel,0,1,cylinder,0,2
peel,1,0,box,0,2
peel,1,0,capsule,0,2
peel,1,0,upright,0,2
peel,1,0,sphere,0,2
peel,1,0,cylinder,0,2
peel,1,1,box,0,2
peel,1,1,capsule,0,2
peel,1,1,upright,0,2
peel,1,1,sphere,0,2
peel,1,1,cylinder,0,2
peel,2,0,box,0,2
peel,2,0,capsule,0,2
peel,2,0,upright,0,2
peel,2,0,sphere,0,2
peel,2,0,cylinder,0,2
peel,2,1,box,0,2
peel,2,1,capsule,0,2
peel,2,1,upright,0,2
peel,2,1,sphere,0,2
peel,2,1,cylinder,0,2
peel,3,0,box,0,2
peel,3,0,capsule,0,2
peel,3,0,upright,0,2
peel,3,0,sphere,0,2
peel,3,0,cylinder,0,2
peel,3,1,box,0,2
peel,3,1,capsule,0,2
peel,3,1,upright,0,2
peel,3,1,sphere,0,2
peel,3,1,cylinder,0,2
chamfer,0,0,box,0,2
chamfer,0,0,cylinder,0,2
chamfer,0,1,box,0,2
chamfer,0,1,cylinder,0,2
rail,0,0,box,0,2
rail,0,0,capsule,0,2
rail,0,0,upright,0,5
rail,0,0,sphere,0,4
rail,0,0,cylinder,0,3
rail,0,1,box,0,2
rail,0,1,capsule,0,2
rail,0,1,upright,0,5
rail,0,1,sphere,0,4
rail,0,1,cylinder,0,3
1 scene preset mirror body ghosts runs
2 flat 0 0 box 0 2
3 flat 0 0 capsule 0 2
4 flat 0 0 upright 0 2
5 flat 0 0 sphere 0 2
6 flat 0 0 cylinder 0 2
7 flat 0 1 box 0 2
8 flat 0 1 capsule 0 2
9 flat 0 1 upright 0 2
10 flat 0 1 sphere 0 2
11 flat 0 1 cylinder 0 2
12 ramp 0 0 box 0 3
13 ramp 0 0 capsule 0 3
14 ramp 0 0 upright 0 3
15 ramp 0 0 sphere 0 3
16 ramp 0 0 cylinder 0 3
17 ramp 0 1 box 0 3
18 ramp 0 1 capsule 0 3
19 ramp 0 1 upright 0 3
20 ramp 0 1 sphere 0 3
21 ramp 0 1 cylinder 0 3
22 cliff 0 0 box 0 2
23 cliff 0 0 capsule 0 2
24 cliff 0 0 upright 0 2
25 cliff 0 0 sphere 0 2
26 cliff 0 0 cylinder 0 2
27 cliff 0 1 box 0 2
28 cliff 0 1 capsule 0 2
29 cliff 0 1 upright 0 2
30 cliff 0 1 sphere 0 2
31 cliff 0 1 cylinder 0 2
32 crest 0 0 box 0 2
33 crest 0 0 capsule 0 2
34 crest 0 0 upright 0 2
35 crest 0 0 sphere 0 2
36 crest 0 0 cylinder 0 2
37 crest 0 1 box 0 2
38 crest 0 1 capsule 0 2
39 crest 0 1 upright 0 2
40 crest 0 1 sphere 0 2
41 crest 0 1 cylinder 0 2
42 bumps 0 0 box 0 1
43 bumps 0 0 capsule 0 1
44 bumps 0 0 upright 0 1
45 bumps 0 0 sphere 0 1
46 bumps 0 0 cylinder 0 1
47 bumps 0 1 box 0 1
48 bumps 0 1 capsule 0 1
49 bumps 0 1 upright 0 1
50 bumps 0 1 sphere 0 1
51 bumps 0 1 cylinder 0 1
52 peel 0 0 box 0 2
53 peel 0 0 capsule 0 2
54 peel 0 0 upright 0 2
55 peel 0 0 sphere 0 2
56 peel 0 0 cylinder 0 2
57 peel 0 1 box 0 2
58 peel 0 1 capsule 0 2
59 peel 0 1 upright 0 2
60 peel 0 1 sphere 0 2
61 peel 0 1 cylinder 0 2
62 peel 1 0 box 0 2
63 peel 1 0 capsule 0 2
64 peel 1 0 upright 0 2
65 peel 1 0 sphere 0 2
66 peel 1 0 cylinder 0 2
67 peel 1 1 box 0 2
68 peel 1 1 capsule 0 2
69 peel 1 1 upright 0 2
70 peel 1 1 sphere 0 2
71 peel 1 1 cylinder 0 2
72 peel 2 0 box 0 2
73 peel 2 0 capsule 0 2
74 peel 2 0 upright 0 2
75 peel 2 0 sphere 0 2
76 peel 2 0 cylinder 0 2
77 peel 2 1 box 0 2
78 peel 2 1 capsule 0 2
79 peel 2 1 upright 0 2
80 peel 2 1 sphere 0 2
81 peel 2 1 cylinder 0 2
82 peel 3 0 box 0 2
83 peel 3 0 capsule 0 2
84 peel 3 0 upright 0 2
85 peel 3 0 sphere 0 2
86 peel 3 0 cylinder 0 2
87 peel 3 1 box 0 2
88 peel 3 1 capsule 0 2
89 peel 3 1 upright 0 2
90 peel 3 1 sphere 0 2
91 peel 3 1 cylinder 0 2
92 chamfer 0 0 box 0 2
93 chamfer 0 0 cylinder 0 2
94 chamfer 0 1 box 0 2
95 chamfer 0 1 cylinder 0 2
96 rail 0 0 box 0 2
97 rail 0 0 capsule 0 2
98 rail 0 0 upright 0 5
99 rail 0 0 sphere 0 4
100 rail 0 0 cylinder 0 3
101 rail 0 1 box 0 2
102 rail 0 1 capsule 0 2
103 rail 0 1 upright 0 5
104 rail 0 1 sphere 0 4
105 rail 0 1 cylinder 0 3

View file

@ -0,0 +1,105 @@
scene,preset,mirror,body,ghosts,runs
flat,0,0,box,0,2
flat,0,0,capsule,0,2
flat,0,0,upright,0,2
flat,0,0,sphere,0,2
flat,0,0,cylinder,0,2
flat,0,1,box,0,2
flat,0,1,capsule,0,2
flat,0,1,upright,0,2
flat,0,1,sphere,0,2
flat,0,1,cylinder,0,2
ramp,0,0,box,0,3
ramp,0,0,capsule,0,3
ramp,0,0,upright,0,3
ramp,0,0,sphere,0,3
ramp,0,0,cylinder,0,3
ramp,0,1,box,0,3
ramp,0,1,capsule,0,3
ramp,0,1,upright,0,3
ramp,0,1,sphere,0,3
ramp,0,1,cylinder,0,3
cliff,0,0,box,0,2
cliff,0,0,capsule,0,2
cliff,0,0,upright,0,2
cliff,0,0,sphere,0,2
cliff,0,0,cylinder,0,2
cliff,0,1,box,0,2
cliff,0,1,capsule,0,2
cliff,0,1,upright,0,2
cliff,0,1,sphere,0,2
cliff,0,1,cylinder,0,2
crest,0,0,box,0,2
crest,0,0,capsule,0,2
crest,0,0,upright,0,2
crest,0,0,sphere,0,2
crest,0,0,cylinder,0,2
crest,0,1,box,0,2
crest,0,1,capsule,0,2
crest,0,1,upright,0,2
crest,0,1,sphere,0,2
crest,0,1,cylinder,0,2
bumps,0,0,box,0,1
bumps,0,0,capsule,0,1
bumps,0,0,upright,0,1
bumps,0,0,sphere,0,1
bumps,0,0,cylinder,0,1
bumps,0,1,box,0,1
bumps,0,1,capsule,0,1
bumps,0,1,upright,0,1
bumps,0,1,sphere,0,1
bumps,0,1,cylinder,0,1
peel,0,0,box,0,2
peel,0,0,capsule,0,2
peel,0,0,upright,0,2
peel,0,0,sphere,0,2
peel,0,0,cylinder,0,2
peel,0,1,box,0,2
peel,0,1,capsule,0,2
peel,0,1,upright,0,2
peel,0,1,sphere,0,2
peel,0,1,cylinder,0,2
peel,1,0,box,0,2
peel,1,0,capsule,0,2
peel,1,0,upright,0,2
peel,1,0,sphere,0,2
peel,1,0,cylinder,0,2
peel,1,1,box,0,2
peel,1,1,capsule,0,2
peel,1,1,upright,0,2
peel,1,1,sphere,0,2
peel,1,1,cylinder,0,2
peel,2,0,box,0,2
peel,2,0,capsule,0,2
peel,2,0,upright,0,2
peel,2,0,sphere,0,2
peel,2,0,cylinder,0,2
peel,2,1,box,0,2
peel,2,1,capsule,0,2
peel,2,1,upright,0,2
peel,2,1,sphere,0,2
peel,2,1,cylinder,0,2
peel,3,0,box,0,2
peel,3,0,capsule,0,2
peel,3,0,upright,0,2
peel,3,0,sphere,0,2
peel,3,0,cylinder,0,2
peel,3,1,box,0,2
peel,3,1,capsule,0,2
peel,3,1,upright,0,2
peel,3,1,sphere,0,2
peel,3,1,cylinder,0,2
chamfer,0,0,box,0,2
chamfer,0,0,cylinder,0,2
chamfer,0,1,box,0,2
chamfer,0,1,cylinder,0,2
rail,0,0,box,0,5
rail,0,0,capsule,0,4
rail,0,0,upright,0,5
rail,0,0,sphere,0,5
rail,0,0,cylinder,0,4
rail,0,1,box,0,5
rail,0,1,capsule,0,4
rail,0,1,upright,0,5
rail,0,1,sphere,0,5
rail,0,1,cylinder,0,4
1 scene preset mirror body ghosts runs
2 flat 0 0 box 0 2
3 flat 0 0 capsule 0 2
4 flat 0 0 upright 0 2
5 flat 0 0 sphere 0 2
6 flat 0 0 cylinder 0 2
7 flat 0 1 box 0 2
8 flat 0 1 capsule 0 2
9 flat 0 1 upright 0 2
10 flat 0 1 sphere 0 2
11 flat 0 1 cylinder 0 2
12 ramp 0 0 box 0 3
13 ramp 0 0 capsule 0 3
14 ramp 0 0 upright 0 3
15 ramp 0 0 sphere 0 3
16 ramp 0 0 cylinder 0 3
17 ramp 0 1 box 0 3
18 ramp 0 1 capsule 0 3
19 ramp 0 1 upright 0 3
20 ramp 0 1 sphere 0 3
21 ramp 0 1 cylinder 0 3
22 cliff 0 0 box 0 2
23 cliff 0 0 capsule 0 2
24 cliff 0 0 upright 0 2
25 cliff 0 0 sphere 0 2
26 cliff 0 0 cylinder 0 2
27 cliff 0 1 box 0 2
28 cliff 0 1 capsule 0 2
29 cliff 0 1 upright 0 2
30 cliff 0 1 sphere 0 2
31 cliff 0 1 cylinder 0 2
32 crest 0 0 box 0 2
33 crest 0 0 capsule 0 2
34 crest 0 0 upright 0 2
35 crest 0 0 sphere 0 2
36 crest 0 0 cylinder 0 2
37 crest 0 1 box 0 2
38 crest 0 1 capsule 0 2
39 crest 0 1 upright 0 2
40 crest 0 1 sphere 0 2
41 crest 0 1 cylinder 0 2
42 bumps 0 0 box 0 1
43 bumps 0 0 capsule 0 1
44 bumps 0 0 upright 0 1
45 bumps 0 0 sphere 0 1
46 bumps 0 0 cylinder 0 1
47 bumps 0 1 box 0 1
48 bumps 0 1 capsule 0 1
49 bumps 0 1 upright 0 1
50 bumps 0 1 sphere 0 1
51 bumps 0 1 cylinder 0 1
52 peel 0 0 box 0 2
53 peel 0 0 capsule 0 2
54 peel 0 0 upright 0 2
55 peel 0 0 sphere 0 2
56 peel 0 0 cylinder 0 2
57 peel 0 1 box 0 2
58 peel 0 1 capsule 0 2
59 peel 0 1 upright 0 2
60 peel 0 1 sphere 0 2
61 peel 0 1 cylinder 0 2
62 peel 1 0 box 0 2
63 peel 1 0 capsule 0 2
64 peel 1 0 upright 0 2
65 peel 1 0 sphere 0 2
66 peel 1 0 cylinder 0 2
67 peel 1 1 box 0 2
68 peel 1 1 capsule 0 2
69 peel 1 1 upright 0 2
70 peel 1 1 sphere 0 2
71 peel 1 1 cylinder 0 2
72 peel 2 0 box 0 2
73 peel 2 0 capsule 0 2
74 peel 2 0 upright 0 2
75 peel 2 0 sphere 0 2
76 peel 2 0 cylinder 0 2
77 peel 2 1 box 0 2
78 peel 2 1 capsule 0 2
79 peel 2 1 upright 0 2
80 peel 2 1 sphere 0 2
81 peel 2 1 cylinder 0 2
82 peel 3 0 box 0 2
83 peel 3 0 capsule 0 2
84 peel 3 0 upright 0 2
85 peel 3 0 sphere 0 2
86 peel 3 0 cylinder 0 2
87 peel 3 1 box 0 2
88 peel 3 1 capsule 0 2
89 peel 3 1 upright 0 2
90 peel 3 1 sphere 0 2
91 peel 3 1 cylinder 0 2
92 chamfer 0 0 box 0 2
93 chamfer 0 0 cylinder 0 2
94 chamfer 0 1 box 0 2
95 chamfer 0 1 cylinder 0 2
96 rail 0 0 box 0 5
97 rail 0 0 capsule 0 4
98 rail 0 0 upright 0 5
99 rail 0 0 sphere 0 5
100 rail 0 0 cylinder 0 4
101 rail 0 1 box 0 5
102 rail 0 1 capsule 0 4
103 rail 0 1 upright 0 5
104 rail 0 1 sphere 0 5
105 rail 0 1 cylinder 0 4

521
benchmark/ghost_scan.c Normal file
View file

@ -0,0 +1,521 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Headless scan of the Mesh / Ghost Collisions sample. Runs every scene, body, mirror and PEEL
// preset for a fixed number of steps and counts the ghost manifolds that pushed on the body. A
// written result file can be compared against a later build, which fails on any count that grew. It
// also fails on a config that completed fewer runs, because a body stopped on an edge or dropped
// through the ground crosses fewer edges and so logs fewer ghosts.
#if defined( _MSC_VER ) && !defined( _CRT_SECURE_NO_WARNINGS )
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "ghost_collisions.h"
#include "box3d/box3d.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Command line and result file keys
static const char* s_sceneKeys[e_ghostSceneCount] = { "flat", "ramp", "cliff", "crest", "bumps", "peel", "chamfer", "rail" };
static const char* s_bodyKeys[e_ghostBodyCount] = { "box", "capsule", "upright", "sphere", "cylinder" };
#define MAX_CONFIGS 256
static bool s_recycling = true;
typedef struct Config
{
GhostScene scene;
int preset;
bool mirror;
GhostBody body;
int ghostCount;
int runCount;
// From the compare file, -1 when absent
int baseGhostCount;
int baseRunCount;
} Config;
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;
}
// Returns -1 for all, -2 for unknown
static int ParseKey( const char* value, const char** keys, int count )
{
if ( strcmp( value, "all" ) == 0 )
{
return -1;
}
for ( int i = 0; i < count; ++i )
{
if ( strcmp( value, keys[i] ) == 0 )
{
return i;
}
}
char* end;
long index = strtol( value, &end, 10 );
if ( *end == '\0' && 0 <= index && index < count )
{
return (int)index;
}
return -2;
}
static void RunConfig( Config* config, GhostSettings settings, int stepCount, bool verbose )
{
settings.scene = config->scene;
settings.peelPreset = config->preset;
settings.mirror = config->mirror;
settings.body = config->body;
// The s&box character is a fixed rotation hull without speculative contact. Speculative contact or
// rotation hide the ghost.
if ( config->scene == e_ghostChamfer )
{
settings.fixedRotation = true;
settings.speculative = false;
}
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
if ( s_recycling == false )
{
b3World_SetContactRecycleDistance( worldId, 0.0f );
}
GhostCollisionsData data = CreateGhostCollisions( worldId, settings );
for ( int step = 0; step < stepCount; ++step )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
GhostReport reports[16];
int ghostCount = UpdateGhostCollisions( worldId, &data, reports, 16 );
if ( verbose )
{
ghostCount = b3MinInt( ghostCount, 16 );
for ( int i = 0; i < ghostCount; ++i )
{
GhostReport* r = reports + i;
printf( " ghost step %d run %d n (%.3f %.3f %.3f) p (%.2f %.2f %.2f) sep %.4f impulse %.3f\n", step + 1, data.runCount,
r->normal.x, r->normal.y, r->normal.z, (float)r->point.x, (float)r->point.y, (float)r->point.z,
r->separation, r->impulse );
}
}
}
config->ghostCount = data.ghostCount;
config->runCount = data.runCount;
b3DestroyWorld( worldId );
DestroyGhostCollisions( &data );
}
static void FormatRow( char* buffer, size_t size, const Config* config )
{
if ( config->scene == e_ghostInternal )
{
snprintf( buffer, size, "%s %d%s", s_sceneKeys[config->scene], config->preset, config->mirror ? " mirror" : "" );
}
else
{
snprintf( buffer, size, "%s%s", s_sceneKeys[config->scene], config->mirror ? " mirror" : "" );
}
}
static bool SameConfig( const Config* a, const Config* b )
{
return a->scene == b->scene && a->preset == b->preset && a->mirror == b->mirror && a->body == b->body;
}
// Filters are -1 for all
static int BuildConfigs( Config* configs, int sceneFilter, int presetFilter, int mirrorFilter, int bodyFilter )
{
int configCount = 0;
for ( int scene = 0; scene < e_ghostSceneCount; ++scene )
{
if ( sceneFilter >= 0 && scene != sceneFilter )
{
continue;
}
int presetCount = scene == e_ghostInternal ? GHOST_PEEL_PRESET_COUNT : 1;
for ( int preset = 0; preset < presetCount; ++preset )
{
if ( scene == e_ghostInternal && presetFilter >= 0 && preset != presetFilter )
{
continue;
}
for ( int mirror = 0; mirror < 2; ++mirror )
{
if ( mirrorFilter >= 0 && mirror != mirrorFilter )
{
continue;
}
for ( int body = 0; body < e_ghostBodyCount; ++body )
{
if ( bodyFilter >= 0 && body != bodyFilter )
{
continue;
}
// Only a flat bottom can rest on the chamfer edges
if ( scene == e_ghostChamfer && body != e_ghostBox && body != e_ghostCylinder )
{
continue;
}
B3_ASSERT( configCount < MAX_CONFIGS );
configs[configCount++] = (Config){
.scene = (GhostScene)scene,
.preset = preset,
.mirror = mirror != 0,
.body = (GhostBody)body,
.baseGhostCount = -1,
.baseRunCount = -1,
};
}
}
}
}
return configCount;
}
static bool ReadBaseline( const char* path, Config* configs, int configCount )
{
FILE* file = fopen( path, "r" );
if ( file == NULL )
{
printf( "cannot read %s\n", path );
return false;
}
char line[256];
while ( fgets( line, sizeof( line ), file ) != NULL )
{
char sceneKey[32], bodyKey[32];
int preset, mirror, ghosts, runs;
if ( sscanf( line, "%31[^,],%d,%d,%31[^,],%d,%d", sceneKey, &preset, &mirror, bodyKey, &ghosts, &runs ) != 6 )
{
continue;
}
int scene = ParseKey( sceneKey, s_sceneKeys, e_ghostSceneCount );
int body = ParseKey( bodyKey, s_bodyKeys, e_ghostBodyCount );
for ( int i = 0; i < configCount; ++i )
{
Config* c = configs + i;
if ( (int)c->scene == scene && c->preset == preset && c->mirror == ( mirror != 0 ) && (int)c->body == body )
{
c->baseGhostCount = ghosts;
c->baseRunCount = runs;
}
}
}
fclose( file );
return true;
}
// Replaces only the rows of this run and keeps the rest of an existing file, in canonical order
static bool WriteResults( const char* path, const Config* configs, int configCount )
{
Config allConfigs[MAX_CONFIGS];
int allCount = BuildConfigs( allConfigs, -1, -1, -1, -1 );
FILE* existing = fopen( path, "r" );
if ( existing != NULL )
{
fclose( existing );
if ( ReadBaseline( path, allConfigs, allCount ) == false )
{
return false;
}
}
FILE* file = fopen( path, "w" );
if ( file == NULL )
{
printf( "cannot write %s\n", path );
return false;
}
fprintf( file, "scene,preset,mirror,body,ghosts,runs\n" );
for ( int i = 0; i < allCount; ++i )
{
const Config* c = allConfigs + i;
int ghostCount = c->baseGhostCount;
int runCount = c->baseRunCount;
for ( int j = 0; j < configCount; ++j )
{
if ( SameConfig( c, configs + j ) )
{
ghostCount = configs[j].ghostCount;
runCount = configs[j].runCount;
break;
}
}
if ( ghostCount < 0 )
{
continue;
}
fprintf( file, "%s,%d,%d,%s,%d,%d\n", s_sceneKeys[c->scene], c->preset, c->mirror ? 1 : 0, s_bodyKeys[c->body], ghostCount,
runCount );
}
fclose( file );
return true;
}
int main( int argc, char** argv )
{
int sceneFilter = -1;
int bodyFilter = -1;
int mirrorFilter = -1;
int presetFilter = -1;
int stepCount = 900;
bool verbose = false;
const char* writePath = NULL;
const char* comparePath = NULL;
GhostSettings settings = GetDefaultGhostSettings();
for ( int i = 1; i < argc; ++i )
{
const char* arg = argv[i];
const char* value;
if ( ( value = MatchValue( arg, "-s=", "--scene=" ) ) != NULL )
{
sceneFilter = ParseKey( value, s_sceneKeys, e_ghostSceneCount );
}
else if ( ( value = MatchValue( arg, "-b=", "--body=" ) ) != NULL )
{
bodyFilter = ParseKey( value, s_bodyKeys, e_ghostBodyCount );
}
else if ( ( value = MatchValue( arg, "-m=", "--mirror=" ) ) != NULL )
{
mirrorFilter = strcmp( value, "all" ) == 0 ? -1 : atoi( value ) != 0;
}
else if ( ( value = MatchValue( arg, "-p=", "--preset=" ) ) != NULL )
{
presetFilter = strcmp( value, "all" ) == 0 ? -1 : b3ClampInt( atoi( value ), 0, GHOST_PEEL_PRESET_COUNT - 1 );
}
else if ( ( value = MatchValue( arg, "-n=", "--steps=" ) ) != NULL )
{
stepCount = atoi( value );
}
else if ( ( value = MatchValue( arg, "-w=", "--write=" ) ) != NULL )
{
writePath = value;
}
else if ( ( value = MatchValue( arg, "-c=", "--compare=" ) ) != NULL )
{
comparePath = value;
}
else if ( ( value = MatchValue( arg, "--speed=", "--speed=" ) ) != NULL )
{
settings.speed = (float)atof( value );
}
else if ( ( value = MatchValue( arg, "--yaw=", "--yaw=" ) ) != NULL )
{
settings.yaw = (float)atof( value );
}
else if ( ( value = MatchValue( arg, "--friction=", "--friction=" ) ) != NULL )
{
settings.friction = (float)atof( value );
}
else if ( ( value = MatchValue( arg, "--cell=", "--cell=" ) ) != NULL )
{
settings.cellSize = (float)atof( value );
}
else if ( strcmp( arg, "--fixed-rotation" ) == 0 )
{
settings.fixedRotation = true;
}
else if ( strcmp( arg, "--no-speculative" ) == 0 )
{
settings.speculative = false;
}
else if ( strcmp( arg, "--no-recycling" ) == 0 )
{
s_recycling = false;
}
else if ( strcmp( arg, "--height-field" ) == 0 )
{
settings.heightField = true;
}
else if ( strcmp( arg, "-v" ) == 0 || strcmp( arg, "--verbose" ) == 0 )
{
verbose = true;
}
else
{
sceneFilter = -2;
}
if ( sceneFilter == -2 || bodyFilter == -2 )
{
printf( "Usage: ghost_scan [options]\n"
"Runs the Ghost Collisions sample headless and counts ghost manifolds per scene and body.\n"
" -s, --scene=<key|all> flat, ramp, cliff, crest, bumps, peel, chamfer, rail (default all)\n"
" chamfer runs only the box and cylinder, fixed rotation without speculative\n"
" -b, --body=<key|all> box, capsule, upright, sphere, cylinder (default all)\n"
" -m, --mirror=<0|1|all> mirrored mesh (default all)\n"
" -p, --preset=<0-3|all> PEEL preset (default all)\n"
" -n, --steps=<int> steps per config (default 900)\n"
" -w, --write=<file> write results as csv, replacing only the rows of this run\n"
" -c, --compare=<file> compare with a written csv, fail if any count grew, any config\n"
" completed fewer runs, or has no row\n"
" --speed=, --yaw=, --friction=, --cell=, --fixed-rotation, --no-speculative\n"
" --height-field height field ground, one static body per height field\n"
" --no-recycling disable contact recycling\n"
" -v, --verbose print every ghost\n"
"Exit code is 1 when a compared count grew, completed fewer runs or has no row, 0 otherwise.\n" );
return 2;
}
}
Config configs[MAX_CONFIGS];
int configCount = BuildConfigs( configs, sceneFilter, presetFilter, mirrorFilter, bodyFilter );
if ( comparePath != NULL && ReadBaseline( comparePath, configs, configCount ) == false )
{
return 2;
}
printf( "ghost scan: %d configs, %d steps, speed %.1f, yaw %.0f, friction %.2f, cell %.2f%s\n", configCount, stepCount,
settings.speed, settings.yaw, settings.friction, settings.cellSize, settings.heightField ? ", height field" : "" );
fflush( stdout );
uint64_t ticks = b3GetTicks();
for ( int i = 0; i < configCount; ++i )
{
if ( verbose )
{
char row[64];
FormatRow( row, sizeof( row ), configs + i );
printf( "%s %s\n", row, s_bodyKeys[configs[i].body] );
}
RunConfig( configs + i, settings, stepCount, verbose );
}
float seconds = 0.001f * b3GetMilliseconds( ticks );
// One row per ground, one column per body. A compared cell that changed prints as old>new.
printf( "\n%-18s", "" );
for ( int body = 0; body < e_ghostBodyCount; ++body )
{
if ( bodyFilter < 0 || body == bodyFilter )
{
printf( "%10s", s_bodyKeys[body] );
}
}
printf( "\n" );
int totalGhosts = 0;
int grewCount = 0;
int shrankCount = 0;
int missingCount = 0;
int fewerRunsCount = 0;
int column = 0;
for ( int i = 0; i < configCount; ++i )
{
const Config* c = configs + i;
bool newRow = i == 0 || c->scene != configs[i - 1].scene || c->preset != configs[i - 1].preset ||
c->mirror != configs[i - 1].mirror;
if ( newRow )
{
char row[64];
FormatRow( row, sizeof( row ), c );
printf( "%s%-18s", i == 0 ? "" : "\n", row );
column = 0;
}
// A scene that skips a body leaves its column empty
int bodyColumn = bodyFilter >= 0 ? 0 : (int)c->body;
while ( column < bodyColumn )
{
printf( "%10s", "-" );
column += 1;
}
column += 1;
char cell[32];
if ( comparePath != NULL && c->baseGhostCount < 0 )
{
snprintf( cell, sizeof( cell ), "?>%d", c->ghostCount );
}
else if ( c->baseGhostCount >= 0 && c->baseGhostCount != c->ghostCount )
{
snprintf( cell, sizeof( cell ), "%d>%d", c->baseGhostCount, c->ghostCount );
}
else
{
snprintf( cell, sizeof( cell ), "%d", c->ghostCount );
}
printf( "%10s", cell );
totalGhosts += c->ghostCount;
grewCount += c->baseGhostCount >= 0 && c->ghostCount > c->baseGhostCount;
shrankCount += c->baseGhostCount >= 0 && c->ghostCount < c->baseGhostCount;
missingCount += c->baseGhostCount < 0;
fewerRunsCount += c->baseRunCount >= 0 && c->runCount < c->baseRunCount;
}
printf( "\n\ntotal ghosts %d, time %.1f s\n", totalGhosts, seconds );
for ( int i = 0; i < configCount && fewerRunsCount > 0; ++i )
{
const Config* c = configs + i;
if ( c->baseRunCount >= 0 && c->runCount < c->baseRunCount )
{
char row[64];
FormatRow( row, sizeof( row ), c );
printf( "fewer runs: %s %s %d>%d\n", row, s_bodyKeys[c->body], c->baseRunCount, c->runCount );
}
}
if ( writePath != NULL && WriteResults( writePath, configs, configCount ) == false )
{
return 2;
}
if ( comparePath != NULL )
{
bool pass = grewCount == 0 && missingCount == 0 && fewerRunsCount == 0;
printf( "compared with %s: %d grew, %d shrank, %d missing, %d with fewer runs\n", comparePath, grewCount, shrankCount,
missingCount, fewerRunsCount );
printf( pass ? "PASS\n" : "FAIL\n" );
return pass ? 0 : 1;
}
return 0;
}

View file

@ -6,6 +6,7 @@
#endif
#include "benchmarks.h"
#include "mesh_benchmark.h"
#include "utils.h"
#ifdef BOX3D_INTERNAL_BENCHMARKS
@ -215,6 +216,9 @@ static void PrintBenchmarks( const Benchmark* benchmarks, int count )
// Compare GJK and SAT on hull pairs in the speculative regime. Static Box3D only.
// start /affinity 0x5555 .\build\bin\Release\benchmark.exe --sat -r=5
// Time mesh creation.
// start /affinity 0x5555 .\build\bin\Release\benchmark.exe --mesh -r=5
int main( int argc, char** argv )
{
#ifdef TRACY_ENABLE
@ -286,6 +290,8 @@ int main( int argc, char** argv )
bool enableContinuous = true;
bool recordStepTimes = false;
bool runSat = false;
bool runMesh = false;
const char* meshCase = NULL;
int simdWidth = 0;
assert( maxThreadCount <= B3_MAX_WORKERS );
@ -343,6 +349,15 @@ int main( int argc, char** argv )
exit( 1 );
#endif
}
else if ( ( value = MatchValue( arg, "-mesh=", "--mesh=" ) ) != NULL )
{
runMesh = true;
meshCase = value;
}
else if ( strcmp( arg, "-mesh" ) == 0 || strcmp( arg, "--mesh" ) == 0 )
{
runMesh = true;
}
else if ( ( value = MatchValue( arg, "-simd=", "--simd-width=" ) ) != NULL )
{
simdWidth = atoi( value );
@ -372,6 +387,7 @@ int main( int argc, char** argv )
"-nc, --no-continuous: disable continuous collision\n"
"-s, --record-steps: record step times\n"
"-sat, --sat: compare GJK and SAT on hull pairs, then exit\n"
"-mesh, --mesh[=<case>]: time b3CreateMesh on several meshes, or one case, then exit\n"
"-simd, --simd-width=<4|8>: force the SIMD width (static Box3D only)\n"
"-l, --list: list the registered benchmarks\n"
"-h, --help: print this help\n" );
@ -402,6 +418,13 @@ int main( int argc, char** argv )
}
#endif
if ( runMesh )
{
RunMeshBenchmarks( runCount, meshCase );
free( profiles );
return 0;
}
printf( "Starting benchmarks\n" );
printf( "======================================\n" );
#ifdef BOX3D_INTERNAL_BENCHMARKS

233
benchmark/mesh_benchmark.c Normal file
View file

@ -0,0 +1,233 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "mesh_benchmark.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>
typedef enum MeshShape
{
meshShape_wave,
meshShape_torus,
meshShape_soup,
} MeshShape;
typedef struct MeshCase
{
const char* name;
MeshShape shape;
int countA;
int countB;
bool useMedianSplit;
bool identifyEdges;
bool weldVertices;
} MeshCase;
typedef struct MeshSource
{
b3Vec3* vertices;
int32_t* indices;
int vertexCount;
int triangleCount;
} MeshSource;
static float WaveHeight( int i, int j )
{
return 0.5f * sinf( 0.31f * (float)i ) * cosf( 0.23f * (float)j ) + 0.25f * sinf( 0.07f * (float)( i + 2 * j ) );
}
// Shared-vertex grid, or a triangle soup with three vertices per triangle when unshared is set
static MeshSource MakeWave( int xCount, int zCount, bool unshared )
{
float cellWidth = 0.5f;
MeshSource source = { 0 };
source.triangleCount = 2 * xCount * zCount;
source.indices = malloc( 3 * source.triangleCount * sizeof( int32_t ) );
if ( unshared == false )
{
source.vertexCount = ( xCount + 1 ) * ( zCount + 1 );
source.vertices = malloc( source.vertexCount * sizeof( b3Vec3 ) );
for ( int i = 0; i <= xCount; ++i )
{
for ( int j = 0; j <= zCount; ++j )
{
source.vertices[i * ( zCount + 1 ) + j] = (b3Vec3){ cellWidth * i, WaveHeight( i, j ), cellWidth * j };
}
}
int index = 0;
for ( int i = 0; i < xCount; ++i )
{
for ( int j = 0; j < zCount; ++j )
{
int a = i * ( zCount + 1 ) + j;
int b = a + 1;
int c = a + ( zCount + 1 ) + 1;
int d = a + ( zCount + 1 );
source.indices[index++] = a;
source.indices[index++] = b;
source.indices[index++] = c;
source.indices[index++] = a;
source.indices[index++] = c;
source.indices[index++] = d;
}
}
}
else
{
source.vertexCount = 3 * source.triangleCount;
source.vertices = malloc( source.vertexCount * sizeof( b3Vec3 ) );
int index = 0;
for ( int i = 0; i < xCount; ++i )
{
for ( int j = 0; j < zCount; ++j )
{
b3Vec3 a = { cellWidth * i, WaveHeight( i, j ), cellWidth * j };
b3Vec3 b = { cellWidth * i, WaveHeight( i, j + 1 ), cellWidth * ( j + 1 ) };
b3Vec3 c = { cellWidth * ( i + 1 ), WaveHeight( i + 1, j + 1 ), cellWidth * ( j + 1 ) };
b3Vec3 d = { cellWidth * ( i + 1 ), WaveHeight( i + 1, j ), cellWidth * j };
b3Vec3 tris[6] = { a, b, c, a, c, d };
for ( int k = 0; k < 6; ++k )
{
source.vertices[index] = tris[k];
source.indices[index] = index;
index += 1;
}
}
}
}
return source;
}
static MeshSource MakeTorus( int radialCount, int tubularCount )
{
float radius = 8.0f;
float thickness = 2.0f;
MeshSource source = { 0 };
source.vertexCount = radialCount * tubularCount;
source.triangleCount = 2 * radialCount * tubularCount;
source.vertices = malloc( source.vertexCount * sizeof( b3Vec3 ) );
source.indices = malloc( 3 * source.triangleCount * sizeof( int32_t ) );
for ( int i = 0; i < radialCount; ++i )
{
float u = 2.0f * B3_PI * i / radialCount;
for ( int j = 0; j < tubularCount; ++j )
{
float v = 2.0f * B3_PI * j / tubularCount;
float r = radius + thickness * cosf( v );
source.vertices[i * tubularCount + j] = (b3Vec3){ r * cosf( u ), thickness * sinf( v ), r * sinf( u ) };
}
}
int index = 0;
for ( int i = 0; i < radialCount; ++i )
{
int i2 = ( i + 1 ) % radialCount;
for ( int j = 0; j < tubularCount; ++j )
{
int j2 = ( j + 1 ) % tubularCount;
int a = i * tubularCount + j;
int b = i2 * tubularCount + j;
int c = i2 * tubularCount + j2;
int d = i * tubularCount + j2;
source.indices[index++] = a;
source.indices[index++] = c;
source.indices[index++] = b;
source.indices[index++] = a;
source.indices[index++] = d;
source.indices[index++] = c;
}
}
return source;
}
void RunMeshBenchmarks( int runCount, const char* caseName )
{
MeshCase cases[] = {
{ "wave_64", meshShape_wave, 64, 64, true, true, false },
{ "wave_128", meshShape_wave, 128, 128, true, true, false },
{ "wave_256", meshShape_wave, 256, 256, true, true, false },
{ "wave_128_no_edges", meshShape_wave, 128, 128, true, false, false },
{ "wave_128_sah", meshShape_wave, 128, 128, false, true, false },
{ "torus_128x64", meshShape_torus, 128, 64, false, true, false },
{ "soup_128_weld", meshShape_soup, 128, 128, true, true, true },
};
int caseCount = sizeof( cases ) / sizeof( cases[0] );
#ifdef NDEBUG
int targetTriangles = 1 << 20;
#else
int targetTriangles = 1 << 14;
#endif
printf( "benchmark: mesh creation, runs = %d\n", runCount );
printf( "%-20s %10s %8s %12s %12s\n", "case", "triangles", "builds", "ms / build", "ns / tri" );
for ( int caseIndex = 0; caseIndex < caseCount; ++caseIndex )
{
const MeshCase* mc = cases + caseIndex;
if ( caseName != NULL && strcmp( caseName, mc->name ) != 0 )
{
continue;
}
MeshSource source;
if ( mc->shape == meshShape_torus )
{
source = MakeTorus( mc->countA, mc->countB );
}
else
{
source = MakeWave( mc->countA, mc->countB, mc->shape == meshShape_soup );
}
b3MeshDef def = { 0 };
def.vertices = source.vertices;
def.vertexCount = source.vertexCount;
def.indices = source.indices;
def.triangleCount = source.triangleCount;
def.useMedianSplit = mc->useMedianSplit;
def.identifyEdges = mc->identifyEdges;
def.weldVertices = mc->weldVertices;
def.weldTolerance = mc->weldVertices ? 0.001f : 0.0f;
int buildCount = targetTriangles / source.triangleCount;
if ( buildCount < 1 )
{
buildCount = 1;
}
float bestMs = FLT_MAX;
for ( int runIndex = 0; runIndex < runCount; ++runIndex )
{
uint64_t ticks = b3GetTicks();
for ( int buildIndex = 0; buildIndex < buildCount; ++buildIndex )
{
b3MeshData* mesh = b3CreateMesh( &def, NULL, 0 );
b3DestroyMesh( mesh );
}
float ms = b3GetMilliseconds( ticks ) / buildCount;
bestMs = b3MinFloat( bestMs, ms );
}
float nsPerTriangle = 1.0e6f * bestMs / source.triangleCount;
printf( "%-20s %10d %8d %12.3f %12.1f\n", mc->name, source.triangleCount, buildCount, bestMs, nsPerTriangle );
free( source.vertices );
free( source.indices );
}
printf( "\n" );
}

View file

@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
void RunMeshBenchmarks( int runCount, const char* caseName );

672
benchmark/mesh_soak.c Normal file
View file

@ -0,0 +1,672 @@
// 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. 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 MAX_REPORTED_FAILURES 32
#define MAX_THREADS 64
typedef enum FailureKind
{
e_tunnel,
e_awake,
} FailureKind;
typedef struct Failure
{
FailureKind kind;
MeshDropShape shape;
int generation;
uint32_t seed;
int step;
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;
// -1 rotates through the shapes
int shapeFilter;
bool fixedSeed;
bool recycling;
int completedCount;
int failureCount;
long long totalSteps;
int maxSteps;
ShapeStats stats[e_meshDropShapeCount];
Failure failures[MAX_REPORTED_FAILURES];
} Soak;
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;
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,
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. 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;
// The world registry is global and not thread safe
b3LockMutex( soak->mutex );
b3WorldId worldId = b3CreateWorld( &worldDef );
b3UnlockMutex( soak->mutex );
if ( soak->recycling == false )
{
b3World_SetContactRecycleDistance( worldId, 0.0f );
}
CreateMeshDropGround( worldId, soak->groundMesh );
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 = 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 < MESH_DROP_BODY_COUNT; ++i )
{
b3Pos center = b3Body_GetWorldCenter( bodies[i] );
if ( center.y < tunnelHeight )
{
Failure failure = { e_tunnel, shape, generation, seed, step, i, center };
RecordFailure( soak, &failure );
*failureKind = e_tunnel;
failed = true;
break;
}
}
if ( b3World_GetBodyEvents( worldId ).moveCount == 0 )
{
break;
}
if ( failed == false && step > maxSteps )
{
int awakeIndex = 0;
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
{
if ( b3Body_IsAwake( bodies[i] ) )
{
awakeIndex = i;
break;
}
}
b3Pos center = b3Body_GetWorldCenter( bodies[awakeIndex] );
Failure failure = { e_awake, shape, generation, seed, step, awakeIndex, center };
RecordFailure( soak, &failure );
*failureKind = e_awake;
failed = true;
}
}
b3LockMutex( soak->mutex );
b3DestroyWorld( worldId );
b3UnlockMutex( soak->mutex );
return step;
}
static void SoakWorker( void* context )
{
Soak* soak = context;
b3BodyId* bodies = malloc( MESH_DROP_BODY_COUNT * sizeof( b3BodyId ) );
MeshDropDepth* depth = malloc( sizeof( MeshDropDepth ) );
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 : GetMeshDropSeed( soak->baseSeed, generation );
MeshDropShape shape =
soak->shapeFilter >= 0 ? (MeshDropShape)soak->shapeFilter : (MeshDropShape)( generation % e_meshDropShapeCount );
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 % b3MaxInt( 100, soak->generationCount / 10 ) == 0 )
{
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 );
// Read the whole file so neither a row count nor a row length can drop a row
char* text = NULL;
FILE* file = fopen( path, "rb" );
if ( file != NULL )
{
fseek( file, 0, SEEK_END );
long textLength = ftell( file );
fseek( file, 0, SEEK_SET );
text = malloc( textLength + 1 );
textLength = (long)fread( text, 1, textLength, file );
text[textLength] = '\0';
fclose( file );
}
file = fopen( path, "w" );
if ( file == NULL )
{
printf( "cannot write %s\n", path );
free( text );
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" );
if ( text != NULL )
{
bool header = true;
char* line = text;
while ( *line != '\0' )
{
char* next = strchr( line, '\n' );
size_t lineLength = next != NULL ? (size_t)( next - line ) : strlen( line );
if ( lineLength > 0 && line[lineLength - 1] == '\r' )
{
lineLength -= 1;
}
if ( header == false && lineLength > 0 && strncmp( line, key, keyLength ) != 0 )
{
fprintf( file, "%.*s\n", (int)lineLength, line );
}
header = false;
line = next != NULL ? next + 1 : line + strlen( line );
}
free( text );
}
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 );
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 shapeFilter = e_meshDropBox;
uint32_t seed = (uint32_t)b3GetTicks();
bool fixedSeed = false;
bool recycling = true;
const char* writePath = NULL;
const char* comparePath = NULL;
MeshDropSettings settings = GetDefaultMeshDropSettings();
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 )
{
shapeFilter = -2;
for ( int k = 0; k < e_meshDropShapeCount; ++k )
{
if ( strcmp( value, g_meshDropShapeNames[k] ) == 0 )
{
shapeFilter = k;
}
}
if ( strcmp( value, "all" ) == 0 )
{
shapeFilter = -1;
}
if ( shapeFilter == -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 )
{
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 if ( strcmp( arg, "--no-recycling" ) == 0 )
{
recycling = false;
}
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 (default random)\n"
" --seed=<uint> run every generation with this exact seed (replay)\n"
" -a, --amplitude=<float> wave amplitude (default 0.5)\n"
" -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"
" --no-recycling disable contact recycling\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.settings = settings;
soak.recycling = recycling;
soak.groundMesh = CreateMeshDropMesh( settings.amplitude );
soak.cylinder = CreateMeshDropCylinder();
soak.baseSeed = seed;
soak.fixedSeed = fixedSeed;
soak.generationCount = generationCount;
soak.shapeFilter = shapeFilter;
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();
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;
float slop = B3_LINEAR_SLOP;
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", g_meshDropShapeNames[f->shape],
f->seed, f->index / MESH_DROP_GRID_COUNT, f->index % MESH_DROP_GRID_COUNT );
}
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 exitCode;
}

View file

@ -0,0 +1,9 @@
filter,base,generations,shape,tunnels,awake,depth4,depth8,depth16,depth32
all,12345,1000,box,0,0,1538,220,3,0
all,12345,1000,capsule,0,0,14507,3488,28,0
all,12345,1000,cylinder,0,0,11210,2353,37,0
all,12345,1000,sphere,0,0,56,0,0,0
all,12345,16000,box,0,0,23676,3191,44,0
all,12345,16000,capsule,0,0,231496,54552,515,0
all,12345,16000,cylinder,0,0,178981,37441,480,0
all,12345,16000,sphere,0,0,987,0,0,0
1 filter base generations shape tunnels awake depth4 depth8 depth16 depth32
2 all 12345 1000 box 0 0 1538 220 3 0
3 all 12345 1000 capsule 0 0 14507 3488 28 0
4 all 12345 1000 cylinder 0 0 11210 2353 37 0
5 all 12345 1000 sphere 0 0 56 0 0 0
6 all 12345 16000 box 0 0 23676 3191 44 0
7 all 12345 16000 capsule 0 0 231496 54552 515 0
8 all 12345 16000 cylinder 0 0 178981 37441 480 0
9 all 12345 16000 sphere 0 0 987 0 0 0