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

@ -419,7 +419,8 @@ B3_API void b3RecPlayer_SetDebugShapeCallbacks( b3RecPlayer* player, b3CreateDeb
/// @param player a valid player handle
/// @param draw debug draw callbacks
/// @param queryIndex index of the frame query to draw, or -1 to draw all of them
B3_API void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int queryIndex );
/// @param selectedIndex index of the query to emphasize (reserved color plus a label), or -1 for none
B3_API void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int queryIndex, int selectedIndex );
/// The kind of a recorded spatial query, matching the public query and cast functions.
typedef enum b3RecQueryType
@ -438,10 +439,13 @@ typedef struct b3RecQueryInfo
{
b3RecQueryType type;
b3QueryFilter filter;
b3AABB aabb; // overlap AABB, world space
b3AABB aabb; // world-space bounds of the query, swept for casts
b3Pos origin; // query origin (zero for overlap AABB)
b3Vec3 translation; // ray and cast translation
int hitCount; // number of recorded results
uint64_t key; // identity key, the hash of (id, name), 0 if untagged
uint64_t id; // query id, 0 if none
const char* name; // query label, NULL if none
} b3RecQueryInfo;
/// One result of a recorded spatial query.
@ -834,12 +838,6 @@ B3_API b3WorldId b3Shape_GetWorld( b3ShapeId shapeId );
/// Returns true if the shape is a sensor
B3_API bool b3Shape_IsSensor( b3ShapeId shapeId );
/// Set the shape name. Up to B3_NAME_LENGTH characters including null termination.
B3_API void b3Shape_SetName( b3ShapeId shapeId, const char* name );
/// Get the shape name.
B3_API const char* b3Shape_GetName( b3ShapeId shapeId );
/// Set the user data for a shape
B3_API void b3Shape_SetUserData( b3ShapeId shapeId, void* userData );

View file

@ -14,6 +14,12 @@ B3_API void b3SetLengthUnitsPerMeter( float lengthUnits );
/// Get the current length units per meter.
B3_API float b3GetLengthUnitsPerMeter( void );
/// Set the threshold for logging stalls.
B3_API void b3SetStallThreshold( float seconds );
/// Get the threshold for logging stalls.
B3_API float b3GetStallThreshold( void );
// Used to detect bad values. In float mode positions greater than about 16km have precision
// problems, so 100km is a safe limit. Large world mode keeps coordinates accurate much farther
// from the origin, so the sanity limit widens to keep valid far-field positions from tripping it.

View file

@ -562,6 +562,28 @@ B3_API b3Quat b3MakeQuatFromMatrix( const b3Matrix3* m );
/// Find a quaternion that rotates one vector to another.
B3_API b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 );
/// Twist angle around the z-axis, used for twist limit and revolute angle limit
B3_INLINE float b3GetTwistAngle( b3Quat q )
{
// Account for polarity to keep the twist angle in range.
// This is simpler than asking the user to check polarity or unwinding.
float twist = q.s < 0.0f ? b3Atan2( -q.v.z, -q.s ) : b3Atan2( q.v.z, q.s );
twist *= 2.0f;
B3_ASSERT( -B3_PI <= twist && twist <= B3_PI );
return twist;
}
/// Swing angle used for cone limit
B3_INLINE float b3GetSwingAngle( b3Quat q )
{
// Polarity should not matter because all terms are squared.
float x = sqrtf( q.v.z * q.v.z + q.s * q.s );
float y = sqrtf( q.v.x * q.v.x + q.v.y * q.v.y );
float swing = 2.0f * b3Atan2( y, x );
B3_ASSERT( 0.0f <= swing && swing <= B3_PI );
return swing;
}
/// Linearly interpolate and normalize between two quaternions
B3_INLINE b3Quat b3NLerp( b3Quat q1, b3Quat q2, float alpha )
{
@ -1033,6 +1055,24 @@ B3_INLINE b3Vec3 b3ClosestPointToAABB( b3Vec3 point, b3AABB a )
return b3Clamp( point, a.lowerBound, a.upperBound );
}
/// The closest points between to segments or infinite lines.
typedef struct b3SegmentDistanceResult
{
b3Vec3 point1;
float fraction1;
b3Vec3 point2;
float fraction2;
} b3SegmentDistanceResult;
/// Compute the closest point on the segment a-b to the target q.
B3_API b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q );
/// Compute the closest points on two infinite lines.
B3_API b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
/// Compute the closest points on two line segments.
B3_API b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
/// Is this a valid number? Not NaN or infinity.
B3_API bool b3IsValidFloat( float a );

View file

@ -10,7 +10,7 @@
#include <stdint.h>
#define B3_DEFAULT_CATEGORY_BITS 1
#define B3_DEFAULT_CATEGORY_BITS UINT64_MAX
#define B3_DEFAULT_MASK_BITS UINT64_MAX
/// Task interface
@ -451,9 +451,6 @@ typedef enum b3ShapeType
/// @ingroup shape
typedef struct b3ShapeDef
{
/// Optional body name for debugging. Up to B3_NAME_LENGTH characters (including null termination)
const char* name;
/// Use this to store application specific shape data.
void* userData;
@ -1287,6 +1284,16 @@ typedef struct b3QueryFilter
/// The collision mask bits. This states the shape categories that this
/// query would accept for collision.
uint64_t maskBits;
/// Optional id combined with @ref name to identify this query in a recording, e.g. an entity id.
/// Need not be unique on its own. 0 with a null name means untagged. Ignored when not recording.
uint64_t id;
/// Optional label combined with @ref id to identify this query, e.g. "bullet". Need not be unique
/// on its own. The recorder hashes (id, name) into one stable key the viewer tracks the query by,
/// so the same id and name pair identifies the same query across frames. NULL means none. Ignored
/// when not recording.
const char* name;
} b3QueryFilter;
/// Use this to initialize your query filter
@ -1449,6 +1456,7 @@ typedef struct b3WorldCastOutput
#else
/// Same type in single precision.
typedef b3CastOutput b3WorldCastOutput;
#endif
@ -1699,7 +1707,7 @@ typedef struct b3TreeNode
} b3TreeNode;
/// Dynamic tree version for compatibility testing.
#define B3_DYNAMIC_TREE_VERSION 0x8E867C390754064Bull
#define B3_DYNAMIC_TREE_VERSION 0x93EDAF889FD30B4Aull
/// The dynamic tree structure. This should be considered private data.
/// It is placed here for performance reasons.
@ -1944,7 +1952,7 @@ typedef struct b3HullFace
} b3HullFace;
/// 64-bit hull version. Useful for validating serialized data.
#define B3_HULL_VERSION 0x8F5034CF987D4FD9ull
#define B3_HULL_VERSION 0x9D4716CE3793900Eull
/// A convex hull.
/// @note This data structure has data hanging off the end and cannot be directly copied.
@ -2062,7 +2070,7 @@ typedef struct b3MeshDef
} b3MeshDef;
/// 64-bit mesh version. Useful for validating serialized data.
#define B3_MESH_VERSION 0x4A1E7B2C8D5F3091ull
#define B3_MESH_VERSION 0xABD11AB62A6E886Dull
/// Triangle mesh edge flags.
typedef enum b3MeshEdgeFlags
@ -2240,7 +2248,7 @@ typedef struct b3HeightFieldDef
#define B3_HEIGHT_FIELD_HOLE 0xFF
/// 64-bit height-field version. Useful for validating serialized data.
#define B3_HEIGHT_FIELD_VERSION 0x3D9A1F6C24E87B05ull
#define B3_HEIGHT_FIELD_VERSION 0x8B18CBD138A6BC84ull
/// A height field with compressed storage.
/// @note This data structure has data hanging off the end and cannot be directly copied.
@ -2387,7 +2395,7 @@ typedef struct b3CompoundDef
} b3CompoundDef;
/// The compound version depends on the tree, mesh, and hull versions.
#define B3_COMPOUND_VERSION ( 0x902AC5D34D9BD452ull ^ B3_DYNAMIC_TREE_VERSION ^ B3_MESH_VERSION ^ B3_HULL_VERSION )
#define B3_COMPOUND_VERSION ( 0x830778DB07086EB4ull ^ B3_DYNAMIC_TREE_VERSION ^ B3_MESH_VERSION ^ B3_HULL_VERSION )
/// Meshes used in compounds have limited space for materials. If you have
/// a mesh with many materials, you can use it outside of the compound.
@ -2949,6 +2957,9 @@ typedef struct b3DebugDraw
/// Draw a sphere.
void ( *DrawSphereFcn )( b3Pos p, float radius, b3HexColor color, float alpha, void* context );
/// Draw a capsule.
void ( *DrawCapsuleFcn )( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, void* context );
/// Draw a bounding box.
void ( *DrawBoundsFcn )( b3AABB aabb, b3HexColor color, void* context );

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

View file

@ -1,17 +1,19 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include <stddef.h>
#include <string.h>
#define B3_TYPE_OF( A ) __typeof__( A )
// Swap two same-size lvalues through a byte buffer. Avoids __typeof__ so it builds on any C compiler.
#define B3_SWAP( x, y ) \
do \
{ \
B3_TYPE_OF( x ) B3_SWAP_TEMP = x; \
x = y; \
y = B3_SWAP_TEMP; \
_Static_assert( sizeof( x ) == sizeof( y ), "size mismatch" ); \
char B3_SWAP_TEMP[sizeof( x )]; \
memcpy( B3_SWAP_TEMP, &( x ), sizeof( x ) ); \
memcpy( &( x ), &( y ), sizeof( x ) ); \
memcpy( &( y ), B3_SWAP_TEMP, sizeof( x ) ); \
} \
while ( 0 )

View file

@ -55,18 +55,9 @@ void* b3AllocateElement( b3BlockAllocator* allocator )
return element;
}
int startIndex = allocator->nextIndex;
int startOffset = startIndex & ( B3_BLOCK_SIZE - 1 );
int index = allocator->nextIndex++;
if ( startOffset + 1 > B3_BLOCK_SIZE )
{
startIndex = ( startIndex + B3_BLOCK_SIZE ) & ~( B3_BLOCK_SIZE - 1 );
}
allocator->nextIndex = startIndex + 1;
int lastIndex = allocator->nextIndex - 1;
int requiredBlockCount = ( lastIndex >> B3_BLOCK_EXPONENT ) + 1;
int requiredBlockCount = ( index >> B3_BLOCK_EXPONENT ) + 1;
if ( requiredBlockCount > allocator->blocks.count )
{
@ -79,8 +70,8 @@ void* b3AllocateElement( b3BlockAllocator* allocator )
}
}
int blockIndex = startIndex >> B3_BLOCK_EXPONENT;
int blockOffset = startIndex & ( B3_BLOCK_SIZE - 1 );
int blockIndex = index >> B3_BLOCK_EXPONENT;
int blockOffset = index & ( B3_BLOCK_SIZE - 1 );
return allocator->blocks.data[blockIndex].memory + blockOffset * allocator->elementSize;
}

View file

@ -30,6 +30,6 @@ typedef struct b3BlockAllocator
b3BlockAllocator b3CreateBlockAllocator( int elementSize, int initialCount );
void b3DestroyBlockAllocator( b3BlockAllocator* allocator );
// Elements are guaranteed contiguous.
// Returns one element of elementSize contiguous bytes. Address is stable until freed.
void* b3AllocateElement( b3BlockAllocator* allocator );
void b3FreeElement( b3BlockAllocator* allocator, void* element );

View file

@ -43,7 +43,7 @@
#define b3Array_CreateN( a, n ) \
do \
{ \
( a ).data = ( n ) > 0 ? (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( NULL, 0, ( n ) * sizeof( *( a ).data ) ) : NULL; \
( a ).data = ( n ) > 0 ? b3GrowAlloc( NULL, 0, ( n ) * sizeof( *( a ).data ) ) : NULL; \
( a ).count = 0; \
( a ).capacity = ( n ); \
} \
@ -66,7 +66,7 @@
{ \
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newSize = ( n ) * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).data = b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = ( n ); \
} \
} \
@ -89,7 +89,7 @@
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newCapacity = ( a ).capacity == 0 ? 8 : 2 * ( a ).capacity; \
int newSize = newCapacity * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).data = b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = newCapacity; \
} \
( a ).data[( a ).count++] = ( value ); \
@ -101,7 +101,7 @@
// Create a new uninitialized element and return a pointer to it
#define b3Array_Emplace( a ) \
( (B3_TYPE_OF( ( a ).data ))b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ) )
( b3EmplaceHelper( (void**)&( a ).data, &( a ).count, &( a ).capacity, sizeof( *( a ).data ) ) )
// Remove the last element and return it by value.
#define b3Array_Pop( a ) ( B3_ASSERT( 0 < ( a ).count ), ( a ).data[-1 + ( a ).count--] )
@ -121,7 +121,7 @@
int newCapacity = req > 2 ? req + ( req >> 1 ) : 8; \
int oldSize = ( a ).capacity * sizeof( *( a ).data ); \
int newSize = newCapacity * sizeof( *( a ).data ); \
( a ).data = (B3_TYPE_OF( ( a ).data ))b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).data = b3GrowAlloc( ( a ).data, oldSize, newSize ); \
( a ).capacity = newCapacity; \
} \
memcpy( ( a ).data + ( a ).count, ( src ), _n * sizeof( *( a ).data ) ); \

View file

