Added a compile time option to use double precision body positions. Most
math remains single precision with minimal performance loss.

`BOX3D_DOUBLE_PRECISION`

Improved accuracy of body inertia computation when shapes are far from
the body origin.

WARNING: several APIs changed but migration should be straight forward
if doubles are not enabled.
This commit is contained in:
Erin Catto 2026-06-18 20:51:16 -07:00 • committed by GitHub
commit 09c65b08ea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
115 changed files with 7591 additions and 5295 deletions

View file

@ -149,10 +149,16 @@ if(BOX3D_VALIDATE)
endif()
if (BOX3D_DISABLE_SIMD)
message(STATUS "Box3D SIMD disabled")
message(STATUS "Box3D SIMD disabled")
target_compile_definitions(box3d PRIVATE BOX3D_DISABLE_SIMD)
endif()
if (BOX3D_DOUBLE_PRECISION)
message(STATUS "Box3D double precision ON")
# PUBLIC: consumers must see the same precision mode in the headers or they cannot match the ABI
target_compile_definitions(box3d PUBLIC BOX3D_DOUBLE_PRECISION)
endif()
if (MSVC)
message(STATUS "Box3D on MSVC")
if (BUILD_SHARED_LIBS)

View file

@ -33,14 +33,14 @@ b3Body* b3GetBodyFullId( b3World* world, b3BodyId bodyId )
return b3Array_Get( world->bodies, bodyId.index1 - 1 );
}
b3Transform b3GetBodyTransformQuick( b3World* world, b3Body* body )
b3WorldTransform b3GetBodyTransformQuick( b3World* world, b3Body* body )
{
b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex );
b3BodySim* bodySim = b3Array_Get( set->bodySims, body->localIndex );
return bodySim->transform;
}
b3Transform b3GetBodyTransform( b3World* world, int bodyId )
b3WorldTransform b3GetBodyTransform( b3World* world, int bodyId )
{
b3Body* body = b3Array_Get( world->bodies, bodyId );
return b3GetBodyTransformQuick( world, body );
@ -71,7 +71,7 @@ b3BodyState* b3GetBodyState( b3World* world, b3Body* body )
return NULL;
}
static void b3SyncBodyFlags(b3World* world, b3Body* body)
static void b3SyncBodyFlags( b3World* world, b3Body* body )
{
// Never sync transient flags
uint32_t flags = body->flags & ~b3_bodyTransientFlags;
@ -80,7 +80,7 @@ static void b3SyncBodyFlags(b3World* world, b3Body* body)
bodySim->flags = flags;
b3BodyState* bodyState = b3GetBodyState( world, body );
if (bodyState != NULL)
if ( bodyState != NULL )
{
bodyState->flags = flags;
}
@ -156,7 +156,7 @@ static void b3DestroyBodyContacts( b3World* world, b3Body* body, bool wakeBodies
b3BodyId b3CreateBody( b3WorldId worldId, const b3BodyDef* def )
{
B3_CHECK_DEF( def );
B3_ASSERT( b3IsValidVec3( def->position ) );
B3_ASSERT( b3IsValidPosition( def->position ) );
B3_ASSERT( b3IsValidQuat( def->rotation ) );
B3_ASSERT( b3IsValidVec3( def->linearVelocity ) );
B3_ASSERT( b3IsValidVec3( def->angularVelocity ) );
@ -508,8 +508,9 @@ b3AABB b3Body_ComputeAABB( b3BodyId bodyId )
b3Body* body = b3GetBodyFullId( world, bodyId );
if ( body->headShapeId == B3_NULL_INDEX )
{
b3Transform transform = b3GetBodyTransform( world, body->id );
return (b3AABB){ transform.p, transform.p };
b3WorldTransform transform = b3GetBodyTransform( world, body->id );
b3Vec3 p = b3ToVec3( transform.p );
return (b3AABB){ p, p };
}
b3Shape* shape = b3Array_Get( world->shapes, body->headShapeId );
@ -533,15 +534,17 @@ float b3Body_GetClosestPoint( b3BodyId bodyId, b3Vec3* result, b3Vec3 target )
}
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransform( world, body->id );
b3WorldTransform worldTransform = b3GetBodyTransform( world, body->id );
b3Transform transform = b3ToRelativeTransform( worldTransform, b3Pos_zero );
float closestDistance = FLT_MAX;
b3Vec3 closestPoint = transform.p;
b3DistanceInput input = { 0 };
input.proxyA = (b3ShapeProxy){ &target, 1, 0.0f };
input.transformA.q = b3Quat_identity;
input.transformB = transform;
// Target rides in frame A at the origin, so the relative pose of the shape in A is the body transform
input.transform = transform;
input.useRadii = false;
int shapeId = body->headShapeId;
@ -571,7 +574,8 @@ float b3Body_GetClosestPoint( b3BodyId bodyId, b3Vec3* result, b3Vec3 target )
return closestDistance;
}
b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, const b3BodyRayCastInput* input, b3Transform bodyTransform )
b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter, float maxFraction,
b3WorldTransform bodyTransform )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
@ -582,128 +586,13 @@ b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, const b3BodyRayCastInput* inpu
b3BodyCastResult result = { 0 };
b3Body* body = b3GetBodyFullId( world, bodyId );
// The consistent framing is to center on the ray origin.
b3RayCastInput shapeInput = { 0 };
shapeInput.origin = input->origin;
shapeInput.translation = input->translation;
shapeInput.maxFraction = input->maxFraction;
shapeInput.origin = b3Vec3_zero;
shapeInput.translation = translation;
shapeInput.maxFraction = maxFraction;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
shapeId = shape->nextShapeId;
if ( b3ShouldQueryCollide( &shape->filter, &input->filter ) == false )
{
continue;
}
b3CastOutput shapeOutput = b3RayCastShape( shape, bodyTransform, &shapeInput );
if ( shapeOutput.hit == false )
{
continue;
}
if ( shapeOutput.fraction > shapeInput.maxFraction )
{
continue;
}
// Careful with id, shapeId is the next shape.
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
result = (b3BodyCastResult){
.shapeId = id,
.point = shapeOutput.point,
.normal = shapeOutput.normal,
.fraction = shapeOutput.fraction,
.triangleIndex = shapeOutput.triangleIndex,
.userMaterialId = userMaterialId,
.iterations = shapeOutput.iterations,
.hit = true,
};
shapeInput.maxFraction = shapeOutput.fraction;
}
return result;
}
b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, const b3BodyShapeCastInput* input, b3Transform bodyTransform )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
{
return (b3BodyCastResult){ 0 };
}
b3BodyCastResult result = { 0 };
b3Body* body = b3GetBodyFullId( world, bodyId );
b3ShapeCastInput shapeInput = { 0 };
shapeInput.proxy = input->proxy;
shapeInput.translation = input->translation;
shapeInput.maxFraction = input->maxFraction;
shapeInput.canEncroach = input->canEncroach;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
shapeId = shape->nextShapeId;
if ( b3ShouldQueryCollide( &shape->filter, &input->filter ) == false )
{
continue;
}
b3CastOutput shapeOutput = b3ShapeCastShape( shape, bodyTransform, &shapeInput );
if ( shapeOutput.hit == false )
{
continue;
}
if ( shapeOutput.fraction > shapeInput.maxFraction )
{
continue;
}
// Careful with id, shapeId is the next shape.
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
result = (b3BodyCastResult){
.shapeId = id,
.point = shapeOutput.point,
.normal = shapeOutput.normal,
.fraction = shapeOutput.fraction,
.triangleIndex = shapeOutput.triangleIndex,
.userMaterialId = userMaterialId,
.iterations = shapeOutput.iterations,
.hit = true,
};
shapeInput.maxFraction = shapeOutput.fraction;
}
return result;
}
bool b3Body_OverlapShape( b3BodyId bodyId, const b3ShapeProxy* proxy, b3QueryFilter filter, b3Transform bodyTransform )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
{
return false;
}
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3ToRelativeTransform( bodyTransform, origin );
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
@ -716,7 +605,130 @@ bool b3Body_OverlapShape( b3BodyId bodyId, const b3ShapeProxy* proxy, b3QueryFil
continue;
}
bool overlaps = b3OverlapShape( shape, bodyTransform, proxy );
b3CastOutput shapeOutput = b3RayCastShape( shape, transform, &shapeInput );
if ( shapeOutput.hit == false )
{
continue;
}
if ( shapeOutput.fraction > shapeInput.maxFraction )
{
continue;
}
// Careful with id, shapeId is the next shape.
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
result = (b3BodyCastResult){
.shapeId = id,
.point = b3OffsetPos( origin, shapeOutput.point ),
.normal = shapeOutput.normal,
.fraction = shapeOutput.fraction,
.triangleIndex = shapeOutput.triangleIndex,
.userMaterialId = userMaterialId,
.iterations = shapeOutput.iterations,
.hit = true,
};
shapeInput.maxFraction = shapeOutput.fraction;
}
return result;
}
b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, b3Pos origin, const b3ShapeProxy* proxy, b3Vec3 translation,
b3QueryFilter filter, float maxFraction, bool canEncroach, b3WorldTransform bodyTransform )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
{
return (b3BodyCastResult){ 0 };
}
b3BodyCastResult result = { 0 };
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3ToRelativeTransform( bodyTransform, origin );
b3ShapeCastInput shapeInput = { 0 };
shapeInput.proxy = *proxy;
shapeInput.translation = translation;
shapeInput.maxFraction = maxFraction;
shapeInput.canEncroach = canEncroach;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
shapeId = shape->nextShapeId;
if ( b3ShouldQueryCollide( &shape->filter, &filter ) == false )
{
continue;
}
b3CastOutput shapeOutput = b3ShapeCastShape( shape, transform, &shapeInput );
if ( shapeOutput.hit == false )
{
continue;
}
if ( shapeOutput.fraction > shapeInput.maxFraction )
{
continue;
}
// Careful with id, shapeId is the next shape.
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
int materialIndex = b3ClampInt( shapeOutput.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
result = (b3BodyCastResult){
.shapeId = id,
.point = b3OffsetPos( origin, shapeOutput.point ),
.normal = shapeOutput.normal,
.fraction = shapeOutput.fraction,
.triangleIndex = shapeOutput.triangleIndex,
.userMaterialId = userMaterialId,
.iterations = shapeOutput.iterations,
.hit = true,
};
shapeInput.maxFraction = shapeOutput.fraction;
}
return result;
}
bool b3Body_OverlapShape( b3BodyId bodyId, b3Pos origin, const b3ShapeProxy* proxy, b3QueryFilter filter,
b3WorldTransform bodyTransform )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
{
return false;
}
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3ToRelativeTransform( bodyTransform, origin );
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
shapeId = shape->nextShapeId;
if ( b3ShouldQueryCollide( &shape->filter, &filter ) == false )
{
continue;
}
bool overlaps = b3OverlapShape( shape, transform, proxy );
if ( overlaps )
{
return true;
@ -726,8 +738,8 @@ bool b3Body_OverlapShape( b3BodyId bodyId, const b3ShapeProxy* proxy, b3QueryFil
return false;
}
int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, const b3Capsule* mover,
b3QueryFilter filter, b3Transform bodyTransform )
int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, b3Pos origin, const b3Capsule* mover,
b3QueryFilter filter, b3WorldTransform bodyTransform )
{
b3World* world = b3GetUnlockedWorld( bodyId.world0 );
if ( world == NULL )
@ -743,6 +755,8 @@ int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int pla
int resultCount = 0;
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3ToRelativeTransform( bodyTransform, origin );
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
@ -761,11 +775,11 @@ int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int pla
}
b3PlaneResult plane;
int count = b3CollideMover( &plane, 1, shape, bodyTransform, mover );
int count = b3CollideMover( &plane, 1, shape, transform, mover );
if ( count > 0 )
{
b3ShapeId id = { shape->id + 1, world->worldId, shape->generation };
b3ShapeId id = { shape->id + 1, bodyId.world0, shape->generation };
bodyPlanes[resultCount] = (b3BodyPlaneResult){ .shapeId = id, .result = plane };
resultCount += 1;
if ( resultCount == planeCapacity )
@ -823,9 +837,13 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
return;
}
int shapeCount = body->shapeCount;
b3MassData* masses = b3StackAlloc( &world->stack, shapeCount * sizeof( b3MassData ), "mass data" );
// Accumulate mass over all shapes.
b3Vec3 localCenter = b3Vec3_zero;
int shapeId = body->headShapeId;
int shapeIndex = 0;
while ( shapeId != B3_NULL_INDEX )
{
const b3Shape* s = b3Array_Get( world->shapes, shapeId );
@ -833,13 +851,17 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
if ( s->density == 0.0f )
{
masses[shapeIndex] = (b3MassData){ 0 };
shapeIndex += 1;
continue;
}
b3MassData massData = b3ComputeShapeMass( s );
body->mass += massData.mass;
localCenter = b3MulAdd( localCenter, massData.mass, massData.center );
body->inertia = b3AddMM( body->inertia, massData.inertia );
masses[shapeIndex] = massData;
shapeIndex += 1;
}
// Compute center of mass.
@ -847,10 +869,31 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
{
bodySim->invMass = 1.0f / body->mass;
localCenter = b3MulSV( bodySim->invMass, localCenter );
}
// Shift inertia to mass center
body->inertia = b3SubMM( body->inertia, b3Steiner( body->mass, localCenter ) );
// Second loop to accumulate the rotational inertia about the center of mass
for ( shapeIndex = 0; shapeIndex < shapeCount; ++shapeIndex )
{
b3MassData massData = masses[shapeIndex];
if ( massData.mass == 0.0f )
{
continue;
}
// Shift to center of mass. This is safe because it can only increase.
b3Vec3 offset = b3Sub( localCenter, massData.center );
b3Matrix3 inertia = b3AddMM( massData.inertia, b3Steiner( massData.mass, offset ) );
body->inertia = b3AddMM(body->inertia, inertia);
}
b3StackFree( &world->stack, masses );
masses = NULL;
float det = b3Det( body->inertia );
B3_ASSERT( det >= 0.0f );
if ( det > 0.0f )
{
// This call is faster than b3Invert
bodySim->invInertiaLocal = b3InvertT( body->inertia );
@ -859,16 +902,16 @@ void b3UpdateBodyMassData( b3World* world, b3Body* body )
}
// Move center of mass.
b3Vec3 oldCenter = bodySim->center;
b3Pos oldCenter = bodySim->center;
bodySim->localCenter = localCenter;
bodySim->center = b3TransformPoint( bodySim->transform, bodySim->localCenter );
bodySim->center = b3TransformWorldPoint( bodySim->transform, bodySim->localCenter );
bodySim->center0 = bodySim->center;
// Update center of mass velocity
b3BodyState* state = b3GetBodyState( world, body );
if ( state != NULL )
{
b3Vec3 deltaLinear = b3Cross( state->angularVelocity, b3Sub( bodySim->center, oldCenter ) );
b3Vec3 deltaLinear = b3Cross( state->angularVelocity, b3SubPos( bodySim->center, oldCenter ) );
state->linearVelocity = b3Add( state->linearVelocity, deltaLinear );
}
@ -899,7 +942,7 @@ void b3DumpBody( b3World* world, b3Body* body )
// int32 bodyIndex = m_islandIndex;
b3BodySim* sim = b3GetBodySim( world, body );
b3Vec3 p = sim->transform.p;
b3Vec3 p = b3ToVec3( sim->transform.p );
b3Quat q = sim->transform.q;
b3Vec3 v = b3Vec3_zero;
@ -946,11 +989,11 @@ void b3DumpBody( b3World* world, b3Body* body )
b3Dump( "}\n" );
}
b3Vec3 b3Body_GetPosition( b3BodyId bodyId )
b3Pos b3Body_GetPosition( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
return transform.p;
}
@ -958,38 +1001,38 @@ b3Quat b3Body_GetRotation( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
return transform.q;
}
b3Transform b3Body_GetTransform( b3BodyId bodyId )
b3WorldTransform b3Body_GetTransform( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
return b3GetBodyTransformQuick( world, body );
}
b3Vec3 b3Body_GetLocalPoint( b3BodyId bodyId, b3Vec3 worldPoint )
b3Vec3 b3Body_GetLocalPoint( b3BodyId bodyId, b3Pos worldPoint )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
return b3InvTransformPoint( transform, worldPoint );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
return b3InvTransformWorldPoint( transform, worldPoint );
}
b3Vec3 b3Body_GetWorldPoint( b3BodyId bodyId, b3Vec3 localPoint )
b3Pos b3Body_GetWorldPoint( b3BodyId bodyId, b3Vec3 localPoint )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
return b3TransformPoint( transform, localPoint );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
return b3TransformWorldPoint( transform, localPoint );
}
b3Vec3 b3Body_GetLocalVector( b3BodyId bodyId, b3Vec3 worldVector )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
return b3InvRotateVector( transform.q, worldVector );
}
@ -997,13 +1040,13 @@ b3Vec3 b3Body_GetWorldVector( b3BodyId bodyId, b3Vec3 localVector )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
return b3RotateVector( transform.q, localVector );
}
void b3Body_SetTransform( b3BodyId bodyId, b3Vec3 position, b3Quat rotation )
void b3Body_SetTransform( b3BodyId bodyId, b3Pos position, b3Quat rotation )
{
B3_ASSERT( b3IsValidVec3( position ) );
B3_ASSERT( b3IsValidPosition( position ) );
B3_ASSERT( b3IsValidQuat( rotation ) );
B3_ASSERT( b3Body_IsValid( bodyId ) );
b3World* world = b3GetWorld( bodyId.world0 );
@ -1014,7 +1057,7 @@ void b3Body_SetTransform( b3BodyId bodyId, b3Vec3 position, b3Quat rotation )
bodySim->transform.p = position;
bodySim->transform.q = rotation;
bodySim->center = b3TransformPoint( bodySim->transform, bodySim->localCenter );
bodySim->center = b3TransformWorldPoint( bodySim->transform, bodySim->localCenter );
b3Matrix3 rotationMatrix = b3MakeMatrixFromQuat( bodySim->transform.q );
bodySim->invInertiaWorld = b3MulMM( b3MulMM( rotationMatrix, bodySim->invInertiaLocal ), b3Transpose( rotationMatrix ) );
@ -1024,20 +1067,14 @@ void b3Body_SetTransform( b3BodyId bodyId, b3Vec3 position, b3Quat rotation )
b3BroadPhase* broadPhase = &world->broadPhase;
b3Transform transform = bodySim->transform;
b3WorldTransform transform = bodySim->transform;
const float speculativeDistance = B3_SPECULATIVE_DISTANCE;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
b3AABB aabb = b3ComputeShapeAABB( shape, transform );
aabb.lowerBound.x -= speculativeDistance;
aabb.lowerBound.y -= speculativeDistance;
aabb.lowerBound.z -= speculativeDistance;
aabb.upperBound.x += speculativeDistance;
aabb.upperBound.y += speculativeDistance;
aabb.upperBound.z += speculativeDistance;
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeDistance );
shape->aabb = aabb;
if ( b3AABB_Contains( shape->fatAABB, aabb ) == false )
@ -1145,9 +1182,9 @@ void b3Body_SetAngularVelocity( b3BodyId bodyId, b3Vec3 angularVelocity )
state->angularVelocity = w;
}
void b3Body_SetTargetTransform( b3BodyId bodyId, b3Transform target, float timeStep, bool wake )
void b3Body_SetTargetTransform( b3BodyId bodyId, b3WorldTransform target, float timeStep, bool wake )
{
B3_ASSERT( b3IsValidTransform( target ) );
B3_ASSERT( b3IsValidWorldTransform( target ) );
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -1169,11 +1206,11 @@ void b3Body_SetTargetTransform( b3BodyId bodyId, b3Transform target, float timeS
b3BodySim* sim = b3GetBodySim( world, body );
// Compute linear velocity
b3Vec3 center1 = sim->center;
b3Vec3 center2 = b3TransformPoint( target, sim->localCenter );
// Compute linear velocity. The center difference is taken in world precision then demoted.
b3Pos center1 = sim->center;
b3Pos center2 = b3TransformWorldPoint( target, sim->localCenter );
float invTimeStep = 1.0f / timeStep;
b3Vec3 linearVelocity = b3MulSV( invTimeStep, b3Sub( center2, center1 ) );
b3Vec3 linearVelocity = b3MulSV( invTimeStep, b3SubPos( center2, center1 ) );
// Compute angular velocity:
// q' = 0.5 * w * q
@ -1232,7 +1269,7 @@ b3Vec3 b3Body_GetLocalPointVelocity( b3BodyId bodyId, b3Vec3 localPoint )
return v;
}
b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Vec3 worldPoint )
b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Pos worldPoint )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -1245,12 +1282,12 @@ b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Vec3 worldPoint )
b3SolverSet* set = b3Array_Get( world->solverSets, body->setIndex );
b3BodySim* bodySim = b3Array_Get( set->bodySims, body->localIndex );
b3Vec3 r = b3Sub( worldPoint, bodySim->center );
b3Vec3 r = b3SubPos( worldPoint, bodySim->center );
b3Vec3 v = b3Add( state->linearVelocity, b3Cross( state->angularVelocity, r ) );
return v;
}
void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Vec3 point, bool wake )
void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Pos point, bool wake )
{
B3_ASSERT( b3IsValidVec3( force ) );
@ -1266,7 +1303,7 @@ void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Vec3 point, bool wake )
{
b3BodySim* bodySim = b3GetBodySim( world, body );
bodySim->force = b3Add( bodySim->force, force );
bodySim->torque = b3Add( bodySim->torque, b3Cross( b3Sub( point, bodySim->center ), force ) );
bodySim->torque = b3Add( bodySim->torque, b3Cross( b3SubPos( point, bodySim->center ), force ) );
}
}
@ -1308,10 +1345,10 @@ void b3Body_ApplyTorque( b3BodyId bodyId, b3Vec3 torque, bool wake )
}
}
void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Vec3 point, bool wake )
void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Pos point, bool wake )
{
B3_ASSERT( b3IsValidVec3( impulse ) );
B3_ASSERT( b3IsValidVec3( point ) );
B3_ASSERT( b3IsValidPosition( point ) );
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -1336,7 +1373,7 @@ void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Vec3 point, b
state->linearVelocity = b3MulSV( maxLinearSpeed, b3Normalize( state->linearVelocity ) );
}
b3Vec3 delta = b3MulMV( bodySim->invInertiaWorld, b3Cross( b3Sub( point, bodySim->center ), impulse ) );
b3Vec3 delta = b3MulMV( bodySim->invInertiaWorld, b3Cross( b3SubPos( point, bodySim->center ), impulse ) );
state->angularVelocity = b3Add( state->angularVelocity, delta );
}
}
@ -1597,7 +1634,7 @@ void b3Body_SetType( b3BodyId bodyId, b3BodyType type )
}
// Recreate shape proxies in broadphase
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
{
@ -1729,7 +1766,7 @@ b3Vec3 b3Body_GetLocalCenterOfMass( b3BodyId bodyId )
return bodySim->localCenter;
}
b3Vec3 b3Body_GetWorldCenterOfMass( b3BodyId bodyId )
b3Pos b3Body_GetWorldCenterOfMass( b3BodyId bodyId )
{
b3World* world = b3GetWorld( bodyId.world0 );
b3Body* body = b3GetBodyFullId( world, bodyId );
@ -1756,7 +1793,7 @@ void b3Body_SetMassData( b3BodyId bodyId, b3MassData massData )
body->inertia = massData.inertia;
bodySim->localCenter = massData.center;
b3Vec3 center = b3TransformPoint( bodySim->transform, massData.center );
b3Pos center = b3TransformWorldPoint( bodySim->transform, massData.center );
bodySim->center = center;
bodySim->center0 = center;
@ -2048,7 +2085,7 @@ void b3Body_Enable( b3BodyId bodyId )
b3TransferBody( world, targetSet, disabledSet, body );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
// Add shapes to broad-phase
b3BodyType proxyType = body->type;

View file

@ -180,15 +180,15 @@ static const b3BodyState b3_identityBodyState = {
// Transform data used for collision and solver preparation.
typedef struct b3BodySim
{
// transform for body origin
b3Transform transform;
// transform for body origin, double translation in large world mode
b3WorldTransform transform;
// center of mass position in world space
b3Vec3 center;
b3Pos center;
// previous rotation and COM for TOI
b3Quat rotation0;
b3Vec3 center0;
b3Pos center0;
// location of center of mass relative to the body origin
b3Vec3 localCenter;
@ -220,8 +220,8 @@ typedef struct b3BodySim
// Get a validated body from a world using an id.
b3Body* b3GetBodyFullId( b3World* world, b3BodyId bodyId );
b3Transform b3GetBodyTransformQuick( b3World* world, b3Body* body );
b3Transform b3GetBodyTransform( b3World* world, int bodyId );
b3WorldTransform b3GetBodyTransformQuick( b3World* world, b3Body* body );
b3WorldTransform b3GetBodyTransform( b3World* world, int bodyId );
// Create a b3BodyId from a raw id.
b3BodyId b3MakeBodyId( b3World* world, int bodyId );
@ -239,11 +239,12 @@ bool b3WakeBodyWithLock( b3World* world, b3Body* body );
void b3UpdateBodyMassData( b3World* world, b3Body* body );
void b3DumpBody( b3World* world, b3Body* body );
static inline b3Sweep b3MakeSweep( const b3BodySim* bodySim )
// Make a sweep relative to a base position to keep TOI in float precision far from the origin.
static inline b3Sweep b3MakeRelativeSweep( const b3BodySim* bodySim, b3Pos base )
{
b3Sweep s;
s.c1 = bodySim->center0;
s.c2 = bodySim->center;
s.c1 = b3SubPos( bodySim->center0, base );
s.c2 = b3SubPos( bodySim->center, base );
s.q1 = bodySim->rotation0;
s.q2 = bodySim->transform.q;
s.localCenter = bodySim->localCenter;

View file

@ -14,6 +14,15 @@
<DisplayString>[ {v}, {s} ]</DisplayString>
</Type>
<!-- Distinct types only in BOX3D_DOUBLE_PRECISION builds; otherwise they alias b3Vec3 / b3Transform -->
<Type Name="b3Pos">
<DisplayString>[ {x}, {y}, {z} ]</DisplayString>
</Type>
<Type Name="b3WorldTransform">
<DisplayString>[ {p}, {q} ]</DisplayString>
</Type>
<Type Name="b3WorldId">
<DisplayString>index: {index1}</DisplayString>
<Expand>

View file

@ -176,7 +176,8 @@ static bool b3PairQueryCallback( int proxyId, uint64_t userData, void* context )
b3Shape* shape = b3Array_Get( world->shapes, shapeIndex );
if ( shape->type == b3_compoundShape )
{
b3Transform compoundTransform = b3GetBodyTransform( world, shape->bodyId );
// Query bounds are float world space, so the demoted transform is the matching float frame
b3Transform compoundTransform = b3ToRelativeTransform( b3GetBodyTransform( world, shape->bodyId ), b3Pos_zero );
b3AABB localAABB = b3AABB_Transform( b3InvertTransform( compoundTransform ), queryContext->aabb );
// recurse

View file

@ -39,14 +39,15 @@ b3MassData b3ComputeCapsuleMass( const b3Capsule* shape, float density )
rotation = b3MakeMatrixFromQuat( q );
}
// Parallel Axis Theorem capsule
float mass = sphereMass + cylinderMass;
b3Vec3 center = b3MulSV( 0.5f, b3Add( c1, c2 ) );
b3MassData out;
out.mass = mass;
out.center = center;
out.inertia = b3AddMM( b3MulMM( rotation, b3MulMM( inertia, b3Transpose( rotation ) ) ), b3Steiner( mass, center ) );
// Rotate the central inertia into the shape frame
out.inertia = b3MulMM( rotation, b3MulMM( inertia, b3Transpose( rotation ) ) );
return out;
}
@ -106,8 +107,7 @@ bool b3OverlapCapsule( const b3Capsule* shape, b3Transform shapeTransform, const
b3DistanceInput input;
input.proxyA = (b3ShapeProxy){ &shape->center1, 2, shape->radius };
input.proxyB = *proxy;
input.transformA = shapeTransform;
input.transformB = b3Transform_identity;
input.transform = b3InvMulTransforms( shapeTransform, b3Transform_identity );
input.useRadii = true;
b3SimplexCache cache = { 0 };
@ -255,8 +255,7 @@ b3CastOutput b3ShapeCastCapsule( const b3Capsule* capsule, const b3ShapeCastInpu
b3ShapeCastPairInput pairInput;
pairInput.proxyA = (b3ShapeProxy){ &capsule->center1, 2, capsule->radius };
pairInput.proxyB = input->proxy;
pairInput.transformA = b3Transform_identity;
pairInput.transformB = b3Transform_identity;
pairInput.transform = b3Transform_identity;
pairInput.translationB = input->translation;
pairInput.maxFraction = input->maxFraction;
pairInput.canEncroach = input->canEncroach;

View file

@ -759,6 +759,8 @@ struct b3CompoundCastContext
{
const b3Compound* compound;
b3CastOutput* output;
// origin of the shape cast, the box cast callback only carries the advancing fraction
const b3ShapeCastInput* shapeInput;
};
static float b3CompoundRayCastCallback( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context )
@ -833,32 +835,35 @@ b3CastOutput b3RayCastCompound( const b3Compound* shape, const b3RayCastInput* i
return result;
}
static float b3CompoundShapeCastCallback( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context )
static float b3CompoundShapeCastCallback( const b3BoxCastInput* input, int proxyId, uint64_t userData, void* context )
{
B3_UNUSED( proxyId );
struct b3CompoundCastContext* castContext = context;
const b3Compound* compound = castContext->compound;
const b3ShapeCastInput* shapeInput = castContext->shapeInput;
int childIndex = (int)userData;
b3ChildShape child = b3GetCompoundChild( compound, childIndex );
b3ShapeCastInput localInput = *input;
// Rebuild from the carried shape cast input, taking only the advancing fraction from the tree
b3ShapeCastInput localInput = *shapeInput;
localInput.maxFraction = input->maxFraction;
b3Vec3 localPoints[B3_MAX_SHAPE_CAST_POINTS];
localInput.proxy.count = b3MinInt( input->proxy.count, B3_MAX_SHAPE_CAST_POINTS );
localInput.proxy.count = b3MinInt( shapeInput->proxy.count, B3_MAX_SHAPE_CAST_POINTS );
b3Transform invTransform = b3InvertTransform( child.transform );
b3Matrix3 R = b3MakeMatrixFromQuat( invTransform.q );
for ( int i = 0; i < localInput.proxy.count; ++i )
{
localPoints[i] = b3Add( b3MulMV( R, input->proxy.points[i] ), invTransform.p );
localPoints[i] = b3Add( b3MulMV( R, shapeInput->proxy.points[i] ), invTransform.p );
}
localInput.proxy.points = localPoints;
localInput.translation = b3MulMV( R, input->translation );
localInput.translation = b3MulMV( R, shapeInput->translation );
b3CastOutput output = { 0 };
@ -909,11 +914,21 @@ b3CastOutput b3ShapeCastCompound( const b3Compound* shape, const b3ShapeCastInpu
{
b3CastOutput result = { 0 };
if ( input->proxy.count == 0 )
{
return result;
}
struct b3CompoundCastContext context = {
.compound = shape,
.output = &result,
.shapeInput = input,
};
(void)b3DynamicTree_ShapeCast( &shape->tree, input, ~0ull, false, b3CompoundShapeCastCallback, &context );
// The compound tree is in the compound local frame, so the proxy box needs no origin offset
b3AABB box = b3MakeAABB( input->proxy.points, input->proxy.count, input->proxy.radius );
b3BoxCastInput treeInput = { box, input->translation, input->maxFraction };
(void)b3DynamicTree_BoxCast( &shape->tree, &treeInput, ~0ull, false, b3CompoundShapeCastCallback, &context );
return result;
}

View file

@ -471,8 +471,8 @@ void b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies )
}
}
static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, b3Transform xfA,
const b3Shape* shapeB, b3Transform xfB, b3Arena arena )
static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA,
b3WorldTransform xfA, const b3Shape* shapeB, b3WorldTransform xfB, b3Arena arena )
{
b3ShapeType typeA = shapeA->type;
b3ShapeType typeB = shapeB->type;
@ -485,7 +485,7 @@ static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact*
b3LocalManifold geomManifold = { 0 };
geomManifold.points = pointBuffer;
b3Transform transformBtoA = b3InvMulTransforms( xfA, xfB );
b3Transform transformBtoA = b3InvMulWorldTransforms( xfA, xfB );
if ( typeA == b3_sphereShape )
{
@ -567,7 +567,7 @@ static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact*
// Contact points are computed in frame A
target->anchorA = b3MulMV( matrixA, source->point );
target->anchorB = b3Add( target->anchorA, b3Sub( xfA.p, xfB.p ) );
target->anchorB = b3Add( target->anchorA, b3SubPos( xfA.p, xfB.p ) );
target->separation = source->separation;
target->featureId = b3MakeFeatureId( source->pair );
target->triangleIndex = B3_NULL_INDEX;
@ -606,8 +606,8 @@ static bool b3ComputeConvexManifold( b3World* world, int workerIndex, b3Contact*
return true;
}
static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Transform xfA,
b3Shape* shapeB, b3Transform xfB, bool flip, b3Arena arena )
static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3WorldTransform xfA,
b3Shape* shapeB, b3WorldTransform xfB, bool flip, b3Arena arena )
{
// Compute new manifold
bool touching = b3ComputeConvexManifold( world, workerIndex, contact, shapeA, xfA, shapeB, xfB, arena );
@ -693,7 +693,7 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c
b3ShapeId shapeIdB = { shapeB->id + 1, world->worldId, shapeB->generation };
// this call assumes thread safety
b3Vec3 point = b3Add( contact->manifolds[0].points[0].anchorA, xfA.p );
b3Pos point = b3OffsetPos( xfA.p, contact->manifolds[0].points[0].anchorA );
b3Vec3 normal = contact->manifolds[0].normal;
touching = world->preSolveFcn( shapeIdA, shapeIdB, point, normal, world->preSolveContext );
if ( touching == false )
@ -720,8 +720,8 @@ static bool b3UpdateConvexContact( b3World* world, int workerIndex, b3Contact* c
// Update the contact manifold and touching status.
// Note: do not assume the shape AABBs are overlapping or are valid.
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3Transform xfA,
b3Shape* shapeB, b3Vec3 localCenterB, b3Transform xfB, bool isFast, b3Arena arena )
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3WorldTransform xfA,
b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast, b3Arena arena )
{
bool touching;
@ -756,14 +756,14 @@ bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Sha
else if ( child.type == b3_hullShape )
{
childShapeA.hull = child.hull;
b3Transform xfChild = b3MulTransforms( xfA, child.transform );
b3WorldTransform xfChild = b3MulWorldTransforms( xfA, child.transform );
bool flip = false;
touching = b3UpdateConvexContact( world, workerIndex, contact, &childShapeA, xfChild, shapeB, xfB, flip, arena );
}
else if ( child.type == b3_meshShape )
{
childShapeA.mesh = child.mesh;
b3Transform xfChild = b3MulTransforms( xfA, child.transform );
b3WorldTransform xfChild = b3MulWorldTransforms( xfA, child.transform );
touching = b3ComputeMeshManifolds( world, workerIndex, contact, &childShapeA, child.materialIndices, xfChild, shapeB,
xfB, isFast, arena );

View file

@ -133,8 +133,10 @@ typedef struct b3Contact
b3Manifold* manifolds;
int manifoldCount;
b3Transform cachedTransformA;
b3Transform cachedTransformB;
// Cache for contact recycling.
b3Quat cachedRotationA;
b3Quat cachedRotationB;
b3Transform cachedRelativePose;
// Mixed friction and restitution
float friction;
@ -171,8 +173,8 @@ void b3InitializeContactRegisters( void );
void b3CreateContact( b3World* world, b3Shape* shapeA, b3Shape* shapeB, int childIndex );
void b3DestroyContact( b3World* world, b3Contact* contact, bool wakeBodies );
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3Transform xfA,
b3Shape* shapeB, b3Vec3 localCenterB, b3Transform xfB, bool isFast, b3Arena arena );
bool b3UpdateContact( b3World* world, int workerIndex, b3Contact* contact, b3Shape* shapeA, b3Vec3 localCenterA, b3WorldTransform xfA,
b3Shape* shapeB, b3Vec3 localCenterB, b3WorldTransform xfB, bool isFast, b3Arena arena );
bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, const int* materialMap,
b3Transform xfA, const b3Shape* shapeB, b3Transform xfB, bool isFast, b3Arena arena );
b3WorldTransform xfA, const b3Shape* shapeB, b3WorldTransform xfB, bool isFast, b3Arena arena );

View file

@ -586,8 +586,7 @@ void b3CollideHullAndSphere( b3LocalManifold* manifold, int capacity, const b3Hu
b3DistanceInput distanceInput;
distanceInput.proxyA = (b3ShapeProxy){ b3GetHullPoints( hullA ), hullA->vertexCount, 0.0f };
distanceInput.proxyB = (b3ShapeProxy){ &center, 1, 0.0f };
distanceInput.transformA = b3Transform_identity;
distanceInput.transformB = b3Transform_identity;
distanceInput.transform = b3Transform_identity;
distanceInput.useRadii = false;
float radiusA = 0.0f;
@ -948,8 +947,7 @@ void b3CollideHullAndCapsule( b3LocalManifold* manifold, int capacity, const b3H
b3DistanceInput distanceInput;
distanceInput.proxyA = (b3ShapeProxy){ b3GetHullPoints( hullA ), hullA->vertexCount, 0.0f };
distanceInput.proxyB = (b3ShapeProxy){ &capsuleB->center1, 2, 0.0f };
distanceInput.transformA = b3Transform_identity;
distanceInput.transformB = transformBtoA;
distanceInput.transform = transformBtoA;
distanceInput.useRadii = false;
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, cache, NULL, 0 );

View file

@ -105,6 +105,15 @@ b3Version b3GetVersion( void )
return (b3Version){ 0, 2, 0 };
}
bool b3IsDoublePrecision( void )
{
#if defined( BOX3D_DOUBLE_PRECISION )
return true;
#else
return false;
#endif
}
static b3AllocFcn* b3_allocFcn = NULL;
static b3FreeFcn* b3_freeFcn = NULL;

View file

@ -712,17 +712,12 @@ static void b3ComputeWitnessPoints( const b3Simplex* simplex, b3Vec3* vertexA, b
b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache* cache, b3Simplex* simplexes, int simplexCapacity )
{
// Build initial simplex
b3Transform transformA = input->transformA;
b3Transform transformB = input->transformB;
// Work in relative space
b3Transform xf = b3InvMulTransforms( transformA, transformB );
// The query runs in frame A using the relative pose of B in A.
b3Transform xf = input->transform;
// Use matrices for faster math
b3Matrix3 m = b3MakeMatrixFromQuat( xf.q );
b3Matrix3 mt = b3Transpose( m );
b3Matrix3 mA = b3MakeMatrixFromQuat( transformA.q );
const b3ShapeProxy* proxyA = &input->proxyA;
const b3ShapeProxy* proxyB = &input->proxyB;
@ -850,8 +845,8 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
// Overlap
b3Vec3 localPointA, localPointB;
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
distanceOutput.pointA = b3Add( b3MulMV( mA, localPointA ), transformA.p );
distanceOutput.pointB = b3Add( b3MulMV( mA, localPointB ), transformA.p );
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
return distanceOutput;
}
@ -946,8 +941,8 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
// Thus the shapes are overlapped.
b3Vec3 localPointA, localPointB;
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
distanceOutput.pointA = b3Add( b3MulMV( mA, localPointA ), transformA.p );
distanceOutput.pointB = b3Add( b3MulMV( mA, localPointB ), transformA.p );
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
B3_VALIDATE( b3Distance( localPointA, localPointB ) < FLT_EPSILON );
return distanceOutput;
}
@ -1001,10 +996,9 @@ b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache*
b3ComputeWitnessPoints( &simplex, &localPointA, &localPointB );
b3WriteCache( cache, &simplex );
// Convert results from frame A into world space
normal = b3MulMV( mA, normal );
distanceOutput.pointA = b3Add( b3MulMV( mA, localPointA ), transformA.p );
distanceOutput.pointB = b3Add( b3MulMV( mA, localPointB ), transformA.p );
// Results stay in frame A
distanceOutput.pointA = localPointA;
distanceOutput.pointB = localPointB;
distanceOutput.distance = b3Distance( localPointA, localPointB );
distanceOutput.normal = normal;
distanceOutput.iterations = iteration;
@ -1053,10 +1047,12 @@ b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input )
b3DistanceInput distanceInput = { 0 };
distanceInput.proxyA = input->proxyA;
distanceInput.proxyB = input->proxyB;
distanceInput.transformA = input->transformA;
distanceInput.transformB = input->transformB;
distanceInput.useRadii = false;
// The whole cast runs in frame A. Advance the relative pose of B in float each iteration,
// which keeps the math near the local origin and avoids re-relativizing world poses.
distanceInput.transform = input->transform;
b3Vec3 delta2 = input->translationB;
b3DistanceOutput distanceOutput = { 0 };
b3CastOutput output = { 0 };
@ -1111,14 +1107,9 @@ b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input )
b3Log( "radiusB = %.9f", input->proxyB.radius );
{
b3Transform xfA = input->transformA;
b3Log( "xfA = {{%.9f, %.9f, %.9f}, {{%.9f, %.9f, %.9f}, %.9f}", xfA.p.x, xfA.p.y, xfA.p.z, xfA.q.v.x,
xfA.q.v.y, xfA.q.v.z, xfA.q.s );
}
{
b3Transform xfB = input->transformB;
b3Log( "xfB = {{%.9f, %.9f, %.9f}, {{%.9f, %.9f, %.9f}, %.9f}", xfB.p.x, xfB.p.y, xfB.p.z, xfB.q.v.x,
xfB.q.v.y, xfB.q.v.z, xfB.q.s );
b3Transform xf = input->transform;
b3Log( "transform = {{%.9f, %.9f, %.9f}, {{%.9f, %.9f, %.9f}, %.9f}", xf.p.x, xf.p.y, xf.p.z, xf.q.v.x,
xf.q.v.y, xf.q.v.z, xf.q.s );
}
{
@ -1162,7 +1153,7 @@ b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input )
return output;
}
distanceInput.transformB.p = b3MulAdd( input->transformB.p, alpha, delta2 );
distanceInput.transform.p = b3MulAdd( input->transform.p, alpha, delta2 );
}
// Failure!
@ -1257,10 +1248,10 @@ typedef struct b3SeparationFunction
static b3SeparationFunction b3MakeSeparationFunction( const b3SimplexCache cache, const b3ShapeProxy* proxyA,
const b3Sweep* sweepA, const b3ShapeProxy* proxyB, const b3Sweep* sweepB,
const b3DistanceOutput* query, float t1 )
b3Vec3 worldNormal, float t1 )
{
B3_ASSERT( 1 <= cache.count && cache.count <= 3 );
B3_VALIDATE( b3IsNormalized( query->normal ) );
B3_VALIDATE( b3IsNormalized( worldNormal ) );
b3SeparationFunction fcn = { 0 };
fcn.proxyA = proxyA;
@ -1290,7 +1281,7 @@ static b3SeparationFunction b3MakeSeparationFunction( const b3SimplexCache cache
{
// Witness is the world space direction
fcn.type = b3_separationVertices;
fcn.witness1 = query->normal;
fcn.witness1 = worldNormal;
}
break;
@ -1318,7 +1309,7 @@ static b3SeparationFunction b3MakeSeparationFunction( const b3SimplexCache cache
{
// The axis is not safe to normalize so we use a world axis instead!
fcn.type = b3_separationVertices;
fcn.witness1 = query->normal;
fcn.witness1 = worldNormal;
}
else
{
@ -1351,11 +1342,11 @@ static b3SeparationFunction b3MakeSeparationFunction( const b3SimplexCache cache
}
else
{
B3_VALIDATE( b3IsNormalized( query->normal ) );
B3_VALIDATE( b3IsNormalized( worldNormal ) );
// Vertex versus edge, use world axis witness
fcn.type = b3_separationVertices;
fcn.witness1 = query->normal;
fcn.witness1 = worldNormal;
}
}
break;
@ -1447,7 +1438,7 @@ static b3SeparationFunction b3MakeSeparationFunction( const b3SimplexCache cache
{
// The axis is not safe to normalize so we use a world axis instead!
fcn.type = b3_separationVertices;
fcn.witness1 = query->normal;
fcn.witness1 = worldNormal;
}
else
{
@ -1693,11 +1684,17 @@ b3TOIOutput b3TimeOfImpact( const b3TOIInput* input )
for ( ;; )
{
// Get the distance between shapes. We can also use the results to get a separating axis.
distanceInput.transformA = b3GetSweepTransform( &sweepA, t1 );
distanceInput.transformB = b3GetSweepTransform( &sweepB, t1 );
b3Transform xfA = b3GetSweepTransform( &sweepA, t1 );
b3Transform xfB = b3GetSweepTransform( &sweepB, t1 );
distanceInput.transform = b3InvMulTransforms( xfA, xfB );
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, &cache, NULL, 0 );
output.distance = distanceOutput.distance;
// The distance query runs in frame A, project the witness data back to the shifted world
b3Vec3 worldNormal = b3RotateVector( xfA.q, distanceOutput.normal );
b3Vec3 worldPointA = b3TransformPoint( xfA, distanceOutput.pointA );
b3Vec3 worldPointB = b3TransformPoint( xfA, distanceOutput.pointB );
output.distanceIterations += 1;
distanceIterations += 1;
@ -1715,11 +1712,11 @@ b3TOIOutput b3TimeOfImpact( const b3TOIInput* input )
output.state = b3_toiStateHit;
// Averaged hit point
b3Vec3 pA = b3MulAdd( distanceOutput.pointA, proxyA.radius, distanceOutput.normal );
b3Vec3 pB = b3MulAdd( distanceOutput.pointB, -proxyB.radius, distanceOutput.normal );
b3Vec3 pA = b3MulAdd( worldPointA, proxyA.radius, worldNormal );
b3Vec3 pB = b3MulAdd( worldPointB, -proxyB.radius, worldNormal );
output.point = b3Lerp( pA, pB, 0.5f );
output.point = b3Add( output.point, origin );
output.normal = distanceOutput.normal;
output.normal = worldNormal;
output.fraction = t1;
break;
}
@ -1732,17 +1729,17 @@ b3TOIOutput b3TimeOfImpact( const b3TOIInput* input )
output.fraction = t1;
// Averaged hit point
b3Vec3 pA = b3MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal );
b3Vec3 pB = b3MulAdd( distanceOutput.pointB, -input->proxyB.radius, distanceOutput.normal );
b3Vec3 pA = b3MulAdd( worldPointA, input->proxyA.radius, worldNormal );
b3Vec3 pB = b3MulAdd( worldPointB, -input->proxyB.radius, worldNormal );
output.point = b3Lerp( pA, pB, 0.5f );
output.point = b3Add( output.point, origin );
output.normal = distanceOutput.normal;
output.normal = worldNormal;
break;
}
// Initialize the separating axis.
b3SeparationFunction function =
b3MakeSeparationFunction( cache, &proxyA, &sweepA, &proxyB, &sweepB, &distanceOutput, t1 );
b3MakeSeparationFunction( cache, &proxyA, &sweepA, &proxyB, &sweepB, worldNormal, t1 );
#if B3_ENABLE_VALIDATION && 0
// todo this can give a negative value for diagonal edge contact on faces, typical GJK problem
@ -1890,11 +1887,11 @@ b3TOIOutput b3TimeOfImpact( const b3TOIInput* input )
if ( done )
{
// Averaged hit point
b3Vec3 pA = b3MulAdd( distanceOutput.pointA, input->proxyA.radius, distanceOutput.normal );
b3Vec3 pB = b3MulAdd( distanceOutput.pointB, -input->proxyB.radius, distanceOutput.normal );
b3Vec3 pA = b3MulAdd( worldPointA, input->proxyA.radius, worldNormal );
b3Vec3 pB = b3MulAdd( worldPointB, -input->proxyB.radius, worldNormal );
output.point = b3Lerp( pA, pB, 0.5f );
output.point = b3Add( output.point, origin );
output.normal = distanceOutput.normal;
output.normal = worldNormal;
break;
}
}

View file

@ -80,12 +80,12 @@ float b3DistanceJoint_GetCurrentLength( b3JointId jointId )
return 0.0f;
}
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3Vec3 pA = b3TransformPoint( transformA, base->localFrameA.p );
b3Vec3 pB = b3TransformPoint( transformB, base->localFrameB.p );
b3Vec3 d = b3Sub( pB, pA );
b3Pos pA = b3TransformWorldPoint( transformA, base->localFrameA.p );
b3Pos pB = b3TransformWorldPoint( transformB, base->localFrameB.p );
b3Vec3 d = b3SubPos( pB, pA );
float length = b3Length( d );
return length;
}
@ -195,12 +195,12 @@ b3Vec3 b3GetDistanceJointForce( b3World* world, b3JointSim* base )
{
b3DistanceJoint* joint = &base->distanceJoint;
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3Vec3 pA = b3TransformPoint( transformA, base->localFrameA.p );
b3Vec3 pB = b3TransformPoint( transformB, base->localFrameB.p );
b3Vec3 d = b3Sub( pB, pA );
b3Pos pA = b3TransformWorldPoint( transformA, base->localFrameA.p );
b3Pos pB = b3TransformWorldPoint( transformB, base->localFrameB.p );
b3Vec3 d = b3SubPos( pB, pA );
b3Vec3 axis = b3Normalize( d );
float force = ( joint->impulse + joint->lowerImpulse - joint->upperImpulse + joint->motorImpulse ) * world->inv_h;
return b3MulSV( force, axis );
@ -262,7 +262,7 @@ void b3PrepareDistanceJoint( b3JointSim* base, b3StepContext* context )
// initial anchors in world space
joint->anchorA = b3RotateVector( bodySimA->transform.q, b3Sub( base->localFrameA.p, bodySimA->localCenter ) );
joint->anchorB = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
b3Vec3 rA = joint->anchorA;
b3Vec3 rB = joint->anchorB;
@ -514,21 +514,21 @@ void b3SolveDistanceJoint( b3JointSim* base, b3StepContext* context, bool useBia
}
}
void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB )
void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB )
{
B3_ASSERT( base->type == b3_distanceJoint );
b3DistanceJoint* joint = &base->distanceJoint;
b3Vec3 pA = b3TransformPoint( transformA, base->localFrameA.p );
b3Vec3 pB = b3TransformPoint( transformB, base->localFrameB.p );
b3Pos pA = b3TransformWorldPoint( transformA, base->localFrameA.p );
b3Pos pB = b3TransformWorldPoint( transformB, base->localFrameB.p );
b3Vec3 axis = b3Normalize( b3Sub( pB, pA ) );
b3Vec3 axis = b3Normalize( b3SubPos( pB, pA ) );
if ( joint->minLength < joint->maxLength && joint->enableLimit )
{
b3Vec3 pMin = b3MulAdd( pA, joint->minLength, axis );
b3Vec3 pMax = b3MulAdd( pA, joint->maxLength, axis );
b3Pos pMin = b3OffsetPos( pA, b3MulSV( joint->minLength, axis ) );
b3Pos pMax = b3OffsetPos( pA, b3MulSV( joint->maxLength, axis ) );
if ( joint->minLength > B3_LINEAR_SLOP )
{
@ -552,7 +552,7 @@ void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform trans
if ( joint->hertz > 0.0f && joint->enableSpring )
{
b3Vec3 pRest = b3MulAdd( pA, joint->length, axis );
b3Pos pRest = b3OffsetPos( pA, b3MulSV( joint->length, axis ) );
draw->DrawPointFcn( pRest, 4.0f, b3_colorBlue, draw->context );
}
}

View file

@ -761,12 +761,6 @@ static void b3RemoveLeaf( b3DynamicTree* tree, int leaf )
int b3DynamicTree_CreateProxy( b3DynamicTree* tree, b3AABB aabb, uint64_t categoryBits, uint64_t userData )
{
B3_ASSERT( b3IsValidAABB( aabb ) );
B3_VALIDATE( -B3_HUGE < aabb.lowerBound.x && aabb.lowerBound.x < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.lowerBound.y && aabb.lowerBound.y < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.lowerBound.z && aabb.lowerBound.z < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.upperBound.x && aabb.upperBound.x < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.upperBound.y && aabb.upperBound.y < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.upperBound.z && aabb.upperBound.z < B3_HUGE );
int proxyId = b3AllocateNode( tree );
b3TreeNode* node = tree->nodes + proxyId;
@ -805,12 +799,6 @@ int b3DynamicTree_GetProxyCount( const b3DynamicTree* tree )
void b3DynamicTree_MoveProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb )
{
B3_ASSERT( b3IsValidAABB( aabb ) );
B3_VALIDATE( -B3_HUGE < aabb.lowerBound.x && aabb.lowerBound.x < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.lowerBound.y && aabb.lowerBound.y < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.lowerBound.z && aabb.lowerBound.z < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.upperBound.x && aabb.upperBound.x < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.upperBound.y && aabb.upperBound.y < B3_HUGE );
B3_VALIDATE( -B3_HUGE < aabb.upperBound.z && aabb.upperBound.z < B3_HUGE );
B3_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity );
B3_ASSERT( b3IsLeaf( tree->nodes + proxyId ) );
@ -826,9 +814,6 @@ void b3DynamicTree_EnlargeProxy( b3DynamicTree* tree, int proxyId, b3AABB aabb )
{
b3TreeNode* nodes = tree->nodes;
B3_VALIDATE( b3IsValidAABB( aabb ) );
B3_VALIDATE( aabb.upperBound.x - aabb.lowerBound.x < B3_HUGE );
B3_VALIDATE( aabb.upperBound.y - aabb.lowerBound.y < B3_HUGE );
B3_VALIDATE( aabb.upperBound.z - aabb.lowerBound.z < B3_HUGE );
B3_ASSERT( 0 <= proxyId && proxyId < tree->nodeCapacity );
B3_VALIDATE( b3IsLeaf( tree->nodes + proxyId ) );
@ -1375,32 +1360,22 @@ b3TreeStats b3DynamicTree_RayCast( const b3DynamicTree* tree, const b3RayCastInp
return result;
}
b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCastInput* input, uint64_t maskBits,
bool requireAllBits, b3TreeShapeCastCallbackFcn* callback, void* context )
b3TreeStats b3DynamicTree_BoxCast( const b3DynamicTree* tree, const b3BoxCastInput* input, uint64_t maskBits, bool requireAllBits,
b3TreeBoxCastCallbackFcn* callback, void* context )
{
b3TreeStats stats = { 0 };
if ( tree->nodeCount == 0 || input->proxy.count == 0 )
if ( tree->nodeCount == 0 )
{
return stats;
}
b3AABB originAABB = { input->proxy.points[0], input->proxy.points[0] };
for ( int i = 1; i < input->proxy.count; ++i )
{
originAABB.lowerBound = b3Min( originAABB.lowerBound, input->proxy.points[i] );
originAABB.upperBound = b3Max( originAABB.upperBound, input->proxy.points[i] );
}
b3Vec3 radius = { input->proxy.radius, input->proxy.radius, input->proxy.radius };
originAABB.lowerBound = b3Sub( originAABB.lowerBound, radius );
originAABB.upperBound = b3Add( originAABB.upperBound, radius );
// The caller folds the shape radius and the world origin into the box
b3AABB originAABB = input->box;
b3Vec3 p1 = b3AABB_Center( originAABB );
b3Vec3 extension = b3AABB_Extents( originAABB );
// v is perpendicular to the segment.
b3Vec3 d = input->translation;
b3V32 pv1 = b3LoadV( &p1.x );
@ -1409,14 +1384,14 @@ b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCas
float maxFraction = input->maxFraction;
// Build total box for the shape cast
// Build total box for the cast
b3Vec3 t = b3MulSV( maxFraction, input->translation );
b3AABB totalAABB = {
b3Min( originAABB.lowerBound, b3Add( originAABB.lowerBound, t ) ),
b3Max( originAABB.upperBound, b3Add( originAABB.upperBound, t ) ),
};
b3ShapeCastInput subInput = *input;
b3BoxCastInput subInput = *input;
const b3TreeNode* nodes = tree->nodes;
int stack[B3_TREE_STACK_SIZE];
@ -1428,7 +1403,6 @@ b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCas
int nodeId = stack[--stackCount];
if ( nodeId == B3_NULL_INDEX )
{
// todo is this possible?
B3_ASSERT( false );
continue;
}
@ -1436,7 +1410,6 @@ b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCas
const b3TreeNode* node = nodes + nodeId;
stats.nodeVisits += 1;
// todo look at disassembly
uint64_t bitMatch = requireAllBits ? ( node->categoryBits & maskBits ) == maskBits : ( node->categoryBits & maskBits );
if ( bitMatch == 0 || b3AABB_Overlaps( node->aabb, totalAABB ) == false )
@ -1462,13 +1435,12 @@ b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCas
if ( value == 0.0f )
{
// The client has terminated the ray cast.
// The client has terminated the cast.
return stats;
}
if ( 0.0f < value && value < maxFraction )
{
// Update segment bounding box.
maxFraction = value;
t = b3MulSV( maxFraction, input->translation );
totalAABB.lowerBound = b3Min( originAABB.lowerBound, b3Add( originAABB.lowerBound, t ) );

View file

@ -755,9 +755,8 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3S
B3_UNUSED( cellCount );
b3ShapeCastPairInput pairInput = { 0 };
pairInput.transformA = b3Transform_identity;
pairInput.proxyB = input->proxy;
pairInput.transformB = b3Transform_identity;
pairInput.transform = b3Transform_identity;
pairInput.translationB = input->translation;
pairInput.canEncroach = input->canEncroach;
@ -919,7 +918,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3S
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point21, origin ), b3Sub( point12, origin ) };
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.maxFraction = bestFraction;
pairInput.transformB.p = b3Neg( origin );
pairInput.transform.p = b3Neg( origin );
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
@ -939,7 +938,7 @@ b3CastOutput b3ShapeCastHeightField( const b3HeightField* heightField, const b3S
b3Vec3 triangleVertices[] = { b3Vec3_zero, b3Sub( point22, origin ), b3Sub( point12, origin ) };
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.maxFraction = bestFraction;
pairInput.transformB.p = b3Neg( origin );
pairInput.transform.p = b3Neg( origin );
b3CastOutput pairOutput = b3ShapeCast( &pairInput );
@ -1047,8 +1046,7 @@ bool b3OverlapHeightField( const b3HeightField* shape, b3Transform shapeTransfor
b3DistanceInput input;
input.proxyB = localProxy;
input.transformA = b3Transform_identity;
input.transformB = b3Transform_identity;
input.transform = b3Transform_identity;
input.useRadii = true;
b3SimplexCache cache = { 0 };
@ -1202,8 +1200,7 @@ int b3CollideMoverAndHeightField( b3PlaneResult* planes, int capacity, const b3H
{
b3DistanceInput distanceInput = { 0 };
distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, 0.0f };
distanceInput.transformA = b3Transform_identity;
distanceInput.transformB = b3Transform_identity;
distanceInput.transform = b3Transform_identity;
distanceInput.useRadii = false;
b3SimplexCache cache = { 0 };

View file

@ -157,7 +157,7 @@ static inline void b3QHList_Init( b3QHListNode* head )
head->next = head;
}
#define B3_LIST_EMPTY( A ) ( ( A )->next == (A) )
#define B3_LIST_EMPTY( A ) ( ( A )->next == ( A ) )
static inline bool b3QHList_Contains( const b3QHListNode* node )
{
@ -1837,6 +1837,41 @@ b3HullData* b3CreateCone( float height, float radius1, float radius2, int slices
return hull;
}
b3HullData* b3CreateRock( float radius )
{
int pointCount = 10;
// Golden ratio
const float phi = ( 1.0f + sqrtf( 5.0f ) ) / 2.0f;
// Fibonacci lattice
b3Vec3 points[10];
// Azimuthal angle
float theta = 2.0f * B3_PI / phi;
b3CosSin cs = { 1.0f, 0.0 };
b3CosSin deltaCS = b3ComputeCosSin( theta );
for ( int i = 0; i < pointCount; ++i )
{
// Z coordinate
float z = 1.0f - ( 2.0f * i + 1.0f ) / pointCount;
// Radius in xy-plane
float radius_XY = sqrtf( 1.0f - z * z );
points[i].x = radius * radius_XY * cs.cosine;
points[i].y = radius * radius_XY * cs.sine;
points[i].z = radius * z;
b3CosSin cs0 = cs;
cs.cosine = deltaCS.cosine * cs0.cosine - deltaCS.sine * cs0.sine;
cs.sine = deltaCS.sine * cs0.cosine + deltaCS.cosine * cs0.sine;
}
return b3CreateHull( points, pointCount, pointCount );
}
static void b3UpdateHullBounds( b3HullData* hull )
{
const b3Vec3* points = b3GetHullPoints( hull );
@ -2384,8 +2419,8 @@ b3MassData b3ComputeHullMass( const b3HullData* shape, float density )
out.mass = density * shape->volume;
out.center = shape->center;
// todo_erin switch to central
out.inertia = b3AddMM( b3MulSM( density, shape->centralInertia ), b3Steiner( out.mass, out.center ) );
// Inertia about the center of mass
out.inertia = b3MulSM( density, shape->centralInertia );
return out;
}
@ -2408,8 +2443,7 @@ bool b3OverlapHull( const b3HullData* shape, b3Transform shapeTransform, const b
b3DistanceInput input;
input.proxyA = (b3ShapeProxy){ points, shape->vertexCount, 0.0f };
input.proxyB = *proxy;
input.transformA = shapeTransform;
input.transformB = b3Transform_identity;
input.transform = b3InvMulTransforms( shapeTransform, b3Transform_identity );
input.useRadii = true;
b3SimplexCache cache = { 0 };
@ -2492,8 +2526,7 @@ b3CastOutput b3ShapeCastHull( const b3HullData* shape, const b3ShapeCastInput* i
b3ShapeCastPairInput pairInput;
pairInput.proxyA = (b3ShapeProxy){ points, shape->vertexCount, 0.0f };
pairInput.proxyB = input->proxy;
pairInput.transformA = b3Transform_identity;
pairInput.transformB = b3Transform_identity;
pairInput.transform = b3Transform_identity;
pairInput.translationB = input->translation;
pairInput.maxFraction = input->maxFraction;
pairInput.canEncroach = input->canEncroach;
@ -2508,8 +2541,7 @@ int b3CollideMoverAndHull( b3PlaneResult* result, const b3HullData* shape, const
b3DistanceInput distanceInput;
distanceInput.proxyA = (b3ShapeProxy){ points, shape->vertexCount, 0.0f };
distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, mover->radius };
distanceInput.transformA = b3Transform_identity;
distanceInput.transformB = b3Transform_identity;
distanceInput.transform = b3Transform_identity;
distanceInput.useRadii = false;
float totalRadius = mover->radius;

View file

@ -1045,8 +1045,8 @@ void b3GetJointReaction( b3World* world, b3JointSim* sim, float invTimeStep, flo
b3SphericalJoint* joint = &sim->sphericalJoint;
linearImpulse = b3Length( joint->linearImpulse );
b3Transform xfA = b3GetBodyTransform( world, sim->bodyIdA );
b3Transform xfB = b3GetBodyTransform( world, sim->bodyIdB );
b3WorldTransform xfA = b3GetBodyTransform( world, sim->bodyIdA );
b3WorldTransform xfB = b3GetBodyTransform( world, sim->bodyIdB );
b3Quat qA = b3MulQuat( xfA.q, sim->localFrameA.q );
b3Quat qB = b3MulQuat( xfB.q, sim->localFrameB.q );
@ -1185,12 +1185,12 @@ float b3Joint_GetLinearSeparation( b3JointId jointId )
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* base = b3GetJointSim( world, joint );
b3Transform xfA = b3GetBodyTransform( world, joint->edges[0].bodyId );
b3Transform xfB = b3GetBodyTransform( world, joint->edges[1].bodyId );
b3WorldTransform xfA = b3GetBodyTransform( world, joint->edges[0].bodyId );
b3WorldTransform xfB = b3GetBodyTransform( world, joint->edges[1].bodyId );
b3Vec3 pA = b3TransformPoint( xfA, base->localFrameA.p );
b3Vec3 pB = b3TransformPoint( xfB, base->localFrameB.p );
b3Vec3 dp = b3Sub( pB, pA );
b3Pos pA = b3TransformWorldPoint( xfA, base->localFrameA.p );
b3Pos pB = b3TransformWorldPoint( xfB, base->localFrameB.p );
b3Vec3 dp = b3SubPos( pB, pA );
switch ( joint->type )
{
@ -1309,8 +1309,8 @@ float b3Joint_GetAngularSeparation( b3JointId jointId )
b3Joint* joint = b3GetJointFullId( world, jointId );
b3JointSim* base = b3GetJointSim( world, joint );
b3Transform xfA = b3GetBodyTransform( world, joint->edges[0].bodyId );
b3Transform xfB = b3GetBodyTransform( world, joint->edges[1].bodyId );
b3WorldTransform xfA = b3GetBodyTransform( world, joint->edges[0].bodyId );
b3WorldTransform xfB = b3GetBodyTransform( world, joint->edges[1].bodyId );
b3Quat relQ = b3InvMulQuat( xfA.q, xfB.q );
@ -1638,10 +1638,10 @@ void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint )
b3JointSim* jointSim = b3GetJointSim( world, joint );
b3Transform transformA = b3GetBodyTransformQuick( world, bodyA );
b3Transform transformB = b3GetBodyTransformQuick( world, bodyB );
b3Vec3 pA = b3TransformPoint( transformA, jointSim->localFrameA.p );
b3Vec3 pB = b3TransformPoint( transformB, jointSim->localFrameB.p );
b3WorldTransform transformA = b3GetBodyTransformQuick( world, bodyA );
b3WorldTransform transformB = b3GetBodyTransformQuick( world, bodyB );
b3Pos pA = b3TransformWorldPoint( transformA, jointSim->localFrameA.p );
b3Pos pB = b3TransformWorldPoint( transformB, jointSim->localFrameB.p );
b3HexColor color = b3_colorDarkSeaGreen;
@ -1705,7 +1705,7 @@ void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint )
int colorIndex = joint->colorIndex;
if ( colorIndex != B3_NULL_INDEX )
{
b3Vec3 p = b3Lerp( pA, pB, 0.5f );
b3Pos p = b3LerpPosition( pA, pB, 0.5f );
draw->DrawPointFcn( p, 5.0f, graphColors[colorIndex], draw->context );
}
}
@ -1714,9 +1714,9 @@ void b3DrawJoint( b3DebugDraw* draw, b3World* world, b3Joint* joint )
{
b3Vec3 force = b3GetJointConstraintForce( world, joint );
b3Vec3 torque = b3GetJointConstraintTorque( world, joint );
b3Vec3 p = b3Lerp( pA, pB, 0.5f );
b3Pos p = b3LerpPosition( pA, pB, 0.5f );
draw->DrawSegmentFcn( p, b3MulAdd( p, 0.001f, force ), b3_colorAzure, draw->context );
draw->DrawSegmentFcn( p, b3OffsetPos( p, b3MulSV( 0.001f, force ) ), b3_colorAzure, draw->context );
char buffer[64];
snprintf( buffer, 64, "f = %g, t = %g", b3Length( force ), b3Length( torque ) );

View file

@ -406,10 +406,10 @@ void b3SolveSphericalJoint( b3JointSim* base, b3StepContext* context, bool useBi
void b3SolveWeldJoint( b3JointSim* base, b3StepContext* context, bool useBias );
void b3SolveWheelJoint( b3JointSim* base, b3StepContext* context, bool useBias );
void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB );
void b3DrawParallelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale );
void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale );
void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale );
void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale );
void b3DrawWeldJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale );
void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale );
void b3DrawDistanceJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB );
void b3DrawParallelJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale );
void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale );
void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale );
void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale );
void b3DrawWeldJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale );
void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale );

