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

@ -3,6 +3,7 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
// clang-format off
@ -148,6 +149,9 @@ typedef struct b3Version
/// Get the current version of Box3D
B3_API b3Version b3GetVersion( void );
/// @return true if the library was built with BOX3D_DOUBLE_PRECISION (large world mode)
B3_API bool b3IsDoublePrecision( void );
/**@}*/
//! @cond

View file

@ -16,12 +16,19 @@
* These functions allow you to create a simulation world.
*
* You can add rigid bodies and joint constraints to the world and run the simulation. You can get contact
* information to get contact points and normals as well as events. You can query the world, checking for overlaps and casting rays
* or shapes. There is also debugging information such as debug draw, timing information, and counters. You can find documentation
* here: https://box2d.org/
* information to get contact points and normals as well as events. You can query the world, checking for overlaps and casting
* rays or shapes. There is also debugging information such as debug draw, timing information, and counters. You can find
* documentation here: https://box2d.org/
* @{
*/
#if defined( BOX3D_DOUBLE_PRECISION )
// Force a link error if the application and library disagree on precision. A float app linking
// a double precision library, or the reverse, gets one unresolved external on the first call
// every program makes. CMake consumers inherit the define and cannot mismatch.
#define b3CreateWorld b3CreateWorldDoublePrecision
#endif
/// Create a world for rigid body simulation. A world contains bodies, shapes, and constraints. You may create
/// up to 128 worlds. Each world is completely independent and may be simulated in parallel.
/// @return the world id.
@ -68,8 +75,9 @@ B3_API b3JointEvents b3World_GetJointEvents( b3WorldId worldId );
B3_API b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter filter, b3OverlapResultFcn* fcn,
void* context );
/// Overlap test for all shapes that overlap the provided shape proxy.
B3_API b3TreeStats b3World_OverlapShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3QueryFilter filter,
/// Overlap test for all shapes that overlap the provided shape proxy. The proxy points are relative
/// to the world origin, which lets the query stay precise far from the world origin.
B3_API b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const b3ShapeProxy* proxy, b3QueryFilter filter,
b3OverlapResultFcn* fcn, void* context );
/// Cast a ray into the world to collect shapes in the path of the ray.
@ -82,35 +90,38 @@ B3_API b3TreeStats b3World_OverlapShape( b3WorldId worldId, const b3ShapeProxy*
/// @param fcn A user implemented callback function
/// @param context A user context that is passed along to the callback function
/// @return traversal performance counters
B3_API b3TreeStats b3World_CastRay( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter,
B3_API b3TreeStats b3World_CastRay( b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter,
b3CastResultFcn* fcn, void* context );
/// Cast a ray into the world to collect the closest hit. This is a convenience function. Ignores initial overlap.
/// This is less general than b3World_CastRay() and does not allow for custom filtering.
B3_API b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Vec3 origin, b3Vec3 translation, b3QueryFilter filter );
B3_API b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter );
/// Cast a shape through the world. Similar to a cast ray except that a shape is cast instead of a point.
/// The proxy points are relative to the origin and the hit points come back as world positions, so the
/// cast stays precise far from the world origin.
/// @see b3World_CastRay
B3_API b3TreeStats b3World_CastShape( b3WorldId worldId, const b3ShapeProxy* proxy, b3Vec3 translation, b3QueryFilter filter,
b3CastResultFcn* fcn, void* context );
B3_API b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3ShapeProxy* proxy, b3Vec3 translation,
b3QueryFilter filter, b3CastResultFcn* fcn, void* context );
/// Cast a capsule mover through the world. This is a special shape cast that handles sliding along other shapes while reducing
/// clipping. This is not a good source of information about what the mover is touching. Instead use the planes returned by
/// b3World_CollideMover.
/// @param worldId World to cast the mover against
/// @param mover Capsule mover in world space
/// @param origin World position the mover capsule is relative to
/// @param mover Capsule mover, relative to the origin
/// @param translation Desired mover translation
/// @param filter Contains bit flags to filter unwanted shapes from the results
/// @param fcn Optional callback for custom shape filtering
/// @param context A user context that is passed along to the callback function
/// @return the translation fraction
B3_API float b3World_CastMover( b3WorldId worldId, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter,
B3_API float b3World_CastMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter,
b3MoverFilterFcn* fcn, void* context );
/// Collide a capsule mover with the world, gathering collision planes that can be fed to b3SolvePlanes. Useful for
/// kinematic character movement.
B3_API void b3World_CollideMover( b3WorldId worldId, const b3Capsule* mover, b3QueryFilter filter, b3PlaneResultFcn* fcn,
void* context );
/// kinematic character movement. The mover and the returned planes are relative to the origin.
B3_API void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover, b3QueryFilter filter,
b3PlaneResultFcn* fcn, void* context );
/// Enable/disable sleep. If your application does not need sleeping, you can gain some performance
/// by disabling sleep completely at the world level.
@ -286,24 +297,24 @@ B3_API void b3Body_SetUserData( b3BodyId bodyId, void* userData );
B3_API void* b3Body_GetUserData( b3BodyId bodyId );
/// Get the world position of a body. This is the location of the body origin.
B3_API b3Vec3 b3Body_GetPosition( b3BodyId bodyId );
B3_API b3Pos b3Body_GetPosition( b3BodyId bodyId );
/// Get the world rotation of a body as a quaternion
B3_API b3Quat b3Body_GetRotation( b3BodyId bodyId );
/// Get the world transform of a body.
B3_API b3Transform b3Body_GetTransform( b3BodyId bodyId );
B3_API b3WorldTransform b3Body_GetTransform( b3BodyId bodyId );
/// Set the world transform of a body. This acts as a teleport and is fairly expensive.
/// @note Generally you should create a body with the intended transform.
/// @see b3BodyDef::position and b3BodyDef::rotation
B3_API void b3Body_SetTransform( b3BodyId bodyId, b3Vec3 position, b3Quat rotation );
B3_API void b3Body_SetTransform( b3BodyId bodyId, b3Pos position, b3Quat rotation );
/// Get a local point on a body given a world point
B3_API b3Vec3 b3Body_GetLocalPoint( b3BodyId bodyId, b3Vec3 worldPoint );
B3_API b3Vec3 b3Body_GetLocalPoint( b3BodyId bodyId, b3Pos worldPoint );
/// Get a world point on a body given a local point
B3_API b3Vec3 b3Body_GetWorldPoint( b3BodyId bodyId, b3Vec3 localPoint );
B3_API b3Pos b3Body_GetWorldPoint( b3BodyId bodyId, b3Vec3 localPoint );
/// Get a local vector on a body given a world vector
B3_API b3Vec3 b3Body_GetLocalVector( b3BodyId bodyId, b3Vec3 worldVector );
@ -327,13 +338,13 @@ B3_API void b3Body_SetAngularVelocity( b3BodyId bodyId, b3Vec3 angularVelocity )
/// The result will be close but maybe not exact. This is meant for kinematic bodies.
/// The target is not applied if the velocity would be below the sleep threshold.
/// This will optionally wake the body if asleep, but only if the movement is significant.
B3_API void b3Body_SetTargetTransform( b3BodyId bodyId, b3Transform target, float timeStep, bool wake );
B3_API void b3Body_SetTargetTransform( b3BodyId bodyId, b3WorldTransform target, float timeStep, bool wake );
/// Get the linear velocity of a local point attached to a body. Usually in meters per second.
B3_API b3Vec3 b3Body_GetLocalPointVelocity( b3BodyId bodyId, b3Vec3 localPoint );
/// Get the linear velocity of a world point attached to a body. Usually in meters per second.
B3_API b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Vec3 worldPoint );
B3_API b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Pos worldPoint );
/// Apply a force at a world point. If the force is not applied at the center of mass,
/// it will generate a torque and affect the angular velocity. This optionally wakes up the body.
@ -342,7 +353,7 @@ B3_API b3Vec3 b3Body_GetWorldPointVelocity( b3BodyId bodyId, b3Vec3 worldPoint )
/// @param force The world force vector, usually in newtons (N)
/// @param point The world position of the point of application
/// @param wake Option to wake up the body
B3_API void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Vec3 point, bool wake );
B3_API void b3Body_ApplyForce( b3BodyId bodyId, b3Vec3 force, b3Pos point, bool wake );
/// Apply a force to the center of mass. This optionally wakes up the body.
/// The force is ignored if the body is not awake.
@ -368,7 +379,7 @@ B3_API void b3Body_ApplyTorque( b3BodyId bodyId, b3Vec3 torque, bool wake );
/// @param wake also wake up the body
/// @warning This should be used for one-shot impulses. If you need a steady force,
/// use a force instead, which will work better with the sub-stepping solver.
B3_API void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Vec3 point, bool wake );
B3_API void b3Body_ApplyLinearImpulse( b3BodyId bodyId, b3Vec3 impulse, b3Pos point, bool wake );
/// Apply an impulse to the center of mass. This immediately modifies the velocity.
/// The impulse is ignored if the body is not awake. This optionally wakes the body.
@ -404,7 +415,7 @@ B3_API b3Matrix3 b3Body_GetWorldInverseRotationalInertia( b3BodyId bodyId );
B3_API b3Vec3 b3Body_GetLocalCenterOfMass( b3BodyId bodyId );
/// Get the center of mass position of the body in world space
B3_API b3Vec3 b3Body_GetWorldCenterOfMass( b3BodyId bodyId );
B3_API b3Pos b3Body_GetWorldCenterOfMass( b3BodyId bodyId );
/// Override the body's mass properties. Normally this is computed automatically using the
/// shape geometry and density. This information is lost if a shape is added or removed or if the
@ -527,17 +538,21 @@ B3_API b3AABB b3Body_ComputeAABB( b3BodyId bodyId );
B3_API float b3Body_GetClosestPoint( b3BodyId bodyId, b3Vec3* result, b3Vec3 target );
/// Cast a ray at a specific body using a specified body transform.
B3_API b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, const b3BodyRayCastInput* input, b3Transform bodyTransform );
B3_API b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter,
float maxFraction, b3WorldTransform bodyTransform );
/// Cast a shape at a specific body using a specified body transform.
B3_API b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, const b3BodyShapeCastInput* input, b3Transform bodyTransform );
B3_API b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, b3Pos origin, const b3ShapeProxy* proxy, b3Vec3 translation,
b3QueryFilter filter, float maxFraction, bool canEncroach,
b3WorldTransform bodyTransform );
/// Overlap a shape with a specific body using a specified body transform.
B3_API bool b3Body_OverlapShape( b3BodyId bodyId, const b3ShapeProxy* proxy, b3QueryFilter filter, b3Transform bodyTransform );
B3_API bool b3Body_OverlapShape( b3BodyId bodyId, b3Pos origin, const b3ShapeProxy* proxy, b3QueryFilter filter,
b3WorldTransform bodyTransform );
/// Collide a character mover with a specific body using a specified body transform.
B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, const b3Capsule* mover,
b3QueryFilter filter, b3Transform bodyTransform );
B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, b3Pos origin, const b3Capsule* mover,
b3QueryFilter filter, b3WorldTransform bodyTransform );
/** @} */ // body
@ -567,8 +582,8 @@ B3_API b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, cons
/// Use this for non-uniform or mirrored scale or a baked local transform. The baked result is shared through the
/// world hull database. The shape definition and geometry are fully cloned. Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull, b3Transform transform,
b3Vec3 scale );
B3_API b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull,
b3Transform transform, b3Vec3 scale );
/// Create a mesh hull shape and attach it to a body. The shape definition is fully cloned but the mesh is not.
/// Contacts are not created until the next time step.
@ -694,8 +709,9 @@ B3_API void b3Shape_EnableHitEvents( b3ShapeId shapeId, bool flag );
/// Returns true if hit events are enabled
B3_API bool b3Shape_AreHitEventsEnabled( b3ShapeId shapeId );
/// Ray cast a shape directly
B3_API b3CastOutput b3Shape_RayCast( b3ShapeId shapeId, const b3RayCastInput* input );
/// Ray cast a shape directly. The ray runs from origin to origin + translation and the hit point
/// comes back as a world position, so the cast stays precise far from the world origin.
B3_API b3WorldCastOutput b3Shape_RayCast( b3ShapeId shapeId, b3Pos origin, b3Vec3 translation );
/// Get a copy of the shape's sphere. Asserts the type is correct.
B3_API b3Sphere b3Shape_GetSphere( b3ShapeId shapeId );

