Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
c7908394eb Broad-phase: rebuild the trees when the move buffer is empty
b3BroadPhase_DestroyProxy unbuffers the proxy's move, but its ancestors
in the dynamic tree keep the enlarged flags set when it was enlarged in
the last step. If it was the only buffered proxy, b3UpdateBroadPhasePairs
returned before the tree rebuild that clears them, and the next solve
tripped ValidateNoEnlarged (dynamic_tree.c:1081) with validation on.
In release the stale flags only deferred the rebuild.

The early return now runs the rebuild; on a tree with no enlarged node
it is a walk of the root. Upstream replaced this move buffer with moved
flags in the tree (#159).

DestroyEnlargedProxyTest: aborts before, passes after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:16:01 +01:00
Meta Vens
ebe346a925 Contact friction hook also runs on recycled contacts
A recycled contact skips its update and with it the friction mix, so friction never followed
the application's patches under a body at rest. With a hook installed the recycle branch mixes
again and runs the hook (anchors are centre-relative there, in the cached frame); with no hook
nothing changes. The hook body moves to b3ApplyContactFrictionHook. ContactFrictionRecycledTest
fails without the recycle call.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 06:32:58 +01:00
Meta Vens
2a43faeaec Contact friction hook: a per-contact friction override after the mix
b3ContactFrictionFcn is called from b3UpdateConvexContact right after the friction
mix with the mean manifold point in each body's frame, both bodies' user data and the
mixed value. Convex contacts only. Test: ContactFrictionHookTest.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 05:45:44 +01:00
Meta Vens
fb719c49c0 Substep callback: an external constraint solver inside the soft step
b3World_SetSubStepCallback runs a callback subStepCount times per b3World_Step on the
orchestrating thread, after the biased solve and before positions integrate, also when no
body is awake. b3Body_GetSubStepState reads a body's pose at the substep's start and its
solved velocity; b3Body_ApplySubStepImpulse changes the velocity of an awake body without
waking it. Both assert the callback is running. Not recorded.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 04:15:20 +01:00
Meta Vens
6cfeeff232 Static assert RELAX_ITERATIONS == 1 beside stepNormalImpulse
stepNormalImpulse sums the impulse applied after each relax pass, which is
the step impulse only with one relax iteration. Also indents two stray
column-0 lines of the previous commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 02:48:16 +01:00
Meta Vens
e421ffaf88 Contact points report the normal impulse applied over the whole step
Adds b3ManifoldPoint.stepNormalImpulse: the impulse each sub-step applied
(accumulated after the relax pass, plus restitution's delta), summed over the
step, in the scalar and SIMD solver paths. Exact only while RELAX_ITERATIONS
is 1. GameCult fork for Ymir (lodur:ruling:ymir-box3d-fork); upstream is
erincatto/box3d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:22:49 +01:00
12 changed files with 366 additions and 0 deletions

View file

@ -167,6 +167,21 @@ B3_API void b3World_SetPreSolveCallback( b3WorldId worldId, b3PreSolveFcn* fcn,
/// @see b3WorldDef /// @see b3WorldDef
B3_API void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity ); B3_API void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity );
/// GameCult fork: an external constraint solver run inside the soft step. Called on the solver's
/// orchestrating thread subStepCount times per b3World_Step, after the biased solve and before
/// positions integrate (also when no body is awake). Not recorded.
B3_API void b3World_SetSubStepCallback( b3WorldId worldId, b3SubStepFcn* fcn, void* context );
/// GameCult fork, valid only inside the substep callback: the body's centre of mass and rotation at
/// the start of this substep and its velocity after the biased solve. Returns false (and zero
/// velocity) for a body the solver does not move this step: static or asleep.
B3_API bool b3Body_GetSubStepState( b3BodyId bodyId, b3Pos* center, b3Quat* rotation, b3Vec3* linearVelocity,
b3Vec3* angularVelocity );
/// GameCult fork, valid only inside the substep callback: a velocity change from a linear impulse at
/// the centre of mass and an angular impulse, on an awake body. Never wakes a body.
B3_API void b3Body_ApplySubStepImpulse( b3BodyId bodyId, b3Vec3 linearImpulse, b3Vec3 angularImpulse );
/// Get the gravity vector /// Get the gravity vector
B3_API b3Vec3 b3World_GetGravity( b3WorldId worldId ); B3_API b3Vec3 b3World_GetGravity( b3WorldId worldId );
@ -224,6 +239,10 @@ B3_API void* b3World_GetUserData( b3WorldId worldId );
/// Set the friction callback. Passing NULL resets to default. /// Set the friction callback. Passing NULL resets to default.
B3_API void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callback ); B3_API void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callback );
/// Set the per-contact friction hook (GameCult fork). Passing NULL removes it. The hook is called on worker threads, so the
/// context must be read-only for the duration of a step.
B3_API void b3World_SetContactFrictionCallback( b3WorldId worldId, b3ContactFrictionFcn* fcn, void* context );
/// Set the restitution callback. Passing NULL resets to default. /// Set the restitution callback. Passing NULL resets to default.
B3_API void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback ); B3_API void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback );

View file

@ -53,6 +53,14 @@ typedef void b3DestroyDebugShapeCallback( void* userShape, void* userContext );
/// @ingroup world /// @ingroup world
typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB ); typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB );
/// Optional per-contact friction override (GameCult fork). Called from b3UpdateConvexContact right after the friction mix,
/// from a worker thread, with the mean of the manifold points expressed in each body's frame, the bodies' user data, and the
/// mixed friction. Return the friction to use for this contact this update. Convex contacts only; mesh contacts are not hooked.
/// @warning Must be pure and read-only: no Box3D calls, no writes to application state.
/// @ingroup world
typedef float b3ContactFrictionFcn( void* bodyUserDataA, void* bodyUserDataB, b3Vec3 localPointA, b3Vec3 localPointB, float mixed,
void* context );
/// Optional restitution mixing callback. This intentionally provides no context objects because this is called /// Optional restitution mixing callback. This intentionally provides no context objects because this is called
/// from a worker thread. /// from a worker thread.
/// @warning This function should not attempt to modify Box3D state or user application state. /// @warning This function should not attempt to modify Box3D state or user application state.
@ -94,6 +102,9 @@ typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point,
/// @ingroup world /// @ingroup world
typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context ); typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context );
/// GameCult fork: see b3World_SetSubStepCallback
typedef void b3SubStepFcn( b3WorldId worldId, int subStepIndex, float h, void* context );
/// Prototype callback for ray casts. /// Prototype callback for ray casts.
/// Called for each shape found in the query. You control how the ray cast /// Called for each shape found in the query. You control how the ray cast
/// proceeds by returning a float: /// proceeds by returning a float:
@ -2576,6 +2587,9 @@ typedef struct b3ManifoldPoint
/// to identify speculative contact points that had an interaction in the time step. /// to identify speculative contact points that had an interaction in the time step.
float totalNormalImpulse; float totalNormalImpulse;
/// Sum over sub-steps of the impulse each sub-step applied, plus restitution: the step impulse.
float stepNormalImpulse;
/// Relative normal velocity pre-solve. Used for hit events. If the normal impulse is /// Relative normal velocity pre-solve. Used for hit events. If the normal impulse is
/// zero then there was no hit. Negative means shapes are approaching. /// zero then there was no hit. Negative means shapes are approaching.
float normalVelocity; float normalVelocity;

View file