View file

@ -96,6 +96,21 @@ bool b3IsValidAABB( b3AABB a )
return true;
}
bool b3IsBoundedAABB( b3AABB a )
{
if ( a.lowerBound.x < -B3_HUGE || a.lowerBound.y < -B3_HUGE || a.lowerBound.z < -B3_HUGE )
{
return false;
}
if ( a.upperBound.x > B3_HUGE || a.upperBound.y > B3_HUGE || a.upperBound.z > B3_HUGE )
{
return false;
}
return true;
}
bool b3IsSaneAABB( b3AABB a )
{
if ( b3IsValidAABB( a ) == false )
@ -131,6 +146,26 @@ bool b3IsValidPlane( b3Plane a )
return b3IsValidFloat( a.offset );
}
bool b3IsValidPosition( b3Pos p )
{
if ( isnan( p.x ) || isnan( p.y ) || isnan( p.z ) )
{
return false;
}
if ( isinf( p.x ) || isinf( p.y ) || isinf( p.z ) )
{
return false;
}
return true;
}
bool b3IsValidWorldTransform( b3WorldTransform t )
{
return b3IsValidPosition( t.p ) && b3IsValidQuat( t.q );
}
// https://stackoverflow.com/questions/46210708/atan2-approximation-with-11bits-in-mantissa-on-x86with-sse2-and-armwith-vfpv4
float b3Atan2( float y, float x )
{

View file

@ -76,7 +76,6 @@ b3Matrix3 b3CylinderInertia( float mass, float radius, float height );
b3Matrix3 b3BoxInertia( float mass, b3Vec3 min, b3Vec3 max );
// Inertia helper (Io = Ic + Is and Ic = Io - Is)
b3Matrix3 b3Steiner( float mass, b3Vec3 origin );
int b3GetProxySupport( const b3ShapeProxy* proxy, b3Vec3 axis );
int b3GetPointSupport( const b3Vec3* points, int count, b3Vec3 axis );

View file

@ -1791,8 +1791,7 @@ bool b3OverlapMesh( const b3Mesh* shape, b3Transform shapeTransform, const b3Sha
b3DistanceInput input;
input.proxyB = localProxy;
input.transformA = b3Transform_identity;
input.transformB = b3Transform_identity;
input.transform = b3Transform_identity;
input.useRadii = true;
int count = 0;
@ -2098,8 +2097,7 @@ b3CastOutput b3ShapeCastMesh( const b3Mesh* mesh, const b3ShapeCastInput* input
b3ShapeCastPairInput pairInput;
pairInput.proxyA = (b3ShapeProxy){ triangleVertices, 3, 0.0f };
pairInput.proxyB = input->proxy;
pairInput.transformA = b3Transform_identity;
pairInput.transformB = shiftedOrigin;
pairInput.transform = shiftedOrigin;
pairInput.maxFraction = bestOutput.fraction;
pairInput.translationB = input->translation;
pairInput.canEncroach = input->canEncroach;
@ -2212,8 +2210,7 @@ int b3CollideMoverAndMesh( b3PlaneResult* planes, int capacity, const b3Mesh* sh
b3DistanceInput distanceInput = { 0 };
distanceInput.proxyB = (b3ShapeProxy){ &mover->center1, 2, 0.0f };
distanceInput.transformA = b3Transform_identity;
distanceInput.transformB = b3Transform_identity;
distanceInput.transform = b3Transform_identity;
distanceInput.useRadii = false;
b3SimplexCache cache = { 0 };

View file

@ -74,7 +74,7 @@ static int b3QueryHeightFieldTriangles( int* indices, int capacity, const b3Heig
return context.count;
}
static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3Transform xfA, const b3AABB* bounds )
static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3WorldTransform xfA, const b3AABB* bounds )
{
B3_ASSERT( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape );
@ -106,8 +106,10 @@ static void b3RefreshCache( b3Contact* contact, const b3Shape* shapeA, b3Transfo
int triangleIndices[B3_MAX_MESH_CONTACT_TRIANGLES];
// Bounds are in world space. Convert to the local mesh frame.
b3AABB localBounds = b3AABB_Transform( b3InvertTransform( xfA ), meshContact->queryBounds );
// Bounds are in world space. Convert to the local mesh frame. The broadphase bounds are float,
// so the demoted mesh transform is the matching float world frame (exact in float mode).
b3Transform meshTransform = b3ToRelativeTransform( xfA, b3Pos_zero );
b3AABB localBounds = b3AABB_Transform( b3InvertTransform( meshTransform ), meshContact->queryBounds );
int triangleCount;
if ( shapeA->type == b3_meshShape )
{
@ -521,7 +523,7 @@ typedef struct b3Cluster
} b3Cluster;
bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact, const b3Shape* shapeA, const int* materialMap,
b3Transform xfA, const b3Shape* shapeB, b3Transform xfB, bool isFast, b3Arena arena )
b3WorldTransform xfA, const b3Shape* shapeB, b3WorldTransform xfB, bool isFast, b3Arena arena )
{
B3_ASSERT( shapeA->type == b3_meshShape || shapeA->type == b3_heightShape );
B3_UNUSED( workerIndex );
@ -549,7 +551,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
foundVertices.count = 0;
// This transform converts from mesh frame into the shapeB frame
b3Transform transformAtoB = b3InvMulTransforms( xfB, xfA );
b3Transform transformAtoB = b3InvMulWorldTransforms( xfB, xfA );
b3Matrix3 relativeMatrix = b3MakeMatrixFromQuat( transformAtoB.q );
float linearSlop = B3_LINEAR_SLOP;
@ -1006,7 +1008,7 @@ bool b3ComputeMeshManifolds( b3World* world, int workerIndex, b3Contact* contact
}
b3Matrix3 matrixB = b3MakeMatrixFromQuat( xfB.q );
b3Vec3 offsetA = b3Sub( xfB.p, xfA.p );
b3Vec3 offsetA = b3SubPos( xfB.p, xfA.p );
const float normalMatchTolerance = 0.995f;
for ( int i = 0; i < clusterCount; ++i )

View file

@ -200,7 +200,7 @@ void b3PrepareMotorJoint( b3JointSim* base, b3StepContext* context )
joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
// Compute the initial center delta. Incremental position updates are relative to this.
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
joint->linearSpring = b3MakeSoft( joint->linearHertz, joint->linearDampingRatio, context->h );
joint->angularSpring = b3MakeSoft( joint->angularHertz, joint->angularDampingRatio, context->h );

View file

@ -232,13 +232,13 @@ void b3SolveParallelJoint( b3JointSim* base, b3StepContext* context )
}
}
void b3DrawParallelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale )
void b3DrawParallelJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale )
{
float length = 0.1f * scale;
b3Transform frameA = b3MulTransforms( transformA, base->localFrameA );
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length, b3RotateVector( frameA.q, b3Vec3_axisZ ) ), b3_colorGreen, draw->context );
b3WorldTransform frameA = b3MulWorldTransforms( transformA, base->localFrameA );
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length, b3RotateVector( frameA.q, b3Vec3_axisZ ) ) ), b3_colorGreen, draw->context );
b3Transform frameB = b3MulTransforms( transformB, base->localFrameB );
draw->DrawSegmentFcn( frameB.p, b3MulAdd( frameB.p, length, b3RotateVector( frameB.q, b3Vec3_axisZ ) ), b3_colorBlue, draw->context );
b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB );
draw->DrawSegmentFcn( frameB.p, b3OffsetPos( frameB.p, b3MulSV( length, b3RotateVector( frameB.q, b3Vec3_axisZ ) ) ), b3_colorBlue, draw->context );
}

