Dynamic Mover (#202)

Port the dynamic character mover from Box2D including the mover joint
and pogo joint.

Match the mover and sample structure of Box2D.
This commit is contained in:
Erin Catto 2026-10-27 22:33:17 -07:00 • committed by GitHub
commit 3362633204
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 4580 additions and 885 deletions

View file

@ -169,8 +169,10 @@ set(SAMPLE_FILES
sample.h
mesh_loader.cpp
mesh_loader.h
mover.cpp
mover.h
dynamic_mover.cpp
dynamic_mover.h
geometric_mover.cpp
geometric_mover.h
jsmn.h
tiny_obj_loader.h
earcut.h

584
samples/dynamic_mover.cpp Normal file
View file

@ -0,0 +1,584 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "dynamic_mover.h"
#include "gfx/draw.h"
#include "box3d/box3d.h"
#include "box3d/math_functions.h"
#include <float.h>
struct CastContext
{
DynamicMoverCastResult result;
b3BodyId moverId;
};
static float CastCallback( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction,
uint64_t userMaterialId, int triangleIndex, int childIndex,
void* context )
{
(void)triangleIndex;
(void)childIndex;
CastContext* castContext = (CastContext*)context;
b3BodyId bodyId = b3Shape_GetBody( shapeId );
// The probes start inside or on the capsule. Sensors can't hold up the mover.
if ( B3_ID_EQUALS( bodyId, castContext->moverId ) || b3Shape_IsSensor( shapeId ) )
{
return -1.0f;
}
DynamicMoverCastResult* result = &castContext->result;
result->point = point;
result->normal = normal;
result->bodyId = bodyId;
result->userMaterialId = userMaterialId;
result->fraction = fraction;
result->hit = true;
return fraction;
}
DynamicMover::DynamicMover()
{
DynamicMoverDef def;
m_jumpSpeed = def.jumpSpeed;
m_maxSpeed = def.maxSpeed;
m_minSpeed = def.minSpeed;
m_stopSpeed = def.stopSpeed;
m_accelerate = def.accelerate;
m_airSteer = def.airSteer;
m_friction = def.friction;
m_gravityScale = def.gravityScale;
m_maxGroundForce = def.maxGroundForce;
m_maxAirForce = def.maxAirForce;
m_pogoRestLength = def.pogoRestLength;
m_pogoHertz = def.pogoHertz;
m_pogoDampingRatio = def.pogoDampingRatio;
m_pogoCompressionScale = def.pogoCompressionScale;
m_pogoTensionScale = def.pogoTensionScale;
m_enableSkirtPogo = def.enableSkirtPogo;
m_platformMaterialId = def.platformMaterialId;
m_minGroundNormalY = 0.7f;
m_capsule = def.capsule;
m_filter = def.filter;
m_worldId = b3_nullWorldId;
m_groundId = b3_nullBodyId;
m_moverId = b3_nullBodyId;
m_surfaceBodyId = b3_nullBodyId;
m_moverJointId = b3_nullJointId;
m_pogoJointId = b3_nullJointId;
m_castResult = {};
m_velocity = b3Vec3_zero;
m_timeSliding = 0.0f;
m_slideDuration = 0.2f;
m_onGround = false;
m_walkable = false;
m_jumping = false;
m_jumpTicks = 0;
m_pogoImpulse = 0.0f;
m_pogoVelocity = 0.0f;
m_pogoLength = 0.0f;
for ( DynamicMoverProbe& probe : m_probes )
{
probe = { b3Pos_zero, b3Vec3_zero, 1.0f, false };
}
m_probeCount = 0;
m_selectedProbe = 0;
}
void DynamicMover::Create( b3WorldId worldId, const DynamicMoverDef* def )
{
m_capsule = def->capsule;
m_filter = def->filter;
m_jumpSpeed = def->jumpSpeed;
m_maxSpeed = def->maxSpeed;
m_minSpeed = def->minSpeed;
m_stopSpeed = def->stopSpeed;
m_accelerate = def->accelerate;
m_airSteer = def->airSteer;
m_friction = def->friction;
m_gravityScale = def->gravityScale;
m_maxGroundForce = def->maxGroundForce;
m_maxAirForce = def->maxAirForce;
m_pogoRestLength = def->pogoRestLength;
m_pogoHertz = def->pogoHertz;
m_pogoDampingRatio = def->pogoDampingRatio;
m_pogoCompressionScale = def->pogoCompressionScale;
m_pogoTensionScale = def->pogoTensionScale;
m_enableSkirtPogo = def->enableSkirtPogo;
m_platformMaterialId = def->platformMaterialId;
m_worldId = worldId;
m_velocity = b3Vec3_zero;
m_onGround = false;
m_walkable = false;
m_jumping = false;
m_jumpTicks = 0;
m_pogoImpulse = 0.0f;
m_pogoVelocity = 0.0f;
m_pogoLength = 0.0f;
m_pogoJointId = b3_nullJointId;
b3BodyDef bodyDef = b3DefaultBodyDef();
m_groundId = b3CreateBody( worldId, &bodyDef );
// Position is the center of the capsule.
bodyDef.type = b3_dynamicBody;
bodyDef.position = def->position;
bodyDef.gravityScale = m_gravityScale;
bodyDef.motionLocks.angularX = true;
bodyDef.motionLocks.angularY = true;
bodyDef.motionLocks.angularZ = true;
bodyDef.enableSleep = false;
bodyDef.name = "mover";
m_moverId = b3CreateBody( worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = def->density;
// The mover joint and the pogo joint handle all the movement, surface friction would fight
// them.
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = 0.0f;
shapeDef.baseMaterial.customColor = b3_colorDodgerBlue;
shapeDef.filter = def->filter;
shapeDef.enablePreSolveEvents = def->enablePreSolveEvents;
shapeDef.enableSensorEvents = def->enableSensorEvents;
b3CreateCapsuleShape( m_moverId, &shapeDef, &m_capsule );
CreateMoverJoint( m_groundId );
}
void DynamicMover::CreateMoverJoint( b3BodyId baseId )
{
b3MoverJointDef moverDef = b3DefaultMoverJointDef();
moverDef.linearVelocity = m_velocity;
moverDef.maxForce = m_maxGroundForce;
moverDef.base.bodyIdA = baseId;
moverDef.base.bodyIdB = m_moverId;
moverDef.base.collideConnected = true;
m_moverJointId = b3CreateMoverJoint( m_worldId, &moverDef );
}
void DynamicMover::Destroy()
{
if ( B3_IS_NON_NULL( m_moverId ) )
{
b3DestroyBody( m_moverId );
}
if ( B3_IS_NON_NULL( m_groundId ) )
{
b3DestroyBody( m_groundId );
}
m_groundId = b3_nullBodyId;
m_moverId = b3_nullBodyId;
// Joints are implicitly destroyed.
m_moverJointId = b3_nullJointId;
m_pogoJointId = b3_nullJointId;
}
void DynamicMover::SetGravityScale( float gravityScale )
{
m_gravityScale = gravityScale;
if ( B3_IS_NON_NULL( m_moverId ) )
{
b3Body_SetGravityScale( m_moverId, gravityScale );
}
}
bool DynamicMover::Jump()
{
if ( m_onGround == false || m_walkable == false )
{
return false;
}
float surfaceVelocity = 0.0f;
if ( b3Body_IsValid( m_castResult.bodyId ) )
{
b3Vec3 v = b3Body_GetWorldPointVelocity( m_castResult.bodyId, m_castResult.point );
surfaceVelocity = v.y;
}
float mass = b3Body_GetMass( m_moverId );
float vy = b3Body_GetLinearVelocity( m_moverId ).y;
// Remove the pogo constraint velocity but add the surface velocity.
float dv = b3MaxFloat( 0.0f, m_jumpSpeed - vy ) + surfaceVelocity;
b3Body_ApplyLinearImpulseToCenter( m_moverId, { 0.0f, mass * dv, 0.0f }, true );
Launch();
return true;
}
void DynamicMover::Launch()
{
// This removes the pogo step down on the next update.
m_onGround = false;
m_walkable = false;
m_jumping = true;
m_jumpTicks = 0;
}
// Movement follows the Quake ground and air model:
// https://github.com/id-Software/Quake/blob/master/QW/client/pmove.c#L390
// onGround - controls friction, mover max force, and pogo step-down extension
// walkable - controls air steer
// jumping - blocks the pogo from pulling down
void DynamicMover::Update( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle,
float speedScale )
{
// Reach further while grounded so the spring can find the ground over a step
float stepDownLength = m_pogoRestLength;
float rayLength = m_onGround ? m_pogoRestLength + stepDownLength : m_pogoRestLength;
b3Vec3 translation = { 0.0f, -rayLength, 0.0f };
b3Pos position = b3Body_GetPosition( m_moverId );
b3Pos origin = position + m_capsule.center1;
b3QueryFilter queryFilter = {
.categoryBits = m_filter.categoryBits,
.maskBits = m_filter.maskBits,
.id = 0,
.name = "dynamic_mover_pogo",
};
CastContext castContext = { {}, m_moverId };
b3World_CastRay( m_worldId, origin, translation, queryFilter, CastCallback, &castContext );
m_castResult = castContext.result;
m_probes[0] = { origin, translation, m_castResult.hit ? m_castResult.fraction : 1.0f,
m_castResult.hit };
m_probeCount = 1;
m_selectedProbe = 0;
b3Vec3 pogoOffset = b3Vec3_zero;
bool centerWalkable = m_castResult.hit && m_castResult.normal.y >= m_minGroundNormalY;
if ( centerWalkable == false && m_enableSkirtPogo )
{
// The skirt turns with the direction of travel so ties go to the leading probe
b3Vec3 moverVelocity = b3Body_GetLinearVelocity( m_moverId );
b3Vec3 heading = { moverVelocity.x, 0.0f, moverVelocity.z };
if ( b3LengthSquared( heading ) < FLT_EPSILON )
{
heading = b3Vec3_axisX;
}
heading = b3Normalize( heading );
b3Vec3 side = { -heading.z, 0.0f, heading.x };
float bestDisplacement = FLT_MAX;
for ( int i = 0; i < m_skirtCount; ++i )
{
b3CosSin cs = b3ComputeCosSin( 2.0f * B3_PI * i / m_skirtCount );
b3Vec3 offset = m_capsule.radius * ( cs.cosine * heading + cs.sine * side );
b3Pos skirtOrigin = origin + offset;
CastContext skirtContext = { {}, m_moverId };
b3World_CastRay( m_worldId, skirtOrigin, translation, queryFilter, CastCallback,
&skirtContext );
const DynamicMoverCastResult& result = skirtContext.result;
m_probes[m_probeCount] = { skirtOrigin, translation,
result.hit ? result.fraction : 1.0f, result.hit };
// Use the walkable result that causes the least movement. With none the mover keeps
// the central hit and slides off the steep surface.
if ( result.hit && result.normal.y >= m_minGroundNormalY )
{
float displacement = b3AbsFloat( result.fraction * rayLength - m_pogoRestLength );
if ( displacement < bestDisplacement )
{
bestDisplacement = displacement;
m_castResult = result;
m_selectedProbe = m_probeCount;
pogoOffset = offset;
}
}
m_probeCount += 1;
}
}
// Should jumping end?
if ( m_jumping )
{
m_jumpTicks += 1;
// Jump ticks allow time for the jump to leave the ground. Otherwise jumping ends
// when the character approaches the current ground.
if ( m_jumpTicks > 2 && m_castResult.hit &&
b3Dot( m_velocity, m_castResult.normal ) <= 0.0f )
{
m_jumping = false;
}
}
if ( m_castResult.hit )
{
// Is the ground too steep to walk?
m_walkable = m_castResult.normal.y >= m_minGroundNormalY;
// The cast can still hit while jumping.
m_onGround = m_jumping == false;
if ( m_onGround )
{
if ( m_walkable )
{
m_timeSliding = b3MaxFloat( m_timeSliding - timeStep, 0.0f );
}
else
{
m_timeSliding = b3MinFloat( m_timeSliding + timeStep, m_slideDuration );
}
}
}
else
{
m_onGround = false;
m_walkable = false;
m_timeSliding = b3MaxFloat( m_timeSliding - timeStep, 0.0f );
}
// Connect the mover joint to platform. Acts like friction.
b3BodyId baseId = m_groundId;
if ( m_castResult.hit && m_platformMaterialId != 0 &&
m_castResult.userMaterialId == m_platformMaterialId &&
b3Body_GetType( m_castResult.bodyId ) == b3_kinematicBody )
{
baseId = m_castResult.bodyId;
}
// The mover joint can be destroyed if attached to a platform that gets destroyed.
bool moverJointValid = b3Joint_IsValid( m_moverJointId );
if ( moverJointValid == false ||
B3_ID_EQUALS( b3Joint_GetBodyA( m_moverJointId ), baseId ) == false )
{
if ( moverJointValid )
{
b3DestroyJoint( m_moverJointId, false );
}
CreateMoverJoint( baseId );
}
m_velocity = b3Body_GetLinearVelocity( m_moverId ) - b3Body_GetLinearVelocity( baseId );
// Friction acts in the horizontal plane. The pogo owns the vertical motion.
if ( m_onGround )
{
float speed = sqrtf( m_velocity.x * m_velocity.x + m_velocity.z * m_velocity.z );
if ( speed < m_minSpeed )
{
m_velocity.x = 0.0f;
m_velocity.z = 0.0f;
}
else
{
// Linear damping above stopSpeed and fixed reduction below stopSpeed
float control = speed < m_stopSpeed ? m_stopSpeed : speed;
// friction has units of 1/time
float drop = control * m_friction * timeStep;
float newSpeed = b3MaxFloat( 0.0f, speed - drop );
float ratio = newSpeed / speed;
m_velocity.x *= ratio;
m_velocity.z *= ratio;
}
}
// Mover force
float maxForce;
if ( m_onGround )
{
if ( m_slideDuration > 0.0f )
{
float scale = b3ClampFloat( 1.0f - m_timeSliding / m_slideDuration, 0.0f, 1.0f );
maxForce = scale * m_maxGroundForce;
}
else
{
maxForce = m_walkable ? m_maxGroundForce : 0.0f;
}
}
else
{
maxForce = m_maxAirForce;
}
b3MoverJoint_SetMaxVelocityForce( m_moverJointId, maxForce );
float maxSpeed = speedScale * m_maxSpeed;
b3Vec3 desiredVelocity = maxSpeed * throttle.x * forward + maxSpeed * throttle.y * right;
desiredVelocity.y = 0.0f;
float desiredSpeed;
b3Vec3 desiredDirection = b3GetLengthAndNormalize( &desiredSpeed, desiredVelocity );
if ( desiredSpeed > maxSpeed )
{
desiredSpeed = maxSpeed;
}
// Accelerate
float currentSpeed = b3Dot( m_velocity, desiredDirection );
float addSpeed = desiredSpeed - currentSpeed;
if ( addSpeed > 0.0f )
{
float steer = m_walkable ? 1.0f : m_airSteer;
float accelSpeed = steer * m_accelerate * maxSpeed * timeStep;
if ( accelSpeed > addSpeed )
{
accelSpeed = addSpeed;
}
m_velocity.x += accelSpeed * desiredDirection.x;
m_velocity.z += accelSpeed * desiredDirection.z;
}
if ( m_castResult.hit == true && b3IsNormalized( m_castResult.normal ) )
{
m_pogoLength = m_castResult.fraction * rayLength;
float moverMass = b3Body_GetMass( m_moverId );
float gravity = b3Length( b3World_GetGravity( m_worldId ) );
float moverWeight = m_gravityScale * gravity * moverMass;
bool pogoJointValid = b3Joint_IsValid( m_pogoJointId );
// Create or recreate the pogo joint as needed.
if ( B3_ID_EQUALS( m_castResult.bodyId, m_surfaceBodyId ) == false ||
pogoJointValid == false )
{
if ( pogoJointValid )
{
m_pogoImpulse = b3PogoJoint_GetImpulse( m_pogoJointId );
m_pogoVelocity = b3PogoJoint_GetCurrentSpeed( m_pogoJointId );
b3DestroyJoint( m_pogoJointId, false );
m_pogoJointId = b3_nullJointId;
}
m_surfaceBodyId = m_castResult.bodyId;
b3PogoJointDef pogoDef = b3DefaultPogoJointDef();
pogoDef.base.localFrameA.p =
b3Body_GetLocalPoint( m_surfaceBodyId, m_castResult.point );
pogoDef.base.localFrameB.p = m_capsule.center1 + pogoOffset;
pogoDef.normal = m_castResult.normal;
pogoDef.base.bodyIdA = m_surfaceBodyId;
pogoDef.base.bodyIdB = m_moverId;
pogoDef.base.collideConnected = true;
pogoDef.restLength = m_pogoRestLength;
pogoDef.hertz = m_pogoHertz;
pogoDef.dampingRatio = m_pogoDampingRatio;
pogoDef.maxCompressionForce = m_pogoCompressionScale * moverWeight;
// Warm start from the joint that was just destroyed
pogoDef.impulse = m_pogoImpulse;
pogoDef.velocity = m_pogoVelocity;
if ( m_jumping )
{
// Don't allow the pogo to pull down
pogoDef.maxTensionForce = 0.0f;
}
else
{
// The pogo can pull down at a multiple of the gravity force.
pogoDef.maxTensionForce = m_pogoTensionScale * moverWeight;
}
m_pogoJointId = b3CreatePogoJoint( m_worldId, &pogoDef );
}
else
{
// Preserve the joint, improving performance.
b3Transform localFrameA;
localFrameA.p = b3Body_GetLocalPoint( m_surfaceBodyId, m_castResult.point );
localFrameA.q = b3Quat_identity;
b3Joint_SetLocalFrameA( m_pogoJointId, localFrameA );
b3Transform localFrameB;
localFrameB.p = m_capsule.center1 + pogoOffset;
localFrameB.q = b3Quat_identity;
b3Joint_SetLocalFrameB( m_pogoJointId, localFrameB );
b3PogoJoint_SetNormal( m_pogoJointId, m_castResult.normal );
if ( m_jumping )
{
// Don't allow the pogo to pull down
b3PogoJoint_SetMaxTensionForce( m_pogoJointId, 0.0f );
}
else
{
// The pogo can pull down at a multiple of the gravity force.
b3PogoJoint_SetMaxTensionForce( m_pogoJointId, m_pogoTensionScale * moverWeight );
}
b3PogoJoint_SetMaxCompressionForce( m_pogoJointId,
m_pogoCompressionScale * moverWeight );
b3PogoJoint_SetSpringHertz( m_pogoJointId, m_pogoHertz );
b3PogoJoint_SetSpringDampingRatio( m_pogoJointId, m_pogoDampingRatio );
}
}
else
{
if ( b3Joint_IsValid( m_pogoJointId ) )
{
b3DestroyJoint( m_pogoJointId, false );
m_pogoJointId = b3_nullJointId;
}
m_surfaceBodyId = b3_nullBodyId;
m_pogoImpulse = 0.0f;
m_pogoVelocity = 0.0f;
m_pogoLength = 0.0f;
}
b3MoverJoint_SetLinearVelocity( m_moverJointId, m_velocity );
}
void DynamicMover::Draw() const
{
for ( int i = 0; i < m_probeCount; ++i )
{
const DynamicMoverProbe& probe = m_probes[i];
b3Pos end = b3OffsetPos( probe.origin, probe.fraction * probe.translation );
if ( probe.hit == false )
{
DrawLine( probe.origin, end, MakeColor( b3_colorGray ) );
continue;
}
b3HexColor color = i == m_selectedProbe ? b3_colorGreen : b3_colorYellow;
DrawLine( probe.origin, end, MakeColor( color ) );
DrawPoint( end, 6.0f, MakeColor( color ) );
}
}

167
samples/dynamic_mover.h Normal file
View file

@ -0,0 +1,167 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/types.h"
struct DynamicMoverDef
{
b3Pos position = {};
b3Capsule capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f };
float density = 200.0f;
b3Filter filter = b3DefaultFilter();
float jumpSpeed = 7.0f;
float maxSpeed = 6.0f;
float minSpeed = 0.1f;
float stopSpeed = 3.0f;
float accelerate = 20.0f;
float airSteer = 0.25f;
float friction = 8.0f;
float gravityScale = 1.5f;
float maxGroundForce = 6000.0f;
float maxAirForce = 1500.0f;
float pogoRestLength = 0.9f;
float pogoHertz = 3.0f;
float pogoDampingRatio = 0.8f;
float pogoCompressionScale = 100.0f;
float pogoTensionScale = 100.0f;
uint64_t platformMaterialId = 0;
bool enableSkirtPogo = true;
bool enablePreSolveEvents = false;
bool enableSensorEvents = false;
};
struct DynamicMoverCastResult
{
b3Pos point;
b3Vec3 normal;
b3BodyId bodyId;
uint64_t userMaterialId;
float fraction;
bool hit;
};
struct DynamicMoverProbe
{
b3Pos origin;
b3Vec3 translation;
float fraction;
bool hit;
};
// Dynamic character mover. The capsule is a rigid body with locked rotation, so it
// collides and is pushed like everything else in the world. A mover joint drives it to
// the target velocity and a pogo joint holds it above the ground so it can climb
// steps without touching the capsule.
//
// The dynamic mover should be vendored into your project so you can alter it to meet
// your game's specific needs.
//
// This system is inspired by Tom Waterson's presentation:
// https://www.youtube.com/watch?v=_jRLlTDqoGI
class DynamicMover
{
public:
DynamicMover();
void Create( b3WorldId worldId, const DynamicMoverDef* def );
void Destroy();
// Advance the mover. Throttle is the input along the forward and right directions on [-1, 1].
void Update( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, float speedScale );
// Jump if grounded. Returns false when airborne.
bool Jump();
// Release the ground so an external impulse can carry the mover into the air. Otherwise the
// pogo pulls it back down.
void Launch();
// Gravity scale is used to size the pogo forces, so change it here.
void SetGravityScale( float gravityScale );
b3BodyId GetBodyId() const
{
return m_moverId;
}
void Draw() const;
static constexpr int m_skirtCount = 8;
static constexpr int m_probeCapacity = m_skirtCount + 1;
float m_jumpSpeed;
float m_maxSpeed;
float m_minSpeed;
float m_stopSpeed;
float m_accelerate;
// Fraction of the ground acceleration available in the air.
float m_airSteer;
// Ground friction in units of 1/time.
float m_friction;
// A character usually wants to fall faster than the rest of the world.
float m_gravityScale;
// Force budget the mover joint has for reaching the target velocity. The air value
// is small so the character keeps its momentum while jumping.
float m_maxGroundForce;
float m_maxAirForce;
float m_pogoRestLength;
float m_pogoHertz;
float m_pogoDampingRatio;
// Pogo force limits as a multiple of the mover weight.
float m_pogoCompressionScale;
float m_pogoTensionScale;
// Casts an octagon skirt of rays around the capsule when the central ray misses or
// lands on a surface too steep to walk, so the mover can stand on a ledge or a thin
// rail, or step off the foot of a steep slope.
bool m_enableSkirtPogo;
// Used for the pogo to detect moving platforms.
uint64_t m_platformMaterialId;
// Surfaces steeper than this are not ground.
float m_minGroundNormalY;
b3Capsule m_capsule;
b3Filter m_filter;
b3WorldId m_worldId;
b3BodyId m_groundId;
b3BodyId m_moverId;
b3BodyId m_surfaceBodyId;
b3JointId m_moverJointId;
b3JointId m_pogoJointId;
DynamicMoverCastResult m_castResult;
b3Vec3 m_velocity;
float m_timeSliding;
float m_slideDuration;
bool m_onGround;
bool m_walkable;
bool m_jumping;
int m_jumpTicks;
// Pogo joint state, carried across the joint being recreated each update.
float m_pogoImpulse;
float m_pogoVelocity;
float m_pogoLength;
// Pogo ray cast results for drawing.
DynamicMoverProbe m_probes[m_probeCapacity];
int m_probeCount;
int m_selectedProbe;
private:
void CreateMoverJoint( b3BodyId baseId );
};

351
samples/geometric_mover.cpp Normal file
View file

@ -0,0 +1,351 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "geometric_mover.h"
#include "gfx/draw.h"
#include "box3d/box3d.h"
#include "box3d/math_functions.h"
#include <assert.h>
#include <float.h>
static bool MoverFilterCallback( b3ShapeId shapeId, void* context )
{
GeometricMover* self = (GeometricMover*)context;
for ( int i = 0; i < self->m_ignoreCount; ++i )
{
if ( B3_ID_EQUALS( shapeId, self->m_ignoreShapeIds[i] ) )
{
return false;
}
}
return true;
}
static bool PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* planeResults, int planeCount,
void* context )
{
if ( MoverFilterCallback( shapeId, context ) == false )
{
// ignore these planes but continue looking for more
return true;
}
GeometricMover* self = static_cast<GeometricMover*>( context );
float maxPush = FLT_MAX;
bool clipVelocity = true;
MoverShapeUserData* userData =
static_cast<MoverShapeUserData*>( b3Shape_GetUserData( shapeId ) );
if ( userData != nullptr )
{
maxPush = userData->maxPush;
clipVelocity = userData->clipVelocity;
}
for ( int i = 0; i < planeCount && self->m_planeCount < GeometricMover::m_planeCapacity; ++i )
{
assert( b3IsValidPlane( planeResults[i].plane ) );
self->m_planes[self->m_planeCount] = {
.plane = planeResults[i].plane,
.pushLimit = maxPush,
.push = 0.0f,
.clipVelocity = clipVelocity,
};
// The plane point is relative to the origin passed to the collide call
self->m_planeExtras[self->m_planeCount] = {
.point = b3OffsetPos( self->m_position, planeResults[i].point ),
.shapeId = shapeId,
};
self->m_planeCount += 1;
}
return true;
}
GeometricMover::GeometricMover()
{
GeometricMoverDef def;
m_jumpSpeed = def.jumpSpeed;
m_maxSpeed = def.maxSpeed;
m_minSpeed = def.minSpeed;
m_stopSpeed = def.stopSpeed;
m_accelerate = def.accelerate;
m_friction = def.friction;
m_gravity = def.gravity;
m_pogoRestLength = def.pogoRestLength;
m_pogoHertz = def.pogoHertz;
m_pogoDampingRatio = def.pogoDampingRatio;
m_clipVelocity = true;
m_ignoreShapeIds = nullptr;
m_ignoreCount = 0;
m_capsule = def.capsule;
m_worldId = b3_nullWorldId;
m_position = def.position;
m_velocity = b3Vec3_zero;
m_pogoVelocity = 0.0f;
m_onGround = false;
m_planeCount = 0;
m_totalIterations = 0;
m_pogoOrigin = b3Pos_zero;
m_pogoTranslation = b3Vec3_zero;
m_pogoPoint = b3Pos_zero;
m_pogoHit = false;
}
void GeometricMover::Create( b3WorldId worldId, const GeometricMoverDef* def )
{
m_capsule = def->capsule;
m_jumpSpeed = def->jumpSpeed;
m_maxSpeed = def->maxSpeed;
m_minSpeed = def->minSpeed;
m_stopSpeed = def->stopSpeed;
m_accelerate = def->accelerate;
m_friction = def->friction;
m_gravity = def->gravity;
m_pogoRestLength = def->pogoRestLength;
m_pogoHertz = def->pogoHertz;
m_pogoDampingRatio = def->pogoDampingRatio;
m_worldId = worldId;
m_position = def->position;
m_velocity = b3Vec3_zero;
m_pogoVelocity = 0.0f;
m_onGround = false;
m_planeCount = 0;
m_totalIterations = 0;
m_pogoHit = false;
}
bool GeometricMover::Jump()
{
if ( m_onGround == false )
{
return false;
}
m_velocity.y = m_jumpSpeed;
m_onGround = false;
return true;
}
// Solve a normal constraint between the mover and each touched rigid body. This is the
// same velocity constraint the solver uses for a contact, except the mover is treated as
// having infinite mass, so all of the impulse lands on the body.
void GeometricMover::PushBodies()
{
for ( int i = 0; i < m_planeCount; ++i )
{
b3BodyId bodyId = b3Shape_GetBody( m_planeExtras[i].shapeId );
if ( b3Body_GetType( bodyId ) != b3_dynamicBody )
{
continue;
}
MoverShapeUserData* userData =
static_cast<MoverShapeUserData*>( b3Shape_GetUserData( m_planeExtras[i].shapeId ) );
if ( userData != nullptr && userData->canMoverPush == false )
{
continue;
}
// Plane normals point at the mover
b3Pos point = m_planeExtras[i].point;
b3Vec3 normal = b3Neg( m_planes[i].plane.normal );
float invMassA = 0.0f;
float invMassB = b3Body_GetInverseMass( bodyId );
b3Matrix3 invIB = b3Body_GetWorldInverseRotationalInertia( bodyId );
b3Pos centerB = b3Body_GetWorldCenter( bodyId );
b3Vec3 rB = b3SubPos( point, centerB );
b3Vec3 rnB = b3Cross( rB, normal );
float kNormal = invMassA + invMassB + b3Dot( rnB, b3MulMV( invIB, rnB ) );
float normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
b3Vec3 vB = b3Body_GetLinearVelocity( bodyId );
b3Vec3 omegaB = b3Body_GetAngularVelocity( bodyId );
b3Vec3 vrB = b3Add( vB, b3Cross( omegaB, rB ) );
float vn = b3Dot( b3Sub( vrB, m_velocity ), normal );
// Push only, a separating body is left alone
float impulse = b3MaxFloat( -normalMass * vn, 0.0f );
b3Vec3 P = b3MulSV( impulse, normal );
m_velocity = b3MulSub( m_velocity, invMassA, P );
b3Body_ApplyLinearImpulse( bodyId, P, point, true );
}
}
// Movement follows the Quake ground and air model:
// https://github.com/id-Software/Quake/blob/master/QW/client/pmove.c#L390
void GeometricMover::Update( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle,
float speedScale )
{
// Friction
float speed = b3Length( m_velocity );
if ( speed < m_minSpeed )
{
m_velocity.x = 0.0f;
m_velocity.z = 0.0f;
}
else
{
// Linear damping above stopSpeed and fixed reduction below stopSpeed
float control = speed < m_stopSpeed ? m_stopSpeed : speed;
// friction has units of 1/time
float drop = control * m_friction * timeStep;
float newSpeed = b3MaxFloat( 0.0f, speed - drop );
float ratio = newSpeed / speed;
m_velocity.x *= ratio;
m_velocity.z *= ratio;
}
float maxSpeed = speedScale * m_maxSpeed;
b3Vec3 desiredVelocity = maxSpeed * throttle.x * forward + maxSpeed * throttle.y * right;
float desiredSpeed;
b3Vec3 desiredDirection = b3GetLengthAndNormalize( &desiredSpeed, desiredVelocity );
if ( desiredSpeed > maxSpeed )
{
desiredSpeed = maxSpeed;
}
if ( m_onGround )
{
m_velocity.y = 0.0f;
}
// Accelerate
float currentSpeed = b3Dot( m_velocity, desiredDirection );
float addSpeed = desiredSpeed - currentSpeed;
if ( addSpeed > 0.0f )
{
float accelSpeed = m_accelerate * maxSpeed * timeStep;
if ( accelSpeed > addSpeed )
{
accelSpeed = addSpeed;
}
m_velocity += accelSpeed * desiredDirection;
}
m_velocity.y -= m_gravity * timeStep;
// The probe reaches past the rest length so the spring can be stretched
float rayLength = m_pogoRestLength + m_capsule.radius;
b3Pos rayOrigin = m_position + m_capsule.center1;
b3Vec3 rayTranslation = -rayLength * b3Vec3_axisY;
b3QueryFilter pogoFilter = { 1, ~2ull, 0, "pogo" };
b3RayResult rayResult =
b3World_CastRayClosest( m_worldId, rayOrigin, rayTranslation, pogoFilter );
m_pogoOrigin = rayOrigin;
m_pogoTranslation = rayTranslation;
m_pogoPoint = rayResult.point;
// After gravity was applied, disable pogo when still moving up.
// Avoids getting pulled back to the ground when jumping.
bool suppressPogo = m_velocity.y > 0.0f;
if ( rayResult.hit == false || suppressPogo )
{
m_onGround = false;
m_pogoVelocity = 0.0f;
}
else
{
m_onGround = true;
float pogoCurrentLength = rayResult.fraction * rayLength;
float offset = pogoCurrentLength - m_pogoRestLength;
m_pogoVelocity =
b3SpringDamper( m_pogoHertz, m_pogoDampingRatio, offset, m_pogoVelocity, timeStep );
}
m_pogoHit = m_onGround;
b3Pos startPosition = m_position;
b3Pos target = m_position + timeStep * m_velocity + timeStep * m_pogoVelocity * b3Vec3_axisY;
// Want the mover to collide with allies
b3QueryFilter moverFilter = {
.categoryBits = 1, .maskBits = ~0ull, .id = 1, .name = "mover_collide" };
// The cast should ignore allies
b3QueryFilter castFilter = {
.categoryBits = 1, .maskBits = ~2ull, .id = 1, .name = "mover_cast" };
m_totalIterations = 0;
float tolerance = 0.01f;
for ( int iteration = 0; iteration < 5; ++iteration )
{
m_planeCount = 0;
b3World_CollideMover( m_worldId, m_position, &m_capsule, moverFilter, PlaneResultFcn,
this );
b3Vec3 targetDelta = target - m_position;
b3PlaneSolverResult result = b3SolvePlanes( targetDelta, m_planes, m_planeCount );
m_totalIterations += result.iterationCount;
float fraction = b3World_CastMover( m_worldId, m_position, &m_capsule, result.delta,
castFilter, MoverFilterCallback, this );
b3Vec3 delta = fraction * result.delta;
m_position = m_position + delta;
if ( b3LengthSquared( delta ) < tolerance * tolerance )
{
break;
}
}
PushBodies();
if ( m_clipVelocity )
{
// Stop pushing into surfaces so speed can't accumulate against a wall
m_velocity = b3ClipVector( m_velocity, m_planes, m_planeCount );
}
else if ( timeStep > 0.0f )
{
m_velocity = ( 1.0f / timeStep ) * ( m_position - startPosition );
}
}
void GeometricMover::Draw() const
{
if ( m_pogoHit )
{
DrawLine( m_pogoOrigin, m_pogoPoint, MakeColor( b3_colorGreen ) );
}
else
{
DrawLine( m_pogoOrigin, b3OffsetPos( m_pogoOrigin, m_pogoTranslation ),
MakeColor( b3_colorGray ) );
}
for ( int i = 0; i < m_planeCount; ++i )
{
b3Plane plane = m_planes[i].plane;
b3Pos p1 = m_position + ( plane.offset - m_capsule.radius ) * plane.normal;
b3Pos p2 = p1 + 0.1f * plane.normal;
DrawPoint( p1, 5.0f, MakeColor( b3_colorYellow ) );
DrawLine( p1, p2, MakeColor( b3_colorYellow ) );
}
DrawSolidCapsule( { m_position, b3Quat_identity }, m_capsule, MakeColor( b3_colorBlue ) );
DrawLine( m_position, m_position + m_velocity, MakeColor( b3_colorPurple ) );
}

114
samples/geometric_mover.h Normal file
View file

@ -0,0 +1,114 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/collision.h"
#include "box3d/types.h"
struct GeometricMoverDef
{
b3Pos position = {};
b3Capsule capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f };
float jumpSpeed = 5.0f;
float maxSpeed = 6.0f;
float minSpeed = 0.01f;
float stopSpeed = 1.0f;
float accelerate = 30.0f;
float friction = 4.0f;
float gravity = 15.0f;
float pogoRestLength = 0.9f;
float pogoHertz = 4.0f;
float pogoDampingRatio = 0.7f;
};
// Optional shape user data read by GeometricMover when it gathers collision planes.
// Shapes without user data are treated as rigid, fully clipping, and pushable.
struct MoverShapeUserData
{
// Distance limit on the push this surface may apply to the mover. FLT_MAX is rigid.
float maxPush;
// False keeps the velocity along this surface, which is what soft collision needs.
bool clipVelocity;
// False stops the mover from shoving this body.
bool canMoverPush;
};
// Extra data kept alongside each collision plane so the mover can push rigid bodies.
struct PlaneExtra
{
b3Pos point;
b3ShapeId shapeId;
};
// Geometric character mover. The capsule is moved by casting and by solving collision
// planes, so the game keeps full control of the motion.
//
// A pogo spring holds the capsule above the ground so it can move up steps.
class GeometricMover
{
public:
GeometricMover();
void Create( b3WorldId worldId, const GeometricMoverDef* def );
// Advance the mover. Throttle is the input along the forward and right directions on [-1, 1].
void Update( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, float speedScale );
// Jump if grounded. Returns false when airborne.
bool Jump();
void Draw() const;
static constexpr int m_planeCapacity = 8;
float m_jumpSpeed;
float m_maxSpeed;
float m_minSpeed;
float m_stopSpeed;
float m_accelerate;
// Friction in units of 1/time.
float m_friction;
// The mover is not simulated so it needs its own gravity.
float m_gravity;
float m_pogoRestLength;
float m_pogoHertz;
float m_pogoDampingRatio;
// The clipper avoids picking up velocity from soft collision depenetration. Otherwise the
// velocity comes from the position delta, which is more intuitive in some cases.
bool m_clipVelocity;
// Shapes the mover passes through. Set before calling Update.
const b3ShapeId* m_ignoreShapeIds;
int m_ignoreCount;
// The capsule is relative to the mover position.
b3Capsule m_capsule;
b3WorldId m_worldId;
b3Pos m_position;
b3Vec3 m_velocity;
float m_pogoVelocity;
bool m_onGround;
// Planes from the last solve, kept for debug drawing.
b3CollisionPlane m_planes[m_planeCapacity] = {};
PlaneExtra m_planeExtras[m_planeCapacity] = {};
int m_planeCount;
int m_totalIterations;
b3Pos m_pogoOrigin;
b3Vec3 m_pogoTranslation;
b3Pos m_pogoPoint;
bool m_pogoHit;
private:
void PushBodies();
};