@ -1119,6 +1119,44 @@ b3Vec3 b3Body_GetLinearVelocity( b3BodyId bodyId )
return b3Vec3_zero; return b3Vec3_zero;
} }
bool b3Body_GetSubStepState( b3BodyId bodyId, b3Pos* center, b3Quat* rotation, b3Vec3* linearVelocity,
b3Vec3* angularVelocity )
{
b3World* world = b3GetWorld( bodyId.world0 );
B3_ASSERT( world->inSubStep );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodySim* sim = b3GetBodySim( world, body );
b3BodyState* state = b3GetBodyState( world, body );
if ( state == NULL )
{
*center = sim->center;
*rotation = sim->transform.q;
*linearVelocity = b3Vec3_zero;
*angularVelocity = b3Vec3_zero;
return false;
}
*center = b3OffsetPos( sim->center, state->deltaPosition );
*rotation = b3NormalizeQuat( b3MulQuat( state->deltaRotation, sim->transform.q ) );
*linearVelocity = state->linearVelocity;
*angularVelocity = state->angularVelocity;
return true;
}
void b3Body_ApplySubStepImpulse( b3BodyId bodyId, b3Vec3 linearImpulse, b3Vec3 angularImpulse )
{
b3World* world = b3GetWorld( bodyId.world0 );
B3_ASSERT( world->inSubStep );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3BodyState* state = b3GetBodyState( world, body );
if ( state == NULL )
{
return;
}
b3BodySim* sim = b3GetBodySim( world, body );
state->linearVelocity = b3MulAdd( state->linearVelocity, sim->invMass, linearImpulse );
state->angularVelocity = b3Add( state->angularVelocity, b3MulMV( sim->invInertiaWorld, angularImpulse ) );
}
b3Vec3 b3Body_GetAngularVelocity( b3BodyId bodyId ) b3Vec3 b3Body_GetAngularVelocity( b3BodyId bodyId )
{ {
b3World* world = b3GetWorld( bodyId.world0 ); b3World* world = b3GetWorld( bodyId.world0 );

View file

@ -403,6 +403,9 @@ void b3UpdateBroadPhasePairs( b3World* world )
if ( moveCount == 0 ) if ( moveCount == 0 )
{ {
// GameCult fork: destroying a proxy unbuffers its move but leaves its ancestors flagged enlarged, so an empty
// move buffer does not mean the trees are clean. The rebuild clears the flags; on a clean tree it is a no-op.
b3UpdateTreesTask( world );
return; return;
} }

View file

@ -607,6 +607,53 @@ static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact*
return true; return true;
} }
// The per-contact friction hook, when one is installed: the mean manifold point in each body's frame (the anchors' frame, rotated back
// by q and moved by the offset: zero for origin-relative anchors, the local centre for centre-relative ones), the bodies' user data and
// the mixed friction. Convex contacts only.
void b3ApplyContactFrictionHook( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Quat qA, b3Quat qB,
b3Vec3 offsetA, b3Vec3 offsetB, float mixed )
{
if ( world->contactFrictionFcn == NULL )
{
return;
}
b3Manifold* manifold = contact->manifolds + 0;
int pointCount = manifold->pointCount;
b3Vec3 sumA = b3Vec3_zero;
b3Vec3 sumB = b3Vec3_zero;
for ( int i = 0; i < pointCount; ++i )
{
sumA = b3Add( sumA, manifold->points[i].anchorA );
sumB = b3Add( sumB, manifold->points[i].anchorB );
}
float inv = 1.0f / (float)pointCount;
b3Vec3 localA = b3Add( b3InvRotateVector( qA, b3MulSV( inv, sumA ) ), offsetA );
b3Vec3 localB = b3Add( b3InvRotateVector( qB, b3MulSV( inv, sumB ) ), offsetB );
void* userDataA = b3Array_Get( world->bodies, shapeA->bodyId )->userData;
void* userDataB = b3Array_Get( world->bodies, shapeB->bodyId )->userData;
contact->friction = world->contactFrictionFcn( userDataA, userDataB, localA, localB, mixed, world->contactFrictionContext );
}
// A recycled contact skips its update, and with it the friction mix: with a hook installed, mix again and run the hook so the friction follows
// the application's patches under a body at rest. Anchors are centre-relative here, in the frame the contact was cached in.
void b3RefreshRecycledFriction( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Vec3 localCenterA,
b3Vec3 localCenterB )
{
if ( world->contactFrictionFcn == NULL || ( contact->flags & b3_simMeshContact ) || contact->manifoldCount != 1 ||
contact->manifolds[0].pointCount == 0 || shapeA->type == b3_compoundShape || shapeB->type == b3_compoundShape )
{
return;
}
const b3SurfaceMaterial* materialA = b3GetShapeMaterials( shapeA );
const b3SurfaceMaterial* materialB = b3GetShapeMaterials( shapeB );
float mixed =
world->frictionCallback( materialA->friction, materialA->userMaterialId, materialB->friction, materialB->userMaterialId );
b3ApplyContactFrictionHook( world, contact, shapeA, shapeB, contact->cachedRotationA, contact->cachedRotationB, localCenterA,
localCenterB, mixed );
}
static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3WorldTransform xfA, static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3WorldTransform xfA,
b3Shape* shapeB, b3WorldTransform xfB, bool flip, b3Arena arena ) b3Shape* shapeB, b3WorldTransform xfB, bool flip, b3Arena arena )
{ {
@ -640,6 +687,8 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c
// Keep these updated in case the values on the shapes are modified // Keep these updated in case the values on the shapes are modified
contact->friction = contact->friction =
world->frictionCallback( materialA->friction, materialA->userMaterialId, materialB->friction, materialB->userMaterialId ); world->frictionCallback( materialA->friction, materialA->userMaterialId, materialB->friction, materialB->userMaterialId );
b3ApplyContactFrictionHook( world, contact, shapeA, shapeB, xfA.q, xfB.q, b3Vec3_zero, b3Vec3_zero, contact->friction );
contact->restitution = world->restitutionCallback( materialA->restitution, materialA->userMaterialId, materialB->restitution, contact->restitution = world->restitutionCallback( materialA->restitution, materialA->userMaterialId, materialB->restitution,
materialB->userMaterialId ); materialB->userMaterialId );

View file

@ -173,6 +173,11 @@ void b3InitializeContactRegisters( void );
void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int childIndex ); void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int childIndex );
void b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies ); void b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies );
void b3ApplyContactFrictionHook( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Quat qA, b3Quat qB,
b3Vec3 offsetA, b3Vec3 offsetB, float mixed );
void b3RefreshRecycledFriction( b3World* world, b3Contact* contact, const b3Shape* shapeA, const b3Shape* shapeB, b3Vec3 localCenterA,
b3Vec3 localCenterB );
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3WorldTransform xfA, bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3WorldTransform xfA,
b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast, b3Arena arena ); b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast, b3Arena arena );