@ -36,7 +36,7 @@
#include <stdio.h>
// This allows the user to change the length units at runtime
float b3_lengthUnitsPerMeter = 1.0f;
static float b3_lengthUnitsPerMeter = 1.0f;
void b3SetLengthUnitsPerMeter( float lengthUnits )
{
@ -49,6 +49,19 @@ float b3GetLengthUnitsPerMeter( void )
return b3_lengthUnitsPerMeter;
}
static float b3_stallThreshold = FLT_MAX;
void b3SetStallThreshold(float seconds)
{
B3_ASSERT( b3IsValidFloat( seconds ) && seconds > 0.0f );
b3_stallThreshold = seconds;
}
float b3GetStallThreshold(void)
{
return b3_stallThreshold;
}
static int b3DefaultAssertFcn( const char* condition, const char* fileName, int lineNumber )
{
printf( "BOX3D ASSERTION: %s, %s, line %d\n", condition, fileName, lineNumber );

View file

@ -345,11 +345,6 @@ b3Quat b3ComputeQuatBetweenUnitVectors( b3Vec3 v1, b3Vec3 v2 )
return b3NormalizeQuat( out );
}
//--------------------------------------------------------------------------------------------------
// Collision utilities
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 )
{
b3SegmentDistanceResult result;
@ -389,7 +384,6 @@ b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3
return result;
}
//--------------------------------------------------------------------------------------------------
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 )
{
b3SegmentDistanceResult result;

View file

@ -45,24 +45,6 @@ typedef struct b3ShapeExtent
b3TrianglePoint b3ClosestPointOnTriangle( b3Vec3 a, b3Vec3 b, b3Vec3 c, b3Vec3 q );
// The closest points between to segments or infinite lines.
typedef struct b3SegmentDistanceResult
{
b3Vec3 point1;
float fraction1;
b3Vec3 point2;
float fraction2;
} b3SegmentDistanceResult;
// Compute the closest point on the segment a-b to the target q
b3Vec3 b3PointToSegmentDistance( b3Vec3 a, b3Vec3 b, b3Vec3 q );
// Compute the closest points on two infinite lines
b3SegmentDistanceResult b3LineDistance( b3Vec3 p1, b3Vec3 d1, b3Vec3 p2, b3Vec3 d2 );
// Compute the closest points on two line segments
b3SegmentDistanceResult b3SegmentDistance( b3Vec3 p1, b3Vec3 q1, b3Vec3 p2, b3Vec3 q2 );
float b3IntersectSegmentTriangle( b3Vec3 p, b3Vec3 q, b3Vec3 a, b3Vec3 b, b3Vec3 c );
float b3IntersectSegmentSphere( b3Vec3 p, b3Vec3 q, b3Vec3 c, float r );
@ -489,28 +471,6 @@ static inline b3Matrix3 b3TransformInertia( b3Transform transform, b3Matrix3 cen
return inertia;
}
// Twist angle around the z-axis, used for twist limit and revolute angle limit
static inline float b3GetTwistAngle( b3Quat q )
{
// Account for polarity to keep the twist angle in range.
// This is simpler than asking the user to check polarity or unwinding.
float twist = q.s < 0.0f ? b3Atan2( -q.v.z, -q.s ) : b3Atan2( q.v.z, q.s );
twist *= 2.0f;
B3_ASSERT( -B3_PI <= twist && twist <= B3_PI );
return twist;
}
// Swing angle used for cone limit
static inline float b3GetSwingAngle( b3Quat q )
{
// Polarity should not matter because all terms are squared.
float x = sqrtf( q.v.z * q.v.z + q.s * q.s );
float y = sqrtf( q.v.x * q.v.x + q.v.y * q.v.y );
float swing = 2.0f * b3Atan2( y, x );
B3_ASSERT( 0.0f <= swing && swing <= B3_PI );
return swing;
}
// Add a point to an AABB.
static inline b3AABB b3AABB_AddPoint( b3AABB a, b3Vec3 point )
{

View file

@ -9,7 +9,6 @@
#include "bitset.h"
#include "body.h"
#include "broad_phase.h"
#include "compound.h"
#include "constraint_graph.h"
#include "contact.h"
#include "core.h"
@ -1366,7 +1365,8 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
B3_ASSERT( b3IsValidAABB( draw->drawingBounds ) );
const float axisScale = 0.3f * b3GetLengthUnitsPerMeter();
float lengthScale = b3GetLengthUnitsPerMeter();
float axisScale = 0.3f * lengthScale;
b3HexColor farColor = b3_colorDarkBlue;
b3HexColor speculativeColor = b3_colorBlue;
b3HexColor addColor = b3_colorLimeGreen;
@ -1521,7 +1521,7 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
b3Pos p1 = p;
b3Pos p2 = b3OffsetPos( p1, b3MulSV( draw->forceScale * force, normal ) );
draw->DrawSegmentFcn( p1, p2, impulseColor, draw->context );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.1f", force );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.1f", force );
draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context );
}
else if ( draw->drawContactFeatures )
@ -1571,8 +1571,9 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
draw->DrawSegmentFcn( p1, p2, frictionColor, draw->context );
draw->DrawPointFcn( p1, 5.0f, frictionColor, draw->context );
p1 = b3OffsetPos( p1, b3MulSV(0.05f * lengthScale, normal) );
char buffer[32];
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.2f", b3Length( frictionForce ) );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), "%.2f", b3Length( frictionForce ) );
draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context );
}
}
@ -2593,7 +2594,7 @@ b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter f
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.overlapFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_AABB( &recWriter.buf, aabb );
@ -2683,7 +2684,7 @@ b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const b3Shape
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.overlapFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -2780,7 +2781,7 @@ void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mov
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.planeFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -2894,7 +2895,7 @@ b3TreeStats b3World_CastRay( b3WorldId worldId, b3Pos origin, b3Vec3 translation
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.castFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -3002,7 +3003,7 @@ b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Pos origin, b3Vec3 tran
if ( world->recording != NULL )
{
b3RecQueryWriter recWriter = { 0 };
b3RecQueryBegin( &recWriter, NULL );
b3RecQueryBegin( &recWriter, NULL, filter.id, filter.name );
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
b3RecW_VEC3( &recWriter.buf, translation );
@ -3094,7 +3095,7 @@ b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3ShapePro
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.castFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );
@ -3225,7 +3226,7 @@ float b3World_CastMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover
b3RecQueryWriter recWriter = { 0 };
if ( world->recording != NULL )
{
b3RecQueryBegin( &recWriter, context );
b3RecQueryBegin( &recWriter, context, filter.id, filter.name );
recWriter.userFcn.moverFilterFcn = fcn;
b3RecW_WORLDID( &recWriter.buf, worldId );
b3RecW_POSITION( &recWriter.buf, origin );

View file

@ -87,8 +87,8 @@ void b3RecW_U32( b3RecBuffer* buf, uint32_t v )
void b3RecW_U64( b3RecBuffer* buf, uint64_t v )
{
uint8_t b[8] = { (uint8_t)v, (uint8_t)( v >> 8 ), (uint8_t)( v >> 16 ), (uint8_t)( v >> 24 ),
(uint8_t)( v >> 32 ), (uint8_t)( v >> 40 ), (uint8_t)( v >> 48 ), (uint8_t)( v >> 56 ) };
uint8_t b[8] = { (uint8_t)v, (uint8_t)( v >> 8 ), (uint8_t)( v >> 16 ), (uint8_t)( v >> 24 ),
(uint8_t)( v >> 32 ), (uint8_t)( v >> 40 ), (uint8_t)( v >> 48 ), (uint8_t)( v >> 56 ) };
b3RecBufAppend( buf, b, 8 );
}
@ -316,29 +316,29 @@ void b3RecW_STR( b3RecBuffer* buf, const char* s )
// so the writer and reader both get updated. Only enforced on the 64-bit target; each def lists the
// single-precision and double-precision sizes (equal for most), so either build configuration passes.
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ExplosionDef ) == 32 || sizeof( b3ExplosionDef ) == 48,
"b3ExplosionDef changed: update b3RecW_EXPLOSIONDEF and b3RecR_EXPLOSIONDEF together" );
"b3ExplosionDef changed: update b3RecW_EXPLOSIONDEF and b3RecR_EXPLOSIONDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3BodyDef ) == 104 || sizeof( b3BodyDef ) == 120,
"b3BodyDef changed: update b3RecW_BODYDEF and b3RecR_BODYDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ShapeDef ) == 120,
"b3ShapeDef changed: update b3RecW_SHAPEDEF and b3RecR_SHAPEDEF together" );
"b3BodyDef changed: update b3RecW_BODYDEF and b3RecR_BODYDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ShapeDef ) == 112,
"b3ShapeDef changed: update b3RecW_SHAPEDEF and b3RecR_SHAPEDEF together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3ParallelJointDef ) == 128,
"b3ParallelJointDef changed: update b3RecW_PARALLELJOINTDEF and its reader together" );
"b3ParallelJointDef changed: update b3RecW_PARALLELJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3DistanceJointDef ) == 160,
"b3DistanceJointDef changed: update b3RecW_DISTANCEJOINTDEF and its reader together" );
"b3DistanceJointDef changed: update b3RecW_DISTANCEJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3FilterJointDef ) == 112,
"b3FilterJointDef changed: update b3RecW_FILTERJOINTDEF and its reader together" );
"b3FilterJointDef changed: update b3RecW_FILTERJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3MotorJointDef ) == 168,
"b3MotorJointDef changed: update b3RecW_MOTORJOINTDEF and its reader together" );
"b3MotorJointDef changed: update b3RecW_MOTORJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3PrismaticJointDef ) == 152,
"b3PrismaticJointDef changed: update b3RecW_PRISMATICJOINTDEF and its reader together" );
"b3PrismaticJointDef changed: update b3RecW_PRISMATICJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3RevoluteJointDef ) == 152,
"b3RevoluteJointDef changed: update b3RecW_REVOLUTEJOINTDEF and its reader together" );
"b3RevoluteJointDef changed: update b3RecW_REVOLUTEJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3SphericalJointDef ) == 184,
"b3SphericalJointDef changed: update b3RecW_SPHERICALJOINTDEF and its reader together" );
"b3SphericalJointDef changed: update b3RecW_SPHERICALJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3WeldJointDef ) == 128,
"b3WeldJointDef changed: update b3RecW_WELDJOINTDEF and its reader together" );
"b3WeldJointDef changed: update b3RecW_WELDJOINTDEF and its reader together" );
_Static_assert( sizeof( void* ) != 8 || sizeof( b3WheelJointDef ) == 184,
"b3WheelJointDef changed: update b3RecW_WHEELJOINTDEF and its reader together" );
"b3WheelJointDef changed: update b3RecW_WHEELJOINTDEF and its reader together" );
void b3RecW_EXPLOSIONDEF( b3RecBuffer* buf, b3ExplosionDef v )
{
@ -375,7 +375,6 @@ void b3RecW_BODYDEF( b3RecBuffer* buf, b3BodyDef v )
void b3RecW_SHAPEDEF( b3RecBuffer* buf, b3ShapeDef v )
{
b3RecW_STR( buf, v.name );
// userData: not preserved
b3RecW_U64( buf, 0u );
// Per-triangle materials: length-prefixed so the reader can rebuild the array.
@ -565,29 +564,52 @@ void b3RecPatchU32( b3RecBuffer* buf, int offset, uint32_t v )
p[3] = (uint8_t)( v >> 24 );
}
void b3RecCommitRecord( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize )
// Frame and append one record into the buffer. Caller holds rec->lock.
static void b3RecCommitRecordLocked( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize )
{
B3_ASSERT( payloadSize >= 0 && payloadSize < ( 1 << 24 ) );
b3LockMutex( rec->lock );
b3RecW_U8( &rec->buffer, opcode );
uint8_t sz[3] = { (uint8_t)payloadSize, (uint8_t)( payloadSize >> 8 ), (uint8_t)( payloadSize >> 16 ) };
b3RecBufAppend( &rec->buffer, sz, 3 );
b3RecBufAppend( &rec->buffer, payload, payloadSize );
}
void b3RecCommitRecord( b3Recording* rec, uint8_t opcode, const uint8_t* payload, int payloadSize )
{
b3LockMutex( rec->lock );
b3RecCommitRecordLocked( rec, opcode, payload, payloadSize );
b3UnlockMutex( rec->lock );
}
void b3RecQueryBegin( b3RecQueryWriter* w, void* context )
void b3RecQueryBegin( b3RecQueryWriter* w, void* context, uint64_t tagId, const char* tagName )
{
w->buf = ( b3RecBuffer ){ 0 };
w->buf = (b3RecBuffer){ 0 };
w->userFcn.overlapFcn = NULL;
w->userContext = context;
w->hitCount = 0;
w->countOffset = 0;
w->tagId = tagId;
w->tagName = tagName;
}
void b3RecQueryCommit( b3Recording* rec, uint8_t opcode, b3RecQueryWriter* w )
{
b3RecCommitRecord( rec, opcode, w->buf.data, w->buf.size );
b3LockMutex( rec->lock );
// A tagged query writes its identity key right before the query record, under one lock so the pair
// stays adjacent even with concurrent queries. The key is the hash of the caller (id, name), which
// are interned once into the trailing tag table so the viewer can show them.
bool tagged = w->tagId != 0 || ( w->tagName != NULL && w->tagName[0] != '\0' );
if ( tagged )
{
uint64_t key = b3HashQueryTag( w->tagId, w->tagName );
b3RecInternTag( rec, key, w->tagId, w->tagName );
b3RecBuffer tagBuf = { 0 };
b3RecW_U64( &tagBuf, key );
b3RecCommitRecordLocked( rec, b3_recOpQueryTag, tagBuf.data, tagBuf.size );
b3RecBufFree( &tagBuf );
}
b3RecCommitRecordLocked( rec, opcode, w->buf.data, w->buf.size );
b3UnlockMutex( rec->lock );
b3RecBufFree( &w->buf );
}
@ -669,13 +691,17 @@ void b3RecEndRecord( b3Recording* rec )
#undef B3_REC_OP
#undef ARG
// Codegen: full writers
// Codegen: full writers. Setters may run on threads that each own a distinct object,
// so hold the lock across the whole record. Without it a concurrent writer splices its bytes between
// our begin and end and the record desyncs replay. Same lock the query commit path takes.
#define B3_REC_OP( op, Name, RET, ... ) \
void b3RecWrite_##Name( b3Recording* rec, const b3RecArgs_##Name* a ) \
{ \
b3LockMutex( rec->lock ); \
b3RecBeginRecord( rec, (uint8_t)( op ) ); \
b3RecWriteArgs_##Name( rec, a ); \
b3RecEndRecord( rec ); \
b3UnlockMutex( rec->lock ); \
}
#include "recording_ops.inl"
#undef B3_REC_OP
@ -684,13 +710,15 @@ void b3RecEndRecord( b3Recording* rec )
#define B3_REC_RETWRITE( op, Name, idType, idW ) \
void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, idType id ) \
{ \
b3LockMutex( rec->lock ); \
b3RecBeginRecord( rec, (uint8_t)( op ) ); \
b3RecWriteArgs_##Name( rec, a ); \
idW( &rec->buffer, id ); \
b3RecEndRecord( rec ); \
b3UnlockMutex( rec->lock ); \
}
#define B3_REC_RETWRITE_RET_NONE( op, Name )
#define B3_REC_RETWRITE_RET_BODYID( op, Name ) B3_REC_RETWRITE( op, Name, b3BodyId, b3RecW_BODYID )
#define B3_REC_RETWRITE_RET_BODYID( op, Name ) B3_REC_RETWRITE( op, Name, b3BodyId, b3RecW_BODYID )
#define B3_REC_RETWRITE_RET_SHAPEID( op, Name ) B3_REC_RETWRITE( op, Name, b3ShapeId, b3RecW_SHAPEID )
#define B3_REC_RETWRITE_RET_JOINTID( op, Name ) B3_REC_RETWRITE( op, Name, b3JointId, b3RecW_JOINTID )
#define B3_REC_OP( op, Name, RET, ... ) B3_REC_RETWRITE_##RET( op, Name )
@ -704,16 +732,47 @@ void b3RecEndRecord( b3Recording* rec )
// Geometry registry
// Fold a 32-bit hash into 64 bits. Collisions are caught by the byteCount+memcmp fallback.
// Full 64-bit content hash, so distinct blobs of the same length get independent bits. A reseeded
// 32-bit djb2 cannot: djb2 is affine in its seed, so a same-length collision survives every seed and
// the high word would just track the low one. Word folded for speed, byte order normalized on
// big-endian to match b3Hash, then a splitmix64 finalizer so tiny inputs still spread across all bits.
// From Fowler/Noll/Vo FNV-1a salted by length, then the splitmix64 mix.
uint64_t b3Hash64Blob( const uint8_t* bytes, int n )
{
uint32_t h = b3Hash( B3_HASH_INIT, bytes, n );
return (uint64_t)h | ( (uint64_t)b3NonZeroHash( ~h ) << 32 );
uint64_t h = 0xcbf29ce484222325ull ^ (uint64_t)(uint32_t)n;
const uint64_t prime = 0x100000001b3ull;
int i = 0;
while ( i + 8 <= n )
{
uint64_t word;
memcpy( &word, bytes + i, sizeof( word ) );
#if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
word = ( ( word & 0x00000000000000FFULL ) << 56 ) | ( ( word & 0x000000000000FF00ULL ) << 40 ) |
( ( word & 0x0000000000FF0000ULL ) << 24 ) | ( ( word & 0x00000000FF000000ULL ) << 8 ) |
( ( word & 0x000000FF00000000ULL ) >> 8 ) | ( ( word & 0x0000FF0000000000ULL ) >> 24 ) |
( ( word & 0x00FF000000000000ULL ) >> 40 ) | ( ( word & 0xFF00000000000000ULL ) >> 56 );
#endif
h = ( h ^ word ) * prime;
i += 8;
}
while ( i < n )
{
h = ( h ^ (uint64_t)bytes[i] ) * prime;
i += 1;
}
h ^= h >> 30;
h *= 0xbf58476d1ce4e5b9ull;
h ^= h >> 27;
h *= 0x94d049bb133111ebull;
h ^= h >> 31;
return h;
}
// Content hash to entry id, so dedup is O(1) average instead of a linear scan. A 64-bit content-hash
// collision between distinct blobs is still caught by the byteCount + memcmp check, so it can never
// return the wrong id; the worst case is a missed dedup in that astronomically unlikely event.
// Content hash to chain head, so dedup is near O(1). Colliding hashes share a head and are walked
// through b3GeometryEntry::hashNext, so the byteCount + memcmp check always finds an existing blob.
#define NAME b3GeometryHashMap
#define KEY_TY uint64_t
#define VAL_TY uint32_t
@ -723,8 +782,50 @@ uint64_t b3Hash64Blob( const uint8_t* bytes, int n )
#define FREE_FN b3Free
#include "verstable.h"
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash,
uint8_t* bytes, int byteCount )
// Tag key to tag index, so interning a query tag is O(1) rather than a linear scan over the tag table.
#define NAME b3RecTagMap
#define KEY_TY uint64_t
#define VAL_TY uint32_t
#define HASH_FN vt_hash_integer
#define CMPR_FN vt_cmpr_integer
#define MALLOC_FN b3Alloc
#define FREE_FN b3Free
#include "verstable.h"
// Append a fresh entry and splice it onto the front of its hash chain. The map value is the chain head.
static uint32_t b3RegistryPush( b3GeometryRegistry* reg, b3GeometryHashMap* map, b3GeometryHashMap_itr itr, bool hashPresent,
b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount )
{
if ( reg->count >= reg->capacity )
{
int newCap = reg->capacity < 8 ? 8 : reg->capacity * 2;
reg->entries = (b3GeometryEntry*)b3GrowAlloc( reg->entries, reg->capacity * (int)sizeof( b3GeometryEntry ),
newCap * (int)sizeof( b3GeometryEntry ) );
reg->capacity = newCap;
}
uint32_t id = (uint32_t)reg->count;
b3GeometryEntry* entry = reg->entries + reg->count;
entry->contentHash = contentHash;
entry->id = id;
entry->kind = kind;
entry->byteCount = byteCount;
entry->bytes = bytes; // take ownership
entry->hashNext = hashPresent ? (int)itr.data->val : B3_NULL_INDEX;
reg->count++;
if ( hashPresent )
{
itr.data->val = id;
}
else
{
b3GeometryHashMap_insert( map, contentHash, id );
}
return id;
}
static b3GeometryHashMap* b3RegistryMap( b3GeometryRegistry* reg )
{
if ( reg->dedupMap == NULL )
{
@ -732,48 +833,39 @@ uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_
b3GeometryHashMap_init( fresh );
reg->dedupMap = fresh;
}
b3GeometryHashMap* map = (b3GeometryHashMap*)reg->dedupMap;
return (b3GeometryHashMap*)reg->dedupMap;
}
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount )
{
b3GeometryHashMap* map = b3RegistryMap( reg );
b3GeometryHashMap_itr itr = b3GeometryHashMap_get( map, contentHash );
bool hashPresent = b3GeometryHashMap_is_end( itr ) == false;
if ( hashPresent )
{
b3GeometryEntry* e = reg->entries + itr.data->val;
if ( e->byteCount == byteCount && memcmp( e->bytes, bytes, (size_t)byteCount ) == 0 )
// Walk every entry sharing this hash so a collision still finds the identical blob.
for ( int idx = (int)itr.data->val; idx != B3_NULL_INDEX; idx = reg->entries[idx].hashNext )
{
// Duplicate: the caller transferred ownership; return existing id
b3Free( bytes, (size_t)byteCount );
return e->id;
b3GeometryEntry* e = reg->entries + idx;
if ( e->byteCount == byteCount && memcmp( e->bytes, bytes, (size_t)byteCount ) == 0 )
{
// Duplicate: the caller transferred ownership; return existing id
b3Free( bytes, (size_t)byteCount );
return e->id;
}
}
// Same hash, different bytes: a 64-bit collision. Store a new entry and leave the map pointing
// at the first, so only a later blob identical to this rare one would miss dedup.
}
// New entry — grow the array if needed
if ( reg->count >= reg->capacity )
{
int newCap = reg->capacity < 8 ? 8 : reg->capacity * 2;
reg->entries = (b3GeometryEntry*)b3GrowAlloc( reg->entries,
reg->capacity * (int)sizeof( b3GeometryEntry ),
newCap * (int)sizeof( b3GeometryEntry ) );
reg->capacity = newCap;
}
return b3RegistryPush( reg, map, itr, hashPresent, kind, contentHash, bytes, byteCount );
}
uint32_t id = (uint32_t)reg->count;
b3GeometryEntry* entry = reg->entries + reg->count;
entry->contentHash = contentHash;
entry->id = id;
entry->kind = kind;
entry->byteCount = byteCount;
entry->bytes = bytes; // take ownership
reg->count++;
// Only the first entry for a given hash goes in the map; a hash hit is verified by memcmp above.
if ( hashPresent == false )
{
b3GeometryHashMap_insert( map, contentHash, id );
}
return id;
uint32_t b3AppendGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount )
{
b3GeometryHashMap* map = b3RegistryMap( reg );
b3GeometryHashMap_itr itr = b3GeometryHashMap_get( map, contentHash );
bool hashPresent = b3GeometryHashMap_is_end( itr ) == false;
return b3RegistryPush( reg, map, itr, hashPresent, kind, contentHash, bytes, byteCount );
}
void b3FreeRegistry( b3GeometryRegistry* reg )
@ -791,13 +883,73 @@ void b3FreeRegistry( b3GeometryRegistry* reg )
b3GeometryHashMap_cleanup( (b3GeometryHashMap*)reg->dedupMap );
b3Free( reg->dedupMap, sizeof( b3GeometryHashMap ) );
}
reg->entries = NULL;
reg->count = 0;
reg->entries = NULL;
reg->count = 0;
reg->capacity = 0;
reg->dedupMap = NULL;
}
// Write the trailing registry block: u32 entryCount then per-entry { u8 kind, u32 byteCount, bytes }.
uint64_t b3HashQueryTag( uint64_t id, const char* name )
{
uint64_t h = B3_SNAP_FNV_INIT;
for ( int i = 0; i < 8; ++i )
{
h = ( h ^ ( ( id >> ( 8 * i ) ) & 0xFFu ) ) * B3_SNAP_FNV_PRIME;
}
if ( name != NULL )
{
for ( int i = 0; name[i] != '\0'; ++i )
{
h = ( h ^ (uint8_t)name[i] ) * B3_SNAP_FNV_PRIME;
}
}
// Never 0 so the key doubles as the tagged flag.
return h != 0 ? h : 1;
}
static b3RecTagMap* b3RecTags( b3Recording* rec )
{
if ( rec->tagMap == NULL )
{
b3RecTagMap* fresh = b3Alloc( sizeof( b3RecTagMap ) );
b3RecTagMap_init( fresh );
rec->tagMap = fresh;
}
return rec->tagMap;
}
void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* name )
{
b3RecTagMap* map = b3RecTags( rec );
if ( b3RecTagMap_is_end( b3RecTagMap_get( map, key ) ) == false )
{
return; // first id/name for a key wins
}
if ( rec->tagCount == rec->tagCapacity )
{
int newCap = rec->tagCapacity == 0 ? 8 : 2 * rec->tagCapacity;
rec->tags = b3GrowAlloc( rec->tags, rec->tagCapacity * (int)sizeof( b3RecTag ), newCap * (int)sizeof( b3RecTag ) );
rec->tagCapacity = newCap;
}
uint32_t index = (uint32_t)rec->tagCount;
b3RecTag* tag = &rec->tags[rec->tagCount++];
tag->key = key;
tag->id = id;
int n = 0;
while ( name != NULL && name[n] != '\0' && n < B3_NAME_LENGTH )
{
tag->name[n] = name[n];
n++;
}
tag->name[n] = '\0';
b3RecTagMap_insert( map, key, index );
}
// Write the trailing registry block: u32 entryCount then per-entry { u8 kind, u32 byteCount, bytes },
// followed by the query-tag table { u32 tagCount, per-tag uu64 id, STR name }. A reader built before
// the tag table stops after the geometry entries and ignores the trailing tag bytes.
void b3RecWriteRegistry( b3Recording* rec )
{
b3RecW_U32( &rec->buffer, (uint32_t)rec->registry.count );
@ -808,6 +960,14 @@ void b3RecWriteRegistry( b3Recording* rec )
b3RecW_U32( &rec->buffer, (uint32_t)e->byteCount );
b3RecBufAppend( &rec->buffer, e->bytes, e->byteCount );
}
b3RecW_U32( &rec->buffer, (uint32_t)rec->tagCount );
for ( int i = 0; i < rec->tagCount; ++i )
{
b3RecW_U64( &rec->buffer, rec->tags[i].key );
b3RecW_U64( &rec->buffer, rec->tags[i].id );
b3RecW_STR( &rec->buffer, rec->tags[i].name );
}
}
// Lifecycle
@ -818,9 +978,9 @@ b3Recording* b3CreateRecording( int byteCapacity )
*rec = (b3Recording){ 0 };
int initCap = byteCapacity > 0 ? byteCapacity : 65536;
rec->buffer.data = (uint8_t*)b3Alloc( (size_t)initCap );
rec->buffer.data = (uint8_t*)b3Alloc( (size_t)initCap );
rec->buffer.capacity = initCap;
rec->buffer.size = 0;
rec->buffer.size = 0;
rec->lock = b3CreateMutex();
return rec;
}
@ -834,6 +994,15 @@ void b3DestroyRecording( b3Recording* recording )
b3RecBufFree( &recording->buffer );
b3FreeRegistry( &recording->registry );
if ( recording->tags != NULL )
{
b3Free( recording->tags, (size_t)recording->tagCapacity * sizeof( b3RecTag ) );
}
if ( recording->tagMap != NULL )
{
b3RecTagMap_cleanup( (b3RecTagMap*)recording->tagMap );
b3Free( recording->tagMap, sizeof( b3RecTagMap ) );
}
b3DestroyMutex( recording->lock );
b3Free( recording, sizeof( b3Recording ) );
}
@ -859,18 +1028,31 @@ void b3StartRecordingIntoBuffer( b3World* world, b3Recording* recording )
// Reset so a recording handle can be reused for a fresh session
recording->buffer.size = 0;
recording->recordStart = 0;
recording->haveBounds = false;
recording->haveBounds = false;
b3FreeRegistry( &recording->registry );
if ( recording->tags != NULL )
{
b3Free( recording->tags, (size_t)recording->tagCapacity * sizeof( b3RecTag ) );
recording->tags = NULL;
}
if ( recording->tagMap != NULL )
{
b3RecTagMap_cleanup( (b3RecTagMap*)recording->tagMap );
b3Free( recording->tagMap, sizeof( b3RecTagMap ) );
recording->tagMap = NULL;
}
recording->tagCount = 0;
recording->tagCapacity = 0;
b3RecHeader hdr = { 0 };
hdr.magic = B3_REC_MAGIC;
hdr.versionMajor = B3_REC_VERSION_MAJOR;
hdr.versionMinor = B3_REC_VERSION_MINOR;
hdr.pointerWidth = (uint8_t)sizeof( void* );
hdr.bigEndian = 0;
hdr.magic = B3_REC_MAGIC;
hdr.versionMajor = B3_REC_VERSION_MAJOR;
hdr.versionMinor = B3_REC_VERSION_MINOR;
hdr.pointerWidth = (uint8_t)sizeof( void* );
hdr.bigEndian = 0;
hdr.validationEnabled = B3_ENABLE_VALIDATION ? 1u : 0u;
hdr.lengthScale = b3GetLengthUnitsPerMeter();
hdr.registryOffset = 0; // backpatched in b3StopRecordingInternal
hdr.lengthScale = b3GetLengthUnitsPerMeter();
hdr.registryOffset = 0; // backpatched in b3StopRecordingInternal
hdr.registryByteCount = 0;
world->recording = recording;
@ -924,14 +1106,14 @@ void b3StopRecordingInternal( b3World* world )
// Backpatch registryOffset and registryByteCount into the header
uint8_t* hdrBytes = rec->buffer.data;
uint64_t regOff = (uint64_t)registryOffset;
uint64_t regSz = (uint64_t)registryByteCount;
uint64_t regSz = (uint64_t)registryByteCount;
// Little-endian backpatch in place; offsetof keeps this correct if the header layout shifts
uint8_t* pOff = hdrBytes + offsetof( b3RecHeader, registryOffset );
uint8_t* pSz = hdrBytes + offsetof( b3RecHeader, registryByteCount );
uint8_t* pSz = hdrBytes + offsetof( b3RecHeader, registryByteCount );
for ( int i = 0; i < 8; ++i )
{
pOff[i] = (uint8_t)( regOff >> ( 8 * i ) );
pSz[i] = (uint8_t)( regSz >> ( 8 * i ) );
pSz[i] = (uint8_t)( regSz >> ( 8 * i ) );
}
}

