A body definition holds all the data needed to construct a rigid body.
You can safely re-use body definitions. Shapes are added to a body after construction.
Body definitions are temporary objects used to bundle creation parameters.
Must be initialized using b3DefaultBodyDef().
@ingroup body
Body events are buffered in the world and are available
as event arrays after the time step is complete.
Note: this data becomes invalid if bodies are destroyed
Body move events triggered when a body moves.
Triggered when a body moves due to simulation. Not reported for bodies moved by the user.
This also has a flag to indicate that the body went to sleep so the application can also
sleep that actor/entity/object associated with the body.
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.
@note If sleeping is disabled all dynamic and kinematic bodies will trigger move events.
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.
The runtime data for a compound shape. This is a potentially large yet highly optimized
data structure. It can contain thousands of child shapes, yet at runtime it populates
into the world as a single shape in the runtime broad-phase.
This data structure has data living off the end and must be accessed using offsets.
Accessors are provided for user relevant data.
The contact data for two shapes. By convention the manifold normal points
from shape A to shape B.
@see b3Shape_GetContactData() and b3Body_GetContactData()
An end touch event is generated when two shapes stop touching.
You will get an end event if you do anything that destroys contacts previous to the last
world step. These include things like setting the transform, destroying a body
or shape, or changing a filter or body type.
Contact events are buffered in the world and are available
as event arrays after the time step is complete.
Note: these may become invalid if bodies and/or shapes are destroyed
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.
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.
Contact points are always the result of two edges intersecting.
It can be two edges of the same shape, which is just a shape vertex.
Or a contact point can be the result of two edges crossing from different shapes.
This is designed to support hull versus hull, but it is adapted to work
with all shape types. The feature pair is used to identify contact points
for temporal coherence and warm starting.
This is used to filter collision on shapes. It affects shape-vs-shape collision
and shape-versus-query collision (such as b3World_CastRay).
@ingroup shape
Joint events report joints that are awake and have a force and/or torque exceeding the threshold
The observed forces and torques are not returned for efficiency reasons.
Joint events are buffered in the world and are available
as event arrays after the time step is complete.
Note: this data becomes invalid if joints are destroyed
A contact manifold describes the contact points between colliding shapes.
@note Box3D uses speculative collision so some contact points may be separated.
A manifold point is a contact point belonging to a contact manifold.
It holds details related to the geometry and dynamics of the contact points.
Box3D uses speculative collision so some contact points may be separated.
You may use the maxNormalImpulse to determine if there was an interaction during
the time step.
Parallel joint definition. Constrains the angle between axis z in body A and axis z in body B
using a spring. Useful to keep a body upright.
@ingroup parallel_joint
Prismatic joint definition. Body B may slide along the x-axis in local frame A.
Body B cannot rotate relative to body A. The joint translation is zero when the
local frame origins coincide in world space.
@ingroup prismatic_joint
The query filter is used to filter collisions between queries and shapes. For example,
you may want a ray-cast representing a projectile to hit players and the static environment
but not debris.
An end touch event is generated when a shape stops overlapping a sensor shape.
These include things like setting the transform, destroying a body or shape, or changing
a filter. You will also get an end event if the sensor or visitor are destroyed.
Therefore you should always confirm the shape id is valid using b3Shape_IsValid.
Sensor events are buffered in the world and are available
as begin/end overlap event arrays after the time step is complete.
Note: these may become invalid if bodies and/or shapes are destroyed
Low level shape cast input in generic form. This allows casting an arbitrary point
cloud wrap with a radius. For example, a sphere is a single point with a non-zero radius.
A capsule is two points with a non-zero radius. A box is four points with a zero radius.
Used to warm start the GJK simplex. If you call this function multiple times with nearby
transforms this might improve performance. Otherwise you can zero initialize this.
The distance cache must be initialized to zero on the first call.
Users should generally just zero initialize this structure for each call.
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.
Weld joint definition
Connects two bodies together rigidly. This constraint provides springs to mimic
soft-body simulation.
@note The approximate solver in Box3D cannot hold many bodies together rigidly
@ingroup weld_joint
Wheel joint definition
Body A is the chassis and body B is the wheel.
The wheel rotates around the local z-axis in frame B.
The wheel translates along the local x-axis in frame A.
The wheel can optionally steer along the x-axis in frame A.
@ingroup wheel_joint
Compute an approximate arctangent in the range [-pi, pi]
This is hand coded for cross-platform determinism. The atan2f
function in the standard library is not cross-platform deterministic.
Accurate to around 0.0023 degrees.
Apply an angular impulse in world space. The impulse is ignored if the body is not awake.
This optionally wakes the body.
@param bodyId The body id
@param impulse the world angular impulse vector, usually in units of kgmm/s
@param wake also wake up the body
@warning This should be used for one-shot impulses. If you need a steady torque,
use a torque instead, which will work better with the sub-stepping solver.
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.
The force is ignored if the body is not awake.
@param bodyId The body id
@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
Apply a force to the center of mass. This optionally wakes up the body.
The force is ignored if the body is not awake.
@param bodyId The body id
@param force the world force vector, usually in newtons (N).
@param wake also wake up the body
Apply an impulse at a point. This immediately modifies the velocity.
It also modifies the angular velocity if the point of application
is not at the center of mass. This optionally wakes the body.
The impulse is ignored if the body is not awake.
@param bodyId The body id
@param impulse the world impulse vector, usually in Ns or kgm/s.
@param point the world position of the point of application.
@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.
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.
@param bodyId The body id
@param impulse the world impulse vector, usually in Ns or kgm/s.
@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.
This updates the mass properties to the sum of the mass properties of the shapes.
This normally does not need to be called unless you called SetMassData to override
the mass and you later want to reset the mass.
You may also use this when automatic mass computation has been disabled.
You should call this regardless of body type.
Apply a torque. This affects the angular velocity without affecting the linear velocity.
This optionally wakes the body. The torque is ignored if the body is not awake.
@param bodyId The body id
@param torque the world torque vector, usually in N*m.
@param wake also wake up the body
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.
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
Body identifier validation. A valid body exists in a world and is non-null.
This can be used to detect orphaned ids. Provides validation for up to 64K allocations.
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.
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
body type changes.
Set the velocity to reach the given transform after a given time step.
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.
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
Convert bytes to compound. This does not clone. The bytes must remain in scope while the
compound is used. This is done to improve run-time performance and allow for instancing.
The bytes are mutated to fixup pointers.
If bytes is null then this returns the number of required bytes. This clones all the
data into the bytes buffer. This is expected to run offline or asynchronously.
This mutates the compound to nullify pointers, leaving the compound in an unusable state.
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);
@endcode
@warning This function is locked during callbacks.
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
Create a grid mesh along the x and z axes.
@param xCount the number of rows in the x direction
@param zCount the number of rows in the z direction
@param cellWidth the width of each cell
@param materialCount the number of materials to generate
@param identifyEdges compute adjacency information
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
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
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
Create a recording buffer with an optional initial byte capacity.
Pass 0 to use the default (64 KiB). The buffer grows on demand.
@return a new recording, owned by the caller
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
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
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.
Destroy a rigid body given an id. This destroys all shapes and joints attached to the body.
Do not keep references to the associated shapes and joints.
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
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.
Query an AABB for the closest object. The callback function is called for each proxy that might be closest to the supplied point.
@param tree the dynamic tree to query
@param point the query point
@param maskBits nodes are skipped if the bit-wise AND with the node category bits is zero
@param requireAllBits nodes are skipped if the bit-wise AND with the node category bits does not equal the maskBits
@param callback a user provided instance of b3TreeQueryClosestCallbackFcn
@param context a user context object that is provided to the callback
@param minDistanceSqr the initial and final minimum squared distance. Provide a small initial to restrict the search and
improve performance. If the value is large this query has performance that scales linearly with the number of proxies and
would be slower than a brute force search.
@return performance data
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.
Bit-wise filtering using mask bits can greatly improve performance in some scenarios.
However, this filtering may be approximate, so the user should still apply filtering to results.
@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 ray
@param context user context that is passed to the callback
@return performance data
Set the joint constraint tuning. Advanced feature.
@param jointId the joint
@param hertz the stiffness in Hertz (cycles per second)
@param dampingRatio the non-dimensional damping ratio (one for critical damping)
Load a recording from a file. Returns NULL on failure (file not found, wrong magic).
The caller owns the returned recording and must destroy it with b3DestroyRecording.
@param path file path to read
This makes a transformed box hull with post scaling. This is useful for boxes that are scaled in
a level editor. Such scaling can have reflection and shear. In the case of shear the result
may be approximate. If you need to support shear consider using b3CreateHull.
Do not call b3DestroyHull on this.
@param halfWidths positive half widths
@param transform local transform of box
@param postScale scale applied after the transform, may be negative
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.
Query a height field for triangles overlapping a bounding box in local space. May have false positives. Useful for debug draw.
@param heightField the height field to query
@param bounds the bounding box in local space
@param fcn a user function to collect triangles
@param context the context sent to the user function.
Query a mesh for triangles overlapping a bounding box in local space. May have false positives. Useful for debug draw.
@param mesh the mesh to query, includes scale
@param bounds the bounding box in local space
@param fcn a user function to collect triangles
@param context the context sent to the user function.
Ray cast versus capsule in local space. A zero length ray is a point query. Initial overlap
reports a hit at the ray origin with zero fraction and zero normal.
Ray cast versus compound in local space. A zero length ray is a point query. Initial overlap
with a child reports a hit at the ray origin with zero fraction and zero normal.
Ray cast versus a hollow sphere shell in local space. Unlike the solid sphere a ray starting
inside is not an overlap: it passes through and hits the far wall.
Ray cast versus hull shape in local space. A zero length ray is a point query. Initial overlap
reports a hit at the ray origin with zero fraction and zero normal.
Ray cast versus sphere in local space. A zero length ray is a point query. Initial overlap
reports a hit at the ray origin with zero fraction and zero normal.
Create a player over a recording. Owns a private copy of the bytes.
@param data pointer to recording bytes
@param size byte count of the recording
@param workerCount worker count for the replay world; pass 1 to match a serial recording.
Replaying at a different count re-partitions the constraint graph, so the StateHash check
becomes a cross-thread determinism test. Adjustable later with b3RecPlayer_SetWorkerCount.
@return a new player, or NULL on bad header or deserialization failure
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
Resolve a creation ordinal to the live body id at the current frame.
@return the body id, or a null id if that ordinal is out of range or its body is destroyed
@return the current keyframe spacing in frames; starts at the min interval and doubles as the
ring evicts to stay under budget, so it reflects the effective backward-seek granularity now
Wire host debug-shape callbacks into the player’s replay world so a renderer can build
per-shape draw resources (the 3D sample needs this or the replay world draws nothing).
Rebuilds the current world under the new callbacks and rewinds to frame 0, so call it
once right after b3RecPlayer_Create and re-read the world id afterward. The callbacks
persist across Restart and backward seeks, which recreate the world internally.
@param player the player to configure
@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
Tune the keyframe ring used to speed up backward seeking. A keyframe is a periodic snapshot the
player restores from instead of replaying from the start, trading memory for seek speed.
@param player the recording player
@param budgetBytes memory cap for the kept snapshots; the spacing widens to stay under it
@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.
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.
Get a pointer to the raw recording bytes.
Valid until the recording buffer is modified or destroyed.
@param recording the recording handle
@return pointer to the byte buffer, or NULL if no bytes have been written
This takes a box with a transform and post scale and converts it into a box with the post scale
resolved with new half-widths and transform. This accepts non-uniform and negative scale.
This is approximate if there is shear.
@param halfWidths [in/out] the box half widths
@param transform [in/out] the box transform with rotation and translation
@param postScale the post scale being applied to the box after the transform
@param minHalfWidth the minimum half width after scale is applied
Box3D bases all length units on meters, but you may need different units for your game.
You can set this value to use different units. This should be done at application startup
and only modified once. Default value is 1.
@warning This must be modified before any calls to Box3D
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.
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.
Apply a wind force to the body for this shape using the density of air. This considers
the projected area of the shape in the wind direction. This also considers
the relative velocity of the shape.
@param shapeId the shape id
@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 wake should this wake the body
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
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
Get the maximum capacity required for retrieving all the overlapped shapes on a sensor shape.
This returns 0 if the provided shape is not a sensor.
@param shapeId the id of a sensor shape
@returns the required capacity to get all the overlaps in b3Shape_GetSensorOverlaps
Get the overlap data for a sensor shape.
@param shapeId the id of a sensor shape
@param visitorIds a user allocated array that is filled with the overlapping shapes (visitors)
@param capacity the capacity of overlappedShapes
@returns the number of elements filled in the provided array
@warning do not ignore the return value, it specifies the valid number of elements
@warning overlaps may contain destroyed shapes so use b3Shape_IsValid to confirm each overlap
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.
Set the mass density of a shape, usually in kg/m^3.
This will optionally update the mass properties on the parent body.
@see b3ShapeDef::density, b3Body_ApplyMassFromShapes
Set the current filter. This is almost as expensive as recreating the shape.
@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)
Solves the position of a mover that satisfies the given collision planes.
@param targetDelta the desired translation from the position used to generate the collision planes
@param planes the collision planes
@param count the number of collision planes
Compute the upper bound on time before two shapes penetrate. Time is represented as
a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
non-tunneling collisions. If you change the time interval, you should call this function
again.
Replay a recording from memory and verify it reproduces the same world-state hashes.
Stands up a fresh world, restores the seed snapshot, replays every op, and checks each embedded
StateHash record. Returns true if replay completed without id mismatches or hash divergences.
@param data pointer to recording bytes
@param size byte count of the recording
@param workerCount reserved for future multithreaded replay; pass 1 for now
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 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
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.
@note The callback function may receive shapes in any order
@param worldId The world to cast the ray against
@param origin The start point of the ray
@param translation The translation of the ray from the start point to the end point
@param filter Contains bit flags to filter unwanted shapes from the results
@param fcn A user implemented callback function
@param context A user context that is passed along to the callback function
@return traversal performance counters
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.
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
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.
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
Enable/disable sleep. If your application does not need sleeping, you can gain some performance
by disabling sleep completely at the world level.
@see b3WorldDef
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.
Adjust contact tuning parameters
@param worldId The world id
@param hertz The contact stiffness (cycles per second)
@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
Set the gravity vector for the entire world. Box3D has no concept of an up direction and this
is left as a decision for the application. Usually in m/s^2.
@see b3WorldDef
Adjust the hit event threshold. This controls the collision speed needed to generate a b3ContactHitEvent.
Usually in meters per second.
@see b3WorldDef::hitEventThreshold
Adjust the restitution threshold. It is recommended not to make this value very small
because it will prevent bodies from sleeping. Usually in meters per second.
@see b3WorldDef
Begin recording world mutations into the provided buffer.
The buffer is reset on each call so a single b3Recording can be reused for multiple sessions.
@param worldId the world to record
@param recording the recording handle to write into
Simulate a world for one time step. This performs collision detection, integration, and constraint solution.
@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.
End the current recording session. Writes the trailing geometry registry and
backpatches the header. The buffer remains valid until the recording is destroyed.
@param worldId the world currently being recorded
Prototype for user allocation function.
@param size the allocation size in bytes
@param alignment the required alignment, guaranteed to be a power of 2
Prototype callback for ray casts.
Called for each shape found in the query. You control how the ray cast
proceeds by returning a float:
return -1: ignore this shape and continue
return 0: terminate the ray cast
return fraction: clip the ray to this point
return 1: don’t clip the ray and continue
@param shapeId the shape hit by the ray
@param point the point of initial intersection
@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 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
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
Prototype for a contact filter callback.
This is called when a contact pair is considered for collision. This allows you to
perform custom logic to prevent collision between shapes. This is only called if
one of the two shapes has custom filtering enabled. @see b3ShapeDef.
Notes:
Debug draw material preset. Optionally packed into the unused high byte of a
b3HexColor (or b3SurfaceMaterial::customColor) to drive the renderer’s PBR
roughness and metalness. The low 24 bits stay RGB, so a plain 0xRRGGBB color
reads as b3_debugMaterialDefault and keeps the renderer’s per-body-type look.
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.
@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
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
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
These colors are used for debug draw and mostly match the named SVG colors.
See https://www.rapidtables.com/web/color/index.html
https://johndecember.com/html/spec/colorsvg.html
https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg
Prototype callback for overlap queries.
Called for each shape found in the query.
@see b3World_OverlapAABB
@return false to terminate the query.
@ingroup world
Prototype for a pre-solve callback.
This is called after a contact is updated. This allows you to inspect a
collision before it goes to the solver.
Notes:
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
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.
@ingroup world
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