View file

@ -122,6 +122,10 @@ typedef struct
bool transparentDynamic;
bool transparentKinematic;
// One body drawn with reduced alpha, such as a character the camera is close to
b3BodyId alphaBodyId;
float bodyAlpha;
// View box for compound child culling, world space, refreshed once per frame.
b3AABB viewBounds;
bool hasViewBounds;
@ -158,6 +162,8 @@ void InitAdapter( void )
s_adapter.selectedShapeId = b3_nullShapeId;
s_adapter.transparentDynamic = false;
s_adapter.transparentKinematic = false;
s_adapter.alphaBodyId = b3_nullBodyId;
s_adapter.bodyAlpha = 1.0f;
s_adapter.hasViewBounds = false;
s_adapter.lastCompoundAppended = 0;
@ -197,6 +203,8 @@ void ResetAdapterPool( void )
s_adapter.selectedShapeId = b3_nullShapeId;
s_adapter.transparentDynamic = false;
s_adapter.transparentKinematic = false;
s_adapter.alphaBodyId = b3_nullBodyId;
s_adapter.bodyAlpha = 1.0f;
s_adapter.hasViewBounds = false;
s_adapter.lastCompoundAppended = 0;
@ -239,6 +247,12 @@ void SetTransparentKinematic( bool enabled )
s_adapter.transparentKinematic = enabled;
}
void SetBodyAlpha( b3BodyId bodyId, float alpha )
{
s_adapter.alphaBodyId = bodyId;
s_adapter.bodyAlpha = alpha;
}
void SetViewBounds( b3AABB bounds )
{
s_adapter.viewBounds = bounds;
@ -862,6 +876,11 @@ static void DrawShape( void* userShape, b3WorldTransform shapeTransform, b3HexCo
c.w = BOX3D_TRANSPARENT_ALPHA;
}
if ( s_adapter.bodyAlpha < 1.0f && B3_ID_EQUALS( us->bodyId, s_adapter.alphaBodyId ) )
{
c.w = b3MinFloat( c.w, s_adapter.bodyAlpha );
}
if ( s_adapter.transparentKinematic && us->bodyType == b3_kinematicBody )
{
c.w = BOX3D_TRANSPARENT_ALPHA;

View file

@ -42,6 +42,7 @@ void SetGroundShape( b3ShapeId shapeId );
void SetShapeMaterial( b3ShapeId shapeId, Vec4 color, float metallic, float roughness );
void SetTransparentDynamic( bool enabled );
void SetTransparentKinematic( bool enabled );
void SetBodyAlpha( b3BodyId bodyId, float alpha );
// View box for compound child culling, world space. Set once per frame before
// b3World_Draw. A compound then submits only the children overlapping this box

View file

@ -16,6 +16,7 @@ enum
KEY_D = SAPP_KEYCODE_D,
KEY_F = SAPP_KEYCODE_F,
KEY_G = SAPP_KEYCODE_G,
KEY_K = SAPP_KEYCODE_K,
KEY_L = SAPP_KEYCODE_L,
KEY_M = SAPP_KEYCODE_M,
KEY_O = SAPP_KEYCODE_O,
@ -32,6 +33,9 @@ enum
KEY_ESCAPE = SAPP_KEYCODE_ESCAPE,
KEY_TAB = SAPP_KEYCODE_TAB,
KEY_LEFT_SHIFT = SAPP_KEYCODE_LEFT_SHIFT,
KEY_RIGHT_SHIFT = SAPP_KEYCODE_RIGHT_SHIFT,
KEY_LEFT_CONTROL = SAPP_KEYCODE_LEFT_CONTROL,
KEY_RIGHT_CONTROL = SAPP_KEYCODE_RIGHT_CONTROL,
KEY_LEFT_BRACKET = SAPP_KEYCODE_LEFT_BRACKET,
KEY_RIGHT_BRACKET = SAPP_KEYCODE_RIGHT_BRACKET,
KEY_PAUSE = SAPP_KEYCODE_PAUSE,

View file

@ -12,7 +12,6 @@ static constexpr float ORBIT_SENS = 0.005f; // radians per pixel
static constexpr float FLY_LOOK_SENS = 0.005f; // radians per pixel
static constexpr float PAN_SENS = 0.005f; // meters per pixel per meter of radius
static constexpr float RADIAL_ZOOM_SENS = 0.02f; // meters per pixel (alt+right-drag)
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 MIN_SPEED = 0.06f; // matches box3d's 0.001*60
@ -502,7 +501,7 @@ void Camera::Update( float dt, int width, int height )
if ( m_speedScrollAccum != 0.0f )
{
m_speed += m_speedScrollAccum * FLY_SPEED_STEP;
m_speed *= powf( 1.1f, m_speedScrollAccum );
m_speed = b3ClampFloat( m_speed, MIN_SPEED, MAX_SPEED );
}
}

View file

@ -14,6 +14,7 @@
#include "gfx/debug_adapter.h"
#include "gfx/keycodes.h"
#include "gfx/renderer.h"
#include "gfx/text.h"
#include "host/gui.h"
#include "sample.h"
#include "sokol_app.h"
@ -160,6 +161,17 @@ static void OnEvent( const sapp_event* e )
s_context.camera.OnEvent( e );
}
// Releases go to the key table even when the UI captures them. Otherwise Ctrl let go
// while the Ctrl+O picker is open stays down in the next sample.
if ( e->type == SAPP_EVENTTYPE_KEY_UP )
{
SetKeyDown( e->key_code, false );
}
else if ( e->type == SAPP_EVENTTYPE_UNFOCUSED )
{
ClearKeysDown();
}
if ( uiCaptured )
{
return;
@ -181,7 +193,18 @@ static void OnEvent( const sapp_event* e )
switch ( e->key_code )
{
case SAPP_KEYCODE_TAB:
s_context.showUI = !s_context.showUI;
if ( mods & SAPP_MODIFIER_SHIFT )
{
bool hide = s_context.showUI || s_context.showText;
s_context.showUI = !hide;
s_context.showText = !hide;
}
else
{
// Plain Tab also restores text so it always leads back to the full view
s_context.showUI = !s_context.showUI;
s_context.showText = true;
}
break;
case SAPP_KEYCODE_ESCAPE:
@ -267,10 +290,6 @@ static void OnEvent( const sapp_event* e )
}
break;
case SAPP_EVENTTYPE_KEY_UP:
SetKeyDown( e->key_code, false );
break;
case SAPP_EVENTTYPE_CHAR:
// ? toggles the controls window. Read the typed character so it works
// on any layout and a text field can still type a literal ?, since the
@ -406,6 +425,12 @@ static void OnFrame( void )
s_context.sample->Step();
s_context.sample->Render();
// Before RenderFrame so world labels drop too
if ( s_context.showText == false )
{
ResetTextArena();
}
FrameInput fi{};
fi.view = camera.View();
fi.viewInv = camera.ViewInverse();

View file

@ -1,353 +0,0 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#include "mover.h"
#include "gfx/draw.h"
#include "sample.h"
#include "box3d/box3d.h"
#include <assert.h>
#include <gfx/keycodes.h>
static bool MoverFilterCallback( b3ShapeId shapeId, void* context )
{
CharacterMover* self = (CharacterMover*)context;
for ( int i = 0; i < self->m_ignoreCount; ++i )
{
if ( B3_ID_EQUALS( shapeId, self->m_ignoreShapeIds[i] ) )
{
return false;
}
}
return true;
}
void CharacterMover::Initialize( Sample* sample, b3Pos position )
{
m_sample = sample;
m_transform.p = position;
m_transform.q = b3Quat_identity;
m_velocity = { 0.0f, 0.0f, 0.0f };
m_capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f };
m_planeCount = 0;
m_totalIterations = 0;
m_pogoVelocity = 0.0f;
m_onGround = false;
m_sprint = false;
m_ignoreShapeIds = nullptr;
m_ignoreCount = 0;
}
static bool PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* planeResults, int planeCount, void* context )
{
if ( MoverFilterCallback( shapeId, context ) == false )
{
// ignore these planes but continue looking for more
return true;
}
CharacterMover* self = static_cast<CharacterMover*>( context );
float maxPush = FLT_MAX;
bool clipVelocity = true;
MoverShapeUserData* userData = static_cast<MoverShapeUserData*>( (void*)b3Shape_GetUserData( shapeId ) );
if ( userData != nullptr )
{
maxPush = userData->maxPush;
clipVelocity = userData->clipVelocity;
}
for ( int i = 0; i < planeCount && self->m_planeCount < CharacterMover::m_planeCapacity; ++i )
{
assert( b3IsValidPlane( planeResults[i].plane ) );
self->m_planes[self->m_planeCount] = {
.plane = planeResults[i].plane,
.pushLimit = maxPush,
.push = 0.0f,
.clipVelocity = clipVelocity,
};
self->m_planeExtras[self->m_planeCount] = {
.point = b3OffsetPos( self->m_transform.p, planeResults[i].point ),
.shapeId = shapeId,
};
self->m_planeCount += 1;
}
return true;
}
void CharacterMover::SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity )
{
// Friction
float speed = b3Length( m_velocity );
if ( speed < m_minSpeed )
{
m_velocity.x = 0.0f;
m_velocity.z = 0.0f;
}
else
{
// Linear damping above stopSpeed and fixed reduction below stopSpeed
float control = speed < m_stopSpeed ? m_stopSpeed : speed;
// friction has units of 1/time
float drop = control * m_friction * timeStep;
float newSpeed = b3MaxFloat( 0.0f, speed - drop );
float ratio = newSpeed / speed;
m_velocity.x *= ratio;
m_velocity.z *= ratio;
}
float maxSpeed = m_sprint ? 1.5f * m_maxSpeed : m_maxSpeed;
b3Vec3 desiredVelocity = maxSpeed * throttle.x * forward + maxSpeed * throttle.y * right;
float desiredSpeed;
b3Vec3 desiredDirection = b3GetLengthAndNormalize( &desiredSpeed, desiredVelocity );
if ( desiredSpeed > maxSpeed )
{
desiredVelocity *= maxSpeed / desiredSpeed;
desiredSpeed = maxSpeed;
}
if ( m_onGround )
{
m_velocity.y = 0.0f;
}
// Accelerate
float currentSpeed = b3Dot( m_velocity, desiredDirection );
float addSpeed = desiredSpeed - currentSpeed;
if ( addSpeed > 0.0f )
{
float accelSpeed = m_accelerate * maxSpeed * timeStep;
if ( accelSpeed > addSpeed )
{
accelSpeed = addSpeed;
}
m_velocity += accelSpeed * desiredDirection;
}
m_velocity.y -= m_gravity * timeStep;
b3WorldId worldId = m_sample->m_worldId;
float pogoRestLength = 3.0f * m_capsule.radius;
float rayLength = pogoRestLength + m_capsule.radius;
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 );
// After gravity was applied, disable pogo when still moving up.
// Avoids getting pulled back to the ground when jumping.
bool suppressPogo = m_velocity.y > 0.0f;
if ( rayResult.hit == false || suppressPogo )
{
m_onGround = false;
m_pogoVelocity = 0.0f;
DrawLine( rayOrigin, b3OffsetPos( rayOrigin, rayTranslation ), MakeColor( b3_colorGray ) );
}
else
{
m_onGround = true;
float pogoCurrentLength = rayResult.fraction * rayLength;
float zeta = 0.7f;
float hertz = 4.0f;
float omega = 2.0f * B3_PI * hertz;
float omegaH = omega * timeStep;
m_pogoVelocity = ( m_pogoVelocity - omega * omegaH * ( pogoCurrentLength - pogoRestLength ) ) /
( 1.0f + 2.0f * zeta * omegaH + omegaH * omegaH );
DrawLine( rayOrigin, rayResult.point, MakeColor( b3_colorGreen ) );
}
b3Pos startPosition = m_transform.p;
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, .id = 1, .name = "mover_collide" };
// The cast should ignore allies
b3QueryFilter castFilter = { .categoryBits = 1, .maskBits = ~2u, .id = 1, .name = "mover_cast" };
m_totalIterations = 0;
float tolerance = 0.01f;
for ( int iteration = 0; iteration < 5; ++iteration )
{
m_planeCount = 0;
b3Capsule mover;
mover.center1 = m_capsule.center1;
mover.center2 = m_capsule.center2;
mover.radius = m_capsule.radius;
b3World_CollideMover( worldId, m_transform.p, &mover, moverFilter, PlaneResultFcn, this );
b3Vec3 targetDelta = target - m_transform.p;
b3PlaneSolverResult result = b3SolvePlanes( targetDelta, m_planes, m_planeCount );
m_totalIterations += result.iterationCount;
b3Vec3 delta = result.delta;
float fraction = b3World_CastMover( worldId, m_transform.p, &mover, delta, castFilter, MoverFilterCallback, this );
delta *= fraction;
m_transform.p = m_transform.p + delta;
if ( b3LengthSquared( delta ) < tolerance * tolerance )
{
break;
}
}
for ( int i = 0; i < m_planeCount; ++i )
{
b3BodyId bodyId = b3Shape_GetBody( m_planeExtras[i].shapeId );
b3BodyType bodyType = b3Body_GetType( bodyId );
if ( bodyType != b3_dynamicBody )
{
continue;
}
MoverShapeUserData* userData = static_cast<MoverShapeUserData*>( b3Shape_GetUserData( m_planeExtras[i].shapeId ) );
if ( userData != nullptr && userData->canMoverPush == false )
{
continue;
}
b3Pos point = m_planeExtras[i].point;
b3Vec3 normal = b3Neg( m_planes[i].plane.normal );
float invMassA = 0.0f;
float invMassB = b3Body_GetInverseMass( bodyId );
b3Matrix3 invIB = b3Body_GetWorldInverseRotationalInertia( bodyId );
b3Pos pB = b3Body_GetWorldCenter( bodyId );
b3Vec3 rB = b3SubPos( point, pB );
b3Vec3 rnB = b3Cross( rB, normal );
float kNormal = invMassA + invMassB + b3Dot( rnB, b3MulMV( invIB, rnB ) );
float normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
b3Vec3 vB = b3Body_GetLinearVelocity( bodyId );
b3Vec3 omegaB = b3Body_GetAngularVelocity( bodyId );
b3Vec3 vrB = b3Add( vB, b3Cross( omegaB, rB ) );
float vn = b3Dot( b3Sub( vrB, m_velocity ), normal );
float impulse = b3MaxFloat( -normalMass * vn, 0.0f );
b3Vec3 P = b3MulSV( impulse, normal );
m_velocity = b3MulSub( m_velocity, invMassA, P );
b3Body_ApplyLinearImpulse( bodyId, P, point, true );
}
if ( clipVelocity )
{
// Using the velocity clipper can avoid picking up velocity from depenetration.
// This allows the mover to avoid velocity from soft collision depenetration.
m_velocity = b3ClipVector( m_velocity, m_planes, m_planeCount );
}
else if ( timeStep > 0.0f )
{
// Using the position delta is more holistic and intuitive in some cases.
m_velocity = ( 1.0f / timeStep ) * ( m_transform.p - startPosition );
}
}
void CharacterMover::Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity )
{
m_ignoreShapeIds = ignoreShapes;
m_ignoreCount = ignoreCount;
b3Vec2 throttle = { 0.0f, 0.0f };
b3Vec3 forward = -m_sample->m_camera->GetForward();
b3Vec3 right = m_sample->m_camera->GetRight();
forward.y = 0.0f;
forward = b3Normalize( forward );
if ( m_sample->m_camera->m_thirdPerson )
{
if ( IsKeyDown( KEY_W ) )
{
throttle.x += 1.0f;
}
if ( IsKeyDown( KEY_S ) )
{
throttle.x -= 1.0f;
}
if ( IsKeyDown( KEY_A ) )
{
throttle.y -= 1.0f;
}
if ( IsKeyDown( KEY_D ) )
{
throttle.y += 1.0f;
}
if ( IsKeyDown( KEY_SPACE ) && m_onGround == true )
{
m_velocity.y = m_jumpSpeed;
m_onGround = false;
}
if ( m_onGround == true )
{
m_sprint = IsKeyDown( KEY_LEFT_SHIFT );
}
else
{
m_sprint = false;
}
}
float hertz = m_sample->m_context->hertz;
float timeStep = hertz > 0.0f ? 1.0f / hertz : 0.0f;
// throttle = { 0.0f, 0.0f, -1.0f };
SolveMove( timeStep, forward, right, throttle, clipVelocity );
b3Pos position = m_transform.p;
// Follow the mover and latch the draw origin before drawing, so the overlays below demote
// against the same eye the view renders from.
if ( m_sample->m_camera->m_thirdPerson )
{
m_sample->m_camera->m_pivot = position;
m_sample->m_camera->UpdateTransform();
}
SetDrawOrigin( m_sample->m_camera->DrawOrigin() );
int count = m_planeCount;
for ( int i = 0; i < count; ++i )
{
b3Plane plane = m_planes[i].plane;
b3Pos p1 = position + ( plane.offset - m_capsule.radius ) * plane.normal;
b3Pos p2 = p1 + 0.1f * plane.normal;
DrawPoint( p1, 5.0f, MakeColor( b3_colorYellow ) );
DrawLine( p1, p2, MakeColor( b3_colorYellow ) );
}
DrawSolidCapsule( m_transform, m_capsule, MakeColor( b3_colorBlue ) );
DrawLine( position, position + m_velocity, MakeColor( b3_colorPurple ) );
m_ignoreShapeIds = nullptr;
m_ignoreCount = 0;
}