View file

@ -46,26 +46,27 @@ typedef struct b3World b3World;
#define B3_REC_MAGIC 0x43523342u
// Minor tracks op-stream additions that keep the 48 byte header shape (e.g. the spatial query ops).
#define B3_REC_VERSION_MAJOR 1
#define B3_REC_VERSION_MINOR 1
// Minor 2 added the QueryTag op and the interned query-tag table at the tail of the registry block.
#define B3_REC_VERSION_MAJOR 2
#define B3_REC_VERSION_MINOR 2
// File header, fixed 48 bytes, little-endian. Contains the registry locator so the player
// can load geometry before replaying any ops.
typedef struct b3RecHeader
{
uint32_t magic; // 'B3RC' = 0x43523342
uint16_t versionMajor; // B3_REC_VERSION_MAJOR
uint16_t versionMinor; // B3_REC_VERSION_MINOR
uint8_t pointerWidth; // sizeof(void*), gates POD-def struct layout
uint8_t bigEndian; // 0 on all supported targets
uint8_t validationEnabled; // 1 if built with BOX3D_VALIDATE, diagnostic only
uint8_t reserved;
float lengthScale; // b3GetLengthUnitsPerMeter()
uint32_t magic; // 'B3RC' = 0x43523342
uint16_t versionMajor; // B3_REC_VERSION_MAJOR
uint16_t versionMinor; // B3_REC_VERSION_MINOR
uint8_t pointerWidth; // sizeof(void*), gates POD-def struct layout
uint8_t bigEndian; // 0 on all supported targets
uint8_t validationEnabled; // 1 if built with BOX3D_VALIDATE, diagnostic only
uint8_t reserved;
float lengthScale; // b3GetLengthUnitsPerMeter()
uint32_t reserved2;
uint32_t reserved3; // explicit pad so the 64-bit fields align with no implicit gap
uint64_t snapshotSize; // bytes of snapshot blob after the header (0 in Phase 1)
uint64_t registryOffset; // absolute offset to trailing registry block, backpatched at stop
uint64_t registryByteCount; // size of the registry block
uint32_t reserved3; // explicit pad so the 64-bit fields align with no implicit gap
uint64_t snapshotSize; // bytes of snapshot blob after the header (0 in Phase 1)
uint64_t registryOffset; // absolute offset to trailing registry block, backpatched at stop
uint64_t registryByteCount; // size of the registry block
} b3RecHeader;
_Static_assert( sizeof( b3RecHeader ) == 48, "recording header must be 48 bytes" );
@ -75,9 +76,9 @@ _Static_assert( sizeof( b3RecHeader ) == 48, "recording header must be 48 bytes"
typedef struct b3RecBuffer
{
uint8_t* data;
int capacity;
int size;
bool countOnly;
int capacity;
int size;
bool countOnly;
} b3RecBuffer;
// Geometry kinds for the trailing registry section
@ -90,13 +91,16 @@ typedef enum b3GeometryKind
} b3GeometryKind;
// One entry per unique geometry blob. id == index in the entries array.
// hashNext chains entries that share a content hash so dedup stays exact under a hash collision,
// which the keyframe registry depends on to never grow during capture. B3_NULL_INDEX ends the chain.
typedef struct b3GeometryEntry
{
uint64_t contentHash;
uint32_t id;
uint64_t contentHash;
uint32_t id;
b3GeometryKind kind;
int byteCount;
uint8_t* bytes;
int byteCount;
uint8_t* bytes;
int hashNext;
} b3GeometryEntry;
// Growable array of geometry entries. Ids are array indices, so the array is serialized in order.
@ -104,68 +108,85 @@ typedef struct b3GeometryEntry
typedef struct b3GeometryRegistry
{
b3GeometryEntry* entries;
int count;
int capacity;
void* dedupMap;
int count;
int capacity;
void* dedupMap;
} b3GeometryRegistry;
// Query tag from b3QueryFilter.
// Stored once per key in the trailing block so a tagged query carries only the 8 byte key on the wire.
// Shared by the recorder (accumulate) and the player (load).
typedef struct b3RecTag
{
uint64_t key; // hash of (id, name)
uint64_t id; // entity/actor id
char name[B3_NAME_LENGTH + 1]; // query label
} b3RecTag;
// User-owned recording buffer. The world appends into it while active; the host saves and
// destroys it. Opaque across the public API.
typedef struct b3Recording
{
b3RecBuffer buffer;
int recordStart; // offset of the 3-byte size field for u24 backpatch
b3Mutex* lock; // serializes query commits from concurrent threads
b3RecBuffer buffer;
int recordStart; // offset of the 3-byte size field for u24 backpatch
b3Mutex* lock; // serializes record writes from concurrent threads
b3GeometryRegistry registry;
// Interned query tags accumulated during capture, written to the tail of the registry block at stop.
// tagMap maps a tag key to its index for O(1) dedup.
b3RecTag* tags;
int tagCount;
int tagCapacity;
void* tagMap;
// Union of world bounds over every recorded step, written at stop.
b3AABB accumulatedBounds;
bool haveBounds;
b3AABB accumulatedBounds;
bool haveBounds;
} b3Recording;
// C type aliases per TAG, used in the X-macro codegen arg structs
typedef bool b3RecCType_BOOL;
typedef int32_t b3RecCType_I32;
typedef uint8_t b3RecCType_U8;
typedef uint16_t b3RecCType_U16;
typedef uint32_t b3RecCType_U32;
typedef uint64_t b3RecCType_U64;
typedef float b3RecCType_F32;
typedef double b3RecCType_F64;
typedef b3Vec3 b3RecCType_VEC3;
typedef b3Quat b3RecCType_QUAT;
typedef b3Transform b3RecCType_TRANSFORM;
typedef b3Pos b3RecCType_POSITION;
typedef bool b3RecCType_BOOL;
typedef int32_t b3RecCType_I32;
typedef uint8_t b3RecCType_U8;
typedef uint16_t b3RecCType_U16;
typedef uint32_t b3RecCType_U32;
typedef uint64_t b3RecCType_U64;
typedef float b3RecCType_F32;
typedef double b3RecCType_F64;
typedef b3Vec3 b3RecCType_VEC3;
typedef b3Quat b3RecCType_QUAT;
typedef b3Transform b3RecCType_TRANSFORM;
typedef b3Pos b3RecCType_POSITION;
typedef b3WorldTransform b3RecCType_WORLDXF;
typedef b3Matrix3 b3RecCType_MATRIX3;
typedef b3AABB b3RecCType_AABB;
typedef b3Sphere b3RecCType_SPHERE;
typedef b3Capsule b3RecCType_CAPSULE;
typedef b3QueryFilter b3RecCType_QUERYFILTER;
typedef b3ShapeProxy b3RecCType_SHAPEPROXY;
typedef b3Matrix3 b3RecCType_MATRIX3;
typedef b3AABB b3RecCType_AABB;
typedef b3Sphere b3RecCType_SPHERE;
typedef b3Capsule b3RecCType_CAPSULE;
typedef b3QueryFilter b3RecCType_QUERYFILTER;
typedef b3ShapeProxy b3RecCType_SHAPEPROXY;
// Geometry reference: a plain u32 id into the trailing registry
typedef uint32_t b3RecCType_GEOMID;
typedef b3Filter b3RecCType_FILTER;
typedef uint32_t b3RecCType_GEOMID;
typedef b3Filter b3RecCType_FILTER;
typedef b3SurfaceMaterial b3RecCType_MATERIAL;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_STR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
typedef b3JointId b3RecCType_JOINTID;
typedef b3BodyDef b3RecCType_BODYDEF;
typedef b3ShapeDef b3RecCType_SHAPEDEF;
typedef b3ExplosionDef b3RecCType_EXPLOSIONDEF;
typedef b3ParallelJointDef b3RecCType_PARALLELJOINTDEF;
typedef b3DistanceJointDef b3RecCType_DISTANCEJOINTDEF;
typedef b3FilterJointDef b3RecCType_FILTERJOINTDEF;
typedef b3MotorJointDef b3RecCType_MOTORJOINTDEF;
typedef b3MassData b3RecCType_MASSDATA;
typedef b3MotionLocks b3RecCType_LOCKS;
typedef const char* b3RecCType_STR;
typedef b3WorldId b3RecCType_WORLDID;
typedef b3BodyId b3RecCType_BODYID;
typedef b3ShapeId b3RecCType_SHAPEID;
typedef b3JointId b3RecCType_JOINTID;
typedef b3BodyDef b3RecCType_BODYDEF;
typedef b3ShapeDef b3RecCType_SHAPEDEF;
typedef b3ExplosionDef b3RecCType_EXPLOSIONDEF;
typedef b3ParallelJointDef b3RecCType_PARALLELJOINTDEF;
typedef b3DistanceJointDef b3RecCType_DISTANCEJOINTDEF;
typedef b3FilterJointDef b3RecCType_FILTERJOINTDEF;
typedef b3MotorJointDef b3RecCType_MOTORJOINTDEF;
typedef b3PrismaticJointDef b3RecCType_PRISMATICJOINTDEF;
typedef b3RevoluteJointDef b3RecCType_REVOLUTEJOINTDEF;
typedef b3RevoluteJointDef b3RecCType_REVOLUTEJOINTDEF;
typedef b3SphericalJointDef b3RecCType_SPHERICALJOINTDEF;
typedef b3WeldJointDef b3RecCType_WELDJOINTDEF;
typedef b3WheelJointDef b3RecCType_WHEELJOINTDEF;
typedef b3WeldJointDef b3RecCType_WELDJOINTDEF;
typedef b3WheelJointDef b3RecCType_WHEELJOINTDEF;
// Codegen pass 1a: arg structs. Generated here so call sites (body.c, shape.c, etc.) can see them.
#define ARG( TAG, field ) b3RecCType_##TAG field;
@ -251,7 +272,7 @@ void b3RecEndRecord( b3Recording* rec );
// Create ops: declare writers that also append the returned id inside the record.
#define B3_REC_RETDECL_RET_NONE( Name )
#define B3_REC_RETDECL_RET_BODYID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3BodyId id );
#define B3_REC_RETDECL_RET_BODYID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3BodyId id );
#define B3_REC_RETDECL_RET_SHAPEID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3ShapeId id );
#define B3_REC_RETDECL_RET_JOINTID( Name ) void b3RecWriteRet_##Name( b3Recording* rec, const b3RecArgs_##Name* a, b3JointId id );
#define B3_REC_OP( op, Name, RET, ... ) B3_REC_RETDECL_##RET( Name )
@ -268,8 +289,8 @@ void b3RecEndRecord( b3Recording* rec );
{ \
if ( ( world )->recording != NULL ) \
{ \
b3RecArgs_##Name recArgs = { __VA_ARGS__ }; \
b3RecWrite_##Name( ( world )->recording, &recArgs ); \
b3RecArgs_##Name recArgs = { __VA_ARGS__ }; \
b3RecWrite_##Name( ( world )->recording, &recArgs ); \
} \
} \
while ( 0 )
@ -280,14 +301,14 @@ void b3RecEndRecord( b3Recording* rec );
{ \
if ( ( world )->recording != NULL ) \
{ \
b3RecArgs_##Name recCreateArgs = { __VA_ARGS__ }; \
b3RecWriteRet_##Name( ( world )->recording, &recCreateArgs, id ); \
b3RecArgs_##Name recCreateArgs = { __VA_ARGS__ }; \
b3RecWriteRet_##Name( ( world )->recording, &recCreateArgs, id ); \
} \
} \
while ( 0 )
// Patch helpers for the query hit-count backfill
int b3RecReserveU32( b3RecBuffer* buf );
int b3RecReserveU32( b3RecBuffer* buf );
void b3RecPatchU32( b3RecBuffer* buf, int offset, uint32_t v );
// Commit a finished query record under the lock. The payload buffer stays owned by the caller.
@ -299,31 +320,44 @@ typedef struct b3RecQueryWriter
union
{
b3OverlapResultFcn* overlapFcn;
b3CastResultFcn* castFcn;
b3PlaneResultFcn* planeFcn;
b3MoverFilterFcn* moverFilterFcn;
b3CastResultFcn* castFcn;
b3PlaneResultFcn* planeFcn;
b3MoverFilterFcn* moverFilterFcn;
} userFcn;
void* userContext;
b3RecBuffer buf; // per-call local payload, heap-backed
int countOffset; // offset of the reserved u32 hit-count slot
uint32_t hitCount;
void* userContext;
b3RecBuffer buf; // per-call local payload, heap-backed
int countOffset; // offset of the reserved u32 hit-count slot
uint32_t hitCount;
uint64_t tagId; // caller query id, 0 = untagged. Emitted as a QueryTag before the record.
const char* tagName; // caller query name, interned by id. NULL = none.
} b3RecQueryWriter;
void b3RecQueryBegin( b3RecQueryWriter* w, void* context );
void b3RecQueryBegin( b3RecQueryWriter* w, void* context, uint64_t tagId, const char* tagName );
void b3RecQueryCommit( b3Recording* rec, uint8_t opcode, b3RecQueryWriter* w );
// Recording trampolines: replace the user fcn so hits are captured before dispatch. The overlap
// trampoline doubles for the mover filter, which has the same bool(shapeId, ctx) shape.
bool b3RecOverlapTrampoline( b3ShapeId id, void* ctx );
bool b3RecOverlapTrampoline( b3ShapeId id, void* ctx );
float b3RecCastTrampoline( b3ShapeId id, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId, int triangleIndex,
int childIndex, void* ctx );
bool b3RecPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx );
bool b3RecPlaneTrampoline( b3ShapeId id, const b3PlaneResult* planes, int planeCount, void* ctx );
// Geometry registry
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash,
uint8_t* bytes, int byteCount );
void b3FreeRegistry( b3GeometryRegistry* reg );
void b3RecWriteRegistry( b3Recording* rec );
uint32_t b3InternGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount );
// Append an entry unconditionally and return its id, which equals its array index. Unlike
// b3InternGeometry it never deduplicates, so the keyframe seed can mirror slots 1:1 even when an
// already-recorded file carries byte-identical duplicate slots (a hash collision wrote them apart).
uint32_t b3AppendGeometry( b3GeometryRegistry* reg, b3GeometryKind kind, uint64_t contentHash, uint8_t* bytes, int byteCount );
void b3FreeRegistry( b3GeometryRegistry* reg );
void b3RecWriteRegistry( b3Recording* rec );
// Hash a query (id, name) pair into the stable key the viewer tracks the query by. Never returns 0,
// so the key doubles as a tagged/untagged flag.
uint64_t b3HashQueryTag( uint64_t id, const char* name );
// Record a key->(id, name) mapping once, deduped by key (a repeated key keeps its first id/name).
// The name is clamped to B3_NAME_LENGTH.
void b3RecInternTag( b3Recording* rec, uint64_t key, uint64_t id, const char* name );
// Intern each large geometry kind and return a stable u32 id for use in create ops.
// Caller does NOT free bytes; b3InternGeometry takes ownership (frees on duplicate).

