Dynamic Mover (#202)

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

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

View file

@ -15,10 +15,10 @@
* @defgroup world World
* 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/
* 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/
* @{
*/
@ -29,8 +29,9 @@
#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.
/// 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.
B3_API b3WorldId b3CreateWorld( const b3WorldDef* def );
@ -46,41 +47,47 @@ B3_API int b3GetMaxWorldCount( void );
/// World id validation. Provides validation for up to 64K allocations.
B3_API bool b3World_IsValid( b3WorldId id );
/// Simulate a world for one time step. This performs collision detection, integration, and constraint solution.
/// A time step of zero runs the broad-phase and collision, but skips the solver. So you can still get contact
/// and sensor events.
/// Simulate a world for one time step. This performs collision detection, integration, and
/// constraint solution. A time step of zero runs the broad-phase and collision, but skips the
/// solver. So you can still get contact and sensor events.
/// @param worldId The world to simulate
/// @param timeStep The amount of time to simulate, this should be a fixed number. Usually 1/60.
/// @param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4.
/// @param subStepCount The number of sub-steps, increasing the sub-step count can increase
/// accuracy. Usually 4.
B3_API void b3World_Step( b3WorldId worldId, float timeStep, int subStepCount );
/// Call this to draw shapes and other debug draw data
B3_API void b3World_Draw( b3WorldId worldId, b3DebugDraw* draw, uint64_t maskBits );
/// Get the world's bounds. This is the bounding box that covers the current simulation. May have a small
/// amount of padding.
/// Get the world's bounds. This is the bounding box that covers the current simulation. May have a
/// small amount of padding.
B3_API b3AABB b3World_GetBounds( b3WorldId worldId );
/// Get the body events for the current time step. The event data is transient. Do not store a reference to this data.
/// Get the body events for the current time step. The event data is transient. Do not store a
/// reference to this data.
B3_API b3BodyEvents b3World_GetBodyEvents( b3WorldId worldId );
/// Get sensor events for the current time step. The event data is transient. Do not store a reference to this data.
/// Get sensor events for the current time step. The event data is transient. Do not store a
/// reference to this data.
B3_API b3SensorEvents b3World_GetSensorEvents( b3WorldId worldId );
/// Get contact events for this current time step. The event data is transient. Do not store a reference to this data.
/// Get contact events for this current time step. The event data is transient. Do not store a
/// reference to this data.
B3_API b3ContactEvents b3World_GetContactEvents( b3WorldId worldId );
/// Get the joint events for the current time step. The event data is transient. Do not store a reference to this data.
/// Get the joint events for the current time step. The event data is transient. Do not store a
/// reference to this data.
B3_API b3JointEvents b3World_GetJointEvents( b3WorldId worldId );
/// Overlap test for all shapes that *potentially* overlap the provided AABB
B3_API b3TreeStats b3World_OverlapAABB( b3WorldId worldId, b3AABB aabb, b3QueryFilter filter, b3OverlapResultFcn* fcn,
void* context );
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. 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 );
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.
/// Your callback function controls whether you get the closest point, any point, or n-points.
@ -93,24 +100,28 @@ B3_API b3TreeStats b3World_OverlapShape( b3WorldId worldId, b3Pos origin, const
/// @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, b3Pos origin, b3Vec3 translation, b3QueryFilter filter,
b3CastResultFcn* fcn, void* context );
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. Ignores back-side collision
/// on meshes and height-fields.
B3_API b3RayResult b3World_CastRayClosest( b3WorldId worldId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter );
/// 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. Ignores back-side collision on meshes and height-fields.
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. Ignores back-side collision on meshes and height-fields.
/// 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. Ignores back-side collision on
/// meshes and height-fields.
/// @see b3World_CastRay
B3_API b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, 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. Ignores back-side collision on meshes and height-fields.
/// 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. Ignores back-side
/// collision on meshes and height-fields.
/// @param worldId World to cast the mover against
/// @param origin World position the mover capsule is relative to
/// @param mover Capsule mover, relative to the origin
@ -119,14 +130,15 @@ B3_API b3TreeStats b3World_CastShape( b3WorldId worldId, b3Pos origin, const b3S
/// @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, b3Pos origin, const b3Capsule* mover, b3Vec3 translation, b3QueryFilter filter,
b3MoverFilterFcn* fcn, void* context );
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. The mover and the returned planes are relative to the origin.
/// Ignores back-side collision on meshes and height-fields.
B3_API void b3World_CollideMover( b3WorldId worldId, b3Pos origin, const b3Capsule* mover, b3QueryFilter filter,
b3PlaneResultFcn* fcn, void* context );
/// Collide a capsule mover with the world, gathering collision planes that can be fed to
/// b3SolvePlanes. Useful for kinematic character movement. The mover and the returned planes are
/// relative to the origin. Ignores back-side collision on meshes and height-fields.
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.
@ -136,9 +148,9 @@ B3_API void b3World_EnableSleeping( b3WorldId worldId, bool flag );
/// Is body sleeping enabled?
B3_API bool b3World_IsSleepingEnabled( b3WorldId worldId );
/// Enable/disable continuous collision between dynamic and static bodies. Generally you should keep continuous
/// collision enabled to prevent fast moving objects from going through static objects. The performance gain from
/// disabling continuous collision is minor.
/// Enable/disable continuous collision between dynamic and static bodies. Generally you should keep
/// continuous collision enabled to prevent fast moving objects from going through static objects.
/// The performance gain from disabling continuous collision is minor.
/// @see b3WorldDef
B3_API void b3World_EnableContinuous( b3WorldId worldId, bool flag );
@ -166,8 +178,8 @@ B3_API void b3World_EnableRestitutionPropagation( b3WorldId worldId, bool flag )
/// Is restitution propagation enabled?
B3_API bool b3World_IsRestitutionPropagationEnabled( b3WorldId worldId );
/// Adjust the hit event threshold. This controls the collision speed needed to generate a b3ContactHitEvent.
/// Usually in meters per second.
/// Adjust the hit event threshold. This controls the collision speed needed to generate a
/// b3ContactHitEvent. Usually in meters per second.
/// @see b3WorldDef::hitEventThreshold
B3_API void b3World_SetHitEventThreshold( b3WorldId worldId, float value );
@ -175,7 +187,8 @@ B3_API void b3World_SetHitEventThreshold( b3WorldId worldId, float value );
B3_API float b3World_GetHitEventThreshold( b3WorldId worldId );
/// Register the custom filter callback. This is optional.
B3_API void b3World_SetCustomFilterCallback( b3WorldId worldId, b3CustomFilterFcn* fcn, void* context );
B3_API void b3World_SetCustomFilterCallback( b3WorldId worldId, b3CustomFilterFcn* fcn,
void* context );
/// Register the pre-solve callback. This is optional.
B3_API void b3World_SetPreSolveCallback( b3WorldId worldId, b3PreSolveFcn* fcn, void* context );
@ -199,7 +212,8 @@ B3_API void b3World_Explode( b3WorldId worldId, const b3ExplosionDef* explosionD
/// @param dampingRatio The contact bounciness with 1 being critical damping (non-dimensional)
/// @param contactSpeed The maximum contact constraint push out speed (meters per second)
/// @note Advanced feature
B3_API void b3World_SetContactTuning( b3WorldId worldId, float hertz, float dampingRatio, float contactSpeed );
B3_API void b3World_SetContactTuning( b3WorldId worldId, float hertz, float dampingRatio,
float contactSpeed );
/// Set the contact point recycling distance. Setting this to zero disables contact point recycling.
/// Usually in meters.
@ -396,8 +410,8 @@ B3_API int b3RecPlayer_GetDivergeFrame( const b3RecPlayer* player );
/// Set the worker count of the replay world. Clamped to [1, B3_MAX_WORKERS]. Applied to the live
/// world at once and reused whenever the player rebuilds its world on Restart or a backward seek.
/// Replaying at a different count than recorded re-partitions the constraint graph, so the StateHash
/// check becomes a cross-thread determinism test.
/// Replaying at a different count than recorded re-partitions the constraint graph, so the
/// StateHash check becomes a cross-thread determinism test.
B3_API void b3RecPlayer_SetWorkerCount( b3RecPlayer* player, int count );
/// Tune the keyframe ring used to speed up backward seeking. A keyframe is a periodic snapshot the
@ -407,7 +421,8 @@ B3_API void b3RecPlayer_SetWorkerCount( b3RecPlayer* player, int count );
/// @param minIntervalFrames finest spacing between keyframes, in frames
/// A zero budget or a non-positive interval keeps that value. Clears the existing ring, so call
/// b3RecPlayer_Restart afterward to repopulate it under the new policy.
B3_API void b3RecPlayer_SetKeyframePolicy( b3RecPlayer* player, size_t budgetBytes, int minIntervalFrames );
B3_API void b3RecPlayer_SetKeyframePolicy( b3RecPlayer* player, size_t budgetBytes,
int minIntervalFrames );
/// @return the keyframe memory budget in bytes
B3_API size_t b3RecPlayer_GetKeyframeBudget( const b3RecPlayer* player );
@ -438,16 +453,20 @@ B3_API b3BodyId b3RecPlayer_GetBodyId( const b3RecPlayer* player, int index );
/// @param createDebugShape called when a replayed shape is added; returns a user draw handle
/// @param destroyDebugShape called when a replayed shape is removed; may be NULL
/// @param context user context passed to both callbacks
B3_API void b3RecPlayer_SetDebugShapeCallbacks( b3RecPlayer* player, b3CreateDebugShapeCallback* createDebugShape,
b3DestroyDebugShapeCallback* destroyDebugShape, void* context );
B3_API void b3RecPlayer_SetDebugShapeCallbacks( b3RecPlayer* player,
b3CreateDebugShapeCallback* createDebugShape,
b3DestroyDebugShapeCallback* destroyDebugShape,
void* context );
/// Draw the spatial queries recorded during the most recently replayed frame, layered on top of the
/// world. Call after b3World_Draw. NULL draw function pointers are skipped.
/// @param player a valid player handle
/// @param draw debug draw callbacks
/// @param queryIndex index of the frame query to draw, or -1 to draw all of them
/// @param selectedIndex index of the query to emphasize (reserved color plus a label), or -1 for none
B3_API void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int queryIndex, int selectedIndex );
/// @param selectedIndex index of the query to emphasize (reserved color plus a label), or -1 for
/// none
B3_API void b3RecPlayer_DrawFrameQueries( b3RecPlayer* player, b3DebugDraw* draw, int queryIndex,
int selectedIndex );
/// The kind of a recorded spatial query, matching the public query and cast functions.
typedef enum b3RecQueryType
@ -491,7 +510,8 @@ B3_API int b3RecPlayer_GetFrameQueryCount( const b3RecPlayer* player );
B3_API b3RecQueryInfo b3RecPlayer_GetFrameQuery( const b3RecPlayer* player, int index );
/// Get one result of a recorded query from the most recently replayed frame.
B3_API b3RecQueryHit b3RecPlayer_GetFrameQueryHit( const b3RecPlayer* player, int queryIndex, int hitIndex );
B3_API b3RecQueryHit b3RecPlayer_GetFrameQueryHit( const b3RecPlayer* player, int queryIndex,
int hitIndex );
/**@}*/ // recording
@ -503,8 +523,8 @@ B3_API b3RecQueryHit b3RecPlayer_GetFrameQueryHit( const b3RecPlayer* player, in
* @{
*/
/// Create a rigid body given a definition. No reference to the definition is retained. So you can create the definition
/// on the stack and pass it as a pointer.
/// Create a rigid body given a definition. No reference to the definition is retained. So you can
/// create the definition on the stack and pass it as a pointer.
/// @code{.c}
/// b3BodyDef bodyDef = b3DefaultBodyDef();
/// b3BodyId myBodyId = b3CreateBody(myWorldId, &bodyDef);
@ -581,7 +601,8 @@ 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, b3WorldTransform 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 );
@ -698,8 +719,8 @@ B3_API float b3Body_GetGravityScale( b3BodyId bodyId );
B3_API bool b3Body_IsAwake( b3BodyId bodyId );
/// Wake a body from sleep. This wakes the entire island the body is touching.
/// @warning Putting a body to sleep will put the entire island of bodies touching this body to sleep,
/// which can be expensive and possibly unintuitive.
/// @warning Putting a body to sleep will put the entire island of bodies touching this body to
/// sleep, which can be expensive and possibly unintuitive.
B3_API void b3Body_SetAwake( b3BodyId bodyId, bool awake );
/// Enable or disable sleeping for this body. If sleeping is disabled the body will wake.
@ -714,7 +735,8 @@ B3_API void b3Body_SetSleepThreshold( b3BodyId bodyId, float sleepThreshold );
/// Get the sleep threshold, usually in meters per second.
B3_API float b3Body_GetSleepThreshold( b3BodyId bodyId );
/// Set the continuous collision safety factor. Smaller is safer but can lead to hitching. Recommended range [0.01, 0.5]. Non-dimensional.
/// Set the continuous collision safety factor. Smaller is safer but can lead to hitching.
/// Recommended range [0.01, 0.5]. Non-dimensional.
B3_API void b3Body_SetSafetyFactor( b3BodyId bodyId, float safetyFactor );
/// Get the continuous collision safety factor. Non-dimensional.
@ -750,10 +772,10 @@ B3_API void b3Body_AllowFastRotation( b3BodyId bodyId, bool flag );
/// Is this body allowed to rotate fast?
B3_API bool b3Body_IsFastRotationAllowed( b3BodyId bodyId );
/// Enable or disable contact recycling for this body. Contact recycling is a performance optimization
/// that reuses contact manifolds when bodies move slightly. Disabling it can avoid ghost collisions
/// on characters at the cost of higher per-step work. Existing contacts retain their prior setting;
/// only contacts created after this call see the new value.
/// Enable or disable contact recycling for this body. Contact recycling is a performance
/// optimization that reuses contact manifolds when bodies move slightly. Disabling it can avoid
/// ghost collisions on characters at the cost of higher per-step work. Existing contacts retain
/// their prior setting; only contacts created after this call see the new value.
/// @see b3BodyDef::enableContactRecycling
B3_API void b3Body_EnableContactRecycling( b3BodyId bodyId, bool flag );
@ -787,8 +809,9 @@ B3_API int b3Body_GetContactCapacity( b3BodyId bodyId );
/// Get the touching contact data for a body
B3_API int b3Body_GetContactData( b3BodyId bodyId, b3ContactData* contactData, int capacity );
/// Get the current world AABB that contains all the attached shapes. Note that this may not encompass the body origin.
/// If there are no shapes attached then the returned AABB is empty and centered on the body origin.
/// Get the current world AABB that contains all the attached shapes. Note that this may not
/// encompass the body origin. If there are no shapes attached then the returned AABB is empty and
/// centered on the body origin.
B3_API b3AABB b3Body_ComputeAABB( b3BodyId bodyId );
/// The minimum distance from any shape to the shape centroid.
@ -805,29 +828,34 @@ B3_API float b3Body_GetClosestPoint( b3BodyId bodyId, b3Vec3* result, b3Vec3 tar
/// Cast a ray at a specific body using a specified body transform.
/// Ignores back-side collision on meshes and height-fields.
B3_API b3BodyCastResult b3Body_CastRay( b3BodyId bodyId, b3Pos origin, b3Vec3 translation, b3QueryFilter filter,
float maxFraction, b3WorldTransform 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.
/// Ignores back-side collision on meshes and height-fields.
B3_API b3BodyCastResult b3Body_CastShape( b3BodyId bodyId, b3Pos origin, const b3ShapeProxy* proxy, b3Vec3 translation,
b3QueryFilter filter, float maxFraction, bool canEncroach,
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, b3Pos origin, const b3ShapeProxy* proxy, b3QueryFilter filter,
b3WorldTransform 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.
/// Only considers convex shapes on the body.
B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity, b3Pos origin,
const b3Capsule* mover, b3QueryFilter filter, b3WorldTransform bodyTransform );
B3_API int b3Body_CollideMover( b3BodyId bodyId, b3BodyPlaneResult* bodyPlanes, int planeCapacity,
b3Pos origin, const b3Capsule* mover, b3QueryFilter filter,
b3WorldTransform bodyTransform );
/// Perform a time of impact between a character mover and a body using specified sweep transforms.
/// Perform a time of impact between a character mover and a body using specified sweep transforms.
/// Initial overlap of any shape on the body is ignored. A non-overlapped shape can still be hit.
/// Only considers convex shapes on the body.
B3_API b3BodyTOIResult b3Body_TimeOfImpactMover( b3BodyId bodyId, b3Pos origin, const b3Capsule* mover, b3Vec3 moverTranslation,
b3QueryFilter filter, b3WorldTransform bodyTransform1,
B3_API b3BodyTOIResult b3Body_TimeOfImpactMover( b3BodyId bodyId, b3Pos origin,
const b3Capsule* mover, b3Vec3 moverTranslation,
b3QueryFilter filter,
b3WorldTransform bodyTransform1,
b3WorldTransform bodyTransform2 );
/** @} */ // body
@ -835,56 +863,68 @@ B3_API b3BodyTOIResult b3Body_TimeOfImpactMover( b3BodyId bodyId, b3Pos origin,
/**
* @defgroup shape Shape
* Functions to create, destroy, and access.
* Shapes bind raw geometry to bodies and hold material properties including friction and restitution.
* You may add multiple shapes to a single body. There are no hard limits on shape count per body.
* Shapes bind raw geometry to bodies and hold material properties including friction and
* restitution. You may add multiple shapes to a single body. There are no hard limits on shape
* count per body.
*
* When you create a shape on a body the center of mass moves. This can lead to the body linear velocity
* changing if the angular velocity is non-zero.
* When you create a shape on a body the center of mass moves. This can lead to the body linear
* velocity changing if the angular velocity is non-zero.
* @{
*/
/// Create a circle shape and attach it to a body. The shape definition and geometry are fully cloned.
/// Create a circle shape and attach it to a body. 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 b3CreateSphereShape( b3BodyId bodyId, const b3ShapeDef* def,
const b3Sphere* sphere );
/// Create a capsule shape and attach it to a body. 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 b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def,
const b3Capsule* capsule );
/// Create a convex hull shape and attach it to a body. The shape definition is fully cloned.
/// Contacts are not created until the next time step.
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateSphereShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Sphere* sphere );
B3_API b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def,
const b3HullData* hull );
/// Create a capsule shape and attach it to a body. The shape definition and geometry are fully cloned.
/// Contacts are not created until the next time step.
/// Create a convex hull shape and attach it to a body. The hull is cloned then transformed with
/// scale applied first. 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 b3CreateCapsuleShape( b3BodyId bodyId, const b3ShapeDef* def, const b3Capsule* capsule );
B3_API b3ShapeId b3CreateTransformedHullShape( b3BodyId bodyId, const b3ShapeDef* def,
const b3HullData* hull, b3Transform transform,
b3Vec3 scale );
/// Create a convex hull shape and attach it to a body. The shape definition is fully cloned. Contacts are not created
/// until the next time step.
/// 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. Mesh collision only creates
/// contacts on static bodies.
/// @warning this holds reference to the input mesh data which must remain valid for the lifetime of
/// this shape
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateHullShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HullData* hull );
B3_API b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3MeshData* mesh,
b3Vec3 scale );
/// Create a convex hull shape and attach it to a body. The hull is cloned then transformed with scale applied first.
/// 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.
/// Create a height-field shape and attach it to a body. The shape definition is fully cloned but
/// the height field is not. Contacts are not created until the next time step. Height field is only
/// allowed on static bodies.
/// @warning this holds reference to the input height field which must remain valid for the lifetime
/// of this shape
/// @return the shape id for accessing the shape
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.
/// Mesh collision only creates contacts on static bodies.
/// @warning this holds reference to the input mesh data which must remain valid for the lifetime of this shape
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateMeshShape( b3BodyId bodyId, const b3ShapeDef* def, const b3MeshData* mesh, b3Vec3 scale );
/// Create a height-field shape and attach it to a body. The shape definition is fully cloned but the height field is not.
/// Contacts are not created until the next time step.
/// Height field is only allowed on static bodies.
/// @warning this holds reference to the input height field which must remain valid for the lifetime of this shape
/// @return the shape id for accessing the shape
B3_API b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def, const b3HeightFieldData* heightField );
B3_API b3ShapeId b3CreateHeightFieldShape( b3BodyId bodyId, const b3ShapeDef* def,
const b3HeightFieldData* heightField );
/// Baked compound shapes are only allowed on static bodies.
/// Note: runtime compounds are achieved by adding multiple shapes to a body.
/// Runtime compounds can be dynamic and/or kinematic.
B3_API b3ShapeId b3CreateBakedCompoundShape( b3BodyId bodyId, b3ShapeDef* def, const b3CompoundData* compound );
B3_API b3ShapeId b3CreateBakedCompoundShape( b3BodyId bodyId, b3ShapeDef* def,
const b3CompoundData* compound );
/// Destroy a shape. You may defer the body mass update which can improve performance if several shapes on a
/// Destroy a shape. You may defer the body mass update which can improve performance if several
/// shapes on a
/// body are destroyed at once.
/// @see b3Body_ApplyMassFromShapes
B3_API void b3DestroyShape( b3ShapeId shapeId, bool updateBodyMass );
@ -947,7 +987,8 @@ B3_API b3SurfaceMaterial b3Shape_GetSurfaceMaterial( b3ShapeId shapeId );
B3_API int b3Shape_GetMeshMaterialCount( b3ShapeId shapeId );
/// Set a surface material for a mesh shape.
B3_API void b3Shape_SetMeshMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial, int index );
B3_API void b3Shape_SetMeshMaterial( b3ShapeId shapeId, b3SurfaceMaterial surfaceMaterial,
int index );
/// Get a surface material for a mesh shape
B3_API b3SurfaceMaterial b3Shape_GetMeshSurfaceMaterial( b3ShapeId shapeId, int index );
@ -959,25 +1000,28 @@ B3_API b3Filter b3Shape_GetFilter( b3ShapeId shapeId );
/// @see b3ShapeDef::filter
/// @param shapeId the shape
/// @param filter the new filter
/// @param invokeContacts if true then the shape will have all contacts recomputed the next time step (expensive)
/// @param invokeContacts if true then the shape will have all contacts recomputed the next time
/// step (expensive)
B3_API void b3Shape_SetFilter( b3ShapeId shapeId, b3Filter filter, bool invokeContacts );
/// Enable sensor events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors.
/// Enable sensor events for this shape. Only applies to kinematic and dynamic bodies. Ignored for
/// sensors.
/// @see b3ShapeDef::isSensor
B3_API void b3Shape_EnableSensorEvents( b3ShapeId shapeId, bool flag );
/// Returns true if sensor events are enabled
B3_API bool b3Shape_AreSensorEventsEnabled( b3ShapeId shapeId );
/// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors.
/// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for
/// sensors.
/// @see b3ShapeDef::enableContactEvents
B3_API void b3Shape_EnableContactEvents( b3ShapeId shapeId, bool flag );
/// Returns true if contact events are enabled
B3_API bool b3Shape_AreContactEventsEnabled( b3ShapeId shapeId );
/// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive
/// and must be carefully handled due to multithreading. Ignored for sensors.
/// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are
/// expensive and must be carefully handled due to multithreading. Ignored for sensors.
/// @see b3PreSolveFcn
B3_API void b3Shape_EnablePreSolveEvents( b3ShapeId shapeId, bool flag );
@ -1036,7 +1080,8 @@ B3_API void b3Shape_SetMesh( b3ShapeId shapeId, const b3MeshData* meshData, b3Ve
/// Get the maximum capacity required for retrieving all the touching contacts on a shape
B3_API int b3Shape_GetContactCapacity( b3ShapeId shapeId );
/// Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or shapeIdB on the contact data.
/// Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or
/// shapeIdB on the contact data.
/// @note Box3D uses speculative collision so some contact points may be separated.
/// @returns the number of elements filled in the provided array
/// @warning do not ignore the return value, it specifies the valid number of elements
@ -1073,15 +1118,18 @@ B3_API b3Vec3 b3Shape_GetClosestPoint( b3ShapeId shapeId, b3Vec3 target );
/// @param wind the wind velocity in world space
/// @param drag the drag coefficient, the force that opposes the relative velocity
/// @param lift the lift coefficient, the force that is perpendicular to the relative velocity
/// @param maxSpeed the maximum relative speed. Speed cap is necessary for stability. Typically 10m/s or less.
/// @param maxSpeed the maximum relative speed. Speed cap is necessary for stability. Typically
/// 10m/s or less.
/// @param wake should this wake the body
B3_API void b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift, float maxSpeed, bool wake );
B3_API void b3Shape_ApplyWind( b3ShapeId shapeId, b3Vec3 wind, float drag, float lift,
float maxSpeed, bool wake );
/** @} */ // shape
/**
* @defgroup joint Joint
* @brief Joints allow you to connect rigid bodies together while allowing various forms of relative motions.
* @brief Joints allow you to connect rigid bodies together while allowing various forms of relative
* motions.
* @{
*/
@ -1139,10 +1187,12 @@ B3_API b3Vec3 b3Joint_GetConstraintForce( b3JointId jointId );
/// Get the current constraint torque for this joint
B3_API b3Vec3 b3Joint_GetConstraintTorque( b3JointId jointId );
/// Get the current linear separation error for this joint. Does not consider admissible movement. Usually in meters.
/// Get the current linear separation error for this joint. Does not consider admissible movement.
/// Usually in meters.
B3_API float b3Joint_GetLinearSeparation( b3JointId jointId );
/// Get the current angular separation error for this joint. Does not consider admissible movement. Usually in radians.
/// Get the current angular separation error for this joint. Does not consider admissible movement.
/// Usually in radians.
B3_API float b3Joint_GetAngularSeparation( b3JointId jointId );
/// Set the joint constraint tuning. Advanced feature.
@ -1221,10 +1271,12 @@ B3_API void b3DistanceJoint_EnableSpring( b3JointId jointId, bool enableSpring )
B3_API bool b3DistanceJoint_IsSpringEnabled( b3JointId jointId );
/// Set the force range for the spring.
B3_API void b3DistanceJoint_SetSpringForceRange( b3JointId jointId, float lowerForce, float upperForce );
B3_API void b3DistanceJoint_SetSpringForceRange( b3JointId jointId, float lowerForce,
float upperForce );
/// Get the force range for the spring.
B3_API void b3DistanceJoint_GetSpringForceRange( b3JointId jointId, float* lowerForce, float* upperForce );
B3_API void b3DistanceJoint_GetSpringForceRange( b3JointId jointId, float* lowerForce,
float* upperForce );
/// Set the spring stiffness in Hertz
B3_API void b3DistanceJoint_SetSpringHertz( b3JointId jointId, float hertz );
@ -1238,8 +1290,8 @@ B3_API float b3DistanceJoint_GetSpringHertz( b3JointId jointId );
/// Get the spring damping ratio
B3_API float b3DistanceJoint_GetSpringDampingRatio( b3JointId jointId );
/// Enable joint limit. The limit only works if the joint spring is enabled. Otherwise the joint is rigid
/// and the limit has no effect.
/// Enable joint limit. The limit only works if the joint spring is enabled. Otherwise the joint is
/// rigid and the limit has no effect.
B3_API void b3DistanceJoint_EnableLimit( b3JointId jointId, bool enableLimit );
/// Is the distance joint limit enabled?
@ -1358,12 +1410,101 @@ B3_API float b3MotorJoint_GetMaxSpringTorque( b3JointId jointId );
/**@}*/ // motor_joint
/**
* @defgroup mover_joint Mover Joint
* @brief Functions for the mover joint.
*
* The mover joint is designed for a dynamic character mover.
*
* @warning Experimental. The mover joint may change in future versions.
* @{
*/
/// Create a mover joint.
/// @see b3MoverJointDef for details
B3_API b3JointId b3CreateMoverJoint( b3WorldId worldId, const b3MoverJointDef* def );
/// Set the desired relative linear velocity, usually in meters per second.
B3_API void b3MoverJoint_SetLinearVelocity( b3JointId jointId, b3Vec3 velocity );
/// Get the desired relative linear velocity, usually in meters per second.
B3_API b3Vec3 b3MoverJoint_GetLinearVelocity( b3JointId jointId );
/// Set the joint maximum force, usually in newtons.
B3_API void b3MoverJoint_SetMaxVelocityForce( b3JointId jointId, float maxForce );
/// Get the joint maximum force, usually in newtons.
B3_API float b3MoverJoint_GetMaxVelocityForce( b3JointId jointId );
/**@}*/ // mover_joint
/**
* @defgroup pogo_joint Pogo Joint
* @brief Functions for the pogo joint. Used for dynamic character movers.
*
* @warning Experimental. The pogo joint may change in future versions.
* @{
*/
/// Create a pogo joint
/// @see b3PogoJointDef for details
B3_API b3JointId b3CreatePogoJoint( b3WorldId worldId, const b3PogoJointDef* def );
/// Set the rest length of a pogo joint
/// @param jointId The id for a pogo joint
/// @param length The new pogo joint length
B3_API void b3PogoJoint_SetRestLength( b3JointId jointId, float length );
/// Get the rest length of a pogo joint
B3_API float b3PogoJoint_GetRestLength( b3JointId jointId );
/// Set the spring stiffness in Hertz
B3_API void b3PogoJoint_SetSpringHertz( b3JointId jointId, float hertz );
/// Get the spring Hertz
B3_API float b3PogoJoint_GetSpringHertz( b3JointId jointId );
/// Set the spring damping ratio, non-dimensional
B3_API void b3PogoJoint_SetSpringDampingRatio( b3JointId jointId, float dampingRatio );
/// Get the spring damping ratio
B3_API float b3PogoJoint_GetSpringDampingRatio( b3JointId jointId );
/// Set the max tension force, usually in Newtons.
B3_API void b3PogoJoint_SetMaxTensionForce( b3JointId jointId, float force );
/// Get the max tension force, usually in Newtons.
B3_API float b3PogoJoint_GetMaxTensionForce( b3JointId jointId );
/// Set the max compression force, usually in Newtons.
B3_API void b3PogoJoint_SetMaxCompressionForce( b3JointId jointId, float force );
/// Get the max compression force, usually in Newtons.
B3_API float b3PogoJoint_GetMaxCompressionForce( b3JointId jointId );
// Set the unit ground normal.
B3_API void b3PogoJoint_SetNormal( b3JointId jointId, b3Vec3 normal );
// Get the unit ground normal.
B3_API b3Vec3 b3PogoJoint_GetNormal( b3JointId jointId );
/// Get the current length of the pogo.
B3_API float b3PogoJoint_GetCurrentLength( b3JointId jointId );
/// Get the internal pogo velocity.
B3_API float b3PogoJoint_GetCurrentSpeed( b3JointId jointId );
/// Get the internal pogo impulse.
B3_API float b3PogoJoint_GetImpulse( b3JointId jointId );
/**@}*/ // pogo_joint
/**
* @defgroup filter_joint Filter Joint
* @brief Functions for the filter joint.
*
* The filter joint is used to disable collision between two bodies. As a side effect of being a joint, it also
* keeps the two bodies in the same simulation island.
* The filter joint is used to disable collision between two bodies. As a side effect of being a
* joint, it also keeps the two bodies in the same simulation island.
* @{
*/
@ -1377,8 +1518,8 @@ B3_API b3JointId b3CreateFilterJoint( b3WorldId worldId, const b3FilterJointDef*
* @defgroup prismatic_joint Prismatic Joint
* @brief A prismatic joint allows for translation along a single axis with no rotation.
*
* The prismatic joint is useful for things like pistons and moving platforms, where you want a body to translate
* along an axis and have no rotation. Also called a *slider* joint.
* The prismatic joint is useful for things like pistons and moving platforms, where you want a body
* to translate along an axis and have no rotation. Also called a *slider* joint.
* @{
*/
@ -1393,8 +1534,8 @@ B3_API void b3PrismaticJoint_EnableSpring( b3JointId jointId, bool enableSpring
B3_API bool b3PrismaticJoint_IsSpringEnabled( b3JointId jointId );
/// Set the prismatic joint stiffness in Hertz.
/// This should usually be less than a quarter of the simulation rate. For example, if the simulation
/// runs at 60Hz then the joint stiffness should be 15Hz or less.
/// This should usually be less than a quarter of the simulation rate. For example, if the
/// simulation runs at 60Hz then the joint stiffness should be 15Hz or less.
B3_API void b3PrismaticJoint_SetSpringHertz( b3JointId jointId, float hertz );
/// Get the prismatic joint stiffness in Hertz
@ -1458,7 +1599,8 @@ B3_API float b3PrismaticJoint_GetSpeed( b3JointId jointId );
/**
* @defgroup revolute_joint Revolute Joint
* @brief A revolute joint allows for relative rotation about a single axis with no relative translation.
* @brief A revolute joint allows for relative rotation about a single axis with no relative
* translation.
*
* Also called a *hinge* or *pin* joint.
* @{
@ -1509,7 +1651,8 @@ B3_API float b3RevoluteJoint_GetLowerLimit( b3JointId jointId );
B3_API float b3RevoluteJoint_GetUpperLimit( b3JointId jointId );
/// Set the revolute joint limits in radians
B3_API void b3RevoluteJoint_SetLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians );
B3_API void b3RevoluteJoint_SetLimits( b3JointId jointId, float lowerLimitRadians,
float upperLimitRadians );
/// Enable/disable a revolute joint motor
B3_API void b3RevoluteJoint_EnableMotor( b3JointId jointId, bool enableMotor );
@ -1536,7 +1679,8 @@ B3_API float b3RevoluteJoint_GetMaxMotorTorque( b3JointId jointId );
/**
* @defgroup spherical_joint Spherical Joint
* @brief A spherical joint allows for relative rotation in the 3D space with no relative translation.
* @brief A spherical joint allows for relative rotation in the 3D space with no relative
* translation.
*
* Also called a *ball-in-socket* or *point-to-point* joint.
* @{
@ -1574,7 +1718,8 @@ B3_API float b3SphericalJoint_GetLowerTwistLimit( b3JointId jointId );
B3_API float b3SphericalJoint_GetUpperTwistLimit( b3JointId jointId );
/// Set the spherical joint limits in radians
B3_API void b3SphericalJoint_SetTwistLimits( b3JointId jointId, float lowerLimitRadians, float upperLimitRadians );
B3_API void b3SphericalJoint_SetTwistLimits( b3JointId jointId, float lowerLimitRadians,
float upperLimitRadians );
/// Get the spherical joint current twist angle in radians.
B3_API float b3SphericalJoint_GetTwistAngle( b3JointId jointId );
@ -1630,12 +1775,14 @@ B3_API float b3SphericalJoint_GetMaxMotorTorque( b3JointId jointId );
/**
* @defgroup weld_joint Weld Joint
* @brief A weld joint fully constrains the relative transform between two bodies while allowing for springiness
* @brief A weld joint fully constrains the relative transform between two bodies while allowing for
* springiness
*
* A weld joint constrains the relative rotation and translation between two bodies. Both rotation and translation
* can have damped springs.
* A weld joint constrains the relative rotation and translation between two bodies. Both rotation
* and translation can have damped springs.
*
* @note The accuracy of weld joint is limited by the accuracy of the solver. Long chains of weld joints may flex.
* @note The accuracy of weld joint is limited by the accuracy of the solver. Long chains of weld
* joints may flex.
* @{
*/
@ -1777,7 +1924,8 @@ B3_API float b3WheelJoint_GetLowerSteeringLimit( b3JointId jointId );
B3_API float b3WheelJoint_GetUpperSteeringLimit( b3JointId jointId );
/// Set the wheel joint steering limits in radians.
B3_API void b3WheelJoint_SetSteeringLimits( b3JointId jointId, float lowerRadians, float upperRadians );
B3_API void b3WheelJoint_SetSteeringLimits( b3JointId jointId, float lowerRadians,
float upperRadians );
/// Set the wheel joint target steering angle in radians.
B3_API void b3WheelJoint_SetTargetSteeringAngle( b3JointId jointId, float radians );

View file

@ -1053,6 +1053,20 @@ B3_INLINE b3Vec3 b3ClosestPointToAABB( b3Vec3 point, b3AABB a )
return b3Clamp( point, a.lowerBound, a.upperBound );
}
/// One-dimensional mass-spring-damper simulation. Returns the new velocity given the position and
/// time step. You can then compute the new position using:
/// position += timeStep * newVelocity
/// This drives towards a zero position. By using implicit integration we get a stable solution that
/// doesn't require transcendental functions.
B3_INLINE float b3SpringDamper( float hertz, float dampingRatio, float position, float velocity,
float timeStep )
{
float omega = 2.0f * B3_PI * hertz;
float omegaH = omega * timeStep;
return ( velocity - omega * omegaH * position ) /
( 1.0f + 2.0f * dampingRatio * omegaH + omegaH * omegaH );
}
/// The closest points between to segments or infinite lines.
typedef struct b3SegmentDistanceResult
{

View file

@ -15,50 +15,57 @@
#define B3_DEFAULT_MASK_BITS UINT64_MAX
/// Task interface
/// This is the prototype for a Box3D task. Your task system is expected to run this callback on a worker thread,
/// exactly once per enqueue, passing back the same taskContext pointer supplied to b3EnqueueTaskCallback.
/// This is the prototype for a Box3D task. Your task system is expected to run this callback on a
/// worker thread, exactly once per enqueue, passing back the same taskContext pointer supplied to
/// b3EnqueueTaskCallback.
/// @ingroup world
typedef void b3TaskCallback( void* taskContext );
/// These functions can be provided to Box3D to invoke a task system.
/// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box3D that the work was executed
/// serially within the callback and there is no need to call b3FinishTaskCallback. Otherwise the returned
/// value must be non-null will be passed to b3FinishTaskCallback as the userTask.
/// Returns a pointer to the user's task object. May be nullptr. A nullptr indicates to Box3D that
/// the work was executed serially within the callback and there is no need to call
/// b3FinishTaskCallback. Otherwise the returned value must be non-null will be passed to
/// b3FinishTaskCallback as the userTask.
/// @param task the Box3D task to be called by the scheduler
/// @param taskContext the Box3D context object that the scheduler must pass to the task
/// @param userContext the scheduler context object that is opaque to Box3D
/// @param taskName the Box3D task name that the scheduler can use for diagnostics
/// @ingroup world
typedef void* b3EnqueueTaskCallback( b3TaskCallback* task, void* taskContext, void* userContext, const char* taskName );
typedef void* b3EnqueueTaskCallback( b3TaskCallback* task, void* taskContext, void* userContext,
const char* taskName );
/// Finishes a user task object that wraps a Box3D task. This must block until the task has completed.
/// The step blocks here on the tasks it spawned, so b3World_Step holds its stack across every
/// fork/join. Drive it from a thread you can dedicate to the step, or from a fiber this callback can
/// park to free the underlying thread. In a job system that cannot park a job's stack, do not call
/// b3World_Step from inside a job: a job that blocks on its own sub-jobs without yielding its thread
/// can deadlock. The in-tree scheduler instead runs other pending tasks on the waiting thread.
/// Finishes a user task object that wraps a Box3D task. This must block until the task has
/// completed. The step blocks here on the tasks it spawned, so b3World_Step holds its stack across
/// every fork/join. Drive it from a thread you can dedicate to the step, or from a fiber this
/// callback can park to free the underlying thread. In a job system that cannot park a job's stack,
/// do not call b3World_Step from inside a job: a job that blocks on its own sub-jobs without
/// yielding its thread can deadlock. The in-tree scheduler instead runs other pending tasks on the
/// waiting thread.
/// @ingroup world
typedef void b3FinishTaskCallback( void* userTask, void* userContext );
typedef struct b3DebugShape b3DebugShape;
/// The user needs to be able to create debug draw shapes for multi-pass rendering to work efficiently.
/// These user shapes are created and destroyed via callback so they can be bound to shape lifetime and scaling updates.
/// The user needs to be able to create debug draw shapes for multi-pass rendering to work
/// efficiently. These user shapes are created and destroyed via callback so they can be bound to
/// shape lifetime and scaling updates.
/// @ingroup debug_draw
typedef void* b3CreateDebugShapeCallback( const b3DebugShape* debugShape, void* userContext );
typedef void b3DestroyDebugShapeCallback( void* userShape, void* userContext );
/// Optional friction mixing callback. This intentionally provides no context objects because this is called
/// from a worker thread.
/// Optional friction mixing callback. This intentionally provides no context objects because this
/// is called from a worker thread.
/// @warning This function should not attempt to modify Box3D state or user application state.
/// @ingroup world
typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB, uint64_t userMaterialIdB );
typedef float b3FrictionCallback( float frictionA, uint64_t userMaterialIdA, float frictionB,
uint64_t userMaterialIdB );
/// Optional restitution mixing callback. This intentionally provides no context objects because this is called
/// from a worker thread.
/// Optional restitution mixing callback. This intentionally provides no context objects because
/// this is called from a worker thread.
/// @warning This function should not attempt to modify Box3D state or user application state.
/// @ingroup world
typedef float b3RestitutionCallback( float restitutionA, uint64_t userMaterialIdA, float restitutionB, uint64_t userMaterialIdB );
typedef float b3RestitutionCallback( float restitutionA, uint64_t userMaterialIdA,
float restitutionB, uint64_t userMaterialIdB );
/// Prototype for a contact filter callback.
/// This is called when a contact pair is considered for collision. This allows you to
@ -86,7 +93,8 @@ 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, b3Pos 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,14 +115,16 @@ typedef bool b3OverlapResultFcn( b3ShapeId shapeId, void* context );
/// @param normal the normal vector at the point of intersection
/// @param fraction the fraction along the ray at the point of intersection
/// @param userMaterialId the shape or triangle surface type
/// @param triangleIndex the triangle index for mesh or height field shapes or -1 for other shape types
/// @param triangleIndex the triangle index for mesh or height field shapes or -1 for other shape
/// types
/// @param childIndex the child shape index for compound shapes
/// @param context the user 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, b3Pos point, b3Vec3 normal, float fraction, uint64_t userMaterialId,
int triangleIndex, int childIndex, void* context );
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
/// @ingroup world
@ -147,7 +157,8 @@ typedef struct b3WorldDef
/// speed have restitution applied (will bounce).
float restitutionThreshold;
/// Number of iterations of the restitution solver. More iterations can lead to less box spinning.
/// Number of iterations of the restitution solver. More iterations can lead to less box
/// spinning.
/// @see B3_MAX_RESTITUTION_ITERATIONS
int restitutionIterations;
@ -158,16 +169,17 @@ typedef struct b3WorldDef
/// speed can generate hit events if the shape also enables hit events.
float hitEventThreshold;
/// Contact stiffness. Cycles per second. Increasing this increases the speed of overlap recovery, but can introduce jitter.
/// Contact stiffness. Cycles per second. Increasing this increases the speed of overlap
/// recovery, but can introduce jitter.
float contactHertz;
/// Contact bounciness. Non-dimensional. You can speed up overlap recovery by decreasing this with
/// the trade-off that overlap resolution becomes more energetic.
/// Contact bounciness. Non-dimensional. You can speed up overlap recovery by decreasing this
/// with the trade-off that overlap resolution becomes more energetic.
float contactDampingRatio;
/// This parameter controls how fast overlap is resolved and usually has units of meters per second. This only
/// puts a cap on the resolution speed. The resolution speed is increased by increasing the hertz and/or
/// decreasing the damping ratio.
/// This parameter controls how fast overlap is resolved and usually has units of meters per
/// second. This only puts a cap on the resolution speed. The resolution speed is increased by
/// increasing the hertz and/or decreasing the damping ratio.
float contactSpeed;
/// Maximum linear speed. Usually meters per second.
@ -190,11 +202,11 @@ typedef struct b3WorldDef
bool enableContinuous;
/// Number of workers to use with the provided task system. Box3D performs best when using only
/// performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading provide
/// little benefit and may even harm performance.
/// This is clamped to the range [1, B3_MAX_WORKERS]. Using a value above 1 will turn on multithreading.
/// If task callbacks are provided then Box3D will use the user provided task system. Otherwise Box3D
/// will create threads and use an internal scheduler.
/// performance cores and accessing a single L2 cache. Efficiency cores and hyper-threading
/// provide little benefit and may even harm performance. This is clamped to the range [1,
/// B3_MAX_WORKERS]. Using a value above 1 will turn on multithreading. If task callbacks are
/// provided then Box3D will use the user provided task system. Otherwise Box3D will create
/// threads and use an internal scheduler.
uint32_t workerCount;
/// function to spawn task
@ -231,7 +243,8 @@ typedef struct b3WorldDef
B3_API b3WorldDef b3DefaultWorldDef( void );
/// The body simulation type.
/// Each body is one of these three types. The type determines how the body behaves in the simulation.
/// Each body is one of these three types. The type determines how the body behaves in the
/// simulation.
/// @ingroup body
typedef enum b3BodyType
{
@ -282,8 +295,8 @@ typedef struct b3BodyDef
b3BodyType type;
/// 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.
/// @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.
b3Pos position;
/// The initial world rotation of the body.
@ -315,10 +328,11 @@ typedef struct b3BodyDef
float sleepThreshold;
/// Continuous collision safety factor. The solver only uses continuous collision if there is a
/// risk of tunneling. If the body is moving fast enough to risk tunneling then it is considered a "fast body".
/// This improves performance and prevents movement hitches. If a body moving N meter risks tunneling, then the
/// body will be considered fast if it moves more than a safetyFactor times N meters over one full time step.
/// Non-dimensional. Recommended range [0.01, 0.5]. Default is 0.5 for high performance with low tunneling risk.
/// risk of tunneling. If the body is moving fast enough to risk tunneling then it is considered
/// a "fast body". This improves performance and prevents movement hitches. If a body moving N
/// meter risks tunneling, then the body will be considered fast if it moves more than a
/// safetyFactor times N meters over one full time step. Non-dimensional. Recommended range
/// [0.01, 0.5]. Default is 0.5 for high performance with low tunneling risk.
float safetyFactor;
/// Optional body name for debugging.
@ -338,18 +352,19 @@ typedef struct b3BodyDef
/// Treat this body as a high speed object that performs continuous collision detection
/// against dynamic and kinematic bodies, but not other bullet bodies.
/// @warning Bullets should be used sparingly. They are not a solution for general dynamic-versus-dynamic
/// continuous collision. They do not guarantee accurate collision if both bodies are fast moving because
/// the bullet does a continuous check after all non-bullet bodies have moved. You could get unlucky and have
/// the bullet body end a time step very close to a non-bullet body and the non-bullet body then moves over
/// the bullet body. In continuous collision, initial overlap is ignored to avoid freezing bodies in place.
/// I do not recommend using them for game projectiles if precise collision timing is needed. Instead consider
/// using a ray or shape cast. You can use a marching ray or shape cast for projectile that moves over time.
/// If you want a fast moving projectile to collide with a fast moving target, you need to consider the relative
/// movement in your ray or shape cast. This is out of the scope of Box3D.
/// So what are good use cases for bullets? Pinball games or games with dynamic containers that hold other objects.
/// It should be a use case where it doesn't break the game if there is a collision missed, but having them
/// captured improves the quality of the game.
/// @warning Bullets should be used sparingly. They are not a solution for general
/// dynamic-versus-dynamic continuous collision. They do not guarantee accurate collision if
/// both bodies are fast moving because the bullet does a continuous check after all non-bullet
/// bodies have moved. You could get unlucky and have the bullet body end a time step very close
/// to a non-bullet body and the non-bullet body then moves over the bullet body. In continuous
/// collision, initial overlap is ignored to avoid freezing bodies in place. I do not recommend
/// using them for game projectiles if precise collision timing is needed. Instead consider
/// using a ray or shape cast. You can use a marching ray or shape cast for projectile that
/// moves over time. If you want a fast moving projectile to collide with a fast moving target,
/// you need to consider the relative movement in your ray or shape cast. This is out of the
/// scope of Box3D. So what are good use cases for bullets? Pinball games or games with dynamic
/// containers that hold other objects. It should be a use case where it doesn't break the game
/// if there is a collision missed, but having them captured improves the quality of the game.
bool isBullet;
/// Used to disable a body. A disabled body does not move or collide.
@ -403,8 +418,8 @@ typedef struct b3Filter
/// or always collide (positive). A group index of zero has no effect. Non-zero group filtering
/// always wins against the mask bits.
/// For example, you may want ragdolls to collide with other ragdolls but you don't want
/// ragdoll self-collision. In this case you would give each ragdoll a unique negative group index
/// and apply that group index to all shapes on the ragdoll.
/// ragdoll self-collision. In this case you would give each ragdoll a unique negative group
/// index and apply that group index to all shapes on the ragdoll.
int groupIndex;
} b3Filter;
@ -423,7 +438,8 @@ typedef struct b3SurfaceMaterial
/// https://en.wikipedia.org/wiki/Coefficient_of_restitution
float restitution;
/// The rolling resistance usually in the range [0,1]. This is only used for spheres and capsules.
/// The rolling resistance usually in the range [0,1]. This is only used for spheres and
/// capsules.
float rollingResistance;
/// The tangent velocity for conveyor belts. This is local to the shape and will be projected
@ -483,7 +499,8 @@ typedef struct b3ShapeDef
/// Use this to store application specific shape data.
void* userData;
/// Surface material used on mesh shapes per triangle. Ignored for convex shapes. Ignored for compound shapes.
/// Surface material used on mesh shapes per triangle. Ignored for convex shapes. Ignored for
/// compound shapes.
b3SurfaceMaterial* materials;
/// Surface material count.
@ -501,42 +518,49 @@ typedef struct b3ShapeDef
/// Contact filtering data.
b3Filter filter;
/// Enable custom filtering. Only one of the two shapes needs to enable custom filtering. See b3WorldDef.
/// Enable custom filtering. Only one of the two shapes needs to enable custom filtering. See
/// b3WorldDef.
bool enableCustomFiltering;
/// A sensor shape generates overlap events but never generates a collision response.
/// Sensors do not have continuous collision. Instead, use a ray or shape cast for those scenarios.
/// Sensors still contribute to the body mass if they have non-zero density.
/// Sensors do not have continuous collision. Instead, use a ray or shape cast for those
/// scenarios. Sensors still contribute to the body mass if they have non-zero density.
/// @note Sensor events are disabled by default.
/// @see enableSensorEvents
bool isSensor;
/// Enable sensor events for this shape. This applies to sensors and non-sensors. False by default, even for sensors.
/// Only convex shapes may act as sensor visitors.
/// Enable sensor events for this shape. This applies to sensors and non-sensors. False by
/// default, even for sensors. Only convex shapes may act as sensor visitors.
bool enableSensorEvents;
/// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. False by default.
/// Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored
/// for sensors. False by default.
bool enableContactEvents;
/// Enable hit events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors. False by default.
/// Enable hit events for this shape. Only applies to kinematic and dynamic bodies. Ignored for
/// sensors. False by default.
bool enableHitEvents;
/// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive
/// Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are
/// expensive
/// and must be carefully handled due to multithreading. Ignored for sensors.
bool enablePreSolveEvents;
/// When shapes are created they will scan the environment for collision the next time step. This can significantly slow down
/// static body creation when there are many static shapes.
/// This is flag is ignored for dynamic and kinematic shapes which always invoke contact creation.
/// When shapes are created they will scan the environment for collision the next time step.
/// This can significantly slow down static body creation when there are many static shapes.
/// This is flag is ignored for dynamic and kinematic shapes which always invoke contact
/// creation.
bool invokeContactCreation;
/// Should the body update the mass properties when this shape is created. Default is true.
/// Warning: if this is false, you MUST call b3Body_ApplyMassFromShapes or b3Body_SetMassData before simulating the world.
/// Warning: if this is false, you MUST call b3Body_ApplyMassFromShapes or b3Body_SetMassData
/// before simulating the world.
bool updateBodyMass;
/// Enable speculative collision. Leave this true unless you care about reducing ghost collision
/// more than continuous collision under rotation.
/// Experimental: this can only disable speculative contact between hulls and triangles (meshes and height fields).
/// Experimental: this can only disable speculative contact between hulls and triangles (meshes
/// and height fields).
bool enableSpeculativeContact;
/// Used internally to detect a valid definition. DO NOT SET.
@ -628,6 +652,8 @@ typedef enum b3JointType
b3_sphericalJoint,
b3_weldJoint,
b3_wheelJoint,
b3_moverJoint,
b3_pogoJoint,
} b3JointType;
/// Base joint definition used by all joint types. The local frames are measured from the
@ -767,6 +793,64 @@ typedef struct b3MotorJointDef
/// @ingroup motor_joint
B3_API b3MotorJointDef b3DefaultMotorJointDef( void );
/// A mover joint is used to move a dynamic character mover through velocity commands. Force is only
/// applied in the xz plane of joint frame B. Does not affect rotation.
/// @ingroup mover_joint
typedef struct b3MoverJointDef
{
/// Base joint definition
b3JointDef base;
/// The desired linear velocity
b3Vec3 linearVelocity;
/// The maximum motor force in newtons.
float maxForce;
} b3MoverJointDef;
/// Use this to initialize your joint definition
/// @ingroup mover_joint
B3_API b3MoverJointDef b3DefaultMoverJointDef( void );
/// The pogo joint is used for the dynamic character mover. The pogo axis is along the frame B
/// y-axis.
/// @ingroup pogo_joint
typedef struct b3PogoJointDef
{
/// Base joint definition
b3JointDef base;
/// Normal vector at the contact
b3Vec3 normal;
/// The spring stiffness Hertz, cycles per second
float hertz;
/// The spring damping ratio, non-dimensional
float dampingRatio;
/// Spring length.
float restLength;
/// Maximum tension force. Controls how sticky the mover is to ground.
float maxTensionForce;
/// Maximum compression force. How hard the pogo pushes the mover up from the ground.
float maxCompressionForce;
/// The initial pogo internal impulse. The pogo is typically recreated every frame. This gives a
/// way to move the internal state forward for smoother spring behavior.
float impulse;
/// The initial pogo internal velocity. The pogo is typically recreated every frame. This gives
/// a way to move the internal state forward for smoother spring behavior.
float velocity;
} b3PogoJointDef;
/// Use this to initialize your joint definition
/// @ingroup pogo_joint
B3_API b3PogoJointDef b3DefaultPogoJointDef( void );
/// A filter joint is used to disable collision between two specific bodies.
/// @ingroup filter_joint
typedef struct b3FilterJointDef
@ -1075,8 +1159,9 @@ B3_API b3ExplosionDef b3DefaultExplosionDef( void );
* Also when events occur in the simulation step it may be problematic to modify the world, which is
* often what applications want to do when events occur.
*
* With event arrays, you can scan the events in a loop and modify the world. However, you need to be careful
* that some event data may become invalid. There are several samples that show how to do this safely.
* With event arrays, you can scan the events in a loop and modify the world. However, you need to
* be careful that some event data may become invalid. There are several samples that show how to do
* this safely.
*
* @{
*/
@ -1135,8 +1220,8 @@ typedef struct b3ContactBeginTouchEvent
/// Id of the second shape
b3ShapeId shapeIdB;
/// The transient contact id. This contact may be destroyed automatically when the world is modified or simulated.
/// Use b3Contact_IsValid before using this id.
/// The transient contact id. This contact may be destroyed automatically when the world is
/// modified or simulated. Use b3Contact_IsValid before using this id.
b3ContactId contactId;
} b3ContactBeginTouchEvent;
@ -1162,8 +1247,8 @@ typedef struct b3ContactEndTouchEvent
b3ContactId contactId;
} b3ContactEndTouchEvent;
/// A hit touch event is generated when two shapes collide with a speed faster than the hit speed threshold.
/// This may be reported for speculative contacts that have a confirmed impulse.
/// A hit touch event is generated when two shapes collide with a speed faster than the hit speed
/// threshold. This may be reported for speculative contacts that have a confirmed impulse.
typedef struct b3ContactHitEvent
{
/// Id of the first shape
@ -1227,8 +1312,8 @@ typedef struct b3ContactEvents
/// On the other hand if the flag does not indicate the body went to sleep then the application
/// can treat the actor/entity/object associated with the body as awake.
/// This is an efficient way for an application to update game object transforms rather than
/// calling functions such as b3Body_GetTransform() because this data is delivered as a contiguous array
/// and it is only populated with bodies that have moved.
/// calling functions such as b3Body_GetTransform() because this data is delivered as a contiguous
/// array and it is only populated with bodies that have moved.
/// @note If sleeping is disabled all dynamic and kinematic bodies will trigger move events.
typedef struct b3BodyMoveEvent
{
@ -1299,7 +1384,8 @@ typedef struct b3ContactData
/// this pointer.
const struct b3Manifold* manifolds;
/// The number of contact manifolds. For mesh and height-field collision there can be multiple manifolds.
/// The number of contact manifolds. For mesh and height-field collision there can be multiple
/// manifolds.
int manifoldCount;
} b3ContactData;
@ -1325,14 +1411,15 @@ typedef struct b3QueryFilter
/// query would accept for collision.
uint64_t maskBits;
/// Optional id combined with @ref name to identify this query in a recording, e.g. an entity id.
/// Need not be unique on its own. 0 with a null name means untagged. Ignored when not recording.
/// Optional id combined with @ref name to identify this query in a recording, e.g. an entity
/// id. Need not be unique on its own. 0 with a null name means untagged. Ignored when not
/// recording.
uint64_t id;
/// Optional label combined with @ref id to identify this query, e.g. "bullet". Need not be unique
/// on its own. The recorder hashes (id, name) into one stable key the viewer tracks the query by,
/// so the same id and name pair identifies the same query across frames. NULL means none. Ignored
/// when not recording.
/// Optional label combined with @ref id to identify this query, e.g. "bullet". Need not be
/// unique on its own. The recorder hashes (id, name) into one stable key the viewer tracks the
/// query by, so the same id and name pair identifies the same query across frames. NULL means
/// none. Ignored when not recording.
const char* name;
} b3QueryFilter;
@ -1416,7 +1503,8 @@ typedef struct b3ShapeCastInput
/// The maximum fraction of the translation to consider, typically 1.
float maxFraction;
/// Allow shape cast to encroach when initially touching. This only works if the radius is greater than zero.
/// Allow shape cast to encroach when initially touching. This only works if the radius is
/// greater than zero.
bool canEncroach;
} b3ShapeCastInput;
@ -1562,7 +1650,7 @@ typedef struct b3ShapeCastPairInput
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
bool canEncroach; ///< Allows shapes with a radius to move slightly closer if already touching
} b3ShapeCastPairInput;
/// Input for b3ShapeDistance
@ -1575,7 +1663,8 @@ typedef struct b3DistanceInput
b3ShapeProxy proxyB;
/// 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.
/// (b3InvMulWorldTransforms( worldA, worldB )). The query is origin independent and runs in
/// frame A.
b3Transform transform;
/// Should the proxy radius be considered?
@ -1611,9 +1700,9 @@ typedef struct b3Simplex
int count; ///< number of valid vertices
} b3Simplex;
/// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin,
/// which may not coincide with the center of mass. However, to support dynamics we must interpolate the center of mass
/// position.
/// This describes the motion of a body/shape for TOI computation. Shapes are defined with respect
/// to the body origin, which may not coincide with the center of mass. However, to support dynamics
/// we must interpolate the center of mass position.
typedef struct b3Sweep
{
b3Vec3 localCenter; ///< Local center of mass position
@ -1682,9 +1771,9 @@ typedef struct b3TOIOutput
* @defgroup tree Dynamic Tree
* The dynamic tree is a binary AABB tree to organize and query large numbers of geometric objects
*
* Box3D uses the dynamic tree internally to sort collision shapes into a binary bounding volume hierarchy.
* This data structure may have uses in games for organizing other geometry data and may be used independently
* of Box3D rigid body simulation.
* Box3D uses the dynamic tree internally to sort collision shapes into a binary bounding volume
* hierarchy. This data structure may have uses in games for organizing other geometry data and may
* be used independently of Box3D rigid body simulation.
*
* A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt.
* A dynamic tree arranges data in a binary tree to accelerate
@ -1813,23 +1902,27 @@ typedef struct b3TreeStats
/// @return true if the query should continue
typedef bool b3TreeQueryCallbackFcn( int proxyId, uint64_t userData, void* context );
/// This function receives the minimum distance squared so far and proxy to check in the closest query.
/// This function receives the minimum distance squared so far and proxy to check in the closest
/// query.
/// @return minimum distance squared to user objects in the proxy
typedef float b3TreeQueryClosestCallbackFcn( float distanceSqrMin, int proxyId, uint64_t userData, void* context );
typedef float b3TreeQueryClosestCallbackFcn( float distanceSqrMin, 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 );
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.
/// - 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 b3TreeRayCastCallbackFcn( const b3RayCastInput* input, int proxyId, uint64_t userData, void* context );
typedef float b3TreeRayCastCallbackFcn( const b3RayCastInput* input, int proxyId, uint64_t userData,
void* context );
/**@}*/ // tree
@ -1873,7 +1966,8 @@ typedef struct b3CollisionPlane
/// The push on the mover determined by b3SolvePlanes. Usually in meters.
float push;
/// Indicates if b3ClipVector should clip against this plane. Should be false for soft collision.
/// Indicates if b3ClipVector should clip against this plane. Should be false for soft
/// collision.
bool clipVelocity;
} b3CollisionPlane;
@ -1915,7 +2009,8 @@ typedef struct b3BodyTOIResult
/// Used to collect collision planes for character movers.
/// Return true to continue gathering planes.
typedef bool b3PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* plane, int planeCount, void* context );
typedef bool b3PlaneResultFcn( b3ShapeId shapeId, const b3PlaneResult* plane, int planeCount,
void* context );
/// Used to filter shapes for shape casting character movers.
/// Return true to accept the collision
@ -3032,8 +3127,8 @@ B3_INLINE uint32_t b3MakeDebugColor( b3HexColor rgb, b3DebugMaterial material )
/// (B3_GRAPH_COLOR_COUNT - 1) is the overflow color.
B3_API b3HexColor b3GetGraphColor( int index );
/// This is sent to the user for debug shape creation. The user should know the type in case they have
/// custom sphere or capsule rendering.
/// This is sent to the user for debug shape creation. The user should know the type in case they
/// have custom sphere or capsule rendering.
typedef struct b3DebugShape
{
/// Shape id.
@ -3059,10 +3154,11 @@ typedef struct b3DebugShape
/// it stays accurate far from the origin. Shift into your own camera frame inside the callbacks.
typedef struct b3DebugDraw
{
/// Draws a user shape. The userShape pointer is owned by the application and is known to Box3D as
/// an opaque pointer returned from b3CreateDebugShapeCallback. When this is called the drawn shape has
/// passed a culling test against drawingBounds below.
void ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color, void* context );
/// Draws a user shape. The userShape pointer is owned by the application and is known to Box3D
/// as an opaque pointer returned from b3CreateDebugShapeCallback. When this is called the drawn
/// shape has passed a culling test against drawingBounds below.
void ( *DrawShapeFcn )( void* userShape, b3WorldTransform transform, b3HexColor color,
void* context );
/// Draw a line segment.
void ( *DrawSegmentFcn )( b3Pos p1, b3Pos p2, b3HexColor color, void* context );
@ -3077,13 +3173,15 @@ typedef struct b3DebugDraw
void ( *DrawSphereFcn )( b3Pos p, float radius, b3HexColor color, float alpha, void* context );
/// Draw a capsule.
void ( *DrawCapsuleFcn )( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha, void* context );
void ( *DrawCapsuleFcn )( b3Pos p1, b3Pos p2, float radius, b3HexColor color, float alpha,
void* context );
/// Draw a bounding box.
void ( *DrawBoundsFcn )( b3AABB aabb, b3HexColor color, void* context );
/// Draw an oriented box.
void ( *DrawBoxFcn )( b3Vec3 extents, b3WorldTransform transform, b3HexColor color, void* context );
void ( *DrawBoxFcn )( b3Vec3 extents, b3WorldTransform transform, b3HexColor color,
void* context );
/// Draw a string in world space
void ( *DrawStringFcn )( b3Pos p, const char* s, b3HexColor color, void* context );