View file

@ -1,53 +0,0 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/types.h"
class Sample;
struct MoverShapeUserData
{
float maxPush;
bool clipVelocity;
bool canMoverPush;
};
struct PlaneExtra
{
b3Pos point;
b3ShapeId shapeId;
};
struct CharacterMover
{
static constexpr int m_planeCapacity = 8;
static constexpr float m_jumpSpeed = 5.0f;
static constexpr float m_maxSpeed = 6.0f;
static constexpr float m_minSpeed = 0.01f;
static constexpr float m_stopSpeed = 1.0f;
static constexpr float m_accelerate = 30.0f;
static constexpr float m_friction = 4.0f;
static constexpr float m_gravity = 15.0f;
void Initialize( Sample* sample, b3Pos position );
void SolveMove( float timeStep, b3Vec3 forward, b3Vec3 right, b3Vec2 throttle, bool clipVelocity );
void Step( b3ShapeId* ignoreShapes, int ignoreCount, bool clipVelocity );
Sample* m_sample;
b3WorldTransform m_transform;
b3Vec3 m_velocity;
b3Capsule m_capsule;
b3CollisionPlane m_planes[m_planeCapacity] = {};
PlaneExtra m_planeExtras[m_planeCapacity] = {};
int m_planeCount;
int m_totalIterations;
float m_pogoVelocity;
bool m_onGround;
bool m_sprint;
// Transient
b3ShapeId* m_ignoreShapeIds;
int m_ignoreCount;
};