View file

@ -629,8 +629,8 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
}
}
b3Transform transformA = bodySimA->transform;
b3Transform transformB = bodySimB->transform;
b3WorldTransform transformA = bodySimA->transform;
b3WorldTransform transformB = bodySimB->transform;
bool isFast = ( bodySimA->flags & b3_isFast ) || ( bodySimB->flags & b3_isFast );
@ -647,12 +647,12 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
if ( ( isFast == false || isMeshContact == false ) && recycleDistance > 0.0f &&
( contact->flags & b3_relativeTransformValid ) && ( contact->flags & b3_contactRecycleFlag ) )
{
float angleA = b3DotQuat( transformA.q, contact->cachedTransformA.q );
float angleB = b3DotQuat( transformB.q, contact->cachedTransformB.q );
float angleA = b3DotQuat( transformA.q, contact->cachedRotationA );
float angleB = b3DotQuat( transformB.q, contact->cachedRotationB );
float angularDistance = b3MinFloat( angleA * angleA, angleB * angleB );
b3Transform xf = b3InvMulTransforms( transformA, transformB );
b3Transform xfc = b3InvMulTransforms( contact->cachedTransformA, contact->cachedTransformB );
b3Transform xf = b3InvMulWorldTransforms( transformA, transformB );
b3Transform xfc = contact->cachedRelativePose;
b3Vec3 maxExtentA = isStaticA ? b3Vec3_zero : bodySimA->maxExtent;
b3Vec3 maxExtentB = isStaticB ? b3Vec3_zero : bodySimB->maxExtent;
b3Vec3 maxExtent = b3Max( maxExtentA, maxExtentB );
@ -680,13 +680,13 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
float arcSq = 4.0f * b3LengthSquared( arc );
if ( arcSq < slack * slack )
{
b3Quat dqA = b3MulQuat( transformA.q, b3Conjugate( contact->cachedTransformA.q ) );
b3Quat dqB = b3MulQuat( transformB.q, b3Conjugate( contact->cachedTransformB.q ) );
b3Quat dqA = b3MulQuat( transformA.q, b3Conjugate( contact->cachedRotationA ) );
b3Quat dqB = b3MulQuat( transformB.q, b3Conjugate( contact->cachedRotationB ) );
b3Matrix3 matrixA = b3MakeMatrixFromQuat( dqA );
b3Matrix3 matrixB = b3MakeMatrixFromQuat( dqB );
// Minimize round-off
b3Vec3 dc = b3Sub( bodySimB->center, bodySimA->center );
b3Vec3 dc = b3SubPos( bodySimB->center, bodySimA->center );
int manifoldCount = contact->manifoldCount;
for ( int manifoldIndex = 0; manifoldIndex < manifoldCount; ++manifoldIndex )
@ -723,8 +723,9 @@ static void b3CollideTask( int startIndex, int endIndex, int workerIndex, void*
}
// Caching for contact recycling.
contact->cachedTransformA = transformA;
contact->cachedTransformB = transformB;
contact->cachedRotationA = transformA.q;
contact->cachedRotationB = transformB.q;
contact->cachedRelativePose = b3InvMulWorldTransforms( transformA, transformB );
contact->flags |= b3_relativeTransformValid;
// This updates solid contacts
@ -1315,8 +1316,7 @@ static bool DrawQueryCallback( int proxyId, uint64_t userData, void* context )
if ( draw->drawBounds )
{
b3AABB aabb = shape->fatAABB;
draw->DrawBoundsFcn( aabb, b3_colorGold, draw->context );
draw->DrawBoundsFcn( shape->fatAABB, b3_colorGold, draw->context );
}
return true;
@ -1383,8 +1383,8 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
if ( draw->drawBodyNames && body->name[0] != 0 )
{
b3Vec3 offset = { 0.05f, 0.05f, 0.05f };
b3Transform transform = { bodySim->center, bodySim->transform.q };
b3Vec3 p = b3TransformPoint( transform, offset );
b3WorldTransform transform = { bodySim->center, bodySim->transform.q };
b3Pos p = b3TransformWorldPoint( transform, offset );
draw->DrawStringFcn( p, body->name, b3_colorOrange, draw->context );
}
@ -1392,9 +1392,9 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
{
b3Vec3 offset = { 0.1f, 0.1f, 0.1f };
b3Transform transform = { bodySim->center, bodySim->transform.q };
b3WorldTransform transform = { bodySim->center, bodySim->transform.q };
draw->DrawTransformFcn( transform, draw->context );
b3Vec3 p = b3TransformPoint( transform, offset );
b3Pos p = b3TransformWorldPoint( transform, offset );
char buffer[32];
snprintf( buffer, 32, " %.2f", body->mass );
@ -1451,7 +1451,10 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
B3_ASSERT( manifold->pointCount > 0 );
b3Vec3 normal = manifold->normal;
b3Vec3 frictionCenter = b3Vec3_zero;
// Average the anchors not the world points so the friction center stays exact far from the origin
b3Pos contactCenter = draw->drawAnchorA == 1 ? bodySimA->center : bodySimB->center;
b3Vec3 anchorSum = b3Vec3_zero;
const b3ManifoldPoint* points = manifold->points;
for ( int pointIndex = 0; pointIndex < manifold->pointCount; ++pointIndex )
@ -1460,22 +1463,15 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
char buffer[32];
b3Vec3 p;
if ( draw->drawAnchorA == 1 )
{
p = b3Add( bodySimA->center, mp->anchorA );
}
else
{
p = b3Add( bodySimB->center, mp->anchorB );
}
b3Vec3 anchor = draw->drawAnchorA == 1 ? mp->anchorA : mp->anchorB;
b3Pos p = b3OffsetPos( contactCenter, anchor );
frictionCenter = b3Add( frictionCenter, p );
anchorSum = b3Add( anchorSum, anchor );
if ( draw->drawContactNormals )
{
b3Vec3 p1 = p;
b3Vec3 p2 = b3MulAdd( p1, axisScale, normal );
b3Pos p1 = p;
b3Pos p2 = b3OffsetPos( p1, b3MulSV( axisScale, normal ) );
draw->DrawSegmentFcn( p1, p2, b3_colorLightGray, draw->context );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.2f", 100.0f * mp->separation );
@ -1488,8 +1484,8 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
// todo validate
// multiply by one-half due to relax iteration
float force = 0.5f * mp->totalNormalImpulse * inv_dt;
b3Vec3 p1 = p;
b3Vec3 p2 = b3MulAdd( p1, draw->forceScale * force, normal );
b3Pos p1 = p;
b3Pos p2 = b3OffsetPos( p1, b3MulSV( draw->forceScale * force, normal ) );
draw->DrawSegmentFcn( p1, p2, impulseColor, draw->context );
snprintf( buffer, B3_ARRAY_COUNT( buffer ), " %.1f", force );
draw->DrawStringFcn( p1, buffer, b3_colorWhite, draw->context );
@ -1534,9 +1530,10 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
// Hack inv_dt for single step debugging
float inv_dt = world->inv_dt > 0.0f ? world->inv_dt : 60.0f;
b3Vec3 p1 = b3MulSV( 1.0f / manifold->pointCount, frictionCenter );
b3Vec3 avgAnchor = b3MulSV( 1.0f / manifold->pointCount, anchorSum );
b3Pos p1 = b3OffsetPos( contactCenter, avgAnchor );
b3Vec3 frictionForce = b3MulSV( 0.5f * inv_dt, manifold->frictionImpulse );
b3Vec3 p2 = b3MulAdd( p1, draw->forceScale, frictionForce );
b3Pos p2 = b3OffsetPos( p1, b3MulSV( draw->forceScale, frictionForce ) );
draw->DrawSegmentFcn( p1, p2, frictionColor, draw->context );
draw->DrawPointFcn( p1, 5.0f, frictionColor, draw->context );
@ -1608,9 +1605,10 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
for ( int j = 0; j < pointCount; ++j )
{
b3DebugPoint* point = points + j;
draw->DrawPointFcn( point->p, 5.0f, point->color, draw->context );
b3Pos p = point->p;
draw->DrawPointFcn( p, 5.0f, point->color, draw->context );
snprintf( buffer, 32, " %d, %.2f", point->label, point->value );
b3Vec3 ps = b3Add( point->p, offset );
b3Pos ps = b3OffsetPos( p, offset );
draw->DrawStringFcn( ps, buffer, point->color, draw->context );
}
@ -1619,10 +1617,12 @@ void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits )
for ( int j = 0; j < lineCount; ++j )
{
b3DebugLine* line = lines + j;
draw->DrawSegmentFcn( line->p1, line->p2, line->color, draw->context );
draw->DrawPointFcn( line->p1, 10.0f, line->color, draw->context );
b3Pos p1 = line->p1;
b3Pos p2 = line->p2;
draw->DrawSegmentFcn( p1, p2, line->color, draw->context );
draw->DrawPointFcn( p1, 10.0f, line->color, draw->context );
snprintf( buffer, 32, "%d", line->label );
b3Vec3 ps = b3Add( line->p1, offset );
b3Pos ps = b3OffsetPos( p1, offset );
draw->DrawStringFcn( ps, buffer, line->color, draw->context );
}
}
@ -2278,8 +2278,7 @@ void b3World_DumpMemoryStats( b3WorldId worldId )
int hullBucketCount = (int)b3HullMap_bucket_count( hullDatabase );
uint64_t hullMapBytes = b3HullMapByteCount( hullDatabase );
uint64_t hullDataBytes = 0;
for ( b3HullMap_itr itr = b3HullMap_first( hullDatabase ); b3HullMap_is_end( itr ) == false;
itr = b3HullMap_next( itr ) )
for ( b3HullMap_itr itr = b3HullMap_first( hullDatabase ); b3HullMap_is_end( itr ) == false; itr = b3HullMap_next( itr ) )
{
hullDataBytes += itr.data->key->byteCount;
}
@ -2537,6 +2536,7 @@ typedef struct WorldOverlapContext
b3OverlapResultFcn* fcn;
b3QueryFilter filter;
b3ShapeProxy proxy;
b3Pos origin;
void* userContext;
} WorldOverlapContext;
@ -2558,8 +2558,9 @@ static bool b3TreeOverlapCallback( int proxyId, uint64_t userData, void* context
return true;
}
// Re-center on the query origin so the overlap test stays in float precision far from the origin
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3Transform transform = b3ToRelativeTransform( b3GetBodyTransformQuick( world, body ), worldContext->origin );
bool overlapping = b3OverlapShape( shape, transform, &worldContext->proxy );
if ( overlapping == false )
@ -2572,8 +2573,8 @@ static bool b3TreeOverlapCallback( int proxyId, uint64_t userData, void* context
return result;
}
b3TreeStats b3World_OverlapShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3QueryFilter filter, b3OverlapResultFcn* fcn,
void* context )
b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const b3ShapeProxy* proxy, b3QueryFilter filter,
b3OverlapResultFcn* fcn, void* context )
{
b3TreeStats treeStats = { 0 };
@ -2583,9 +2584,12 @@ b3TreeStats b3World_OverlapShape( b3WorldId worldId, const b3ShapeProxy* proxy,
return treeStats;
}
b3AABB aabb = b3MakeAABB( proxy->points, proxy->count, proxy->radius );
B3_ASSERT( b3IsValidPosition( origin ) );
// Bound the proxy in origin relative space then lift to a conservative world float box
b3AABB aabb = b3OffsetAABB( b3MakeAABB( proxy->points, proxy->count, proxy->radius ), origin );
WorldOverlapContext worldContext = {
world, fcn, filter, *proxy, context,
world, fcn, filter, *proxy, origin, context,
};
for ( int i = 0; i < b3_bodyTypeCount; ++i )
@ -2606,6 +2610,7 @@ typedef struct WorldMoverContext
b3PlaneResultFcn* fcn;
b3QueryFilter filter;
b3Capsule mover;
b3Pos origin;
void* userContext;
} WorldMoverContext;
@ -2627,8 +2632,10 @@ static bool TreeCollideCallback( int proxyId, uint64_t userData, void* context )
return true;
}
// Re-center on the query origin, the mover and the resulting planes are origin relative
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform bodyTransform = b3GetBodyTransformQuick( world, body );
b3Transform transform = b3ToRelativeTransform( bodyTransform, worldContext->origin );
b3PlaneResult buffer[64];
int count = b3CollideMover( buffer, 64, shape, transform, &worldContext->mover );
@ -2644,7 +2651,8 @@ static bool TreeCollideCallback( int proxyId, uint64_t userData, void* context )
// It is tempting to use a shape proxy for the mover, but this makes handling deep overlap difficult and the generality may
// not be worth it.
void b3World_CollideMover( b3WorldId worldId, const b3Capsule* mover, b3QueryFilter filter, b3PlaneResultFcn* fcn, void* context )
void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover, b3QueryFilter filter, b3PlaneResultFcn* fcn,
void* context )
{
b3World* world = b3GetUnlockedWorldFromId( worldId );
if ( world == NULL )
@ -2652,14 +2660,18 @@ void b3World_CollideMover( b3WorldId worldId, const b3Capsule* mover, b3QueryFil
return;
}
B3_ASSERT( b3IsValidPosition( origin ) );
b3Vec3 r = { mover->radius, mover->radius, mover->radius };
b3AABB aabb;
aabb.lowerBound = b3Sub( b3Min( mover->center1, mover->center2 ), r );
aabb.upperBound = b3Add( b3Max( mover->center1, mover->center2 ), r );
// Relative box lifted to world float with outward rounding, conservative for the tree
b3AABB relBox;
relBox.lowerBound = b3Sub( b3Min( mover->center1, mover->center2 ), r );
relBox.upperBound = b3Add( b3Max( mover->center1, mover->center2 ), r );
b3AABB aabb = b3OffsetAABB( relBox, origin );
WorldMoverContext worldContext = {
world, fcn, filter, *mover, context,
world, fcn, filter, *mover, origin, context,
};
for ( int i = 0; i < b3_bodyTypeCount; ++i )
@ -2674,6 +2686,7 @@ typedef struct WorldRayCastContext
b3CastResultFcn* fcn;
b3QueryFilter filter;
float fraction;
b3Pos origin;
void* userContext;
} WorldRayCastContext;
@ -2695,22 +2708,26 @@ static float RayCastCallback( const b3RayCastInput* input, int proxyId, uint64_t
}
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3CastOutput output = b3RayCastShape( shape, transform, input );
b3WorldTransform bodyTransform = b3GetBodyTransformQuick( world, body );
b3Transform transform = b3ToRelativeTransform( bodyTransform, worldContext->origin );
b3RayCastInput localInput = *input;
localInput.origin = b3Vec3_zero;
b3CastOutput output = b3RayCastShape( shape, transform, &localInput );
if ( output.hit )
{
B3_ASSERT( output.fraction <= input->maxFraction );
b3ShapeId id = { shapeId + 1, world->worldId, shape->generation };
b3Pos point = b3OffsetPos( worldContext->origin, output.point );
int materialIndex = b3ClampInt( output.materialIndex, 0, shape->materialCount - 1 );
uint64_t userMaterialId = shape->materials[materialIndex].userMaterialId;
int triangleIndex = output.triangleIndex;
int childIndex = output.childIndex;
float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, userMaterialId, triangleIndex,
childIndex, worldContext->userContext );
float fraction = worldContext->fcn( id, point, output.normal, output.fraction, userMaterialId, triangleIndex, childIndex,
worldContext->userContext );
// The user may return -1 to skip this shape
if ( 0.0f <= fraction && fraction <= 1.0f )
@ -2724,7 +2741,7 @@ static float RayCastCallback( const b3RayCastInput* input, int proxyId, uint64_t
return input->maxFraction;
}
b3TreeStats b3World_CastRay( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter, b3CastResultFcn* fcn,
b3TreeStats b3World_CastRay( b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter, b3CastResultFcn* fcn,
void* context )
{
b3TreeStats treeStats = { 0 };
@ -2735,12 +2752,14 @@ b3TreeStats b3World_CastRay( b3WorldId worldId, b3Vec3 origin, b3Vec3 translatio
return treeStats;
}
B3_ASSERT( b3IsValidVec3( origin ) );
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3RayCastInput input = { origin, translation, 1.0f };
// The tree traverses in float relative to the world origin. Each shape is then re-differenced at
// full precision against the origin, so a hit stays accurate far from the origin.
b3RayCastInput input = { b3ToVec3( origin ), translation, 1.0f };
WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context };
WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, origin, context };
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
@ -2761,7 +2780,7 @@ b3TreeStats b3World_CastRay( b3WorldId worldId, b3Vec3 origin, b3Vec3 translatio
}
// This callback finds the closest hit. This is the most common callback used in games.
static float b3RayCastClosestFcn( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t userMaterialId,
static float b3RayCastClosestFcn( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId,
int triangleIndex, int childIndex, void* context )
{
// Ignore initial overlap
@ -2782,7 +2801,7 @@ static float b3RayCastClosestFcn( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal
return fraction;
}
b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter )
b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter )
{
b3RayResult result = { 0 };
@ -2792,15 +2811,18 @@ b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Vec3 origin, b3Vec3 tra
return result;
}
B3_ASSERT( b3IsValidVec3( origin ) );
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3RayCastInput input = { origin, translation, 1.0f };
// The tree traverses in float relative to the world origin. Each shape is then re-differenced at
// full precision against its body, so a hit stays accurate far from the origin.
b3RayCastInput input = { b3ToVec3( origin ), translation, 1.0f };
WorldRayCastContext worldContext = {
.world = world,
.fcn = b3RayCastClosestFcn,
.filter = filter,
.fraction = 1.0f,
.origin = origin,
.userContext = &result,
};
@ -2822,12 +2844,24 @@ b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Vec3 origin, b3Vec3 tra
return result;
}
static float b3ShapeCastCallback( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context )
typedef struct WorldShapeCastContext
{
b3World* world;
b3CastResultFcn* fcn;
b3QueryFilter filter;
float fraction;
b3Pos origin;
// origin relative input
b3ShapeCastInput input;
void* userContext;
} WorldShapeCastContext;
static float b3ShapeCastCallback( const b3BoxCastInput* input, int proxyId, uint64_t userData, void* context )
{
B3_UNUSED( proxyId );
int shapeId = (int)userData;
WorldRayCastContext* worldContext = (WorldRayCastContext*)context;
WorldShapeCastContext* worldContext = (WorldShapeCastContext*)context;
b3World* world = worldContext->world;
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
@ -2839,10 +2873,16 @@ static float b3ShapeCastCallback( const b3ShapeCastInput* input, int proxyId, ui
return input->maxFraction;
}
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
// Rebuild from the origin relative input, taking only the advancing fraction from the tree.
// The tree box is world float and would lose the cast far from the origin.
b3ShapeCastInput localInput = worldContext->input;
localInput.maxFraction = input->maxFraction;
b3CastOutput output = b3ShapeCastShape( shape, transform, input );
// Re-center on the query origin so the per-shape cast stays in float precision far from the origin
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3ToRelativeTransform( b3GetBodyTransformQuick( world, body ), worldContext->origin );
b3CastOutput output = b3ShapeCastShape( shape, transform, &localInput );
if ( output.hit )
{
@ -2852,8 +2892,8 @@ static float b3ShapeCastCallback( const b3ShapeCastInput* input, int proxyId, ui
int triangleIndex = output.triangleIndex;
int childIndex = output.childIndex;
float fraction = worldContext->fcn( id, output.point, output.normal, output.fraction, userMaterialId, triangleIndex,
childIndex, worldContext->userContext );
float fraction = worldContext->fcn( id, b3OffsetPos( worldContext->origin, output.point ), output.normal, output.fraction,
userMaterialId, triangleIndex, childIndex, worldContext->userContext );
// The user may return -1 to skip this shape
if ( 0.0f <= fraction && fraction <= 1.0f )
@ -2867,8 +2907,8 @@ static float b3ShapeCastCallback( const b3ShapeCastInput* input, int proxyId, ui
return input->maxFraction;
}
b3TreeStats b3World_CastShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3Vec3 translation, b3QueryFilter filter,
b3CastResultFcn* fcn, void* context )
b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3ShapeProxy* proxy, b3Vec3 translation,
b3QueryFilter filter, b3CastResultFcn* fcn, void* context )
{
b3TreeStats treeStats = { 0 };
@ -2878,20 +2918,31 @@ b3TreeStats b3World_CastShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3V
return treeStats;
}
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3ShapeCastInput input;
input.proxy = *proxy;
input.translation = translation;
input.maxFraction = 1.0f;
input.canEncroach = false;
WorldShapeCastContext worldContext = { 0 };
worldContext.world = world;
worldContext.fcn = fcn;
worldContext.filter = filter;
worldContext.fraction = 1.0f;
worldContext.origin = origin;
worldContext.input.proxy = *proxy;
worldContext.input.translation = translation;
worldContext.input.maxFraction = 1.0f;
worldContext.input.canEncroach = false;
worldContext.userContext = context;
WorldRayCastContext worldContext = { world, fcn, filter, 1.0f, context };
// Bound the proxy in origin relative space then lift to a conservative world float box. The tree
// node boxes use the same directed rounding, so the swept box never clips a shape far from the
// origin. Per shape casts re-difference at full precision against the carried origin.
b3AABB localBox = b3MakeAABB( proxy->points, proxy->count, proxy->radius );
b3BoxCastInput treeInput = { b3OffsetAABB( localBox, origin ), translation, 1.0f };
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
b3TreeStats treeResult = b3DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, false,
b3ShapeCastCallback, &worldContext );
b3TreeStats treeResult = b3DynamicTree_BoxCast( world->broadPhase.trees + i, &treeInput, filter.maskBits, false,
b3ShapeCastCallback, &worldContext );
treeStats.nodeVisits += treeResult.nodeVisits;
treeStats.leafVisits += treeResult.leafVisits;
@ -2900,7 +2951,7 @@ b3TreeStats b3World_CastShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3V
return treeStats;
}
input.maxFraction = worldContext.fraction;
treeInput.maxFraction = worldContext.fraction;
}
return treeStats;
@ -2912,10 +2963,13 @@ typedef struct WorldMoverCastContext
b3MoverFilterFcn* fcn;
b3QueryFilter filter;
float fraction;
b3Pos origin;
// origin relative input
b3ShapeCastInput input;
void* userContext;
} WorldMoverCastContext;
static float MoverCastCallback( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context )
static float MoverCastCallback( const b3BoxCastInput* input, int proxyId, uint64_t userData, void* context )
{
B3_UNUSED( proxyId );
@ -2942,10 +2996,15 @@ static float MoverCastCallback( const b3ShapeCastInput* input, int proxyId, uint
}
}
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
// Rebuild from the origin relative input, taking only the advancing fraction from the tree
b3ShapeCastInput localInput = worldContext->input;
localInput.maxFraction = input->maxFraction;
b3CastOutput output = b3ShapeCastShape( shape, transform, input );
// Re-center on the query origin so the per-shape cast stays in float precision far from the origin
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3ToRelativeTransform( b3GetBodyTransformQuick( world, body ), worldContext->origin );
b3CastOutput output = b3ShapeCastShape( shape, transform, &localInput );
if ( output.fraction == 0.0f )
{
// Ignore overlapping shapes
@ -2956,9 +3015,10 @@ static float MoverCastCallback( const b3ShapeCastInput* input, int proxyId, uint
return output.fraction;
}
float b3World_CastMover( b3WorldId worldId, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter,
float b3World_CastMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter,
b3MoverFilterFcn* fcn, void* context )
{
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3World* world = b3GetUnlockedWorldFromId( worldId );
@ -2967,30 +3027,34 @@ float b3World_CastMover( b3WorldId worldId, const b3Capsule* mover, b3Vec3 trans
return 1.0f;
}
b3ShapeCastInput input;
input.proxy = (b3ShapeProxy){ &mover->center1, 2, mover->radius };
input.translation = translation;
input.maxFraction = 1.0f;
input.canEncroach = mover->radius > 0.0f;
WorldMoverCastContext worldContext = {
.world = world,
.fcn = fcn,
.filter = filter,
.fraction = 1.0f,
.origin = origin,
.userContext = context,
};
worldContext.input.proxy = (b3ShapeProxy){ &mover->center1, 2, mover->radius };
worldContext.input.translation = translation;
worldContext.input.maxFraction = 1.0f;
worldContext.input.canEncroach = mover->radius > 0.0f;
// Bound the capsule in origin relative space then lift to a conservative world float box
b3Vec3 centers[2] = { mover->center1, mover->center2 };
b3BoxCastInput treeInput = { b3OffsetAABB( b3MakeAABB( centers, 2, mover->radius ), origin ), translation, 1.0f };
for ( int i = 0; i < b3_bodyTypeCount; ++i )
{
b3DynamicTree_ShapeCast( world->broadPhase.trees + i, &input, filter.maskBits, false, MoverCastCallback, &worldContext );
b3DynamicTree_BoxCast( world->broadPhase.trees + i, &treeInput, filter.maskBits, false, MoverCastCallback,
&worldContext );
if ( worldContext.fraction == 0.0f )
{
return 0.0f;
}
input.maxFraction = worldContext.fraction;
treeInput.maxFraction = worldContext.fraction;
}
return worldContext.fraction;
@ -3033,7 +3097,7 @@ b3Vec3 b3World_GetGravity( b3WorldId worldId )
typedef struct ExplosionContext
{
b3World* world;
b3Vec3 position;
b3Pos position;
float radius;
float falloff;
float impulsePerArea;
@ -3056,13 +3120,16 @@ static bool ExplosionCallback( int proxyId, uint64_t userData, void* context )
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
B3_ASSERT( body->type == b3_dynamicBody );
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform xf = b3GetBodyTransformQuick( world, body );
// Re-center the explosion into the shape local frame so distance and direction stay precise
// far from the origin. Everything below runs in that near-origin frame.
b3Vec3 localPosition = b3InvTransformWorldPoint( xf, explosionContext->position );
b3DistanceInput input;
input.proxyA = b3MakeShapeProxy( shape );
input.proxyB = (b3ShapeProxy){ &explosionContext->position, 1, 0.0f };
input.transformA = transform;
input.transformB = b3Transform_identity;
input.proxyB = (b3ShapeProxy){ &localPosition, 1, 0.0f };
input.transform = b3Transform_identity;
input.useRadii = true;
b3SimplexCache cache = { 0 };
@ -3082,14 +3149,14 @@ static bool ExplosionCallback( int proxyId, uint64_t userData, void* context )
return true;
}
// Witness point is already in the body local query frame
b3Vec3 closestPoint = output.pointA;
if ( output.distance == 0.0f )
{
b3Vec3 localCentroid = b3GetShapeCentroid( shape );
closestPoint = b3TransformPoint( transform, localCentroid );
closestPoint = b3GetShapeCentroid( shape );
}
b3Vec3 direction = b3Sub( closestPoint, explosionContext->position );
b3Vec3 direction = b3Sub( closestPoint, localPosition );
if ( b3LengthSquared( direction ) > 100.0f * FLT_EPSILON * FLT_EPSILON )
{
direction = b3Normalize( direction );
@ -3107,15 +3174,17 @@ static bool ExplosionCallback( int proxyId, uint64_t userData, void* context )
}
float magnitude = explosionContext->impulsePerArea * area * scale * shape->explosionScale;
b3Vec3 impulse = b3MulSV( magnitude, direction );
b3Vec3 impulse = b3MulSV( magnitude, b3RotateVector( xf.q, direction ) );
int localIndex = body->localIndex;
b3SolverSet* set = b3Array_Get( world->solverSets, b3_awakeSet );
b3BodyState* state = b3Array_Get( set->bodyStates, localIndex );
b3BodySim* bodySim = b3Array_Get( set->bodySims, localIndex );
state->linearVelocity = b3MulAdd( state->linearVelocity, bodySim->invMass, impulse );
state->angularVelocity = b3Add(
state->angularVelocity, b3MulMV( bodySim->invInertiaWorld, b3Cross( b3Sub( closestPoint, bodySim->center ), impulse ) ) );
// Lever arm from the center of mass to the closest point, rotated to world
b3Vec3 r = b3RotateVector( xf.q, b3Sub( closestPoint, bodySim->localCenter ) );
state->angularVelocity = b3Add( state->angularVelocity, b3MulMV( bodySim->invInertiaWorld, b3Cross( r, impulse ) ) );
return true;
}
@ -3123,12 +3192,12 @@ static bool ExplosionCallback( int proxyId, uint64_t userData, void* context )
void b3World_Explode( b3WorldId worldId, const b3ExplosionDef* explosionDef )
{
uint64_t maskBits = explosionDef->maskBits;
b3Vec3 position = explosionDef->position;
b3Pos position = explosionDef->position;
float radius = explosionDef->radius;
float falloff = explosionDef->falloff;
float impulsePerArea = explosionDef->impulsePerArea;
B3_ASSERT( b3IsValidVec3( position ) );
B3_ASSERT( b3IsValidPosition( position ) );
B3_ASSERT( b3IsValidFloat( radius ) && radius >= 0.0f );
B3_ASSERT( b3IsValidFloat( falloff ) && falloff >= 0.0f );
B3_ASSERT( b3IsValidFloat( impulsePerArea ) );
@ -3144,9 +3213,10 @@ void b3World_Explode( b3WorldId worldId, const b3ExplosionDef* explosionDef )
struct ExplosionContext explosionContext = { world, position, radius, falloff, impulsePerArea };
float totalRadius = radius + falloff;
b3Vec3 r = { totalRadius, totalRadius, totalRadius };
b3AABB aabb = { b3Sub( position, r ), b3Add( position, r ) };
// The broad-phase tree is float, so translate a local query box out to world with outward rounding
float extent = radius + falloff;
b3AABB localBox = { { -extent, -extent, -extent }, { extent, extent, extent } };
b3AABB aabb = b3OffsetAABB( localBox, position );
b3DynamicTree_Query( world->broadPhase.trees + b3_dynamicBody, aabb, maskBits, false, ExplosionCallback, &explosionContext );

View file

@ -53,7 +53,7 @@ enum b3SetType
typedef struct b3DebugPoint
{
b3Vec3 p;
b3Pos p;
int label;
float value;
b3HexColor color;
@ -61,7 +61,7 @@ typedef struct b3DebugPoint
typedef struct b3DebugLine
{
b3Vec3 p1, p2;
b3Pos p1, p2;
int label;
b3HexColor color;
} b3DebugLine;

View file

@ -94,15 +94,15 @@ float b3PrismaticJoint_GetTranslation( b3JointId jointId )
{
b3World* world = b3GetWorld( jointId.world0 );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_prismaticJoint );
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3Vec3 jointAxis = b3RotateVector( base->localFrameA.q, b3Vec3_axisX );
jointAxis = b3RotateVector( transformA.q, jointAxis );
b3Vec3 anchorA = b3RotateVector( transformA.q, base->localFrameA.p );
b3Vec3 anchorB = b3RotateVector( transformB.q, base->localFrameB.p );
b3Vec3 d = b3Add( b3Sub( transformB.p, transformA.p ), b3Sub( anchorB, anchorA ) );
b3Vec3 d = b3Add( b3SubPos( transformB.p, transformA.p ), b3Sub( anchorB, anchorA ) );
float translation = b3Dot( d, jointAxis );
return translation;
}
@ -206,7 +206,7 @@ float b3PrismaticJoint_GetMaxMotorForce( b3JointId jointId )
b3Vec3 b3GetPrismaticJointForce( b3World* world, b3JointSim* base )
{
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3PrismaticJoint* joint = &base->prismaticJoint;
// impulse in joint space
@ -229,7 +229,7 @@ b3Vec3 b3GetPrismaticJointForce( b3World* world, b3JointSim* base )
b3Vec3 b3GetPrismaticJointTorque( b3World* world, b3JointSim* base )
{
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3PrismaticJoint* joint = &base->prismaticJoint;
b3Vec3 torque = b3MulSV( world->inv_h, joint->angularImpulse );
@ -275,7 +275,7 @@ void b3PreparePrismaticJoint( b3JointSim* base, b3StepContext* context )
joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q );
joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
joint->rotationMass = b3InvertMatrix( invInertiaSum );
// Initial joint axes in world space
@ -631,10 +631,10 @@ void b3SolvePrismaticJoint( b3JointSim* base, b3StepContext* context, bool useBi
}
}
void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale )
void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale )
{
b3Transform frameA = b3MulTransforms( transformA, base->localFrameA );
b3Transform frameB = b3MulTransforms( transformB, base->localFrameB );
b3WorldTransform frameA = b3MulWorldTransforms( transformA, base->localFrameA );
b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB );
b3Matrix3 R = b3MakeMatrixFromQuat( frameA.q );
b3Vec3 axis = R.cx;
@ -642,22 +642,22 @@ void b3DrawPrismaticJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform tran
b3Vec3 perpZ = R.cz;
float s = 0.2f * scale;
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, s, perpY ), b3_colorGreen, draw->context );
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, s, perpZ ), b3_colorBlue, draw->context );
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( s, perpY ) ), b3_colorGreen, draw->context );
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( s, perpZ ) ), b3_colorBlue, draw->context );
b3PrismaticJoint* joint = &base->prismaticJoint;
if ( joint->enableLimit )
{
b3Vec3 p1 = b3MulAdd( frameA.p, joint->lowerTranslation, axis );
b3Vec3 p2 = b3MulAdd( frameA.p, joint->upperTranslation, axis );
b3Pos p1 = b3OffsetPos( frameA.p, b3MulSV( joint->lowerTranslation, axis ) );
b3Pos p2 = b3OffsetPos( frameA.p, b3MulSV( joint->upperTranslation, axis ) );
draw->DrawSegmentFcn( p1, p2, b3_colorOrange, draw->context );
draw->DrawPointFcn( p1, 10.0f, b3_colorGreen, draw->context );
draw->DrawPointFcn( p2, 10.0f, b3_colorRed, draw->context );
}
else
{
b3Vec3 p1 = b3MulSub( frameA.p, 0.5f * scale, axis );
b3Vec3 p2 = b3MulAdd( frameA.p, 0.5f * scale, axis );
b3Pos p1 = b3OffsetPos( frameA.p, b3MulSV( -0.5f * scale, axis ) );
b3Pos p2 = b3OffsetPos( frameA.p, b3MulSV( 0.5f * scale, axis ) );
draw->DrawSegmentFcn( p1, p2, b3_colorOrange, draw->context );
}