View file

@ -223,6 +223,11 @@ B3_REC_OP( 0xED, QueryCastMover, RET_NONE,
B3_REC_OP( 0xEE, QueryCollideMover, RET_NONE,
ARG( WORLDID, world ) ARG( POSITION, origin ) ARG( CAPSULE, mover ) ARG( QUERYFILTER, filter ) )
// Identity key (hash of the caller id + label) for the query that immediately follows. Emitted only
// for a tagged query. The id and label are interned in the trailing tag table, so only the 8 byte key
// rides the stream.
B3_REC_OP( 0xEF, QueryTag, RET_NONE, ARG( U64, key ) )
B3_REC_OP( 0xF1, StateHash, RET_NONE, ARG( WORLDID, world ) ARG( U64, hash ) )
// Accumulated world bounds over the whole recording, written once at stop. Informational.

File diff suppressed because it is too large Load diff

View file

@ -15,17 +15,17 @@ typedef struct b3RecPlayer b3RecPlayer;
// replicated across a shape's planes so the replay walker can re-group and compare per shape.
typedef struct b3RecRecordedHit
{
b3ShapeId id;
b3Pos point;
b3Vec3 normal;
float fraction;
uint64_t userMaterialId;
int triangleIndex;
int childIndex;
b3PlaneResult plane; // collide-mover: this plane
int planeCount; // collide-mover: planes in this hit's shape group (replicated)
float userReturnF; // cast queries
bool userReturnB; // overlap / collide-mover (per shape, replicated)
b3ShapeId id;
b3Pos point;
b3Vec3 normal;
float fraction;
uint64_t userMaterialId;
int triangleIndex;
int childIndex;
b3PlaneResult plane; // collide-mover: this plane
int planeCount; // collide-mover: planes in this hit's shape group (replicated)
float userReturnF; // cast queries
bool userReturnB; // overlap / collide-mover (per shape, replicated)
} b3RecRecordedHit;
// Recorded query kind, matching the public b3RecQueryType order.
@ -45,20 +45,21 @@ typedef enum b3RecQueryKind
// AABB, which is world space in 3D.
typedef struct b3RecDrawQuery
{
int kind;
int kind;
uint64_t key; // identity key (hash of caller id+name), 0 = untagged
b3QueryFilter filter;
b3AABB aabb; // overlap AABB, world space
b3Vec3 proxyPoints[B3_MAX_SHAPE_CAST_POINTS]; // overlap/cast shape proxy, origin relative
int proxyCount;
float proxyRadius;
b3Capsule mover; // cast/collide mover, origin relative
b3Pos origin;
b3Vec3 translation;
float castFraction; // cast-mover result fraction
b3RayResult rayResult; // cast-ray-closest result
b3ShapeId shape;
int hitStart; // first hit in the player's frameHits store
int hitCount;
b3AABB aabb; // world-space bounds of the query, swept for casts
b3Vec3 proxyPoints[B3_MAX_SHAPE_CAST_POINTS]; // overlap/cast shape proxy, origin relative
int proxyCount;
float proxyRadius;
b3Capsule mover; // cast/collide mover, origin relative
b3Pos origin;
b3Vec3 translation;
float castFraction; // cast-mover result fraction
b3RayResult rayResult; // cast-ray-closest result
b3ShapeId shape;
int hitStart; // first hit in the player's frameHits store
int hitCount;
} b3RecDrawQuery;
// One slot in the preloaded geometry registry. Loaded from the trailing block before any
@ -66,174 +67,184 @@ typedef struct b3RecDrawQuery
typedef struct b3RegistrySlot
{
b3GeometryKind kind;
int byteCount;
uint8_t* bytes; // raw bytes from the file (always freed at teardown)
void* live; // reconstructed live object, freed after b3DestroyWorld
int byteCount;
uint8_t* bytes; // raw bytes from the file (always freed at teardown)
void* live; // reconstructed live object, freed after b3DestroyWorld
} b3RegistrySlot;
// Reader state threaded through the replay loop and all dispatch functions
typedef struct b3RecReader
{
const uint8_t* data;
int size;
int cursor;
b3WorldId replayWorldId;
bool ok; // false on read overrun or id mismatch, fatal stop
bool diverged; // a StateHash failed, non-fatal
int size;
int cursor;
b3WorldId replayWorldId;
bool ok; // false on read overrun or id mismatch, fatal stop
bool diverged; // a StateHash failed, non-fatal
// Player that owns this reader, or NULL during a headless b3ValidateReplay. Body
// create/destroy and the bounds record fold back into it for the outliner and camera framing.
b3RecPlayer* owner;
b3RecPlayer* owner;
// Scratch for per-triangle materials in shape defs (grown on demand, freed at teardown)
b3SurfaceMaterial* matScratch;
int matScratchCap;
int matScratchCap;
// Scratch for string reads: rotating slots, valid until the next 4 STR reads
char strBufs[4][B3_NAME_LENGTH + 1];
int strNext;
int strNext;
// Preloaded geometry registry
b3RegistrySlot* slots;
int slotCount;
int slotCount;
// Preloaded query-tag table (key -> id, name), loaded with the registry. Resolves the caller id and
// label for the viewer. tagMap maps a key to its tag index for O(1) lookup; opaque, owned by the player.
b3RecTag* tags;
int tagCount; // tags that loaded; a truncated tail loads fewer
int tagCapacity; // tags allocated, used to free the array
void* tagMap;
// Key from the QueryTag op preceding the next query, consumed by the next stash. 0 = untagged.
uint64_t pendingQueryKey;
// Scratch for recorded query hits; grown on demand, freed with the player.
b3RecRecordedHit* hits;
int hitCap;
int hitCap;
// Scratch for a shape-proxy point cloud read from the stream. b3ShapeProxy holds the points
// behind a pointer, so a decoded proxy borrows this until the next proxy read or teardown.
b3Vec3* proxyScratch;
int proxyScratchCap;
int proxyScratchCap;
} b3RecReader;
// Stored snapshot for fast backward seek.
typedef struct b3RecKeyframe
{
uint8_t* image; // serialized world image at the end of this frame
int imageSize;
int imageCapacity; // allocation size (may exceed imageSize)
int frame; // frame index this restores to
int cursor; // op-stream cursor for the frame AFTER this one
int divergeFrame; // divergeFrame state at capture
bool diverged; // rdr.diverged state at capture
uint8_t* image; // serialized world image at the end of this frame
int imageSize;
int imageCapacity; // allocation size (may exceed imageSize)
int frame; // frame index this restores to
int cursor; // op-stream cursor for the frame AFTER this one
int divergeFrame; // divergeFrame state at capture
bool diverged; // rdr.diverged state at capture
// Outliner body list as it stood at this frame, restored verbatim so ordinals are stable.
b3BodyId* bodyIds;
int bodyIdCount;
int bodyIdCount;
} b3RecKeyframe;
struct b3RecPlayer
{
uint8_t* data; // owned copy of recording bytes
int size;
int headerEnd; // first byte of op stream (past header + snapshot blob)
int registryEnd; // end of op stream = start of registry block (or size)
float lengthScale;
float previousLengthScale;
int frame;
int frameCount;
float recordedDt;
int recordedSubStepCount;
int recordedWorkerCount; // worker count requested for the replay world
b3AABB bounds; // accumulated world bounds, decoded from the trailing record
bool atEnd;
int divergeFrame; // first frame that diverged, -1 until then
uint8_t* data; // owned copy of recording bytes
int size;
int headerEnd; // first byte of op stream (past header + snapshot blob)
int registryEnd; // end of op stream = start of registry block (or size)
float lengthScale;
float previousLengthScale;
int frame;
int frameCount;
float recordedDt;
int recordedSubStepCount;
int recordedWorkerCount; // worker count requested for the replay world
b3AABB bounds; // accumulated world bounds, decoded from the trailing record
bool atEnd;
int divergeFrame; // first frame that diverged, -1 until then
// Outliner body list, indexed by creation ordinal. Holes (null ids) mark destroyed bodies so
// later ordinals never shift. Snapshotted into each keyframe and the frame-0 copy, not rebuilt
// from the world, so a stored selection survives backward seeks.
b3BodyId* bodyIds;
int bodyIdCount;
int bodyIdCap;
int bodyIdCount;
int bodyIdCap;
b3BodyId* frame0BodyIds;
int frame0BodyIdCount;
int frame0BodyIdCount;
// Per-frame query store, reset at the top of each StepFrame and filled by the query dispatchers.
// Drawn by b3RecPlayer_DrawFrameQueries and inspected via the public GetFrameQuery API.
b3RecDrawQuery* frameQueries;
int frameQueryCount;
int frameQueryCap;
b3RecDrawQuery* frameQueries;
int frameQueryCount;
int frameQueryCap;
b3RecRecordedHit* frameHits;
int frameHitCount;
int frameHitCap;
int frameHitCount;
int frameHitCap;
// Host debug-shape callbacks applied to every world the player creates. The 3D
// sample renderer builds GPU meshes here, so a replay world without them draws
// nothing. Set once via b3RecPlayer_SetDebugShapeCallbacks; persisted so a world
// rebuilt under new callbacks keeps drawing.
b3CreateDebugShapeCallback* createDebugShape;
b3CreateDebugShapeCallback* createDebugShape;
b3DestroyDebugShapeCallback* destroyDebugShape;
void* debugShapeContext;
void* debugShapeContext;
b3RecReader rdr;
// Frame-0 restore image, points into the owned data copy. Restart and backward seek
// deserialize this in place so the replay world id stays stable.
const uint8_t* frame0Image;
int frame0Size;
int frame0Size;
// Keyframe ring
b3RecKeyframe* keyframes;
int keyframeCount;
int keyframeCapacity;
size_t keyframeBudget;
size_t keyframeBytes;
int keyframeMinInterval;
int keyframeInterval;
int lastKeyframeFrame;
int keyframeCount;
int keyframeCapacity;
size_t keyframeBudget;
size_t keyframeBytes;
int keyframeMinInterval;
int keyframeInterval;
int lastKeyframeFrame;
// Pre-populated recording used by b3SerializeWorld during keyframe capture.
// Its registry mirrors rdr.slots so geometry ids stay stable.
b3Recording* keyframeRec;
b3Recording* keyframeRec;
};
// Read primitives
uint8_t b3RecR_U8( b3RecReader* rdr );
uint16_t b3RecR_U16( b3RecReader* rdr );
uint32_t b3RecR_U24( b3RecReader* rdr );
uint32_t b3RecR_U32( b3RecReader* rdr );
uint64_t b3RecR_U64( b3RecReader* rdr );
int32_t b3RecR_I32( b3RecReader* rdr );
float b3RecR_F32( b3RecReader* rdr );
double b3RecR_F64( b3RecReader* rdr );
bool b3RecR_BOOL( b3RecReader* rdr );
b3Vec3 b3RecR_VEC3( b3RecReader* rdr );
b3Quat b3RecR_QUAT( b3RecReader* rdr );
b3Transform b3RecR_TRANSFORM( b3RecReader* rdr );
b3Pos b3RecR_POSITION( b3RecReader* rdr );
uint8_t b3RecR_U8( b3RecReader* rdr );
uint16_t b3RecR_U16( b3RecReader* rdr );
uint32_t b3RecR_U24( b3RecReader* rdr );
uint32_t b3RecR_U32( b3RecReader* rdr );
uint64_t b3RecR_U64( b3RecReader* rdr );
int32_t b3RecR_I32( b3RecReader* rdr );
float b3RecR_F32( b3RecReader* rdr );
double b3RecR_F64( b3RecReader* rdr );
bool b3RecR_BOOL( b3RecReader* rdr );
b3Vec3 b3RecR_VEC3( b3RecReader* rdr );
b3Quat b3RecR_QUAT( b3RecReader* rdr );
b3Transform b3RecR_TRANSFORM( b3RecReader* rdr );
b3Pos b3RecR_POSITION( b3RecReader* rdr );
b3WorldTransform b3RecR_WORLDXF( b3RecReader* rdr );
b3Matrix3 b3RecR_MATRIX3( b3RecReader* rdr );
b3AABB b3RecR_AABB( b3RecReader* rdr );
b3WorldId b3RecR_WORLDID( b3RecReader* rdr );
b3BodyId b3RecR_BODYID( b3RecReader* rdr );
b3ShapeId b3RecR_SHAPEID( b3RecReader* rdr );
b3JointId b3RecR_JOINTID( b3RecReader* rdr );
b3Sphere b3RecR_SPHERE( b3RecReader* rdr );
b3Capsule b3RecR_CAPSULE( b3RecReader* rdr );
uint32_t b3RecR_GEOMID( b3RecReader* rdr );
b3Filter b3RecR_FILTER( b3RecReader* rdr );
b3Matrix3 b3RecR_MATRIX3( b3RecReader* rdr );
b3AABB b3RecR_AABB( b3RecReader* rdr );
b3WorldId b3RecR_WORLDID( b3RecReader* rdr );
b3BodyId b3RecR_BODYID( b3RecReader* rdr );
b3ShapeId b3RecR_SHAPEID( b3RecReader* rdr );
b3JointId b3RecR_JOINTID( b3RecReader* rdr );
b3Sphere b3RecR_SPHERE( b3RecReader* rdr );
b3Capsule b3RecR_CAPSULE( b3RecReader* rdr );
uint32_t b3RecR_GEOMID( b3RecReader* rdr );
b3Filter b3RecR_FILTER( b3RecReader* rdr );
b3SurfaceMaterial b3RecR_MATERIAL( b3RecReader* rdr );
b3MassData b3RecR_MASSDATA( b3RecReader* rdr );
b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr );
const char* b3RecR_STR( b3RecReader* rdr );
b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr );
b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr );
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr );
b3ParallelJointDef b3RecR_PARALLELJOINTDEF( b3RecReader* rdr );
b3DistanceJointDef b3RecR_DISTANCEJOINTDEF( b3RecReader* rdr );
b3FilterJointDef b3RecR_FILTERJOINTDEF( b3RecReader* rdr );
b3MotorJointDef b3RecR_MOTORJOINTDEF( b3RecReader* rdr );
b3MassData b3RecR_MASSDATA( b3RecReader* rdr );
b3MotionLocks b3RecR_LOCKS( b3RecReader* rdr );
const char* b3RecR_STR( b3RecReader* rdr );
b3ExplosionDef b3RecR_EXPLOSIONDEF( b3RecReader* rdr );
b3BodyDef b3RecR_BODYDEF( b3RecReader* rdr );
b3ShapeDef b3RecR_SHAPEDEF( b3RecReader* rdr );
b3ParallelJointDef b3RecR_PARALLELJOINTDEF( b3RecReader* rdr );
b3DistanceJointDef b3RecR_DISTANCEJOINTDEF( b3RecReader* rdr );
b3FilterJointDef b3RecR_FILTERJOINTDEF( b3RecReader* rdr );
b3MotorJointDef b3RecR_MOTORJOINTDEF( b3RecReader* rdr );
b3PrismaticJointDef b3RecR_PRISMATICJOINTDEF( b3RecReader* rdr );
b3RevoluteJointDef b3RecR_REVOLUTEJOINTDEF( b3RecReader* rdr );
b3RevoluteJointDef b3RecR_REVOLUTEJOINTDEF( b3RecReader* rdr );
b3SphericalJointDef b3RecR_SPHERICALJOINTDEF( b3RecReader* rdr );
b3WeldJointDef b3RecR_WELDJOINTDEF( b3RecReader* rdr );
b3WheelJointDef b3RecR_WHEELJOINTDEF( b3RecReader* rdr );
b3QueryFilter b3RecR_QUERYFILTER( b3RecReader* rdr );
b3ShapeProxy b3RecR_SHAPEPROXY( b3RecReader* rdr );
b3TreeStats b3RecR_TREESTATS( b3RecReader* rdr );
b3RayResult b3RecR_RAYRESULT( b3RecReader* rdr );
b3PlaneResult b3RecR_PLANERESULT( b3RecReader* rdr );
b3WeldJointDef b3RecR_WELDJOINTDEF( b3RecReader* rdr );
b3WheelJointDef b3RecR_WHEELJOINTDEF( b3RecReader* rdr );
b3QueryFilter b3RecR_QUERYFILTER( b3RecReader* rdr );
b3ShapeProxy b3RecR_SHAPEPROXY( b3RecReader* rdr );
b3TreeStats b3RecR_TREESTATS( b3RecReader* rdr );
b3RayResult b3RecR_RAYRESULT( b3RecReader* rdr );
b3PlaneResult b3RecR_PLANERESULT( b3RecReader* rdr );
// Grow the reader's hit scratch to at least n entries, preserving contents. n is bounded by the
// file size since every recorded hit consumes at least one byte.

