Replay fixes (#17)

Fixes to work with our game.
Replay fixes and improvements.
Removed shape names (save memory).
B3_DEFAULT_CATEGORY_BITS  is now UINT64_MAX to make selection easier.
This commit is contained in:
Erin Catto 2026-06-26 21:10:10 -07:00 • committed by GitHub
commit 0c8ef46931
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
51 changed files with 5653 additions and 3853 deletions

View file

@ -107,8 +107,8 @@ typedef struct
MaterialOverride materialOverrides[BOX3D_MATERIAL_OVERRIDE_CAPACITY];
int materialOverrideCount;
b3BodyId hoveredBodyId;
b3BodyId selectedBodyId;
b3ShapeId selectedShapeId;
// Function pointers, drawingBounds, and context inside this struct are NOT used.
// Only used for settings
@ -141,8 +141,8 @@ void InitAdapter( void )
s_adapter.allocCount = 0;
s_adapter.groundShapeId = b3_nullShapeId;
s_adapter.materialOverrideCount = 0;
s_adapter.hoveredBodyId = b3_nullBodyId;
s_adapter.selectedBodyId = b3_nullBodyId;
s_adapter.selectedShapeId = b3_nullShapeId;
s_adapter.transparentDynamic = false;
s_adapter.guiDraw = b3DefaultDebugDraw();
@ -169,8 +169,8 @@ void ResetAdapterPool( void )
s_adapter.groundShapeId = b3_nullShapeId;
s_adapter.materialOverrideCount = 0;
s_adapter.hoveredBodyId = b3_nullBodyId;
s_adapter.selectedBodyId = b3_nullBodyId;
s_adapter.selectedShapeId = b3_nullShapeId;
s_adapter.transparentDynamic = false;
}
@ -245,24 +245,22 @@ int GetDebugShapeCount( void )
return s_adapter.allocCount;
}
void SetHoveredBody( b3BodyId bodyId )
{
s_adapter.hoveredBodyId = b3Body_IsValid( bodyId ) ? bodyId : b3_nullBodyId;
}
b3BodyId GetHoveredBody( void )
{
return s_adapter.hoveredBodyId;
}
void SetSelectedBody( b3BodyId bodyId )
{
s_adapter.selectedBodyId = b3Body_IsValid( bodyId ) ? bodyId : b3_nullBodyId;
s_adapter.selectedShapeId = b3_nullShapeId;
}
void SetSelectedShape( b3ShapeId shapeId )
{
s_adapter.selectedShapeId = b3Shape_IsValid( shapeId ) ? shapeId : b3_nullShapeId;
s_adapter.selectedBodyId = b3_nullBodyId;
}
void ClearSelection( void )
{
s_adapter.selectedBodyId = b3_nullBodyId;
s_adapter.selectedShapeId = b3_nullShapeId;
}
b3BodyId GetSelectedBody( void )
@ -280,19 +278,19 @@ bool IsBodySelected( b3BodyId bodyId )
return B3_ID_EQUALS( s_adapter.selectedBodyId, bodyId );
}
static HighlightKind ResolveHighlightKind( b3BodyId bodyId )
static bool IsShapeSelected( b3ShapeId shapeId )
{
if ( IsBodySelected( bodyId ) )
if ( B3_IS_NULL( s_adapter.selectedShapeId ) )
{
return HIGHLIGHT_KIND_SELECT;
return false;
}
if ( B3_ID_EQUALS( bodyId, s_adapter.hoveredBodyId ) )
{
return HIGHLIGHT_KIND_HOVER;
}
return B3_ID_EQUALS( s_adapter.selectedShapeId, shapeId );
}
return HIGHLIGHT_KIND_NONE;
static HighlightKind ResolveHighlightKind( b3BodyId bodyId, b3ShapeId shapeId )
{
return ( IsShapeSelected( shapeId ) || IsBodySelected( bodyId ) ) ? HIGHLIGHT_KIND_SELECT : HIGHLIGHT_KIND_NONE;
}
static int AllocDebugShape( void )
@ -698,9 +696,9 @@ static void AppendResolvedShape( const DebugShape* us, b3Transform baseTransform
MeshMaterialMode mode = us->isGround ? MESH_MATERIAL_MODE_GROUND_GRID : MESH_MATERIAL_MODE_SOLID;
float cell = us->isGround ? BOX3D_GROUND_GRID_CELL_SIZE : 0.0f;
AppendMesh( us->geom.handle, baseTransform, us->geom.scale, c, metallic, roughness, mode, cell, shadowCast );
if ( hk != HIGHLIGHT_KIND_NONE && us->kind == Box3DUS_Hull )
if ( hk != HIGHLIGHT_KIND_NONE )
{
AppendHighlightHull( us->geom.handle, baseTransform, us->geom.scale, hk );
AppendHighlightGeometry( us->geom.handle, baseTransform, us->geom.scale, hk );
}
}
}
@ -756,9 +754,9 @@ static bool DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexCo
TransparentShadowCast shadowCast = TRANSPARENT_SHADOW_NONE;
// Resolve hover/select state once. Body-keyed, so every supported shape on
// a hovered/selected body outlines together, compound children included.
HighlightKind hk = ResolveHighlightKind( us->bodyId );
// Resolve selection state once. A selected shape outlines alone, a selected
// body outlines all its shapes, compound children included.
HighlightKind hk = ResolveHighlightKind( us->bodyId, us->shapeId );
if ( us->kind == Box3DUS_Compound )
{
@ -819,6 +817,28 @@ static void DrawSphereFcn( b3Pos p, float radius, b3HexColor color, float alpha,
DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_NONE );
}
static void DrawCapsuleFcn( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, void* context )
{
(void)context;
b3Vec3 e = b3SubPos(p2, p1);
float length = b3Length( e );
if (length < FLT_EPSILON)
{
DrawSphereEx( (b3WorldTransform){ p1, b3Quat_identity }, radius, HexColorAToVec4( color, alpha ), DEFAULT_METALLIC,
DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_NONE );
return;
}
b3Vec3 en = b3MulSV( 1.0f / length, e );
b3WorldTransform transform;
transform.p = b3OffsetPos( p1, b3MulSV( 0.5f, e ));
transform.q = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisX, en );
DrawCapsuleEx( transform, 0.5f * length, radius, HexColorAToVec4( color, alpha ), DEFAULT_METALLIC,
DEFAULT_ROUGHNESS, TRANSPARENT_SHADOW_NONE );
}
static void DrawBoundsFcn( b3AABB aabb, b3HexColor color, void* context )
{
(void)context;
@ -935,6 +955,7 @@ void MakeDebugDraw( b3DebugDraw* out )
out->DrawTransformFcn = DrawTransformFcn;
out->DrawPointFcn = DrawPointFcn;
out->DrawSphereFcn = DrawSphereFcn;
out->DrawCapsuleFcn = DrawCapsuleFcn;
out->DrawBoundsFcn = DrawBoundsFcn;
out->DrawBoxFcn = DrawBoxFcn;
out->DrawStringFcn = DrawStringFcn;

View file

@ -37,10 +37,8 @@ void SetShapeMaterial( b3ShapeId shapeId, Vec4 color, float metallic, float roug
void SetTransparentDynamic( bool enabled );
bool GetTransparentDynamic( void );
void SetHoveredBody( b3BodyId bodyId );
b3BodyId GetHoveredBody( void );
void SetSelectedBody( b3BodyId bodyId );
void SetSelectedShape( b3ShapeId shapeId );
void ClearSelection( void );
b3BodyId GetSelectedBody( void );
bool IsBodySelected( b3BodyId bodyId );

View file

@ -50,7 +50,7 @@ void DrawSphereEx( b3WorldTransform transform, float radius, Vec4 baseColor, flo
// axis becomes the world long axis, rotation about local +X drives the
// cylinder/cap surface pattern so roll is visible) and the center
// (translation). halfLength is the distance from center to either cap
// center along local +X. radius is the cap radius.
// center along local +X.
void DrawCapsule( b3WorldTransform transform, float halfLength, float radius, Vec4 baseColor );
void DrawCapsuleEx( b3WorldTransform transform, float halfLength, float radius, Vec4 baseColor, float metallic, float roughness,
TransparentShadowCast shadowCast );

View file

@ -222,7 +222,7 @@ MeshHandle RegisterMesh( uint32_t hash, const MeshVertex* vertices, int vertexCo
vbDesc.data.ptr = vertices;
vbDesc.data.size = (size_t)vertexCount * sizeof( MeshVertex );
vbDesc.label = debugLabel ? debugLabel : "geom_vbo";
e->vbo = sg_make_buffer( &vbDesc );
sg_buffer vbo = sg_make_buffer( &vbDesc );
sg_buffer_desc ibDesc = { 0 };
ibDesc.usage.index_buffer = true;
@ -230,8 +230,20 @@ MeshHandle RegisterMesh( uint32_t hash, const MeshVertex* vertices, int vertexCo
ibDesc.data.ptr = indices;
ibDesc.data.size = (size_t)indexCount * sizeof( uint32_t );
ibDesc.label = debugLabel ? debugLabel : "geom_ibo";
e->ibo = sg_make_buffer( &ibDesc );
sg_buffer ibo = sg_make_buffer( &ibDesc );
// A full GPU buffer pool returns an invalid handle. Bail before committing
// the slot so a huge recording drops geometry instead of crashing. The
// slot stays free (refCount 0) for the next caller.
if ( sg_query_buffer_state( vbo ) != SG_RESOURCESTATE_VALID || sg_query_buffer_state( ibo ) != SG_RESOURCESTATE_VALID )
{
sg_destroy_buffer( ibo );
sg_destroy_buffer( vbo );
return InvalidMeshHandle();
}
e->vbo = vbo;
e->ibo = ibo;
e->hash = hash;
e->refCount = 1;
e->indexCount = indexCount;
@ -272,13 +284,30 @@ void RegisterMeshEdges( MeshHandle h, const EdgeVertex* edges, int edgeCount, co
bdesc.data.ptr = edges;
bdesc.data.size = (size_t)( 2 * edgeCount ) * sizeof( EdgeVertex );
bdesc.label = debugLabel ? debugLabel : "geom_edges";
e->edgeBuf = sg_make_buffer( &bdesc );
sg_buffer edgeBuf = sg_make_buffer( &bdesc );
// On a full pool the edge buffer is invalid. Passing it to sg_make_view
// trips a sokol assert (no active view type), so skip the overlay and let
// the shape draw without edges.
if ( sg_query_buffer_state( edgeBuf ) != SG_RESOURCESTATE_VALID )
{
sg_destroy_buffer( edgeBuf );
return;
}
sg_view_desc vdesc = { 0 };
vdesc.storage_buffer.buffer = e->edgeBuf;
vdesc.storage_buffer.buffer = edgeBuf;
vdesc.label = debugLabel ? debugLabel : "geom_edges_view";
e->edgeStorageView = sg_make_view( &vdesc );
sg_view edgeView = sg_make_view( &vdesc );
if ( sg_query_view_state( edgeView ) != SG_RESOURCESTATE_VALID )
{
sg_destroy_view( edgeView );
sg_destroy_buffer( edgeBuf );
return;
}
e->edgeBuf = edgeBuf;
e->edgeStorageView = edgeView;
e->edgeCount = edgeCount;
}

View file

@ -92,7 +92,12 @@ void HighlightMaskInit( void )
sphPdesc.colors[0].pixel_format = SG_PIXELFORMAT_R8;
sphPdesc.color_count = 1;
sphPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
sphPdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
// Mask the full unoccluded projection, not the visible silhouette. A large
// shape occluded by many others (the ground box) would otherwise punch a
// hole per occluder and the outline would ring every one of them. Drawing
// the whole projection leaves only the true outer contour. The outline is
// no longer occlusion aware as a result.
sphPdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
sphPdesc.depth.write_enabled = false;
// Impostor convention: front-face cull on the proxy box, so the
// analytic intersection is rasterized from the back faces and remains
@ -128,7 +133,7 @@ void HighlightMaskInit( void )
capPdesc.colors[0].pixel_format = SG_PIXELFORMAT_R8;
capPdesc.color_count = 1;
capPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
capPdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
capPdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
capPdesc.depth.write_enabled = false;
capPdesc.cull_mode = SG_CULLMODE_FRONT;
capPdesc.face_winding = SG_FACEWINDING_CCW;
@ -165,7 +170,7 @@ void HighlightMaskInit( void )
hullPdesc.colors[0].pixel_format = SG_PIXELFORMAT_R8;
hullPdesc.color_count = 1;
hullPdesc.depth.pixel_format = SG_PIXELFORMAT_DEPTH;
hullPdesc.depth.compare = SG_COMPAREFUNC_GREATER_EQUAL;
hullPdesc.depth.compare = SG_COMPAREFUNC_ALWAYS;
hullPdesc.depth.write_enabled = false;
hullPdesc.cull_mode = SG_CULLMODE_BACK;
hullPdesc.face_winding = SG_FACEWINDING_CCW;
@ -258,7 +263,7 @@ void AppendHighlightCapsule( b3Transform transform, float halfLength, float radi
inst->params = MakeVec4( halfLength, radius, (float)kind, 0.0f );
}
void AppendHighlightHull( MeshHandle handle, b3Transform transform, b3Vec3 scale, HighlightKind kind )
void AppendHighlightGeometry( MeshHandle handle, b3Transform transform, b3Vec3 scale, HighlightKind kind )
{
if ( kind == HIGHLIGHT_KIND_NONE )
return;

View file

@ -7,8 +7,9 @@
// outline post-pass then reads the mask and composites silhouette colors
// over the resolved scene.
//
// Restricted to spheres, capsules, and hulls by design, meshes and
// heightfields look poor outlined and aren't worth the pipeline weight.
// Covers spheres, capsules, and any registered geometry (hull, mesh,
// height field). The geometry path is occlusion unaware, so a large
// selected shape outlines its whole projected footprint.
//
// Encodes one of three states per pixel as the kind value passed in:
// 1 = hover -> R8 UNORM 0.5
@ -53,10 +54,11 @@ void AppendHighlightSphere( b3Transform transform, float radius, HighlightKind k
// world-space scalars. Logs + drops on overflow.
void AppendHighlightCapsule( b3Transform transform, float halfLength, float radius, HighlightKind kind );
// Append a highlighted hull. handle resolves to a registered geometry
// (vbo/ibo). transform + scale match AppendMesh, rotation matters because
// hulls aren't rotationally symmetric. Logs + drops on overflow.
void AppendHighlightHull( MeshHandle handle, b3Transform transform, b3Vec3 scale, HighlightKind kind );
// Append highlighted geometry (hull, mesh, or height field). handle resolves
// to a registered geometry (vbo/ibo). transform + scale match AppendMesh,
// rotation matters because the geometry isn't rotationally symmetric. Logs +
// drops on overflow.
void AppendHighlightGeometry( MeshHandle handle, b3Transform transform, b3Vec3 scale, HighlightKind kind );
// True when at least one shape was submitted this frame. Lets the caller
// skip mask + outline passes entirely on the common empty case.

View file

@ -100,6 +100,10 @@ static struct
// by RebuildImageBasedLightingIfDirty after a successful rebuild.
bool dirty;
bool ready;
// Up axis the cube and SH were last baked for. A change reorients the
// sky, so it forces a rebuild even when sun and turbidity hold.
bool zUp;
} s_ibl;
// CPU Preetham (mirror of common/preetham.glsl)
@ -108,6 +112,13 @@ static struct
// from the shader. Comments are deliberately spare to avoid two sources
// of truth, read preetham.glsl for the rationale.
// Rotate a sky direction into the model's Y-up frame, mirror of
// preethamToYUp in common/preetham.glsl.
static b3Vec3 SkyDirToYUpC( b3Vec3 v, bool zUp )
{
return zUp ? ( b3Vec3 ){ v.x, v.z, -v.y } : v;
}
static float PreethamPerezC( float cos_theta, float cos_gamma, float gamma, float A, float B, float C, float D, float E )
{
const float ct = ( cos_theta < 0.01f ) ? 0.01f : cos_theta;
@ -116,11 +127,14 @@ static float PreethamPerezC( float cos_theta, float cos_gamma, float gamma, floa
return term1 * term2;
}
static b3Vec3 PreethamSkyScaledC( b3Vec3 view_dir, b3Vec3 sun_dir, float turbidity, float fade )
static b3Vec3 PreethamSkyScaledC( b3Vec3 view_dir, b3Vec3 sun_dir, float turbidity, float fade, bool zUp )
{
const float PI = 3.14159265358979323846f;
const float LUMINANCE_SCALE = 0.06f; // mirrors PREETHAM_LUMINANCE_SCALE
view_dir = SkyDirToYUpC( view_dir, zUp );
sun_dir = SkyDirToYUpC( sun_dir, zUp );
const float sun_y_clamped = ( sun_dir.y < 0.0f ) ? 0.0f : ( sun_dir.y > 1.0f ) ? 1.0f : sun_dir.y;
b3Vec3 view_clamped;
@ -233,7 +247,7 @@ static float cubeTexelSolidAngle( float u, float v, int n )
// accumulating sum L(omega) * Y_i(omega) * domega, then multiplying by the Funk-Hecke
// diffuse convolution weights so the shader's evaluation is a straight
// dot product against the SH basis.
static void ProjectSkyToSh( b3Vec3 dirToSun, float turbidity, float fade )
static void ProjectSkyToSh( b3Vec3 dirToSun, float turbidity, float fade, bool zUp )
{
b3Vec3 coef[9];
for ( int i = 0; i < 9; ++i )
@ -267,7 +281,10 @@ static void ProjectSkyToSh( b3Vec3 dirToSun, float turbidity, float fade )
}
const float dW = cubeTexelSolidAngle( u, v, N );
const b3Vec3 L = PreethamSkyScaledC( dir, dirToSun, turbidity, fade );
// dir stays in sim space, it indexes the SH basis below which
// the lit shader evaluates at a sim-space normal. Only the
// Preetham color lookup rotates into the model's Y-up frame.
const b3Vec3 L = PreethamSkyScaledC( dir, dirToSun, turbidity, fade, zUp );
const float x = dir.x;
const float y = dir.y;
@ -340,7 +357,7 @@ static void GenerateBrdfLut( void )
sg_pop_debug_group();
}
static void GenerateSkyCube( b3Vec3 dirToSun, float turbidity, float fade )
static void GenerateSkyCube( b3Vec3 dirToSun, float turbidity, float fade, bool zUp )
{
// Six passes, one per face. Each pass fills the raw cube's
// corresponding face via a fullscreen-triangle Preetham eval.
@ -358,7 +375,7 @@ static void GenerateSkyCube( b3Vec3 dirToSun, float turbidity, float fade )
const CubeFaceBasis b = s_cubeFaceBasis[face];
sky_to_cube_ub_face_t up = { 0 };
up.face_right = MakeVec4( b.right.x, b.right.y, b.right.z, 0.0f );
up.face_up = MakeVec4( b.up.x, b.up.y, b.up.z, 0.0f );
up.face_up = MakeVec4( b.up.x, b.up.y, b.up.z, zUp ? 1.0f : 0.0f );
up.face_forward = MakeVec4( b.forward.x, b.forward.y, b.forward.z, fade );
up.sun_dir_world = MakeVec4( dirToSun.x, dirToSun.y, dirToSun.z, turbidity );
sg_apply_uniforms( UB_sky_to_cube_ub_face, &SG_RANGE( up ) );
@ -610,8 +627,16 @@ void MarkIblDirty( void )
s_ibl.dirty = true;
}
void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity )
void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity, bool zUp )
{
// A changed up axis reorients the baked sky, so treat it like a sun or
// turbidity change and force a rebuild.
if ( zUp != s_ibl.zUp )
{
s_ibl.zUp = zUp;
s_ibl.dirty = true;
}
if ( s_ibl.dirty == false || s_ibl.ready == false )
{
return;
@ -620,13 +645,13 @@ void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity )
// Renormalize just in case to avoid NaNs
float lenSq = dirToSun.x * dirToSun.x + dirToSun.y * dirToSun.y + dirToSun.z * dirToSun.z;
b3Vec3 sun = ( lenSq > 0.0f ) ? b3Normalize( dirToSun ) : b3Vec3_axisY;
float fade = SkySunFadeWeight( sun );
float fade = SkySunFadeWeight( sun, zUp );
sg_push_debug_group( "ibl_rebuild" );
GenerateSkyCube( sun, turbidity, fade );
GenerateSkyCube( sun, turbidity, fade, zUp );
GeneratePrefilter();
ProjectSkyToSh( sun, turbidity, fade );
ProjectSkyToSh( sun, turbidity, fade, zUp );
sg_pop_debug_group();

View file

@ -52,8 +52,9 @@ void ShutdownImageBasedLighting( void );
void MarkIblDirty( void );
// If dirty, regenerate the prefiltered sky cube and recompute SH from
// the current sun direction + turbidity. Idempotent when clean.
void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity );
// the current sun direction + turbidity. Idempotent when clean. zUp picks
// the sky's up axis, a change forces a rebuild on its own.
void RebuildImageBasedLightingIfDirty( b3Vec3 dirToSun, float turbidity, bool zUp );
// Prefiltered sky cubemap (mip 0 = mirror, mip GFX_IBL_CUBE_MIPS-1 =
// fully rough). Bind once per lit-pipeline draw.

View file

@ -649,14 +649,13 @@ void InitRenderer( const sg_environment* env )
sg_desc desc = { 0 };
desc.environment = *env;
desc.logger.func = OnSokolLog;
// Sokol's default buffer/view pools are 128/256, which is fine for the
// demo scenes but exhausts on Box3D benchmark scenes that register many
// unique hull geometries (the washer benchmark: 40 distinct 8-vertex
// hulls, each consuming 1 vertex + 1 index + 1 edge buffer + 1 edge
// view in the geometry registry). Size up generously, each pool slot
// is a small struct, so 1024 each is < 1 MB of headroom.
desc.buffer_pool_size = 1024;
desc.view_pool_size = 1024;
// Sokol's default buffer/view pools are 128/256, which exhausts on scenes that register many unique geometries.
// The geometry registry holds up to MAX_REGISTRY_ENTRIES (4096) entries, each consuming 3 buffers (vertex,
// index, edge) and 1 edge view. Size the pools past 4096 entries worth so the registry cap, which degrades
// gracefully, is the binding limit rather than a sokol pool assert. Pool slots are small structs, a few MB total.
desc.buffer_pool_size = 16384;
desc.view_pool_size = 8192;
sg_setup( &desc );
#if defined( SOKOL_GLCORE )
@ -1248,11 +1247,11 @@ void InitRenderer( const sg_environment* env )
// Default exposure: Preetham at physical strength is bright, -2 EV
// brings the integrated sky+sun into AgX's sweet spot.
s_gfx.exposureEv = -2.5f;
// 1.0 is AgX's stock Standard look (identity), the Render Settings
// panel raises it to counteract AgX's path-to-white desaturation.
s_gfx.tonemapSaturation = 1.4f;
// IBL on by default, the Render Settings panel toggles it.
s_gfx.iblEnabled = true;
@ -1269,8 +1268,9 @@ void InitRenderer( const sg_environment* env )
// Bring IBL in sync with the initial sun before the first frame so
// lit pipelines (once they sample the cubemap) don't read garbage
// upper mips on frame 0. Per-frame mark-dirty/rebuild is not yet implemented.
RebuildImageBasedLightingIfDirty( s_gfx.sun.dirToSun, s_gfx.turbidity );
// upper mips on frame 0. Bakes y-up, the first frame's up axis arrives
// via FrameInput and rebakes if it differs.
RebuildImageBasedLightingIfDirty( s_gfx.sun.dirToSun, s_gfx.turbidity, false );
}
void SetSun( Sun sun )
@ -1920,7 +1920,7 @@ static void DrawScene( int targetWidth, int targetHeight, const FrameInput* fram
// Draw after all opaque shapes. The sky pipeline tests GREATER_EQUAL
// at NDC z = 0 against the reverse-Z cleared depth (0), so it fills
// only pixels that no opaque draw touched.
DrawSky( s_gfx.sun.dirToSun, s_gfx.turbidity, frame->cameraPosition, invViewProj );
DrawSky( s_gfx.sun.dirToSun, s_gfx.turbidity, frame->cameraPosition, invViewProj, frame->zUp );
}
// Depth-only pre-pass. Renders all opaque shapes from the main camera
@ -2106,7 +2106,7 @@ static void PreSceneWork( int width, int height, const FrameInput* frame )
UploadInstances();
// IBL regen must run before the main pass starts
RebuildImageBasedLightingIfDirty( s_gfx.sun.dirToSun, s_gfx.turbidity );
RebuildImageBasedLightingIfDirty( s_gfx.sun.dirToSun, s_gfx.turbidity, frame->zUp );
RenderShadowCascades( frame, frame->disableShadows == false );
@ -2620,8 +2620,9 @@ void RenderFrame( const sg_swapchain* swapChain, const FrameInput* frame )
GetTransparentMeshInstanceView(), &s_gfx.edgeOverlay );
// highlight mask, only when the box3d adapter (or test scene)
// forwarded hovered/selected shapes for this frame. Mask depth-tests
// against the GTAO prepass depth so occluded highlights don't bleed.
// forwarded hovered/selected shapes for this frame. The mask captures the
// full unoccluded projection so the outline rings only a shape's outer
// contour, never its occluders.
const bool drawHighlights = s_gfx.highlight.enabled && HasHighlightMaskContent();
if ( drawHighlights )
{

View file

@ -51,6 +51,11 @@ typedef struct FrameInput
// depth pre-pass + trace + upsample skipped
// the full-res AO target is cleared to 1.0 (no occlusion) instead
bool disableAmbientOcclusion;
// Simulation up axis. The camera folds the sim->display map into the
// view transform, but the procedural sky reconstructs directions in sim
// space, so it needs the up axis to orient the Preetham model.
bool zUp;
} FrameInput;
// Directional light. The renderer owns one. Defaults are set in InitRenderer:

View file

@ -63,16 +63,17 @@ void ShutdownSky( void )
s_sky.ready = false;
}
float SkySunFadeWeight( b3Vec3 dirToSun )
float SkySunFadeWeight( b3Vec3 dirToSun, bool zUp )
{
// dirToSun is assumed unit-length. The rendering side renormalizes
// before calling. The fade reads dirToSun.y directly as sin(elevation).
float t = ( dirToSun.y - BELOW_HORIZON_FADE_START_SIN ) / ( BELOW_HORIZON_FADE_END_SIN - BELOW_HORIZON_FADE_START_SIN );
// before calling. sin(elevation) is the component along the sim up axis.
float elevSin = zUp ? dirToSun.z : dirToSun.y;
float t = ( elevSin - BELOW_HORIZON_FADE_START_SIN ) / ( BELOW_HORIZON_FADE_END_SIN - BELOW_HORIZON_FADE_START_SIN );
t = ( t < 0.0f ) ? 0.0f : ( t > 1.0f ? 1.0f : t );
return t * t * ( 3.0f - 2.0f * t );
}
void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewProj )
void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewProj, bool zUp )
{
if ( !s_sky.ready )
{
@ -85,14 +86,16 @@ void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewPr
const float lenSq = dirToSun.x * dirToSun.x + dirToSun.y * dirToSun.y + dirToSun.z * dirToSun.z;
b3Vec3 sun = ( lenSq > 0.0f ) ? b3Normalize( dirToSun ) : b3Vec3_axisY;
const float fade = SkySunFadeWeight( sun );
const float fade = SkySunFadeWeight( sun, zUp );
sky_ub_frame_t ub = { 0 };
ub.inv_view_proj = invViewProj;
// Sun stays in sim space, the FS rotates it into the model's Y-up frame
// alongside the view ray when zUp is set.
sky_ub_pass_t up = { 0 };
up.sun_dir_world = MakeVec4( sun.x, sun.y, sun.z, fade );
up.sky_params = MakeVec4( turbidity, 0.0f, 0.0f, 0.0f );
up.sky_params = MakeVec4( turbidity, zUp ? 1.0f : 0.0f, 0.0f, 0.0f );
up.camera_pos = MakeVec4( cameraPos.x, cameraPos.y, cameraPos.z, 0.0f );
sg_apply_pipeline( s_sky.pipeline );

View file

@ -30,8 +30,9 @@ void ShutdownSky( void );
// Below-horizon fade weight in [0, 1], 1 well above the horizon, 0
// below it, smoothstep between sin(2 deg) and sin(5 deg). The IBL cubemap
// renderer reads this so its sky matches the backdrop exactly when the
// sun is near the horizon. dirToSun.y == sin(elevation) when normalized.
float SkySunFadeWeight( b3Vec3 dirToSun );
// sun is near the horizon. Elevation is sin = dirToSun.y for a y-up sim,
// dirToSun.z for a z-up sim, selected by zUp.
float SkySunFadeWeight( b3Vec3 dirToSun, bool zUp );
// Issue the sky draw. Call inside the main lit pass after all opaque
// shape draws. Parameters:
@ -42,7 +43,8 @@ float SkySunFadeWeight( b3Vec3 dirToSun );
// direction as (world_far_point - cameraPos).
// invViewProj inverse of proj * view for the current frame, the VS
// unprojects NDC corners through this to get world rays.
void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewProj );
// zUp simulation up axis, reorients the sky model for z-up.
void DrawSky( b3Vec3 dirToSun, float turbidity, b3Vec3 cameraPos, Mat4 invViewProj, bool zUp );
#ifdef __cplusplus
} // extern "C"