View file

@ -86,8 +86,8 @@ float b3RevoluteJoint_GetAngle( b3JointId jointId )
{
b3World* world = b3GetWorld( jointId.world0 );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_revoluteJoint );
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3Quat quatA = b3MulQuat( transformA.q, base->localFrameA.q );
b3Quat quatB = b3MulQuat( transformB.q, base->localFrameB.q );
@ -208,7 +208,7 @@ b3Vec3 b3GetRevoluteJointForce( b3World* world, b3JointSim* base )
b3Vec3 b3GetRevoluteJointTorque( b3World* world, b3JointSim* base )
{
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3RevoluteJoint* joint = &base->revoluteJoint;
b3Vec3 axis = b3RotateVector( base->localFrameA.q, b3Vec3_axisZ );
axis = b3RotateVector( transformA.q, axis );
@ -274,7 +274,7 @@ void b3PrepareRevoluteJoint( b3JointSim* base, b3StepContext* context )
joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q );
joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
{
// Rotation axis is the z-axis of body A.
@ -587,19 +587,19 @@ void b3SolveRevoluteJoint( b3JointSim* base, b3StepContext* context, bool useBia
}
}
void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale )
void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale )
{
b3Transform frameA = b3MulTransforms( transformA, base->localFrameA );
b3WorldTransform frameA = b3MulWorldTransforms( transformA, base->localFrameA );
float length1 = 0.1f * scale;
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisX ) ), b3_colorRed,
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length1, b3RotateVector( frameA.q, b3Vec3_axisX ) ) ), b3_colorRed,
draw->context );
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisY ) ), b3_colorGreen,
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length1, b3RotateVector( frameA.q, b3Vec3_axisY ) ) ), b3_colorGreen,
draw->context );
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisZ ) ), b3_colorBlue,
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length1, b3RotateVector( frameA.q, b3Vec3_axisZ ) ) ), b3_colorBlue,
draw->context );
b3Transform frameB = b3MulTransforms( transformB, base->localFrameB );
b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB );
b3RevoluteJoint* joint = &base->revoluteJoint;
enum { kSliceCount = 16 };
@ -631,19 +631,19 @@ void b3DrawRevoluteJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform trans
if ( index == 0 )
{
draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, vertex1 ), b3_colorCyan, draw->context );
draw->DrawSegmentFcn( frameA.p, b3TransformWorldPoint( frameA, vertex1 ), b3_colorCyan, draw->context );
}
if ( index == kSliceCount - 1 )
{
draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex2 ), frameA.p, b3_colorCyan, draw->context );
draw->DrawSegmentFcn( b3TransformWorldPoint( frameA, vertex2 ), frameA.p, b3_colorCyan, draw->context );
}
draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex1 ), b3TransformPoint( frameA, vertex2 ), b3_colorCyan,
draw->DrawSegmentFcn( b3TransformWorldPoint( frameA, vertex1 ), b3TransformWorldPoint( frameA, vertex2 ), b3_colorCyan,
draw->context );
}
float twistAngle = b3GetTwistAngle( relQ );
b3Vec3 p2 = { wedgeRadius * b3Cos( twistAngle ), wedgeRadius * b3Sin( twistAngle ), 0.0f };
draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, p2 ), b3_colorYellow, draw->context );
draw->DrawSegmentFcn( frameA.p, b3TransformWorldPoint( frameA, p2 ), b3_colorYellow, draw->context );
}
}

