# Space3d **A cross-platform 3D game engine in Rust — one codebase for desktop, the web, Android and iOS, with testing built in from the first line.** Space3d is a small, modular engine built on [wgpu](https://wgpu.rs) and [winit](https://github.com/rust-windowing/winit): an ECS (hecs) with a deterministic fixed tick, a GPU-driven renderer that draws a million instances in a handful of draw calls, async assets/networking/database access that never blocks a frame, and a test harness where input simulation and golden screenshots are ordinary `cargo test`s. The `space3d` CLI scaffolds a game, builds it for every platform, serves the web build, runs the storybook and publishes releases to GitHub. ```rust use space3d::prelude::*; struct Spin; fn build(app: &mut App) { app.add_plugin(DefaultPlugins::new().title("Hello cube")); app.add_system(Stage::Startup, |ctx| { let cube = ctx.resources.expect_mut::().add_mesh(MeshData::cube(1.0)); ctx.world.spawn((Transform::default(), Mesh3d(cube), Material::srgb(0.9, 0.4, 0.2), Spin)); ctx.world.spawn((Transform::default().looking_at(Vec3::new(-0.4, -1.0, -0.3), Vec3::Y), DirectionalLight::default())); ctx.world.spawn((Transform::from_xyz(0.0, 1.5, 4.0).looking_at(Vec3::ZERO, Vec3::Y), Camera3d::default())); }); app.add_system(Stage::FixedUpdate, |ctx| { let dt = ctx.time().fixed_delta.as_secs_f32(); for (t, _) in ctx.world.query_mut::<(&mut Transform, &Spin)>() { t.rotation *= Quat::from_rotation_y(dt); } }); } // `fn main` on desktop, `#[wasm_bindgen(start)]` on the web, // `android_main` on Android, `extern "C" start_app` on iOS. space3d::main!(build); ``` ## Features * **Everything is a plugin.** `DefaultPlugins` / `MinimalPlugins` groups; every engine crate is optional behind a cargo feature of the `space3d` facade. * **Deterministic simulation.** `Stage::FixedUpdate` runs at a fixed `TickRate` (60 Hz by default), decoupled from the frame rate; tests drive time with `App::step_ticks(n)`. * **Renderer (wgpu 30).** Metallic/roughness lighting, directional + point lights, textures, render-to-texture, MSAA; automatic instancing of ECS entities and explicit `InstanceBuffer`s for 1M+ instances; GPU frustum culling + (multi-)indirect draws with a CPU fallback (WebGL2); dirty-range uploads through a staging belt; headless rendering and capture. * **Graphics.** HDR with AgX/ACES/Khronos tonemapping, bloom, auto exposure, color grading and LUTs, FXAA, lens effects, screen-space distortion; normal, ORM and emissive maps lit straight from glTF, every blend mode; cubemap skyboxes with image-based lighting; a shadow-casting sun; 100k GPU particles with ribbons, beams, flipbooks and a built-in effect library; render nodes and HDR overlay stages for custom effects; `GraphicsQuality` presets from WebGL2 to Ultra ([below](#graphics)). * **Never block the frame.** I/O runs on `space3d_tasks` (tokio natively, `wasm-bindgen-futures` on the web); CPU work on a compute pool; systems only poll `Task`s or register `AsyncQueue` callbacks. * **Assets.** Async asset server with typed handles and hot reload; PNG/JPEG/WebP/…, glTF/GLB and OBJ; texture editing (resize, filters, brushes, flood fill, generators, undo/redo) and mesh editing (normals, weld, subdivide, extrude, UV projection, decimation, OBJ/glTF export). * **Networking.** HTTP client and WebSocket client on every platform; HTTP/WebSocket servers (axum) natively; typed channels for replication. * **Persistence.** SQLite on a worker thread (migrations, KV store, save slots with thumbnails, leaderboards) with a `localStorage` fallback on the web. * **Physics, audio, scenes.** rapier rigid bodies/colliders/raycasts on the fixed tick; kira audio with spatial emitters; RON/JSON scenes, prefabs and world snapshots. * **UI and tools.** egui integration with a compact debug overlay (F3), profiler (F4) and console; an opt-in compact density (`app.insert_resource(UiTheme::compact())`); Chinese and Japanese line breaking (kinsoku, plus no break before a no-break space or after an opening bracket) in egui's text layout (both in [docs/ui.md](docs/ui.md)); scene inspector, texture and model editors; a storybook for isolated, parameterized scenes. * **Testing.** Headless `TestApp`, tick-accurate keyboard/mouse/touch/gamepad simulation and recorded input scripts, golden screenshots with diff images and an HTML report, determinism and performance assertions. GPU tests skip when there is no adapter. * **Shipping.** `space3d` CLI for desktop, web (wasm-bindgen), Android (cargo-apk) and iOS (Xcode via XcodeGen) builds, a local web server with cross-origin isolation, GitHub Actions generation and GitHub releases; in-game update checker and opt-in crash reporter. ## Architecture ```text ┌──────────────────────────── your game ─────────────────────────────┐ │ build(app) · GamePlugin · systems · stories · tests │ └───────────────┬──────────────────────────────────────┬─────────────┘ │ space3d::prelude / space3d::main! │ space3d::test ┌─────────────── space3d (facade: features, DefaultPlugins, MinimalPlugins, entry points) ─────┐ │ │ │ platform ── winit runner (desktop · web canvas · Android NativeActivity · iOS UIKit), Input │ │ │ │ │ render ──── wgpu: mesh arena · PBR maps · lights · IBL · shadows · HDR · post · nodes │ │ particles ─ GPU/CPU effects: sprites · ribbons · beams · built-in library │ │ ui ──────── egui overlay · debug overlay · profiler · console editor ── inspectors │ │ assets ──── asset server · loaders · hot reload · texture/mesh editing │ │ physics (rapier) · audio (kira) · scene (RON) · net (HTTP/WS) · db (SQLite/localStorage) │ │ stories ─── storybook, gallery test ── TestApp, input sim, goldens github ── CI │ │ │ │ tasks ───── spawn / spawn_compute / Task::poll / AsyncQueue (tokio · rayon · wasm futures) │ │ core ────── App · Plugin · ECS (hecs) · Resources · Events · Stages · TickRate · Transform │ └───────────────────────────────────────────────────────────────────────────────────────────────┘ Frame: Startup (once) → PreUpdate (task completions, input, network inbox) → FixedUpdate × N (deterministic simulation, physics) → Update → PostUpdate (transforms) → Render → Last (event buffers, cleanup) ``` | crate | role | |---|---| | [`space3d`](crates/space3d) | facade: feature-gated re-exports, plugin groups, prelude, `main!` | | [`space3d-core`](crates/space3d-core) | App, Plugin, ECS, resources, events, stages, fixed tick, Transform | | [`space3d-tasks`](crates/space3d-tasks) | async runtime bridge, `Task`, `AsyncQueue` | | [`space3d-render`](crates/space3d-render) | wgpu renderer ([architecture](crates/space3d-render/ARCHITECTURE.md), [graphics](docs/graphics.md)) | | [`space3d-particles`](crates/space3d-particles) | particle effects drawn as a render node ([docs](docs/graphics/particles.md)) | | [`space3d-platform`](crates/space3d-platform) | winit runner for all platforms, input, action maps | | [`space3d-assets`](crates/space3d-assets) | asset server, loaders, hot reload, editing ops | | [`space3d-net`](crates/space3d-net) | HTTP/WebSocket clients and servers | | [`space3d-db`](crates/space3d-db) | SQLite / localStorage stores | | [`space3d-physics`](crates/space3d-physics) | rapier integration | | [`space3d-audio`](crates/space3d-audio) | kira integration | | [`space3d-scene`](crates/space3d-scene) | scenes, prefabs, snapshots | | [`space3d-ui`](crates/space3d-ui) | egui integration, debug tools | | [`space3d-editor`](crates/space3d-editor) | scene inspector, texture and model editors | | [`space3d-stories`](crates/space3d-stories) | storybook | | [`space3d-test`](crates/space3d-test) | test harness | | [`space3d-github`](crates/space3d-github) | GitHub REST, update checker, crash reporter, CI templates | | [`space3d-cli`](crates/space3d-cli) | the `space3d` command | ## Graphics ![SpaceCorps look](crates/space3d-stories/tests/__screenshots__/Engine/Showcase/SpaceCorps_Look.png) The renderer draws a top-down space battle with every effect a space game needs — and nothing changes until a game asks: a camera without `PostProcess` renders exactly as before. ```rust use space3d::particles::prelude::*; use space3d::prelude::*; ctx.world.spawn(( Transform::from_xyz(0.0, 400.0, 150.0).looking_at(Vec3::ZERO, Vec3::Y), Camera3d::default(), PostProcess::default().with_tonemapper(Tonemapper::AgXPunchy).with_exposure(0.5), // HDR + bloom Skybox::new(nebula), // a cubemap behind everything … EnvironmentLight::new(nebula), // … that also lights the hulls )); ctx.world.spawn((sun_transform, DirectionalLight::default(), DirectionalShadow::default())); let ship = space3d::assets::render::spawn_model(ctx.world, &hull, transform); // glTF maps as authored ctx.spawn_effect(builtin::EXPLOSION, EffectSpawn::at(p)); // one call: fireball, debris, flash, shockwave GraphicsQuality::recommended_for(renderer).apply(ctx.world, ctx.resources); // Low on WebGL2 ``` | feature | what you get | |---|---| | HDR, tonemapping, exposure | `PostProcess` on a camera: linear HDR scene, AgX / AgX punchy / ACES / Khronos PBR Neutral / Reinhard, manual or histogram auto exposure | | bloom | position-stable, energy-proportional, resolution-independent; emissive, particles and HDR skies glow | | post chain | color grading (white balance, lift/gamma/gain, 3D LUTs, WGSL hooks), FXAA, vignette, chromatic aberration, film grain | | distortion | heat haze and shockwaves from particles, `DistortionMaterial` meshes and render nodes | | materials | normal, ORM, metallic-roughness, occlusion and emissive maps; opaque, alpha-mask, alpha, premultiplied and additive blending; GGX shading | | glTF | every material slot straight from the file, sRGB/linear by slot, `texCoord` sets, texture transforms, MikkTSpace tangents | | sky and IBL | cubemaps from faces, three.js faces or panoramas (LDR/HDR); `Skybox`; diffuse + GGX-prefiltered specular baked on the GPU | | shadows | one directional shadow, fitted to a top-down camera, PCF 1–16 taps | | particles | GPU simulation (CPU on WebGL2), 100k+, sprites, ribbons, beams, flipbooks, soft particles, light flashes, sorting, LOD; 14 built-in space effects | | extension | render nodes (compute + draws in the frame's passes), HDR overlay stages, custom WGSL | | quality | `GraphicsQuality::{Low, Medium, High, Ultra}` for every knob; `recommended` per device; prewarm plans | | WebGL2 | every feature has a path (Ldr fallback, CPU particles, CPU culling) | The Battle reference scene (300 ships with PBR maps, 100k particles, IBL, shadows, bloom, MSAA) costs about **1.5 ms of GPU and 1.45 ms of CPU** per 1080p frame on an Apple M4 Max. Overview and how-tos: [docs/graphics.md](docs/graphics.md) · adopting it in a game: [docs/graphics/migration.md](docs/graphics/migration.md) · try it: `cargo run -p graphics_showcase --release`. ## Quickstart ```sh # install the CLI from this repository cargo install --path crates/space3d-cli space3d new my_game --template 3d # basic | 3d | multiplayer cd my_game space3d run # desktop space3d serve # web: builds wasm, serves http://localhost:8080 space3d test # input-simulation + screenshot tests space3d stories # storybook viewer space3d editor # editor with the game scene loaded space3d doctor # what is missing for web / Android / iOS, and how to fix it ``` `space3d new` depends on Space3d via git by default; `--space3d-path ../Space3d` uses a local checkout. The generated project contains the game library (`build` + `GamePlugin`), the desktop/web entry point, a storybook binary, tests, `web/index.html`, a `mobile/` crate for Android and iOS, and a GitHub Actions workflow. See [docs/getting-started.md](docs/getting-started.md). Other commands: `space3d build --target desktop|web|android|ios [--release]`, `space3d publish --tag v1.0.0 [--dry-run]`, `space3d ci init --targets desktop,web,android,ios`, `space3d editor`, `space3d bench`. Every command takes `--dry-run` to print what it would run. ## Platform support | | Windows | macOS | Linux | Web | Android | iOS | |---|---|---|---|---|---|---| | graphics backend | DX12 / Vulkan | Metal | Vulkan / GLES | WebGPU / WebGL2 | Vulkan / GLES | Metal | | typical draw path | GPU multi-draw-count | GPU multi-draw | GPU multi-draw-count | GPU indirect / CPU | GPU / CPU | GPU multi-draw | | entry point (`main!`) | `fn main` | `fn main` | `fn main` | `#[wasm_bindgen(start)]` | `android_main` | `start_app()` | | build | `space3d build` | `space3d build` | `space3d build` | `space3d build -t web` | `space3d build -t android` | `space3d build -t ios` | | input | keyboard, mouse | keyboard, mouse | keyboard, mouse | keyboard, mouse, touch | touch | touch | | audio | ✓ | ✓ | ✓ | ✓ (after a user gesture) | ✓ | ✓ | | database | SQLite | SQLite | SQLite | localStorage (KV/saves) | SQLite | SQLite | | HTTP / WebSocket client | ✓ | ✓ | ✓ | ✓ (fetch / WebSocket) | ✓ | ✓ | | HTTP / WebSocket server | ✓ | ✓ | ✓ | — | ✓ | ✓ | | hot reload | ✓ | ✓ | ✓ | — | — | — | Details and per-platform setup: [docs/platforms.md](docs/platforms.md). ## Testing and screenshots Games test themselves with the same harness the engine uses: ```rust use space3d::prelude::*; use space3d::test::prelude::*; #[test] fn holding_right_moves_the_player() { let mut app = TestApp::headless(320, 240); // no window; renderer only if a GPU exists app.add_plugin(my_game::GamePlugin); app.hold_key(KeyCode::ArrowRight, 30); // exactly 30 fixed ticks assert!(app.translation(app.find_by_name("player").unwrap()).x > 1.0); assert_screenshot!(&mut app, "moved_right"); // golden image in tests/__screenshots__/ } ``` * The first run writes the golden PNG; later runs compare (tolerances, SSIM, per-backend variants) and write `*.actual.png` / `*.diff.png` on failure. * `space3d test` sets `SPACE3D_TEST_REPORT` and prints a summary with links into an HTML report (expected / actual / diff side by side); `space3d test --update-snapshots` re-blesses. * Without a GPU adapter, screenshot tests skip instead of failing (`SPACE3D_REQUIRE_GPU=1` makes them fail); CI uses a software Vulkan driver (lavapipe) so they run there too. * Determinism (`assert_deterministic`), frame budgets and allocation counts are assertions too. More: [docs/testing.md](docs/testing.md). ## Storybook A *story* is an isolated, parameterized scene — a prop, a material, a level chunk, a UI panel — with knobs (floats, colors, choices, …). The same story is browsed interactively, rendered into a static gallery, and checked as a golden screenshot test: ```sh space3d stories # viewer space3d stories --headless --out target/stories # PNGs + index.html gallery ``` ```rust space3d::stories::storybook_tests!(my_game::stories::storybook); // one golden per story ``` More: [docs/storybook.md](docs/storybook.md). ## Performance notes Numbers from the renderer design ([ARCHITECTURE.md](crates/space3d-render/ARCHITECTURE.md)) and the [`instancing_million`](examples/instancing_million) example: * **1,000,000 cubes, one draw.** An explicit `InstanceBuffer` stores each instance in **32 bytes** (position, uniform scale, snorm16 quaternion, unorm8 color, layer) — 2.5× smaller than matrix + color — so a million instances are ~31 MiB of vertex data, culled on the GPU by a compute pass (64 instances per workgroup, compacted in-workgroup) and drawn with (multi-)indirect draws. * **Upload only what changed.** User buffers track dirty ranges (merged within 16 instances, at most 64 ranges; >50 % dirty → one full copy). The example rewrites a 16,384-instance band per frame and uploads **512 KiB** instead of 31 MiB; `--static` uploads **0 bytes** after the first frame. * **Measured** (`cargo run -p instancing_million --release`, Apple M4 Max, Metal, `GpuMultiDraw`): 1,000,000 cubes = 12 M triangles in **1 indirect draw call**, holding the display's 120 Hz vsync while uploading 512 KiB per frame (0 KiB with `--static`). * **Static scenes cost nothing.** Renderer-owned buffers keep a CPU shadow and upload only differing byte ranges: an unchanged scene with a still camera uploads **0 bytes** per frame; moving one ECS entity uploads one **64-byte** matrix. * **No per-frame staging allocations.** All uploads go through a 4 MiB-chunk staging belt recycled after the GPU is done; copies ≥ 1 MiB are split across rayon workers. * **Automatic batching.** Entities with equal mesh + material are sorted into one instanced draw, so 1,000 identical-looking entities are one draw call even with separate `Material` values. * **One mesh arena.** All meshes share one vertex and one index buffer (36-byte vertices), so a GPU multi-draw covers many meshes without rebinding. `RenderStats` (draw calls, instances, triangles, bytes uploaded, draw path, …) is a resource, and the debug overlay (F3) shows it live. More: [docs/performance.md](docs/performance.md). ## Examples | example | shows | |---|---| | [`hello_cube`](examples/hello_cube) | window, lit rotating cube | | [`instancing_million`](examples/instancing_million) | 1M instances, dirty-range uploads, stats overlay | | [`physics_playground`](examples/physics_playground) | rapier bodies, click/space to drop, raycasts | | [`multiplayer_chat`](examples/multiplayer_chat) | WebSocket server + clients in one binary | | [`save_game`](examples/save_game) | SQLite save slots + key/value settings | | [`async_loading`](examples/async_loading) | assets over HTTP + compute-pool meshes while the frame keeps ticking | | [`web_demo`](examples/web_demo) | a browser-first scene built with `space3d::main!` | | [`graphics_showcase`](examples/graphics_showcase) | the Battle reference scene with every graphics feature, quality tiers, egui HUD, headless PNG, web | | [`pbr_showcase`](examples/pbr_showcase) | a glTF ship with PBR maps, skybox + IBL, a shadow-casting sun, every blend mode | | [`post_processing`](examples/post_processing) | every post effect toggled with keys | | [`particles`](examples/particles), [`particles_stress`](examples/particles_stress) | the particle library in a small battle; 100k+ particles | ```sh cargo run -p hello_cube cargo run -p instancing_million --release SPACE3D_EXIT_AFTER_FRAMES=120 cargo run -p physics_playground # smoke test: quit after 120 frames SPACE3D_HEADLESS=1 SPACE3D_EXIT_AFTER_FRAMES=60 cargo run -p hello_cube # no window at all SPACE3D_HEADLESS=1 cargo run -p graphics_showcase --release # writes graphics_showcase.png ``` ## Dependency policy: latest stable only Every dependency is pinned to its newest **stable** release (no alpha/beta/rc) in `[workspace.dependencies]` of the root `Cargo.toml`; crates use `foo.workspace = true`. Before adding a crate, check `cargo search --limit 1 `. (Example: winit stays on 0.30.x because 0.31 is still a beta.) One crate is patched: egui's `epaint`, vendored in `third_party/` with the kinsoku patch; an egui bump needs `python3 scripts/update-epaint.py` ([third_party/README.md](third_party/README.md)). ## Contributing Read [AGENTS.md](AGENTS.md). In short: everything is a `Plugin`; never block the frame; the simulation lives in `FixedUpdate`; runtime crates must build for `wasm32-unknown-unknown`; GPU tests skip without an adapter; and ```sh cargo fmt --all cargo clippy --workspace --all-targets -- -D warnings cargo test --workspace ``` ## License Licensed under the [Apache License, Version 2.0](LICENSE). See [NOTICE](NOTICE) for the copyright line and the third-party code kept in this repository. Unless you say otherwise, any contribution you submit for inclusion in Space3d is licensed under the same terms, without additional conditions. # Getting started ## 1. Install * Rust **1.98+** (`rustup update stable`). * The CLI: `cargo install --path crates/space3d-cli` from a Space3d checkout (installs the `space3d` binary into `~/.cargo/bin`). * Run `space3d doctor` — it lists what is installed for each platform and prints the exact command for anything missing (wasm target, `wasm-bindgen-cli`, Android NDK, Xcode, …). ## 2. Create a game ```sh space3d new my_game # basic: a cube you move around space3d new arena --template 3d # physics: roll a ball, knock crates off the arena space3d new party --template multiplayer # WebSocket server + clients, server-authoritative ``` Names are lower case with single `_` or `-` separators (`my_game`, `my-game`); the Rust crate is always the `_` form (`my_game::build`). Options: `--space3d-path ` (use a local engine checkout instead of git), `--git [--branch b | --rev r]`, `--dir `, `--targets desktop,web,android,ios` (CI workflow), `--no-ci`, `--force`. ```text my_game/ ├── Cargo.toml space3d dependency, epaint patch, profiles, workspace with mobile/ ├── src/lib.rs the game: `build(app)` + `GamePlugin` ├── src/main.rs space3d::main!(my_game::build) ├── src/stories.rs storybook ├── src/bin/stories.rs storybook viewer / gallery ├── src/bin/editor.rs editor with the game scene (`space3d editor`) ├── tests/input.rs gameplay driven by simulated input ├── tests/screenshots.rs golden screenshots (+ one per story) ├── assets/ textures, models, sounds ├── web/index.html page for the web build ├── mobile/ cdylib/staticlib crate for Android and iOS ├── android/README.md cargo-apk setup ├── ios/ XcodeGen project.yml, main.m, README └── .github/workflows/space3d.yml ``` ## 3. Run it ```sh space3d run # cargo run space3d run --release space3d run --frames 120 # quit after 120 frames (smoke test) space3d run --headless # no window (renders offscreen) space3d serve # web build + http://localhost:8080 (add --watch to rebuild on save) space3d editor # the editor with your scene: hierarchy, inspector, gizmos, play/pause/step ``` ## 4. The shape of a Space3d game ```rust use space3d::prelude::*; /// Everything: engine plugins + gameplay. Called by `space3d::main!`. pub fn build(app: &mut App) { app.add_plugin(DefaultPlugins::new().title("My game")); app.add_plugin(GamePlugin); } /// Only gameplay — tests and stories add this to a headless app. pub struct GamePlugin; impl Plugin for GamePlugin { fn build(&self, app: &mut App) { app.add_system(Stage::Startup, setup); // once app.add_system(Stage::FixedUpdate, simulate); // 60 Hz, deterministic app.add_system(Stage::Update, animate); // once per frame } } ``` * **Systems** are `FnMut(&mut SystemCtx)`: `ctx.world` (hecs ECS) and `ctx.resources` (type-keyed singletons such as `Input`, `ActionState`, `RenderAssets`, `Physics`, `Time`). * **Simulation** goes in `Stage::FixedUpdate` and uses `ctx.time().fixed_delta`, so it is identical for any frame rate — and tests can step it tick by tick. * **Never block the frame**: loading, networking and database calls return `Task`s. Poll them, or let `AsyncQueue` / `Http::*_then` call you back on the main thread: ```rust ctx.resources.expect_mut::().compute_then( || build_huge_mesh(), // runs on the compute pool |ctx, mesh| { let h = ctx.resources.expect_mut::().add_mesh(mesh); /* … */ }, ); ``` * **Input** via named actions: `ActionMap::bind("jump", Binding::Key(KeyCode::Space))`, then `ctx.resources.expect::().just_pressed("jump")`. Touch regions work as virtual buttons on phones. `KeyCode`s are physical key positions (WASD stays WASD-shaped on AZERTY); show players the key's label on their layout with `Input::key_cap` — see [Keyboard layouts](platforms.md#keyboard-layouts). ## 5. `DefaultPlugins` and `MinimalPlugins` `DefaultPlugins` adds, depending on the facade's cargo features: logging, tasks, window + renderer + input (`platform`), asset server (`assets`), audio, physics, scenes, HTTP/WebSocket clients (`net`) and egui (`ui`, F3 debug overlay). The database is opt-in: `.with_db(DbPlugin::new("save.db"))`. Builders: `.title()`, `.window(WindowPlugin { .. })`, `.tick_rate(hz)`, `.without_audio()`, `.without_physics()`, `.without_net()`, `.without_ui()`, `.with_debug_overlay()`, `DefaultPlugins::headless(w, h)`. `MinimalPlugins` is tasks + auto-exit + optional logging: servers and tools. Environment switches understood by both: | variable | effect | |---|---| | `SPACE3D_EXIT_AFTER_FRAMES=N` | send `AppExit` after N frames | | `SPACE3D_EXIT_AFTER_SECS=S` | … after S seconds | | `SPACE3D_HEADLESS=1` / `=640x360` | no window; offscreen renderer (each axis clamped to 1–8192) | | `RUST_LOG=debug` | log filter | ## 6. Cargo features of `space3d` Default: `render`, `platform`, `assets`, `audio`, `physics`, `scene`, `net`, `db`, `ui`. Optional: `editor`, `github`, `stories`, `test` (generated projects enable `stories` and `editor`, plus `test` for their tests; `stories` holds the engine's UI stories, so it builds egui even without `ui`). The engine crates of features you leave off stay out of your `Cargo.lock` too, except `space3d-assets` (and its image / glTF / OBJ loaders), which `render` lists without building it so that `render` + `assets` get their integration. Third-party crates list their own unbuilt optional dependencies: with `physics`, nalgebra and parry add glam 0.30–0.32, robust and spade. A dedicated server can use `space3d = { …, default-features = false, features = ["net"] }` (see `examples/multiplayer_chat`). ## 7. Updating Space3d Space3d is consumed by git revision. After bumping the pinned `rev`, run `cargo update -p space3d` (or `cargo update`). Bump the `rev` of the `[patch.crates-io] epaint` entry with it: it gives egui Space3d's Chinese and Japanese line breaking, and only applies while it comes from the same Space3d revision (a game created before it existed adds it by hand, see [UI: Chinese and Japanese line breaking](ui.md#chinese-and-japanese-line-breaking-kinsoku); `space3d doctor` warns when it is missing, unused or not Space3d's). Space3d always tracks the latest stable release of its dependencies, so a consumer lockfile pinned to an older version can fail to resolve, e.g. `space3d-net` needs `hyper-util ^0.1.21` ("failed to select a version for `hyper-util`"): update that crate too — `cargo update -p hyper-util` — or simply `cargo update`. ## Next * [Testing](testing.md) · [Storybook](storybook.md) · [Platforms](platforms.md) · [UI](ui.md) · [Networking](networking.md) · [Performance](performance.md) # Graphics Space3d's renderer draws a space battle with HDR, bloom, PBR materials lit straight from glTF, a skybox that is also the image-based lighting, a shadow-casting sun, 100k GPU particles with ribbons, beams and screen-space distortion, and a post chain — at 1080p in about 1.5 ms of GPU time on an Apple M4 Max, and on WebGL2 with a coherent Low preset. ![The SpaceCorps look](../crates/space3d-stories/tests/__screenshots__/Engine/Showcase/SpaceCorps_Look.png) *`Engine/Showcase/SpaceCorps Look`: procedural hulls with base color, ORM, normal and emissive maps; the nebula sky as skybox and image-based lighting; the sun's shadows on the asteroids; engines, afterburners, a laser beam with hit sparks and shield ripples, bolts, a missile's smoke ribbon, an explosion with its light flash and shockwave, a ship warping in; bloom, AgX punchy, a vignette — `GraphicsQuality::High`.* Nothing changes until you ask: a camera without `PostProcess`, a `Material` without maps and an app without the new components render exactly as before, pixel for pixel (spec D20). Everything here is additive to the API games already use ([`graphics/api.md`](graphics/api.md)). | page | covers | |---|---| | this page | overview, the frame, a how-to per feature, WebGL2, budgets, quality presets, showcase | | [`graphics/migration.md`](graphics/migration.md) | adopting every feature in SpaceCorps2027, step by step, with code | | [`graphics/frame.md`](graphics/frame.md) | frame modes, HDR, tonemapping, render scale, dynamic resolution, levels of detail, several cameras, render nodes, overlay stages, depth views, GPU timings and CPU spans | | [`graphics/materials.md`](graphics/materials.md) | material maps, blend modes, glTF import, tangents, cubemaps, skybox, image-based lighting, the directional shadow, prewarm | | [`graphics/post.md`](graphics/post.md) | bloom, auto exposure, color grading and LUTs, FXAA, vignette, chromatic aberration, film grain, distortion | | [`graphics/particles.md`](graphics/particles.md) | emitters, effects, sprites, ribbons, beams, flipbooks, light flashes, the built-in library, budgets, LOD | | [`graphics/api.md`](graphics/api.md) | the compatibility policy and where each type lives | | [`design/graphics.md`](design/graphics.md) | the normative design | ## Quick start: the SpaceCorps look ```rust use space3d::particles::prelude::*; use space3d::prelude::*; // PostProcess, Tonemapper, Skybox, EnvironmentLight, DirectionalShadow, … use space3d::render::{GraphicsQuality, ShadowFit, Vignette}; fn build(app: &mut App) { app.add_plugin(DefaultPlugins::new().title("My space game")); app.add_plugin(ParticlesPlugin::default()); app.add_system(Stage::Startup, setup); } fn setup(ctx: &mut SystemCtx) { // An HDR sky: a panorama, six faces or a `.skybox` manifest (materials.md). let sky = ctx.resources.expect_mut::().add_cubemap(my_sky_source()); // The camera: HDR + the battle look, the sky as background and as image-based lighting. ctx.world.spawn(( Transform::from_xyz(0.0, 400.0, 150.0).looking_at(Vec3::ZERO, Vec3::Y), Camera3d::default(), PostProcess::default() .with_tonemapper(Tonemapper::AgXPunchy) .with_exposure(0.5) .with_vignette(Vignette { enabled: true, intensity: 0.24, ..Vignette::default() }), Skybox::new(sky), EnvironmentLight::new(sky).with_intensity(0.7, 1.0), )); // One sun that casts shadows over the flight plane. ctx.world.spawn(( Transform::IDENTITY.looking_at(Vec3::new(-0.4, -0.8, -0.4), Vec3::Y), DirectionalLight { color: Vec3::new(1.0, 0.94, 0.86), intensity: 2.2 }, DirectionalShadow::new().with_fit(ShadowFit::top_down(0.0, 60.0, 900.0)), )); // Ships: glTF models with their normal / ORM / emissive maps (`upload_model`), engines. // … } /// One quality tier for everything, picked for the device (Low on WebGL2). Windowed apps get /// their renderer after `Startup`: run this once it exists (a `PreUpdate` system, as /// `graphics_showcase` does). fn choose_quality(ctx: &mut SystemCtx) { let Some(renderer) = ctx.resources.get::() else { return }; let q = GraphicsQuality::recommended_for(renderer); let particles = ParticleSettings::for_quality_on(q, renderer.graphics_caps()); q.apply(ctx.world, ctx.resources); *ctx.resources.expect_mut::() = particles; } ``` `examples/graphics_showcase` is this, complete: the Battle reference scene with every feature, the tier chosen for the device and cycled with `Q`, content generated off the frame, an egui HUD (`cargo run -p graphics_showcase --release`; `SPACE3D_HEADLESS=1` writes a PNG). ## The frame A frame runs in one command encoder and one submit. Cameras are grouped by render target; a camera with an enabled `PostProcess` makes its target group render through a scene texture `S` (HDR `Rgba16Float` / `Rg11b10Ufloat`, or 8-bit in the Ldr fallback) that the composite pass exposes, blooms, tonemaps and grades into the display target `D`. Without one, the group renders straight into `D` as always (Direct mode). ```text render_frame upload meshes, textures, cubemaps · extract and batch the ECS · plan views, groups, modes lighting: cubemap conversion, IBL bake, shadow light · post: plan each post group render nodes prepare once (particle simulation, uploads) · per view: node prepare, GpuView compute: GPU culling of every view (camera views and shadow maps) · particle sim / compaction depth views: the shadow map per camera view (camera order): scene pass → D (Direct) or S: Opaque (meshes, alpha mask) → Skybox → Transparent (blended meshes by render_order, then node slots: particles) depth resolve + SceneRead (soft particles) · Distortion pass → DB (the post group's offsets) finish each intermediate group: HdrScene overlays → S (bloomed and tonemapped with the scene) per post group: auto exposure → bloom chain → composite → D (or → FXAA → D) display views (cameras after the post camera: gizmos, HUD) → D, LDR AfterTonemap overlays (egui) → D · submit · present ``` Details: [`frame.md`](graphics/frame.md); normative order: spec §1.4. ## How to … **Turn on HDR, exposure and tonemapping.** Insert `PostProcess` next to a `Camera3d`. Pick the look explicitly: `Tonemapper::AgXPunchy` with `.with_exposure(0.5)` keeps faction colors, lasers and fire saturated in a dark space scene but skews dim saturated skies toward their strongest channel; `AgX` (the default) is gentler, with `ColorGrading::vivid()` it keeps those skies' hues; `KhronosPbrNeutral` keeps base colors but its toe crushes dim saturated ones, which `KhronosPbrNeutralNoToe` passes unchanged; `AcesFitted` and `Reinhard` are there too (numbers in frame.md, "Choose the look explicitly"). Clear colors pass through exposure and the tonemapper like everything else. `FrameSettings::post = false` turns post off globally. ([frame.md](graphics/frame.md)) **Make things glow.** Bloom is on in `PostProcess::default()` (`Bloom::glow()`: threshold 1, a soft knee): anything brighter than 1 after exposure glows — emissive above 1, additive particles, stars in an HDR sky. `Bloom::natural()` is a photographic veil. Emissive maps × `emissive` factors above 1 make windows and engines glow. ([post.md](graphics/post.md#bloom)) **Expose automatically.** `.with_auto_exposure(AutoExposure::on())`; `exposure` becomes the compensation. Black space is not metered, but an HDR skybox is: where a nebula fills most of the frame it sets the exposure (the Battle brightens by about +0.9 EV and washes out), so give sky scenes a negative compensation and a low `max_ev`, or keep a manual exposure. ([post.md](graphics/post.md#auto-exposure)) **Anti-alias.** MSAA on the primary target (`Renderer::set_msaa_samples(4)`, or the quality preset) and on render targets (`RenderTargetDesc::with_samples(4)`); FXAA in the composite (`.with_fxaa(FxaaQuality::Medium)`) where MSAA is too expensive (WebGL2). **Grade and add lens effects.** `ColorGrading` (white balance, saturation, contrast, lift/gamma/gain, a 3D LUT, WGSL hooks), `Vignette`, `.with_chromatic_aberration(x)`, `FilmGrain`. `PostProcess::cinematic()` is a starting point. ([post.md](graphics/post.md)) **Bend space.** Distortion is on by default and costs nothing until something writes it: explosions, warps, EMPs and engines of the particle library, `SpriteRender::distortion` in your own effects, `DistortionMaterial` meshes (shockwave rings, heat haze), or a render node through `DISTORTION_WGSL`. ([post.md](graphics/post.md#distortion)) **Use material maps.** `Material::with_normal_map`, `with_orm_map` (one texture for occlusion, roughness, metallic), `with_metallic_roughness_map`, `with_occlusion_map`, `with_emissive_map(texture, factor)`; maps multiply the factors. Normal maps need tangents: glTF `TANGENT`, `MeshExtras::with_tangents` (MikkTSpace from `space3d::assets::edit::mesh::compute_mikktspace_tangents`), or per-pixel frames when absent. ([materials.md](graphics/materials.md#maps)) **Load glTF materials as authored.** `space3d::assets::render::upload_model` (or `prepare_model_async` + `PreparedModel::upload` off the frame) converts every slot — base color, normal (+ scale), metallic-roughness, occlusion (+ strength, ORM packing), emissive (+ factor and `KHR_materials_emissive_strength`), alpha mode, `texCoord` sets, `KHR_texture_transform` — with sRGB for base color and emissive, linear for the rest, and generates tangents. Custom material code adds the maps with `apply_material_maps`. ([materials.md](graphics/materials.md#gltf-import)) **Blend.** `BlendMode::{Opaque, AlphaMask, AlphaBlend, Premultiplied, Additive}` (`Material::additive(color)`, `Material::premultiplied(color)`, `.with_alpha_mask(cutoff)`); `render_order` orders transparent meshes; `LightingSettings::transparent_sort` sorts instances back to front. ([materials.md](graphics/materials.md#blend-modes)) **Show a sky and light with it.** `RenderAssets::add_cubemap(CubemapSource::…)` from six faces, three.js faces (`.skybox` manifests), an LDR or HDR panorama; `Skybox::new(cube)` on the camera draws it behind everything; `EnvironmentLight::new(cube)` bakes irradiance and GGX-prefiltered specular from it (once, on the GPU) so metal reflects the nebula. Use `ShadingModel::Standard` (the presets do). ([materials.md](graphics/materials.md#image-based-lighting)) **Cast shadows.** `DirectionalShadow` next to one `DirectionalLight`; `ShadowFit::top_down(plane_y, half_thickness, max_distance)` fits the camera's view of a slab (top-down games), `Bounds(aabb)` a fixed box; `ShadowFilter::{Hard, Pcf4, Pcf9, Pcf16}`; `Material::shadows` opts meshes in or out. ([materials.md](graphics/materials.md#directional-shadow)) **Spawn effects.** `app.spawn_effect(builtin::EXPLOSION, EffectSpawn::at(p).scale(1.2))` — one call per one-shot; `ParticleEmitter::new(builtin::ENGINE_EXHAUST)` (+ `EffectSpawn::follow`) for engines; beams with `.beam_to(BeamEnd::Entity(target))`; ribbons follow bolts and missiles. 14 built-ins (explosion, hit spark, shield ripple, warps, engines, afterburner, laser trail, beam and shot, missile trail, debris, EMP, repair beam), authored for HDR + bloom; your own in code or `.pfx.ron`. ([particles.md](graphics/particles.md)) **Draw your own effects into the frame.** A `RenderNode` gets slots in the scene passes (Opaque, Skybox, Transparent, SceneRead with the scene depth, Distortion), compute in `prepare`, the view bind groups and `VIEW_WGSL` / `scene_wgsl` / `OUTPUT_WGSL`. A `RenderOverlay` with `fn stage(&self) -> OverlayStage { OverlayStage::HdrScene }` draws into the HDR scene before bloom and tonemapping (below). ([frame.md](graphics/frame.md#render-nodes-drawing-into-the-frames-passes)) **Render at a lower resolution.** `FrameSettings::render_scale` (or `CameraFrame::render_scale` per camera): the scene renders smaller and the composite upscales; egui stays sharp. **Hold the frame rate.** `DynamicResolution::on(60.0)` (a resource, off by default) multiplies `FrameSettings::render_scale` by a step of 1, 0.85, 0.72, 0.6 or 0.5, chosen from the frame time alone: down while frames are over budget and a lower resolution makes them faster, up again when there is room. ([frame.md](graphics/frame.md#dynamic-resolution)) **Draw small models with fewer triangles.** `lod::simplify_to(&mesh, &extras, 0.25)` makes a coarser mesh; `MeshLod::new(radius, &[full, mid, low])` on the entity lets the renderer set its `Mesh3d` each frame from its size on screen (`LodSettings`). Shadow maps draw the same level. ([frame.md](graphics/frame.md#levels-of-detail)) **Preview a ship in the UI.** A render target (`add_render_target_with(w, h, RenderTargetDesc::default().with_samples(4))`), a camera with a transparent clear and `PostProcess` targeting it: the composite keeps alpha, egui shows it (`UiTextures`). **Measure.** `FrameSettings::gpu_timing` fills `GpuTimings` (per-pass GPU ms, labels in frame.md); `RenderStats` counts draws, passes, targets bytes; `ParticleStats` the particles. The frame's CPU parts are trace spans named `render.*`, which the F4 profiler lists beside the systems ([frame.md](graphics/frame.md#cpu-spans)). **Build pipelines on the loading screen.** WebGL2 links a program in 50–150 ms: render one frame of the loading scene, then `renderer.prewarm(&quality.prewarm_request(&materials))`. ## Overlay stages | stage | when | target | gets | |---|---|---|---| | `OverlayStage::AfterTonemap` (default: every existing overlay, egui) | after every post group, FXAA and display view | the display target, display format | nothing: the old placement and pixels | | `OverlayStage::HdrScene` (opt-in) | after the primary target's scene views, before its post groups (Direct mode: after its last view) | the scene color (`Rgba16Float`, `Rg11b10Ufloat`, or 8-bit in the Ldr fallback), scene size | distortion, exposure metering, bloom, tonemapping, grading, FXAA, grain | An HdrScene overlay writes the encoding `prepare_scene` gives it (`OverlayScene::output`) and reads the scene depth when `scene_reads()` contains `DEPTH`. Worked example — the game's additive sprite overlay: [frame.md](graphics/frame.md#migrating-an-additive-overlay-the-games-additivers). ## WebGL2 and other downlevel devices Every feature has a path without compute shaders and without storage buffers in vertex shaders. Classes (spec §4.1): **A** native Vulkan/Metal/DX12 and WebGPU; **B** WebGL2 with float color buffers (most desktop browsers; ANGLE); **C** WebGL2 without them; **D** GLES 3.1+ Android. | feature | A | B (WebGL2 + float) | C (WebGL2, 8-bit) | D (GLES 3.1) | |---|---|---|---|---| | HDR scene, tonemapping | ✓ | ✓ | Ldr fallback: tonemapped per fragment, CPU-tonemapped clears | ✓ if float renderable | | bloom | ✓ | ✓ | off (warned) | ✓ | | auto exposure | compute histogram | render-pass chain | off | compute | | FXAA, vignette, CA, grain, grading, LUT | ✓ | ✓ | ✓ | ✓ | | distortion | ✓ | ✓ (unoccluded with MSAA) | ✓ | ✓ | | material maps, blend modes, alpha mask | ✓ | ✓ | ✓ | ✓ | | skybox, IBL bake | ✓ | ✓ (passes spread over frames) | ✓ (8-bit environment) | ✓ | | directional shadow | ✓ | ✓ (CPU culling) | ✓ | ✓ | | particles | GPU backend (compute) | CPU backend (16k native / 8k web) | CPU | GPU | | ribbons and beams | CPU-built strips everywhere | ✓ | ✓ | ✓ | | soft particles | ✓ | ✓ (fade off with MSAA) | ✓ | ✓ | | GPU timings | ✓ | — | — | if offered | `GraphicsQuality::recommended` picks **Low** on WebGL2 / GL, without float targets or without compute, and `ParticleSettings::for_quality_on` gives the particles Low's CPU budget there whatever the tier. Test any path on any GPU with `FrameSettings::downlevel` (`DownlevelOverride::webgl2()` forces all three limits); `Engine/Showcase/WebGL2 *` are the showcase under it. On this Mac, ANGLE runs the GL backend (`--features angle`, `WGPU_BACKEND=gl`; see the spec §5.0). ## Budgets The reference scene **Battle** (spec §4.4): 300 ships of three hulls with ORM, normal and emissive maps, a nebula skybox with IBL, one shadowed sun, ~20–40 point lights (the explosions' light flashes), 100k particles with 64 ribbons, 16 beams and warp shockwaves, bloom, MSAA 4, two 256² render-target previews — `space3d_stories::showcase::{spawn_battle, dress_battle}`, the `Engine/Showcase/Battle` story, `benches/graphics.rs` and `tests/perf_graphics.rs` in `space3d-stories`. | gate (Dev: Apple M4 Max, Metal, 1080p, release) | budget | measured (High) | |---|---|---| | Battle GPU frame | ≤ 3.0 ms | 1.49 ms | | Battle CPU `render_frame` | ≤ 1.5 ms | 1.45 ms (shared machine; see performance.md) | | frame and post targets (T1/T2 VRAM line) | ≤ 220 MB | 133.5 MB | | bloom 6 levels | ≤ 0.20 ms | 0.19–0.23 ms (shared GPU) | | all post effects | ≤ 0.60 ms | 0.41 ms | | particles 100k: sim + compaction / draw | ≤ 0.06 / 0.40 ms | 0.048 / 0.382 ms | | shadow 2048², 100k casters | ≤ 0.30 ms | 0.28 ms | | full-screen lit pixels, all maps + IBL + PCF9, over the old shader | ≤ +0.20 ms | +0.12 ms | | IBL bake (LDR faces / HDR faces / HDR panorama) | ≤ 3 ms | 0.5–1.3 / 1.8 / 2.0–2.2 ms | Per-tier Battle figures and the history of every gate: [performance.md](performance.md). Design targets for other devices (T1 dGPU ≈ 5.8 ms, T2 Apple M1 ≈ 11 ms, T3 WebGL2 iGPU at Low ≈ 12.8 ms): spec §4.4. Steady state: no CPU reallocations, no textures created after warm-up, a static scene uploads 0 bytes. ## Quality presets `GraphicsQuality` sets the performance knobs of every area coherently; it never changes a game's look otherwise (tonemapper, exposure, grading, bloom intensity, materials stay as authored). | knob | Low (WebGL2 / C-class) | Medium (iGPU, Apple, mobile) | High (dGPU) | Ultra (opt-in) | |---|---|---|---|---| | render scale (primary) | 0.75 | 1 | 1 | 1 | | MSAA / AA | 1 + FXAA Low | 4 on tile-based GPUs, else 1 + FXAA Medium | 4 | 4 | | bloom mips / max mip height | 4 / 270 | 6 / 540 | 7 / 720 | 8 / 720 | | auto exposure, chromatic aberration, film grain | off | as authored | as authored | as authored | | shadow map / filter | 1024 / Pcf4 | 2048 / Pcf9 | 2048 / Pcf16 | 4096 / Pcf16 | | IBL specular / irradiance / samples / passes per frame | 128 / 16 / 32 / 6 | 256 / 32 / 64 / all | 512 / 32 / 128 / all | 512 / 32 / 256 / all | | shading model | Classic | Standard | Standard | Standard | | particles (`ParticleSettings::for_quality`) | CPU 16k (8k web) | GPU 262k (65k mobile) | GPU 262k | GPU 262k | | recommended sky face size | 512 | 1024 | 2048 | 2048 | ```rust use space3d::render::GraphicsQuality; let q = GraphicsQuality::recommended_for(renderer); // Low on WebGL2/GL, no float or no compute; // High on discrete GPUs; Medium otherwise q.apply(world, resources); // FrameSettings, LightingSettings, MSAA, // every PostProcess and DirectionalShadow *resources.expect_mut::() = ParticleSettings::for_quality_on(q, caps); // Loading screen, after one frame of the scene: renderer.prewarm(&q.prewarm_request(&materials)); ``` * `apply` is lossless: the post settings a camera had before the first `apply` are remembered, so switching Low → High restores the chromatic aberration Low turned off. Cameras and lights spawned later take the tier with `q.post_for(post, msaa)` / `q.shadow(shadow)` (or `apply` again). * The adapters (`frame_settings`, `msaa_samples`, `post`, `post_for`, `lighting`, `shadow`, `sky_face_size`) are there for games that store their own settings. * **Ultra** is never recommended: a menu choice for big GPUs. It is High plus a 4096² PCF16 shadow, one more (wider) bloom level (8 / 720) and a 256-sample environment bake. A level 0 is never larger than half the rect, so at 1080p High and Ultra both run their chains at 960 × 540 (High 13 bloom passes, Ultra 15); before M2's fix High's 720 cap resampled level 0 up to 1280 × 720 and cost more than Ultra. * Map a game's own setting names to tiers (SpaceCorps2027: `low`/`medium`/`high` → `Low`/`Medium`/`High`): [migration.md](graphics/migration.md#2-quality-presets). ## Showcase, stories, tests | where | what | |---|---| | `Engine/Showcase/SpaceCorps Look` | the close-up skirmish above; knobs: quality tier, shadows, IBL, bloom, distortion | | `Engine/Showcase/Battle` | the reference scene at 320 × 180 (goldens), previews in the corner | | `Engine/Showcase/WebGL2 SpaceCorps Look`, `WebGL2 Battle` | both under `DownlevelOverride::webgl2()` at Low | | `examples/graphics_showcase` | the Battle, windowed (egui HUD, keys), headless PNG, web | | `space3d_stories::showcase` | the content generators (hulls, hull maps, sky, asteroids) and scenes | | `crates/space3d-stories/tests/perf_graphics.rs` | steady state and VRAM (always); the Dev gates (`--ignored`) | | `crates/space3d-stories/benches/graphics.rs` | CPU per tier (criterion), `graphics/report` per tier | Every area has its own stories (`Engine/Frame/*`, `Engine/Materials/*`, `Engine/Environment/*`, `Engine/Lights/*`, `Engine/Post/*`, `Engine/Particles/*`) and goldens; the whole book runs as one golden test (`cargo test -p space3d-stories --test storybook`), on Metal and on ANGLE (GL variants `*.gl.png` where drivers differ). ![Battle](../crates/space3d-stories/tests/__screenshots__/Engine/Showcase/Battle.png) ![Battle on WebGL2](../crates/space3d-stories/tests/__screenshots__/Engine/Showcase/WebGL2_Battle.png) # Networking `space3d-net` (facade feature `net`, on by default) provides HTTP and WebSocket clients on every platform and HTTP/WebSocket servers natively. All I/O runs on the background runtime from `space3d-tasks`; engine systems only poll tasks and channels, so **a slow network never stalls a frame**. | piece | native | web | |---|---|---| | `Http` client | reqwest + rustls | `fetch` | | `WsClient` / `WsConnection` | tokio-tungstenite + rustls | browser `WebSocket` | | `HttpServer`, `WsServer` | axum + tower-http | — | | `Channel`, `Codec`, `Frame` | ✓ | ✓ | `NetPlugin` (part of `DefaultPlugins`) inserts `Http` and `WsClient`, runs HTTP callbacks and emits `Events` in `PreUpdate`, and — when a `WsServer` resource exists — `Events`. ## HTTP ```rust #[derive(serde::Deserialize)] struct Motd { text: String } // Callback style: runs on the main thread with full SystemCtx access. ctx.resources.expect::().get_json_then("https://example.com/motd.json", |ctx, r: Result| { if let Ok(motd) = r { ctx.resources.insert(motd.text); } }); // Task style: poll it from a system. let mut task = http.get("https://example.com/level/3.json"); if let Some(result) = task.poll() { /* … */ } ``` Requests support headers, JSON bodies, timeouts and retry policies (`HttpRequest::…`). `Http::fetch` exposes the raw future for composing inside other async code — e.g. an asset source that loads over HTTP (see `examples/async_loading`). ## WebSocket client ```rust let chat = ctx.resources.expect_mut::().open_with( "wss://example.com/chat", WsConfig::default().reconnect(ReconnectPolicy::default()), ); ctx.resources.expect::().send(chat, "hello")?; // queued until the socket opens // Every frame: let mut reader = EventReader::default(); app.add_system(Stage::Update, move |ctx| { for event in reader.read(ctx.resources.expect::>()) { match &event.kind { WsEventKind::Opened => { /* (re)send hello */ } WsEventKind::Message(m) => { /* m.as_text() / m.as_bytes() */ } WsEventKind::Closed { reason, reconnecting } => { /* … */ } } } }); ``` After a reconnect you get another `Opened` — send your handshake there, not only at start-up. ## Servers (native) ```rust // Static files + JSON API + WebSockets on one port. let ws = WsServer::new(); let handle = HttpServer::new() .bind(([0, 0, 0, 0], 8080)) .serve_spa("dist/web") .get_json("/api/status", || serde_json::json!({ "ok": true })) .ws("/ws", &ws) .cross_origin_isolated() // COOP/COEP for SharedArrayBuffer .start()?; // binds synchronously; serves on the background runtime app.insert_resource(ws); // NetPlugin → Events app.insert_resource(handle); // dropping the handle shuts the server down ``` A bare WebSocket server: `WsServer::new().listen(addr)?`. `WsServer` has `send`, `broadcast`, `broadcast_except`, `disconnect`, `clients`. `ServerEvent::{Connected, Message, Disconnected}` arrive in order per client. `space3d serve` is built on the same `HttpServer` (`serve_spa` + `cross_origin_isolated` + `no_cache`). ## Multiplayer architecture The `multiplayer` template (`space3d new party --template multiplayer`) is a complete, server-authoritative example: * **Protocol**: JSON text frames — `ClientMsg::{Hello, Input}` up, `ServerMsg::{Welcome, Snapshot}` down; a pure `step(position, input, dt)` movement rule shared by everyone. * **Server** (`ServerPlugin`): keeps players in a resource keyed by `ClientId`, simulates them on `FixedUpdate`, broadcasts a snapshot every 3 ticks (20 Hz at 60 Hz). * **Client** (`ClientPlugin`): sends input when it changes (plus a keep-alive), applies snapshots to replica entities and eases them towards the latest state; re-sends `Hello` after every (re)connect. * **Modes**: `cargo run` = listen server (server + client in one process); `cargo run --bin server` = dedicated headless server (`MinimalPlugins`, no window); `--connect ws://host:7777` joins. The web build is client-only. * **Tests**: a real server and client in one headless `TestApp`, stepping with short sleeps until the key press has moved the player on the server and the replica followed. For typed, sequenced, tick-stamped messages over any transport, see `space3d_net::channel` (`Channel` with a `Codec`, including a snapshot/input replication example in its docs). `examples/multiplayer_chat` shows the smallest possible server + clients (`default-features = false, features = ["net"]` — no window or renderer compiled in). # Performance Space3d's rules for staying fast are simple: **never block the frame**, **draw many things with few draw calls**, and **upload only what changed**. This page explains the mechanisms and how to measure them. The renderer internals are documented in [crates/space3d-render/ARCHITECTURE.md](../crates/space3d-render/ARCHITECTURE.md). ## Never block the frame * File, network and database I/O return `space3d_tasks::Task`s (tokio natively, `wasm-bindgen-futures` on the web). Systems `poll()` them or register callbacks with `AsyncQueue::spawn_then` / `track`, which run on the main thread in `PreUpdate`. * CPU-heavy work (mesh generation, pathfinding, decoding) goes to the compute pool with `spawn_compute` / `AsyncQueue::compute_then`. * The asset server reads bytes on the I/O runtime, decodes on the compute pool and inserts the result in `PreUpdate`; SQLite runs on its own worker thread. * `Task::block()` exists for tools and tests only — never call it from a system. `examples/async_loading` streams 12 textures and a model over HTTP with 0.2–1.6 s of artificial latency each, builds a 24k-triangle mesh on the compute pool, and reports the longest frame while all of that is in flight. In a debug build on an M4 Max the 14 assets arrive over ~1.4 s while ~155 frames are rendered and the longest frame stays around 17–22 ms (texture uploads and first-use pipeline creation) — no frame ever waits for a download or a decode. ## Draw many things with few draw calls **Automatic instancing.** Every entity with `Mesh3d + Material + GlobalTransform` is sorted by (pipeline, material, mesh); each run becomes one instanced draw. Equal materials are interned, so 1,000 entities with equal-but-separate `Material` values are still one draw. **Explicit instance buffers** for 100k–1M+ objects without per-entity ECS cost: ```rust let buffer = ctx.resources.expect_mut::().insert( InstanceBuffer::from_vec(instances /* Vec */, BufferUsage::Dynamic), ); ctx.world.spawn((InstancedMesh { mesh, material, instances: buffer },)); ``` | instance type | size | contents | |---|---|---| | `InstanceTransform` | 64 B | model matrix | | `InstanceTransformColor` | 80 B | matrix + color | | `InstanceCompact` | 32 B | position, uniform scale, f32 quaternion | | `InstancePacked` | 32 B | position, scale, snorm16 quaternion, unorm8 color, texture layer | Any `Pod` struct with an `InstanceLayout` works; the shader is generated for its layout. **GPU-driven culling.** On adapters with compute + indirect draws, a compute pass frustum-culls instances (64 per workgroup, compacted inside the workgroup) and writes indirect draw arguments; batches become one `multi_draw_indexed_indirect(_count)` per pipeline run. The chosen path is in `RenderStats::draw_path`: | path | used on | culling | |---|---|---| | `GpuMultiDrawCount` | Vulkan, DX12 | compute, empty batches skipped by the GPU | | `GpuMultiDraw` | Metal, WebGPU with `indirect-first-instance` | compute | | `GpuIndirect` | other compute-capable adapters | compute | | `CpuDirect` | WebGL2, GLES, downlevel | CPU sphere/AABB tests | **One mesh arena.** All meshes share one vertex buffer (36-byte vertices) and one index buffer, so multi-draws cover many meshes without rebinding. ## Upload only what changed * **Staging belt.** All buffer uploads are copied straight into mapped staging memory (4 MiB chunks) that is recycled once the GPU is done — no staging allocations in the steady state. Copies of 1 MiB or more are split across worker threads. * **Dirty ranges for user buffers.** Every mutating `InstanceBuffer` accessor (`set`, `get_mut`, `range_mut`, `push`, …) records a range; adjacent ranges within 16 instances merge, at most 64 ranges are kept, and more than 50 % dirty becomes one full copy. `Static` buffers upload once; `Stream` buffers upload everything every frame without bookkeeping. * **Shadow diffing for renderer buffers.** ECS instances, per-view data, materials and indirect argument templates keep a CPU shadow; only differing bytes are uploaded. **A static scene with a still camera uploads 0 bytes per frame; moving one entity uploads one 64-byte matrix.** * **No per-frame reallocations.** Buffers grow 1.5× (meshes 2×) and are reused. ### `instancing_million` ```sh cargo run -p instancing_million --release # 1,000,000 cubes, animated band cargo run -p instancing_million --release -- --static # no edits: 0 bytes uploaded per frame cargo run -p instancing_million --release -- --count 250000 --band 65536 ``` Measured on an Apple M4 Max (Metal, `GpuMultiDraw` path, release build): | run | instances | triangles | draw calls | uploaded / frame | frame rate | |---|---|---|---|---|---| | default (animated band) | 1,000,000 | 12,000,000 | 1 (indirect) | 512 KiB | 120 fps (vsync-limited) | | `--static` | 1,000,000 | 12,000,000 | 1 (indirect) | 0 KiB | 120 fps (vsync-limited) | 1,000,000 `InstancePacked` cubes are 32 MB (30.5 MiB) of instance data. Each frame the example rewrites a band of 16,384 instances — **512 KiB uploaded instead of 30.5 MiB** — and the window title (plus stdout every 120 frames) shows FPS, draw path, draw calls and bytes uploaded. `C` toggles the CPU path, `F` frustum culling, `Space` pauses the wave; F3 shows the engine debug overlay. ## Measuring * `RenderStats` resource: draw calls (direct / indirect / multi), batches, instances, triangles, `bytes_uploaded`, `instance_bytes_uploaded`, buffer reallocations, compute dispatches, draw path, meshes/textures uploaded. * **F3** debug overlay (FPS, frame-time graph, ticks, render stats) and **F4** profiler (per-system timings from `tracing` spans, and the renderer's `render.*` parts of the frame: [graphics/frame.md](graphics/frame.md#cpu-spans)) with the `ui` feature. * In tests: `assert_frame_budget`, `RenderBudget` (max draw calls / bytes uploaded / …), `assert_max_allocations` — see [testing.md](testing.md). * Benchmarks: `space3d bench` (= `cargo bench`); the engine has criterion benches for the schedule (`space3d-core`), instancing (`space3d-render`), texture ops, SQLite inserts and physics. ## Build settings Generated projects (and the engine workspace) use: ```toml [profile.dev] opt-level = 1 # your code: fast to compile, not unbearably slow [profile.dev.package."*"] opt-level = 3 # dependencies: fully optimized once [profile.release] lto = "thin" codegen-units = 1 ``` Release web builds additionally run `wasm-opt -Oz` when binaryen is installed. ## Graphics upgrade baselines Measured values of the graphics upgrade's gates (`docs/design/graphics.md` §4.4). Each gate is checked against the numbers recorded here; a gate is relaxed only with a new measurement and a reason. ### F — foundation (F0 baseline, Direct mode) Dev machine: Apple M4 Max, Metal, wgpu 30.0.1, Rust 1.98.1. `benches/instancing.rs` (`cargo bench -p space3d-render --bench instancing -- --warm-up-time 1 --measurement-time 3`, bench profile; criterion median and range). The "Direct mode" gate is ±5 % of these. | bench | time | |---|---| | `extract_upload/explicit/100k` | 918 µs (716 µs – 1.30 ms) | | `extract_upload/explicit/1000k` | 2.16 ms (2.11 – 2.21 ms) | | `extract_upload/ecs/100k` | 1.79 ms (1.76 – 1.84 ms) | | `extract_upload/ecs_static_mixed/100k` | 2.18 ms (2.13 – 2.24 ms) | | `mesh_arena/upload_1000` | 1.72 ms (1.70 – 1.74 ms) | Steady-state heap allocations per frame (`tests/alloc.rs`, test profile; all of them inside wgpu/wgpu-hal, 0 in the renderer; bounds 95 CPU / 215 GPU paths on Metal): | path | allocations per frame (min / max / mean) | |---|---| | `CpuDirect` | 82 / 86 / 83.6 | | `GpuIndirect`, `GpuMultiDraw` | 191 / 195 / 192.6 | | `GpuMultiDraw` + 2 viewport cameras | 314.6 with or without viewport clears | Live bytes grow by 0 over 120 frames on every path; `cpu_reallocations` and `buffer_reallocations` are 0. Engine storybook (`cargo run -p space3d-stories --example gallery`, dev profile; setup + simulation + capture per story; the first story includes device creation): | story | ms | |---|---| | Engine/Basics/Lit Cube | 158.5 | | Engine/Materials/Material Grid | 16.2 | | Engine/Materials/Single Material | 15.9 | | Engine/Instancing/10k Cubes | 63.1 | | Engine/Textures/Checker Plane | 67.6 | | Engine/Lights/Point Lights | 16.8 | | Engine/Camera/Projection | 16.4 | | Engine/Transforms/Hierarchy | 16.1 | | Engine/Physics/Falling Bodies | 16.9 | The engine goldens (`crates/space3d-stories/tests/__screenshots__/Engine/`) were already exact for the merged renderer at F0 (no re-bless needed): they are the baseline of every "bit-identical" claim. `cargo test -p space3d-stories --test storybook -- --ignored engine_goldens_are_exact` checks them with tolerance 0. ### F3 / F4 — output tail, `GpuView`, HDR frame modes `GpuView` grew to its frozen 1312 bytes (1536-byte stride; 1376 bytes since `inv_proj_rot` was appended, the same stride); forward modules no longer depend on the output encoding (an override). Direct mode is unchanged: the engine goldens are bit-exact, and the steady-state allocations of `tests/alloc.rs` are identical to F0 (82–86 CPU path, 191–195 GPU paths, 314.6 with two viewport cameras). `benches/instancing.rs` after F4 (same command as F0; the machine was shared with other builds, load average 6–18, so the ranges are wide): `explicit/100k` 581 µs, `explicit/1000k` 1.77 ms, `ecs/100k` 1.69 ms, `ecs_static_mixed/100k` 2.68 ms (2.14 – 3.87 ms), `mesh_arena/upload_1000` 2.10 ms (1.88 – 2.45 ms). The medians of the first three are below F0; the last two overlap F0 within their noise ranges. Gate "Hdr minimal (composite only) over Direct" (`benches/frame.rs`, 1080p headless, a lit ground plane with 400 cubes, `PostProcess::default().without_bloom()`: exposure, AgX, dither). The criterion groups `frame/{cpu,gpu,throughput}/*` run Direct, then Hdr, one after the other: on this shared machine a load change between the two corrupts their difference (one F-core review run measured `frame/cpu/direct` at 477.8 µs, above Hdr's 89.1 µs). The F4 figure recorded here first (throughput +25 µs, 113.6 vs 138.5 µs) came from such a sequential run and was not reproduced. Deltas come from `frame/ab` (`cargo bench -p space3d-render --bench frame -- frame/ab`), which interleaves the two modes round by round and reports medians of the paired deltas: | `frame/ab` (medians, µs) | Direct | Hdr minimal | paired delta | gate | |---|---|---|---|---| | cpu (render stage on the CPU) | 67–75 | 86–97 | +17 to +23 | ≤ +20 µs CPU | | throughput (frames back to back, a wait every 8th; GPU-bound) | 98–104 | 137–141 | +37 to +40 | ≤ +0.10 ms GPU | | latency (render + GPU wait, loaded clocks) | 273–278 | 340–351 | +70 to +81 (incl. the CPU delta) | (upper bound) | | latency, isolated frames 2 ms apart (lowest GPU clocks) | 814–902 | 1064–1297 | +254 to +294 | — (reference) | Three runs at load average 4–6. The F-core review's own interleaved harness measured throughput deltas of +44.6, +67.4 and +77.1 µs and a latency delta of +65 to +98 µs. Instructions retired on the CPU grow by 109k–116k per frame, which is +10 to +17 µs of thread CPU time (median). That is within the CPU gate at the median, but wall-clock runs reach +23 µs. The extra composite render pass is most of it (about 30 wgpu-hal allocations and the Metal encoder setup). **Which GPU regime the gate uses.** The gate is measured with the GPU at its loaded clocks, the way the benches run: frames back to back. At 1080p the HDR path moves about 33 MB more per frame: the scene texture is written at 8 B/px instead of D's 4, then the composite reads it back and writes D. At this GPU's ~550 GB/s, that is about 60 µs uncompressed, the same order as the measured delta. The loaded cost is mostly memory traffic, not ALU. When frames are isolated (2–16 ms apart, e.g. a light scene at 60 Hz), the GPU idles at its lowest performance state and every pass costs about 3× more. Direct's latency goes from ~280 µs to ~850 µs, and the Hdr delta grows to +240 to +290 µs. The review traced the composite pass alone at 258 µs there. By post setting, the delta at 2 ms apart measured +241 µs (default), +191 µs (dither off), +172 µs (tonemapper `None`) and +126 µs (`PostProcess::passthrough()`). This is not a gate failure: a scene heavy enough for frame time to matter keeps the GPU at its loaded clocks. It is still the cost of an idle 60 Hz frame, and it is recorded for P-POST, which owns `composite.wgsl` and its [`post.composite`] budget. Two ALU cuts are open there: * On an sRGB `D`, the dither encodes, adds the noise and decodes again, and then the hardware encodes once more: 6 `pow` per pixel. Writing through a non-sRGB view of `D` (the `S3D_POST_OUT = 1` path) needs 3. * The two per-frame seed hashes can be hashed once on the CPU. Allocations per frame by mode (`tests/alloc_frame.rs`: 400 moving lit cubes, CPU draw path, 320×180; all inside wgpu/wgpu-hal; bounds +10 %): | mode | allocations per frame | bound | |---|---|---| | Direct | 76 | 84 | | Hdr (post camera) | 106 | 117 | | Ldr fallback (`no_float_targets`) | 106 | 117 | | Ldr passthrough (render scale 0.75) | 106 | 117 | The one extra render pass (the composite) costs 30 wgpu-hal allocations on Metal; the renderer itself allocates nothing, creates no textures after the first frame and uploads nothing for a still scene (since the round-1 review not even the dither seeds, which go up 64 frames at a time). ### F5 / F6 — render nodes, scene depth, overlay stages Direct mode is unchanged: the engine goldens are bit-exact, and `tests/alloc.rs` still measures 82–86 (CPU path) / 191–195 (GPU paths) / 314.6 (two viewport cameras) allocations per frame. The built-in skybox and distortion-mesh nodes are asked for work every frame (`prepare` once, `prepare_view` per view) and report none; overlay stages are read every frame. None of it allocates. Allocations per frame (`tests/alloc_frame.rs`, same scene as F4): | mode | allocations per frame | bound | |---|---|---| | Direct, Hdr, Ldr fallback, passthrough | 76 / 106 / 106 / 106 (unchanged) | 84 / 117 | | nodes: an Opaque and a Transparent slot in the scene pass, a depth-reading slot in a SceneRead pass | 119 | 132 | The SceneRead pass (one render pass) accounts for about 30 of the 43 extra; `cpu_reallocations`, `buffer_reallocations` and `textures_created` are 0 and live bytes do not grow. `benches/frame.rs` `frame/cpu/direct`, alternating the F4 build and this one on the same machine (load average 5–13, so single runs vary by up to 3×): the quietest pair measured 60.9 µs (F4) and 60.5 µs (F5/F6); `frame/throughput/direct` 112.0 µs (F4 recorded 113.6 µs). The node and overlay-stage bookkeeping is below the measurement noise. ### F-core review — Direct-mode CPU on a loaded machine A review A/B of `render_frame` (main at eb77fef vs `graphics`, same harness, 1080p headless, Direct mode, medians of 120 frames) saw `explicit/200k` on the CPU path at 192 µs vs 206 µs. Wall-clock medians are not usable on this shared machine: the same binary measured 198 µs and 45 µs in consecutive runs (load average 20–110; the process lands on efficiency cores or not). Instructions retired per frame (`/usr/bin/time -l`, slope between 1000 and 3000 frames, so setup cancels; includes the Metal driver and the GPU wait) do not depend on the load: | scene (CPU path) | main | graphics | delta | |---|---|---|---| | 200k explicit instances, 1 batch | 662 k | 657 k | −0.7 % | | 10k ECS cubes, 7 batches | 5.30 M | 5.18 M | −2.2 % | | empty (camera only) | 548 k | 559 k | +2.0 % (+11 k: plan, nodes, overlay stages, post bookkeeping) | Direct mode costs the same work per frame as before the upgrade, plus a fixed ~11 k instructions (a few µs). The ±5 % gate on `benches/instancing.rs` still needs its wall-clock re-run on a quiet machine before Phase I records final values. ### M1 review — upload ring, honest HDR bench, GPU gates **Staging churn (fixed).** `Uploader::recall` trimmed idle staging chunks to twice the recent per-frame peak and ignored the chunks still in flight. With frames queued on the GPU (an unpaced `App::update` loop), every frame's chunk is still in flight when the next frame allocates, so a still HDR scene — whose only upload is the composite's 16 bytes of per-frame dither and grain seeds — created and dropped a 4 MiB `MAP_WRITE` chunk every few frames (0.5–1 ms of CPU and an `Arc` each: 100–230 per 1200 frames in the review's trace). The ring now also keeps what the queue depth needs (the busiest frame times the deepest queue of the last one to two 512-frame windows, plus one), so it grows to the depth once and then creates nothing; the chunks of a one-off stall are released within two windows. `RenderStats::staging_chunks_created` counts the chunks created per frame. `tests/alloc_frame.rs` renders a still Hdr scene the way `App::update` does (the frame counter advancing, a GPU wait every 8th frame): 7 chunks created in 1200 frames (all while the queue first deepens), 148 allocations per frame (the seed upload's copy and re-map inside wgpu; 106 when nothing is uploaded), bound 165. **The frame bench now uploads the seeds.** `benches/frame.rs` advanced nothing between frames, so its Hdr frames uploaded no seeds and hid both the churn and the upload. Its `render` helper now advances `Time::frame` like `App::update`. `frame/ab` at load average 9–12 (this machine was slower than at F4: Direct CPU 90–98 µs instead of 67–75): | `frame/ab` (medians, µs) | Direct | Hdr minimal | paired delta | same, seeds not uploaded | gate | |---|---|---|---|---|---| | cpu | 89.7–98.1 | 118.3–128.5 | +24.2 to +33.2 | +21.5, +21.6 | ≤ +20 µs CPU | | throughput | 124.5–130.2 | 182.4–184.4 | +50.3 to +58.1 | +31.9, +35.5 | ≤ +0.10 ms GPU | | latency | 295–306 | 395–400 | +84 to +100 | +74 | (upper bound) | The GPU gate holds with the upload (the 16-byte copy costs about 20 µs of GPU throughput in a frame that uploads nothing else; in a frame where anything moves it joins that frame's copies). The CPU gate is at its limit: +21.5 µs without the upload on this slower machine state, about +4 µs more with it (an earlier run, where Direct measured 66 µs, gave +16.0 µs with it). The composite's extra render pass in wgpu-hal is most of it (see F3 / F4). Open: uploading the seeds for a window of frames at once and selecting them with a dynamic offset would remove the per-frame copy. **GPU gates (run alone on an idle Dev GPU; not part of `cargo test --workspace` or CI).** Hosted CI runners have software or paravirtual GPUs, so these are manual Dev-machine gates; each retries a disturbed run (best of 3): ```sh cargo test -p space3d-render --lib bloom_gate -- --ignored --nocapture cargo test -p space3d-particles --lib gpu_100k_within_budget -- --ignored --nocapture ``` | gate | measured at the M1 review (GPU shared: 50–60 % device utilization from other apps) | budget | |---|---|---| | bloom 6 mips @1080p | 0.188–0.265 ms (one of two invocations passed; 0.13–0.16 ms on a quiet GPU) | ≤ 0.20 ms | | particles 100k: sim + compaction, nothing else on the GPU | 0.044 ms (in frames that also draw the 100k billboards: 0.084 ms, reported) | ≤ 0.06 ms | | particles 100k: draw into the HDR scene texture | 0.350 ms (into Direct's 8-bit target: 0.362 ms, reported) | ≤ 0.40 ms | **Bloom CPU.** Bloom's render passes cost about 15 µs of wgpu/Metal overhead each (the renderer's own work per pass allocates nothing): 0.15–0.17 ms of thread CPU per post group at 1080p and above (11 passes; +1.26 M to +1.38 M instructions per frame over the composite alone, measured in an `App::update` loop by the round-1 review; an earlier estimate here said 0.11 ms), about 3× the spec's Battle-scene line "post ≤ 0.05 ms". **That line is not met at M1.** Smaller rects have fewer levels (9 passes at 720p, 5 at 180p). The planned fix is a compute chain (one compute pass of dependent dispatches on class A backends; the render-pass chain kept for WebGL2), after M1. ### M1 review, round 1 — frame pacing, gates at M1 close **Frames in flight (fixed).** Nothing paced `render_frame` without a window: in an `App::update` / `step_ticks` loop (the engine's test pattern, headless batch renders) recording ran ahead of the GPU without bound (Metal queues up to 4096 command buffers), every queued frame kept its command memory, and the staging ring grew with the queue. `render_frame` now keeps at most three frames in flight: after submitting a frame it waits for the one submitted three frames earlier (native only; the browser paces its frames). With a window, presentation already paces frames and the wait returns at once. The review's harness (1920×1080, 2400 unpaced `App::update` frames, then 1200 paced ones; release; load 4–10), before → after: | scene | staging chunks, before / after | footprint before (frame 300 → 2400) | footprint after | µs per frame, frames 300–2400, before / after | |---|---|---|---|---| | Direct, still | 1 / 1 | 882 → 1105 MB | 504 → 507 MB | — | | Hdr minimal, still | 137 (still growing) / 4 | 924 → 2276 MB | 550 MB flat | — | | Hdr + bloom, one cube moving | 138 / 4 | 1709 → 6435 MB | 696 MB flat | 492 / 316 | | bloom + GPU particles 100k | 122 / 4 | 2034 → 6000 MB | 745 MB flat | 568 / 469 | | bloom + CPU particles 16k | 10 / 5 | 886 → 865 MB | 685 MB flat | 487 / 472 | Throughput does not suffer: three frames in flight keep the GPU busy. `tests/alloc_frame.rs` "hdr moving, unpaced" renders 1500 frames of 400 moving cubes without waiting: no staging chunk is created after the first 100 frames (5 were without the pacing), 148 allocations per frame (bound 167). (The harness figures above predate the seed window below.) **Post seeds, a window at a time.** The composite's dither and animated-grain seeds changed every frame and were the only upload of a still Hdr scene: a 16-byte staging copy per post group and frame (about 3–4 µs of CPU, and 20–40 µs of GPU throughput for the copy in an otherwise idle frame). They now go up 64 frames at a time — one aligned uniform slot per frame and post group, selected with a dynamic offset (`SeedWindow`, post/mod.rs) — the seeds themselves unchanged (spec §4.3; the goldens are bit-exact). A still scene uploads nothing in 63 of 64 frames (`tests/alloc_frame.rs`: 18 uploading frames in 1184). **Allocations of the 1080p bloom chain.** `tests/alloc_post.rs` measures bloom at 1920×1080 again (the 6-level chain of 1080p, 11 bloom passes; 1440p and 4K add the resample pass): 332 allocations per frame, pinned at +10 %, besides the 3-level chain at 320×180 (234 since the resample pass of the M1 review's round 2; 211 before). **Gates at M1 close** (Dev machine, 1080p headless): | gate | measured | status | |---|---|---| | Hdr minimal over Direct, CPU ≤ +20 µs | `frame/ab`, round 1, with the seed window: +13.2, +14.9, +14.9, +15.3, +16.6 µs (load 6–7); the same build still copying the seeds every frame: +13.8 to +18.4 µs (load 5–6); the review: +19.3 to +31.8 µs, 4 of 5 runs over (load 7–22) | met on a quiet machine with little margin; heavy load pushes it over. The composite's extra render pass is most of it | | Hdr minimal over Direct, GPU ≤ +0.10 ms | +31.9 to +37.8 µs throughput with the seed window (+55.6 to +59.9 µs with the per-frame seed copy) | met | | bloom 6 mips @1080p ≤ 0.20 ms | 0.150–0.159 ms, 3 of 3 invocations (device utilization ≈ 40 %); the review: 0.222–0.261 ms, 0 of 3, with another app keeping the GPU 49–57 % busy | met on an idle GPU; a shared GPU pushes it over | | Battle CPU "post ≤ 0.05 ms" | bloom alone 0.15–0.17 ms of thread CPU per post group | **not met** (compute chain after M1) | In real frames bloom costs more GPU than the isolated chain the gate times: Hdr + bloom minus Hdr minimal throughput measured +244 µs at load 7.6 and +384 µs at load 40 in the review's own harness (the chain plus the composite's bloom reads, against a GPU shared with other work). `frame/ab` has the `hdr_bloom` mode since M1.1 (below) to reproduce it from the tree. **Particles.** Emitters moved after the tick get a render-time bridge (particles.md "Time model"), built on the CPU on both backends: about 25 ns per bridged trail glow and 45 ns per exhaust particle on one thread — 25–30 µs for 20 bolts at 3200 units/s moved a frame after the tick, 0.10–0.12 ms for a Battle fleet of 300 exhausts and 20 bolts (2260 particles; 0.15 ms before the M1 review's round 2 made the spawn math cheaper) — and, on the GPU backend, one direct draw per layer and an upload per frame (`tests/alloc.rs`: 307 allocations per frame, was 304). Moved in `Stage::Update`, as SpaceCorps2027 moves ships and bolts, that fleet costs the particles node about 0.29 ms of render-thread CPU per frame against 0.14 ms moved in `FixedUpdate` (1080p, HDR + bloom; 0.35–0.44 ms before), so the Battle scene's "particles prepare ≤ 0.1 ms" line is missed about 3× until the bridges move to the GPU (particles.md, "Bridges are not free"). ### F7 / F8 and M1.1 — depth views, GPU timings, bloom memory `cargo bench -p space3d-render --bench frame -- frame/ab` (1080p headless, release) now interleaves four modes — Direct, Hdr minimal, `hdr_bloom` (`PostProcess::default()`: the composite and the default bloom) and `depth_view` (Direct plus one 2048² depth view of the scene's 400 cubes and ground plane, injected with `space3d_render::testing`) — and prints each mode's GPU timings per pass (`FrameSettings::gpu_timing`) and the bloom chain's GPU time at other sizes. Two runs at load average 29–33 (other builds on the machine); medians in µs, paired deltas against Direct in brackets: | `frame/ab` | Direct | Hdr minimal | Hdr + bloom | depth view | |---|---|---|---|---| | cpu, load 29 | 78.0 | 100.0 (+19.8) | 271.1 (+179.5) | 110.0 (+36.7) | | cpu, load 33 | 207.1 | 243.4 (+39.0) | 697.8 (+489.3) | 227.1 (+45.9) | | throughput, load 29 | 130.8 | 163.8 (+33.1) | 420.3 (+293.9) | 172.8 (+43.3) | | latency, load 29 | 293.8 | 377.8 (+76.3) | 701.7 (+400.2) | 379.0 (+76.9) | | GPU timings, load 29 (ms) | cull 0.013, scene 0.048 | + post.composite 0.099 | + post.bloom 0.216, post.composite 0.068 | + shadow 0.024 | **Bloom CPU, one figure.** Bloom adds 0.15–0.18 ms of render-thread CPU per post group at 1080p over the composite alone (the M1 record 0.15–0.17 ms; +0.16 ms in the load-29 run above; the load-33 run, +0.45 ms, shows how far very heavy load pushes it). `docs/graphics/post.md` and `docs/graphics/frame.md` quote this figure (post.md said about 0.10 ms, frame.md 0.10–0.17). The Battle line "post ≤ 0.05 ms" stays not met (compute chain). **Bloom by size** (`post.bloom` in frames, medians of 48, load ≈ 30): 720p 0.196 ms, 1080p 0.227 ms, 1440p 0.254 ms, 4K 0.607 ms, the `GraphicsQuality::Low` chain at the T3 rect (1440 × 810, 4 levels, 270 cap) 0.122 ms. The half-rect prefilter of the M1 review's round 2 costs GPU time wherever the half rect is larger than level 0 (the round-3 review's interleaved sweeps, best-of chain times: +4 % at 1440p, +25 % at the Low rect, +40 % at 4K, nothing at 1080p); post.md's claim that the chain's time was unchanged held at 1080p only and is corrected. Capping the prefilter target at twice level 0, the review's suggestion, changes nothing at these sizes (the half rect is at most twice level 0 there); a cheaper prefilter kernel would change the halo, so the cost is recorded, not traded. **Bloom memory** (M1.1 review finding: `target_bytes` counted 2.8 MB). `tests/footprint.rs` (`cargo test -p space3d-render --release --test footprint -- --ignored --nocapture`; macOS; each scene in its own process, 1080p, footprint after 600 frames): | scene | one frame in flight | three frames in flight | `target_bytes` | render passes | |---|---|---|---|---| | Direct | 490.0 MB | — | 0 | 0 | | Hdr minimal | 512.2 MB | 540.8 MB | 24.9 MB | 1 | | Hdr + bloom | 571.7 MB | 688.4 MB | 27.6 MB | 12 | | depth view 2048² | 513.4 MB | — | 0 (the map: 16.8 MB) | 1 | | raw wgpu, 1 / 11 empty passes into 32 × 32 | 453.7 / 481.6 MB | — | — | 1 / 11 | Each Metal render pass holds about 2.8 MB of driver memory per frame in flight, independent of its attachment's size: bloom's chain holds +59.5 MB paced and +147.6 MB unpaced against +2.7 MB of textures, as the review measured (56–61 / 151 MB). Counted now: the docs (frame.md "Cost", post.md) state `target_bytes + render_passes × 2.8 MB × frames in flight`, the spec's §4.4 VRAM lines are amended, and the footprint test fails above 80 MB (paced) or 200 MB (unpaced) of bloom. Not reduced: every chain level is its own render pass (a level is read while the next is written), and the renderer's frames in flight follow the window (two to three); the reduction is the planned compute chain (one compute pass of dependent dispatches, about one pass's memory), the same follow-up as bloom's CPU. **Depth views** (F7): one 2048² map adds 0.024 ms of GPU (`shadow`), +37 to +46 µs of CPU per frame (culling of the casters, one pass, their draws) and 23 MB of process memory (the map and its pass). `tests/alloc_frame.rs` "depth_views": 103 allocations per frame on Metal (Direct 76 + the depth pass), bound 113; the renderer's own work allocates nothing, a still scene uploads nothing (`tests/depth_views.rs`), and GPU paths add no culling dispatch. **GPU timings** (F8): `tests/alloc_frame.rs` "timings": 100 allocations per frame on Metal (Direct 76 + timestamp writes, the deferred resolve and the two callbacks wgpu boxes per timed frame), bound 110; off, timing costs nothing. ### PO5 / PO6 — distortion, the all-post gate Recorded by the post area (P-POST, M2; `benches/post.rs`, `docs/graphics/post.md` "Hardening"). Dev machine, release, 1080p headless, load average 11–13 from other builds. | gate (spec §4.4) | measured | result | |---|---|---| | all post on (AE compute, bloom, FXAA, CA, grain, grading, LUT, distortion) ≤ 0.60 ms | `post/gate`: 0.387 ms, the paired throughput delta against Direct (frames back to back, interleaved rounds; measured like "Hdr minimal over Direct"); the whole frame takes 0.49 ms of throughput | met | `post/ab` (throughput per frame over Direct, µs): composite +45.9, bloom +236.8, bloom + distortion (two shockwaves and a haze) +264.0, every effect +387.9. The per-pass timestamps of the same frames sum to 1.0–1.3 ms: on Apple GPUs a pass's scope includes its overlap with its neighbours (bloom's scope reads 0.17 ms alone and 0.30–0.39 ms inside the full chain), so they are reference figures, not the gate. Distortion: one render pass (the Distortion pass's own scope 0.05 ms at 1080p, 0.52 ms at 4K), 2.1 MB of buffer at half resolution, 33 allocations per frame on Metal (`tests/alloc_post.rs`: 267 with bloom; every effect 351). Render-stage CPU (`post/cpu/*`): composite 0.12 ms, bloom 0.26 ms, every effect 0.25 ms — post's CPU line of the Battle budget (≤ 0.05 ms) is still not met; bloom's 11 render passes are most of it. ### P-MAT PM1 / PM2 — material maps, blend modes, glTF import Dev machine as above; measured while other builds kept the machine busy (load averages 12–39), so every figure is an interleaved A/B against a pre-materials build (the `instancing` bench binary of `graphics` at 62a28d8) run in the same minutes. | gate / measurement | measured | status | |---|---|---| | ECS 100k static PBR entities ≤ 2.5 ms (`materials/ecs_pbr/100k`: 4 meshes × 8 materials with ORM, normal and emissive maps and a UV transform, render stage, camera looking away) | 2.23 / 2.35 / 2.34 ms | met | | Direct mode unchanged, `extract_upload/ecs_static_mixed/100k` (map-less materials) | 2.13 / 2.21 / 2.22 ms against 2.10–2.27 ms for the pre-materials binary in the same rounds | within noise (the first version of the material key cost +0.8 ms: the per-entity fast path now compares the material field by field without branches, and the cache holds materials, so only real misses build a key) | | `materials/transparent_sort/4096` (one 4096-instance alpha batch sorted back to front per frame, camera moving; whole frame) | 0.38–0.41 ms per frame | recorded (the sort is a u64 `sort_unstable` of depth keys; no allocation) | | steady-state allocations with every PM1/PM2 feature (`tests/alloc_materials.rs`) | 100 per frame on `CpuDirect`, 195 on the GPU culling paths, constant; 0 in the renderer; live bytes +0 over 90 frames | bound 110 / 215 | | static scene with maps (`tests/materials.rs`) | 0 bytes uploaded, 0 textures created once warm | met | Not measured yet: the GPU cost of a full screen of mapped pixels (the gate "all maps + IBL + PCF9 ≤ +0.20 ms" needs PM4/PM5; the maps are sampled behind uniform branches, so map-less materials run the original instruction stream). ### P-MAT PM3 / PM4 — skybox, image-based lighting Dev machine (M4 Max, Metal), release, 1080p headless, frames back to back; load averages 7–33 from other lanes' builds and GPU tests. Commands: `cargo test -p space3d-render --release --test environment -- --ignored --nocapture ibl_bake_gate` and `... forward_full_screen_gate`. | gate / measurement | measured | status | |---|---|---| | IBL bake ≤ 3 ms one-time (spec §4.4 T1; 1024² LDR faces → 256² specular + 32² irradiance; `ibl.bake` GPU scope, medians of 5 cubemaps) — default path: compute dispatches | upload (mip chain, 10 dispatches) 0.18–0.32 ms + bake (7 dispatches) 0.52–0.95 ms = **0.69–1.26 ms** over 5 runs | met | | the same on the fragment path (WebGL2's; `no_compute` on Metal): a render pass per face and mip | upload 60 passes 1.0–1.2 ms + bake 42 passes 2.2–7.1 ms = **3.4–8.2 ms** | recorded (T3 budget ≤ 50 ms total, ≤ 8 ms per frame with `bake_passes_per_frame`) | | per-pass cost on Metal | a 64² cubemap's 66 near-empty passes: 4.2–10.8 ms at load 30, 0.54 ms as 7 compute dispatches | the reason for the compute path | | forward full-screen lit pixels, all maps + IBL (+ PCF9 with PM5) vs today's shader ≤ +0.20 ms (a plane filling 1080p, sun + 4 point lights; legacy Classic material without maps or environment vs base color, normal, ORM and emissive maps at 1024², Standard shading and image-based lighting) | `scene` 0.169 → 0.257 ms; median paired difference **+0.088 ms** (3 runs identical; an earlier unpaired run under GPU contention: +0.15 / +0.22) | met without PCF9 (PM5 adds its taps) | | steady-state allocations with PM1–PM4 in use (`tests/alloc_materials.rs`: + skybox, environment, Standard shading) | 114 per frame on `CpuDirect`, 208 on the GPU culling paths, constant; 0 in the renderer; live bytes +0 over 90 frames | bound 125 / 230 (PM2's 100 / 195 + the skybox draw and the 7-binding view bind group) | | still camera with a skybox and an environment (`environment_steady_state`) | 0 bytes uploaded, 0 textures created, 0 bake steps, identical frames | met | | engine goldens (`engine_goldens_are_exact`) | exact: the image-based term and the Standard multiple-scattering factor are behind a uniform branch / an override | met | Memory (not a gate): a radiance cube is `faces² × 6 × 4/3` texels at 4 B (sRGB) or 8 B (`Rgba16Float`): a 1024² LDR sky 33.6 MB, the stories' 512² HDR nebula 16.8 MB; an environment at the defaults 4.2 MB (256² × 6 faces × 6 mips + 32² irradiance, `Rgba16Float`); the BRDF LUT 16 KiB. ### P-MAT PM5 / PM6 — directional shadow, hardening Dev machine (M4 Max, Metal), release, frames back to back; load averages 4–9. Commands: `cargo test -p space3d-render --release --test shadows -- --ignored --nocapture shadow_map_gate`, `cargo test -p space3d-render --release --test environment -- --ignored --nocapture forward_full_screen_gate`, `cargo bench -p space3d-render --bench materials`. | gate / measurement | measured | status | |---|---|---| | shadow 2048², 100k instanced casters ≤ 0.30 ms (`shadow` GPU scope; 100k cube entities — one instanced batch — on a 400 × 400 field, all inside the map, `ShadowFit::top_down`, PCF9; median of 120 frames) | **0.276 ms** (min 0.27, 3 runs) on `GpuMultiDraw` | met | | the same cubes from one explicit `InstanceBuffer` (recorded) | 0.66 ms; its camera `scene` pass is slower by the same factor (0.94 vs 0.63 ms), with a matrix layout too (0.63 ms), on `CpuDirect` more so (1.46 ms) | recorded at PM5; **not reproduced** at the M2 merge (explicit = ECS within noise, see "M2 merge" below): most likely measured under other GPU load | | forward full-screen lit pixels, all maps + IBL + PCF9 vs today's shader ≤ +0.20 ms (as in PM4, plus the sun's 2048² shadow with the 9-tap filter on every pixel) | `scene` 0.169 → 0.288 ms; median paired difference **+0.119 ms** (2 runs identical) | met (the first PCF version, a loop over dynamically indexed vectors, cost +0.24 ms; the unrolled kernels +0.03 ms over PM4) | | ECS 100k static PBR entities ≤ 2.5 ms (`materials/ecs_pbr/100k`) | 2.27 ms | met | | shadow view CPU at 100k ECS (`materials/shadow_view/ecs{,_off}/100k`: the render stage with and without the shadow, camera seeing 4.7k of 100k cubes) | `CpuDirect` 1.59 → 2.00 ms (**+0.40 ms**: the depth view culls every caster on the CPU like a camera); best path (`GpuMultiDraw`) 1.64 → 1.74 ms (**+0.10 ms**, no extra dispatch) | design budget +0.4 ms: met | | the same with one explicit 100k-instance buffer (`…/explicit{,_off}/100k`, `CpuDirect`) | 0.31 → 0.48 ms (+0.17 ms) | recorded | | steady-state allocations with PM1–PM5 in use (`tests/alloc_materials.rs`: + the sun's shadow, refitted every frame to the moving camera, alpha-masked casters) | 151 per frame on `CpuDirect`, 266 on the GPU culling paths, constant; live bytes +0 over 90 frames. With the shadow's `strength` at 0 (light picked, pipelines specialized, no depth view) exactly PM4's 114 / 208: the lighting's per-frame work allocates nothing, the depth pass and its draws are wgpu's 37 / 58 | bound 165 / 290 | | still scene with a shadow (`static_scene_uploads_nothing_with_shadows`, MSAA 4) | 0 bytes uploaded, 0 textures created, 0 reallocations, identical frames; a new `map_size` creates one texture | met | | engine goldens (`engine_goldens_are_exact`) | exact (without a casting light `S3D_SHADOW_TAPS` is 0 and the shadow code is compiled out) | met | Memory: a shadow map is `map_size²` × 4 B (`Depth32Float`): 16.8 MB at 2048², 4.2 MB at 1024², plus one render pass per frame (≈ 2.8 MB of Metal driver memory per frame in flight, see "F7 / F8 and M1.1"). ### M2 merge — gates re-measured on the merged tree (post + materials + particles) Foundation maintainer, `graphics` after merging graphics-post, graphics-materials and graphics-particles (commits 8ae4b22, 4c54e68, f31dfe1). Dev machine (M4 Max, Metal), release, each gate run alone, but the GPU was shared: another app kept it at 72–78 % device utilization (`ioreg` "Device Utilization %") and the load average was 5–8. | gate (spec §4.4) | command | measured | result | |---|---|---|---| | shadow 2048², 100k instanced casters ≤ 0.30 ms | `--test shadows -- --ignored shadow_map_gate` | ECS 0.277 / 0.277 / 0.278 ms (3 runs, `GpuMultiDraw`) | met | | forward full screen, all maps + IBL + PCF9 ≤ +0.20 ms | `--test environment -- --ignored forward_full_screen_gate` | legacy 0.181 → 0.298 ms, paired +0.121 ms | met | | IBL bake ≤ 3 ms (1024² faces) | `--test environment -- --ignored ibl_bake_gate` | compute 0.98 ms (upload 0.32 + bake 0.66); fragment path 5.5 ms (recorded); HDR skies gated since the M2 final review, on a loaded GPU with cold uploads and steps since its verification: 0.3–1.0 ms (below) | met | | all post ≤ 0.60 ms | `cargo bench -p space3d-render --bench post -- post/gate` | 0.405 ms over Direct (throughput) | met | | particles 100k: sim + compaction ≤ 0.06 ms, draw ≤ 0.40 ms | `-p space3d-particles --lib -- --ignored gpu_100k_within_budget` | 0.048 ms; 0.382 ms into the HDR scene texture | met | | bloom 6 levels at 1080p ≤ 0.20 ms | `--lib -- --ignored bloom_gate_1080p` | best 0.193 ms in the first invocation; 0.211 and 0.232 ms (best of 3 runs each) in the next two | soft: the test's own note says 30–70 % device utilization from other apps reads 0.19–0.30 ms; the lane measured 0.15–0.17 ms on an idle GPU | **Explicit instance buffers vs ECS** (PM5 recorded explicit buffers as 2.4× slower in every pass): not reproduced. The same 100k cubes from one `InstanceBuffer`: shadow pass 0.275 ms vs ECS 0.277 ms on `GpuMultiDraw`, 0.324 vs 0.275 ms on `CpuDirect`; the camera's `scene` pass 0.46–0.51 ms for both, on both paths (3 runs each). Allocations per frame: every allocation test (`space3d-render` `alloc`, `alloc_frame`, `alloc_materials`, `alloc_post`; `space3d-particles` `alloc`; `space3d-core` `alloc_transforms`) passes its lane's bound on the merged tree, on Metal and on ANGLE (GL). ### Phase I — the Battle reference scene and the quality presets Integration builder, `graphics` after the M2 merges. The reference scene of spec §4.4 is `space3d_stories::showcase` (`spawn_battle` + `dress_battle`): 300 ships of three procedural hulls with base color, packed ORM, normal and emissive maps (one material per faction: 9 instanced batches), 60 asteroids, the nebula sky as `Skybox` and `EnvironmentLight`, one sun with a `DirectionalShadow` (`ShadowFit::top_down`) and a shadowless fill light (M2 final review), the particle load of `space3d_particles::testing::battle` (900 engine exhausts, 64 ribbons, 16 beams, 30 explosions a second with their light flashes — 41 point lights —, hits, shield ripples, warps' shockwaves), `battle_look()` (AgX punchy, +0.5 EV, bloom, vignette) and two 256² render-target ship previews (4× MSAA, no post). The egui HUD of windowed runs is not part of the reference (the stories and the example show the previews through a HUD camera; the perf harness leaves it out: it costs 0.08 ms of CPU). Measured with `cargo test --release -p space3d-stories --test perf_graphics -- --ignored --nocapture` (`battle_dev_gates`; `cargo bench -p space3d-stories --bench graphics -- graphics/report` prints the same), 1920 × 1080 headless, Apple M4 Max, Metal, content of 1024² hull maps and 1024² sky faces, 240 warm-up frames, medians of 60 frames. The machine was shared: another session ran the game (≈ 120 % CPU) and an iOS simulator app (≈ 100 % CPU and its Metal host), load average 6.8–7.4. Three runs, every tier, High passing both gates each time: | tier | GPU frame (frozen-frame throughput + particle sim) | CPU `render_frame` (back to back / after an idle GPU) | render passes | targets | particles alive | |---|---|---|---|---|---| | **High** (gates) | **1.49 ms** (1.27 + 0.22) | **1.45 ms** / 1.39–1.43 ms | 19 | 133.5 MB | 101 800 | | Medium | 1.39 ms (1.21 + 0.18) | 1.38–1.41 ms | 16 | 129.3 MB | 61 000 | | Low | 0.71–0.75 ms (CPU particles) | 0.77–0.78 ms | 13 | 25.3 MB | 5 300 | | Ultra | 1.48–1.50 ms (1.26 + 0.22) | 1.43–1.47 ms | 18 | 129.3 MB | 101 800 | Gates (spec §4.4, Dev): **Battle total GPU ≤ 3.0 ms — met (1.49 ms)**; **CPU `render_frame` ≤ 1.5 ms — met at 1.45 ms, a 3 % margin** on the shared machine (the first measurements, with the previews post-processed and the HUD camera, read 1.85 ms: see below); **frame and post targets ≤ 220 MB (T1/T2) — 133.5 MB** (`RenderStats::target_bytes`; asserted by `battle_steady_state`, which also checks no CPU reallocations and no textures created over 30 steady frames, 0 GPU errors). Draws: 12 built-in (hulls, rocks, sky; 4 of them shadow) + 114 particle draws; 1 post group. How the GPU frame is measured: the frozen frame (no ticks) rendered back to back is the frame's throughput — the GPU's time when the GPU is the slower side, else the CPU's — and the particle simulation passes that only ticking frames record (`particles.sim`, `.compact`, `.sort` timestamps, 0.22 ms) are added. Pass scopes of a ticking frame (they overlap on Apple GPUs, so their sum, 4.0 ms, overstates the frame): cull 0.023, shadow 0.046, scene 0.227, depth resolve 0.231, scene_read 0.693, distortion 0.584, post.bloom 0.748, post.composite 0.756, particles.sort 0.127 ms. Where the CPU goes (High, `sample` of the release build, `render_frame` = 100 %): * **58 % wgpu's command encoding** (`CommandEncoder::finish`: wgpu 30 records passes and encodes them to Metal at `finish`): beginning the 19 render passes (27 % of it), **wgpu's indirect-draw validation** (`VALIDATION_INDIRECT_CALL`, on in release by default; 25 % of it — the particles draw with 100+ indirect draws), draws and binds. Every render pass costs about 15–25 µs of CPU: the first version of the scene post-processed the two previews (two more bloom chains and composites: 41 passes) and measured 1.85 ms; the reference scene's previews are one pass each (spec §4.4: "RT 2"), 19 passes in all. With `WGPU_VALIDATION_INDIRECT_CALL=0` the same frame takes 1.33–1.35 ms (not a default: it guards GPU-written indirect arguments). * **35 % the particle node's `prepare`** (≈ 0.5 ms; spec budget 0.1 ms for the GPU backend): the tick replay's uploads (a ticking frame uploads **2.3 MB**, 2.3 MB of it particles: mostly the CPU-built ribbon and beam strips, 40 B a point, rebuilt every frame), emitter transforms of the 900 moving engines, the entry tables, and bounds. The particles lane's own gates (100k sim + compaction ≤ 0.06 ms GPU, draws ≤ 0.40 ms) are GPU gates and are met. * The rest (extraction, planning, lighting, post planning, the scene passes' own recording): under 0.1 ms. Levers, if the CPU gate needs margin on slower machines: incremental strip uploads (only the points that moved) and a GPU strip builder in the particles lane; batching the particles' indirect draws (one multi-draw per pipeline); turning off wgpu's indirect validation for engine-written arguments (a foundation decision); fewer passes (the compute bloom chain the post lane lists). Visual check: every Showcase golden (`Engine/Showcase/{SpaceCorps Look, Battle, WebGL2 SpaceCorps Look, WebGL2 Battle}`) and the example's headless 1280 × 720 PNG (Medium, recommended for the M4 Max as an integrated GPU) were inspected. ### M2 review — fixes and the gates they touch Graphics maintainer, `graphics` after Phase I, answering the M2 reviewers and the game's M1 feedback (game#1–#15). **Direct mode, `benches/instancing.rs` (spec §4.4, ±5 % of F0).** The review measured `extract_upload/ecs/100k` (100k *moving* ECS entities, `CpuDirect`) at 1.91–2.04 ms against F0's 1.66–1.76 ms in interleaved same-machine runs, and bisected the jump to the materials merge (4c54e68); explicit instance buffers and the static paths are within noise. Cause: the `Material` component the spec extends (§2.7, +12 fields) grew from 64 to **160 bytes** (`size_of::()`), and extraction reads each entity's material in full every frame to intern it (the branch-free `same_material` compares every field against the last material; any field may differ): about 10 MB more memory traffic per frame at 100k, 2.5 ns per entity. The intern path is already a one-compare fast path; there is no change detection to skip the read. The gate is relaxed for that path (spec §4.4 amendment: within +20 % of F0, recorded here); 100k+ moving instances belong in `InstanceBuffers`. **VRAM (spec §4.4, T1/T2 ≤ 220 MB).** `RenderStats::target_bytes` did not count the shadow map although `battle_steady_state` said so; it does now, and `RenderStats::lighting_bytes` counts the lighting area's cubemaps and baked environments. The Battle at High, 1080p: **146.0 MB** of frame, post and shadow targets (the 2048² shadow map 16.8 MB; the bloom chain lost its 1280 × 720 resampled level, below) and **83.9 MB** of sky and IBL — the 1024² HDR sky is `Rgba16Float` with mips (67 MB), twice the spec line's 33 MB for a 4-byte format. 230 MB of textures plus the 23 MB particle pool: **not met, by the sky's format** (lever: HDR cubemaps in `Rg11b10Ufloat` where renderable, deferred). Process memory adds the per-pass driver memory of the M1.1 amendment (≈ 2.8 MB per render pass per frame in flight on Metal: the review measured 550 MB of frame-related `phys_footprint` at High, 240 MB of it post). `battle_steady_state` now asserts the two parts (≤ 150 MB and ≤ 90 MB) instead of claiming the 220 MB line. **Battle CPU sub-budgets (spec §4.4: particles `prepare` ≤ 0.1 ms, post ≤ 0.05 ms).** Not met: the review measured `render_frame` 1.42–1.47 ms at High (the top-line 1.5 ms gate met) with particles ≈ 1.05 ms of it (the node's `prepare` ≈ 0.5 ms and its 2.3 MB of strip uploads per ticking frame) and post ≈ 0.38 ms (the bloom chain's render passes). Recorded as not met in the spec; the levers — a GPU strip builder with incremental uploads, the compute bloom chain, no wgpu indirect validation for engine-written arguments — are deferred. The Battle now has 18 render passes at High (19 before: the bloom resample is gone). **Bloom chain at High vs Ultra (1080p).** High's 720 cap made level 0 1280 × 720, resampled *up* from the 960 × 540 prefilter (a bigger target and a pass for no detail), so High cost more than Ultra (19 passes / 133.5 MB against 18 / 129.3 MB). A level 0 is now never larger than half the rect, and Ultra is 8 / 720: at 1080p High runs 7 levels and Ultra 8 at 960 × 540 (13 and 15 bloom passes), Ultra one wider level at every resolution. Small groups gain too: a 320 × 192 preview's chain loses its resample pass. **Small post groups (game#15).** `Bloom::min_rect_height` skips the chain for groups shorter than it (UI previews: 240): four 320 × 192 previews with post next to a 1280 × 720 main view were 47 render passes, 5 post groups; with bloom off on them 15 (post.md, "Small views"). **`ParticleStats::cpu_reallocations` in the steady state.** It flagged frames without any allocation: the runtime compared `HashMap::capacity()` of its entity map, which moves with tombstones as emitters come and go. The map now counts only a capacity beyond any seen before (a real reallocation; `runtime::tests::emitter_churn_counts_no_reallocations`), and `battle_steady_state` asserts 0 over 30 frames after the battle's load has built up (6 s; the growth of pools and scratch buffers while explosions, missiles and smoke accumulate over the first 5 s is warm-up). ### M2 review, round 1 — steady state off High, the budget without a renderer, VRAM, CA Graphics maintainer, answering the second round of the M2 review. **`ParticleStats::cpu_reallocations` off High on Metal.** `battle_steady_state` failed on ANGLE (1 reallocation in the 30 measured frames), and long runs at Low and Medium on Metal flagged reallocations 10–22 s in (Low: 7 of 1500 frames after a 10 s warm-up, Medium: 2). They were real: the Battle's load is random (hits, bolts and missiles by tick hash), so it keeps setting small new peaks, and the collections whose length the effect instances, layer instances or ribbon tracks bound — the instance and entry free lists, the pool's free ranges, the finish list, the entity map, the CPU simulation's per-instance and per-entry tables, the CPU sort's buffers — grew on their own at each new peak of their own length long after the instance and entry tables had stopped growing. They are now reserved with those tables (the entity map at most half full, so its tombstones rehash it in place): the same probe (960 × 540, 600 warm-up ticks + 1500 frames) flags nothing at Low, Medium and High on Metal and at High on ANGLE. `battle_steady_state_low_and_medium` runs Low and Medium for 900 frames after ten seconds on every backend. **The budget with the renderer held aside (spec §4.3).** The tick sized the particle pool for the GPU budget whenever no `Renderer` was in the world — `TestApp::render_on_demand` (every story), the web runner's frames while its renderer is created — even with `DownlevelOverride::webgl2()`, and the rings it reserved then stayed once the CPU backend took over (the Battle at High with webgl2 on demand: 165 971 slots reserved against a budget of 16 384; the GL story runs simulated their CPU backend in a GPU-sized pool). The tick now reads the device from the renderer, the `RendererDevice` a held-aside renderer leaves, or the last device it saw; `no_compute` resolves to the CPU backend without a device; before any device the budget is the smaller one. `tests/determinism.rs::the_budget_is_the_same_on_demand_and_every_tick`. **VRAM (spec §4.4, T1/T2 ≤ 220 MB): met.** HDR radiance cubes are `Rg11b10Ufloat` where it renders and filters (`GraphicsCaps::compact_hdr_format`), else `Rgba16Float`: the Battle at High, 1080p, has 146.0 MB of targets and shadow + 50.4 MB of sky (33.5 MB) and IBL = 196.4 MB of textures, 219.4 MB with the 23 MB particle pool (230 + 23 before). The sky's pixels move by at most 3–4 levels of 255 after tonemapping. GL keeps `Rgba16Float` (83.9 MB of sky and IBL). Process memory keeps the per-render-pass driver memory of the M1.1 amendment on top. **Chromatic aberration.** Round 0's spectral split ran up to 25 taps a pixel apart wherever the split exceeded 1.5 px, most of the frame at typical intensities: the composite at 1080p (minimum `post.composite` GPU time over about 160 frames per setting, interleaved) cost 0.098 ms at CA 0.03, 0.126 at 0.15, 0.150 at 0.25, 0.199 at 0.5 and 0.248 at 1.0. With taps at most 1.5 px apart and at most 17: 0.098, 0.119, 0.137, 0.172, 0.202 (no CA: 0.091). **Particle uniforms on WebGL2.** Chrome's WebGL2 on ANGLE / Metal reports a 32-byte uniform offset alignment (256 natively): the particle node's 112-byte per-layer parameters, placed at multiples of the alignment, overlapped and overran their buffer (a validation error on the showcase's first WebGL2 frame in the browser). They are strided by their size rounded up to the alignment now. The showcase's web page renders into its own canvas and takes `?webgl2` to test that path in a browser with WebGPU. **Battle gates after round 1** (release `battle_dev_gates`, three runs at a load average of about 20): High GPU frame 1.59 / 1.59 / 1.56 ms (gate 3.0), CPU `render_frame` 1.48 / 1.46 / 1.48 ms (gate 1.5); Medium 1.49 / 1.48 / 1.45 GPU, 1.48 / 1.43 / 1.48 CPU; Low 0.74 / 0.75 / 0.71 GPU, 0.76 / 0.79 / 0.80 CPU. The 1.5 ms CPU line is met with little margin, as the review found: the particles' `prepare` (≈ 1 ms with its strip uploads) and post (≈ 0.35 ms) sub-budgets stay not met, their levers (a GPU strip builder with incremental uploads, the compute bloom chain) deferred (spec §4.4 amendment). Round 1 adds no per-frame work: the companion reservations run only when an instance or entry table grows, the velocity smoothing is a few multiplies per emitter per tick. ### M2 final review — HDR sky bake, shadow fill, T3's particle budget Graphics maintainer, answering the M2 final review. Dev machine, release; load averages 14–40 from other processes (a simulator app and a Python job at 100 % each), so pairs of runs are interleaved with the previous commit (8b324fe) built alongside. **IBL bake of HDR skies (spec §4.4: ≤ 3 ms one-time).** Round 1 made HDR radiance cubes `Rg11b10Ufloat` for the VRAM line, but core WebGPU cannot write that format from compute, so their conversion and mips fell back to a render pass per face and mip (66 for 1024² faces, after a copy through a temporary `Rgba16Float` cube). The review's probe (the showcase's 1024² sky with its environment, `ibl.bake` GPU scope, upload and bake in one frame) measured 9.6 ms at High, 74 steps, against 1.1–1.2 ms and 18 steps before round 1; `ibl_bake_gate` measured LDR faces only. Where the adapter writes `Rg11b10Ufloat` from compute (`GraphicsCaps::compact_hdr_storage`, requested through `Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`: Apple GPUs, most Vulkan and D3D12 drivers) the compact cube is converted and mipmapped by one dispatch per mip again; elsewhere with compute (WebGPU) HDR skies stay `Rgba16Float` (`GraphicsCaps::hdr_sky_format`: +33.5 MB for a 1024² sky rather than 66 render passes once; 8-bit skies are unaffected). | measurement | before | after | |---|---|---| | the review's probe, showcase sky 1024², High (steps, `ibl.bake`) | 74 steps, 9.6–9.7 ms | 19 steps, 1.46 ms | | the same at Low / Medium / Ultra | 8.5–8.9 / 9.0 / 9.9–10.4 ms | 0.42 / 0.55 / 1.92 ms | | `ibl_bake_gate`, 1024² LDR faces (upload + bake, medians of 5) | 0.98 ms | 0.55, 1.14 ms (two runs) | | `ibl_bake_gate`, 1024² HDR faces (`Rgba16Float` source, new) | — | 1.85, 1.82 ms (11 + 7 dispatches) | | `ibl_bake_gate`, 4096 × 2048 HDR panorama (new) | — | 2.15, 1.95 ms (12 + 7) | | fragment path (WebGL2's, recorded): LDR / HDR faces / HDR panorama | — | 4.0–8.3 / 8.8–9.4 / 7.4–9.6 ms | | Battle VRAM at High, 1080p (`battle_steady_state`) | 196.4 MB | 196.4 MB (sky + IBL 50.4 MB) | **Shadow fill.** The showcase lit shadowed sides with the nebula's irradiance (≈ 0.03) × 0.7 and a 0.015 ambient: 1.6 % of a sunlit top's light on a side facing away from the sun, 3 % on a top in a cast shadow — black after tonemapping. Diffuse IBL × 6 (`ENV_DIFFUSE`), a shadowless violet `DirectionalLight` at 0.35 against the 2.2 sun (`spawn_fill`) and ambient 0.03 give 15 %, 17 % in a cast shadow, 72 % on a side facing the sun (`showcase::tests::fill_keeps_shadowed_sides_readable`, Metal and ANGLE alike). Cost, with the Look's and Battle's asteroids now 64 × 40 spheres with rock detail maps: the Battle's GPU frame at High 1.52–1.55 ms against 1.46–1.48 ms for the previous commit in four interleaved pairs (+0.04–0.08 ms: the fill in the forward loop, the shadow pass 0.049 → 0.071 ms); CPU `render_frame` 1.46–1.50 against 1.43–1.55 ms (unchanged; gate 1.5 ms, met in every pair at load 14–20; at load 30–40 both commits read 1.54–1.57 ms). **T3's particle budget.** The Battle at Low on the web (8 192, quality 0.125) held 5 s but not 20: the load keeps setting small new peaks, and at 8b324fe it refused 393 layer instances in 20 s from 5.25 s in (seed 1), 307 from 3.1 s (seed 3), 562 from 1.1 s (seed 4), 4 from 16.2 s (seed 2) and 1 185 at 21:9 from the first tick, peaks 6 171–6 780 slots — engine plumes and afterburners among them. With the engines' sparks and heat haze left out below quality 0.3 (`ParticleLayer::min_quality`), their plumes `Normal` in a `Low` effect and an explosion's smoke, embers and debris `Low` in a `High` one (`ParticleLayer::priority`), and quality 0.1 on the web: no refusal in 20 s at 16:9 with any of the four seeds, peaks 4 481–5 187 slots (84 % of the engines' 6 144 at most), every engine in view burning; at 21:9, 103 `Low` layer instances (engine details, combat's leftovers) refused, no plume (`tests/battle.rs::battle_fits_the_web_budget_at_low`). The 5 s table in [particles.md](graphics/particles.md) is re-measured with the ships on seven flight levels. **Other gates on this tree.** `battle_gpu_cost` passes (particle draws 0.300 ms); `battle_steady_state` and `battle_steady_state_low_and_medium`: no reallocations, no textures or render objects created in the steady state. ### M2 final review, verified — the IBL gate, T3 at 21:9, rocks and the lower tiers' shadows Graphics maintainer, answering the verifiers of the M2 final review. Dev machine (M4 Max, Metal), release; load averages 4–10 (a simulator app at 100 % throughout). **`ibl_bake_gate` on a loaded GPU, cold uploads gated, steps pinned.** The gate took medians of 5 cubemaps on a nearly idle GPU. An Apple GPU idling at a low clock runs the same upload and bake 2–5 times slower, at a clock that changes from run to run: the HDR panorama read 1.94–3.18 ms over 20 quiet runs of 1399f68 (3 over the line), and with round 1's render-pass fallback put back (`compact` from `compact_hdr_format`, `Writes::new(compute, false)`: 66 steps for HDR faces) the gate still passed 2 of 6 runs, because the median dropped the cold first upload — 7.6–9.3 ms, what a game pays — while warm ones cost 2.2–3.5 ms. The gate now runs a calibrated compute load of about 4 ms to completion before every frame (it never overlaps the timed passes; the GPU clocks as it does under a game's frames), gates the first cubemap of a fresh renderer (cold) as well as the median of 5, and asserts every upload's and bake's steps against `gate_steps` (one dispatch per mip where compute exists: 10 / 11 / 12 + 7). Ten interleaved runs of each tree: | upload + bake, ms (10 runs) | LDR faces | HDR faces | HDR panorama | gate | |---|---|---|---|---| | this commit, cold / median of 5 | 0.31–0.43 / 0.31–0.40 | 0.51–0.66 / 0.51–0.58 | 0.60–0.97 / 0.61–0.68 | 10 of 10 pass | | round-1 fallback (mutation), cold / median of 5 | 0.31–0.42 / 0.31–0.34 | 7.29–8.34 / 1.46–2.47 | 7.99–9.53 / 2.14–2.69 | 10 of 10 fail: steps (66, 7) and (67, 7), and the cold uploads | | fragment path (WebGL2's, recorded), cold / median | 8.2–10.1 / 2.8–3.5 | 8.1–10.1 / 2.9–3.5 | 9.6–11.4 / 3.6–4.5 | — (T3: ≤ 50 ms total, ≤ 8 per frame) | Under the load the cold upload costs what a warm one does (the fix's cold samples over 3 ms at 1399f68 were the idle clock, not the first upload), while the fallback's cold upload stays at 7–9 ms: its first render passes into a fresh cube. The unit test `lighting::tests::hdr_sky_upload_steps_and_format` keeps catching the fallback as well (42 steps for 7). **The Battle's CPU gate.** `render_frame` at High reads 1.33–1.42 ms in quiet windows (3 runs; GPU frame 1.47–1.65 ms), 2–11 % under the 1.5 ms line, and anything else on the machine only adds. A High window over a line is now measured again, up to three windows of 60 frames, and each figure's best window is gated: a regression fails all three, a burst from another process one (forced with `SPACE3D_PERF_BUDGET_SCALE=0.85`: 1.361, 1.339, 1.401 ms, gated 1.339). **T3 at 21:9, every seed.** `battle_fits_the_web_budget_at_low` ran 21:9 with seed 1 only and counted engines in a 16:9 frame at the last tick. It now checks the frame's own aspect ratio every 10th tick and runs 21:9 with seeds 1–4: seed 1 refuses 103 layer instances, seed 4 refuses 226 and shrinks 3, seeds 2 and 3 none; with every seed no engine in view goes dark at any tick checked and every explosion plays. 16:9 is unchanged (no refusal, peaks 4 481–5 187 slots). **The WebGL2 stories run the web's particles.** `WebGL2 SpaceCorps Look` and `WebGL2 Battle` used native Low's settings (16 384, quality 0.25) where the web build uses 8 192 and 0.1; they now use `ParticleSettings::for_quality_web(Low)` (goldens re-blessed: fewer sparks and debris, a smaller explosion cloud). **Rocks without a pole.** The asteroids were 64 × 40 UV spheres: at the poles `u` collapses and the tiling detail maps pinched into a radial starburst (the Look's hero rock at tick 10). They are now cube spheres, 6 × 20 × 20 quads (4 800 triangles and 2 646 vertices against 5 120 and 2 665), each face one tile of the maps. The maps' noise has border-symmetric lattice values (`noise2_border_symmetric`): along every tile border it is the same function in every orientation and flat across it, so faces meeting turned or mirrored join without a seam (`showcase::content::tests::{asteroids_are_closed_and_welded, rock_noise_joins_at_the_borders}`: at 128²–512² the maps' albedo mismatch across a border is 10–15 % of neighbouring texels' difference, the normals' slope along it 4–13 %). Steep crater walls still stretch the detail (as before: a triplanar mapping is an M3 item, graphics spec §6.2). **The lower tiers' shadows.** With one rig a top in a cast shadow read, over a sunlit one on screen (the Look, 1080p, display-linear): 6.4 % at High, 4.3 % Medium, 3.4 % Low, 2.4 % WebGL2 — bloom's veil shrinks and disappears down the tiers and Low shades Classic. `showcase::fill_lift` raises the diffuse lighting, the ambient and the fill × 1.3 at Medium and × 1.8 at Low: 6.2 %, 8.6 % and 5.9 %; High and Ultra are unchanged. The fill's hue is muted from violet (0.62, 0.5, 1.0) to lavender (0.59, 0.53, 0.82) at the same luminance: the violet slivers along crease walls go (`fill_keeps_shadowed_sides_readable`: 14.8 %, 71.6 %, 17.1 %, as before). # Platforms One `build(app: &mut App)` function runs everywhere; `space3d::main!(build)` generates the platform entry points: | target | generated | what runs | |---|---|---| | Windows / macOS / Linux | `pub fn main()` | `App::new()` → `build` → `app.run()` (winit event loop) | | Web (`wasm32-unknown-unknown`) | `#[wasm_bindgen(start)]` fn (+ a no-op `main`) | panic hook + console logging, then the same; `run()` returns and the browser drives frames | | Android | `#[no_mangle] fn android_main(AndroidApp)` | `space3d_platform::android_main_entry` (NativeActivity) | | iOS | `#[no_mangle] extern "C" fn start_app()` | called from the Xcode project's `main.m`; never returns | Android and iOS load a *library*, so projects created by `space3d new` keep the game in `src/lib.rs` and have two thin entry crates: `src/main.rs` (desktop + web binary) and `mobile/` (`crate-type = ["cdylib", "staticlib"]`). Desktop and web builds therefore never link the mobile library types. `space3d doctor` checks everything below and prints the fix for anything missing. ## Desktop ```sh space3d run [--release] space3d build --release # binary + assets/ in dist/desktop/ ``` Linux needs `libasound2-dev libudev-dev libxkbcommon-dev libwayland-dev` (audio, input, keyboard, Wayland). Graphics: DX12/Vulkan (Windows), Metal (macOS), Vulkan with GLES fallback (Linux). ## Web ```sh rustup target add wasm32-unknown-unknown space3d serve # build + serve http://localhost:8080 (COOP/COEP, no-cache) space3d serve --watch # rebuild on changes to src/, assets/, web/, Cargo.toml space3d serve --host # listen on 0.0.0.0 (open it on a phone on the same network) space3d build --target web --release # dist/web/ ``` What `space3d build --target web` does: 1. `cargo build --target wasm32-unknown-unknown --bin `. 2. Reads the `wasm-bindgen` version from `Cargo.lock` and checks the installed `wasm-bindgen` CLI. They must match exactly; if not it prints `cargo install wasm-bindgen-cli --version --locked` (or installs it with `--install-tools`). 3. `wasm-bindgen --target web --no-typescript --out-name --out-dir dist/web …`. 4. Release builds: `wasm-opt -Oz` when binaryen is installed. 5. Copies `web/` (your `index.html`, icons, …) and `assets/` into `dist/web`. The page loads the bundle with `import init from "./.js"; init();`. Set `WindowPlugin::canvas_id` to render into an existing `` (the templates use `space3d`); otherwise a canvas is appended to ``. winit gives the canvas an inline CSS size from `WindowPlugin::width`/`height`; to let the page decide (e.g. fill the viewport), use `!important` in your stylesheet as the templates do (`canvas#space3d { width: 100vw !important; height: 100vh !important; }`) — the surface follows the canvas' real size. Web specifics: the renderer is created asynchronously (WebGPU when available, WebGL2 otherwise — WebGL2 uses the CPU draw path); assets are fetched over HTTP relative to the page; the database uses `localStorage` (KV, save slots, leaderboards; raw SQL returns `Unsupported`); WebSocket and HTTP clients use the browser APIs; servers are native-only; audio starts after a user gesture. Graphics on the web ([graphics.md](graphics.md#webgl2-and-other-downlevel-devices)): WebGPU browsers get every feature as natively (`GraphicsQuality::recommended` picks Medium or High); WebGL2 gets `GraphicsQuality::Low` — render scale 0.75, FXAA instead of MSAA, a 4-level bloom (where `EXT_color_buffer_float` exists; without it the Ldr fallback tonemaps per fragment and has no bloom), a 1024² PCF4 shadow, the Classic shading model with a small environment bake spread over frames, and the CPU particle backend (8 192 particles, thinner spawns). Every feature has a WebGL2 path (no compute, no storage buffers in vertex shaders). WebGL2 links each shader program when a pipeline is first built (50–150 ms): prewarm on loading screens (`GraphicsQuality::prewarm_request`). `examples/graphics_showcase` builds for the web (`cargo run -p space3d-cli -- serve` from its directory; `web/index.html`), and `DownlevelOverride::webgl2()` shows the WebGL2 look on a desktop GPU (the `Engine/Showcase/WebGL2 *` stories). ## Android One-time setup: ```sh # Android Studio → SDK Manager → SDK Tools → NDK (Side by side) export ANDROID_HOME="$HOME/Library/Android/sdk" # Linux: $HOME/Android/Sdk export ANDROID_NDK_ROOT="$ANDROID_HOME/ndk/" cargo install cargo-apk --locked rustup target add aarch64-linux-android ``` Build and install: ```sh space3d build --target android [--release] # = cargo apk build -p -mobile --lib --target aarch64-linux-android adb install -r dist/android/.apk adb logcat -s RustStdoutStderr ``` Packaging metadata (application id, SDK levels, orientation, permissions, bundled `assets/`) lives in `[package.metadata.android]` of `mobile/Cargo.toml`. Rendering uses Vulkan (GLES fallback); touch input arrives as multi-touch `Touch`es and `Binding::TouchRegion` maps screen areas to actions. When the app is backgrounded the surface is dropped and recreated on resume — meshes and textures survive. ## iOS One-time setup (macOS only): ```sh # Install Xcode from the App Store (the Command Line Tools alone are not enough: C dependencies # such as SQLite and rustls' aws-lc need the iOS SDK), then: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer rustup target add aarch64-apple-ios aarch64-apple-ios-sim brew install xcodegen ``` Build: ```sh space3d build --target ios --sim # simulator: cargo build -p -mobile --target aarch64-apple-ios-sim, # then xcodegen + xcodebuild space3d build --target ios --release # device (needs signing in Xcode) ``` The Xcode project is generated from `ios/project.yml` by XcodeGen: an app target with `main.m` (calls the Rust `start_app()`), `assets/` as a resource folder, the Rust static library linked from `target/aarch64-apple-ios[-sim]//`, and a pre-build phase that runs `cargo build -p -mobile` for the SDK and configuration being built — so ⌘R in Xcode always runs current Rust code. To run on a device, open `ios/.xcodeproj` and pick your signing team. Manual equivalent: ```sh cargo build -p -mobile --lib --target aarch64-apple-ios-sim (cd ios && xcodegen generate) xcodebuild -project ios/.xcodeproj -scheme -sdk iphonesimulator \ -configuration Debug -derivedDataPath target/xcode CODE_SIGNING_ALLOWED=NO build xcrun simctl install booted target/xcode/Build/Products/Debug-iphonesimulator/.app xcrun simctl launch booted ``` ## Keyboard layouts Players use AZERTY, QWERTZ, Dvorak, JIS and many other layouts. Every keyboard event carries two identities, and the engine keeps both: * **Physical key** (`KeyCode`) — the key's *position*, named after the US QWERTY key in that place. `Input::pressed`, `just_pressed` and `Binding::Key` use it. `KeyCode::KeyW` is the key right of Tab on every keyboard, labelled W on QWERTY and Z on AZERTY. * **Logical key** (`LogicalKey`, winit's `Key`) — what the key *means* on the player's layout. The window runner records it on a `KeyEvent` per OS event: `physical`, `logical_key` (with Shift/AltGr/Option applied), `key_without_modifiers` (desktop only), `text`, `location`, `pressed`, `repeat`. Read this frame's events with `Input::key_events()`, or the last logical key of a physical key with `Input::logical_key(KeyCode)`. **Bindings.** Bind physical keys for movement and anything position-based: WASD bound as `KeyW/KeyA/KeyS/KeyD` is `Z/Q/S/D` on AZERTY — still an inverted T under the left hand. What the player must see is the label on *their* keyboard, not the code name: ```rust let input = ctx.resources.expect::(); let cap = input.key_cap(KeyCode::KeyW); // "W" on QWERTY, "Z" on AZERTY — never empty let label = input.key_label(KeyCode::KeyW); // Some("z") / None while unknown let space = input.key_label(KeyCode::Space); // Some("Space") — English: localize it let gen = input.keyboard_layout().generation(); // changes when labels may have changed ``` `key_label` returns what the key types **without modifiers** (dead keys: their base character, `^`), or an English name for non-character keys (`Space`, `Enter`, `Shift`, `F1`, `Numpad 1`; `Command`/`Option` on Apple platforms, `Windows` on Windows). `key_label_info` adds the shifted character and the source (`Os`, `Learned`, `Named`); `key_cap` upper-cases letters as keyboards print them (`Q`, but AZERTY's `é`/`2` key stays `é`) and falls back to the US QWERTY character of the position while the layout's is unknown. **UI.** egui receives the logical key (`Event::Key::key`) and the physical one (`physical_key`), like egui-winit, so text fields and shortcuts follow the layout as in native apps: `Ctrl/Cmd+Z/A/C/V/X` act on the keys labelled Z/A/C/V/X (on AZERTY, undo is the key in QWERTY's W position). Layouts without Latin letters (Cyrillic, Greek, …) fall back to the physical key, so shortcuts still work in the QWERTY positions. Hotkeys read from egui follow the layout too: `i.key_pressed(egui::Key::M)` fires on the key *labelled* M — `KeyCode::Semicolon` on AZERTY, `KeyU` for `G` on Dvorak — where it used to fire on physical `KeyM`. Code that compares such a hotkey with physical-key bindings (skip the hotkey while an action is bound to the same key) must translate it first, or the two disagree on other layouts: ```rust let input = ctx.resources.expect::(); // The physical key egui reads as M right now (None: the key labelled M is not known yet). let m_key = space3d_ui::physical_key_for_egui_key(input, egui::Key::M); let m_free = m_key.is_none_or(|k| !bound_to_an_action(k)); ``` Alternatively read position-based hotkeys from `Input::just_pressed(KeyCode::KeyM)` and show `Input::key_cap(KeyCode::KeyM)`. `physical_key_for_egui_key` is cheap enough for every frame: it walks a reverse map (label → physical key) that the layout caches per `generation()` and does not allocate while the labels stay the same. Use the map directly for "which key types this character": ```rust let layout = ctx.resources.expect::().keyboard_layout(); let m = layout.key_for_label("m"); // Some(KeyCode::Semicolon) on AZERTY let digit = layout.key_for_label_matching(|t| t.chars().all(|c| c.is_ascii_digit())); let text: Option<&str> = layout.label_text(KeyCode::KeyA); // borrowed, no allocation ``` When several keys print the same text, the first in keyboard order (`writing_system_keys()`) wins. **Fake and sample layouts.** `KeyboardLayout::set_os_layout(id, labels)` sets a layout table directly (custom platforms, tests, screenshots of another layout's key caps). On macOS, Windows and the web the window runner re-reads the OS table (once per second, on focus), which replaces such a table; pin it to keep it: ```rust let layout = ctx.resources.expect_mut::().keyboard_layout_mut(); layout.set_os_layout(Some("sample-azerty".into()), azerty_labels); layout.set_pinned(true); // no OS re-reads, key events teach nothing, until unpinned // ... layout.set_pinned(false); // the runner re-reads the OS table on its next frame ``` While pinned, explicit calls (`set_os_layout`, `learn`, `clear_learned`, `clear_os_layout`) still apply; `refresh_from_os` / `Input::refresh_keyboard_layout` do nothing. **Where labels come from.** Learned labels (from key events on the current layout) win over the OS table; the OS table is read by the window runner on the event-loop thread at start-up, on focus gain and when the layout id changes (checked at most once per second) — never per frame. | platform | OS table | layout switch detected | notes | |---|---|---|---| | macOS | `TISCopyCurrentKeyboardLayoutInputSource` + `UCKeyTranslate`, main thread only | yes (input source id, keyboard type) | first query at start-up initializes Text Input Services (~35 ms, once); IMEs report the layout they type through; ISO and JIS keys: see below | | Windows | `MapVirtualKeyExW` + `ToUnicodeEx` for the thread's `HKL` | yes (`HKL`) | | | Web | `navigator.keyboard.getLayoutMap()` (Chromium-based browsers), async | on focus | Firefox/Safari, or iframes without the `keyboard-map` permission: learned only; no shifted characters | | Linux X11/Wayland | none (no hard `libxkbcommon` dependency) | no | learned from winit's `key_without_modifiers` | | Android, iOS | none | no | learned from unmodified presses (Shift/Alt presses only teach the shifted character) | Limitations: * Without an OS table a character key has no label until the player presses it once; after an undetected layout switch the old learned labels stay until each key is pressed again (a key that types a new character forgets the shifted character learned on the old layout). * Key-cap capitalization without a known shifted character is a heuristic (letter rows only). * Caps Lock on the web and mobile: letters are learned in lower case (`"A"` → `"a"`), but where Caps Lock also locks Shift on other keys (the digit row of Windows AZERTY) a press teaches the shifted character until the key is pressed without Caps Lock. * macOS Text Input Sources are main-thread only (macOS 14+ aborts the process otherwise): the runner reads them on the event-loop thread, and `Input::refresh_keyboard_layout` reads nothing on other threads (headless tests on libtest threads use learned labels only). * macOS ISO keyboards (most European Macs): winit 0.30 reports both the key left of `1` (`§` on US/British, `@` on French, `^` on German Macs; virtual key `0x0A`) and the key right of left Shift (`` ` `` on US/British, `<` on French/German; `0x32`) as `KeyCode::Backquote`. The runner reads the virtual key of the event AppKit is dispatching (`NSApp.currentEvent`) and reports the key right of left Shift as `KeyCode::IntlBackslash` (its W3C position, as on Windows); each key has its own OS label (egui gets its character's key, else `egui::Key::IntlBackslash`, like egui-winit). A `Backquote` binding (such as the UI console's default key) now fires on the key left of `1` only. If winit delivers a key event late (it queues events that arrive while it is handling another), the virtual key is unknown and either key reads `Backquote` (a release still releases the key its press named), so on ISO keyboards `key_label(Backquote)` comes from the OS table only and is not learned from presses. * macOS JIS keyboards: winit 0.30 has no code for the Ro key (`_`, left of right Shift; virtual key `0x5E`); the runner reports it as `KeyCode::IntlRo` with its OS label. * A table set with `set_os_layout` lasts until the next OS check unless pinned (see above). ## Mouse buttons, focus and the UI `Input` holds the mouse buttons (`mouse_pressed`, per-frame edges `mouse_just_pressed` / `mouse_just_released`) and also records this frame's presses and releases **in order**: `Input::mouse_button_events()` lists a `MouseButtonEvent` per change with the button, `pressed`, the cursor `position` at the time (`None`: outside the window) and a `cause`. The edges alone lose the order — a release and a new press in one frame (the second click of a fast double click) show both edges with the button held; the events say it went up first. Every injection records events (`inject_mouse_button_down` / `inject_mouse_button_up` as `Device` events), so tests and replays drive the same path as the window runner. **Releases without a release event.** A button normally comes up with its release event. Two more things release it, as **cancels** (`MouseButtonEvent::cancelled()`, `MouseButtonCause::is_cancel()`): * `MouseButtonCause::FocusLost` — the window lost the focus (or the app was suspended): the runner calls `Input::release_all()`, which releases every held key and button so game state never sticks. * `MouseButtonCause::OsReconciled` — the OS reports the button up although its release event never arrived. On macOS the release goes elsewhere when the system takes the pointer between press and release (Mission Control, App Exposé, a Spaces swipe, a hot corner, the screenshot overlay) while the window stays key; nothing else would ever release the button. Before each frame the runner asks the OS which buttons it holds — one call, only while a button is held — and releases a button the OS showed held during this press and has shown up since, on consecutive checks spanning at least 50 ms (two at least, with a frame's events delivered in between: the OS state can be ahead of the event queue, and a real release event still on its way stays a real release). Only a press the window itself received (an event of the OS window) is checked: a press a test, a replay or a script injected (`Input::inject_mouse_button_down`) was never held by the OS, so the developer's own physical button — held in another window and let go later — cannot release it. There is no check either while the window has no focus or in background mode (windowed runs of tests, CI and agents: `space3d_platform::background`): the OS's buttons then belong to another app, and what was seen of a press is forgotten. A press the OS never showed held (a click shorter than a frame, a synthetic press) is left to its own release. It never presses anything. | platform | OS button state | a lost release | |---|---|---| | macOS | `+[NSEvent pressedMouseButtons]` (window server state) | released as `OsReconciled` | | Windows | `GetAsyncKeyState` (physical buttons, swapped back for left-handed mice: `SM_SWAPBUTTON`) | released as `OsReconciled` | | Linux, web, Android, iOS | none | waits for the next click or a focus loss | Leaving the window releases nothing: macOS, Windows and X11 deliver the release of a drag that ends outside, and a drag may cross the window's edge (a slider, a window, hold-to-steer). **What the UI does with them.** `space3d-ui` sends egui the button events in order, each where the cursor was (egui's pointer moves there first, so a release after a move beyond egui's click distance is no click), then the cursor's current position. A button event while the cursor is outside the window goes to the last position egui saw, and the pointer is gone again right after (`PointerGone`), so nothing at the window's corner gets hovered. `Event::WindowFocused` is sent when `WindowState::focused` changes (egui then forgets the keys and modifiers it held). * **A release outside the window is not a click on a widget at the window's edge**, even in the frame the pointer leaves: it is delivered at the last position egui saw, after egui's pointer detoured off-screen (as for a cancel), so the widget under that position sees a release but no click. A drag-and-drop payload is dropped nowhere. (The one exception is the case described under "A cancel only concerns its own button": when egui has no press in progress for the button, it has nothing to withhold a click from.) * **No pointer position yet.** A button event before any pointer position is known (nothing has moved the cursor into the window; a test that presses first) is *dropped*, not sent to (0, 0): the press is ignored and so is its release, whenever it comes (a release after the cursor moved in is not delivered to a press egui never saw). Buttons work as soon as one position was seen; `Input` itself still records them (`mouse_pressed`, `mouse_button_events`). * **A cancel only concerns its own button.** egui follows one press at a time and any release ends the click in progress, so a cancel between another button's press and release would swallow that click. The UI therefore sends a cancel as early as it can: ahead of the presses and clicks of the other buttons in its frame (after its own button's earlier events, after other cancels, and after the release that ends a click begun in an earlier frame). A right click that starts and ends in the frame the held left button is cancelled is a right click. (When a click begun earlier ends in the same frame as another button's cancel, egui has no press in progress when the cancel comes and judges it alone: the click of the other button is kept, and the cancelled release may count as a click there.) * **Touches.** `TouchPhase::Cancelled` (an incoming call, a rejected palm, a system gesture that took the finger) ends the touch like `Ended` but is no tap: `Input::just_ended_touches` lists it, `Input::just_cancelled_touches` tells which of those were cancelled, egui gets `TouchPhase::Cancel`, and the pointer touch's release is a cancelled release of the primary button (no click). Games should not fire on the release of a cancelled touch. A cancelled release registers **neither a click nor a drop** in egui — like switching away from a native app mid-drag. Drags end (`Response::drag_stopped`), a dragged slider keeps its value, a button pressed before the focus loss does not fire, and egui's drag-and-drop payload is dropped without reaching any drop zone (`dnd_release_payload` returns `None`). Game code that implements its own drag-and-drop or "release over X" logic from `Input` should skip releases with `cancelled()`: ```rust for e in ctx.resources.expect::().mouse_button_events() { if e.button == MouseButton::Left && !e.pressed { if e.cancelled() { cancel_drag(); // focus lost / release only the OS saw: no drop } else { drop_here(e.position); // a real release } } } ``` **Deciding drops and commits from egui.** egui has no notion of a cancel: a cancelled release still ends the press, so `Response::drag_stopped()`, `PointerState::button_released` and `any_released()` are `true` in that frame, and "drop here" logic written as `hovered()` (or `contains_pointer()`) with `any_released()` would act on a focus loss. Ask whether the release was a cancel: `EguiContext::pointer_cancelled_this_frame()` (any button) and `EguiContext::button_cancelled_this_frame(button)`, or, when only an `egui::Context` is at hand, the free functions `space3d_ui::pointer_cancelled_this_frame(ctx)` and `space3d_ui::pointer_cancel_cause(ctx, button)` (the `MouseButtonCause`: `FocusLost` or `OsReconciled`; a cancelled touch is the primary button's, `FocusLost`). They describe the frame's pass, from `Stage::PreUpdate` (`ui::begin_frame`) until the next frame's, and are `false` without a running `UiPlugin` or while the UI is disabled. ```rust app.add_root_ui_system(|ui: &mut egui::Ui, sys: &mut SystemCtx| { let cancelled = sys .resources .expect::() .button_cancelled_this_frame(egui::PointerButton::Primary); let (_, zone) = ui.allocate_exact_size(egui::vec2(60.0, 30.0), egui::Sense::hover()); let released = ui.input(|i| i.pointer.any_released()); if zone.contains_pointer() && released { if cancelled { put_it_back(); // focus lost / a release only the OS saw: no drop } else { drop_here(); // a real release } } }); ``` egui's own drag-and-drop (`Response::dnd_release_payload`) needs none of this: the engine drops the payload before the pass on a cancel. Code that runs outside the UI systems (a game system reading `Input`) uses `MouseButtonEvent::cancelled()` as above. **Sub-apps in the editor.** A `LiveView` (the editor's sub-app viewport, the storybook's story view) forwards its host UI's pointer to the sub-app's `Input`: a press as a device press, a release as a device release — or, when the host cancelled it (`pointer_cancel_cause`), as `Input::release_mouse_button(button, cause)` with the host's cause, so the story or sub-app's own `MouseButtonEvent::cancelled()` and UI behave as in a window of their own. **egui plugins.** egui 0.36 runs its plugins' pass hooks (`Plugin::on_begin_pass` / `on_end_pass`) only from `Context::run_ui`; the engine's pass spans `Stage::PreUpdate` to `Stage::PostUpdate` (`begin_pass` / `end_pass`), so the engine runs the hooks itself, in `run_ui`'s order and with a top-level `Ui` like `run_ui`'s: the begin hooks before the UI systems, the end hooks after them. That covers egui's built-in plugins — label text selection (a drag to select ends with the release), drag-and-drop (a payload nobody took ends with the release or Esc) and `egui::debug_text` — and plugins added with `EguiContext::add_plugin(plugin)` (or made known with `EguiContext::register_pass_hooks::