View file

@ -196,6 +196,7 @@ void b3PrepareContacts_Mesh( b3SolverBlock block, b3StepContext* context )
cp->baseSeparation = mp->separation - b3Dot( b3Sub( cp->rB, cp->rA ), normal ); cp->baseSeparation = mp->separation - b3Dot( b3Sub( cp->rB, cp->rA ), normal );
cp->normalImpulse = warmStartScale * mp->normalImpulse; cp->normalImpulse = warmStartScale * mp->normalImpulse;
cp->totalNormalImpulse = 0.0f; cp->totalNormalImpulse = 0.0f;
cp->stepNormalImpulse = 0.0f;
b3Vec3 rA = cp->rA; b3Vec3 rA = cp->rA;
b3Vec3 rB = cp->rB; b3Vec3 rB = cp->rB;
@ -456,6 +457,7 @@ void b3SolveContacts_Mesh( b3SolverBlock block, b3StepContext* context, bool use
deltaImpulse = newImpulse - cp->normalImpulse; deltaImpulse = newImpulse - cp->normalImpulse;
cp->normalImpulse = newImpulse; cp->normalImpulse = newImpulse;
cp->totalNormalImpulse += newImpulse; cp->totalNormalImpulse += newImpulse;
if ( useBias == false ) cp->stepNormalImpulse += newImpulse;
totalNormalImpulse += newImpulse; totalNormalImpulse += newImpulse;
totalTwistLimit += cp->leverArm * cp->normalImpulse; totalTwistLimit += cp->leverArm * cp->normalImpulse;
@ -650,6 +652,7 @@ void b3ApplyRestitution_Mesh( b3SolverBlock block, b3StepContext* context )
impulse = newImpulse - cp->normalImpulse; impulse = newImpulse - cp->normalImpulse;
cp->normalImpulse = newImpulse; cp->normalImpulse = newImpulse;
cp->totalNormalImpulse += impulse; cp->totalNormalImpulse += impulse;
cp->stepNormalImpulse += impulse;
// apply contact impulse // apply contact impulse
b3Vec3 P = b3MulSV( impulse, normal ); b3Vec3 P = b3MulSV( impulse, normal );
@ -754,6 +757,7 @@ void b3StoreImpulses_Mesh( b3SolverBlock block, b3StepContext* context, int work
b3ManifoldPoint* mp = manifold->points + pointIndex; b3ManifoldPoint* mp = manifold->points + pointIndex;
mp->normalImpulse = cp->normalImpulse; mp->normalImpulse = cp->normalImpulse;
mp->totalNormalImpulse = cp->totalNormalImpulse; mp->totalNormalImpulse = cp->totalNormalImpulse;
mp->stepNormalImpulse = cp->stepNormalImpulse;
mp->normalVelocity = cp->relativeVelocity; mp->normalVelocity = cp->relativeVelocity;
if ( checkHitEvents && flagged == false && if ( checkHitEvents && flagged == false &&
@ -1330,6 +1334,7 @@ typedef struct b3ContactConstraintPointWide
b3FloatW baseSeparations; b3FloatW baseSeparations;
b3FloatW normalImpulses; b3FloatW normalImpulses;
b3FloatW totalNormalImpulses; b3FloatW totalNormalImpulses;
b3FloatW stepNormalImpulses;
b3FloatW normalMasses; b3FloatW normalMasses;
b3FloatW leverArms; b3FloatW leverArms;
b3FloatW relativeVelocities; b3FloatW relativeVelocities;
@ -1805,6 +1810,7 @@ void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context )
( (float*)&cp->normalImpulses )[lane] = warmStartScale * mp->normalImpulse; ( (float*)&cp->normalImpulses )[lane] = warmStartScale * mp->normalImpulse;
( (float*)&cp->totalNormalImpulses )[lane] = 0.0f; ( (float*)&cp->totalNormalImpulses )[lane] = 0.0f;
( (float*)&cp->stepNormalImpulses )[lane] = 0.0f;
b3Vec3 rnA = b3Cross( rA, normal ); b3Vec3 rnA = b3Cross( rA, normal );
b3Vec3 rnB = b3Cross( rB, normal ); b3Vec3 rnB = b3Cross( rB, normal );
@ -1892,6 +1898,7 @@ void b3PrepareContacts_Convex( b3SolverBlock block, b3StepContext* context )
( (float*)&cp->baseSeparations )[lane] = 0.0f; ( (float*)&cp->baseSeparations )[lane] = 0.0f;
( (float*)&cp->normalImpulses )[lane] = 0.0f; ( (float*)&cp->normalImpulses )[lane] = 0.0f;
( (float*)&cp->totalNormalImpulses )[lane] = 0.0f; ( (float*)&cp->totalNormalImpulses )[lane] = 0.0f;
( (float*)&cp->stepNormalImpulses )[lane] = 0.0f;
( (float*)&cp->normalMasses )[lane] = 0.0f; ( (float*)&cp->normalMasses )[lane] = 0.0f;
( (float*)&cp->relativeVelocities )[lane] = 0.0f; ( (float*)&cp->relativeVelocities )[lane] = 0.0f;
( (float*)&cp->leverArms )[lane] = 0.0f; ( (float*)&cp->leverArms )[lane] = 0.0f;
@ -2051,6 +2058,7 @@ void b3SolveContacts_Convex( b3SolverBlock block, b3StepContext* context, bool u
b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses ); b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses );
cp->normalImpulses = newImpulse; cp->normalImpulses = newImpulse;
cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, newImpulse ); cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, newImpulse );
if ( useBias == false ) cp->stepNormalImpulses = b3AddW( cp->stepNormalImpulses, newImpulse );
totalNormalImpulse = b3AddW( totalNormalImpulse, newImpulse ); totalNormalImpulse = b3AddW( totalNormalImpulse, newImpulse );
totalTwistLimit = b3AddW( totalTwistLimit, b3MulW( cp->leverArms, newImpulse ) ); totalTwistLimit = b3AddW( totalTwistLimit, b3MulW( cp->leverArms, newImpulse ) );
@ -2232,6 +2240,7 @@ void b3ApplyRestitution_Convex( b3SolverBlock block, b3StepContext* context )
b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses ); b3FloatW deltaImpulse = b3SubW( newImpulse, cp->normalImpulses );
cp->normalImpulses = newImpulse; cp->normalImpulses = newImpulse;
cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, deltaImpulse ); cp->totalNormalImpulses = b3AddW( cp->totalNormalImpulses, deltaImpulse );
cp->stepNormalImpulses = b3AddW( cp->stepNormalImpulses, deltaImpulse );
// Apply contact impulse // Apply contact impulse
b3Vec3W P = b3MulSVW( deltaImpulse, c->normal ); b3Vec3W P = b3MulSVW( deltaImpulse, c->normal );
@ -2335,6 +2344,7 @@ void b3StoreImpulses_Convex( b3SolverBlock block, b3StepContext* context, int wo
b3ManifoldPoint* mp = m->points + pointIndex; b3ManifoldPoint* mp = m->points + pointIndex;
mp->normalImpulse = normalImpulse[lane]; mp->normalImpulse = normalImpulse[lane];
mp->totalNormalImpulse = totalNormalImpulse[lane]; mp->totalNormalImpulse = totalNormalImpulse[lane];
mp->stepNormalImpulse = ((const float*)&cp->stepNormalImpulses)[lane];
mp->normalVelocity = normalVelocity[lane]; mp->normalVelocity = normalVelocity[lane];
} }