View file

@ -148,7 +148,7 @@ static bool b3SensorQueryCallback( int proxyId, uint64_t userData, void* context
}
}
b3Transform otherTransform = b3GetBodyTransform( world, otherShape->bodyId );
b3Transform otherTransform = b3ToRelativeTransform( b3GetBodyTransform( world, otherShape->bodyId ), b3Pos_zero );
bool overlap = b3OverlapSensor( sensorShape, queryContext->transform, otherShape, otherTransform );
if ( overlap == false )
@ -217,7 +217,7 @@ static void b3SensorTask( int startIndex, int endIndex, int workerIndex, void* c
continue;
}
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3Transform transform = b3ToRelativeTransform( b3GetBodyTransformQuick( world, body ), b3Pos_zero );
b3SensorQueryContext queryContext = {
.world = world,

View file

@ -77,19 +77,13 @@ static float b3ComputeShapeMargin( b3Shape* shape )
return b3MinFloat( B3_MAX_AABB_MARGIN, B3_AABB_MARGIN_FRACTION * margin );
}
static void b3UpdateShapeAABBs( b3Shape* shape, b3Transform transform, b3BodyType proxyType )
static void b3UpdateShapeAABBs( b3Shape* shape, b3WorldTransform transform, b3BodyType proxyType )
{
// Compute a bounding box with a speculative margin
const float speculativeDistance = B3_SPECULATIVE_DISTANCE;
const float aabbMargin = shape->aabbMargin;
b3AABB aabb = b3ComputeShapeAABB( shape, transform );
aabb.lowerBound.x -= speculativeDistance;
aabb.lowerBound.y -= speculativeDistance;
aabb.lowerBound.z -= speculativeDistance;
aabb.upperBound.x += speculativeDistance;
aabb.upperBound.y += speculativeDistance;
aabb.upperBound.z += speculativeDistance;
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeDistance );
shape->aabb = aabb;
// Smaller margin for static bodies. Cannot be zero due to TOI tolerance.
@ -102,11 +96,9 @@ static void b3UpdateShapeAABBs( b3Shape* shape, b3Transform transform, b3BodyTyp
fatAABB.upperBound.y = aabb.upperBound.y + margin;
fatAABB.upperBound.z = aabb.upperBound.z + margin;
shape->fatAABB = fatAABB;
B3_VALIDATE( b3IsSaneAABB( fatAABB ) );
}
static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3Transform bodyTransform, const b3ShapeDef* def,
static b3Shape* b3CreateShapeInternal( b3World* world, b3Body* body, b3WorldTransform bodyTransform, const b3ShapeDef* def,
const void* geometry, b3ShapeType shapeType, b3Transform shapeTransform, b3Vec3 scale,
bool haveShapeTransform )
{
@ -297,7 +289,7 @@ static b3ShapeId b3CreateShape( b3BodyId bodyId, const b3ShapeDef* def, const vo
world->locked = true;
b3Transform bodyTransform = b3GetBodyTransformQuick( world, body );
b3WorldTransform bodyTransform = b3GetBodyTransformQuick( world, body );
b3Shape* shape =
b3CreateShapeInternal( world, body, bodyTransform, def, geometry, shapeType, transform, scale, haveTransform );
@ -521,6 +513,26 @@ b3AABB b3ComputeShapeAABB( const b3Shape* shape, b3Transform transform )
}
}
b3AABB b3ComputeFatShapeAABB( const b3Shape* shape, b3WorldTransform transform, float extra )
{
b3Vec3 r = { extra, extra, extra };
#if defined( BOX3D_DOUBLE_PRECISION )
// Build the box in the body local frame, inflate, then translate by the double origin and
// round outward. Inflating before the single rounding matters far from the origin where the
// float margin would otherwise vanish.
b3Transform rotation = { b3Vec3_zero, transform.q };
b3AABB localBox = b3ComputeShapeAABB( shape, rotation );
localBox.lowerBound = b3Sub( localBox.lowerBound, r );
localBox.upperBound = b3Add( localBox.upperBound, r );
return b3OffsetAABB( localBox, transform.p );
#else
b3AABB aabb = b3ComputeShapeAABB( shape, transform );
aabb.lowerBound = b3Sub( aabb.lowerBound, r );
aabb.upperBound = b3Add( aabb.upperBound, r );
return aabb;
#endif
}
b3AABB b3ComputeSweptShapeAABB( const b3Shape* shape, const b3Sweep* sweep, float time )
{
B3_ASSERT( 0.0f <= time && time <= 1.0f );
@ -894,7 +906,7 @@ int b3CollideMover( b3PlaneResult* planes, int planeCapacity, const b3Shape* sha
return planeCount;
}
void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3Transform transform, bool forcePairCreation )
void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3WorldTransform transform, bool forcePairCreation )
{
B3_ASSERT( shape->proxyKey == B3_NULL_INDEX );
@ -1081,57 +1093,31 @@ const char* b3Shape_GetName( b3ShapeId shapeId )
}
// todo no tests
b3CastOutput b3Shape_RayCast( b3ShapeId shapeId, const b3RayCastInput* input )
b3WorldCastOutput b3Shape_RayCast( b3ShapeId shapeId, b3Pos origin, b3Vec3 translation )
{
B3_ASSERT( b3IsValidPosition( origin ) );
B3_ASSERT( b3IsValidVec3( translation ) );
b3World* world = b3GetWorld( shapeId.world0 );
b3Shape* shape = b3GetShape( world, shapeId );
b3Transform transform = b3GetBodyTransform( world, shape->bodyId );
// Re-center on the origin so the cast runs in float precision far from the world origin
b3Transform transform = b3ToRelativeTransform( b3GetBodyTransform( world, shape->bodyId ), origin );
// input in local coordinates
b3RayCastInput localInput;
localInput.origin = b3InvTransformPoint( transform, input->origin );
localInput.translation = b3InvRotateVector( transform.q, input->translation );
localInput.maxFraction = input->maxFraction;
// The ray starts at the origin, so its origin in the re-centered frame is zero
b3RayCastInput input = { b3Vec3_zero, translation, 1.0f };
b3CastOutput output = { 0 };
switch ( shape->type )
{
case b3_capsuleShape:
output = b3RayCastCapsule( &shape->capsule, &localInput );
break;
case b3_compoundShape:
output = b3RayCastCompound( shape->compound, &localInput );
break;
case b3_sphereShape:
output = b3RayCastSphere( &shape->sphere, &localInput );
break;
case b3_meshShape:
output = b3RayCastMesh( &shape->mesh, &localInput );
break;
case b3_hullShape:
output = b3RayCastHull( shape->hull, &localInput );
break;
case b3_heightShape:
output = b3RayCastHeightField( shape->heightField, &localInput );
break;
default:
B3_ASSERT( false );
return output;
}
if ( output.hit )
{
// convert to world coordinates
output.normal = b3RotateVector( transform.q, output.normal );
output.point = b3TransformPoint( transform, output.point );
}
// Lift the re-centered float result back to a world position
b3CastOutput local = b3RayCastShape( shape, transform, &input );
b3WorldCastOutput output;
output.normal = local.normal;
output.point = b3OffsetPos( origin, local.point );
output.fraction = local.fraction;
output.iterations = local.iterations;
output.triangleIndex = local.triangleIndex;
output.childIndex = local.childIndex;
output.materialIndex = local.materialIndex;
output.hit = local.hit;
return output;
}
@ -1280,7 +1266,7 @@ static void b3ResetProxy( b3World* world, b3Shape* shape, bool wakeBodies, bool
}
}
b3Transform transform = b3GetBodyTransformQuick( world, body );
b3WorldTransform transform = b3GetBodyTransformQuick( world, body );
if ( shape->proxyKey != B3_NULL_INDEX )
{
b3BodyType proxyType = B3_PROXY_TYPE( shape->proxyKey );
@ -1739,19 +1725,20 @@ b3Vec3 b3Shape_GetClosestPoint( b3ShapeId shapeId, b3Vec3 target )
b3Shape* shape = b3GetShape( world, shapeId );
b3Body* body = b3Array_Get( world->bodies, shape->bodyId );
b3Transform transform = b3GetBodyTransformQuick( world, body );
// Low level closest point query is a documented float carve-out far from the origin
b3Transform transform = b3ToRelativeTransform( b3GetBodyTransformQuick( world, body ), b3Pos_zero );
b3DistanceInput input;
input.proxyA = b3MakeShapeProxy( shape );
input.proxyB = (b3ShapeProxy){ &target, 1, 0.0f };
input.transformA = transform;
input.transformB = b3Transform_identity;
input.transform = b3InvMulTransforms( transform, b3Transform_identity );
input.useRadii = true;
b3SimplexCache cache = { 0 };
b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 );
return output.pointA;
// Witness point comes back in frame A, lift it back to the query frame
return b3TransformPoint( transform, output.pointA );
}
#define B3_DEBUG_WIND 0
@ -1804,7 +1791,8 @@ void b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift,
B3_ASSERT( body->setIndex == b3_awakeSet );
b3BodyState* state = b3GetBodyState( world, body );
b3Transform transform = sim->transform;
// Only the rotation is used below, so the demoted world transform is exact
b3Transform transform = b3ToRelativeTransform( sim->transform, b3Pos_zero );
float lengthUnits = b3GetLengthUnitsPerMeter();
float volumeUnits = lengthUnits * lengthUnits * lengthUnits;
@ -1935,8 +1923,8 @@ void b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift,
if ( lineIndex < B3_DEBUG_LINE_CAPACITY )
{
b3DebugLine* line = world->taskContexts.data[0].lines + lineIndex;
line->p1 = b3Add( b3MulMV( matrix, localCenter ), transform.p );
line->p2 = b3Add( line->p1, deltaForce );
line->p1 = b3OffsetPos( sim->transform.p, b3MulMV( matrix, localCenter ) );
line->p2 = b3OffsetPos( line->p1, deltaForce );
line->label = i;
line->color = b3_colorBlanchedAlmond;
world->taskContexts.data[0].lineCount += 1;

View file

@ -57,7 +57,7 @@ typedef struct b3Shape
} b3Shape;
void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3Transform transform, bool forcePairCreation );
void b3CreateShapeProxy( b3Shape* shape, b3BroadPhase* bp, b3BodyType type, b3WorldTransform transform, bool forcePairCreation );
void b3DestroyShapeProxy( b3Shape* shape, b3BroadPhase* bp );
void b3DestroyShapeAllocations( b3World* world, b3Shape* shape );
@ -69,6 +69,10 @@ b3AABB b3ComputeSweptSphereAABB( const b3Sphere* shape, b3Transform xf1, b3Trans
b3AABB b3ComputeSweptCapsuleAABB( const b3Capsule* shape, b3Transform xf1, b3Transform xf2 );
b3AABB b3ComputeShapeAABB( const b3Shape* shape, b3Transform transform );
// Conservative world AABB for a shape inflated by extra margin. In double precision mode the
// box is built in the body local frame, translated by the double origin, and rounded outward.
b3AABB b3ComputeFatShapeAABB( const b3Shape* shape, b3WorldTransform transform, float extra );
b3AABB b3ComputeSweptShapeAABB( const b3Shape* shape, const b3Sweep* sweep, float time );
b3Vec3 b3GetShapeCentroid( const b3Shape* shape );
float b3GetShapeArea( const b3Shape* shape );

View file

@ -319,6 +319,8 @@ typedef struct b3ContinuousContext
b3Shape* fastShape;
b3Vec3 centroid1, centroid2;
b3Sweep sweep;
// World base for re-centering sweeps. Keeps TOI in float precision far from the origin.
b3Pos base;
float fraction;
b3SensorHit sensorHits[B2_MAX_CONTINUOUS_SENSOR_HITS];
float sensorFractions[B2_MAX_CONTINUOUS_SENSOR_HITS];
@ -406,7 +408,7 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
}
// todo does having a sweep on shapeA help with bullets?
b3Sweep sweepA = b3MakeSweep( bodySim );
b3Sweep sweepA = b3MakeRelativeSweep( bodySim, continuousContext->base );
// Time of impact versus shape. Supports all shape types
b3TOIOutput output = b3ShapeTimeOfImpact( shape, fastShape, &sweepA, &continuousContext->sweep, continuousContext->fraction );
@ -436,7 +438,8 @@ static bool b3ContinuousQueryCallback( int proxyId, uint64_t userData, void* con
{
b3ShapeId shapeIdA = { shape->id + 1, world->worldId, shape->generation };
b3ShapeId shapeIdB = { fastShape->id + 1, world->worldId, fastShape->generation };
didHit = world->preSolveFcn( shapeIdA, shapeIdB, output.point, output.normal, world->preSolveContext );
b3Pos point = b3OffsetPos( continuousContext->base, output.point );
didHit = world->preSolveFcn( shapeIdA, shapeIdB, point, output.normal, world->preSolveContext );
}
if ( didHit )
@ -462,7 +465,10 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
b3BodySim* fastBodySim = b3Array_Get( awakeSet->bodySims, bodySimIndex );
B3_ASSERT( fastBodySim->flags & b3_isFast );
b3Sweep sweep = b3MakeSweep( fastBodySim );
// Re-center the sweep on the fast body so the TOI and the swept query stay in float precision
b3Pos base = fastBodySim->center0;
b3Sweep sweep = b3MakeRelativeSweep( fastBodySim, base );
b3Transform xf1;
xf1.q = sweep.q1;
@ -480,6 +486,7 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
b3ContinuousContext context = { 0 };
context.world = world;
context.sweep = sweep;
context.base = base;
context.fastBodySim = fastBodySim;
context.fraction = 1.0f;
@ -496,7 +503,8 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
context.centroid2 = b3TransformPoint( xf2, fastShape->localCentroid );
b3AABB box1 = fastShape->aabb;
b3AABB box2 = b3ComputeShapeAABB( fastShape, xf2 );
// xf2 is relative to the base, so translate the box back to world space, rounding outward
b3AABB box2 = b3OffsetAABB( b3ComputeShapeAABB( fastShape, xf2 ), base );
// Store this to avoid double computation in the case there is no impact event
fastShape->aabb = box2;
@ -524,21 +532,22 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
}
const float speculativeScalar = B3_SPECULATIVE_DISTANCE;
const b3Vec3 speculativeMargin = { speculativeScalar, speculativeScalar, speculativeScalar };
if ( context.fraction < 1.0f )
{
// Handle time of impact event
// Handle time of impact event. The sweep is relative to the base, so re-add the base
// to return the advanced pose to world space.
b3Quat q = b3NLerp( sweep.q1, sweep.q2, context.fraction );
b3Vec3 c = b3Lerp( sweep.c1, sweep.c2, context.fraction );
b3Vec3 origin = b3Sub( c, b3RotateVector( q, sweep.localCenter ) );
// Advance body
b3Transform transform = { origin, q };
b3WorldTransform transform = { b3OffsetPos( base, origin ), q };
b3Pos center = b3OffsetPos( base, c );
fastBodySim->transform = transform;
fastBodySim->center = c;
fastBodySim->center = center;
fastBodySim->rotation0 = q;
fastBodySim->center0 = c;
fastBodySim->center0 = center;
// Prepare AABBs for broad-phase.
// Even though a body is fast, it may not move much. So the AABB may not need enlargement.
@ -549,9 +558,7 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
b3Shape* shape = b3Array_Get( world->shapes, shapeId );
// Must recompute aabb at the interpolated transform
b3AABB aabb = b3ComputeShapeAABB( shape, transform );
aabb.lowerBound = b3Sub( aabb.lowerBound, speculativeMargin );
aabb.upperBound = b3Add( aabb.upperBound, speculativeMargin );
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeScalar );
shape->aabb = aabb;
if ( b3AABB_Contains( shape->fatAABB, aabb ) == false )
@ -592,12 +599,6 @@ static void b3SolveContinuous( b3World* world, int bodySimIndex, b3TaskContext*
.upperBound = b3Add( shape->aabb.upperBound, aabbMargin ),
};
if ( b3IsSaneAABB( shape->fatAABB ) == false )
{
b3Vec3 c = fastBodySim->center;
b3Log( "body %s out of bounds at %g %g %g", fastBody->name, c.x, c.y, c.z );
}
shape->enlargedAABB = true;
fastBodySim->flags |= b3_enlargeBounds;
}
@ -650,7 +651,6 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
b3BitSet* awakeIslandBitSet = &taskContext->awakeIslandBitSet;
const float speculativeScalar = B3_SPECULATIVE_DISTANCE;
const b3Vec3 speculativeMargin = { speculativeScalar, speculativeScalar, speculativeScalar };
for ( int simIndex = startIndex; simIndex < endIndex; ++simIndex )
{
@ -670,7 +670,7 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
B3_ASSERT( b3IsValidVec3( v ) );
B3_ASSERT( b3IsValidVec3( w ) );
sim->center = b3Add( sim->center, state->deltaPosition );
sim->center = b3OffsetPos( sim->center, state->deltaPosition );
sim->transform.q = b3NormalizeQuat( b3MulQuat( state->deltaRotation, sim->transform.q ) );
// Use the velocity of the farthest point on the body to account for rotation.
@ -691,7 +691,7 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
state->deltaPosition = b3Vec3_zero;
state->deltaRotation = b3Quat_identity;
sim->transform.p = b3Sub( sim->center, b3RotateVector( sim->transform.q, sim->localCenter ) );
sim->transform.p = b3OffsetPos( sim->center, b3Neg( b3RotateVector( sim->transform.q, sim->localCenter ) ) );
// cache miss here, however I need the shape list below
b3Body* body = bodies + sim->bodyId;
@ -777,7 +777,7 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
}
// Update shapes AABBs
b3Transform transform = sim->transform;
b3WorldTransform transform = sim->transform;
bool isFast = ( sim->flags & b3_isFast ) != 0;
int shapeId = body->headShapeId;
while ( shapeId != B3_NULL_INDEX )
@ -795,9 +795,7 @@ static void b3FinalizeBodiesTask( int startIndex, int endIndex, int workerIndex,
}
else
{
b3AABB aabb = b3ComputeShapeAABB( shape, transform );
aabb.lowerBound = b3Sub( aabb.lowerBound, speculativeMargin );
aabb.upperBound = b3Add( aabb.upperBound, speculativeMargin );
b3AABB aabb = b3ComputeFatShapeAABB( shape, transform, speculativeScalar );
shape->aabb = aabb;
B3_ASSERT( shape->enlargedAABB == false );
@ -1972,7 +1970,7 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
b3Body* bodyB = b3Array_Get( world->bodies, shapeB->bodyId );
b3BodySim* simA = b3GetBodySim( world, bodyA );
b3BodySim* simB = b3GetBodySim( world, bodyB );
b3Vec3 midCenter = b3Lerp( simA->center, simB->center, 0.5f );
b3Pos midCenter = b3LerpPosition( simA->center, simB->center, 0.5f );
b3ContactHitEvent event = { 0 };
event.approachSpeed = threshold;
@ -1993,7 +1991,7 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
if ( approachSpeed > event.approachSpeed && mp->totalNormalImpulse > 0.0f )
{
event.approachSpeed = approachSpeed;
event.point = b3Add( midCenter, b3Lerp( mp->anchorA, mp->anchorB, 0.5f ) );
event.point = b3OffsetPos( midCenter, b3Lerp( mp->anchorA, mp->anchorB, 0.5f ) );
event.normal = manifold->normal;
triangleIndex = mp->triangleIndex;
found = true;
@ -2106,8 +2104,6 @@ void b3Solve( b3World* world, b3StepContext* stepContext )
// A fast body may have been flagged as enlarged despite having no shapes enlarged.
if ( shape->enlargedAABB )
{
B3_VALIDATE( b3IsSaneAABB( shape->fatAABB ) );
b3BroadPhase_EnlargeProxy( broadPhase, shape->proxyKey, shape->fatAABB );
shape->enlargedAABB = false;
}

View file

@ -22,7 +22,9 @@ b3MassData b3ComputeSphereMass( const b3Sphere* shape, float density )
b3MassData out;
out.mass = mass;
out.center = center;
out.inertia = b3AddMM( b3MakeDiagonalMatrix( ixx, ixx, ixx ), b3Steiner( mass, center ) );
// Inertia about the center of mass
out.inertia = b3MakeDiagonalMatrix( ixx, ixx, ixx );
return out;
}
@ -47,8 +49,7 @@ bool b3OverlapSphere( const b3Sphere* shape, b3Transform shapeTransform, const b
b3DistanceInput input;
input.proxyA = ( b3ShapeProxy ){ &shape->center, 1, shape->radius };
input.proxyB = *proxy;
input.transformA = shapeTransform;
input.transformB = b3Transform_identity;
input.transform = b3InvMulTransforms( shapeTransform, b3Transform_identity );
input.useRadii = true;
b3SimplexCache cache = { 0 };
@ -206,8 +207,7 @@ b3CastOutput b3ShapeCastSphere( const b3Sphere* sphere, const b3ShapeCastInput*
b3ShapeCastPairInput pairInput;
pairInput.proxyA = ( b3ShapeProxy ){ &sphere->center, 1, sphere->radius };
pairInput.proxyB = input->proxy;
pairInput.transformA = b3Transform_identity;
pairInput.transformB = b3Transform_identity;
pairInput.transform = b3Transform_identity;
pairInput.translationB = input->translation;
pairInput.maxFraction = input->maxFraction;
pairInput.canEncroach = input->canEncroach;

View file

@ -46,8 +46,8 @@ float b3SphericalJoint_GetConeAngle( b3JointId jointId )
{
b3World* world = b3GetWorld( jointId.world0 );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3Quat quatA = b3MulQuat( transformA.q, base->localFrameA.q );
b3Quat quatB = b3MulQuat( transformB.q, base->localFrameB.q );
@ -109,8 +109,8 @@ float b3SphericalJoint_GetTwistAngle( b3JointId jointId )
{
b3World* world = b3GetWorld( jointId.world0 );
b3JointSim* base = b3GetJointSimCheckType( jointId, b3_sphericalJoint );
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformB = b3GetBodyTransform( world, base->bodyIdB );
b3Quat quatA = b3MulQuat( transformA.q, base->localFrameA.q );
b3Quat quatB = b3MulQuat( transformB.q, base->localFrameB.q );
@ -231,8 +231,8 @@ b3Vec3 b3GetSphericalJointForce( b3World* world, b3JointSim* base )
b3Vec3 b3GetSphericalJointTorque( b3World* world, b3JointSim* base )
{
b3Transform xfA = b3GetBodyTransform( world, base->bodyIdA );
b3Transform xfB = b3GetBodyTransform( world, base->bodyIdB );
b3WorldTransform xfA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform xfB = b3GetBodyTransform( world, base->bodyIdB );
b3Quat qA = b3MulQuat( xfA.q, base->localFrameA.q );
b3Quat qB = b3MulQuat( xfB.q, base->localFrameB.q );
@ -300,7 +300,7 @@ void b3PrepareSphericalJoint( b3JointSim* base, b3StepContext* context )
joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q );
joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
// Cone axis is the z-axis of body A.
b3Vec3 coneAxis = b3RotateVector( joint->frameA.q, b3Vec3_axisZ );
@ -630,22 +630,22 @@ void b3SolveSphericalJoint( b3JointSim* base, b3StepContext* context, bool useBi
}
}
void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale )
void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale )
{
b3Transform frameA = b3MulTransforms( transformA, base->localFrameA );
b3WorldTransform frameA = b3MulWorldTransforms( transformA, base->localFrameA );
float length1 = 0.1f * scale;
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisX ) ), b3_colorRed,
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length1, b3RotateVector( frameA.q, b3Vec3_axisX ) ) ), b3_colorRed,
draw->context );
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisY ) ), b3_colorGreen,
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length1, b3RotateVector( frameA.q, b3Vec3_axisY ) ) ), b3_colorGreen,
draw->context );
draw->DrawSegmentFcn( frameA.p, b3MulAdd( frameA.p, length1, b3RotateVector( frameA.q, b3Vec3_axisZ ) ), b3_colorBlue,
draw->DrawSegmentFcn( frameA.p, b3OffsetPos( frameA.p, b3MulSV( length1, b3RotateVector( frameA.q, b3Vec3_axisZ ) ) ), b3_colorBlue,
draw->context );
b3Transform frameB = b3MulTransforms( transformB, base->localFrameB );
b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB );
float length2 = 0.2f * scale;
draw->DrawSegmentFcn( frameB.p, b3MulAdd( frameB.p, length2, b3RotateVector( frameB.q, b3Vec3_axisZ ) ), b3_colorOrange,
draw->DrawSegmentFcn( frameB.p, b3OffsetPos( frameB.p, b3MulSV( length2, b3RotateVector( frameB.q, b3Vec3_axisZ ) ) ), b3_colorOrange,
draw->context );
b3SphericalJoint* joint = &base->sphericalJoint;
@ -678,20 +678,20 @@ void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform tran
if ( index == 0 )
{
draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, vertex1 ), b3_colorCyan, draw->context );
draw->DrawSegmentFcn( frameA.p, b3TransformWorldPoint( frameA, vertex1 ), b3_colorCyan, draw->context );
}
if ( index == kSliceCount - 1 )
{
draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex2 ), frameA.p, b3_colorCyan, draw->context );
draw->DrawSegmentFcn( b3TransformWorldPoint( frameA, vertex2 ), frameA.p, b3_colorCyan, draw->context );
}
draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex1 ), b3TransformPoint( frameA, vertex2 ), b3_colorCyan,
draw->DrawSegmentFcn( b3TransformWorldPoint( frameA, vertex1 ), b3TransformWorldPoint( frameA, vertex2 ), b3_colorCyan,
draw->context );
}
float twistAngle = b3GetTwistAngle( relQ );
b3Vec3 p2 = { wedgeRadius * b3Cos( twistAngle ), wedgeRadius * b3Sin( twistAngle ), 0.0f };
draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, p2 ), b3_colorYellow, draw->context );
draw->DrawSegmentFcn( frameA.p, b3TransformWorldPoint( frameA, p2 ), b3_colorYellow, draw->context );
}
// Swing limit
@ -709,8 +709,8 @@ void b3DrawSphericalJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform tran
b3Vec3 vertex1 = { coneRadius * b3Cos( phi1 ), coneRadius * b3Sin( phi1 ), coneHeight };
b3Vec3 vertex2 = { coneRadius * b3Cos( phi2 ), coneRadius * b3Sin( phi2 ), coneHeight };
draw->DrawSegmentFcn( frameA.p, b3TransformPoint( frameA, vertex1 ), b3_colorCyan, draw->context );
draw->DrawSegmentFcn( b3TransformPoint( frameA, vertex1 ), b3TransformPoint( frameA, vertex2 ), b3_colorCyan,
draw->DrawSegmentFcn( frameA.p, b3TransformWorldPoint( frameA, vertex1 ), b3_colorCyan, draw->context );
draw->DrawSegmentFcn( b3TransformWorldPoint( frameA, vertex1 ), b3TransformWorldPoint( frameA, vertex2 ), b3_colorCyan,
draw->context );
}
}