View file

@ -191,20 +191,6 @@ static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTran
shape->fatAABB = (b3AABB){ b3Vec3_zero, b3Vec3_zero };
shape->generation += 1;
if ( def->name )
{
#if defined( _MSC_VER )
strncpy_s( shape->name, B3_NAME_LENGTH + 1, def->name, B3_NAME_LENGTH );
#else
strncpy( shape->name, def->name, B3_NAME_LENGTH );
shape->name[B3_NAME_LENGTH] = 0;
#endif
}
else
{
memset( shape->name, 0, sizeof( shape->name ) );
}
if ( shape->type == b3_compoundShape )
{
// Own a copy of the compound materials so every shape frees its array the same way. Compounds
@ -381,7 +367,22 @@ b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def,
b3Vec3 scale )
{
B3_VALIDATE( b3IsValidHull( hull ) );
return b3CreateShape( bodyId, def, hull, b3_hullShape, transform, scale, true );
b3ShapeId shapeId = b3CreateShape( bodyId, def, hull, b3_hullShape, transform, scale, true );
if ( shapeId.index1 != 0 )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world != NULL && world->recording != NULL )
{
// The transform and scale are baked into fresh hull data at create time. Record the baked hull
// as a plain hull shape so replay rebuilds identical geometry with no rebake, and the keyframe
// registry, which interns the live baked hull, stays seeded.
b3Shape* shape = b3Array_Get( world->shapes, shapeId.index1 - 1 );
uint32_t geometryId = b3RecInternHull( world->recording, shape->hull );
b3RecArgs_CreateHullShape createArgs = { bodyId, *def, geometryId };
b3RecWriteRet_CreateHullShape( world->recording, &createArgs, shapeId );
}
}
return shapeId;
}
b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3MeshData* mesh, b3Vec3 scale )
@ -1134,33 +1135,6 @@ bool b3Shape_IsSensor( b3ShapeId shapeId )
return shape->sensorIndex != B3_NULL_INDEX;
}
void b3Shape_SetName( b3ShapeId shapeId, const char* name )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
if ( name )
{
#if defined( _MSC_VER )
strncpy_s( shape->name, B3_NAME_LENGTH + 1, name, B3_NAME_LENGTH );
#else
strncpy( shape->name, name, B3_NAME_LENGTH );
shape->name[B3_NAME_LENGTH] = 0;
#endif
}
else
{
memset( shape->name, 0, sizeof( shape->name ) );
}
}
const char* b3Shape_GetName( b3ShapeId shapeId )
{
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
return shape->name;
}
// todo no tests
b3WorldCastOutput b3Shape_RayCast( b3ShapeId shapeId, b3Pos origin, b3Vec3 translation )
{
@ -2050,13 +2024,17 @@ typedef struct b3MeshImpactContext
b3Vec3 meshLocalCentroidB1, meshLocalCentroidB2;
float fallbackRadius;
bool isSensor;
int visitCount;
} b3MeshImpactContext;
static bool b3MeshTimeOfImpactFcn( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context )
{
B3_UNUSED( triangleIndex );
b3MeshImpactContext* toiContext = (b3MeshImpactContext*)context;
b3MeshImpactContext* toiContext = context;
toiContext->visitCount += 1;
// Early out for parallel movement
b3Vec3 c1 = toiContext->meshLocalCentroidB1;
@ -2257,6 +2235,8 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
// todo implement b3MeshTimeOfImpact and b3HeightFieldTimeOfImpact
// Note: assuming mesh is static
uint64_t ticks = b3GetTicks();
b3MeshImpactContext context = { 0 };
context.toiInput.sweepA = *sweepA;
context.toiInput.proxyA.count = 3;
@ -2284,11 +2264,6 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
.q = sweepB->q2,
};
// b3Vec3 centroidB1 = b3InvRotateVector( xfA.q, b3RotateVector( sweepB->q1, localCentroidB - sweepB->localCenter ) +
// ( sweepB->c1 - xfA.p ) );
// b3Vec3 centroidB2 = b3InvRotateVector( xfA.q, b3RotateVector( sweepB->q2, localCentroidB - sweepB->localCenter ) +
// ( sweepB->c2 - xfA.p ) );
context.meshLocalCentroidB1 = b3InvTransformPoint( xfA, b3TransformPoint( xfB1, localCentroidB ) );
context.meshLocalCentroidB2 = b3InvTransformPoint( xfA, b3TransformPoint( xfB2, localCentroidB ) );
@ -2311,6 +2286,12 @@ b3TOIOutput b3ShapeTimeOfImpact( b3Shape* shapeA, b3Shape* shapeB, b3Sweep* swee
b3QueryHeightField( shapeA->heightField, localBounds, b3MeshTimeOfImpactFcn, &context );
}
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Log( "CCD stall: visited %d triangles", context.visitCount );
}
return context.toiOutput;
}
@ -2396,11 +2377,6 @@ void b3DumpShape( b3World* world, int shapeIndex )
b3Dump( " b3ShapeDef sd = b3DefaultShapeDef();\n" );
if ( shape->name[0] != 0 )
{
b3Dump( " sd.name = \"%s\";\n", shape->name );
}
// printf("%" PRIx64 ";\n", t);
b3Dump( " sd.density = %.9g;\n", shape->density );
b3Dump( " sd.isSensor = bool(%d);\n", shape->sensorIndex != B3_NULL_INDEX );

