Ghost collision improvements (#61)

- flag to disable hull-mesh speculative collision
- faster atomics #55 
- fix triangle vs hull logic
- fix #58 and #59
- improved shadows in samples app, a bit more expensive
This commit is contained in:
Erin Catto 2026-07-08 23:53:06 -07:00 • committed by GitHub
commit ef8ef0187a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
39 changed files with 16639 additions and 12086 deletions

View file

@ -8,13 +8,6 @@ project(box3d
LANGUAGES C CXX
)
# sokol's Metal backend is Objective-C; samples/host/sokol_app_impl.c and
# samples/gfx/sokol_impl.c compile as OBJC on Apple. Enable the language here
# so those source properties are honored.
if(APPLE)
enable_language(OBJC)
endif()
# stuff to help debug cmake
# message(STATUS "cmake tool chain: ${CMAKE_TOOLCHAIN_FILE}")
# message(STATUS "cmake source dir: ${CMAKE_SOURCE_DIR}")

View file

@ -102,7 +102,7 @@ typedef void b3LogFcn( const char* message );
B3_API void b3SetAllocator( b3AllocFcn* allocFcn, b3FreeFcn* freeFcn );
/// Total bytes allocated by Box3D
B3_API int32_t b3GetByteCount( void );
B3_API int b3GetByteCount( void );
/// Override the default assert callback.
/// @param assertFcn a non-null assert callback

View file

@ -616,7 +616,7 @@ B3_API void b3CollideCapsuleAndTriangle( b3LocalManifold* manifold, int capacity
/// Collide a hull and a triangle.
B3_API void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2,
b3Vec3 v3, int triangleFlags, b3SATCache* cache );
b3Vec3 v3, int triangleFlags, b3SATCache* cache, bool enableSpeculative );
/// Collide a sphere and a triangle.
B3_API void b3CollideSphereAndTriangle( b3LocalManifold* manifold, int capacity, const b3Sphere* sphereA,

View file

@ -511,6 +511,11 @@ typedef struct b3ShapeDef
/// Warning: if this is false, you MUST call b3Body_ApplyMassFromShapes or b3Body_SetMassData before simulating the world.
bool updateBodyMass;
/// Enable speculative collision. Leave this true unless you care about reducing ghost collision
/// more than continuous collision under rotation.
/// Experimental: this can only disable speculative contact between hulls and triangles (meshes and height fields).
bool enableSpeculativeContact;
/// Used internally to detect a valid definition. DO NOT SET.
int internalValue;

View file

@ -1,5 +1,12 @@
# Box3D samples
# sokol's Cocoa/Metal backends are Objective-C. gfx/sokol_impl.c and
# host/sokol_app_impl.c compile as OBJC, so enable the language here where the
# samples need it. Consumers embedding box3d (no samples) don't require OBJC.
if(APPLE)
enable_language(OBJC)
endif()
FetchContent_Declare(imgui
GIT_REPOSITORY https://github.com/ocornut/imgui.git
GIT_TAG v1.92.7

View file

@ -31,6 +31,7 @@ enum
KEY_LEFT_SHIFT = SAPP_KEYCODE_LEFT_SHIFT,
KEY_LEFT_BRACKET = SAPP_KEYCODE_LEFT_BRACKET,
KEY_RIGHT_BRACKET = SAPP_KEYCODE_RIGHT_BRACKET,
KEY_PAUSE = SAPP_KEYCODE_PAUSE,
MOD_SHIFT = SAPP_MODIFIER_SHIFT,
MOD_CTRL = SAPP_MODIFIER_CTRL,

View file

@ -387,27 +387,28 @@ static void BuildIcosphere( float ( *outVerts )[3], uint32_t* outIndices )
}
// Capsule proxy for shadows
// 12-slice cylinder + two hemispherical caps with 2 latitude rings each
// (alpha at pi/6 and pi/3, plus a single pole). Verts are encoded with two
// vec3s, in_axis (scaled by halfLength) and in_radial (scaled by radius),
// so the same proxy mesh works for any (halfLength, radius) pair.
// Lat/long mesh: CAPSULE_SLICES azimuthal slices around the long axis, a
// cylinder body, and two hemispherical caps with CAPSULE_CAP_RINGS interior
// latitude rings plus a pole each. Verts are encoded with two vec3s, in_axis
// (scaled by halfLength) and in_radial (scaled by radius), so the same proxy
// mesh works for any (halfLength, radius) pair.
//
// Layout (74 vertices, 144 tris):
// 0..11 body ring -X in_axis=(-1,0,0), in_radial=(0, cos beta, sin beta)
// 12..23 body ring +X in_axis=(+1,0,0), in_radial=(0, cos beta, sin beta)
// 24..35 +X cap ring alpha=pi/6 in_axis=(+1,0,0), in_radial=(sin alpha, cos alpha cos beta, cos alpha sin beta)
// 36..47 +X cap ring alpha=pi/3 ditto with alpha=pi/3
// 48 +X pole in_axis=(+1,0,0), in_radial=(1, 0, 0)
// 49..60 -X cap ring alpha=pi/6 in_axis=(-1,0,0), in_radial=(-sin alpha, cos alpha cos beta, cos alpha sin beta)
// 61..72 -X cap ring alpha=pi/3 ditto
// 73 -X pole in_axis=(-1,0,0), in_radial=(-1, 0, 0)
// An inscribed facet mesh casts a shadow up to 1 - cos(halfAz) cos(halfLat)
// too small and its outline shows the slices. Scaling the radial vectors so
// facets straddle the true surface halves the max silhouette error, at 32
// slices it lands under 0.5% of radius, below a cascade texel.
//
// Caps share their equator ring with the body's end ring (the body ring
// at +X is the +X cap's alpha=0 equator, etc.), saves 24 verts and avoids
// any seam in the depth render.
#define CAPSULE_SLICES 12
#define CAPSULE_VERTICES 74
#define CAPSULE_INDICES ( 144 * 3 )
// Vertex layout:
// - body ring -X, then body ring +X (these double as the caps' equators)
// - +X cap: interior rings equator->pole order, then the pole
// - -X cap: same
//
// Caps share their equator ring with the body's end ring, saves a ring of
// verts per cap and avoids any seam in the depth render.
#define CAPSULE_SLICES 32
#define CAPSULE_CAP_RINGS 7
#define CAPSULE_VERTICES ( 2 * CAPSULE_SLICES + 2 * ( CAPSULE_CAP_RINGS * CAPSULE_SLICES + 1 ) )
#define CAPSULE_INDICES ( 12 * CAPSULE_SLICES * ( CAPSULE_CAP_RINGS + 1 ) )
typedef struct CapsuleVertex
{
@ -432,136 +433,122 @@ typedef struct CapsuleVertex
static void BuildCapsuleProxy( CapsuleVertex* outVerts, uint32_t* outIndices )
{
const float TWO_PI = 6.28318530717958647692f;
const float ALPHA1 = TWO_PI / 12.0f; // pi/6
const float ALPHA2 = 2.0f * TWO_PI / 12.0f; // pi/3
// Quad centers of an inscribed lat/long mesh dip below the true surface
// by cos(halfAz) cos(halfLat). Scale all radials so facets straddle the
// surface, halving the max silhouette error. Uniform scale keeps the
// proxy a true capsule of radius scale * r, no seam at the equators.
const float halfAz = B3_PI / (float)CAPSULE_SLICES;
const float halfLat = 0.25f * B3_PI / (float)( CAPSULE_CAP_RINGS + 1 );
const float scale = 2.0f / ( 1.0f + cosf( halfAz ) * cosf( halfLat ) );
// Vertices
int v = 0;
// 0..11: body ring -X
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
// Body rings, -X then +X. These double as the caps' equators.
for ( int side = 0; side < 2; ++side )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = -1.0f;
const float sx = ( side == 0 ) ? -1.0f : +1.0f;
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = sx;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = 0.0f;
outVerts[v].radial[1] = scale * cosf( beta );
outVerts[v].radial[2] = scale * sinf( beta );
}
}
// Caps, +X then -X: interior latitude rings equator->pole, then the pole.
// Ring r sits at latitude alpha = r * (pi/2) / (rings + 1).
for ( int side = 0; side < 2; ++side )
{
const float sx = ( side == 0 ) ? +1.0f : -1.0f;
for ( int r = 1; r <= CAPSULE_CAP_RINGS; ++r )
{
const float alpha = 0.5f * B3_PI * (float)r / (float)( CAPSULE_CAP_RINGS + 1 );
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = sx;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = scale * sx * sinf( alpha );
outVerts[v].radial[1] = scale * cosf( alpha ) * cosf( beta );
outVerts[v].radial[2] = scale * cosf( alpha ) * sinf( beta );
}
}
outVerts[v].axis[0] = sx;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = 0.0f;
outVerts[v].radial[1] = cosf( beta );
outVerts[v].radial[2] = sinf( beta );
outVerts[v].radial[0] = scale * sx;
outVerts[v].radial[1] = 0.0f;
outVerts[v].radial[2] = 0.0f;
++v;
}
// 12..23: body ring +X
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = +1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = 0.0f;
outVerts[v].radial[1] = cosf( beta );
outVerts[v].radial[2] = sinf( beta );
}
// 24..35: +X cap ring alpha=pi/6
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = +1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = sinf( ALPHA1 );
outVerts[v].radial[1] = cosf( ALPHA1 ) * cosf( beta );
outVerts[v].radial[2] = cosf( ALPHA1 ) * sinf( beta );
}
// 36..47: +X cap ring alpha=pi/3
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = +1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = sinf( ALPHA2 );
outVerts[v].radial[1] = cosf( ALPHA2 ) * cosf( beta );
outVerts[v].radial[2] = cosf( ALPHA2 ) * sinf( beta );
}
// 48: +X pole
outVerts[v].axis[0] = +1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = +1.0f;
outVerts[v].radial[1] = 0.0f;
outVerts[v].radial[2] = 0.0f;
++v;
// 49..60: -X cap ring alpha=pi/6
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = -1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = -sinf( ALPHA1 );
outVerts[v].radial[1] = cosf( ALPHA1 ) * cosf( beta );
outVerts[v].radial[2] = cosf( ALPHA1 ) * sinf( beta );
}
// 61..72: -X cap ring alpha=pi/3
for ( int i = 0; i < CAPSULE_SLICES; ++i, ++v )
{
const float beta = TWO_PI * (float)i / (float)CAPSULE_SLICES;
outVerts[v].axis[0] = -1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = -sinf( ALPHA2 );
outVerts[v].radial[1] = cosf( ALPHA2 ) * cosf( beta );
outVerts[v].radial[2] = cosf( ALPHA2 ) * sinf( beta );
}
// 73: -X pole
outVerts[v].axis[0] = -1.0f;
outVerts[v].axis[1] = 0.0f;
outVerts[v].axis[2] = 0.0f;
outVerts[v].radial[0] = -1.0f;
outVerts[v].radial[1] = 0.0f;
outVerts[v].radial[2] = 0.0f;
++v;
// Indices
int index = 0;
// Body: ring -X (verts 0..11) to ring +X (verts 12..23). For slice i
// and i+1, the outward face winds from -X[i] up the slice direction
// (beta increasing) to -X[i+1], across to +X[i+1], down to +X[i].
// Body: ring -X to ring +X. For slice i and i+1, the outward face winds
// from -X[i] up the slice direction (beta increasing) to -X[i+1], across
// to +X[i+1], down to +X[i].
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
const int mxi = i; // ring -X
const int mxn = next;
const int pxi = 12 + i; // ring +X
const int pxn = 12 + next;
CAPSULE_QUAD( mxi, mxn, pxn, pxi );
CAPSULE_QUAD( i, next, CAPSULE_SLICES + next, CAPSULE_SLICES + i );
}
// +X cap: equator (ring +X, 12..23) -> alpha=pi/6 ring (24..35) -> alpha=pi/3 (36..47) -> pole (48).
// Going outward, alpha increases. For slice i to i+1, the outward face
// winds equator[i] -> equator[i+1] -> ring1[i+1] -> ring1[i].
for ( int i = 0; i < CAPSULE_SLICES; ++i )
// +X cap: quad bands march outward from the equator (the +X body ring)
// through the latitude rings, then a fan to the pole. Going outward the
// face winds prev[i] -> prev[i+1] -> cur[i+1] -> cur[i].
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( 12 + i, 12 + next, 24 + next, 24 + i );
CAPSULE_QUAD( 24 + i, 24 + next, 36 + next, 36 + i );
// Fan to pole: tri (ring2[i], ring2[i+1], pole).
outIndices[index++] = (uint32_t)( 36 + i );
outIndices[index++] = (uint32_t)( 36 + next );
outIndices[index++] = (uint32_t)48;
int prev = CAPSULE_SLICES;
int cur = 2 * CAPSULE_SLICES;
for ( int r = 0; r < CAPSULE_CAP_RINGS; ++r )
{
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( prev + i, prev + next, cur + next, cur + i );
}
prev = cur;
cur += CAPSULE_SLICES;
}
const int pole = cur;
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
outIndices[index++] = (uint32_t)( prev + i );
outIndices[index++] = (uint32_t)( prev + next );
outIndices[index++] = (uint32_t)pole;
}
}
// -X cap: equator (ring -X, 0..11) -> alpha=pi/6 ring (49..60) -> alpha=pi/3 (61..72) -> pole (73).
// Winding flipped relative to +X cap because the outward normal points
// toward -X, the "outside-front" side of each quad swaps slice order.
for ( int i = 0; i < CAPSULE_SLICES; ++i )
// -X cap: winding flipped relative to +X because the outward normal
// points toward -X, the "outside-front" side of each quad swaps slice
// order.
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( 0 + next, 0 + i, 49 + i, 49 + next );
CAPSULE_QUAD( 49 + next, 49 + i, 61 + i, 61 + next );
// Fan to pole: tri (ring2[i+1], ring2[i], pole), opposite winding to +X.
outIndices[index++] = (uint32_t)( 61 + next );
outIndices[index++] = (uint32_t)( 61 + i );
outIndices[index++] = (uint32_t)73;
int prev = 0;
int cur = 2 * CAPSULE_SLICES + CAPSULE_CAP_RINGS * CAPSULE_SLICES + 1;
for ( int r = 0; r < CAPSULE_CAP_RINGS; ++r )
{
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
CAPSULE_QUAD( prev + next, prev + i, cur + i, cur + next );
}
prev = cur;
cur += CAPSULE_SLICES;
}
const int pole = cur;
for ( int i = 0; i < CAPSULE_SLICES; ++i )
{
const int next = ( i + 1 ) % CAPSULE_SLICES;
outIndices[index++] = (uint32_t)( prev + next );
outIndices[index++] = (uint32_t)( prev + i );
outIndices[index++] = (uint32_t)pole;
}
}
}
@ -1681,6 +1668,7 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
const sg_backend backend = sg_query_backend();
const float uvYSign = ( backend == SG_BACKEND_GLCORE || backend == SG_BACKEND_GLES3 ) ? 1.0f : -1.0f;
const Vec4 cascadeFarViewZ = MakeVec4( GetCascadeFarViewZ( 0 ), GetCascadeFarViewZ( 1 ), GetCascadeFarViewZ( 2 ), uvYSign );
const Vec4 cascadePcfScale = MakeVec4( GetCascadePcfScale( 0 ), GetCascadePcfScale( 1 ), GetCascadePcfScale( 2 ), 0.0f );
Mat4 cascadeMatrices[3];
for ( int i = 0; i < 3; ++i )
{
@ -1726,6 +1714,7 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
up.sun_color = sunColor;
up.flags[0] = frame->debugMode;
up.cascade_far_view_z = cascadeFarViewZ;
up.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
up.cascade_matrices[i] = cascadeMatrices[i];
up.view = frame->view;
@ -1774,6 +1763,7 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
sup.view_proj = viewProj;
sup.view = frame->view;
sup.cascade_far_view_z = cascadeFarViewZ;
sup.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
sup.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
@ -1817,6 +1807,7 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
cup.view_proj = viewProj;
cup.view = frame->view;
cup.cascade_far_view_z = cascadeFarViewZ;
cup.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
cup.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
@ -1869,6 +1860,7 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
gup.grid_offset = MakeVec4( frame->gridWrap.x, frame->gridWrap.y, frame->drawOrigin.x, frame->drawOrigin.z );
gup.view = frame->view;
gup.cascade_far_view_z = cascadeFarViewZ;
gup.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
gup.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
@ -2279,6 +2271,7 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
const sg_backend backend = sg_query_backend();
const float uvYSign = ( backend == SG_BACKEND_GLCORE || backend == SG_BACKEND_GLES3 ) ? 1.0f : -1.0f;
const Vec4 cascadeFarViewZ = MakeVec4( GetCascadeFarViewZ( 0 ), GetCascadeFarViewZ( 1 ), GetCascadeFarViewZ( 2 ), uvYSign );
const Vec4 cascadePcfScale = MakeVec4( GetCascadePcfScale( 0 ), GetCascadePcfScale( 1 ), GetCascadePcfScale( 2 ), 0.0f );
Mat4 cascadeMatrices[3];
for ( int i = 0; i < 3; ++i )
{
@ -2313,6 +2306,7 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
cubePass.sun_color = sunColor;
cubePass.flags[0] = frame->debugMode;
cubePass.cascade_far_view_z = cascadeFarViewZ;
cubePass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
{
cubePass.cascade_matrices[i] = cascadeMatrices[i];
@ -2335,6 +2329,7 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
spherePass.view_proj = view_proj;
spherePass.view = frame->view;
spherePass.cascade_far_view_z = cascadeFarViewZ;
spherePass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
spherePass.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
@ -2351,6 +2346,7 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
capsulePass.view_proj = view_proj;
capsulePass.view = frame->view;
capsulePass.cascade_far_view_z = cascadeFarViewZ;
capsulePass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
capsulePass.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )
@ -2368,6 +2364,7 @@ static void DrawTransparentIntoResolve( int width, int height, const FrameInput*
geomPass.grid_offset = MakeVec4( frame->gridWrap.x, frame->gridWrap.y, frame->drawOrigin.x, frame->drawOrigin.z );
geomPass.view = frame->view;
geomPass.cascade_far_view_z = cascadeFarViewZ;
geomPass.cascade_pcf_scale = cascadePcfScale;
for ( int i = 0; i < 3; ++i )
geomPass.cascade_matrices[i] = cascadeMatrices[i];
for ( int i = 0; i < 9; ++i )

View file

@ -40,6 +40,7 @@ static struct
sg_sampler sampler; // comparison sampler (LESS_EQUAL, linear PCF)
Mat4 cascadeMatrices[SHADOW_CASCADE_COUNT]; // light-space view-proj per cascade
float cascadeFarViewZ[SHADOW_CASCADE_COUNT]; // far end (positive view-Z) per cascade
float cascadeRadius[SHADOW_CASCADE_COUNT]; // bounding-sphere radius = ortho half-extent
bool inPass; // safety against unbalanced begin/end
} s_shadow;
@ -119,7 +120,7 @@ static void FrustumSliceCornersWorld( const Mat4* viewInv, const Mat4* proj, flo
// post-translation. This pins the cascade to a fixed grid in light
// space, small camera motions no longer cause the shadow texels to
// drift relative to the casters.
static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun, float nearZ, float farZ )
static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun, float nearZ, float farZ, float* radiusOut )
{
b3Vec3 corners[8];
FrustumSliceCornersWorld( viewInv, proj, nearZ, farZ, corners );
@ -145,6 +146,7 @@ static Mat4 FitCascade( const Mat4* viewInv, const Mat4* proj, b3Vec3 dirToSun,
{
radius = 0.01f;
}
*radiusOut = radius;
// Avoid a degenerate up vector when the sun is straight up/down.
b3Vec3 up = b3Vec3_axisY;
@ -184,6 +186,12 @@ void InitShadows( void )
s_shadow.splitFar = SHADOW_SPLIT_FAR;
s_shadow.splitLambda = SplitLambdaForRange( s_shadow.splitNear, s_shadow.splitFar );
// Sane ratios if a getter runs before the first FitShadows
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
s_shadow.cascadeRadius[i] = 1.0f;
}
sg_image_desc desc = { 0 };
desc.type = SG_IMAGETYPE_ARRAY;
desc.usage.depth_stencil_attachment = true;
@ -285,7 +293,7 @@ void FitShadows( const Mat4* viewInv, const Mat4* proj )
for ( int i = 0; i < SHADOW_CASCADE_COUNT; ++i )
{
s_shadow.cascadeMatrices[i] = FitCascade( viewInv, proj, s_shadow.sunDir, splits[i], splits[i + 1] );
s_shadow.cascadeMatrices[i] = FitCascade( viewInv, proj, s_shadow.sunDir, splits[i], splits[i + 1], &s_shadow.cascadeRadius[i] );
s_shadow.cascadeFarViewZ[i] = splits[i + 1];
}
}
@ -334,6 +342,20 @@ float GetCascadeFarViewZ( int cascade )
return s_shadow.cascadeFarViewZ[cascade];
}
float GetCascadePcfScale( int cascade )
{
if ( cascade < 0 || cascade >= SHADOW_CASCADE_COUNT )
{
return 1.0f;
}
// Texel world size is proportional to the cascade's ortho half-extent,
// so the radius ratio is the texel-size ratio. The floor keeps the
// shrunken kernel at least ~2 texels wide so bilinear smoothing still
// gets some support in the far cascades.
const float scale = s_shadow.cascadeRadius[0] / s_shadow.cascadeRadius[cascade];
return b3ClampFloat( scale, 0.25f, 1.0f );
}
sg_view GetShadowSampleView( void )
{
return s_shadow.sampleView;

View file

@ -43,7 +43,7 @@ extern "C"
#endif
#define SHADOW_CASCADE_COUNT 3
#define SHADOW_RESOLUTION 2048
#define SHADOW_RESOLUTION 4096
// Default cascade far split, view-space distance from the camera. Scenes
// smaller than this keep the default range, larger ones widen it.
@ -87,6 +87,13 @@ Mat4 GetCascadeMatrix( int cascade );
// these to pick which cascade to sample.
float GetCascadeFarViewZ( int cascade );
// PCF tap-offset multiplier for a cascade, in (0, 1]. The kernel is
// authored in texels of cascade 0, farther cascades cover more world per
// texel, so their tap offsets shrink by the texel-size ratio. This keeps
// the penumbra a constant world width, without it the shadow edge blur
// visibly jumps at every cascade boundary.
float GetCascadePcfScale( int cascade );
// Bound by lit pipelines once for sampling across all cascades. The view
// is the depth array's full-array sampling view. Per-cascade selection
// happens inside the shader by passing `cascade` as the layer index.

View file

@ -160,11 +160,11 @@ static void OnEvent( const sapp_event* e )
{
switch ( e->key_code )
{
case KEY_TAB:
case SAPP_KEYCODE_TAB:
s_context.showUI = !s_context.showUI;
break;
case KEY_ESCAPE:
case SAPP_KEYCODE_ESCAPE:
// Layered cancel. An open picker is an ImGui popup that
// already swallowed this. So peel the controls window, then
// the selection. Quit lives on Ctrl+Q now.
@ -179,7 +179,7 @@ static void OnEvent( const sapp_event* e )
break;
case KEY_Q:
if ( mods & MOD_CTRL )
if ( mods & SAPP_MODIFIER_CTRL )
{
sapp_request_quit();
break;
@ -188,7 +188,7 @@ static void OnEvent( const sapp_event* e )
break;
case KEY_O:
if ( mods & MOD_CTRL )
if ( mods & SAPP_MODIFIER_CTRL )
{
// Ctrl+O opens the fuzzy picker. Force the UI visible so it shows.
s_context.showUI = true;
@ -196,34 +196,32 @@ static void OnEvent( const sapp_event* e )
}
else
{
s_context.singleStep += ( mods & MOD_SHIFT ) ? 5 : 1;
s_context.singleStep += ( mods & SAPP_MODIFIER_SHIFT ) ? 5 : 1;
}
break;
case KEY_P:
// Pause stays on P. Space is not bound here on purpose. Global
// keys are dispatched before the sample sees them, so claiming
// Space would steal jump from the Mover sample.
case SAPP_KEYCODE_P:
case SAPP_KEYCODE_PAUSE:
s_context.pause = !s_context.pause;
break;
case KEY_M:
case SAPP_KEYCODE_M:
s_context.showMetrics = !s_context.showMetrics;
break;
case KEY_R:
case SAPP_KEYCODE_R:
SelectSample( &s_context, s_context.sampleIndex, true );
break;
case KEY_LEFT_BRACKET:
case SAPP_KEYCODE_LEFT_BRACKET:
SelectSample( &s_context, b3MaxInt( 0, s_context.sampleIndex - 1 ), false );
break;
case KEY_RIGHT_BRACKET:
case SAPP_KEYCODE_RIGHT_BRACKET:
SelectSample( &s_context, b3MinInt( g_sampleCount - 1, s_context.sampleIndex + 1 ), false );
break;
case KEY_F:
case SAPP_KEYCODE_F:
{
// Frame the selection, or let the sample frame its whole scene when nothing is
// selected. A non-body selection such as a recorded query supplies its own bounds and

View file

@ -93,8 +93,6 @@ void SampleContext::Save()
fprintf( file, "{\n" );
fprintf( file, " \"sampleIndex\": %d,\n", sampleIndex );
fprintf( file, " \"drawShapes\": %s,\n", gd->drawShapes ? "true" : "false" );
fprintf( file, " \"drawJoints\": %s,\n", gd->drawJoints ? "true" : "false" );
fprintf( file, " \"drawContacts\": %s,\n", gd->drawContacts ? "true" : "false" );
fprintf( file, " \"enableShadows\": %s,\n", enableShadows ? "true" : "false" );
fprintf( file, " \"enableGtao\": %s,\n", enableGtao ? "true" : "false" );
fprintf( file, " \"gtaoQuality\": %d,\n", gtaoQuality );
@ -171,16 +169,6 @@ void SampleContext::Load()
const char* s = data + tokens[i + 1].start;
GetGuiDraw()->drawShapes = strncmp( s, "true", 4 ) == 0;
}
else if ( jsoneq( data, &tokens[i], "drawJoints" ) == 0 )
{
const char* s = data + tokens[i + 1].start;
GetGuiDraw()->drawJoints = strncmp( s, "true", 4 ) == 0;
}
else if ( jsoneq( data, &tokens[i], "drawContacts" ) == 0 )
{
const char* s = data + tokens[i + 1].start;
GetGuiDraw()->drawContacts = strncmp( s, "true", 4 ) == 0;
}
else if ( jsoneq( data, &tokens[i], "enableShadows" ) == 0 )
{
const char* s = data + tokens[i + 1].start;

View file

@ -2367,9 +2367,9 @@ public:
float length = b3Length( d );
assert( b3AbsFloat( length - output.distance ) < 10.0f * FLT_EPSILON );
b3Vec3 n = b3Normalize( d );
assert( b3AbsFloat( n.x - output.normal.x ) < 100.0f * FLT_EPSILON );
assert( b3AbsFloat( n.y - output.normal.y ) < 100.0f * FLT_EPSILON );
assert( b3AbsFloat( n.z - output.normal.z ) < 100.0f * FLT_EPSILON );
assert( b3AbsFloat( n.x - output.normal.x ) < 0.0001f );
assert( b3AbsFloat( n.y - output.normal.y ) < 0.0001f );
assert( b3AbsFloat( n.z - output.normal.z ) < 0.0001f );
}
m_simplexCount = output.simplexCount;

View file

@ -556,7 +556,7 @@ public:
g_randomSeed = (uint32_t)b3GetTicks();
bool simulateAll = true;
// g_randomSeed = 3963634789;
//g_randomSeed = 1910133196;
m_runCount += 1;
m_stepCount = 0;
@ -569,7 +569,7 @@ public:
b3Vec3 linearVelocity = RandomVec3Uniform( -1.0f, 1.0f );
b3Vec3 angularVelocity = RandomVec3Uniform( -5.0f, 5.0f );
if ( simulateAll || ( i == 5 && j == 4 ) )
if ( simulateAll || ( i == 19 && j == 20 ) )
{
bodyDef.position = { 0.5f * ( i - 0.5f * m_gridCount ), 5.0f, 0.5f * ( j - 0.5f * m_gridCount ) };
bodyDef.linearVelocity = linearVelocity;

View file

@ -530,3 +530,416 @@ public:
};
static int sampleIndex = RegisterSample( "Issues", "Capsule Mesh", CapsuleMeshBug::Create );
// Reproduces s&box rigid body character ghost collisions on a FLAT floor.
//
// The s&box player is a fixed rotation dynamic body (zero radius box hull) moved by setting
// velocity. The floor here is modeled on an s&box map area that ghosts badly: concrete slabs
// and a run of parallel chamfered beams over deep pits. Every walkable vertex is at exactly
// y = 0 - there is nothing to climb and nothing to trip on. The only mesh features are AT or
// BELOW the walkable plane: chamfer facets sloping down from beam tops, pit walls and floors,
// T-junction seams between tiles tessellated at different resolutions, and a chunk seam where
// two mesh shapes meet (separate contact pairs, like s&box world chunks).
//
// Walking back and forth still launches the body upward (60-190 inch/s at run speed). No shape
// casts, no step up, no ground snapping - any upward velocity spike is a ghost collision from
// speculative hull vs triangle contacts against below-plane geometry.
class SBoxGhostCollisions : public Sample
{
public:
// s&box works in inches: 1 unit = 0.0254 m (40 units per meter)
static constexpr float SRC = 0.0254f;
// Floor layout (s&box inches)
static constexpr int m_halfLengthU = 256; // strip half length along x
static constexpr int m_halfWidthU = 64; // strip half width along z
static constexpr int m_tileSizeU = 32; // slab tile stride
// Beam section: beams run along z, the character walks along x across them.
// Tops are 12 wide with 1.5 chamfers, pits between are 10 wide and 24 deep.
// The 16 wide hull always spans the 13 gap between flat tops.
static constexpr float m_beamPitchU = 22.0f;
static constexpr float m_beamWidthU = 12.0f;
static constexpr float m_chamferWidthU = 1.5f;
static constexpr float m_chamferDropU = 1.0f;
static constexpr float m_pitDepthU = 24.0f;
static constexpr int m_beamCount = 9;
static constexpr float m_beamRegion0 = -94.0f; // first beam start
static constexpr float m_beamRegion1 = 94.0f; // last beam end
// Character (s&box player: 16 wide zero radius box hull, 72 tall, mass 500)
static constexpr float m_bodyHalfWidth = 16.0f * SRC;
static constexpr float m_bodyHalfHeight = 36.0f * SRC;
static constexpr float m_characterMass = 500.0f;
explicit SBoxGhostCollisions( SampleContext* context )
: Sample( context )
{
if ( m_context->restart == false )
{
m_camera->SetView( 90.0f, 25.0f, 10.0f, { 0.0f, 1.0f, 0.0f } );
}
// Two chunks meeting at x = 0, each its own body and mesh shape, so seam contacts live
// in separate contact pairs like s&box world mesh chunks. A beam top straddles the seam.
CreateFloorChunk( 0, -(float)m_halfLengthU, 0.0f );
CreateFloorChunk( 1, 0.0f, (float)m_halfLengthU );
// Character
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { -m_walkRange, m_bodyHalfHeight + 0.1f, 0.0f };
bodyDef.motionLocks.angularX = true;
bodyDef.motionLocks.angularY = true;
bodyDef.motionLocks.angularZ = true;
bodyDef.enableSleep = false;
bodyDef.enableContactRecycling = false;
bodyDef.gravityScale = 2.03f; // s&box gravity: 800 inch/s^2
bodyDef.name = "character";
m_characterId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = 0.0f;
//shapeDef.baseMaterial.customColor = b3_colorLimeGreen;
float volume = 8.0f * m_bodyHalfWidth * m_bodyHalfHeight * m_bodyHalfWidth;
shapeDef.density = m_characterMass / volume;
shapeDef.enableSpeculativeContact = false;
b3BoxHull box = b3MakeBoxHull( m_bodyHalfWidth, m_bodyHalfHeight, m_bodyHalfWidth );
b3CreateHullShape( m_characterId, &shapeDef, &box.base );
}
m_walkDirection = 1.0f;
m_walkSpeed = 350.0f * SRC; // s&box run speed
m_launchCount = 0;
m_maxLaunchSpeed = 0.0f;
m_launchMarkerCount = 0;
m_wasLaunched = false;
m_stepWhilePaused = true;
}
~SBoxGhostCollisions() override
{
b3DestroyMesh( m_chunkMesh[0] );
b3DestroyMesh( m_chunkMesh[1] );
}
// Deterministic integer hash for tile tessellation selection
static uint32_t Hash( uint32_t x )
{
x ^= x >> 16;
x *= 0x7feb352du;
x ^= x >> 15;
x *= 0x846ca68bu;
x ^= x >> 16;
return x;
}
static void EmitTriangle( std::vector<b3Vec3>& vertices, std::vector<int32_t>& indices, b3Vec3 a, b3Vec3 b, b3Vec3 c )
{
int32_t base = (int32_t)vertices.size();
vertices.push_back( a );
vertices.push_back( b );
vertices.push_back( c );
indices.push_back( base );
indices.push_back( base + 1 );
indices.push_back( base + 2 );
}
// Horizontal patch at height y spanning [x0,x1]x[z0,z1] (inches), normal +y
static void EmitPatch( std::vector<b3Vec3>& vertices, std::vector<int32_t>& indices, float x0, float x1, float z0, float z1,
float y, float cell )
{
if ( x1 - x0 < 0.01f )
{
return;
}
int countX = (int)( ( x1 - x0 ) / cell + 0.99f );
int countZ = (int)( ( z1 - z0 ) / cell + 0.99f );
for ( int ix = 0; ix < countX; ++ix )
{
for ( int iz = 0; iz < countZ; ++iz )
{
float cx0 = x0 + ( x1 - x0 ) * (float)ix / (float)countX;
float cx1 = x0 + ( x1 - x0 ) * (float)( ix + 1 ) / (float)countX;
float cz0 = z0 + ( z1 - z0 ) * (float)iz / (float)countZ;
float cz1 = z0 + ( z1 - z0 ) * (float)( iz + 1 ) / (float)countZ;
b3Vec3 a = { SRC * cx0, SRC * y, SRC * cz0 };
b3Vec3 b = { SRC * cx1, SRC * y, SRC * cz0 };
b3Vec3 c = { SRC * cx1, SRC * y, SRC * cz1 };
b3Vec3 d = { SRC * cx0, SRC * y, SRC * cz1 };
// Alternate the split diagonal like typical cooked map data
if ( ( ix + iz ) & 1 )
{
EmitTriangle( vertices, indices, a, d, c );
EmitTriangle( vertices, indices, a, c, b );
}
else
{
EmitTriangle( vertices, indices, a, d, b );
EmitTriangle( vertices, indices, b, d, c );
}
}
}
}
// Sloped strip from edge (xLow, yLow) to edge (xHigh, yHigh) spanning the full z width
static void EmitSlope( std::vector<b3Vec3>& vertices, std::vector<int32_t>& indices, float xLow, float yLow, float xHigh,
float yHigh, float zCell )
{
int countZ = (int)( 2.0f * (float)m_halfWidthU / zCell + 0.99f );
for ( int iz = 0; iz < countZ; ++iz )
{
float z0 = -(float)m_halfWidthU + 2.0f * (float)m_halfWidthU * (float)iz / (float)countZ;
float z1 = -(float)m_halfWidthU + 2.0f * (float)m_halfWidthU * (float)( iz + 1 ) / (float)countZ;
b3Vec3 l0 = { SRC * xLow, SRC * yLow, SRC * z0 };
b3Vec3 l1 = { SRC * xLow, SRC * yLow, SRC * z1 };
b3Vec3 h0 = { SRC * xHigh, SRC * yHigh, SRC * z0 };
b3Vec3 h1 = { SRC * xHigh, SRC * yHigh, SRC * z1 };
EmitTriangle( vertices, indices, l0, l1, h1 );
EmitTriangle( vertices, indices, l0, h1, h0 );
}
}
// Vertical wall at x from y0 (bottom) to y1 (top). facing = +1 faces +x, -1 faces -x
static void EmitWall( std::vector<b3Vec3>& vertices, std::vector<int32_t>& indices, float x, float y0, float y1, int facing,
float zCell )
{
int countZ = (int)( 2.0f * (float)m_halfWidthU / zCell + 0.99f );
for ( int iz = 0; iz < countZ; ++iz )
{
float z0 = -(float)m_halfWidthU + 2.0f * (float)m_halfWidthU * (float)iz / (float)countZ;
float z1 = -(float)m_halfWidthU + 2.0f * (float)m_halfWidthU * (float)( iz + 1 ) / (float)countZ;
b3Vec3 b0 = { SRC * x, SRC * y0, SRC * z0 };
b3Vec3 b1 = { SRC * x, SRC * y0, SRC * z1 };
b3Vec3 t0 = { SRC * x, SRC * y1, SRC * z0 };
b3Vec3 t1 = { SRC * x, SRC * y1, SRC * z1 };
if ( facing > 0 )
{
EmitTriangle( vertices, indices, b0, b1, t1 );
EmitTriangle( vertices, indices, b0, t1, t0 );
}
else
{
EmitTriangle( vertices, indices, b0, t0, t1 );
EmitTriangle( vertices, indices, b0, t1, b1 );
}
}
}
// Clip [a0,a1] to [c0,c1]
static bool ClipSpan( float a0, float a1, float c0, float c1, float* o0, float* o1 )
{
*o0 = a0 > c0 ? a0 : c0;
*o1 = a1 < c1 ? a1 : c1;
return *o1 - *o0 > 0.01f;
}
void CreateFloorChunk( int chunk, float x0U, float x1U )
{
std::vector<b3Vec3> vertices;
std::vector<int32_t> indices;
float s0, s1;
// --- Concrete slabs at y = 0 outside the beam region ---
// Tiles tessellate at a hash-picked resolution so neighbors meet with T-junctions,
// like cooked s&box map collision.
float slabSpans[2][2] = { { -(float)m_halfLengthU, m_beamRegion0 }, { m_beamRegion1, (float)m_halfLengthU } };
for ( int i = 0; i < 2; ++i )
{
if ( ClipSpan( slabSpans[i][0], slabSpans[i][1], x0U, x1U, &s0, &s1 ) == false )
{
continue;
}
for ( float tx = s0; tx < s1; tx += (float)m_tileSizeU )
{
float tx1 = b3MinFloat( tx + (float)m_tileSizeU, s1 );
for ( int tz = -m_halfWidthU; tz < m_halfWidthU; tz += m_tileSizeU )
{
uint32_t h = Hash( (uint32_t)( (int)tx * 73856093 ) ^ (uint32_t)( tz * 19349663 ) ^
(uint32_t)( chunk * 2654435761u ) );
float cells[3] = { 4.0f, 8.0f, 16.0f };
EmitPatch( vertices, indices, tx, tx1, (float)tz, (float)( tz + m_tileSizeU ), 0.0f, cells[h % 3] );
}
}
}
// --- Beam section: flat tops at y = 0, chamfers dropping to pits ---
float pitTop = -m_chamferDropU;
float pitBottom = -m_pitDepthU;
for ( int k = 0; k < m_beamCount; ++k )
{
float bx = m_beamRegion0 + m_beamPitchU * (float)k;
bool pitLeft = k > 0;
bool pitRight = k < m_beamCount - 1;
// Flat top (flush with the slab on outer sides)
float top0 = pitLeft ? bx + m_chamferWidthU : bx;
float top1 = pitRight ? bx + m_beamWidthU - m_chamferWidthU : bx + m_beamWidthU;
if ( ClipSpan( top0, top1, x0U, x1U, &s0, &s1 ) )
{
EmitPatch( vertices, indices, s0, s1, -(float)m_halfWidthU, (float)m_halfWidthU, 0.0f, 8.0f );
}
// Chamfers sloping below the walkable plane
if ( pitLeft && bx >= x0U && bx < x1U )
{
EmitSlope( vertices, indices, bx, pitTop, bx + m_chamferWidthU, 0.0f, 8.0f );
}
if ( pitRight && bx + m_beamWidthU > x0U && bx + m_beamWidthU <= x1U )
{
EmitSlope( vertices, indices, bx + m_beamWidthU, pitTop, bx + m_beamWidthU - m_chamferWidthU, 0.0f, 8.0f );
}
// Pit to the right of this beam
if ( pitRight )
{
float pitL = bx + m_beamWidthU;
float pitR = bx + m_beamPitchU;
if ( pitL >= x0U && pitL < x1U )
{
EmitWall( vertices, indices, pitL, pitBottom, pitTop, +1, 16.0f );
}
if ( pitR > x0U && pitR <= x1U )
{
EmitWall( vertices, indices, pitR, pitBottom, pitTop, -1, 16.0f );
}
if ( ClipSpan( pitL, pitR, x0U, x1U, &s0, &s1 ) )
{
EmitPatch( vertices, indices, s0, s1, -(float)m_halfWidthU, (float)m_halfWidthU, pitBottom, 16.0f );
}
}
}
b3MeshDef meshDef = {};
meshDef.vertices = vertices.data();
meshDef.indices = indices.data();
meshDef.vertexCount = (int)vertices.size();
meshDef.triangleCount = (int)( indices.size() / 3 );
meshDef.weldVertices = true;
meshDef.weldTolerance = 0.005f; // == B3_LINEAR_SLOP, same as s&box
meshDef.identifyEdges = true;
m_chunkMesh[chunk] = b3CreateMesh( &meshDef, nullptr, 0 );
b3BodyDef bodyDef = b3DefaultBodyDef();
b3BodyId body = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( body, &shapeDef, m_chunkMesh[chunk], b3Vec3_one );
}
void Step() override
{
// Drive the character with pure velocity control: keep the solver's vertical velocity,
// set the horizontal velocity. This is how the s&box player controller moves.
b3Pos position = b3Body_GetPosition( m_characterId );
if ( position.x > m_walkRange )
{
m_walkDirection = -1.0f;
}
else if ( position.x < -m_walkRange )
{
m_walkDirection = 1.0f;
}
b3Vec3 velocity = b3Body_GetLinearVelocity( m_characterId );
velocity.x = m_walkDirection * m_walkSpeed;
velocity.z = 0.0f;
b3Body_SetLinearVelocity( m_characterId, velocity );
Sample::Step();
if ( m_didStep )
{
// The walkable plane is exactly y = 0, so the grounded body center never rises above
// rest height. Any upward velocity spike while grounded is a ghost collision: there
// is nothing to climb and nothing to bounce off.
position = b3Body_GetPosition( m_characterId );
velocity = b3Body_GetLinearVelocity( m_characterId );
bool grounded = position.y < m_bodyHalfHeight + 0.01f + 4.0f * SRC;
bool launched = velocity.y > m_launchThreshold;
if ( grounded && launched && m_wasLaunched == false )
{
m_launchCount += 1;
m_maxLaunchSpeed = b3MaxFloat( m_maxLaunchSpeed, velocity.y );
if ( m_launchMarkerCount < m_markerCapacity )
{
m_launchMarkers[m_launchMarkerCount] = position;
m_launchMarkerCount += 1;
}
}
m_wasLaunched = launched;
}
for ( int i = 0; i < m_launchMarkerCount; ++i )
{
DrawPoint( m_launchMarkers[i], 8.0f, MakeColor( b3_colorRed ) );
}
b3Vec3 currentVelocity = b3Body_GetLinearVelocity( m_characterId );
DrawTextLine( "ghost launches: %d, worst: %.2f m/s (%.0f inch/s)", m_launchCount, m_maxLaunchSpeed,
m_maxLaunchSpeed / SRC );
DrawTextLine( "vertical velocity: %.2f m/s", currentVelocity.y );
}
bool DrawControls() override
{
float speedU = m_walkSpeed / SRC;
if ( ImGui::SliderFloat( "Walk Speed (inch/s)", &speedU, 100.0f, 400.0f, "%.0f" ) )
{
m_walkSpeed = speedU * SRC;
}
if ( ImGui::Button( "Reset Counters" ) )
{
m_launchCount = 0;
m_maxLaunchSpeed = 0.0f;
m_launchMarkerCount = 0;
}
ImGui::Text( "Launches: %d", m_launchCount );
return true;
}
static Sample* Create( SampleContext* context )
{
return new SBoxGhostCollisions( context );
}
static constexpr float m_walkRange = 3.5f; // turn around beyond +/- this x (meters)
static constexpr float m_launchThreshold = 0.5f; // upward m/s counted as a ghost launch (~20 inch/s)
static constexpr int m_markerCapacity = 64;
b3MeshData* m_chunkMesh[2] = {};
b3BodyId m_characterId;
float m_walkDirection;
float m_walkSpeed;
int m_launchCount;
float m_maxLaunchSpeed;
bool m_wasLaunched;
b3Pos m_launchMarkers[m_markerCapacity];
int m_launchMarkerCount;
};
static int sampleSBoxGhostCollisions = RegisterSample( "Issues", "s&box Ghost Collisions", SBoxGhostCollisions::Create );

View file

@ -232,7 +232,7 @@ public:
{
const b3LocalManifoldPoint& manifoldPoint = m_manifold.points[pointIndex];
b3Pos point = b3TransformWorldPoint(m_transformB, manifoldPoint.point );
b3Pos point = b3TransformWorldPoint( m_transformB, manifoldPoint.point );
DrawLine( point, point + length * normal, MakeColor( b3_colorWhite ) );
if ( manifoldPoint.separation > 0.0f )
@ -247,8 +247,8 @@ public:
DrawString3D( point, MakeColor( b3_colorWhite ), " %.2f", 100.0f * manifoldPoint.separation );
b3FeaturePair pair = manifoldPoint.pair;
DrawString3D( point + 0.025f * normal, MakeColor( b3_colorPapayaWhip ), " %X:%X %X:%X", pair.owner1,
pair.index1, pair.owner2, pair.index2 );
DrawString3D( point + 0.025f * normal, MakeColor( b3_colorPapayaWhip ), " %X:%X %X:%X", pair.owner1, pair.index1,
pair.owner2, pair.index2 );
}
}
@ -829,15 +829,23 @@ public:
m_camera->SetView( 0.0f, 30.0f, 3.0f, b3Pos_zero );
}
m_triangle[0] = { 1.00000000, 0, 1.00000000 };
m_triangle[1] = { 1.00000000, 0, 0.00000000 };
m_triangle[2] = { 0.00000000, 0, 0.00000000 };
//m_triangle[0] = { 1.00000000, 0, 1.00000000 };
//m_triangle[1] = { 1.00000000, 0, 0.00000000 };
//m_triangle[2] = { 0.00000000, 0, 0.00000000 };
m_boxHull = b3MakeBoxHull( 0.5f, 0.5f, 0.5f );
m_triangle[0x00000000] = { -1.82879996, -0.0253999997, -0.609600008 };
m_triangle[0x00000001] = { -1.82879996, -0.0253999997, -0.406399995 };
m_triangle[0x00000002] = { -1.79069996, 0.00000000, -0.406399995 };
float SRC = 0.0254f;
float bodyHalfWidth = 16.0f * SRC;
float bodyHalfHeight = 36.0f * SRC;
m_boxHull = b3MakeBoxHull( bodyHalfWidth, bodyHalfHeight, bodyHalfWidth );
m_transformA = b3WorldTransform_identity;
m_transformB = b3WorldTransform_identity;
m_transformB.p = { 0.0f, 0.45f, 0.1f };
m_transformB.p = { -2.16650009f, 0.912535489f, 0.00000000f };
// b3MeshEdgeFlags
m_flags = 0;
@ -911,7 +919,7 @@ public:
};
b3CollideHullAndTriangle( &m_manifold, m_pointCapacity, m_hull, localTriangle[0], localTriangle[1], localTriangle[2],
m_flags, &m_satCache );
m_flags, &m_satCache, true );
}
int m_flags;