View file

@ -346,8 +346,7 @@ void b3CollideCapsuleAndTriangle( b3LocalManifold* manifold, int capacity, const
b3DistanceInput distanceInput;
distanceInput.proxyA = (b3ShapeProxy){ triangleB, 3, 0.0f };
distanceInput.proxyB = (b3ShapeProxy){ &capsuleA->center1, 2, 0.0f };
distanceInput.transformA = b3Transform_identity;
distanceInput.transformB = b3Transform_identity;
distanceInput.transform = b3Transform_identity;
distanceInput.useRadii = false;
b3DistanceOutput distanceOutput = b3ShapeDistance( &distanceInput, cache, NULL, 0 );
@ -1230,8 +1229,7 @@ void b3CollideHullAndTriangle( b3LocalManifold* manifold, int capacity, const b3
.radius = 0.0f,
};
input.proxyB = (b3ShapeProxy){ .points = hullPoints, .count = hullA->vertexCount, .radius = 0.0f };
input.transformA = b3Transform_identity;
input.transformB = b3Transform_identity;
input.transform = b3Transform_identity;
input.useRadii = false;
b3SimplexCache simplexCache = { 0 };

View file

@ -79,23 +79,23 @@ b3ShapeDef b3DefaultShapeDef( void )
return def;
}
static bool b3EmptyDrawShape( void* userShape, b3Transform transform, b3HexColor color, void* context )
static bool b3EmptyDrawShape( void* userShape, b3WorldTransform transform, b3HexColor color, void* context )
{
B3_UNUSED( userShape, transform, color, context );
return false;
}
static void b3EmptyDrawSegment( b3Vec3 p1, b3Vec3 p2, b3HexColor color, void* context )
static void b3EmptyDrawSegment( b3Pos p1, b3Pos p2, b3HexColor color, void* context )
{
B3_UNUSED( p1, p2, color, context );
}
static void b3EmptyDrawTransform( b3Transform transform, void* context )
static void b3EmptyDrawTransform( b3WorldTransform transform, void* context )
{
B3_UNUSED( transform, context );
}
static void b3EmptyDrawPoint( b3Vec3 p, float size, b3HexColor color, void* context )
static void b3EmptyDrawPoint( b3Pos p, float size, b3HexColor color, void* context )
{
B3_UNUSED( p, size, color, context );
}
@ -105,12 +105,12 @@ static void b3EmptyDrawBounds( b3AABB aabb, b3HexColor color, void* context )
B3_UNUSED( aabb, color, context );
}
static void b3EmptyDrawBox( b3Vec3 extents, b3Transform transform, b3HexColor color, void* context )
static void b3EmptyDrawBox( b3Vec3 extents, b3WorldTransform transform, b3HexColor color, void* context )
{
B3_UNUSED( extents, transform, color, context );
}
static void b3EmptyDrawString( b3Vec3 p, const char* s, b3HexColor color, void* context )
static void b3EmptyDrawString( b3Pos p, const char* s, b3HexColor color, void* context )
{
B3_UNUSED( p, s, color, context );
}