View file

@ -15,7 +15,6 @@ static constexpr float RADIAL_ZOOM_SENS = 0.02f; // meters per pixel (alt+right-
static constexpr float FLY_SPEED_STEP = 1.0f; // m/s per scroll tick
static constexpr float ZOOM_STEP = 0.9f; // multiplier per scroll tick
static constexpr float MIN_DIST = 0.1f;
static constexpr float MAX_DIST = 1000.0f;
static constexpr float MIN_SPEED = 0.06f; // matches box3d's 0.001*60
static constexpr float MAX_SPEED = 30000.0f; // matches box3d's 500*60
static constexpr float PITCH_LIM = HALF_PI - 0.01f;
@ -23,7 +22,7 @@ static constexpr float THIRD_PERSON_MIN_RADIUS = 0.25f; // matches box3d
// Build a reverse-Z RH projection and its inverse together by swapping the
// near/far args. mat4PerspectiveAndInverse normally puts ndc.z=0 at near, 1
// at far; with the arguments swapped you get 1 at near, 0 at far - what the
// at far. With the arguments swapped you get 1 at near, 0 at far - what the
// project's pipeline expects (compare GREATER, far-clear 0). The inverse is
// closed-form from the same params so the un-project path stays accurate.
static void ReverseZPerspectiveAndInverse( Mat4* outProj, Mat4* outProjInv, float fov, float aspect, float n, float f )
@ -31,8 +30,8 @@ static void ReverseZPerspectiveAndInverse( Mat4* outProj, Mat4* outProjInv, floa
MakePerspectiveAndInverse( outProj, outProjInv, fov, aspect, f, n );
}
// Yaw/pitch -> the "+view-Z" direction (pivot -> camera), matching Box3D's
// sample convention. The actual looking direction is -ForwardFromAngles.
// Yaw/pitch -> the "+view-Z" direction (pivot -> camera). The actual looking
// direction is -ForwardFromAngles.
static b3Vec3 ForwardFromAngles( float yaw, float pitch )
{
const float cp = cosf( pitch );
@ -59,7 +58,16 @@ static void RebuildBasisAndView( Camera& c )
c.m_right = right;
c.m_up = up;
c.m_forward = forward;
MakeViewAndInverse( &c.m_view, &c.m_viewInv, right, up, forward, c.m_position );
// The basis view assumes meters, Y-up, eye at the origin. Geometry reaches the
// GPU shifted against the draw origin in length units, so fold the sim->display
// map in: view = basis * S maps a length-unit eye-relative point to view space.
// The inverse mirrors it (viewInv = S^-1 * basisInv) so unproject and the sky's
// invViewProj recover length-unit points.
Mat4 viewBasis, viewBasisInv;
MakeViewAndInverse( &viewBasis, &viewBasisInv, right, up, forward, c.m_position );
c.m_view = MulMM4( viewBasis, c.m_renderXform );
c.m_viewInv = MulMM4( c.m_renderXformInv, viewBasisInv );
}
Camera::Camera()
@ -69,7 +77,7 @@ Camera::Camera()
, m_radius( 25.0f )
, m_fov( 60.0f * DEG_TO_RAD )
, m_near( 0.1f )
, m_far( 1000.0f )
, m_far( kViewDistance )
, m_speed( 10.0f )
, m_width( 0 )
, m_height( 0 )
@ -83,6 +91,10 @@ Camera::Camera()
, m_viewInv( MakeIdentity() )
, m_proj( MakeIdentity() )
, m_projInv( MakeIdentity() )
, m_renderXform( MakeIdentity() )
, m_renderXformInv( MakeIdentity() )
, m_lengthUnitsPerMeter( 1.0f )
, m_zUp( false )
{
RebuildBasisAndView( *this );
RebuildProj( 1.0f );
@ -95,19 +107,65 @@ void Camera::RebuildProj( float aspect )
ReverseZPerspectiveAndInverse( &m_proj, &m_projInv, m_fov, aspect, m_near, m_far );
}
void Camera::SetRenderTransform( float lengthUnitsPerMeter, bool zUp )
{
m_lengthUnitsPerMeter = lengthUnitsPerMeter > 0.0f ? lengthUnitsPerMeter : 1.0f;
m_zUp = zUp;
const float s = 1.0f / m_lengthUnitsPerMeter; // meters per length unit
const float u = m_lengthUnitsPerMeter; // length units per meter
if ( zUp )
{
// S = s * Rx(-90): sim (x,y,z) -> display (x, z, -y), so sim +Z is view up.
// A proper rotation (det +1), not an axis swap, so winding and normals stay
// correct and back-face culling is not inverted.
m_renderXform =
Mat4{ { s, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, -s, 0.0f }, { 0.0f, s, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } };
m_renderXformInv =
Mat4{ { u, 0.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, u, 0.0f }, { 0.0f, -u, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } };
}
else
{
m_renderXform =
Mat4{ { s, 0.0f, 0.0f, 0.0f }, { 0.0f, s, 0.0f, 0.0f }, { 0.0f, 0.0f, s, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } };
m_renderXformInv =
Mat4{ { u, 0.0f, 0.0f, 0.0f }, { 0.0f, u, 0.0f, 0.0f }, { 0.0f, 0.0f, u, 0.0f }, { 0.0f, 0.0f, 0.0f, 1.0f } };
}
RebuildBasisAndView( *this );
}
// Map a simulation-space AABB into display space (meters, view up axis). S is a
// scaled signed-axis permutation, so transforming the two opposite corners and
// taking the per-axis min/max recovers the display AABB exactly.
static b3AABB TransformAABBToDisplay( const Mat4& s, b3AABB a )
{
Vec4 lo = MulMV4( s, MakeVec4( a.lowerBound.x, a.lowerBound.y, a.lowerBound.z, 1.0f ) );
Vec4 hi = MulMV4( s, MakeVec4( a.upperBound.x, a.upperBound.y, a.upperBound.z, 1.0f ) );
b3AABB out;
out.lowerBound = { fminf( lo.x, hi.x ), fminf( lo.y, hi.y ), fminf( lo.z, hi.z ) };
out.upperBound = { fmaxf( lo.x, hi.x ), fmaxf( lo.y, hi.y ), fmaxf( lo.z, hi.z ) };
return out;
}
void Camera::Frame( b3AABB aabb, float aspect, float padding )
{
if ( !b3IsValidAABB( aabb ) )
{
return;
}
// Bounds arrive in simulation space. frame against the display-space box so the
// fit accounts for the render scale and up axis.
aabb = TransformAABBToDisplay( m_renderXform, aabb );
b3Vec3 center = b3AABB_Center( aabb );
b3Vec3 ext = b3AABB_Extents( aabb ); // half-extents
float r = sqrtf( ext.x * ext.x + ext.y * ext.y + ext.z * ext.z );
m_pivot = b3ToPos( center );
if ( r < 1.0e-6f )
{
// Point-like; preserve current radius, just retarget. The cached
// Point-like. Preserve current radius, just retarget. The cached
// position/basis depend on m_pivot, so refresh them before returning.
RebuildBasisAndView( *this );
return;
@ -128,16 +186,8 @@ void Camera::Frame( b3AABB aabb, float aspect, float padding )
void Camera::SetOrbit( float yawRadians, float pitchRadians, float radius )
{
m_yaw = yawRadians;
if ( pitchRadians > PITCH_LIM )
pitchRadians = PITCH_LIM;
if ( pitchRadians < -PITCH_LIM )
pitchRadians = -PITCH_LIM;
m_pitch = pitchRadians;
if ( radius < MIN_DIST )
radius = MIN_DIST;
if ( radius > MAX_DIST )
radius = MAX_DIST;
m_radius = radius;
m_pitch = b3ClampFloat( pitchRadians, -PITCH_LIM, PITCH_LIM );
m_radius = b3ClampFloat( radius, MIN_DIST, kViewDistance );
RebuildBasisAndView( *this );
}
@ -171,34 +221,35 @@ PickRay Camera::BuildPickRay( float x, float y ) const
}
// Pixel -> NDC. Origin top-left, Y down. NDC has Y up, X right.
const float ndcX = ( 2.0f * x / (float)m_width ) - 1.0f;
const float ndcY = 1.0f - ( 2.0f * y / (float)m_height );
float ndcX = ( 2.0f * x / (float)m_width ) - 1.0f;
float ndcY = 1.0f - ( 2.0f * y / (float)m_height );
// Reverse-Z: near maps to clip-Z = +w, far to 0. Unproject both clip points
// through inv(P*V) = viewInv * projInv, no runtime matrix inversion. The
// matrices are eye-relative, so the recovered points are too.
const Mat4 invVP = MulMM4( m_viewInv, m_projInv );
Mat4 invVP = MulMM4( m_viewInv, m_projInv );
const Vec4 clipN = MakeVec4( ndcX, ndcY, 1.0f, 1.0f );
const Vec4 clipF = MakeVec4( ndcX, ndcY, 0.0f, 1.0f );
Vec4 clipN = MakeVec4( ndcX, ndcY, 1.0f, 1.0f );
Vec4 clipF = MakeVec4( ndcX, ndcY, 0.0f, 1.0f );
const Vec4 wN = MulMV4( invVP, clipN );
const Vec4 wF = MulMV4( invVP, clipF );
Vec4 wN = MulMV4( invVP, clipN );
Vec4 wF = MulMV4( invVP, clipF );
if ( wN.w == 0.0f || wF.w == 0.0f )
{
return ray;
}
const float invWN = 1.0f / wN.w;
const float invWF = 1.0f / wF.w;
float invWN = 1.0f / wN.w;
float invWF = 1.0f / wF.w;
b3Vec3 nearWorld = { wN.x * invWN, wN.y * invWN, wN.z * invWN };
b3Vec3 farWorld = { wF.x * invWF, wF.y * invWF, wF.z * invWF };
// Lift the near point to absolute world with the double eye. Translation is
// a delta so it stays eye-relative and needs no offset.
ray.origin = b3OffsetPos( m_worldEye, nearWorld );
// viewInv folds in S^-1, so the unprojected points are in simulation space
// relative to the eye. Lift the near point with the simulation eye so the ray
// feeds straight into the world queries, which run in length units.
ray.origin = b3OffsetPos( DrawOrigin(), nearWorld );
ray.translation = b3Sub( farWorld, nearWorld );
return ray;
}
@ -206,7 +257,7 @@ PickRay Camera::BuildPickRay( float x, float y ) const
void Camera::OnEvent( const sapp_event* e )
{
uint32_t mods = e->modifiers & ( SAPP_MODIFIER_SHIFT | SAPP_MODIFIER_CTRL | SAPP_MODIFIER_ALT );
const bool canOrbit = mods == SAPP_MODIFIER_ALT;
bool canOrbit = mods == SAPP_MODIFIER_ALT;
switch ( e->type )
{
@ -411,10 +462,7 @@ void Camera::Update( float dt, int width, int height )
if ( m_speedScrollAccum != 0.0f )
{
m_speed += m_speedScrollAccum * FLY_SPEED_STEP;
if ( m_speed < MIN_SPEED )
m_speed = MIN_SPEED;
if ( m_speed > MAX_SPEED )
m_speed = MAX_SPEED;
m_speed = b3ClampFloat( m_speed, MIN_SPEED, MAX_SPEED );
}
}
else
@ -424,10 +472,7 @@ void Camera::Update( float dt, int width, int height )
{
m_yaw -= m_orbitDX * ORBIT_SENS;
m_pitch -= m_orbitDY * ORBIT_SENS;
if ( m_pitch > PITCH_LIM )
m_pitch = PITCH_LIM;
if ( m_pitch < -PITCH_LIM )
m_pitch = -PITCH_LIM;
m_pitch = b3ClampFloat( m_pitch, -PITCH_LIM, PITCH_LIM );
}
if ( m_panDX != 0.0f || m_panDY != 0.0f )
@ -448,19 +493,13 @@ void Camera::Update( float dt, int width, int height )
{
// Drag down -> zoom in (radius shrinks). Matches Box3D.
m_radius -= RADIAL_ZOOM_SENS * m_radialZoomDY;
if ( m_radius < MIN_DIST )
m_radius = MIN_DIST;
if ( m_radius > MAX_DIST )
m_radius = MAX_DIST;
m_radius = b3ClampFloat( m_radius, MIN_DIST, kViewDistance );
}
if ( m_scrollAccum != 0.0f )
{
m_radius *= powf( ZOOM_STEP, m_scrollAccum );
if ( m_radius < MIN_DIST )
m_radius = MIN_DIST;
if ( m_radius > MAX_DIST )
m_radius = MAX_DIST;
m_radius = b3ClampFloat( m_radius, MIN_DIST, kViewDistance );
}
}