View file

@ -97,6 +97,11 @@ void SetKeyDown( int key, bool down )
}
}
void ClearKeysDown()
{
memset( s_keyDown, 0, sizeof( s_keyDown ) );
}
void SampleContext::Save()
{
const b3DebugDraw* gd = GetGuiDraw();
@ -1789,6 +1794,11 @@ static void DrawMenuBar( SampleContext* context )
{
context->showUI = false;
}
if ( ImGui::MenuItem( "Hide UI and Text", "Shift+Tab" ) )
{
context->showUI = false;
context->showText = false;
}
if ( ImGui::MenuItem( "Frame Selection", "F" ) )
{
FrameSelection( context );
@ -1921,6 +1931,7 @@ static void DrawMenuBar( SampleContext* context )
if ( ImGui::BeginTable( "keys", 2, ImGuiTableFlags_SizingFixedFit ) )
{
DrawRow( "Tab", "Show / hide UI" );
DrawRow( "Shift+Tab", "Show / hide UI and text" );
DrawRow( "M", "Show / hide metrics" );
DrawRow( "I", "Show / hide profile" );
DrawRow( "P", "Pause / resume" );
@ -2261,7 +2272,7 @@ static void DrawHud( SampleContext* context )
const SampleEntry& entry = g_sampleEntries[context->sampleIndex];
float fontSize = ImGui::GetFontSize();
DrawScreenStringFormat( 5, (int)( 1.5f * fontSize ), MakeColor( b3_colorYellow ), "%s : %s", entry.Category, entry.Name );
DrawScreenStringFormat( 5, (int)( 0.5f * fontSize ), MakeColor( b3_colorYellow ), "%s : %s", entry.Category, entry.Name );
if ( context->pause )
{
@ -2277,7 +2288,10 @@ void DrawUI( SampleContext* context )
// Hidden shows only the minimal in-world HUD.
if ( context->showUI == false )
{
DrawHud( context );
if ( context->showText )
{
DrawHud( context );
}
return;
}
@ -2308,6 +2322,46 @@ void Sample::ToggleThirdPerson()
}
}
MoverInput Sample::GetMoverInput() const
{
MoverInput input = {};
input.forward = -m_camera->GetForward();
input.right = m_camera->GetRight();
input.forward.y = 0.0f;
input.forward = b3Normalize( input.forward );
if ( m_camera->m_thirdPerson == false )
{
return input;
}
if ( IsKeyDown( KEY_W ) )
{
input.throttle.x += 1.0f;
}
if ( IsKeyDown( KEY_S ) )
{
input.throttle.x -= 1.0f;
}
if ( IsKeyDown( KEY_A ) )
{
input.throttle.y -= 1.0f;
}
if ( IsKeyDown( KEY_D ) )
{
input.throttle.y += 1.0f;
}
input.jump = IsKeyDown( KEY_SPACE );
input.sprint = IsKeyDown( KEY_LEFT_SHIFT ) || IsKeyDown( KEY_RIGHT_SHIFT );
input.walk = IsKeyDown( KEY_LEFT_CONTROL ) || IsKeyDown( KEY_RIGHT_CONTROL );
return input;
}
float CastClosestCallback( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t materialId, int triangleIndex,
int childIndex, void* context )
{

View file

@ -11,6 +11,7 @@
// Fed from the host event loop; read with the KEY_* aliases in gfx/keycodes.h.
bool IsKeyDown( int key );
void SetKeyDown( int key, bool down );
void ClearKeysDown();
// Key action passed to Keyboard, matching the old GLFW press/release values so
// sample code reads naturally without leaking sokol_app event types.
@ -20,6 +21,17 @@ enum
ACTION_PRESS = 1,
};
// Character input relative to the camera. Throttle x is forward and y is right.
struct MoverInput
{
b3Vec3 forward;
b3Vec3 right;
b3Vec2 throttle;
bool jump;
bool sprint;
bool walk;
};
struct SampleContext
{
void Save();
@ -85,6 +97,9 @@ struct SampleContext
// UI visibility (Tab / View > Hide UI). When hidden only the minimal HUD shows.
bool showUI = true;
// Viewport text: HUD, sample text lines and world labels.
bool showText = true;
// Bottom metrics drawer (M), set by Ctrl+O for the fuzzy picker.
bool showMetrics = false;
bool openSamplePicker = false;
@ -211,6 +226,9 @@ public:
void ToggleThirdPerson();
// WASD, space, shift and ctrl, active only in third person so the free camera keeps its keys.
MoverInput GetMoverInput() const;
B3_PRINTF_FORMAT( 2, 3 )
void DrawTextLine( const char* text, ... );
void ResetProfile();

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "geometric_mover.h"
#include "gfx/debug_adapter.h"
#include "gfx/draw.h"
#include "human.h"
#include "mesh_loader.h"
#include "mover.h"
#include "sample.h"
#include "utils.h"
@ -13,6 +13,8 @@
#include <imgui.h>
#include <vector>
class SimpleCompound : public Sample
{
public:
@ -484,6 +486,39 @@ static bool OverlapResultFcn( b3ShapeId shapeId, void* context )
return false;
}
struct VillageBoxQuery
{
b3AABB aabb;
int shapeCount;
int childCount;
};
static bool CountCompoundChildFcn( const b3CompoundData* compound, int childIndex, void* context )
{
(void)compound;
(void)childIndex;
int* count = (int*)context;
*count += 1;
return true;
}
// The world query only reaches the compound as a whole, so descend into its children like a game would
static bool VillageBoxQueryFcn( b3ShapeId shapeId, void* context )
{
VillageBoxQuery* query = (VillageBoxQuery*)context;
query->shapeCount += 1;
if ( b3Shape_GetType( shapeId ) == b3_compoundShape )
{
b3WorldTransform bodyTransform = b3Body_GetTransform( b3Shape_GetBody( shapeId ) );
b3Transform worldToLocal = b3InvMulWorldTransforms( bodyTransform, b3WorldTransform_identity );
b3AABB localBox = b3AABB_Transform( worldToLocal, query->aabb );
b3QueryCompound( b3Shape_GetCompound( shapeId ), localBox, CountCompoundChildFcn, &query->childCount );
}
return true;
}
class Village : public Sample
{
public:
@ -501,7 +536,9 @@ public:
}
m_launchSpeedScale = 2.0f;
m_mover.Initialize( this, position );
GeometricMoverDef moverDef;
moverDef.position = position;
m_mover.Create( m_worldId, &moverDef );
{
constexpr int capsuleCapacity = gridCount * gridCount / 8 + 1;
@ -689,6 +726,80 @@ public:
}
}
// Fixed seed so timings compare across runs and builds
void CreateStressQueries()
{
uint32_t savedSeed = g_randomSeed;
g_randomSeed = 271828;
float h = 0.45f * m_worldWidth;
m_stressRays.resize( m_stressRayCount );
for ( StressRay& ray : m_stressRays )
{
ray.origin = { RandomFloatRange( -h, h ), 20.0f, RandomFloatRange( -h, h ) };
ray.translation = { RandomFloatRange( -10.0f, 10.0f ), -40.0f, RandomFloatRange( -10.0f, 10.0f ) };
}
m_stressBoxes.resize( m_stressBoxCount );
for ( b3AABB& box : m_stressBoxes )
{
b3Vec3 center = { RandomFloatRange( -h, h ), RandomFloatRange( 0.0f, 8.0f ), RandomFloatRange( -h, h ) };
b3Vec3 extents = RandomVec3( { 0.5f, 0.5f, 0.5f }, { 4.0f, 4.0f, 4.0f } );
box = { center - extents, center + extents };
}
g_randomSeed = savedSeed;
}
void RunStressQueries()
{
b3QueryFilter filter = b3DefaultQueryFilter();
uint64_t ticks = b3GetTicks();
int rayHitCount = 0;
for ( const StressRay& ray : m_stressRays )
{
CastClosestContext context = {};
(void)b3World_CastRay( m_worldId, ray.origin, ray.translation, filter, CastClosestCallback, &context );
rayHitCount += context.hit ? 1 : 0;
}
float rayTime = b3GetMillisecondsAndReset( &ticks );
VillageBoxQuery query = {};
for ( b3AABB box : m_stressBoxes )
{
query.aabb = box;
(void)b3World_OverlapAABB( m_worldId, box, filter, VillageBoxQueryFcn, &query );
}
float boxTime = b3GetMilliseconds( ticks );
int rayCount = (int)m_stressRays.size();
int boxCount = (int)m_stressBoxes.size();
DrawTextLine( "rays = %d, hits = %d", rayCount, rayHitCount );
DrawTextLine( "ray time = %.3f ms, ave = %.3f us", rayTime, 1000.0f * rayTime / rayCount );
DrawTextLine( "aabb queries = %d, shapes = %d, children = %d", boxCount, query.shapeCount, query.childCount );
DrawTextLine( "aabb time = %.3f ms, ave = %.3f us", boxTime, 1000.0f * boxTime / boxCount );
}
bool DrawControls() override
{
bool changed = ImGui::Checkbox( "Query Stress", &m_stressQueries );
changed = ImGui::SliderInt( "Rays", &m_stressRayCount, 1, 100000 ) || changed;
changed = ImGui::SliderInt( "AABB Queries", &m_stressBoxCount, 1, 100000 ) || changed;
if ( changed && m_stressQueries )
{
CreateStressQueries();
}
return true;
}
void Render() override
{
Sample::Render();
@ -711,9 +822,40 @@ public:
void Step() override
{
m_mover.Step( nullptr, 0, true );
MoverInput input = GetMoverInput();
if ( input.jump )
{
m_mover.Jump();
}
float speedScale = 1.0f;
if ( input.walk )
{
speedScale = 0.25f;
}
else if ( m_mover.m_onGround && input.sprint )
{
speedScale = 1.5f;
}
float moverTimeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f;
m_mover.Update( moverTimeStep, input.forward, input.right, input.throttle, speedScale );
if ( m_camera->m_thirdPerson )
{
m_camera->m_pivot = m_mover.m_position;
m_camera->UpdateTransform();
}
SetDrawOrigin( m_camera->DrawOrigin() );
m_mover.Draw();
DrawTextLine( "third person (T) = %d", m_camera->m_thirdPerson );
if ( m_stressQueries )
{
RunStressQueries();
}
b3Vec3 translation = { 10.0f, -40.0f, -5.0f };
b3QueryFilter filter = b3DefaultQueryFilter();
@ -800,10 +942,22 @@ public:
return new Village( context );
}
struct StressRay
{
b3Pos origin;
b3Vec3 translation;
};
b3CompoundData* m_compound;
CharacterMover m_mover;
GeometricMover m_mover;
float m_worldWidth;
b3Pos m_rayOrigin;
std::vector<StressRay> m_stressRays;
std::vector<b3AABB> m_stressBoxes;
int m_stressRayCount = 1000;
int m_stressBoxCount = 1000;
bool m_stressQueries = false;
};
static int sampleVillage = RegisterSample( "Compound", "Village", Village::Create );

View file

@ -1722,13 +1722,17 @@ public:
b3Vec3 axis = b3Normalize( b3Cross( u, v ) );
b3Vec3 w = b3Cross( axis, u );
constexpr int segmentCount = 96;
b3CosSin cs = b3ComputeCosSin( 2.0f * B3_PI / segmentCount );
float x1 = 1.0f, y1 = 0.0f;
b3Pos previous = GaussPoint( u );
for ( int i = 1; i <= segmentCount; ++i )
for ( int i = 0; i < segmentCount; ++i )
{
float angle = 2.0f * B3_PI * i / segmentCount;
b3CosSin cs = b3ComputeCosSin( angle );
b3Pos point = GaussPoint( b3Add( b3MulSV( cs.cosine, u ), b3MulSV( cs.sine, w ) ) );
float x2 = cs.cosine * x1 - cs.sine * y1;
float y2 = cs.sine * x1 + cs.cosine * y1;
b3Pos point = GaussPoint( b3Add( b3MulSV( x2, u ), b3MulSV( y2, w ) ) );
DrawLineEx( previous, point, color, 1.0f, OVERLAY_THICKNESS_PIXELS, OVERLAY_OCCLUSION_DASHED );
x1 = x2;
y1 = y2;
previous = point;
}
}

View file

@ -94,6 +94,10 @@ static const char* ReplayJointTypeName( b3JointType type )
return "weld";
case b3_wheelJoint:
return "wheel";
case b3_moverJoint:
return "mover";
case b3_pogoJoint:
return "pogo";
default:
return "?";
}