View file

@ -110,7 +110,7 @@ void b3PrepareWeldJoint( b3JointSim* base, b3StepContext* context )
joint->frameB.q = b3MulQuat( bodySimB->transform.q, base->localFrameB.q );
joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
joint->angularMass = b3InvertMatrix( invInertiaSum );
if ( joint->linearHertz == 0.0f )
@ -294,10 +294,10 @@ void b3SolveWeldJoint( b3JointSim* base, b3StepContext* context, bool useBias )
}
}
void b3DrawWeldJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale )
void b3DrawWeldJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale )
{
b3Transform frameA = b3MulTransforms( transformA, base->localFrameA );
b3Transform frameB = b3MulTransforms( transformB, base->localFrameB );
b3WorldTransform frameA = b3MulWorldTransforms( transformA, base->localFrameA );
b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB );
b3Vec3 extents = { 0.1f * scale, 0.05f * scale, 0.025f * scale };
draw->DrawBoxFcn( extents, frameA, b3_colorDarkOrange, draw->context );

View file

@ -323,7 +323,7 @@ float b3WheelJoint_GetSteeringTorque( b3JointId jointId )
b3Vec3 b3GetWheelJointForce( b3World* world, b3JointSim* base )
{
b3Transform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WorldTransform transformA = b3GetBodyTransform( world, base->bodyIdA );
b3WheelJoint* joint = &base->wheelJoint;
// impulse in joint space
@ -416,7 +416,7 @@ void b3PrepareWheelJoint( b3JointSim* base, b3StepContext* context )
joint->frameB.p = b3RotateVector( bodySimB->transform.q, b3Sub( base->localFrameB.p, bodySimB->localCenter ) );
// Compute the initial center delta. Incremental position updates are relative to this.
joint->deltaCenter = b3Sub( bodySimB->center, bodySimA->center );
joint->deltaCenter = b3SubPos( bodySimB->center, bodySimA->center );
b3Vec3 rA = joint->frameA.p;
b3Vec3 rB = joint->frameB.p;
@ -988,14 +988,14 @@ void b3WheelJoint_Dump()
}
#endif
void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transformA, b3Transform transformB, float scale )
void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3WorldTransform transformA, b3WorldTransform transformB, float scale )
{
B3_ASSERT( base->type == b3_wheelJoint );
b3WheelJoint* joint = &base->wheelJoint;
b3Transform frameA = b3MulTransforms( transformA, base->localFrameA );
b3Transform frameB = b3MulTransforms( transformB, base->localFrameB );
b3WorldTransform frameA = b3MulWorldTransforms( transformA, base->localFrameA );
b3WorldTransform frameB = b3MulWorldTransforms( transformB, base->localFrameB );
b3Matrix3 matrixA = b3MakeMatrixFromQuat( frameA.q );
b3Matrix3 matrixB = b3MakeMatrixFromQuat( frameB.q );
@ -1004,19 +1004,19 @@ void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transfor
if ( joint->enableSuspensionLimit )
{
b3Vec3 lower = b3MulAdd( frameA.p, joint->lowerSuspensionLimit, matrixA.cx );
b3Vec3 upper = b3MulAdd( frameA.p, joint->upperSuspensionLimit, matrixA.cx );
b3Pos lower = b3OffsetPos( frameA.p, b3MulSV( joint->lowerSuspensionLimit, matrixA.cx ) );
b3Pos upper = b3OffsetPos( frameA.p, b3MulSV( joint->upperSuspensionLimit, matrixA.cx ) );
b3Vec3 perp = matrixA.cy;
draw->DrawSegmentFcn( lower, upper, b3_colorGray, draw->context );
draw->DrawSegmentFcn( b3MulSub( lower, 0.1f * scale, perp ), b3MulAdd( lower, 0.1f * scale, perp ), b3_colorGreen,
draw->context );
draw->DrawSegmentFcn( b3MulSub( upper, 0.1f * scale, perp ), b3MulAdd( upper, 0.1f * scale, perp ), b3_colorRed,
draw->context );
draw->DrawSegmentFcn( b3OffsetPos( lower, b3MulSV( -0.1f * scale, perp ) ), b3OffsetPos( lower, b3MulSV( 0.1f * scale, perp ) ),
b3_colorGreen, draw->context );
draw->DrawSegmentFcn( b3OffsetPos( upper, b3MulSV( -0.1f * scale, perp ) ), b3OffsetPos( upper, b3MulSV( 0.1f * scale, perp ) ),
b3_colorRed, draw->context );
}
else
{
draw->DrawSegmentFcn( b3MulSub( frameA.p, 1.0f * scale, matrixA.cx ), b3MulAdd( frameA.p, 1.0f * scale, matrixA.cx ),
b3_colorGray, draw->context );
draw->DrawSegmentFcn( b3OffsetPos( frameA.p, b3MulSV( -1.0f * scale, matrixA.cx ) ),
b3OffsetPos( frameA.p, b3MulSV( 1.0f * scale, matrixA.cx ) ), b3_colorGray, draw->context );
}
if ( joint->enableSteering && joint->enableSteeringLimit )
@ -1032,7 +1032,7 @@ void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transfor
// b3Quat relQ = b3InvMulQuat( quatA, quatB );
b3Transform frame = {
b3WorldTransform frame = {
.p = frameB.p,
.q = frameA.q,
};
@ -1043,7 +1043,7 @@ void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transfor
float upper = joint->upperSteeringLimit;
b3CosSin cs = b3ComputeCosSin( lower );
b3Vec3 vertex1 = b3TransformPoint( frame, (b3Vec3){ 0.0f, -radius * cs.sine, radius * cs.cosine } );
b3Pos vertex1 = b3TransformWorldPoint( frame, (b3Vec3){ 0.0f, -radius * cs.sine, radius * cs.cosine } );
for ( int index = 0; index < sliceCount; ++index )
{
@ -1051,7 +1051,7 @@ void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transfor
float phi = b3LerpFloat( lower, upper, t2 );
cs = b3ComputeCosSin( phi );
b3Vec3 vertex2 = b3TransformPoint( frame, (b3Vec3){ 0.0f, -radius * cs.sine, radius * cs.cosine } );
b3Pos vertex2 = b3TransformWorldPoint( frame, (b3Vec3){ 0.0f, -radius * cs.sine, radius * cs.cosine } );
if ( index == 0 )
{
@ -1068,8 +1068,8 @@ void b3DrawWheelJoint( b3DebugDraw* draw, b3JointSim* base, b3Transform transfor
}
}
draw->DrawSegmentFcn( b3MulSub( frameB.p, 0.5f * scale, matrixB.cz ), b3MulAdd( frameB.p, 0.5f * scale, matrixB.cz ),
b3_colorMagenta, draw->context );
draw->DrawSegmentFcn( b3OffsetPos( frameB.p, b3MulSV( -0.5f * scale, matrixB.cz ) ),
b3OffsetPos( frameB.p, b3MulSV( 0.5f * scale, matrixB.cz ) ), b3_colorMagenta, draw->context );
draw->DrawPointFcn( frameA.p, 5.0f, b3_colorGray, draw->context );
draw->DrawPointFcn( frameB.p, 5.0f, b3_colorDimGray, draw->context );