View file

@ -13,6 +13,7 @@ typedef struct b3ManifoldConstraintPoint
float relativeVelocity; float relativeVelocity;
float normalImpulse; float normalImpulse;
float totalNormalImpulse; float totalNormalImpulse;
float stepNormalImpulse;
float normalMass; float normalMass;
float leverArm; float leverArm;
} b3ManifoldConstraintPoint; } b3ManifoldConstraintPoint;

View file

@ -721,6 +721,7 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
// Contact is recycled. This also skips updating other aspects of the contact // Contact is recycled. This also skips updating other aspects of the contact
// such as material parameters. // such as material parameters.
b3RefreshRecycledFriction( world, contact, shapeA, shapeB, bodySimA->localCenter, bodySimB->localCenter );
continue; continue;
} }
} }
@ -2214,6 +2215,18 @@ void b3World_SetFrictionCallback( b3WorldId worldId, b3FrictionCallback* callbac
world->frictionCallback = callback != NULL ? callback : b3DefaultFrictionCallback; world->frictionCallback = callback != NULL ? callback : b3DefaultFrictionCallback;
} }
void b3World_SetContactFrictionCallback( b3WorldId worldId, b3ContactFrictionFcn* fcn, void* context )
{
b3World* world = b3GetUnlockedWorldFromId( worldId );
if ( world == NULL )
{
return;
}
world->contactFrictionFcn = fcn;
world->contactFrictionContext = context;
}
void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback ) void b3World_SetRestitutionCallback( b3WorldId worldId, b3RestitutionCallback* callback )
{ {
b3World* world = b3GetUnlockedWorldFromId( worldId ); b3World* world = b3GetUnlockedWorldFromId( worldId );
@ -3333,6 +3346,14 @@ void b3World_SetGravity( b3WorldId worldId, b3Vec3 gravity )
world->gravity = gravity; world->gravity = gravity;
} }
void b3World_SetSubStepCallback( b3WorldId worldId, b3SubStepFcn* fcn, void* context )
{
b3World* world = b3GetWorldFromId( worldId );
B3_ASSERT( world->locked == false );
world->subStepFcn = fcn;
world->subStepContext = context;
}
b3Vec3 b3World_GetGravity( b3WorldId worldId ) b3Vec3 b3World_GetGravity( b3WorldId worldId )
{ {
b3World* world = b3GetWorldFromId( worldId ); b3World* world = b3GetWorldFromId( worldId );

View file

@ -231,6 +231,8 @@ typedef struct b3World
float contactRecycleDistance; float contactRecycleDistance;
b3FrictionCallback* frictionCallback; b3FrictionCallback* frictionCallback;
b3ContactFrictionFcn* contactFrictionFcn;
void* contactFrictionContext;
b3RestitutionCallback* restitutionCallback; b3RestitutionCallback* restitutionCallback;
uint16_t generation; uint16_t generation;
@ -275,6 +277,11 @@ typedef struct b3World
// not a real mutex. This should have minimal performance impact. // not a real mutex. This should have minimal performance impact.
bool locked; bool locked;
// GameCult fork: the substep callback, and whether it is running
b3SubStepFcn* subStepFcn;
void* subStepContext;
bool inSubStep;
// Non-NULL while a recording session is active. Set by b3World_StartRecording, // Non-NULL while a recording session is active. Set by b3World_StartRecording,
// cleared by b3World_StopRecording. Hooks in mutators check this before writing. // cleared by b3World_StopRecording. Hooks in mutators check this before writing.
struct b3Recording* recording; struct b3Recording* recording;
@ -285,6 +292,11 @@ typedef struct b3World
bool inUse; bool inUse;
} b3World; } b3World;
static inline b3WorldId b3MakeWorldIdFromWorld( b3World* world )
{
return (b3WorldId){ (uint16_t)( world->worldId + 1 ), world->generation };
}
b3World* b3GetUnlockedWorldFromId( b3WorldId id ); b3World* b3GetUnlockedWorldFromId( b3WorldId id );
b3World* b3GetWorldFromId( b3WorldId id ); b3World* b3GetWorldFromId( b3WorldId id );