View file

@ -45,6 +45,10 @@ class Camera
public:
Camera();
// One knob for how far the camera reaches, in meters: the projection far plane,
// the maximum orbit radius, and (scaled to length units) the draw cull box.
static constexpr float kViewDistance = 1000.0f;
// Feed each sokol_app event here. Safe to call from event_cb at any
// time during the frame; deltas are summed and consumed by Update().
void OnEvent( const sapp_event* e );
@ -143,7 +147,33 @@ public:
// ray if the camera has no size yet, so callers never read uninitialized values.
PickRay BuildPickRay( float x, float y ) const;
b3Pos m_pivot; // look-at point, world space. Double precision so it stays exact far from origin.
// Set the simulation->display transform: a uniform scale of 1/lengthUnitsPerMeter
// so the scene renders in meters, plus an optional rotation taking simulation +Z
// to view up. Folded into the view matrix, so simulation data and the draw origin
// stay in length units and only the rendered result is scaled and reoriented. The
// camera itself then lives in meters, so radius and speeds read in meters.
void SetRenderTransform( float lengthUnitsPerMeter, bool zUp );
// Eye in simulation space (length units). The renderer shifts simulation-space
// geometry against this. The view folds in the sim->display map afterward. With
// an identity transform this is just m_worldEye.
b3Pos DrawOrigin() const
{
Vec4 e = MulMV4( m_renderXformInv, MakeVec4( m_worldEye.x, m_worldEye.y, m_worldEye.z, 1.0f ) );
return b3Pos{ e.x, e.y, e.z };
}
// Cull box for b3World_Draw, in simulation space (length units): a cube of the
// view distance centered on the simulation eye, so the draw set matches the far
// plane reach. The broad phase is queried in length units, hence the scale.
b3AABB DrawBounds() const
{
float h = kViewDistance * m_lengthUnitsPerMeter;
b3Vec3 r = { h, h, h };
return b3OffsetAABB( { b3Neg( r ), r }, DrawOrigin() );
}
b3Pos m_pivot; // look-at point, display space (meters). Double precision so it stays exact far from origin.
float m_yaw; // radians, around Y
float m_pitch; // radians, around camera-frame X
float m_radius; // meters from pivot
@ -185,6 +215,14 @@ public:
Mat4 m_proj;
Mat4 m_projInv;
// Simulation -> display transform and its inverse, folded into m_view / m_viewInv
// by RebuildBasisAndView. Identity until SetRenderTransform runs, so the default
// is meters and y-up.
Mat4 m_renderXform;
Mat4 m_renderXformInv;
float m_lengthUnitsPerMeter;
bool m_zUp;
// Per-frame input deltas accumulated by OnEvent and zeroed by Update.
// Routing into the right bucket happens in OnEvent based on which mouse
// buttons + Alt are held when the event arrives.