View file

@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
// Cascaded shadow map PCF, shared by the lit shape shaders via
// @include. The texture and comparison sampler are passed as parameters
// so this file has no binding declarations of its own.
//
// 7x7 uniform kernel evaluated with 16 bilinear comparison taps. Tap
// positions and weights steer the hardware 2x2 compare so the fetches
// reproduce the full 49-texel kernel with triangle-filtered sub-texel
// placement, a moving shadow edge slides smoothly instead of stepping
// texel by texel. Follows the optimized PCF from The Witness (Ignacio
// Castano), via MJP's shadows sample.
//
// Manually unrolled: the HLSL compiler emits warning X3570 ("gradient
// instruction used in a loop with varying iteration") on looped texture
// calls. Unrolling keeps cross-compilation clean on the D3D11 backend.
float sampleShadowTap( texture2DArray tex, samplerShadow smp, vec2 uv, float layer, float ref_z )
{
return texture( sampler2DArrayShadow( tex, smp ), vec4( uv, layer, ref_z ) );
}
// scale multiplies the tap offsets. Cascades cover different world sizes
// per texel, the caller passes GetCascadePcfScale's texel-size ratio so
// the penumbra keeps a constant world width instead of jumping from
// crisp to blurry at every cascade boundary. 1.0 = the full 7x7 kernel.
float sampleShadowPCF( texture2DArray tex, samplerShadow smp, int cascade, vec3 light_uv, float bias, float scale )
{
// Must match SHADOW_RESOLUTION in shadow.h
const float size = 4096.0;
const float inv_size = 1.0 / size;
float ly = float( cascade );
float rz = light_uv.z - bias;
// Texel-space position split into the nearest texel corner and the
// sub-texel fraction that drives the tap weights.
vec2 tuv = light_uv.xy * size;
vec2 base = floor( tuv + 0.5 );
float s = tuv.x + 0.5 - base.x;
float t = tuv.y + 0.5 - base.y;
base = ( base - 0.5 ) * inv_size;
// Shrinking the offsets bunches the 16 bilinear taps inside a smaller
// footprint. The box property degrades gracefully, at the 0.25 floor
// the taps still span ~2 texels and overlap through the hardware 2x2
// compare, so the response stays smooth.
float step = inv_size * scale;
float uw0 = 5.0 * s - 6.0;
float uw1 = 11.0 * s - 28.0;
float uw2 = -( 11.0 * s + 17.0 );
float uw3 = -( 5.0 * s + 1.0 );
float u0 = ( 4.0 * s - 5.0 ) / uw0 - 3.0;
float u1 = ( 4.0 * s - 16.0 ) / uw1 - 1.0;
float u2 = -( 7.0 * s + 5.0 ) / uw2 + 1.0;
float u3 = -s / uw3 + 3.0;
float vw0 = 5.0 * t - 6.0;
float vw1 = 11.0 * t - 28.0;
float vw2 = -( 11.0 * t + 17.0 );
float vw3 = -( 5.0 * t + 1.0 );
float v0 = ( 4.0 * t - 5.0 ) / vw0 - 3.0;
float v1 = ( 4.0 * t - 16.0 ) / vw1 - 1.0;
float v2 = -( 7.0 * t + 5.0 ) / vw2 + 1.0;
float v3 = -t / vw3 + 3.0;
float sum = 0.0;
sum += uw0 * vw0 * sampleShadowTap( tex, smp, base + vec2( u0, v0 ) * step, ly, rz );
sum += uw1 * vw0 * sampleShadowTap( tex, smp, base + vec2( u1, v0 ) * step, ly, rz );
sum += uw2 * vw0 * sampleShadowTap( tex, smp, base + vec2( u2, v0 ) * step, ly, rz );
sum += uw3 * vw0 * sampleShadowTap( tex, smp, base + vec2( u3, v0 ) * step, ly, rz );
sum += uw0 * vw1 * sampleShadowTap( tex, smp, base + vec2( u0, v1 ) * step, ly, rz );
sum += uw1 * vw1 * sampleShadowTap( tex, smp, base + vec2( u1, v1 ) * step, ly, rz );
sum += uw2 * vw1 * sampleShadowTap( tex, smp, base + vec2( u2, v1 ) * step, ly, rz );
sum += uw3 * vw1 * sampleShadowTap( tex, smp, base + vec2( u3, v1 ) * step, ly, rz );
sum += uw0 * vw2 * sampleShadowTap( tex, smp, base + vec2( u0, v2 ) * step, ly, rz );
sum += uw1 * vw2 * sampleShadowTap( tex, smp, base + vec2( u1, v2 ) * step, ly, rz );
sum += uw2 * vw2 * sampleShadowTap( tex, smp, base + vec2( u2, v2 ) * step, ly, rz );
sum += uw3 * vw2 * sampleShadowTap( tex, smp, base + vec2( u3, v2 ) * step, ly, rz );
sum += uw0 * vw3 * sampleShadowTap( tex, smp, base + vec2( u0, v3 ) * step, ly, rz );
sum += uw1 * vw3 * sampleShadowTap( tex, smp, base + vec2( u1, v3 ) * step, ly, rz );
sum += uw2 * vw3 * sampleShadowTap( tex, smp, base + vec2( u2, v3 ) * step, ly, rz );
sum += uw3 * vw3 * sampleShadowTap( tex, smp, base + vec2( u3, v3 ) * step, ly, rz );
return sum / 2704.0;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,7 @@
Generated by sokol-shdc (https://github.com/floooh/sokol-tools)
Cmdline:
sokol-shdc --input ibl/sky.glsl --output generated/sky.glsl.h --slang hlsl5:metal_macos:glsl430
sokol-shdc --input E:/box/box3d/samples/shaders/ibl/sky.glsl --output E:/box/box3d/samples/shaders/generated/sky.glsl.h --slang hlsl5:metal_macos:glsl430
Overview:
=========

View file

@ -5,7 +5,7 @@
Generated by sokol-shdc (https://github.com/floooh/sokol-tools)
Cmdline:
sokol-shdc --input ibl/sky_to_cube.glsl --output generated/sky_to_cube.glsl.h --slang hlsl5:metal_macos:glsl430
sokol-shdc --input E:/box/box3d/samples/shaders/ibl/sky_to_cube.glsl --output E:/box/box3d/samples/shaders/generated/sky_to_cube.glsl.h --slang hlsl5:metal_macos:glsl430
Overview:
=========

File diff suppressed because it is too large Load diff

View file

@ -142,6 +142,7 @@ layout( binding = 1 ) uniform ub_pass
mat4 view; // for view-space depth debug mode + cascade selection
vec4 cascade_far_view_z; // .xyz = far view-space Z per cascade
mat4 cascade_matrices[3]; // light-space view-proj per cascade
vec4 cascade_pcf_scale; // .xyz = PCF tap-offset scale per cascade (constant world penumbra)
vec4 sh[9]; // IBL diffuse SH coefficients (band 0..2, RGB in .xyz)
vec4 ibl_params; // .x = prefilter cube max_lod, .y = IBL enable (1=IBL, 0=flat ambient), .zw reserved
};
@ -168,26 +169,7 @@ layout( binding = 4 ) uniform texture2D tex_ao;
#pragma sokol @sampler_type smp_ao filtering
layout( binding = 3 ) uniform sampler smp_ao;
// 3x3 PCF over a 1-texel radius. Manually unrolled, see cube.glsl for
// the X3570 rationale.
float sampleShadowPCF( int cascade, vec3 light_uv, float bias )
{
float t = 1.0 / 2048.0;
float ly = float( cascade );
float rz = light_uv.z - bias;
vec2 c = light_uv.xy;
float s = 0.0;
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y + t, ly, rz ) );
return s / 9.0;
}
#pragma sokol @include ../common/shadow_pcf.glsl
float sampleCascade( int cascade, vec3 world_pos, vec3 world_normal )
{
@ -205,7 +187,7 @@ float sampleCascade( int cascade, vec3 world_pos, vec3 world_normal )
float n_dot_l = max( dot( world_normal, normalize( sun_dir_world.xyz ) ), 0.0 );
float bias = mix( 0.0040, 0.0008, n_dot_l );
float pcf = sampleShadowPCF( cascade, light_uv, bias );
float pcf = sampleShadowPCF( tex_shadow, smp_shadow, cascade, light_uv, bias, cascade_pcf_scale[cascade] );
// See cube.glsl for the longer note. Cascade 2 has no fallback at its
// UV boundary, so fade PCF toward 1.0 over the outer 10% to hide the

View file

@ -109,6 +109,7 @@ layout( binding = 1 ) uniform ub_pass
ivec4 flags; // .x = debug_view_mode
vec4 cascade_far_view_z; // .xyz = far view-space Z per cascade
mat4 cascade_matrices[3]; // light-space view-proj per cascade
vec4 cascade_pcf_scale; // .xyz = PCF tap-offset scale per cascade (constant world penumbra)
mat4 view; // IBL: world->view rotation for view->world n_view transform
vec4 camera_pos_world; // IBL: world camera pos for V_world derivation
vec4 sh[9]; // IBL diffuse SH coefficients (band 0..2, RGB in .xyz)
@ -150,31 +151,9 @@ flat in vec4 v_base_color;
flat in vec4 v_material;
out vec4 out_color;
// 3x3 PCF over a 1-texel radius. The comparison sampler returns 0..1
// per tap (0 = occluded, 1 = lit). Uniform 1/9 weighting.
//
// Manually unrolled: the HLSL compiler emits warning X3570 ("gradient
// instruction used in a loop with varying iteration") on the looped
// version because texture uses implicit derivatives. Unrolling here
// keeps cross-compilation clean on the D3D11 backend.
float sampleShadowPCF( int cascade, vec3 light_uv, float bias )
{
float t = 1.0 / 2048.0;
float ly = float( cascade );
float rz = light_uv.z - bias;
vec2 c = light_uv.xy;
float s = 0.0;
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y + t, ly, rz ) );
return s / 9.0;
}
// The comparison sampler returns 0..1 per tap (0 = occluded, 1 = lit).
// Kernel details and the X3570 unrolling note live in the include.
#pragma sokol @include ../common/shadow_pcf.glsl
float sampleCascade( int cascade, vec3 world_pos, float n_dot_l )
{
@ -205,12 +184,12 @@ float sampleCascade( int cascade, vec3 world_pos, float n_dot_l )
float texelDepthStep = 0.001;
float bias = clamp( texelDepthStep * tanAngle, 0.0005, 0.05 );
float pcf = sampleShadowPCF( cascade, light_uv, bias );
float pcf = sampleShadowPCF( tex_shadow, smp_shadow, cascade, light_uv, bias, cascade_pcf_scale[cascade] );
// Cascade 2 is the last cascade, sampleShadowCascaded's view-z blend
// has nothing to blend into beyond it. On flat ground at glancing sun
// angles PCF inside the cascade reads slightly below 1.0 (bias slop
// across a 3x3 kernel that covers ~5 cm of world per texel here), while
// across a kernel that covers ~5 cm of world per texel here), while
// fragments outside the cascade's spatial sphere fall through to the
// OOB return of 1.0. Without smoothing, cascade 2's UV boundary reads
// as a hexagonal polygon on the ground. Fade PCF toward 1.0 over the

View file

@ -112,6 +112,7 @@ layout( binding = 1 ) uniform ub_pass
mat4 view; // for view-space depth debug mode + cascade selection
vec4 cascade_far_view_z; // .xyz = far view-space Z per cascade
mat4 cascade_matrices[3]; // light-space view-proj per cascade
vec4 cascade_pcf_scale; // .xyz = PCF tap-offset scale per cascade (constant world penumbra)
vec4 sh[9]; // IBL diffuse SH coefficients (band 0..2, RGB in .xyz)
vec4 ibl_params; // .x = prefilter cube max_lod, .y = IBL enable (1=IBL, 0=flat ambient), .zw reserved
};
@ -138,26 +139,7 @@ layout( binding = 4 ) uniform texture2D tex_ao;
#pragma sokol @sampler_type smp_ao filtering
layout( binding = 3 ) uniform sampler smp_ao;
// 3x3 PCF over a 1-texel radius. Manually unrolled, see cube.glsl for
// the X3570 rationale.
float sampleShadowPCF( int cascade, vec3 light_uv, float bias )
{
float t = 1.0 / 2048.0;
float ly = float( cascade );
float rz = light_uv.z - bias;
vec2 c = light_uv.xy;
float s = 0.0;
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y + t, ly, rz ) );
return s / 9.0;
}
#pragma sokol @include ../common/shadow_pcf.glsl
float sampleCascade( int cascade, vec3 world_pos, vec3 world_normal )
{
@ -175,7 +157,7 @@ float sampleCascade( int cascade, vec3 world_pos, vec3 world_normal )
float n_dot_l = max( dot( world_normal, normalize( sun_dir_world.xyz ) ), 0.0 );
float bias = mix( 0.0040, 0.0008, n_dot_l );
float pcf = sampleShadowPCF( cascade, light_uv, bias );
float pcf = sampleShadowPCF( tex_shadow, smp_shadow, cascade, light_uv, bias, cascade_pcf_scale[cascade] );
// See cube.glsl for the longer note. Cascade 2 has no fallback at its
// UV boundary, so fade PCF toward 1.0 over the outer 10% to hide the

View file

@ -2,8 +2,9 @@
// SPDX-License-Identifier: MIT
// Shadow caster for capsules. As with the sphere caster, we substitute
// a low-poly proxy mesh for the analytic impostor. The proxy is a
// 12-slice cylinder with two hemispherical caps. Vertices are authored in
// a proxy mesh for the analytic impostor. The proxy is a lat/long cylinder
// with two hemispherical caps (see BuildCapsuleProxy in renderer.c for
// counts and the silhouette-straddling scale). Vertices are authored in
// a "unit-capsule" coordinate frame where each component carries enough
// information to scale independently by halfLength and radius.
//

View file

@ -139,6 +139,7 @@ layout( binding = 1 ) uniform ub_pass
mat4 view; // for view-space depth debug mode + cascade selection
vec4 cascade_far_view_z; // .xyz = far view-space Z per cascade
mat4 cascade_matrices[3]; // light-space view-proj per cascade
vec4 cascade_pcf_scale; // .xyz = PCF tap-offset scale per cascade (constant world penumbra)
vec4 sh[9]; // IBL diffuse SH coefficients (band 0..2, RGB in .xyz)
vec4 ibl_params; // .x = prefilter cube max_lod, .y = IBL enable (1=IBL, 0=flat ambient), .zw reserved
};
@ -165,26 +166,7 @@ layout( binding = 4 ) uniform texture2D tex_ao;
#pragma sokol @sampler_type smp_ao filtering
layout( binding = 3 ) uniform sampler smp_ao;
// 3x3 PCF over a 1-texel radius. Manually unrolled, see cube.glsl for
// the X3570 rationale.
float sampleShadowPCF( int cascade, vec3 light_uv, float bias )
{
float t = 1.0 / 2048.0;
float ly = float( cascade );
float rz = light_uv.z - bias;
vec2 c = light_uv.xy;
float s = 0.0;
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y - t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x - t, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x, c.y + t, ly, rz ) );
s += texture( sampler2DArrayShadow( tex_shadow, smp_shadow ), vec4( c.x + t, c.y + t, ly, rz ) );
return s / 9.0;
}
#pragma sokol @include ../common/shadow_pcf.glsl
float sampleCascade( int cascade, vec3 world_pos, vec3 world_normal )
{
@ -202,7 +184,7 @@ float sampleCascade( int cascade, vec3 world_pos, vec3 world_normal )
float n_dot_l = max( dot( world_normal, normalize( sun_dir_world.xyz ) ), 0.0 );
float bias = mix( 0.0040, 0.0008, n_dot_l );
float pcf = sampleShadowPCF( cascade, light_uv, bias );
float pcf = sampleShadowPCF( tex_shadow, smp_shadow, cascade, light_uv, bias, cascade_pcf_scale[cascade] );
// See cube.glsl for the longer note. Cascade 2 has no fallback at its
// UV boundary, so fade PCF toward 1.0 over the outer 10% to hide the

View file

@ -102,7 +102,7 @@ void CreateLargePyramid( b3WorldId worldId )
{
b3World_EnableSleeping( worldId, false );
int baseCount = BENCHMARK_DEBUG ? 20 : 90;
int baseCount = BENCHMARK_DEBUG ? 20 : 100;
{
b3BodyDef bodyDef = b3DefaultBodyDef();

View file

@ -248,6 +248,11 @@ void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int chil
contact->flags |= b3_contactEnableContactEvents;
}
if ( ( shapeA->flags & b3_enableSpeculative ) && ( shapeB->flags & b3_enableSpeculative ) )
{
contact->flags |= b3_enableSpeculativePoints;
}
// Connect to body A
{
contact->edges[0].bodyId = shapeA->bodyId;

View file

@ -65,8 +65,11 @@ enum b3ContactFlags
// This is a mesh contact
b3_simMeshContact = 0x00400000,
// Relative transform is cached for contact recycling
b3_relativeTransformValid = 0x00800000,
// Enable speculative contact points
b3_enableSpeculativePoints = 0x01000000,
};
// A contact edge is used to connect bodies and contacts together

View file

@ -561,6 +561,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
// It leads to a small visual gap but seems to improve the quality of mesh
// collision, especially for hull versus mesh.
float restOffset = B3_MESH_REST_OFFSET;
bool enableSpeculative = contact->flags & b3_enableSpeculativePoints;
// Make room for clip points
int pointBufferCapacity = B3_MAX_POINTS_PER_TRIANGLE * triangleCount;
@ -618,8 +619,8 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
cache->satCache = (b3SATCache){ 0 };
}
b3CollideHullAndTriangle( manifold, pointCapacity, hullB, vertices[0], vertices[1], vertices[2],
triangle.flags, &cache->satCache );
b3CollideHullAndTriangle( manifold, pointCapacity, hullB, vertices[0], vertices[1], vertices[2], triangle.flags,
&cache->satCache, enableSpeculative );
context->satCallCount += 1;
context->satCacheHitCount += cache->satCache.hit;
break;

View file

@ -31,18 +31,24 @@ static inline void b3AtomicStoreInt( b3AtomicInt* a, int value )
#elif defined( __GNUC__ ) || defined( __clang__ )
__atomic_store_n( &a->value, value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
static inline int b3AtomicLoadInt( b3AtomicInt* a )
{
#if defined( _MSC_VER )
return _InterlockedOr( (long*)&a->value, 0 );
#if defined( _MSC_VER ) && !defined( __clang__ )
int value = __iso_volatile_load32( (volatile __int32*)&a->value );
#if defined( _M_ARM ) || defined( _M_ARM64 ) || defined( _M_ARM64EC )
__dmb( 0xB );
#else
_ReadWriteBarrier();
#endif
return value;
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_load_n( &a->value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
@ -53,7 +59,7 @@ static inline int b3AtomicFetchAddInt( b3AtomicInt* a, int increment )
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_fetch_add( &a->value, increment, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
@ -65,7 +71,7 @@ static inline bool b3AtomicCompareExchangeInt( b3AtomicInt* a, int expected, int
// The value written to expected is ignored
return __atomic_compare_exchange_n( &a->value, &expected, desired, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
@ -76,17 +82,23 @@ static inline void b3AtomicStoreU32( b3AtomicU32* a, uint32_t value )
#elif defined( __GNUC__ ) || defined( __clang__ )
__atomic_store_n( &a->value, value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}
static inline uint32_t b3AtomicLoadU32( b3AtomicU32* a )
{
#if defined( _MSC_VER )
return (uint32_t)_InterlockedOr( (long*)&a->value, 0 );
#if defined( _MSC_VER ) && !defined( __clang__ )
uint32_t value = (uint32_t)__iso_volatile_load32( (volatile __int32*)&a->value );
#if defined( _M_ARM ) || defined( _M_ARM64 ) || defined( _M_ARM64EC )
__dmb( 0xB );
#else
_ReadWriteBarrier();
#endif
return value;
#elif defined( __GNUC__ ) || defined( __clang__ )
return __atomic_load_n( &a->value, __ATOMIC_SEQ_CST );
#else
#error "Unsupported platform"
#error "Unsupported platform"
#endif
}

View file

@ -399,6 +399,7 @@ void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v )
b3RecW_BOOL( buf, v.enablePreSolveEvents );
b3RecW_BOOL( buf, v.invokeContactCreation );
b3RecW_BOOL( buf, v.updateBodyMass );
b3RecW_BOOL( buf, v.enableSpeculativeContact );
// internalValue omitted
}

View file

@ -46,8 +46,8 @@ typedef struct b3World b3World;
#define B3_REC_MAGIC 0x43523342u
// Major recording version is bumped when writers change.
// Major version 3 added shape names.
#define B3_REC_VERSION_MAJOR 3
// Major version 4 added b3ShapeDef::enableSpeculativeContact
#define B3_REC_VERSION_MAJOR 4
// Minor tracks op-stream additions that keep the 48 byte header shape.
// Minor version 3 added name cache.

View file

@ -483,6 +483,7 @@ b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr )
def.enablePreSolveEvents = b3RecR_BOOL( rdr );
def.invokeContactCreation = b3RecR_BOOL( rdr );
def.updateBodyMass = b3RecR_BOOL( rdr );
def.enableSpeculativeContact = b3RecR_BOOL( rdr );
def.userData = NULL;
return def;
}

View file

@ -181,6 +181,7 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->flags |= def->enableCustomFiltering ? b3_enableCustomFiltering : 0;
shape->flags |= def->enableHitEvents ? b3_enableHitEvents : 0;
shape->flags |= def->enablePreSolveEvents ? b3_enablePreSolveEvents : 0;
shape->flags |= def->enableSpeculativeContact ? b3_enableSpeculative : 0;
shape->proxyKey = B3_NULL_INDEX;
shape->localCentroid = b3GetShapeCentroid( shape );
shape->aabbMargin = b3ComputeShapeMargin( shape );

View file

@ -20,6 +20,7 @@ typedef enum b3ShapeFlags
b3_enableHitEvents = 0x08,
b3_enablePreSolveEvents = 0x10,
b3_enlargedAABB = 0x20,
b3_enableSpeculative = 0x40,
} b3ShapeFlags;
typedef struct b3Shape

View file

@ -595,8 +595,8 @@ static b3EdgeQuery b3TestEdgePairs( const b3TriangleData* triangle, const b3Hull
return result;
}
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle, const b3HullData* hull,
b3FaceQuery query, b3SATCache* cache )
static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle,
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache, bool enableSpeculative )
{
manifold->pointCount = 0;
@ -663,23 +663,31 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
pointCount = b3MinInt( pointCount, pointCapacity );
float minSeparation = FLT_MAX;
int finalPointCount = 0;
for ( int i = 0; i < pointCount; ++i )
{
b3ClipVertex* clipPoint = input + i;
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
if ( enableSpeculative == false && clipPoint->separation > 0.0f )
{
continue;
}
// Move point onto hull face improved culling
b3Vec3 point = b3MulSub( clipPoint->position, clipPoint->separation, refPlane.normal );
b3LocalManifoldPoint* pt = manifold->points + i;
b3LocalManifoldPoint* pt = manifold->points + finalPointCount;
pt->point = point;
pt->separation = clipPoint->separation;
pt->pair = b3FlipPair( clipPoint->pair );
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
finalPointCount += 1;
}
if ( minSeparation > B3_SPECULATIVE_DISTANCE )
float speculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : 0.0f;
if ( minSeparation > speculativeDistance )
{
// This can occur with a stale SAT cache
manifold->pointCount = 0;
@ -687,7 +695,7 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
return minSeparation;
}
manifold->pointCount = pointCount;
manifold->pointCount = finalPointCount;
manifold->normal = b3Neg( refPlane.normal );
manifold->feature = b3_featureHullFace;
@ -700,7 +708,7 @@ static float b3CollideHullFace( b3LocalManifold* manifold, int pointCapacity, co
}
static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity, const b3TriangleData* triangle,
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache )
const b3HullData* hull, b3FaceQuery query, b3SATCache* cache, bool enableSpeculative )
{
B3_VALIDATE( manifold->pointCount == 0 );
@ -770,30 +778,38 @@ static float b3CollideTriangleFace( b3LocalManifold* manifold, int pointCapacity
float minSeparation = FLT_MAX;
int finalPointCount = 0;
for ( int i = 0; i < pointCount; ++i )
{
b3ClipVertex* clipPoint = input + i;
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
if ( enableSpeculative == false && clipPoint->separation > 0.0f )
{
continue;
}
// Move point onto triangle surface for improved culling
// b3Vec3 point = b3MulSub( clipPoint->position, clipPoint->separation, refPlane.normal );
b3Vec3 point = clipPoint->position;
b3LocalManifoldPoint* pt = manifold->points + i;
b3LocalManifoldPoint* pt = manifold->points + finalPointCount;
pt->point = point;
pt->separation = clipPoint->separation;
pt->pair = clipPoint->pair;
minSeparation = b3MinFloat( minSeparation, clipPoint->separation );
finalPointCount += 1;
}
if ( minSeparation >= B3_SPECULATIVE_DISTANCE )
float speculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : 0.0f;
if ( minSeparation >= speculativeDistance )
{
// This can happens if the objects move a part while re-using a cached axis
*cache = (b3SATCache){ 0 };
return minSeparation;
}
manifold->pointCount = pointCount;
manifold->pointCount = finalPointCount;
manifold->normal = refPlane.normal;
manifold->feature = b3_featureTriangleFace;
@ -853,7 +869,8 @@ static void b3CollideHullAndTriangleEdges( b3LocalManifold* manifold, int capaci
b3SegmentDistanceResult result = b3LineDistance( pA, eA, pB, eB );
// Is one of the closest points outside of the associated edge segment?
if ( capacity == 0 || result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f || 1.0f < result.fraction2 )
if ( capacity == 0 || result.fraction1 < 0.0f || 1.0f < result.fraction1 || result.fraction2 < 0.0f ||
1.0f < result.fraction2 )
{
// Invalid edge pair, no points generated
B3_ASSERT( manifold->pointCount == 0 );
@ -901,7 +918,7 @@ b3AtomicInt b3_triangleCacheHits;
// Computes the manifold in the local space of the hull
void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3HullData* hullA, b3Vec3 v1, b3Vec3 v2, b3Vec3 v3,
int triangleFlags, b3SATCache* cache )
int triangleFlags, b3SATCache* cache, bool enableSpeculative )
{
manifold->pointCount = 0;
manifold->feature = b3_featureNone;
@ -954,7 +971,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
const b3Plane* hullPlanes = b3GetHullPlanes( hullA );
const b3Vec3* hullPoints = b3GetHullPoints( hullA );
float speculativeDistance = B3_SPECULATIVE_DISTANCE;
float speculativeDistance = enableSpeculative ? B3_SPECULATIVE_DISTANCE : 0.0f;
cache->hit = 1;
// Attempt to use the cache to speed up collision
@ -967,7 +984,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
int vertexIndex = b3FindHullSupportVertex( hullA, b3Neg( trianglePlane.normal ) );
b3Vec3 support = hullPoints[vertexIndex];
float separation = b3PlaneSeparation( trianglePlane, support );
if ( separation >= speculativeDistance )
if ( separation > speculativeDistance )
{
// Cache hit, shapes are separated
return;
@ -980,7 +997,8 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
// Read cache but don't modify it
b3SATCache localCache = *cache;
float clippedSeparation = b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache );
float clippedSeparation =
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache, enableSpeculative );
if ( manifold->pointCount > 0 && b3AbsFloat( cache->separation - clippedSeparation ) < linearSlop )
{
@ -1017,7 +1035,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
// Separation of triangle support point with hull plane
float separation = b3PlaneSeparation( plane, support );
if ( separation >= speculativeDistance )
if ( separation > speculativeDistance )
{
// Cache hit, shapes are separated
return;
@ -1038,7 +1056,8 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
// Read cache but don't modify it
b3SATCache localCache = *cache;
float clippedSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache );
float clippedSeparation =
b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQuery, &localCache, enableSpeculative );
// Cache reuse is only successful if it creates contact points and the clipped separation didn't change much.
if ( manifold->pointCount > 0 && b3AbsFloat( cache->separation - clippedSeparation ) < linearSlop )
@ -1116,7 +1135,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
case b3_manualFaceAxisA:
{
b3FaceQuery faceQueryA = b3QueryTriangleFace( &triangle, hullA );
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache );
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache, enableSpeculative );
return;
}
@ -1124,7 +1143,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
case b3_manualFaceAxisB:
{
b3FaceQuery faceQueryB = b3QueryHullFace( &triangle, hullA );
b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache );
b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache, enableSpeculative );
return;
}
@ -1186,16 +1205,19 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
float clippedFaceSeparation;
// Don't allow a hull face opposed to the triangle face.
// Don't admit a hull face significantly opposed to the triangle face.
// Need a tolerance to avoid ghost collisions.
// todo hull query skips faces that point along the triangle normal
b3Vec3 hullNormal = hullPlanes[faceQueryB.faceIndex].normal;
bool pushingUp = b3Dot( hullNormal, trianglePlane.normal ) < 0.0f;
if ( faceQueryB.separation > faceQueryA.separation + linearSlop && pushingUp )
bool pushingDown = b3Dot( hullNormal, trianglePlane.normal ) > 0.25f;
if ( faceQueryB.separation > faceQueryA.separation + linearSlop && pushingDown == false )
{
clippedFaceSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache );
clippedFaceSeparation = b3CollideHullFace( manifold, capacity, &triangle, hullA, faceQueryB, cache, enableSpeculative );
}
else
{
clippedFaceSeparation = b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache );
clippedFaceSeparation =
b3CollideTriangleFace( manifold, capacity, &triangle, hullA, faceQueryA, cache, enableSpeculative );
}
// Does an edge axis exist?

View file

@ -75,6 +75,7 @@ b3ShapeDef b3DefaultShapeDef( void )
def.filter = b3DefaultFilter();
def.updateBodyMass = true;
def.invokeContactCreation = true;
def.enableSpeculativeContact = true;
def.internalValue = B3_SECRET_COOKIE;
return def;
}