Stage Overview & Renderer
The stage is Xodó's unified scene API and renderer for 2D, 2.5D, and 3D games. Its core lives in two crates that hosts opt into directly:
engine-stage(stage/) — Headless CPU scene model (transforms, cameras, visibility, sorting, culling, picking, and text layout viaharfrustandskrifa).engine-stage-render(stage/render/) — Draws stage draw lists through the device layer.
Optional world capabilities (regions, cells and portals, terrain, skeletal skinning, converted assets, and built-in world materials) live in separate crates under stage/ (World capabilities), so small 2D/3D hosts never link or pay for them.
Scene Model
Stage is a retained store. The host creates nodes, cameras, meshes, and textures, mutates them through typed handles, and destroys them. The stage owns no schedule, ECS, or game loop.
- Handles —
Id<Kind>(NodeId,CameraId,TextureId,MeshId) packs a slot index and generation. Destroying an occupant bumps the generation so stale handles returnNoneorfalse(to_bits/from_bitsserialize a handle as one integer). - Nodes — Each node has an optional parent, a
Transform(translation, rotation quaternion, scale),visible, aLayerMaskof render layers, and optional drawables or lights. World space is right-handed and Y-up; a camera looks down its node's-Z, so larger Z is nearer. - Dirty tracking — Setters mark a node dirty;
updaterefreshes each changed subtree from its topmost dirty ancestor, caching world matrices and inherited visibility.revisioncounts changes so hosts can skip redrawing static frames. Setting an identical value is a no-op;edit_sprite/edit_meshbump revision only on change. Render layers are per node and not inherited. - Textures — The stage stores a texture's dimensions and
Filter(NearestorLinear) for UV math and batching; pixel data lives inStageRenderer. - Sprites — Texture, optional atlas rectangle in texels, world size, anchor, tint, flips, optional nine-slice (texel borders + world-units-per-texel
scale),BlendMode(Alpha,Premultiplied,Additive,Add,Multiply,Screen),Material(UnlitorLit),AlphaMode, optional normal texture, emissive colour,cast_shadow/receive_shadow, sortinglayer, andz_offset. - Meshes —
MeshData(positions, normals, UVs, optional tangents and vertex colours, 32-bit triangle indices; counter-clockwise outward, V down) is validated byMeshData::info(MeshInfocounts and bounds underMeshId); the renderer owns GPU buffers.MeshData::planeandcuboidbuild primitives. Nodes carry aMeshDrawable(mesh,MeshMaterial,draw,cast_shadow,receive_shadow,layer,z_offset).MeshDrawable::castercreates a shadow-only caster.MeshMaterial::late > 0draws after opaque surfaces and regions before blended draws in ascending order;depth_test = falsedraws over existing depth without writing depth;MeshMaterial::ambient(default1.0) scales classic ambient light.Stage::set_cloud_shadowsshades directional lights by the coastal cloud deck (shaders/scene/coastal_sky.slang). - Lights —
Ambient,Directional,Point(range), orSpot(range, inner/outer half-angles), with colour, intensity,cast_shadow, and shadow bias. Position is the node's; direction is its-Z. - Cameras — Sit on a node (scale ignored) with a
Projection,Viewport(target fractions),Target(window drawable or texture), optional clear colour, ascendingorder,LayerMask,YSort,Resolution, andpixel_snap.
Projections & Virtual Resolution
Projection is #[non_exhaustive]. Aspect always comes from the camera's picture (viewport or virtual resolution), keeping clip Z in 0..1 and clip W:
Orthographic { height, near, far }—heightcamera-space units tall;nearandfarmay be negative. For 2.5D top-down views,Projection::tilted_orthographic(ground_height, pitch, distance, depth)andTransform::orbit(target, yaw, pitch, distance)set up a pitched orthographic camera over the XZ ground plane.Perspective { fov_y, near, far }— Vertical field of view in radians with positivenearandfarand perspective-correct UV interpolation.Resolution—Nativefills the viewport;Letterbox { size, integer }centres a virtual resolution (largest integer multiple whenintegeris true) with clear-coloured bars that ignore draws and picks;Scale { size, mode }fills viaStretchorCover.screen_to_virtualandvirtual_to_screenmap coordinates to the virtual grid.pixel_snap— Snaps each sprite's lower-left corner to whole picture pixels in parallel projections so pixel art never shimmers (sorting and picking still use true node positions).- Low-resolution upscaling — Render into a small nearest-filtered texture target and call
Stage::create_upscale(source, layer, order, integer)to letterbox it onto the window at crisp integer scale.
Queries & Picking
camera_viewreturnsCameraView(view, projection, view-projection and inverse, viewport, andcontentpixel rectangle).screen_to_ray,screen_to_world(point, depth),screen_to_plane(point, plane_point, normal), andworld_to_screenoperate in target pixels (origin top-left).pickandpick_allreturn sprite nodes hit by the pointer ray front-to-back, respecting camera layers and excluding letterbox bars.
Ordering, Culling, and Batching
A camera draws visible nodes intersecting its LayerMask whose geometry touches its clip volume (near-plane clipped for sprites; bounding-sphere culled for meshes).
- Opaque & cutout drawables (
AlphaMode::Opaque,Cutout(threshold)) write depth and draw first, grouped by bindings (mesh, textures, lit, sidedness) into instanced batches ordered nearest-first. Mirrored mesh instances (negative determinant) batch separately (SurfaceBatch::mirrored) with flipped face culling. - Blended drawables (
AlphaMode::Blend) follow, sorted by sortinglayer, depth key (camera-space Z +z_offset, or negated world Y onYSortlayers), secondary key, and creation order, testing opaque depth without writing it. A camera allocates aDepth32Floattransient only when it draws opaque geometry. - Sprite vs. surface path — Unlit blended sprites without emission take the fast sprite path (
instances,batches). Meshes and lit/opaque/cutout/emissive sprites take the surface path (surface.instances,surface.batches).DrawList::stepsinterleaves both in exact draw order.
Draw List
Stage::build_draw_list(camera, window_size, &mut DrawList) populates reusable CPU buffers:
- Camera target, size, viewport,
contentrectangle,scissor, and view-projection matrix. instances: Vec<SpriteInstance>— 96-byte#[repr(C)]quads checked againstshaders/stage_sprite.slangbybuild/device-shaders.ts.batches: Vec<Batch>and surface batches, plus drawn/culled counts.
StageRenderer
StageRenderer holds no device; each call borrows &mut dyn Device. It compiles shaders/stage_sprite.slang and shaders/stage_surface.slang in the background, creating pipelines lazily per target format, blend mode, depth mode, and sidedness.
Textures & Mip Chains
create_texture(stage, w, h, rgba, filter),create_target,resize_target,write_texture,resize_texture,destroy_texture.create_texture_with_mipsaccepts a host mip chain;create_texture_generating_mipsbuilds 2×2 linear-light alpha-weighted mips on the CPU.create_texture_from_sourcestreams anRgbaMipSourceacross frames within the device's per-frame upload budget, resuming at the next unsubmitted row if backpressured.- PNG decoding is outside the crate (use
engine_platform::load_pngor a host decoder to pass RGBA8).
Meshes & Dynamic Updates
create_mesh(stage, &MeshData),create_dynamic_mesh,destroy_mesh. Vertices are 64-byte records pulled from storage buffers; indices are 32-bit.update_mesh(stage, id, &MeshUpdate { ... })updates geometry and bounds. Dynamic meshes accept partial attribute updates at the same vertex count; static meshes require all attributes. Oversized transfers stream across frames while cameras continue drawing the previous complete revision.DrawableReport::mesh_uploadsandmesh_bytestrack transfers.
Recording Frames & Pass Selection
record(device, stage, graph, window) appends one raster pass per enabled camera to the host's Graph, returning Ready, Pending (while pipelines compile or uploads defer), or Failed(message).
Passes and resources follow actual camera usage:
- A 2D sprite camera records a single sprite pass with no depth buffer, light buffer, or shadow atlas — even if other layers contain lights or 3D geometry.
StageRenderer::reportcounts camera passes, depth buffers, light buffers, shadow passes, and shadow tiles.read_target(graph, texture)schedules an async readback;captureruns full frames and returns RGBA8 pixels for tests and screenshots.
Multisampling (MSAA)
Camera::msaa selects Msaa::Off (default), Msaa::X2 (falls back to 4× if unsupported), or Msaa::X4. Multisampled cameras draw into memoryless transient colour/depth attachments resolved in the same pass. SDR cameras resolve directly into full-viewport clearing targets; any HDR camera can enable MSAA before its post chain. StageRenderer::msaa_report tracks multisampled cameras and attachments.
Render Scale
Camera::render_scale (default 1.0, clamped to 0.25..=1.0) renders the camera and its post chain at reduced resolution and upscales over the viewport via postUpscale in shaders/stage_post.slang, with optional contrast-limited sharpening (StageRenderer::set_upscale_sharpness).
- Cameras that compose over another camera's output (such as a world over a sky) use
Camera::backdropso the HDR picture starts from the decoded backdrop texture and can still scale cleanly. - Hosts can drive
render_scaledynamically from GPU frame time usingengine_core::dynamic_resolution::DynamicResolution.