View file

@ -72,7 +72,7 @@ static void OnInit( void )
constexpr float DEG = 3.14159265358979323846f / 180.0f;
s_context.camera.SetFov( 50.0f * DEG );
s_context.camera.SetClip( 0.1f, 1000.0f );
s_context.camera.SetClip( 0.1f, Camera::kViewDistance );
s_context.Load();
@ -178,24 +178,30 @@ static void OnEvent( const sapp_event* e )
case KEY_F:
case KEY_HOME:
{
// Frame the selection, or the whole world when nothing is selected.
b3BodyId bodyId = GetHoveredBody();
b3AABB aabb;
float padding;
if ( B3_IS_NON_NULL( bodyId ) )
// 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
// takes priority over the hovered body. The replay viewer's scene lives in a
// player-owned world, not the base world, so the whole-scene case routes through
// FocusHome.
Camera& cam = s_context.camera;
float aspect = cam.m_height > 0 ? (float)cam.m_width / (float)cam.m_height : 1.0f;
b3AABB bounds;
if ( s_context.sample->FocusBounds( &bounds ) )
{
aabb = b3Body_ComputeAABB( bodyId );
padding = 1.5f;
cam.Frame( bounds, aspect, 1.5f );
}
else
{
aabb = b3World_GetBounds( s_context.sample->m_worldId );
padding = 0.75f;
b3BodyId bodyId = s_context.sample->FocusBody();
if ( B3_IS_NON_NULL( bodyId ) )
{
cam.Frame( b3Body_ComputeAABB( bodyId ), aspect, 1.5f );
}
else
{
s_context.sample->FocusHome();
}
}
Camera& cam = s_context.camera;
float aspect = cam.m_height > 0 ? (float)cam.m_width / (float)cam.m_height : 1.0f;
cam.Frame( aabb, aspect, padding );
}
break;
@ -295,10 +301,17 @@ static void OnFrame( void )
Camera& camera = s_context.camera;
camera.Update( dt, W, H );
// Push the current length scale and Z-up choice. The replay player sets length
// units from its header on load and restores them on close, so querying every
// frame tracks load/unload without extra wiring. Live samples sit at 1 unit per
// meter, leaving the transform identity.
camera.SetRenderTransform( b3GetLengthUnitsPerMeter(), s_context.viewZUp );
// Sync the draw origin to the camera eye once per frame, before any drawing. This must hold even
// for samples that drive their own Step without calling Sample::Step. Render re-syncs after Step
// because a third person follow moves the eye while stepping.
SetDrawOrigin( camera.m_worldEye );
// because a third person follow moves the eye while stepping. The draw origin is in simulation
// space; the view folds in the scale and up axis.
SetDrawOrigin( camera.DrawOrigin() );
ResetFrameArena();
@ -339,6 +352,7 @@ static void OnFrame( void )
fi.debugMode = s_context.debugView;
fi.disableShadows = !s_context.enableShadows;
fi.disableAmbientOcclusion = !s_context.enableGtao;
fi.zUp = s_context.viewZUp;
const sg_swapchain sc = sglue_swapchain();
RenderFrame( &sc, &fi );

View file

@ -24,9 +24,8 @@
#include "box3d/box3d.h"
#include <nfd.h>
#include <ctype.h>
#include <nfd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@ -105,7 +104,9 @@ void SampleContext::Save()
fprintf( file, " \"sunStrength\": %g,\n", GetSun().strength );
fprintf( file, " \"debugView\": %d,\n", debugView );
fprintf( file, " \"showHullEdges\": %s,\n", GetEdgeOverlayParams().showHulls ? "true" : "false" );
fprintf( file, " \"showEdgeConvexity\": %s\n", GetEdgeOverlayParams().showEdgeConvexity ? "true" : "false" );
fprintf( file, " \"showEdgeConvexity\": %s,\n", GetEdgeOverlayParams().showEdgeConvexity ? "true" : "false" );
fprintf( file, " \"replayKeyframeBudgetMB\": %d,\n", replayKeyframeBudgetMB );
fprintf( file, " \"replayKeyframeMinInterval\": %d\n", replayKeyframeMinInterval );
fprintf( file, "}\n" );
fclose( file );
}
@ -253,6 +254,30 @@ void SampleContext::Load()
p.showEdgeConvexity = strncmp( s, "true", 4 ) == 0;
SetEdgeOverlayParams( &p );
}
else if ( jsoneq( data, &tokens[i], "replayKeyframeBudgetMB" ) == 0 )
{
int count = tokens[i + 1].end - tokens[i + 1].start;
if ( count > (int)sizeof( buffer ) - 1 )
{
count = (int)sizeof( buffer ) - 1;
}
const char* s = data + tokens[i + 1].start;
memcpy( buffer, s, count );
buffer[count] = 0;
replayKeyframeBudgetMB = b3ClampInt( (int)strtol( buffer, nullptr, 10 ), 64, 4096 );
}
else if ( jsoneq( data, &tokens[i], "replayKeyframeMinInterval" ) == 0 )
{
int count = tokens[i + 1].end - tokens[i + 1].start;
if ( count > (int)sizeof( buffer ) - 1 )
{
count = (int)sizeof( buffer ) - 1;
}
const char* s = data + tokens[i + 1].start;
memcpy( buffer, s, count );
buffer[count] = 0;
replayKeyframeMinInterval = b3ClampInt( (int)strtol( buffer, nullptr, 10 ), 1, 1024 );
}
}
free( data );
@ -436,53 +461,66 @@ void Sample::Step()
m_triangleIndex = -1;
m_userMaterialId = 0;
// Cursor pick feeds the surface type readout only. Highlighting is selection driven.
if ( m_camera->m_thirdPerson == false )
{
PickRay pickRay = m_camera->BuildPickRay( m_context->mouseX, m_context->mouseY );
b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() );
b3QueryFilter filter = b3DefaultQueryFilter();
filter.name = "pick";
b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, filter );
b3BodyId hovered = b3_nullBodyId;
if ( result.hit )
{
b3ShapeType type = b3Shape_GetType( result.shapeId );
if ( type == b3_meshShape )
if ( b3Shape_GetType( result.shapeId ) == b3_meshShape )
{
m_triangleIndex = result.triangleIndex;
}
m_userMaterialId = result.userMaterialId;
// Only dynamic bodies highlight, so the static ground never lights up.
b3BodyId bodyId = b3Shape_GetBody( result.shapeId );
if ( b3Body_GetType( bodyId ) == b3_dynamicBody )
{
hovered = bodyId;
}
}
SetHoveredBody( hovered );
}
// The frame latched the origin before Step, but a third person follow moves the eye while
// stepping, so refresh it here. Shapes come back demoted to float against this origin, the same
// relative frame the translation free view renders, so everything stays precise far from the origin.
SetDrawOrigin( m_camera->m_worldEye );
SetDrawOrigin( m_camera->DrawOrigin() );
b3DebugDraw debugDraw;
MakeDebugDraw( &debugDraw );
// Generous visible volume around the eye. Box3D uses this to decide which shapes enter the
// draw set and lazily fire createDebugShape. The cull bounds live in absolute world space to
// match the broad-phase tree; the draw origin is the world eye.
b3Vec3 r = { 1000.0f, 1000.0f, 1000.0f };
b3AABB bounds = b3OffsetAABB( { b3Neg( r ), r }, m_camera->m_worldEye );
debugDraw.drawingBounds = bounds;
// Box3D uses this to decide which shapes enter the draw set and lazily fire
// createDebugShape. The camera derives it from the view distance, in length units
// around the simulation eye, matching the broad-phase tree and the far plane.
debugDraw.drawingBounds = m_camera->DrawBounds();
ApplyGuiFlags( &debugDraw );
b3World_Draw( m_worldId, &debugDraw, B3_DEFAULT_MASK_BITS );
}
bool Sample::FocusBounds( b3AABB* )
{
return false;
}
float Sample::InfoPanelWidthEm() const
{
return INFO_PANEL_WIDTH;
}
b3BodyId Sample::FocusBody() const
{
return GetSelectedBody();
}
void Sample::FocusHome()
{
b3AABB aabb = b3World_GetBounds( m_worldId );
float aspect = m_camera->m_height > 0 ? (float)m_camera->m_width / (float)m_camera->m_height : 1.0f;
m_camera->Frame( aabb, aspect, 0.75f );
}
void Sample::ResetProfile()
{
m_stepCount = 0;
@ -539,7 +577,7 @@ void Sample::DrawMetrics()
}
float fontSize = ImGui::GetFontSize();
float menuWidth = INFO_PANEL_WIDTH * fontSize;
float menuWidth = InfoPanelWidthEm() * fontSize;
float drawerHeight = 16.0f * fontSize;
float drawerWidth = m_camera->m_width - menuWidth - 1.5f * fontSize;
@ -1089,12 +1127,33 @@ void Sample::MouseDown( b3Vec2 p, int button, int modifiers )
{
if ( button == 0 && modifiers == 0 )
{
// Plain click selects the body under the cursor, any type. Empty space clears.
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation,
b3DefaultQueryFilter() );
b3QueryFilter filter = b3DefaultQueryFilter();
filter.name = "select";
b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, filter );
if ( result.hit )
{
SetSelectedBody( b3Shape_GetBody( result.shapeId ) );
}
else
{
ClearSelection();
}
}
else if ( button == 0 && modifiers == MOD_CTRL )
{
// Ctrl click grabs a dynamic body with a kinematic mouse body and a motor joint.
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
b3QueryFilter filter = b3DefaultQueryFilter();
filter.name = "grab";
b3RayResult result = b3World_CastRayClosest( m_worldId, pickRay.origin, pickRay.translation, filter );
b3BodyId bodyId = result.hit ? b3Shape_GetBody( result.shapeId ) : b3_nullBodyId;
if ( result.hit && b3Body_GetType( bodyId ) == b3_dynamicBody )
{
m_mousePoint = result.point;
@ -1104,17 +1163,8 @@ void Sample::MouseDown( b3Vec2 p, int button, int modifiers )
bodyDef.enableSleep = false;
m_mouseBodyId = b3CreateBody( m_worldId, &bodyDef );
b3BodyId bodyId = b3Shape_GetBody( result.shapeId );
// A plain click also sets the selection. Dynamic only, matching hover.
if ( b3Body_GetType( bodyId ) == b3_dynamicBody )
{
SetSelectedBody( bodyId );
}
else
{
ClearSelection();
}
// Grabbing also selects so the body stays highlighted while dragged.
SetSelectedBody( bodyId );
b3MotorJointDef jointDef = b3DefaultMotorJointDef();
jointDef.base.bodyIdA = m_mouseBodyId;
@ -1142,11 +1192,6 @@ void Sample::MouseDown( b3Vec2 p, int button, int modifiers )
m_mouseFraction = result.fraction;
}
else
{
// Click into empty space clears the selection.
ClearSelection();
}
}
else if ( modifiers & MOD_SHIFT )
{
@ -1206,8 +1251,6 @@ void Sample::MouseUp( b3Vec2 p, int button )
m_mouseJointId = b3_nullJointId;
m_mouseBodyId = b3_nullBodyId;
m_mouseFraction = 0.0f;
ClearSelection();
}
void Sample::MouseMove( b3Vec2 p )
@ -1546,7 +1589,6 @@ static void DrawMenuBar( SampleContext* context )
float aspect = cam.m_height > 0 ? (float)cam.m_width / (float)cam.m_height : 1.0f;
cam.Frame( aabb, aspect, 0.75f );
}
ImGui::Separator();
ImGui::MenuItem( "Shapes", nullptr, &gd->drawShapes );
ImGui::MenuItem( "Transparent", nullptr, &context->transparentDynamic );
ImGui::MenuItem( "Joints", nullptr, &gd->drawJoints );
@ -1581,7 +1623,7 @@ static void DrawMenuBar( SampleContext* context )
{
ImGui::PushItemWidth( 6.0f * fontSize );
ImGui::InputFloat( "Joint", &gd->jointScale );
ImGui::InputFloat( "Force", &gd->forceScale );
ImGui::InputFloat( "Force", &gd->forceScale, 0, 0, "%.6f", ImGuiInputTextFlags_CharsScientific );
ImGui::PopItemWidth();
ImGui::EndMenu();
}
@ -1813,7 +1855,7 @@ static void DrawInfoPanel( SampleContext* context )
{
const SampleEntry& entry = g_sampleEntries[context->sampleIndex];
float fontSize = ImGui::GetFontSize();
float menuWidth = INFO_PANEL_WIDTH * fontSize;
float menuWidth = context->sample->InfoPanelWidthEm() * fontSize;
float menuBarHeight = ImGui::GetFrameHeight();
// Full-height panel pinned under the menu bar at the right edge, matching Box2D.
@ -1833,12 +1875,15 @@ static void DrawInfoPanel( SampleContext* context )
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "step %d", context->sample->m_stepCount );
ImGui::Separator();
// The camera lives in display space, so pivot, radius and speed are in meters
// regardless of the simulation's length units.
b3Pos p = context->camera.m_pivot;
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "pivot (%.1f, %.1f, %.1f)", p.x, p.y, p.z );
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "pivot m (%.1f, %.1f, %.1f)", p.x, p.y, p.z );
float yawDeg = B3_RAD_TO_DEG * context->camera.m_yaw;
float pitchDeg = B3_RAD_TO_DEG * context->camera.m_pitch;
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "yaw/pitch (%.1f, %.1f)", yawDeg, pitchDeg );
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "radius %.1f", context->camera.m_radius );
ImGui::TextColored( HexColor( b3_colorSeaGreen ), "radius m %.1f, speed m/s %.1f", context->camera.m_radius,
context->camera.m_speed );
ImGui::Separator();
@ -2103,6 +2148,7 @@ void CharacterMover::SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3
b3Pos rayOrigin = b3TransformWorldPoint( m_transform, m_capsule.center1 );
b3Vec3 rayTranslation = -rayLength * b3Vec3_axisY;
b3QueryFilter skipTeamFilter = { 1, ~2u };
skipTeamFilter.name = "pogo";
b3RayResult rayResult = b3World_CastRayClosest( worldId, rayOrigin, rayTranslation, skipTeamFilter );
if ( rayResult.hit == false )
@ -2131,10 +2177,10 @@ void CharacterMover::SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3
b3Pos target = m_transform.p + timeStep * m_velocity + timeStep * m_pogoVelocity * b3Vec3_axisY;
// Want the mover to collide with allies
b3QueryFilter moverFilter = { .categoryBits = 1, .maskBits = ~0u };
b3QueryFilter moverFilter = { .categoryBits = 1, .maskBits = ~0u, .id = 1, .name = "mover_collide" };
// The cast should ignore allies
b3QueryFilter castFilter = { .categoryBits = 1, .maskBits = ~2u };
b3QueryFilter castFilter = { .categoryBits = 1, .maskBits = ~2u, .id = 1, .name = "mover_cast" };
m_totalIterations = 0;
float tolerance = 0.01f;
@ -2281,7 +2327,7 @@ void CharacterMover::Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVe
m_sample->m_camera->UpdateTransform();
}
SetDrawOrigin( m_sample->m_camera->m_worldEye );
SetDrawOrigin( m_sample->m_camera->DrawOrigin() );
int count = m_planeCount;
for ( int i = 0; i < count; ++i )

