dynamic mover

This commit is contained in:
Erin Catto 2026-10-20 23:33:18 -07:00
commit f0b1ed2fca
29 changed files with 3078 additions and 432 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

505
samples/dynamic_mover.cpp Normal file
View file

@ -0,0 +1,505 @@
// 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_moverJointId = b3_nullJointId;
m_pogoJointId = b3_nullJointId;
m_castResult = {};
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;
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.filter = def->filter;
shapeDef.enablePreSolveEvents = def->enablePreSolveEvents;
shapeDef.enableSensorEvents = def->enableSensorEvents;
b3CreateCapsuleShape( m_moverId, &shapeDef, &m_capsule );
CreateMoverJoint( m_groundId, { m_maxGroundForce, 0.0f, m_maxGroundForce } );
}
void DynamicMover::CreateMoverJoint( b3BodyId baseId, b3Vec3 maxForce )
{
b3MoverJointDef moverDef = b3DefaultMoverJointDef();
moverDef.linearVelocity = m_velocity;
moverDef.maxVelocityForce = maxForce;
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 )
{
// The cast can still hit while jumping.
m_onGround = m_jumping == false;
// Is the ground too steep to walk?
m_walkable = m_castResult.normal.y >= m_minGroundNormalY;
}
else
{
m_onGround = false;
m_walkable = false;
}
// 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;
}
if ( B3_ID_EQUALS( b3Joint_GetBodyA( m_moverJointId ), baseId ) == false )
{
b3Vec3 maxForce = b3MoverJoint_GetMaxVelocityForce( m_moverJointId );
b3DestroyJoint( m_moverJointId, false );
CreateMoverJoint( baseId, maxForce );
}
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 )
{
maxForce = m_walkable ? m_maxGroundForce : 0.0f;
}
else
{
maxForce = m_maxAirForce;
}
b3MoverJoint_SetMaxVelocityForce( m_moverJointId, { maxForce, 0.0f, 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;
}
// The pogo joint is rebuilt every update because it may land on a different body
if ( b3Joint_IsValid( m_pogoJointId ) )
{
m_pogoLength = b3PogoJoint_GetCurrentLength( m_pogoJointId );
m_pogoImpulse = b3PogoJoint_GetImpulse( m_pogoJointId );
m_pogoVelocity = b3PogoJoint_GetCurrentSpeed( m_pogoJointId );
b3DestroyJoint( m_pogoJointId, false );
m_pogoJointId = b3_nullJointId;
}
if ( m_castResult.hit == true )
{
float moverMass = b3Body_GetMass( m_moverId );
float moverWeight =
m_gravityScale * b3Length( b3World_GetGravity( m_worldId ) ) * moverMass;
b3PogoJointDef pogoDef = b3DefaultPogoJointDef();
pogoDef.base.localFrameA.p =
b3Body_GetLocalPoint( m_castResult.bodyId, m_castResult.point );
pogoDef.base.localFrameB.p = m_capsule.center1 + pogoOffset;
pogoDef.normal = m_castResult.normal;
pogoDef.base.bodyIdA = m_castResult.bodyId;
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
{
m_pogoImpulse = 0.0f;
m_pogoVelocity = 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 ) );
}
b3Pos position = b3Body_GetPosition( m_moverId );
b3HexColor color = m_onGround ? b3_colorOrange : b3_colorAquamarine;
DrawLine( position, position + m_velocity, MakeColor( color ) );
}

161
samples/dynamic_mover.h Normal file
View file

@ -0,0 +1,161 @@
// SPDX-FileCopyrightText: 2026 Erin Catto
// SPDX-License-Identifier: MIT
#pragma once
#include "box3d/collision.h"
#include "box3d/types.h"
struct DynamicMoverDef
{
b3Pos position = {};
b3Capsule capsule = { { 0.0f, -0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, 0.3f };
// About 80 kilograms for the default capsule
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.5f;
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 );
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;
b3JointId m_moverJointId;
b3JointId m_pogoJointId;
DynamicMoverCastResult m_castResult;
b3Vec3 m_velocity;
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, b3Vec3 maxForce );
};

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, ~2u, 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 = ~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;
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

@ -32,6 +32,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

@ -160,6 +160,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;
@ -267,10 +278,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

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();
@ -2308,6 +2313,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();
@ -211,6 +223,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();

View file