View file

@ -36,7 +36,6 @@ typedef struct b3Shape
b3Filter filter;
void* userData;
void* userShape;
char name[B3_NAME_LENGTH + 1];
uint16_t generation;
bool enableSensorEvents;

View file

@ -326,6 +326,8 @@ typedef struct b3ContinuousContext
float sensorFractions[B2_MAX_CONTINUOUS_SENSOR_HITS];
int sensorCount;
int visitCount;
int distanceIterations;
int pushBackIterations;
int rootIterations;
@ -337,7 +339,9 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
B3_UNUSED( proxyId );
int shapeId = (int)userData;
b3ContinuousContext* continuousContext = (b3ContinuousContext*)context;
b3ContinuousContext* continuousContext = context;
continuousContext->visitCount += 1;
b3Shape* fastShape = continuousContext->fastShape;
b3BodySim* fastBodySim = continuousContext->fastBodySim;
@ -407,6 +411,8 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
}
}
uint64_t ticks = b3GetTicks();
// todo does having a sweep on shapeA help with bullets?
b3Sweep sweepA = b3MakeRelativeSweep( bodySim, continuousContext->base );
@ -452,6 +458,12 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
}
}
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Log( "CCD stall: duration %.1f ms for %s versus %s", ms, fastBody->name, body->name );
}
// Continue query
return true;
}
@ -461,6 +473,8 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
{
b3TracyCZoneNC( ccd, "CCD", b3_colorDarkGoldenRod, true );
uint64_t ticks = b3GetTicks();
b3SolverSet* awakeSet = b3Array_Get( world->solverSets, b3_awakeSet );
b3BodySim* fastBodySim = b3Array_Get( awakeSet->bodySims, bodySimIndex );
B3_ASSERT( fastBodySim->flags & b3_isFast );
@ -621,6 +635,16 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
taskContext->pushBackIterations = b3MaxInt( taskContext->pushBackIterations, context.pushBackIterations );
taskContext->rootIterations = b3MaxInt( taskContext->rootIterations, context.rootIterations );
float ms = b3GetMilliseconds( ticks );
if ( ms > 1000.0f * b3GetStallThreshold() )
{
b3Vec3 c1 = sweep.c1;
b3Vec3 c2 = sweep.c2;
int vc = context.visitCount;
b3Log( "CCD stall: duration %.1f ms and visit count %d for %s: c1 = (%g, %g, %g), c2 = (%g, %g, %g)", ms, vc,
fastBody->name, c1.x, c1.y, c1.z, c2.x, c2.y, c2.z );
}
b3TracyCZoneEnd( ccd );
}

View file