View file

@ -79,6 +79,10 @@ struct SampleContext
bool enableShadows = true;
bool enableGtao = true;
// View-only: treat simulation +Z as up when drawing. Does not touch the
// simulation. The frame loop hands this to the camera's render transform.
bool viewZUp = false;
float sunStrength = 1.0f;
int debugView = 0;
@ -115,6 +119,25 @@ public:
return true;
}
// Width of the right info panel in em. The bottom drawer clears to the same width. A sample that
// hosts heavier content there, such as the replay viewer's detail pane, can widen it.
virtual float InfoPanelWidthEm() const;
// Bounds the Frame shortcut should fit when the selection is not a body, e.g. a recorded query.
// Takes priority over FocusBody so an explicit selection wins over a hovered body. Returns false
// by default, leaving the body and whole-scene paths in charge.
virtual bool FocusBounds( b3AABB* bounds );
// Body the Frame shortcut should fit. Defaults to whatever the cursor is over.
// The replay viewer overrides this to fit its persistent selection instead, so
// framing works regardless of where the cursor sits.
virtual b3BodyId FocusBody() const;
// Frame shortcut with nothing selected: fit the whole scene. Defaults to the live world bounds.
// The replay viewer overrides this to fit the recording, whose world is player-owned and separate
// from the empty base world.
virtual void FocusHome();
// Arm recording on the live world, snapshotting it as the seed so capture can begin at any
// step boundary. Stop writes the file named by the context and frees the buffer.
void StartRecording();

View file

@ -383,7 +383,6 @@ public:
}
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.name = "grid";
m_gridMesh = b3CreateGridMesh( 40, 40, 1.0f, 0, true );
b3BodyDef bodyDef = b3DefaultBodyDef();
@ -397,7 +396,6 @@ public:
transform.p = { 0.0f, hy, -20.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, hy, 0.1f, transform );
shapeDef.name = "wall1";
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
}
@ -406,7 +404,6 @@ public:
transform.p = { 0.0f, hy, 20.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 20.0f, hy, 0.1f, transform );
shapeDef.name = "wall2";
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
}
@ -415,7 +412,6 @@ public:
transform.p = { -20.0f, hy, 0.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, hy, 20.0f, transform );
shapeDef.name = "wall3";
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
}
@ -424,7 +420,6 @@ public:
transform.p = { 20.0f, hy, 0.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, hy, 20.0f, transform );
shapeDef.name = "wall4";
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
}
@ -1253,7 +1248,6 @@ public:
CreateWorld( &capacity );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.name = "grid";
m_gridMesh = b3CreateGridMesh( 40, 40, 1.0f, 0, true );
b3BodyDef bodyDef = b3DefaultBodyDef();

View file

@ -1604,7 +1604,7 @@ public:
// Latch the draw origin to the followed eye so the debug overlays demote against the same
// point the view renders from.
SetDrawOrigin(m_camera->m_worldEye);
SetDrawOrigin( m_camera->DrawOrigin() );
// Debug visualization
if ( m_showDebug )

View file

@ -627,13 +627,15 @@ public:
break;
}
b3QueryFilter filter = b3DefaultQueryFilter();
filter.name = "cast_world";
if ( m_castType == e_rayCast )
{
b3World_CastRay( m_worldId, m_origin, m_translation, b3DefaultQueryFilter(), modeFcn, &m_castContext );
b3World_CastRay( m_worldId, m_origin, m_translation, filter, modeFcn, &m_castContext );
}
else
{
b3World_CastShape( m_worldId, m_origin, &proxy, m_translation, b3DefaultQueryFilter(), modeFcn, &m_castContext );
b3World_CastShape( m_worldId, m_origin, &proxy, m_translation, filter, modeFcn, &m_castContext );
}
if ( m_castContext.count > 0 )
@ -1073,16 +1075,6 @@ public:
return true;
}
void Render() override
{
Sample::Render();
DrawTextLine( "Shift + LMB and drag to shift start position" );
DrawGroundGrid( 10 );
DrawAxes( b3WorldTransform_identity, 1.0f );
}
void MouseDown( b3Vec2 p, int button, int modifiers ) override
{
if ( button == 0 )
@ -1124,9 +1116,15 @@ public:
void Step() override
{
Sample::Step();
CastSpheres();
CastCapsules();
CastHulls();
DrawTextLine( "Shift + LMB and drag to shift start position" );
DrawGroundGrid( 10 );
DrawAxes( b3WorldTransform_identity, 1.0f );
}
static Sample* Create( SampleContext* context )
@ -1277,18 +1275,6 @@ public:
}
}
void Render() override
{
Sample::Render();
DrawTextLine( "Shift + LMB and drag to move shapes" );
DrawGroundGrid( 10 );
DrawLine( b3Pos_zero, b3OffsetPos( b3Pos_zero, 0.4f * b3Vec3_axisX ), MakeColor( b3_colorRed ) );
DrawLine( b3Pos_zero, b3OffsetPos( b3Pos_zero, 0.4f * b3Vec3_axisY ), MakeColor( b3_colorGreen ) );
DrawLine( b3Pos_zero, b3OffsetPos( b3Pos_zero, 0.4f * b3Vec3_axisZ ), MakeColor( b3_colorBlue ) );
}
void MouseDown( b3Vec2 p, int button, int modifiers ) override
{
if ( button == 0 )
@ -1319,9 +1305,17 @@ public:
void Step() override
{
Sample::Step();
OverlapSpheres();
OverlapCapsules();
OverlapHulls();
DrawTextLine( "Shift + LMB and drag to move shapes" );
DrawGroundGrid( 10 );
DrawLine( b3Pos_zero, b3OffsetPos( b3Pos_zero, 0.4f * b3Vec3_axisX ), MakeColor( b3_colorRed ) );
DrawLine( b3Pos_zero, b3OffsetPos( b3Pos_zero, 0.4f * b3Vec3_axisY ), MakeColor( b3_colorGreen ) );
DrawLine( b3Pos_zero, b3OffsetPos( b3Pos_zero, 0.4f * b3Vec3_axisZ ), MakeColor( b3_colorBlue ) );
}
b3BoxHull m_box;

View file

@ -491,7 +491,6 @@ public:
transform.p = { 0.0f, halfHeight, -extent };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( extent, halfHeight, 0.1f, transform );
shapeDef.name = "wall1";
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
@ -500,7 +499,6 @@ public:
transform.p = { 0.0f, halfHeight, extent };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( extent, halfHeight, 0.1f, transform );
shapeDef.name = "wall2";
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
@ -509,7 +507,6 @@ public:
transform.p = { -extent, halfHeight, 0.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, halfHeight, extent, transform );
shapeDef.name = "wall3";
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
@ -518,7 +515,6 @@ public:
transform.p = { extent, halfHeight, 0.0f };
transform.q = b3Quat_identity;
b3BoxHull wallBox = b3MakeTransformedBoxHull( 0.1f, halfHeight, extent, transform );
shapeDef.name = "wall4";
b3CreateHullShape( m_groundId, &shapeDef, &wallBox.base );
}
}
@ -996,3 +992,87 @@ public:
};
static int sampleIsFast = RegisterSample( "Continuous", "Is Fast", IsFast::Create );
// CCD versus a dense mesh can stall the solver. CCD does an AABB query so it considers
// along the sweep.
class Stall : public Sample
{
public:
explicit Stall( SampleContext* context )
: Sample( context )
{
if ( context->restart == false )
{
m_camera->SetView( 130.0f, 15.0f, 15.0f, { 0.0f, 2.0f, 0.0f } );
}
AddGroundBox( 500.0f );
{
m_mesh = b3CreateTorusMesh( 200, 200, 2.0f, 1.0f );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.name = "torus";
bodyDef.position.y = 2.0f;
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3CreateMeshShape( bodyId, &shapeDef, m_mesh, b3Vec3_one );
}
m_savedThreshold = b3GetStallThreshold();
// Log any CCD that takes longer than 1 ms.
b3SetStallThreshold( 0.001f );
Launch();
}
void Launch()
{
if ( B3_IS_NON_NULL( m_bulletId ) )
{
b3DestroyBody( m_bulletId );
}
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.isBullet = true;
bodyDef.name = "rock";
bodyDef.position = { 0.0f, 1.0f, -10.0f };
// This exceeds the default maximum speed.
bodyDef.linearVelocity = { 0.0f, 0.0f, 600.0f };
bodyDef.angularVelocity = { 0.0f, 0.0f, 20.0f };
m_bulletId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3HullData* rock = b3CreateRock( 0.25f );
b3CreateHullShape( m_bulletId, &shapeDef, rock );
b3DestroyHull( rock );
}
bool DrawControls() override
{
if ( ImGui::Button( "Launch" ) )
{
Launch();
}
return true;
}
~Stall() override
{
b3DestroyMesh( m_mesh );
b3SetStallThreshold( m_savedThreshold );
}
static Sample* Create( SampleContext* context )
{
return new Stall( context );
}
b3MeshData* m_mesh = nullptr;
b3BodyId m_bulletId = b3_nullBodyId;
float m_savedThreshold;
};
static int sampleStall = RegisterSample( "Continuous", "Stall", Stall::Create );

View file