@ -1,10 +1,11 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "dynamic_mover.h"
#include "geometric_mover.h"
#include "gfx/draw.h"
#include "gfx/keycodes.h"
#include "mesh_loader.h"
#include "mover.h"
#include "sample.h"
#include "box3d/box3d.h"
@ -321,10 +322,10 @@ struct MoverImpact
bool valid;
};
class GeometricMover : public Sample
class GeometricMoverSample : public Sample
{
public:
explicit GeometricMover( SampleContext* context )
explicit GeometricMoverSample( SampleContext* context )
: Sample( context )
{
b3Pos moverPosition = { 7.5f, 0.75f, 9.0f };
@ -334,7 +335,11 @@ public:
m_camera->SetView( 120.0f, 30.0f, 5.0f, moverPosition );
}
m_mover.Initialize( this, moverPosition );
GeometricMoverDef moverDef;
moverDef.position = moverPosition;
m_mover.Create( m_worldId, &moverDef );
m_mover.m_ignoreShapeIds = &m_ignoreShapeId;
m_mover.m_ignoreCount = 1;
{
m_levelMesh = CreateMeshData( "data/meshes/test_map01.obj", 1.0f, false, false, true, true );
@ -557,7 +562,6 @@ public:
//}
m_camera->m_thirdPerson = false;
m_clipVelocity = true;
// sapp_lock_mouse( true );
// m_haveMouseLast = false;
@ -565,7 +569,7 @@ public:
// m_mouseDelta = { 0.0f, 0.0f };
}
~GeometricMover() override
~GeometricMoverSample() override
{
m_camera->m_thirdPerson = false;
sapp_lock_mouse( false );
@ -589,7 +593,7 @@ public:
ToggleThirdPerson();
}
ImGui::Checkbox( "Clip Velocity", &m_clipVelocity );
ImGui::Checkbox( "Clip Velocity", &m_mover.m_clipVelocity );
return true;
}
@ -691,7 +695,7 @@ public:
void UpdateFallingTree( b3Pos moverStart, b3WorldTransform treeStart )
{
b3WorldTransform treeEnd = b3Body_GetTransform( m_treeId );
b3Vec3 moverTranslation = b3SubPos( m_mover.m_transform.p, moverStart );
b3Vec3 moverTranslation = b3SubPos( m_mover.m_position, moverStart );
b3BodyTOIResult toi = b3Body_TimeOfImpactMover( m_treeId, moverStart, &m_mover.m_capsule, moverTranslation,
b3DefaultQueryFilter(), treeStart, treeEnd );
@ -712,7 +716,7 @@ public:
void UpdateFallingBox( b3Pos moverStart, b3WorldTransform boxStart )
{
b3WorldTransform boxEnd = b3Body_GetTransform( m_fallingBoxId );
b3Vec3 moverTranslation = b3SubPos( m_mover.m_transform.p, moverStart );
b3Vec3 moverTranslation = b3SubPos( m_mover.m_position, moverStart );
b3BodyTOIResult toi = b3Body_TimeOfImpactMover( m_fallingBoxId, moverStart, &m_mover.m_capsule, moverTranslation,
b3DefaultQueryFilter(), boxStart, boxEnd );
@ -742,11 +746,37 @@ public:
void Step() override
{
b3Pos moverStart = m_mover.m_transform.p;
b3Pos moverStart = m_mover.m_position;
b3WorldTransform boxStart = b3Body_GetTransform( m_fallingBoxId );
b3WorldTransform treeStart = b3Body_GetTransform( m_treeId );
m_mover.Step( &m_ignoreShapeId, 1, m_clipVelocity );
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 timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f;
m_mover.Update( timeStep, 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 );
DrawTextLine( "deltaX = %g, deltaY = %g", m_mouseDelta.x, m_mouseDelta.y );
@ -769,10 +799,10 @@ public:
static Sample* Create( SampleContext* context )
{
return new GeometricMover( context );
return new GeometricMoverSample( context );
}
CharacterMover m_mover;
GeometricMover m_mover;
MoverShapeUserData m_enemyShape;
MoverShapeUserData m_friendlyShape;
MoverShapeUserData m_treeShapeUserData;
@ -793,10 +823,751 @@ public:
b3Vec3 m_fallingExtent;
b3Vec3 m_fallingSpin;
float m_respawnTimer;
bool m_clipVelocity;
};
static int sampleMover = RegisterSample( "Character", "Geometric Mover", GeometricMover::Create );
static int sampleMover =
RegisterSample( "Character", "Geometric Mover", GeometricMoverSample::Create );
// A playground for the dynamic mover. Collect every gem to finish a lap. The course has stairs, a
// rope bridge, an elevator and a shuttle to a high route, a seesaw, crates to shove, a sweeper arm
// to jump over, and a row of thin pillars that only the skirt probes can stand on.
class DynamicMoverSample : public Sample
{
public:
explicit DynamicMoverSample( SampleContext* context )
: Sample( context )
{
b3Pos startPosition = { 0.0f, 1.5f, 0.0f };
if ( m_context->restart == false )
{
m_camera->SetView( 180.0f, 20.0f, 6.0f, startPosition );
}
b3BodyId groundId = AddGroundBox( 80.0f );
{
DynamicMoverDef def;
def.position = startPosition;
def.filter = { MoverBit, AllBits, 0 };
def.platformMaterialId = m_platformMaterial;
def.enableSensorEvents = true;
m_mover.Create( m_worldId, &def );
}
b3ShapeDef shapeDef = b3DefaultShapeDef();
// Stairs up to the bridge
{
b3BodyDef bodyDef = b3DefaultBodyDef();
b3BodyId stairsId = b3CreateBody( m_worldId, &bodyDef );
shapeDef.baseMaterial.customColor = b3_colorCornflowerBlue;
for ( int i = 0; i < 10; ++i )
{
float halfHeight = 0.1f * ( i + 1 );
b3Transform transform = { { -6.0f, halfHeight, 3.3f + 0.6f * i }, b3Quat_identity };
b3BoxHull box = b3MakeTransformedBoxHull( 1.5f, halfHeight, 0.3f, transform );
b3CreateHullShape( stairsId, &shapeDef, &box.base );
}
}
// Towers at each end of the bridge
b3BodyId towerIds[2];
for ( int i = 0; i < 2; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { i == 0 ? -6.0f : 6.0f, 1.0f, 11.0f };
towerIds[i] = b3CreateBody( m_worldId, &bodyDef );
shapeDef.baseMaterial.customColor = b3_colorSlateGray;
b3BoxHull box = b3MakeBoxHull( 1.5f, 1.0f, 2.0f );
b3CreateHullShape( towerIds[i], &shapeDef, &box.base );
}
// The pogo presses down on the planks, so the bridge sags and sways underfoot
{
int plankCount = 18;
float plankLength = 9.0f / plankCount;
float xBase = -4.5f;
float y = 1.95f;
float z = 11.0f;
b3ShapeDef plankShapeDef = b3DefaultShapeDef();
plankShapeDef.density = 300.0f;
plankShapeDef.baseMaterial.customColor = b3_colorBurlywood;
b3BoxHull plank = b3MakeBoxHull( 0.5f * plankLength - 0.01f, 0.05f, 0.75f );
// The hinge is the local z-axis, across the bridge
b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef();
jointDef.enableMotor = true;
jointDef.maxMotorTorque = 50.0f;
b3BodyId prevId = towerIds[0];
for ( int i = 0; i < plankCount; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { xBase + plankLength * ( i + 0.5f ), y, z };
bodyDef.angularDamping = 0.5f;
b3BodyId plankId = b3CreateBody( m_worldId, &bodyDef );
b3CreateHullShape( plankId, &plankShapeDef, &plank.base );
b3Pos pivot = { xBase + plankLength * i, y, z };
jointDef.base.bodyIdA = prevId;
jointDef.base.bodyIdB = plankId;
jointDef.base.localFrameA.p = b3Body_GetLocalPoint( prevId, pivot );
jointDef.base.localFrameB.p = b3Body_GetLocalPoint( plankId, pivot );
b3CreateRevoluteJoint( m_worldId, &jointDef );
prevId = plankId;
}
b3Pos pivot = { xBase + plankLength * plankCount, y, z };
jointDef.base.bodyIdA = prevId;
jointDef.base.bodyIdB = towerIds[1];
jointDef.base.localFrameA.p = b3Body_GetLocalPoint( prevId, pivot );
jointDef.base.localFrameB.p = b3Body_GetLocalPoint( towerIds[1], pivot );
b3CreateRevoluteJoint( m_worldId, &jointDef );
}
// Ramps from the east tower down to the ground, one walkable and one too steep
AddRamp( { 6.0f, 2.0f, 9.0f }, { 6.0f, 0.0f, 3.5f }, 1.5f, b3_colorOliveDrab );
AddRamp( { 12.0f, 3.0f, -12.0f }, { 12.0f, 0.0f, -9.5f }, 3.5f, b3_colorIndianRed );
// High route: an elevator up to a ledge, then a shuttle across to a second ledge
for ( int i = 0; i < 2; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { i == 0 ? 18.0f : 32.0f, 2.0f, 0.0f };
b3BodyId ledgeId = b3CreateBody( m_worldId, &bodyDef );
shapeDef.baseMaterial.customColor = b3_colorDarkSlateGray;
b3BoxHull box = b3MakeBoxHull( 2.0f, 2.0f, 2.0f );
b3CreateHullShape( ledgeId, &shapeDef, &box.base );
}
for ( int i = 0; i < m_platformCount; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_kinematicBody;
bodyDef.position = GetPlatformPosition( i, 0.0f );
m_platformIds[i] = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef platformShapeDef = b3DefaultShapeDef();
platformShapeDef.baseMaterial.userMaterialId = m_platformMaterial;
platformShapeDef.baseMaterial.customColor = b3_colorGoldenRod;
b3BoxHull box = b3MakeBoxHull( 1.5f, 0.1f, 1.5f );
b3CreateHullShape( m_platformIds[i], &platformShapeDef, &box.base );
}
// Seesaw
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { -14.0f, 0.4f, 0.0f };
b3BodyId fulcrumId = b3CreateBody( m_worldId, &bodyDef );
shapeDef.baseMaterial.customColor = b3_colorSlateGray;
b3BoxHull fulcrum = b3MakeBoxHull( 0.25f, 0.4f, 0.75f );
b3CreateHullShape( fulcrumId, &shapeDef, &fulcrum.base );
bodyDef.type = b3_dynamicBody;
bodyDef.position = { -14.0f, 0.9f, 0.0f };
b3BodyId plankId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef plankShapeDef = b3DefaultShapeDef();
plankShapeDef.density = 200.0f;
plankShapeDef.baseMaterial.customColor = b3_colorBurlywood;
b3BoxHull plank = b3MakeBoxHull( 3.5f, 0.1f, 0.8f );
b3CreateHullShape( plankId, &plankShapeDef, &plank.base );
b3Pos pivot = { -14.0f, 0.8f, 0.0f };
b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef();
jointDef.base.bodyIdA = fulcrumId;
jointDef.base.bodyIdB = plankId;
jointDef.base.localFrameA.p = b3Body_GetLocalPoint( fulcrumId, pivot );
jointDef.base.localFrameB.p = b3Body_GetLocalPoint( plankId, pivot );
jointDef.enableLimit = true;
jointDef.lowerAngle = -0.3f;
jointDef.upperAngle = 0.3f;
b3CreateRevoluteJoint( m_worldId, &jointDef );
}
// Large pyramid past the seesaw, standing in the yz plane
{
int baseCount = m_isDebug ? 20 : 100;
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3ShapeDef boxShapeDef = b3DefaultShapeDef();
boxShapeDef.density = 50.0f;
float h = 0.25f;
b3BoxHull box = b3MakeCubeHull( h );
for ( int i = 0; i < baseCount; ++i )
{
float y = ( 2.0f * i + 1.0f ) * h;
for ( int j = i; j < baseCount; ++j )
{
float z = ( i + 1.0f ) * h + 2.0f * ( j - i ) * h - h * baseCount;
bodyDef.position = { -50.0f, y, z };
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
b3CreateHullShape( bodyId, &boxShapeDef, &box.base );
}
}
}
// Crates to shove around
{
b3ShapeDef crateShapeDef = b3DefaultShapeDef();
crateShapeDef.density = 100.0f;
crateShapeDef.baseMaterial.friction = 0.6f;
crateShapeDef.baseMaterial.customColor = b3_colorPeru;
b3BoxHull crate = b3MakeCubeHull( 0.4f );
for ( int row = 0; row < 4; ++row )
{
for ( int i = 0; i < 4 - row; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { -10.0f + 0.82f * ( i - 0.5f * ( 3 - row ) ),
0.4f + 0.8f * row, -8.0f };
b3BodyId crateId = b3CreateBody( m_worldId, &bodyDef );
b3CreateHullShape( crateId, &crateShapeDef, &crate.base );
}
}
}
// Chest high spheres on soft welds the mover can push aside
{
b3ShapeDef sphereShapeDef = b3DefaultShapeDef();
sphereShapeDef.density = 100.0f;
sphereShapeDef.baseMaterial.customColor = b3_colorLightSeaGreen;
sphereShapeDef.filter = { SphereBit, AllBits, 0 };
b3Sphere sphere = { b3Vec3_zero, 0.35f };
b3WeldJointDef jointDef = b3DefaultWeldJointDef();
jointDef.linearHertz = 0.5f;
jointDef.linearDampingRatio = 0.2f;
jointDef.base.bodyIdA = groundId;
jointDef.base.collideConnected = true;
int gridCount = 20;
for ( int i = 0; i < gridCount; ++i )
{
for ( int j = 0; j < gridCount; ++j )
{
b3Pos position = { -9.5f + 1.0f * i, 1.7f, 17.0f + 1.0f * j };
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = position;
bodyDef.gravityScale = 0.0f;
b3BodyId sphereId = b3CreateBody( m_worldId, &bodyDef );
b3CreateSphereShape( sphereId, &sphereShapeDef, &sphere );
jointDef.base.bodyIdB = sphereId;
jointDef.base.localFrameA.p = b3Body_GetLocalPoint( groundId, position );
jointDef.base.localFrameB.p = b3Vec3_zero;
b3CreateWeldJoint( m_worldId, &jointDef );
}
}
}
// Pressure plate under the middle of the sphere grid
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = m_plateCenter;
b3BodyId plateId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef plateShapeDef = b3DefaultShapeDef();
plateShapeDef.density = 20.0f;
plateShapeDef.baseMaterial.customColor = b3_colorFireBrick;
plateShapeDef.filter = { PlateBit, MoverBit, 0 };
// The blast would only slam the plate into its lower limit
plateShapeDef.explosionScale = 0.0f;
b3BoxHull plate = b3MakeBoxHull( 1.5f, 0.1f, 1.5f );
b3CreateHullShape( plateId, &plateShapeDef, &plate.base );
// The motor force works like a preloaded spring. The plate holds its own weight but
// sinks under the mover.
float gravity = b3Length( b3World_GetGravity( m_worldId ) );
float plateWeight = gravity * b3Body_GetMass( plateId );
float moverWeight = m_mover.m_gravityScale * gravity * b3Body_GetMass( m_mover.m_moverId );
// The prismatic axis is the local x-axis, so turn it upright
b3Quat upright = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 0.5f * B3_PI );
b3PrismaticJointDef jointDef = b3DefaultPrismaticJointDef();
jointDef.base.bodyIdA = groundId;
jointDef.base.bodyIdB = plateId;
jointDef.base.localFrameA = { b3Body_GetLocalPoint( groundId, m_plateCenter ), upright };
jointDef.base.localFrameB = { b3Vec3_zero, upright };
jointDef.enableLimit = true;
jointDef.lowerTranslation = -m_plateTravel;
jointDef.upperTranslation = 0.0f;
jointDef.enableMotor = true;
jointDef.motorSpeed = 0.5f;
jointDef.maxMotorForce = plateWeight + 0.5f * moverWeight;
m_plateJointId = b3CreatePrismaticJoint( m_worldId, &jointDef );
m_plateArmed = true;
}
// Sleeping boxes overhead that the blast wakes, kept inside its reach
if ( m_isDebug == false )
{
b3ShapeDef boxShapeDef = b3DefaultShapeDef();
boxShapeDef.density = 100.0f;
boxShapeDef.baseMaterial.customColor = b3_colorPeru;
// The blast should wake these rather than launch them
boxShapeDef.explosionScale = 0.05f;
b3BoxHull box = b3MakeCubeHull( 0.1f );
int gridCount = 32;
int layerCount = 3;
float spacing = 0.5f;
float offset = -0.5f * spacing * ( gridCount - 1 );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.isAwake = false;
for ( int layer = 0; layer < layerCount; ++layer )
{
for ( int i = 0; i < gridCount; ++i )
{
for ( int j = 0; j < gridCount; ++j )
{
bodyDef.position = { m_plateCenter.x + offset + spacing * i, 8.0f + spacing * layer,
m_plateCenter.z + offset + spacing * j };
b3BodyId boxId = b3CreateBody( m_worldId, &bodyDef );
b3CreateHullShape( boxId, &boxShapeDef, &box.base );
}
}
}
}
// A big ball to roll
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { 6.0f, 1.0f, -6.0f };
b3BodyId ballId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef ballShapeDef = b3DefaultShapeDef();
ballShapeDef.density = 30.0f;
ballShapeDef.baseMaterial.rollingResistance = 0.05f;
ballShapeDef.baseMaterial.customColor = b3_colorTomato;
b3Sphere sphere = { b3Vec3_zero, 1.0f };
b3CreateSphereShape( ballId, &ballShapeDef, &sphere );
}
// The sweeper arms are at waist height, so time a jump to get past
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = m_sweeperCenter;
//bodyDef.angularVelocity = { 0.0f, 1.2f, 0.0f };
b3BodyId sweeperId = b3CreateBody( m_worldId, &bodyDef );
shapeDef.baseMaterial.customColor = b3_colorCrimson;
b3BoxHull post = b3MakeTransformedBoxHull( 0.3f, 0.6f, 0.3f,
{ { 0.0f, 0.6f, 0.0f }, b3Quat_identity } );
b3CreateHullShape( sweeperId, &shapeDef, &post.base );
b3BoxHull armX = b3MakeTransformedBoxHull( 5.0f, 0.15f, 0.15f,
{ { 0.0f, 1.0f, 0.0f }, b3Quat_identity } );
b3CreateHullShape( sweeperId, &shapeDef, &armX.base );
b3BoxHull armZ = b3MakeTransformedBoxHull( 0.15f, 0.15f, 5.0f,
{ { 0.0f, 1.0f, 0.0f }, b3Quat_identity } );
b3CreateHullShape( sweeperId, &shapeDef, &armZ.base );
b3Quat upright = b3MakeQuatFromAxisAngle( b3Vec3_axisX, -0.5f * B3_PI );
b3RevoluteJointDef jointDef = b3DefaultRevoluteJointDef();
jointDef.base.bodyIdA = groundId;
jointDef.base.bodyIdB = sweeperId;
jointDef.base.localFrameA = { b3Body_GetLocalPoint( groundId, m_sweeperCenter ),
upright };
jointDef.base.localFrameB = { b3Vec3_zero, upright };
jointDef.enableMotor = true;
jointDef.motorSpeed = 1.0f;
jointDef.maxMotorTorque = 10000.0f;
b3CreateRevoluteJoint( m_worldId, &jointDef );
}
shapeDef.baseMaterial.customColor = b3_colorMediumPurple;
for ( int i = 0; i < m_pillarCount; ++i )
{
b3Pos top = GetPillarTop( i );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { top.x, 0.0f, top.z };
b3BodyId pillarId = b3CreateBody( m_worldId, &bodyDef );
b3HullData* pillar = b3CreateCylinder( (float)top.y, 0.75f, 0.0f, 12 );
b3CreateHullShape( pillarId, &shapeDef, pillar );
b3DestroyHull( pillar );
}
SpawnGems();
m_camera->m_thirdPerson = true;
sapp_lock_mouse( true );
m_jumpReleased = true;
m_drawProbes = true;
m_time = 0.0f;
m_lapTime = 0.0f;
m_bestLapTime = 0.0f;
m_lapCount = 0;
}
~DynamicMoverSample() override
{
m_camera->m_thirdPerson = false;
sapp_lock_mouse( false );
}
// A thin static slab whose top face runs from the high point to the low point
void AddRamp( b3Vec3 high, b3Vec3 low, float halfWidth, b3HexColor color )
{
b3Vec3 axis = b3Sub( high, low );
float length = b3Length( axis );
axis = b3MulSV( 1.0f / length, axis );
b3Quat rotation = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisZ, axis );
b3Vec3 normal = b3RotateVector( rotation, b3Vec3_axisY );
float halfThickness = 0.1f;
b3Vec3 center = b3MulAdd( b3Lerp( low, high, 0.5f ), -halfThickness, normal );
b3BodyDef bodyDef = b3DefaultBodyDef();
b3BodyId rampId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.customColor = color;
b3BoxHull box = b3MakeTransformedBoxHull( halfWidth, halfThickness, 0.5f * length,
{ center, rotation } );
b3CreateHullShape( rampId, &shapeDef, &box.base );
}
b3Pos GetPlatformPosition( int index, float time ) const
{
if ( index == 0 )
{
// Elevator, the top face rises from the ground to the first ledge
float y = 1.95f - 1.95f * cosf( 0.6f * time );
return { 14.0f, y, 0.0f };
}
// Shuttle between the two ledges
float x = 25.0f - 3.5f * cosf( 0.5f * time );
return { x, 3.9f, 0.0f };
}
b3Pos GetPillarTop( int index ) const
{
return { -20.0f, 0.5f + 0.6f * index, -3.0f - 5.0f * index };
}
void SpawnGems()
{
b3Pos positions[m_gemCount] = {
{ 0.0f, 1.2f, 5.0f }, { -6.0f, 2.2f, 6.0f }, { -6.0f, 3.2f, 11.0f },
{ 0.0f, 3.2f, 11.0f }, { 6.0f, 3.2f, 11.0f }, { 6.0f, 2.2f, 6.0f },
{ 18.0f, 5.2f, 0.0f }, { 25.0f, 5.2f, 0.0f }, { 32.0f, 5.2f, 0.0f },
{ -17.0f, 2.2f, 0.0f }, { -10.0f, 4.4f, -8.0f }, { 6.0f, 1.2f, -9.5f },
{ 3.0f, 1.2f, -16.0f }, { -3.0f, 1.2f, -16.0f }, { 0.0f, 1.2f, -19.0f },
{ 0.0f, 1.2f, -13.0f }, { -20.0f, 0.0f, 0.0f },
};
// The last gem waits on the tallest pillar
positions[m_gemCount - 1] = GetPillarTop( m_pillarCount - 1 );
positions[m_gemCount - 1].y += 1.2f;
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.isSensor = true;
shapeDef.enableSensorEvents = true;
shapeDef.filter = { GemBit, MoverBit, 0 };
shapeDef.baseMaterial.customColor = b3_colorGold;
// Stand a cube on a corner so it reads as a gem
b3Quat tilt = b3MakeQuatFromAxisAngle( b3Normalize( { 1.0f, 0.0f, -1.0f } ), 0.9553f );
b3BoxHull gem = b3MakeTransformedBoxHull( 0.2f, 0.2f, 0.2f, { b3Vec3_zero, tilt } );
for ( int i = 0; i < m_gemCount; ++i )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_kinematicBody;
bodyDef.position = positions[i];
bodyDef.angularVelocity = { 0.0f, 2.0f, 0.0f };
m_gemIds[i] = b3CreateBody( m_worldId, &bodyDef );
b3CreateHullShape( m_gemIds[i], &shapeDef, &gem.base );
}
m_gemsLeft = m_gemCount;
}
void UpdatePressurePlate()
{
float translation = b3PrismaticJoint_GetTranslation( m_plateJointId );
// Fire once per press. The plate has to spring back up to rearm.
if ( m_plateArmed && translation < -m_plateTravel + 0.01f )
{
b3ExplosionDef def = b3DefaultExplosionDef();
def.position = b3OffsetPos( m_plateCenter, b3Vec3{ 0.0f, 0.1f, 0.0f } );
def.radius = 1.0f;
def.falloff = 14.0f;
def.impulsePerArea = 3000.0f;
b3World_Explode( m_worldId, &def );
m_mover.Launch();
m_plateArmed = false;
}
else if ( m_plateArmed == false && translation > -0.01f )
{
m_plateArmed = true;
}
}
void CollectGems()
{
b3SensorEvents events = b3World_GetSensorEvents( m_worldId );
for ( int i = 0; i < events.beginCount; ++i )
{
b3SensorBeginTouchEvent* event = events.beginEvents + i;
if ( b3Shape_IsValid( event->visitorShapeId ) == false ||
b3Shape_IsValid( event->sensorShapeId ) == false )
{
continue;
}
b3BodyId visitorId = b3Shape_GetBody( event->visitorShapeId );
if ( B3_ID_EQUALS( visitorId, m_mover.m_moverId ) == false )
{
continue;
}
b3BodyId gemId = b3Shape_GetBody( event->sensorShapeId );
for ( b3BodyId& id : m_gemIds )
{
if ( B3_ID_EQUALS( id, gemId ) )
{
b3DestroyBody( id );
id = b3_nullBodyId;
m_gemsLeft -= 1;
break;
}
}
}
if ( m_gemsLeft == 0 )
{
m_lapCount += 1;
if ( m_bestLapTime == 0.0f || m_lapTime < m_bestLapTime )
{
m_bestLapTime = m_lapTime;
}
m_lapTime = 0.0f;
SpawnGems();
}
}
// Pull the boom in when the view to the mover is blocked
void FollowMover( b3Pos position )
{
if ( m_camera->m_thirdPerson == false )
{
return;
}
m_camera->m_pivot = position;
m_camera->UpdateTransform();
b3Vec3 translation = b3SubPos( m_camera->m_worldEye, position );
float distance = b3Length( translation );
if ( distance < 0.01f )
{
return;
}
b3QueryFilter filter = { StaticBit, StaticBit, 0, "camera" };
b3RayResult result = b3World_CastRayClosest( m_worldId, position, translation, filter );
if ( result.hit )
{
float savedRadius = m_camera->m_radius;
m_camera->m_radius = b3MaxFloat( 0.1f, result.fraction * distance - 0.15f );
m_camera->UpdateTransform();
m_camera->m_radius = savedRadius;
}
}
void Keyboard( int key, int action, int mods ) override
{
if ( key == KEY_T && action == ACTION_PRESS )
{
ToggleThirdPerson();
}
}
bool DrawControls() override
{
bool thirdPerson = m_camera->m_thirdPerson;
if ( ImGui::Checkbox( "Third Person (T)", &thirdPerson ) )
{
ToggleThirdPerson();
}
ImGui::Checkbox( "Skirt Pogo", &m_mover.m_enableSkirtPogo );
ImGui::Checkbox( "Draw Probes", &m_drawProbes );
ImGui::Separator();
ImGui::SliderFloat( "Jump Speed", &m_mover.m_jumpSpeed, 0.0f, 20.0f, "%.1f" );
ImGui::SliderFloat( "Max Speed", &m_mover.m_maxSpeed, 0.0f, 20.0f, "%.0f" );
ImGui::SliderFloat( "Accelerate", &m_mover.m_accelerate, 0.0f, 100.0f, "%.0f" );
ImGui::SliderFloat( "Friction", &m_mover.m_friction, 0.0f, 20.0f, "%.1f" );
ImGui::SliderFloat( "Air Steer", &m_mover.m_airSteer, 0.0f, 1.0f, "%.2f" );
float gravityScale = m_mover.m_gravityScale;
if ( ImGui::SliderFloat( "Gravity Scale", &gravityScale, 0.0f, 4.0f, "%.1f" ) )
{
m_mover.SetGravityScale( gravityScale );
}
ImGui::SliderFloat( "Pogo Hertz", &m_mover.m_pogoHertz, 0.0f, 30.0f, "%.0f" );
ImGui::SliderFloat( "Pogo Damping", &m_mover.m_pogoDampingRatio, 0.0f, 4.0f, "%.1f" );
ImGui::SliderFloat( "Ground Force", &m_mover.m_maxGroundForce, 0.0f, 20000.0f, "%.0f" );
return true;
}
void Step() override
{
bool pause = m_context->pause && m_context->singleStep == 0;
float timeStep = m_context->hertz > 0.0f ? 1.0f / m_context->hertz : 0.0f;
if ( pause == false && timeStep > 0.0f )
{
m_time += timeStep;
m_lapTime += timeStep;
for ( int i = 0; i < m_platformCount; ++i )
{
b3WorldTransform target = { GetPlatformPosition( i, m_time ), b3Quat_identity };
b3Body_SetTargetTransform( m_platformIds[i], target, timeStep, true );
}
MoverInput input = GetMoverInput();
// Jumping again needs a fresh press
if ( input.jump )
{
if ( m_jumpReleased && m_mover.Jump() )
{
m_jumpReleased = false;
}
}
else
{
m_jumpReleased = true;
}
float speedScale = 1.0f;
if ( input.walk )
{
speedScale = 0.25f;
}
else if ( input.sprint )
{
speedScale = 1.5f;
}
m_mover.Update( timeStep, input.forward, input.right, input.throttle, speedScale );
}
Sample::Step();
if ( m_didStep )
{
CollectGems();
UpdatePressurePlate();
}
b3Pos position = b3Body_GetPosition( m_mover.m_moverId );
FollowMover( position );
SetDrawOrigin( m_camera->DrawOrigin() );
if ( m_drawProbes )
{
m_mover.Draw();
}
DrawTextLine( "WASD = move, Space = jump, Shift = sprint, Ctrl = walk, T = camera" );
DrawTextLine( "gems %d / %d, lap time %.1f s", m_gemCount - m_gemsLeft, m_gemCount,
m_lapTime );
if ( m_lapCount > 0 )
{
DrawTextLine( "laps %d, best %.1f s", m_lapCount, m_bestLapTime );
}
float normalY = m_mover.m_castResult.hit ? m_mover.m_castResult.normal.y : 0.0f;
DrawTextLine( "on ground %d, walkable %d, normal y %.2f", (int)m_mover.m_onGround,
(int)m_mover.m_walkable, normalY );
DrawTextLine( "pogo length %.2f / %.2f", m_mover.m_pogoLength, m_mover.m_pogoRestLength );
}
static Sample* Create( SampleContext* context )
{
return new DynamicMoverSample( context );
}
static constexpr uint64_t StaticBit = 0x1;
static constexpr uint64_t MoverBit = 0x2;
static constexpr uint64_t GemBit = 0x4;
static constexpr uint64_t PlateBit = 0x8;
static constexpr uint64_t SphereBit = 0x10;
static constexpr uint64_t AllBits = ~0ull;
static constexpr uint64_t m_platformMaterial = 7;
static constexpr int m_platformCount = 2;
static constexpr int m_pillarCount = 6;
static constexpr int m_gemCount = 17;
static constexpr b3Pos m_sweeperCenter = { 0.0f, 0.0f, -16.0f };
static constexpr b3Pos m_plateCenter = { 0.0f, 0.05f, 26.5f };
static constexpr float m_plateTravel = 0.1f;
DynamicMover m_mover;
b3JointId m_plateJointId;
bool m_plateArmed;
b3BodyId m_platformIds[m_platformCount];
b3BodyId m_gemIds[m_gemCount];
int m_gemsLeft;
int m_lapCount;
float m_time;
float m_lapTime;
float m_bestLapTime;
bool m_jumpReleased;
bool m_drawProbes;
};
static int sampleDynamicMover =
RegisterSample( "Character", "Dynamic Mover", DynamicMoverSample::Create );
struct ClosestShapeCastContext
{

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"
@ -501,7 +501,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;
@ -711,7 +713,33 @@ 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 );
b3Vec3 translation = { 10.0f, -40.0f, -5.0f };
@ -801,7 +829,7 @@ public:
}
b3CompoundData* m_compound;
CharacterMover m_mover;
GeometricMover m_mover;
float m_worldWidth;
b3Pos m_rayOrigin;
};

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 "?";
}