View file

@ -28,6 +28,10 @@
#define ITERATIONS 1 #define ITERATIONS 1
#define RELAX_ITERATIONS 1 #define RELAX_ITERATIONS 1
// stepNormalImpulse (contact_solver.c) sums the impulse applied after each relax pass; it is the step
// impulse only with one relax pass per sub-step
_Static_assert( RELAX_ITERATIONS == 1, "stepNormalImpulse is exact only with one relax iteration" );
#if ( defined( __GNUC__ ) || defined( __clang__ ) ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) #if ( defined( __GNUC__ ) || defined( __clang__ ) ) && ( defined( __i386__ ) || defined( __x86_64__ ) )
static void b3Pause( void ) static void b3Pause( void )
{ {
@ -1265,6 +1269,15 @@ static void b3SolverTask( void* taskContext )
profile->solveImpulses += b3GetMillisecondsAndReset( &ticks ); profile->solveImpulses += b3GetMillisecondsAndReset( &ticks );
// GameCult fork: the external solver's substep, on this thread while the workers wait
b3World* world = context->world;
if ( world->subStepFcn != NULL )
{
world->inSubStep = true;
world->subStepFcn( b3MakeWorldIdFromWorld( world ), subStepIndex, context->h, world->subStepContext );
world->inSubStep = false;
}
// Integrate positions // Integrate positions
B3_ASSERT( stages[iterationStageIndex].type == b3_stageIntegratePositions ); B3_ASSERT( stages[iterationStageIndex].type == b3_stageIntegratePositions );
syncBits = ( bodySyncIndex << 16 ) | iterationStageIndex; syncBits = ( bodySyncIndex << 16 ) | iterationStageIndex;
@ -1427,6 +1440,16 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
int awakeBodyCount = awakeSet->bodySims.count; int awakeBodyCount = awakeSet->bodySims.count;
if ( awakeBodyCount == 0 ) if ( awakeBodyCount == 0 )
{ {
// GameCult fork: the external solver still runs its substeps
if ( world->subStepFcn != NULL )
{
world->inSubStep = true;
for ( int i = 0; i < stepContext->subStepCount; ++i )
{
world->subStepFcn( b3MakeWorldIdFromWorld( world ), i, stepContext->h, world->subStepContext );
}
world->inSubStep = false;
}
b3ValidateNoEnlarged( &world->broadPhase ); b3ValidateNoEnlarged( &world->broadPhase );
return; return;
} }

View file

@ -995,6 +995,174 @@ static int TestExplosion( void )
return 0; return 0;
} }
static int s_hookCalls;
static int s_hookBad;
static float ZeroFrictionHook( void* userDataA, void* userDataB, b3Vec3 localA, b3Vec3 localB, float mixed, void* context )
{
// Ground is body A (user data 1), box is body B (user data 2); the box rests 1 m above its ground contact point.
s_hookCalls += 1;
if ( userDataA != (void*)(intptr_t)1 || userDataB != (void*)(intptr_t)2 || b3AbsFloat( localB.y + 1.0f ) > 0.1f ||
b3AbsFloat( mixed - 0.6f ) > 1.0e-5f || context != &s_hookCalls )
{
s_hookBad += 1;
}
return 0.0f;
}
static float SlideSpeed( bool hooked )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.gravity = (b3Vec3){ 0.0f, -10.0f, 0.0f };
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.position = (b3Pos){ 0.0f, -10.0f, 0.0f };
groundDef.userData = (void*)(intptr_t)1;
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 10.0f, 50.0f );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.6f;
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 1.0f, 0.0f };
bodyDef.linearVelocity = (b3Vec3){ 5.0f, 0.0f, 0.0f };
bodyDef.userData = (void*)(intptr_t)2;
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3BoxHull box = b3MakeCubeHull( 1.0f );
shapeDef.density = 1.0f;
b3CreateHullShape( bodyId, &shapeDef, &box.base );
if ( hooked )
{
b3World_SetContactFrictionCallback( worldId, ZeroFrictionHook, &s_hookCalls );
}
for ( int i = 0; i < 60; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
float speed = b3Body_GetLinearVelocity( bodyId ).x;
b3DestroyWorld( worldId );
return speed;
}
// Run by name: `test.exe WorldTest` (the unfiltered run stops at CompoundTest, which fails at fb719c4 as well: CompoundMaterialDedup).
int ContactFrictionHookTest( void )
{
s_hookCalls = 0;
s_hookBad = 0;
float dry = SlideSpeed( false );
ENSURE( s_hookCalls == 0 );
ENSURE( dry < 0.5f );
float slick = SlideSpeed( true );
ENSURE( s_hookCalls > 0 );
ENSURE( s_hookBad == 0 );
ENSURE( slick > 4.9f );
return 0;
}
static float SwitchHook( void* userDataA, void* userDataB, b3Vec3 localA, b3Vec3 localB, float mixed, void* context )
{
return *(bool*)context ? 0.0f : mixed;
}
// A box rests for 30 ticks under no push, the hook's answer changes, then a push of 30 N (below mu m g = 48 N) runs for 30 ticks. The
// contact is recycled all the while the box rests, so the answer reaches it only if the hook runs on recycled contacts too.
static float PushedSpeed( bool slickWhileResting, bool slickWhilePushed )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.gravity = (b3Vec3){ 0.0f, -10.0f, 0.0f };
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef groundDef = b3DefaultBodyDef();
groundDef.position = (b3Pos){ 0.0f, -10.0f, 0.0f };
b3BodyId groundId = b3CreateBody( worldId, &groundDef );
b3BoxHull groundBox = b3MakeBoxHull( 50.0f, 10.0f, 50.0f );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.6f;
b3CreateHullShape( groundId, &shapeDef, &groundBox.base );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = (b3Pos){ 0.0f, 1.0f, 0.0f };
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
b3BoxHull box = b3MakeCubeHull( 1.0f );
shapeDef.density = 1.0f;
b3CreateHullShape( bodyId, &shapeDef, &box.base );
bool slick = slickWhileResting;
b3World_SetContactFrictionCallback( worldId, SwitchHook, &slick );
for ( int i = 0; i < 30; ++i )
{
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
slick = slickWhilePushed;
for ( int i = 0; i < 30; ++i )
{
b3Body_ApplyForceToCenter( bodyId, (b3Vec3){ 30.0f, 0.0f, 0.0f }, true );
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
float speed = b3Body_GetLinearVelocity( bodyId ).x;
b3DestroyWorld( worldId );
return speed;
}
int ContactFrictionRecycledTest( void )
{
// Friction lowered under a box that has rested: it slides. Friction restored under a box that rested on the lowered value: it holds.
ENSURE( PushedSpeed( false, true ) > 1.0f );
ENSURE( PushedSpeed( true, false ) < 0.05f );
ENSURE( PushedSpeed( false, false ) < 0.05f );
return 0;
}
// GameCult fork. A body whose proxy was enlarged in the last step is destroyed before the next step, and it was
// the only proxy in the move buffer. Its ancestors in the dynamic tree are still flagged enlarged, so the next
// step must still rebuild the tree: with validation on, a skipped rebuild trips ValidateNoEnlarged in the solver.
int DestroyEnlargedProxyTest( void )
{
b3WorldDef worldDef = b3DefaultWorldDef();
worldDef.gravity = b3Vec3_zero;
b3WorldId worldId = b3CreateWorld( &worldDef );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
b3ShapeDef shapeDef = b3DefaultShapeDef();
b3Sphere sphere = { b3Vec3_zero, 0.25f };
// Resting bodies far apart: they never leave their fat AABBs, so after the first step only the mover is buffered.
enum
{
e_count = 8
};
b3BodyId bodyIds[e_count];
for ( int i = 0; i < e_count; ++i )
{
bodyDef.position = (b3Pos){ 4.0f * i, 0.0f, 0.0f };
bodyIds[i] = b3CreateBody( worldId, &bodyDef );
b3CreateSphereShape( bodyIds[i], &shapeDef, &sphere );
}
b3World_Step( worldId, 1.0f / 60.0f, 4 );
// Each body in turn is the mover; some lie deep enough that an enlarged ancestor outlives their removal.
for ( int i = 0; i < e_count; ++i )
{
b3Body_SetLinearVelocity( bodyIds[i], (b3Vec3){ 0.0f, 30.0f, 0.0f } );
b3World_Step( worldId, 1.0f / 60.0f, 4 );
b3DestroyBody( bodyIds[i] );
b3World_Step( worldId, 1.0f / 60.0f, 4 );
}
b3DestroyWorld( worldId );
return 0;
}
int WorldTest( void ) int WorldTest( void )
{ {
RUN_SUBTEST( HelloWorld ); RUN_SUBTEST( HelloWorld );
@ -1016,6 +1184,9 @@ int WorldTest( void )
RUN_SUBTEST( EnableContactRecyclingTest ); RUN_SUBTEST( EnableContactRecyclingTest );
RUN_SUBTEST( TestSetWorkerCount ); RUN_SUBTEST( TestSetWorkerCount );
RUN_SUBTEST( TestHullDatabase ); RUN_SUBTEST( TestHullDatabase );
RUN_SUBTEST( ContactFrictionHookTest );
RUN_SUBTEST( ContactFrictionRecycledTest );
RUN_SUBTEST( DestroyEnlargedProxyTest );
return 0; return 0;
} }