@ -9,10 +9,28 @@
#include "box3d/box3d.h"
#include <ctype.h>
#include <float.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unordered_map>
#include <vector>
// Whole-recording query index, built lazily by scanning the player once. Backs the search box.
struct QueryIndexRow
{
int frame;
b3RecQueryType type;
int kindOrdinal;
int instance; // occurrence among same-key queries in its frame
uint64_t key;
uint64_t id;
const char* name; // points into the player's tag table, stable for the player's lifetime
b3QueryFilter filter;
b3Pos origin;
int hitCount;
};
// Inspector readout names
static const char* ReplayBodyTypeName( b3BodyType type )
@ -108,27 +126,97 @@ static ImVec4 PanelColor( b3HexColor hexColor )
return ImGui::ColorConvertU32ToFloat4( IM_COL32( ( h >> 16 ) & 0xFF, ( h >> 8 ) & 0xFF, h & 0xFF, 255 ) );
}
// Number of b3RecQueryType values, for per-kind bookkeeping in the outline and search.
static constexpr int ReplayQueryTypeCount = 7;
// Outline text and the 3D overlay share one color per query kind, so a row reads as the geometry it
// draws. Matches the colors b3RecPlayer_DrawFrameQueries paints with.
static b3HexColor QueryKindColor( b3RecQueryType type )
{
switch ( type )
{
case b3_recQueryCastRay:
case b3_recQueryCastRayClosest:
return b3_colorYellow;
case b3_recQueryCastShape:
return b3_colorSkyBlue;
case b3_recQueryCastMover:
return b3_colorLightSkyBlue;
case b3_recQueryCollideMover:
return b3_colorTan;
default:
return b3_colorLimeGreen; // overlap AABB and overlap shape
}
}
// Case-insensitive substring test for the query search box.
static bool ContainsNoCase( const char* haystack, const char* needle )
{
if ( needle[0] == '\0' )
{
return true;
}
for ( ; *haystack != '\0'; ++haystack )
{
const char* h = haystack;
const char* n = needle;
while ( *h != '\0' && *n != '\0' && tolower( (unsigned char)*h ) == tolower( (unsigned char)*n ) )
{
++h;
++n;
}
if ( *n == '\0' )
{
return true;
}
}
return false;
}
// Compose a query's display label from its caller id and label, falling back to kind and per-kind
// ordinal when untagged. e.g. "bullet (53)", "bullet", "#53", or "cast ray #0".
static void FormatQueryLabel( char* out, int cap, const char* name, uint64_t id, b3RecQueryType type, int kindOrdinal )
{
if ( name != nullptr && id != 0 )
{
snprintf( out, cap, "%s (%llu)", name, (unsigned long long)id );
}
else if ( name != nullptr )
{
snprintf( out, cap, "%s", name );
}
else if ( id != 0 )
{
snprintf( out, cap, "#%llu", (unsigned long long)id );
}
else
{
snprintf( out, cap, "%s #%d", ReplayQueryTypeName( type ), kindOrdinal );
}
}
enum SelectionKind
{
SelNone,
SelBody,
SelShape,
SelJoint,
SelQuery,
};
// Plays back a .b3rec recording by driving the keyframe player one recorded step at a time and
// drawing the replayed world. The player owns the world, so the base sample world is left empty and
// unused. Mouse picking only reads the world (no drag joint), since mutating it would diverge the
// replay from the recording.
//
// The UI is spread across three surfaces, matching Box2D's viewer:
// - right info panel (DrawControls): Show Timeline button, divergence flag, frame counter
// - left Outline / Detail window (DrawSampleWindows): the recorded scene tree and selection detail
// - right info panel (DrawControls): Show Timeline button, view toggles, frame counter, and the
// selection detail
// - left Outline window (DrawSampleWindows): the recorded scene tree
// - Timeline tab in the diagnostics drawer (DrawMetricsTab): transport, scrubber, keyframe readout
class ReplayViewer : public Sample
{
public:
enum SelKind
{
SelNone,
SelBody,
SelShape,
SelJoint,
SelQuery,
};
explicit ReplayViewer( SampleContext* context )
: Sample( context )
{
@ -142,7 +230,18 @@ public:
m_selBodyOrdinal = -1;
m_selSlot = -1;
m_selQuery = -1;
m_selQueryKey = 0;
m_selQueryLabel[0] = '\0';
m_selQueryKind = b3_recQueryOverlapAABB;
m_selQueryKindOrdinal = -1;
m_selQueryInstance = 0;
m_hoverQuery = -1;
m_revealSelection = false;
m_drawAllQueries = false;
m_queryIndexBuilt = false;
m_querySearch[0] = '\0';
m_querySearchKind = 0;
m_querySearchMinHits = 0;
m_requestLoadPopup = false;
m_generating = false;
m_popupBudgetMB = m_context->replayKeyframeBudgetMB;
@ -160,6 +259,10 @@ public:
m_context->pause = true;
m_selectTimelineTab = true;
// Z-up is a replay-only view choice and has no toggle elsewhere, so restore it on exit
// rather than leak a tilted view into the next sample.
m_prevViewZUp = m_context->viewZUp;
snprintf( m_path, sizeof( m_path ), "%s", m_context->replayFile );
// A fresh open gathers the keyframe policy through the Load popup, then pre-generates every
@ -188,6 +291,7 @@ public:
// debug-shape pool. Destroying the player here releases the replay world's pool entries first.
ClosePlayer();
m_context->showMetrics = m_prevShowMetrics;
m_context->viewZUp = m_prevViewZUp;
}
void ClosePlayer()
@ -198,12 +302,17 @@ public:
m_player = nullptr;
}
m_replayWorldId = b3_nullWorldId;
SetHoveredBody( b3_nullBodyId );
SetSelectedBody( b3_nullBodyId );
m_selKind = SelNone;
m_selBodyOrdinal = -1;
m_selSlot = -1;
m_selQuery = -1;
m_selQueryKey = 0;
m_selQueryLabel[0] = '\0';
m_selQueryKindOrdinal = -1;
m_selQueryInstance = 0;
m_queryIndexBuilt = false;
m_queryIndex.clear();
}
// Load m_path into a fresh player and adopt its world. Sets m_status on any failure: missing
@ -224,8 +333,8 @@ public:
b3Recording* recording = b3LoadRecordingFromFile( m_path );
if ( recording != nullptr )
{
m_player = b3RecPlayer_Create( b3Recording_GetData( recording ), b3Recording_GetSize( recording ),
m_context->workerCount );
m_player =
b3RecPlayer_Create( b3Recording_GetData( recording ), b3Recording_GetSize( recording ), m_context->workerCount );
b3DestroyRecording( recording );
}
else
@ -258,16 +367,31 @@ public:
m_info = b3RecPlayer_GetInfo( m_player );
snprintf( m_status, sizeof( m_status ), "loaded" );
// Frame the recorded motion. Bounds come from the trailing RecordingBounds record; an empty
// extent means an older recording, so leave the default view.
// Frame the recorded motion on a fresh open. A restart keeps the user's current camera.
if ( m_context->restart == false )
{
b3Vec3 extent = b3Sub( m_info.bounds.upperBound, m_info.bounds.lowerBound );
if ( extent.x > 0.0f || extent.y > 0.0f || extent.z > 0.0f )
{
float aspect = m_camera->m_height > 0 ? (float)m_camera->m_width / (float)m_camera->m_height : 1.0f;
m_camera->Frame( m_info.bounds, aspect, 1.4f );
}
FrameRecording();
}
}
// Fit the view to the recorded bounds for the current up axis. The player applies the recording's
// length scale on load, so frame against the same sim->display transform the frame loop uses, or
// the fit lands at the wrong distance. Reused on a Z-up toggle, where the transform rotates about
// the sim origin and would otherwise swing the bounds out of view. An empty extent means an older
// recording with no bounds record, so leave the default view.
void FrameRecording()
{
if ( m_player == nullptr )
{
return;
}
b3Vec3 extent = b3Sub( m_info.bounds.upperBound, m_info.bounds.lowerBound );
if ( extent.x > 0.0f || extent.y > 0.0f || extent.z > 0.0f )
{
m_camera->SetRenderTransform( b3GetLengthUnitsPerMeter(), m_context->viewZUp );
float aspect = m_camera->m_height > 0 ? (float)m_camera->m_width / (float)m_camera->m_height : 1.0f;
m_camera->Frame( m_info.bounds, aspect, 0.75f );
}
}
@ -287,8 +411,7 @@ public:
}
float fontSize = ImGui::GetFontSize();
ImGui::SetNextWindowPos( { m_camera->m_width * 0.5f, m_camera->m_height * 0.35f }, ImGuiCond_Appearing,
{ 0.5f, 0.5f } );
ImGui::SetNextWindowPos( { m_camera->m_width * 0.5f, m_camera->m_height * 0.35f }, ImGuiCond_Appearing, { 0.5f, 0.5f } );
ImGui::SetNextWindowSize( { 26.0f * fontSize, 0.0f }, ImGuiCond_Appearing );
if ( ImGui::BeginPopupModal( popupId, nullptr, ImGuiWindowFlags_AlwaysAutoResize ) == false )
@ -335,8 +458,8 @@ public:
}
ImGui::PushItemWidth( 10.0f * fontSize );
ImGui::SliderInt( "Memory budget (MB)", &m_popupBudgetMB, 128, 4096 );
ImGui::SliderInt( "Min sample interval", &m_popupMinInterval, 8, 60 );
ImGui::SliderInt( "Memory budget (MB)", &m_popupBudgetMB, 128, 8 * 1024 );
ImGui::SliderInt( "Min sample interval", &m_popupMinInterval, 8, 256 );
ImGui::PopItemWidth();
// Surface a failed open inline so Load can be retried.
@ -385,7 +508,7 @@ public:
if ( m_generating )
{
m_stepCount = m_player != nullptr ? b3RecPlayer_GetFrame( m_player ) : 0;
SetDrawOrigin( m_camera->m_worldEye );
SetDrawOrigin( m_camera->DrawOrigin() );
return;
}
@ -428,7 +551,7 @@ public:
m_stepCount = b3RecPlayer_GetFrame( m_player );
}
SetDrawOrigin( m_camera->m_worldEye );
SetDrawOrigin( m_camera->DrawOrigin() );
if ( B3_IS_NULL( m_replayWorldId ) )
{
@ -436,33 +559,53 @@ public:
return;
}
// Highlight the dynamic body under the cursor, matching the live samples.
PickRay pickRay = m_camera->BuildPickRay( m_context->mouseX, m_context->mouseY );
b3RayResult hover = b3World_CastRayClosest( m_replayWorldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() );
b3BodyId hovered = b3_nullBodyId;
if ( hover.hit && b3Body_GetType( b3Shape_GetBody( hover.shapeId ) ) == b3_dynamicBody )
{
hovered = b3Shape_GetBody( hover.shapeId );
}
SetHoveredBody( hovered );
// Mirror the ordinal selection into the renderer highlight each frame.
SetSelectedBody( SelectedBody() );
// Draw the replay world through the same adapter path the live samples use.
b3DebugDraw debugDraw;
MakeDebugDraw( &debugDraw );
ApplyGuiFlags( &debugDraw );
b3Vec3 r = { 1000.0f, 1000.0f, 1000.0f };
debugDraw.drawingBounds = b3OffsetAABB( { b3Neg( r ), r }, m_camera->m_worldEye );
debugDraw.drawingBounds = m_camera->DrawBounds(); // view-distance box in length units around the eye
// Drive the shared outline highlight from the selection. A shape selection outlines that
// shape alone, a body selection outlines the whole body. Set before the draw so the mask
// is filled by the draw callback.
if ( m_selKind == SelShape )
{
SetSelectedShape( SelectedShape() );
}
else if ( m_selKind == SelBody )
{
SetSelectedBody( SelectedBody() );
}
else
{
ClearSelection();
}
b3World_Draw( m_replayWorldId, &debugDraw, B3_DEFAULT_MASK_BITS );
DrawSelectionHighlight();
// Overlay the selected query's geometry and recorded hits on top of the world.
if ( m_selKind == SelQuery )
// Overlay query geometry and recorded hits on top of the world. The toggle draws every recorded
// query, otherwise just the selected one. Re-resolve the pinned query to this frame so a repeated
// query keeps drawing as the recording steps; it vanishes only on a frame that does not issue it.
m_selQuery = m_selKind == SelQuery ? ResolveSelectedQuery() : -1;
if ( m_drawAllQueries )
{
b3RecPlayer_DrawFrameQueries( m_player, &debugDraw, m_selQuery );
// Draw all, emphasizing the selected one so it stands out from the crowd.
b3RecPlayer_DrawFrameQueries( m_player, &debugDraw, -1, m_selQuery );
}
else if ( m_selQuery >= 0 )
{
b3RecPlayer_DrawFrameQueries( m_player, &debugDraw, m_selQuery, m_selQuery );
}
// Light up the query row under the cursor even when it is not the pinned one. Set during the
// outline draw, so the highlight trails the cursor by a frame, which is invisible in practice.
// Keep passing the selected index so hovering the selected query does not repaint over its
// emphasis color with the kind color.
if ( m_hoverQuery >= 0 )
{
b3RecPlayer_DrawFrameQueries( m_player, &debugDraw, m_hoverQuery, m_selQuery );
}
}
@ -473,6 +616,61 @@ public:
return false;
}
// Wider than the default so the detail pane, hosted in the info panel, has room for ids and vectors.
float InfoPanelWidthEm() const override
{
return 24.0f;
}
// F frames the selected query by its recorded world-space bounds. Absent this frame, fall through
// to the body paths.
bool FocusBounds( b3AABB* bounds ) override
{
// A shape selection frames that shape alone, finer than its whole body.
if ( m_selKind == SelShape )
{
b3ShapeId shape = SelectedShape();
if ( b3Shape_IsValid( shape ) )
{
*bounds = b3Shape_GetAABB( shape );
return true;
}
}
if ( m_selKind != SelQuery || m_player == nullptr )
{
return false;
}
int sel = ResolveSelectedQuery();
if ( sel < 0 )
{
return false;
}
*bounds = b3RecPlayer_GetFrameQuery( m_player, sel ).aabb;
return true;
}
// Frame the selection by body. A body, shape, or joint pick resolves to a body. A shape pick is
// framed tighter in FocusBounds, so this is its fallback. Null when nothing resolves.
b3BodyId FocusBody() const override
{
if ( m_selKind == SelBody || m_selKind == SelShape || m_selKind == SelJoint )
{
b3BodyId body = SelectedBody();
if ( b3Body_IsValid( body ) )
{
return body;
}
}
return b3_nullBodyId;
}
// Nothing selected: fit the recording, not the empty base world. Reuses the on-load framing so the
// current up-axis view transform is applied.
void FocusHome() override
{
FrameRecording();
}
// Transport row shared by the right panel and the Timeline tab. Play is green, Pause red.
void DrawTransport()
{
@ -539,7 +737,7 @@ public:
if ( m_player == nullptr )
{
ImGui::TextWrapped( "%s", m_status );
return true;
return false;
}
if ( ImGui::Button( "Show Timeline" ) )
@ -548,6 +746,16 @@ public:
m_selectTimelineTab = true;
}
// Overlay every recorded query, not just the one selected in the outline.
ImGui::Checkbox( "Draw All Queries", &m_drawAllQueries );
// View-only stand-up for recordings authored with +Z as up. The simulation is untouched.
// Reframe on a toggle so the rotated bounds stay centered, matching the fit done on load.
if ( ImGui::Checkbox( "Z-up View", &m_context->viewZUp ) )
{
FrameRecording();
}
if ( b3RecPlayer_HasDiverged( m_player ) )
{
ImGui::TextColored( PanelColor( b3_colorRed ), "****DIVERGED****" );
@ -555,7 +763,16 @@ public:
ImGui::TextDisabled( "Frame %d / %d%s", b3RecPlayer_GetFrame( m_player ), m_info.frameCount,
b3RecPlayer_IsAtEnd( m_player ) ? " (end)" : "" );
return true;
// Selection detail lives here in the info panel, not the Outline window, so the scene tree gets
// the full left column. The child takes the remaining panel height and scrolls a long detail.
// Return false so the panel adds no trailing separator below this full-height child.
ImGui::Separator();
ImGui::TextColored( PanelColor( b3_colorGoldenRod ), "Detail" );
ImGui::BeginChild( "DetailPane", { 0.0f, 0.0f } );
DrawDetail();
ImGui::EndChild();
return false;
}
// Selection resolution. The selection is stored as creation ordinals so it survives a backward
@ -570,16 +787,27 @@ public:
return b3RecPlayer_GetBodyId( m_player, m_selBodyOrdinal );
}
b3ShapeId SelectedShape() const
// Every shape on a body, sized to the real count so a body with many shapes still
// selects. The slot model breaks under a fixed cap once the count exceeds it.
void BodyShapes( std::vector<b3ShapeId>& buffer, b3BodyId bodyId ) const
{
int count = b3Body_GetShapeCount( bodyId );
buffer.resize( count );
if ( count > 0 )
{
b3Body_GetShapes( bodyId, buffer.data(), count );
}
}
b3ShapeId SelectedShape()
{
b3BodyId body = SelectedBody();
if ( m_selKind != SelShape || b3Body_IsValid( body ) == false )
{
return b3_nullShapeId;
}
b3ShapeId shapes[32];
int n = b3Body_GetShapes( body, shapes, 32 );
return ( m_selSlot >= 0 && m_selSlot < n ) ? shapes[m_selSlot] : b3_nullShapeId;
BodyShapes( m_shapeBuffer, body );
return ( m_selSlot >= 0 && m_selSlot < (int)m_shapeBuffer.size() ) ? m_shapeBuffer[m_selSlot] : b3_nullShapeId;
}
b3JointId SelectedJoint() const
@ -594,6 +822,47 @@ public:
return ( m_selSlot >= 0 && m_selSlot < n ) ? joints[m_selSlot] : b3_nullJointId;
}
// Map the pinned query to this frame's flat query index, or -1 when the frame did not issue it. A
// tagged query is matched by its caller id and instance, which track the logical query across steps
// and seeks regardless of call order. An untagged query falls back to the per-kind call position.
int ResolveSelectedQuery() const
{
if ( m_player == nullptr || m_selKind != SelQuery )
{
return -1;
}
int n = b3RecPlayer_GetFrameQueryCount( m_player );
if ( m_selQueryKey != 0 )
{
int instance = 0;
for ( int i = 0; i < n; ++i )
{
if ( b3RecPlayer_GetFrameQuery( m_player, i ).key == m_selQueryKey )
{
if ( instance == m_selQueryInstance )
{
return i;
}
instance += 1;
}
}
return -1;
}
if ( m_selQueryKindOrdinal < 0 )
{
return -1;
}
int ord = 0;
for ( int i = 0; i < n; ++i )
{
if ( b3RecPlayer_GetFrameQuery( m_player, i ).type == m_selQueryKind && ord++ == m_selQueryKindOrdinal )
{
return i;
}
}
return -1;
}
int FindBodyOrdinal( b3BodyId body ) const
{
int count = b3RecPlayer_GetBodyCount( m_player );
@ -622,12 +891,11 @@ public:
m_selKind = SelNone;
return;
}
b3ShapeId shapes[32];
int n = b3Body_GetShapes( body, shapes, 32 );
BodyShapes( m_shapeBuffer, body );
int slot = -1;
for ( int i = 0; i < n; ++i )
for ( int i = 0; i < (int)m_shapeBuffer.size(); ++i )
{
if ( B3_ID_EQUALS( shapes[i], shape ) )
if ( B3_ID_EQUALS( m_shapeBuffer[i], shape ) )
{
slot = i;
break;
@ -665,8 +933,8 @@ public:
}
}
// Highlight the current selection without touching the world: AABB box, body axes, center of
// mass, and contacts. Joints mark both connected body centers.
// Selection overlays drawn on top of the outline highlight: body axes, center of mass, and
// contacts. Joints mark both connected body centers.
void DrawSelectionHighlight()
{
if ( m_selKind == SelShape )
@ -677,7 +945,6 @@ public:
return;
}
b3BodyId body = b3Shape_GetBody( shape );
DrawBounds( b3Shape_GetAABB( shape ), 0.0f, MakeColor( b3_colorYellow ) );
DrawAxes( b3Body_GetTransform( body ), 0.5f );
DrawPoint( b3Body_GetWorldCenterOfMass( body ), 8.0f, MakeColor( b3_colorYellow ) );
DrawBodyContacts( body );
@ -689,7 +956,6 @@ public:
{
return;
}
DrawBounds( b3Body_ComputeAABB( body ), 0.0f, MakeColor( b3_colorYellow ) );
DrawAxes( b3Body_GetTransform( body ), 0.5f );
DrawPoint( b3Body_GetWorldCenterOfMass( body ), 8.0f, MakeColor( b3_colorYellow ) );
DrawBodyContacts( body );
@ -714,7 +980,8 @@ public:
}
}
// Left-edge Outline / Detail window plus the keyframe-policy popup.
// Left-edge Outline window plus the keyframe-policy popup. The selection detail lives in the right
// info panel (DrawControls), so the tree owns the whole column.
void DrawSampleWindows() override
{
DrawLoadPopup();
@ -741,26 +1008,171 @@ public:
ImGuiWindowFlags_NoTitleBar );
ImGui::TextColored( PanelColor( b3_colorGoldenRod ), "Outline" );
float avail = ImGui::GetContentRegionAvail().y;
ImGui::BeginChild( "OutlineTree", { 0.0f, 0.55f * avail } );
ImGui::BeginChild( "OutlineTree", { 0.0f, 0.0f } );
DrawOutlineTree();
ImGui::EndChild();
ImGui::Separator();
ImGui::TextColored( PanelColor( b3_colorGoldenRod ), "Detail" );
ImGui::BeginChild( "DetailPane", { 0.0f, 0.0f } );
DrawDetail();
ImGui::EndChild();
ImGui::End();
}
// Scan the whole recording once to index every recorded query. Drives the player frame 0 to end,
// then seeks back to where the user was so the live view is undisturbed. One full replay pass, so
// build lazily and cache. The scan replays the same deterministic path as playback, so it must not
// trip the divergence flag on a clean recording.
void BuildQueryIndex()
{
m_queryIndex.clear();
m_queryIndexBuilt = true;
if ( m_player == nullptr )
{
return;
}
int resume = b3RecPlayer_GetFrame( m_player );
b3RecPlayer_SeekFrame( m_player, 0 );
while ( b3RecPlayer_IsAtEnd( m_player ) == false )
{
b3RecPlayer_StepFrame( m_player );
int frame = b3RecPlayer_GetFrame( m_player );
int qn = b3RecPlayer_GetFrameQueryCount( m_player );
int kindOrdinal[ReplayQueryTypeCount] = { 0 };
// Running occurrence count per key, so disambiguating same-key calls stays linear in the frame.
std::unordered_map<uint64_t, int> keyInstance;
for ( int i = 0; i < qn; ++i )
{
b3RecQueryInfo q = b3RecPlayer_GetFrameQuery( m_player, i );
QueryIndexRow row;
row.frame = frame;
row.type = q.type;
row.kindOrdinal = kindOrdinal[q.type]++;
row.instance = q.key != 0 ? keyInstance[q.key]++ : 0;
row.key = q.key;
row.id = q.id;
row.name = q.name;
row.filter = q.filter;
row.origin = q.origin;
row.hitCount = q.hitCount;
m_queryIndex.push_back( row );
}
}
b3RecPlayer_SeekFrame( m_player, resume );
m_replayWorldId = b3RecPlayer_GetWorldId( m_player );
}
// Search box over the whole-recording query index, drawn above the scene tree. The index is built
// lazily on first open, then cached until the recording changes. A result jumps to its frame and
// pins the query, so stepping from there tracks it.
void DrawQuerySearch()
{
if ( ImGui::CollapsingHeader( "Query Search" ) == false )
{
return;
}
if ( m_queryIndexBuilt == false )
{
BuildQueryIndex();
}
float fontSize = ImGui::GetFontSize();
ImGui::PushItemWidth( -1.0f );
ImGui::InputTextWithHint( "##qsearch", "Filter by kind, frame, or category...", m_querySearch, sizeof( m_querySearch ) );
ImGui::PopItemWidth();
// Kind 0 is any, otherwise a specific b3RecQueryType in enum order.
const char* kindNames[ReplayQueryTypeCount + 1] = {
"any kind", "overlap AABB", "overlap shape", "cast ray",
"cast shape", "cast ray closest", "cast mover", "collide mover",
};
ImGui::PushItemWidth( 8.0f * fontSize );
ImGui::Combo( "Kind", &m_querySearchKind, kindNames, ReplayQueryTypeCount + 1 );
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushItemWidth( 4.0f * fontSize );
ImGui::InputInt( "Min hits", &m_querySearchMinHits, 0, 0 );
ImGui::PopItemWidth();
if ( m_querySearchMinHits < 0 )
{
m_querySearchMinHits = 0;
}
if ( ImGui::SmallButton( "Rebuild" ) )
{
BuildQueryIndex();
}
ImGui::SameLine();
ImGui::TextDisabled( "%d recorded", (int)m_queryIndex.size() );
ImGui::BeginChild( "##qresults", { 0.0f, 11.0f * fontSize }, ImGuiChildFlags_Borders );
int shown = 0;
for ( int r = 0; r < (int)m_queryIndex.size(); ++r )
{
const QueryIndexRow& row = m_queryIndex[r];
if ( m_querySearchKind != 0 && (int)row.type != m_querySearchKind - 1 )
{
continue;
}
if ( row.hitCount < m_querySearchMinHits )
{
continue;
}
// The label (name + id) is searchable, so typing a label or an entity id narrows results.
char base[64];
FormatQueryLabel( base, sizeof( base ), row.name, row.id, row.type, row.kindOrdinal );
char text[112];
snprintf( text, sizeof( text ), "f%-5d %s (%d) cat 0x%llx", row.frame, base, row.hitCount,
(unsigned long long)row.filter.categoryBits );
if ( ContainsNoCase( text, m_querySearch ) == false )
{
continue;
}
// Hold the full text plus the ###qr id so a long label cannot truncate the id and collide rows.
char label[128];
snprintf( label, sizeof( label ), "%s###qr%d", text, r );
ImGui::PushStyleColor( ImGuiCol_Text, PanelColor( QueryKindColor( row.type ) ) );
bool clicked = ImGui::Selectable( label, false );
ImGui::PopStyleColor();
if ( clicked )
{
b3RecPlayer_SeekFrame( m_player, row.frame );
m_replayWorldId = b3RecPlayer_GetWorldId( m_player );
m_context->pause = true;
m_frameAccumulator = 0.0f;
m_selKind = SelQuery;
m_selQueryKey = row.key;
FormatQueryLabel( m_selQueryLabel, sizeof( m_selQueryLabel ), row.name, row.id, row.type, row.kindOrdinal );
m_selQueryKind = row.type;
m_selQueryKindOrdinal = row.kindOrdinal;
m_selQueryInstance = row.instance;
m_selQuery = ResolveSelectedQuery();
m_revealSelection = true; // expand and scroll the Queries node to the pinned row
}
shown++;
}
if ( shown == 0 )
{
ImGui::TextDisabled( "No matching queries." );
}
ImGui::EndChild();
ImGui::Separator();
}
// Recorded scene tree: bodies by creation ordinal, expandable to their shapes and joints.
// Destroyed bodies keep their ordinal but are not shown, so a stored selection stays put.
void DrawOutlineTree()
{
// A viewport pick asks the tree to reveal its target once: expand the owning body and scroll
// to the row. Consumed at the end so it never fights the user's own expand/collapse.
// Cleared each draw, set again if the cursor lands on a query row this frame.
m_hoverQuery = -1;
// Whole-recording query search sits above the scene tree. A jump from there can set the reveal
// flag, so draw it before capturing reveal below.
DrawQuerySearch();
// A viewport pick or a search jump asks the tree to reveal its target once: expand the owner and
// scroll to the row. Consumed at the end so it never fights the user's own expand/collapse.
bool reveal = m_revealSelection;
int count = b3RecPlayer_GetBodyCount( m_player );
@ -806,13 +1218,12 @@ public:
continue;
}
b3ShapeId shapes[32];
int sn = b3Body_GetShapes( body, shapes, 32 );
for ( int s = 0; s < sn; ++s )
BodyShapes( m_shapeBuffer, body );
for ( int s = 0; s < (int)m_shapeBuffer.size(); ++s )
{
b3ShapeType shapeType = b3Shape_GetType( m_shapeBuffer[s] );
char sl[64];
snprintf( sl, sizeof( sl ), "Shape %d %s###b%ds%d", s, ReplayShapeTypeName( b3Shape_GetType( shapes[s] ) ),
ord, s );
snprintf( sl, sizeof( sl ), "Shape %d %s###b%ds%d", s, ReplayShapeTypeName( shapeType ), ord, s );
ImGuiTreeNodeFlags lf =
ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_NoTreePushOnOpen;
if ( m_selKind == SelShape && m_selBodyOrdinal == ord && m_selSlot == s )
@ -856,28 +1267,59 @@ public:
ImGui::TreePop();
}
// Spatial queries recorded for the current frame. Selecting one overlays its geometry and
// recorded hits on the world. The list is rebuilt each frame, so a selection is by index only.
int qn = b3RecPlayer_GetFrameQueryCount( m_player );
// Spatial queries recorded for the current frame. A row is colored by kind and numbered within
// its kind, so the Nth ray cast keeps the same label every frame the app issues it. Selecting one
// pins that kind and ordinal, and the overlay and detail then track it as the recording steps.
int qn = b3RecPlayer_GetFrameQueryCount( m_player );
char ql[32];
snprintf( ql, sizeof( ql ), "Queries (%d)###queries", qn );
if ( reveal && m_selKind == SelQuery )
{
ImGui::SetNextItemOpen( true );
}
if ( ImGui::TreeNodeEx( ql, ImGuiTreeNodeFlags_SpanAvailWidth ) )
{
int kindOrdinal[ReplayQueryTypeCount] = { 0 };
// Count earlier same-key queries as we go so a tag issued several times this frame (the mover
// slide loop) gets a stable instance number. Untagged queries have no shared identity.
std::unordered_map<uint64_t, int> keyInstance;
for ( int i = 0; i < qn; ++i )
{
b3RecQueryInfo q = b3RecPlayer_GetFrameQuery( m_player, i );
char qi[64];
snprintf( qi, sizeof( qi ), "%s (%d)###q%d", ReplayQueryTypeName( q.type ), q.hitCount, i );
int ord = kindOrdinal[q.type]++;
int instance = q.key != 0 ? keyInstance[q.key]++ : 0;
char base[64];
FormatQueryLabel( base, sizeof( base ), q.name, q.id, q.type, ord );
char qi[96];
snprintf( qi, sizeof( qi ), "%s (%d)###q%d", base, q.hitCount, i );
ImGuiTreeNodeFlags lf =
ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_NoTreePushOnOpen;
if ( m_selKind == SelQuery && m_selQuery == i )
bool pinned = m_selKind == SelQuery &&
( m_selQueryKey != 0 ? ( q.key == m_selQueryKey && instance == m_selQueryInstance )
: ( q.type == m_selQueryKind && ord == m_selQueryKindOrdinal ) );
if ( pinned )
{
lf |= ImGuiTreeNodeFlags_Selected;
}
ImGui::PushStyleColor( ImGuiCol_Text, PanelColor( QueryKindColor( q.type ) ) );
ImGui::TreeNodeEx( qi, lf );
ImGui::PopStyleColor();
if ( reveal && pinned )
{
ImGui::SetScrollHereY( 0.5f );
}
if ( ImGui::IsItemHovered() )
{
m_hoverQuery = i;
}
if ( ImGui::IsItemClicked() )
{
m_selKind = SelQuery;
m_selQueryKey = q.key;
FormatQueryLabel( m_selQueryLabel, sizeof( m_selQueryLabel ), q.name, q.id, q.type, ord );
m_selQueryKind = q.type;
m_selQueryKindOrdinal = ord;
m_selQueryInstance = instance;
m_selQuery = i;
}
}
@ -1059,13 +1501,18 @@ public:
}
}
// Detail for the selected recorded query: type, filter, origin, and the recorded hit shapes.
// Detail for the pinned recorded query: type, filter, origin, sweep, and the recorded hit shapes.
// The pin is a kind plus per-kind ordinal, so re-resolve it to this frame; absent means the frame
// did not issue it, while the pin stays put and repopulates when the query returns.
void DrawQueryDetail()
{
int count = b3RecPlayer_GetFrameQueryCount( m_player );
if ( m_selQuery < 0 || m_selQuery >= count )
m_selQuery = ResolveSelectedQuery();
if ( m_selQuery < 0 )
{
ImGui::TextDisabled( "Query not present at this frame." );
ImGui::PushStyleColor( ImGuiCol_Text, PanelColor( QueryKindColor( m_selQueryKind ) ) );
ImGui::TextUnformatted( m_selQueryLabel[0] != '\0' ? m_selQueryLabel : "query" );
ImGui::PopStyleColor();
ImGui::TextDisabled( "Not present at this frame." );
return;
}
@ -1075,18 +1522,39 @@ public:
return;
}
ImGui::Text( "type %s", ReplayQueryTypeName( q.type ) );
if ( q.name != nullptr )
{
ImGui::Text( "label %s", q.name );
}
if ( q.id != 0 )
{
ImGui::Text( "id %llu", (unsigned long long)q.id );
}
if ( q.key != 0 )
{
ImGui::Text( "type %s", ReplayQueryTypeName( q.type ) );
}
else
{
ImGui::Text( "type %s #%d", ReplayQueryTypeName( q.type ), m_selQueryKindOrdinal );
}
ImGui::Text( "category 0x%016llx", (unsigned long long)q.filter.categoryBits );
ImGui::Text( "mask 0x%016llx", (unsigned long long)q.filter.maskBits );
if ( q.type != b3_recQueryOverlapAABB )
{
ImGui::Text( "origin (%.2f, %.2f, %.2f)", q.origin.x, q.origin.y, q.origin.z );
}
// Translation is the ray or sweep vector. Overlaps and collide-mover leave it zero.
if ( q.type == b3_recQueryCastRay || q.type == b3_recQueryCastRayClosest || q.type == b3_recQueryCastShape ||
q.type == b3_recQueryCastMover )
{
ImGui::Text( "sweep (%.2f, %.2f, %.2f)", q.translation.x, q.translation.y, q.translation.z );
}
ImGui::Text( "hits %d", q.hitCount );
// Hit shape ids as one wrapped list so a many-hit query stays compact.
char line[256];
int len = 0;
int len = 0;
for ( int h = 0; h < q.hitCount && len < (int)sizeof( line ) - 12; ++h )
{
b3RecQueryHit hit = b3RecPlayer_GetFrameQueryHit( m_player, m_selQuery, h );
@ -1184,8 +1652,7 @@ public:
ImGui::SameLine();
ImGui::Text( " %.0f hz, %d sub-steps", hz, m_info.subStepCount );
ImGui::SameLine();
ImGui::Text( " bodies %d shapes %d contacts %d joints %d", c.bodyCount, c.shapeCount, c.contactCount,
c.jointCount );
ImGui::Text( " bodies %d shapes %d contacts %d joints %d", c.bodyCount, c.shapeCount, c.contactCount, c.jointCount );
if ( divergeFrame >= 0 )
{
@ -1207,7 +1674,8 @@ public:
}
PickRay pickRay = m_camera->BuildPickRay( p.x, p.y );
b3RayResult result = b3World_CastRayClosest( m_replayWorldId, pickRay.origin, pickRay.translation, b3DefaultQueryFilter() );
b3QueryFilter queryFilter = b3DefaultQueryFilter();
b3RayResult result = b3World_CastRayClosest( m_replayWorldId, pickRay.origin, pickRay.translation, queryFilter );
SelectShape( result.hit ? result.shapeId : b3_nullShapeId );
}
@ -1226,7 +1694,7 @@ public:
b3RecPlayer* m_player;
b3WorldId m_replayWorldId; // player-owned world we draw and pick; separate from the empty base world
b3RecPlayerInfo m_info; // cached at load for the timeline readout and camera framing
b3RecPlayerInfo m_info; // cached at load for the timeline readout and camera framing
char m_path[256];
char m_status[128];
float m_speed;
@ -1234,7 +1702,8 @@ public:
bool m_loop;
bool m_selectTimelineTab; // one-shot: focus the Timeline tab on the next draw
bool m_prevShowMetrics; // restore the drawer state on exit
bool m_prevShowMetrics; // restore the drawer state on exit
bool m_prevViewZUp; // restore the up-axis view on exit
// Load popup state. A fresh open configures the keyframe policy here, then the popup switches to a
// progress bar while every keyframe is generated up front. Temporaries hold the in-popup edits so
@ -1245,11 +1714,33 @@ public:
int m_popupMinInterval;
// Selection by creation ordinal so it survives a backward seek that rebuilds the world.
SelKind m_selKind;
SelectionKind m_selKind;
int m_selBodyOrdinal;
int m_selSlot; // shape or joint slot within the selected body
int m_selQuery; // query index, only meaningful for the current frame
bool m_revealSelection; // one-shot: expand and scroll the tree to a viewport pick
int m_selSlot; // shape or joint slot within the selected body
int m_selQuery; // resolved query index for the current frame, recomputed from the pin below
bool m_revealSelection; // one-shot: expand and scroll the tree to a viewport pick or search jump
bool m_drawAllQueries; // overlay every recorded query, not just the selected one
int m_hoverQuery; // outline query row under the cursor, drawn as a transient highlight
// Re-usable buffer for getting all shapes from a body.
std::vector<b3ShapeId> m_shapeBuffer;
// A pinned query prefers its identity key (the hash of the caller id and label), the robust identity
// that tracks the logical query regardless of call order. A tag issued several times per step (the
// mover slide loop) shares one key across its calls, so the instance index tells those calls apart.
// Untagged queries (key 0) fall back to the per-kind call position, stable only while queries keep
// the same order each frame.
uint64_t m_selQueryKey;
char m_selQueryLabel[64]; // pinned query's display label, for the absent-frame readout
b3RecQueryType m_selQueryKind;
int m_selQueryKindOrdinal;
int m_selQueryInstance; // occurrence among same-key queries this frame, 0 unless a tag repeats
std::vector<QueryIndexRow> m_queryIndex;
bool m_queryIndexBuilt;
char m_querySearch[64];
int m_querySearchKind; // 0 any, else b3RecQueryType + 1
int m_querySearchMinHits; // hide queries with fewer hits
};
static int sampleReplayViewer = RegisterReplay( "Replay", "Viewer", ReplayViewer::Create );

