Expand description
§Crabby Engine
A fast 2D engine for games with huge numbers of things on screen.
use ponko::*;
fn main() {
Game::new("My Game", 800, 600).run(|ctx| {
let crab = ctx.load_texture("crab.png");
let mut pos = vec2(400.0, 300.0);
move |ctx: &mut Ctx| {
if ctx.key_down(Key::Right) { pos.x += 200.0 * ctx.dt(); }
if ctx.key_down(Key::Left) { pos.x -= 200.0 * ctx.dt(); }
if ctx.key_pressed(Key::Escape) { ctx.quit(); }
ctx.draw(&crab, pos);
}
});
}Everything you need comes in with use ponko::*;.
§Features
window(default): a window and GPU rendering (winit + wgpu). Without it the engine is simulation only:Game::run_headlessworks, drawing calls do nothing,Game::runpanics. For simulation servers and CI, with a much smaller build.audio(default): sound through kira; without it sounds are silent.inspector(default): the in-game inspector overlay (egui), opened with the backquote key. On in debug builds; seeGame::inspector.gamepad(default): gamepads through gilrs; without itCtx::gamepadsis always empty. On Linux it needs libudev headers.profiling: per-system scopes forpuffin_viewer. (Not needed forprofile_scope!,Ctx::perf_reportorCountingAllocator, which are always built in and cost one atomic load while profiling is off.)hotpatch: change system code while the game runs, withdx serve --hot-patch --features hotpatch.physics: 2D physics with rapier (Game::physics);physics-determinismfor bit-identical results across platforms.physics3d: 3D physics with rapier (Game::physics3d): bodies, colliders (heightfield terrain too), queries, a character controller and raycast-wheel vehicles.steam: lockstep and byte messages over Steam’s relays and lobbies (Net::steam_host), with thesteamworkscrate re-exported.
Re-exports§
pub use steamworks;pub use taffy as ui_layout;pub use ponko_ecs as ecs_core;pub use serde_json;
Macros§
- json
- JSON values used by reflection (re-exported from
serde_json). Construct aserde_json::Valuefrom a JSON literal. - profile_
scope - Times the rest of the block as a scope called
$name.
Structs§
- Action
Map - Serializable bindings, ordered by name. Runtime state is never serialized. Unknown names and queries of the wrong kind return false/zero.
- Alloc
Counts - Heap allocations made while profiling was on, from
alloc_counts. - Alloc
Report - Heap allocations per frame, from
PerfReport::allocs. - Ambient
Occlusion - Ground-truth ambient occlusion. Radius is in world units; quality controls angular slices and horizon steps. Disabled by default to preserve scenes.
- Animation
- Plays frames of a
SpriteSheeton an entity’sSprite. The built-inanimate_spritessystem advances it every frame. - Animation
Clip - Cheaply cloned, shared animation data. Sampling clamps time; for looping
use
time.rem_euclid(clip.duration())when duration is positive. The first sample on each distinct joint list allocates a name mapping; later samples (including skeleton clones) allocate nothing. Source skeletons use indices directly. Missing joints and shortened pose entries are skipped. - Animation
Event - A named event on a state’s normalized clock.
- Animation
Graph - Immutable graph shared by animators with independent parameters and clocks.
- Animation
Layer - An overlay with its own graph, parameters, events and clock. Layers run even
at weight zero. Configure parameters/commands through
animator; base-layer commands remain on the parent Animator. Nested layers are supported. - Animation
State - State playback settings. Use
AnimationState::newfor looping defaults. - Animation
Track - A vector track (translation or scale), or a quaternion track stored as xyzw.
Use
AnimationTrack::newto validate times and value counts. - Animation
Transition - An ordered transition. The graph’s first matching transition wins, with at most one taken per update; any-state transitions ignore exit time and do not reenter their current target. Exit time is a minimum on the state’s unwrapped normalized clock, checked against the end of this update.
- Animator
- Animation component. The engine updates it every frame after the frame
systems and before the draw systems: frame systems see the previous
frame’s pose, draw systems and the renderer this frame’s.
run_headlesshas no frames, so there (or to pose it at another point) setmanualand callupdateyourself, e.g. from a sim system. Buffers allocate on first use or skeleton changes, never in steady state. Interruptions freeze the last displayed mixed pose as the new fade source; ordinary fades continue advancing the outgoing state. Only the destination emits events and tests transitions. Events accumulate until drained, up to 64 entries; excess events are dropped, retaining the earliest events. - Attach
ToJoint - Keeps this entity’s
Transform3Don a joint of another entity’sSkeleton, moved byoffsetin the joint’s space: a gun in a hand, a hat on a head. The engine sets it just before drawing, so systems see last frame’s place;Skeleton::joint_matrixgives this frame’s. - Attached
- Keeps this entity’s
Transform2Dposition and rotation at an offset from another entity’s, updated byfollow_attachments. Its own scale is left alone. When the entity it’s attached to is despawned, this one is despawned too. Attachments can be attached to attachments. - Audio
Bus - Named mixer bus, created once with
Ctx::audio_bus. Handles belong to their creating context. The default handle selects thesfxbus. - Audio
Effects - Per-voice Kira low-pass and shared reverb send settings. Invalid values become defaults; cutoff is clamped to 20–20,000 Hz and send to 0–1.
- Audio
Listener3D - Where the ears are. By default they follow
ctx.camera3d; set your own withCtx::set_audio_listener. Velocity (for doppler) is estimated from frame to frame. - Audio
Settings3D - Settings for a positional voice. Distances are in world units (metres for
doppler); pitch is controlled by
sound.speed. Invalid ranges are clamped. - Audio
Source3D - A sound that plays from an entity, paired with
Transform3D. It starts by itself and follows the entity every frame. Removing the component or the entity stops it. One-shots don’t restart after they finish. - Authority
- Who owns an entity right now: an owner peer and an epoch counter. A handoff gives the entity to another peer and bumps the epoch; updates stamped with an older epoch are rejected, so a late packet from the previous owner can’t undo the handoff.
- Budget
- Limits for a
PerfReport, checked withPerfReport::assert_withinin tests and CI. Everything starts unlimited. - Budget
Violation - A limit in a
Budgetthat the report went over. - Camera2D
- Which part of the world the window shows:
ctx.camera. - Camera3D
- The 3D camera: where it is, which way it looks, and how wide it sees.
One per game, at
Ctx::camera3d. - Cell
Streamer - Which cells of a square grid on the ground (X and Z) to have loaded
around a point, such as the camera: those within
load_radius, started nearest first, and kept until they’re beyondkeep_radius. The gap between the two keeps cells at the edge from loading and dropping over and over as the camera moves back and forth. - Character3D
- A walking character (a player, a person): an upright capsule moved by
its
velocitythat slides along walls, climbs slopes up tomax_slopeand steps up tostep_height, stays on the ground going downhill, falls by gravity and pushes dynamic bodies. Needs aTransform3D, whose position is at its feet. - Clock
Sync - Maps a sender’s clock to ours. Every packet carries the sender’s time
sand arrives at our timer;r - sis the clock offset plus the trip time. The trip time only ever adds, so the estimate follows the lower end of the recent samples (the fastest packets), which makes it robust against jitter and late packets, then smooths that to avoid steps. Needs no round trips, and works one way. - Collider
- The solid shape of a body, and how it touches others.
- Collider3D
- The solid shape of a 3D body, its surface (friction, bounciness) and what it touches.
- Collider
Focus - Keeps static colliders around an entity (the player, a vehicle) once
Physics3D::stream_collidersis on: the colliders of fixed bodies andTerrainColliders withinradiusof it (on the ground, X and Z) are in the physics world, nearest first, and stay until they’re beyondkeep_radiusof every focus. The gap between the two stops a collider at the edge from coming and going as the focus moves back and forth. - Collision
Groups - Which colliders touch which: a collider is a member of the groups in
memberships(one bit each, 32 groups) and touches colliders whose memberships share a bit with itsfilter. Both sides must agree. Queries use the same test againstQueryFilter3D::groups. - Collision
Mesh - A convex hull, triangle mesh or heightfield, built once with
Physics3D::convex_hull,Physics3D::trimesh,Physics3D::heightfieldorPhysics3D::add_meshand shared by any number ofCollider3D::meshcolliders andTerrainColliders. A handle: copying it doesn’t copy the data. Handles are only meaningful in the game that made them. - Collision
Mesh Data - A convex hull, triangle mesh or heightfield built on the CPU, on any
thread: the slow half of
Physics3D::heightfieldand friends. Build it in aJobwith the rest of a streamed cell, then hand it toPhysics3D::add_meshon the game’s thread, which is quick. - Collision
Started - Event: two colliders started touching (or overlapping, for sensors).
Read with
ctx.events.read::<CollisionStarted>(). - Collision
Stopped - Event: two colliders stopped touching.
- Color
- An RGBA color. Components are 0.0 to 1.0, in sRGB (the values you’d pick in a paint program or see in CSS).
- Commands
- The ECS: entities, components, queries, resources, commands. A list of world changes to apply later. Use it to spawn or despawn while a query is running, since the query holds the world.
- Component
Id - The ECS: entities, components, queries, resources, commands.
Identifies a component type inside one
World. - Compute
- A compute pass shader, made with
Ctx::load_computeorCtx::create_compute; a cheap handle. Run it by adding aComputePasstoCtx::compute_passes. - Compute
Pass - One entry of
Ctx::compute_passes: a shader, the render target it updates, and a material whose custom values and textures it reads. - Contact
Modifier3D - Changes how a body’s contacts behave. Put it on an entity with a
Collider3D(the one-way side and the conveyor velocity are in that body’s own frame, so they turn with it): - Contact
Pair3D - The contacts between two bodies this step, as the custom contact hook
sees them (see
Physics3D::set_contact_hook). Changes affect this step only; the hook runs again the next. - Contributor
- Something that cost time in a
WorstFrame. - Counting
Allocator - The system allocator, counting what it hands out while profiling is on.
- Ctx
- What every system gets: the world, commands, events, input, drawing,
the clock, sound, the camera, physics and the network session. Systems are
fn(&mut Ctx). - Decal3D
- A box that paints an image onto the opaque surfaces inside it. The
entity’s
Transform3Dplaces the box (its scale multipliessize). The image is projected along the box’s -Z (looking from +Z), its top along +Y, as withMeshData::decal; only surfaces turned towards +Z get it. - Desync
- The peers’ worlds stopped matching: from
tickon, they’re different games. - Draw
Params - Optional settings for
Ctx::draw_ex. Start fromDrawParams::default()and change what you need. - Effect
- A screen effect shader, made with
Ctx::load_effectorCtx::create_effect; a cheap handle. Run it by adding aScreenEffecttoCtx::effects. - Entity
- The ECS: entities, components, queries, resources, commands.
A handle to a thing in the
World. Cheap to copy and store. - Events
- Messages between systems, by type:
Ctx::events. - FarTerrain
- Low-detail ground for the whole world, drawn beyond the terrain tiles
that are loaded: a few large meshes made from a coarse grid of heights
the game provides (the world’s heights, sampled every
spacingworld units), with the terrain material. Where a cell has its own tile, the far ground is cut away (FarTerrain::cut), so the two never overlap or fight over depth. A short skirt hangs down from every cut edge, and the tiles’ own skirts hang down beside it, so there’s no crack between the fine and coarse ground. - Field
- One field of a component described with
WorldReflect::reflect_fields. - Flow
Field - The way to the nearest goal from every cell of a
NavGrid. - Font
- A loaded font. Get one from
Ctx::load_font;Font::DEFAULTis always there. - Frame
Stats - Frame-time statistics over the last few seconds, from
Ctx::frame_stats. All times in milliseconds; the CPU and GPU parts are averages. - Frame
Times - Frame times, in milliseconds. In a headless run a frame is one tick.
- Friction
Curve - How much grip a tyre has for how much it slips: a curve rising from 0
to its peak
(extremum_slip, extremum_value), falling to(asymptote_slip, asymptote_value)and staying there, both pieces smooth and flat at their ends. The value timesstiffnesstimes the load on the wheel is the tyre’s force. - Game
- A game: a window plus the loop that drives your code.
- Gamepad
- A connected gamepad, from
Ctx::gamepads. It keeps its slot while connected, sopads[0]stays player one; a pad that reconnects takes the lowest free slot. - Global
Illumination - Real-time global illumination: sunlight, sky light and lamp light
bounced off the world’s surfaces onto others, at
Lighting::gi. A red wall in the sun tints the floor beside it red, a room lit through a window is lit all over (and a closed one goes dark instead of taking the sky’s light), and it all follows the sun through a day. - GpuBuffer
- A GPU array of
vec4<f32>. Empty initial data creates zeroed elements. - GpuPass
- One GPU pass of a frame, from
Ctx::gpu_passes. - Graphics
Quality - The settings that decide how heavy the 3D picture is, in one place: the
resolution it is drawn at, shadows, ambient occlusion, screen-space
reflections, global illumination and antialiasing.
low,medium,highandultraare ready-made sets; apply one withCtx::set_graphics_qualityand read the current one back withCtx::graphics_quality. - Grid
Entry - One entity in the grid: its handle, where it was at the last rebuild,
and optional data stored with it (see
SpatialGrid::rebuild_with_data). - Heightfield
- A terrain tile’s heights, for finding the ground under a point on the CPU: where to put a tree, keep a camera above the hills, or stand a character. Heights between the grid points follow the same triangles the tile is drawn with, so what’s found is exactly what’s seen. Coordinates are from the tile’s corner, X and Z from 0 to its size.
- Hit3D
- What a ray or a shape cast hit.
- Instance
Batch - A persistent batch. Handles are never recycled; freeing twice is harmless. Create one batch per streamed region and free it when that region unloads.
- Instance
Batch Options - Settings for a batch; materials come from the mesh’s parts.
- Instant
- A point in time for measuring how long something took, like
std::time::Instant(which it is, on desktop), but also working in web builds, wherestd::time::Instant::now()panics. Re-exported fromweb-time. - Interest
- Decides, tick by tick, which entities each peer receives and how often:
rings of distance around each viewer (
InterestConfig), a hysteresis at their edges, and a spatial grid so thousands of entities cost little. - Interest
Change - An entity entering or leaving a peer’s interest, from
Interest::changes. - Interest
Config - Rings of interest, from near to far, plus how sticky their edges are. Entities beyond the last ring are not sent at all.
- Interest
Entity - An entity in the world, for
Interest::update. The id is yours (a network id), unique within one update. - Interest
Entry - One entity a peer is interested in, from
Interest::entries. - Interest
Tier - One ring of interest: entities up to
radiusfrom a viewer (and beyond the previous, smaller ring) are sent everyeveryticks. - Interest
Viewer - Somebody who looks at the world: a peer and where. A peer may have several (split screen, a camera apart from its avatar); an entity counts by its nearest.
- Job
- Work running on a worker thread, and its result once it’s done.
- Joint
- One joint of a
Skeleton: its name, the joint it hangs from, and where it sits relative to that joint when nothing moves it (its rest pose). - Joint3D
- Put this component on a separate entity to connect two bodies. Removing that entity/component or either body’s physics components removes the joint next step. Missing endpoints are retried on later steps. Multiple joint entities may share bodies. Changing this component rebuilds its joint and wakes both endpoints.
- Joint
Animation - Tracks for a joint, identified both by its source index and name. Missing tracks leave the corresponding pose property untouched.
- Joint
Drive3D - A spring/damper drive. Zero stiffness gives a velocity motor. Rapier’s default acceleration motor model is used; targets use meters or radians.
- Joint
Mask - Joint indices selected for one skeleton layout. Build once, reuse each frame.
- Latest
Wins - A “latest wins per entity” filter for unreliable state updates: accepts an update only if it is newer than everything already accepted for the same key, which drops duplicates, reordered packets and updates from a previous authority epoch.
- Lighting
- The light in the 3D world: a sun far away (one direction everywhere)
and ambient light from all around. At
Ctx::lighting. - Line3D
- A line through
points(in its entity’s space), drawn as a camera-facing stripwidthmeters wide: laser beams, cables, ropes, power lines, paths. Changepointsany time; it’s rebuilt every frame it’s seen. - LodGroup
- Levels of detail: the meshes this entity draws depend on how much of the
screen it covers. Goes on an entity with a
Transform3D(and noModel: the group draws instead). - LodLevel
- One level of a
LodGroup: the meshes drawn while the group is at leastscreen_heighttall on screen. - LodRenderer
- One mesh of a
LodLevel, placed relative to theLodGroup’s transform. - LodSettings
- Global settings for
LodGroups, atCtx::lod: what a graphics quality setting changes. - Mat4
- 3D and 4D vectors, rotation and 4x4 matrix, for 3D (re-exported from
glam). A 4x4 column major matrix. - Material
- How a surface looks: its color (and texture), how rough and how metallic
it is, and light it gives off. Made with
Ctx::create_material; a cheap handle. - Material
Desc - What a
Materialis made from. - Mesh
- A mesh on the GPU: triangles, split into parts that each have a
Material. Made withCtx::create_meshor loaded withCtx::load_mesh; a cheap handle. - Mesh
Cost - What one mesh cost to draw in the last frame, from
Ctx::mesh_costs. - Mesh
Data - Triangles to make a
Meshfrom: corners with their normals and texture coordinates, and three indices per triangle (counter-clockwise seen from the front). - Message
Stats - Cumulative transport counters, including handshake, heartbeat and resends.
- Model
- Draws a
Meshwhere the entity’sTransform3Dis. - Morph
Animation - A named morph channel. Values use the track’s x component, in units where 1 is full weight. Cubic tangents use weight units per second.
- Morph
Frame - One frame of a piecewise linear morph channel. The channel’s weight is
stored at
channelin MorphWeights;targetselects this frame’s deltas. Every participating target must belong to exactly one channel. - Morph
Target - One shape a mesh can blend toward (see
MeshData::morph_targets): per corner, how far it moves and how its normal changes at full weight. - Morph
Weights - How much of each of its mesh’s morph targets
a
Modelshows: 0 none, 1 all of it (more or less than that exaggerates or inverts). By target index; missing ones are 0. A model without this component shows its mesh’s own weights (from its glTF file, else none). Animation clips with weight tracks set it. - Motion
Child - A motion inside a tree; positive time scale multiplies seconds.
- NavAgent3D
- Agent component; its feet follow the surface, without gravity.
Enable
avoidanceto use DetourCrowd instead of the original path follower. The original follower retains path storage and allocates only on replans. Crowd mode retains slots/corridors but the backend allocates query scratch. - NavBake
Error - Invalid input, resource limits or a Recast/Detour failure. No partial mesh is returned.
- NavBake
Settings - Bake clearances in world units, with slopes in degrees. +Y is up. Height/radius round up to cells; climb rounds down, so clearance is conservative.
- NavGrid
- A grid of walking costs: how hard each cell is to enter.
- NavMesh3D
- Tiled navmesh resource. Replace it with a new bake to invalidate agent paths.
Queries reject partial or truncated paths. Same ordered inputs yield the same
results; the backend’s
libmfeature removes platform libm differences. - NavObstacle3D
- World-space axis-aligned blocking box component; no Transform3D is needed.
- NavSource
- World-space, counter-clockwise triangle soup; include walls and ceilings too.
- Net
- A lockstep session:
ctx.net. Start one withNet::host,Net::joinorNet::loopbackand pass it toGame::lockstep. Without one,ctx.netis offline: one player whose input applies on the next tick, so the same game code runs alone and online. - NetMessages
- A game-owned, explicitly polled message endpoint. Hosts talk to clients; clients talk to their host. For P2P, each peer can host a separate endpoint. No simulation barriers, background threads or async runtime. Poll and drain every frame, even when simulation is paused. Application messages allocate; Renet also allocates outgoing packet batches. Queues are bounded.
- NetPose
- Component: a remote entity’s incoming
Posesnapshots, applied to itsTransform3Dbyapply_net_poses. Push each decoded update from your message handler withctx.time()as the arrival time. - NetStats
- What a session has sent so far (
Net::stats). - Particle
Curve - A piecewise linear size multiplier over normalized lifetime. Keys must be finite, strictly increasing, and in 0..=1; sampling clamps to the endpoints.
- Particle
Emitter3D - A CPU particle pool component, paired with
Transform3D. Simulation runs after frame systems; no meshes are required.run_headlessskips this visual frame phase. Cloning copies the live particles and RNG state. Capped emission is discarded. - Particle
Gradient - A piecewise linear RGBA gradient, interpolated in the supplied color space.
- Particle
Settings3D - Settings copied into an emitter. Change settings by creating a new emitter.
All numeric inputs must be finite; ranges must be ordered and nonnegative
(rotation may be negative). Invalid settings panic in
ParticleEmitter3D::new. - Pass
Report - One GPU pass, in
RenderReport::gpu_passes. - PeerId
- Opaque, session-local peer identifier. Clients address the host as
HOST; hosts obtain client identifiers from connection events. IDs are not reused. - Perf
Report - Where a game’s time and allocations go, over its last frames. It comes
from
Ctx::perf_reportin a running game andGame::profile_headlessin a headless run. - Perf
Warning - A problem the report found, and what to do about it.
- Physics
- The physics world:
ctx.physics. Add it to a game withGame::physics; then entities withRigidBody,ColliderandTransform2Dare simulated. - Physics3D
- The 3D physics world:
ctx.physics3d. Add it to a game withGame::physics3d; then entities withRigidBody3D,Collider3DandTransform3Dare simulated, and entities withCharacter3DandTransform3Dwalk. - Playing
- A sound that was started, to stop it later with
Ctx::stop_sound. - Point
Light3D - Omnidirectional light at its entity’s
Transform3D::position. Scale is ignored. Intensity is linear radiant intensity; distance attenuation is inverse-square, softened within one world unit and smoothly windowed to zero atrange. Invalid/nonpositive ranges or intensities disable the light. - Pose
- A position and rotation, optionally with the velocity the owner was moving
at. Interpolates position linearly, or along a cubic Hermite curve when
both neighbouring snapshots carry a velocity (smoother through curves and
at low send rates), and rotation with slerp. Extrapolation moves the
position on at
velocity, or at the speed seen between the last two snapshots when there is none; rotation is held. - Post
- What happens to the lit 3D frame before it reaches the screen. Sprites and UI drawn on top are not changed.
- Profile
Scope - One named scope: where
profile_scope!adds up the time spent inside it. - Quat
- Rotation and 3D vector (re-exported from
glam); also used by the replication helpers (Pose,Interest), which need no3dfeature. A quaternion representing an orientation. - Query
- The ECS: entities, components, queries, resources, commands.
A query over a
World, created byWorld::query. - Query
Filter3D - Which colliders a query sees. The default sees every solid collider and no sensors.
- Ragdoll3D
- A skeleton in physics’ hands, on the entity with the
SkeletonandTransform3D; made byCtx::start_ragdoll, ended byCtx::stop_ragdoll. While it lasts, the entity’sAnimatoris paused and the pose follows the bodies. Push it withPhysics3D::apply_impulseonbody. Stop it before despawning the entity: its bodies are entities of their own. - Ragdoll
Bone - One bone of a ragdoll: the skeleton joint it starts at, how thick it is, and how far its joint to the parent bone bends.
- Random
- Where a system’s random numbers come from this tick: from
Ctx::random.Copy, so it can be used insidepar_for_each. - RayHit
- What a ray hit.
- Receives
Decals - Which decal layers a model takes (see
Decal3D::layers). Models without it take every decal. Only the low 16 bits count. - Rect
- An axis-aligned rectangle:
minis the top-left corner,maxthe bottom-right (y grows downward, like window pixels). - Reflection
Probe3D - A local environment at an entity’s
Transform3D::position. Rotation and scale are ignored. Four baked environments can be resident; zero content falls back to sky lighting. Capture excludes transparent objects. - Regression
- Something that got slower between two reports, from
PerfReport::regressions. - Render
Report - What drawing cost, in a windowed game’s
PerfReport. - Render
Stats - What drawing the last frame cost, from
Ctx::render_stats. - Rigid
Body - Makes an entity a physics body. It also needs a
Colliderand aTransform2D. - Rigid
Body3D - Makes an entity a 3D physics body. It also needs a
Collider3Dand aTransform3D. - Rng
- A small, fast random number generator (xoshiro256++). Same seed, same numbers, on every machine.
- Root
Motion - Horizontal translation in skeleton-local axes and yaw for the latest update. Vertical motion and pitch/roll stay in the pose. Apply translation using the entity’s pre-update orientation, then postmultiply its rotation.
- Scope
Guard - Times the code until it is dropped. From
profile_scope!orProfileScope::enter. - Scope
Report - One profiling scope’s cost, from
PerfReport::scopes. - Scope
Timing - One scope’s times, from
Ctx::scope_timings. - Screen
Effect - One effect in
Ctx::effects: its shader, and a material whose custom values and textures the shader reads (material.custom[0]to[3],custom_texture0, …). - Shader
- A material shader written in WGSL: made with
Ctx::load_shaderorCtx::create_shader; a cheap handle. See the 3D chapter of the guide for what a shader can do. - Shadow
Mesh - Draws a different mesh into the shadow maps than the entity’s
Modelshows: a cheap stand-in for a detailed model’s shadow (a simplified copy, a billboard), orNonefor no shadow from this entity. Without it, the model’s own mesh casts the shadow (unlessCtx::set_mesh_shadowsturned that mesh’s shadows off). - Skeleton
- A component that poses the skinned
Modelon the same entity (and the models whoseSkinOfpoints at it): each joint’sposeis where it sits relative to its parent this frame, and the mesh’s corners follow the joints they’re weighted to. Loaded from a glTF file withCtx::load_skeleton, or made in code withSkeleton::new. Cloning one is cheap: the joints are shared. - SkinOf
- Poses this entity’s skinned
Modelwith another entity’sSkeleton, and draws it where that entity is: clothes, hair and swappable parts made for the same skeleton. Joints are matched by name, so a part works on any skeleton that has its joints. The entity needs noTransform3Dof its own. - Sky
- The sky behind the 3D world, and the fog in front of it:
ctx.sky. - Snapshot
Buffer - Timestamped states of one entity, in time order, read back at any time:
interpolated between two snapshots, predicted for a bounded time past the
newest, then held. Times are the sender’s, in seconds on any timeline you
like (for a remote entity use
SnapshotStream, which also converts your local clock). - Snapshot
Config - Tuning for
SnapshotBufferandSnapshotStream. - Snapshot
Sample - A state read from a
SnapshotBufferorSnapshotStream. - Snapshot
Stream - A
SnapshotBufferplus aClockSync: what you need per remote entity. Push each decoded snapshot with the sender’s timestamp and our clock; sample with our clock, once a frame. - Sound
- A loaded sound. Cheap to copy. Get one from
Ctx::load_soundorCtx::create_sound. - Sound
Params - Optional settings for
Ctx::play_sound_ex. - Spatial
Grid - A uniform grid over the whole (unbounded) world, rebuilt from scratch each tick: answers radius, rectangle and nearest-neighbor queries without checking every entity.
- Spot
Light3D - Cone light pointing along its entity’s rotated local -Z (its forward).
Angles are cone half angles in radians,
0 <= inner <= outer < pi/2. Equal angles give a hard cone edge. Invalid angles disable the light. Position, intensity, range, scale and shadows followPointLight3D; a shadowed spot light needs one shadow view. - Sprite
- Makes an entity visible: drawn at its
Transform2Dby the built-indraw_spritessystem. - Sprite
Sheet - A texture cut into equal frames on a grid, numbered left to right, top to bottom: an animation strip, a tileset, a texture atlas of icons.
- Steam
Lobby - An asynchronously created/joined Steam lobby. Call
polleach frame;idisNoneuntil Steam completes the request. Drop orleaveleaves it. Metadata is cached by Steam; remote changes become visible after callbacks. - System
Report - One system’s cost, from
PerfReport::systems. - System
Timing - How long one system took. See
Ctx::system_timings. - Target
Camera - A camera drawing the 3D world into a render target each frame, before
the main view: one entry of
Ctx::target_cameras. - Terrain
Collider - Makes an entity’s terrain tile solid: a fixed collider of a
heightfield made from the tile’s heights, at
the entity’s
Transform3D(the tile’s corner), turned and scaled with it, so it matches the drawn ground triangle for triangle. Holes are open. Put it on the entity with theTerrainTile(not with aRigidBody3D): despawning the tile removes its collider, and giving it a new mesh after an edit swaps the collider at the next physics step. - Terrain
Material Desc - What a terrain material is made from: ground layers (grass, dirt, rock,
…) and a weight map saying how much of each shows where. Made into a
MaterialwithCtx::create_terrain_materialand used forCtx::create_terrain_tile. - Terrain
Tile - A square of terrain from a grid of heights, made with
Ctx::create_terrain_tile. Spawn it with aTransform3Dat the tile’s corner, instead of aModel. The renderer picks a detail level by how far the camera is: the full grid nearer thanlod_distance, then every 2nd height to twice that, every 4th to four times that, and every 8th beyond. Skirts hide the cracks where tiles of different detail meet. - Terrain
Tile Data - The meshes of a terrain tile at every detail level, made on the CPU
from its heights: build them on a worker thread with a
Job, thenCtx::upload_terrain_tileon the game’s. - Text3D
- Text in the world, drawn on its entity’s
Transform3D: a shop sign, a name over a head, a damage number. It stays sharp at any size and distance, and can have an outline and a soft edge (for glows and shadows). Any loadedFontworks, and one entity’s text can’t mix fonts; use several entities for that. - Text
Params - Optional settings for
Ctx::draw_text_ex. - Texture
- A loaded image on the GPU. Cheap to copy: it’s just an id plus its size.
- Texture
Array - Several images of the same size in one texture, for materials that use
many: terrain layers, foliage variants. Made with
Ctx::create_texture_arrayorCtx::load_texture_array; a cheap handle. Custom shaders read one throughMaterialDesc::custom_arrays, and it gets mipmaps. - TileMap
- A grid of tiles, each a frame of
sheetor empty. Put it on an entity with aTransform2D: its position is the map’s top-left corner (the rotation and scale are ignored). The built-indraw_tilemapssystem draws the tiles the camera can see, so maps can be huge. - Trail3D
- A ribbon left behind its entity as it moves: tracers, sword swings,
streaks behind cars or projectiles. It faces the camera, is widest where
widthsays (over age, 0 at the entity, 1 at the end) and fades bycolor. Points are recorded in the world, so the ribbon stays where the entity went. Like particles, trails are only for show: headless runs don’t record them. - Transform2D
- Where an entity is: position, rotation and scale.
- Transform3D
- Position, rotation and scale of a 3D entity.
- Turns
- Which entities update this tick, from
Ctx::turns. - UVec2
- Whole-number 2D vector, for tile coordinates (re-exported from
glam). A 2-dimensional vector. - Ui
- Owned UI tree and screen stack. Build once, then mutate node properties. Draining events avoids callbacks borrowing the game and UI together.
- UiId
- Stable node identity, never reused within a UI.
- UiInput
- Input snapshot in logical window coordinates.
Ctxsupplies this each frame; tests and custom hosts can callUi::framedirectly. - UiPaint
- Visual style, independent of Taffy’s layout style. A texture with
slice > 0is drawn as nine patches;sliceis the source border in pixels. - UiPanel3D
- Retained UI shown on a quad in the world (Rust’s
Uion a surface): a computer screen, a shop terminal, a sign with buttons. BuilduilikeCtx::ui_retained; its widgets are laid out intexture’s pixels. - UiStyle
- Colors and sizes of the built-in UI:
ctx.ui_style. - Update
Stamp - A state update’s place in time: the owner’s
epoch(bumped on every authority handoff) and aseqcounter that wraps and restarts per sender. A higher epoch always beats a lower one; within an epoch the newerseqwins. - Vec2
- 2D vector used for positions, sizes and velocities (re-exported from
glam). A 2-dimensional vector. - Vec3
- Rotation and 3D vector (re-exported from
glam); also used by the replication helpers (Pose,Interest), which need no3dfeature. A 3-dimensional vector. - Vec4
- 3D and 4D vectors, rotation and 4x4 matrix, for 3D (re-exported from
glam). A 4-dimensional vector. - Vehicle3D
- A car, truck or any wheeled vehicle: up to
MAX_WHEELSraycastWheel3Ds holding up the entity’s chassis, which needs a dynamicRigidBody3D, aCollider3Dand aTransform3D. The chassis faces its -Z. - Velocity
- A body’s speed, in pixels and radians per second. Read it after a step; write it to set the speed (a jump, a thrown crate, a moving platform).
- Velocity3D
- A 3D body’s speed: meters per second, and radians per second around each axis. Read it after a step; write it to set the speed.
- Wheel3D
- One wheel of a
Vehicle3D: where it’s mounted, its suspension and tyres (set these up once), what drives it this tick (yours to set), and what happened to it in the last physics step (read after the step). - World
- The ECS: entities, components, queries, resources, commands. Holds everything in the simulation: entities, their components, and global resources.
- Worst
Frame - One of the slowest frames, from
PerfReport::worst_frames.
Enums§
- Action
- An action’s kind and sources. Buttons OR together; axes select the source with greatest magnitude (first wins ties), avoiding doubled movement.
- Animation
Condition - Transition predicates, all of which must hold.
- Animation
Parameter - Parameter defaults; indices in the graph identify parameters.
- Anti
Aliasing - Antialiasing of the 3D frame. FXAA and SMAA work on the tone mapped image
before sprites/UI;
Taaworks on the lit HDR frame. - Audio
Rolloff - Distance gain curve. Keyed curves use normalized distance and linear gain; keys must be sorted by distance. Values outside the keys use the nearest key.
- Authority
Check - What to do with a state update, judged against an
Authority. - Axis2
Binding - A vector source. Keyboard diagonals are normalized; sticks use a radial deadzone and retain their direction. Y is positive down.
- Axis
Binding - A scalar source. Gamepad values inside the deadzone read zero; outside they are rescaled continuously to full range. Invalid deadzones read zero.
- Blend
- How a material covers what’s behind it.
- Body
Kind - How a body moves.
- Button
Binding - A digital source. Gamepad slots are stable while connected.
- Field
Type - The type of a field in
WorldReflect::reflect_fields, and how it looks in JSON. - Gamepad
Axis - One axis of a gamepad: a stick’s x or y (
-1.0..=1.0, y down is positive like screen coordinates) or a trigger (0.0..=1.0). - Gamepad
Button - A gamepad button, named by its position, so it means the same on every brand of controller.
- Gamepad
Stick - Which stick, for
Ctx::gamepad_stick. - Input
Event - Raw input for headless tests and replay. Feed before querying actions.
- Interest
Change Kind - Whether an entity entered or left a peer’s interest.
- Interpolation
- Interpolation between keys. Cubic values are stored as incoming tangent, value, outgoing tangent for each key; tangents are derivatives per second.
- Joint
Axis3D - The six axes in the joint’s local frames, translations followed by rotations.
- Joint
Motion3D - Freedom on one joint axis; distances are meters, angles radians.
- Key
- A keyboard key, identified by its physical position on a US layout.
- Lane
- Delivery policy; ordering is independent in each direction and peer.
- Layer
Blend - How a layer combines with the lower pose.
- LodPick
- Which level or levels of a
LodGroupare drawn, fromLodGroup::pick. - LodShadow
- What a
LodLevelcasts into the shadow maps. - Message
Event - Connection changes and owned application payloads. Drain events every poll.
- Motion
- A recursive motion. Trees use seconds, with each child scaling its clock. Tree duration is the longest child duration divided by its time scale. 2D uses normalized inverse squared distance; an exact point selects only that child (the first if points coincide). Quaternion blends use ordered incremental slerp, so child order matters for more than two rotations.
- Mouse
Button - A mouse button.
- NetState
- Where a session is.
- Particle
Blend3D - Particle compositing, always depth tested with depth writes disabled.
- Particle
Shape3D - Emission volume in the entity’s coordinates; cone directions point along +Y.
- Particle
Space3D - Whether existing particles follow the emitter’s transform.
- Quality
Level - Which of the
GraphicsQualitypresets some settings are. - Reflect
Error - Why a reflection call failed.
- Shape
- A collider’s shape, in pixels, centered on the entity (plus
Collider::offset) and turned with it. - Shape3D
- A collider’s shape, in world units (meters), centered on the entity
(plus
Collider3D::offset) and turned with it. Scale isn’t applied. - Snapshot
Push - What happened to a snapshot given to
SnapshotBuffer::push. - Snapshot
State - How a
SnapshotSamplewas produced. - Steam
Lobby Visibility - Visibility of a Steam lobby (feature
steam). - Text
Align3D - How the lines of a
Text3Dline up. - Texture
Filter - How a texture looks when drawn bigger or smaller than its pixels:
Ctx::set_texture_filter. - Texture
Kind - What a
TextureArray’s pixels hold. - Tonemap
- How HDR light (which can be far brighter than white) is mapped to the screen.
- UiEvent
- One semantic event; values are read from the node after
Changed. - UiText
Align - Text alignment within a node’s content box.
- UiWidget
- Built-in behavior; text, images and decoration are configured separately.
- Value
- JSON values used by reflection (re-exported from
serde_json). Represents any valid JSON value. - Warning
Kind - What a
PerfWarningis about.
Constants§
- DEFAULT_
SEED - The seed games use unless
Game::seedsets one, so runs are reproducible by default. - LIGHT_
SHADOW_ ATLAS_ SIZE - Default width and height of the depth atlas every point and spot light
shadow view is packed into, in texels (see
Lighting::light_shadow_atlas). - LIGHT_
SHADOW_ SIZE - Default width and height of the largest point or spot light shadow
view, in texels (see
Lighting::light_shadow_resolution): what a light near the camera gets. - MAX_
DECALS - The most decals drawn in a frame. When more are in view, the ones nearest the camera are kept.
- MAX_
DECALS_ PER_ CLUSTER - The most decals one screen cell blends (the screen is 16 x 9 cells, each
split into 24 slices of depth). Where more overlap, the ones with the
highest
Decal3D::orderare kept. - MAX_
GAMEPADS - How many gamepads the engine tracks at once.
- MAX_
GI_ PROBES - The most probes a
GlobalIlluminationgrid has: a biggerextentat the same spacing is shrunk to fit. - MAX_
GI_ PROBES_ PER_ FRAME - The most probes updated in one frame
(
GlobalIllumination::probes_per_frame). - MAX_
INPUT_ BYTES - The most bytes one player’s input for one tick can have.
- MAX_
INTEREST_ TIERS - The most tiers in an
InterestConfig. - MAX_
LIGHT_ SHADOW_ VIEWS - The most shadow views point and spot lights can share each frame (see
Lighting::light_shadow_views, 12 by default): a shadowed spot light takes one, a shadowed point light six. Each view is a square tile of the lights’ shadow atlas. - MAX_
MESSAGE_ BYTES - Maximum application payload, in either lane (1 MiB).
- MAX_
PLAYERS - The most players in one session.
- MAX_
POLYGON_ POINTS - Most corners a
Shape::Polygoncan have. - MAX_
RENDER_ SCALE - See
MIN_RENDER_SCALE. - MIN_
RENDER_ SCALE - Smallest and largest
Post::render_scale. - PHYSIC
S3D_ HZ - The simulation rate
Game::physics3dsets, unless the game picked its own withGame::fixed_hz: 50 steps per second. - SPATIAL_
SORT_ EVERY - How often (in ticks) the built-in grid also reorders entities in memory
by
spatial_key. Positions drift slowly, so occasional sorting keeps neighbors close in memory at a small amortized cost (1M entities: ~18 ms per sort, ~0.5 ms per tick). - TERRAIN_
LAYERS - The most ground layers a terrain material blends.
- TERRAIN_
LODS - How many detail levels a
TerrainTilehas: every height, then every 2nd, 4th and 8th.
Traits§
- Component
- The ECS: entities, components, queries, resources, commands.
Any
Send + Sync + 'statictype can be a component. No derive needed. - Interpolate
- A state that can be blended between two snapshots and predicted past the
last one. Implemented for
f32,Vec2,Vec3,QuatandPose; implement it for your own state to useSnapshotBufferwith it. - Setup
Result - What
setupmay return: nothing, or a closure to run every frame. - World
Reflect - Reflection methods on
World: read and write components by name as JSON.
Functions§
- alloc_
counts - The allocations counted so far (while profiling was on). Take two readings
and subtract to count a stretch of code. All zero if
CountingAllocatorisn’t installed and nothing callsnote_allocation. - animate_
sprites - Built-in system: advances every
Animationand shows its frame on the entity’sSprite.Gameruns it every frame, beforedraw_sprites. - apply_
net_ poses - System: sets the
Transform3Dposition and rotation of every entity with aNetPosefrom its stream, sampled atctx.time()(scale is left alone). Entities without snapshots stay where they are. Add it withGame::system, so entities move every frame whatever the simulation does; the stream’s timestamps are matched againstctx.time(), so push with that clock. - camera_
controls - A ready-made system for looking around big worlds: drag with the right or middle mouse button to pan, scroll to zoom toward the mouse.
- draw_
sprites - Built-in system: draws every entity that has a
Transform2Dand aSprite.Gameruns it every frame by default. - draw_
tilemaps - Built-in system: draws the visible tiles of every
TileMap.Gameruns it every frame, beforedraw_sprites. - follow_
attachments - Moves every entity with
Attachedto its place next to the entity it follows, on all cores, and despawns those whose entity is gone. Add it as a simulation system after the ones that move things. - interpolate_
physics3d - Draws moving bodies smoothly: between two physics steps, sets each
moving body’s
Transform3Dto a blend of its last two poses, by how far the frame is between them (Ctx::fixed_alpha). Added as the first frame system byGame::physics3d, so camera code sees the blended pose too. Does nothing in headless runs, where frames and ticks line up. Transforms you changed since the last step are left alone (they teleport the body at the next step). - look_
at_ joint - Aims
axis(joint-local) at a world point, limiting the correction angle in radians in the joint parent’s space, then applying weight (clamped 0..1). Call in parent-to-child order with separate weights to spread over a chain. Zero axes, coincident targets, invalid indices and singular transforms are ignored. Entity scale is handled by inverse transformation; non-uniform joint scales/shear make the angular limit approximate in world space. - note_
allocation - Counts one allocation of
bytesmade by something that isn’t Rust’s allocator, such as C++’soperator new(seeCRABBY_COUNT_CPP_ALLOCATIONSincrabby.hpp). Counts only while profiling is on. - rebuild_
spatial_ grid - Built-in system added by
Game::spatial_grid: re-indexes everyTransform2Dentity intoctx.spatial. It runs first in every simulation tick, and everySPATIAL_SORT_EVERYticks it also sorts entities by cell so neighbor queries stay cache-friendly. - scope_
named - The scope called
name, made the first time it is asked for. Names are kept for the life of the process. - seq_
diff - Signed distance from
btoaon a 16-bit circle: positive whenais ahead ofb, negative when behind, zero when equal. Sequence numbers more than half the range (32768) apart are ambiguous; that exact distance yieldsi16::MIN. - seq_
newer - Is
anewer thanb, with 16-bit wrap-around? Equal numbers are not newer. Exactly half the range apart (32768) is ambiguous: neither is newer. - spatial_
key - Z-order (Morton) key of the grid cell containing
position: points that are close in space usually get close keys. Sort entities by it so that neighbors sit next to each other in memory: - steam_
lobby_ from_ args - The lobby of a Steam invite this game was launched with (Steam starts
the game with
+connect_lobby <id>when a friend accepts an invite while it isn’t running). Featuresteam. - steam_
wait_ for_ invite - Waits up to
timeoutfor the player to accept a friend’s Steam invite to a lobby, while the game is running (Steam tells a running game instead of starting it). For a “join a friend” screen before the game starts;steam_lobby_from_argscovers invites accepted while it wasn’t running. Featuresteam. - step_
navmesh3d - Register with
Game::sim_system, just like the exposed physics step. No resource means no-op. Each tick gathers obstacle components, invalidates paths on mesh/obstacle/destination changes or teleports, then moves agents. Stalled agents retry when those inputs change. No window/GPU is required. - step_
physics - Steps the physics world one simulation tick: picks up new, changed and
removed bodies, simulates, writes positions and velocities back, and
sends
CollisionStarted/CollisionStoppedevents. Added byGame::physics; remove or reorder it like any other system. - step_
physics3d - Steps the 3D physics world one simulation tick: picks up new, changed
and removed bodies, moves characters, simulates, writes poses and
velocities back, and sends
CollisionStarted/CollisionStoppedevents. Added byGame::physics3d; remove or reorder it like any other system. - two_
bone_ ik - Rotates a direct parent-child-child chain toward a world target without
changing translations or lengths.
poleis a world-space bend direction. Weight is clamped to 0..1. Invalid indices, incomplete poses, singular transforms and zero-length bones are ignored. Collinear hints use a stable perpendicular. Targets outside reach use the closest reachable distance. - uvec2
- Whole-number 2D vector, for tile coordinates (re-exported from
glam). Creates a 2-dimensional vector. - vec2
- 2D vector used for positions, sizes and velocities (re-exported from
glam). Creates a 2-dimensional vector. - vec3
- Rotation and 3D vector (re-exported from
glam); also used by the replication helpers (Pose,Interest), which need no3dfeature. Creates a 3-dimensional vector. - vec4
- 3D and 4D vectors, rotation and 4x4 matrix, for 3D (re-exported from
glam). Creates a 4-dimensional vector.