()` when a library already added them with `egui::Context::add_plugin`). egui cannot list a context's plugins, so hooks of plugins the engine does not know about do not run, and `egui::Context::on_begin_pass` / `on_end_pass` callbacks (kept in a private egui plugin) never run: register a plugin instead. **Tests** drive all of this headless: `WindowState::focused = false` plus `Input::release_all()` is what the runner does on a focus loss, and `Input::release_mouse_button(b, MouseButtonCause::OsReconciled)` is what the OS check does. Injected presses (`inject_mouse_button_down`) are never subject to the OS check; only the runner's own window events are (crate-internal `Input::os_mouse_button`). ## The mouse cursor and the window icon The pointer shape over the window is the `WindowCursor` resource (inserted by `WindowPlugin`). `space3d-ui` writes egui's cursor into it whenever egui asks for a different one (the I-beam over text fields, resize arrows, a pointing hand where the game asks for it with `on_hover_cursor` or egui's `interact_cursor` style); a game may set `WindowCursor::icon` itself (a crosshair in flight, say), and that stays until egui's cursor changes. After every frame the runner applies it with winit's `Window::set_cursor`, so it survives Windows re-applying the window cursor on `WM_SETCURSOR` and macOS's cursor rects. `icon: None` (egui's `CursorIcon::None`) hides the pointer, as does `WindowState::cursor_visible = false`; grabbing (`cursor_grab`) is independent. `WindowCursor::applied()` reports what was last applied to a real window (shape and visibility; `None` headless), for tests that run a window in background mode. `WindowPlugin::icon` sets the window icon (title bar, Alt-Tab) from RGBA8 pixels (`WindowIcon { rgba, width, height }` or `WindowIcon::from_image`); on Windows it is also the taskbar icon, which Windows 11 otherwise shows blank for an exe without an embedded icon. macOS ignores it (the Dock shows the app bundle's icon); the web and mobile use their own manifests. ## CI and releases `space3d ci init --targets desktop,web,android,ios` (also run by `space3d new`) writes `.github/workflows/space3d.yml`: tests with a software GPU, a desktop matrix (Linux, Windows, macOS), the web bundle (deployed to GitHub Pages), an APK and an unsigned `.ipa`, and a GitHub Release with all of them on `v*` tags. The file goes to the repository root (`git rev-parse --show-toplevel`, else the cargo workspace root), the only place GitHub reads workflows; for a package nested inside a bigger repository the command says which `-p` / `working-directory` to add to the jobs. The `wasm-bindgen-cli` version it installs is taken from `Cargo.lock`. Locally, `space3d publish --tag v1.2.0 [--targets desktop,web,android] [--draft] [--dry-run]` builds release artifacts into `dist/`, archives them (`-v1.2.0-.tar.gz`, `.apk`) in `dist/release/`, creates the GitHub release (or reuses the existing one for that tag) and uploads the archives. It needs `GITHUB_TOKEN`/`GH_TOKEN` or `gh auth login`; the repository is taken from `git remote get-url origin` unless `--repo owner/name` is given. # Dedicated server guide Space3d games can run a **separate, authoritative server** that owns the game state and the players. Native, mobile and browser clients connect to it; clients only send input and never send state. This guide covers how to run it, deploy it, configure it and scale it. - **Design and internals:** [`docs/design/game-server.md`](design/game-server.md). - **Crates:** - `space3d-server` is native only: the process, the game server and the player service. - `space3d-replication` is shared by server and client, and compiles for `wasm32`: protocol, replication, prediction and interpolation. - **Example:** `examples/multiplayer_arena` is the smallest complete game. - `server` binary: the dedicated server. - `client` binary: a native or web client, with a `--headless --bot` mode. - `loadtest` binary: headless bots. - `examples/arena-*` is a larger game with shooting, lag compensation, matches and leaderboards. --- ## 1. What runs where The server has two roles. Both are in one library, and one binary can run either or both. | role | owns | clients talk to it over | |---|---|---| | **Player service (PS)** | accounts, sessions, profiles, player data, leaderboards, matchmaking, lobbies, the fleet registry of game servers, room checkpoints | HTTPS JSON (`/v1/*`) | | **Game server (GS)** | rooms. A room is an isolated simulation of 1–N players, ticking at a fixed rate on a shard thread. | WebSocket (`/play`) | The `role` config key picks what a process runs: | `role` | runs | typical use | |---|---|---| | `all-in-one` | PS + GS, joined by an in-process fleet link. They can share one port. | development, small games, a single VM | | `player-service` | PS only. The stock `space3d-server` binary has no game code. | scale-out | | `game-server` | GS only. It registers with the PS over the fleet WebSocket. | scale-out, one per node or pod | ### 1.1 Topologies **All-in-one (one process, one port):** ``` native / web client │ POST /v1/auth/guest, POST /v1/play/quick ──►┐ │ WS /play (Hello{Ticket}) ──────────────────►│ 127.0.0.1:7777 ▼ ▼ ┌──────────────────────── server (role = all-in-one) ────────────────────────┐ │ player service ──in-process fleet link──► game server │ │ SQLite: accounts, player data, outbox, ingress + gatekeeper → rooms │ │ checkpoints (shard threads, 60 Hz ticks) │ │ admin / metrics / health :9090 (loopback) │ └────────────────────────────────────────────────────────────────────────────┘ ``` **Split (one player service, N game servers):** ``` ┌──────────── player service (1 instance) ───────────┐ client ──HTTPS /v1──► │ accounts · sessions · matchmaking · lobbies │ │ │ fleet registry (leases) · checkpoints · SQLite │ │ └──────▲──────────────────────────▲──────────────────┘ │ Assignment │ fleet WS: register, │ checkpoint upload │ {server_url, room_id, │ heartbeat, presence, │ (HTTP PUT) │ join_ticket} │ results (outbox) │ ▼ │ │ ┌── game server gs-1 ───────┴──┐ ┌── game server gs-2 ──┴──┐ … │ WS :7777/play │ │ WS :7777/play │ │ shards × S → rooms × k │ │ │ │ admin :9090 (private) │ │ │ │ local SQLite: outbox │ │ │ └──────────────────────────────┘ └─────────────────────────┘ ``` A game server needs no inbound internal port. It dials the player service. The player service hands out URLs, and clients connect to the game server directly. **Join sequence:** ``` client player service game server │ POST /v1/auth/guest ──►│ access 1 h / refresh 30 d │ POST /v1/play/quick ──►│ pick an open room or allocate one; │ │ sign JoinClaims{player, server_id, room spec, jti, exp=60 s} │ ◄── Assignment ────────│ │ WS /play Hello{v, game_id, schema_hash, Ticket} ─────────────────►│ verify HMAC offline, │ │ single-use jti, bans, │ │ create room lazily │ ◄──────────────────────── Welcome{slot, tick, resume token} ───────│ │ ◄──── snapshots 30 Hz ── inputs 60 Hz ──► pings 4 Hz ─────────────│ ``` The ticket carries the room spec, so starting a match needs no RPC between the services. A dropped link resumes the same slot within 20 s using the resume token (the client stops trying when those 20 s are over). After a room crash or a server loss, the client calls `POST /v1/sessions/rejoin`. The player service may then restore the room on another game server from its last checkpoint. --- ## 2. Quickstart: run it locally ```sh # Terminal 1: all-in-one dev server on 127.0.0.1:7777 (admin on 127.0.0.1:9090) cargo run -p multiplayer_arena --bin server # Terminal 2 and 3: windowed clients through the player service (WASD / arrows to move) cargo run -p multiplayer_arena --bin client -- --ps http://127.0.0.1:7777 --name alice cargo run -p multiplayer_arena --bin client -- --ps http://127.0.0.1:7777 --name bob # Or headless bots (exit after 10 s; exit code 0 only if they were connected) cargo run -p multiplayer_arena --bin client -- --headless --bot --ps http://127.0.0.1:7777 --name bot-1 --seconds 10 # Dev auth straight to the game server, with no player service (loopback only) cargo run -p multiplayer_arena --bin client -- --server ws://127.0.0.1:7777/play --name carol ``` With no arguments the server runs its **built-in dev config** (`examples/multiplayer_arena/server.toml`): - all-in-one, loopback binds, one shared port for `/v1` and `/play`; - dev auth on; - relaxed per-IP limits, so local bots can connect; - data under `target/multiplayer_arena/`; - the public dev signing key. It logs a warning, and `env = "production"` refuses it. Look inside the running server: ```sh curl -s 127.0.0.1:9090/readyz # ready curl -s 127.0.0.1:9090/admin/v1/rooms | jq # rooms, players, tick cost (open on loopback in dev) curl -s 127.0.0.1:9090/metrics | grep space3d_tick_seconds ``` Stop it with Ctrl-C (SIGINT) or SIGTERM: 1. Clients get a `ShuttingDown` notice. 2. Rooms write a final checkpoint. 3. Clients are disconnected with `ServerShutdown`. 4. The process exits 0. A second signal forces exit 1 without waiting: every room is checkpointed synchronously into the game server's own database, clients are disconnected with `ServerShutdown`, and the next start moves those checkpoints into the configured store so rejoining players are restored. ### 2.1 Split mode on one machine ```sh export SPACE3D_KEYS="$(cargo run -q -p space3d-server -- keygen)" # shared signing key export SPACE3D_FLEET_TOKEN=local-fleet-token-0123456789 # Player service (stock binary, no game code) SPACE3D__ROLE=player-service SPACE3D__PLAYER_SERVICE__BIND=127.0.0.1:8080 \ SPACE3D__ADMIN__BIND=127.0.0.1:9080 SPACE3D__PLAYER_SERVICE__DB_PATH=target/split/players.db \ cargo run -p space3d-server # A game server (the game's binary), registering over the fleet WebSocket SPACE3D__SERVER_ID=gs-1 SPACE3D__GAME__BIND=127.0.0.1:7777 SPACE3D__GAME__PUBLIC_URL=ws://127.0.0.1:7777/play \ SPACE3D__ADMIN__BIND=127.0.0.1:9091 SPACE3D__PERSISTENCE__DATA_DIR=target/split/gs-1 \ SPACE3D__FLEET__PLAYER_SERVICE_URL=ws://127.0.0.1:8080/internal/v1/fleet \ SPACE3D__FLEET__PLAYER_SERVICE_HTTP=http://127.0.0.1:8080 \ cargo run -p multiplayer_arena --bin server -- --role game-server cargo run -p multiplayer_arena --bin client -- --ps http://127.0.0.1:8080 --name alice ``` For a second game server, repeat with `gs-2`, other ports and another data dir. Quick play, matchmaking and rejoin spread players over every registered server. ### 2.2 Your own game The server and every client add the **same protocol plugin**. It registers the replicated components, the input type, the messages and the predicted simulation, and it is hashed into the schema hash. ```rust // shared (native + wasm) impl Plugin for CubesProtocol { fn build(&self, app: &mut App) { app.add_plugin(ReplicationPlugin::default()) // Transform (predicted / interpolated), Name .replicate::("cubes.color") .add_input::("cubes.input") .add_sim_system("cubes::drive", drive); // runs on the server and in client prediction } } // server binary impl GameDefinition for CubesGame { fn game_id(&self) -> &str { "multiplayer_arena" } fn protocol(&self, app: &mut App) { app.add_plugin(CubesProtocol); } fn build_room(&self, app: &mut App, _spec: &RoomSpec) { app.add_plugin(CubesRules); } // spawn a cube per PlayerJoined } fn main() -> ExitCode { match ServerMain::from_env_with_defaults(CubesGame, include_str!("../server.toml")) { Ok(main) => main.run(), Err(e) => { eprintln!("{e}"); ExitCode::from(2) } } } // client app.add_plugin(ClientReplicationPlugin { config: ClientConfig { game_id: "multiplayer_arena".into(), ..Default::default() } }) .add_plugin(CubesProtocol); app.set_input_sampler(|ctx| CubeInput::from_axes(/* ActionState axes */)); app.resources.expect_mut::().connect(ConnectTarget::Ticket { url, ticket }); ``` Rules that keep prediction exact: - Put predicted gameplay in `add_sim_system`. - Query `With<&Simulated>` and read `SimTime`, not wall time. - Inputs carry **state, not edges**. - Add the replication plugin before game plugins. Also: - Anything that takes time on the client, such as player-service calls, returns a `space3d_tasks::Task`. Poll it from a system and never block the frame. The example client's `online_flow` shows how. - `ServerMain::from_env_with_defaults` layers the game's defaults under `--config` and the env overlay. `ServerMain::from_env` starts from the library defaults. - List the modes your game hosts in `GameDefinition::modes` (and reject others in `validate_spec`): quick play then opens rooms only of those modes. --- ## 3. Docker The image is distroless, runs as non-root (uid 65532), stops on SIGTERM, and keeps its state in a `/data` volume. Build from the workspace root (that is the build context; `.dockerignore` keeps it to the sources, about 9 MB): ```sh # the example's dedicated server (without the windowed client and its GPU dependencies) docker build -f crates/space3d-server/deploy/Dockerfile \ --build-arg BIN=server --build-arg CARGO_ARGS="-p multiplayer_arena --no-default-features" \ -t multiplayer-arena-server . # the stock player service docker build -f crates/space3d-server/deploy/Dockerfile -t space3d-player-service . ``` **The build.** - *Toolchain.* The build stage is `rust:${RUST_VERSION}-slim-bookworm`. `RUST_VERSION` must equal the `channel` in `rust-toolchain.toml`: the Dockerfile stops with a message when it does not, and `tests/deploy.rs` checks it. The stage sets `RUSTUP_TOOLCHAIN`, so rustup never follows the toolchain file's `components` and `targets` (rustfmt, clippy, wasm32), which it would otherwise download at the first `cargo` call. - *Network.* It is needed by the two base-image pulls (`rust`, `gcr.io/distroless/cc-debian12`), `apt-get` (`cmake clang perl pkg-config`, which `aws-lc-sys` needs, plus a cross gcc for a foreign `--platform`), `rustup target add` (a no-op for the native target) and `cargo fetch --locked` (crates.io). Nothing else: the compile step runs under `RUN --network=none` from the fetched registry, so it is hermetic. The repository does not vendor its dependencies. For an air-gapped build, mirror the base images and point `apt` and cargo (a `.cargo/config.toml` source replacement, e.g. from `cargo vendor`) at internal mirrors; that was not tried here. - *Caching.* The cargo registry and `target/` are BuildKit cache mounts. After a source edit only the changed crates and their dependents recompile (a one-line change in `space3d-server` recompiles that crate alone and relinks: about 70 s on 8 cores, dominated by the thin-LTO link). A cold builder compiles everything once (about 2 min for the player service on 8 cores, and about another minute for the game server on top of that). The cache lives on the builder, in cache mounts, and **`--cache-to` does not export it**: BuildKit's exported cache carries image layers, not the contents of `RUN --mount=type=cache`. A CI runner that starts empty every time therefore compiles cold on every run. Keep a persistent builder (a self-hosted runner, or a remote BuildKit daemon with a volume), or save and restore the two cargo mounts and `target/` between runs yourself (for example with a cache-dance step in the workflow; this was not tried here). `--build-arg CACHE_ID=other` selects a private cache. `docker compose build` builds the player service and the game server at once: the `cargo fetch` step holds the registry mounts with `sharing=locked` so that two cold fetches do not unpack the same crate at the same time (without it a cold `up --build` failed with `failed to unpack package ... File exists`). - *Architectures.* The image is `linux/`. `--platform linux/amd64` and `--platform linux/arm64` **cross-compile** with the native toolchain (a cross gcc as linker), so an Apple Silicon machine builds an amd64 image for a cluster without emulation. (Running the compiler under qemu was tried and is not usable: the build fails intermittently with `cc` segfaults.) - *Size.* About 71 MB: the distroless base, the binary (about 17 MB) and the config. The image starts `server` with `SPACE3D_CONFIG=/etc/space3d/server.toml`, a copy of `deploy/server.example.toml`, and `SPACE3D__ENV=production`, JSON logs, `/data` as the data directory and `/data/players.db` as the player database. Production refuses to start without real secrets: ```sh # --stop-timeout: docker kills after 10 s by default; a drain may take drain_timeout (15 min) + 30 s docker run --rm --stop-timeout 930 -p 7777:7777 -p 8080:8080 -v arena-data:/data \ -e SPACE3D_KEYS="k1:$(openssl rand -base64 32)" \ -e SPACE3D_FLEET_TOKEN="$(openssl rand -hex 24)" \ -e SPACE3D_ADMIN_TOKENS="$(openssl rand -hex 24)" \ -e SPACE3D__SERVER_ID=arena-1 \ -e SPACE3D__GAME__PUBLIC_URL=wss://arena-1.play.example.com/play \ multiplayer-arena-server ``` - **Volume permissions.** `/data` belongs to uid 65532. A named volume copies that when it is first used. A bind mount keeps the host's ownership: on Linux `chown 65532:65532` the directory first (or run with `--user`). - **Read-only root filesystem.** The server writes only under `/data`, so `docker run --read-only` works (verified for the player service alone with the image's own `/data` volume; the compose stack runs all three services read-only). The compose file also mounts a `tmpfs` on `/tmp` as a precaution for SQLite temporary files, drops every capability and sets `no-new-privileges`. - **Ports.** `7777` game WebSocket, `8080` player service, `9090` admin, `/metrics`, `/healthz`, `/readyz`. The example config binds admin to `127.0.0.1`; set `SPACE3D__ADMIN__BIND=0.0.0.0:9090` to reach it from outside the container (compose does), and publish it on a private interface only. - **Probes.** The image has no shell and no curl. Use `server healthcheck` for liveness and `server healthcheck --ready` for readiness (they read `SPACE3D_CONFIG`, so they follow a mounted config). The compose file already does this. - **Stopping.** `docker stop` sends SIGTERM and then SIGKILL after 10 s by default. A game server that hosts matches drains for up to `game.drain_timeout`, so give it `--stop-timeout` (or `stop_grace_period` in compose) of `drain_timeout + 30 s`. A server with no players exits within a second with code 0; one whose room still holds players, or players who dropped less than `resume_window` (20 s) ago, waits for them, up to `drain_timeout` (a container stopped with docker's default 10 s was killed while it waited: exit 137). `docker start` afterwards re-registers with the player service; persistent rooms are restored from their checkpoints when a player rejoins. - **Split stack.** One player service and two game servers (loopback ports 8080, 7777, 7778; admin 9090 to 9092; read-only root filesystems; game servers wait for a healthy player service): ```sh SPACE3D_KEYS=k1:$(openssl rand -base64 32) SPACE3D_FLEET_TOKEN=$(openssl rand -hex 24) \ SPACE3D_ADMIN_TOKENS=$(openssl rand -hex 24) \ docker compose -f crates/space3d-server/deploy/compose.yaml up --build ``` `compose.yaml` builds `examples/arena-server` for the game servers (one image for both). Build the `multiplayer_arena` example's server instead with `GAME_BIN=server GAME_CARGO_ARGS="-p multiplayer_arena --no-default-features"`, then drive it with the headless bots: ```sh cargo run -p multiplayer_arena --bin client -- --headless --bot --ps http://127.0.0.1:8080 --name bot-1 --seconds 10 ``` Its rooms are not persistent by default. To see a room move when you `docker stop` its game server, set a persistent queue in the environment of the three services (as the process tests do): `SPACE3D__MATCHMAKING__QUEUES='[{ name = "arena", mode = "arena", teams = 1, team_size = 16, min_players = 1, max_wait = "5s", backfill = true, params = { persistent = "true" } }]'`. - **TLS:** terminate TLS at your ingress or load balancer. Browsers on an https page need `wss://`. **What was verified in containers** (Docker 29 on a Colima aarch64 VM, the compose stack with the `multiplayer_arena` server and two headless bots from the host): `/healthz`, `/readyz` and `/metrics` answer on all three services; the admin API returns 401 without a token or with a wrong one and 200 with a token, and never prints the secrets in `/admin/v1/config`; the containers run as uid 65532 with a read-only root filesystem; bots connect through the player service and play (RTT about 20 ms); `POST /admin/v1/rooms/{id}/checkpoint` answers 202 and `space3d_checkpoint_seconds_count` advances; `docker stop` of the game server hosting a persistent room exits 0 in about 1 s, the room moves to the other game server with the same id and both bots play on; stopping both game servers and starting them again restores the room from the player service's checkpoint (its tick continues) and the bot rejoins; stopping the player service exits 0 in under 1 s, its volume keeps accounts and player data across the restart, and game servers re-register on their own. The amd64 image (62 MB) was cross-built on the arm64 machine in under 3 minutes; the binary is an x86-64 ELF, and under qemu emulation the container answers `--help`, `check-config` and `/readyz` and exits 0 on SIGTERM. It was not load-tested, and the compose stack was only run natively (arm64). A warm rebuild with crates.io, static.crates.io, github.com and static.rust-lang.org unreachable succeeds (`cargo fetch` finds everything in the registry cache, then the offline compile runs). Bind-mounted `/data` ownership on a native Linux host was not tested. ### 3.1 Kubernetes `crates/space3d-server/deploy/k8s/` has plain manifests (and a `kustomization.yaml`): | file | what | |---|---| | `namespace.yaml` | `space3d`, restricted Pod Security | | `configmap.yaml` | `server.toml`: every key of `server.example.toml`, production values | | `player-service.yaml` | PVC, `Deployment` (1 replica, `Recreate`), `Service` | | `game-server.yaml` | headless `Service`, `StatefulSet` (2 replicas, PVC per pod), `PodDisruptionBudget` | | `secret.example.yaml` | template for `SPACE3D_KEYS`, `SPACE3D_FLEET_TOKEN`, `SPACE3D_ADMIN_TOKENS` (placeholders the production image rejects) | | `ingress.example.yaml` | optional: `/v1` for the player service (never `/internal`), one host and Service (`publishNotReadyAddresses: true`) per game-server pod | | `networkpolicy.yaml` | optional: default deny, then only the flows the stack needs | ```sh # 1. secrets, created out of band (never commit them) kubectl create namespace space3d kubectl -n space3d create secret generic space3d-server-secrets \ --from-literal=SPACE3D_KEYS="k1:$(openssl rand -base64 32)" \ --from-literal=SPACE3D_FLEET_TOKEN="$(openssl rand -hex 24)" \ --from-literal=SPACE3D_ADMIN_TOKENS="$(openssl rand -hex 24)" # 2. images: push the two images and point kustomization.yaml (`images:`) at them # 3. apply kubectl apply -k crates/space3d-server/deploy/k8s ``` - **Roles.** The player service is one pod: its state is SQLite on a ReadWriteOnce volume, so the `Deployment` uses `Recreate`. Game servers are a `StatefulSet`: `server_id` is the pod name (stable across restarts, as join tickets require) and each pod keeps its `/data` volume with the outbox and the local checkpoint rescue store. The game server dials the player service (`space3d-players:8080`); it needs no inbound internal port. - **Drain semantics.** The manifests encode §6, "Draining and upgrades": 1. `readinessProbe` on `/readyz`: 503 until the pod registered, and again as soon as it drains. `startupProbe` and `livenessProbe` use `/healthz`. 2. `preStop` sleeps 5 s (`sleep` action, Kubernetes 1.30+; the image has no shell), so anything routed through a Service that honours readiness sees the pod leave before SIGTERM. The per-pod Services of `ingress.example.yaml` do **not** honour it: they set `publishNotReadyAddresses: true`, because a draining game server is NotReady and then Terminating, Kubernetes removes such a pod from a Service's endpoints, and the ingress would then answer 503 to a resume after a link blip or a rejoin into a match that is still running on it (§6: both are accepted while draining). New players stay away from the pod because the player service stops allocating to it and the pod refuses tickets that would open a room (`Reject(ServerDraining)`). Give a `LoadBalancer` or `hostPort` front the same property. 3. SIGTERM starts the drain: matches finish within `game.drain_timeout` (15 min in the ConfigMap), persistent rooms hand off, checkpoints upload, the process exits 0. 4. `terminationGracePeriodSeconds: 960` = 900 s drain + 5 s preStop + 30 s final checkpoints + 25 s slack. The grace period includes the preStop hook. `tests/deploy.rs` fails when the ConfigMap's `drain_timeout` and the StatefulSet's numbers stop adding up. 5. `PodDisruptionBudget` `maxUnavailable: 1`: node drains and cluster upgrades evict one game server at a time; each eviction is a full drain, so a rolling update of N pods takes up to N times the drain timeout. Lower `drain_timeout` (and the grace period with it) for games with short matches. - **Config and secrets.** The ConfigMap is mounted over `/etc/space3d/server.toml`. It restates every key of the example on purpose: a game binary's built-in defaults (the arena example turns dev auth on and relaxes the per-IP limits) sit under the file, and a key the file omits would leak through. What differs per pod comes from the environment (`SPACE3D__ROLE`, `SPACE3D__SERVER_ID` from `metadata.name`, `SPACE3D__GAME__PUBLIC_URL`). Set `security.trusted_proxies` to your ingress controller's pod CIDR: without it every client shares the ingress address and the per-IP limits. The Secret holds the three keys; key rotation is in §4. - **Reaching a game server.** Clients connect straight to the pod the player service assigned, at `game.public_url` (`wss://{server_id}.play.example.com/play`), so each pod needs its own host or address: `ingress.example.yaml` (one `Service` per pod selected by `statefulset.kubernetes.io/pod-name`, one ingress host each), a `LoadBalancer` per pod, or `hostPort`. Block `/internal/*` of the player service at the ingress; only game servers use it, inside the cluster. - **Autoscaling (note).** The player service does not scale out (§6, "Limits of v1"). Game servers scale on the player service's `space3d_fleet_free_seats{region}` gauge. It falls as players arrive, and an HPA scales *up* when its metric rises above the target, so feed it an inverted signal (a Prometheus recording rule such as "seats wanted minus free seats", exposed through prometheus-adapter as an External metric with an `AverageValue` of the seats per pod), or use KEDA's Prometheus scaler. Scale-in removes the highest ordinal, which drains for up to the grace period: use a long `behavior.scaleDown.stabilizationWindowSeconds` and one pod per step. No HPA manifest is shipped because it depends on your metrics pipeline. - **Validation.** All manifests pass `kubeconform -strict` (v0.8.0) against the Kubernetes 1.30 and 1.34 schemas, `kustomize build` (v5.8.1) renders the eight resources of the kustomization and the output validates too, and the ConfigMap's `server.toml` is accepted by `check-config` of the built images with production secrets (and each placeholder of the Secret template is refused: the key as invalid base64, the tokens by name). **They have not been run on a cluster**: probes, the PVCs, the ingress example, the NetworkPolicy and the actual drain behaviour under `kubectl delete pod` are unverified. In particular the claim that a Service with `publishNotReadyAddresses: true` keeps routing to a NotReady, Terminating pod (so a draining game server still receives resumes) comes from Kubernetes' endpoint semantics, not from a cluster run. The drain itself (`/readyz` 503, exit 0) was run in Docker, and that a draining server accepts a rejoin into its running match is tested in `tests/cluster.rs` (`rejoin_during_a_drain_returns_to_the_running_match`). --- ## 4. Configuration reference Configuration is loaded in this order, where later layers win: 1. library defaults; 2. the game binary's built-in TOML (`from_env_with_defaults`); 3. the `--config` file or `SPACE3D_CONFIG`; 4. environment variables `SPACE3D__SECTION__KEY=value`; 5. `--role`. Merging rules: - Tables merge key by key. - Arrays, such as `[[matchmaking.queues]]`, replace the whole array. - Env values are parsed as TOML, so `SPACE3D__MATCHMAKING__QUEUES='[{ name = "arena", mode = "arena", teams = 1, team_size = 20 }]'` works. Value formats: - `${VAR}` expands inside strings. - `{server_id}` expands inside `game.public_url`. - Durations are strings: `"250ms"`, `"30s"`, `"15m"`, `"24h"`, `"30d"`. - Sizes are integers or strings: `"16KiB"`, `"1MiB"`. Tools: - `--check-config` validates the config and the secrets and prints the redacted effective config. - `--print-default-config` prints the commented example. ### Top level | key | default | meaning | |---|---|---| | `role` | `"all-in-one"` | `all-in-one` \| `player-service` \| `game-server` | | `env` | `"dev"` | `production` enforces real secrets. It rejects missing keys, keys under 32 bytes, the dev key, the dev fleet token and short admin tokens. | | `server_id` | `"local-1"` | Stable id, such as the pod name. Join tickets are bound to it, so keep it stable across restarts. | | `region` | `"local"` | Used in allocation. `region_pings` from clients choose among regions. | ### `[game]`: game-server role | key | default | meaning | |---|---|---| | `bind` | `0.0.0.0:7777` | `/play` WebSocket and `/ping` | | `path` | `"/play"` | WebSocket path | | `public_url` | `ws://127.0.0.1:7777/play` | URL written into assignments, e.g. `wss://{server_id}.play.example.com/play` | | `shards` | `0` | Room threads. 0 means cores − 1, minimum 1. | | `max_rooms` / `max_players` | 128 / 1024 | Capacity reported to the fleet | | `tick_hz` | 60 | Room tick rate, whole Hz (clients receive it as an integer) | | `send_interval` | 2 | Snapshot every N ticks (30 Hz) | | `resume_window` | `"20s"` | How long a dropped player's slot and pawn are kept | | `empty_room_ttl` | `"30s"` | Empty non-persistent rooms close after this | | `drain_timeout` | `"15m"` | Budget for matches to finish on SIGTERM | | `max_catchup_ticks` | 3 | Late ticks a room may run back to back before it skips | | `allow_dev_auth` | false | `Hello{Dev}` without a ticket. Refused unless `bind` is loopback. | | `allowed_origins` | `[]` | Browser `Origin` allowlist. Empty means any. | | `room_inbox` | 8192 | Messages queued per room | ### `[limits]`: per connection | key | default | meaning | |---|---|---| | `max_message_bytes` | 16 KiB | Inbound WebSocket message and frame cap (close 1009) | | `max_connections` | 10000 | All links | | `max_connections_per_ip` / `handshakes_per_ip_per_min` | 8 / 20 | Raise these for local load tests | | `handshake_timeout` / `idle_timeout` | 5 s / 10 s | | | `client_bandwidth` | 48 KiB | Default downstream snapshot budget per client, in bytes/s. Priority decides what fits. | | `outbound_backlog_bytes` | 1 MiB | Above this for 5 s, the link is kicked as `SlowConsumer`. Snapshots are skipped above 256 KiB. | | `http_connections_per_ip` / `http_max_connections` | 64 / 16384 | Every HTTP listener (game port, player service, admin): connections that have not completed a request or a WebSocket upgrade, per client IP (IPv6 per /64; `trusted_proxies` exempt) and in total. Extra sockets are closed at accept. Raise the per-IP cap for local load tests. | | `http_header_timeout` / `http_body_timeout` | 10 s / 10 s | Every listener closes a connection that does not complete a request head in time (idle keep-alive connections too); the player service answers 408 to a body that does not arrive in time. | | `input_packets_per_sec` / `messages_per_sec` | 90 / 30 | Token buckets. The packet bucket adds 30/s for pings and control (120/s, burst 60, never under 1.5 × `tick_hz` for inputs). Overflow is dropped; drops in 3 consecutive seconds (or 10 s worth of the allowance within one second) kick with `RateLimited`. The gateway also caps each link at 4 × `input_packets_per_sec` into the shared room inbox and closes sustained flooders. | ### `[player_service]` | key | default | meaning | |---|---|---| | `bind` | `0.0.0.0:8080` | `/v1/*` and `/internal/v1/*`. In all-in-one mode, the same address as `game.bind` shares one listener. | | `db_path` | `data/players.db` | SQLite (WAL) | | `session_ttl` / `refresh_ttl` / `join_ticket_ttl` | 1 h / 30 d / 60 s | Refresh tokens rotate, and reusing one revokes the whole family | | `guest_auth` / `password_auth` | true / false | Password auth needs the `password-auth` feature, which uses argon2id | | `client_writable_keys` | `["settings"]` | Player-data keys that clients may `PUT` | | `max_body_bytes` | 64 KiB | | | `cors_origins` | `[]` | Allowlist for browser clients | | `http_rps_per_ip` / `login_attempts_per_min` | 20 / 5 | | | `motd` | none | Returned by `GET /v1/status` | ### `[fleet]`: game server to player service | key | default | meaning | |---|---|---| | `player_service_url` | `ws://127.0.0.1:8080/internal/v1/fleet` | Fleet WebSocket | | `player_service_http` | `http://127.0.0.1:8080` | Checkpoint upload and download | | `heartbeat` / `lease_ttl` | 2 s / 10 s | A server silent for `lease_ttl` is dead. Its rooms are orphaned and can be restored elsewhere. | ### `[admin]`, `[security]`, `[persistence]`, `[matchmaking]` | key | default | meaning | |---|---|---| | `admin.bind` | `127.0.0.1:9090` | Admin API, `/metrics`, `/healthz`, `/readyz`. Keep it private. | | `security.signing_kid` | `"k1"` | Key that signs tokens. Every listed key verifies. | | `security.keys_env` / `keys_file` | `SPACE3D_KEYS` / none | `k2:,k1:` or a TOML file `{ k1 = "" }`. Rotate by adding k2 everywhere, switching `signing_kid`, and dropping k1 after 30 days. | | `security.fleet_token_env` / `_file` | `SPACE3D_FLEET_TOKEN` | Shared by the PS and the GSs. The fleet WebSocket requires it in the upgrade (`Authorization: Bearer …`) and closes connections that do not register within 10 s; `/internal/v1/*` checks it (and the per-IP rate) before reading a request body. | | `security.admin_token_env` / `_file` | `SPACE3D_ADMIN_TOKENS` | Comma-separated. With no tokens the admin API is open on a loopback bind (only to requests with a loopback `Host` and, if any, a loopback `Origin`: web pages cannot drive it) and locked otherwise. In production every token must be ≥ 16 characters and not a template placeholder (`REPLACE-WITH-...`, `change-me`). | | `security.trusted_proxies` | `[]` | CIDRs whose `X-Forwarded-For` is honoured (every header line, joined in order; the right-most address that is not a trusted proxy is the client). Per-address limits and strikes key IPv4 addresses as is and IPv6 addresses by /64. | | `persistence.data_dir` | `data` | Game-server outbox and local checkpoints | | `persistence.checkpoint_interval` | 10 s | Rooms also checkpoint on phase change, drain and admin request | | `persistence.checkpoint_store` | `player-service` | `none` \| `local` \| `player-service`. With `player-service`, any GS can restore. | | `persistence.recovery_max_age` | 5 min | Older checkpoints are not restored, and are deleted (checked once a minute, 1 min grace) | | `matchmaking.interval` | 250 ms | Matcher period | | `[[matchmaking.queues]]` | none | `name`, `mode`, `teams`, `team_size`, `min_players`, `max_wait`, `rating_window` (+`_growth`), `region_ping_ms` (+`_max_ms`), `backfill`, `params`. The queue whose `mode` matches also sets quick-play room capacity to `teams × team_size`. The default is 16. | **Quick play and lobbies.** Quick play opens rooms only for a mode that a queue configures or that a game server hosts: list them in `GameDefinition::modes` (sent at registration; a game that lists none accepts any mode `validate_spec` allows). An account holds one unused quick-play seat at a time (asking again releases the previous one), makes at most 1 quick play per second (burst 10) and opens at most 3 rooms at once, then 6 per minute. A host has one open lobby at a time; idle lobbies close after 30 minutes. Password logins count failures per (username, address) and per username (4× the per-address budget), and only failures. --- ## 5. Admin API, metrics and health These live on `admin.bind`. **Auth:** - Send `Authorization: Bearer `. Tokens are compared in constant time against SHA-256 hashes. - Every action is written to the audit log. - `/metrics`, `/healthz` and `/readyz` need no token. | method and path | what it does | |---|---| | `GET /healthz` | 200 while the supervisor ticks and every shard heartbeat is under 5 s old | | `GET /readyz` | 200 when the server is not draining, the DB is up, it has registered with the PS once (GS role; a later PS outage keeps it ready), and its shards are alive | | `GET /metrics` | Prometheus text: `space3d_tick_seconds`, `space3d_ticks_skipped_total`, `space3d_rooms{phase}`, `space3d_players{state}`, `space3d_bytes_total{dir,channel="all"}`, `space3d_input_total{result}`, `space3d_handshakes_total{result}`, `space3d_disconnects_total{reason}` (every `DisconnectCode` label plus `link_lost` and `room_inbox_full`), `space3d_rate_limited_total{kind}` (`packets`, `messages`, `link_packets`, `room_inbox`), `space3d_fleet_connected`, `space3d_outbox_pending`, `space3d_checkpoint_seconds`, and on the PS `space3d_logins_total`, `space3d_sessions_active`, `space3d_db_queue_depth`, `space3d_matches_void_total`, `space3d_mm_*`, `space3d_fleet_*`, `space3d_http_*` | | `GET /admin/v1/status` | server id, role, version, schema hash, phase, registration, fleet link state | | `GET /admin/v1/rooms`, `GET /admin/v1/rooms/{id}` | room list and detail: phase, players, tick cost, entities | | `POST /admin/v1/rooms/{id}/close` | Close a room. Body: `{"reason": "…"}`, optional. | | `POST /admin/v1/rooms/{id}/checkpoint` | Checkpoint now. Returns 202. | | `GET /admin/v1/players` | connected players | | `POST /admin/v1/players/{id}/kick` | Kick a player from every room of the server | | `POST /admin/v1/bans`, `GET /admin/v1/bans`, `DELETE /admin/v1/bans/{id}` | Body: `{"player": ""}` or `{"cidr": "10.0.0.0/8"}`, plus `"reason"` and an optional `"duration_s"`. The PS persists bans and pushes them to every GS. A player ban removes the player from every room they are in and refuses their resumes (`Disconnect(Banned)`); an IP/CIDR ban also closes connections already open from that range. | | `POST /admin/v1/broadcast` | Body: `{"text": "…", "room": ""?, "level": "info\|warn"?}` | | `POST /admin/v1/drain` | Same as SIGTERM: not ready, no new rooms, matches finish, final checkpoints, then the process exits 0 once the drain completes (idle, or `drain_timeout`) | | `GET /admin/v1/config`, `GET /admin/v1/schema` | Redacted effective config; the replication manifest, for diffing client builds | | `POST /admin/v1/backup` | PS: `VACUUM INTO` a timestamped copy under `data_dir` | --- ## 6. Scaling **Measured capacity.** These numbers come from the load test in §7.3: - **Setup:** one Apple M4 Max machine (16 cores) runs the server and all bots on loopback. The server uses `--profile server`, is all-in-one, and has 15 shard threads. - **Server tick time:** 200 players in 10 rooms of 20 moving cubes. Mean tick 0.084 ms, p99 ≤ 0.5 ms, no skipped ticks. - **Server resources:** about 20–30 % of one core and 55 MB RSS. - **Traffic:** each client receives about 7.8 KB/s and sends about 0.8 KB/s of application data. Size real games by measuring them. Tick cost grows with game logic, entities per room and clients per room. **Vertical: one game server.** - Rooms spread over `shards` threads. A new room goes to the least-loaded shard, and rooms never migrate. - A room is single-threaded. Keep one room's tick well under the tick budget: 16.7 ms at 60 Hz, and the design target is < 5 ms p99 for 200 clients. - `space3d_tick_seconds` and `space3d_ticks_skipped_total` tell you when a room is too big. - Bandwidth per client is capped by `limits.client_bandwidth`. Priority and interest decide what fits. For large worlds use `InterestPolicy::Spatial`, so each client only receives nearby entities. **Horizontal: more game servers.** - Run N `game-server` processes behind one `player-service`. - Each game server needs a stable `server_id` and its own public URL. For example, a Kubernetes StatefulSet with `gs-N.play.example.com` per pod, or `hostPort` (§3.1). - Allocation picks the least-loaded ready server in the requested region: players plus reserved seats over capacity, plus tick p99 over the budget. Only servers of the client's build qualify: quick play, matchmaking and lobby requests carry `game_id` and `schema_hash` (`PlayerServiceClient::with_build`), matchmaking only matches players of one build, and a restore after a server loss only goes to a server of the room's build. During a rolling deploy that changes the replication schema, old and new clients each land on their own servers. - Seats count both the players in each heartbeat and the join / leave events between heartbeats. Quick play finds or opens a room atomically. So bursts of quick plays neither oversubscribe a room nor scatter over half-empty ones. - Scale on `space3d_fleet_free_seats{region}`, which the PS exports. **Draining and upgrades.** - Draining a game server removes it from allocation. - Match rooms run to completion within `drain_timeout`. A player who rejoins meanwhile goes back to the same room on the draining server (a match is never forked onto a second server). - Persistent rooms warn clients (`Notice::Reconnect`), tell the PS they are moving and, once it acknowledged (at most 2 s), freeze: clients get `Disconnect(ServerShutdown)` and the final checkpoint is captured in the same tick, so it holds everything the players saw. Clients rejoin through the PS (`POST /v1/sessions/rejoin`); the PS already holds that rejoin — it never sends a client back to the draining server — and it waits (up to 10 s, then answers 503 `room_moving` with `retry_after_ms`) until that checkpoint is stored, then the room is restored on another server from exactly that state. A move that has not completed after 30 s is given up on: the rejoin restores the room elsewhere from its last stored checkpoint. A room that panics during its handoff is rebuilt still handing off. The room keeps retrying the upload as long as the process runs; if the checkpoint store stays unreachable until the server stops, that capture is kept in the game server's local database (uploaded on its next start) and the room counts as lost with the server (rejoin restores the newest stored checkpoint). The example client rejoins on any lost session, honouring retry hints (`Reject(ServerDraining).retry_after_ms`, `ApiError.retry_after_ms`) with backoff (0.25 s doubling to 4 s, 8 attempts in a row). - A quick play into the mode of a persistent room that is moving waits for the move the same way (then joins the room where it was restored), and a quick play into the mode of a persistent room that was handed off or lost with its server restores it, as a rejoin would. A ticket the PS issued a moment before it heard of the drain is refused as transient (`Reject(ServerDraining)` with `retry_after_ms`), so its holder asks the PS again. Quick play never opens a second copy of a world while the first one is on its way. - Rooms still open at the drain deadline also report the move and wait for the acknowledgement before they disconnect their clients (their checkpoints stay restorable). - When the drain completes the server deregisters (the PS stops counting it at once) and closes its fleet link cleanly (the PS logs `fleet link closed (server left the fleet)` at INFO; a WARN `fleet link closed` means a server went away without draining). - Set `terminationGracePeriodSeconds ≥ drain_timeout + 30 s` (plus the `preStop` sleep: the grace period includes it; §3.1 has the numbers, and `docker stop -t` / compose `stop_grace_period` follow the same rule). **Failures.** | failure | what happens | |---|---| | Link blip | Resume within `resume_window`: same slot and pawn, with a full resync | | Room panic | Build with `--profile server`, which uses `panic = "unwind"`. The room is rebuilt from its last checkpoint and players rejoin (a room that was draining or handing off stays so). Three crashes in 5 minutes close the room and delete its checkpoint (after every upload still in flight, so none brings it back). | | Game server lost | The lease expires in `lease_ttl`. Rejoin (or a quick play into the mode of a lost persistent room) restores the room from the PS-stored checkpoint on another server of the same game and schema hash; with no such server free, `503 no_capacity` carries `retry_after_ms` (5 s). Clients stop resuming when `resume_window` is over; the example client also asks the PS every 2 s while its reconnect keeps failing, so it is back in the restored room about `lease_ttl` + 2 s after the loss. With `RecoveryPolicy::Abandon` the room is voided instead (audit `match_void`); rejoin answers 404 and players queue again. | | Player service down | Rooms keep playing, results queue in the game servers' durable outbox, and `/readyz` stays ready (`space3d_fleet_connected` shows the link). Logins and matchmaking pause until the PS returns; the outbox then flushes. | | Game server cut off from the PS (PS up) for longer than `lease_ttl` | The game server keeps playing its rooms, but the PS counts it as lost: a player who rejoins meanwhile gets the room restored elsewhere, and that copy is the one that counts. When the link is back, the PS closes the stale copy (`Disconnect(ServerShutdown)`); its players rejoin the live copy and lose what they did in the stale one — including its match results, scores and player-data writes after the point the live copy was restored from, which the PS drops when the outbox replays them. A stale copy that closes on its own (match over, empty) never deletes the live copy's checkpoint. | **Limits of v1.** - There is a single player-service instance. SQLite in WAL mode handles thousands of writes per second. A Postgres `PlayerStore` and an HA matchmaker are deferred. - WebSocket (TCP) is the only transport, so loss shows up as head-of-line stalls (§7.1). QUIC and WebTransport datagrams are deferred. --- ## 7. Testing and measured behaviour | what | where | run | |---|---|---| | Replication unit tests and proptests, harness scenarios (prediction, interpolation, interest, budget, resume, bursts after stalls) | `crates/space3d-replication/{src,tests}` | `cargo test -p space3d-replication` | | Full stack in process: PS, GSs, gatekeeper, tickets, rooms and clients over the conditioned memory network, with manual clocks (`TestCluster`) | `crates/space3d-server/tests/{cluster,acceptance}.rs` | `cargo test -p space3d-server` | | Real sockets: all-in-one; split with lease expiry and restore; separate PS and GS Apps with ticket then connect | `crates/space3d-server/tests/{e2e,split,acceptance}.rs` | same | | Abuse over real sockets: idle / slow / excess sockets, trickled bodies, `X-Forwarded-For` lines, login lockout, cross-site admin requests, lobby limits, audit actor; the deployment files (documented compose command; the Dockerfile's pinned toolchain; the Kubernetes ConfigMap under production validation and restating every example key; grace periods that cover the drain) | `crates/space3d-server/tests/{abuse,deploy}.rs` | same | | Example: WASD through the `ActionMap` in the harness; the shipped `server` plus 2 `client --headless --bot` processes; the split drain handoff with real processes (player service, 2 game servers, 2 bots, SIGTERM the hosting game server mid-play: the room moves, both bots play on; 2 more bots that quick play while it moves join it there, one world); the split crash (SIGKILL the hosting game server: with a 4 s lease both bots are back in the restored room within 12 s). Every process's stdout and stderr is captured and must hold no ERROR line (`SPACE3D_PROCESS_TEST_LOGS=