View file

@ -679,7 +679,7 @@ public:
DrawAxes( b3WorldTransform_identity, 2.0f );
b3Pos cp = m_camera->m_worldEye;
b3Pos cp = m_camera->DrawOrigin();
b3TreeNode* nodes = m_tree.nodes;
float distSquared = m_drawDistance * m_drawDistance * 1000.0f * 1000.0f;

View file

@ -135,12 +135,26 @@ vec3 preethamSky(vec3 view_dir, vec3 sun_dir, float turbidity)
return max(rgb, vec3(0.0));
}
// Rotate a sky direction from simulation space into the model's Y-up
// frame. Y-up sims pass through. Z-up sims need Rx(-90), (x,y,z) ->
// (x, z, -y), the same map the renderer folds into its view transform so
// sim +Z becomes view up. zUp is 0.0 or 1.0. View ray and sun rotate
// together so their relative angle is preserved, only horizon and zenith
// reorient.
vec3 preethamToYUp(vec3 v, float zUp)
{
return mix(v, vec3(v.x, v.z, - v.y), zUp);
}
// Convenience wrapper: raw Preetham scaled by the empirical luminance
// factor and the caller's below-horizon fade weight (1 above horizon,
// 0 below). The sky backdrop shader and the IBL sky cubemap both call
// this so they're guaranteed to agree pixel-for-pixel.
vec3 preethamSkyScaled(vec3 view_dir, vec3 sun_dir, float turbidity, float fade)
// this so they're guaranteed to agree pixel-for-pixel. zUp reorients the
// model for a z-up simulation, see preethamToYUp.
vec3 preethamSkyScaled(vec3 view_dir, vec3 sun_dir, float turbidity, float fade, float zUp)
{
return preethamSky(view_dir, sun_dir, turbidity) * PREETHAM_LUMINANCE_SCALE * fade;
vec3 v = preethamToYUp(view_dir, zUp);
vec3 s = preethamToYUp(sun_dir, zUp);
return preethamSky(v, s, turbidity) * PREETHAM_LUMINANCE_SCALE * fade;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -72,7 +72,7 @@ void main()
layout(binding = 1)uniform sky_ub_pass
{
vec4 sun_dir_world; // .xyz = world dir TO sun (normalized), .w = below-horizon fade weight [0,1]
vec4 sky_params; // .x = turbidity (Preetham T), .yzw = reserved
vec4 sky_params; // .x = turbidity (Preetham T), .y = z-up flag (0 or 1), .zw = reserved
vec4 camera_pos; // .xyz = world camera position, .w = unused
};
@ -94,7 +94,7 @@ void main()
// preethamSkyScaled so the IBL sky cubemap (sky_to_cube.glsl) sees
// the same backdrop. Fade weight comes from the C side via
// sun_dir_world.w (1 above horizon, 0 below).
vec3 rgb = preethamSkyScaled(view_dir, sun_dir, sky_params.x, sun_dir_world.w);
vec3 rgb = preethamSkyScaled(view_dir, sun_dir, sky_params.x, sun_dir_world.w, sky_params.y);
out_color = vec4(rgb, 1.0);
}