View file

@ -75,20 +75,11 @@ B3_API b3TreeStats b3DynamicTree_QueryClosest( const b3DynamicTree* tree, b3Vec3
B3_API b3TreeStats b3DynamicTree_RayCast( const b3DynamicTree* tree, const b3RayCastInput* input, uint64_t maskBits,
bool requireAllBits, b3TreeRayCastCallbackFcn* callback, void* context );
/// Ray cast against the proxies in the tree. This relies on the callback
/// to perform an exact ray cast in the case where the proxy contains a shape.
/// The callback also performs any collision filtering. This has performance
/// roughly equal to k * log(n), where k is the number of collisions and n is the
/// number of proxies in the tree.
/// @param tree the dynamic tree to ray cast
/// @param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
/// @param maskBits bit mask test: `bool accept = (maskBits & node->categoryBits) != 0;`
/// @param requireAllBits modifies bit mask test: `bool accept = (maskBits & node->categoryBits) == maskBits;`
/// @param callback a callback function that is called for each proxy that is hit by the shape
/// @param context user context that is passed to the callback
/// @return performance data
B3_API b3TreeStats b3DynamicTree_ShapeCast( const b3DynamicTree* tree, const b3ShapeCastInput* input, uint64_t maskBits,
bool requireAllBits, b3TreeShapeCastCallbackFcn* callback, void* context );
/// Sweep an AABB through the tree. The box is in the tree's world float frame and the callback
/// re-differences each shape at full precision against the query origin. Used by the large world
/// spatial queries so the tree traversal stays float while the narrow phase stays precise.
B3_API b3TreeStats b3DynamicTree_BoxCast( const b3DynamicTree* tree, const b3BoxCastInput* input, uint64_t maskBits,
bool requireAllBits, b3TreeBoxCastCallbackFcn* callback, void* context );
/// Validate this tree. For testing.
B3_API void b3DynamicTree_Validate( const b3DynamicTree* tree );
@ -203,6 +194,9 @@ B3_API b3HullData* b3CreateCylinder( float height, float radius, float yOffset,
/// Create a tessellated cone as a hull.
B3_API b3HullData* b3CreateCone( float height, float radius1, float radius2, int slices );
/// Create a rock shaped hull.
B3_API b3HullData* b3CreateRock( float radius );
/// Create a generic convex hull.
B3_API b3HullData* b3CreateHull( const b3Vec3* points, int pointCount, int maxVertexCount );
@ -532,11 +526,13 @@ B3_API void b3QueryHeightField( const b3HeightField* heightField, b3AABB bounds,
/// Compute the closest points between two shapes represented as point clouds.
/// b3SimplexCache cache is input/output. On the first call set b3SimplexCache.count to zero.
/// The query runs in frame A, so the witness points and normal are returned in frame A.
/// The underlying GJK algorithm may be debugged by passing in debug simplexes and capacity. You may pass in NULL and 0 for these.
B3_API b3DistanceOutput b3ShapeDistance( const b3DistanceInput* input, b3SimplexCache* cache, b3Simplex* simplexes,
int simplexCapacity );
/// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction.
/// The query runs in frame A, so the hit point and normal are returned in frame A. Initially touching shapes are a miss.
B3_API b3CastOutput b3ShapeCast( const b3ShapeCastPairInput* input );
/// Evaluate the transform sweep at a specific time.

View file

@ -14,9 +14,14 @@ B3_API void b3SetLengthUnitsPerMeter( float lengthUnits );
/// Get the current length units per meter.
B3_API float b3GetLengthUnitsPerMeter( void );
// Used to detect bad values. Positions greater than about 16km will have precision
// problems, so 100km as a limit should be fine in all cases.
#define B3_HUGE ( 100000.0f * b3GetLengthUnitsPerMeter() )
// Used to detect bad values. In float mode positions greater than about 16km have precision
// problems, so 100km is a safe limit. Large world mode keeps coordinates accurate much farther
// from the origin, so the sanity limit widens to keep valid far-field positions from tripping it.
#if defined( BOX3D_DOUBLE_PRECISION )
#define B3_HUGE ( 1.0e9f * b3GetLengthUnitsPerMeter() )
#else
#define B3_HUGE ( 1.0e5f * b3GetLengthUnitsPerMeter() )
#endif
/// Maximum parallel workers. Used for some fixed size arrays.
#define B3_MAX_WORKERS 32

View file

@ -67,6 +67,33 @@ typedef struct b3Transform
b3Quat q;
} b3Transform;
#if defined( BOX3D_DOUBLE_PRECISION )
/// A world position. Double precision in large world mode so coordinates stay accurate far
/// from the origin.
typedef struct b3Pos
{
double x, y, z;
} b3Pos;
/// A world transform with double precision translation and float quaternion rotation. Rotation
/// is frame local and never needs the extra range, the same split as Jolt's DMat44.
typedef struct b3WorldTransform
{
b3Pos p;
b3Quat q;
} b3WorldTransform;
#else
/// In single precision mode these types are the same.
typedef b3Vec3 b3Pos;
/// In single precision mode these types are the same.
typedef b3Transform b3WorldTransform;
#endif
/// A 3x3 matrix.
typedef struct b3Matrix3
{
@ -106,6 +133,10 @@ static const b3Matrix3 b3Mat3_identity = {
{ 0.0f, 0.0f, 1.0f },
};
// Valid in both modes: 0.0f promotes to double, the identity rotation stays float
static const b3Pos b3Pos_zero = { 0.0f, 0.0f, 0.0f };
static const b3WorldTransform b3WorldTransform_identity = { { 0.0f, 0.0f, 0.0f }, { { 0.0f, 0.0f, 0.0f }, 1.0f } };
/// @return the minimum of two integers.
B3_INLINE int b3MinInt( int a, int b )
{
@ -591,6 +622,136 @@ B3_INLINE b3Vec3 b3InvTransformPoint( b3Transform t, b3Vec3 v )
return b3InvRotateVector( t.q, b3Sub( v, t.p ) );
}
// World position boundary. These cross between the double precision world space at the public
// boundary and the float interior. One set of bodies serves both modes: the typedefs collapse
// the types in float mode and the explicit float casts become no-ops.
/// Convert a vector to a world position.
B3_INLINE b3Pos b3ToPos( b3Vec3 v )
{
return B3_LITERAL( b3Pos ){ v.x, v.y, v.z };
}
/// Lossy conversion of a world position to a float vector.
B3_INLINE b3Vec3 b3ToVec3( b3Pos p )
{
return B3_LITERAL( b3Vec3 ){ (float)p.x, (float)p.y, (float)p.z };
}
/// Narrow a world coordinate to float, rounding toward negative infinity. Use with
/// b3RoundUpFloat to build a conservative float box that always contains the double bounds,
/// where plain rounding far from the origin could clip. nextafterf is an exact IEEE operation,
/// so this is cross-platform deterministic. With large world mode off this is a plain conversion.
B3_INLINE float b3RoundDownFloat( double x )
{
#if defined( BOX3D_DOUBLE_PRECISION )
float f = (float)x;
return (double)f > x ? nextafterf( f, -FLT_MAX ) : f;
#else
return (float)x;
#endif
}
/// Narrow a world coordinate to float, rounding toward positive infinity.
B3_INLINE float b3RoundUpFloat( double x )
{
#if defined( BOX3D_DOUBLE_PRECISION )
float f = (float)x;
return (double)f < x ? nextafterf( f, FLT_MAX ) : f;
#else
return (float)x;
#endif
}
/// a - b, demoted to float. The primary precision boundary operation.
B3_INLINE b3Vec3 b3SubPos( b3Pos a, b3Pos b )
{
return B3_LITERAL( b3Vec3 ){ (float)( a.x - b.x ), (float)( a.y - b.y ), (float)( a.z - b.z ) };
}
/// p + d
B3_INLINE b3Pos b3OffsetPos( b3Pos p, b3Vec3 d )
{
return B3_LITERAL( b3Pos ){ p.x + d.x, p.y + d.y, p.z + d.z };
}
/// World position interpolation for sweeps and sampling.
B3_INLINE b3Pos b3LerpPosition( b3Pos a, b3Pos b, float t )
{
return B3_LITERAL( b3Pos ){
( 1.0f - t ) * a.x + t * b.x,
( 1.0f - t ) * a.y + t * b.y,
( 1.0f - t ) * a.z + t * b.z,
};
}
/// Transform a local point to a world position. Rotation in float, translation in double.
B3_INLINE b3Pos b3TransformWorldPoint( b3WorldTransform t, b3Vec3 p )
{
b3Vec3 r = b3RotateVector( t.q, p );
return B3_LITERAL( b3Pos ){ t.p.x + r.x, t.p.y + r.y, t.p.z + r.z };
}
/// Transform a world position to a local point. One double subtraction, then float.
B3_INLINE b3Vec3 b3InvTransformWorldPoint( b3WorldTransform t, b3Pos p )
{
b3Vec3 d = { (float)( p.x - t.p.x ), (float)( p.y - t.p.y ), (float)( p.z - t.p.z ) };
return b3InvRotateVector( t.q, d );
}
/// Relative transform of frame B in frame A. The narrow phase boundary.
B3_INLINE b3Transform b3InvMulWorldTransforms( b3WorldTransform A, b3WorldTransform B )
{
b3Transform C;
C.q = b3InvMulQuat( A.q, B.q );
b3Vec3 d = { (float)( B.p.x - A.p.x ), (float)( B.p.y - A.p.y ), (float)( B.p.z - A.p.z ) };
C.p = b3InvRotateVector( A.q, d );
return C;
}
/// Compose a world transform with a local transform.
B3_INLINE b3WorldTransform b3MulWorldTransforms( b3WorldTransform A, b3Transform B )
{
b3WorldTransform C;
C.q = b3MulQuat( A.q, B.q );
b3Vec3 r = b3RotateVector( A.q, B.p );
C.p = B3_LITERAL( b3Pos ){ A.p.x + r.x, A.p.y + r.y, A.p.z + r.z };
return C;
}
/// Shift a world transform into the frame of a base position.
B3_INLINE b3Transform b3ToRelativeTransform( b3WorldTransform t, b3Pos base )
{
b3Transform r;
r.q = t.q;
r.p = B3_LITERAL( b3Vec3 ){ (float)( t.p.x - base.x ), (float)( t.p.y - base.y ), (float)( t.p.z - base.z ) };
return r;
}
/// Promote a float transform to a world transform. Lossless.
B3_INLINE b3WorldTransform b3MakeWorldTransform( b3Transform t )
{
b3WorldTransform w;
w.p = b3ToPos( t.p );
w.q = t.q;
return w;
}
/// Translate a local AABB by a world origin, rounding outward so the float box always contains
/// the double box. Far from the origin a plain conversion could clip a shape out of its own box.
/// In float mode the origin is float and the rounding is a no-op.
B3_INLINE b3AABB b3OffsetAABB( b3AABB localBox, b3Pos origin )
{
b3AABB out;
out.lowerBound.x = b3RoundDownFloat( origin.x + localBox.lowerBound.x );
out.lowerBound.y = b3RoundDownFloat( origin.y + localBox.lowerBound.y );
out.lowerBound.z = b3RoundDownFloat( origin.z + localBox.lowerBound.z );
out.upperBound.x = b3RoundUpFloat( origin.x + localBox.upperBound.x );
out.upperBound.y = b3RoundUpFloat( origin.y + localBox.upperBound.y );
out.upperBound.z = b3RoundUpFloat( origin.z + localBox.upperBound.z );
return out;
}
/// Compute the determinant of a 3-by-3 matrix.
B3_INLINE float b3Det( b3Matrix3 m )
{
@ -890,12 +1051,21 @@ B3_API bool b3IsValidMatrix3( b3Matrix3 a );
/// Is this a valid bounding box? Not Nan or infinity. Upper bound greater than or equal to lower bound.
B3_API bool b3IsValidAABB( b3AABB a );
/// Is this AABB valid and not huge or very far from the origin?
/// Is this AABB reasonably close to the origin? See B3_HUGE.
B3_API bool b3IsBoundedAABB( b3AABB a );
/// Is this AABB valid and reasonable?
B3_API bool b3IsSaneAABB( b3AABB a );
/// Is this a valid plane? Normal is a unit vector. Not Nan or infinity.
B3_API bool b3IsValidPlane( b3Plane a );
/// Is this a valid world position? Not NaN or infinity.
B3_API bool b3IsValidPosition( b3Pos p );
/// Is this a valid world transform? Not NaN or infinity. Rotation is normalized.
B3_API bool b3IsValidWorldTransform( b3WorldTransform t );
/**@}*/ // math
/**
@ -971,6 +1141,28 @@ B3_FORCE_INLINE b3Vec3 operator-( b3Vec3 a, b3Vec3 b )
return { a.x - b.x, a.y - b.y, a.z - b.z };
}
#if defined( BOX3D_DOUBLE_PRECISION )
/// Offset a world position by a vector.
B3_FORCE_INLINE b3Pos operator+( b3Pos a, b3Vec3 b )
{
return { a.x + b.x, a.y + b.y, a.z + b.z };
}
/// Offset a world position by a vector.
B3_FORCE_INLINE b3Pos operator-( b3Pos a, b3Vec3 b )
{
return { a.x - b.x, a.y - b.y, a.z - b.z };
}
/// Delta between two world positions, demoted to float.
B3_FORCE_INLINE b3Vec3 operator-( b3Pos a, b3Pos b )
{
return { (float)( a.x - b.x ), (float)( a.y - b.y ), (float)( a.z - b.z ) };
}
#endif
#endif
/**@}*/ // math_cpp

View file

@ -80,7 +80,7 @@ typedef bool b3CustomFilterFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, void* co
/// full contact manifold.
/// @warning Do not attempt to modify the world inside this callback
/// @ingroup world
typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Vec3 point, b3Vec3 normal, void* context );
typedef bool b3PreSolveFcn( b3ShapeId shapeIdA, b3ShapeId shapeIdB, b3Pos point, b3Vec3 normal, void* context );
/// Prototype callback for overlap queries.
/// Called for each shape found in the query.
@ -107,7 +107,7 @@ typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context );
/// @return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue
/// @see b3World_CastRay
/// @ingroup world
typedef float b3CastResultFcn( b3ShapeId shapeId, b3Vec3 point, b3Vec3 normal, float fraction, uint64_t userMaterialId,
typedef float b3CastResultFcn( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId,
int triangleIndex, int childIndex, void* context );
/// Optional world capacities that can be use to avoid run-time allocations
@ -268,7 +268,7 @@ typedef struct b3BodyDef
/// The initial world position of the body. Bodies should be created with the desired position.
/// @note Creating bodies at the origin and then moving them nearly doubles the cost of body creation, especially
/// if the body is moved after shapes have been added.
b3Vec3 position;
b3Pos position;
/// The initial world rotation of the body.
b3Quat rotation;
@ -1009,7 +1009,7 @@ typedef struct b3ExplosionDef
uint64_t maskBits;
/// The center of the explosion in world space
b3Vec3 position;
b3Pos position;
/// The radius of the explosion
float radius;
@ -1143,7 +1143,7 @@ typedef struct b3ContactHitEvent
/// Point where the shapes hit at the beginning of the time step.
/// This is a mid-point between the two surfaces. It could be at speculative
/// point where the two shapes were not touching at the beginning of the time step.
b3Vec3 point;
b3Pos point;
/// Normal vector pointing from shape A to shape B
b3Vec3 normal;
@ -1199,7 +1199,7 @@ typedef struct b3BodyMoveEvent
void* userData;
/// The body transform.
b3Transform transform;
b3WorldTransform transform;
/// The body id.
b3BodyId bodyId;
@ -1313,7 +1313,7 @@ typedef struct b3RayResult
b3ShapeId shapeId;
/// The world point of the hit.
b3Vec3 point;
b3Pos point;
/// The world normal of the shape surface at the hit point.
b3Vec3 normal;
@ -1373,6 +1373,21 @@ typedef struct b3ShapeCastInput
bool canEncroach;
} b3ShapeCastInput;
/// Input for sweeping an AABB through a dynamic tree. The box is in the tree's world float frame.
/// The caller folds the cast shape radius and any world origin into the box, so the tree traversal
/// stays a conservative box sweep and the precise narrow phase happens per shape in the callback.
typedef struct b3BoxCastInput
{
/// The AABB to cast, in the tree's frame.
b3AABB box;
/// The sweep translation.
b3Vec3 translation;
/// The maximum fraction of the translation to consider, typically 1.
float maxFraction;
} b3BoxCastInput;
/// Low level ray cast or shape-cast output data.
typedef struct b3CastOutput
{
@ -1401,43 +1416,42 @@ typedef struct b3CastOutput
bool hit;
} b3CastOutput;
/// Body ray cast for ray casting a specific body with a specified transform.
typedef struct b3BodyRayCastInput
#if defined( BOX3D_DOUBLE_PRECISION )
/// Ray cast or shape-cast output in world space. The hit point is a world position so the result
/// stays precise far from the world origin. Mirrors b3CastOutput with a double precision point.
typedef struct b3WorldCastOutput
{
/// Start point of the ray cast
b3Vec3 origin;
/// The surface normal at the hit point.
b3Vec3 normal;
/// Translation of the ray cast.
/// end = start + translation.
b3Vec3 translation;
/// The surface hit point in world space.
b3Pos point;
/// The query filter bits.
b3QueryFilter filter;
/// The fraction of the input translation at collision.
float fraction;
/// The maximum fraction to consider along the ray.
/// end = start + fraction * translation
float maxFraction;
} b3BodyRayCastInput;
/// The number of iterations used.
int iterations;
/// Body shape cast for shape casting a specific body with a specified transform.
typedef struct b3BodyShapeCastInput
{
/// A generic query shape.
b3ShapeProxy proxy;
/// The index of the mesh or height field triangle hit.
int triangleIndex;
/// The translation of the shape cast.
b3Vec3 translation;
/// The index of the compound child shape.
int childIndex;
/// The query filter bits.
b3QueryFilter filter;
/// The material index. May be -1 for null.
int materialIndex;
/// The maximum fraction to consider along the shape cast.
/// end = start + fraction * translation
float maxFraction;
/// Did the cast hit?
bool hit;
} b3WorldCastOutput;
/// Allow shape cast to encroach when initially touching. This only works if the radius is greater than zero.
bool canEncroach;
} b3BodyShapeCastInput;
#else
typedef b3CastOutput b3WorldCastOutput;
#endif
/// Body cast result for ray and shape casts.
typedef struct b3BodyCastResult
@ -1446,7 +1460,7 @@ typedef struct b3BodyCastResult
b3ShapeId shapeId;
/// The world point on the shape surface.
b3Vec3 point;
b3Pos point;
/// The world normal vector on the shape surface.
b3Vec3 normal;
@ -1495,13 +1509,12 @@ static const b3SimplexCache b3_emptyDistanceCache = B3_ZERO_INIT;
/// Input parameters for b3ShapeCast
typedef struct b3ShapeCastPairInput
{
b3ShapeProxy proxyA; ///< The proxy for shape A
b3ShapeProxy proxyB; ///< The proxy for shape B
b3Transform transformA; ///< The world transform for shape A
b3Transform transformB; ///< The world transform for shape B
b3Vec3 translationB; ///< The translation of shape B
float maxFraction; ///< The fraction of the translation to consider, typically 1
bool canEncroach; ///< Allows shapes with a radius to move slightly closer if already touching
b3ShapeProxy proxyA; ///< The proxy for shape A
b3ShapeProxy proxyB; ///< The proxy for shape B
b3Transform transform; ///< Transform of shape B in shape A's frame, the relative pose B in A
b3Vec3 translationB; ///< The translation of shape B, in A's frame
float maxFraction; ///< The fraction of the translation to consider, typically 1
bool canEncroach; ///< Allows shapes with a radius to move slightly closer if already touching
} b3ShapeCastPairInput;
/// Input for b3ShapeDistance
@ -1513,11 +1526,9 @@ typedef struct b3DistanceInput
/// The proxy for shape B
b3ShapeProxy proxyB;
/// The world transform for shape A
b3Transform transformA;
/// The world transform for shape B
b3Transform transformB;
/// Transform of shape B in shape A's frame, the relative pose B in A
/// (b3InvMulWorldTransforms( worldA, worldB )). The query is origin independent and runs in frame A.
b3Transform transform;
/// Should the proxy radius be considered?
bool useRadii;
@ -1526,9 +1537,9 @@ typedef struct b3DistanceInput
/// Output for b3ShapeDistance
typedef struct b3DistanceOutput
{
b3Vec3 pointA; ///< Closest point on shapeA
b3Vec3 pointB; ///< Closest point on shapeB
b3Vec3 normal; ///< Normal vector pointing from A to B
b3Vec3 pointA; ///< Closest point on shapeA, in shape A's frame
b3Vec3 pointB; ///< Closest point on shapeB, in shape A's frame
b3Vec3 normal; ///< A to B normal in shape A's frame. Invalid if distance is zero.
float distance; ///< The final distance, zero if overlapped
int iterations; ///< Number of GJK iterations used
int simplexCount; ///< The number of simplexes stored in the simplex array
@ -1637,7 +1648,7 @@ typedef struct b3TOIOutput
* @{
*/
/// Flags for dynamic tree nodes. Internal usage.
/// Flags for tree nodes. For internal usage.
typedef enum b3TreeNodeFlags
{
b3_allocatedNode = 0x0001,
@ -1645,7 +1656,7 @@ typedef enum b3TreeNodeFlags
b3_leafNode = 0x0004,
} b3TreeNodeFlags;
/// Flags for dynamic tree node child indices. Internal usage.
/// Tree node child indices. For internal usage.
typedef struct b3TreeNodeChildren
{
int child1; ///< child node index 1
@ -1750,12 +1761,12 @@ typedef bool b3TreeQueryCallbackFcn( int proxyId, uint64_t userData, void* conte
/// @return minimum distance squared to user objects in the proxy
typedef float b3TreeQueryClosestCallbackFcn( float distanceSqrMin, int proxyId, uint64_t userData, void* context );
/// This function receives clipped ray cast input for a proxy. The function
/// returns the new ray fraction.
/// - return a value of 0 to terminate the ray cast
/// - return a value less than input->maxFraction to clip the ray
/// - return a value of input->maxFraction to continue the ray cast without clipping
typedef float b3TreeShapeCastCallbackFcn( const b3ShapeCastInput* input, int proxyId, uint64_t userData, void* context );
/// This function receives clipped AABB cast input for a proxy. The function returns the new cast
/// fraction.
/// - return a value of 0 to terminate the cast
/// - return a value less than input->maxFraction to clip the cast
/// - return a value of input->maxFraction to continue the cast without clipping
typedef float b3TreeBoxCastCallbackFcn( const b3BoxCastInput* input, int proxyId, uint64_t userData, void* context );
/// This function receives clipped ray cast input for a proxy. The function
/// returns the new ray fraction.
@ -1848,8 +1859,8 @@ typedef struct b3MassData
/// The local center of mass position.
b3Vec3 center;
/// The inertia tensor.
b3Matrix3 inertia; // todo this should be central inertia
/// The inertia tensor about the shape center of mass.
b3Matrix3 inertia;
} b3MassData;
/**
@ -2910,28 +2921,30 @@ typedef struct b3DebugShape
} b3DebugShape;
/// This struct is passed to b3World_Draw to draw a debug view of the simulation world.
/// Callbacks receive world coordinates. In large world mode the translation is double precision so
/// it stays accurate far from the origin. Shift into your own camera frame inside the callbacks.
typedef struct b3DebugDraw
{
/// Draws a shape and returns true if drawing should continue
bool ( *DrawShapeFcn )( void* userShape, b3Transform transform, b3HexColor color, void* context );
bool ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color, void* context );
/// Draw a line segment.
void ( *DrawSegmentFcn )( b3Vec3 p1, b3Vec3 p2, b3HexColor color, void* context );
void ( *DrawSegmentFcn )( b3Pos p1, b3Pos p2, b3HexColor color, void* context );
/// Draw a transform. Choose your own length scale.
void ( *DrawTransformFcn )( b3Transform transform, void* context );
void ( *DrawTransformFcn )( b3WorldTransform transform, void* context );
/// Draw a point.
void ( *DrawPointFcn )( b3Vec3 p, float size, b3HexColor color, void* context );
void ( *DrawPointFcn )( b3Pos p, float size, b3HexColor color, void* context );
/// Draw a bounding box.
void ( *DrawBoundsFcn )( b3AABB aabb, b3HexColor color, void* context );
/// Draw a bounding box.
void ( *DrawBoxFcn )( b3Vec3 extents, b3Transform transform, b3HexColor color, void* context );
/// Draw an oriented box.
void ( *DrawBoxFcn )( b3Vec3 extents, b3WorldTransform transform, b3HexColor color, void* context );
/// Draw a string in world space
void ( *DrawStringFcn )( b3Vec3 p, const char* s, b3HexColor color, void* context );
void ( *DrawStringFcn )( b3Pos p, const char* s, b3HexColor color, void* context );
/// World bounds to use for debug draw
b3AABB drawingBounds;