` keeps them) | `examples/multiplayer_arena/tests/{netcode,processes}.rs` | `cargo test -p multiplayer_arena` | | Load: 200 bots | `examples/multiplayer_arena/tests/load.rs` (`#[ignore]`), `loadtest` binary | see §7.3 | ### 7.1 Lossy network acceptance This is `tests/acceptance.rs`: - **Setup:** 4 clients join through guest login, quick play and a ticket. The link has 100 ms RTT, ±20 ms jitter in each direction and 5 % loss in each direction, with WebSocket (stream) semantics. On a stream, every lost segment stalls everything behind it for a 200 ms retransmission timeout. - **Measurement:** 10 s of play with pawns moving at 4 m/s. Bots change direction every 0.75 s. The run is deterministic (seeded). | measurement | result | |---|---| | Remote pawns: drawn position vs the server's position at the client's render tick | p50 0 mm, p95 0 mm, p99 0.49 m, max 1.9 m. The tail is TCP stalls: at most 100 ms of extrapolation, then hold. | | Own pawn: predicted vs authoritative, all ticks | 94.2 % exact, p99 1.85 m. Mispredictions happen only when an input stalled behind a lost segment and the server repeated the previous one. This affected 7.5 % of client ticks (171 of 2295). | | Own pawn after reconciliation (the server had the inputs) | **100 % exact** (1356 samples), no snaps | | What the player sees (smoothed correction) | p95 0.07 m | | After input stops | every client within 1 mm of the server | | Session resume after a 3 s blackout | same slot, same pawn and `NetId`, on a fresh link | | Bandwidth, 4 movers | about 1.7 KB/s down and 0.85 KB/s up per client (application bytes) | | Bandwidth, 300 moving NPCs with a 12 KiB/s budget | 11.9–12.0 KB/s down per client, and every client knows every NPC | ### 7.2 Local smoke `examples/multiplayer_arena/tests/processes.rs` runs the real binaries: 1. Start `server` and two `client --headless --bot --ps …` processes over localhost WebSockets for 4 s. 2. Both bots connect and see both cubes, with about 1.2 KB/s down and 0.65 KB/s up at around 23 ms loopback RTT. The RTT is frame-quantized. 3. SIGTERM drains the server, which exits 0. The whole test takes about 8 s. ### 7.3 Load test Run it against a server you started: ```sh cargo build --profile server -p multiplayer_arena --no-default-features --bin server --bin loadtest SPACE3D__MATCHMAKING__QUEUES='[{ name = "arena", mode = "arena", teams = 1, team_size = 20, min_players = 1, backfill = true }]' \ target/server/server & target/server/loadtest --ps http://127.0.0.1:7777 --queue arena --quick-play --clients 200 --ramp 50 \ --duration 20 --metrics http://127.0.0.1:9090/metrics --slo-tick-p99-ms 4 ``` Or run it as a test, which starts the server itself: `cargo test -p multiplayer_arena --release --test load -- --ignored --nocapture` (`LOAD_CLIENTS`, `LOAD_SECS`). The load test prints a JSON report. Exit codes: 0 means every SLO held, 1 means an SLO failed, 2 means a setup error. Recorded run: 200 clients, 20 s after a 4 s ramp. The server was built with `--profile server` on an M4 Max, with the bots on the same machine. | | result | |---|---| | connected | 200 / 200, 10 rooms, no disconnects | | handshake (connect → synced) | p50 36 ms, p99 53 ms | | RTT (loopback) | p50 17 ms, p99 24 ms | | per client down / up | p50 7.8 / 0.81 KB/s, p99 8.2 / 0.85 KB/s | | snapshot rate | 100 % of nominal (30 Hz) | | rollbacks | 0.06 per client per second | | server room tick | mean 0.084 ms, p50 ≤ 0.25 ms, p99 ≤ 0.5 ms (histogram buckets), 13 336 ticks, 0 skipped | | server replication traffic | 1.39 MB/s out, 0.15 MB/s in | | server process | 55 MB RSS; `ps` reported 29 % CPU (average over the process lifetime) | The unoptimised test profile (`cargo test` without `--release`) showed a tick mean of 0.19 ms, a p99 ≤ 1 ms, and 3 skipped ticks out of 13 335. # Storybook A **story** is an isolated, parameterized setup — a prop, a material, a camera rig, a level chunk, a UI panel — that you can look at without playing the game to get there. Stories come from `space3d-stories` (facade feature `stories`) and are used three ways: 1. **Interactively** — `space3d stories` opens the storybook viewer from `space3d-editor` (story tree with search, live viewport, knob widgets, tick controls, screenshot capture). 2. **As a gallery** — `space3d stories --headless --out target/stories` renders every story to PNG plus `index.html` and `manifest.json` (knobs, backend, draw calls, timings). 3. **As tests** — every story is a golden screenshot test. ## Writing stories ```rust use space3d::prelude::*; pub fn storybook() -> Storybook { let mut book = Storybook::new(); book.add( Story::new("Props/Crate stack", |app, knobs| { let height = knobs.i64("height"); let tint = knobs.color("tint"); app.add_plugin(PhysicsPlugin::default()); app.add_system(Stage::Startup, move |ctx| { /* spawn crates, light, camera */ }); }) .description("A physics-stacked tower of crates") .knob_i64("height", 4, 1..=8) .knob_color("tint", [0.8, 0.55, 0.3, 1.0]) .ticks(30) // simulate 30 fixed ticks before capturing .size(256, 256), // capture size ); book } ``` * The id `"Group/Sub/Name"` organizes the viewer and gallery. * A story's setup only **adds content** (entities, resources, game plugins). The host adds window/render/input plugins — so the same story runs in the viewer, headless and in tests. * Knobs: `knob_bool`, `knob_f32`, `knob_i64`, `knob_color` (linear RGBA), `knob_text`, `knob_choice`; read them with `knobs.f32("name")`, … Defaults are filled in for missing values; `Knob::clamp` sanitizes UI input. * Tags: `.tag("slow")`; the `no-screenshot` tag excludes a story from galleries and golden tests (e.g. for stories that only make sense interactively). * `.tolerance(0.02)` loosens the screenshot comparison for one story. The engine ships its own book (`space3d::stories::engine_storybook()`: lighting, materials, instancing, textures, cameras, hierarchies, physics, the graphics areas `Engine/Frame/*`, `Engine/Materials/*`, `Engine/Environment/*`, `Engine/Lights/*`, `Engine/Post/*`, `Engine/Particles/*` and `Engine/Showcase/*`, and the UI stories `Engine/UI/Theme/*` and `Engine/UI/Tools/*` — see [ui.md](ui.md)) — `book.extend(engine_storybook())` to browse both. The UI stories need egui, so they sit behind `space3d-stories`' `ui` feature (not a default): the editor's storybook viewer turns it on, and so does the facade's `stories` feature (which thus builds egui even without the facade's `ui`; `cargo test -p space3d-stories --features ui` checks their goldens alone; `cargo test --workspace` always does). The facade deliberately does not tie it to its `ui` feature with a weak `space3d-stories?/ui`: Cargo writes every package such a feature could reach into the lockfiles of downstream crates, so a game with `ui` but no `stories` would list the storybook's whole tree (physics, rapier, the test harness) without ever building it. The viewer itself uses the compact UI density. The **showcase** stories put every graphics feature together: `Engine/Showcase/SpaceCorps Look` (a close-up skirmish in the SpaceCorps top-down view: PBR hulls with all maps, the nebula skybox and its image-based lighting, shadows on asteroids, engines, beams, bolts, a missile's ribbon, an explosion with its shockwave, a warp; a `quality` knob over the `GraphicsQuality` tiers and toggles for shadows, IBL, bloom and distortion), `Engine/Showcase/Battle` (the graphics spec's reference scene: 300 ships, 100k particles, two render-target previews in the corner), and both again under `DownlevelOverride::webgl2()` at Low (`Engine/Showcase/WebGL2 *`). Their content and scenes are public (`space3d::stories::showcase`) and shared with `examples/graphics_showcase` and the graphics benchmarks. See [graphics.md](graphics.md). ## The storybook binary Projects created by `space3d new` have `src/bin/stories.rs`; `space3d stories [args]` runs it as `cargo run --bin stories -- [args]`: | command | does | |---|---| | `space3d stories` | opens the viewer (`space3d::editor::run_storybook_with`) | | `space3d stories --filter crate` | opens the viewer on the first story whose id or tags contain "crate" | | `space3d stories --list` | prints ids and descriptions | | `space3d stories --headless --out shots` | renders the gallery into `shots/` (exit code 1 if a story failed) | The headless gallery uses `space3d::stories::screenshot_all(&book, out_dir, filter)`; each story runs in a fresh `TestApp` with the story's size and tick count, inside `catch_unwind`, so one broken story does not stop the rest. Without a GPU, stories are reported as skipped. ## Stories as golden tests ```rust // tests/screenshots.rs space3d::stories::storybook_tests!(my_game::stories::storybook); ``` This generates one `#[test]` that renders every story (except `no-screenshot`) and compares it against `tests/__screenshots__//.png` using the usual golden workflow (first run writes, `space3d test --update-snapshots` re-blesses, diffs + HTML report on failure). For more control use `check_storybook` / `assert_storybook_in` with `StorybookTestOptions`. # Testing Space3d games are tested with plain `cargo test` (or `space3d test`, which adds a report). The harness is `space3d-test`, available through the facade's `test` feature: ```toml [dev-dependencies] space3d = { …, features = ["test"] } ``` ```rust use space3d::prelude::*; use space3d::test::prelude::*; ``` ## `TestApp`: deterministic and headless `TestApp` wraps an `App` so that **every step is exactly one fixed tick** — no wall clock, no window. It adds `InputPlugin` and `RenderPlugin`, plus a headless renderer when a GPU adapter exists. ```rust let mut app = TestApp::headless(320, 240); // renderer if available let mut app = TestApp::no_render(); // simulation only (fastest) app.add_plugin(my_game::GamePlugin); app.step(); // one tick (runs Startup first) app.step_ticks(60); // one second at 60 Hz app.run_until(|app| app.count::() == 0, 600)?; ``` World helpers: `find_by_name`, `translation`, `get::`, `single::`, `count::`, `entities_with::`, `resource::`, `events::`. ## Input simulation ```rust app.hold_key(KeyCode::ArrowRight, 30); // press, 30 ticks, release app.tap_key(KeyCode::Space); app.click(MouseButton::Left, Vec2::new(100.0, 80.0)); app.drag(MouseButton::Left, from, to, 20); app.touch_tap(Vec2::new(250.0, 128.0)); app.swipe(from, to, 15); app.pinch(center, 100.0, 200.0, 20); app.gamepad_press(0, GamepadButton::South, 5); ``` Longer sequences are `InputScript`s (tick-relative events, serializable as RON). Record one from a real play session with `InputRecorderPlugin` and replay it in a test: ```rust let script = InputScript::new() .hold_key(0, KeyCode::ArrowUp, 50) .hold_key(20, KeyCode::ArrowLeft, 25); app.play(&script); ``` Because simulation runs on fixed ticks, the same script always gives the same result — `assert_deterministic` runs two apps in lockstep and compares world fingerprints every tick. Keyboard layouts: `tap_key`/`inject_key_*` press physical keys only. To test what a player on another layout sees (UI shortcuts, typed text, key labels), inject the logical key too — the same `KeyEvent` the window runner records ([Keyboard layouts](platforms.md#keyboard-layouts)): ```rust let input = app.input(); // &mut space3d_platform::Input // AZERTY: the key labelled Z sits in QWERTY's W position. input.inject_key_tap_logical(KeyCode::KeyW, LogicalKey::Character("z".into())); input.inject_key_event(KeyEvent::press(KeyCode::Digit2, LogicalKey::Character("é".into())) .with_logical_key(LogicalKey::Character("2".into()))); // with Shift held assert_eq!(input.key_cap(KeyCode::KeyW), "Z"); // learned from the event ``` Mouse buttons: `Input::mouse_button_events()` lists the frame's presses and releases in order. A focus loss is `WindowState::focused = false` plus `Input::release_all()` (what the window runner does); its releases are cancels, like a release only the OS saw (`Input::release_mouse_button(b, MouseButtonCause::OsReconciled)`): the UI registers no click and no drop for them ([Mouse buttons, focus and the UI](platforms.md#mouse-buttons-focus-and-the-ui)). A release the runner's OS check makes never touches a press a test injected: only presses of the window's own events are checked against the OS, and only while the window has the focus outside background mode, so a developer's physical button cannot release a scripted press. The recorder (`InputRecorderPlugin`) records a cancelled release as `InputEvent::MouseCancel { button, cause }` (script builder `mouse_cancel`; `MouseUp` stays a device release) and replays it through `Input::release_mouse_button`, so a replay's UI sees the same cancel. A touch the system cancelled (`TouchPhase::Cancelled`, `Input::just_cancelled_touches`) is recorded as cancelled too and is no tap. `InputEvent` is `#[non_exhaustive]`: a `match` on it needs a wildcard arm (scripts written before load as they did). Tests on libtest threads never read the developer's own layout on macOS (Text Input Sources are main-thread only), so learned labels keep them deterministic. The OS tables themselves are tested on the main thread by `crates/space3d-platform/tests/os_layout.rs`, a custom harness (`harness = false`); it skips on macOS without a GUI login session. ## Golden screenshots ```rust #[test] fn title_screen() { require_gpu!(); // skip (not fail) without a GPU let mut app = TestApp::headless(320, 240); app.add_plugin(my_game::GamePlugin); app.step_ticks(2); assert_screenshot!(&mut app, "title_screen"); assert_screenshot!(&mut app, "title_lenient", CompareOptions::perceptual()); } ``` * Goldens live in `/tests/__screenshots__/.png`. **The first run writes them** — review and commit them. * On mismatch the test fails and writes `.actual.png` and `.diff.png` next to the golden (ignored by the generated `.gitignore`). * Re-bless intended changes: `space3d test --update-snapshots` (sets `SPACE3D_UPDATE_SNAPSHOTS=1`). * GPUs differ slightly: `CompareOptions` has per-channel tolerance, allowed differing-pixel fraction and SSIM; `SPACE3D_SNAPSHOT_VARIANT=backend|os|os-backend` stores per-platform goldens when a backend renders visibly differently. ### Environment switches | variable | effect | |---|---| | `SPACE3D_UPDATE_SNAPSHOTS=1` | re-bless goldens instead of comparing | | `SPACE3D_CI=1` / `CI=true` | a missing golden is a failure (not silently written) | | `SPACE3D_SNAPSHOT_VARIANT=…` | write platform-specific goldens | | `SPACE3D_REQUIRE_GPU=1` | fail instead of skip without a GPU | | `SPACE3D_NO_GPU=1` | pretend there is no GPU (test the skip paths) | | `SPACE3D_TEST_REPORT=dir` | write `results.jsonl`, `report.json`, `index.html` | | `SPACE3D_PERF_BUDGET_SCALE=2` | loosen performance budgets on slow machines | ## `space3d test` ```sh space3d test # cargo test + report summary space3d test -- player # test-name filter space3d test --update-snapshots space3d test --report out/report # default: target/space3d-report space3d test --workspace ``` After the run it prints counts per status (passed / failed / created / skipped), every failed screenshot with its diff image, and the path of the HTML report (expected / actual / diff side by side). Each run starts a fresh report: the previous report's own files (`results.jsonl`, `report.json`, `index.html`, `images/`) are removed, nothing else. A `--report` directory that is not empty and holds no previous report (e.g. `--report docs`) is refused rather than cleared. ## Performance assertions ```rust assert_frame_budget(&mut app, 120, Duration::from_millis(4)); // average CPU frame time RenderBudget::new() .max_draw_calls(10) .max_bytes_uploaded(64) // a static scene should upload (almost) nothing .assert_frame(&mut app); // renders one frame, checks its RenderStats ``` `space3d_test::install_counting_allocator!();` (once per test binary) + `assert_max_allocations(n, || app.step())` catch per-frame allocations. ### Headless frame timing The headless runner (no window) paces frames in real time against deadlines: frame *n* is due at `start + n × step`, so an OS sleep that overshoots (4–5 ms is common on macOS) shortens the next sleep instead of adding to every frame. Frame-to-frame `Time::delta` is therefore *pacing* (≈ the fixed step), not cost. To measure what a frame costs: * read `Time::update_duration` — the CPU time of the previous `App::update` (all stages, excluding any sleep or vsync wait); * or run unpaced: `SPACE3D_HEADLESS_UNPACED=1` (or insert `HeadlessPacing::Unpaced` before `App::run`). Frames then run back to back and each advances time by exactly one fixed step, which is deterministic and shows throughput directly (e.g. 600 frames of a 60 Hz game in well under a second). ## CI The workflow generated by `space3d new` / `space3d ci init` runs `cargo fmt --check`, `cargo clippy -D warnings` and `cargo test` on Ubuntu with Mesa's software Vulkan driver (lavapipe), so screenshot tests really render in CI; on failure it uploads `*.actual.png` and `*.diff.png` as an artifact. # UI `space3d-ui` runs egui inside the engine: `UiPlugin` translates input in `Stage::PreUpdate`, UI systems (`app.add_ui_system`, `app.add_root_ui_system`) run in `Stage::Update`, and the frame is tessellated in `Stage::PostUpdate` and drawn by the renderer's overlay hook (so it shows up in headless screenshots). `UiPlugin::deterministic()` gives reproducible pixels for golden tests. Pointer, focus and egui plugin details: [platforms.md, "Mouse buttons, focus and the UI"](platforms.md#mouse-buttons-focus-and-the-ui). ## Theming: the compact density egui's default sizes are generous for tool panels and HUDs. The engine ships a **compact preset** — dense editor panels in the spirit of Blender or Unity that stay readable at 1 pixel per point — and it is strictly **opt-in**: ```rust app.insert_resource(space3d_ui::UiTheme::compact()); // space3d::ui::UiTheme with the facade ``` * **Without the resource the app's UI does not change.** The engine never writes egui's `Style` unless a `UiTheme` resource exists: the UI of an app that does not opt in renders exactly as before, pixel for pixel. * **The engine's dev tools are compact in every app.** The F3 overlay, F4 profiler and console are the engine's tools, not the app's UI: with or without a `UiTheme` they have their own compact look, and they get it by restyling only their own windows (a scoped copy of the style on their own `Ui`s) — never the global style, never the app's windows. See [In-game tools](#in-game-tools). * **Applied once, between passes.** `UiPlugin` applies the theme when the resource is inserted or changed, right before the next egui pass begins, to both the dark and the light style. In every other frame it costs one comparison and no allocation (`UiThemeSync`; tokens compare bit for bit, so even a NaN token counts as unchanged); there is no per-frame style churn. * **Sizes only.** The theme writes the tokens below. Colors, fonts (families), shadows, animation time and every other `Style` field keep the values the context has, so the preset also works on top of a game's own look. * **Removing the resource** leaves the style as it is (the engine does not restore anything). Inserting a theme again applies it again. `UiTheme::Compact(UiDensity)` is the engine preset (`UiTheme::compact()`, possibly tweaked); `UiTheme::Custom(UiDensity)` names a density of your own. Both are applied the same way: ```rust use space3d_ui::{UiDensity, UiTheme}; app.insert_resource(UiTheme::Custom(UiDensity { body_size: 13.0, button_size: 13.0, ..UiDensity::compact() })); ``` ### Tokens | token | egui `Style` field | compact | egui default | why | |---|---|---|---|---| | `item_spacing` | `spacing.item_spacing` | 6 × 2 | 8 × 3 | rows 1 pt closer, columns 2 pt | | `button_padding` | `spacing.button_padding` | 4 × 1 | 4 × 1 | already tight | | `window_margin` | `spacing.window_margin` | 4 | 6 | also the engine tools' panel margin | | `menu_margin` | `spacing.menu_margin` | 3 | 6 | menus, popups, tooltips | | `control_height` | `spacing.interact_size.y` | 18 | 18 | the smallest hit target stays 18 pt | | `control_min_width` | `spacing.interact_size.x` | 32 | 40 | narrower drag values / color buttons | | `indent` | `spacing.indent` | 14 | 18 | tree levels, collapsing bodies | | `icon_size` | `spacing.icon_width` (inner: 4/7) | 12 | 14 | checkbox / radio / collapse icons | | `icon_spacing` | `spacing.icon_spacing` | 4 | 4 | | | `slider_width` | `spacing.slider_width` | 90 | 100 | | | `combo_width` | `spacing.combo_width` | 84 | 100 | | | `text_edit_width` | `spacing.text_edit_width` | 160 | 280 | egui's 280 pt fields waste the most room | | `scroll_bar_width` | `spacing.scroll.bar_width` | 8 | 10 | | | `heading_size` | `TextStyle::Heading` | 14 | 18 | window titles too | | `body_size` | `TextStyle::Body` | 12.5 | 13 | readable at 1 ppp | | `button_size` | `TextStyle::Button` | 12.5 | 13 | also drag values | | `small_size` | `TextStyle::Small` | 10 | 9 | 9 pt is hard to read; 10 still small | | `monospace_size` | `TextStyle::Monospace` | 12 | 13 | | | `widget_radius` | `visuals.widgets.*.corner_radius` | 2 | 2 (3 hovered) | one radius for every state | | `window_radius` | `visuals.window_corner_radius` | 4 | 6 | | | `menu_radius` | `visuals.menu_corner_radius` | 3 | 6 | | | `table_row_height` | — (read by tables) | 16 | — (18) | text rows; rows with controls stay 18 | | `tooltip_delay` | `interaction.tooltip_delay` | 0.3 s | 0.5 s | snappier tool tips | `UiDensity::egui_default()` holds the right-hand column. egui's `Style` has no table row height: tables read it with `UiDensity::row_height(ui)` (the applied theme's `table_row_height`, or the style's control height without a theme) or `UiDensity::of(ctx)`. Both only report a theme that still holds: after the `UiTheme` resource is removed, or once the game changed the style's sizes after the theme was applied (colors do not count), `of` is `None` and `row_height` follows the style again: ```rust egui::Grid::new("assets") .striped(true) .min_row_height(UiDensity::row_height(ui)) .show(ui, |ui| { /* ... */ }); ``` The pure functions are public too: `compact_style(&base, &density) -> egui::Style`, `apply_density(&mut style, &density)` and `apply_theme(&ctx, &theme)`. For tool panels, `visible_scroll_bars(width)` is a `ScrollStyle` whose bars stay visible while content is hidden, keep a column of their own and draw the handle in the text color (so it shows on any palette): `ui.spacing_mut().scroll = visible_scroll_bars(8.0)`. ### How much denser `ThemePreview` is a representative tool panel (menu bar, toolbar, buttons, checkbox, slider, combo box, text field, a collapsing section and a 10-row striped table). Its width is that of its "Space [combo] Name [text field]" row at the style's default widths (`ThemePreview::panel_width`), and every other row fills it: the slider rail, the transform fields and the table's columns (numbers and their headers right-aligned). With the compact preset it takes **338 × 354 pt instead of 487 × 390 pt — 63.1 % of the area** — with every widget whole, no text wrapped or clipped and every control at least 18 pt tall (`crates/space3d-ui/tests/theme.rs`). The stories `Engine/UI/Theme/Default` and `Engine/UI/Theme/Compact` show the same panel side by side, each in an `egui::Window`. ### Window width The theme holds sizes of egui's `Style`; the width of a window is not one of them. An `egui::Window` is **340 pt wide by default whatever it holds** (its contents fill that width), so a small game window ("Cargo hold: 12 t [Jettison]") keeps a lot of empty space under any theme, `UiTheme::compact()` included. That width is the game's choice, not the theme's: the engine does not resize an app's windows (its own tools size themselves). To size game windows compactly: * `.auto_sized()`: the window takes the width of its contents. Give the contents a width (`ui.set_width(..)`, fixed-width widgets): widgets that fill the available width — separators, right-to-left rows, `TextEdit::desired_width(f32::INFINITY)` — stretch an auto-sized window to the screen edge (its first frame spans the screen, so pin it with `fixed_pos` or keep it clear of the edges); * or `.default_width(w)` (with `.resizable(false)` for a fixed width). ```rust // A small HUD window as wide as "Salvage: 12 t [Jettison]", not 340 pt. egui::Window::new("Cargo hold") .fixed_pos([520.0, 300.0]) .auto_sized() .show(ctx, |ui| { ui.label("Salvage: 12 t"); let _ = ui.button("Jettison"); }); ``` ### Games that style egui themselves A game that sets egui's `Style` itself (say, once at startup) needs to do nothing: without a `UiTheme` resource the engine never touches the style. Should it want the compact sizes under its own colors and fonts, it has two options: * insert `UiTheme::compact()` (or a `Custom` density): the tokens are written over the game's style at the start of the next frame, once. A game that restyles later is not overwritten — the theme is applied again only when the resource changes (or call `apply_theme` yourself); * or build its style from the preset: `compact_style(&my_style, &UiDensity::compact())`. ## In-game tools The debug overlay (**F3**), profiler (**F4**) and console (**`**) show up inside games, so they never read their sizes from the global style and never change it. They are the engine's tools, not the app's UI: they are compact **in every app**, with or without a `UiTheme`. Each applies the compact density to its own `Ui` only (cached copies of the style, none per frame), keeps the context's colors, and draws its own compact header (egui's title bar height follows the global heading size). Their size and layout are the same under egui's default, the compact theme or a game's roomy style; only the colors follow the game's (story `Engine/UI/Tools/Game Style`, `crates/space3d-ui/tests/tools.rs`). Text people read — the header summaries, counts, log targets — is in the normal text color. Weak text (trace / debug log lines, placeholders) takes an opacity derived from the palette: the least, from the palette's own `weak_text_alpha` up to 0.85, at which it reaches 65 % of the normal text's contrast on the window fill (at least 3:1, at most 4.5:1) — about 0.78 on egui's greys (3.4:1 where egui's 0.6 gives 2.4:1), and egui's 0.6 under a bright game palette, where that already reads at 5.9:1 and stays clearly dimmer than the 16:1 of normal text. Scroll bars stay visible while content is hidden, with the handle in the text color (`visible_scroll_bars`). ### Docking The tools dock to the corners of the **dock area**, 6 pt in from its edges (and from each other): the overlay top-left, the profiler top-right, the console bottom-left (in an area too short for that, side by side: [Short dock areas](#short-dock-areas)). The dock area is the whole screen, or the `ToolDockArea` resource when a host sets it: hosts that cover part of the screen with their own panels set it every frame to what is left, and the tools then never cover their menu bars or side panels — the editor sets it to its viewport (between the menu bar, hierarchy and inspector; the whole screen while F1 hides the editor), the storybook viewer to the story viewport. An area partly off screen is clipped to the screen; one too small to hold a tool window is ignored. A game with panels of its own can do the same: ```rust app.add_root_ui_system(|ui: &mut egui::Ui, sys: &mut SystemCtx| { egui::Panel::right("inventory").show(ui, |ui| { /* ... */ }); // The tools draw early in the frame: they use the area set in the previous one. space3d_ui::set_tool_dock_area(sys.resources, ui.available_rect_before_wrap()); }); ``` * **Docked tools follow the dock area.** When the window or a panel is resized — larger or smaller — the docked corner goes to the new corner, and a tool the user has not resized takes its default size for the new area: the same layout as an app started at that size (the console 40 % of the new height; a profiler above it, the room left over it). A tool the user resized — larger or smaller — keeps that size, capped to the area and to the room the other tools leave it, and gets it back when the area grows again. A resize changes only the edges it drags: dragging the console's right edge leaves its height (a whole number of log lines) as it was. * **Dragging a tool undocks it**: it stays where it was put (inside the screen) until its title is double-clicked, which docks it again. Clicks inside a docked tool, or resizing it by a free edge (the console's top or right edge, the profiler's left edge), leave it docked; resizing it by a docked edge undocks it. * **Above the game's windows**: the tool windows sit on egui's foreground layer (with menus and popups, under tooltips), so a game window (egui's middle layer) never draws over them. Windows that must be able to come in front of the tools share that layer: the editor's texture and model editors do. Within the layer the window opened or clicked last is in front — clicking an editor window brings it over F3 / F4 / the console, clicking a tool brings the tool back. The debug overlay never takes the pointer: a window opened or clicked after it covers it (toggle F3 twice to bring it back on top). The profiler is exactly as tall as its contents, up to 45 % of the dock area's height (at least 300 pt, but never more than the area) and never down into the open console. With the debug overlay open beside it (small screens, e.g. 640 × 360 pt at 2x) it ends 6 pt right of the overlay, down to 240 pt wide (where names would get narrower than 12 digits, under about 370 pt, its table keeps the avg and calls columns only); when not even that fits (a tall, narrow screen such as a phone held upright) it docks under the overlay if 160 pt fit there. Its table scrolls by whole rows (no row is ever cut), under a header whose titles sit right above their right-aligned columns whether or not the scroll bar takes a column of its own. In a window too short for its two sections and 3 table rows (all its rows, with fewer systems; under about 190 pt) it leaves out the *Timeline* and *Systems* section headers — the flame view and the table stay, always open — so 3 rows still fit in about 150 pt. The console is 640 × 40 % of the dock area (140–360 pt), a whole number of log lines tall (stuck to the newest line, the oldest shown is never a sliver; at least 3 lines, about 125 pt), and wraps long lines (paths, backtraces) under their message instead of widening. It lays out only the lines in view (the others keep the height measured when they arrived, or when the log's width last changed), so its cost per frame does not grow with the 1000 lines it holds. #### Short dock areas A game whose HUD leaves only a band of the screen free sets a dock area too short to stack the tools (SpaceCorps2027: 1024 × 233 pt of a 1024 × 640 screen, where the overlay, the profiler's 300 pt and the console's 40 % used to overlap). The console then docks beside the tools instead of under them, so all three stay inside the area and apart: * **Right of the overlay** when the overlay reaches down into it: the overlay's height, 6 pt and the console's height as drawn (a whole number of log lines: about 125 pt of its default 140 pt) are more than the area's height. It stays docked at the bottom. * **Left of the profiler** when the profiler's smallest layout with 3 table rows (about 150 pt, measured as drawn; before its first frames only its message, about 76 pt) does not fit above the console as drawn; the profiler then takes the area's height. The profiler gives up width (440 down to 240 pt) before the console gets narrower than 320 pt; a profiler the user narrowed leaves the console the room. * With neither tool above it the console is **as tall as the area** (up to 360 pt) instead of 40 % of it. In the band above: overlay | console (347 pt wide) | profiler (440 pt), each as tall as the area's 221 pt allow. * When the area gets tall again the tools **dock back** to their corners, at the sizes a fresh start at that area gives them. A console or profiler the user resized docks by the same rules at its own size, squeezed only as far as the area and the other tools need, and gets that size back when the area is tall again (the console widened to 890 pt is 347 pt in the band above, 890 pt again after it); a dragged one floats and is left out. * **Resizing one toward the other stops a gap before it**, on every frame of the drag: the console's right edge at the profiler (as wide as the user left it), the profiler's left edge at the console. In a wide, short area where the profiler is clear of the console (1920 × 260 pt) both keep their places, the console its height. * **Overlap only where nothing else fits.** Side by side needs an area about 640 pt wide (overlay 213, console 160, profiler 240 and the 6 pt gaps). In a narrower short area the console still docks right of the overlay, under the profiler, which shows what rows fit (at least one, about 115 pt; without frames yet its message, which wraps there, about 90 pt); when not even that fits the two overlap, the one opened or clicked last in front (the console, when both open together, covers the profiler's last row). With the overlay alone the console needs 160 pt right of it or keeps its corner under the overlay. The overlay (about 145 pt tall with render stats, 200 with its details) and the smallest profiler and console (3 log lines, about 125 pt) do not shrink further, so each reaches past the edges of an area shorter than it and its gaps — the overlay under about 157 pt (212 pt with its details), the console under about 137 pt: the overlay and the profiler past the bottom edge (the profiler is cut off there), the console, docked at the bottom, past the top one — its title row is cut off (its key, backquote by default, still closes it), its newest lines and command line stay in the area. * Normal and tall areas, and short ones where the stacked layout fits as drawn (a 1100 × 300 pt band), keep the layout above: the console moves only when the stacked layout would overlap. The first tool system to run in a frame computes the plan and the others take it (`space3d-ui/src/dock.rs`); the edges the console docks against beside the others (the area's own left edge too) snap to the pixel grid, so the 6 pt gaps stay whole on a dock area off the grid. * **Debug overlay** (`DebugOverlay`): a small panel at the top-left that never takes the pointer, opaque (the renderer blends in linear space, where a translucent black lets a bright scene or window through far more than its alpha suggests: at 98 % the text of a window under it still showed between the values; its labels keep 8:1) — FPS, average and worst frame time, a sparkline of the last 240 frames (60 / 30 Hz guides), and a monospace grid of label/value pairs with right-aligned numbers: frame, tick, rate, dropped ticks, entities, alpha, draws, triangles, drawn instances, uploaded bytes, egui primitives and vertices; the last line names the other tools' keys. `DebugOverlay::details` (console: `debug details`) adds the draw path, indirect / multi draws, batches, views, culled instances and instance bytes. Each grid row is one text the values are written into (no string per label or value). * **Profiler** (`Profiler`): header with the last frame's time, span count and a close button; Freeze / Timing toggles; collapsible, full-width *Timeline* (flame view; names truncated with "…", full name and time on hover) and *Systems* (striped table sorted by average time: a bar of the average, the name — truncated, full name on hover — and right-aligned avg / last / max / calls columns under a fixed header) sections. Names are shortened to their last two path segments, generic arguments to their last (`events::Events`). `Profiler::record(FrameTimeline)` aggregates frames from other sources (recordings, replays, tests). * **Console** (`Console`): level / filter / clear toolbar (the filter fills the row), one dense monospace line per entry — the level tag in a column of its own, then target and message; a wrapped entry continues under its message — and the command line. `Console::capture_logs = false` keeps only the console's own lines (command output and `Console::print`). ## Engine tools `run_editor` / `editor_app` and `run_storybook` / `storybook_app` insert `UiTheme::compact()` themselves. Their panels use property rows (a label column in the normal text color and the value on one line, shared by every section so values align), collapsible component sections with header actions (remove, edit JSON), and panel margins from the style. Rows never ask for more than the panel's width, under any style or density: sliders get a fixed-width value box (the same in every row, so the boxes line up) and the rail takes the rest; x / y / z and paired fields split the row into equal cells (axis color bars instead of "x " prefixes) and drop decimals before they would widen it; groups of checkboxes or buttons wrap within the value column; actions sit in rows of equal cells as wide as the property rows (the texture editor's "Apply …", flip and rotate rows), so every slider's value box stays in one column. Rows reuse the styles they derive (slider widths, header spacing, scroll bars) frame after frame instead of copying the `Style` per row. The side panels keep their width frame after frame and whatever is selected (hierarchy 160–400 pt, inspector 220–480 pt), their scroll bars stay visible while content is hidden, and buttons (the section "×" included) are at least 18 pt tall. A slider's rail stays at least two control heights long: in a narrow column with big fonts the value box gives up room first (down to three digits), and the texture and model editors' tool columns grow with the body text size. The menu bar is as tall as egui's own top panel (one control plus 2 pt above and below), and the texture and model editors open over the viewport, 6 pt clear of the menu bar and the side panels (`TextureEditor::show_in`, `ModelEditor::show_in` with the viewport rect; `show` keeps egui's placement). Both sit on egui's foreground layer with F3 / F4 / the console, so the one opened or clicked last is in front (see [Docking](#docking)). The editor and the storybook viewer set the `ToolDockArea` to their viewport, so F3 / F4 / the console dock there too. `EditorPlugin` added to a game does **not** insert the theme: the game's style stays as it is (insert the theme yourself to get the same density), and its panels still keep their width. ## Fonts for Chinese, Japanese and Korean egui's built-in fonts have no Han characters, kana or Hangul: add a font that has them, e.g. right after the Latin font so that it also draws the full-width punctuation (,。!()), which egui's emoji fonts would otherwise draw: ```rust use space3d::ui::egui::{self, FontData, FontDefinitions, FontFamily}; use std::sync::Arc; let mut fonts = FontDefinitions::default(); fonts.font_data.insert("cjk".into(), Arc::new(FontData::from_static(CJK_FONT_BYTES))); for family in [FontFamily::Proportional, FontFamily::Monospace] { let faces = fonts.families.entry(family).or_default(); faces.insert(faces.len().min(1), "cjk".into()); } ctx.set_fonts(fonts); // `EguiContext::ctx()`, or in a UI system ``` ## Chinese and Japanese line breaking (kinsoku) Space3d's egui breaks Chinese and Japanese text by the kinsoku (禁則処理) rules of JIS X 4051 and the W3C JLREQ/CLREQ: no line starts with a closing bracket or quote, a comma or full stop (、。,.), a colon, ?, !, a middle dot, a small kana (ッ ャ ェ), the prolonged sound mark ー, an iteration mark (々), a postfixed sign (% ℃), an ellipsis or a Bopomofo tone mark (ㄏㄠˇ); no line ends with an opening bracket or quote (「(【“) or ¥, also not across spaces (「 重要 」); "——" and "……" stay whole; Latin words and numbers inside CJK text stay whole and get breaks around them. A run the rules keep together that is wider than the row breaks where the row is full, never inside "——" "……" that fit a row, and the rules never make a row wider than the wrap width, also in a label after another widget in `horizontal_wrapped` (egui indents its first row; only that row can be left empty, when the label's first run doesn't fit after the widget). Upstream egui starts lines with "," "?" ")" "、" and ends them with "「". Text without Chinese or Japanese characters lays out as with upstream egui (German „…“ quotes included), except for two rules of Unicode line breaking (UAX #14) that hold in every script and ellipses and doubled dashes: no line ends with an ASCII opening bracket `(` `[` `{` (also not with the spaces after it) and none starts with a no-break space U+00A0 unless a space comes before it — a chat line's company tag joined to the name with a no-break space ("[T]\u{a0}Name:") moves to the next row whole and a name wider than a row breaks inside the name, where upstream left "[T]" alone ("[T]" | "\u{a0}Name:") or split it ("[" | "T] Name:"); no line starts with "…" after a word and "——" "……" are not split, so at narrow widths such text can wrap differently ("ove" | "r……" where upstream has "over" | "……"). Laying text out takes about 5 % longer for Latin text and 8–11 % for Chinese or Japanese than with upstream egui; egui caches laid-out text, so this is paid only when a text or its width changes. The rules and their limits are in `third_party/README.md`; games that lay text out themselves can use them directly: `egui::epaint::text::kinsoku::{line_break, Break, is_line_start_prohibited, is_line_end_prohibited}` (`kinsoku::VERSION` is 4 with the UAX #14 rules; a game whose chat joins a tag to a name with a no-break space can assert `VERSION >= 4`). The rules live in a patched copy of egui's text layout crate, `epaint`, in `third_party/epaint`. Cargo applies a `[patch]` only from the **root** `Cargo.toml` of the workspace being built, so Space3d's own patch covers Space3d's apps, examples and tests, and a game needs the same entry in its root `Cargo.toml`, pointing at the **same Space3d revision** as its `space3d` dependency: ```toml [dependencies] space3d = { git = "https://github.com/SpaceCorps/Space3d", rev = "" } # Chinese and Japanese line breaking (kinsoku) for egui: Space3d's patched epaint. [patch.crates-io] epaint = { git = "https://github.com/SpaceCorps/Space3d", rev = "" } # same rev as space3d ``` Cargo finds the `epaint` package inside the Space3d repository by its name (`third_party/epaint`); with the same `rev` both come from one checkout. With a local engine checkout, use `epaint = { path = "../Space3d/third_party/epaint" }` next to `space3d = { path = "../Space3d/crates/space3d" }`. `space3d new` writes the entry for you. When the entry is missing, or points at a Space3d revision whose egui differs from the one `space3d` uses, cargo only warns (`Patch 'epaint v… (…)' was not used in the crate graph`) and builds crates.io's epaint, without kinsoku. Check with: * `space3d doctor` — the `ui` line warns and prints the entry to add when epaint comes from crates.io, from another Space3d revision than `space3d`, or from a path without Space3d's kinsoku module (a game's own older copy), and says when `space3d`'s revision predates `third_party/epaint` (update `space3d` first); * `cargo tree -i epaint` — shows `epaint v0.36.2 (https://github.com/SpaceCorps/Space3d?rev=…)` (or the local path), not a bare version; * a test in the game that only compiles with the patched epaint: `const _: u32 = space3d::ui::egui::epaint::text::kinsoku::VERSION;` (with the UAX #14 rules, `const _: () = assert!(space3d::ui::egui::epaint::text::kinsoku::VERSION >= 4);`). When updating Space3d, bump the `rev` of both lines together. A game that carried its own `third_party/epaint` (as SpaceCorps did) replaces its `[patch.crates-io]` path with the git entry above and deletes the copy; its kinsoku tests keep passing. Space3d itself: `third_party/README.md` explains the patch, its tests and the egui upgrade procedure (`scripts/update-epaint.py`); `crates/space3d-ui/tests/kinsoku.rs` lays out Japanese and Chinese paragraphs at many widths and holds the golden story `UI/Text/Kinsoku`; `crates/space3d-ui/tests/line_breaks.rs` wraps chat lines with company tags and brackets at every width from 140 to 600 pt. ## Stories and tests The engine storybook (`space3d_stories::engine_storybook`, feature `ui`: not a default feature, since it pulls in egui; the editor and the facade's `stories` feature turn it on) holds `Engine/UI/Theme/Default`, `Engine/UI/Theme/Compact`, `Engine/UI/Tools/Debug Overlay`, `Engine/UI/Tools/Profiler`, `Engine/UI/Tools/Console` and `Engine/UI/Tools/Game Style`, with goldens in `crates/space3d-stories/tests/__screenshots__/Engine/UI/`. The tool stories have a `style` knob (egui default, compact theme, roomy game style). Tests: `crates/space3d-ui/tests/theme.rs` (density, default path untouched, applied once, never fights a game's style; unit tests: `UiDensity::of` forgets a removed or overridden theme), `crates/space3d-ui/tests/tools.rs` (docked tools stay inside the screen and apart at several sizes and scale factors, never grow, same geometry under a game's style; the profiler keeps clear of the debug overlay and above the console on 640 × 330–400 pt screens and shares 480 × 320 and 390 × 844 pt screens without overlaps; docked tools follow the screen as it grows and shrinks, or the dock area, at the size a fresh start gives them (also when a host sets the area after the first frame, as the editor does), while a tool the user resized keeps its size and stays docked; a dragged tool floats until its title is double-clicked; tools dock inside a `ToolDockArea`; a game window never covers them; in short dock areas — the reported 1024 × 233 band and 800 × 200, 1280 × 180, 1920 × 260, 640 × 240, 1100 × 280 pt — they dock side by side, inside and apart, the full 6 pt apart on an area off the pixel grid, and dock back when the area gets tall again, while short areas where the stacked layout fits as drawn — 1100 × 300 pt at 1–2x, 640 × 330 pt with nested profiler spans — keep it; a profiler without frames stays above the console; a tool made smaller by a free edge keeps that size, and a narrowed profiler leaves the console its room; resized tools get their sizes back after a short area, at 1–2x; an edge dragged toward the other tool stops a gap from it on every frame, without losing a log line, also in a wide band), the dock plan's unit tests (`dock.rs`: roomy areas stay stacked, the plan goes by the console's drawn height, the band goes side by side, the console moves right of a tall overlay, gaps stay whole on the pixel grid with or without the overlay, the console's limit holds as it reaches the profiler, a resized profiler and the console stay apart, a tiny area keeps the corners), the console's `drawn_height_is_the_height_the_console_is_drawn_at` (at 1–2x; the estimate before its first frame is exact at 1x), the profiler's `table_headers_line_up_with_their_columns` (header titles over their columns with and without a scroll bar, and in a narrow table), `a_short_profiler_leaves_out_its_section_headers` (at least 3 rows from about 150 pt; the measured minimum is exact) and `a_profiler_with_few_systems_keeps_its_sections_where_they_fit`, `crates/space3d-ui/tests/alloc_free.rs` (no allocation while the theme is unchanged or absent; the console allocates as much per frame with 1000 lines as with 40) and the editor's `standalone_tools_are_compact_and_the_plugin_keeps_a_games_style`, `editor_panels_keep_their_width_under_any_style`, `tool_windows_stay_over_the_viewport`, `editor_windows_and_engine_tools_come_to_the_front_when_clicked`, `engine_tools_dock_inside_the_viewport` (at 1280 × 720 and 1920 × 1080, after resizes, and the whole screen with the editor hidden) and `rows_reuse_their_styles_frame_after_frame`.