The engine, running in your browser.
Each demo is a crate example from the repository, compiled to WebAssembly and drawn with WebGPU. The source below each one is the whole program, exactly as it builds for macOS and the browser.
Lantern, a small maze game
Carry a lantern through a dark maze to the green door. Brick walls are lit meshes the lantern's point light shadows, the walker and pickups are upright lit sprites, and a second camera draws the oil gauge over the scene.
Walk with the arrows or WASD, or hold the pointer where to go. The light shrinks as the oil burns; amber flasks in the dead ends refill it.
//! Lantern: a small game on the lit 2.5D stage. Carry a lantern through a dark maze to the green door; the lantern's
//! light shrinks as its oil burns, and the amber flasks in the dead ends refill it. Each door opens a larger maze.
//! The walls are lit meshes the lantern's point light shadows, the walker and the pickups are upright lit sprites, and a
//! second camera draws the oil gauge and the doors passed over the scene.
//! Arrows or WASD walk; holding the mouse button (or a finger) walks toward it.
//! `cargo run -p engine-stage-render --example lantern` (ENGINE_SHADER_DIR as for the crate); close the window to quit.
//! `bun build/build.ts web-example engine-stage-render lantern` builds it for the browser.
#[cfg(any(target_os = "macos", target_os = "emscripten"))]
mod game {
use engine_platform::{Platform, sdl};
use engine_render_device::Graph;
use engine_stage::*;
use engine_stage_render::StageRenderer;
/// A maze cell's side, in world units.
const CELL: f32 = 16.0;
const WALL_HEIGHT: f32 = 18.0;
const PITCH: f32 = 0.95;
const DISTANCE: f32 = 300.0;
/// World units the view spans from the bottom of the window to the top.
const VIEW: f32 = 190.0;
const SPEED: f32 = 52.0;
const RADIUS: f32 = 3.5;
/// Seconds a full lantern burns.
const BURN: f32 = 50.0;
/// Flagstones along a side of the floor: the largest maze (41 x 25 cells) fits on it.
const FLOOR: f32 = 41.0;
/// The HUD camera's height in its own units.
const HUD: f32 = 540.0;
/// What a frame did: native hosts wait a moment when the device had no drawable to give.
pub enum Frame {
Drawn,
Skipped,
Quit,
}
/// A maze of `columns` x `rows` grid cells, walls and floor, with corridors on the odd cells.
struct Maze {
columns: usize,
rows: usize,
wall: Vec<bool>,
}
impl Maze {
/// A perfect maze over `width` x `height` rooms, carved by a depth-first walk from the first room.
fn carve(width: usize, height: usize, seed: u64) -> Self {
let (columns, rows) = (width * 2 + 1, height * 2 + 1);
let mut wall = vec![true; columns * rows];
let mut random = seed | 1;
let mut next = move || {
random ^= random << 13;
random ^= random >> 7;
random ^= random << 17;
random
};
let mut stack = vec![(0usize, 0usize)];
wall[columns + 1] = false;
while let Some(&(x, y)) = stack.last() {
let mut ways: Vec<(usize, usize)> = [(0, -1), (1, 0), (0, 1), (-1, 0)]
.iter()
.filter_map(|&(dx, dy): &(i32, i32)| {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
let inside = nx >= 0 && ny >= 0 && (nx as usize) < width && (ny as usize) < height;
(inside && wall[(ny as usize * 2 + 1) * columns + nx as usize * 2 + 1]).then_some((nx as usize, ny as usize))
})
.collect();
if ways.is_empty() {
stack.pop();
continue;
}
let (nx, ny) = ways.swap_remove(next() as usize % ways.len());
wall[(y + ny + 1) * columns + x + nx + 1] = false;
wall[(ny * 2 + 1) * columns + nx * 2 + 1] = false;
stack.push((nx, ny));
}
Maze { columns, rows, wall }
}
fn is_wall(&self, column: i32, row: i32) -> bool {
column < 0 || row < 0 || column as usize >= self.columns || row as usize >= self.rows || self.wall[row as usize * self.columns + column as usize]
}
/// Steps from `from` to every open cell, by breadth-first search.
fn distances(&self, from: (usize, usize)) -> Vec<Option<u32>> {
let mut distance = vec![None; self.wall.len()];
let mut queue = std::collections::VecDeque::from([from]);
distance[from.1 * self.columns + from.0] = Some(0);
while let Some((x, y)) = queue.pop_front() {
let here = distance[y * self.columns + x].unwrap();
for (dx, dy) in [(0, -1), (1, 0), (0, 1), (-1, 0)] {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
if !self.is_wall(nx, ny) && distance[ny as usize * self.columns + nx as usize].is_none() {
distance[ny as usize * self.columns + nx as usize] = Some(here + 1);
queue.push_back((nx as usize, ny as usize));
}
}
}
distance
}
fn centre(column: usize, row: usize) -> Vec3 {
Vec3::new(column as f32 * CELL, 0.0, row as f32 * CELL)
}
}
/// The textures and meshes every level is built from.
struct Assets {
floor: TextureId,
brick: TextureId,
person: TextureId,
person_normals: TextureId,
flask: TextureId,
door: TextureId,
white: TextureId,
wall: MeshId,
}
/// One maze's nodes, under a root the next level destroys.
struct Level {
root: NodeId,
maze: Maze,
door: NodeId,
door_at: Vec3,
flasks: Vec<(NodeId, Vec3)>,
}
pub struct Game {
stage: Stage,
// The stage renderer drops before the platform, whose device it draws with.
renderer: StageRenderer,
platform: Platform,
assets: Assets,
camera_node: NodeId,
world: CameraId,
hud: NodeId,
walker: NodeId,
lantern: NodeId,
gauge: (NodeId, NodeId),
pips: Vec<NodeId>,
level: Level,
cleared: u32,
oil: f32,
position: Vec3,
focus: Vec3,
keys: [bool; 4],
pointer: Vec2,
dragging: bool,
start: std::time::Instant,
last: std::time::Instant,
}
fn pixels(width: u32, height: u32, paint: impl Fn(u32, u32) -> [u8; 4]) -> Vec<u8> {
(0..width * height).flat_map(|i| paint(i % width, i / width)).collect()
}
impl Game {
pub fn new() -> Self {
let mut platform = Platform::new(false, [960, 540], Some("Lantern"));
let mut stage = Stage::new();
let mut renderer = StageRenderer::new(platform.renderer.device());
// Pixel art: flagstones, bricks, a cloaked walker with a cylinder's normals, a flask and a door.
let floor = pixels(16, 16, |x, y| {
let joint = x == 0 || y == 0 || (y == 8 && x != 0);
let shade = ((x * 7 + y * 13) % 5) as u8 * 4;
if joint { [52, 50, 58, 255] } else { [96 + shade, 92 + shade, 100 + shade, 255] }
});
let brick = pixels(16, 16, |x, y| {
let offset = if (y / 4) % 2 == 0 { 0 } else { 4 };
let joint = y % 4 == 0 || (x + offset) % 8 == 0;
if joint { [70, 62, 60, 255] } else { [150 - (y % 4) as u8 * 6, 112, 92, 255] }
});
let person = pixels(8, 16, |x, y| {
if (2..6).contains(&x) && (1..5).contains(&y) {
[236, 204, 168, 255]
} else if (1..7).contains(&x) && (5..15).contains(&y) {
[120, 140, 205, 255]
} else {
[0, 0, 0, 0]
}
});
let person_normals = pixels(8, 16, |x, _| {
let lean = ((x as f32 + 0.5) / 8.0 * 2.0 - 1.0) * 0.9;
let z = (1.0 - lean * lean).max(0.0).sqrt();
[((lean * 0.5 + 0.5) * 255.0) as u8, 128, ((z * 0.5 + 0.5) * 255.0) as u8, 255]
});
let flask = pixels(6, 8, |x, y| match (x, y) {
(2..=3, 0..=1) => [120, 90, 60, 255],
(1..=4, 2..=7) => [255, 190, 70, 255],
_ => [0, 0, 0, 0],
});
let door = pixels(10, 16, |x, y| {
let frame = x == 0 || x == 9 || y == 0;
if frame { [60, 160, 110, 255] } else if (x + y) % 3 == 0 { [140, 255, 190, 255] } else { [90, 230, 150, 255] }
});
let assets = Assets {
floor: renderer.create_texture(&mut stage, 16, 16, floor, Filter::Nearest),
brick: renderer.create_texture(&mut stage, 16, 16, brick, Filter::Nearest),
person: renderer.create_texture(&mut stage, 8, 16, person, Filter::Nearest),
person_normals: renderer.create_texture(&mut stage, 8, 16, person_normals, Filter::Linear),
flask: renderer.create_texture(&mut stage, 6, 8, flask, Filter::Nearest),
door: renderer.create_texture(&mut stage, 10, 16, door, Filter::Nearest),
white: renderer.create_texture(&mut stage, 1, 1, vec![255; 4], Filter::Nearest),
wall: renderer.create_mesh(&mut stage, &MeshData::cuboid(Vec3::new(CELL, WALL_HEIGHT, CELL))).unwrap(),
};
// The floor: one plane of flagstones, a cell each, under the largest maze; its joints fall between cells.
let floor_mesh = renderer.create_mesh(&mut stage, &MeshData::plane(FLOOR * CELL, FLOOR * CELL, FLOOR)).unwrap();
let floor = stage.create_node(None);
stage.set_translation(floor, Vec3::new(20.0 * CELL, 0.0, 12.0 * CELL));
let mut material = MeshMaterial::lit([1.0; 4]);
material.texture = Some(assets.floor);
let mut drawable = MeshDrawable::new(floor_mesh, material);
drawable.cast_shadow = false;
stage.set_mesh(floor, drawable);
// The night: a dim blue ambient that leaves the lantern to show the way.
let night = stage.create_node(None);
stage.set_light(night, Light::ambient([0.13, 0.14, 0.24], 1.0));
// The walker, and the lantern held high over the walls, so its light spills into the next corridors.
let walker = stage.create_node(None);
let mut sprite = Sprite::new(assets.person, Vec2::new(8.0, 16.0));
sprite.anchor = Vec2::new(0.5, 0.0);
sprite.material = Material::Lit;
sprite.normal_texture = Some(assets.person_normals);
sprite.alpha = AlphaMode::Cutout(0.5);
sprite.emissive = [0.08, 0.07, 0.05];
stage.set_sprite(walker, sprite);
let lantern = stage.create_node(Some(walker));
stage.set_translation(lantern, Vec3::new(3.0, 34.0, 4.0));
stage.set_light(lantern, Light::point([1.0, 0.72, 0.42], 1.7, 140.0).with_shadows());
let camera_node = stage.create_node(None);
let world = stage
.create_camera(Camera {
clear: Some([0.02, 0.02, 0.04, 1.0]),
layers: LayerMask::layer(0),
..Camera::new(camera_node, Projection::tilted_orthographic(VIEW, PITCH, DISTANCE, 400.0))
})
.unwrap();
// The HUD: an orthographic camera far from the maze, drawing its own layer over the world's picture.
let hud_node = stage.create_node(None);
stage.set_translation(hud_node, Vec3::new(0.0, -10_000.0, 0.0));
stage
.create_camera(Camera { clear: None, order: 1, layers: LayerMask::layer(1), ..Camera::new(hud_node, Projection::orthographic(HUD)) })
.unwrap();
let bar = |stage: &mut Stage, colour: [f32; 4], z: f32| {
let node = stage.create_node(Some(hud_node));
let mut sprite = Sprite::new(assets.white, Vec2::new(1.0, 1.0));
sprite.anchor = Vec2::new(0.0, 0.5);
sprite.tint = colour;
stage.set_sprite(node, sprite);
stage.set_layers(node, LayerMask::layer(1));
stage.set_translation(node, Vec3::new(0.0, 0.0, z));
node
};
let gauge = (bar(&mut stage, [0.0, 0.0, 0.0, 0.55], 0.0), bar(&mut stage, [1.0, 0.72, 0.3, 1.0], 1.0));
let level = Self::build(&mut stage, &assets, 0);
let position = Maze::centre(1, 1);
let now = std::time::Instant::now();
Game {
stage,
renderer,
platform,
assets,
camera_node,
world,
hud: hud_node,
walker,
lantern,
gauge,
pips: Vec::new(),
level,
cleared: 0,
oil: 1.0,
position,
focus: position,
keys: [false; 4],
pointer: Vec2::new(-1.0, -1.0),
dragging: false,
start: now,
last: now,
}
}
/// The maze for the level after `cleared` doors: a size that grows with each, its door at the farthest room
/// from the start, and flasks in the dead ends farthest from both.
fn build(stage: &mut Stage, assets: &Assets, cleared: u32) -> Level {
let (width, height) = (8 + cleared as usize * 2, 5 + cleared as usize);
let maze = Maze::carve(width.min(20), height.min(12), 0x9E37_79B9_7F4A_7C15 ^ (cleared as u64 + 1).wrapping_mul(0x2545_F491_4F6C_DD1D));
let root = stage.create_node(None);
// The walls: a brick block on every wall cell, each casting the lantern's shadows.
let mut material = MeshMaterial::lit([1.0; 4]);
material.texture = Some(assets.brick);
for row in 0..maze.rows {
for column in 0..maze.columns {
if maze.wall[row * maze.columns + column] {
let node = stage.create_node(Some(root));
stage.set_translation(node, Maze::centre(column, row) + Vec3::new(0.0, WALL_HEIGHT * 0.5, 0.0));
stage.set_mesh(node, MeshDrawable::new(assets.wall, material));
}
}
}
let from_start = maze.distances((1, 1));
let rooms: Vec<(usize, usize)> = (0..maze.rows).flat_map(|r| (0..maze.columns).map(move |c| (c, r))).filter(|&(c, r)| c % 2 == 1 && r % 2 == 1).collect();
let far = *rooms.iter().max_by_key(|&&(c, r)| from_start[r * maze.columns + c]).unwrap();
let from_door = maze.distances(far);
// The door glows and lights its room.
let door_at = Maze::centre(far.0, far.1);
let door = upright(stage, root, assets.door, Vec2::new(10.0, 16.0), door_at, [0.3, 0.9, 0.55]);
let glow = stage.create_node(Some(door));
stage.set_translation(glow, Vec3::new(0.0, 10.0, 0.0));
stage.set_light(glow, Light::point([0.4, 1.0, 0.6], 1.2, 46.0));
// Flasks in the dead ends, the ones farthest from both the start and the door first.
let mut dead_ends: Vec<(usize, usize)> = rooms
.iter()
.copied()
.filter(|&room| room != (1, 1) && room != far)
.filter(|&(c, r)| [(0, -1), (1, 0), (0, 1), (-1, 0)].iter().filter(|(dx, dy)| !maze.is_wall(c as i32 + dx, r as i32 + dy)).count() == 1)
.collect();
dead_ends.sort_by_key(|&(c, r)| std::cmp::Reverse(from_start[r * maze.columns + c].unwrap_or(0).min(from_door[r * maze.columns + c].unwrap_or(0))));
let flasks = dead_ends
.into_iter()
.take(2 + cleared as usize)
.map(|(c, r)| {
let at = Maze::centre(c, r);
let node = upright(stage, root, assets.flask, Vec2::new(6.0, 8.0), at, [0.6, 0.4, 0.1]);
let light = stage.create_node(Some(node));
stage.set_translation(light, Vec3::new(0.0, 5.0, 0.0));
stage.set_light(light, Light::point([1.0, 0.7, 0.3], 0.8, 22.0));
(node, at)
})
.collect();
Level { root, maze, door, door_at, flasks }
}
/// Walks `by` world units, one axis at a time, stopping at walls.
fn walk(&mut self, by: Vec3) {
let maze = &self.level.maze;
let blocked = |p: Vec3| {
[(-RADIUS, -RADIUS), (RADIUS, -RADIUS), (-RADIUS, RADIUS), (RADIUS, RADIUS)]
.iter()
.any(|(dx, dz)| maze.is_wall(((p.x + dx) / CELL + 0.5).floor() as i32, ((p.z + dz) / CELL + 0.5).floor() as i32))
};
let x = self.position + Vec3::new(by.x, 0.0, 0.0);
if !blocked(x) {
self.position = x;
}
let z = self.position + Vec3::new(0.0, 0.0, by.z);
if !blocked(z) {
self.position = z;
}
}
/// Reads the window's events, plays a step and draws it.
pub fn frame(&mut self) -> Frame {
let mut event = sdl::SDL_Event::default();
// SAFETY: the event is ours and the SDL video subsystem is up while the platform lives.
while unsafe { sdl::SDL_PollEvent(&mut event) } {
// SAFETY: only the member for the event's type is read.
unsafe {
match sdl::SDL_EventType(event.r#type) {
sdl::SDL_EVENT_QUIT | sdl::SDL_EVENT_WINDOW_CLOSE_REQUESTED => return Frame::Quit,
sdl::SDL_EVENT_KEY_DOWN | sdl::SDL_EVENT_KEY_UP => {
let down = sdl::SDL_EventType(event.r#type) == sdl::SDL_EVENT_KEY_DOWN;
let key = match event.key.key {
sdl::SDLK_UP | sdl::SDLK_W => Some(0),
sdl::SDLK_RIGHT | sdl::SDLK_D => Some(1),
sdl::SDLK_DOWN | sdl::SDLK_S => Some(2),
sdl::SDLK_LEFT | sdl::SDLK_A => Some(3),
_ => None,
};
if let Some(key) = key {
self.keys[key] = down;
}
}
sdl::SDL_EVENT_MOUSE_MOTION => self.pointer = self.window_pixels(event.motion.x, event.motion.y),
sdl::SDL_EVENT_MOUSE_BUTTON_DOWN if event.button.button == 1 => {
self.pointer = self.window_pixels(event.button.x, event.button.y);
self.dragging = true;
}
sdl::SDL_EVENT_MOUSE_BUTTON_UP if event.button.button == 1 => self.dragging = false,
_ => {}
}
}
}
let now = std::time::Instant::now();
let step = (now - self.last).as_secs_f32().min(0.05);
self.last = now;
let t = (now - self.start).as_secs_f32();
let [width, height] = self.platform.renderer.output_size();
if width <= 0 || height <= 0 {
return Frame::Skipped;
}
let window = [width as u32, height as u32];
// Walk: the keys, or toward the ground under a held pointer. -Z is up the screen.
let mut heading = Vec3::new(
(self.keys[1] as i32 - self.keys[3] as i32) as f32,
0.0,
(self.keys[2] as i32 - self.keys[0] as i32) as f32,
);
let held = self.dragging.then(|| self.stage.camera_view(self.world, window)).flatten();
if let Some(ground) = held.and_then(|view| view.screen_to_plane(self.pointer, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0))) {
let toward = Vec3::new(ground.x - self.position.x, 0.0, ground.z - self.position.z);
if toward.length() > 3.0 {
heading = toward;
}
}
if heading.length() > 0.0 {
self.walk(heading * (SPEED * step / heading.length()));
}
// The lantern burns; a flask in reach refills it, and the door opens the next maze.
self.oil = (self.oil - step / BURN).max(0.0);
let position = self.position;
let stage = &mut self.stage;
let before = self.level.flasks.len();
self.level.flasks.retain(|&(node, at)| {
let reached = (at - position).length() < 8.0;
if reached {
stage.destroy_node(node);
}
!reached
});
self.oil = (self.oil + 0.45 * (before - self.level.flasks.len()) as f32).min(1.0);
if (self.level.door_at - self.position).length() < 7.0 {
self.cleared += 1;
self.stage.destroy_node(self.level.root);
self.level = Self::build(&mut self.stage, &self.assets, self.cleared);
self.position = Maze::centre(1, 1);
self.oil = (self.oil + 0.3).min(1.0);
let pip = self.stage.create_node(Some(self.hud));
let mut sprite = Sprite::new(self.assets.door, Vec2::new(10.0, 16.0));
sprite.anchor = Vec2::new(0.0, 0.5);
self.stage.set_sprite(pip, sprite);
self.stage.set_layers(pip, LayerMask::layer(1));
self.pips.push(pip);
}
// The light follows the oil, with a flicker.
let flicker = 1.0 + 0.06 * (t * 13.0).sin() * (t * 7.3).cos();
if let Some(light) = self.stage.light_mut(self.lantern) {
light.range = (48.0 + 132.0 * self.oil) * flicker;
light.intensity = 1.5 + 0.9 * self.oil;
}
// The camera eases after the walker and stops at the maze's edges, centring a maze narrower than the view.
let span = Vec2::new(VIEW * PITCH.sin() * width as f32 / height as f32, VIEW) * 0.5;
let maze = &self.level.maze;
let clamp = |value: f32, cells: usize, half: f32| {
let (low, high) = (half - CELL * 0.5, (cells as f32 - 0.5) * CELL - half);
if low > high { (cells as f32 - 1.0) * CELL * 0.5 } else { value.clamp(low, high) }
};
let wanted = Vec3::new(clamp(self.position.x, maze.columns, span.x), 0.0, clamp(self.position.z, maze.rows, span.y));
self.focus = self.focus + (wanted - self.focus) * (1.0 - (-step * 6.0).exp());
let orbit = Transform::orbit(self.focus, 0.0, PITCH, DISTANCE);
self.stage.set_transform(self.camera_node, orbit);
self.stage.set_transform(self.walker, Transform { translation: self.position, rotation: orbit.rotation, scale: Vec3::ONE });
let pulse = 0.25 + 0.2 * (t * 3.0).sin();
for (node, at) in self.level.flasks.iter().copied().chain(std::iter::once((self.level.door, self.level.door_at))) {
self.stage.set_transform(node, Transform { translation: at, rotation: orbit.rotation, scale: Vec3::ONE });
if node == self.level.door
&& let Some(sprite) = self.stage.sprite_mut(node)
{
sprite.emissive = [0.6 * pulse, 1.8 * pulse, 1.1 * pulse];
}
}
// The HUD, laid out from the window's left edge in the HUD camera's units.
let left = -HUD * 0.5 * width as f32 / height as f32 + 24.0;
let top = HUD * 0.5 - 28.0;
let (back, fill) = self.gauge;
self.stage.set_transform(back, Transform { translation: Vec3::new(left - 3.0, top, 0.0), rotation: Quat::IDENTITY, scale: Vec3::new(166.0, 14.0, 1.0) });
self.stage.set_transform(fill, Transform { translation: Vec3::new(left, top, 1.0), rotation: Quat::IDENTITY, scale: Vec3::new(160.0 * self.oil.max(0.001), 8.0, 1.0) });
for (i, &pip) in self.pips.iter().enumerate() {
self.stage.set_translation(pip, Vec3::new(left + i as f32 * 14.0, top - 26.0, 1.0));
}
let device = self.platform.renderer.device();
device.poll();
if !device.begin_frame() {
return Frame::Skipped;
}
let mut graph = Graph::new();
if let Some(surface) = device.acquire(window[0], window[1]) {
let target = graph.import_texture(&surface, false);
self.renderer.record(device, &mut self.stage, &mut graph, Some(target));
if graph.check().is_none() {
graph.execute(device);
}
}
device.submit();
Frame::Drawn
}
/// A point in window points as the drawable's pixels, which the cameras work in.
fn window_pixels(&self, x: f32, y: f32) -> Vec2 {
let (mut width, mut height) = (0, 0);
// SAFETY: the window is live while the platform is.
unsafe { sdl::SDL_GetWindowSize(self.platform.window(), &mut width, &mut height) };
let [pixels_wide, pixels_high] = self.platform.renderer.output_size();
Vec2::new(x * pixels_wide as f32 / width.max(1) as f32, y * pixels_high as f32 / height.max(1) as f32)
}
}
/// A lit sprite standing on the ground at `at`, glowing with `emissive`.
fn upright(stage: &mut Stage, parent: NodeId, texture: TextureId, size: Vec2, at: Vec3, emissive: [f32; 3]) -> NodeId {
let node = stage.create_node(Some(parent));
let mut sprite = Sprite::new(texture, size);
sprite.anchor = Vec2::new(0.5, 0.0);
sprite.material = Material::Lit;
sprite.alpha = AlphaMode::Cutout(0.5);
sprite.emissive = emissive;
stage.set_sprite(node, sprite);
stage.set_translation(node, at);
node
}
}
#[cfg(target_os = "macos")]
fn main() {
use game::{Frame, Game};
let mut game = Game::new();
loop {
match game.frame() {
Frame::Drawn => {}
Frame::Skipped => std::thread::sleep(std::time::Duration::from_millis(1)),
Frame::Quit => break,
}
}
}
/// The browser calls a frame per animation frame once the WebGPU device has arrived.
#[cfg(target_os = "emscripten")]
fn main() {
use game::{Frame, Game};
engine_platform::web::frames::run(Game::new, |game| !matches!(game.frame(), Frame::Quit));
}
#[cfg(not(any(target_os = "macos", target_os = "emscripten")))]
fn main() {}
Sorted, blended sprites
An orthographic stage camera over a tiled floor: alpha, additive and multiply discs sorted by depth, walkers on a y-sorted layer, a nine-slice panel and a spinning sprite.
Move the pointer over a sprite: picking finds the node under it, and it grows.
//! Sorted, blended sprites under an orthographic camera in a window: depth-sorted discs with alpha, additive and multiply
//! blending, y-sorted walkers, a nine-slice panel and a spinning sprite; the sprite under the pointer grows.
//! `cargo run -p engine-stage-render --example sprites` (ENGINE_SHADER_DIR as for the crate); close the window to quit.
//! With STAGE_FRAMES=N it quits after N frames and prints their mean time (the budget check, `build/budget.ts`).
//! `bun build/build.ts web-example engine-stage-render sprites` builds it for the browser, where the page drives the frames.
#[cfg(any(target_os = "macos", target_os = "emscripten"))]
mod demo {
use engine_platform::{Platform, sdl};
use engine_render_device::Graph;
use engine_stage::*;
use engine_stage_render::StageRenderer;
/// What a frame did: native hosts wait a moment when the device had no drawable to give.
pub enum Frame {
Drawn,
Skipped,
Quit,
}
pub struct Demo {
stage: Stage,
// The stage renderer drops before the platform, whose device it draws with.
renderer: StageRenderer,
platform: Platform,
camera: CameraId,
walkers: Vec<NodeId>,
panel: NodeId,
spinner: NodeId,
pointer: Vec2,
hovered: Option<NodeId>,
start: std::time::Instant,
}
impl Demo {
pub fn new() -> Self {
// A soft disc, a pixel-art tile and a bordered panel, as RGBA8.
let disc: Vec<u8> = (0..64 * 64)
.flat_map(|i| {
let (x, y) = ((i % 64) as f32 - 31.5, (i / 64) as f32 - 31.5);
let alpha = (1.0 - (x.hypot(y) - 24.0) / 8.0).clamp(0.0, 1.0);
[255, 255, 255, (alpha * 255.0) as u8]
})
.collect();
let tile: Vec<u8> = (0..16 * 16)
.flat_map(|i| {
let (x, y) = (i % 16, i / 16);
let edge = x == 0 || y == 0 || x == 15 || y == 15;
if edge { [30, 30, 40, 255] } else if (x / 4 + y / 4) % 2 == 0 { [90, 140, 200, 255] } else { [70, 110, 170, 255] }
})
.collect();
let panel: Vec<u8> = (0..32 * 32)
.flat_map(|i| {
let (x, y) = (i % 32, i / 32);
if x < 4 || y < 4 || x >= 28 || y >= 28 { [240, 220, 140, 255] } else { [40, 50, 70, 230] }
})
.collect();
let mut platform = Platform::new(false, [960, 540], Some("Stage sprites"));
let mut stage = Stage::new();
let mut renderer = StageRenderer::new(platform.renderer.device());
let disc = renderer.create_texture(&mut stage, 64, 64, disc, Filter::Linear);
let tile = renderer.create_texture(&mut stage, 16, 16, tile, Filter::Nearest);
let panel = renderer.create_texture(&mut stage, 32, 32, panel, Filter::Nearest);
let camera_node = stage.create_node(None);
let camera = stage.create_camera(Camera { clear: Some([0.08, 0.09, 0.12, 1.0]), y_sort: YSort::Layers { first: 1, last: 1 }, ..Camera::new(camera_node, Projection::orthographic(540.0)) }).unwrap();
let place = |stage: &mut Stage, texture: TextureId, x: f32, y: f32, z: f32, size: f32, edit: &dyn Fn(&mut Sprite)| {
let node = stage.create_node(None);
stage.set_transform(node, Transform::at(x, y, z));
let mut sprite = Sprite::new(texture, Vec2::new(size, size));
edit(&mut sprite);
stage.set_sprite(node, sprite);
node
};
// A floor of pixel-art tiles, behind everything (layer -1).
for row in -4..4 {
for column in -7..7 {
place(&mut stage, tile, column as f32 * 64.0 + 32.0, row as f32 * 64.0 + 32.0, 0.0, 64.0, &|s| s.layer = -1);
}
}
// Overlapping discs: creation order is the reverse of depth order, and each has its own blending.
let colours = [[1.0, 0.3, 0.3, 0.8], [0.3, 1.0, 0.4, 0.8], [0.4, 0.5, 1.0, 0.8]];
let blends = [BlendMode::Alpha, BlendMode::Additive, BlendMode::Multiply];
for i in (0..3).rev() {
place(&mut stage, disc, -300.0 + i as f32 * 60.0, 120.0 - i as f32 * 20.0, i as f32, 160.0, &|s| {
s.tint = colours[i];
s.blend = blends[i];
});
}
// Walkers on a y-sorted layer: the lower one draws in front.
let walkers: Vec<NodeId> = (0..2)
.map(|i| place(&mut stage, tile, 120.0 + i as f32 * 40.0, -60.0, 0.0, 56.0, &|s| {
s.layer = 1;
s.anchor = Vec2::new(0.5, 0.0);
s.tint = if i == 0 { [1.0, 0.7, 0.7, 1.0] } else { [0.7, 1.0, 0.7, 1.0] };
}))
.collect();
let panel = place(&mut stage, panel, 250.0, 130.0, 2.0, 200.0, &|s| {
s.size = Vec2::new(220.0, 110.0);
s.nine_slice = Some(NineSlice { left: 4.0, right: 4.0, top: 4.0, bottom: 4.0, scale: 3.0 });
});
let spinner = place(&mut stage, disc, -200.0, -150.0, 3.0, 90.0, &|s| s.tint = [1.0, 1.0, 0.4, 1.0]);
Demo {
stage,
renderer,
platform,
camera,
walkers,
panel,
spinner,
pointer: Vec2::new(-1.0, -1.0),
hovered: None,
start: std::time::Instant::now(),
}
}
/// Reads the window's events, moves the scene and draws it.
pub fn frame(&mut self) -> Frame {
let mut event = sdl::SDL_Event::default();
// SAFETY: the event is ours and the SDL video subsystem is up while the platform lives.
while unsafe { sdl::SDL_PollEvent(&mut event) } {
// SAFETY: only the member for the event's type is read.
unsafe {
match sdl::SDL_EventType(event.r#type) {
sdl::SDL_EVENT_QUIT | sdl::SDL_EVENT_WINDOW_CLOSE_REQUESTED => return Frame::Quit,
sdl::SDL_EVENT_MOUSE_MOTION => {
let (mut width, mut height) = (0, 0);
sdl::SDL_GetWindowSize(self.platform.window(), &mut width, &mut height);
let [pixels_wide, pixels_high] = self.platform.renderer.output_size();
self.pointer = Vec2::new(event.motion.x * pixels_wide as f32 / width as f32, event.motion.y * pixels_high as f32 / height as f32);
}
_ => {}
}
}
}
let stage = &mut self.stage;
let t = self.start.elapsed().as_secs_f32();
for (i, &walker) in self.walkers.iter().enumerate() {
stage.set_translation(walker, Vec3::new(120.0 + i as f32 * 40.0, -60.0 + 50.0 * (t * (1.0 + i as f32 * 0.5)).sin(), 0.0));
}
stage.set_transform(self.spinner, Transform { translation: Vec3::new(-200.0, -150.0, 3.0), rotation: Quat::from_z(t), scale: Vec3::ONE });
stage.set_transform(self.panel, Transform { translation: Vec3::new(250.0 + 20.0 * t.cos(), 130.0, 2.0), ..Transform::IDENTITY });
let [width, height] = self.platform.renderer.output_size();
if width <= 0 || height <= 0 {
return Frame::Skipped;
}
// The sprite under the pointer grows.
let under = stage.pick(self.camera, [width as u32, height as u32], self.pointer);
if under != self.hovered {
if let Some(sprite) = self.hovered.and_then(|node| stage.sprite_mut(node)) {
sprite.size = sprite.size * (1.0 / 1.15);
}
if let Some(sprite) = under.and_then(|node| stage.sprite_mut(node)) {
sprite.size = sprite.size * 1.15;
}
self.hovered = under;
}
let device = self.platform.renderer.device();
device.poll();
if !device.begin_frame() {
return Frame::Skipped;
}
let mut graph = Graph::new();
if let Some(surface) = device.acquire(width as u32, height as u32) {
let target = graph.import_texture(&surface, false);
self.renderer.record(device, stage, &mut graph, Some(target));
if graph.check().is_none() {
graph.execute(device);
}
}
device.submit();
Frame::Drawn
}
}
}
#[cfg(target_os = "macos")]
fn main() {
use demo::{Demo, Frame};
let mut demo = Demo::new();
let frames: Option<u32> = std::env::var("STAGE_FRAMES").ok().and_then(|value| value.parse().ok());
let (mut drawn, mut timed, mut last) = (0u32, std::time::Duration::ZERO, std::time::Instant::now());
loop {
if let Some(limit) = frames {
// The first frames compile pipelines: the mean is over the rest.
let now = std::time::Instant::now();
if drawn > limit / 4 {
timed += now - last;
}
last = now;
if drawn == limit {
let counted = limit - limit / 4 - 1;
println!("stage frames: {counted}, mean {:.3} ms", timed.as_secs_f64() * 1000.0 / f64::from(counted.max(1)));
break;
}
}
match demo.frame() {
Frame::Drawn => drawn += 1,
Frame::Skipped => std::thread::sleep(std::time::Duration::from_millis(1)),
Frame::Quit => break,
}
}
}
/// The browser calls a frame per animation frame once the WebGPU device has arrived.
#[cfg(target_os = "emscripten")]
fn main() {
use demo::{Demo, Frame};
engine_platform::web::frames::run(Demo::new, |demo| !matches!(demo.frame(), Frame::Quit));
}
#[cfg(not(any(target_os = "macos", target_os = "emscripten")))]
fn main() {}
A counter component
An Elm-style component on the retained UI tree: a model, its messages, an update and a view. Each press renders the view again, and only the count's text node changes.
Press − and +: hover and press fills are the tree's own, and the count re-renders on each message.
//! A counter as a component: a model, its messages, an update and a view, mounted on the host's tree.
//! `cargo run -p engine-ui-view --example counter` opens a window (close it to quit); `-- --capture out.png` presses +
//! three times in a hidden window and saves the frame. ENGINE_SHADER_DIR as for the crates.
//! `bun build/build.ts web-example engine-ui-view counter --embed …` builds it for the browser (website/scripts/demos.ts).
#[cfg(any(target_os = "macos", target_os = "emscripten"))]
mod app {
use engine_ui::{Event, Host, Layout, NodeKind, Size};
use engine_ui_view::{Component, Element, Mount, column, row, text};
pub struct Counter;
#[derive(Clone)]
pub enum Message {
Add(i64),
}
/// What the view is given: its fonts.
#[derive(PartialEq)]
pub struct Fonts {
pub big: u32,
pub label: u32,
}
impl Component for Counter {
type Props = Fonts;
type Model = i64;
type Message = Message;
type Output = ();
fn update(count: &mut i64, message: Message) -> Option<()> {
match message {
Message::Add(by) => *count += by,
}
None
}
fn view(fonts: &Fonts, count: &i64) -> Element<Message> {
let button = |caption: &str, by: i64| {
row().key(caption).size(56.0, 36.0).justify_center().items_center()
.bg(0x2d333bff).hover_bg(0x39414bff).press_bg(0x4e5967ff).radius(8.0)
.focusable().role(1, caption).on_press(Message::Add(by))
.child(text(fonts.label, caption, 0xe2e6ecff))
};
column().grow().grow_y().justify_center().items_center().gap(16.0)
.child(text(fonts.big, &count.to_string(), 0xf2ece0ff))
.child(row().gap(12.0).child(button("−", -1)).child(button("+", 1)))
}
}
pub const BACKGROUND: u32 = 0x14181fff;
/// The host's window and the counter mounted on its tree.
pub struct App {
pub host: Host,
pub counter: Mount<Counter>,
}
impl App {
/// Loads `face` at the two sizes the view uses and mounts the counter, at 0, on the host's tree.
pub fn new(mut host: Host, face: &std::path::Path) -> Self {
let (big, label) = (host.font_file(face, 48).expect("the font"), host.font_file(face, 16).expect("the font"));
let tree = host.tree();
let root = tree.create(NodeKind::Box);
tree.set_layout(root, &Layout { width: Size::Fill(1.0), height: Size::Fill(1.0), ..Default::default() });
tree.set_root(root);
let mut counter: Mount<Counter> = Mount::new(root, 0, 0);
counter.render(host.tree(), Fonts { big, label });
App { host, counter }
}
/// Hands one event to the tree and the counter; false once the window should close.
pub fn event(&mut self, event: Event) -> bool {
match event {
Event::Quit => return false,
Event::PointerMove { x, y } => {
self.host.tree().pointer(x, y);
}
Event::PointerDown { x, y, button: 1, .. } => {
self.host.tree().pointer(x, y);
self.host.tree().press(true);
}
Event::PointerUp { x, y, button: 1 } => {
let tree = self.host.tree();
tree.press(false);
// The message of the element under the pointer goes to the update; the view renders again and
// only the count's text node changes.
let hit = tree.hit(x, y);
self.counter.press(&mut *tree, hit);
self.counter.render_again(tree);
}
_ => {}
}
true
}
}
}
#[cfg(target_os = "macos")]
fn main() {
use app::{App, BACKGROUND};
use engine_ui::{Event, Host, TreeFrame};
let capture = std::env::args().skip_while(|argument| argument != "--capture").nth(1);
let host = if capture.is_some() { Host::open_headless(320, 200) } else { Host::open(320, 200, "Counter", false) }.expect("a window");
// $ENGINE_TEST_FONT, or the system's Geneva (the interface fonts sit beside a packaged host's binary).
let face = [std::env::var_os("ENGINE_TEST_FONT").map(std::path::PathBuf::from), Some("/System/Library/Fonts/Geneva.ttf".into())]
.into_iter()
.flatten()
.find(|path| std::fs::read(path).is_ok_and(|bytes| bytes.starts_with(&[0, 1, 0, 0])))
.expect("a font");
let mut app = App::new(host, &face);
if let Some(path) = capture {
// Three presses of +, as the pointer's would send them, then the frame they leave.
for _ in 0..3 {
let plus = app.counter.node_of("+").expect("the + button");
app.counter.press(app.host.tree(), plus);
app.counter.render_again(app.host.tree());
}
while app.host.tree_frame(BACKGROUND) != TreeFrame::Presented {
std::thread::sleep(std::time::Duration::from_millis(2));
}
assert!(app.host.capture(std::path::Path::new(&path)), "the frame is saved");
println!("saved {path}");
return;
}
loop {
while let Some(event) = app.host.poll(app.host.tree_wait().or(Some(1000))) {
if event == Event::Other {
break;
}
if !app.event(event) {
return;
}
}
if let TreeFrame::Again = app.host.tree_frame(BACKGROUND) {
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
}
/// The browser calls a frame per animation frame: it takes the events that arrived, without waiting, and draws. The window
/// fills the page's canvas, and the build embeds the interface font.
#[cfg(target_os = "emscripten")]
fn main() {
use app::{App, BACKGROUND};
use engine_ui::Host;
engine_platform::web::frames::run(
|| {
let [width, height] = engine_platform::web::frames::canvas_size().unwrap_or([640, 360]);
let host = Host::open(width, height, "Counter", false).expect("a window");
App::new(host, std::path::Path::new("/assets/fonts/PTSans-Regular.ttf"))
},
|app| {
while let Some(event) = app.host.poll(Some(0)) {
if !app.event(event) {
return false;
}
}
app.host.tree_frame(BACKGROUND);
true
},
);
}
#[cfg(not(any(target_os = "macos", target_os = "emscripten")))]
fn main() {}