@ -52,7 +52,7 @@ b3Filter b3DefaultFilter( void )
b3QueryFilter b3DefaultQueryFilter( void )
{
b3QueryFilter filter = { B3_DEFAULT_CATEGORY_BITS, B3_DEFAULT_MASK_BITS };
b3QueryFilter filter = { B3_DEFAULT_CATEGORY_BITS, B3_DEFAULT_MASK_BITS, 0, NULL };
return filter;
}
@ -105,6 +105,11 @@ static void b3EmptyDrawSphere( b3Pos p, float radius, b3HexColor color, float al
B3_UNUSED( p, radius, color, alpha, context );
}
static void b3EmptyDrawCapsule( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, void* context )
{
B3_UNUSED( p1, p2, radius, color, alpha, context );
}
static void b3EmptyDrawBounds( b3AABB aabb, b3HexColor color, void* context )
{
B3_UNUSED( aabb, color, context );
@ -130,6 +135,7 @@ b3DebugDraw b3DefaultDebugDraw( void )
draw.DrawTransformFcn = b3EmptyDrawTransform;
draw.DrawPointFcn = b3EmptyDrawPoint;
draw.DrawSphereFcn = b3EmptyDrawSphere;
draw.DrawCapsuleFcn = b3EmptyDrawCapsule;
draw.DrawBoundsFcn = b3EmptyDrawBounds;
draw.DrawBoxFcn = b3EmptyDrawBox;
draw.DrawStringFcn = b3EmptyDrawString;

View file

@ -32,10 +32,10 @@
#include <string.h>
// Snapshot image magic 'BNS3' and version
#define B3_SNAP_MAGIC 0x33534E42u
#define B3_SNAP_MAGIC 0x33534E42u
#define B3_SNAP_VERSION 1u
#define B3_SNAP_FLAG_VALIDATION 0x1u
#define B3_SNAP_FLAG_VALIDATION 0x1u
#define B3_SNAP_FLAG_DOUBLE_PRECISION 0x2u
// Layout hash over all POD-copied structs + key constants.
@ -43,8 +43,8 @@
static uint32_t b3ComputeLayoutHash( void )
{
uint32_t h = 2166136261u;
#define MIX( x ) \
h ^= (uint32_t)( x ); \
#define MIX( x ) \
h ^= (uint32_t)( x ); \
h *= 16777619u;
MIX( sizeof( b3Body ) )
MIX( sizeof( b3BodySim ) )
@ -88,9 +88,9 @@ typedef struct b3SnapHeader
typedef struct b3SnapReader
{
const uint8_t* data;
int cursor;
int size;
bool ok;
int cursor;
int size;
bool ok;
} b3SnapReader;
static void b3SnapRCheck( b3SnapReader* r, int need )
@ -158,36 +158,36 @@ static bool b3SnapCheckCount( const b3SnapReader* r, int count, int memSize, int
}
// POD array: count + raw bytes
#define b3SerPodArray( buf, arr ) \
do \
{ \
b3SnapW_I32( buf, ( arr ).count ); \
if ( ( arr ).count > 0 ) \
{ \
b3SnapW_Bytes( buf, ( arr ).data, ( arr ).count * (int)sizeof( *( arr ).data ) ); \
} \
} \
#define b3SerPodArray( buf, arr ) \
do \
{ \
b3SnapW_I32( buf, ( arr ).count ); \
if ( ( arr ).count > 0 ) \
{ \
b3SnapW_Bytes( buf, ( arr ).data, ( arr ).count * (int)sizeof( *( arr ).data ) ); \
} \
} \
while ( 0 )
#define b3DesPodArray( r, arr ) \
do \
{ \
int cnt = b3SnapR_I32( r ); \
int elemSize = (int)sizeof( *( arr ).data ); \
if ( (r)->ok && b3SnapCheckCount( r, cnt, elemSize, elemSize ) == false ) \
{ \
(r)->ok = false; \
} \
if ( (r)->ok && cnt > 0 ) \
{ \
b3Array_Resize( arr, cnt ); \
b3SnapR_Bytes( r, ( arr ).data, cnt * elemSize ); \
} \
else if ( (r)->ok ) \
{ \
( arr ).count = 0; \
} \
} \
#define b3DesPodArray( r, arr ) \
do \
{ \
int cnt = b3SnapR_I32( r ); \
int elemSize = (int)sizeof( *( arr ).data ); \
if ( ( r )->ok && b3SnapCheckCount( r, cnt, elemSize, elemSize ) == false ) \
{ \
( r )->ok = false; \
} \
if ( ( r )->ok && cnt > 0 ) \
{ \
b3Array_Resize( arr, cnt ); \
b3SnapR_Bytes( r, ( arr ).data, cnt * elemSize ); \
} \
else if ( ( r )->ok ) \
{ \
( arr ).count = 0; \
} \
} \
while ( 0 )
// Id pool: nextIndex + freeArray
@ -229,7 +229,7 @@ static void b3DesBitSet( b3SnapReader* r, b3BitSet* bs )
bs->bits = (uint64_t*)b3Alloc( blockCapacity * sizeof( uint64_t ) );
memset( bs->bits, 0, blockCapacity * sizeof( uint64_t ) );
bs->blockCapacity = blockCapacity;
bs->blockCount = blockCount;
bs->blockCount = blockCount;
if ( blockCount > 0 )
{
b3SnapR_Bytes( r, bs->bits, (int)( blockCount * sizeof( uint64_t ) ) );
@ -252,7 +252,7 @@ static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs )
uint32_t cap = b3SnapR_U32( r );
uint32_t cnt = b3SnapR_U32( r );
bool valid = b3SnapCheckCount( r, (int)cap, (int)sizeof( b3SetItem ), (int)sizeof( b3SetItem ) ) &&
( cap & ( cap - 1 ) ) == 0 && cnt <= cap;
( cap & ( cap - 1 ) ) == 0 && cnt <= cap;
if ( r->ok && valid == false && ( cap != 0 || cnt != 0 ) )
{
r->ok = false;
@ -264,16 +264,16 @@ static void b3DesHashSet( b3SnapReader* r, b3HashSet* hs )
}
if ( cap > 0 )
{
hs->items = (b3SetItem*)b3Alloc( cap * sizeof( b3SetItem ) );
hs->items = (b3SetItem*)b3Alloc( cap * sizeof( b3SetItem ) );
hs->capacity = cap;
hs->count = cnt;
hs->count = cnt;
b3SnapR_Bytes( r, hs->items, (int)( cap * sizeof( b3SetItem ) ) );
}
else
{
hs->items = NULL;
hs->items = NULL;
hs->capacity = 0;
hs->count = 0;
hs->count = 0;
}
}
@ -296,11 +296,11 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
{
uint64_t version;
b3SnapR_Bytes( r, &version, sizeof( uint64_t ) );
int root = b3SnapR_I32( r );
int nodeCount = b3SnapR_I32( r );
int root = b3SnapR_I32( r );
int nodeCount = b3SnapR_I32( r );
int nodeCapacity = b3SnapR_I32( r );
int freeList = b3SnapR_I32( r );
int proxyCount = b3SnapR_I32( r );
int freeList = b3SnapR_I32( r );
int proxyCount = b3SnapR_I32( r );
if ( r->ok && b3SnapCheckCount( r, nodeCapacity, (int)sizeof( b3TreeNode ), (int)sizeof( b3TreeNode ) ) == false )
{
@ -309,16 +309,16 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
// Free existing allocation including any rebuild scratch
b3Free( tree->nodes, tree->nodeCapacity * (int)sizeof( b3TreeNode ) );
b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) );
b3Free( tree->leafBoxes, tree->rebuildCapacity * (int)sizeof( b3AABB ) );
b3Free( tree->leafCenters, tree->rebuildCapacity * (int)sizeof( b3Vec3 ) );
b3Free( tree->binIndices, tree->rebuildCapacity * (int)sizeof( int ) );
tree->nodes = NULL;
tree->leafIndices = NULL;
tree->leafBoxes = NULL;
tree->leafCenters = NULL;
tree->binIndices = NULL;
tree->nodeCapacity = 0;
b3Free( tree->leafIndices, tree->rebuildCapacity * (int)sizeof( int ) );
b3Free( tree->leafBoxes, tree->rebuildCapacity * (int)sizeof( b3AABB ) );
b3Free( tree->leafCenters, tree->rebuildCapacity * (int)sizeof( b3Vec3 ) );
b3Free( tree->binIndices, tree->rebuildCapacity * (int)sizeof( int ) );
tree->nodes = NULL;
tree->leafIndices = NULL;
tree->leafBoxes = NULL;
tree->leafCenters = NULL;
tree->binIndices = NULL;
tree->nodeCapacity = 0;
tree->rebuildCapacity = 0;
if ( !r->ok )
@ -326,11 +326,11 @@ static void b3DesTree( b3SnapReader* r, b3DynamicTree* tree )
return;
}
tree->version = version;
tree->root = root;
tree->nodeCount = nodeCount;
tree->version = version;
tree->root = root;
tree->nodeCount = nodeCount;
tree->nodeCapacity = nodeCapacity;
tree->freeList = freeList;
tree->freeList = freeList;
tree->proxyCount = proxyCount;
if ( nodeCapacity > 0 )
@ -389,50 +389,50 @@ static void b3DesGraphColor( b3SnapReader* r, b3GraphColor* color, bool isOverfl
// World simulation scalars (never host/callback/worker state)
static void b3SerWorldConfig( b3RecBuffer* buf, const b3World* world )
{
b3SnapW_Bytes( buf, &world->gravity, sizeof( b3Vec3 ) );
b3SnapW_Bytes( buf, &world->hitEventThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->restitutionThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->maxLinearSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactHertz, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactDampingRatio, sizeof( float ) );
b3SnapW_Bytes( buf, &world->gravity, sizeof( b3Vec3 ) );
b3SnapW_Bytes( buf, &world->hitEventThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->restitutionThreshold, sizeof( float ) );
b3SnapW_Bytes( buf, &world->maxLinearSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactSpeed, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactHertz, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactDampingRatio, sizeof( float ) );
b3SnapW_Bytes( buf, &world->contactRecycleDistance, sizeof( float ) );
b3SnapW_Bytes( buf, &world->stepIndex, sizeof( uint64_t ) );
b3SnapW_Bytes( buf, &world->stepIndex, sizeof( uint64_t ) );
b3SnapW_I32( buf, world->splitIslandId );
b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_h, sizeof( float ) );
b3SnapW_Bytes( buf, &world->inv_dt, sizeof( float ) );
b3SnapW_I32( buf, world->endEventArrayIndex );
b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) );
b3SnapW_Bytes( buf, &world->maxCapacity, sizeof( b3Capacity ) );
uint8_t flags = 0;
flags |= world->enableSleep ? 0x01u : 0u;
flags |= world->enableWarmStarting ? 0x02u : 0u;
flags |= world->enableContinuous ? 0x04u : 0u;
flags |= world->enableSpeculative ? 0x08u : 0u;
flags |= world->enableSleep ? 0x01u : 0u;
flags |= world->enableWarmStarting ? 0x02u : 0u;
flags |= world->enableContinuous ? 0x04u : 0u;
flags |= world->enableSpeculative ? 0x08u : 0u;
b3RecBufAppend( buf, &flags, 1 );
}
static void b3DesWorldConfig( b3SnapReader* r, b3World* world )
{
b3SnapR_Bytes( r, &world->gravity, sizeof( b3Vec3 ) );
b3SnapR_Bytes( r, &world->hitEventThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->restitutionThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->maxLinearSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactHertz, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactDampingRatio, sizeof( float ) );
b3SnapR_Bytes( r, &world->gravity, sizeof( b3Vec3 ) );
b3SnapR_Bytes( r, &world->hitEventThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->restitutionThreshold, sizeof( float ) );
b3SnapR_Bytes( r, &world->maxLinearSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactSpeed, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactHertz, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactDampingRatio, sizeof( float ) );
b3SnapR_Bytes( r, &world->contactRecycleDistance, sizeof( float ) );
b3SnapR_Bytes( r, &world->stepIndex, sizeof( uint64_t ) );
b3SnapR_Bytes( r, &world->stepIndex, sizeof( uint64_t ) );
world->splitIslandId = b3SnapR_I32( r );
b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_h, sizeof( float ) );
b3SnapR_Bytes( r, &world->inv_dt, sizeof( float ) );
world->endEventArrayIndex = b3SnapR_I32( r );
b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) );
b3SnapR_Bytes( r, &world->maxCapacity, sizeof( b3Capacity ) );
uint8_t flags = 0;
b3SnapR_Bytes( r, &flags, 1 );
world->enableSleep = ( flags & 0x01u ) != 0;
world->enableSleep = ( flags & 0x01u ) != 0;
world->enableWarmStarting = ( flags & 0x02u ) != 0;
world->enableContinuous = ( flags & 0x04u ) != 0;
world->enableSpeculative = ( flags & 0x08u ) != 0;
world->enableContinuous = ( flags & 0x04u ) != 0;
world->enableSpeculative = ( flags & 0x08u ) != 0;
}
// Shapes carry pointer fields: materials, userData, userShape, and the geometry union.
@ -447,12 +447,12 @@ static void b3SerShapes( b3RecBuffer* buf, b3World* world, b3Recording* rec )
for ( int i = 0; i < count; ++i )
{
b3Shape shape = world->shapes.data[i];
bool isLive = ( shape.id == i );
bool isLive = ( shape.id == i );
// Null out pointer fields before writing the raw struct
shape.materials = NULL;
shape.userData = NULL;
shape.userShape = NULL;
shape.materials = NULL;
shape.userData = NULL;
shape.userShape = NULL;
// Zero the geometry union so free-slot images have deterministic bytes
if ( !isLive )
{
@ -463,7 +463,7 @@ static void b3SerShapes( b3RecBuffer* buf, b3World* world, b3Recording* rec )
if ( !isLive )
{
// Free slot: no materials or geometry
b3SnapW_I32( buf, 0 ); // materialCount
b3SnapW_I32( buf, 0 ); // materialCount
b3SnapW_I32( buf, -1 ); // geometry kind sentinel
continue;
}
@ -549,18 +549,18 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
// GPU mesh on each seek, which the host (a 3D renderer) would otherwise pay for. Handles that are
// not reclaimed below belong to shapes that are gone or were replaced, and get released so the host
// pool does not leak across seeks. Box2D has no such handles, so its restore skips all of this.
int oldShapeCount = world->shapes.count;
void** savedUserShape = NULL;
int oldShapeCount = world->shapes.count;
void** savedUserShape = NULL;
uint16_t* savedGeneration = NULL;
if ( oldShapeCount > 0 )
{
savedUserShape = (void**)b3Alloc( (size_t)oldShapeCount * sizeof( void* ) );
savedUserShape = (void**)b3Alloc( (size_t)oldShapeCount * sizeof( void* ) );
savedGeneration = (uint16_t*)b3Alloc( (size_t)oldShapeCount * sizeof( uint16_t ) );
for ( int i = 0; i < oldShapeCount; ++i )
{
b3Shape* old = world->shapes.data + i;
bool oldLive = ( old->id == i );
savedUserShape[i] = oldLive ? old->userShape : NULL;
b3Shape* old = world->shapes.data + i;
bool oldLive = ( old->id == i );
savedUserShape[i] = oldLive ? old->userShape : NULL;
savedGeneration[i] = old->generation;
}
}
@ -574,7 +574,7 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
b3SnapR_Bytes( r, dst, sizeof( b3Shape ) );
// Pointer fields were written as NULL; set them cleanly
dst->materials = NULL;
dst->userData = NULL;
dst->userData = NULL;
dst->userShape = NULL;
memset( &dst->capsule, 0, sizeof( dst->capsule ) );
@ -583,9 +583,9 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
// Carry the renderer handle over when the same shape still occupies this slot. Consumed
// handles are nulled so the teardown sweep only releases the ones that vanished.
if ( isLive && i < oldShapeCount && savedUserShape != NULL && savedUserShape[i] != NULL &&
savedGeneration[i] == dst->generation )
savedGeneration[i] == dst->generation )
{
dst->userShape = savedUserShape[i];
dst->userShape = savedUserShape[i];
savedUserShape[i] = NULL;
}
@ -615,7 +615,7 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
break;
}
dst->materialCount = matCount;
dst->materials = (b3SurfaceMaterial*)b3Alloc( (size_t)matCount * sizeof( b3SurfaceMaterial ) );
dst->materials = (b3SurfaceMaterial*)b3Alloc( (size_t)matCount * sizeof( b3SurfaceMaterial ) );
b3SnapR_Bytes( r, dst->materials, matCount * (int)sizeof( b3SurfaceMaterial ) );
}
else
@ -667,7 +667,7 @@ static void b3DesShapes( b3SnapReader* r, b3World* world, b3RecReader* rdr )
}
b3RegistrySlot* slot = rdr->slots + gid;
// Mesh is a self-contained blob used by reference; point straight at the pristine bytes.
dst->mesh.data = (const b3MeshData*)slot->bytes;
dst->mesh.data = (const b3MeshData*)slot->bytes;
dst->mesh.scale = scale;
break;
}
@ -746,17 +746,17 @@ static void b3SerContacts( b3RecBuffer* buf, b3World* world )
for ( int i = 0; i < count; ++i )
{
const b3Contact* c = world->contacts.data + i;
bool isLive = ( c->contactId == i );
bool isLive = ( c->contactId == i );
// Write raw struct with pointer fields zeroed
b3Contact copy = *c;
copy.manifolds = NULL;
copy.bodySimIndexA = B3_NULL_INDEX;
copy.bodySimIndexB = B3_NULL_INDEX;
copy.manifolds = NULL;
copy.bodySimIndexA = B3_NULL_INDEX;
copy.bodySimIndexB = B3_NULL_INDEX;
if ( copy.flags & b3_simMeshContact )
{
copy.meshContact.triangleCache.data = NULL;
copy.meshContact.triangleCache.count = 0;
copy.meshContact.triangleCache.data = NULL;
copy.meshContact.triangleCache.count = 0;
copy.meshContact.triangleCache.capacity = 0;
}
b3SnapW_Bytes( buf, &copy, sizeof( b3Contact ) );
@ -783,7 +783,7 @@ static void b3SerContacts( b3RecBuffer* buf, b3World* world )
if ( c->meshContact.triangleCache.count > 0 )
{
b3SnapW_Bytes( buf, c->meshContact.triangleCache.data,
c->meshContact.triangleCache.count * (int)sizeof( b3TriangleCache ) );
c->meshContact.triangleCache.count * (int)sizeof( b3TriangleCache ) );
}
}
}
@ -808,13 +808,13 @@ static void b3DesContacts( b3SnapReader* r, b3World* world )
{
b3Contact* dst = world->contacts.data + i;
b3SnapR_Bytes( r, dst, sizeof( b3Contact ) );
dst->manifolds = NULL;
dst->manifolds = NULL;
dst->bodySimIndexA = B3_NULL_INDEX;
dst->bodySimIndexB = B3_NULL_INDEX;
if ( dst->flags & b3_simMeshContact )
{
dst->meshContact.triangleCache.data = NULL;
dst->meshContact.triangleCache.count = 0;
dst->meshContact.triangleCache.data = NULL;
dst->meshContact.triangleCache.count = 0;
dst->meshContact.triangleCache.capacity = 0;
}
@ -834,13 +834,13 @@ static void b3DesContacts( b3SnapReader* r, b3World* world )
r->ok = false;
break;
}
dst->manifolds = b3AllocateManifolds( world, manifoldCount );
dst->manifolds = b3AllocateManifolds( world, manifoldCount );
dst->manifoldCount = manifoldCount;
b3SnapR_Bytes( r, dst->manifolds, manifoldCount * (int)sizeof( b3Manifold ) );
}
else
{
dst->manifolds = NULL;
dst->manifolds = NULL;
dst->manifoldCount = 0;
}
@ -883,7 +883,7 @@ static void b3FreeLiveSimElements( b3World* world )
if ( s->materials != NULL )
{
b3Free( s->materials, (size_t)s->materialCount * sizeof( b3SurfaceMaterial ) );
s->materials = NULL;
s->materials = NULL;
s->materialCount = 0;
}
// Hull is ref-counted in the world DB; release before overwrite so re-adding is ref-neutral.
@ -904,7 +904,7 @@ static void b3FreeLiveSimElements( b3World* world )
if ( c->manifolds != NULL )
{
b3FreeManifolds( world, c->manifolds, c->manifoldCount );
c->manifolds = NULL;
c->manifolds = NULL;
c->manifoldCount = 0;
}
if ( c->flags & b3_simMeshContact )
@ -939,10 +939,10 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
// Snapshot header
b3SnapHeader hdr;
hdr.magic = B3_SNAP_MAGIC;
hdr.version = B3_SNAP_VERSION;
hdr.magic = B3_SNAP_MAGIC;
hdr.version = B3_SNAP_VERSION;
hdr.layoutHash = b3ComputeLayoutHash();
hdr.flags = B3_ENABLE_VALIDATION ? B3_SNAP_FLAG_VALIDATION : 0u;
hdr.flags = B3_ENABLE_VALIDATION ? B3_SNAP_FLAG_VALIDATION : 0u;
#if defined( BOX3D_DOUBLE_PRECISION )
hdr.flags |= B3_SNAP_FLAG_DOUBLE_PRECISION;
#endif
@ -973,7 +973,7 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
b3SnapW_I32( buf, bodyCount );
for ( int i = 0; i < bodyCount; ++i )
{
b3Body elem = world->bodies.data[i];
b3Body elem = world->bodies.data[i];
elem.userData = NULL;
b3SnapW_Bytes( buf, &elem, sizeof( b3Body ) );
}
@ -991,7 +991,7 @@ int b3SerializeWorld( b3World* world, b3RecBuffer* buf, b3Recording* rec )
b3SnapW_I32( buf, jointCount );
for ( int i = 0; i < jointCount; ++i )
{
b3Joint elem = world->joints.data[i];
b3Joint elem = world->joints.data[i];
elem.userData = NULL;
b3SnapW_Bytes( buf, &elem, sizeof( b3Joint ) );
}
@ -1085,10 +1085,10 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
b3SnapReader readerStorage;
b3SnapReader* r = &readerStorage;
r->data = data;
r->data = data;
r->cursor = (int)sizeof( b3SnapHeader );
r->size = size;
r->ok = true;
r->size = size;
r->ok = true;
// Free existing per-object heap before overwriting
b3FreeLiveSimElements( world );
@ -1240,9 +1240,9 @@ bool b3DeserializeIntoShell( const uint8_t* data, int size, b3World* world, b3Re
for ( int i = 0; i < islandCount && r->ok; ++i )
{
b3Island* island = world->islands.data + i;
island->setIndex = b3SnapR_I32( r );
island->localIndex = b3SnapR_I32( r );
island->islandId = b3SnapR_I32( r );
island->setIndex = b3SnapR_I32( r );
island->localIndex = b3SnapR_I32( r );
island->islandId = b3SnapR_I32( r );
island->constraintRemoveCount = b3SnapR_I32( r );
b3Array_Create( island->bodies );
b3Array_Create( island->contacts );

View file

@ -869,6 +869,103 @@ static int QueryReplay( void )
return 0;
}
// Tagged queries: the caller (id, label) is hashed into a key that rides the QueryTag op, with the id
// and label interned in the trailing tag table. The same label under two entity ids is two distinct
// keys. All survive a file round-trip and resolve back through b3RecQueryInfo; untagged queries report
// key 0 / id 0 / name NULL.
static int TaggedQuery( void )
{
b3Recording* rec = b3CreateRecording( 0 );
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.type = b3_staticBody;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 20.0f, 1.0f, 20.0f );
b3ShapeDef groundShape = b3DefaultShapeDef();
b3CreateHullShape( groundId, &groundShape, &groundBox.base );
b3World_StartRecording( worldId, rec );
// Same label, different entity ids: distinct logical queries with distinct keys.
b3QueryFilter bullet53 = b3DefaultQueryFilter();
bullet53.id = 53;
bullet53.name = "bullet";
b3QueryFilter bullet54 = b3DefaultQueryFilter();
bullet54.id = 54;
bullet54.name = "bullet";
b3QueryFilter untagged = b3DefaultQueryFilter();
uint64_t key53 = b3HashQueryTag( 53, "bullet" );
uint64_t key54 = b3HashQueryTag( 54, "bullet" );
ENSURE( key53 != 0 && key54 != 0 && key53 != key54 );
const int totalFrames = 10;
for ( int i = 0; i < totalFrames; ++i )
{
b3Pos origin = { 0.0f, 6.0f, 0.0f };
b3Vec3 translation = { 0.0f, -8.0f, 0.0f };
b3AABB aabb = { { -5.0f, -1.0f, -5.0f }, { 5.0f, 6.0f, 5.0f } };
// Two tagged rays sharing the label "bullet" plus one untagged overlap, every frame.
b3World_CastRay( worldId, origin, translation, bullet53, QueryReplayCastFcn, NULL );
b3World_CastRay( worldId, origin, translation, bullet54, QueryReplayCastFcn, NULL );
b3World_OverlapAABB( worldId, aabb, untagged, QueryReplayOverlapFcn, NULL );
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3World_StopRecording( worldId );
b3DestroyWorld( worldId );
ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) );
// Round-trip through a file so the interned tag table is exercised on the persisted bytes.
const char* path = "tagged_query_test.b3rec";
ENSURE( b3SaveRecordingToFile( rec, path ) );
b3Recording* loaded = b3LoadRecordingFromFile( path );
ENSURE( loaded != NULL );
b3RecPlayer* player = b3RecPlayer_Create( b3Recording_GetData( loaded ), b3Recording_GetSize( loaded ), 1 );
ENSURE( player != NULL );
b3RecPlayer_SeekFrame( player, 5 );
ENSURE( !b3RecPlayer_HasDiverged( player ) );
ENSURE( b3RecPlayer_GetFrameQueryCount( player ) == 3 );
bool saw53 = false, saw54 = false, sawUntagged = false;
for ( int qi = 0; qi < b3RecPlayer_GetFrameQueryCount( player ); ++qi )
{
b3RecQueryInfo info = b3RecPlayer_GetFrameQuery( player, qi );
if ( info.key == key53 )
{
saw53 = true;
ENSURE( info.id == 53 && info.name != NULL && strcmp( info.name, "bullet" ) == 0 );
}
else if ( info.key == key54 )
{
saw54 = true;
ENSURE( info.id == 54 && info.name != NULL && strcmp( info.name, "bullet" ) == 0 );
}
else
{
sawUntagged = true;
ENSURE( info.key == 0 && info.id == 0 && info.name == NULL );
}
}
ENSURE( saw53 && saw54 && sawUntagged );
b3RecPlayer_Destroy( player );
b3DestroyRecording( loaded );
b3DestroyRecording( rec );
return 0;
}
// Empty world: recording starts with no bodies and none are ever created. The empty world is still
// seed-serialized like any other, so replay validates and Restart restores in place with a stable
// world id rather than tearing down and rebuilding the world.
@ -1014,6 +1111,19 @@ static int AllOps( void )
b3ShapeId boxShapeId = b3CreateHullShape( boxBodyId, &boxShapeDef, &boxHull.base );
ENSURE( b3Shape_IsValid( boxShapeId ) );
// Transformed hull shape on a fifth dynamic body (b3CreateTransformedHullShape path)
b3BodyDef xformBodyDef = b3DefaultBodyDef();
xformBodyDef.type = b3_dynamicBody;
xformBodyDef.position = (b3Pos){ 12.0f, 5.0f, 0.0f };
b3BodyId xformBodyId = b3CreateBody( worldId, &xformBodyDef );
ENSURE( b3Body_IsValid( xformBodyId ) );
b3ShapeDef xformShapeDef = b3DefaultShapeDef();
xformShapeDef.density = 1.0f;
b3Transform xformXf = { (b3Vec3){ 0.1f, 0.2f, -0.1f }, b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 1.0f, 0.0f }, 0.4f ) };
b3ShapeId xformShapeId = b3CreateTransformedHullShape( xformBodyId, &xformShapeDef, customHull, xformXf,
(b3Vec3){ 1.25f, 0.75f, 1.5f } );
ENSURE( b3Shape_IsValid( xformShapeId ) );
// Mesh, height field, and compound static shapes (3D-only)
b3BodyDef meshBodyDef = b3DefaultBodyDef();
meshBodyDef.type = b3_staticBody;
@ -1395,7 +1505,7 @@ static int AllOps( void )
{
if ( frames % 2 == 0 )
{
b3RecPlayer_DrawFrameQueries( player, &dd, -1 );
b3RecPlayer_DrawFrameQueries( player, &dd, -1, -1 );
}
frames += 1;
}
@ -1428,6 +1538,73 @@ static int AllOps( void )
return 0;
}
// A transformed hull bakes its transform and non-uniform scale into fresh hull data at create time.
// It must be recorded like any other shape create, else its shape id allocation is invisible to the
// player and every later id drifts. A plain hull created after it would then mismatch on replay.
static int TransformedHullRoundTrip( void )
{
b3Vec3 pts[8] = {
{ -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f },
{ -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f },
{ 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f },
};
b3HullData* hull = b3CreateHull( pts, 8, 8 );
ENSURE( hull != NULL );
b3Recording* rec = b3CreateRecording( 0 );
ENSURE( rec != NULL );
b3WorldDef worldDef = b3DefaultWorldDef();
b3WorldId worldId = b3CreateWorld( &worldDef );
b3World_StartRecording( worldId, rec );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
// Baked transform with a rotation and non-uniform scale, the path Unreal uses for instanced hulls.
b3Transform xf = { (b3Vec3){ 0.25f, 0.0f, -0.5f }, b3MakeQuatFromAxisAngle( (b3Vec3){ 0.0f, 0.0f, 1.0f }, 0.3f ) };
b3Vec3 scl = { 1.5f, 0.5f, 2.0f };
for ( int i = 0; i < 3; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ (float)( i * 3 ), 5.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeId sid = b3CreateTransformedHullShape( bodyId, &shapeDef, hull, xf, scl );
ENSURE( b3Shape_IsValid( sid ) );
}
// A plain hull after the transformed ones: if the transformed creates desynced the id pool, this
// shape's recorded id would not match what replay allocates and b3ValidateReplay would fail.
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 10.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3ShapeId sid = b3CreateHullShape( bodyId, &shapeDef, hull );
ENSURE( b3Shape_IsValid( sid ) );
}
// Step past the keyframe interval so replay captures a keyframe. That path re-serializes the live
// world and interns the baked hull, which must already be in the pre-seeded registry.
for ( int i = 0; i < 20; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3World_StopRecording( worldId );
b3DestroyWorld( worldId );
b3DestroyHull( hull );
ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 1 ) );
ENSURE( b3ValidateReplay( b3Recording_GetData( rec ), b3Recording_GetSize( rec ), 4 ) );
b3DestroyRecording( rec );
return 0;
}
// Patch the reserved header bytes to nonzero and confirm b3ValidateReplay ignores them.
// Guards a future change that starts validating them or shrinks the header.
static int ReservedHeaderBytes( void )
@ -1483,8 +1660,85 @@ static int ReservedHeaderBytes( void )
return 0;
}
// Geometry that shares a content hash but differs in bytes must dedup exactly. Mirrors the keyframe
// flow that crashed: the seed appends every slot 1:1 (even byte-identical duplicates a hash collision
// left in an already-recorded file), then capture must resolve a live blob back to an existing slot
// without growing the registry. Forces the collision by handing the same hash to distinct blobs.
static int GeometryHashCollision( void )
{
const int n = 16;
const uint64_t sharedHash = 0xABCD1234ull;
// The content hash must use its full width: a one-byte change in a same-length blob has to perturb
// the high word too, not just the low one, which is the trap a reseeded 32-bit djb2 fell into.
{
uint8_t p[16];
uint8_t q[16];
memset( p, 0x11, sizeof( p ) );
memset( q, 0x11, sizeof( q ) );
q[7] = 0x12;
uint64_t hp = b3Hash64Blob( p, (int)sizeof( p ) );
uint64_t hq = b3Hash64Blob( q, (int)sizeof( q ) );
ENSURE( hp != hq );
ENSURE( (uint32_t)( hp >> 32 ) != (uint32_t)( hq >> 32 ) );
}
b3GeometryRegistry reg = { 0 };
uint8_t* blobA = (uint8_t*)b3Alloc( (size_t)n );
uint8_t* blobB = (uint8_t*)b3Alloc( (size_t)n );
memset( blobA, 0xAA, (size_t)n );
memset( blobB, 0xBB, (size_t)n );
// Distinct blobs colliding on the hash must become two entries, not a false dedup.
uint32_t idA = b3InternGeometry( &reg, b3_geometryHull, sharedHash, blobA, n );
uint32_t idB = b3InternGeometry( &reg, b3_geometryHull, sharedHash, blobB, n );
ENSURE( idA != idB );
ENSURE( reg.count == 2 );
// Re-interning either blob must find it through the hash chain and never grow the registry,
// including the one shadowed behind the bucket head. The old single-entry lookup missed the
// shadowed blob and appended a duplicate, which is exactly what tripped the keyframe assert.
uint8_t* blobA2 = (uint8_t*)b3Alloc( (size_t)n );
memset( blobA2, 0xAA, (size_t)n );
ENSURE( b3InternGeometry( &reg, b3_geometryHull, sharedHash, blobA2, n ) == idA );
ENSURE( reg.count == 2 );
uint8_t* blobB2 = (uint8_t*)b3Alloc( (size_t)n );
memset( blobB2, 0xBB, (size_t)n );
ENSURE( b3InternGeometry( &reg, b3_geometryHull, sharedHash, blobB2, n ) == idB );
ENSURE( reg.count == 2 );
b3FreeRegistry( &reg );
// Seed-then-capture: appending byte-identical duplicate slots keeps id == slot index, and a later
// exact intern still resolves to one of them without appending a new entry.
b3GeometryRegistry seeded = { 0 };
uint8_t* slot0 = (uint8_t*)b3Alloc( (size_t)n );
uint8_t* slot1 = (uint8_t*)b3Alloc( (size_t)n );
uint8_t* slot2 = (uint8_t*)b3Alloc( (size_t)n );
memset( slot0, 0xAA, (size_t)n );
memset( slot1, 0xBB, (size_t)n );
memset( slot2, 0xAA, (size_t)n ); // duplicate of slot0
ENSURE( b3AppendGeometry( &seeded, b3_geometryHull, sharedHash, slot0, n ) == 0 );
ENSURE( b3AppendGeometry( &seeded, b3_geometryHull, sharedHash, slot1, n ) == 1 );
ENSURE( b3AppendGeometry( &seeded, b3_geometryHull, sharedHash, slot2, n ) == 2 );
uint8_t* live = (uint8_t*)b3Alloc( (size_t)n );
memset( live, 0xAA, (size_t)n );
uint32_t resolved = b3InternGeometry( &seeded, b3_geometryHull, sharedHash, live, n );
ENSURE( seeded.count == 3 ); // no growth
ENSURE( resolved == 0 || resolved == 2 ); // a valid slot index for that content
ENSURE( seeded.entries[resolved].byteCount == n );
ENSURE( memcmp( seeded.entries[resolved].bytes, slot0, (size_t)n ) == 0 );
b3FreeRegistry( &seeded );
return 0;
}
int RecordingTest( void )
{
RUN_SUBTEST( GeometryHashCollision );
RUN_SUBTEST( SphereRoundTrip );
RUN_SUBTEST( EmptyWorldRoundTrip );
RUN_SUBTEST( HullDedup );
@ -1496,6 +1750,8 @@ int RecordingTest( void )
RUN_SUBTEST( PlayerAccessors );
RUN_SUBTEST( KeyframeHandleReuse );
RUN_SUBTEST( QueryReplay );
RUN_SUBTEST( TaggedQuery );
RUN_SUBTEST( TransformedHullRoundTrip );
RUN_SUBTEST( AllOps );
RUN_SUBTEST( ReservedHeaderBytes );
return 0;