View file

@ -46,10 +46,10 @@ void main()
layout(binding = 0)uniform ub_face
{
// Three rows of a mat3 basis. Stored as vec4 for std140 alignment,
// .xyz are the axis vectors, .w is unused (.w on face_forward
// doubles as the below-horizon fade weight to save a UBO slot).
// .xyz are the axis vectors. The .w lanes carry scalars to save UBO
// slots: face_up.w = z-up flag, face_forward.w = below-horizon fade.
vec4 face_right; // .xyz = world-space face right axis
vec4 face_up; // .xyz = world-space face up axis
vec4 face_up; // .xyz = world-space face up axis, .w = z-up flag (0 or 1)
vec4 face_forward; // .xyz = world-space face forward axis, .w = fade weight
vec4 sun_dir_world; // .xyz = world-space direction TO sun, .w = turbidity
};
@ -62,7 +62,7 @@ void main()
vec2 uv = v_uv * 2.0 - 1.0; // [-1, +1] across the face
vec3 dir = normalize(face_forward.xyz + uv.x * face_right.xyz + uv.y * face_up.xyz);
vec3 rgb = preethamSkyScaled(dir, sun_dir_world.xyz, sun_dir_world.w, face_forward.w);
vec3 rgb = preethamSkyScaled(dir, sun_dir_world.xyz, sun_dir_world.w, face_forward.w, face_up.w);
out_color = vec4(rgb, 1.0);
}
#pragma sokol @end