# NSGo Game documentation --- Source: https://game.nsgo.dev/docs/ # Overview game is a pure-Go 2D and 3D game layer for [NSGo](https://nsgo.dev) apps. A game draws into one NSGo view—a `Canvas`, a pixel buffer, a shader or a GPU view—while its HUD and menus stay ordinary native NSGo views on top. It uses only NSGo's public API (`core`, `audio`, `gamepad`, and GPU views), so an app that does not import it links none of it. > NSGo Game `v0.1.0` requires Go 1.27+ and NSGo `v0.3.4+`. [API Stability](https://game.nsgo.dev/docs/stability/) says which packages are stable and which are experimental. Start with [Getting Started](https://game.nsgo.dev/docs/getting-started/) to build and run a game, pick one of the [starter templates](https://game.nsgo.dev/docs/templates/), or follow the [tutorial](https://game.nsgo.dev/docs/tutorial/) to build a complete game. ## 2D and 3D 1. **2D**: a fixed-step loop, input actions, sprites, tilemaps, scenes, physics, lighting, particles, UI and sound, drawn at 60 fps or the display's rate. 2. **3D**: meshes, cameras, PBR lighting, skeletal animation, 3D physics, terrain, voxels and glTF models drawn with depth on NSGo's GPU view. See [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/) for coordinate conventions, Blender 4.x export settings, FBX/OBJ conversion and sample glTF assets, and [Lantern 3D](https://github.com/nsgo-dev/game/tree/main/examples/lantern3d) for an interactive glTF 3D scene example with orbit camera, dynamic lighting, a native HUD, and 2D ↔ 3D scene switching with shared input and sound. The loop, input actions, sound, assets and scene switching are shared by both 2D and 3D, so you can combine 2D and 3D scenes in one game without rewriting its structure. Every author-facing file—scenes, prefabs, materials, animations, tables and project settings—is plain-text versioned YAML ([File Formats](https://game.nsgo.dev/docs/formats/)), editable by hand, with coding agents, or in the visual [Scene Editor](https://game.nsgo.dev/docs/editor/). ## Packages | Package | Import path | Guide | What it holds | | --- | --- | --- | --- | | `game` | `github.com/nsgo-dev/game` | [Loop](https://game.nsgo.dev/docs/loop/) | `Loop`, the fixed-step loop every package shares | | `sprite` | `github.com/nsgo-dev/game/pkg/sprite` | [sprite](https://game.nsgo.dev/docs/sprite/) | Atlases, frames, animations, sprites and batches drawn into a `Canvas` | | `sound` | `github.com/nsgo-dev/game/pkg/sound` | [sound](https://game.nsgo.dev/docs/sound/) | The `Mixer`, its effects and music | | `input` | `github.com/nsgo-dev/game/pkg/input` | [input](https://game.nsgo.dev/docs/input/) | Named actions and axes from touch regions, mouse buttons, keyboard keys, pointer-lock mouselook and game controllers, persisted in `core.Storage` | | `tilemap` | `github.com/nsgo-dev/game/pkg/tilemap` | [tilemap](https://game.nsgo.dev/docs/tilemap/) | 2D `Camera`, culled tilemaps, Tiled `.tmj` loader, animated tiles and raycasts | | `scene` | `github.com/nsgo-dev/game/pkg/scene` | [scene](https://game.nsgo.dev/docs/scene/) | World/screen layers, hit testing, scene stacks and animated transitions | | `physics` | `github.com/nsgo-dev/game/pkg/physics` | [physics](https://game.nsgo.dev/docs/physics/) | `Box`/`Circle` overlaps, `MoveAndSlide` tile resolution and `World` queries | | `platformer` | `github.com/nsgo-dev/game/pkg/platformer` | [platformer](https://game.nsgo.dev/docs/platformer/) | Platformer `Controller` on `CharacterBody`: coyote time, jump buffer, variable jump height, wall slide and wall jump from a YAML config | | `screen` | `github.com/nsgo-dev/game/pkg/screen` | [screen](https://game.nsgo.dev/docs/screen/) | Virtual resolution `Viewport` scaling, pixel snapping, safe-area rectangles and video settings | | `project` | `github.com/nsgo-dev/game/pkg/project` | [Project File](https://game.nsgo.dev/docs/project/) | `game.yaml`, the one project file: window, virtual resolution, input map, audio buses, autoloads and export presets, kept in step with `nsgo.yaml` | | `refs` | `github.com/nsgo-dev/game/pkg/refs` | [Stable references](https://game.nsgo.dev/docs/project/#stable-references) | Stable file IDs, the project index and moves that rewrite every reference to a file, behind `game mv`, `game index` and `game check` | | `assets` | `github.com/nsgo-dev/game/pkg/assets` | [assets](https://game.nsgo.dev/docs/assets/) | Async per-scene asset groups, reactive progress and `LoadingScreen` | | `resource` | `github.com/nsgo-dev/game/pkg/resource` | [resource](https://game.nsgo.dev/docs/resources/) | Shared YAML resource files (materials, curves, gradients, animation clips, UI themes, bus layouts, physics materials) and a `Library` that shares and reloads them | | `text` | `github.com/nsgo-dev/game/pkg/text` | [text](https://game.nsgo.dev/docs/text/) | AngelCode BMFont bitmap fonts, signed-distance-field fonts in 2D and 3D world space, and platform text via `DrawPlatform` | | `placeholder` | `github.com/nsgo-dev/game/pkg/placeholder` | [Placeholder Assets](https://game.nsgo.dev/docs/placeholder/) | A CC0 pack of sprite sheets, a tileset and level, a pixel font, sounds and glTF models, with their import settings sidecars, to prototype with | | `particles` | `github.com/nsgo-dev/game/pkg/particles` | [particles](https://game.nsgo.dev/docs/particles/) | Seeded deterministic 2D `Emitter`, spawn shapes, bursts and lifetime curves | | `pixelfx` | `github.com/nsgo-dev/game/pkg/pixelfx` | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | A Go port of pixelfx's pixel art effects: the painter, simulation and acting system, effects by category (`pixelfx/fire`, `pixelfx/explosions`, ...), recoloring, mirroring and sprite sheet export | | `bullets` | `github.com/nsgo-dev/game/pkg/bullets` | [bullets](https://game.nsgo.dev/docs/bullets/) | Shooter bullet patterns (rings, spirals, aimed bursts) from YAML, pooled and drawn through a sprite batch | | `save` | `github.com/nsgo-dev/game/pkg/save` | [save](https://game.nsgo.dev/docs/save/) | Versioned JSON save slots, schema migrations and atomic backup recovery | | `achievements` | `github.com/nsgo-dev/game/pkg/achievements` | [achievements](https://game.nsgo.dev/docs/achievements/) | Achievements declared in versioned YAML, monotonic progress persisted in `core.Storage`, and reporting to Game Center and Play Games | | `datatable` | `github.com/nsgo-dev/game/pkg/tooling/datatable` | [datatable](https://game.nsgo.dev/docs/datatable/) | Typed data tables in versioned YAML (and CSV/JSON) with cell-level errors, deterministic saves and hot reload | | `debug` | `github.com/nsgo-dev/game/pkg/debug` | [debug](https://game.nsgo.dev/docs/debug/) | Frame-time graph, wireframe shapes, scene inspector and `-tags release` stripping | | `mcp` | `github.com/nsgo-dev/game/pkg/mcp` | [mcp](https://game.nsgo.dev/docs/mcp/) | MCP tools registered through `nsgo/automation` to inspect running scenes, layers, entities and components | | `flow` | `github.com/nsgo-dev/game/pkg/flow` | [flow](https://game.nsgo.dev/docs/flow/) | Game-clock `Timers`, `Machine[S]`, `Seq`/`Parallel`/`Race` and typed event `Bus` | | `stats` | `github.com/nsgo-dev/game/pkg/stats` | [stats](https://game.nsgo.dev/docs/stats/) | Base stats with add/mul/override modifiers from sources, recomputed on change, timed modifiers on the fixed step and a YAML stats file | | `tween` | `github.com/nsgo-dev/game/pkg/tween` | [tween](https://game.nsgo.dev/docs/tween/) | Fixed-step `Tween`, `Timeline` and camera choreography helpers | | `animclip` | `github.com/nsgo-dev/game/pkg/animclip` | [animclip](https://game.nsgo.dev/docs/animclip/) | Animation clips that key any registered property, played on scene objects through `tween.Timeline` | | `cards` | `github.com/nsgo-dev/game/pkg/cards` | [cards](https://game.nsgo.dev/docs/cards/) | Drag and drop between board slots with snap and return, fanned hands, decks, piles and grids, and YAML board files | | `rooms` | `github.com/nsgo-dev/game/pkg/rooms` | [rooms](https://game.nsgo.dev/docs/rooms/) | Room maps with per-room camera bounds and cut, slide or fade transitions between them | | `ai` | `github.com/nsgo-dev/game/pkg/ai` | [ai](https://game.nsgo.dev/docs/ai/) | Grid `AStar`, 2D `NavMesh`, steering behaviors, behavior trees and perception | | `ai/perception3d` | `github.com/nsgo-dev/game/pkg/ai/perception3d` | [ai](https://game.nsgo.dev/docs/ai/#3d) | `ai` perception for 3D agents on `math3d.Vec3`, with `physics3d` line of sight | | `navbake` | `github.com/nsgo-dev/game/pkg/navbake` | [navbake](https://game.nsgo.dev/docs/navbake/) | Bakes `ai.NavMesh` polygons from concave obstacles or a tilemap's solid cells for each agent radius, saved as versioned YAML, with a debug overlay | | `rts` | `github.com/nsgo-dev/game/pkg/rts` | [rts](https://game.nsgo.dev/docs/rts/) | Flow fields, a `Crowd` of many units with separation, YAML formations, box/click selection and control groups | | `procgen` | `github.com/nsgo-dev/game/pkg/procgen` | [procgen](https://game.nsgo.dev/docs/procgen/) | Seeded BSP rooms, cellular-automata caves and wave function collapse from YAML rules, with connectivity checks and tilemap painting | | `replay` | `github.com/nsgo-dev/game/pkg/replay` | [replay](https://game.nsgo.dev/docs/replay/) | Input `Recorder`/`Player` with editable YAML recordings and deterministic test assertions | | `statedump` | `github.com/nsgo-dev/game/pkg/statedump` | [statedump](https://game.nsgo.dev/docs/statedump/) | Headless runs dumped as deterministic YAML (entities, components, scene stack, values) and a line `Diff` between runs | | `cutscene` | `github.com/nsgo-dev/game/pkg/cutscene` | [cutscene](https://game.nsgo.dev/docs/cutscene/) | Skippable video cutscenes over the game's view, in a scene or between scenes, from YAML files | | `rhythm` | `github.com/nsgo-dev/game/pkg/rhythm` | [rhythm](https://game.nsgo.dev/docs/rhythm/) | YAML beat maps with tempo and meter changes, a music clock on the audio clock, and per-device audio/video latency calibration | | `undo` | `github.com/nsgo-dev/game/pkg/undo` | [undo](https://game.nsgo.dev/docs/undo/) | Reversible moves with unlimited undo, redo and `Seek`, saved as a YAML `Log` | | `fighting` | `github.com/nsgo-dev/game/pkg/fighting` | [fighting](https://game.nsgo.dev/docs/fighting/) | Per-step input buffer, numpad motion inputs, charges, double taps, chords and combos from YAML move sets | | `math2d` | `github.com/nsgo-dev/game/pkg/math2d` | [math2d](https://game.nsgo.dev/docs/math2d/) | Shared 2D `Vec2`, `Rect`, `Circle` and `Affine` types with lossless `core` conversions | | `gameui` | `github.com/nsgo-dev/game/pkg/gameui` | [gameui](https://game.nsgo.dev/docs/gameui/) | In-canvas box-layout menus, virtual-resolution scaling, spatial focus nav and world-anchored views | | `lights2d` | `github.com/nsgo-dev/game/pkg/lights2d` | [lights2d](https://game.nsgo.dev/docs/lights2d/) | 2D ambient darkness, point/cone lights, visibility-polygon shadows and normal-mapped sprites | | `tileshape` | `github.com/nsgo-dev/game/pkg/tileshape` | [tileshape](https://game.nsgo.dev/docs/tileshape/) | Tilemap collision and lighting geometry: a physics `TileGrid` view, slopes from per-tile shapes, merged outlines and `lights2d` occluders | | `effects` | `github.com/nsgo-dev/game/pkg/effects` | [effects](https://game.nsgo.dev/docs/effects/) | Kage shader passes chained over the game's frame in one draw, uniforms on the frame clock and CPU reference pictures | | `worldmap` | `github.com/nsgo-dev/game/pkg/worldmap` | [worldmap](https://game.nsgo.dev/docs/worldmap/) | YAML room maps, saved room discovery and markers, a minimap of the current area and a world map | | `fog` | `github.com/nsgo-dev/game/pkg/fog` | [fog](https://game.nsgo.dev/docs/fog/) | Per-team fog of war: shadowcast vision sources, explored versus visible cells, map overlay and JSON saves | | `quality` | `github.com/nsgo-dev/game/pkg/quality` | [quality](https://game.nsgo.dev/docs/quality/) | Low, medium and high presets picked from the device class and measured frame times, overridable in settings | | `a11y` | `github.com/nsgo-dev/game/pkg/a11y` | [a11y](https://game.nsgo.dev/docs/a11y/) | Live captions, color-blind palettes and CVD simulation, persisted assist options and accessible menus | | `l10n` | `github.com/nsgo-dev/game/pkg/l10n` | [l10n](https://game.nsgo.dev/docs/l10n/) | JSON string tables with CLDR plurals, script `FontSet`, RTL visual ordering and per-language asset catalogs | | `perf` | `github.com/nsgo-dev/game/pkg/perf` | [perf](https://game.nsgo.dev/docs/perf/) | Zero-alloc `Pool`/`Arena`/`SlicePool`, `SpatialHash`, `Quadtree` and `CullBatch` | | `idle` | `github.com/nsgo-dev/game/pkg/idle` | [idle](https://game.nsgo.dev/docs/idle/) | `Number` past float64's range, capped offline progress and short/scientific/locale formatting of large numbers | | `net` | `github.com/nsgo-dev/game/pkg/net` | [net](https://game.nsgo.dev/docs/net/) | Cross-target WebSocket/UDP/loopback transports, delta replication and lockstep/rollback netcode | | `server` | `github.com/nsgo-dev/game/pkg/server` | [server](https://game.nsgo.dev/docs/server/) | Headless fixed-step `Runner` for dedicated servers: several matches at their own rates, overrun reports and bounded signal shutdown | | `accounts` | `github.com/nsgo-dev/game/pkg/accounts` | [accounts](https://game.nsgo.dev/docs/accounts/) | Self-hosted player accounts: guests upgraded to email or a linked platform/OAuth identity, argon2id passwords, SQLite/Postgres stores and Ed25519 tokens game servers verify offline | | `cloudsave` | `github.com/nsgo-dev/game/pkg/cloudsave` | [cloudsave](https://game.nsgo.dev/docs/cloudsave/) | Self-hosted cloud saves behind `liveops.CloudSync`: per-account slots over HTTPS, conditional writes that turn concurrent saves into conflicts, size limits, kept versions with restore, SQLite/Postgres stores | | `leaderboard` | `github.com/nsgo-dev/game/pkg/leaderboard` | [leaderboard](https://game.nsgo.dev/docs/leaderboard/) | Boards declared once in YAML, scores submitted and native boards shown through Game Center or Play Games | | `leaderboard/selfhost` | `github.com/nsgo-dev/game/pkg/leaderboard/selfhost` | [leaderboard/selfhost](https://game.nsgo.dev/docs/leaderboard-selfhost/) | Self-hosted cross-platform leaderboards: all-time, daily and weekly boards with kept past periods, scores authenticated by account tokens and optionally signed by the game server, top-N, around-me and friends queries | | `presence` | `github.com/nsgo-dev/game/pkg/presence` | [presence](https://game.nsgo.dev/docs/presence/) | Rich presence on Steam (`ISteamFriends` via purego) and Discord (pure Go local IPC v1) behind a provider-neutral `Activity` and `Manager` | | `inventory` | `github.com/nsgo-dev/game/pkg/inventory` | [inventory](https://game.nsgo.dev/docs/inventory/) | Item definitions in YAML, stacking slot containers, typed equipment slots and save snapshots | | `ability` | `github.com/nsgo-dev/game/pkg/ability` | [ability](https://game.nsgo.dev/docs/ability/) | YAML ability sets and a per-step `Caster`: costs, cooldowns, charges, cast and channel times and conditions driven by input actions | | `quest` | `github.com/nsgo-dev/game/pkg/quest` | [quest](https://game.nsgo.dev/docs/quest/) | YAML quest books with collect/reach/defeat/talk objectives, prerequisites and rewards, advanced by bus events and saved as snapshots | | `loot` | `github.com/nsgo-dev/game/pkg/loot` | [loot](https://game.nsgo.dev/docs/loot/) | Nested weighted drop tables in YAML with guaranteed drops and hard/soft pity counters on seeded streams | | `vn` | `github.com/nsgo-dev/game/pkg/vn` | [vn](https://game.nsgo.dev/docs/vn/) | Visual novel presenter: YAML cast of portraits and expressions, name plates, typewriter text box, choices, backlog, auto/skip modes and voice lines | | `modding` | `github.com/nsgo-dev/game/pkg/modding` | [modding](https://game.nsgo.dev/docs/modding/) | Capability-sandboxed TSX `"game"` modding API and `mod.yaml` dependency/lifecycle manager | | `math3d` | `github.com/nsgo-dev/game/pkg/math3d` | [math3d](https://game.nsgo.dev/docs/math3d/) | 3D vectors, matrices, quaternions, transforms, bounds, rays, frustums and conventions | | `scene3d` | `github.com/nsgo-dev/game/pkg/scene3d` | [scene3d](https://game.nsgo.dev/docs/scene3d/) | 3D node tree, sockets/attachments, dynamic fat-AABB/SAH BVH, Orbit/FPS/ThirdPerson cameras and picking | | `anim3d` | `github.com/nsgo-dev/game/pkg/anim3d` | [anim3d](https://game.nsgo.dev/docs/anim3d/) | 3D pose state machines, 1D/2D blend spaces, bone-masked/additive layers, clip events, IK and root motion | | `world3d` | `github.com/nsgo-dev/game/pkg/world3d` | [world3d](https://game.nsgo.dev/docs/world3d/) | Heightmap terrain, multi-level 3D navmeshes, 3D `GridMap`, scattered foliage and floating-origin streaming | | `navbake3d` | `github.com/nsgo-dev/game/pkg/navbake3d` | [navbake3d](https://game.nsgo.dev/docs/navbake3d/) | Navigation meshes baked from glTF, terrain, `GridMap` and physics level geometry per agent type, saved as YAML a scene names, with debug drawing and `game navmesh` | | `voxel` | `github.com/nsgo-dev/game/pkg/voxel` | [voxel](https://game.nsgo.dev/docs/voxel/) | Chunked 3D voxel worlds with greedy meshing, cross-chunk culling and AO, dirty-chunk editing, DDA raycasting and YAML saves | | `render3d` | `github.com/nsgo-dev/game/pkg/render3d` | [render3d](https://game.nsgo.dev/docs/render3d/) | GPU mesh buffers, textures and samplers, camera uniforms, CPU frustum culling, draw sorting, 0-alloc instancing, LOD hysteresis, debug draw/gizmos, billboards, 3D ribbon trails and GPU budgets | | `scenemodel` | `github.com/nsgo-dev/game/pkg/scenemodel` | [scenemodel](https://game.nsgo.dev/docs/scenemodel/) | Scene file objects drawn in 3D: built-in primitives and glTF models with material overrides, built into a `scene3d` tree with bounds and drawn by a lit, textured renderer | | `tooling/jsonschema` | `github.com/nsgo-dev/game/pkg/tooling/jsonschema` | [Schemas for YAML files](https://game.nsgo.dev/docs/schemas/) | JSON Schemas built from Go types for editors and AI tools, the published scene schema and validation with JSON Pointer paths | | `tooling/library` | `github.com/nsgo-dev/game/pkg/tooling/library` | [Asset and Plugin Library](https://game.nsgo.dev/docs/library/) | A YAML index of shared asset, editor plugin and template packs, checked by digest and installed into a project with their files and `game.yaml` references recorded | | `framedata` | `github.com/nsgo-dev/game/pkg/framedata` | [framedata](https://game.nsgo.dev/docs/framedata/) | Fighting game hitboxes, hurtboxes, hitstun and cancel windows per frame in YAML, resolved deterministically each step | | `vehicle` | `github.com/nsgo-dev/game/pkg/vehicle` | [vehicle](https://game.nsgo.dev/docs/vehicle/) | Raycast cars on `physics3d`: wheel suspension, tire friction and a car controller, race checkpoints and laps, and YAML car files and lap ghosts | For a single-page summary of the core APIs, see [Packages](https://game.nsgo.dev/docs/packages/). Every loader reports a file it cannot use with the file, line, field and a fix; see [Errors](https://game.nsgo.dev/docs/errors/). [File Formats](https://game.nsgo.dev/docs/formats/) lists every file a game reads or writes, with its version and an example. ## Coming from another engine Each guide maps that engine's scenes, nodes, resources, signals, input maps, physics and export to the packages above: [Godot](https://game.nsgo.dev/docs/from-godot/), [Ebitengine](https://game.nsgo.dev/docs/from-ebitengine/) and [Unity](https://game.nsgo.dev/docs/from-unity/). ## Install The module needs Go 1.27 and NSGo `v0.3.4` or later: ```sh go get github.com/nsgo-dev/game ``` ## How a frame runs A game is an NSGo component. It starts a `game.Loop` on its scope, which runs on NSGo's `RequestAnimationFrame`: 1. Each display frame adds the time since the last one and runs `Update` once for each whole fixed step it holds, zero or more times. 2. `Update` moves the game's state by the fixed `dt`, advancing animations and timers. 3. `Draw` runs once, with how far the frame falls into the next step, and sets a signal the game's `Canvas` reads, so the canvas draws again without a commit of the view tree. While the window is in the background, the loop runs no updates and the mixer plays nothing; both resume from where they were. ## Targets macOS, iOS, Windows, Linux, Android and the web. HarmonyOS, mini programs, watchOS and tvOS are outside the first stage. Consoles (Nintendo Switch, PlayStation and Xbox) are out of scope: their SDKs are under NDA and need C toolchains, and NSGo and this repository are Go only, with no hand-written C. See [Building and Shipping](https://game.nsgo.dev/docs/shipping/) for icons, signing, notarization, store packaging and `nsgo check` across all six targets, and [Command Line](https://game.nsgo.dev/docs/cli/) for `nsgo game`, which packs atlases, converts audio, generates asset manifests, encodes textures, opens the scene editor, and builds all of a game's assets from `game.yaml`, rebuilding only what changed. ### VR and AR The game layer does not support VR or AR for now ([#495](https://github.com/nsgo-dev/game/issues/495)). Every package draws into one flat NSGo view, a `Canvas` or a GPU view, and reads touch, mouse, keyboard, gamepads and device motion. NSGo currently has no XR runtime on any of its targets, and this repository uses only NSGo's public API and holds no platform code, so it cannot add one itself. XR work here can start once NSGo provides, on at least one runtime (OpenXR on desktop and Android headsets, visionOS, ARKit, ARCore or WebXR): - **An XR session**: starting it, pausing when the headset is taken off or the app loses focus, and ending it. - **Poses**: the head's and each controller's pose every frame, predicted for when the frame is shown, and the runtime's controller and hand input. - **Stereo rendering**: a render target per eye with its own view and projection, drawn by the GPU view at the headset's rate and handed to the runtime's compositor. - **For AR**: the camera's passthrough behind the drawing, detected planes, hit tests against the real world and anchors that stay in place. OpenXR is the runtime to target first, since one API covers headsets on Windows, Linux and Android, three of NSGo's targets; visionOS, ARKit, ARCore and WebXR can follow. The session, poses and stereo rendering come first and are enough for VR; the AR items come after them. With those, this repository would add an XR camera rig to `scene3d` and XR actions to `input`, reusing `math3d`'s transforms for poses. Until then a 3D game runs on a flat screen. ## For language models The site publishes the English docs for language models and coding agents, as [nsgo.dev](https://nsgo.dev/llms.txt) does: [llms.txt](https://game.nsgo.dev/llms.txt) lists every page with a line about it, and [llms-full.txt](https://game.nsgo.dev/llms-full.txt) holds every page's Markdown in one file. Both are built from `docs/en` with the site, so they always match these pages. For contributors, the [Agent Evaluation Suite](https://game.nsgo.dev/docs/agent-eval/) grades fixed game tasks with YAML, build and `game/mcp` checks, and can run a coding agent on them. For coding agents that support Agent Skills, install the game-layer skill with `bunx skills add nsgo-dev/game`; see [Agent Skill](https://game.nsgo.dev/docs/agent-skill/). --- Source: https://game.nsgo.dev/docs/getting-started/ # Getting Started Create an NSGo game, run it on desktop, web, iOS and Android, draw an animated sprite on a fixed-step loop, handle touch and mouse input, and play sound. ## Requirements - **Go 1.27** or later. - **NSGo `v0.3.4`** or later, which a new project requires and runs as the `nsgo` tool, and the `nsgo` command installed to run `nsgo game` ([Command Line](https://game.nsgo.dev/docs/cli/#install)). - For iOS builds: macOS with Xcode. - For running on Android devices or emulators: `adb` (Android SDK Platform-Tools). Building an `android_arm64` APK needs only Go. Run `go tool nsgo doctor` inside a project to check what toolchains this machine has. ## Create a project Create the project with the `game` command's `new` subcommand, run as `nsgo game` ([Command Line](https://game.nsgo.dev/docs/cli/#install)). It writes the starter into a new directory and has Go add the game layer and the `game` tool to its `go.mod`, beside the `nsgo` tool the starter already has: ```sh nsgo game new mygame cd mygame go tool nsgo dev ``` `nsgo game` outside a project uses the `nsgo-game` extension binary on `PATH` (install once with `go install github.com/nsgo-dev/game/cmd/nsgo-game@latest`), or `go run github.com/nsgo-dev/game/cmd/game@latest new mygame` does the same directly with nothing to install. Inside the created project, `nsgo game` automatically runs the module's pinned `game` tool. The starter includes an animated sprite, tap-to-score input, and tests. Its settings live in `game.yaml`, the [project file](https://game.nsgo.dev/docs/project/), which `nsgo.yaml` mirrors. `new` names the game after its directory in both files' `name` and `id` and in the module path; `-name` and `-module` choose others, such as `-module example.com/mygame`. [Command Line](https://game.nsgo.dev/docs/cli/#new) describes every flag, and `-template` starts from another of the [templates](https://game.nsgo.dev/docs/templates/), which `new -list` lists. Change the identifier to your own before you ship the game: edit the game's name and identifier in `game.yaml`, then run `go run github.com/nsgo-dev/game/cmd/gameproject sync` to write them into `nsgo.yaml`. NSGo's own command writes the same starter from the template module, without the `game` tool: `nsgo init -template github.com/nsgo-dev/game/template -module example.com/mygame mygame`, with an NSGo command that supports [Go module templates](https://nsgo.dev/docs/getting-started/#templates-from-go-modules), such as the installed `nsgo` of v0.3.4 or later. Its `game.yaml` and `nsgo.yaml` name the game `Starter Game` until you edit them. From a checkout of this repository, `go run ./cmd/game new ../mygame` creates a project from the starter in `template/template/`; a command built from a checkout has no version of its own, so the project requires the latest published game layer unless `-version` names another. From the checkout itself, run the original starter with `go tool nsgo dev ./template/template`. Add `resources/` for files your game loads at runtime and `assets/` for files the tool uses to build the app, such as app icons: ```text mygame/ ├─ go.mod ├─ game.yaml ├─ nsgo.yaml ├─ main.go ├─ project.go ├─ game.go ├─ game_test.go ├─ resources/ │ ├─ hero.png │ ├─ hero.json │ ├─ jump.wav │ └─ theme.m4a └─ assets/ └─ Icon.png ``` Anything under `resources/` is packaged with the app on every target and resolved by `"asset:"` (for example `"asset:hero.png"` or `"asset:sounds/jump.wav"`). Atlas JSON files can be embedded directly into the Go binary with `//go:embed`. ## Run on every target `nsgo dev` builds the app, launches it, and hot-reloads on save. Desktop (this machine's native backend, the default in `nsgo.yaml`): ```sh go tool nsgo dev ``` Web (starts a local dev server on port 8080 and opens the browser): ```sh go tool nsgo dev -target web ``` iOS (simulator, or a connected iPhone signed with `-team` or Xcode's last team): ```sh go tool nsgo dev -target ios_simulator go tool nsgo dev -target ios ``` Android (a connected device or running emulator; pass `-device` when several are attached): ```sh go tool nsgo dev -target android ``` Add `-fps` to any `nsgo dev` command to show NSGo's performance monitor over the running game. To also reload atlases, images and data files in the running game when you save them under `resources/`, run it with `nsgo game dev` (after `go get -tool github.com/nsgo-dev/game/cmd/game`) and start a watcher on them with `hotreload.NewDevWatcher`, as [Reloading on save](https://game.nsgo.dev/docs/assets/#reloading-on-save) shows. ## Draw a sprite on a fixed-step loop A game is an NSGo component. It starts a `game.Loop` on its scope, updates state in `Update` at a fixed rate (60 updates a second by default), and triggers a `core.Canvas` redraw from `Draw` through a `core.Signal` without re-committing the view tree. Pack a sprite sheet with TexturePacker or Aseprite (with rotation off), put the PNG in `resources/hero.png`, and embed its JSON with `//go:embed`. If you do not have a sheet yet, you can construct a `*sprite.Atlas` literal directly as shown in the [sprite guide](https://game.nsgo.dev/docs/sprite/). ```go package main import ( _ "embed" "math" "time" "github.com/nsgo-dev/game" "github.com/nsgo-dev/game/pkg/sprite" "github.com/nsgo-dev/nsgo" "github.com/nsgo-dev/nsgo/core" ) //go:embed resources/hero.json var heroJSON []byte func Game(cx *core.Scope) core.Node { atlas, err := sprite.LoadAtlas(core.Src("asset:hero.png"), heroJSON) if err != nil { panic(err) } walk := atlas.Animations["walk"] hero := sprite.NewSprite(walk.Frame()) hero.OriginX = hero.Frame.Width / 2 hero.OriginY = hero.Frame.Height / 2 hero.X, hero.Y = 160, 120 batch := &sprite.Batch{ Atlas: atlas, Sprites: []*sprite.Sprite{&hero}, } x, y := hero.X, hero.Y lastX, lastY := x, y targetX, targetY := x, y alpha := core.NewSignal(cx, 0.0) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { lastX, lastY = x, y dx, dy := targetX-x, targetY-y if dist := float32(math.Hypot(float64(dx), float64(dy))); dist > 1 { step := min(dist, 180*float32(dt.Seconds())) x += dx / dist * step y += dy / dist * step hero.FlipX = dx < 0 walk.Update(dt) hero.Frame = walk.Frame() } }, Draw: func(a float64) { alpha.Set(a) }, } loop.Run(cx) return core.Canvas{ Style: core.Style{FlexGrow: 1, FlexShrink: 1, Background: core.RGB(0x181c24)}, OnPress: func(e core.PressEvent) { targetX = float32(e.Position.X) targetY = float32(e.Position.Y) }, Draw: func(d *core.Drawing, _ core.Size) { a := float32(alpha.Get()) hero.X = lastX + (x-lastX)*a hero.Y = lastY + (y-lastY)*a batch.Draw(d) }, } } func main() { nsgo.Run(Game) } ``` Because `Draw` reads `alpha.Get()`, NSGo redraws only the `Canvas` on each display frame. Interpolating between `(lastX, lastY)` and `(x, y)` keeps movement smooth on 60 Hz, 120 Hz and variable-refresh displays while the simulation stays locked to 60 Hz. ## Handle touch and mouse input `core.Canvas.OnPress` handles taps on phones and clicks on desktops and the web, delivering `e.Position` in the canvas's own points. For continuous pointer tracking, drags or multi-touch, wrap the `Canvas` in a `core.View` that listens to NSGo's pointer and touch handlers (`OnPressDown`, `OnPressUp`, `OnMouseMove`, `OnTouch`, `OnPan`) and layer native HUD views on top with `core.Absolute`: ```go return core.View{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, OnMouseMove: func(e core.MouseEvent) { if e.PressedButton == core.MouseButtonLeft { targetX, targetY = float32(e.Position.X), float32(e.Position.Y) } }, OnTouch: func(e core.TouchEvent) { if len(e.Touches) > 0 { targetX = float32(e.Touches[0].Position.X) targetY = float32(e.Touches[0].Position.Y) } }, Children: []core.Node{ canvas, core.View{ Style: core.Style{ Position: core.Absolute, Top: core.Pt(12), Left: core.Pt(12), PaddingEnv: core.EnvAll(core.EnvSafeArea), }, Children: []core.Node{ core.Text{Content: "Score: 0", Style: core.Style{Color: core.RGB(0xffffff)}}, }, }, }, } ``` Keyboard and gamepad action mapping will live in `game/input` ([#3](https://github.com/nsgo-dev/game/issues/3)). ## Play sound with sound.Mixer Create one `sound.Mixer` on the component's scope. It persists master and group volumes in `core.Storage`, mutes automatically when the app moves to the background, and manages both short sound effects (`Effect`) and streaming music (`Music`). Ship audio as WAV, AAC (`.m4a`) or MP3 under `resources/`: ```go mixer := sound.NewMixer(cx, "sound") music := mixer.Music("music") music.Loop = true var jump *sound.Effect audio.LoadSound(cx, audio.Source{URI: "asset:jump.wav"}, func(s *audio.Sound, err error) { if err != nil { return } jump = mixer.Effect(s, "effects", 4) }) ``` Trigger the effect and start music on a user press (on the web, browsers block audio until the first user gesture): ```go started := false // Inside OnPress: if !started { started = true music.Play(audio.Source{URI: "asset:theme.m4a"}, 2*time.Second) } if jump != nil { jump.Play(audio.Voice{Volume: 0.8}) } ``` ## Next steps - Follow the [tutorial](https://game.nsgo.dev/docs/tutorial/), which builds a whole game, Star Catcher, from an empty project to release builds in nine chapters. - Read the package guides for [Loop](https://game.nsgo.dev/docs/loop/), [sprite](https://game.nsgo.dev/docs/sprite/) and [sound](https://game.nsgo.dev/docs/sound/), or the combined [Packages](https://game.nsgo.dev/docs/packages/) reference. - Play and read [Cave Run](https://github.com/nsgo-dev/game/tree/main/examples/caverun), the sample platformer: the loop, input actions on the keyboard, game controllers, touch and the mouse, a sprite batch, a Tiled map with a camera, scenes, sound groups and a native HUD and pause menu, with a 1000-sprite stress mode and headless tests that play its level to the end. - Explore [Lantern 3D](https://github.com/nsgo-dev/game/tree/main/examples/lantern3d), the 3D glTF scene example: an embedded binary glTF 2.0 diorama loaded with `game/gltf`, uploaded with `render3d.UploadMesh` and `render3d.UploadTexture`, lit through a `render3d.LightRig` (a directional key light, an orbiting warm point light, the shrine's glow and ambient) with render3d's metallic-roughness PBR shading on NSGo's `gpu.View`, with a `scene3d.OrbitController` camera and a native `scene.HUD3D` overlay. - When you are ready to verify all targets and produce release builds for macOS, Windows, Linux, the web, iOS and Android, read [Building and Shipping](https://game.nsgo.dev/docs/shipping/). --- Source: https://game.nsgo.dev/docs/playground/ # Playground The [playground](https://game.nsgo.dev/playground/) runs this repository's examples in the browser, built for NSGo's web target, with each example's source beside it. To change an example, run it on your machine with the dev server, which rebuilds and reloads it each time you save. ## In the browser Each example has a page of its own, such as `/playground/caverun/`, so its address is the link to share. The page shows: - **The game**, which loads when you press **Run**: its WebAssembly is about 15 MB, so nothing is downloaded before then. Click the game to give it the keyboard. **Restart** loads it again from the start, and **Open in a new tab** runs the build on a page of its own. - **The source**, a tab per file: the example's main package without its tests, then its `nsgo.yaml`. The tab shown is the address's fragment, so `/playground/caverun/#level.go` opens on `level.go`. Each file links to it on GitHub. The site is static, hosted on GitHub Pages, so it compiles nothing: a page runs the build the site was deployed with, from the same commit as the source it shows. ## Edit on your machine With Go 1.27 or later, clone the repository and start an example with the dev server for the web target: ```sh git clone https://github.com/nsgo-dev/game.git cd game/examples/caverun go tool nsgo dev -target web ``` It opens the game in your browser, Chrome and Safari alike, and rebuilds and reloads it each time you save a file of the example or of the root module (`pkg/`), which the examples use through the checkout's `go.work`. A failed build shows its errors over the game until the next save builds. Without `-target web` the example runs as a native app, which reloads in the same way. ## How the builds are made `bun run playground`, from the repository's root, builds each example with `go tool nsgo build -target web` into the example's `dist/playground/`, then copies the site it writes into `apps/website/public/play//`, which Git ignores. The website serves that directory at `/play//` and each example's page shows it in a frame. `bun run playground caverun` builds one example. The website's workflow sets up Go and runs it before building the site, on every push to `main` and every pull request that touches the site, the examples, `pkg/`, `cmd/`, or root `.go` files. In CI a missing build fails the site's build, so a deploy never publishes a page with no game; a local `bun run build` without the builds warns, and the example's page shows the command that makes its build. ## Add an example 1. Put the example under `examples//` with an `nsgo.yaml`, a main package that builds for the web target, and an entry for it in `go.work`. 2. Add `` to `PLAYGROUND_IDS` in `apps/website/src/content/playground.ts`. 3. Give it an entry in `apps/website/src/content/showcase.ts`, whose title and description the playground shows, in English and Chinese. --- Source: https://game.nsgo.dev/docs/packages/ # Packages What each package holds and how its parts behave, from the packages' doc comments. The full API of every package is in the [API reference](https://game.nsgo.dev/docs/api/), and every file format the packages read and write is in [File Formats](https://game.nsgo.dev/docs/formats/). ## API reference The [API reference](https://game.nsgo.dev/docs/api/) has a page for each package of `github.com/nsgo-dev/game`, rendered from the doc comments in its source at every build of the site, as `go doc` shows them: the package's doc, an index, then its constants, variables, functions and types, each type with its values, constructors and methods. Every exported identifier has an anchor named as pkg.go.dev names it, `Name` for a constant, variable, function or type and `Type.Name` for a method, a struct field or an interface method, so `https://game.nsgo.dev/docs/api/game/#Loop.Update` is `Loop.Update`. A declaration that only some targets build lists them. Agents read the same reference as JSON at [`/api.json`](https://game.nsgo.dev/api.json): every package with its synopsis and doc, and every declaration with its anchor, its gofmt-formatted source, its doc comment, its file and line below the repository root, and the targets that build it when not all of them do. Its `version` field is 1 and changes when a field is removed or changes meaning. To write it from a checkout, run at the repository root: ```sh go run ./cmd/gameapi -out api.json ``` `-html` adds each doc comment rendered as HTML, as the site's pages show it. The reference is read from the files the linux, macos, windows, android, ios and web targets build in a development build; packages main, `internal` directories and `testdata` are left out. Every library package also has runnable examples: `Example` functions in its `example_test.go` that show the main use of its types. They appear with the package's Go doc (on pkg.go.dev, for instance), and `go tool nsgo test` runs each one and checks what it prints against its `// Output:` comment, so an example that no longer matches the code fails the tests. Commands (`package main`, such as those under `cmd/` and `server/cmd/dedicatedserver`) have none, as they export no API to show, and neither do internal packages, which only the module itself imports. Examples that need an outside service, such as `accounts/pgstore`'s Postgres database, or a running test, such as `accounts/storetest`, have no `// Output:` comment, so they are compiled but not run. ## Loop ```go import "github.com/nsgo-dev/game" ``` `Loop` runs a game's updates at a fixed rate on a scope's display frames, and draws once a frame in between. ```go type Loop struct { Rate int // updates a second, 60 when 0 MaxSteps int // most updates one frame runs, Rate/10 and at least 1 when 0 Update func(dt time.Duration) // moves the game on by dt, always 1/Rate seconds Draw func(alpha float64) // draws the frame, alpha in [0, 1) } func (l *Loop) Run(cx *core.Scope) (stop func()) ``` - Each frame adds the time since the last one and runs `Update` once for each whole step of `1/Rate` seconds it holds, then `Draw` once with how far the time left over reaches into the next step. A game moves its state in `Update` by the fixed `dt`, so it plays alike at any display rate, and `Draw` places what moves between the last two states by `alpha`, so it moves smoothly. - A frame that would run more than `MaxSteps` updates drops the whole steps past it, so an `Update` slower than its step, or a long hitch, slows the game rather than making each frame run more updates than the last. - `Run` starts the loop until the scope is disposed or `stop` is called. It reads the fields on each frame, so a game may change them while the loop runs. - The loop pauses while the scope's window is in the background (`core.Env.Lifecycle`) and resumes from the time it shows again, so the time away runs no updates. - A frame's time is the display's frame time where the platform stamps one, and the graph clock's otherwise; the loop adds it as it is. ## sprite ```go import "github.com/nsgo-dev/game/pkg/sprite" ``` Atlases, frames, animations, sprites and batches drawn into a `Canvas`. ### Atlas and Frame An `Atlas` is an image that packs many pictures (`Image`), the frames that say where each one is (`Frames`, by name), and its animations (`Animations`, by name). `LoadAtlas(img, data)` reads the JSON atlas data that TexturePacker ("JSON (Hash)" and "JSON (Array)") or Aseprite (json-hash and json-array) exports for the image it packed: - Rectangles are in the image's pixels, divided by the export's `meta.scale`, so the image measures its points as a 1x image does. - Aseprite's frame tags become `Animations`, each frame for the duration the export gives it, in the tag's direction, looping unless the tag has a repeat count. - Frames a packer rotated are refused: export with rotation off. A game can also write the table by hand as an `Atlas` literal. A `Frame` is one picture: the part of the image it draws (`X`, `Y`, `W`, `H`), where that part sits in the untrimmed picture (`OffsetX`, `OffsetY`), and the untrimmed size (`Width`, `Height`). ### Animation An `Animation` plays frames one after another, each for its own duration, moved on by `Update` with a `Loop`'s fixed steps. It is a value that keeps where it is in its frames, so each sprite plays its own copy: copy one from an atlas's `Animations`, or write one by hand. - `Update(dt)` moves it on past as many frames as `dt` covers. - `Frame()` is the frame showing now, `Index()` its index, and `Done()` reports whether an animation that does not loop has shown its last frame for that frame's duration. - `Reset()` starts it over. ### Sprite and Batch A `Sprite` is a frame placed in a drawing: moved (`X`, `Y`), turned (`Rotation`, in radians, clockwise), scaled (`ScaleX`, `ScaleY`; negative mirrors), flipped inside its untrimmed frame (`FlipX`, `FlipY`), faded (`Alpha`), tinted (`Tint`) and styled per sprite (`Effect`: solid-color flash and silhouette, alpha outline, dissolve, palette swap or custom pixel hook) about its origin (`OriginX`, `OriginY`). `Z` orders the sprites of a batch. Its zero value draws nothing; `NewSprite(f)` returns one at full size and opacity. `Tint` and `Effect` modify only the sprite's own pixels, leaving neighboring sprites and what is drawn under it unchanged. A `Batch` draws sprites of one atlas into a `core.Drawing`, lowest `Z` first and in the batch's order for the same `Z`. Consecutive sprites that are only moved, rotated and scaled evenly draw with one NSGo `DrawAtlas`; a sprite that is mirrored, scaled unevenly, tinted, blended, masked or has an active `Effect` draws on its own (`DrawImageFrom`, `DrawTintedImageFrom`, or a reused per-slot effect buffer). `EffectProgram` and `EffectShader` also run the built-in per-sprite effects on the GPU via `core.Shader`. It leaves the drawing's state as it found it. ```go walk := atlas.Animations["walk"] hero := sprite.NewSprite(walk.Frame()) batch := &sprite.Batch{Atlas: atlas, Sprites: []*sprite.Sprite{&hero}} loop := &game.Loop{ Update: func(dt time.Duration) { walk.Update(dt) hero.Frame = walk.Frame() }, } // In a core.Canvas's Draw: batch.Draw(d) ``` ## sound ```go import "github.com/nsgo-dev/game/pkg/sound" ``` The `Mixer`, its effects and music, on top of NSGo's `audio` package. Its methods are called on the engine's goroutine, as `audio`'s are. ### Mixer A `Mixer` sets how loud a game's sounds and music play: a master volume and a volume for each group the app names, such as `"effects"`, `"music"` and `"ui"`, each from 0 to 1 and 1 until set. - `NewMixer(cx, key)` keeps the volumes in the app's storage (`core.Storage`) under keys starting with `key`, so they hold across launches. - `Master`, `SetMaster`, `Volume(group)` and `SetVolume(group, v)` read and set them. Read in a computation, a volume subscribes it to changes; a set fails with a `*core.StorageFullError` when the storage is full. - `SetDefaultMaster` and `SetDefaultVolume(group, v)` set the volumes a mixer has until the player sets one, such as a project file's, without keeping them in storage. - An effect plays at its own voice's volume times its group's and the master volume, and music at its group's and the master volume. - A volume change applies at once to the effects playing and to music as it plays. An effect whose group or master volume reaches 0 plays on in silence and is heard again as the volume comes back. - While the window is in the background, the mixer silences the effects playing and pauses the music; when the window shows again, it restores the effects still playing and plays the music on from there. `Suspend()` does the same until the `resume` it returns is called, as a cutscene does while it plays ([cutscene](https://game.nsgo.dev/docs/cutscene/)). ### Effect `mixer.Effect(s, group, limit)` plays an `*audio.Sound` through the mixer in a group, at most `limit` playbacks at once (0 for no limit of its own, under the platform's 32 for all sounds), so a burst of one sound does not take every voice. `Play(voice)` starts a playback and reports whether it did. It plays nothing while the volume is 0, for a voice with `Muted` set, or while the app is in the background. With `Limit` playbacks still playing, it stops the oldest to make room. `Stop()` stops every playback of the sound. ### Music `mixer.Music(group)` plays long tracks through the mixer, one at a time, each through an `audio.Player`. - `Play(src, fade)` fades the new track in over `fade` as the tracks playing fade out, by the display's frames, closing them as they reach silence; it switches at once when `fade` is 0. - `Stop(fade)` fades the music out. ```go mixer := sound.NewMixer(cx, "sound") music := mixer.Music("music") music.Play(audio.Source{URI: "asset:theme.m4a"}, 2*time.Second) ``` --- Source: https://game.nsgo.dev/docs/stability/ # API Stability Every package of the module is either stable or experimental. The status says how a package may change from one release to the next, how its changes are announced, and how long an app has to move off what it deprecates. ## Statuses **Stable** packages change only in ways an app can plan for: - From v1.0.0, a stable package keeps its exported API compatible within a major version, as [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and Go's own [compatibility promise](https://go.dev/doc/go1compat) describe: no identifier is removed or renamed, no signature changes, and documented behavior holds. Adding methods, fields, functions and types is compatible. - Before v1.0.0, where Semantic Versioning allows any change, a stable package breaks its API only in a minor release (v0.x.0, never a patch release), and only after deprecating what it removes or changes for at least one minor release, as [Deprecation](https://game.nsgo.dev/docs/stability/#deprecation) describes. - A stable package imports no experimental package of this module, so a change to an experimental package never breaks it. **Experimental** packages are still finding their shape, usually because they wait on an NSGo primitive, a format decision or more use in the sample games: - An experimental package may change or remove any part of its API in any minor release, without a deprecation period. Patch releases still only fix bugs. - Every change to its API is listed in `CHANGELOG.md` under the release that makes it, so an upgrade is never a surprise. - An app may use experimental packages; it should pin the module's version and read the changelog before it upgrades. ## What the promise covers - The exported Go API of a package: its identifiers, signatures, and the behavior its doc comments document. - The text formats a package defines, such as its YAML files. Each has a `version` field; a stable package keeps loading every version of its formats it has written since it became stable, and migrates them on load. - The formats of other tools a package reads, such as Tiled's and LDtk's maps and Aseprite's and TexturePacker's atlases. A stable package keeps reading every version of those exports it has read since it became stable. - For a command (a `cmd` directory), its flags, arguments, exit codes and the formats of its output files. It does not cover: - Packages under `internal/`, which no other module can import. - Behavior a doc comment calls unspecified, and anything that depends on a bug: a fix to a bug is not a breaking change. - Performance, allocation counts and binary size, which are tracked by [budgets](https://game.nsgo.dev/docs/package-size-budgets/) rather than promised. - The minimum Go and NSGo versions, which a minor release may raise; the README's compatibility table lists them for each release. ## Deprecation When a stable package replaces or removes part of its API: 1. The release that deprecates it adds a paragraph starting `Deprecated:` to the identifier's doc comment, naming what to use instead, as Go's [deprecation convention](https://go.dev/wiki/Deprecated) describes, so gopls, staticcheck and pkg.go.dev flag its uses: ```go // DrawAll draws every sprite of the batch. // // Deprecated: Use Batch.Draw, which also orders the sprites by Z. func (b *Batch) DrawAll(d core.Drawing) ``` 2. The same release lists it under `### Deprecated` in `CHANGELOG.md`, with the issue that tracks it. 3. The deprecated identifier keeps working, unchanged, for at least one whole minor release after the one that deprecates it: deprecated in v0.4.0, it is removed in v0.6.0 at the earliest. 4. The release that removes it lists it under `### Removed` in `CHANGELOG.md`. From v1.0.0 nothing is removed from a stable package before the next major version. The releases themselves, their tags, changelog sections and the NSGo version each one needs, are described in [#39](https://github.com/nsgo-dev/game/issues/39). ## Changing a status - A package becomes stable in a minor release through a pull request that changes its row below, says so in the changelog, and has the package's guide in place. It should be used by at least one sample game in `examples` and depend only on stable packages. - A stable package never goes back to experimental. A design it outgrows is replaced by a new package or, from v1.0.0, a new major version. - A new package starts experimental. ## Packages Paths are relative to `github.com/nsgo-dev`. The table is checked by a test in the module, so every package has exactly one row. | Package | Status | Guide | | --- | --- | --- | | `game` | Stable | [Loop](https://game.nsgo.dev/docs/loop/) | | `game/cmd/editor` | Experimental | [Scene Editor](https://game.nsgo.dev/docs/editor/) | | `game/cmd/game` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/cmd/gameapi` | Experimental | | | `game/cmd/gameproject` | Experimental | [Project File](https://game.nsgo.dev/docs/project/) | | `game/cmd/gameschema` | Experimental | [Schemas for YAML files](https://game.nsgo.dev/docs/schemas/) | | `game/cmd/nsgo-game` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/cmd/sizecheck` | Experimental | [Package Size Budgets](https://game.nsgo.dev/docs/package-size-budgets/) | | `game/cmd/wasmprobe` | Experimental | [Package Size Budgets](https://game.nsgo.dev/docs/package-size-budgets/) | | `game/pkg/a11y` | Experimental | [a11y](https://game.nsgo.dev/docs/a11y/) | | `game/pkg/ability` | Experimental | [ability](https://game.nsgo.dev/docs/ability/) | | `game/pkg/accounts` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/accounts/cmd/accountsd` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/accounts/pgstore` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/accounts/sqlitestore` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/accounts/sqlstore` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/accounts/storetest` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/accounts/token` | Experimental | [accounts](https://game.nsgo.dev/docs/accounts/) | | `game/pkg/achievements` | Experimental | [achievements](https://game.nsgo.dev/docs/achievements/) | | `game/pkg/ai` | Stable | [ai](https://game.nsgo.dev/docs/ai/) | | `game/pkg/ai/perception3d` | Experimental | [ai](https://game.nsgo.dev/docs/ai/) | | `game/pkg/anim3d` | Experimental | [anim3d](https://game.nsgo.dev/docs/anim3d/) | | `game/pkg/animclip` | Experimental | [animclip](https://game.nsgo.dev/docs/animclip/) | | `game/pkg/assets` | Experimental | [assets](https://game.nsgo.dev/docs/assets/) | | `game/pkg/bullets` | Experimental | [bullets](https://game.nsgo.dev/docs/bullets/) | | `game/pkg/cards` | Experimental | [cards](https://game.nsgo.dev/docs/cards/) | | `game/pkg/cloudsave` | Experimental | [cloudsave](https://game.nsgo.dev/docs/cloudsave/) | | `game/pkg/cloudsave/cmd/cloudsaved` | Experimental | [cloudsave](https://game.nsgo.dev/docs/cloudsave/) | | `game/pkg/cloudsave/sqlstore` | Experimental | [cloudsave](https://game.nsgo.dev/docs/cloudsave/) | | `game/pkg/cloudsave/storetest` | Experimental | [cloudsave](https://game.nsgo.dev/docs/cloudsave/) | | `game/pkg/cutscene` | Experimental | [cutscene](https://game.nsgo.dev/docs/cutscene/) | | `game/pkg/debug` | Experimental | [debug](https://game.nsgo.dev/docs/debug/) | | `game/pkg/editor` | Experimental | [editor](https://game.nsgo.dev/docs/editor/) | | `game/pkg/editor/editorcmd` | Experimental | [editor](https://game.nsgo.dev/docs/editor/) | | `game/pkg/editor/editormcp` | Experimental | [mcp](https://game.nsgo.dev/docs/mcp/) | | `game/pkg/effects` | Experimental | [effects](https://game.nsgo.dev/docs/effects/) | | `game/pkg/entities` | Experimental | [entities](https://game.nsgo.dev/docs/entities/) | | `game/pkg/fighting` | Experimental | [fighting](https://game.nsgo.dev/docs/fighting/) | | `game/pkg/flow` | Stable | [flow](https://game.nsgo.dev/docs/flow/) | | `game/pkg/fog` | Experimental | [fog](https://game.nsgo.dev/docs/fog/) | | `game/pkg/framedata` | Experimental | [framedata](https://game.nsgo.dev/docs/framedata/) | | `game/pkg/gametest` | Experimental | | | `game/pkg/gameui` | Experimental | [gameui](https://game.nsgo.dev/docs/gameui/) | | `game/pkg/gltf` | Experimental | [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/) | | `game/pkg/idle` | Experimental | [idle](https://game.nsgo.dev/docs/idle/) | | `game/pkg/input` | Stable | [input](https://game.nsgo.dev/docs/input/) | | `game/pkg/inventory` | Experimental | [inventory](https://game.nsgo.dev/docs/inventory/) | | `game/pkg/l10n` | Experimental | [l10n](https://game.nsgo.dev/docs/l10n/) | | `game/pkg/leaderboard` | Experimental | [leaderboard](https://game.nsgo.dev/docs/leaderboard/) | | `game/pkg/leaderboard/selfhost` | Experimental | [leaderboard/selfhost](https://game.nsgo.dev/docs/leaderboard-selfhost/) | | `game/pkg/leaderboard/selfhost/cmd/leaderboardd` | Experimental | [leaderboard/selfhost](https://game.nsgo.dev/docs/leaderboard-selfhost/) | | `game/pkg/lights2d` | Experimental | [lights2d](https://game.nsgo.dev/docs/lights2d/) | | `game/pkg/liveops` | Experimental | [liveops](https://game.nsgo.dev/docs/liveops/) | | `game/pkg/loaderr` | Stable | [Errors](https://game.nsgo.dev/docs/errors/) | | `game/pkg/loot` | Experimental | [loot](https://game.nsgo.dev/docs/loot/) | | `game/pkg/math2d` | Stable | [math2d](https://game.nsgo.dev/docs/math2d/) | | `game/pkg/math3d` | Experimental | [math3d](https://game.nsgo.dev/docs/math3d/) | | `game/pkg/mcp` | Experimental | [mcp](https://game.nsgo.dev/docs/mcp/) | | `game/pkg/modding` | Experimental | [modding](https://game.nsgo.dev/docs/modding/) | | `game/pkg/navbake` | Experimental | [navbake](https://game.nsgo.dev/docs/navbake/) | | `game/pkg/navbake3d` | Experimental | [navbake3d](https://game.nsgo.dev/docs/navbake3d/) | | `game/pkg/net` | Experimental | [net](https://game.nsgo.dev/docs/net/) | | `game/pkg/particles` | Experimental | [particles](https://game.nsgo.dev/docs/particles/) | | `game/pkg/perf` | Experimental | [perf](https://game.nsgo.dev/docs/perf/) | | `game/pkg/physics` | Stable | [physics](https://game.nsgo.dev/docs/physics/) | | `game/pkg/physics3d` | Experimental | [physics3d](https://game.nsgo.dev/docs/physics3d/) | | `game/pkg/pixelfx` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/arcane` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/critters` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/explosions` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/fire` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/holy` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/ice` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/impacts` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/lightning` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/melee` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/moves` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/nature` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/pickups` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/projectiles` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/scifi` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/shadow` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/spawn` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/status` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/transitions` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/ui` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/water` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/pixelfx/weather` | Experimental | [pixelfx](https://game.nsgo.dev/docs/pixelfx/) | | `game/pkg/placeholder` | Experimental | [Placeholder Assets](https://game.nsgo.dev/docs/placeholder/) | | `game/pkg/platformer` | Experimental | [platformer](https://game.nsgo.dev/docs/platformer/) | | `game/pkg/playtest` | Experimental | [playtest](https://game.nsgo.dev/docs/playtest/) | | `game/pkg/presence` | Experimental | [presence](https://game.nsgo.dev/docs/presence/) | | `game/pkg/procgen` | Experimental | [procgen](https://game.nsgo.dev/docs/procgen/) | | `game/pkg/project` | Experimental | [Project File](https://game.nsgo.dev/docs/project/) | | `game/pkg/quality` | Experimental | [quality](https://game.nsgo.dev/docs/quality/) | | `game/pkg/quest` | Experimental | [quest](https://game.nsgo.dev/docs/quest/) | | `game/pkg/random` | Stable | [Determinism](https://game.nsgo.dev/docs/determinism/) | | `game/pkg/refs` | Experimental | [Project File](https://game.nsgo.dev/docs/project/) | | `game/pkg/render3d` | Experimental | [render3d](https://game.nsgo.dev/docs/render3d/) | | `game/pkg/replay` | Experimental | [replay](https://game.nsgo.dev/docs/replay/) | | `game/pkg/resource` | Experimental | [resources](https://game.nsgo.dev/docs/resources/) | | `game/pkg/rhythm` | Experimental | [rhythm](https://game.nsgo.dev/docs/rhythm/) | | `game/pkg/rooms` | Experimental | [rooms](https://game.nsgo.dev/docs/rooms/) | | `game/pkg/rts` | Experimental | [rts](https://game.nsgo.dev/docs/rts/) | | `game/pkg/save` | Stable | [save](https://game.nsgo.dev/docs/save/) | | `game/pkg/scene` | Stable | [scene](https://game.nsgo.dev/docs/scene/) | | `game/pkg/scene3d` | Experimental | [scene3d](https://game.nsgo.dev/docs/scene3d/) | | `game/pkg/sceneformat` | Experimental | [editor](https://game.nsgo.dev/docs/editor/) | | `game/pkg/scenemodel` | Experimental | [scenemodel](https://game.nsgo.dev/docs/scenemodel/) | | `game/pkg/screen` | Stable | [screen](https://game.nsgo.dev/docs/screen/) | | `game/pkg/server` | Experimental | [server](https://game.nsgo.dev/docs/server/) | | `game/pkg/server/cmd/dedicatedserver` | Experimental | [server](https://game.nsgo.dev/docs/server/) | | `game/pkg/skeletal` | Experimental | [skeletal](https://game.nsgo.dev/docs/skeletal/) | | `game/pkg/sound` | Stable | [sound](https://game.nsgo.dev/docs/sound/) | | `game/pkg/sprite` | Stable | [sprite](https://game.nsgo.dev/docs/sprite/) | | `game/pkg/statedump` | Experimental | [statedump](https://game.nsgo.dev/docs/statedump/) | | `game/pkg/stats` | Experimental | [stats](https://game.nsgo.dev/docs/stats/) | | `game/pkg/text` | Experimental | [text](https://game.nsgo.dev/docs/text/) | | `game/pkg/tilemap` | Stable | [tilemap](https://game.nsgo.dev/docs/tilemap/) | | `game/pkg/tileshape` | Experimental | [tileshape](https://game.nsgo.dev/docs/tileshape/) | | `game/pkg/tooling/apiref` | Experimental | | | `game/pkg/tooling/assetbuild` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/pkg/tooling/assetcheck` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/pkg/tooling/audioconv` | Experimental | | | `game/pkg/tooling/bench` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/pkg/tooling/credits` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/pkg/tooling/datatable` | Experimental | | | `game/pkg/tooling/devstate` | Experimental | | | `game/pkg/tooling/hotreload` | Experimental | | | `game/pkg/tooling/importsettings` | Experimental | [Command Line](https://game.nsgo.dev/docs/cli/) | | `game/pkg/tooling/jsonschema` | Experimental | [Schemas for YAML files](https://game.nsgo.dev/docs/schemas/) | | `game/pkg/tooling/ktx2` | Experimental | | | `game/pkg/tooling/library` | Experimental | [Asset and Plugin Library](https://game.nsgo.dev/docs/library/) | | `game/pkg/tooling/manifest` | Experimental | | | `game/pkg/tooling/pack` | Experimental | | | `game/pkg/tween` | Stable | [tween](https://game.nsgo.dev/docs/tween/) | | `game/pkg/undo` | Experimental | [undo](https://game.nsgo.dev/docs/undo/) | | `game/pkg/vehicle` | Experimental | [vehicle](https://game.nsgo.dev/docs/vehicle/) | | `game/pkg/vn` | Experimental | [vn](https://game.nsgo.dev/docs/vn/) | | `game/pkg/vn/cmd/vnsample` | Experimental | [vn](https://game.nsgo.dev/docs/vn/) | | `game/pkg/voxel` | Experimental | [voxel](https://game.nsgo.dev/docs/voxel/) | | `game/pkg/world3d` | Experimental | [world3d](https://game.nsgo.dev/docs/world3d/) | | `game/pkg/worldmap` | Experimental | [worldmap](https://game.nsgo.dev/docs/worldmap/) | --- Source: https://game.nsgo.dev/docs/loop/ # Loop `game.Loop` drives fixed-step updates and interpolated frame draws on an NSGo scope's display frames, pausing automatically while the app is in the background. ```go import "github.com/nsgo-dev/game" ``` ## How the fixed step works Displays run at different refresh rates (60 Hz, 90 Hz, 120 Hz, or variable). If a game moves physics by raw frame delta times, jump heights and collisions change with the display rate. `Loop` decouples simulation from rendering: ```go type Loop struct { Rate int // updates a second, 60 when 0 MaxSteps int // most updates one frame runs, max(1, Rate/10) when 0 Update func(dt time.Duration) // moves the game on by dt, always 1/Rate seconds Draw func(alpha float64) // draws the frame, alpha in [0, 1) } func (l *Loop) Run(cx *core.Scope) (stop func()) ``` On each display frame from NSGo's `RequestAnimationFrame`: 1. The loop adds the elapsed time since the previous frame to an accumulator. 2. While the accumulator holds at least one whole step (`time.Second / time.Duration(Rate)`), it subtracts one step and calls `Update(step)`. A single display frame may run zero, one or several updates. 3. Once fewer than one whole step remains, it calls `Draw(alpha)` with `alpha = float64(acc) / float64(step)` in `[0, 1)`. `Run` reads `Rate`, `MaxSteps`, `Update` and `Draw` on every frame, so you can swap handlers or adjust the rate while the loop is running. ## Interpolating with alpha When the display rate does not evenly divide `Rate` (for example, a 60 Hz simulation on a 120 Hz display), drawing the raw state from `Update` produces visible stutter because some frames run zero updates and some run one. Keep the previous and current state in `Update`, pass `alpha` into a `core.Signal[float64]` from `Draw`, and interpolate inside `core.Canvas.Draw`: ```go func Ball(cx *core.Scope) core.Node { var x, last float32 alpha := core.NewSignal(cx, 0.0) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { last = x x += 120 * float32(dt.Seconds()) }, Draw: func(a float64) { alpha.Set(a) }, } loop.Run(cx) return core.Canvas{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, Draw: func(d *core.Drawing, _ core.Size) { at := last + (x-last)*float32(alpha.Get()) d.SetFillColor(core.RGB(0xff5a1f)).FillRect(at, 40, 16, 16) }, } } ``` Because `alpha` is read only inside `Canvas.Draw`, setting it redraws the canvas without re-evaluating or committing the surrounding view tree. ## Hitch protection and MaxSteps If a single frame takes much longer than usual (a debugger pause, a slow frame, or a device stall), catching up every missed step would cause an even slower next frame — the classic "spiral of death". `MaxSteps` caps how many `Update` calls one display frame may execute: - When `MaxSteps <= 0`, it defaults to `max(1, Rate/10)` — one tenth of a second of simulation (6 steps at 60 Hz, 12 steps at 120 Hz). - When a frame reaches `MaxSteps`, the loop drops the remaining whole steps (`acc %= step`) and moves straight to `Draw`. The game briefly slows down instead of freezing. Set `MaxSteps` explicitly when you need a tighter bound (for example, `MaxSteps: 3` for heavy physics): ```go loop := &game.Loop{ Rate: 60, MaxSteps: 3, Update: stepWorld, Draw: renderWorld, } ``` ## Frame time Each frame adds the time between its timestamp and the previous frame's, exactly as `RequestAnimationFrame` gives it. Where the platform stamps its display frames, that is the display's own frame time, so a frame's length is the display's rather than when the engine got to the frame; elsewhere it is the graph clock's. The first frame after the loop starts or resumes adds the time from then to its timestamp, which may lie a frame ahead where the display stamps a frame with when it will show, so the loop's time is the shown frame's. A frame stamped before the time the loop started or resumed adds nothing, so resuming never moves the accumulator backward, and the next frame adds the time from then. Set `FrameTime` to read each frame's length, the time it adds, ahead of the frame's updates; a frame that adds nothing passes 0. Frame-time statistics, such as [quality](https://game.nsgo.dev/docs/quality/)'s `Selector`, read it. The first frame back from the background measures from the time the window showed again, not the time away, and `FrameTime` may call the `stop` function `Run` returned, which ends the frame before any update. It also fires while `Paused` is set, so a caller that should only measure frames that simulate skips them itself. ```go loop := &game.Loop{ FrameTime: func(dt time.Duration) { selector.Observe(dt) }, Update: stepWorld, Draw: renderWorld, } ``` ## Pausing and syncing subsystems `SetPaused(true)` (or setting `Paused = true`) stops `Update` from advancing while `Draw` keeps running, and unpausing resumes without a catch-up backlog. Set `OnPause` to keep subsystems such as [`sound.Mixer`](https://game.nsgo.dev/docs/sound/#pausing-with-the-game) in sync with the loop's paused state: ```go mixer.SetPauseExempt("ui", true) loop := &game.Loop{ Rate: 60, OnPause: mixer.SetPaused, Update: stepWorld, Draw: renderWorld, } loop.Run(cx) ``` - `SetPaused` calls `OnPause` immediately whenever the paused state changes (repeating the same value does nothing). - Editing `Paused` directly calls `OnPause` on the next frame, or in the same frame when `Update` changes it. - If `Paused` is already `true` when `Run` starts, `Run` calls `OnPause(true)`. - Backgrounding does not call `OnPause`; both `Loop.Run` and `sound.NewMixer` watch `core.Env.Lifecycle` directly so backgrounding pauses and resumes everything in sync without clearing an open pause menu. ## Background pause and stopping `Loop.Run` watches `cx.Env().Lifecycle()`: - **`core.LifecycleBackground`** (minimized, hidden or covered on desktop; app backgrounded on iOS or Android): the loop cancels its pending frame request and runs no updates. - **`core.LifecycleActive` or `core.LifecycleInactive`** (visible, even without focus on desktop): the loop runs normally. When returning from the background, it resets its clock anchor to `cx.Now()`, so time spent away produces zero catch-up steps. The loop ends permanently when either: - The `cx` scope is disposed (for example, navigating away or hiding the component with `core.Show`), or - You call the `stop` function returned by `Run`. Calling `stop()` is safe to repeat and safe from inside `Update`: if `Update` stops the loop, no further updates and no `Draw` run for that frame, and returning from the background will not restart it. ```go var stop func() loop := &game.Loop{ Update: func(dt time.Duration) { if gameOver { stop() } }, Draw: func(alpha float64) { frame.Set(alpha) }, } stop = loop.Run(cx) ``` ## Immersive mode on phones Set `Immersive` to hide a phone's system bars while the game plays and bring them back in menus. The loop calls NSGo's `mobile.Immersive`: Android hides its status and navigation bars and shows them briefly on an edge swipe, iOS hides the status bar and lets the home indicator fade, and HarmonyOS hides its status bar, navigation bar and navigation indicator. Desktop and web targets ignore it. ```go loop := &game.Loop{ Immersive: true, Update: stepWorld, Draw: renderWorld, } loop.Run(cx) // Opening the pause menu shows the bars on the next frame; closing it hides them again. openMenu := func() { loop.SetPaused(true) } closeMenu := func() { loop.SetPaused(false) } ``` - The bars hide while the loop runs and is not `Paused`, and come back while it is `Paused`, when `stop` is called and when `cx` is disposed, so a menu screen that replaces the game's view brings them back too. - The loop hides them as it starts or returns from the background, applies a change to `Immersive` or `Paused` on its next frame (in the same frame when `Update` pauses), and asks the platform only when the state changes. It leaves the bars as they are while the app is in the background. - Hiding and showing the bars can change the safe-area insets the platform reports (HarmonyOS, for one, keeps only the display cutout while they are hidden), so lay HUDs out with [`screen.Viewport.SafeGameRectForEnv`](https://game.nsgo.dev/docs/screen/#safe-area-for-mobile-huds), which follows the insets as they change. - Loops in the same window share the bars: they stay hidden while any loop with `Immersive` set plays, and come back once the last of them pauses or ends. A scene that starts its own loop while the previous scene's loop is still alive, as under a scene transition, keeps the bars hidden when the old loop is disposed, and a pushed scene's loop keeps them hidden when the scene below pauses its own. A menu shown as an NSGo page or dialog can also set `StatusBar: core.StatusBarSetting{Immersive: core.ToggleOff}`, which overrides the window's setting while it is shown. ## Testing with nsgotest `nsgotest` runs display frames deterministically on a virtual clock (one frame every 16.667 ms, 60 frames a second), so you can test gameplay loops, `MaxSteps` hitches and background pauses without sleeping. ```go package mygame_test import ( "testing" "time" "github.com/nsgo-dev/game" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/nsgotest" ) func TestMain(m *testing.M) { nsgotest.Main(m) } func TestLoopSimulation(t *testing.T) { updates := 0 l := &game.Loop{ Rate: 60, MaxSteps: 4, Update: func(dt time.Duration) { updates++ }, } app := nsgotest.Start(t, func(cx *core.Scope) core.Node { l.Run(cx) return core.View{} }) // Advance steps frame by frame for one full second. app.Advance(time.Second) if updates != 60 { t.Fatalf("got %d updates, want 60", updates) } // FastForward jumps in a single frame, exercising MaxSteps. app.FastForward(500 * time.Millisecond) if updates != 64 { t.Fatalf("got %d updates after hitch, want 64", updates) } // Background pauses the loop with no catch-up on resume. app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleBackground}) app.Advance(time.Second) app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleActive}) if updates != 64 { t.Fatalf("got %d updates while backgrounded, want 64", updates) } } ``` --- Source: https://game.nsgo.dev/docs/sprite/ # sprite `game/sprite` loads packed sprite atlases, plays frame animations on a fixed step, and draws Z-ordered sprite batches into an NSGo `core.Canvas`. ```go import "github.com/nsgo-dev/game/pkg/sprite" ``` ## Atlases from TexturePacker and Aseprite An `Atlas` pairs one packed image (`Image`) with its named frames (`Frames`) and optional named animations (`Animations`). `LoadAtlas(img, data)` reads the JSON exported by: - **TexturePacker**: "JSON (Hash)" and "JSON (Array)" - **Aseprite**: `json-hash` and `json-array` (with frame tags enabled to populate `Animations`) Put the packed PNG in `resources/` so NSGo packages it as `"asset:..."`, and embed the JSON with `//go:embed`: ```go //go:embed resources/hero.json var heroJSON []byte atlas, err := sprite.LoadAtlas(core.Src("asset:hero.png"), heroJSON) if err != nil { return err } ``` ### Export settings and scale - **Turn rotation off**: `LoadAtlas` rejects rotated frames with an error. - **Keep frame names unique**: duplicate frame names return an error. - **High-DPI sheets (`meta.scale`)**: all frame rectangles, offsets and source sizes are divided by `meta.scale` (defaults to `1`). A 2× sheet exported with `"scale": "2"` produces coordinates in 1× points, matching NSGo's point coordinates. ### Hand-written atlases For simple tile sheets, prototypes or tests, build an `Atlas` literal directly without JSON: ```go sheet := &sprite.Atlas{ Image: core.Src("asset:sheet.png"), Frames: map[string]sprite.Frame{ "hero": {Name: "hero", X: 0, Y: 0, W: 16, H: 16, Width: 16, Height: 16}, "coin": {Name: "coin", X: 16, Y: 0, W: 8, H: 10, OffsetX: 4, OffsetY: 3, Width: 16, Height: 16}, }, } ``` ## Trimmed frames Packers often trim transparent borders around each frame to pack more pictures into one image. `Frame` keeps both the trimmed rectangle in the atlas and its untrimmed box: ```go type Frame struct { Name string X, Y, W, H float32 // trimmed rectangle in the atlas image, in points OffsetX, OffsetY float32 // position of the trimmed rectangle inside the untrimmed box Width, Height float32 // untrimmed frame size (W, H when untrimmed) } ``` `Sprite` always aligns `OriginX`, `OriginY`, `FlipX`, `FlipY`, rotation and scaling to the untrimmed box (`Width`, `Height`). Trimming never shifts a character's feet or hitbox as animations change from frame to frame. ## Animation `Animation` advances through a slice of `AnimationFrame` values, each with its own `Duration`, driven by `Update(dt)` inside `game.Loop.Update`: ```go type Animation struct { Frames []AnimationFrame Loop bool // ... } type AnimationFrame struct { Frame Frame Duration time.Duration } ``` `Animation` is a value that holds its playback state (current frame index, elapsed time, and completion flag). Copy it from `atlas.Animations` so every entity advances independently: ```go walk := atlas.Animations["walk"] attack := atlas.Animations["attack"] ``` Methods on `Animation`: - `Update(dt)`: advances by `dt`, skipping past as many frames (or full loops) as `dt` covers. - `Frame()`: returns the current `Frame` (zero `Frame` if `Frames` is empty). - `Index()`: returns the current index in `Frames`. - `Done()`: reports whether a non-looping animation has finished displaying its final frame for that frame's full duration. - `Reset()`: rewinds back to frame 0 and clears `Done()`. ### Aseprite frame tags When loading an Aseprite export, each entry in `meta.frameTags` becomes an entry in `atlas.Animations`: - Frame durations come from each frame's `duration` in milliseconds (every frame used by a tag must have a positive duration). - Supported tag directions: `"forward"` (default), `"reverse"`, `"pingpong"` and `"pingpong_reverse"`. - A tag with no `repeat` (or `repeat: 0`) sets `Loop: true`. A tag with `repeat: N` expands `N` passes into a non-looping `Animation` (`Loop: false`). Ping-pong tags count each direction pass as one repeat and never show the turning frame twice in a row. ### Hand-written animations For TexturePacker sheets (which carry no frame tags), assemble an `Animation` from `atlas.Frames`: ```go spin := sprite.Animation{ Loop: true, Frames: []sprite.AnimationFrame{ {Frame: atlas.Frames["coin_0.png"], Duration: 100 * time.Millisecond}, {Frame: atlas.Frames["coin_1.png"], Duration: 100 * time.Millisecond}, {Frame: atlas.Frames["coin_2.png"], Duration: 100 * time.Millisecond}, }, } ``` ## Sprite placement and transforms A `Sprite` places one `Frame` in a `core.Drawing`. Its zero value has `ScaleX == 0`, `ScaleY == 0` and `Alpha == 0`, so it draws nothing. Start with `sprite.NewSprite(frame)` to get full scale (`1, 1`) and full opacity (`1`): ```go hero := sprite.NewSprite(walk.Frame()) hero.OriginX = hero.Frame.Width / 2 hero.OriginY = hero.Frame.Height // anchor at the character's feet hero.X, hero.Y = 120, 200 ``` Fields on `Sprite`: | Field | Meaning | | --- | --- | | `Frame` | The `Frame` to draw; a zero frame (`W <= 0` or `H <= 0`) draws nothing. | | `X`, `Y` | Where the sprite's origin sits in the drawing, in points. | | `OriginX`, `OriginY` | Pivot point inside the untrimmed frame, from its top left. | | `Rotation` | Clockwise rotation about the origin, in radians. | | `ScaleX`, `ScaleY` | Scale about the origin; a negative value mirrors about the origin; `0` draws nothing. | | `FlipX`, `FlipY` | Mirrors the frame inside its untrimmed box before placement, keeping the origin in place. | | `Alpha` | Opacity in `[0, 1]`; `<= 0` draws nothing. Replaces the drawing's alpha for this sprite. | | `Tint` | A `core.Color` that multiplies the frame's red, green, blue and alpha before the sprite is composited; the zero value and opaque white draw the frame unchanged, and any other tint with alpha `0` draws nothing. To fade a sprite out, lower `Alpha`: a tint that reaches transparent black is the zero value and draws the frame unchanged. | | `Effect` | Optional `*Effect` applying per-sprite solid-color flash or silhouette, alpha outline, dissolve, palette swap, or a custom pixel hook to this sprite's pixels alone. A `nil` or inactive `Effect` keeps the sprite on `DrawAtlas`. | | `Z` | Draw order inside a `Batch`; higher `Z` draws on top of lower `Z`. | A tinted sprite recolors only its own pixels: it draws with NSGo's `DrawTintedImageFrom`, which multiplies the image's channels by the tint before compositing with the default source-over mode, so transparent pixels leave what is under the sprite unchanged. `Tint` combines with `Alpha`, `Blend` and `Mask` in the same draw: ```go hit := sprite.NewSprite(atlas.Frames["slime.png"]) hit.Tint = core.RGB(0xff6060) // flash red when damaged ghost := hit ghost.Tint = core.RGBA(0x80c0ff, 0.5) // a pale blue at half the sprite's opacity ``` On the web, a cross-origin atlas image must allow anonymous CORS requests for NSGo to tint its pixels. On HarmonyOS, NSGo tints atlases loaded from bytes or the app's resources, but tinting is not yet checked on a device there, and an atlas built from a pixel buffer or an offscreen image draws nothing there yet. ## Per-sprite effects `Sprite.Tint` multiplies existing channels (so dark pixels stay dark under a white tint) and `game/effects` runs fragment passes over the whole game view. For per-sprite hit flashes, silhouettes, outlines, dissolves and palette swaps that never touch neighboring sprites or the backdrop drawn beneath the sprite, set `Sprite.Effect`: ```go fx := &sprite.Effect{ Flash: sprite.Flash{Color: core.RGB(0xffffff), Strength: 0.8}, // or sprite.Silhouette(core.RGB(0xffffff)) Outline: sprite.Outline{Color: core.RGB(0xffdd00), Thickness: 1}, } hero.Effect = fx // Parameters can change every frame; clearing them returns the sprite to DrawAtlas. fx.Flash.Strength = 0 ``` Stages on `Effect` compose in a fixed order: 1. **`PaletteSwap`**: remaps straight 8-bit sRGB colors matching `Entries` (within `Tolerance`, first match wins) while scaling pixel alpha by `To`'s alpha. 2. **`Sprite.Tint`**: multiplies base sprite color when `Tint` is also set (so hit flashes and outlines are not darkened by the sprite's base tint). 3. **`Dissolve`**: discards pixels whose noise value is below `Threshold` (`[0, 1]`), optionally coloring surviving pixels in `[Threshold, Threshold+EdgeWidth)` with `EdgeColor`. Uses deterministic hash/value noise seeded by `Seed` and cell size `Scale`, or samples a custom grayscale `Noise` image. 4. **`Flash`**: lerps non-transparent RGB toward `Flash.Color` by `Strength` (`[0, 1]`) while preserving each pixel's alpha. `Silhouette(color)` is shorthand for `Strength: 1`. 5. **`Outline`**: draws a rounded solid-color border of `Thickness` source pixels around pixels whose alpha is at least `AlphaThreshold` (default: any non-zero alpha). The sprite buffer expands by `ceil(Thickness)` transparent pixels on every side so tightly cropped frames are never clipped and adjacent frames in the atlas never bleed into the border. 6. **`Custom`**: optional per-pixel hook `func(x, y, w, h int, r, g, b, a float32) (nr, ng, nb, na float32)` over premultiplied RGBA after the built-in stages. ### GPU shader view (`EffectShader`) When a sprite is rendered as its own GPU shader node (for example a boss or portrait animated on the platform's frame clock with `core.AnimatedNode` uniforms, or an `asset:` URI atlas on a GPU-backed target), `EffectProgram`, `Effect.Uniforms` and `EffectShader` run the same built-in stages (palette swap up to `MaxShaderPaletteEntries` = 8 entries, tint, dissolve, flash/silhouette and outline) in a Kage fragment shader (`core.Shader`): ```go sh, err := sprite.EffectShader(atlas, hero) if err != nil { return err } sh.Uniforms["FlashStrength"] = flashNode // animates on the frame clock with no commit per frame ``` `EffectProgram` compiles lazily on first call, so games that only use `Batch.Draw` do not link NSGo's shader compiler. ### Cost per sprite - **Inactive `Effect`**: a `nil` or zero/inactive `*Effect` adds one nil/boolean check and stays on `Batch`'s `DrawAtlas` fast path with zero extra draw calls or pixel work. - **Static active `Effect` in `Batch.Draw`**: each effected sprite occupies one reused scratch slot in `Batch`. When the atlas version, frame, tint and effect parameters are unchanged from the previous frame, `Batch.Draw` skips pixel recomputation and reuses the same `ImageSource.Version`, so NSGo skips copying and uploading the buffer (`~0.21 µs` per 32×32 sprite). - **Changing parameters every frame in `Batch.Draw`**: `Batch` reuses each slot's `*image.RGBA` and alpha scratch slice in place (growing capacity only when dimensions increase and trimming idle tail slots back down), so mutating `Flash.Strength`, `Outline.Thickness`, `Dissolve.Threshold` or `PaletteSwap.Entries` every frame performs zero pixel-buffer allocations and bumps `ImageSource.Version` monotonically. Cost scales linearly with the frame's pixel area (`W × H`, plus `(W+2p) × (H+2p) × πr²` for `Outline` on non-opaque edge pixels). Reference `BenchmarkSpriteEffects` readings on Apple Silicon (`-cpu 1`): | Effect (32×32 sprite, updated every frame) | CPU time / sprite | Heap allocs / frame | | --- | ---: | ---: | | `Flash` (16×16) | 0.84 µs | 1 (`96 B`, `DrawOp` image copy) | | `Flash` (32×32) | 3.3 µs | 1 (`96 B`) | | `Outline` (1 px, 32×32) | 6.2 µs | 1 (`96 B`) | | `Outline` (2 px, 32×32) | 13.1 µs | 1 (`96 B`) | | `Dissolve` + edge glow (32×32) | 7.1 µs | 1 (`96 B`) | | Static `PaletteSwap` (32×32, cached hit) | 0.21 µs | 1 (`96 B`) | - **GPU `EffectShader`**: one `core.Shader` surface per sprite view (no per-frame CPU pixel writes or uploads once the atlas texture is on the GPU; best suited to a small number of hero/boss/UI sprites rather than hundreds of batched entities). ### Per-target behavior and fallbacks `Batch.Draw` applies exact CPU pixel effects whenever the atlas exposes pixels (`Atlas.Image.Pixels != nil`, or `Atlas.Image.Data` decoded lazily via `image.Decode` using any decoder the app imports such as `_ "image/png"`). If an atlas is URI-only (`core.Src("asset:...")` with neither `Pixels` nor `Data`), `Batch.Draw` falls back without touching neighbors or canvas composite state: full dissolve (`Threshold >= 1`) skips drawing, `Flash` falls back to NSGo's per-draw multiply tint (`DrawTintedImageFrom`, exact for darkening flashes and black silhouettes, unable to brighten dark texels toward white), and `Outline`, partial `Dissolve`, `PaletteSwap` and `Custom` draw the sprite unmodified. | Target | `Batch.Draw` (`Pixels` or `Data` atlas) | `Batch.Draw` (URI-only atlas) | `EffectShader` (`core.Shader` GPU) | | --- | --- | --- | --- | | macOS, iOS | Full exact effects via `CGImage` pixel buffer | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (Metal) | | Windows | Full exact effects via Direct2D premultiplied BGRA bitmap | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (Direct3D 11) | | Linux | Full exact effects via Cairo ARGB32 surface | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (OpenGL 3.3 / ES 3.0) | | Android | Full exact effects via `Bitmap` pipe transfer | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Full GPU shader (GLES 3.0) | | Web (Wasm) | Full exact effects via cached offscreen `` | `DrawTintedImageFrom` flash fallback (CORS required cross-origin); full dissolve skipped | Full GPU shader (WebGL 2) | | HarmonyOS | Full exact effects via `PixelMap` pixel buffer (`Tint` folded into pixels) | `DrawTintedImageFrom` flash fallback (not yet device-verified); full dissolve skipped | Unavailable (shader view draws empty; use `Batch.Draw`) | | Mini programs | Full exact effects via offscreen 2D canvas `putImageData` | `DrawTintedImageFrom` flash fallback; full dissolve skipped | Unavailable (`nsgo_noshader`; use `Batch.Draw`) | | Headless (`gametest.RenderOps`) | Full exact pixel output for pixel-comparison tests | Records `DrawTintedImageFrom` / `DrawImageFrom` ops | Models lanes and uniforms in `nsgotest` | ## Batch and Z ordering A `Batch` draws sprites from a single `Atlas` into a `*core.Drawing`: ```go batch := &sprite.Batch{ Atlas: atlas, Sprites: []*sprite.Sprite{&shadow, &hero, &weapon}, } // Inside core.Canvas.Draw: batch.Draw(d) ``` - **Ordering**: `Draw` stably sorts sprites into an internal scratch slice by ascending `Z` (lowest `Z` drawn first, equal `Z` in the order `Sprites` lists them). `batch.Sprites` itself is never reordered. - **Drawing state**: `Draw` leaves `d`'s transform, alpha, composite and clip exactly as it found them. - **Draw calls**: consecutive sprites, in Z order, that are only moved, rotated and scaled evenly (`ScaleX == ScaleY`, or both flips together) with the default `Blend` and no `Mask` of their own draw with one NSGo `DrawAtlas`. A mirrored, unevenly scaled, blended or masked sprite, and a run of only one sprite, draws with its own `DrawImageFrom`, wrapped in `Save`/`Restore` when it is turned, mirrored, faded, blended or masked. - **Alpha in a run**: a run of sprites at full opacity keeps the drawing's alpha, as a single sprite does. A run of faded sprites draws between `Save` and `Restore` with the alpha set to `1` and each sprite's own `Alpha`, so `Alpha` still replaces the drawing's alpha. A change from opaque to faded sprites starts a new run. - **Depth-sorted scene layers**: a `game/scene` layer sorted by Y (`SortY`) or by a custom key draws its sprites one at a time, so each is a run of one and still draws with its own `DrawImageFrom`. Only layers without per-sprite sorting, and batches drawn directly, get `DrawAtlas`. - **Skipped sprites**: a sprite whose position, origin, rotation, scale or alpha is NaN or infinite draws nothing, as does a batch with no `Atlas`. The picture is the same as one `DrawImageFrom` per sprite: the tests replay both recordings and compare every drawn rectangle, a fuzz test does so for random batches, and `gametest.RenderOps` renders both to identical pixels. ### Recording cost before and after `DrawAtlas` `BenchmarkBatchRecord` records a frame of 1,000 and 5,000 moving sprites, a fifth of them rotated and scaled, with one `DrawImageFrom` each (`per-sprite`) and with `DrawAtlas` (`atlas`). It times only recording on the CPU, not the platform's drawing. `sprites/60Hz` is 16.7 ms divided by the recording time per sprite, an upper bound that no frame reaches, not a measured sprite count at 60 frames per second: ```sh go tool nsgo test ./pkg/sprite -- -run '^$' -bench BatchRecord -benchmem -cpu 1 -benchtime 2s ``` Readings from 2026-11-23 on a shared 24-core x86-64 Linux machine; the times move with the machine's load, the allocations do not: | Sprites | Recording time per frame | Allocations per frame | Sprites recorded per 16.7 ms | | ---: | ---: | ---: | ---: | | 1,000 | 219 µs → 81 µs | 1,000 → 3 | 76,000 → 206,400 | | 5,000 | 926 µs → 586 µs | 5,000 → 3 | 90,000 → 142,300 | Recording is the smaller part of a frame: the platform still draws every sprite. The largest sprite count this repository's `Batch` holds at 60 frames per second on a device, before and after, has not been measured yet ([#28](https://github.com/nsgo-dev/game/issues/28)). NSGo's own [many-sprite comparison](https://github.com/nsgo-dev/nsgo/blob/main/docs/architecture/performance.md#canvas-atlas-batching) of `DrawAtlas` against one `DrawImageFrom` per sprite, with its own fixture of 32 × 32 crops rather than this `Batch`, measured frame rates at a fixed sprite count: 5,000 sprites rose from 29.3 to 39.9 frames per second on a Pixel 3 XL, from 55.5 to 60.0 in headless Chromium and from 6.6 to 7.8 on macOS, with 1,000 sprites already at 60 frames per second on Android and Chromium. On Linux it has no reliable reading yet: in a shared Ubuntu VM the isolated Cairo replay of 5,000 sprites fell from 20.86 to 15.81 ms, but the end-to-end rates, which moved with the host's load, were lower in the first atlas run (25.54 to 10.83 at 1,000 sprites and 10.37 to 1.98 at 5,000), and NSGo calls for a paired run on a dedicated machine. ## Testing with nsgotest Because `Batch.Draw` records ordinary `core.DrawOp` operations on a `core.Canvas`, you can inspect what a batch drew headlessly with `nsgotest`: ```go app := nsgotest.Start(t, func(cx *core.Scope) core.Node { return core.Canvas{ TestID: "stage", Style: core.Style{Width: core.Pt(320), Height: core.Pt(240)}, Draw: func(d *core.Drawing, _ core.Size) { batch.Draw(d) }, } }) ops := app.Find("stage").Ops if len(ops) == 0 { t.Fatal("expected sprite draw operations") } ``` A batch records its sprites in `DrawAtlas` operations as well as `DrawImageFrom` ones, so check what it drew with `gametest.ImageDraws(ops)` rather than by counting `DrawImage` operations. It returns each drawn rectangle of an image, with its source rectangle, its corners on the canvas, its alpha, composite, tint, sampling and clip, however it was recorded. `gametest.AssertSameImages(t, got, want)` compares two recordings that way, images only (fills, strokes and texts are checked separately), such as a batch against hand-written `DrawImageFrom` calls, and `gametest.RenderOps` renders `DrawAtlas` too. --- Source: https://game.nsgo.dev/docs/sound/ # sound `game/sound` layers a persistent volume `Mixer`, voice-limited sound `Effect`s, crossfading `Music`, and automatic background muting on top of NSGo's `audio` package. ```go import ( "github.com/nsgo-dev/game/pkg/sound" "github.com/nsgo-dev/nsgo/audio" ) ``` All `Mixer`, `Effect` and `Music` methods run on the engine's goroutine, just like `audio`'s methods. From any other goroutine, dispatch through `cx.Post`. Ship audio files under `resources/` as **WAV**, **AAC (`.m4a`)** or **MP3**. ## Mixer and persistent volumes A `Mixer` holds one master volume and a volume for every group name your game uses (for example `"effects"`, `"music"` and `"ui"`). Every volume is in `[0, 1]` and defaults to `1`. ```go mixer := sound.NewMixer(cx, "sound") ``` `NewMixer(cx, key)` stores values in `cx.Storage()` (`core.Storage`) under: - `.master` - `.group.` Volumes persist automatically across app launches. Passing values outside `[0, 1]` clamps them (and `NaN` resets to `1`). If storage is full, `SetMaster` and `SetVolume` return `*core.StorageFullError` and keep the previous volume. `SetDefaultMaster` and `SetDefaultVolume(group, v)` set the volume a mixer has until the player sets one, such as a bus volume from the [project file](https://game.nsgo.dev/docs/project/). They keep nothing in storage, so a volume the player set wins; set them before the game reads volumes. ### Reactive settings UI `Master()` and `Volume(group)` read from `core.Storage`, so calling them inside a reactive view function subscribes that view to volume changes automatically: ```go core.Text{ ContentFunc: func() string { return fmt.Sprintf("Music: %.0f%%", mixer.Volume("music")*100) }, } ``` ### How volume changes take effect - **Effects**: each playback uses `voice.Volume * mixer.Volume(group) * mixer.Master()`. Volume changes apply at once to effects already playing, through each playback's `audio.Playback`, and to those started afterwards. A playback whose group or master volume reaches `0` plays on in silence and is heard again when the volume comes back. - **Music**: active tracks update live at `mixer.Volume(group) * mixer.Master()`, pausing when the effective gain reaches `0` and resuming from the same position when raised above `0`. ## Effect and voice limits Short sounds (under 8 MiB encoded and 5 seconds decoded) are decoded into memory once with `audio.LoadSound`, then wrapped in a mixer `Effect`: ```go var hit *sound.Effect audio.LoadSound(cx, audio.Source{URI: "asset:sounds/hit.wav"}, func(s *audio.Sound, err error) { if err != nil { return } hit = mixer.Effect(s, "effects", 4) }) ``` The third argument (`limit`) caps how many overlapping playbacks of that sound may run at once (`0` means no per-effect cap, still bounded by the platform's 32 concurrent sound voices). This prevents rapid bursts — such as coins or footsteps — from starving every other sound. - `Play(v audio.Voice) bool` starts a playback and reports whether it asked for one. It returns `false` when effective gain is `0` (including a voice with `Muted` set) or the app is in the background, and `true` otherwise, even where the playback ends at once because the backend could not start it. When `Limit` playbacks are still playing, it stops the oldest of them to make room, so the newest are heard; playbacks that end on their own free their place without stopping another, and one that never started leaves them playing. A backend that cannot address playbacks plays the voice as it started, outside the limit and later volume changes; every NSGo backend with audio can. - `Stop()` stops every playback of that sound (and any other `*audio.Sound` sharing the same source). - Close the underlying `*audio.Sound` when you no longer need it, or let `cx`'s scope disposal free it. ```go if hit != nil { hit.Play(audio.Voice{Volume: 0.9, Rate: 1.05}) } ``` ## Positional effects in 2D A `Listener2D` hears effects placed in the world from where the 2D camera looks: an effect to the left of the camera plays panned left, one to the right panned right, and both play quieter the further they are. ```go listener := sound.Listener2D{ Position: math2d.V2(cam.X, cam.Y), Rotation: cam.Rotation, Near: 64, // full volume up to 64 world units away Far: 640, // silent from 640 away Rolloff: sound.RolloffInverse, } hit.PlayAt(listener, math2d.V2(enemy.X, enemy.Y), audio.Voice{Volume: 0.9}) ``` - `Position` and `Rotation` follow the camera, such as `tilemap.Camera`'s `X`, `Y` and `Rotation`, so left and right are the view's even when the camera turns. Distances are in world units; the camera's zoom does not change them. - `Gain(pos)` is `1` within `Near`, `0` at `Far` and beyond, and falls between them by `Rolloff`: `RolloffLinear` (the default) in a straight line, `RolloffInverse` as `Near / distance` rescaled to reach `0` at `Far`, and `RolloffExponential` as `(Near / distance)^2` rescaled to reach `0` at `Far`. A `Far` that is not greater than `Near`, infinite or `NaN` turns attenuation off. - `Pan(pos)` is the effect's offset across the view divided by `PanWidth`, clamped to `[-1, 1]`; a `PanWidth` of `0` takes `Far`. An effect straight above or below the camera plays centered. - `PlayAt(l, pos, v)` plays with `v.Volume * l.Gain(pos)`, then the group and master volumes as `Play` does, and `v.Pan` replaced by `l.Pan(pos)`. It returns `false` and plays nothing beyond `Far`, so silent effects never take a voice or count against `Limit`. - `Cue.PlayAt(l, pos)` picks the cue's next variant as `Play` does and plays it through its effect's `PlayAt`, at the variant's volume and pitch, so randomized footsteps and hits can be placed too. - `Voice(pos, v)` returns the voice `PlayAt` would play with, for playing an `audio.Sound` directly. Where the effect is silent it sets `Muted`, since `audio` plays a volume of `0` at full volume. - The camera's rotation only turns the pan; distance ignores it, and an infinite or `NaN` `Rotation` counts as `0`. The pan and volume are fixed when the playback starts, because NSGo's `audio.Playback` cannot change its pan once playing. Suit it to short effects; a long sound that follows a moving source would need to be replayed. ## Positional effects in 3D `Listener3D` hears effects placed in a right-handed Y-up 3D world (`+X` right, `+Y` up, `-Z` forward — matching `math3d` and `scene3d.Camera`). Because `sound.Vec3` shares the exact field layout of `math3d.Vec3`, convert camera vectors directly with `sound.Vec3(...)`: ```go listener := sound.Listener3D{ Position: sound.Vec3(cam.Pos), Forward: sound.Vec3(cam.Forward()), Up: sound.Vec3(cam.Up()), Near: 2, Far: 40, Rolloff: sound.RolloffInverse, } mixer.SetListener3D(listener) // Fire-and-forget 3D effect (mirrors Effect.PlayAt): hit.PlayAt3D(listener, sound.Vec3(enemyPos), audio.Voice{Volume: 0.9}) // Live 3D playback that tracks camera and source motion: engine := loopSFX.Play3D(sound.Vec3(shipPos), audio.Voice{Loop: true}, sound.Spatial3DOptions{}) engine.SetPosition(sound.Vec3(nextShipPos)) ``` - **Distance attenuation**: `Gain(pos)` is `1` within `Near`, `0` at `Far` and beyond, and falls between them by `Rolloff` (`RolloffLinear`, `RolloffInverse`, or `RolloffExponential`, shaped by optional `RolloffFactor`). A `Far` not greater than `Near`, infinite, or `NaN` turns distance attenuation off. - **Rear head-shadow attenuation**: sounds behind the listener (`dot(dir, forward) < 0`) interpolate linearly from `1` at the lateral plane down to `RearGain` directly behind (`DefaultRearGain`, `0.7`, when `RearGain` is zero, negative, or `NaN`; set `RearGain: 1` to disable). An effect behind the camera is therefore quieter than an equidistant effect in front while remaining panned to its left or right side. - **Stereo pan**: `Pan(pos)` projects the unit direction from the listener to the source onto the listener's right axis (`dot(dir, right)`), clamped to `[-1, 1]`. Sounds at the listener, directly ahead, directly behind, directly overhead/underfoot, or with `NaN` coordinates play centered (`0`). Set a positive finite `PanWidth` to use linear lateral-offset panning like `Listener2D`. - **Directional source cones & overrides**: pass `Spatial3DOptions` to `Listener3D.Spatialize`, `Spatialize3D`, `Listener3D.VoiceWithOptions`, `Effect.Play3D`, or `Cue.Play3D` to add a directional emission cone (`SourceForward`, `InnerConeAngle`, `OuterConeAngle`, `OuterGain`) or per-source `Near`/`Far`/`Rolloff`/`RolloffFactor` overrides. - **Live `Playback3D` tracking**: `Mixer.SetListener3D(l)` refreshes every active `Playback3D` started by `Effect.Play3D` or `Cue.Play3D`, and `Playback3D.SetPosition` / `SetOptions` refresh a single source. Live distance, rear, and source-cone attenuation update immediately through `audio.Playback.SetVolume` while honoring master/group volumes, `SetPaused`, `SetPauseExempt`, `Suspend`, and background muting. Because NSGo's `audio.Playback` cannot change stereo pan after starting, `Playback3D.Pan()` tracks the latest computed pan while the backend playback keeps its initial pan. - **Pose helpers & cues**: `Listener3D.SetPose(pos, forward, up)` and `Listener3D.LookAt(target, up)` update orientation without altering attenuation settings. `Cue.PlayAt3D` and `Cue.Play3D` position randomized sound cues in 3D. ## Music and crossfades `mixer.Music(group)` plays streaming tracks through `audio.Player`, one active track at a time, with smooth crossfades: ```go music := mixer.Music("music") music.Loop = true music.Play(audio.Source{URI: "asset:music/overworld.m4a"}, 2*time.Second) ``` - `Loop`: when `true`, tracks started by subsequent `Play` calls loop at their end. - `Play(src, fade)`: starts the new track at once, muted, and fades it in over `fade` while fading all currently playing tracks out on display frames (`core.Scope.Animate`), closing faded-out players once they reach silence. When `fade <= 0`, it switches immediately. Starting another `Play` mid-crossfade smoothly fades out the incoming track from its current level. - `Stop(fade)`: fades active music out over `fade` and closes its players (`fade <= 0` stops immediately). On the web, browsers enforce autoplay policies and refuse playback (`audio.NotAllowed`) until the user interacts with the page; start music from a button press or first tap/click. ## Pausing with the game `mixer.SetPaused(true)` pauses gameplay audio when a pause menu opens, and `mixer.SetPaused(false)` resumes it when the menu closes: - **Gameplay groups** (any group not marked exempt): playing `Effect`s are silenced through their `audio.Playback` without stopping, new `Effect.Play` calls return `false`, and `Music` pauses at its current position. On resume, effects still playing return to their volume and music continues from where it paused. Because NSGo v0.3.0's `audio.Playback` provides volume, rate and stop controls without a playhead pause command, short one-shot effects finish silently if the pause lasts longer than their remaining duration, while looping effects and `Music` (`audio.Player`) resume right where they left off. - **Exempt groups**: call `mixer.SetPauseExempt("ui", true)` so pause-menu clicks or menu music keep playing while `mixer.Paused()` is `true`. `mixer.PauseExempt(group)` reports whether a group is exempt, and toggling exemption while paused applies immediately. - **Loop sync**: pair `mixer.SetPaused` with [`game.Loop.OnPause`](https://game.nsgo.dev/docs/loop/#pausing-and-syncing-subsystems) so gameplay sounds pause and resume automatically whenever `loop.SetPaused` or `loop.Paused` changes: ```go mixer.SetPauseExempt("ui", true) loop := &game.Loop{ Rate: 60, OnPause: mixer.SetPaused, Update: stepWorld, Draw: renderWorld, } loop.Run(cx) ``` ## Background muting `NewMixer` watches `cx.Env().Lifecycle()` on the same condition as `game.Loop.Run`, so backgrounding pauses and resumes audio in sync with the loop: - When the app enters **`core.LifecycleBackground`** (minimized, hidden or covered on desktop; backgrounded on iOS or Android), the mixer silences every playing effect (including pause-exempt groups such as `"ui"`), drops new `Effect.Play` calls, and pauses all music. - When the window returns to **`core.LifecycleActive`** or **`core.LifecycleInactive`** (visible, even unfocused on desktop), pause-exempt groups resume at once, while gameplay groups resume only if `mixer.Paused()` is `false` — returning from the background while the pause menu is still open keeps gameplay sounds silenced and gameplay music paused at its position until the menu closes. ## Suspending for a cutscene `mixer.Suspend()` silences the mixer the same way the background does, until the `resume` function it returns is called: effects playing are silenced, new `Effect.Play` calls play nothing, and music pauses and later plays on from where it stopped. Holds nest, so the mixer plays again only once every `Suspend` has been resumed; calling one `resume` twice does nothing. `mixer.Suspended()` reports whether a hold is left. ```go resume := mixer.Suspend() // ... something else has the speakers ... resume() ``` [cutscene](https://game.nsgo.dev/docs/cutscene/)'s `Player` suspends the mixer while a video plays. ## Testing with nsgotest Enable virtual audio in `nsgotest` with `nsgotest.Environment(core.Environment{Audio: true})` and configure decoded durations on `app.AudioDurations` to test voice limits, crossfades, persistence and background muting deterministically: ```go package mygame_test import ( "testing" "time" "github.com/nsgo-dev/game/pkg/sound" "github.com/nsgo-dev/nsgo/audio" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/nsgotest" ) func TestMain(m *testing.M) { nsgotest.Main(m) } func TestMixerCrossfadeAndMute(t *testing.T) { var mixer *sound.Mixer var music *sound.Music app := nsgotest.Start(t, func(cx *core.Scope) core.Node { mixer = sound.NewMixer(cx, "sound") music = mixer.Music("music") music.Loop = true return core.View{} }, nsgotest.Environment(core.Environment{Audio: true}), func(a *nsgotest.App) { a.AudioDurations = map[string]time.Duration{ "asset:a.m4a": time.Minute, "asset:b.m4a": time.Minute, } }, ) mixer.SetVolume("music", 0.5) music.Play(audio.Source{URI: "asset:a.m4a"}, 0) music.Play(audio.Source{URI: "asset:b.m4a"}, time.Second) app.Advance(1100 * time.Millisecond) if !app.Players[0].Closed || !app.Players[1].Playing { t.Fatalf("expected track A closed and track B playing") } app.SetEnvironment(core.Environment{Audio: true, Lifecycle: core.LifecycleBackground}) app.Settle() if app.Players[1].Playing { t.Fatal("expected music paused in background") } } ``` --- Source: https://game.nsgo.dev/docs/3d-models-blender/ # 3D Models from Blender Prepare static, skinned, and animated 3D models in Blender 4.x or convert FBX and OBJ assets into glTF 2.0 (`.glb`/`.gltf`) matching NSGo's 3D conventions, verified against two committed round-trip sample models. > NSGo's 3D rendering layer is Stage 2 of the [overview](https://game.nsgo.dev/docs/) ([nsgo#1059](https://github.com/nsgo-dev/nsgo/issues/1059)). The conventions and glTF 2.0 asset contract on this page let you author, convert, and validate 3D assets ahead of time so they load cleanly without re-exporting. ## NSGo 3D conventions NSGo adopts the standard glTF 2.0 coordinate system and physical units across every 3D package: | Property | Convention | Notes | | --- | --- | --- | | Handedness | Right-handed | Matches glTF 2.0 and OpenGL/Metal/Vulkan view math | | Axes | `+X` right, `+Y` up, `-Z` forward | Characters and vehicles face `-Z` in local space | | Units | Meters (`1.0` = 1 m) | Human character ≈ `1.7`–`1.8` units tall; physics and lighting assume meters | | Front-face winding | Counter-clockwise (CCW) | Outward normals satisfy `(v1 - v0) × (v2 - v0) · n > 0` | | Texture UVs | Origin `(0, 0)` at top-left | Standard glTF 2.0 UV layout; Blender's glTF exporter flips V automatically | | PBR workflow | Metallic-Roughness | `Principled BSDF` base color, metallic, roughness, normal, occlusion, emissive | | Runtime format | Binary glTF 2.0 (`.glb`) | Single self-contained file with aligned binary buffers; use `.gltf` for JSON inspection | | Skinning limit | 4 bone influences per vertex | One `JOINTS_0` / `WEIGHTS_0` `VEC4` attribute per vertex, normalized to sum to `1.0` | ### Project layout for 3D assets Keep runtime `.glb` files inside `resources/` so `nsgo build` bundles them on all six targets and your game loads them via `"asset:..."`. Keep heavy authoring files (`.blend`, `.fbx`, `.obj`, `.psd`) outside `resources/` (for example in `art/`) so they never inflate release packages. A `.gltf` export with its `.bin` buffer and texture files can stay in `art/` too: a model target of [`game assets`](https://game.nsgo.dev/docs/cli/#assets) packs it into one `.glb` under `resources/`, scaled and with or without its animations as the model's import settings sidecar says: ```text mygame/ ├─ art/ # authoring sources, not shipped in builds │ ├─ crate.blend │ └─ robot_arm.blend ├─ resources/ # packaged with every target ("asset:...") │ └─ models/ │ ├─ crate.glb │ └─ robot_arm.glb └─ nsgo.yaml ``` See [Building and Shipping](https://game.nsgo.dev/docs/shipping/) for using `mobile.exclude_resources` when desktop and mobile builds ship different LODs or texture sizes. ## Blender 4.x export checklist Blender uses a right-handed **Z-up** viewport (`+X` right, `+Y` into screen, `+Z` up). When you export with **+Y Up** enabled, Blender's glTF 2.0 exporter rotates the scene `-90°` around X so Blender's `+Z` becomes `+Y` and Blender's `-Y` (Front View, Numpad `1`) becomes **`-Z` forward** in glTF. ### Before exporting (every asset) 1. **Set metric units**: in *Scene Properties → Units*, set *Unit System* to `Metric` and *Unit Scale* to `1.0`. Verify the object's dimensions in meters in the *N* sidebar (`Item → Dimensions`). 2. **Face `-Y` in Blender**: orient characters, weapons, and vehicles so their front faces `-Y` (looking toward you in Front Orthographic View, Numpad `1`). After `+Y Up` export, they face `-Z` forward. 3. **Place the pivot cleanly**: put static props and characters with their base or feet resting at `(0, 0, 0)` so spawning at `y = 0` places them flush on the floor. 4. **Apply transforms**: select the mesh (and armature for rigged assets) and press `Ctrl+A → Rotation & Scale` (plus `Location` for origin-anchored props). Never export with negative scale (`-1`), which flips triangle winding inside out. 5. **Check face orientation**: enable *Viewport Overlays → Face Orientation*. Every visible outside surface must be blue. If any faces appear red, enter Edit Mode, select all (`A`), and run `Mesh → Normals → Recalculate Outside` (`Shift+N`). 6. **Use `Principled BSDF`**: wire textures into `Base Color`, `Metallic`, `Roughness`, `Normal` (via a `Normal Map` node), and `Emission`. Bake procedural Blender shader nodes (Noise, Voronoi, ColorRamp) to image textures before exporting; procedural Blender nodes do not exist in glTF. ### Static meshes (`.glb`) Open `File → Export → glTF 2.0 (.glb/.gltf)` and verify these settings: - **Format**: `glTF Binary (.glb)`. - **Include**: enable `Selected Objects` (or `Active Collection`) so cameras, lights, and guide empties stay out of the asset. - **Transform**: check **`+Y Up`**. - **Data → Mesh**: - Check `Apply Modifiers` (bakes Subdivision, Mirror, Bevel, and Weighted Normal modifiers). - Check `UVs` and `Normals`. - Check `Tangents` if the material uses a normal map (avoids tangent-space mismatches across renderers). - Uncheck `Vertex Colors` unless your shader reads them. - **Data → Material**: `Materials: Export`, images as `Automatic` (PNG/JPEG) or `WebP` where supported. - **Data → Compression**: leave **Draco mesh compression unchecked** while iterating, so the file stays easy to inspect; turn it on for shipped assets when download size matters. `game/gltf` decodes Draco in pure Go (see [Compressed geometry](https://game.nsgo.dev/docs/3d-models-blender/#compressed-geometry)). ### Skinned meshes and animations Rigged characters and props need a few extra checks so GPU skinning and animation blending work cleanly: 1. **Single Armature root with unit scale**: apply `Scale = (1, 1, 1)` to both the Armature and the skinned Mesh before exporting. Keep the Armature modifier on the mesh (do **not** apply the Armature modifier). 2. **Enforce the 4-bone influence limit**: - Select the mesh, switch to *Weight Paint* mode, and run `Weights → Limit Total` with **Limit = `4`**. - Immediately run `Weights → Normalize All` (with *Lock Active* unchecked) so every vertex's weights sum strictly to `1.0`. - In the glTF exporter under *Data → Skinning*, check `Skinning` and leave **`Include All Bone Influences` unchecked** so only `JOINTS_0` and `WEIGHTS_0` (4 joints per vertex) are emitted. 3. **Export multiple clips via Actions / NLA**: - Give each clip a clean Action name (`Idle`, `Walk`, `Jump`, `Wave`). - Push each Action down to an NLA strip in the *Non-Linear Animation* editor so Blender preserves every clip in the file. - In the exporter under *Animation*, set *Animation Mode* to **`Actions`** (or `NLA Tracks`), check **`Always Sample Animations`** if the rig uses IK, Copy Rotation, or drivers, and set *Sampling Rate* to `30` or `60` fps (matching your fixed step). - Enable `Optimize Animation Size` to drop redundant flat channels while keeping keyframe curves accurate. 4. **Root motion vs in-place locomotion**: - Structure your rig with a ground-level `Root` bone at `(0, 0, 0)` parenting `Hips`/`Pelvis`. - For **in-place** clips (where Go code moves the entity transform), keep `Root` stationary at `(0, 0, 0)` and strip horizontal `X`/`Z` drift from `Hips`. - For **root-motion** clips (such as dodge rolls or lunge attacks), author horizontal translation and yaw rotation exclusively on the `Root` bone. Runtime playback can then sample per-step root deltas and hand them to your movement controller without double-applying displacement. 5. **Clip events (`extras.events`)**: - NSGo reads per-clip event markers from `animations[i].extras.events`, an array of `{ "time": , "name": "" }` objects: ```json "extras": { "events": [ { "time": 0.0, "name": "wave_start" }, { "time": 0.5, "name": "wave_apex" }, { "time": 1.0, "name": "wave_end" } ] } ``` - In Blender, add **Pose Markers** to an Action in the *Dope Sheet → Action Editor* (`M` to add a marker, `Ctrl+M` to rename it), then copy them onto `action["events"]` before exporting with **`Include → Custom Properties`** enabled: ```python import bpy fps = bpy.context.scene.render.fps / bpy.context.scene.render.fps_base for action in bpy.data.actions: if not action.pose_markers: continue start = action.frame_range[0] events = [ {"time": round((m.frame - start) / fps, 6), "name": m.name} for m in sorted(action.pose_markers, key=lambda item: item.frame) ] action["events"] = events ``` ## Converting FBX and OBJ from other tools Assets from Maya, 3ds Max, ZBrush, Mixamo, or third-party marketplaces frequently arrive as `.fbx` or `.obj`, often in **centimeters** (`100×` too large) or **Z-up** orientation. Convert them to `.glb` during asset preparation instead of parsing FBX or OBJ at runtime. ### Headless Blender CLI conversion You can batch-convert `.fbx` and `.obj` files reproducibly in CI or a local script using Blender's headless CLI (`blender --background`). Save the following helper as `tools/convert_to_glb.py`: ```python import os import sys import bpy argv = sys.argv[sys.argv.index("--") + 1 :] src_path, dst_path = argv[0], argv[1] scale_factor = float(argv[2]) if len(argv) > 2 else 1.0 # pass 0.01 for cm -> m bpy.ops.wm.read_factory_settings(use_empty=True) ext = os.path.splitext(src_path)[1].lower() if ext == ".fbx": bpy.ops.import_scene.fbx( filepath=src_path, use_anim=True, ignore_leaf_bones=True, automatic_bone_orientation=True, ) elif ext == ".obj": bpy.ops.wm.obj_import( filepath=src_path, forward_axis="NEGATIVE_Z", up_axis="Y", ) else: raise SystemExit(f"unsupported input format: {ext}") # Apply centimeter -> meter scale when source tools authored in cm (Maya, Unreal, Mixamo). if scale_factor != 1.0: bpy.ops.object.select_all(action="SELECT") for obj in bpy.context.selected_objects: if obj.parent is None: obj.scale = tuple(s * scale_factor for s in obj.scale) bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) # Normalize skinning weights to 4 bone influences per vertex on any skinned mesh. for obj in bpy.data.objects: if obj.type == "MESH" and obj.vertex_groups: bpy.context.view_layer.objects.active = obj bpy.ops.object.mode_set(mode="WEIGHT_PAINT") bpy.ops.object.vertex_group_limit_total(limit=4) bpy.ops.object.vertex_group_normalize_all(lock_active=False) bpy.ops.object.mode_set(mode="OBJECT") bpy.ops.export_scene.gltf( filepath=dst_path, export_format="GLB", export_yup=True, export_apply=True, export_texcoords=True, export_normals=True, export_tangents=True, export_skins=True, export_all_influences=False, export_animations=True, export_force_sampling=True, export_extras=True, export_draco_mesh_compression_enable=False, ) ``` Run it from the command line: ```sh # Convert an OBJ prop authored in meters blender --background --python tools/convert_to_glb.py -- art/barrel.obj resources/models/barrel.glb # Convert a Maya / Mixamo FBX authored in centimeters (0.01x -> meters) blender --background --python tools/convert_to_glb.py -- art/character.fbx resources/models/character.glb 0.01 ``` ### Handling common source-tool quirks - **Maya / 3ds Max / Unreal FBX (`cm` → `m`)**: Blender's FBX importer respects the FBX `UnitScaleFactor` header when present, but many marketplace exports leave `UnitScaleFactor = 1` while modeling `180` units tall. Always verify bounding-box height in meters after conversion and pass `0.01` when needed. - **Z-up OBJ files** (CAD tools, older 3ds Max exports): pass `up_axis="Z"` to `bpy.ops.wm.obj_import(...)` so Blender rotates the mesh upright before exporting with `export_yup=True`. - **Mixamo multi-clip FBX downloads**: download the character mesh once (`With Skin`), then download additional animations `Without Skin`, import their Armature actions into the same `.blend` file, push each Action to the NLA stack, and export a single `.glb` containing all clips. - **Standalone inspection & optimization**: after exporting, you can inspect node trees, accessor bounds, and texture sizes with `gltf-transform inspect model.glb` or validate strict spec compliance with the Khronos `gltf_validator`. ## Compressed geometry `game/gltf` decodes both common glTF geometry compression extensions in pure Go, with no C++ or Wasm decoder, so compressed files load through the same `gltf.Load` and `gltf.LoadFS` calls as plain ones: | Extension | What it compresses | Typical producer | | --- | --- | --- | | `KHR_draco_mesh_compression` | Whole triangle primitives: connectivity plus quantized attributes | Blender's exporter (*Data → Compression*), `gltf-pipeline -d`, `gltf-transform draco` | | `EXT_meshopt_compression`, `KHR_meshopt_compression` | Individual buffer views: vertex attributes, triangle and index lists, animation keyframes | `gltfpack -c`, `gltf-transform meshopt` | | `KHR_mesh_quantization` | Integer positions, normals and texture coordinates, usually paired with meshopt | `gltfpack`, `gltf-transform quantize` | The decoded data is what the readers return: `Primitive.Positions`, `Indices` and the other attributes, `ReadVec3` and friends, animation channels and skins all see uncompressed values. A buffer tagged as a meshopt fallback is never fetched, so a `.glb` that ships its uncompressed fallback as a separate optional `.bin` loads without that file. Choosing between them: - **Draco** gives the smallest files for dense static meshes, but decoding is slower and it may change the order and number of vertices, so tools that compare against the uncompressed file must match by value, not by index. Quantization is lossy: Blender's default 14-bit positions are enough for props; check close-ups of large meshes. - **meshopt** decodes much faster, keeps vertex order, also compresses animation data, and suits skinned characters and scenes with many small meshes. Its filters (octahedral, quaternion, exponential, color) are lossy; plain attribute, triangle and index streams are lossless. Both decoders charge their output and working memory to the same per-load budget as uncompressed data before allocating it, so a small stream that declares huge counts or many wide attributes fails fast, and malformed streams return an error instead of panicking. An `EXT_meshopt_compression` file may use only what that extension defines: version 0 of the attribute codec and no `COLOR` filter. Other required extensions, such as `KHR_texture_basisu`, are still refused at load time. ## Texture transforms and material variants `game/gltf` supports both `KHR_texture_transform` and `KHR_materials_variants` (whether listed in `extensionsUsed` or `extensionsRequired`): - **`KHR_texture_transform`**: parsed on every PBR and material-extension texture slot (`BaseColorTexture`, `MetallicRoughnessTexture`, `NormalTexture`, `OcclusionTexture`, `EmissiveTexture`, `Clearcoat.Texture`, `Clearcoat.RoughnessTexture`, `Clearcoat.NormalTexture`, `Transmission.Texture`) into `TextureRef.Transform` (`*TextureTransform`). - Defaults match the Khronos specification (`offset: [0, 0]`, `rotation: 0`, `scale: [1, 1]`), and transforms apply in exact `T * R * S` order in glTF UV space (`+U` right, `+V` down, positive rotation counter-clockwise) via `TextureTransform.Apply`, `TextureTransform.ApplyUV`, `TextureTransform.Matrix`, or `TextureRef.ApplyUV`. - When `KHR_texture_transform.texCoord` is present, `TextureRef.EffectiveTexCoord()` returns the overridden UV set instead of `TextureRef.TexCoord`. - `Document.PrimitiveTexCoords(prim, set)` returns `TEXCOORD_0`/`TEXCOORD_1` directly and decodes higher sets (`TEXCOORD_2`, …) on demand; `Document.TransformTexCoords(prim, ref, out)` evaluates the final transformed UVs for a primitive and texture slot into a reusable slice. - Malformed transforms (non-object payloads, `offset` or `scale` arrays with length other than 2, non-finite numbers, or negative/non-integer `texCoord`) are rejected at load time with `*loaderr.Error` locations. - **`KHR_materials_variants`**: top-level variant names load into `Document.Variants` (`[]MaterialVariant`), and per-primitive mappings load into `Primitive.VariantMappings` (`map[int]int`). - Look up variants by name with `Document.VariantIndex(name)` and resolve materials without mutating `Primitive.Material` via `Document.MaterialForPrimitive(prim, variantIndex)`, `Document.MaterialForVariant(prim, name)`, `Document.MeshMaterials(meshIndex, variantIndex)`, and `Document.ResolveVariantMaterials(variantIndex)`. Any unmapped primitive or out-of-range/negative variant falls back to `Primitive.Material`. - Spec constraints are enforced at load time: non-empty `variants` and `mappings` arrays, required variant `name`, valid material and variant indices, and at most one mapping per variant on any primitive. ## Material extensions `game/gltf` accepts four material extensions in `extensionsUsed` and `extensionsRequired`: - **`KHR_materials_unlit`**: sets `Material.Unlit`. - **`KHR_materials_emissive_strength`**: `Material.EmissiveStrength()` returns the multiplier for `EmissiveFactor`, 1 when the extension or its `emissiveStrength` is omitted, and an error when the payload is not an object or the value is not a finite number >= 0. - **`KHR_materials_clearcoat`**: populates `Material.Clearcoat` (`*Clearcoat`) with `Factor`, `RoughnessFactor`, `Texture`, `RoughnessTexture`, and `NormalTexture` (including `Scale`, `TexCoord`, and `KHR_texture_transform`), rejecting out-of-range factors or invalid texture references at load time. - **`KHR_materials_transmission`**: populates `Material.Transmission` (`*Transmission`) with `Factor` and `Texture` (including `TexCoord` and `KHR_texture_transform`), rejecting out-of-range factors or invalid texture references at load time. ## Baked lightmaps Bake lighting in Blender (or another baker) into a second UV map, export it as `TEXCOORD_1`, and point the material at the baked texture with `MOZ_lightmap` (what the Hubs Blender add-on writes), `EXT_lightmap`, or an `extras.lightmap` object. Both extensions are accepted in `extensionsUsed` and `extensionsRequired`. - `Document.MaterialLightmap(materialIndex)` returns a `*LightmapRef` (nil when the material has no lightmap) with the texture, `Intensity`, the `Encoding` hint (`linear`, `srgb`, `rgbm`, `rgbd`), `RGBMMaxRange`, and the atlas `UVScale` / `UVOffset`. - `UVScale` / `UVOffset` are the authoritative atlas transform. They come from, in increasing precedence, the lightmap's `KHR_texture_transform` scale and offset, a `scaleOffset` `[sx, sy, ox, oy]` field, and separate `uvScale` / `uvOffset` fields. A rotated lightmap transform is refused. The transform is not left in `LightmapRef.Texture.Transform` (which keeps only a `texCoord` override), so `TransformTexCoords` on it never applies the atlas transform twice. - `Document.LightmapTexCoords(prim, ref)` returns the lightmap UV set, falling back to `TEXCOORD_0` when `TEXCOORD_1` is missing, and fails when the primitive has neither. [render3d](https://game.nsgo.dev/docs/render3d/#baked-lightmaps-lightmapmesh-lightmaprenderer) shows how to draw the result. ## Morph targets `game/gltf` decodes glTF 2.0 morph targets (`POSITION`, `NORMAL`, and `TANGENT` displacement deltas, including sparse accessors), default `mesh.weights` and `node.weights`, and animated `weights` channels (`STEP`, `LINEAR`, and `CUBICSPLINE`). In Blender, author morph targets as **Shape Keys** on the mesh, keyframe their *Value* sliders in an Action, and enable *Data → Shape Keys* (plus *Shape Key Normals* and *Shape Key Tangents* when needed) in the glTF 2.0 exporter. At runtime, evaluate morph targets without per-frame heap allocations by reusing weight and `MorphResult` buffers: ```go weights := gltf.ResolveWeights(doc, nodeIdx) // node.Weights > mesh.Weights > zeros var morphed gltf.MorphResult // Each frame: if sampled, ok := gltf.SampleMorphWeights(doc.Animations[0], nodeIdx, animTime, weights); ok { weights = sampled } gltf.ApplyMorphWeights(prim, weights, &morphed) // morphed.Positions, morphed.Normals (renormalized), morphed.Tangents (XYZ renormalized, W preserved), morphed.Bounds ``` - `ResolveWeights` and `ResolveWeightsInto` apply glTF 2.0 weight precedence (`node.Weights` overrides `mesh.Weights`; missing weights default to zeros matching the primitive's morph target count). - `SampleMorphWeights` unpacks `N` target weights per keyframe (`3 * N` floats per keyframe in `[inTangent, value, outTangent]` order for `CUBICSPLINE`), clamping outside the channel's keyframe time range. - `EvaluateMorphTangents` blends tangent `XYZ` displacements, renormalizes `XYZ`, and preserves `W` handedness unchanged, complementing `EvaluateMorphPositions` and `EvaluateMorphNormals`. - To draw an animated morph mesh in an NSGo `gpu.View`, upload the base primitive and targets into `render3d.GPUMorphMesh` (see [`render3d`](https://game.nsgo.dev/docs/render3d/#morph-target-meshes-morphmesh-gpumorphmesh)). The test suite verifies full animation playback and pixel readback against the Khronos `AnimatedMorphCube` sample model. ## Collision nodes (`-colonly` and `extras.collider`) Author level colliders directly alongside visual geometry in Blender using Godot-style node name suffixes or Custom Properties (`extras.collider`), and keep collider-only nodes out of visual draws: | Name suffix | Collider shape | Drawn visually? | | --- | --- | --- | | `-col` / `-colonly` | Triangle mesh (`ColliderTriMesh`) | Yes / No | | `-boxcol` / `-boxcolonly` | Oriented box (`ColliderBox`) | Yes / No | | `-spherecol` / `-spherecolonly` | Sphere (`ColliderSphere`) | Yes / No | | `-capsulecol` / `-capsulecolonly` | Capsule (`ColliderCapsule`) | Yes / No | | `-convcol` / `-convcolonly` | Convex (`ColliderConvex`, currently built as trimesh) | Yes / No | Suffix matching is case-insensitive and strips Blender's trailing duplicate numbers (such as `Wall-colonly.001`). Nodes can also declare `extras.collider` (as a shape string, `true`/`false`, or an object with `shape`/`type`, `draw`/`only`/`visible`, `trigger`, `tag`, `center`, `halfExtents`/`size`, `radius`, `height`, `friction`, `restitution`, `layer`, and `mask`) — including on meshless Empty nodes. - **Filter visual draws**: call `doc.DrawableNodes()` (or `doc.SceneDrawableNodes(sceneIdx)` / `node.IsDrawable()`) so `-colonly` and `draw: false` nodes are excluded from rendering. - **Inspect or build physics colliders**: call `doc.ColliderNodes()` / `gltf.ParseNodeCollider(node)` for raw metadata, or pass `doc` directly to [`physics3d.World.AddGLTFColliders`](https://game.nsgo.dev/docs/physics3d/#gltf-gridmap-and-heightmap-colliders). ## Round-trip sample models The [placeholder pack](https://game.nsgo.dev/docs/placeholder/) holds three minimal, deterministic glTF 2.0 sample models under [`pkg/placeholder/pack/models/`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/), generated and round-trip verified in Go by [`internal/samplegltf/`](https://github.com/nsgo-dev/game/blob/main/internal/samplegltf/samplegltf.go). Like the rest of the pack they are dedicated to the public domain under CC0 1.0, and `placeholder.Model` loads them. ### 1. Static binary crate (`crate.glb`) File: [`models/crate.glb`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/crate.glb) (1,920 bytes, GLB 2.0) - **Geometry**: `1 m × 1 m × 1 m` cube with pivot at bottom center (`X ∈ [-0.5, 0.5]`, `Y ∈ [0, 1]`, `Z ∈ [-0.5, 0.5]`), right-handed `+Y` up, `-Z` forward. - **Mesh data**: 24 vertices (4 per face for crisp hard normals), 12 triangles (36 `UNSIGNED_SHORT` indices), strict CCW outward winding, `POSITION` (with exact `min`/`max`), unit `NORMAL`, and per-face `TEXCOORD_0`. - **Material**: `CrateMaterial` using `pbrMetallicRoughness` (`baseColorFactor: [0.72, 0.52, 0.32, 1]`, `metallicFactor: 0.05`, `roughnessFactor: 0.78`, `doubleSided: false`). - **Container layout**: 12-byte GLB header (`glTF` magic `0x46546C67`, version `2`, 4-byte-aligned total length), space-padded `JSON` chunk (`0x4E4F534A`), and zero-padded `BIN` chunk (`0x004E4942`). ### 2. Skinned & animated 2-bone arm (`robot_arm.gltf`) File: [`models/robot_arm.gltf`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/robot_arm.gltf) (embedded base64 buffer, human-readable JSON) - **Hierarchy**: ```text ArmRoot (node 0) ├─ ArmMesh (node 1: mesh 0, skin 0) └─ UpperArm (node 2: skeleton root at 0, 0, 0) └─ Forearm (node 3: translation 0, 0.5, 0) ``` - **Geometry & skinning**: `0.25 m × 1.0 m × 0.25 m` segmented arm (`X ∈ [-0.125, 0.125]`, `Y ∈ [0, 1]`, `Z ∈ [-0.125, 0.125]`), 32 vertices, 20 triangles (60 indices). The shared elbow ring at `y = 0.5` blends smoothly across both joints (`JOINTS_0 = [0, 1, 0, 0]`, `WEIGHTS_0 = [0.5, 0.5, 0, 0]`), while base and tip rings bind `1.0` to `UpperArm` and `Forearm` respectively. - **Skin (`ArmSkin`)**: `joints: [2, 3]`, `skeleton: 2`, and `inverseBindMatrices` containing identity `I` for `UpperArm` and translation `T(0, -0.5, 0)` for `Forearm`, satisfying `worldBind × IBM = I`. - **Animation (`Wave`)**: 1.0-second clip (`times = [0, 0.5, 1]`) with two `LINEAR` quaternion rotation channels (`UpperArm` +15° Z, `Forearm` +60° Z) and three `extras.events` markers (`wave_start` at `0.0 s`, `wave_apex` at `0.5 s`, `wave_end` at `1.0 s`). ### 3. Flat-shaded gem (`gem.glb`) File: [`models/gem.glb`](https://github.com/nsgo-dev/game/blob/main/pkg/placeholder/pack/models/gem.glb) (1,924 bytes, GLB 2.0) - **Geometry**: a hexagonal bipyramid `0.8 m` across and `1 m` tall with its pivot at its bottom point (`Y ∈ [0, 1]`), its girdle at `y = 0.6`, right-handed `+Y` up. - **Mesh data**: 36 vertices and 12 triangles, three vertices per face so each face has its own unit `NORMAL`, with CCW outward winding. - **Material**: `GemMaterial` using `pbrMetallicRoughness` (`baseColorFactor: [0.13, 0.77, 0.45, 1]`, `metallicFactor: 0`, `roughnessFactor: 0.2`). - **Reproducibility**: the generator uses only exactly rounded arithmetic, so it writes the same bytes on every architecture. ### Running the round-trip verifier The Go test suite in [`internal/samplegltf/samplegltf_test.go`](https://github.com/nsgo-dev/game/blob/main/internal/samplegltf/samplegltf_test.go) unpacks the committed models and verifies: - GLB magic, version `2`, 4-byte alignment, JSON/BIN chunk bounds, and zero-byte BIN padding - Embedded data URI base64 decoding and exact buffer byte lengths - Accessor alignment, `POSITION` `min`/`max` bounds, unit normals, and CCW outward triangle winding on every triangle - 4-bone `JOINTS_0`/`WEIGHTS_0` bounds and per-vertex weight sums equal to `1.0` - Exact `worldBind × inverseBindMatrix == Identity` for every joint in `skins` - Strictly increasing animation timestamps, unit rotation quaternions, and in-range `extras.events` - Byte-for-byte reproducibility against the deterministic Go generator Run the tests from the repository root: ```sh go tool nsgo test ./internal/samplegltf ``` If you edit the generator, regenerate the committed models and re-verify in one command: ```sh go test ./internal/samplegltf -update ``` ## Troubleshooting | Symptom | Likely cause | Fix | | --- | --- | --- | | Model is 100× too large or tiny | Source authored in centimeters or unapplied Object Scale | Set Blender units to Metric (`1.0`), apply `Ctrl+A → Scale`, or convert FBX with `0.01` scale | | Model lies on its back or faces away from the camera | `+Y Up` disabled on export, or model built facing `+Y` instead of `-Y` | Rotate model so front faces `-Y` in Blender, apply `Ctrl+A → Rotation`, and enable **`+Y Up`** | | Inside-out or missing faces | Inverted normals or negative scale (`-1`) flipped triangle winding | Apply `Ctrl+A → Scale`, check *Face Orientation* overlay, and run `Shift+N` (*Recalculate Outside*) | | Skinned mesh explodes or stretches weirdly | Unapplied Armature/Mesh scale, >4 bone weights, or unnormalized weights | Apply scale to mesh and armature, run `Limit Total (4)` + `Normalize All`, uncheck `Include All Bone Influences` | | Only one animation exports (or none) | Actions are not pushed to NLA tracks, or IK constraints are unbaked | Push every Action to an NLA strip, set *Animation Mode* to `Actions`, and check `Always Sample Animations` | | Material looks flat white, black, or loses textures | Blender-only procedural nodes or unpacked external image paths | Bake procedural nodes into PBR maps wired to `Principled BSDF` and export as `.glb` | | Character snaps back to origin when a walk cycle loops | Root motion baked into a clip meant to loop in place | Zero horizontal translation on `Root`/`Hips` for in-place loops, or consume root deltas in gameplay code | | `extras.events` missing from exported glTF | Custom properties omitted or stored on the Object instead of the Action | Write `action["events"]` on each Blender Action and enable `Include → Custom Properties` on export | | `gltf.Load` refuses the file | The exporter wrote data the spec forbids: an index past the vertex count, attributes or morph targets with different counts, NaN/Inf vertex data, a `JOINTS_0` value past the skin's joint list, unordered sparse indices, a second GLB JSON chunk, or an `asset.minVersion` above 2.0 | Fix the source mesh (or re-export) and check it with the Khronos `gltf_validator`; the error names the mesh, primitive and element | | A node's `Translation`/`Rotation`/`Scale` do not match its `LocalMatrix` | The node's authored `matrix` has shear, which TRS cannot express; `Node.MatrixNotTRS` is set | Use `LocalMatrix`, or apply the transform in Blender so the node exports as plain TRS | --- Source: https://game.nsgo.dev/docs/shipping/ # Building and Shipping Verify your game across every target with `nsgo check`, configure metadata, icons and signing in `nsgo.yaml`, and build release packages for macOS, Windows, Linux, the web, iOS and Android with `nsgo build`. ## Configure nsgo.yaml `nsgo build` reads app identity, icons, signing and target defaults from `nsgo.yaml` at your project root. Every flag on `nsgo build` (`-name`, `-id`, `-version`, `-build-number`, `-output`, `-target`, `-channel`) overrides the matching setting in `nsgo.yaml` for one build. ```yaml name: My Game id: com.example.mygame version: 1.0.0 build_number: 1 copyright: "© 2026 Example Studio" icon: apple: assets/AppIcon.icon # Icon Composer .icon (macOS/iOS) or .icns (macOS) png: assets/Icon.png # square PNG (1024x1024 recommended) build: output: dist installers: true targets: - macos_arm64 - macos_x64 - windows_x64 - windows_arm64 - linux_x64 - linux_arm64 - web - ios - android_arm64 ``` - **`id`**: reverse-DNS bundle identifier / application ID (for example `com.example.mygame`). Keep it stable across releases; Apple App Store, Google Play and Microsoft Store key your app on it. - **`version`**: user-facing semantic version (`CFBundleShortVersionString`, Android `versionName`). - **`build_number`**: monotonically increasing integer for every store upload (`CFBundleVersion` on Apple platforms, `versionCode` on Android). When omitted, it derives from `version`. - **`resources/` vs `assets/`**: game files loaded at runtime (`"asset:..."`) live in `resources/` and ship inside every package; build-time inputs such as icons live in `assets/` and are compiled into platform icon formats. Use `mobile.exclude_resources` in `nsgo.yaml` to omit desktop-only files from iOS and Android packages. ## App icons Place default icons in `assets/` and `nsgo build` picks them up automatically without extra configuration: - `assets/AppIcon.icon` (Apple Icon Composer) or `assets/AppIcon.icns` (macOS only) for macOS and iOS. - `assets/Icon.png` (a square PNG, 1024×1024 recommended) for Windows, Linux, Android, the web, and any Apple target without `icon.apple`. To distinguish development builds from releases, add `-dev` variants (`assets/AppIcon-dev.icon`, `assets/Icon-dev.png`) or set `dev.icon`; `nsgo dev` uses them automatically. For desktop installers, you can also set `macos.dmg_icon`, `macos.dmg_background` (PNG with optional `@2x` twin), `windows.installer_icon` and `windows.uninstaller_icon` in `nsgo.yaml`. ## Verify all targets before building Check your host machine's toolchains first: ```sh go tool nsgo doctor ``` Run `nsgo check` to vet your Go code (and any catalogs) across every target before building release packages: ```sh go tool nsgo check -target all ``` Or check the 6 game platforms explicitly: ```sh go tool nsgo check -target macos,windows,linux,web,ios,android ``` - Pass `-jobs N` to vet up to `N` targets in parallel. - A bare OS name (`macos`, `windows`, `linux`) expands to both its `arm64` and `x64` architectures; `android` expands to `android_arm64` (`android_x64` requires an Android NDK). - On Linux or Windows hosts, `-target all` skips Apple targets that require macOS and Xcode; naming `ios` explicitly fails if Xcode is absent. Run headless tests with `go tool nsgo test`, or run tests on a real platform with `go tool nsgo test -target macos|windows|linux|web|ios_simulator|android`. ## Build release packages `nsgo build` compiles stripped release binaries and writes one directory per target under `/--`, plus distributable release files. ```sh # Build every target configured in nsgo.yaml go tool nsgo build # Build all targets Go and Xcode can build on this machine go tool nsgo build -target all # Build store-formatted packages instead of direct installers go tool nsgo build -channel store -target macos,windows,linux,ios,android ``` `-channel` chooses how packages are formatted and updated: - **`direct`** (default): direct-download installers and archives (`.dmg`, NSIS `.exe`, `.deb`/Arch/`.AppImage`, `.apk`, `.ipa`, web `.zip`). - **`store`**: store submission packages (Mac App Store `.pkg`, Microsoft Store `.msix`, Flathub `.tar.gz` + Flatpak manifest, Google Play `.aab`, iOS `.ipa`). - **`none`**: skips auto-update feeds while keeping direct packaging. Pass `-installers=false` if you only want the raw unpacked app directories on desktop targets. Pass `-run` to launch a built package immediately on this machine, a connected device, or a local web server. ## Credit your assets Most licenses an asset comes under, Creative Commons Attribution and the SIL Open Font License among them, ask for its author and license to be shipped with the game. Record them in the `credit` section of the import settings sidecar beside each asset (`hero.png.import.yaml`); `nsgo game release`, which runs `nsgo build` for every platform, then writes `CREDITS.md` beside the packages, for the store or download page, and refuses to build while an asset in `game.yaml`'s `assets` section has no credit. `nsgo game credits` checks the credits and prints the file without building; `nsgo game credits -out resources/CREDITS.md` before the release puts it in every package too, since `nsgo build` copies the `resources` folder into each one ([Command Line](https://game.nsgo.dev/docs/cli/#credits)). Assets the game loads from outside the `assets` section are not listed, so credit those yourself. ## Targets | Platform | Target names | Direct build (`-channel direct`) | Store build (`-channel store`) | Host requirements | | --- | --- | --- | --- | --- | | macOS | `macos_arm64`, `macos_x64` (`macos`) | `.app` + `.dmg` | Sandboxed `.pkg` | macOS for signing/notarization | | Windows | `windows_x64`, `windows_arm64` (`windows`) | `.exe` bundle + NSIS installer | `.msix` | Any host (Go cross-compiles) | | Linux | `linux_x64`, `linux_arm64` (`linux`) | Binary bundle + `.deb`, Arch pkg, `.AppImage` | `.tar.gz` + AppStream + Flatpak manifest | Any host (Go cross-compiles) | | Web | `web` | Static WebAssembly site + `.zip` | Same static site | Any host | | iOS | `ios`, `ios_simulator` | `.ipa` | `.ipa` | macOS + Xcode | | Android | `android_arm64` (`android`), `android_x64` | `.apk` | `.aab` | Any host (`android_x64` needs NDK) | Consoles (Nintendo Switch, PlayStation and Xbox) are not targets: their SDKs are under NDA and need C toolchains, and NSGo is Go only. ### macOS Build Apple Silicon, Intel, or both: ```sh go tool nsgo build -target macos ``` - **Code signing**: without an identity, macOS apps are signed ad hoc (fine for local testing, rejected by Gatekeeper when downloaded). For direct distribution, pass a Developer ID Application certificate via `sign.identity` or `-sign`: ```sh go tool nsgo build -target macos -sign "Developer ID Application: Example Studio (TEAMID)" ``` - **Notarization**: to open on other Macs without Gatekeeper warnings, configure a keychain profile (`xcrun notarytool store-credentials`) in `sign.notarize` or pass `-notarize `. In CI, set the App Store Connect API key environment variables `NSGO_NOTARY_KEY` (path to `.p8`), `NSGO_NOTARY_KEY_ID` and `NSGO_NOTARY_ISSUER`. `nsgo build` submits the `.dmg` (or zipped `.app`), waits for approval, and staples the ticket to both the `.app` and `.dmg`. - **Mac App Store**: set `macos.category` (for example `public.app-category.games`), `sign.macos_profile` (Mac App Store provisioning profile) and optionally `sign.installer` (Mac Installer Distribution identity), then build with `-channel store`: ```sh go tool nsgo build -channel store -target macos ``` `nsgo build` signs the app in the App Sandbox and packages a `.pkg` installer ready to upload via Transporter. ### Windows Build x64, ARM64, or both: ```sh go tool nsgo build -target windows ``` - **Direct distribution**: produces the application directory and an NSIS setup installer (`-installers=true`, default). Set `windows.publisher` and `copyright` in `nsgo.yaml` to populate executable metadata and uninstall entries. - **Code signing**: sign executables and the installer to prevent SmartScreen warnings. Pass a PKCS#12 `.pfx` certificate with `-certificate` (or `sign.certificate`) and provide its password in `NSGO_CERTIFICATE_PASSWORD`, plus an RFC 3161 timestamp server (`-timestamp-url` / `sign.timestamp_url`, defaults to `http://timestamp.digicert.com`): ```sh NSGO_CERTIFICATE_PASSWORD="$PFX_PASSWORD" \ go tool nsgo build -target windows -certificate certs/win.pfx ``` For hardware tokens or cloud signing services, use `-sign-command` (or `sign.sign_command`) where `%1` stands for each file path. - **Microsoft Store**: set `windows.store.identity`, `windows.store.publisher` (`CN=...`) and `windows.store.publisher_name` from Partner Center, then build with `-channel store` to produce an `.msix` package (left unsigned so the Store signs it on publication): ```sh go tool nsgo build -channel store -target windows ``` ### Linux Build x64, ARM64, or both: ```sh go tool nsgo build -target linux ``` - **Direct distribution**: builds `.deb` (Debian/Ubuntu), Arch packages and `.AppImage` bundles. Configure desktop metadata in `nsgo.yaml`: ```yaml linux: categories: [Game] maintainer: "Example Studio " summary: "A 2D adventure game" license: MIT ``` Add extra runtime dependencies with `linux.depends` and `linux.recommends` if your game ships helper binaries. - **Flathub / Flatpak**: build with `-channel store` to emit `.tar.gz` archives containing `.metainfo.xml` AppStream metadata and a `flatpak/.yml` manifest targeting the GNOME runtime (`linux.flatpak_runtime` overrides the default runtime version). Submit the manifest to Flathub or build locally with `flatpak-builder`. ### The web Build the static WebAssembly bundle: ```sh go tool nsgo build -target web ``` Test the production build locally before deploying: ```sh go tool nsgo build -target web -run ``` `dist/--web/` contains the HTML, JS, WebAssembly binary and `resources/` files, and `nsgo build` also writes a `.zip` archive in the releases directory. Upload the directory contents to any static host (GitHub Pages, Cloudflare Pages, Netlify, itch.io, or S3). Remember that browsers gate audio behind the first user gesture (see [sound](https://game.nsgo.dev/docs/sound/)). ### iOS Requires macOS with Xcode installed. Build for physical devices (`.ipa`) or the simulator: ```sh go tool nsgo build -target ios go tool nsgo build -target ios_simulator ``` - **Signing**: provide an App Store, Ad Hoc or Development provisioning profile matching `id` via `sign.profile` (or `-profile`). `nsgo build` automatically selects the matching signing identity from your keychain, or you can specify it explicitly with `sign.identity` (or `-sign`). - **Store submission**: - Upload `.ipa` to App Store Connect / TestFlight with Apple's Transporter app or Xcode. - Increment `build_number` (`CFBundleVersion`) for every upload. - Configure iPad multitasking and screen orientations with `apple.requires_full_screen` and `apple.orientations` (`portrait`, `portrait_upside_down`, `landscape_left`, `landscape_right`), and add any required `Info.plist` entries under `apple.info`. `apple.orientations` declares the orientations a full-screen iPad allows, while the runtime request from `cx.RequestOrientation` applies on both the iPhone and the iPad (see [Orientation on phones](https://game.nsgo.dev/docs/screen/#orientation-on-phones)). On an iPad, UIKit allows only the orientations both lists share, so list every orientation the game requests, such as `landscape_left` and `landscape_right` for a landscape game; a request with nothing in common with `apple.orientations` leaves the iPad no valid orientation. ### Android Build ARM64 (needs only Go — `CGO_ENABLED=0`, no Android SDK or NDK required): ```sh go tool nsgo build -target android_arm64 ``` To also build `android_x64` (for x86_64 emulators or Chromebooks), install an Android NDK and pass `-target android_arm64,android_x64`. - **Signing**: configure a PKCS#12 or JKS keystore via `sign.keystore` (or `-keystore`) and `sign.key_alias` (or `-key-alias`). Never commit passwords to `nsgo.yaml`; pass them via environment variables: ```sh NSGO_KEYSTORE_PASSWORD="$STORE_PW" NSGO_KEY_PASSWORD="$KEY_PW" \ go tool nsgo build -channel store -target android_arm64 \ -keystore certs/upload.p12 -key-alias upload ``` Without a keystore, `nsgo build` signs APKs with the project's debug key (for sideloading only, rejected by Google Play). - **Google Play**: build with `-channel store` to produce a signed `.aab` (Android App Bundle) for Google Play Console. Increment `build_number` (`versionCode`) on every upload, set `android.target_sdk` to Google Play's current required API level (`minSdkVersion` is 28), and declare any extra permissions under `android.permissions`. - **Orientation**: the manifest does not fix an orientation; the game requests the one it plays in at runtime with `cx.RequestOrientation` (see [Orientation on phones](https://game.nsgo.dev/docs/screen/#orientation-on-phones)). --- Source: https://game.nsgo.dev/docs/cli/ # Command Line `game` is the game layer's command-line tool: one command whose subcommands pack sprite atlases, convert audio, generate asset manifests, encode textures, open the scene editor, build release packages, play input recordings headless, check benchmarks against a stored baseline, create projects, run the game with asset hot reload, check a game's scenes, maps and atlases, build all of a game's assets from `game.yaml`, rebuilding only what changed, write new components, systems, scenes and prefabs into a project, move files while keeping the references to them working, keep the project index of stable file IDs, render pixelfx effects to sprite sheets and write shell completion scripts. They share how they are called: flags before arguments, `-in` for what a command reads and `-out` for what it writes, and the same help. ## Install Run the command as `nsgo game` through NSGo's extension mechanism (since NSGo v0.3.3). Install `nsgo` once, with Homebrew (`brew install nsgo-dev/tap/nsgo`), with the install script on macOS and Linux (`curl -fsSL https://nsgo.dev/install.sh | sh`) or with Go on any system (`go install github.com/nsgo-dev/nsgo/cmd/nsgo@latest`), as [NSGo's setup](https://nsgo.dev/docs/getting-started/#install-nsgo) describes. In a project whose `go.mod` declares the `game` tool, `nsgo game` automatically runs that module's pinned tool (`go tool github.com/nsgo-dev/game/cmd/game`): ```sh go get -tool github.com/nsgo-dev/game/cmd/game nsgo game help ``` The `tool` line in `go.mod` pins the command to the module's version of the game layer, so everyone working on the game runs the same one. A project created with [`game new`](https://game.nsgo.dev/docs/cli/#new) has it already. An `nsgo` of another version than the one the project's `go.mod` pins runs the project's own instead, so the project's `nsgo` tool needs v0.3.3 or later too; every template's `go.mod` and the game layer itself require v0.3.4, the first release whose software renderer and surface depth buffer draw 3D scenes right. Outside a project, such as before creating one with `nsgo game new`, install the `nsgo-game` extension binary once on `PATH` so `nsgo game` finds it: ```sh go install github.com/nsgo-dev/game/cmd/nsgo-game@latest nsgo game new mygame ``` Or run `go run github.com/nsgo-dev/game/cmd/game@latest` directly anywhere with nothing to install. Inside a project, `go tool game` also runs the same command without an installed `nsgo`. ## Commands | Command | What it does | | --- | --- | | `pack` | Packs a folder of PNG images into sprite atlas pages and TexturePacker JSON-hash metadata for `sprite.LoadAtlas` | | `audio` | Normalizes, resamples and converts a WAV file to WAV, AAC or MP3 | | `manifest` | Generates a typed Go asset manifest from a directory of assets, so a missing asset fails the build | | `tex` | Encodes a PNG or JPEG texture into a KTX2 container as BC1, BC3, ETC2 or RGBA8, with optional mipmaps | | `editor` | Opens the scene editor on a project or a YAML scene, or on the start screen when none is named | | `mcp` | Serves the editor's MCP tools to an agent on standard input and output, forwarding each call to the editor that has the project open | | `release` | Builds the game's release packages for macOS, Windows, Linux, web, iOS and Android, or for `game.yaml`'s export presets, in one run of `nsgo build`, with a credits file of its assets' licenses | | `replay` | Checks the input recordings under the directories and plays them headless through their replay tests, failing on a mismatch | | `bench` | Runs the benchmarks headless and fails when one regresses past its stored baseline, or updates the baseline | | `new` | Creates a game project in a directory from a template, with its `go.mod` requiring the game layer and the `game` and `nsgo` tools | | `dev` | Runs the game with `nsgo dev`, reloading its assets in the running game when they are saved | | `check` | Checks the scenes, Tiled and LDtk maps and sprite atlases under a directory, and the files they refer to, reporting each problem with its file and line | | `assets` | Packs atlases, encodes textures, converts audio, bakes fonts, packs models and generates the manifest from `game.yaml`, rebuilding only what changed | | `generate` | Writes a new component, system, scene or prefab into a game project: its Go code and a test, the scene file of a scene or prefab, and its registration | | `mv` | Moves or renames a file or directory of a project and rewrites every reference to it, keeping the project index up to date | | `index` | Gives every scene and resource file a uid, points references at files moved without the tools, and writes the project index | | `library` | Finds asset, editor plugin and template packs in a library and installs them into a project, updates or removes them, or prints a pack's digest | | `credits` | Writes the credits file `release` ships: every asset's author and license, from the import settings sidecar beside it, failing when an asset has none | | `pixelfx` | Renders a pixelfx effect, or the effect acted out, to a PNG sprite sheet and Aseprite JSON for `sprite.LoadAtlas` | | `navmesh` | Bakes a scene's glTF level geometry into a navigation mesh for each agent type `game.yaml` declares, written to the file the scene's `navMesh` names | | `merge` | Merges scene YAML files object by object for Git, or sets up the `nsgo-scene` Git merge driver in a project | | `completion` | Writes a completion script for zsh, bash or fish | | `help` | Lists the commands, or shows one command's flags | `nsgo game help` lists the commands, and `nsgo game help ` or `nsgo game -h` shows a command's usage line, what it does and its flags. [Command Reference](https://game.nsgo.dev/docs/cli-reference/) lists every command's flags and their defaults on one page, generated from the commands' definitions. A command exits with 0 when it succeeds or shows help, 1 when it fails (a file it cannot read, an encoder it cannot find, a manifest or asset that is out of date, a build that fails, a replay whose end state does not match, a benchmark that regressed, a broken reference `check` found, a file `generate` would overwrite, an asset without a credit) and 2 when it is called wrongly (an unknown flag, a missing required flag, flags that conflict, an argument it does not take), in which case it also prints its usage. Its errors start with its name, such as `game pack: -in directory is required`, except an unknown or malformed flag, which Go's flag package reports in its own words, such as `flag provided but not defined: -nope`. An unknown command also exits with 2, and points to `game help` instead of printing a usage. ### pack ```sh nsgo game pack -in art/ui -out assets -name ui -padding 2 ``` Writes `ui.png` and `ui.json` to `-out` (`ui-0.png`, `ui-0.json`, `ui-1.png` and so on when the frames need more than one page) and prints each path. `-padding` and `-extrude` set the transparent gap and the repeated edge pixels around each frame, `-max-width` and `-max-height` bound a page, `-scale` is written to `meta.scale`, and transparent borders are trimmed, each frame keeping its offset in its untrimmed size, unless `-trim=false`. When an [import settings sidecar](https://game.nsgo.dev/docs/cli/#import-settings-beside-each-asset) sits beside a PNG in `-in`, its `image.slice` and `image.pivot` settings apply as they do in `assets`, slicing sprite sheets into grid frames and writing each frame's normalized TexturePacker `pivot` into the atlas JSON for `sprite.LoadAtlas`. ### audio ```sh nsgo game audio -in sfx/jump.wav -out assets/jump.wav -rate 22050 -channels 1 -peak-db -1 nsgo game audio -in music/theme.wav -out assets/theme.m4a -format aac -rms-db -14 -bitrate 192 ``` Reads a WAV file, resamples it to `-rate`, mixes it to `-channels`, and normalizes either its peak (`-peak-db`) or its loudness (`-rms-db`, with soft clipping), not both. Passing both is a usage error. WAV output is written in Go; MP3 needs `ffmpeg` on `PATH`, and AAC uses `ffmpeg`, or `afconvert` on macOS when `ffmpeg` is missing; otherwise the command fails with an error naming the missing encoder. When an [import settings sidecar](https://game.nsgo.dev/docs/cli/#import-settings-beside-each-asset) sits beside the input, such as `sfx/jump.wav.import.yaml`, its `audio` settings apply as they do in `assets`, loop points included, and a flag given on the command line wins over the sidecar's setting of the same name: `-peak-db` or `-rms-db` replaces the sidecar's level, whichever kind it is. A loop needs `wav` output, and a sidecar holding settings for another kind of asset is refused. ### manifest ```sh nsgo game manifest -in assets -out assets/manifest_gen.go -pkg assets nsgo game manifest -in assets -out assets/manifest_gen.go -pkg assets -check ``` Writes a Go file declaring a typed reference for every asset under `-in`, skipping files and folders whose names start with a dot, Go files and import settings sidecars (`*.import.yaml`), or prints it when `-out` is empty. `-embed` emits `//go:embed` directives instead of `asset:` URIs, with `-embed-dir` prefixed to their patterns. `-check` leaves `-out` alone and fails when it differs from what would be generated, for CI; a `go:generate` line running the first form keeps the file current. The generated file's header names the command that wrote it (`// Code generated by game manifest. DO NOT EDIT.`), so a manifest generated by the earlier `gamemanifest` command must be regenerated once before `-check` passes. ### tex ```sh nsgo game tex -format bc1 -mipmaps -srgb -out assets/albedo.ktx2 art/albedo.png ``` Encodes the image named by the argument (or `-in`) into a KTX2 file at `-out` (`-o` for short), by default the input's path with a `.ktx2` extension. `-format` is `bc1`, `bc3`, `etc2` or `rgba8`, `-mipmaps` writes the whole chain down to 1x1, and `-srgb` marks the texture sRGB and filters its mipmaps in linear light. When an [import settings sidecar](https://game.nsgo.dev/docs/cli/#import-settings-beside-each-asset) sits beside the input, such as `art/albedo.png.import.yaml`, its `image` settings apply as they do for a texture target of `assets`: `format`, `mipmaps` and `srgb`, under the flags given, which win, and `filter`, which is written into the KTX2 file as `game.filter`. `slice` and `pivot` are atlas settings and are not read, since a texture holds the whole image, and a sidecar holding settings for another kind of asset is refused. ### editor ```sh nsgo game editor scenes/level1.yaml nsgo game editor . ``` Opens the NSGo Scene Editor in a window on the scene file named, or on the start screen when none is (showing recent projects, a folder picker, project creation from `game new`'s templates, and Open Demo). A directory or a `game.yaml` opens the game's [project file](https://game.nsgo.dev/docs/project/) and its main scene, and a scene file inside a project's directory opens with that project. A project's scenes draw the project's own sprite atlases, found by name as [`game check`](https://game.nsgo.dev/docs/cli/#check) finds them, the asset browser lists those atlases, its scene files place as instances, and its materials, physics materials, the YAML tilesets of layered tilemaps and Tiled and LDtk sources load from it and fill the tile palette; its components are free-form, since only the game's Go code registers their types. A scene file outside any project reads the files it names from its own directory and draws the demo room's atlases. With a project open, the editor opens the project's other scenes from its file browser, makes new ones, saves them under other paths, and asks before quitting or opening another scene or project loses unsaved edits ([Scene files and unsaved changes](https://game.nsgo.dev/docs/editor/#scene-files-and-unsaved-changes)). `-library` adds a panel that installs packs from that [library](https://game.nsgo.dev/docs/library/) into the open project. It has no [editor plugins](https://game.nsgo.dev/docs/editor/) built in and knows none of a game's component types. A project with an editor command of its own, which [`game generate editor`](https://game.nsgo.dev/docs/cli/#generate) writes, or a `cmd/editor` main package that imports `editorcmd`, as [Field Medic](https://github.com/nsgo-dev/game/tree/main/examples/fieldmedic)'s does, is opened by running that command with `go run` in the project's directory, passing it the same arguments, with the scene and clip paths made absolute, and `-library`; that command checks every component against the game's types and the built-in physics components and builds in its plugins. A `cmd/editor` that does not import `editorcmd` is not run; `game editor` says so and opens the project itself. The scene format is described in [Editor & Scene Format](https://game.nsgo.dev/docs/editor/). The editor, and a game's own editor command built on `editorcmd`, serve the open project to agents on a local endpoint, which `mcp` reaches. ### mcp ```sh go tool game mcp install claude mcp add game-editor -- nsgo game mcp ``` An MCP server on standard input and output, which an agent such as Claude Code or Codex starts in the project's directory, or in a directory inside it, or with `-project` naming it. It finds the editor that has the project open and forwards to it the editor's tools, `scene_read`, `scene_edit`, `selection_get`, `viewport_image`, `game_check`, `game_playtest`, `playtest_define`, `states_write`, `states_test`, `tileset_read` and `tileset_edit`, and its change stream; while no editor has the project open, each call answers with how to open it. Running `go tool game mcp install` (or `nsgo game mcp install`, optionally with `-project`) once in a project writes or updates `.mcp.json` (for Claude Code) and `.codex/config.toml` (for Codex) in the project root with the `nsgo-game-editor` entry, preserving existing entries and file permissions. [mcp](https://game.nsgo.dev/docs/mcp/#editor-tools) describes the tools and setup flow. ### release ```sh nsgo game release nsgo game release -channel store -release-notes notes/0.2.0.md nsgo game release -target macos_arm64,web -output build -dry-run ``` Builds the game in the directory named, the current one by default, which holds its `nsgo.yaml`, for every platform in one run of `nsgo build`: macOS, Windows and Linux on both architectures, web, iOS and Android on arm64 unless told otherwise. Each target's package goes to `/--`, and the files a release uploads (disk images, installers, Debian and Arch packages, AppImages, the IPA, the APK and the site's zip, each with a `.sha256`) to `/releases`, as `nsgo build` lays them out. A target that fails stops the run and exits with 1. The game's module must have NSGo as a tool (`tool github.com/nsgo-dev/nsgo/cmd/nsgo` in `go.mod`, as the starter has), since the command runs `go -C tool nsgo build`, so the build uses the module's own NSGo version; `-dry-run` prints that command instead of running it. The targets come from `-target`, else from the `export` presets of the `game.yaml` beside `nsgo.yaml`, in order, a preset without `targets` building its platform name, else the six platforms above, or only macOS, Windows and Linux when the channel (`-channel`, else `nsgo.yaml`'s `updates.channel`) is `steam`, whose depots `nsgo build` makes of desktop targets alone. `nsgo.yaml`'s `build.targets` is not used: it is the everyday list of a plain `nsgo build`, which in the starter holds a simulator build and leaves out Linux, so a release's own list belongs in the presets. The output directory comes from `-output`, else from `game.yaml`'s `export.output`, else from `nsgo.yaml`'s `build.output`: ```yaml version: 1 export: output: dist presets: - platform: macos - platform: windows targets: [windows_x64] - platform: linux - platform: web - platform: ios - platform: android ``` The command reads `game.yaml`'s `version`, which must be the integer 1, its `export` section and, for the credits file, its `assets` section. It refuses top-level fields outside the project file's (`version`, `name`, `id`, `appVersion`, `window`, `display`, `input`, `audio`, `autoload`, `export`, `editor`, `assets` and `navigation`), so a misspelt `export` is not skipped, and in `export` it refuses unknown fields, an empty `presets` list, unknown platforms and targets, a target of another platform, duplicates and an output outside the project; the rest of the file is the project file's. `-channel` is `nsgo build`'s: `store` builds the packages stores take (a Mac App Store package, universal when both macOS architectures are built, a Windows MSIX, a Flatpak bundle and an Android App Bundle) in place of the disk images, installers and APKs handed out directly, and `-release-notes` and `-jobs` pass through too. Signing, notarizing and store uploads follow `nsgo.yaml` and `nsgo publish`. When `game.yaml` has an `assets` section, which the whole file must then pass [project file](https://game.nsgo.dev/docs/project/) validation for, the release ships a credits file: after `nsgo build` succeeds, the command writes `CREDITS.md` into the output directory, beside the packages, listing the author, license and source of every asset that section reaches and each notice a license asks to be shipped, from the `credit` section of each asset's [import settings sidecar](https://game.nsgo.dev/docs/cli/#import-settings-beside-each-asset), as [`game credits`](https://game.nsgo.dev/docs/cli/#credits) writes it. The assets are the images each atlas packs, the input of each texture, audio, font and model target, the buffers and images each model names by relative path, which its GLB embeds, and every file the manifest lists in its folder, such as fonts, maps and models, leaving out the files the targets write, which are made from those inputs. An asset without a credit stops the release before anything is built, with the list of the sidecars to write; a file the manifest lists that a target wrote before its output changed counts as an asset until `game assets` removes it. `-dry-run` checks the credits too and names the file it would write. A game without an `assets` section gets no credits file, and the command notes it on standard error. Files the game loads from elsewhere, such as `autoload` resources or files it embeds outside the manifest's folder, are not listed, so credit those yourself. The credits file is written beside the packages, not into them, since `nsgo build` decides what a package holds: it is for the publisher to put on the store page or download page. To ship it inside every package as well, write it into NSGo's `resources` folder, which `nsgo build` copies into each package, before the release: `nsgo game credits -out resources/CREDITS.md`. Which targets a machine can build is what `nsgo doctor` shows: iOS needs a Mac with Xcode, and the macOS disk image needs `hdiutil` in a logged-in session, so a release of every platform runs on a Mac. ### replay ```sh nsgo game replay ./... nsgo game replay -run '^TestBossReplay$' ./levels ``` Plays a game's [input recordings](https://game.nsgo.dev/docs/replay/) headless, for CI. A recording needs the game's own simulation to play, so the command plays them through the game's tests: it first loads every `*.replay.yaml` file under each directory and fails, without running any test, when one cannot be played (an unknown key, a name missing from the header, a step out of order) or when a directory holds none, so a mistyped path cannot pass. It then runs the tests whose names match `-run`, by default every test with `Replay` in its name, headless with `go tool nsgo test`, and fails when one fails, which is what `replay.AssertEndState` does when a run ends in another state than the one the test expects. It also fails when no test in a directory passed, as when `-run` matches no test, so a misnamed test or a mistyped pattern cannot pass without playing a recording. Name the tests that play recordings accordingly, such as `TestLevel1ClearReplay`. Each directory is a tree, as `nsgo test` reads it: with or without a trailing `/...`, its subdirectories are searched and tested too, skipping directories whose names start with `.` or `_` and nested modules but not `testdata`. The default is `./...`. The command runs `go tool nsgo`, so the module needs NSGo's command as a tool, as an NSGo app has. ### playtest ```sh nsgo game playtest nsgo game playtest -config playtest.yaml -out playtest.report.yaml -recordings playtest-recordings nsgo game playtest -check ``` Validates `playtest.yaml` (or `-config`) and runs the configured bot headless for every seed through the game's tests matching `-run` (`Playtest` by default, which call `playtest.RunTest`). Each seeded run records its inputs into `/run_NNN_seed_.replay.yaml` so any run can be watched or turned into a `game replay` test, and writes a deterministic YAML report to `-out` (`playtest.report.yaml` by default) containing per-run metrics, goal results (`met`, `missed` or `info`) and position data for heat maps. The command prints the report summary and exits 1 when any goal is missed or no matching test passed. Use `-count` or `-seeds` to override the runs in `playtest.yaml`, or `-check` to validate `playtest.yaml` without running tests. See [playtest](https://game.nsgo.dev/docs/playtest/). ### bench ```sh nsgo game bench ./sprite ./tilemap nsgo game bench -update ./sprite ./tilemap nsgo game bench -in bench.txt ``` Runs the benchmarks under each directory headless with `go tool nsgo test -bench`, `-count` times (3 by default) for `-benchtime` each (200ms by default), takes each benchmark's median time, bytes and allocations per operation, and compares them with the baseline file named by `-baseline`, by default `benchmarks/baseline.yaml`. It prints a line per benchmark in the baseline and fails when one grew past its limit or was not measured, or when the baseline holds no benchmark; a measured benchmark the baseline lacks is listed as new and does not fail. `-bench` narrows the benchmarks run, as `go test -bench` does. `-in` reads the results from a file of `go test -bench -benchmem` output instead of running anything. `-update` writes the measured medians to the baseline instead, creating it when it does not exist, and keeps the benchmarks it did not measure. The baseline is a YAML text file to review and edit like any other: the format version, a note, the regression allowed for each metric in percent, and one line per benchmark in name order. Loading and saving it changes nothing, and unknown keys and missing metrics are refused. ```yaml version: 1 note: Update with nsgo game bench -update ./sprite ./tilemap max_regression_pct: {ns_per_op: 25, bytes_per_op: 25, allocs_per_op: 25} benchmarks: BenchmarkBatchDraw1000: {ns_per_op: 155412, bytes_per_op: 72232, allocs_per_op: 754} BenchmarkRaycast: {ns_per_op: 827.3, bytes_per_op: 0, allocs_per_op: 0} ``` Benchmarks are named without their `-GOMAXPROCS` suffix, so a baseline recorded on one machine is read on another, but time per operation depends on the machine: record the baseline on the kind of machine CI checks it on. The format is read and written by the `tooling/bench` package. ### new ```sh nsgo game new mygame nsgo game new -name "Space Rocks" -module example.com/rocks rocks nsgo game new -list ``` Writes a project from a template into the directory named, creating it if needed, and prints each file's path. It then runs `go get -tool github.com/nsgo-dev/game/cmd/game@` and `go mod tidy` there, which need the Go module proxy, so the project requires that version of the game layer and has the `game` tool beside the `nsgo` tool, and builds and runs with `go tool nsgo dev` without edits. The game is named after the directory unless `-name` gives a name (letters, digits, spaces, `-` and `_`, starting with a letter), which `game.yaml` and `nsgo.yaml` hold as `name`, with `id` derived from it as `dev.nsgo.`. The module path is the name in lower case with its words joined by `-` unless `-module` gives one. A module path that is a standard-library package's, such as `time` for a game called Time, is refused because the project could not build, so such a game needs `-module`, such as `-module example.com/time`. `-version` is the version of the game layer to require, such as `v0.4.0`, a commit or `latest`; by default it is the version of the command running, so `go run …@v0.4.0 new`, or an `nsgo-game` installed at `v0.4.0`, creates a project on `v0.4.0`, and `latest` when the command was built from a checkout of this repository. `-template` chooses the template, `starter` by default, and an unknown name is refused with the names there are. `-list` prints each template's name, the default marked, beside a line saying what it is, and creates nothing. [Templates](https://game.nsgo.dev/docs/templates/) lists them with the module `nsgo init -template` takes for each, and describes how a template is laid out and how to add one. `new` writes nothing when any file it would write already exists in the directory, and fails with 1. Every template includes `.gitattributes` registering `*.scene.yaml` and `*.scene.yml` with the `nsgo-scene` merge driver, and when the directory already holds a `.git` repository, `new` also configures the local Git driver automatically (otherwise run `go tool game merge -setup` after `git init`). When `go get` or `go mod tidy` fails, such as without a network, the files stay where they are written, and the error names the commands left to run in the directory to finish the project: both `go get -tool …` and `go mod tidy` when `go get` failed, and `go mod tidy` alone when it failed. ### dev ```sh nsgo game dev nsgo game dev -target native -fps nsgo game dev -scene scenes/level2.scene.yaml nsgo game dev ./mygame -lang fr ``` Runs `go tool nsgo dev`, which builds the game, starts it and rebuilds it when its Go code changes, and tells the running game where its assets are: the absolute path of `-assets` (`resources` in the project directory by default) in the `NSGO_GAME_ASSETS` environment variable, which `hotreload.DevAssetsDir` returns. Passing `-scene ` sets `NSGO_GAME_SCENE` (`hotreload.SceneEnv`, read by `hotreload.DevScene`) so the running game can start directly at that scene (as the editor's Run command does when starting at the open scene). It must be the directory the game's `assets.Manager` reads `"asset:"` URIs from: one made with `assets.WithFS(os.DirFS(hotreload.DevAssetsDir()))`, since a `Manager` without `WithFS` reads `assets/` in the directory `game dev` runs in. A game that starts a watcher on it with `hotreload.NewDevWatcher` sees an atlas, image, data file, shader or material it has loaded change within a second of the file being saved, without restarting; see [Reloading on save](https://game.nsgo.dev/docs/assets/#reloading-on-save) and [Hot-reloading shaders and materials](https://game.nsgo.dev/docs/render3d/#hot-reloading-shaders-and-materials). The first argument that is not a flag is the project directory, `.` when there is none, and the arguments after it go to `nsgo dev` unchanged; `-target`, `-fps` and `-automation` are passed on too (with `-automation` enabling NSGo's automation server so the editor's Remote tab or `go tool nsgo mcp` can inspect the running game), and a `-target` among the arguments after the directory decides the target, as it does for `nsgo dev`. `nsgo dev`'s output is game dev's, and Control+C stops both. `nsgo game dev` exits with 1 when `nsgo dev` fails. Assets reload on the `native` and `tui` targets, and on `android` with `-android-host`, whose app's Go runs on this machine and reads the files. On the web and on phones the app cannot reach the asset directory, so game dev says so and the game picks up asset changes when `nsgo dev` rebuilds it. Without an asset directory game dev runs `nsgo dev` as it is and says that assets will not reload. An asset the game embeds with `go:embed` is part of its binary: `nsgo dev` rebuilds and restarts the game when such a file changes, and the watcher's reload shows the change before that. ### check ```sh nsgo game check nsgo game check examples/caverun ``` Checks every scene, map, tileset and atlas under the directory named (or `-in`, or the working directory when neither is given), and the references between them, so a broken reference fails before a player reaches it. Each problem is printed to standard error as `file:line: message`, with the file named from the working directory so an editor can open it, followed by a count, and the command exits with 1; with no problems it prints how many files of each kind it checked and exits with 0: ```text examples/caverun/assets/level1.tmj:1397: tileset image "tileset.png": not found game check: 1 problem ``` | Files | What must hold | | --- | --- | | Scenes (`*.scene.yaml`, `*.scene.yml`) | They parse and validate as the [scene format](https://game.nsgo.dev/docs/editor/), with no unknown field; a tilemap `source` is a Tiled map (`.tmj` or `.tmx`, which checks) or an LDtk project (`.ldtk`, which checks and has the `level` it names) that exists; a layered tilemap's `tilesetFile` is a YAML tileset that exists and checks and has every tile its cells place; each sprite's `atlas` exists and has its `frame`; an inline tilemap's `tileset` atlas has a frame for every tile ID it uses; a `material` file exists, is a valid material, and its `texture` exists; a `model` is a `.gltf` or `.glb` file that exists and loads with `gltf.LoadFS`, holds the node a `modelNode` names or the mesh a `modelMesh` names, and a `mesh` is a built-in primitive ([scenemodel](https://game.nsgo.dev/docs/scenemodel/)); a scene that instances or inherits others resolves, and each of its connections' `from` and `to` names an object of the resolved scene ([Checking connections](https://game.nsgo.dev/docs/editor/#checking-connections)) | | Tiled maps (`.tmj`) and tilesets (`.tsj`) | External tilesets are JSON tilesets (`.tsj`, or `.json` as older Tiled versions named them; not `.tsx`) that exist; tileset and image-layer images exist, also inside group layers; the map loads with `tilemap.LoadTiled`. A Tiled XML map (`.tmx`) that a scene names loads with `tilemap.LoadTiled` together with its external tilesets (`.tsx` or `.tsj`), and every tileset and image-layer image it draws exists | | YAML tilesets (`*.tileset.yaml`, `*.tileset.yml`) | They parse and validate as the [tileset format](https://game.nsgo.dev/docs/tilemap/#yaml-tilesets); a grid tileset's `image` exists and is large enough for its `columns`, `tileCount`, `spacing` and `margin`; an atlas tileset's `atlas` exists and has each of its `frames` | | LDtk projects (`.ldtk`) | Tileset images and level backgrounds exist; no level is saved in a separate `.ldtkl` file, which `tilemap.LoadLDtkAll` does not read (turn off "Save levels to separate files" in LDtk); the project loads with `tilemap.LoadLDtkAll` | | Sprite atlases (JSON with top-level `frames` and `meta`, as TexturePacker and Aseprite export) | `meta.image` exists; every frame lies inside the image; the atlas loads with `sprite.LoadAtlas` | | `game.yaml` and every other reference between files | `game.yaml` parses and validates as the [project file](https://game.nsgo.dev/docs/project/); each autoloaded scene and resource exists, as does each `assets` target's `in` (a folder for an atlas) and every other file a reference names that the rows above do not reach: the scene a scene `inherits` and the scene an object instances (`scene`), whatever its file is called, the materials, models and tilemap sources in overrides and in scenes not named `*.scene.yaml`, a material's `texture` wherever the material is used, and the buffers and images a `.gltf` model keeps in separate files. What `game assets` writes (`out`, `cache`, `manifest.in`) and the navigation mesh file a scene's `navMesh` names, which `game navmesh` writes, need not exist yet | | Project indexes (`game.index.yaml`) | They parse, and no two scene or resource files of one project share a `uid`, as a copied file does until `game index` gives it its own; separate projects, such as two games made from one template, may | A path a map, tileset or atlas writes is relative to that file, as Tiled, LDtk and texture packers write them. A scene's tilemap `source`, `tilesetFile`, `material` and `model`, a YAML tileset's `image`, and a material's `texture`, are relative to the project root: the nearest directory above the scene holding `game.yaml`, `nsgo.yaml` or `go.mod`, or the checked directory when there is none. A scene names an atlas the way its game's `sceneformat.AssetResolver` does, so the check finds it by file name: the atlas JSON in the same project whose base name without `.json` is the name (`actors` is `art/actors.json`), or whose path from the project root is (`art/actors`). When several match, the one nearest the scene wins, counting the directories up from the scene and down to the atlas, so an atlas beside the scene beats one in a subdirectory, and two equally near are reported as ambiguous until the scene names one by its path. When no atlas matches but a JSON file of that name does not parse or is not an atlas, that file's fault is reported. A path must be relative and use forward slashes, and must not lead outside the checked directory. PNG, JPEG and GIF images must decode; other images only have to exist. Directories whose names start with `.` or `_`, and those named `testdata`, are skipped, as the go command skips them. Other JSON and YAML files are not read. A problem the loader of a map or atlas reports names no line, so it is printed as `file: message`; the check runs that loader only once the file's references resolve, so one fault is not reported twice. When a reference names a file that is gone and the project index knows where it went, the problem says so, and [`game index`](https://game.nsgo.dev/docs/cli/#index) updates the reference: ```text scenes/room.scene.yaml:10: material "materials/stone.material.yaml": not found; it moved to "materials/rock.material.yaml"; run game index to update the reference ``` The Examples workflow runs `game check` on the sample games. To run it in a game's own CI, add the command as a tool as above and run `nsgo game check` from the game's directory. The checks are also a package, `github.com/nsgo-dev/game/pkg/tooling/assetcheck`, whose `Check` takes an `fs.FS` and returns the problems as values, and whose `CheckWith` also takes the game's component registry to check the events and handlers that connections name. ### assets ```sh nsgo game assets nsgo game assets -check ``` Builds every asset target that `game.yaml` (or the file `-in` names) declares, in one run: it packs the atlases, encodes the textures and converts the audio as `pack`, `tex` and `audio` do, bakes the fonts into bitmap fonts and packs the models into single GLB files, then regenerates the manifest as `manifest` does. Each target is rebuilt only when it changed: a second run with nothing changed writes no file, and changing one image repacks only the atlas it belongs to. It prints a line for each target it built and then the counts, such as `1 built, 4 up to date`. The targets are the `assets` section of `game.yaml`, the project file, which the command reads through package `project` as the game and the editor do, and which `release` accepts too, so one `game.yaml` holds them beside the window, input, autoload and export settings ([Project File](https://game.nsgo.dev/docs/project/)). The file is versioned YAML and the command refuses a field it does not know, a file without an `assets` section, and a file the project schema refuses. The section's paths are slash-separated, relative to the file's directory, and may not leave it: ```yaml version: 1 name: Cave Run id: dev.nsgo.caverun appVersion: 0.1.0 window: {width: 480, height: 640} assets: atlases: - name: ui # pages ui.png and ui.json in: art/ui # PNG images, searched recursively out: assets/atlases padding: 2 # 1 when omitted extrude: 1 maxWidth: 2048 maxHeight: 2048 scale: 1 trim: true # true when omitted textures: - in: art/albedo.png out: assets/albedo.ktx2 format: bc1 # rgba8, bc1, bc3 or etc2; rgba8 when omitted mipmaps: true srgb: true audio: - in: sfx/jump.wav out: assets/jump.wav format: wav # wav, aac or mp3; wav when omitted rate: 22050 channels: 1 peakDB: -1 # or rmsDB, not both bitrate: 128 # for aac and mp3 fonts: - in: fonts/Inter.ttf # a TrueType or OpenType font out: assets/fonts/hud.fnt # pages hud.png, or hud-0.png, hud-1.png and so on, beside it size: 24 # pixels; 32 when omitted chars: " 0123456789:" # printable ASCII when omitted padding: 1 # 1 when omitted models: - in: models/ship.gltf # .gltf or .glb, with the buffers and images it names beside it out: assets/ship.glb scale: 0.01 # 1 when omitted animations: true # true when omitted manifest: in: assets out: assets/manifest_gen.go package: assets prefix: "asset:" embed: false embedDir: "" ``` Every list and the manifest are optional, and each setting means what the flag of the same name means for the single command. Two targets may not write the same file: an atlas named `ui` writes `ui.png` and `ui.json`, or `ui-0.png`, `ui-1.png` and so on with their `.json` files when it needs several pages, so no other target in its folder may write those names, nor another atlas there be named `ui` or `ui-1`. No target, and not the cache, may write over `game.yaml` or a file a target reads, since the next run would then read its own output. An atlas may not write its pages into a folder an atlas reads images from, nor may another target or the cache write a `.png` file there, since the atlas would then pack it on the next run, and the cache may not be inside the manifest's folder, since the manifest would then list it; a folder whose name starts with a dot is skipped by both scans, so any of them may go there. A font's pages are named after its `.fnt` file as an atlas's are after its name, `hud.png` or `hud-0.png`, `hud-1.png` and so on beside `hud.fnt`, and follow the same rules. No target may read a font's page either: fonts are built after textures and models, so a texture made from one would encode the page of the run before. A font target bakes a TrueType or OpenType font into an [AngelCode BMFont](https://game.nsgo.dev/docs/text/) that `text.LoadBMFont` reads: each character of `chars` the font has a glyph for is drawn at `size` pixels, at most 2048, in white with its coverage as alpha, the glyphs are packed onto PNG pages up to 2048 pixels a side, `padding` pixels apart, and the `.fnt` text file records each glyph's place, offsets and advance, the line height and baseline, and the font's kerning between the baked characters. A character the font has no glyph for is left out; a font with none of them is an error. A model target packs a glTF model into one binary glTF file that [gltf](https://game.nsgo.dev/docs/3d-models-blender/) loads with nothing to resolve: the buffers the model holds or names, a `.glb` file's binary chunk among them, are merged into the GLB's binary chunk, and each image it names by file or data URI is embedded there with its media type. Every other property is kept, extensions and extras included, and the result is checked by loading it. `scale` puts each root node of the model's scenes under a new node scaled by it, one per root even when several scenes list it, such as `0.01` for a model exported in centimeters, and `animations: false` leaves the animations out. The buffers and images the model names must be relative paths inside the project; they are inputs of the target, so editing a texture beside a `.gltf` file repacks it. What each target was built from is kept in a cache, `.game/assets-cache.yaml` unless `assets.cache` names another path. It is YAML: for each target, a SHA-256 key over its settings, the version of the game layer that built it, the path and content of every input, a model's buffers and images included, and of the import settings sidecar beside it and, for AAC and MP3, the external encoder and its version, and the path and SHA-256 of every file it wrote. A target is up to date when its key matches and its outputs are still on disk with that content, so editing or deleting an output also rebuilds it, and so does installing another encoder. When an atlas needs fewer pages than before, the pages it no longer writes are deleted, and so are other page files of its name in its folder. When a target is renamed, moved to another output or removed from `game.yaml`, the files it last wrote are deleted before the manifest is generated. The manifest needs no cache entry: it is generated each run, which reads no file's content, and written only when it differs. A missing or damaged cache only costs a full rebuild. Add the `.game` folder to `.gitignore`. `-force` rebuilds every target. `-check` writes nothing in the project: it lists the targets that are out of date and exits with 1 if there are any, for CI. A target the cache does not show as up to date, as in a fresh checkout without the `.game` folder, is built in a temporary folder and counts as up to date when the files in the project are exactly what it writes, so CI needs no cache when the outputs are committed. AAC and MP3 are the exception: another encoder, or another version of one, writes different bytes for the same input, so without a cache entry they count as up to date when their output exists, and CI needs no encoder. An atlas whose folder holds a page file of its name that it does not write, such as `ui-1.png` left from a build that needed more pages, is out of date until a build deletes it. When a target fails, the command keeps the cache of the targets it built before it, so the next run starts from there. #### Import settings beside each asset An asset may have a sidecar: a YAML file beside it, named after it with `.import.yaml` appended, such as `art/albedo.png.import.yaml`, that says how it is imported, as Godot's `.import` files do, and who made it under what license. A setting in the sidecar overrides the same setting of the target that reads the file, so one asset's import is changed by editing the file beside it, and the next run rebuilds the targets that read it. A sidecar is versioned YAML that package `github.com/nsgo-dev/game/pkg/tooling/importsettings` reads and writes; it holds one `image`, `audio`, `font` or `model` section, a `credit` section, or a credit with one of the others, refuses a field it does not know, and is validated by the [published schema](https://game.nsgo.dev/docs/schemas/) `https://game.nsgo.dev/schemas/import.v1.json`. ```yaml # art/albedo.png.import.yaml, read by a texture target version: 1 image: filter: nearest # linear or nearest, written into the KTX2 key/value data as game.filter format: rgba8 # rgba8, bc1, bc3 or etc2 mipmaps: false srgb: true ``` ```yaml # art/hero/run.png.import.yaml, read by the atlas whose folder holds run.png version: 1 image: slice: {width: 16, height: 16, margin: 1, spacing: 2, count: 6} pivot: default: [0.5, 1] cells: - cell: 2 pivot: [0.25, 0.75] ``` ```yaml # music/theme.wav.import.yaml, read by an audio target version: 1 audio: format: wav # wav, aac or mp3 rate: 32000 channels: 2 rmsDB: -14 # or peakDB; either one replaces the target's normalization bitrate: 128 loop: {start: 44100, end: 1323000} # in the source's sample frames; end 0 or left out is the end of the sound ``` ```yaml # fonts/Inter.ttf.import.yaml, read by a font target version: 1 font: size: 24 chars: " 0123456789:" # each once, in any order padding: 2 ``` ```yaml # models/ship.gltf.import.yaml, read by a model target and scenemodel.Build version: 1 model: scale: 0.01 animations: false lodHysteresis: 0.05 lods: - { node: Ship_LOD0, minScreenRatio: 0.25 } - { node: Ship_LOD1, minScreenRatio: 0.0 } ``` ```yaml # assets/fonts/pixel.ttf.import.yaml, a credit beside an asset no target imports version: 1 credit: author: Ana Souza license: OFL-1.1 # an SPDX license expression source: https://example.com/pixel-font notice: |- Copyright 2026 Ana Souza. Licensed under the SIL Open Font License, Version 1.1. ``` - A texture target reads `filter`, `format`, `mipmaps` and `srgb`. `filter` is stored under the key `game.filter` of the KTX2 file's key/value data, and [`render3d.LoadKTX2`](https://game.nsgo.dev/docs/render3d/) sets the sampler's filters from it when it loads the texture: `nearest` draws it sharp, as pixel art wants, and `linear` blends neighboring texels. `slice` and `pivot` are refused, since a texture holds the whole image, unless an atlas also reads the image. - An atlas target reads `slice` and `pivot` from the sidecar of each image in its folder: `slice` cuts the image into cells of `width` by `height` pixels, `margin` pixels from its top and left edges and `spacing` pixels apart, taken row by row, and cell `i` of `run.png` is packed as the frame `run_i.png`. `count` keeps the first cells; left out, every cell that fits is a frame. `pivot` sets normalized `[x, y]` pivot coordinates as fractions of the untrimmed frame size (from `[0, 0]` at top left to `[0.5, 1]` at bottom center), written into each packed frame's TexturePacker `pivot` field so `sprite.LoadAtlas` sets `Frame.PivotX` and `Frame.PivotY`: `default` applies to an unsliced image and every cell of a sliced sheet without an override, and `cells` lists per-cell `{cell, pivot}` overrides in ascending 0-based cell order (requiring `slice`). The texture settings, `filter` included, are refused there, since an atlas page is one texture for every image packed into it, unless a texture target also reads the image: an image read by both may hold both kinds of settings, and each target takes its own. A frame that takes the name of another image in the folder is refused. - A font target reads every `font` setting: `size`, `chars` and `padding`. Listing the same characters in another order changes nothing. - A model target reads every `model` setting: `scale` and `animations`. - `game release` and `game credits` read `credit`, which any asset's sidecar may hold, beside an `image`, `audio`, `font` or `model` section or on its own; `game assets` builds nothing from it. `author` and `license` are required. `license` is an [SPDX license expression](https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/): identifiers from the SPDX license list such as `CC0-1.0`, `CC-BY-4.0` or `OFL-1.1`, joined by `AND` and `OR` and grouped by parentheses, a `+` for "or any later version" and `WITH` for an exception, such as `MIT OR Apache-2.0`; a license with no identifier, such as a store's or a studio's own, is `LicenseRef-` followed by a name of its own, with its terms in `notice`. Its form is checked, not the identifier against the list, and `NONE` and `NOASSERTION` are refused. `source` is where the asset came from, usually a URL, and `notice` is text the license asks to be shipped with the asset, such as a copyright line, kept word for word and on several lines if need be. - An audio target reads every `audio` setting. `loop` is written into the WAV output's `smpl` chunk as a forward loop that repeats forever, scaled to the output rate; AAC and MP3 carry no loop points, so a sound with a loop must be converted to `wav`. A loop already in a source WAV's `smpl` chunk is kept the same way. A sidecar's settings are part of the key of every target that reads its asset, so adding, editing or deleting them rebuilds those targets and no others, and `-check` reports them as out of date until the next run. Its `credit` section, comments and layout are not, since they change no output: fixing an author's name rebuilds nothing. Sidecars are not assets: the manifest skips files named `*.import.yaml`, and an atlas packs only `.png` files. `game pack`, `game tex` and `game audio` read the sidecar beside their input too, under the flags given. A sidecar in a folder a target reads from (an atlas's folder and the folders below it, or the folder of a texture, audio, font or model input) whose asset no target reads is refused, so a mistyped name, a sidecar beside a JPEG in an atlas folder, or one named in another case than its asset, such as `Hero.PNG.import.yaml` beside `hero.png`, is an error rather than settings that silently do nothing. A sidecar that holds only a `credit` says nothing about the build, so it may sit beside any file in those folders, such as a JPEG or an image a model embeds, as long as the file is there under exactly its name. ### generate ```sh nsgo game generate component player_health nsgo game generate system movement nsgo game generate -main scene level_one nsgo game generate prefab enemy nsgo game generate editor ``` Writes the code and files of a new component, system, scene or prefab, or the game's editor command, into the game in `-in`, the working directory by default, laid out as [`game new`](https://game.nsgo.dev/docs/cli/#new) lays out a project, and prints the path of each file it writes. The Go code goes into the package in that directory, under that package's name, and every Go file comes with a test beside it. The name is ASCII letters and digits starting with a letter, in camel case or with its words joined by `-` or `_`, and is written in each form it is used in: `player_health`, `player-health` and `PlayerHealth` all give the Go type `PlayerHealth`, the key `playerHealth` and files named `player_health_*`. | Kind | Writes | Registers it in | | --- | --- | --- | | `component` | `_component.go`: a struct (`PlayerHealth`) and the `sceneformat.ComponentType` scene files set it by (`playerHealth`), both without fields | `Components`, the `sceneformat.ComponentRegistry` that loading a scene checks its objects' components against | | `system` | `_system.go`: a function `MovementSystem(w *entities.World, dt time.Duration)`, added to the scheduler as `movement` | `Systems`, the `entities.Scheduler` the game steps each fixed step | | `scene` | `scenes/.scene.yaml`: a scene in the scene format's current version with an empty layer named `main` and the virtual resolution of `game.yaml` (its window's size when it has none); and `_scene.go`, which embeds the file and parses it with `LoadLevelOneScene`, checking its components against `Components` | `game.yaml`'s `autoload` scenes with `-autoload`, and as its `mainScene` with `-main` | | `prefab` | `prefabs/.scene.yaml`: a scene of one object whose `prefab` is the name, for other scenes to instance with `scene: prefabs/enemy.scene.yaml`; and `_prefab.go`, an `entities.Prefab` (`EnemyPrefab`) of that name | `Prefabs`, the game's prefabs by name | | `editor` (no name) | `editor.go`: the game's scene editor, a `main` function built with the `gameeditor` tag that runs `editorcmd.Main` with `Components` and `editorPlugins`, the game's editor plugins, which it declares empty; and `editor_test.go`, which opens the project in it | adds `//go:build !gameeditor` to the file that declares the game's own `main`, so the tag builds the editor in its place | The registries are declared once, in `components.go`, `systems.go` and `prefabs.go`, which the first component, system, scene or prefab that needs one writes. Each generated file adds itself to its registry in an `init` function, so `generate` never edits a file that is already there. The game uses them where it loads scenes and runs its loop: `sceneformat.ParseWith(data, sceneformat.ParseOptions{Components: Components})` refuses a component or field a scene sets that no component describes, and `Systems.Step(world, dt)` in the `game.Loop`'s `Update` runs the systems in their order, which `entities.After` and `entities.Before` set where each one is added. Fill in the generated code from there: a component's fields and the `sceneformat.Field` of each one a scene may set, a system's queries, a prefab's components with `entities.With`. The editor command is the game's own package built with the `gameeditor` tag, because a game made with `game new` keeps its code in its `main` package, which no other package can import: built that way, the editor links the game's component types, and the game built without the tag links no editor. [`game editor`](https://game.nsgo.dev/docs/cli/#editor) runs it on the project as `go run -tags gameeditor .`, so the project's scenes open with their components and fields checked against `Components`, which the inspector lists. Add a plugin by appending its `editor.Plugin` to `editorPlugins`, keeping code only the editor uses in files built with the tag or in packages only they import; `game.yaml` turns it on under `editor.plugins` ([Editor plugins](https://game.nsgo.dev/docs/editor/#editor-plugins-492)). Run its test with `go tool nsgo test . -tags gameeditor`. `generate editor` refuses a package that is not `main` or has no `main` function, a file declaring `main` whose build constraint is a legacy `// +build` line or names `gameeditor` already, as a second `generate editor` finds it, a file declaring `main` that also declares something the rest of the package needs, which the editor build, leaving out the whole file, would lose: a name another file or a test uses, an `init` function, a blank `var`, or a method on a type another file declares (move it into another file), and identifiers the package already declares; when rewriting that file fails, it removes what it wrote. What `generate` writes builds, passes the tests `go tool nsgo test` runs and passes `game check` as it is. It writes nothing and fails with 1 when a file it would write already exists, or when the package already declares an identifier it would declare, in any of its files, tests and files for other platforms included; choose another name then. It also fails when the package declares `Components`, `Systems` or `Prefabs` as something other than a variable, or declares a name a generated file imports a package as, such as `entities` or `time`, and refuses `components`, `systems` and `prefabs` as names, since their Go names are the registries'. `-autoload` and `-main` rewrite `game.yaml` in the form `gameproject fmt` writes, so they refuse a `game.yaml` in another form, such as one with comments, which rewriting would lose, until `gameproject fmt` has rewritten it, and refuse a name `game.yaml` already autoloads. The starter's `TestAutoloadsLoad` checks the files `game.yaml` autoloads, so an autoloaded scene that goes missing fails the game's tests; it reads them from the project directory, so it is skipped under `nsgo test -target` on a phone, a simulator or the web, where the generated tests read only the scene files their code embeds. ### mv ```sh nsgo game mv materials/stone.material.yaml materials/rock.material.yaml nsgo game mv -dry-run art gfx ``` Moves or renames a file or directory and rewrites every reference to what it moves: in `game.yaml`, scenes, resource files, and Tiled and LDtk files, whose own paths relative to themselves are rewritten too when they move. Each reference is changed in place, keeping its quotes and the rest of its file byte for byte, comments included. The project index, `game.index.yaml`, is brought up to date. The paths are taken from the working directory and must lie inside the project, the directory `-in` names or else the nearest one at or above the working directory that holds `game.yaml`, `nsgo.yaml` or `go.mod`. Each change is printed; `-dry-run` prints them without making them, as it does for `release`. A move that would leave a reference broken is refused before anything changes, as are moving `game.yaml` or the index, a move onto an existing file and a move out of the project. See [Stable references](https://game.nsgo.dev/docs/project/#stable-references). ### index ```sh nsgo game index nsgo game index -dry-run examples/caverun ``` Gives every scene and resource file without a `uid` one, as a line after its `version`, points every reference to a file that was moved without the tools at the file's new path, gives a copied file that kept its original's uid a new one, and writes `game.index.yaml` at each project root, listing each scene and resource file's path and uid and each other referenced file's path and SHA-256. It prints each change, or that the index is up to date; `-dry-run` prints them without making them. The directory is the one named, `-in`, or else the nearest at or above the working directory holding `game.yaml`, `nsgo.yaml` or `go.mod`. Unlike `check`, which checks the working directory and what is under it, `mv` and `index` default to that whole project, since a reference to a moved file can be anywhere in it and the index sits at its root: run from a subdirectory, `check` looks at the subdirectory alone while `index` updates the whole project. Run it once to start keeping an index, and again after moving files by hand or with Git; commit the index with the files. ### library ```sh nsgo game library list tiles nsgo game library install dungeon-tiles nsgo game library remove dungeon-tiles nsgo game library digest library/packs/dungeon-tiles ``` Lists the packs of a library that match the words given (`-kind` keeps one kind), with the version the project has installed; installs packs into the project in the working directory (or `-project`), writing their files and recording them and the autoload entries and editor plugins they add in `game.yaml`; installs a newer release over an older one; removes an installed pack; and prints a pack directory's digest for the library's index. The library is the shared one in this repository unless `-index` names another. The index and pack formats, what an install may and may not overwrite, and how to add a pack are in [Asset and Plugin Library](https://game.nsgo.dev/docs/library/). ### credits ```sh nsgo game credits nsgo game credits -in game.yaml -out CREDITS.md ``` Writes the credits file that `game release` writes beside its packages, to `-out`, or prints it when `-out` is empty, from the `assets` section of `-in` (`game.yaml` by default), without building anything. It lists the same assets as `release`, with the author, license and source from the `credit` section of the [import settings sidecar](https://game.nsgo.dev/docs/cli/#import-settings-beside-each-asset) beside each one, and fails with 1, naming the sidecar each uncredited asset needs, when any has no credit, so CI can run it to keep every asset credited. The file is Markdown and depends only on the credits, so the same sidecars always give the same bytes: ````markdown # Credits | Asset | Author | License | Source | | --- | --- | --- | --- | | `assets/fonts/pixel.ttf` | Ana Souza | OFL-1.1 | | | `sfx/jump.wav` | Kenney | CC0-1.0 | | ## Licenses | License | Assets | | --- | --- | | [CC0-1.0](https://spdx.org/licenses/CC0-1.0.html) | 1 | | [OFL-1.1](https://spdx.org/licenses/OFL-1.1.html) | 1 | ## Notices ### `assets/fonts/pixel.ttf` ```text Copyright 2026 Ana Souza. Licensed under the SIL Open Font License, Version 1.1. ``` ```` The assets are sorted by path. The licenses table counts the assets under each license expression and links each single SPDX identifier to its page in the SPDX license list, and every notice follows word for word. Package `github.com/nsgo-dev/game/pkg/tooling/credits` collects the credits and writes the file, for a game that shows them on a screen of its own. ### pixelfx ```sh nsgo game pixelfx -out assets/fx fire/torch nsgo game pixelfx -set seed=4 -set palette=#102,#215,#43a,#8cf,#fff -flip -name frost-torch -out assets/fx fire/torch nsgo game pixelfx -act -fps 30 -out assets/fx moves/ground-pound nsgo game pixelfx -list ``` Renders one of the [pixelfx](https://game.nsgo.dev/docs/pixelfx/) effects the command was built with to a PNG sprite sheet and its Aseprite JSON, `.png` and `.json` in `-out`, which `sprite.LoadAtlas` reads: every frame at the effect's own frame rate (or `-fps`), laid out in a grid, with each frame's duration and its pivot at the effect's origin, and one animation tag that loops a loop and plays a one-shot once. The name is the effect's (`torch`) unless `-name` gives one, which must be a file name without a directory. `-set name=value` sets one of the effect's options, as a number, `true` or `false`, a color such as `#4a3f69` (`#rgb`, `#rrggbb`, or `#rrggbbaa` with its alpha ignored), colors separated by commas for a palette, or text, and `-flip` mirrors it. `-act` renders the effect acted out instead: the stock character performing it, with its straw target, at 60 frames per second unless `-fps` says otherwise, and the JSON carries the act's timing for a game with its own character. `-list` lists the effects with their size, length and options. An effect, option or value the command does not know exits with 2. The categories it renders are the ones ported so far; each category's port adds its own. ### navmesh ```sh nsgo game navmesh scenes/level1.scene.yaml nsgo game navmesh -out build/level1.navmesh.yaml scenes/level1.scene.yaml ``` Bakes the [navigation meshes](https://game.nsgo.dev/docs/navbake3d/) of a 3D scene: it resolves the scenes the scene instances and inherits, loads the glTF model (`.gltf` or `.glb`) each object's `mesh` names, from the project root, at the object's 3D transform, and bakes the triangles once for each agent type in the `navigation` section of the [project file](https://game.nsgo.dev/docs/project/), with that section's settings; without one, it bakes one agent type called `default` with the default settings. It writes the [navigation mesh file](https://game.nsgo.dev/docs/formats/#3d-navigation-meshes) to `-out`, or to the file the scene's `navMesh` names from the project root, and prints the file and each agent type's number of polygons. The project directory is `-in`, or the nearest directory at or above the working directory that holds `game.yaml`, `nsgo.yaml` or `go.mod`, and the scene must be inside it. The same scene and settings always write the same bytes, so the file belongs in version control beside the scene, and a bake that changes nothing shows no diff. A scene without a `navMesh` and no `-out` exits with 2, and one with no geometry to bake exits with 1. ### merge ```sh go tool game merge -setup go tool game merge %O %A %B %P go tool game merge -out merged.scene.yaml base.scene.yaml ours.scene.yaml theirs.scene.yaml scenes/level1.scene.yaml ``` Three-way Git merge driver for YAML scene files (`*.scene.yaml`, `*.scene.yml`). Instead of merging scenes line by line, it matches layers by `name`, objects by `id` anywhere in the scene tree (including across reparenting and layer moves), tilemaps and overrides by key, and connections by `(from, event, to, handler)`, merging fields one by one so independent edits on two branches combine cleanly and are written in canonical `sceneformat.Encode` order. When Git invokes the driver with ` [path]`, a clean merge overwrites `` (or `-out`) with the canonical merged scene and exits with 0. An empty `` file (a Git add/add merge) is handled by merging `` and `` against an empty ancestor. When both sides change the same field differently, one side deletes what the other modified, both add different objects with the same ID, reparenting conflicts or cycles occur, or the combined scene fails `sceneformat.Validate`, the driver writes a versioned, deterministic [scene merge conflict report](https://game.nsgo.dev/docs/formats/#scene-merge-conflict-report) (`version: 1` YAML naming each object, field, and the `base`, `ours`, and `theirs` values) to `` (or `-conflict-out` / `-out`) and exits with 1 so Git marks the path unmerged. `-setup [dir]` registers `merge.nsgo-scene.name` and `merge.nsgo-scene.driver` (`go tool game merge %O %A %B %P`) in the repository's local Git config and ensures `.gitattributes` routes `*.scene.yaml` and `*.scene.yml` to `merge=nsgo-scene`. New projects created with `game new` already include `.gitattributes` and configure the driver automatically when initialized inside a Git repository. ### completion ```sh mkdir -p ~/.zfunc nsgo game completion zsh > ~/.zfunc/_game ``` Writes a completion script for `zsh`, `bash` or `fish` to standard output. It completes the subcommands with their summaries, each subcommand's flags with their descriptions, the values `-format` and `release`'s `-channel` take, the kinds `generate` writes (offered for its name too, since a command's arguments complete alike at every position), the effects `pixelfx` renders, and file paths for `-in`, `-out` and the files and directories the other commands take. The script is generated from the commands' definitions, so after upgrading the game layer, write it again to complete the subcommands and flags the upgrade added. The script completes both `game` and `nsgo game`: after `nsgo` it offers `game` and `nsgo`'s own commands, and after `nsgo game` whatever it offers after `game`. `go tool game` is not completed, since there the shell completes `go`. `nsgo` has no completion of its own, so the zsh and bash scripts register one for `nsgo` only while it has none: a completion of `nsgo` registered before the script, found by compinit earlier on `$fpath`, or that bash-completion can load, keeps completing `nsgo`, and a `_nsgo` later on `$fpath` still completes `nsgo`'s commands while `nsgo game` completes the game layer's. The fish script adds completions for `nsgo` that hold only after `nsgo game`, beside any of `nsgo`'s own. Save the script to a file once rather than generating it each time a shell starts, since generating it runs the command. zsh, with the script saved as `_game` in a directory on `$fpath`, which compinit registers for both commands, in `~/.zshrc`: ```zsh fpath=(~/.zfunc $fpath) autoload -Uz compinit && compinit ``` After replacing a script written before it completed `nsgo game`, delete `~/.zcompdump` so compinit reads the new registration. bash, in bash-completion's directory, which loads a completion the first time its command is completed, so the script is saved under both names; without bash-completion, source the file from `~/.bashrc`: ```sh mkdir -p ~/.local/share/bash-completion/completions nsgo game completion bash > ~/.local/share/bash-completion/completions/game ln -s game ~/.local/share/bash-completion/completions/nsgo ``` fish, in its completions directory, which loads a command's completions from the file named after it: ```sh nsgo game completion fish > ~/.config/fish/completions/game.fish ln -s game.fish ~/.config/fish/completions/nsgo.fish ``` Leave out the `nsgo` link when `nsgo` has a completion of its own there. To type `game` alone, install the command with `go install github.com/nsgo-dev/game/cmd/game@latest`, or define `game` as a shell function that runs `nsgo game`, which keeps the version a module's `go.mod` pins inside the module: `game() { nsgo game "$@"; }` in zsh and bash, and `function game; nsgo game $argv; end` in fish. --- Source: https://game.nsgo.dev/docs/cli-reference/ # Command Reference Every subcommand of `nsgo game`, which `go tool game` runs alike, with its usage line and flags, generated from the commands' definitions so it always matches `game help`. [Command Line](https://game.nsgo.dev/docs/cli/) shows how to install the command, what each subcommand is for and how to set up shell completion. ## game pack Pack a folder of PNG images into sprite atlas pages and TexturePacker JSON for sprite.LoadAtlas. ```sh nsgo game pack [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-extrude int` | | edge pixels extruded around each frame | | `-in string` | | input directory of PNG images (required) | | `-max-height int` | `2048` | maximum atlas page height in pixels | | `-max-width int` | `2048` | maximum atlas page width in pixels | | `-name string` | `atlas` | base file name for atlas pages | | `-out string` | `.` | output directory for packed atlas PNG and JSON files | | `-padding int` | `1` | transparent pixels between adjacent frames | | `-scale int` | `1` | atlas scale written to meta.scale | | `-trim` | `true` | trim transparent borders around input images | ## game audio Normalize, resample and convert a WAV file to WAV, AAC or MP3. ```sh nsgo game audio [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-bitrate int` | `128` | target bitrate in kbps for aac and mp3 output | | `-channels int` | | target channel count: 1 (mono), 2 (stereo), or 0 (keep input) | | `-format string` | `wav` | output format: wav, aac, or mp3 | | `-in string` | | input WAV file path (required) | | `-out string` | | output audio file path (required) | | `-peak-db float` | | normalize peak amplitude to this level in dBFS (e.g. -1) | | `-rate int` | | target sample rate in Hz (0 keeps input rate) | | `-rms-db float` | | normalize RMS loudness to this level in dBFS with soft-clip protection (e.g. -14) | ## game manifest Generate a typed Go asset manifest from a directory of assets, so a missing asset fails the build. ```sh nsgo game manifest [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | verify that -out is up to date without modifying it | | `-embed` | | emit //go:embed directives instead of URI references | | `-embed-dir string` | | optional directory prefix prepended to //go:embed patterns | | `-in string` | `assets` | input assets directory | | `-out string` | | output Go file path (writes to stdout when empty) | | `-pkg string` | `assets` | Go package name for the generated file | | `-prefix string` | `asset:` | URI prefix prepended to each asset path | ## game tex Encode a PNG or JPEG texture into a KTX2 container as BC1, BC3, ETC2 or RGBA8, with optional mipmaps. ```sh nsgo game tex [flags] [input.png|input.jpg] ``` | Flag | Default | Description | | --- | --- | --- | | `-format string` | `rgba8` | output format: bc1, bc3, etc2, or rgba8 | | `-in string` | | input PNG/JPEG file path (alternative to the positional argument) | | `-mipmaps` | | generate full mipmap chain down to 1x1 | | `-o string` | | shorthand for -out | | `-out string` | | output .ktx2 path (defaults to the input path with a .ktx2 extension) | | `-srgb` | | encode as sRGB with linear-light mipmap filtering | ## game editor Open the scene editor on a project or a YAML scene, and an animation clip on one of its objects, with the project's own editor command when it has one, or on the start screen when none is named. ```sh nsgo game editor [flags] [project-dir | game.yaml | scene.yaml] [clip.animation.yaml [object-id]] ``` | Flag | Default | Description | | --- | --- | --- | | `-library string` | | show the library panel, which installs packs into the open project, for this library index: an https URL such as https://raw.githubusercontent.com/nsgo-dev/game/main/library/index.yaml, an index file, or a directory holding index.yaml | ## game mcp Serve the editor's MCP tools on stdio, or run \`mcp install\` to configure Claude Code and Codex for this project. ```sh nsgo game mcp [flags] [install] ``` | Flag | Default | Description | | --- | --- | --- | | `-project string` | `.` | the project: its directory, a directory inside it, or its game.yaml | ## game release Build the game's release packages for macOS, Windows, Linux, web, iOS and Android, or game.yaml's export presets, in one run of nsgo build, with a credits file of its assets' licenses. ```sh nsgo game release [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-channel channel` | | the channel the packages are handed out through: direct, store, steam or none (default: nsgo.yaml's updates.channel) | | `-dry-run` | | print the nsgo build command instead of running it | | `-jobs int` | | how many targets build at once (default: nsgo's) | | `-output directory` | | the output directory (default: game.yaml's export.output, else nsgo.yaml's build.output) | | `-release-notes file` | | a Markdown file of the release's notes for the update prompts | | `-target targets` | | comma-separated nsgo build targets (default: game.yaml's export presets, else macos,windows,linux,web,ios,android, or macos,windows,linux for the steam channel) | ## game replay Check the input recordings under the directories and play them headless through their replay tests, failing on a mismatch. ```sh nsgo game replay [flags] [directory ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-run regexp` | `Replay` | run the tests matching this regexp, as go test's -run: the tests that play the recordings | ## game playtest Validate playtest.yaml, run headless bot playtests with replays, write a YAML report and fail on missed goals. ```sh nsgo game playtest [flags] [directory ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | validate playtest.yaml without running any tests | | `-config file` | `playtest.yaml` | the playtest configuration file to validate and run | | `-count int` | | override runs.count in playtest.yaml when positive | | `-out file` | `playtest.report.yaml` | write the YAML playtest report to this file | | `-recordings directory` | `playtest-recordings` | write per-seed .replay.yaml recordings into this directory (empty skips writing files) | | `-run regexp` | `Playtest` | run the tests matching this regexp, as go test's -run: the tests that call playtest.RunTest | | `-seeds seeds` | | override runs.seeds with a comma-separated list of uint64 seeds | ## game bench Run the benchmarks headless and fail when one regresses past its stored baseline, or update the baseline. ```sh nsgo game bench [flags] [directory ...] ``` | Flag | Default | Description | | --- | --- | --- | | `-baseline file` | `benchmarks/baseline.yaml` | the baseline file to check against, or to write with -update | | `-bench regexp` | `.` | run the benchmarks matching this regexp, as go test's -bench | | `-benchtime duration` | `200ms` | run each benchmark for this duration, or Nx times, as go test's -benchtime | | `-count times` | `3` | run the benchmarks this many times and compare each one's median | | `-in file` | | read benchmark results from this file of go test -bench output instead of running the benchmarks | | `-update` | | write the measured medians to the baseline instead of checking them | ## game new Create a game project in a directory from a template, with its go.mod requiring the game layer and the game and nsgo tools. ```sh nsgo game new [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-list` | | list the templates, each with a line describing it, instead of creating a project | | `-module string` | | the module path in go.mod (default: the name in lower case with its words joined by -) | | `-name string` | | the game's display name in game.yaml and nsgo.yaml: letters, digits, spaces, - and \_ (default: the directory's name) | | `-template string` | `starter` | the template to start from: starter, action3d, cards2d, fighting2d, fps3d, idle, platformer2d, puzzle2d, racing3d, rhythm, roguelike2d, rpg2d, rts2d, shmup2d, towerdefense2d, visualnovel; -list describes each | | `-version string` | | the version of github.com/nsgo-dev/game to require, such as v0.4.0, a commit or latest (default: this command's own version, or latest for a development build) | ## game dev Run the game with nsgo dev, reloading its assets in the running game when they are saved. ```sh nsgo game dev [flags] [dir] [nsgo dev flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-assets string` | `resources` | the directory, relative to the project directory, that the running game watches and its assets.Manager reads "asset:" URIs from, given to the game as hotreload.DevAssetsDir | | `-automation` | | enable NSGo automation so the editor and nsgo mcp can inspect and drive the running game | | `-fps` | | show NSGo's performance monitor in the running game | | `-scene string` | | start the game at this scene path relative to the project root, given to the game as hotreload.DevScene | | `-target string` | | the nsgo dev target, nsgo.yaml's dev.target when empty; assets reload on native and tui | ## game check Check the scenes, Tiled and LDtk maps and sprite atlases under a directory, and the files they refer to. ```sh nsgo game check [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-in string` | | directory to check (alternative to the positional argument; defaults to the current directory) | ## game assets Pack atlases, encode textures, convert audio, bake fonts, pack models and generate the manifest from game.yaml, rebuilding only what changed. ```sh nsgo game assets [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-check` | | list the targets that are out of date without building them, and fail if there are any | | `-force` | | rebuild every target, even those the cache says are up to date | | `-in string` | `game.yaml` | project file whose assets section declares the targets | ## game generate Write a new component, system, scene or prefab into a game project: its Go code and a test, the scene file of a scene or prefab, and its registration; or the project's editor command, which checks the project's components and builds in its editor plugins. ```sh nsgo game generate [flags] component|system|scene|prefab | editor ``` | Flag | Default | Description | | --- | --- | --- | | `-autoload` | | for a scene, also add it to the scenes game.yaml autoloads | | `-in string` | `.` | the game's project directory, which holds its game.yaml and the Go package the code is written into | | `-main` | | for a scene, also add it to the scenes game.yaml autoloads and make it the main scene | ## game mv Move or rename a file, directory, or text key (-text-key) and rewrite every reference to it, keeping the project index up to date. ```sh nsgo game mv [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-dry-run` | | print what would change without changing anything | | `-in string` | | project directory (defaults to the nearest directory at or above the working directory holding game.yaml, nsgo.yaml or go.mod) | | `-text-key` | | rename a localization text key across screen files and YAML string tables instead of moving a file | ## game index Give every scene and resource file a uid, point references at files moved without the tools, and write the project index. ```sh nsgo game index [flags] [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-dry-run` | | print what would change without changing anything | | `-in string` | | project directory (alternative to the positional argument; defaults to the nearest directory at or above the working directory holding game.yaml, nsgo.yaml or go.mod) | ## game library Find asset, editor plugin and template packs in a library and install them into a project, remove them, or print a pack's digest for the library's index. ```sh nsgo game library [flags] list [words] | install ... | remove ... | digest ``` | Flag | Default | Description | | --- | --- | --- | | `-dir string` | | install the pack into this directory of the project instead of the one it is installed in or its manifest names (one pack at a time) | | `-index string` | `https://raw.githubusercontent.com/nsgo-dev/game/main/library/index.yaml` | the library's index: an https URL, an index file, or a directory holding index.yaml | | `-kind string` | | list only packs of this kind: asset, plugin, template | | `-project string` | `.` | the project directory holding game.yaml, which install and remove change and list marks installed packs from | ## game credits List every asset's author and license from its import settings sidecar as the credits file game release ships, failing when an asset has none. ```sh nsgo game credits [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-in string` | `game.yaml` | project file whose assets section names the assets | | `-out file` | | the credits file to write (default: print it) | ## game pixelfx Render a pixelfx effect, or the effect acted out, to a PNG sprite sheet and Aseprite JSON for sprite.LoadAtlas. ```sh nsgo game pixelfx [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-act` | | render the effect acted out: the stock character performing it, with its target | | `-flip` | | mirror the effect | | `-fps int` | | frames per second (default: the effect's own, or 60 acted out) | | `-list` | | list the effects and their options instead of rendering one | | `-name string` | | base file name and animation tag (default: the effect's name, such as torch) | | `-out directory` | `.` | the directory to write \.png and \.json into | | `-set name=value` | | set one of the effect's options as name=value, such as seed=4 or palette=#102,#215,#fff; repeat it for more | ## game navmesh Bake a scene's glTF level geometry into a navigation mesh per agent type of game.yaml's navigation section, written to the file the scene's navMesh names. ```sh nsgo game navmesh [flags] ``` | Flag | Default | Description | | --- | --- | --- | | `-in string` | | project directory, whose game.yaml holds the navigation settings and from which the scene's paths start (defaults to the nearest directory at or above the working directory holding game.yaml, nsgo.yaml or go.mod) | | `-out file` | | navigation mesh file to write (defaults to the file the scene's navMesh names) | ## game merge Merge scene YAML files object by object for Git, or set up the Git merge driver in a project. ```sh nsgo game merge [flags] [path] | -setup [dir] ``` | Flag | Default | Description | | --- | --- | --- | | `-conflict-out string` | | file to write the YAML conflict report to instead of overwriting the output file on conflict | | `-out string` | | file to write the merged scene or conflict report to (default: overwrite \ in place, as Git expects) | | `-setup` | | register the nsgo-scene merge driver in local Git config and .gitattributes | ## game completion Write a shell completion script for zsh, bash or fish. ```sh nsgo game completion [flags] zsh|bash|fish ``` No flags. ## game help Show the commands, or one command's flags. ```sh nsgo game help [command] ``` No flags. --- Source: https://game.nsgo.dev/docs/a11y/ # a11y `game/a11y` provides accessibility building blocks built on NSGo's public API: live dialogue and directional SFX captions, color-blind-safe palettes with CVD simulation and WCAG contrast helpers, persisted assist options, and screen-reader-ready native menus. ```go import "github.com/nsgo-dev/game/pkg/a11y" ``` ## Persisted assist options (`Assist`) `NewAssist(cx, key)` stores accessibility preferences in `core.Storage` as reactive values so changes persist across launches and update NSGo views automatically: ```go assist := a11y.NewAssist(cx, "a11y") // In game.Loop.Update, scale simulation dt by GameSpeed (0.25..1.0): loop := &game.Loop{ Update: func(dt time.Duration) { sim.Step(assist.ScaleDT(dt)) }, } ``` Available persisted options on `*Assist` (and snapshot struct `AssistOptions` via `Snapshot()` / `Apply(opts)` / `Reset()`): | Option | Range / Default | Notes | | --- | --- | --- | | `GameSpeed` / `ScaleDT` | `0.25`–`1.0` (`1.0`) | Scales gameplay `dt` without changing display refresh rate. | | `ReduceMotion` | `bool` | Defaults to the OS reduce-motion preference when unset. | | `HighContrast` | `bool` | Defaults to the OS high-contrast preference; switches `assist.Palette()` to `VisionHighContrast`. | | `ColorVision` | `ColorVision` | Selects `VisionNormal`, `VisionProtanopia`, `VisionDeuteranopia`, `VisionTritanopia`, or `VisionHighContrast`. | | `TextScale` | `1.0`–`2.0` (`1.0`) | Multiplier read by `CaptionsView` and `AccessibleMenu`. | | `Invincibility`, `AutoAim`, `HoldToToggle` | `bool` | Gameplay assist flags for your combat and input layers. | | `CaptionsEnabled`, `SFXCaptionsEnabled` | `bool` | Toggle dialogue and sound-effect caption overlays. | ## Live captions (`CaptionTrack` & `CaptionsView`) Queue timed dialogue, directional SFX, music cues, and important alerts on a `CaptionTrack`, step it on `game.Loop`, and render it as a native NSGo overlay with `CaptionsView`: ```go captions := a11y.NewCaptionTrack(cx) // When an explosion plays to the player's right (direction in [-1, 1]): if assist.SFXCaptionsEnabled() { captions.ShowSFXAt("Explosion", 0.8, 2500*time.Millisecond) } captions.ShowDialogue("Guide", "Watch the bridge ahead.", 3*time.Second) // In game.Loop.Update: captions.Update(dt) // In your root Stack view: a11y.CaptionsView(cx, captions, a11y.CaptionStyle{Assist: assist}) ``` `Caption.Format()` formats speakers (`"Guide: ..."`), SFX brackets (`"[Explosion →]"`), and music cues (`"♪ ..."`). Dismiss entries early with `Dismiss(id)` or `Clear()`. ## Color-blind palettes & CVD simulation `PaletteFor(mode)` returns an Okabe-Ito / Wong-grounded semantic `Palette` (`Player`, `Ally`, `Enemy`, `Hazard`, `Pickup`, `Neutral`, `Background`, `Foreground`, `Highlight`, `Accent`). Use `Simulate`, `ContrastRatio`, and `EnsureContrast` in tests or runtime UI theming: ```go pal := assist.Palette() simEnemy := a11y.Simulate(pal.Enemy, a11y.VisionDeuteranopia) ratio := a11y.ContrastRatio(pal.Foreground, pal.Background) readable := a11y.EnsureContrast(accentColor, pal.Background, 4.5) _, _, _ = simEnemy, ratio, readable ``` ## Screen-reader menus (`AccessibleMenu`) Render pause, settings, and assist menus with native ARIA/accessibility roles (`RoleMenu`, `RoleMenuItem`, `RoleMenuItemCheckbox`), full keyboard navigation (`Up`/`Down`/`Home`/`End`/`Return`/`Space`/`Escape`), and `cx.Announce` screen-reader feedback: ```go a11y.AccessibleMenu(cx, a11y.MenuProps{ Label: "Assist Options", Assist: assist, OnClose: closeMenu, Items: []a11y.MenuItem{ { ID: "reduce-motion", Label: "Reduce Motion", Checked: assist.ReduceMotion, OnSelect: func() { _ = assist.SetReduceMotion(!assist.ReduceMotion()) }, }, { ID: "game-speed", Label: "Game Speed", Value: func() string { return fmt.Sprintf("%d%%", int(assist.GameSpeed()*100)) }, OnSelect: cycleGameSpeed, }, }, }) ``` --- Source: https://game.nsgo.dev/docs/ability/ # ability `github.com/nsgo-dev/game/pkg/ability` runs gameplay abilities: costs, cooldowns, charges, cast and channel times and conditions, activated by [input](https://game.nsgo.dev/docs/input/) actions and advanced one fixed [`game.Loop`](https://game.nsgo.dev/docs/loop/) step at a time. ```go import "github.com/nsgo-dev/game/pkg/ability" ``` ## Ability sets Abilities are defined in a versioned YAML file: ```yaml version: 1 abilities: - id: fireball name: ability.fireball action: cast costs: - resource: mana amount: 20 cooldown: 2s castTime: 500ms conditions: [grounded, '!silenced'] - id: dash action: dash cooldown: 250ms charges: 3 recharge: 4s - id: drain action: drain trigger: hold costs: - resource: mana amount: 5 cooldown: 6s channelTime: 3s tickInterval: 500ms ``` | Field | Meaning | | --- | --- | | `id` | Unique within the set: ASCII letters, digits, `_`, `-` and `.`, at most 64 bytes | | `name` | Optional display name or localization key | | `action` | The input action that activates it; empty means only code activates it with `TryActivate` | | `trigger` | `press` (default) tries on the step the action is first pressed; `hold` tries on every step it is held and cancels the cast or channel when it is released | | `costs` | Resources one use spends, each resource once, with a positive `amount` | | `cooldown` | Shortest time between two uses, counted from the step a use takes effect; it applies even while charges remain | | `charges` | Uses stored, 1 when omitted, at most 99; more than one needs a `recharge` | | `recharge` | Time for one spent charge to come back; spent charges come back one after another | | `castTime` | Time spent casting before the ability takes effect | | `channelTime` | Time spent channeling after it takes effect | | `tickInterval` | How often a channel ticks; needs a `channelTime` and must not exceed it | | `conditions` | Names that must all hold to start and to keep casting or channeling; `!name` must not hold | Durations are Go duration strings (`500ms`, `1m30s`) from 0 to 24h. `ability.Parse` refuses unknown fields, duplicate keys and IDs, other versions and out-of-range values; `ability.Encode` writes the fields in a fixed order and durations in their canonical form (`1500ms` becomes `1.5s`), and `Parse` reads its output back to an equal `Set`. ## Caster A `Caster` runs one character's abilities. Make it with the set and the loop's rate, then call `Update` once per step after stepping the input: ```go set, err := ability.Parse(data) if err != nil { return err } hero, err := ability.NewCaster(set, 60) // the same Rate as game.Loop if err != nil { return err } hero.Resources = ability.Pool{"mana": 100, "stamina": 50} hero.Condition = func(name string) bool { switch name { case "grounded": return player.OnGround case "silenced": return player.Silenced } return false } hero.OnEvent = func(e ability.Event) { if e.Kind == ability.EventActivated && e.Ability == "fireball" { spawnFireball() } } loop := &game.Loop{Rate: 60, Update: func(dt time.Duration) { actions.Step() hero.Update(actions) }} ``` `Update` takes anything with `Pressed` and `JustPressed`, such as `*input.Actions`, a replay or a network input; `nil` advances timers without reading input. Code activates abilities with `TryActivate(id)`, which returns `ReasonOK` or the reason it did not: `ReasonUnknown`, `ReasonBusy`, `ReasonCooldown`, `ReasonNoCharges`, `ReasonCondition` or `ReasonCost`, checked in that order. `CanActivate(id)` returns the same reason without changing anything, for greying out a button. At most one ability casts or channels at a time. Its life is: 1. Activation checks the cooldown, charges, conditions and costs, and sends `EventStarted`. 2. The cast runs for `castTime`, nothing spent yet. A failing condition interrupts it (`EventInterrupted` with `ReasonCondition`), and `Cancel` stops it (`EventCanceled`), both spending nothing. 3. When the cast completes, the costs and a charge are spent, the cooldown starts and `EventActivated` is sent; this is where the game applies the effect. A cost that is no longer affordable interrupts it with `ReasonCost` instead. An ability with no cast time does this on the step it is activated. 4. A channel then runs for `channelTime`, sending `EventChannelTick` every `tickInterval` and `EventChannelEnded` at the end. Conditions, `Cancel` and releasing a `hold` action stop it early. `EventCooldownEnded` and `EventChargeRestored` report timers finishing. `OnEvent` may call `TryActivate` or `Cancel`, for example to chain a follow-up when an ability takes effect; the events that causes follow the current one. Events that happened before a `Reset` or `Restore` called from `OnEvent` are still delivered, and when that call is made during `Update`, `Update` goes on to read input against the reset or restored state. `Status(id)` reports charges, remaining cooldown and recharge, and the cast or channel progress in steps, and `Duration(steps)` converts them to game time for a cooldown bar. `Active()` reports the ability casting or channeling now. ### Costs and conditions `Resources` is an interface with `Amount` and `Spend`, so costs can draw on the game's own stats. `ability.Pool` is a ready map-based one. Every cost of a use is checked before any is spent. With a nil `Resources`, abilities with costs cannot be activated; with a nil `Condition`, every condition is false. ## Determinism `NewCaster` turns each duration into whole steps at its rate, rounding up, and every timer counts whole steps. At 60 Hz, `game.Loop`'s `dt` is 16,666,666 ns, so summing it would take 121 steps to reach 2 s; a `Caster` puts a 2 s cooldown at exactly 120 steps. Within a step, `Update` advances every cooldown and recharge in set order, then the active cast or channel, then reads input, so an ability whose cooldown ends on a step can be used again on that same step. When several abilities share an action, they are tried in set order and the first that activates wins, which lets conditions pick between them. The same inputs on the same steps therefore give the same events on the same steps on every machine. `Snapshot` returns a `State` (step counts, JSON and YAML tags) for save slots, rollback and replays, and `Restore` puts it back, refusing a state from another set or rate. `Update` does not allocate. --- Source: https://game.nsgo.dev/docs/accounts/ # accounts `github.com/nsgo-dev/game/pkg/accounts` is a self-hostable player account service. A player starts as a guest, upgrades to an email address or links an OAuth or platform identity (Game Center, Play Games, Steam) without losing their data, and every device gets short-lived tokens a game server verifies offline. The service is server-side code in its own packages. A game client or game server that does not import them links none of their dependencies (argon2id from `golang.org/x/crypto`, the SQLite and Postgres drivers); a game server that verifies tokens imports only `accounts/token`, which needs the standard library and the YAML package. | Package | What it holds | | --- | --- | | `accounts` | `Service`, `Config`, the `Store` interface, `MemoryStore`, argon2id password hashing and the HTTP `Handler` | | `accounts/token` | Ed25519 token `Signer` and offline `Verifier`, the `KeySet` YAML file and PEM signing keys | | `accounts/sqlitestore` | A `Store` in a SQLite file (pure Go, no cgo); every target but the web | | `accounts/pgstore` | A `Store` in Postgres, shared by several service processes | | `accounts/sqlstore` | The SQL schema and queries both stores share | | `accounts/storetest` | The `Store` contract tests, for a store of your own | | `accounts/cmd/accountsd` | A standalone HTTP server for guests and email accounts | ## Accounts, sessions and tokens An account is a permanent random ID. Key everything the game keeps for a player (saves, progress, purchases) by that ID: linking an email address or an identity never changes it, so a guest who upgrades keeps their data. Every sign-in returns `Credentials`: - `Session` is a long-lived secret the device stores. It gets new tokens with `Refresh` and is revoked by `SignOut`. For a guest it is the only way back into the account. - `Token` is a short-lived signed token the game sends its server. It expires after the configured `tokenTTL`. - `Created` reports whether the sign-in created the account. ```go svc, err := accounts.New(cfg, accounts.Options{ Store: store, Key: key, // from token.ParsePrivateKey Identities: map[string]accounts.IdentityVerifier{"gamecenter": gameCenter, "steam": steam}, Logger: slog.Default(), }) guest, _ := svc.CreateGuest(ctx) // play at once _ = svc.LinkEmail(ctx, guest.AccountID, "ada@example.com", pass) // upgrade, same ID again, _ := svc.SignInEmail(ctx, "ada@example.com", pass) // a second device fresh, _ := svc.Refresh(ctx, again.Session) // a new token ``` | Method | What it does | | --- | --- | | `CreateGuest` | A new account with neither an email address nor an identity (`ErrGuestsDisabled` with `disableGuests`) | | `Register` | A new account with an email address and password | | `LinkEmail` | Gives an account without one an email address and password | | `SignInEmail` | Signs in with an email address and password | | `SignInIdentity` | Signs in with a provider credential, creating the account when the identity is new | | `LinkIdentity` | Links a provider identity to an account | | `Refresh` / `SignOut` | A new token for a session / revokes the session | | `Profile` | The account, its email address and its identities; `Profile.Guest` reports a guest | Errors are `ErrNotFound`, `ErrTaken` (the address or identity belongs to another account), `ErrAlreadyLinked`, `ErrInvalidCredentials` (never saying whether the address, the password or the session was wrong), `ErrInvalidEmail`, `ErrWeakPassword` and `ErrUnknownProvider`. ## Identities An `IdentityVerifier` turns a credential from the device into the provider's stable subject for the player: ```go steam := accounts.IdentityVerifierFunc(func(ctx context.Context, ticket string) (string, error) { return steamWebAPI.AuthenticateUserTicket(ctx, ticket) // the SteamID }) ``` A Game Center verifier checks the signed identity against Apple's certificate, a Play Games verifier exchanges the server auth code, a Steam verifier authenticates the session ticket with the Steam Web API, and an OAuth provider's verifier checks the OpenID Connect ID token. Those need the platforms' credentials, so the game supplies its verifiers under provider names of its choosing (`a-z`, `0-9`, `.`, `_`, `-`, up to 32 characters). Linking an identity lets a second device sign in to the same account with `SignInIdentity`. An account has at most one identity per provider, and an identity belongs to one account: linking one that another account has returns `ErrTaken`. Two devices signing in with a new identity at the same time get one account between them. The service never shows a verifier's error to the caller or logs it, since it may quote the credential; the caller gets `ErrInvalidCredentials`. ## Verifying tokens on a game server A token is a compact JWT signed with Ed25519 (`"alg": "EdDSA"`) holding the issuer, the account ID as subject, the audience, the issue and expiry times and a random ID. The game server loads the service's public keys from a key set file and verifies each token without a network call: ```go data, _ := os.ReadFile("keys.yaml") ks, err := token.ParseKeySet(data) v, err := token.NewVerifier(ks) v.Leeway = 5 * time.Second // clock skew between the two machines claims, err := v.Verify(tok) if err != nil { /* refuse the player */ } player := claims.Subject // the account ID ``` `Verify` checks the signature, the issuer, the audience and the expiry, and its errors wrap `ErrMalformed`, `ErrUnknownKey`, `ErrSignature`, `ErrIssuer`, `ErrAudience`, `ErrExpired` or `ErrNotYetValid`. Tokens longer than `MaxLength` are refused before any work. A revoked session stops getting new tokens, but tokens already issued stay valid until they expire, so keep `tokenTTL` short. The key set file: ```yaml version: 1 issuer: https://accounts.example.com audience: my-game keys: - id: 2317febd373fcbcd key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg= ``` Each `id` is the first 8 bytes of the key's SHA-256 in hex and must match its key. To rotate the signing key, add the new key beside the old one, give game servers the new file, switch the service to the new key, and drop the old key once its last tokens have expired. Give the service the old keys too, as `Options.KeySet` (or `accountsd serve -keyset keys.yaml`): it then accepts bearer tokens signed with any key in the set, and `GET /v1/keys` serves the signing key followed by those keys, so tokens issued before the restart keep working on the service and on game servers until the old key is removed from the file. ## Configuration The service reads a versioned YAML file: ```yaml version: 1 issuer: https://accounts.example.com audience: my-game tokenTTL: 15m password: minLength: 10 argon2id: time: 2 memoryKiB: 19456 threads: 1 ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `issuer` / `audience` | Written into every token and checked by verifiers | | `tokenTTL` | Token lifetime, whole seconds from `1s` to `24h` | | `disableGuests` | Refuses `CreateGuest`, so every account starts with an email address or an identity | | `password.minLength` | Fewest characters in a password, at least 8; passwords are at most 1024 bytes | | `password.argon2id` | The argon2id cost: passes, memory in KiB and lanes | `ParseConfig` refuses unknown fields, trailing documents and out-of-range values. `Config.Marshal` writes the canonical form: the fields in the order above, durations in their shortest text (`15m`, not `15m0s`) and `disableGuests` only when it is true. A file in that form, such as one `Marshal` or `accountsd init` wrote, reads back and writes again unchanged; a hand-written file in another order or spelling is normalized. `DefaultConfig` returns the settings shown. ## Passwords and secrets - Passwords are stored only as argon2id hashes in the PHC format (`$argon2id$v=19$m=19456,t=2,p=1$salt$hash`), OWASP's recommended cost by default. A sign-in with a password hashed at an older cost rehashes it at the configured one. `Options.MaxConcurrentHashes` bounds how many hashes run at once, so a burst of sign-ins cannot take all the server's memory. - An unknown email address takes as long to refuse as a wrong password, so sign-in does not reveal whether an address has an account. `Register` and `LinkEmail` do: they answer `ErrTaken` (`409 taken`) for an address that belongs to an account, so anyone can test an address there without its password. Rate-limit those requests per client. - Session secrets are 256 random bits; the store keeps only their SHA-256. - `Credentials.Session` and `Credentials.Token` are `Secret` values, which print, log and marshal as `[redacted]`; `Reveal` returns the value for the one place that sends it. The service logs account events (created, signed in, linked) with account IDs and provider names, never a password, session secret, token or identity credential. - Signing keys are PKCS #8 PEM files written with mode `0600`; a Postgres DSN is read from the environment, not the command line. ## Storage `Store` is the interface the service keeps its records in. Implementations enforce uniqueness atomically, so two devices racing to claim one email address or identity cannot both succeed. ```go store, err := sqlitestore.Open(ctx, "accounts.db") // one service process store, err := pgstore.Open(ctx, os.Getenv("ACCOUNTS_POSTGRES_DSN")) // several processes ``` `sqlitestore` uses the pure-Go `modernc.org/sqlite` driver with write-ahead logging and one connection; `pgstore` uses `github.com/jackc/pgx/v5` and takes an advisory lock while it creates the schema. Both create their tables when missing and refuse a database whose schema is newer than they know. `NewMemoryStore` keeps everything in memory for tests and prototypes. A store of your own passes `storetest.Run`: ```go func TestContract(t *testing.T) { storetest.Run(t, func(t *testing.T) accounts.Store { return openEmptyStore(t) }) } ``` ## HTTP `Service.Handler` serves the service with JSON bodies; every response carries `Cache-Control: no-store`: | Request | Body | Answer | | --- | --- | --- | | `POST /v1/guest` | | credentials | | `POST /v1/register` | `{"email", "password"}` | credentials | | `POST /v1/signin/email` | `{"email", "password"}` | credentials | | `POST /v1/signin/identity` | `{"provider", "credential"}` | credentials | | `POST /v1/refresh` | `{"session"}` | credentials | | `POST /v1/signout` | `{"session"}` | 204 | | `POST /v1/link/email` | `{"email", "password"}`, with a bearer token | 204 | | `POST /v1/link/identity` | `{"provider", "credential"}`, with a bearer token | 204 | | `GET /v1/me` | bearer token | profile | | `GET /v1/keys` | | the key set as YAML | Credentials are `{"account", "session", "token", "expires", "created"}`, with status 201 when the account is new. Errors are `{"error": code}`: `invalid_credentials` and `invalid_token` 401, `guests_disabled` 403, `not_found` 404, `taken` and `already_linked` 409, `request_too_large` 413, `bad_request`, `invalid_email`, `weak_password` and `unknown_provider` 400, `unavailable` 503 when the request was cancelled or timed out (for example while waiting for a password hash slot under load), and `internal` 500. Request bodies are limited to 32 KiB and unknown fields are refused. The handler does not limit request rates: run it behind TLS and a rate limiter. ## accountsd `accounts/cmd/accountsd` runs the service for guests and email accounts: ```sh accountsd init -config accounts.yaml -issuer https://accounts.example.com -audience my-game accountsd genkey -config accounts.yaml -key key.pem -keyset keys.yaml accountsd serve -config accounts.yaml -key key.pem -keyset keys.yaml -sqlite accounts.db -addr :8080 ACCOUNTS_POSTGRES_DSN=postgres://... accountsd serve -config accounts.yaml -key key.pem -keyset keys.yaml -postgres ``` `init` never overwrites a configuration and `genkey` never overwrites a key. `genkey` adds the new public key to the key set file, the first step of a rotation; it replaces the file through a temporary file and a rename, so a game server reading it never sees half of it, and it removes the new key again when the key set cannot be written. `serve -keyset` accepts and serves every key in the key set, so tokens signed with an old key keep working on the service after a rotation. `serve` logs JSON to stderr and stops on SIGINT or SIGTERM. A game that links platform identities builds its own command around `accounts.New` with its verifiers. --- Source: https://game.nsgo.dev/docs/achievements/ # Achievements ```go import "github.com/nsgo-dev/game/pkg/achievements" ``` `achievements` declares a game's achievements once, in a versioned YAML file, tracks the player's progress toward them, and reports that progress through NSGo's [`gameservices`](https://nsgo.dev/docs/services/#game-services) package: Game Center on macOS, iOS and tvOS, and Google Play Games Services on Android. It uses only Go's standard library, NSGo's public API and the YAML library the module already depends on. ## The achievements file Each achievement has a game-wide `id` that game code uses, and the ID each platform service knows it by. Game Center IDs are chosen by the developer in App Store Connect and Play Games IDs are generated by Play Console, so each is written out; an achievement without an ID for a service is not reported to that service. ```yaml version: 1 achievements: - id: first-match title: First Match description: Clear your first line of gems. platforms: gameCenter: com.example.mygame.first_match playGames: CgkIxxxxxxxxxxEAIQAQ - id: gem-collector title: Gem Collector description: Clear 300 gems. steps: 300 platforms: gameCenter: com.example.mygame.gem_collector playGames: CgkIxxxxxxxxxxEAIQAg - id: high-roller title: High Roller hidden: true platforms: gameCenter: com.example.mygame.high_roller ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `id` | 1 to 128 ASCII letters, digits, `.`, `_` or `-`, unique in the file | | `title`, `description` | Optional text for the game's own UI; the platform screens show what their consoles hold | | `hidden` | The game's own UI should not reveal the achievement before it is unlocked | | `steps` | Steps that complete the achievement, 1 to `MaxSteps`; omitted means 1, a one-shot achievement | | `platforms.gameCenter`, `platforms.playGames` | The achievement's ID on each service: no whitespace or control characters, at most 255 bytes, and not shared by two achievements on the same service | `Parse` refuses unknown fields, a version other than 1, trailing YAML documents, duplicate IDs and malformed platform IDs. `Encode` writes deterministic 2-space YAML in the order above, and a file `Encode` wrote parses and encodes back to the same bytes, so a test can keep the file canonical: ```go //go:embed achievements.yaml var achievementsYAML []byte set, err := achievements.Parse(achievementsYAML) out, err := achievements.Encode(set) // equal to achievementsYAML when the file is canonical ``` ## Tracking progress A `Tracker` holds the steps the player has made toward each achievement of a `Set`. Progress only moves forward. - `Unlock(id)` completes an achievement; unlocking a completed one does nothing. - `Add(id, n)` adds steps and saturates at the achievement's step count; `SetSteps(id, n)` raises progress to `n` and ignores a lower count. - `Steps`, `Percent`, `Unlocked` and `Lookup` read the state; `Definitions` lists the achievements in declared order. - `OnUnlock(fn)` is called once when an achievement completes through `Unlock`, `Add` or `SetSteps`, never when progress is restored. - An ID the set does not declare returns an error wrapping `ErrUnknownAchievement`. ```go tracker, err := achievements.NewTracker(set) tracker.OnUnlock(func(d achievements.Definition) { status.Set("Achievement unlocked: " + d.Title) }) tracker.Unlock("first-match") tracker.Add("gem-collector", cleared) ``` The Tracker's methods are safe for concurrent use, and its callbacks run without its lock held, so they may call back into it. ## Saving progress `Persist(store, key)` loads the progress stored under `key`, if any, and from then on writes it back after every change. `core.Storage` is a `Store`, as is any type with `GetItem` and `SetItem`. When the stored progress cannot be parsed, `Persist` returns the error and changes nothing, so the game decides whether to discard it: ```go store := cx.Storage() if err := tracker.Persist(store, "mygame.achievements"); err != nil { store.RemoveItem("mygame.achievements") err = tracker.Persist(store, "mygame.achievements") } ``` The stored progress is a versioned YAML document, sorted by ID, holding the steps made and, per service, the steps that service last acknowledged: ```yaml version: 1 achievements: - id: first-match steps: 1 reported: gameCenter: 1 - id: gem-collector steps: 42 ``` `Progress` and `Restore` give and replace the same state in memory, and `ParseProgress` and `EncodeProgress` read and write it with the same rules as the achievements file. Restoring drops records for achievements the set no longer declares and caps steps at an achievement's step count. A failed save keeps the progress in memory and returns an error wrapping `ErrSave`; the next successful write saves it. ## Reporting to Game Center and Play Games `SignIn(cx, tracker, done)` picks the service for the running platform with `ServiceFor`, signs the player in with `gameservices.Authenticate` and, once the player is signed in, connects the Tracker to that service, which reports everything the service has not acknowledged. `done` runs on the engine goroutine with the player or the error: - `gameservices.ErrUnsupported` where the platform has no game service (Windows, Linux, the web, watchOS) or `cx.Env().CanUseGameServices()` is false. - `gameservices.ErrUnauthenticated` when the service answers without a signed-in player, and `gameservices.ErrCancelled` when the player dismisses sign-in. On failure the Tracker keeps counting, and a later `SignIn` reports what was made in the meantime. Answers from the service arrive through `cx`, so disposing `cx` or letting its current owner run again, as a view body does on every render, disconnects the Tracker; sign in from an event handler or an effect, or with a scope that lives as long as the game, such as the root scope, or call `SignIn` again from the next screen. `gameservices.ShowAchievements(cx)` opens the platform's own achievements screen. ```go signedIn := core.NewSignal(cx, false) achievements.SignIn(cx, tracker, func(_ gameservices.Player, err error) { signedIn.Set(err == nil) }) core.Show{ When: signedIn.Get, Then: func(*core.Scope) core.Node { return ui.Button{Text: "Achievements", OnPress: func() { gameservices.ShowAchievements(cx) }} }, } ``` The Tracker remembers, per service, the steps the service last acknowledged, so progress made offline or before sign-in is reported once a service is connected, and progress the service already has is not sent again. While a report is waiting for an answer, further progress on that achievement is held back and sent as one follow-up report, so a run of `Add` calls does not flood the service. A failed report stays pending: `OnError` receives it, and the next change, `Flush` or `Connect` sends it again. `Pending(service)` lists what a service has not acknowledged. Progress goes to the service as a percentage: a 300-step achievement with 42 steps is reported as 14%. Configure it in Play Console as a standard achievement, not an incremental one, since `gameservices` reports percentages. `Connect(service, reporter)` and `Disconnect` attach and detach a service directly, for a game that signs in by other means; `GameServices(cx)` is the `Reporter` backed by `gameservices.ReportAchievement`, and any type with a `ReportAchievement(id, percent, done)` method is a `Reporter`. A `Reporter` must answer every report exactly once; `GameServices(cx)` stops answering once `cx` is disposed, so call `Disconnect` then. ## Platform setup - **Game Center**: enable Game Center for the app's ID and create each achievement in App Store Connect, using the IDs in `platforms.gameCenter`. NSGo does not yet add the Game Center entitlement to the app it builds. - **Play Games**: create each achievement in Play Console and copy its generated ID into `platforms.playGames`. NSGo's `gameservices` has its Android side in place, but the Java runtime hook that reaches Play Games Services is not in NSGo's runtime yet, so `CanUseGameServices` is false on Android today and `SignIn` answers `ErrUnsupported` there; progress is still kept and is reported once that hook ships. ## Testing NSGo's `nsgotest` gives each test app an in-memory game services fake. Enable it with `nsgotest.Environment(core.Environment{OS: core.OSAndroid, CanUseGameServices: true})`, sign a player in with `App.SetGameServicesPlayer`, and read what was reported with `App.GameServicesAchievements`: ```go app := nsgotest.Start(t, root, nsgotest.Environment(core.Environment{OS: core.OSMacOS, CanUseGameServices: true})) app.SetGameServicesPlayer(gameservices.Player{ID: "p1", DisplayName: "Ada"}) // ... play until the achievement unlocks ... app.Settle() got := app.GameServicesAchievements() // [{ID: "com.example.mygame.first_match", PercentComplete: 100, Unlocked: true}] ``` `App.SetGameServicesError` and `App.SetGameServicesAuthError` simulate an outage or a cancelled sign-in. The [SlideGem example](https://github.com/nsgo-dev/game/tree/main/examples/slidegem) unlocks its first achievement on Game Center and on Play Games this way. --- Source: https://game.nsgo.dev/docs/agent-eval/ # Agent Evaluation Suite The agent evaluation suite under `tools/agenteval/` is contributor tooling with fixed game-development tasks. Each task has a starter workspace, a hand-written reference solution and a rubric that scores a workspace from 0 to 100 with YAML checks, `assetcheck`, `nsgo check` and live headless `game/mcp` tools. It supports three modes: deterministic `reference` grading (API and format regression checks with no model or key), built-in tool-calling `agent` grading (Anthropic Messages API or OpenAI-compatible Chat Completions API), and `command` grading for any external coding agent CLI. ## Tasks Each task is a plain-text versioned YAML document (`version: 1`) under `tools/agenteval/tasks/`, with unknown fields refused and deterministic round-trip encoding: | Task ID | Goal | What the rubric grades | | --- | --- | --- | | `platformer-level` | Build a platformer level | Valid `game.yaml` and `scenes/level1.scene.yaml`, `assetcheck.Check`, platforms from `player_spawn` to `goal` with no horizontal gap above `max_gap` and no vertical step above `max_rise`, `nsgo check`, and live MCP checks that holding the `right` action through `game_input_action` moves the player toward the goal over 60 fixed steps | | `add-enemy-type` | Add an enemy type | Valid `game.yaml` and `scenes/arena.scene.yaml`, `assetcheck.Check`, an enemy object (`prefab: enemy`, an `enemy` component or `tag: enemy`) carrying an `enemy` component, `nsgo check`, and live MCP checks that the `"enemy"`-tagged entity moves across 60 fixed steps | | `add-menu` | Add a menu | Valid `game.yaml`, `scenes/menu.scene.yaml` and `scenes/gameplay.scene.yaml`, `assetcheck.Check`, a visible screen-space layer with at least two buttons (`prefab: button` or a `button` component), `nsgo check`, and live MCP checks of `game_scenes_list` and `game_layers_list`, then a click on Play through `game_input_pointer` that must switch to `gameplay` | ## Scoring rubric Every task spreads 100 points across five criteria in `checks.weights`: 1. **`yaml_valid`** (15 pts): every listed `game.yaml` and `*.scene.yaml` parses and round-trips deterministically through `project.Encode` or `sceneformat.Encode`. 2. **`project_check_passes`** (15 pts): `assetcheck.Check` reports zero problems across scenes, maps and references. 3. **Domain check** (`level_geometry_valid`, `enemy_definition_present` or `menu_scene_valid`, 25 pts): the task's scene geometry, enemy definition or menu buttons. 4. **`builds_cleanly`** (15 pts): `go tool nsgo check` succeeds on the workspace against the checkout's root module. 5. **`mcp_verify_passes`** (30 pts): a generated test boots the game headless under `nsgotest.Start`, calls live `game/mcp` tools through `nsgo/automation.Call`, and must report a pass; a clean exit without it scores nothing. The documents a task lists in `context_docs` and the repository's [Agent Skill](https://game.nsgo.dev/docs/agent-skill/) (`skills/nsgo-game/SKILL.md` and `references/`) are not scored. They are copied next to the workspace for the agent, and a missing or empty doc or skill fails the run. `min_score` sets a task's passing score; when it is absent the threshold is 100, and an explicit `0` is kept. ## Running locally ### Reference mode (default) Grades each task's reference solution against the checkout, with no model or API key: ```sh go run ./tools/agenteval ``` Write a JSON report, a standalone Markdown report, and append to a step summary file: ```sh go run ./tools/agenteval -out agent-eval-report.json -markdown-out agent-eval-summary.md -summary summary.md ``` Run some tasks or change the passing score: ```sh go run ./tools/agenteval -task platformer-level,add-menu -min-score 80 ``` ### Agent mode (built-in coding agent) Runs a built-in multi-turn tool-calling agent (`-mode=agent`) against each task's starter workspace, staged docs, Agent Skill (`skills/nsgo-game/`), and MCP config (`mcp.json`), then grades what the agent leaves with the same rubric: ```sh ANTHROPIC_API_KEY=... go run ./tools/agenteval \ -mode=agent \ -min-score=80 \ -out agent-eval-agent-report.json \ -markdown-out agent-eval-agent-summary.md ``` It supports both the Anthropic Messages API (`-agent-provider=anthropic`) and OpenAI-compatible Chat Completions APIs (`-agent-provider=openai`), or `-agent-provider=auto` (default), which selects a provider from `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AGENT_EVAL_API_KEY` (with optional `-agent-model`, `-agent-base-url`, and `-agent-max-turns`, or the matching `AGENT_EVAL_*` environment variables). The built-in agent operates strictly inside the staged temporary directories through five tools (`list_files`, `read_file`, `write_file`, `edit_file`, `run_command`), refuses symlinks and path traversal, and scrubs API keys and CI tokens from `run_command`'s environment. Pass `-skip-if-unconfigured` to emit a skipped report and exit `0` when no API key is configured. ### Command mode (external coding agent CLI) Copies each task's starter workspace, context docs, and Agent Skill into a temporary directory, writes the prompt to `$AGENTEVAL_PROMPT_FILE` and an MCP client config to `$AGENTEVAL_MCP_CONFIG`, runs `-agent-cmd` (or `$AGENT_EVAL_COMMAND`) in the workspace, and grades what the agent leaves with the same rubric: ```sh go run ./tools/agenteval \ -mode=command \ -min-score=80 \ -agent-timeout=20m \ -agent-cmd='my-agent --prompt "$AGENTEVAL_PROMPT_FILE" --mcp-config "$AGENTEVAL_MCP_CONFIG"' ``` The agent gets a temporary `go.work` (in `GOWORK`) that resolves `github.com/nsgo-dev/game` to the checkout, so it can run `go tool nsgo check` and `go tool nsgo test ./...` while it works. It gets no path into the repository, whose fixtures hold the reference solutions. `-agent-timeout` (default 15 minutes) bounds the agent and `-timeout` (default 5 minutes) bounds grading, so a slow agent shows up as `agent_timed_out` in the report rather than as build failures. Environment variables passed to `-agent-cmd` (and `run_command` in `-mode=agent`): - `AGENTEVAL_TASK_ID`: the task identifier, such as `platformer-level`. - `AGENTEVAL_TASK_TITLE`: the task title. - `AGENTEVAL_PROMPT_FILE`: the Markdown prompt. - `AGENTEVAL_WORKSPACE`: the staged starter workspace. - `AGENTEVAL_CONTEXT_DIR`: the directory holding the copied context docs and skill at their repository paths, such as `docs/en/mcp.md` and `skills/nsgo-game/SKILL.md`. - `AGENTEVAL_SKILL_DIR`: the staged `skills/nsgo-game` directory. - `AGENTEVAL_SKILL_FILE`: the staged `skills/nsgo-game/SKILL.md` file. - `AGENTEVAL_MCP_CONFIG`: a ready-to-use `mcp.json` pointing at `go tool nsgo mcp`. - `AGENTEVAL_DOCS`: the context doc paths, comma-separated. - `GOWORK`: the temporary `go.work`. ## Scheduled CI `.github/workflows/agent-eval.yml` runs daily on Depot (`depot-ubuntu-24.04-4`), on demand through `workflow_dispatch`, and when `tools/agenteval/**`, `skills/nsgo-game/**` or the workflow itself changes. It has two jobs: 1. **`eval` (reference)**: runs on pull requests, pushes to `main`, `schedule`, and `workflow_dispatch`. It runs `go tool nsgo test ./...` in `tools/agenteval`, grades the reference solutions with `-mode=reference`, appends the per-task score table and criterion breakdown to `$GITHUB_STEP_SUMMARY`, and uploads `agent-eval-reference-report` (`agent-eval-reference-report.json` and `agent-eval-reference-summary.md`). 2. **`eval-agent` (coding agent)**: runs on `schedule` and `workflow_dispatch` (never on untrusted pull requests). When configured with repository secrets or variables, it runs an actual coding agent on the starter workspaces against the staged docs, skill, and MCP config, reports per-task scores, turns/tool counts, and criterion breakdowns to `$GITHUB_STEP_SUMMARY`, and uploads `agent-eval-agent-report` (`agent-eval-agent-report.json` and `agent-eval-agent-summary.md`). In `auto` / scheduled mode, if no credentials are configured yet, it runs with `-skip-if-unconfigured` so CI records a clear `SKIPPED` summary instead of failing. Repository secrets and variables read by `eval-agent`: - **Secrets**: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `AGENT_EVAL_API_KEY` (for `-mode=agent`), or `AGENT_EVAL_COMMAND` (to run a custom agent CLI via `-mode=command`). - **Variables**: `AGENT_EVAL_COMMAND`, `AGENT_EVAL_PROVIDER` (`auto`, `anthropic`, `openai`), `AGENT_EVAL_MODEL`, `AGENT_EVAL_BASE_URL`, `AGENT_EVAL_MAX_TURNS`, and `AGENT_EVAL_MIN_SCORE`. --- Source: https://game.nsgo.dev/docs/agent-skill/ # Agent Skill The repository publishes an Agent Skill at [`skills/nsgo-game`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/SKILL.md) so coding agents know how to scaffold, build, test, inspect and drive NSGo games using the `nsgo game` CLI, plain-text YAML formats and the `game/mcp` tool suite. ## Install Install the skill with `bunx skills add`: ```sh bunx skills add nsgo-dev/game ``` Pair it with NSGo's own `nsgo` skill for core UI primitives, signals, `nsgotest` and `go tool nsgo`: ```sh bunx skills add nsgo-dev/nsgo ``` To let an agent inspect and drive a running game live, also register NSGo's MCP server: ```sh claude mcp add nsgo -- go tool nsgo mcp ``` ## What the skill covers - **[`SKILL.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/SKILL.md)**: project rules (Go only, plain-text versioned YAML formats, `go tool nsgo check`/`test`, stability tiers), quick-start CLI workflow, minimal `game.Loop` + `mcp.Attach` wiring, and the deterministic MCP verification loop. - **[`references/packages.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/references/packages.md)**: complete grouped catalog of every package in `github.com/nsgo-dev/game`, with import paths and stability status matching [API Stability](https://game.nsgo.dev/docs/stability/). - **[`references/cli-and-formats.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/references/cli-and-formats.md)**: all `nsgo game` subcommands ([Command Reference](https://game.nsgo.dev/docs/cli-reference/)), companion module tools, the YAML format contract ([File Formats](https://game.nsgo.dev/docs/formats/)), JSON Schemas ([Schemas](https://game.nsgo.dev/docs/schemas/)) and native external formats (Tiled, LDtk, Aseprite, TexturePacker, BMFont, glTF, Yarn). - **[`references/mcp-tools.md`](https://github.com/nsgo-dev/game/blob/main/skills/nsgo-game/references/mcp-tools.md)**: `mcp.Bridge` setup ([mcp](https://game.nsgo.dev/docs/mcp/)) and the full tool catalog covering scene/entity inspection, fixed-step loop control, game-coordinate input, live spawning and component editing, screenshots with diagnostic overlays, debug console tunables, input recording/replay, performance telemetry and live asset hot reload. ## Typical agent workflow 1. Scaffold and add building blocks with `nsgo game new`, `nsgo game generate`, `nsgo game assets` and `nsgo game check`. 2. Attach `mcp.Bridge` on the game's `*core.Scope` and run `go tool nsgo dev -automation` (or `nsgotest.Start` in tests). 3. Drive reproducible checks through MCP: pause with `game_loop_pause`, seed with `game_loop_seed`, inject inputs or spawn entities, advance synchronously with `game_loop_step`, inspect entities with `game_entities_list` / `game_entity_inspect` / `game_component_get`, and capture overlays with `game_screenshot`. --- Source: https://game.nsgo.dev/docs/ai/ # ai `game/ai` provides deterministic game AI building blocks stepped cleanly on `game.Loop`: grid `AStar` pathfinding, `HPA` hierarchical pathfinding, `JPS` Jump Point Search, generic `GraphSearch` (A*, Dijkstra, and budgeted movement ranges with paths over hex tilemaps, waypoint graphs, or custom graphs), 2D `NavMesh` navigation with funnel smoothing, steering behaviors, velocity-based local avoidance (ORCA) in 2D and 3D XZ, behavior trees, utility AI scoring, goal-oriented action planning (GOAP), attack tokens and squads, spatial influence maps, EQS-style tactical position queries with cover points and reservations, and perception with sight, hearing and memory. ```go import "github.com/nsgo-dev/game/pkg/ai" ``` Nothing in `ai` uses background goroutines or hidden global randomness. ## Grid A* pathfinding `AStar` searches any `Grid` or weighted `CostGrid` (`BoolGrid`, `CostMap`, or the adapter `GridFunc`), reusing its internal buffers across calls: ```go grid := ai.GridFunc{ Cols: levelMap.Width, Rows: levelMap.Height, Walk: func(col, row int) bool { return levelMap.FlagsAt(col, row)&tilemap.TileSolid == 0 }, Cost: func(col, row int) float64 { if isMud(col, row) { return 2.5 } return 1 }, } astar := ai.NewAStar() astar.Diagonal = true // NoCornerCutting is true by default path, cost, ok := astar.Find(grid, ai.Cell{Col: 1, Row: 1}, ai.Cell{Col: 18, Row: 10}) _, _ = path, cost _ = ok ``` Use `astar.FindInto(dst, grid, start, goal)` to reuse a caller-owned `[]ai.Cell` buffer with zero allocations per search. `NewBoolGrid` and `NewCostMap` provide flat-slice grids when you do not already have a tilemap. ### Line-of-sight path smoothing and any-angle search Tile-grid A* paths step from cell to cell and look jagged when followed with `FollowPath`. Convert a cell path into smooth world-space waypoints with `SmoothGridPath` or the buffer-reusing `SmoothGridPathInto`: ```go opts := ai.GridPathOptions{ Origin: core.Point{X: 0, Y: 0}, CellSize: 16, Radius: 6, // keep circular body radius clear of every blocked cell } rawCells, _, ok := astar.FindInto(cellBuf, grid, startCell, goalCell) if ok { waypoints = ai.SmoothGridPathInto(waypoints, grid, rawCells, opts) } ``` - **Radius-aware line of sight**: `SmoothGridPath` / `SmoothGridPathInto` drops intermediate cells whenever the straight segment between kept waypoints stays at least `Radius` away from every blocked cell (`!grid.Walkable(col, row)`). Set `CellWidth` / `CellHeight` instead of `CellSize` for rectangular tiles, and call `ai.GridLineOfSight(grid, a, b, opts)` or `opts.CellCenter(cell)` directly when needed. - **Zero-allocation buffer reuse**: `SmoothGridPathInto(dst, grid, cells, opts)` writes into `dst[:0]` with `0` heap allocations once `dst` has enough capacity. - **Any-angle (Theta*) search**: set `astar.AnyAngle = true` on square grids (`TopologySquare`, `TopologySquare4`, `TopologySquare8`) to relax neighbors directly from an ancestor cell whenever line of sight between cell centers crosses uniform-cost walkable cells (respecting `NoCornerCutting` and avoiding expensive `CostGrid` cells). When smoothing for a positive body `Radius`, prefer standard cell-by-cell `AStar` (`AnyAngle: false`) followed by `SmoothGridPathInto` so corner cells remain available when the body radius cannot clear a corner directly. ### Hexagonal and staggered topologies Set `astar.Topology` to match any `tilemap.Tilemap` orientation via `ai.TopologyFromTilemap(m)` or pick a topology explicitly (`TopologySquare`, `TopologySquare4`, `TopologySquare8`, `TopologyHexPointyOdd`, `TopologyHexPointyEven`, `TopologyHexFlatOdd`, `TopologyHexFlatEven`, `TopologyStaggeredYOdd`, `TopologyStaggeredYEven`, `TopologyStaggeredXOdd`, `TopologyStaggeredXEven`): ```go astar := ai.NewAStar() astar.Topology = ai.TopologyFromTilemap(hexMap) path, cost, ok := astar.Find(grid, ai.Cell{Col: 1, Row: 1}, ai.Cell{Col: 6, Row: 4}) _, _, _ = path, cost, ok ``` - Hexagonal topologies use 6-way axial adjacency and exact cube-distance heuristics matching `tilemap.Tilemap.HexNeighbors` and `HexDistance`. - Staggered isometric topologies map offset coordinates onto the underlying diamond lattice (`4-way` edge moves by default; set `Diagonal = true` for `8-way` vertex-diagonal moves with `NoCornerCutting`). - Implement `EdgeCostGrid` (`EdgeCost(fromCol, fromRow, toCol, toRow) float64`) when transition costs depend on both source and destination cells (elevation steps, rivers, or zone of control); negative, `NaN`, or infinite values forbid an edge. - Inspect a topology directly with `topo.Neighbors(c)`, `topo.NeighborsInto(dst, c)`, and `topo.Distance(a, b)`. ### Movement-range queries For tactics games, compute every cell reachable from `start` within a movement-point budget using Dijkstra search under `astar.Topology`: ```go reachable := astar.MovementRange(costMap, ai.Cell{Col: 2, Row: 2}, 4) for _, rc := range reachable { // rc.Cell is reachable at minimum cost rc.Cost <= 4 _ = rc } ``` - Results are returned in deterministic order: ascending `Cost`, then row-major cell index. - Use `astar.MovementRangeInto(dst, grid, start, budget)` for zero-allocation buffer reuse, or `astar.MovementRangeWithCost(dst, grid, start, budget, edgeCost)` / `ai.ReachableCells(grid, topo, start, budget, edgeCost)` to supply a custom `func(from, to ai.Cell) float64` callback (supporting sub-unit road costs as well as negative blocked edges). ## Hierarchical pathfinding (HPA*) and Jump Point Search (JPS) For large strategy and open-world tile maps (such as 1024×1024), per-cell `AStar` becomes expensive. `game/ai` provides two complementary fast grid searchers that reuse all internal buffers with zero allocations on `FindInto`: ### HPA* (`HPA`) `HPA` divides any `Grid`, `CostGrid`, or `EdgeCostGrid` into fixed-size square clusters (`ClusterSize`, default `16`), places entrance nodes along shared cluster borders, and precomputes intra-cluster shortest paths between entrances: ```go hpa := ai.NewHPA(grid, ai.HPAOptions{ ClusterSize: 32, Diagonal: true, // AllowCornerCutting is false by default }) path, cost, ok := hpa.Find(ai.Cell{Col: 2, Row: 2}, ai.Cell{Col: 1021, Row: 1021}) _, _, _ = path, cost, ok // When obstacles or terrain costs change, mark only the modified cells or region: grid.SetWalkable(400, 320, false) hpa.UpdateCell(400, 320) // or hpa.UpdateRect(minC, minR, maxC, maxR) hpa.RebuildDirty() // optional: Find also flushes pending dirty clusters automatically ``` - **Performance & path quality**: on the 1024×1024 multi-room benchmark map (`BenchmarkHPA1024` vs `BenchmarkAStar1024`), `HPA.FindInto` is over two orders of magnitude faster than `AStar.FindInto` (~150× faster, ~780× faster for `FindAbstractInto`) while staying well within 1.15× of optimal A* cost. - **Incremental updates**: `UpdateCell` and `UpdateRect` mark only the affected cluster (and adjacent cluster(s) when a cell lies on a shared cluster border) dirty. `RebuildDirty` rebuilds only those dirty borders and clusters instead of the whole map; inspect rebuild counts with `Stats()`. - **Abstract & corridor queries**: use `FindAbstract` / `FindAbstractInto` for coarse entrance waypoints without cell-by-cell refinement, or `FindClusters` / `FindClustersInto` to obtain the traversed `[]ClusterID` corridor (used directly by `rts.SectorFlowField.BuildAlongHPA`). ### Jump Point Search (`JPS`) `JPS` is a fast 8-way solver for uniform-cost square grids (`Grid`) that skips symmetric open-space cells while guaranteeing exact optimal octile path costs identical to `AStar` (`Diagonal: true`): ```go jps := ai.NewJPS() // NoCornerCutting is true by default path, cost, ok := jps.Find(grid, start, goal) waypoints, _, _ := jps.FindJumpPoints(grid, start, goal) // turning points only _, _, _ = path, cost, waypoints ``` - Use `jps.FindInto(dst, grid, start, goal)` or `jps.FindJumpPointsInto(dst, grid, start, goal)` for zero-allocation buffer reuse. - `JPS` assumes uniform traversal cost `1` per walkable cell; use `AStar` or `HPA` for weighted `CostGrid` / `EdgeCostGrid` maps. ## Generic graph search, hex adapters, and waypoint graphs When pathfinding over hexagonal tilemaps, hand-placed waypoints, 3D cell grids, or custom domain graphs, use `GraphSearch[N]` over any `Graph[N]` (`AppendNeighbors(dst []GraphEdge[N], node N) []GraphEdge[N]`) or `HeuristicGraph[N]` (adding `Heuristic(from, goal N) float64`): - **A* and Dijkstra with buffer reuse**: `Find` / `FindInto`, `FindWithHeuristic` / `FindWithHeuristicInto`, and `FindDijkstra` / `FindDijkstraInto` reuse internal node, heap, map, and neighbor buffers across calls (`FindInto` and `FindDijkstraInto` allocate `0` times after warm-up; `Find` allocates only the returned path slice). Ties break deterministically like `AStar`: lowest `f`, lowest `h`, `GraphSearch.Less` (or optional `NodeOrder[N]`), then discovery order. - **Range queries with reconstructed paths**: `Range(g, start, budget)` and buffer-reusing `RangeInto(dst, g, start, budget)` run Dijkstra within `budget` and return a `*GraphRange[N]` containing every reachable node and cost (`Nodes()`, `Contains(n)`, `Cost(n)`, `Parent(n)`) plus direct path reconstruction (`Path(n)` and zero-allocation `PathInto(dst, n)`). - **Custom callback graphs**: wrap quick ad-hoc graphs with `GraphFunc[N]{Neighbors, Estimate, Valid, Less}` or implement optional `ValidatedGraph[N]` to reject invalid/blocked endpoints before searching. ### Hex grid adapter over `tilemap.Tilemap` `NewHexGrid(m)` wraps any hexagonal `*tilemap.Tilemap` across all stagger axes (`StaggerX`, `StaggerY`) and indices (`StaggerOdd`, `StaggerEven`), delegating directly to `m.HexNeighbors` and `m.HexDistance`: ```go hex := ai.NewHexGrid(hexMap) hex.Cost = func(col, row int) float64 { if isForest(col, row) { return 2 } return 1 } search := ai.NewGraphSearch[ai.Cell]() path, cost, ok := search.Find(hex, start, goal) // Movement range for turn-based tactics, including path preview to any cell in range: moveRange := search.Range(hex, start, 4) if preview, reachable := moveRange.Path(hoveredCell); reachable { _, _, _, _ = path, cost, ok, preview } ``` Set `SolidMask` (defaults to `tilemap.TileSolid`), `Walk`, `Cost`, or directed `StepCost` to customize passability and per-cell or per-edge terrain costs. `HexGrid` also satisfies `Grid`, `CostGrid`, and `EdgeCostGrid`. ### Waypoint graphs `NewWaypointGraph()` stores hand-placed 2D (`Add`, `SetPos`, `Pos`, `Nearest`, `Points` / `PointsInto`) or 3D (`Add3D`, `SetPos3D`, `Pos3D`, `Nearest3D`, `Points3D` / `Points3DInto`) waypoints with stable integer IDs, live Euclidean-distance edges (`Connect`, `ConnectUndirected`), explicit weighted directed/undirected edges (`AddEdge`, `AddUndirectedEdge`), temporary node toggling (`SetEnabled`), and deletion (`Remove`): ```go wg := ai.NewWaypointGraph() a := wg.Add(core.Point{X: 0, Y: 0}) b := wg.Add(core.Point{X: 80, Y: 0}) c := wg.Add(core.Point{X: 80, Y: 60}) wg.ConnectUndirected(a, b) // Euclidean distance cost (80) wg.ConnectUndirected(b, c) // Euclidean distance cost (60) wg.AddEdge(a, c, 120) // explicit directed cost search := ai.NewGraphSearch[int]() nodePath, totalCost, ok := search.Find(wg, a, c) waypoints := wg.Points(nodePath) // ready for ai.FollowPath _, _, _ = totalCost, ok, waypoints ``` `WaypointGraph.Heuristic` returns Euclidean distance between waypoints (admissible whenever every edge costs at least Euclidean distance); call `search.FindDijkstra` when a graph includes shortcut or portal edges cheaper than straight-line distance. ## 2D NavMesh with funnel smoothing For open arenas or non-grid worlds, build a `NavMesh` from convex 2D polygons. `BuildNavMesh` normalizes polygon winding, automatically connects adjacent polygons along shared edges (including partial collinear overlaps), and `FindPath` runs portal-graph A* followed by Simple Stupid Funnel Algorithm string-pulling: ```go mesh := ai.BuildNavMesh([][]core.Point{ {{X: 0, Y: 0}, {X: 120, Y: 0}, {X: 120, Y: 80}, {X: 0, Y: 80}}, {{X: 120, Y: 20}, {X: 240, Y: 20}, {X: 240, Y: 100}, {X: 120, Y: 100}}, }) waypoints, ok := mesh.FindPath(core.Point{X: 16, Y: 16}, core.Point{X: 220, Y: 85}) _ = waypoints _ = ok ``` Inspect mesh geometry with `Contains(p)`, `FindPolygon(p)`, `NearestPolygon(p)`, `Neighbors(index)`, `Polygon(index)`, `PolygonCount()`, and `FindCorridor(start, goal)`. Register off-mesh connections with `AddOffMeshLink(NavOffMeshLink{...})`, inspect or clear them with `OffMeshLinks()` and `ClearOffMeshLinks()`, and flag shared edges with `SetEdgeFlags(fromPoly, toPoly, flags)`. To cut a level into these polygons, with paths kept an agent's radius away from the walls, bake the mesh from its outline and obstacles or from a tilemap with [navbake](https://game.nsgo.dev/docs/navbake/). ### Off-mesh links (jumps, ladders, and teleports) Connect polygons that do not share an edge — such as one-way ledge drops, gap jumps, bidirectional ladders, doors, or teleporters — with `AddOffMeshLink`: ```go mesh.AddOffMeshLink(ai.NavOffMeshLink{ Start: core.Point{X: 90, Y: 40}, End: core.Point{X: 140, Y: 40}, Radius: 4, // snap endpoints within 4 units of a polygon edge and trigger agent entry Bidirectional: false, Cost: 12, // <= 0 uses Euclidean distance Area: ai.NavAreaJump, Flags: uint32(ai.NavFlagJump), ID: 1, UserData: "drop", }) res := mesh.FindPathWithOptions(start, goal, ai.PathOptions{}) if res.Found { for i := 0; i+1 < len(res.Path); i++ { if link, ok := res.LinkAt(i); ok { // Segment Path[link.StartIndex] -> Path[link.EndIndex] traverses an off-mesh link. _ = link.UserData } } } ``` - **Path segment metadata**: `NavPathResult.Links` lists every off-mesh link traversed in path order (`StartIndex`, `EndIndex == StartIndex + 1`, `FromPoly`, `ToPoly`, `Start`, `End`, `Radius`, `Area`, `Flags`, `LinkID`, `UserData`), with `HasLinks()` and `LinkAt(segmentIndex)` helpers. Collinear simplification never collapses link entry or exit points. - **Shortcut-aware optimal search & filtering**: A\* treats off-mesh links as directed edges (or two directed edges when `Bidirectional` is true), filters them by `NavFilter` (`Area` and `Flags`, including `NavAreaJump`, `NavAreaClimb`, `NavAreaTeleport`, `NavFlagJump`, `NavFlagClimb`, `NavFlagTeleport`), scales traversal cost by `filter.AreaCost(link.Area)`, and adjusts its heuristic when a link's effective cost is cheaper than straight-line distance so teleporters are used only when strictly cheaper than walking. - **YAML storage and scene placement**: store 2D off-mesh links in baked YAML files via `navbake.Source.Links` / `navbake.Mesh.Links` (applied automatically by `navbake.Mesh.NavMesh`), or place them on scene objects using the built-in `"nav_link"` component (`sceneformat.RegisterNavLink`, `sceneformat.ExtractNavLinks2D`, `sceneformat.ExtractBuiltNavLinks2D`). ### Navigation agents and path corridors (`NavAgent`, `NavAgentGroup`) `NavAgent` maintains an active polygon corridor over an `ai.NavMesh`, computes the next funnel corner (`NextCorner`) directly from its current position, steers smoothly toward it, slows inside `ArrivalRadius` to stop cleanly within `StoppingDistance`, and exposes explicit state (`NavAgentIdle`, `NavAgentMoving`, `NavAgentArrived`, `NavAgentUnreachable`): ```go agent := ai.NewNavAgent(mesh, core.Point{X: 16, Y: 16}, ai.NavAgentConfig{ MaxSpeed: 120, MaxAcceleration: 480, Radius: 10, ArrivalRadius: 40, StoppingDistance: 8, ReplanInterval: 100 * time.Millisecond, OnLink: func(a *ai.NavAgent, ev ai.NavLinkEvent, dt time.Duration) bool { // Return true when custom off-mesh or flagged-edge traversal finishes. return true }, }) agent.SetTarget(playerPos) // Inside game.Loop.Update: agent.SetTarget(playerPos) agent.Step(dt) ``` - **Cheap local corridor repair**: when the agent advances, gets pushed off its corridor onto an adjacent polygon (`SetPosition`), or chases a target moving onto a neighboring polygon, `NavAgent` repairs its corridor locally via bounded adjacency bridging (up to `MaxRepairDepth`, default 2) and loop truncation without running a full A* replan. A full replan runs only when the corridor breaks beyond `MaxRepairDepth`, after sustained tail drift, or when the mesh's `Revision()` changes (`AddOffMeshLink`, `SetEdgeFlags`, `BumpRevision`, or `SetMesh`). - **Throttled and staggered group replanning**: manage many chasing agents with `NewNavAgentGroup(NavAgentGroupConfig{MaxReplansPerStep: 4, ReplanInterval: 100 * time.Millisecond, StaggerStride: 1})` and call `group.Step(dt)`. Full A* replans are strictly bounded to `MaxReplansPerStep` per step in deterministic round-robin order (optionally staggered by `StaggerStride`) so large crowds never spike a single frame. - **Off-mesh and flagged link callbacks**: `OnLink` is invoked each step while traversing an off-mesh link (`NavLinkOffMesh`) or crossing a flagged shared-edge portal (`SetEdgeFlags`); return `false` while driving a custom jump/door transition and `true` to resume normal corridor steering. When `OnLink` is `nil`, off-mesh links traverse linearly at `MaxSpeed`. - **Deterministic stepping**: `Step(dt)` uses no background goroutines, no map iteration, and no hidden randomness; replaying identical inputs produces bit-identical positions every step. ### Polygon areas, runtime flags, and query filters Tag convex polygons at build time with `BuildNavMeshWithAreas` using `NavPolygonInput{Vertices, Area, Flags}` (`NavAreaDefault`, `NavAreaRoad`, `NavAreaGrass`, `NavAreaMud`, `NavAreaWater`, `NavAreaDoor`, `NavAreaHazard`, or any custom `uint8` `NavArea`; `NavFlagWalk`, `NavFlagSwim`, `NavFlagDoor`, `NavFlagJump`, `NavFlagDisabled`, `NavFlagAll` — zero `Flags` defaults to `NavFlagWalk`): ```go mesh := ai.BuildNavMeshWithAreas([]ai.NavPolygonInput{ {Vertices: grassPoly, Area: ai.NavAreaGrass}, {Vertices: roadPoly, Area: ai.NavAreaRoad}, {Vertices: waterPoly, Area: ai.NavAreaWater, Flags: ai.NavFlagSwim}, {Vertices: doorPoly, Area: ai.NavAreaDoor, Flags: ai.NavFlagWalk | ai.NavFlagDoor}, }) filter := ai.DefaultNavFilter() filter.SetAreaCost(ai.NavAreaRoad, 0.5) // roads cost half as much per unit distance filter.SetAreaCost(ai.NavAreaMud, 2.5) filter.ExcludeFlags |= ai.NavFlagSwim // land agents route around water path, ok := mesh.FindPathWithFilter(start, goal, filter) // Close or reopen a doorway at runtime in O(1) without rebuilding the mesh: mesh.AddPolygonFlags(doorIndex, ai.NavFlagDisabled) detour, ok := mesh.FindPathWithFilter(start, goal, filter) mesh.ClearPolygonFlags(doorIndex, ai.NavFlagDisabled) _, _, _ = path, detour, ok ``` - **Default compatibility**: `BuildNavMesh` assigns `NavAreaDefault` and `NavFlagWalk` to every polygon, and `FindPath` runs with `DefaultNavFilter()` (`IncludeFlags: NavFlagAll`, `ExcludeFlags: NavFlagDisabled`, cost `1.0` per area). - **Admissible weighted A\***: `FindPathWithFilter` weights distance inside each polygon by `filter.AreaCost(area)` and scales the A\* distance heuristic by the minimum allowed area cost across the mesh so sub-unit road costs remain optimal. Non-positive, `NaN`, or infinite area costs forbid traversal. - **Runtime updates without rebuild**: inspect or mutate polygons in O(1) via `PolygonArea`, `SetPolygonArea`, `PolygonFlags`, `SetPolygonFlags`, `AddPolygonFlags`, and `ClearPolygonFlags`. Filtered spatial queries (`FindPolygonWithFilter`, `ContainsWithFilter`, `NearestPolygonWithFilter`, `NearestPointWithFilter`, `RaycastWithFilter`, `MoveAlongSurfaceWithFilter`, `RandomPointWithFilter`, `RandomPointAroundWithFilter`) and filtered bounded/incremental searches (`FindPathWithFilterAndOptions`, `StartSearchWithFilter`) honor the same `NavFilter`. ### Spatial queries, surface movement, and zero-allocation path reuse Every `ai.NavMesh` builds a flat 2D AABB BVH spatial index at construction time so `FindPolygon`, `NearestPolygon`, `NearestPoint`, and pathfinding endpoint lookups scale logarithmically on large meshes instead of scanning every polygon: ```go rng := random.New(42) // Snap a click or spawn position onto the nearest allowed polygon within half-extents: snapped, poly, ok := mesh.NearestPoint(clickPos, core.Point{X: 32, Y: 32}) // Test straight-line walkability along the mesh surface: hit, obstructed := mesh.Raycast(agentPos, targetPos) // Slide a moving agent toward desiredPos while clamping cleanly to walkable polygons: moved, onMesh := mesh.MoveAlongSurface(agentPos, desiredPos) // Pick deterministic, area-weighted random points (anywhere or reachable within radius): patrolPt, _, _ := mesh.RandomPoint(rng) wanderPt, _, _ := mesh.RandomPointAround(agentPos, 96, rng) // Reuse caller and query buffers for zero-allocation path and corridor searches: query := ai.NewNavMeshQuery(mesh) pathBuf, ok = query.FindPathInto(pathBuf, snapped, wanderPt) corridorBuf, _ = query.FindCorridorInto(corridorBuf, snapped, wanderPt) _, _, _, _, _, _, _ = poly, hit, obstructed, moved, onMesh, patrolPt, ok ``` - **Extent-bounded snapping**: `NearestPoint(p, extent)` and `NearestPointWithFilter(p, extent, filter)` find the closest point inside `[p - extent, p + extent]` on any allowed polygon (clipping overlapping polygons against the search box when needed). - **Surface raycast and sliding**: `Raycast` / `RaycastWithFilter` walk shared-edge portals and return `NavRaycastHit{Point, Normal, Poly, T, Hit}` (with unit inward edge normal on obstruction); `MoveAlongSurface` / `MoveAlongSurfaceWithFilter` slide along obstructing boundaries across polygons and return `NavMoveResult{Point, Poly, Visited, HitBoundary}`. - **Deterministic area-weighted sampling**: `RandomPoint` / `RandomPointWithFilter` sample uniformly by polygon area across allowed polygons; `RandomPointAround` / `RandomPointAroundWithFilter` restrict sampling to connected allowed polygons reachable from `center` within `radius` (never returning disconnected islands). Given the same `*random.Stream` seed, results are bit-identical across runs and architectures. - **Zero-allocation queries and concurrency**: `mesh.FindPathInto`, `mesh.FindPathWithFilterInto`, `mesh.FindPathWithFilterAndOptionsInto`, and `mesh.FindCorridorInto` reuse generation-stamped scratch buffers for `0` heap allocations after warm-up. Create one `NewNavMeshQuery(mesh)` per worker or goroutine when querying a shared read-only `NavMesh` concurrently (also exposing `MoveAlongSurfaceInto` and buffer-reusing `RandomPointAround`). ### Tiled 2D NavMesh and dynamic obstacles (`TiledNavMesh`) When doors, placed buildings, destructible walls, or streamed regions change walkable areas at runtime, use `TiledNavMesh`: it partitions 2D polygons into fixed-size square tiles (`NavTileCoord{X, Y}`) that can be baked (`BakeNavTile` / `BakeTile`), added (`AddTile`), replaced (`ReplaceTile` / `SetTile`), removed (`RemoveTile`), and rebuilt (`RebuildTile`) independently, automatically linking polygons across tile borders so paths match an untiled `NavMesh`: ```go tm := ai.BuildTiledNavMesh(corridorPolys, 32) // or ai.NewTiledNavMesh(ai.TiledNavMeshConfig{TileSize: 32}) res := tm.FindPathWithOptions(start, goal, ai.PathOptions{}) watchID := tm.WatchPath(res.TileCoords(), func(ev ai.NavTileChange) { // Only paths crossing ev.Coord are notified when that tile changes. replanPath() }) // Carve a box, circle, or (convex/concave) polygon obstacle — rebuilds ONLY the touched tiles: obsID, _ := tm.AddObstacle(ai.NavBoxObstacle(minPt, maxPt)) detour, _ := tm.FindPath(start, goal) // detours around the box; tm.IsPathValid(res) is now false // Remove the obstacle to restore the original polygons and path: tm.RemoveObstacle(obsID) tm.UnwatchPath(watchID) _, _ = detour, watchID ``` - **Dynamic obstacle shapes and modes**: `NavBoxObstacle`, `NavOrientedBoxObstacle`, `NavCircleObstacle`, and `NavPolygonObstacle` (supporting both convex and concave footprints plus optional `Margin` inflation) default to `NavObstacleCarve` (exact convex subtraction so paths detour cleanly around obstacles) or can use `NavObstacleMark` to split polygons along the obstacle footprint and apply `NavFlagDisabled` or a custom `Area`/`Flags` (such as `NavAreaMud`). Wrap multi-obstacle frame updates in `tm.Batch(func() { ... })` so each touched tile rebuilds at most once. - **Two-level spatial index**: `FindPolygon`, `NearestPoint`, `NearestPolygon`, and `Raycast` use an O(1) tile coordinate lookup (or branch-and-bound over a coarse tile BVH for unbounded queries) plus per-tile flat AABB BVHs, avoiding whole-mesh scans. - **Per-tile path invalidation**: `TiledNavPathResult.Tiles` stamps every crossed tile's version so `tm.IsPathValid(res)` detects invalidation in O(crossed tiles); `WatchPath` indexes watchers per tile and notifies only paths whose corridor crossed a modified or removed tile (`AddTileListener` observes all tile events). - **Baked bridge**: convert any 2D baked mesh directly into a tiled mesh with `navbake.Mesh.TiledNavMesh(tileSize)`. ## Bounded, partial, and incremental path searches Clicking an unreachable target should still move a unit as close as possible, and dozens of simultaneous long searches should never stall a frame. `AStar`, 2D `NavMesh`, and [world3d](https://game.nsgo.dev/docs/world3d/)'s 3D `NavMesh` share `PathOptions{MaxExpansions, AllowPartial}` and the `IncrementalSearch` interface: ```go // Single-shot bounded search with partial-path fallback: res := astar.FindWithOptions(grid, start, goal, ai.PathOptions{ MaxExpansions: 128, AllowPartial: true, }) if res.Found { // When res.Partial is true, res.Path ends at the closest explored walkable cell. // res.Exhausted reports whether MaxExpansions stopped the search early. follow(res.Path) } // 2D NavMesh bounded/partial search (same PathOptions): navRes := mesh.FindPathWithOptions(startPt, goalPt, ai.PathOptions{ MaxExpansions: 64, AllowPartial: true, }) _ = navRes ``` - **Partial paths**: when `AllowPartial` is `true` and the goal is walled off, blocked, outside the mesh, or beyond `MaxExpansions`, `FindWithOptions` / `FindWithOptionsInto` (zero-allocation after warm-up) and `NavMesh.FindPathWithOptions` return a valid path to the closest explored cell or closest point on an explored polygon, with `Partial: true`. Setting `AStar.MaxExpansions > 0` also caps `Find` / `FindInto` and acts as the default budget when `PathOptions.MaxExpansions == 0` (pass a negative `PathOptions.MaxExpansions` to override to unlimited). - **Deterministic incremental stepping**: start a multi-frame search with `astar.StartSearch(grid, start, goal, opts)` (`*AStarSearch`, reusable via `Reset`) or `mesh.StartSearch(start, goal, opts)` (`*NavMeshSearch`) and advance it with `Step(maxExpansions)`. Splitting a search across any positive step sizes (even 1 expansion per step) produces the exact same path, cost, partial flag, and expansion count as a single-shot call. - **Budgeted request queue (`PathQueue`)**: service many grid, 2D `NavMesh`, and `world3d.NavMesh` searches within one strict per-step expansion budget using `NewPathQueue`, `Submit` / `SubmitGrid` / `SubmitNavMesh`, `Cancel`, and `Step(budget)` / `StepDefault()`: ```go queue := ai.NewPathQueue(ai.PathQueueConfig{ DefaultBudget: 64, // strict max expansions per StepDefault Policy: ai.PathQueueRoundRobin, // or ai.PathQueueFIFO (default) SliceSize: 16, // max expansions per turn (0 = even split) }) reqID, search := queue.SubmitGrid(astar, grid, start, goal, ai.PathOptions{ AllowPartial: true, }, 1, func(id ai.PathRequestID, res ai.GridPathResult) { assignUnitPath(res.Path, res.Partial) }) // Inside game.Loop.Update: _ = queue.StepDefault() // never exceeds DefaultBudget expansions _ = search.Status() // poll directly, or cancel with queue.Cancel(reqID) _ = reqID ``` Higher-priority requests run first, ties break deterministically in FIFO or round-robin rotation order within each priority tier, and canceled requests are never stepped again or delivered to callbacks. ## Steering behaviors `Agent` integrates smooth 2D steering forces (`MaxSpeed`, `MaxForce`, `Radius`) on fixed steps via `Agent.Step(force, dt)`: ```go agent := ai.Agent{ Pos: core.Point{X: 20, Y: 20}, MaxSpeed: 120, MaxForce: 300, Radius: 10, } var followState ai.PathFollowState // Inside game.Loop.Update: force := ai.Combine(agent.MaxForce, ai.WeightedForce{Force: ai.FollowPath(agent, waypoints, &followState, 8, false), Weight: 1.0}, ai.WeightedForce{Force: ai.Separation(agent, nearbyAgents, 24), Weight: 1.5}, ) agent.Step(force, dt) ``` Built-in 2D steering functions: | Function | Behavior | | --- | --- | | `Seek(a, target)` | Accelerates toward `target` at `MaxSpeed`. | | `Arrive(a, target, slowRadius)` | Scales desired speed smoothly down to zero inside `slowRadius`. | | `Flee(a, threat, panicRadius)` | Accelerates away from `threat` while closer than `panicRadius` (or always if `<= 0`). | | `Pursue(a, target, maxLookAhead)` | Intercepts a moving `target` by predicting its position from `target.Vel`, capped to `maxLookAhead` seconds when positive. | | `Evade(a, pursuer, panicRadius, maxLookAhead)` | Flees the predicted position of `pursuer` while closer than `panicRadius` (or always if `<= 0`). | | `OffsetPursuit(a, leader, localOffset, slowRadius, maxLookAhead)` | Follows `leader` at a heading-frame offset (`X` forward, `Y` left) using `Arrive`. | | `FollowPath(a, path, &state, radius, loop)` | Follows waypoints, using `Arrive` on the final waypoint when `loop` is `false`. | | `Separation(a, neighbors, desiredSep)` | Pushes away from close neighbors (defaults to `a.Radius + neighbor.Radius` when `<= 0`). | | `Alignment(a, neighbors, radius)` | Steers toward the average heading of neighbors within `radius`. | | `Cohesion(a, neighbors, radius)` | Steers toward the center of mass of neighbors within `radius`. | | `ObstacleAvoidance(a, obstacles, maxAhead)` | Deflects around the nearest circular `Obstacle` intersecting the forward detection corridor. | | `WallAvoidance(a, walls, feelerLength)` | Keeps clear of `Wall` line segments using three forward feelers and direct radius containment. | | `Hide(a, pursuer, obstacles, standoff, slowRadius)` | Picks the closest hiding spot behind a circular `Obstacle` opposite `pursuer` (falls back to `Evade` if none exist). | | `Interpose(a, targetA, targetB, slowRadius)` | Intercepts the predicted midpoint between two moving agents. | | `Wander(a, &state, radius, dist, jitter, nextRand)` | Smooth random wandering using your deterministic `nextRand() float32` in `[0, 1)`. | | `Combine(maxForce, forces...)` | Sums weighted forces and clamps magnitude to `maxForce`. | | `CombinePrioritized(maxForce, forces...)` | Spends `maxForce` in priority order (e.g. `WallAvoidance` before `FollowPath`), ignoring lower-priority forces once the budget is saturated. | ### Zero-allocation flocking with `NeighborGrid` For large flocks, index agents once per step in a `NeighborGrid` so `Rebuild`, `Query`, and `QueryInto` reuse internal buffers with zero heap allocations after warm-up: ```go grid := ai.NewNeighborGrid(48) // Inside game.Loop.Update: grid.Rebuild(agents) for i := range agents { neighbors := grid.Query(agents[i].Pos, 48) forces[i] = ai.CombinePrioritized(agents[i].MaxForce, ai.WeightedForce{Force: ai.Separation(agents[i], neighbors, 18), Weight: 1.6}, ai.WeightedForce{Force: ai.Alignment(agents[i], neighbors, 45), Weight: 1.0}, ai.WeightedForce{Force: ai.Cohesion(agents[i], neighbors, 48), Weight: 0.9}, ) } for i := range agents { agents[i].Step(forces[i], dt) } ``` ### 3D and XZ-plane steering `Agent3D`, `Vec3`, `Obstacle3D`, `Wall3D`, `WeightedForce3D`, and `NeighborGrid3D` provide the matching 3D steering suite (`Seek3D`, `Arrive3D`, `Flee3D`, `Pursue3D`, `Evade3D`, `OffsetPursuit3D`, `FollowPath3D`, `Separation3D`, `Alignment3D`, `Cohesion3D`, `ObstacleAvoidance3D`, `WallAvoidance3D`, `Hide3D`, `Interpose3D`, `Combine3D`, `CombinePrioritized3D`). `ai.Vec3` shares the exact `X, Y, Z float32` layout of `math3d.Vec3` (right-handed Y-up: `+X` right, `+Y` up, `-Z` forward), so values convert with `ai.Vec3(v)` at zero cost while keeping `game/ai` free of experimental imports. Set `Agent3D.PlanarXZ = true` for grounded agents following `world3d.NavMesh` paths on the horizontal XZ plane: ```go rawPath, ok := navMesh3D.FindPath(start, goal) if ok { path := make([]ai.Vec3, len(rawPath)) for i, p := range rawPath { path[i] = ai.Vec3(p) } agent := ai.Agent3D{Pos: ai.Vec3(start), MaxSpeed: 12, MaxForce: 40, Radius: 0.5, PlanarXZ: true} var st ai.PathFollowState force := ai.FollowPath3D(agent, path, &st, 0.8, false) agent.Step(force, dt) } ``` ## Velocity-based local avoidance (ORCA) Push-apart separation reacts only after bodies overlap, causing head-on deadlocks and jostling in doorways. `ORCASolver` implements Optimal Reciprocal Collision Avoidance (RVO2-style velocity obstacles with 2D linear programming and minimum-penetration infeasible fallback) so agents steer smoothly around neighbors and static obstacle edges before contact: ```go solver := ai.NewORCASolver(ai.ORCAConfig{ TimeHorizon: 2.0, // seconds to look ahead for agents TimeHorizonObst: 1.0, // seconds to look ahead for static walls MaxNeighbors: 16, }) walls := []ai.ORCAObstacle{ {A: math2d.V2(-12, 0), B: math2d.V2(-1.5, 0)}, {A: math2d.V2(1.5, 0), B: math2d.V2(12, 0)}, } // Inside game.Loop.Update: for i := range agents { agents[i].PrefVel = desiredVelocity(agents[i], goals[i]) } // Step updates Vel and Pos synchronously, or call Solve(out, agents, walls, dt) // to obtain collision-free velocities without mutating agent positions. solver.Step(agents, walls, dt) ``` - **2D and 3D XZ-plane sharing**: use `Solve`, `SolveAgent`, and `Step` with `ORCAAgent` / `ORCAObstacle` (`math2d.Vec2`) in 2D, or `SolveXZ`, `SolveAgentXZ`, and `StepXZ` with `ORCAAgent3D` / `ORCAObstacle3D` (`ai.Vec3`) so 2D and grounded 3D navmesh agents share the same solver while preserving `Pos.Y` and zeroing `Vel.Y`. - **Static obstacle edges**: `ORCAObstacle` line segments are treated as two-sided (winding-agnostic) and act as hard constraints during LP3 infeasible fallback so overcrowded agents stay clear of walls and doorway jambs. - **Layers, masks, and priority**: set `Layer` (zero defaults to `ORCALayerDefault`, bit 0) and `Mask` (zero defaults to `ORCAMaskAll`; obstacle `Layer` 0 also defaults to `ORCAMaskAll`) to separate movement domains such as ground vs. air. When an agent avoids a non-cooperative neighbor whose `Mask` ignores it, or a `Stationary` / zero-`MaxSpeed` neighbor, it automatically takes full avoidance responsibility (`1.0`). Among cooperative neighbors, higher `Priority` smoothly yields less (`pB / (pA + pB)`) so holding-position units hold their ground while lower-priority units steer around them. - **Deterministic and zero-allocation**: internal spatial-hash neighbor lookups and candidate/obstacle sorting canonicalize every constraint by distance and intrinsic agent properties before solving the LP, so shuffling neighbor or obstacle order produces bit-identical velocities and replays produce identical positions every step. Reusing `ORCASolver` and output buffers allocates `0 B/op` after warm-up. ## Behavior trees Compose enemy decision logic from `Node` trees returning `StatusSuccess`, `StatusFailure`, or `StatusRunning` on each `Tick(dt)`: ```go tree := ai.Selector( ai.Guard(playerInRange, ai.Sequence( ai.Cooldown(1500*time.Millisecond, ai.Action(attackPlayer)), ai.Wait(300*time.Millisecond), )), ai.Sequence( ai.Condition(hasPatrolPath), ai.Action(patrolStep), ), ) // Inside game.Loop.Update: tree.Tick(dt) ``` Available nodes: - **Composites**: `Sequence`, `Selector` (preempts and resets lower-priority running branches when a higher-priority branch succeeds or runs), `Parallel(policy, ...)` (`RequireAll` or `RequireOne`), `RandomSelector(stream, ...)`, `RandomSequence(stream, ...)`, `WeightedSelector(stream, options...)` (using `WeightedNode{Node, Weight}`), `UtilitySelector(reasoner, ctx, rng, subtrees)`. - **Decorators**: `Guard(cond, child)`, `BlackboardCondition(bb, key, op, value, abort, child)`, `Cooldown(d, child)`, `TimeLimit(d, child)`, `Retry(n, child)`, `Service(interval, fn, child)`, `WithAttackToken(pool, agentID, priority, child)`, `Inverter`, `Succeeder`, `Failer`, `Repeater(count, child)`, `UntilFail`. - **Leaves**: `Action(fn)`, `Condition(fn)`, `Wait(d)`, `HasAttackToken(pool, agentID)`, `SquadHasOrder(squad, kind)`, `SquadHasRole(squad, agentID, role)`, `SquadStateBool(squad, key)`, `SquadOrderAction(squad, fn)`. ### Blackboard and observer aborts `Blackboard` holds typed keys (`bool`, `int`, `float64`, `string`, 2D vectors via `math2d.Vec2` / `core.Point`, 3D vectors via `ai.Vec3`, and `uint64` entity IDs) scoped per agent with an optional shared parent blackboard for a squad or team (`NewChildBlackboard(parent)`). Reads fall back to the parent when a key is not set locally; `Set*` writes locally and `SetShared*` targets the parent. `KeyRevision(key)` and `Revision()` track mutations monotonically without heap allocations, and `Watch(key, fn)` delivers synchronous change notifications (propagating non-shadowed parent updates) with a returned cancel function. `BlackboardCondition(bb, key, op, value, abort, child)` compares `key` using `BBOpEq`, `BBOpNe`, `BBOpLt`, `BBOpLte`, `BBOpGt`, `BBOpGte`, `BBOpSet`, or `BBOpUnset` (omitting `child` uses it as a condition leaf). Its `AbortMode` controls how key changes interrupt running branches: - `AbortNone` (`none`): checks the condition only on entry. - `AbortSelf` (`self`): resets its own running child (or an enclosing `Sequence`'s later running child when used as a leaf) on the next tick if the watched key changes and the condition becomes false. - `AbortLower` (`lower`): aborts a running lower-priority sibling in an enclosing `Selector` on the next tick when the watched key changes and the condition becomes true. - `AbortBoth` (`both`): combines `AbortSelf` and `AbortLower`. ```go squadBB := ai.NewBlackboard() agentBB := ai.NewChildBlackboard(squadBB) agentBB.SetBool("enemy_seen", false) tree := ai.Selector( ai.BlackboardCondition(agentBB, "enemy_seen", ai.BBOpEq, ai.BBBool(true), ai.AbortBoth, ai.Action(chaseTarget), ), ai.Action(patrol), ) ``` ### Behavior trees in YAML Author behavior trees in versioned `*.bt.yaml` files (`version: 1`, JSON Schema `https://game.nsgo.dev/schemas/bt.v1.json`) with `ParseBehaviorTree` / `ParseBehaviorTreeWith`, `LoadBehaviorTreeFS`, `EncodeBehaviorTree`, `BuildBehaviorTree`, and `BuildBehaviorTreeFS`: ```go doc, err := ai.LoadBehaviorTreeFS(assetsFS, "ai/guard.bt.yaml") if err != nil { return err } tree, err := ai.BuildBehaviorTree(doc, ai.BTBindings{ Blackboard: agentBB, Stream: rng, FS: assetsFS, Actions: map[string]func(ai.BTNodeContext) (ai.Node, error){ "attack": func(ctx ai.BTNodeContext) (ai.Node, error) { dmg, _ := ctx.Params.Int("damage") return ai.Action(func(dt time.Duration) ai.Status { return doAttack(dmg) }), nil }, }, }) ``` - Supports every built-in composite and decorator (`sequence`, `selector`, `parallel`, `random_selector`, `random_sequence`, `weighted_selector`, `guard`, `cooldown`, `time_limit`, `retry`, `service`, `inverter`, `succeeder`, `failer`, `repeater`, `until_fail`, `blackboard_condition`), `wait`, game-registered `action` / `condition` leaves with typed `params`, and `subtree` references by `path` with `${param}` parameter substitution and `keys` blackboard key remapping. - `ParseBehaviorTreeWith`, `LoadBehaviorTreeFS`, and `BuildBehaviorTree` refuse unknown fields, unknown node types, invalid operators or abort modes, trailing YAML documents, and circular subtree references, reporting file, line, column, field path, and fix hints via `*loaderr.Error`. - `EncodeBehaviorTree` writes canonical 2-space YAML prefixed with `BTSchemaComment` in fixed key order so load-and-save round trips change nothing. ### Timeouts, retries, deterministic random choices, and services - **`TimeLimit(d, child)`** fails and calls `child.Reset()` if `child` is still `StatusRunning` once `d` of game time has elapsed. - **`Retry(n, child)`** reruns a failing child up to `n` additional times (`1+n` total attempts), returning `StatusRunning` between attempts and `StatusSuccess` as soon as `child` succeeds. - **`RandomSelector(stream, children...)`** and **`RandomSequence(stream, children...)`** shuffle child order at the start of each run using a caller-supplied `*random.Stream` and keep that order across `StatusRunning` ticks until completion or `Reset()`. - **`WeightedSelector(stream, options...)`** draws `WeightedNode` children without replacement proportional to `Weight` using `stream` (skipping non-positive, `NaN`, or infinite weights and `nil` nodes), keeping a running child across ticks and remaining deterministic for a given seed. - **`Service(interval, fn, child)`** invokes `fn` immediately on entry into `child` and then every `interval` of game time while `child` continues returning `StatusRunning`, stopping cleanly when `child` finishes or is reset. ```go rng := random.New(42) combat := ai.Service(250*time.Millisecond, refreshTarget, ai.WeightedSelector(rng, ai.WeightedNode{Node: ai.TimeLimit(2*time.Second, chargeAttack), Weight: 2}, ai.WeightedNode{Node: ai.Retry(2, rangedShot), Weight: 3}, ), ) ``` ### Saving and restoring behavior tree state Save mid-run behavior tree state (for save slots, rollback netcode, or state dumps) with `SnapshotBehaviorTree` / `RestoreBehaviorTree`, or wrap a root `Node` in `NewBehaviorTree(root)` to call `bt.Snapshot()` and `bt.Restore(snap)`: ```go bt := ai.NewBehaviorTree(tree) bt.Tick(dt) // Capture every built-in stateful node by deterministic structural path ("0/1/2"). snap, err := bt.Snapshot() if err != nil { return err } data, err := yaml.Marshal(snap) // plain struct: marshals to YAML or JSON // Later, restore into a fresh tree of the exact same shape: var loaded ai.BehaviorTreeSnapshot if err := yaml.Unmarshal(data, &loaded); err != nil { return err } if err := freshBT.Restore(loaded); err != nil { return err // refuses mismatched tree shapes without mutating freshBT } ``` - **Complete built-in coverage**: captures progress for `Sequence`, `Selector`, `Parallel`, `Repeater`, `Cooldown`, `Wait`, `TimeLimit`, `Retry`, `RandomSelector`, `RandomSequence`, `WeightedSelector`, `Service`, `BlackboardCondition`, `Guard`, `WithAttackToken`, and `UtilitySelector`, plus wrapper/leaf kinds (`Inverter`, `Succeeder`, `Failer`, `UntilFail`, `Action`, `Condition`) so shape mismatches are always detected. - **Transactional shape validation**: `RestoreBehaviorTree` checks `Version`, every node's structural path and kind, `Parallel` policies, and state bounds before applying any change. Mismatched trees return an error wrapping `ErrInvalidBTSnapshot` naming the exact path and expected vs got kind without mutating the target tree. - **Custom and shared nodes**: custom `Node` implementations can participate by implementing `SnapshotNode` (`SnapshotKind`, `SnapshotState`, `RestoreState`), and custom composites or decorators can expose their children via `ChildNodes` (`Children() []Node`). If a tree uses `RandomSelector`, `RandomSequence`, or `WeightedSelector`, also save and restore the associated `*random.Stream` state for identical subsequent draws. ### Inspecting behavior trees Attach optional labels with `Named(name, child)` (or set `name:` on any node in `*.bt.yaml`, which `BuildBehaviorTree` preserves automatically) and inspect live execution with a reusable `BTInspector`: ```go tree := ai.Named("root", ai.Selector( ai.Named("attack", ai.Sequence( ai.Named("in_range", ai.Condition(playerInRange)), ai.Named("swing", ai.Action(attackPlayer)), )), ai.Named("patrol", ai.Action(patrolStep)), )) inspector := ai.NewBTInspector(tree) traceBuf := make([]ai.BTNodeTrace, 0, inspector.Len()) pathBuf := make([]ai.BTNodeTrace, 0, inspector.Len()) // Inside game.Loop.Update (zero heap allocations once warmed up): tree.Tick(dt) traceBuf = inspector.WalkInto(traceBuf) pathBuf = ai.RunningPathInto(pathBuf, traceBuf) _ = pathBuf ``` - **Read-only pre-order snapshots**: `WalkInto(dst)` (or one-shot `Walk()` / `InspectBehaviorTree(root)`) fills `BTNodeTrace` records (`Path`, `Depth`, `Name`, `Kind`, `LastStatus`, `Ticked`, `Active`, `StatusString()`) without mutating execution state or allocating per tick once `dst` has capacity `inspector.Len()`. - **Running path**: `Active` is `true` for every node along the currently running branch; extract that path with `RunningPathInto(dst, nodes)` or `inspector.RunningPath()`. - **Deterministic text for `statedump`**: `inspector.Format()` (or `FormatBTTrace(nodes)`) renders a canonical indented tree prefixed with `* ` on active nodes so a game can store it in [`statedump`](https://game.nsgo.dev/docs/statedump/) `Values` (`dump.SetValue("guard_bt", inspector.Format())`) and diff AI decisions across runs. - **Live overlay & steering guides**: pass `debug.BehaviorTreeSnapshot("guard", inspector)` to [`game/debug`](https://game.nsgo.dev/docs/debug/) to show the tree with its running path highlighted, and call `overlay.DrawSteering` to draw velocity, desired velocity, target, and path guides (all stripped under `-tags release`). ## Utility AI When agents weigh continuous factors (distance, health, ammo, threat) instead of fixed boolean priorities, score candidate `UtilityAction`s with a `Reasoner[C]` using Dave Mark's Infinite Axis Utility System (IAUS): ```go type UnitState struct { HP float64 EnemyDst float64 Potions float64 } reasoner := ai.NewReasoner( ai.UtilityAction[UnitState]{ Name: "attack", Weight: 1.2, Considerations: []ai.Consideration[UnitState]{ { Name: "close", Input: func(s UnitState) float64 { return s.EnemyDst }, Min: 0, Max: 200, Curve: ai.LinearCurve(-1, 0, 1), }, { Name: "healthy", Input: func(s UnitState) float64 { return s.HP }, Min: 0, Max: 100, Curve: ai.LogisticCurve(1, 10, 0.35, 0), }, }, }, ai.UtilityAction[UnitState]{ Name: "heal", Weight: 1.1, Considerations: []ai.Consideration[UnitState]{ { Name: "low_hp", Input: func(s UnitState) float64 { return s.HP }, Min: 0, Max: 100, Curve: ai.PolynomialCurve(-1, 2, 0, 1), }, { Name: "has_potion", Input: func(s UnitState) float64 { return s.Potions }, Curve: ai.StepCurve(1, 0, 1), }, }, }, ) reasoner.Momentum = 0.1 // bonus for the currently active action idx, score := reasoner.Choose(state, nil) _, _ = reasoner.ActionName(idx), score ``` ### Considerations and response curves Each `Consideration[C]` reads a number from `C`, optionally normalizes `[Min, Max]` into `[0, 1]` (or clamps directly to `[0, 1]` when `Max <= Min`), and maps it through a `ResponseCurve` whose output is clamped to `[0, 1]`: | Kind / Constructor | Formula | | --- | --- | | `CurveLinear` / `LinearCurve(slope, shiftX, shiftY)` | `slope*(x - shiftX) + shiftY` | | `CurvePolynomial` / `PolynomialCurve(slope, exponent, shiftX, shiftY)` | `slope*(x - shiftX)^exponent + shiftY` | | `CurveLogistic` / `LogisticCurve(slope, steepness, midpoint, shiftY)` | `slope / (1 + exp(-steepness*(x - midpoint))) + shiftY` | | `CurveLogit` / `LogitCurve(slope, midpoint, shiftY)` | `slope*ln(u/(1 - u)) + shiftY`, `u = x - midpoint + 0.5` | | `CurveStep` / `StepCurve(threshold, low, high)` | `low` for `x < threshold`, `high` for `x >= threshold` | | `CurveResource` / `ResourceCurve(eval)` | Delegates to a `CurveEvaluator` (`Eval(float32) float32`), satisfied directly by `*resource.Curve` | | `CustomCurve(fn)` | Wraps a `func(float64) float64` as a `CurveEvaluator` | ### Scoring, momentum, and selection - **Compensation factor**: an action's `N` considerations are multiplied together (any `0` vetoes the action immediately) and compensated with `modFactor = 1 - 1/N`, `score = score + (1 - score)*modFactor*score`, then multiplied by `Weight` (defaulting to `1` when `0`; negative disables the action). - **Momentum bonus**: while an action is currently active and its base score is positive, `Reasoner.Momentum + UtilityAction.Momentum` is added so the agent does not oscillate between two nearly equal options every step. A vetoed action (`0`) never receives momentum. - **Top-N weighted choice**: set `Reasoner.TopN > 1` and pass a deterministic `*random.Stream` to pick among the top `N` positive-scoring actions weighted by score. Leaving `TopN <= 1` or passing a `nil` stream picks the highest-scoring action deterministically. Ties always break in fixed action declaration order. - **Zero-allocation multi-agent sharing**: call `reasoner.ChooseWithCurrent(ctx, agent.ActiveAction, rng)` to score many agents with one shared `Reasoner` and zero heap allocations after warm-up. ### Behavior tree integration Use `UtilitySelector(reasoner, ctx, rng, subtrees)` to embed utility scoring as a behavior tree `Node`. Each `UtilitySelector` tracks its own active action for momentum and calls `Reset()` on an interrupted running subtree when another action overtakes it: ```go node := ai.UtilitySelector(reasoner, func() UnitState { return unit.State() }, rng, map[string]ai.Node{ "attack": attackSubtree, "heal": healSubtree, }) ``` ### YAML configuration Define actions, considerations, and curves in a versioned YAML file (`version: 1`) parsed with `ParseUtility` and encoded deterministically with `EncodeUtility`. Bind Go input functions and an optional `resource` curve loader (`LoadCurve`) via `BuildReasoner`: ```go cfg, err := ai.ParseUtility(yamlBytes) if err != nil { return err } reasoner, err := ai.BuildReasoner(cfg, ai.UtilityBindings[UnitState]{ Inputs: map[string]func(UnitState) float64{ "target_distance": func(s UnitState) float64 { return s.EnemyDst }, "health_ratio": func(s UnitState) float64 { return s.HP / 100 }, }, LoadCurve: func(path string) (ai.CurveEvaluator, error) { return resource.LoadAs[*resource.Curve](resLib, path) }, }) ``` Unknown fields, unsupported versions, and trailing YAML documents are refused; canonical documents round-trip byte-for-byte unchanged (see [File Formats](https://game.nsgo.dev/docs/formats/#utility-ai)). ## Goal-oriented action planning (GOAP) When agents need to assemble multi-step action chains dynamically toward goals (fetch an axe, chop wood, build a fire) without hand-wiring every transition, define a `FactSchema`, `GOAPAction`s, and prioritized `GOAPGoal`s for a `GOAPPlanner`: ```go schema := ai.NewFactSchema() hasAxe := schema.MustBool("has_axe") hasFire := schema.MustBool("has_fire") wood := schema.MustInt("wood") planner, err := ai.NewGOAPPlanner( ai.GOAPAction{ Name: "fetch_axe", Cost: 1, Effects: ai.Effects{}.SetBool(hasAxe, true), Check: func(ai.WorldState) bool { return camp.AxeAvailable() }, }, ai.GOAPAction{ Name: "chop_wood", Cost: 1, Preconditions: ai.Conditions{}.RequireBool(hasAxe, true), Effects: ai.Effects{}.AddInt(wood, 1), }, ai.GOAPAction{ Name: "gather_sticks", Cost: 3, Effects: ai.Effects{}.AddInt(wood, 1), }, ai.GOAPAction{ Name: "build_fire", Cost: 1, Preconditions: ai.Conditions{}.RequireIntGte(wood, 2), Effects: ai.Effects{}.SetBool(hasFire, true).AddInt(wood, -2), }, ) if err != nil { return err } goal := ai.GOAPGoal{ Name: "light_campfire", Priority: 10, Target: ai.Conditions{}.RequireBool(hasFire, true), } plan, cost, err := planner.PlanNames(ai.WorldState{}, goal) // plan == ["fetch_axe", "chop_wood", "chop_wood", "build_fire"], cost == 4 _, _, _ = plan, cost, err ``` ### World state, conditions, and effects - **`WorldState`** is a compact comparable value type packing up to `MaxBoolFacts` (128) named boolean facts into a `[2]uint64` bitset and up to `MaxIntFacts` (16) small `int16` integer facts. Register names with `FactSchema.Bool` / `FactSchema.Int` (or `MustBool` / `MustInt`). - **`Conditions`** express required boolean values (`RequireBool`) and integer bounds (`RequireIntEq`, `RequireIntGte`, `RequireIntLte`, `RequireIntGt`, `RequireIntLt`, `RequireIntRange`) for action preconditions and goal targets. - **`Effects`** express boolean assignments (`SetBool`) and integer updates (`SetInt`, `AddInt`). - **`GOAPAction.Check`** is an optional procedural precondition (`func(WorldState) bool`) evaluated against the current world state so actions can verify runtime conditions (such as reachability or entity availability) outside the symbolic bitset. ### Regressive A* search and node budget - `GOAPPlanner` runs deterministic regressive A* from `goal.Target` back to the current `WorldState`, using an admissible heuristic over usable actions to guarantee the cheapest plan. - Ties break in a fixed order (lowest `f`, lowest `h`, fewest actions, lowest discovery index in action declaration order), producing identical plans across runs. - `GOAPPlanner.NodeBudget` (default `DefaultGOAPNodeBudget`, 1024) caps how many search nodes are expanded per plan; exceeding it fails cleanly with `ErrBudgetExceeded` instead of searching unboundedly. Unreachable goals return `ErrNoPlan`. - Internal node, heap, and open-addressing hash-table buffers are reused across calls: use `PlanInto(dst, start, goal)` or `PlanBestGoalInto(dst, start, goals)` for zero heap allocations after warm-up. ### Plan runner and behavior tree integration `NewPlanRunner(planner, worldFn, goals, executors)` executes planned actions in order by ticking each action's bound `Node` (`executors[action.Name]`): - When an action returns `StatusFailure`, `PlanRunner` resets it, temporarily excludes the failed action, and replans to reach the goal by another route (returning `StatusFailure` if no route exists). - When `worldFn()` invalidates a remaining precondition or procedural check, or when a higher-priority goal becomes unsatisfied and achievable, `PlanRunner` resets the running action and replans automatically. - `*PlanRunner` implements `ai.Node` directly, so it can run standalone on `game.Loop` or sit inside any behavior tree: ```go runner := ai.NewPlanRunner(planner, camp.WorldState, goals, map[string]ai.Node{ "fetch_axe": fetchAxeNode, "chop_wood": chopWoodNode, "gather_sticks": gatherSticksNode, "build_fire": buildFireNode, }) tree := ai.Selector( ai.Guard(camp.InDanger, fleeNode), runner, ) ``` ### GOAP YAML configuration Author facts, actions, node budgets, and prioritized goals in a versioned YAML file (`version: 1`) decoded with `ParseGOAP`, encoded deterministically with `EncodeGOAP`, and compiled with `BuildGOAP`: ```go cfg, err := ai.ParseGOAP(yamlBytes) if err != nil { return err } set, err := ai.BuildGOAP(cfg, ai.GOAPBindings{ Checks: map[string]func(ai.WorldState) bool{ "axe_available": func(ai.WorldState) bool { return camp.AxeAvailable() }, }, }) ``` Unknown fields, unsupported versions, undefined fact references, invalid operators, and trailing YAML documents are refused; canonical documents round-trip byte-for-byte unchanged (see [File Formats](https://game.nsgo.dev/docs/formats/#goap-action-set)). ## Attack tokens, engagement slots, and squads Coordinate groups of enemies in action games, brawlers, and shooters so only a bounded number attack at once, surrounding enemies spread around moving targets without crossing paths, and squads share state, tactical roles, and orders. ### Attack token pools `TokenPool` arbitrates a fixed number of attack tokens for one target, and `TokenManager` manages one `TokenPool` per target ID. Agents submit or refresh requests with `Request(agentID, priority)` during a step, and `Step(dt)` advances cooldowns and hold timeouts while resolving pending requests deterministically (highest priority first, breaking ties by lowest `AgentID` regardless of submission order): ```go tokens := ai.NewTokenPool(ai.TokenPoolConfig{ Capacity: 2, // at most 2 attackers at once Cooldown: 400 * time.Millisecond, // pause before a returned token is reused PreemptMargin: 1.5, // advantage needed to take a token from another attacker MaxHoldDuration: 3 * time.Second, // auto-release if an attacker stalls }) // Each enemy's behavior tree requests a token and falls back to circling while waiting: enemyTree := ai.Selector( ai.WithAttackToken(tokens, enemyID, enemyPriority, attackSequence), circleTargetNode, ) // On fixed step: tick behavior trees, then resolve token grants/preemptions: enemyTree.Tick(dt) tokens.Step(dt) // When an enemy dies or disengages: tokens.Remove(enemyID) ``` - **Priority preemption**: when no free tokens are available, a waiting requester whose priority beats the weakest holder by at least `PreemptMargin` (or strictly exceeds it when `PreemptMargin <= 0`) takes that holder's token directly without entering cooldown. `WithAttackToken` resets an interrupted child and returns `StatusFailure` on the next tick so a parent `Selector` falls back cleanly. - **Per-target pools**: use `NewTokenManager(defaultCfg)` when enemies engage multiple targets; call `ConfigureTarget(targetID, cfg)` for custom limits, `RemoveAgent(agentID)` when an enemy dies across all targets, and `Step(dt)` to step every target deterministically in ascending target ID order. ### Engagement slots `SlotAssigner` places agents onto concentric `EngagementRing`s around a target using optimal minimum-cost bipartite matching (the Hungarian algorithm): ```go assigner := ai.NewSlotAssigner( ai.EngagementRing{Radius: 45, Slots: 4}, // inner melee ring fills first ai.EngagementRing{Radius: 90, Slots: 6}, // outer circling ring ) assigner.StayBias = 10 // world-unit hysteresis suppressing boundary oscillation var slots []ai.SlotAssignment // Inside game.Loop.Update as targetPos moves: slots = assigner.Assign(slots, targetPos, []ai.SlotAgent{ {ID: 1, Pos: enemy1.Pos}, {ID: 2, Pos: enemy2.Pos}, }) ``` - **Non-crossing & ring priority**: inner rings fill completely before outer rings are used, and minimizing total Euclidean distance prevents straight-line agent-to-slot paths from crossing. When there are more agents than slots, the optimal subset is assigned and extra agents receive `Assigned: false` (`Ring: -1`, `Slot: -1`). - **Stability & determinism**: setting `StayBias > 0` gives each agent a cost bonus for keeping its previous slot as the target moves. Input agents are sorted by ascending `ID` internally, so assignments are identical across runs regardless of slice order and reuse internal scratch buffers with zero allocations after warm-up. ### Squads `Squad` groups enemy IDs in deterministic ascending order with a shared key-value `SquadState`, score-driven tactical roles (`AssignRoles`), and squad-level `SquadOrder`s readable by behavior trees: ```go squad := ai.NewSquad(1, 10, 20, 30) squad.State().SetBool("player_spotted", true) squad.State().SetPoint("last_known_pos", playerPos) squad.AssignRoles( ai.SquadRoleSpec{Name: "flanker", Count: 1, Score: flankScore}, ai.SquadRoleSpec{Name: "suppressor", Count: 2, Score: suppressScore}, ) squad.SetOrder(ai.SquadOrder{Kind: "pinch", TargetID: playerID, Position: playerPos}) // Inside a squad member's behavior tree: flankBranch := ai.Sequence( ai.SquadStateBool(squad, "player_spotted"), ai.SquadHasOrder(squad, "pinch"), ai.SquadHasRole(squad, memberID, "flanker"), ai.SquadOrderAction(squad, moveToFlank), ) ``` - **`AssignRoles`** solves maximum-weight bipartite matching over `SquadRoleSpec`s, maximizing the number of filled eligible roles first and total score second. Return `NaN` or `±Inf` from `Score` to mark a member ineligible for a role. - **`SquadOrder.Revision`** increments on every `SetOrder` and `ClearOrder` call so behavior trees can detect newly issued directives even when `Kind` is unchanged. - **`SquadState`** provides typed helpers (`Bool`, `Int`, `Float`, `String`, `Point`, `ID`), generic `SquadStateGet[T]`, and deterministic sorted `Keys`. ## Influence maps `InfluenceLayer` stores a 2D scalar influence grid matching an `ai.Grid` (and using the same `Origin` / `CellSize` world mapping as `rts.FlowField`) so strategy and tactics AI can reason about threat, control, tension, and safe positioning: ```go friendly := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) enemy := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) control := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) tension := ai.NewInfluenceLayerForGrid(grid, math2d.Zero(), 16) squadID := friendly.AddSource(ai.InfluenceSource{ Cell: ai.Cell{Col: 2, Row: 3}, Strength: 10, Radius: 5, Falloff: ai.FalloffLinear, }) enemy.AddSource(ai.InfluenceSource{ Cell: ai.Cell{Col: 12, Row: 3}, Strength: 12, Radius: 6, Falloff: ai.FalloffExponential, FalloffRate: 0.45, }) // Incremental update (0 allocs/step after warm-up; matches Rebuild bit-for-bit): friendly.MoveSource(squadID, ai.Cell{Col: 3, Row: 3}) friendly.Update(grid) enemy.Spread(grid, ai.SpreadOptions{Decay: 0.2, Momentum: 0.5, Iterations: 2, Diagonal: true}) // Combine into tactical layers: control.Subtract(friendly, enemy) // positive = friendly control, negative = enemy control tension.Add(friendly, enemy) // total presence from both sides control.Normalize() // signed [-1, 1] preserving 0 as neutral // Find the least threatened reachable cell within 4 cells of a unit: safeCell, threatVal, ok := enemy.LowestInRadius(ai.Cell{Col: 5, Row: 3}, 4, ai.InfluenceQuery{ Grid: grid, Reachable: true, }) // Sample bilinearly or follow the downhill/uphill gradient in world coordinates: val, inBounds := enemy.Sample(unitPos) grad := enemy.Gradient(unitPos) _, _, _, _, _ = safeCell, threatVal, ok, val, inBounds _ = grad ``` ### Sources, falloffs, and obstacle-aware spreading - **Falloffs**: each `InfluenceSource` stamps cells within Euclidean cell `Radius` using `FalloffLinear` (`max(0, 1 - dist/Radius)`), `FalloffExponential` (`exp(-FalloffRate * dist)`), or `FalloffCustom` (`CustomFalloff(dist, radius)`). Blocked cells (`!grid.Walkable(col, row)`) always stay `0`. - **Incremental updates**: register moving units with `AddSource` and update them via `MoveSource`, `SetSource`, `RemoveSource`, `MarkDirtyCell`, or `MarkDirtyRect`. `Update(grid)` recomputes only dirty footprints in fixed source-slot order so results are deterministic, match `Rebuild(grid)` bit-for-bit, and perform zero heap allocations per step after warm-up. For one-off static stamps, call `Stamp(grid, src)`. - **Propagation with decay and momentum**: `Spread(grid, opts)` propagates influence around blocked cells (4-way or 8-way with no corner-cutting around walls, using `(1 - Decay)` on cardinal steps and `(1 - Decay)^sqrt(2)` on diagonals) and blends against previous values with `Momentum` (`next = prev*Momentum + target*(1 - Momentum)`). When tracked sources are present, `Spread` syncs dirty source changes incrementally before propagating so moving or removed sources decay smoothly. ### Layer combinations and spatial queries - **Combining layers**: `Add`, `Subtract`, `Multiply`, `Combine(terms...)`, `AddScaled`, `Scale`, `Abs`, `Clamp`, `Normalize`, and `CopyFrom` operate in place without allocating on pre-sized destination layers and support self-aliasing. - **Queries**: `HighestInRadius` and `LowestInRadius` find extrema within a cell radius, optionally filtering by walkability and BFS reachability (`InfluenceQuery{Grid: grid, Reachable: true, Diagonal: ...}`) with deterministic tie-breaking (closer cell, then smaller row, then smaller column). `Highest(grid)` and `Lowest(grid)` scan the full layer; `Sample(worldPos)` returns bilinearly interpolated values; `Gradient(worldPos)` and `GradientAtCell(col, row)` return uphill `math2d.Vec2` gradients in influence per world unit. ### Debug heatmap Draw any layer over a `tilemap.Camera` for debugging: ```go d.Save() cam.Apply(d) control.DrawHeatmap(d, cam, ai.HeatmapOptions{DrawGrid: true}) d.Restore() ``` `DrawHeatmap` culls cells outside `cam.VisibleBounds()`, tints positive values with `PositiveColor` (default green) and negative values with `NegativeColor` (default red), and scales opacity by `|value| / MaxAbs`. Under `-tags release`, `DrawHeatmap` compiles to a no-op stub and `InfluenceHeatmapEnabled()` returns `false`. ## Tactical position queries and cover points Cover shooters, stealth games, and tactics games use `CoverPoint`, `TacticalQuery`, `PointReservations`, and `QueryBudget` to answer "where should I stand" (behind cover from a threat, at a flanking angle with clear line of fire, or in a low-threat reachable cell) with deterministic ordering and zero heap allocations after warm-up: ```go // Generate cover points from a tilemap's solid edges (or physics 2D/3D colliders, or scene YAML): covers := ai.GenerateCoverFromTilemap(levelMap, ai.TileCoverOptions{ DefaultHeight: ai.CoverFull, }) reservations := ai.NewPointReservations(ai.ReservationConfig{ DefaultTimeout: 3 * time.Second, }) budget := ai.NewQueryBudget(16, 8) // at most 16 LOS raycasts and 8 path queries per step query := ai.NewTacticalQuery( []ai.CandidateGenerator{ &ai.CoverPointGenerator{Points: covers, MaxRadius: 240}, }, &ai.AngleTest{ Mode: ai.AngleCoverToTarget, Filter: ai.AtMost(math.Pi / 3), // cover faces within 60 degrees of the threat Weight: 2.0, Invert: true, }, &ai.CoverHeightTest{Prefer: ai.CoverFull, Weight: 1.0}, &ai.InfluenceTest{Layer: threatLayer, Weight: 1.5, Invert: true}, &ai.LOSTest{LOS: hasLineOfSight, WantClear: false, Weight: 2.0}, // hidden from threat &ai.PathDistanceTest{Grid: navGrid, CellSize: 16, Weight: 2.0, Invert: true}, ) // Inside game.Loop.Update: budget.Reset() reservations.Step(dt) spot, ok := query.RunAndReserve(ai.TacticalContext{ QuerierID: agentID, QuerierPos: agentPos, TargetPos: threatPos, Reservations: reservations, Budget: budget, }, 0) _, _ = spot, ok // When an agent dies or leaves cover: reservations.Release(agentID) ``` ### Cover points and generators Each `CoverPoint` records a world standing position (`Pos`), a unit `Facing` vector pointing from `Pos` into the cover obstacle (the incoming threat direction the cover blocks; the obstacle's outward normal is `Facing.Neg()`), a `CoverHeight` (`CoverHalf` or `CoverFull`), optional 3D `Elevation`, `ID`, and `Tags`. - **Tilemap and grid generation**: `GenerateCoverFromTilemap(m, opts)` merges contiguous exposed solid tile edges (reading optional `HalfCoverMask`, `HeightFunc`, or a tile's `"cover": "half"|"full"` property) and verifies generated positions lie in open tiles. `GenerateCoverFromGrid(g, origin, cellW, cellH, opts)` generates cover directly from any `ai.Grid`. - **2D and 3D collider generation**: `GenerateCoverFromBoxes`, `GenerateCoverFromWorld` (supporting `physics.Box`, `physics.Circle` pillars, and `World.Tiles`), and `GenerateCoverFromSegments` generate 2D cover points while pruning candidates embedded inside neighboring colliders. For 3D scenes, `physics3d.World.GenerateCoverPoints(opts)` projects vertical side faces of axis-aligned boxes, oriented boxes, spheres, capsules, and cylinders standing on an end onto the XZ plane (convex hulls and cylinders lying on their side generate no cover), classifying `CoverHalf` vs `CoverFull` from collider height and preserving floor `Elevation`. - **Scene YAML authoring**: register the built-in `"cover_point"` component on a `sceneformat.ComponentRegistry` via `sceneformat.RegisterCoverPoint(reg)` (`height`, `facingX`, `facingY`, `tags`), then extract world-transformed `[]ai.CoverPoint` values with `sceneformat.ExtractCoverPoints(doc)` or `sceneformat.ExtractBuiltCoverPoints(built)`. ### Candidate generators and ordered tests `TacticalQuery` runs one or more `CandidateGenerator`s, excludes points reserved by other agents, evaluates `TacticalTest`s in declaration order, and returns surviving `TacticalCandidate`s sorted deterministically by descending `Score` (breaking ties by `CoverID`, `Pos.Y`, `Pos.X`, `Facing`, and generation index): - **Generators**: `CoverPointGenerator` (with optional `MaxRadius`, `MinHeight`, `RequiredTag`), `RingGenerator` (concentric rings or arcs around a target or querier with optional `FaceCenter`), `GridGenerator` (world-space grid or walkable `ai.Grid` cells), and `NavMeshGenerator` (polygon centroids or spaced samples contained in an `*ai.NavMesh`). - **Tests**: each test sets `Purpose` (`TestFilterAndScore`, `TestFilterOnly`, or `TestScoreOnly`), optional `Filter` (`AtLeast`, `AtMost`, `Between`), `Weight`, `Invert`, and optional fixed `NormMin`/`NormMax` (defaulting to dynamic normalization across surviving candidates): - `DistanceTest`: Euclidean distance to `OriginQuerier`, `OriginTarget`, or `OriginCustom`. - `AngleTest`: angle in radians (`AngleCoverToTarget`, `AngleFlank`, `AngleToDirection`, `AngleFromTargetToDir`). - `InfluenceTest`: bilinearly sampled value from an `*ai.InfluenceLayer`. - `CoverHeightTest`: filters by `MinHeight` and scores preferred `CoverHalf`/`CoverFull`. - `LOSTest`: line of sight to or from a target via a game-supplied `LOSFunc` (`WantClear: true` for firing lines, `false` for hidden cover). - `PathDistanceTest`: travel distance via a `PathCost` callback, zero-allocation grid `AStar`, or zero-allocation 2D `NavMesh` funnel path length. - `CustomTest`: caller-supplied `Eval(ctx, candidate)` callback. ### Reservations and per-step budgets - **`PointReservations`**: guarantees two agents never reserve the same `CoverID` or non-cover positions closer than `MinSeparation`. `RunAndReserve` selects and reserves the best unreserved candidate while atomically replacing that agent's prior reservation; `Release(agentID)` frees a spot on death, `ReleaseCover(coverID)` frees destroyed cover, `Refresh` extends a timeout, and `Step(dt)` expires timed reservations deterministically. - **`QueryBudget`**: caps `MaxRaycasts` (for `LOSTest`) and `MaxPathQueries` (for `PathDistanceTest`) per simulation step across all agents sharing the budget. Before running a budgeted test, surviving candidates are ordered deterministically by preliminary score so the highest-ranked spots consume the step budget first. Call `Reset()` once per step, and use `Best`, `RunInto(dst, ctx)`, or `RunAndReserve` for zero heap allocations after warm-up. ## Perception A `Perception` gives one agent sight, hearing and a memory of what it sensed, so a guard can see the player right now, go to where it last heard a noise, and give up after a while. A `PerceptionSystem` steps the perceptions of many agents together on `game.Loop`'s fixed steps: ```go walls := []lights2d.Occluder{lights2d.RectOccluder(wallBounds)} guard := &ai.Perception{ Self: guardID, // never senses itself Team: teamGuards, Facing: core.Point{X: 1}, Sight: ai.SightConfig{ Range: 160, HalfAngle: math.Pi / 4, // a 90° cone PeripheralRange: 24, // all around, unless PeripheralHalfAngle narrows it }, Hearing: ai.HearingConfig{Range: 120}, ForgetAfter: 5 * time.Second, } senses := ai.PerceptionSystem{ LineOfSight: lights2d.LineOfSight(&walls), Budget: 32, // line-of-sight checks per step, shared by every agent } senses.Add(guard) // Inside game.Loop.Update: guard.Pos = guardAgent.Pos if guardAgent.Vel != (core.Point{}) { guard.Facing = guardAgent.Vel } if player.Running { senses.PostNoise(ai.Noise{Source: playerID, Team: teamPlayer, Pos: player.Pos, Loudness: 1}) } senses.Step(dt, []ai.Target{{ID: playerID, Team: teamPlayer, Pos: player.Pos, Vel: player.Vel}}) for _, ev := range guard.Events() { switch ev.Kind { case ai.EventGained, ai.EventUpdated: chase(ev.Memory.Pos) case ai.EventLost: search(ev.Memory.Pos, ev.Memory.Vel) case ai.EventForgotten: resumePatrol() } } ``` ### Sight A target is in view when it lies within `Range` of the eye and within `HalfAngle` (radians) of `Facing`, or within the shorter `PeripheralRange` and within `PeripheralHalfAngle`, which is zero for all around; a negative `PeripheralHalfAngle` disables the peripheral range. The eye is `Pos + EyeOffset`, in world space; hearing measures from the same point. A target in view is seen when the system's `LineOfSight` reports the segment from the eye to the target clear; a nil `LineOfSight` lets every target in view be seen. Three adapters cover the usual occluders: | Adapter | Occluders | | --- | --- | | `ai.PhysicsLineOfSight(world, query, layers)` | Bodies and tiles of a `physics.World`, through `RaycastFirstLayer`. | | `lights2d.LineOfSight(&occluders)` | The `lights2d` occluders that cast shadows, through `lights2d.Visible`; it reads the slice on every call, so the level can change it. | | `perception3d.PhysicsLineOfSight(world, layers)` | Bodies and static colliders of a `physics3d.World`, for 3D agents. | A ray that starts inside the agent's body or ends inside the target's hits that body, so keep agents and targets off the layers that block sight, for example by putting walls on a layer of their own. ### Hearing `PostNoise` queues a `Noise` with a position, a `Loudness` and its source's ID and team, and the next `Step` hears it: an agent hears a noise within `Hearing.Range × Loudness` of its eye, with no line of sight needed. Noises are heard in the order they were posted, and a step consumes them. ### Memory and events Each agent keeps one `Memory` per `StimulusID`, so a target seen and later heard refreshes one memory. A memory holds the last known `Pos` and `Vel` (zero when heard), the `Sense` that last refreshed it, its `Age` since it was last sensed, whether it is `Visible` now, and a `Strength` that is 1 when seen, is raised to at least `1 - distance/reach` when heard (1 for an infinite reach), and falls linearly to 0 over `ForgetAfter`. A memory is forgotten once `Age` reaches `ForgetAfter`. Read memories with `Memories`, `AppendMemories`, `Memory(id)` and `Sees(id)`, and drop them with `Forget(id)` and `Clear`. `Remove` takes an agent out of the system but keeps its memories, with none of them visible and no events, so `Sees` reports false until the agent is added and stepped again. A copy of a `Perception` that was added, such as a configured prototype, is a separate agent: `Add` gives it its own copy of the memories. After each `Step`, `Events` lists what changed: | Kind | When | | --- | --- | | `EventGained` | A stimulus is sensed with no memory of it before. | | `EventUpdated` | A remembered stimulus is seen again after being out of sight, is seen moving, or is heard. A still target in sight makes no events. | | `EventLost` | A stimulus in sight leaves it; the memory stays. | | `EventForgotten` | A memory reaches `ForgetAfter` and is dropped. | ### Teams `Team` is a small team number. The system's `Attitude` function, `DefaultAttitude` when nil, decides whether an agent regards a stimulus as `Hostile`, `Neutral` or `Friendly`: the same team is friendly, `NoTeam` on either side is neutral, and other teams are hostile. `SightConfig.Detect` and `HearingConfig.Detect` choose the attitudes each sense notices, with `DetectHostile`, `DetectNeutral`, `DetectFriendly` and `DetectAll`; zero detects hostile stimuli only. ### Budget and determinism With hundreds of agents, casting a ray for every agent and target on every step is too much. `Budget` caps the line-of-sight checks of a step: the pairs in view are ordered by the order agents were added and then by target ID, a step checks `Budget` of them starting after the last pair checked, and the next step carries on from there, so every agent gets its turn in a fixed order. A pair not yet rechecked keeps its previous result. `Stats` reports a step's candidates, checks and deferred pairs. A nil `LineOfSight` casts no rays, so the budget does not apply and every pair in view is seen at once. With a deterministic `LineOfSight`, every run with the same inputs produces the same memories and events. ### 3D The experimental package `game/ai/perception3d` runs the same engine on `math3d.Vec3`, so its senses, memory, events, teams and budget behave exactly as above. Its `Perception` points the cone along `Forward` (zero faces -Z), with angles measured in 3D, and `EyeOffset` is typically head height on +Y; `System`, `Target`, `Noise`, `Memory`, `Event` and `LineOfSight` mirror the 2D types, and it reuses `ai.SightConfig`, `ai.HearingConfig`, `ai.StimulusID`, `ai.Team` and the event kinds: ```go import "github.com/nsgo-dev/game/pkg/ai/perception3d" guard := &perception3d.Perception{ Team: teamGuards, Forward: math3d.Vec3{Z: -1}, EyeOffset: math3d.Vec3{Y: 1.7}, Sight: ai.SightConfig{Range: 40, HalfAngle: math.Pi / 4}, ForgetAfter: 5 * time.Second, } senses := perception3d.System{LineOfSight: perception3d.PhysicsLineOfSight(world, layerWalls), Budget: 64} senses.Add(guard) // Inside game.Loop.Update: senses.Step(dt, []perception3d.Target{{ID: playerID, Team: teamPlayer, Pos: playerPos}}) ``` --- Source: https://game.nsgo.dev/docs/anim3d/ # anim3d `game/anim3d` provides 3D skeletal animation driven on `game.Loop`'s fixed steps: glTF 2.0 node and skin playback (`Player`, `ClipFromGLTF`), pose state machines with cross-fade transitions, 1D/2D blend spaces with foot-phase synchronization, bone-masked override and additive layers, timed clip events, two-bone and FABRIK inverse kinematics, and root motion extraction. ```go import "github.com/nsgo-dev/game/pkg/anim3d" ``` All joint transforms follow [math3d](https://game.nsgo.dev/docs/math3d/) conventions (right-handed Y-up). ## Playing glTF animations Create a `Player` from any loaded `*gltf.Document` to advance translation, rotation, scale, and morph-target weight channels on `game.Loop.Update` fixed steps without mutating the shared document. Multiple players can animate the same `*gltf.Document` independently at different clips or timestamps: ```go player, err := anim3d.NewPlayer(doc) if err != nil { return err } if err := player.PlayByName("Walk"); err != nil { return err } // In game.Loop.Update: player.Step(dt) player.ApplyToScene(scene) // optional: sync named nodes in scene3d.Scene joints, err := player.SkinMatrices(0) // joint matrices for skinned rendering _ = joints ``` `Player` evaluates `STEP`, `LINEAR` (with shortest-path quaternion Slerp), and `CUBICSPLINE` (Hermite spline with normalized rotations) interpolation modes directly from the glTF channels, preserving matrix-authored non-animated nodes (such as COLLADA `Z_UP` roots). It provides `Play`, `PlayByName`, `Crossfade`, `CrossfadeByName`, `Pause`, `Stop`, `Seek`, `SetLoop`, `SetSpeed` (including negative values for reverse playback), `Time`, `Duration`, `Playing`, `LocalTransforms`, `WorldTransforms`, `MorphWeights`, `SkinMatrices`, `SkinMatricesForNode`, `ApplyToScene`, and `ApplyToNodes`. `Player` also implements `PoseSampler` via `Update` and `Pose`. `SkinMatrices(skinIndex)` computes glTF 2.0 joint matrices normalized by the skinned mesh node's inverse world transform (`inverse(worldMatrix[meshNode]) * worldMatrix[joint] * inverseBindMatrix[i]`), so bind-pose joints evaluate to identity matrices even under rotated root nodes. To feed glTF clips into `StateMachine`, `BlendSpace1D`, `BlendSpace2D`, `LayerStack`, or root motion extraction, convert them with `ClipFromGLTF` or `ClipsFromGLTF`. Unanimated TRS components on targeted nodes are seeded from each node's rest transform so bone offsets stay intact, untargeted nodes are omitted from `Tracks` so bone-masked layers leave them untouched, and any timed events in glTF `extras` are attached automatically. ## Clips, state machines, and blend spaces Build a `StateMachine` whose states sample single `*Clip`s, `*BlendSpace1D` (for example idle -> walk -> run by speed), `*BlendSpace2D` (directional strafing), or any custom `PoseSampler`: ```go // Locomotion clips cycle, so mark them looping; a blend-space sample whose clip has Loop false plays once and holds its last frame. idleClip.Loop, walkClip.Loop, runClip.Loop = true, true, true loco := anim3d.NewBlendSpace1D( anim3d.BlendSample1D{Param: 0.0, Clip: idleClip}, anim3d.BlendSample1D{Param: 2.0, Clip: walkClip, FootPhaseOffset: 0.0}, anim3d.BlendSample1D{Param: 6.0, Clip: runClip, FootPhaseOffset: 0.0}, ) loco.ParamName = "speed" sm := anim3d.NewStateMachine("locomotion") sm.AddState(anim3d.State{Name: "locomotion", Blend1D: loco, ParamName: "speed"}) sm.AddState(anim3d.State{Name: "jump", Clip: jumpClip}) sm.AddTransition(anim3d.Transition{ From: "locomotion", To: "jump", BlendDuration: 120 * time.Millisecond, When: func() bool { return sm.Param("airborne") > 0.5 }, }) // In game.Loop.Update: sm.SetParam("speed", moveSpeed) pose := sm.Update(dt) _ = pose ``` `BlendSpace1D` and `BlendSpace2D` advance a shared normalized phase (`[0, 1)`) using weighted cycle speeds and per-sample `FootPhaseOffset` so blending between clips of different lengths avoids foot skating. A sample whose clip has `Loop: true` wraps with the shared phase; a clip with `Loop: false` plays once from the blend space's last `Reset` and holds its final frame, and fires each of its events once. Samples placed at the same parameter (or the same 2D point) split that position's weight equally, so none of them is shadowed. `StateMachine.Update(0)` is a paused step: it returns the current pose without advancing time or starting conditional transitions. A state with a negative `Speed` plays backward and fires the events it crosses in reverse order. When the two states of a crossfade share one blend space or sampler, it advances once per step. ## Bone-masked layers and additive clips Combine a base locomotion sampler with upper-body actions or additive recoil/breathing using `LayerStack` and `BoneMask`: ```go upperMask := anim3d.NewBoneMask(jointCount, 0) upperMask.SetBranch(jointParents, spineJoint, 1.0) stack := anim3d.NewLayerStack(jointCount) stack.AddLayer(anim3d.AnimLayer{Name: "base", Mode: anim3d.LayerOverride, Weight: 1, Sampler: sm}) stack.AddLayer(anim3d.AnimLayer{Name: "aim", Mode: anim3d.LayerOverride, Weight: 0.9, Mask: upperMask, Clip: aimClip, Loop: true}) stack.AddLayer(anim3d.AnimLayer{Name: "recoil", Mode: anim3d.LayerAdditive, Weight: 0.6, Mask: upperMask, Clip: recoilClip, ReferencePose: &idleRef}) finalPose := stack.Update(dt) _ = finalPose ``` When a layer plays a `Clip`, only the joints the clip has a track for take part: an override layer leaves the other joints at the pose below it and an additive layer adds nothing to them. `BlendPosesMasked` likewise keeps base joints the overlay pose does not have, and `MakeAdditivePose` gives them the identity delta. For manual composition, use `BlendPoses`, `BlendPosesWeighted`, `BlendPosesMasked`, `MakeAdditivePose`, and `ApplyAdditivePose`. ## Clip events Attach timed `ClipEvent` markers (`Time`, `Name`, `Payload`, `Data`) to clips directly via `clip.AddEvent` or load them from glTF `extras` (`LoadEventsFromGLTFExtras`) or JSON sidecar files (`LoadEventsSidecar` / `MarshalEventsSidecar`): ```go walkClip.AddEvent(anim3d.ClipEvent{Time: 0.25, Name: "footstep", Payload: "left"}) sm.SetEventWeightThreshold(0.5) // suppress events from low-weight cross-fading states sm.OnEvent(func(ev anim3d.FiredEvent) { if ev.Event.Name == "footstep" { playFootstepSFX(ev.Event.Payload) } }) ``` During a crossfade each state fires its events at its crossfade weight at the midpoint of the part of the step inside the crossfade, so the step that completes the crossfade still fires the outgoing state's events. You can also pull fired events once per step with `sm.DrainEvents()` or drive standalone clips through `EventDispatcher`. ## Inverse kinematics and root motion - **Two-bone IK** (legs/arms): `newMid, newEnd, rootRot, midRot := anim3d.SolveTwoBoneIK(hip, knee, ankle, footTarget, kneePole)` solves an exact analytic hinge bend oriented toward `pole`. If one bone has zero length, the other bone alone is aimed at the target. - **FABRIK** (arbitrary chains such as spines, tails, or tentacles): `solved := anim3d.SolveFABRIK(jointPositions, target, 10, 0.001)`. - **Root motion**: extract per-step translation and yaw/rotation deltas from an authored clip, strip root movement from the sampled pose so the mesh does not double-move, and apply it to the character's world transform: ```go opts := anim3d.RootMotionOptions{RootJoint: 0, ExtractYawOnly: true, StripRootXZ: true, StripRootRot: true} rm := anim3d.ExtractRootMotion(attackClip, prevTime, currTime, opts) pose = anim3d.StripRootMotion(pose, opts) characterTransform = anim3d.ApplyRootMotion(characterTransform, rm) ``` A step that crosses the end of a looping clip, whether passed as wrapped times (`currTime < prevTime`) or monotonic ones, is split at each loop boundary and its rotations compose in playback order, so one long step turns the character exactly as the shorter steps on either side of the boundary would, including clips that pitch and yaw at once. `DeltaPos` is measured in the clip's root parent space and the pieces add. --- Source: https://game.nsgo.dev/docs/animclip/ # animclip `game/animclip` plays animation clips, the [resource files](https://game.nsgo.dev/docs/resources/#animation) of type `animation`, on scene objects: any registered property keyed on a timeline, as Godot's AnimationPlayer does. The [editor](https://game.nsgo.dev/docs/editor/#animation-editor) keys clips with the same package, so a clip plays the same in the game as in the editor's preview. ```go import "github.com/nsgo-dev/game/pkg/animclip" ``` ## Properties A track's `property` is written as in the scene file: - an object field: `x`, `y`, `rotation`, `scaleX`, `scaleY`, `alpha` (0 to 1), `originX`, `originY`, `flipX`, `flipY`, `sprite.frame` (`PropertySpriteFrame`, discrete atlas frame names stepping without interpolation), `posZ`, `rotX`, `rotY`, `rotZ` and `scaleZ` (`ObjectProperties` lists them with their documentation); - a registered component field, written `component.field` and split at the first dot, such as `body.speed`. The field must be registered in a `sceneformat.ComponentRegistry` (see [Component types](https://game.nsgo.dev/docs/editor/#component-types)) as a `FieldFloat`, `FieldInt` or `FieldBool`; a string component field has no number to key. `Properties(reg)` returns every keyable property, the object fields first, and `Lookup(reg, name)` resolves one. A property's `Kind` says how a keyed value is written: a float as it is, an int rounded to the nearest whole number, a bool as true from 0.5 up, and `KindFrame` (`sprite.frame`) as a discrete atlas frame name (`Property.GetFrame`, `Property.SetFrame`, `Property.CheckFrame`). Numeric values are clamped to the field's range. `Check(clip, reg)` checks a whole clip: every property must resolve, `sprite.frame` tracks must hold non-empty `frames` keys, and numeric tracks must hold `keys` whose values their property can take (0 or 1 for a bool, a whole number for an int, and inside the field's range). A track's `target` is the ID of another object in the scene, and an empty target is the object the clip plays on. ## Flipbook clips Three helpers build a `sprite.frame` clip directly from a sprite atlas: - `FromAsepriteTag(atlas, tag)` converts an Aseprite frame tag from `atlas.Animations` into a clip matching the tag's frame sequence (direction and repeat count), exact millisecond durations and loop flag. - `FromSpriteAnimation(name, anim)` does the same for any `sprite.Animation`, turning any frame `Event` names into clip events at each frame's start time. - `FromFrames(name, frames, fps, loop)` builds a clip stepping through an ordered slice of atlas frame names at a fixed frame rate `fps`. ## Playing a clip ```go lib := resource.NewLibrary(os.DirFS(".")) clip, err := resource.LoadAs[*resource.Animation](lib, "anims/hop.animation.yaml") if err != nil { return err } player, err := animclip.NewPlayer(clip, components, animclip.BindScene(built, "hero")) if err != nil { return err // an unknown property, a bad key, or a target the scene does not have } player.OnEvent = func(name string) { if name == "land" { mixer.Play(landSound) } } player.Play() // Inside game.Loop.Update: player.Update(dt) ``` `NewPlayer` turns the clip into a `tween.Timeline`, one tween per pair of neighboring keys eased by the first key's `interp` (`linear`, `smooth` or `step`), so playback runs on the same deterministic clock as every other [timeline](https://game.nsgo.dev/docs/tween/). A track holds its first key's value before it and its last key's value after it, as `Animation.Sample` does. The player writes nothing until the first `Seek` or `Update`. - `Play`, `Pause` and `Restart` start, stop and replay it; `Done` reports a clip that does not loop at its end. - `Seek(at)` writes every track's value at `at` without firing events. A looping clip wraps a time before `0` or past `Length` into `[0, Length)` and shows its end at exactly `Length`, so a playhead dragged to the end shows the last keys; one that does not loop clamps `at`. - `OnEvent` is called with the name of each clip event playback crosses, in time order. - `SetLoop` overrides the clip's `loop` for one player. - Key times and values are widened from the file's float32 by their shortest decimal (`KeyValue`, `Seconds`), so a key written `0.1` sits at exactly 100ms and plays the value 0.1. The player reads the clip once; to play a clip edited or reloaded by `Library.Reload`, make a new player. ## Binding A `Binder` connects each track to what it drives. It receives the track's target and resolved `Property` and returns the function that writes the value, which arrives already rounded and clamped for the property; an error fails `NewPlayer`, so a clip that names a missing object is refused before it plays. - `BindDoc(doc, self)` writes into the objects of a `sceneformat.SceneDoc`, refusing a `sprite.frame` track on an object without a sprite. - `BindScene(built, self)` writes into the objects of a `sceneformat.BuiltScene` and syncs each object it writes (`BuiltObject.Sync`), so the next `Draw` shows the object and its children at their new world transform, sprite frame and alpha, multiplied by the material's opacity as `Build` does. For a `sprite.frame` track, binding checks up front that the target object has a sprite and that its atlas holds every keyed frame name. A track's target may be a nested child object's ID. Component fields are written into the object's `components` mapping as `float64`, `int` or `bool`, creating the component's mapping when the object has none, so code that reads them with `ComponentRegistry.Resolve` sees the animated value. A custom `Binder` receives `Property.Frames` on `KindFrame` tracks and maps keyed indices to frame names with `p.Frame(v)`: ```go bind := func(target string, p animclip.Property) (func(float64), error) { e := world.Find(target) if e == nil { return nil, fmt.Errorf("no entity %q", target) } switch p.Name { case "x": return func(v float64) { e.Pos.X = float32(v) }, nil case animclip.PropertySpriteFrame: return func(v float64) { e.Frame = p.Frame(v) }, nil case "body.speed": return func(v float64) { e.Speed = v }, nil } return nil, fmt.Errorf("entity cannot play %s", p.Name) } ``` ## Sprite state machines A sprite state machine lives in a `*.states.yaml` file (version 1, schema [`states.v1.json`](https://game.nsgo.dev/docs/schemas/#published-schemas)): named `states` pointing at `*.animation.yaml` clips, typed `parameters` (`float`, `bool`, `trigger`), an `entry` state, and ordered `transitions` guarded by `when` expressions and/or `onEnd: true`. Wildcard `from: '*'` transitions (such as a `hurt` interrupt) are checked from any state other than the target. Attach the built-in `animator` component (`sceneformat.AnimatorComponentName`) to an object in a scene file: ```yaml components: animator: states: anim/knight.states.yaml startClip: idle ``` Play it on `game.Loop`'s fixed steps with `animclip.NewAnimator` (or `animclip.NewStateMachine` with a custom `Binder`): ```go lib := resource.NewLibrary(os.DirFS(".")) sm, err := animclip.NewAnimator(built, "knight", animclip.FSStates{FS: os.DirFS(".")}, lib, components) if err != nil { return err } sm.OnTransition = func(from, to string) { /* ... */ } sm.OnEvent = func(state, event string) { /* ... */ } // Inside game.Loop.Update(dt): sm.SetFloat("move.x", vx) sm.SetFloat("velocity.y", vy) sm.SetBool("on_floor", onFloor) if jumpPressed { sm.Trigger("jump") } sm.Update(dt) ``` - **Condition expressions**: `when` supports `||`/`or`, `&&`/`and`, `!`/`not`, `|param|` / `abs(param)`, unary `-`, and comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`, `≤`, `≥`). Expressions are parsed and type-checked against `parameters` at load time (`ParseStateMachine`). - **Triggers**: `Trigger(name)` arms a trigger parameter; it is automatically consumed when a transition referencing it fires or cleared at the end of the fixed step (`Update`). - **Scripted input and testing**: `InputDriver` maps project `input.Actions` (such as `move_left`, `move_right`, `jump`, `attack`, `hurt`) into locomotion parameters (`move.x`, `velocity.y`, `on_floor`, `jump`, `attack`, `hurt`), and `SimulateStateMachine` drives a state machine deterministically across fixed steps to report visited states, transition trace, and stuck states. - **Validation and references**: `game check` (`tooling/assetcheck`) validates every `*.states.yaml` file and `animator` component, refusing transitions to missing states, unknown clip files, and parameters no transition reads, with exact file and line numbers. `refs` follows both `animator.states` and `states[].clip` paths when moving files. --- Source: https://game.nsgo.dev/docs/assets/ # assets `game/assets` loads sprite atlases, sounds, images, raw bytes, and custom game data asynchronously off the engine goroutine, organizes them into per-scene groups with reactive progress signals, releases them cleanly when a scene ends, and provides a ready-made `LoadingScreen` component. ```go import "github.com/nsgo-dev/game/pkg/assets" ``` All `Manager` and `Group` methods run on the engine goroutine; file reading and parsing run in background goroutines and post results back via `core.Scope.Post` so animations and `game.Loop` never hitch. ## Creating a Manager and defining groups Create a `Manager` bound to a `*core.Scope` (typically your root game component's scope). Pass `WithFS` to serve `"asset:"` URIs from an `embed.FS` or `os.DirFS`, or `WithReadAsset` for custom storage: ```go //go:embed assets/* var assetFS embed.FS mgr := assets.NewManager(cx, assets.WithFS(assetFS)) // Register a scene's assets as a named group level1 := mgr.Group("level1"). AddAtlas("hero", "asset:hero.json", core.Src("asset:hero.png")). AddSound("jump", audio.Source{URI: "asset:sounds/jump.wav"}). AddImage("bg", core.Src("asset:bg.png")). AddCustom("map", "asset:maps/level1.tmj", parseMap, nil) ``` Chainable builders on `*Group`: | Method | What it loads | | --- | --- | | `AddAtlas(name, jsonURI, img)` | Reads & parses `sprite.LoadAtlas` off-thread, and prefetches `img` when URI-backed. | | `AddSound(name, src)` | Decodes a short sound via `audio.LoadSound`. | | `AddImage(name, src)` | Prefetches a URI-backed `core.ImageSource` via `core.Scope.PrefetchImage`. | | `AddBytes(name, uri)` | Reads raw bytes from `uri` off-thread. | | `AddCustom(name, uri, parse, release)` | Reads `uri` and parses it off-thread; invokes `release(val)` on group release or cancellation. | | `AddCustomLoader(name, uri, load, release)` | Same as `AddCustom`, passing a cancellable `context.Context` to `load`. | For one-off loads outside a group, `Manager` also exposes `LoadAtlas`, `LoadSound`, `LoadBytes`, and `LoadCustom`. ## Loading, reactive progress, and reading assets Start a group with `mgr.LoadGroup("level1", onDone)` or `level1.Load(onDone)`. Loading is idempotent: calling `Load` on an already-loaded group runs `onDone(nil)` immediately, and calling it while loading queues `onDone` onto the active load. Every status method on `*Group` is backed by a `core.Signal`, so reading them inside an NSGo view subscribes automatically: - `g.Progress()` (`float64` in `[0, 1]`) - `g.Loaded()` and `g.Total()` (`int`) - `g.Loading()`, `g.Done()` (`bool`), and `g.Err()` (`error`) Once loaded, retrieve typed assets from the group or from `Manager` (which searches the most recently registered group holding `name`): ```go heroAtlas, ok := mgr.Atlas("hero") jumpSound, ok := mgr.Sound("jump") bgImage, ok := mgr.Image("bg") rawLevel, ok := mgr.Get("map") ``` ## Releasing groups Release a scene's assets when leaving the scene with `mgr.ReleaseGroup("level1")` (or `level1.Release()`, or `mgr.ReleaseAll()`): ```go mgr.ReleaseGroup("level1") ``` Releasing closes every loaded `*audio.Sound`, calls custom `release` hooks, drops atlas/image/byte references for garbage collection, cancels any in-flight load, and resets progress to `0` so the group can be loaded again later. Disposing `Manager`'s `cx` scope releases all groups automatically and discards late completions without leaking. > Keeping decoded atlas images pinned outside NSGo's 64-source canvas cache is tracked in [nsgo#1127](https://github.com/nsgo-dev/nsgo/issues/1127). ## LoadingScreen Drop `assets.LoadingScreen` (or `assets.LoadingView(cx, props)`) directly into your component tree to start loading a group on mount, render a reactive progress bar, and transition once ready: ```go return assets.LoadingScreen{ Manager: mgr, Group: "level1", Title: "Loading Cavern", OnReady: func() { stage.Set("play") }, OnError: func(err error) { loadErr.Set(err) }, } ``` Set `View: func(progress float64, err error) core.Node` on `LoadingScreen` (or `Render` on `LoadingScreenProps`) to replace the default progress UI with your own branded loading view. ## Reloading on save Run the game with [`nsgo game dev`](https://game.nsgo.dev/docs/cli/#dev) and start a watcher on the asset directory it names, and every atlas, image and raw-bytes asset the manager has loaded changes in the running game within a second of its file being saved: ```go var opts []assets.Option if dir := hotreload.DevAssetsDir(); dir != "" { // Under game dev, read "asset:" URIs from the directory the watcher watches. opts = append(opts, assets.WithFS(os.DirFS(dir))) } mgr := assets.NewManager(cx, opts...) w := hotreload.NewDevWatcher(cx) // nil outside game dev and in release builds w.WatchAssets(mgr, func(path string, names []string, err error) { if err != nil { log.Printf("reload %s: %v", path, err) } }) ``` The watcher and the manager must see the same files: a `Manager` without `WithFS` reads `"asset:"` URIs from `assets/` in the working directory, and `nsgo dev` starts the game in the directory `game dev` was run from, not the project's, so under `game dev` the manager reads from `hotreload.DevAssetsDir()`, the absolute path of the directory `game dev` passes, as above. `WatchAssets` passes each changed file under the directory to `Manager.Reload` as `"asset:"` on the engine goroutine. An atlas whose JSON changed is parsed again, and one whose image changed draws the file's new bytes with the same frames; the `*sprite.Atlas` the group holds is updated in place, so code that kept the pointer draws the edit. JSON that no longer parses keeps the previous frames and reports the error. Images show the new bytes and raw bytes are replaced; sounds and custom assets load again only when their group does. An image that ships in several densities (`Scales`) reloads from the file the screen shows, such as `hero@2x.png` on a 2x screen; saving another density changes nothing until the screen shows it. A group mounted on a DLC pack with `SetFS` keeps the pack's copy of a file the pack has, so saving the base file does not change it. `Manager.Revision` counts the reloads that replaced something, so a `core.Canvas` that reads it in `Draw` draws again after each one; a game drawn every frame by `game.Loop` needs nothing more. For an atlas the game loads itself, such as one embedded with `go:embed`, `w.WatchAtlasFiles("sprites.json", "sprites.png", img, onReload)` delivers the atlas parsed from the saved files. For WGSL/Kage shaders and 3D shader materials, attach `hotreload.ShaderReloader` and `hotreload.MaterialReloader` with `w.WatchShaders` and `w.WatchMaterials`; see [Hot-reloading shaders and materials](https://game.nsgo.dev/docs/render3d/#hot-reloading-shaders-and-materials). `NewDevWatcher` returns nil when the game is not running under `game dev`, and a nil watcher's methods do nothing, so the calls can stay in the game; in release builds (`-tags release`) they compile to nothing. ## Downloadable packs (DLC) `assets.NewDLCManager(assets.DLCOptions{...})` downloads ZIP packs described by a `PackSpec` (usually parsed from a manifest with `ParsePackManifest`), resumes interrupted downloads with HTTP Range requests, verifies size, SHA-256 and an Ed25519 signature, and caches them in a `PackCache`. `Fetch` returns the verified pack as an `fs.FS`; `FetchGroup` also mounts it into a `Group` and loads it. ```go dlc := assets.NewDLCManager(assets.DLCOptions{ AppBuild: 42, PublicKey: packPublicKey, Cache: assets.NewDirPackCache(cacheDir), Limits: assets.PackLimits{MaxTotalBytes: 256 << 20}, }) group, err := dlc.FetchGroup(ctx, mgr, spec, registerAssets, onProgress) ``` - Without a `PublicKey`, every pack is refused with `ErrInvalidSignature`, because whoever supplies the `PackSpec` (URL, size and hash) would otherwise choose what is mounted. Set `AllowUnsigned` to accept unsigned packs during development or when the specs ship inside the app. - A cached pack is verified again on the same reader that is mounted. `DirPackCache` reads a mounted pack through one open file, so replacing or deleting the cache file afterwards does not change what the mount serves (on Windows, deleting a mounted pack fails until it is released). - The `fs.FS` that `Fetch` returns is also an `io.Closer`. Close it when the pack is no longer used; one never closed is released when it is garbage collected. `FetchGroup` hands its pack to the group, which releases it on `Group.Reset`, `Group.SetFS`, the next `FetchGroup` into the same group, or when the asset manager's scope is disposed. `Remove` of a pack that is still mounted deletes its partial download at once and the cached pack when the last mount is released, so it never pulls the bytes from under a loaded group; a `Fetch` of the pack before then keeps it. - `Limits` caps the number of entries, the size of one file, the total unpacked size and the archive itself (zero fields use `DefaultPackLimits()`: 32768 entries, 256 MiB, 1 GiB and 1088 MiB). A pack over a limit is refused before mounting. A download stops with `ErrPackTooLarge` once it would pass `MaxPackBytes`, which bounds the `.part` file of a `PackSpec` without a `Size`. A mounted pack reads each file as it decompresses, growing its buffer with the bytes that arrive rather than allocating the size the header claims, and fails with `ErrPackTooLarge` past `MaxFileBytes`. - A spec that could never verify (a malformed `sha256` or `signature`, or a negative `size`) is refused before the cache is touched, so it cannot delete a good cached pack. A cached pack is deleted only when its bytes do not match the spec's size or hash; one whose bytes match but whose signature or contents are refused stays, since downloading it again would fetch the same bytes. - A resumed download that gets `206 Partial Content` without a `Content-Range` header starts over from the first byte rather than appending a body whose range it cannot check. - `ParsePackManifest` refuses fields it does not define, such as a misspelt `sha265`, a key given twice in one object, and anything after the manifest, with the line and a fix. --- Source: https://game.nsgo.dev/docs/bullets/ # bullets `game/bullets` spawns, moves and draws the bullet patterns of shooters: rings, spirals and aimed bursts defined in YAML, taken from a `perf.Pool` and drawn through one `sprite.Batch`. ```go import "github.com/nsgo-dev/game/pkg/bullets" ``` ## Pattern files A pattern file is YAML with a `version` and a list of named `patterns`: ```yaml version: 1 patterns: - name: bloom kind: ring frame: orb count: 24 speed: 90 spin: 7.5 shots: 6 interval: 400ms lifetime: 6s radius: 4 - name: vortex kind: spiral frame: orb count: 5 speed: 140 speedJitter: 8 angleJitter: 2.5 spin: 11 shots: 0 interval: 50ms accel: -20 turn: 15 radius: 3 - name: volley kind: aimed frame: dart count: 7 speed: 220 spread: 45 shots: 3 delay: 1s interval: 150ms lifetime: 3s radius: 2.5 faceHeading: true ``` `Parse` reads a file and refuses unknown fields, a `version` other than `FormatVersion` (1), trailing YAML documents and invalid patterns. `Encode` writes a file back with 2-space indents, its fields in a fixed order and zero optional fields left out, so the same file always encodes to the same bytes and a load and save changes nothing. `File.Pattern(name)` finds a pattern. Angles are in degrees clockwise from +X on the screen, speeds in points a second, and durations are Go durations (`50ms`, `2s`). | Field | Meaning | | --- | --- | | `name` | Unique, not empty | | `kind` | `ring`, `spiral` or `aimed` | | `frame` | Atlas frame each bullet draws; empty spawns bullets that move and collide but draw nothing | | `count` | Bullets each shot fires, 1 to `MaxCount` (4096) | | `speed`, `speedJitter` | Starting speed, varied by a random amount in `[-speedJitter, speedJitter)`, never below 0 | | `angle`, `angleJitter` | Direction of a shot's first bullet (for `aimed`, the turn from the target's direction), varied per bullet by `[-angleJitter, angleJitter)` | | `spread` | Arc an `aimed` burst covers from its first bullet to its last; `aimed` only, above 0 when `count` is above 1 | | `spin` | Degrees each shot turns more than the one before; a `spiral` needs one other than 0 | | `shots`, `delay`, `interval` | Number of shots (0 fires until stopped), time before the first, time between shots (at least `1ms`, or 0 when `shots` is 1) | | `lifetime` | How long each bullet lives; 0 keeps it until it leaves the field's bounds | | `accel`, `turn` | Speed change in points a second each second (a bullet slowed to 0 stops), and path curve in degrees a second | | `radius` | Hit radius, also used to tell when a bullet has left the bounds | | `faceHeading` | Turns the sprite to the direction the bullet moves | | `z` | Sprite order in the field's batch | - `ring` spaces `count` bullets evenly around a full turn, the first at `angle`, turned by `spin` more each shot. - `spiral` is a ring with a `spin`: with a short `interval`, each of its `count` bullets traces an arm. - `aimed` spreads `count` bullets evenly across `spread`, centered on the direction from the emitter to its target and turned by `angle` and `spin`. With an odd `count` and no `angle` or `spin`, the middle bullet flies straight at the target; a single bullet flies at the target turned by `angle`. ## Field and Emitter A `Field` owns the live bullets. `NewField(atlas, capacity)` keeps `capacity` bullets ready in a pool, so spawning up to that many allocates nothing. Set `Bounds` to remove bullets whose hit circle has wholly left the playfield, and `Limit` to cap how many the field holds. `NewEmitter(field, pattern, seed)` fires a copy of the pattern into the field, and checks that the field's atlas has the pattern's frame. Move it with `X`, `Y`, aim it with `TargetX`, `TargetY`, pause it with `Stopped`, and start it over with `Reset`. A stopped emitter's clock stops too, so when it resumes it picks up its pattern where it paused instead of firing the shots it missed. ```go file, err := bullets.Parse(data) field := bullets.NewField(atlas, 6000) field.Bounds = math2d.Rect{W: 480, H: 640} volley, _ := file.Pattern("volley") boss, err := bullets.NewEmitter(field, volley, seed) loop := &game.Loop{ Update: func(dt time.Duration) { boss.X, boss.Y = bossX, bossY boss.TargetX, boss.TargetY = playerX, playerY field.Update(dt) // move the bullets already in flight boss.Update(dt) // then fire the shots due in this step field.RemoveFunc(func(b *bullets.Bullet) bool { return b.Circle().Overlaps(playerHitbox) }) }, } // In a core.Canvas's Draw: field.Draw(d) ``` - Update the field before its emitters each step. A shot due partway through a step spawns its bullets where they are at the step's end, so bullets do not bunch up when the interval is not a whole number of steps. - One `Update` fires at most 4096 bullets' worth of shots (at least one shot). When more are due, as after a long step from a hitch, it fires the latest and skips the earlier ones, which count as fired but spawn nothing and draw no random numbers. - `Field.Bullets()` lists the live bullets oldest first, each with its position, `Speed`, `Heading` (radians), `Radius`, `Age`, `Lifetime`, `Pattern` name, `Shot` index and `Sprite`. The bullets are the field's: do not keep a pointer past the next `Update`, `RemoveFunc` or `Clear`, as the field reuses it. - `Field.Update` keeps the order of the bullets it keeps, and `Field.Draw` draws them lowest `Z` first and oldest first for the same `Z`. - A shot past the field's `Limit` spawns only the bullets that fit, and still draws the same random numbers. ## Determinism An emitter draws its jitter from its own `random.Stream`. Two emitters with the same pattern and seed, moved and stepped with the same `dt`s and targets, spawn the same bullets in the same places: on one build target the results are bit-for-bit equal, which `random.AssertDeterministic` checks in the package's tests. Floating-point results can differ across CPU architectures, so a lockstep game across platforms should compare inputs, not bullet positions. ## Performance `BenchmarkFrame5000` runs one 60 fps frame of a steady 5000-bullet scene: ten spiral emitters with jitter and curving paths, half of them with turned sprites, moving, expiring, spawning and drawing into a `core.Drawing`. On a desktop Ryzen 9 3900X it takes about 0.63 ms of the 16.7 ms a frame has; moving 5000 bullets alone (`BenchmarkUpdate5000`) takes about 0.14 ms. The performance baselines in CI (`benchmarks/baseline.yaml`) fail a change that makes a frame take more than 6.25 ms on the CI runner. This measures the CPU work of a frame: simulating the bullets and recording their draw ops. It does not measure how long the platform's renderer takes to put those ops on screen, which is NSGo's and depends on the GPU. - Moving and firing allocate nothing once the pool is warm. - `sprite.Batch` draws the bullets as runs through NSGo's `Drawing.DrawAtlas`, which copies each run and allocates three values per run, however many bullets it holds. --- Source: https://game.nsgo.dev/docs/cards/ # cards `game/cards` drags cards between the slots of a board in the game view and lays them out as fanned hands, decks, piles and grids. A card dropped on a slot that accepts it snaps into place; one dropped anywhere else flies back to where it came from. Every move is a `game/tween` advanced on `game.Loop`'s fixed steps, and the mouse and touch take the same path. ```go import "github.com/nsgo-dev/game/pkg/cards" ``` ## Boards, slots and cards A `Board` holds `Slot`s in the order they are added (later slots sit on top), and each slot holds an ordered list of `Card`s, the first at the bottom. A slot's `Rect` is both where its `Layout` places its cards and where a pointer drops onto it. The zero `Board` is ready to use. ```go board := &cards.Board{CardSize: math2d.V2(63, 88), Curve: core.EaseOut} hand := &cards.Slot{ID: "hand", Rect: math2d.Rect{X: 40, Y: 400, W: 560, H: 120}, Layout: cards.Fan{Arc: 24, Sag: 14}} play := &cards.Slot{ID: "play", Rect: math2d.Rect{X: 40, Y: 160, W: 560, H: 200}, Layout: cards.Grid{Gap: math2d.V2(8, 8)}, Accepts: []string{"spell"}, Capacity: 5} deck := &cards.Slot{ID: "deck", Rect: math2d.Rect{X: 620, Y: 400, W: 63, H: 88}, Layout: cards.Stack{Offset: math2d.V2(0, -0.5), Depth: 8}, Grab: cards.GrabTop} for _, s := range []*cards.Slot{hand, play, deck} { board.AddSlot(s) } for _, c := range opening { board.Add(&cards.Card{ID: c.Name, Tags: []string{c.Kind}, Data: c}, hand, -1) } ``` - `Add` places a card at once, for the opening position; `Move` tweens it to another slot, as dealing or an undo does; `Remove` takes it off and closes the gap. None of them checks the slot's rules. - `Card.Pose()` is where to draw a card now: its center `Pos` and its rotation `Rot` in radians. `Slot.Cards()`, `Slot.Top()`, `Card.Slot()` and `Card.Index()` say where it belongs. - `Card.Locked` keeps a card in place, and `Slot.Grab` says which cards of a slot a pointer may take: `GrabAny` (a hand), `GrabTop` (a deck or a discard pile) or `GrabNone`. ## Layouts | Layout | Arranges | Fields | | --- | --- | --- | | `Fan` | A hand in a row centered in the slot, tilting and dropping toward its ends | `Spacing` between centers (0 is 60% of the card's width), `Arc` in degrees for a full-width hand, `Sag` in points at its ends | | `Stack` | A deck or a pile from the slot's top-left corner | `Offset` from each card to the next, `Depth` capping how many offsets show | | `Grid` | Rows of cards from the slot's top-left corner | `Columns` (0 fits the slot's width), `Gap` between cards | A fan closes up when the hand would not fit the slot, and its cards tilt by how far they sit from the middle, so a short hand stays nearly flat and a full one reaches `±Arc/2`. A layout also decides where a dropped card goes: a fan inserts it at the place nearest its center, so dragging within a hand reorders it, a grid at the cell under it and a stack on top. A game can write its own `Layout` with `Arrange` and `InsertIndex`. After changing a slot's `Rect` or `Layout`, `board.Relayout(slot)` tweens its cards to their new places. ## Dragging with the mouse and touch NSGo reports the primary mouse button as finger 0 of `core.TouchEvent` on the desktops and every pointer as a finger on the web, so one handler takes the mouse and touch alike. Attach the board to the view that holds the game's `Canvas`, and step it in the loop: ```go view := core.View{Children: []core.Node{core.Canvas{Draw: draw}}} board.Attach(&view) // chains any OnTouch the view already has loop.Update = func(dt time.Duration) { board.Update(dt) } ``` Touch positions arrive in the view's coordinates; set `board.MapPoint` when the board is drawn through a camera or a scaled viewport, returning false for a point outside it. A game that reads pointers some other way calls `PointerDown`, `PointerMove`, `PointerUp` and `PointerCancel` with its own pointer IDs. - A press takes the topmost card under it, following each card's rotation. The card starts following once the pointer moves more than `DragSlop` (6 points by default), keeping where it was held and turning upright; a release before that is a tap (`OnTap`). - Each finger drags its own card, so two hands can play at once; a card already pressed by one pointer is not taken by another. - On release, the card drops on the topmost slot under the pointer, or failing that the slot its body overlaps most. It snaps in over `SnapDuration` when `CanDrop` allows it: its own slot always does, another needs room under `Capacity`, one of the card's tags in `Accepts` when that is set, and `Slot.Accept` and `Board.Accept` when they are set. Otherwise, or over no slot, or when the touch is cancelled, it flies back to its place over `ReturnDuration`. - `OnPickUp`, `OnDrop` (with the slots and indices it moved between) and `OnReturn` (with the slot that refused it, if any) report each step, and `DropTarget(card)` says during a drag which slot is under the card and whether it would accept it, for highlighting. ```go board.Accept = func(c *cards.Card, from, to *cards.Slot) bool { return to != play || mana >= c.Data.(Spell).Cost } board.OnDrop = func(e cards.DropEvent) { if e.To == play { cast(e.Card.Data.(Spell)) } } ``` ## Drawing `DrawOrder(dst)` lists the cards bottom first: each slot's cards in slot order, then the cards being dragged or flying, in the order they were lifted. Draw each at its pose: ```go order = board.DrawOrder(order[:0]) for _, c := range order { p := c.Pose() d.Save() d.Translate(p.Pos.X, p.Pos.Y) d.Rotate(p.Rot) drawCard(d, c, board.Size()) d.Restore() } ``` Once the board's slices have grown, `DrawOrder`, `Update` and `PointerMove` during a drag allocate nothing. Picking up a rotated card, dropping one and sending one back each allocate a tween for every card that starts to move. ## Board files A board's card size and slots can be written as YAML and loaded with `ParseBoardDoc` and `LoadBoard`. Unknown fields are refused, the version must be `1`, and `EncodeBoardDoc` writes the fields in a fixed order and in block style, as below, so a file in that form is unchanged when read and written again; a hand-written file in flow style (`rect: {x: 40, ...}`) comes back in block style the first time it is saved. `board.Doc()` turns a board built in code back into a `BoardDoc`; a slot's `Accept` function and the board's callbacks and timings stay in code. ```yaml version: 1 card_size: w: 63 h: 88 slots: - id: hand rect: x: 40 "y": 400 w: 560 h: 120 layout: fan: arc: 24 sag: 14 - id: deck rect: x: 620 "y": 400 w: 63 h: 88 layout: stack: offset: x: 0 "y": -0.5 depth: 8 accepts: - spell capacity: 40 grab: top ``` Each slot names exactly one of `fan`, `stack` or `grid`; `grab` is `top` or `none`, and is left out for the default, any card; `grab: any` is refused so the default has one form. The encoder quotes the `y` key, which YAML 1.1 reads as a boolean, so other tools read the file the same way. --- Source: https://game.nsgo.dev/docs/cloudsave/ # cloudsave `github.com/nsgo-dev/game/pkg/cloudsave` is a self-hostable cloud save service: each player account has save slots over HTTPS, kept in versions. Two devices writing the same slot at once cannot overwrite each other, a slot over the size limit is refused with a clear error, and the last few versions of each slot can be listed and restored. Games talk to it through `liveops.CloudClient`, a `liveops.CloudSync`, so a `liveops.CloudSyncer` keeps local saves in step with it and resolves conflicts by its policy. The service is server-side code in its own packages; a game client imports only `liveops`. It keeps no accounts of its own: it verifies the tokens of the [account service](https://game.nsgo.dev/docs/accounts/) offline with `accounts/token`, and files each player's slots under the token's subject, the account ID. A player signed in to the same account on the web and on an Android phone reads and writes the same slots. | Package | What it holds | | --- | --- | | `cloudsave` | `Service`, `Config`, the `Store` interface, `MemoryStore` and the HTTP `Handler` | | `cloudsave/sqlstore` | A `Store` in SQLite (`OpenSQLite`, pure Go, every target but the web) or Postgres (`OpenPostgres`, shared by several service processes) | | `cloudsave/storetest` | The `Store` contract tests, for a store of your own | | `cloudsave/cmd/cloudsaved` | A standalone HTTP server | | `liveops` | `CloudClient`, the game's side | ## On the device ```go cloud, err := liveops.NewCloudClient(liveops.CloudClientOptions{ URL: "https://saves.example.com", Token: func(ctx context.Context) (string, error) { return session.Token(ctx) // the account service's token, refreshed when it expires }, }) if err != nil { return err } syncer, err := liveops.NewCloudSyncer(liveops.CloudSyncOptions{ Local: save.StorageBackend(cx.Storage(), "mygame"), Cloud: cloud, State: cx.Storage(), Device: deviceID, Policy: liveops.PolicyKeepBoth, }) ``` Save through `save.NewStore(syncer.Backend())` and call `syncer.Sync(ctx)` when the game starts, after a save and when it returns to the foreground; see [liveops](https://game.nsgo.dev/docs/liveops/#cloud-saves) for how the syncer detects and resolves conflicts. `CloudClient` needs an `https` URL; `http` is accepted only on a loopback host (`localhost`, `127.0.0.1`, `::1`) for development. It uses `net/http`, so it works on every target: on the web its requests go through the browser's `fetch`, and the page's origin must be in the service's `allowedOrigins`; an Android app needs the `INTERNET` permission. Its errors wrap the `liveops` sentinels: | Error | When | | --- | --- | | `ErrSlotNotFound` | The slot, or the version asked for, does not exist | | `ErrCloudChanged` | A conditional write lost to another device's; nothing was written | | `ErrSlotTooLarge` | The payload is over the service's `maxSlotBytes`; the message gives the limit | | `ErrTooManySlots` | A new slot would exceed the service's `maxSlots` | | `ErrCloudUnavailable` | The network or the service failed, the token source failed or the service refused the token; a sync stops on it as it does when offline | A done context's error is returned as it is. ## Concurrent writes Every write names the payload it replaces. `CloudClient` implements `liveops.ConditionalCloudSync`: `SaveIf(ctx, slot, data, match)` writes only while the slot holds the payload whose `liveops.PayloadHash` is `match` (`"sha256:"` and the hex SHA-256 of the raw bytes), or does not exist when `match` is empty, and `DeleteIf` deletes on the same condition. Over HTTP the condition is `If-Match: ""` or `If-None-Match: *`; the service checks and writes in one atomic step, and answers `412 changed` when the slot holds anything else. `CloudSyncer` makes every cloud write conditional on the copy it read. When the phone and the browser both changed a slot and the browser uploads first, the phone's upload fails with `ErrCloudChanged` and changes nothing; on its next sync the phone sees both copies as a conflict, and the policy keeps the newer, keeps both as a fork slot, or asks the player. No upload is ever overwritten silently. ## Versions and restore Every write or delete adds a version to the slot, numbered from 1, and the service keeps the newest `keepVersions` of them. A delete is a version that marks the slot deleted, so a deleted slot keeps its history and can be brought back. ```go versions, err := cloud.Versions(ctx, "main") // newest first: Number, Deleted, Hash, Size, Created data, err := cloud.LoadVersion(ctx, "main", versions[2].Number) err = cloud.Restore(ctx, "main", versions[2].Number) err = cloud.Purge(ctx, "main") // the slot and its history, for good ``` `Restore` writes the old copy as a new version, conditional on the slot still holding the copy it read (`ErrCloudChanged` otherwise); restoring a deletion deletes the slot. A payload written by `CloudSyncer` is re-stamped with the next revision and the current time, so every device takes the restore as the newest copy: a device whose copy has not changed since its last sync downloads it, and one with unsynced changes gets a conflict its policy resolves. Other payloads are restored byte for byte. `Service.Restore` on the server restores the bytes unchanged. ## Limits - `maxSlotBytes` bounds a payload. A larger one is refused with `413 slot_too_large` and `{"limit": maxSlotBytes}` before the service reads past the limit, and the slot keeps its current copy. A `CloudSyncer` payload is the save inside a JSON envelope: about 250 bytes more, with the save's quotes and backslashes escaped, or base64, a third larger, for data that is not UTF-8. - `maxSlots` bounds an account's live slots; a write that would create one more is refused with `409 too_many_slots`. Fork slots made by `PolicyKeepBoth` count. A deleted slot does not count, but once an account has more than `maxSlots` deleted slots the oldest are purged with their history, so an account never holds more than twice `maxSlots` slots. - Slot names are 1 to 200 bytes of UTF-8 without control characters or `/`, other than `.` and `..` (`ValidateSlot`); every name `save.ValidateSlot` accepts passes. In URLs they are path segments, escaped as `url.PathEscape` does. ## Configuration `Config` is a versioned YAML file: ```yaml version: 1 maxSlotBytes: 1048576 maxSlots: 32 keepVersions: 5 allowedOrigins: - https://play.example.com ``` | Field | Meaning | | --- | --- | | `version` | The schema version, `1` | | `maxSlotBytes` | The largest payload, from 1 byte to 64 MiB | | `maxSlots` | Live slots per account, from 1 to 10000 | | `keepVersions` | Versions kept per slot, the current one included, from 1 to 100 | | `allowedOrigins` | Web origins whose pages may call the service; omitted when empty | `ParseConfig` refuses unknown fields, trailing documents, out-of-range values and an origin with a path, a wildcard, a port outside 1 to 65535 or a scheme other than `http` and `https`. `Config.Marshal` writes the canonical form: the fields in the order above and `allowedOrigins` only when it has entries. A file in that form, such as one `Marshal` or `cloudsaved init` wrote, reads back and writes again unchanged. `DefaultConfig` returns the settings shown, without origins. ## Storage `Store` keeps the versions. Its `Append` is atomic: of two writes based on the same version, at most one commits. ```go store, err := sqlstore.OpenSQLite(ctx, "saves.db") // one service process store, err := sqlstore.OpenPostgres(ctx, os.Getenv("CLOUDSAVE_POSTGRES_DSN")) // several processes svc, err := cloudsave.New(cfg, cloudsave.Options{Store: store, Tokens: verifier, Logger: slog.Default()}) ``` The SQL store keeps two tables, `cloudsave_slots` (each slot's newest version) and `cloudsave_versions` (the kept versions with their payloads), and versions its schema in `cloudsave_schema`. Each write compares and sets the slot's newest version number in one transaction; on Postgres it also takes an advisory lock on the account, so the slot count and pruning see every concurrent write. SQLite uses the pure-Go `modernc.org/sqlite` driver with write-ahead logging and one connection; Postgres uses `github.com/jackc/pgx/v5`. Both create their tables when missing and refuse a schema newer than they know. `NewMemoryStore` keeps everything in memory for tests and prototypes, and a store of your own passes `storetest.Run`. ## HTTP `Service.Handler` serves the service. Every request carries `Authorization: Bearer ` with a token from the account service, and every response `Cache-Control: no-store`. Payloads are `application/octet-stream`; a version is `{"slot", "version", "deleted", "hash", "size", "created"}`, `created` in RFC 3339 with milliseconds and `deleted` and `hash` only when set. | Request | Answer | | --- | --- | | `GET /v1/saves` | `{"slots": [version]}`, the live slots by name | | `GET /v1/saves/{slot}` | the payload, with `ETag` (its hash in quotes) and `Save-Version` | | `PUT /v1/saves/{slot}` | version; `If-Match: ""` or `If-None-Match: *` make it conditional | | `DELETE /v1/saves/{slot}` | 204; the same headers make it conditional | | `GET /v1/saves/{slot}/versions` | `{"versions": [version]}`, newest first | | `GET /v1/saves/{slot}/versions/{n}` | the payload of version `n` | | `DELETE /v1/saves/{slot}/versions` | 204, the slot and its history purged | Errors are `{"error": code}`: `bad_request` 400 (an invalid slot name, version number or precondition header), `invalid_token` 401, `not_found` 404, `too_many_slots` 409, `deleted` 410 (a version that is a deletion has no payload), `changed` 412, `slot_too_large` 413 with `limit`, `unavailable` 503 when the request was cancelled or timed out, and `internal` 500. For `allowedOrigins` the handler answers CORS preflight requests and exposes `ETag` and `Save-Version`. It does not limit request rates: run it behind TLS and a rate limiter. ## cloudsaved `cloudsave/cmd/cloudsaved` runs the service: ```sh cloudsaved init -config cloudsave.yaml cloudsaved serve -config cloudsave.yaml -keyset keys.yaml -sqlite saves.db -addr :8081 CLOUDSAVE_POSTGRES_DSN=postgres://... cloudsaved serve -config cloudsave.yaml -keyset keys.yaml -postgres ``` `init` never overwrites a configuration. `-keyset` is the key set file `accountsd genkey` keeps; `serve` reads it once at start, so restart it after a key rotation adds a key. `serve` logs JSON to stderr and stops on SIGINT or SIGTERM. --- Source: https://game.nsgo.dev/docs/cutscene/ # cutscene `game/cutscene` plays both pre-rendered video cutscenes and in-engine timeline cutscenes in a game, in a scene or between scenes. Video cutscenes play in NSGo's own video view (`core.Video`) over the game's view while pausing `Loop` and `Mixer`. Timeline cutscenes run deterministically on `game.Loop` fixed steps against a `sceneformat.BuiltScene` or `sceneformat.SceneDoc`, driving camera, actor, localized dialogue, sound effect and music tracks. Both kinds are skippable and call the game back when they end. ```go import "github.com/nsgo-dev/game/pkg/cutscene" ``` ## Cutscene files A cutscene is a `Cutscene`, written in YAML as either version 1 (video only, `cutscene.MinVersion`) or version 2 (video or timeline, `cutscene.CurrentVersion`). Published JSON Schemas live at `https://game.nsgo.dev/schemas/cutscene.v1.json` and `https://game.nsgo.dev/schemas/cutscene.v2.json`. ### Video cutscenes (version 1 and 2) ```yaml version: 1 source: asset:cutscenes/intro.mp4 group: cutscenes skippable: true skipAfter: 1.5s fit: cover ``` | Key | Meaning | | --- | --- | | `version` | `1` (`cutscene.MinVersion`) or `2` (`cutscene.CurrentVersion`). | | `kind` | Optional in version 2: `video` (default when `source` is set) or `timeline`. Forbidden in version 1. | | `source` | The video: an `asset:` path in the app's resources, a project-relative path or a URL, as `core.Video` takes. Required for video cutscenes. | | `group` | The mixer group whose volume, times the master volume, the video plays at. Left out: the master volume alone. | | `skippable` | Whether the player can skip it. Left out: `false`. | | `skipAfter` | How far into the cutscene a skippable cutscene must play before a skip works, written as Go writes durations (`500ms`, `2s`), so a press meant for the game just before it does not skip it at once. Left out: from the start. | | `fit` | How the picture fits the screen: `contain` (the default, with bars), `cover` (cropped) or `stretch` (distorted). | | `transparent` | Leave the screen behind the picture clear rather than black, so the game shows in the bars and through a video with an alpha channel where the platform keeps it. | ### Timeline cutscenes (version 2) A version 2 timeline cutscene (`*.cutscene.yaml`) sets `kind: timeline`, `length` and ordered `tracks` of clips, each with a `start`, `duration` and optional `easing` (`linear`, `easeIn`, `easeOut`, `easeInOut`, `hold`): ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/cutscene.v2.json version: 2 kind: timeline scene: scenes/level_01.scene.yaml length: 12s skippable: true skipAfter: 1s tracks: - id: camera name: Camera kind: camera clips: - id: cam1 start: 0s duration: 1.6s easing: hold action: hold target: door - id: cam2 start: 1.6s duration: 2.4s easing: easeInOut action: pan target: knight - id: cam3 start: 4s duration: 8s action: follow target: knight - id: knight name: Knight kind: actor target: knight clips: - id: kn1 start: 1s duration: 2.4s easing: easeOut action: walk fromX: 60 toX: 220 state: run - id: kn2 start: 3.4s duration: 4.6s action: state state: idle - id: slime name: slime_01 kind: actor target: slime_01 clips: - id: sl1 start: 6s duration: 800ms easing: easeIn action: drop fromY: -40 toY: 276 - id: sl2 start: 6.8s duration: 5.2s action: patrol fromX: 420 toX: 520 speed: 40 - id: dialogue name: Dialogue kind: dialogue clips: - id: dl1 start: 3.6s duration: 2.4s line: intro.knight.01 - id: sfx name: Sound kind: sound group: sfx clips: - id: sx1 start: 200ms duration: 600ms source: audio/door_slam.wav - id: music name: Music kind: music group: music clips: - id: mu1 start: 2s duration: 10s source: audio/cellar_theme.ogg fadeIn: 2s ``` | Track kind | Track fields | Clip actions & fields | | --- | --- | --- | | `camera` | `id`, `name`, `kind`, `clips` | `action: hold` (`target` or `toX`/`toY`, optional `offsetX`/`offsetY`, `zoom`), `action: pan` (`target` or `toX`/`toY`, optional `fromX`/`fromY`, `offsetX`/`offsetY`, `zoom`, `easing`), `action: follow` (`target`, optional `offsetX`/`offsetY`, `zoom`). | | `actor` | `id`, `name`, `kind`, `target` (scene object ID), `clips` | `action: walk` (`toX`/`toY`, optional `fromX`/`fromY`, `state`, `easing`), `action: state` (`state`), `action: drop` (`toY`, optional `fromY`/`fromX`/`toX`, `state`, `easing`), `action: patrol` (`toX`/`toY`, optional `fromX`/`fromY`, `speed`, `state`, `easing`). | | `dialogue` | `id`, `name`, `kind`, `clips` | `line` (required l10n key — text lives in the localization tables, never inline), optional `speaker`. | | `sound` | `id`, `name`, `kind`, optional `group` (default `sfx`), `clips` | `source` (audio path or URI), optional `group`, `volume` (`[0, 1]`). | | `music` | `id`, `name`, `kind`, optional `group` (default `music`), `clips` | `source`, optional `group`, `volume` (`[0, 1]`), `fadeIn`, `fadeOut`, `loop`. | `cutscene.Parse(data)` reads both versions strictly, refusing unknown keys, a second YAML document, unsupported versions, timeline fields in version 1, mixing video and timeline fields, overlapping clips on non-sound tracks, non-finite numbers and negative or non-string durations. `cutscene.Encode(c)` writes canonical 2-space YAML (prefixing version 2 files with `SchemaCommentV2` and keeping version 1 output unchanged) so files round-trip byte for byte. A cutscene constructed in code may leave `Version` at 0. ## Playing a timeline cutscene `NewTimelinePlayer(c, target)` runs a timeline cutscene deterministically on `game.Loop`'s fixed steps against a `*sceneformat.BuiltScene` (or `*sceneformat.SceneDoc`), resolving dialogue line IDs through an `*l10n.Catalog` and triggering sound/music cues: ```go tl, err := cutscene.NewTimelinePlayer(c, cutscene.TimelineTarget{ Scene: builtScene, Catalog: catalog, Locale: "en", Mixer: mixer, OnActorState: func(actorID, state string) { setAnim(actorID, state) }, OnSound: func(clip cutscene.Clip, group string, vol float32) { playSFX(clip.Source, group, vol) }, OnDone: func(r cutscene.Result) { resumeGameplay() }, }) if err != nil { return err } tl.Play() // Inside game.Loop.Update: tl.Update(dt) ``` `tl.Seek(at)` scrubs directly to any timestamp in `[0, Length]` and evaluates actor, camera and dialogue states purely without firing sound, music or completion callbacks. `tl.Reset()` rewinds to time 0 and restores initial actor and camera positions. To wire the same skip keys, press-to-skip, back handling, `CanSkip()`, reactive `Dialogue()` and between-scene transitions (`TimelineScene`) as video cutscenes, play through `Player`: ```go _, err := player.PlayTimeline(c, cutscene.TimelineTarget{Scene: builtScene, Catalog: catalog}, func(r cutscene.Result) { resumeGameplay() }) // Inside game.Loop.Update: player.Step(dt) ``` Unlike video cutscenes, `PlayTimeline` leaves `Options.Loop` and `Options.Mixer` running so the scene continues drawing and playing cutscene audio while `Player.View()` captures skip input. ## Validation with `game check` and `refs` `game check` (package `tooling/assetcheck`) validates every `*.cutscene.yaml` / `*.cutscene.yml` file in a project: - Parses and validates the cutscene schema. - Verifies that `scene` (when set) and every project-relative video or audio `source` exists. - Verifies that every actor track `target` and camera clip `target` names an object in the referenced scene (including inherited and instanced scenes). - Verifies that every dialogue clip `line` ID exists in the project's YAML localization string tables (`l10n.ParseYAML`), reporting missing IDs with file and line. `refs` (`game mv` and `game index`) tracks `scene`, project-relative video `source` and timeline audio `source` paths in `*.cutscene.yaml` files so moving a scene or audio asset rewrites cutscene references in place. ## Playing a video cutscene Make one `Player` for the game and mount its `View` over the game's view, as the last child of the view that holds the canvas: ```go loop := &game.Loop{Update: update, Draw: draw} loop.Run(cx) mixer := sound.NewMixer(cx, "sound") player := cutscene.NewPlayer(cx, cutscene.Options{Loop: loop, Mixer: mixer}) return core.View{Class: "flex-1", Children: []core.Node{ core.Canvas{Class: "flex-1" /* ... */}, player.View(), }} ``` `View` shows nothing while no cutscene plays. `player.Play(c, done)` plays one, from a game's `Update` or anywhere else on the engine's goroutine: ```go if bossDoorOpened { player.Play(bossIntro, func(r cutscene.Result) { startBossFight() }) } ``` While it plays: - `Options.Loop` is paused (`Loop.SetPaused`), so `Update` stops and `Draw` goes on under the video. When the cutscene ends the loop is set back as it was, so one the game had paused stays paused. - `Options.Mixer` is suspended (`Mixer.Suspend`, see [sound](https://game.nsgo.dev/docs/sound/)): effects stop and music pauses, then plays on from there. - The display is kept awake, and the video pauses while the app is in the background and plays on as it returns. `done` receives a `Result`: its `Reason` (`Finished`, `Skipped`, `Stopped` or `Failed`), the `Position` the video reached as the platform last reported it, and for `Failed` the platform's `*core.MediaError` in `Err`. The loop and the mixer are back by the time `done` runs, so it can switch scenes or play the next cutscene. `Play` returns an error, and plays nothing, for a cutscene with no source, an unknown fit or a negative `skipAfter`; playing a cutscene while another plays stops the first, whose `done` is told `Stopped`. If that `done` plays a cutscene of its own, that one plays instead, and `Play` returns `cutscene.ErrReplaced`, playing nothing and never calling its own `done`. `Stop` ends the one playing, skippable or not. Disposing the player's scope stops a cutscene without calling `done`, and still sets the loop and the mixer back. ## Between scenes `player.Scene(c, done)` makes a cutscene a [scene](https://game.nsgo.dev/docs/scene/) of its own: it plays as the scene enters, and `done` switches on from it. ```go intro, err := player.Scene(c, func(cutscene.Result) { scenes.Switch(level1, scene.Crossfade(500*time.Millisecond)) }) if err != nil { return err } scenes.Switch(intro, nil) ``` Leaving the scene some other way before the cutscene ends stops it without calling `done`. That holds when switching from one cutscene scene to another of the same player with a transition too, although the new scene enters before the old one exits. ## Skipping A `skippable` cutscene is skipped, once it has played to `skipAfter`, by: - a press on the video; - a skip key, `Enter` or `Space` unless `Options.SkipKeys` names others (an empty slice for none); - back: `Escape`, the back button or gesture, or the browser's back; - `player.Skip()`, for a game that reads its own input. Back is taken while any cutscene plays, so it does not navigate the game away under the video; on one that cannot be skipped it does nothing. `player.CanSkip()` reports whether a skip works now and, read in a view, updates it as that changes, so a game can show its own skip prompt over the video: ```go core.Show{When: player.CanSkip, Then: func(*core.Scope) core.Node { return core.Text{Class: "absolute bottom-6 right-6 text-white", Content: "Skip ›"} }} ``` When the platform pauses the video itself, for a call or headphones unplugged, a press or a skip key plays it on rather than skipping it. It stays paused until then, also when the window loses or regains focus; only returning from the background plays it on by itself. ## Audio routing The platform's player decodes the video and plays its sound, which does not go through the game's mixer: - The mixer's master volume times the cutscene's `group` volume sets how loud the video plays, and follows a settings menu as it changes; a volume of 0 mutes it. - The mixer's bus effects (`EffectChain`) and anything else that processes samples do not apply to it. - Nothing the game draws can go between the video's picture and the screen; only NSGo views over `player.View()` show on top of it. Drawing decoded frames into the game, with the sound in the mixer, needs a frame-decoding API NSGo does not have yet. ## Testing with nsgotest `nsgotest` reports what a platform's player would: `app.Play` loads the video, `app.Progress` plays it to a position (and to its end at its duration), `app.PauseVideo` and `app.PlayVideo` pause and play it as the platform does, and `app.Report` sends an `EventError`. The video's test ID is `cutscene`, or `Options.TestID`. ```go app.Play("id:cutscene", core.VideoInfo{Duration: 3 * time.Second}) app.Progress("id:cutscene", 3*time.Second, 3*time.Second) // done gets Finished ``` --- Source: https://game.nsgo.dev/docs/datatable/ # datatable `game/tooling/datatable` loads typed game data, such as enemies, items, levels and quests, into slices of your own Go struct, and reloads it while the game runs when a designer saves the file. Tables are YAML, so designers and AI tools edit them directly and every change reads as a line in review; CSV and JSON exports from spreadsheets and other tools load too. ```go import "github.com/nsgo-dev/game/pkg/tooling/datatable" ``` ## A table and its type A row type is a struct. Each field is a column named by its `table` tag, else its `json` tag, else its Go field name; a tag of `-` leaves the field out. Fields can be strings, bools, integers, unsigned integers, floats, `time.Duration`, pointers to these (absent or `null` leaves the pointer nil) and slices of them. ```go type Enemy struct { ID string `table:"id"` Name string `table:"name"` HP int `table:"hp"` Speed float64 `table:"speed"` Boss bool `table:"boss"` Tags []string `table:"tags"` Cooldown time.Duration `table:"cooldown"` } ``` The YAML file is a mapping with a `version`, which is `datatable.FormatVersion` (1), and a `rows` list. Each row is a mapping from column names to values; a column a row leaves out keeps its zero value. ```yaml version: 1 rows: - id: goblin name: Cave Goblin hp: 45 speed: 3.5 boss: false tags: [melee, scout] cooldown: 500ms - id: dragon name: Ancient Wyrm hp: 1200 speed: 6.25 boss: true tags: [flying, fire, boss] cooldown: 2s ``` `LoadFile[T](path)` picks the reader by extension (`.yaml`, `.yml`, `.csv` or `.json`); `LoadYAML[T](name, data)` reads bytes you already have, such as an embedded file. ```go enemies, err := datatable.LoadFile[Enemy]("data/enemies.yaml") ``` ## What a YAML table refuses A YAML table is strict, so a typo is an error at load time rather than a silently missing value: - a missing `version`, a version other than 1, or a top-level key other than `version` and `rows`; - a bare list of rows without the `version`/`rows` mapping, or a second YAML document after `---`; - a row key that names no column (`datatable.ErrUnknownField`), including a field tagged `-`; - a column set twice in one row, for example as `hp` and `HP` (`datatable.ErrDuplicateField`); - a merge key (`<<: *defaults`): anchors and aliases load, but each row spells out its own columns; - a value the field's type cannot hold, such as `speed: fast` or an `int8` of 300. Errors inside a row are a `*datatable.CellError` with the file, the 1-based row, the column and the value: ```go var ce *datatable.CellError if errors.As(err, &ce) { log.Printf("%s row %d, %s = %q: %v", ce.File, ce.Row, ce.Field, ce.Value, ce.Err) } ``` Column names match exactly first and then without regard to case, so `Armor` and `armor` both fill a field named `Armor`. CSV and JSON stay as their tools export them: they have no version, and columns the type does not have are skipped. ## Saving a table `MarshalYAML(rows)` and `SaveYAML(path, rows)` write the same format, for an editor or a script that generates data. The output is deterministic: `version` first, then every column of every row in struct declaration order, two-space indentation, lists inline, strings quoted only where YAML needs it, a nil pointer as `null` and a duration in its `String` form. A file saved by `SaveYAML`, loaded and saved again is byte for byte the same. A nil list and an empty list are both written as `[]`. Non-finite floats and field types the loader cannot read (maps, structs, interfaces) are an error. Every column has one field: a row type in which two fields share a column name, such as two fields tagged `hp` or an embedded struct's `name` and the outer struct's own `name`, is refused by both `LoadYAML` and `MarshalYAML`, because only one of the two could be written or read back. Give each field its own tag, or tag one of them `-`. ```go if err := datatable.SaveYAML("data/enemies.yaml", enemies); err != nil { return err } ``` ## Untyped editing and row-type validation Tools and editors that work on YAML data tables without importing every game's Go row struct can open a file as an untyped `*datatable.Document` with `ParseDocument` or `LoadDocument`: - Each `Row` stores an ordered slice of `Cell{Key, Value}` entries so per-row key order is preserved, `Columns()` returns the union of row keys in first-appearance order, and `ColumnKind(col)` infers `KindString`, `KindNumber`, `KindBool`, `KindDuration`, or `KindList`. - `Marshal` and `Save` return the exact input bytes when no edits were made, patch only the edited line when a single scalar or inline-list cell changes, and encode deterministically from the preserved YAML AST after structural edits (`AddRow`, `DeleteRow`, `MoveRow`). - `RowTypeFor[T]()` and `Registry` (`RegisterRowType[T](reg, pattern)`) validate untyped cells, rows, and documents against Go struct types with `LoadYAML`'s exact rules (`ValidateCell`, `ValidateRow`, `ValidateDocument`, `ParseCellText`), refusing unknown fields, duplicate fields, and type-conversion failures with `*datatable.CellError`. ## Hot reload `NewTable[T](path)` loads the file and holds its rows. `Watch` registers it with a `hotreload.Watcher` (from `game/tooling/hotreload`) and calls back on the engine goroutine with the new rows after each valid save: ```go func Game(cx *core.Scope) core.Node { enemies, err := datatable.NewTable[Enemy]("data/enemies.yaml") if err != nil { panic(err) } w := hotreload.NewWatcher(cx, "data") enemies.WatchWithError(w, func(rows []Enemy, err error) { if err != nil { log.Printf("enemies.yaml: %v", err) // rows are still the last valid ones return } spawner.SetEnemies(rows) }) // ... } ``` An edit that does not load, such as a misspelt column, keeps the previous rows, leaves `Version` unchanged and records the error in `LastError`; the next valid save replaces the rows and increases `Version`. `Rows` returns a copy, so callers cannot change the table's rows. In release builds (`-tags release`) the watcher is a no-op and the table keeps the rows it loaded at start. --- Source: https://game.nsgo.dev/docs/debug/ # debug `game/debug` provides development-only diagnostics for NSGo games: a key-toggled frame-time graph, a live scene/layer inspector, and world-space collision and sprite-bounds wireframes — all stripped to zero-cost no-ops with `-tags release`. ```go import "github.com/nsgo-dev/game/pkg/debug" ``` ## Wiring the overlay and frame-time graph Create an `*Overlay` with `debug.New`, wrap your `game.Loop` with `WrapLoop`, and mount `overlay.View(cx)` alongside your game canvas: ```go overlay := debug.New(debug.Options{ ToggleKey: "F3", // default when empty TargetFPS: 60, // reference line on the frame graph LineWidth: 1, Scenes: func() []debug.SceneSnapshot { return []debug.SceneSnapshot{ { Name: "world", Layers: []debug.LayerSnapshot{ {Name: "terrain", Space: "world", Objects: 1}, {Name: "actors", Space: "world", Objects: len(actorsBatch.Sprites)}, {Name: "hud", Space: "screen", Objects: 3}, }, }, } }, }) overlay.WrapLoop(loop) loop.Run(cx) return core.View{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, Children: []core.Node{ gameCanvas, overlay.View(cx), // returns nil under -tags release }, } ``` - **`WrapLoop(l)`** wraps `l.Update` and `l.Draw` to time each frame and call `RecordFrame(total, update, draw)` into the fixed-size `FrameStats` ring buffer (`FrameHistory = 120` samples, zero per-frame heap allocations). - **`overlay.Stats()`** exposes `FPS()`, `Average()`, `Latest()`, `MaxTotal()`, `Len()`, `At(i)`, `Samples(dst)`, `Reset()`, and `DrawGraph(d, size, targetFPS)` if you want to embed metrics elsewhere. - **Toggling**: press `ToggleKey` (default `"F3"`) or call `overlay.Toggle()` / `overlay.SetVisible(true)`. Reading `overlay.Visible()` inside a reactive view or `Canvas.Draw` subscribes automatically. ## Drawing collision and sprite-bounds wireframes Draw world-space debug wireframes inside `core.Canvas.Draw` while your camera/viewport transform is active. `ShapeOverlay` automatically divides `LineWidth` by the drawing's active scale so wireframes stay crisp at any camera zoom: ```go d.Save() cam.Apply(d) worldScene.Draw(d) // Only executes when the overlay is visible; subscribes the canvas to toggles overlay.DrawShapes(d, func(s *debug.ShapeOverlay) { s.DrawBox(d, playerBounds, core.RGB(0x22c55e)) s.DrawCircle(d, aggroX, aggroY, aggroRadius, core.RGB(0xf59e0b)) s.DrawBatchBounds(d, actorsBatch, core.RGB(0x38bdf8)) }) d.Restore() ``` Convenience shortcuts `overlay.DrawBox`, `overlay.DrawCircle`, `overlay.DrawSpriteBounds`, and `overlay.DrawBatchBounds` are also available directly on `*Overlay`. `DrawFighterBoxes(d, fighter, hurt, hit)` strokes the hurtboxes and hitboxes a [framedata](https://game.nsgo.dev/docs/framedata/) `Fighter` has active on its current frame, hitboxes on top, mirrored as the fighter faces: ```go overlay.DrawFighterBoxes(d, p1, core.RGB(0x38bdf8), core.RGB(0xef4444)) ``` ## Draw statistics Report each frame's draw submissions in either of two ways, and the overlay shows them as a `Draw: N calls · N sprites · N batches` line, followed by `· N tris · N verts` once either count is non-zero: 1. **Pull via `Options.DrawStats`**: a `func() debug.DrawStats` called whenever the overlay refreshes. 2. **Push via `overlay.SetDrawStats(stats)`**: used when `Options.DrawStats` is nil; call it once per frame after drawing. ```go overlay := debug.New(debug.Options{ DrawStats: func() debug.DrawStats { return debug.DrawStats{DrawCalls: r.drawCalls, Sprites: len(actorsBatch.Sprites), Batches: r.batches} }, }) ``` `overlay.DrawStats()` returns the current values and `overlay.HasDrawStats()` reports whether either source is set; the line stays hidden until one is. [`game/mcp`](https://game.nsgo.dev/docs/mcp/)'s `game_perf_readout` reports the same values. ## Resetting the readouts - `overlay.ResetStats()` clears the frame-time ring buffer and any pushed draw statistics and refreshes the HUD. An `Options.DrawStats` callback keeps reporting. - `GCMonitor.Reset()` clears the GC frame history, hitch count, pause peaks and per-frame allocation averages, and re-reads the runtime counters so the next frame is measured from that point (see [GC and frame allocations](https://game.nsgo.dev/docs/gc-and-allocations/)). - `Profiler.Reset()` clears every timing scope's accumulated timings and history. Scope names keep their IDs, so a scope still open across the reset is charged to its own name, and a trace recording started with `StartRecording` keeps running and keeps its events. [`game/mcp`](https://game.nsgo.dev/docs/mcp/)'s `game_perf_reset` calls all three. ## Scene inspector Supply live scene structure in either of two ways: 1. **Pull via `Options.Scenes`**: if the callback reads NSGo signals, the inspector updates reactively; otherwise it refreshes on recorded frames and whenever you call `overlay.RefreshScenes()`. 2. **Push via `overlay.SetScenes(snapshots)`**: updates the inspector immediately when `Options.Scenes` is nil. ## AI inspector and steering guides Inspect a chosen agent's [`game/ai`](https://game.nsgo.dev/docs/ai/) behavior tree (with the running path highlighted) or [`game/flow`](https://game.nsgo.dev/docs/flow/) `Machine` state and bounded transition history inside the overlay panel: ```go overlay := debug.New(debug.Options{ AI: func() debug.AISnapshot { return debug.BehaviorTreeSnapshot("guard-1", guardInspector) }, }) // Or push a snapshot on demand (behavior tree, state machine, or both): overlay.SetAI(debug.StateMachineSnapshot("boss", bossFSM)) ``` - **Pull (`Options.AI`) or push (`SetAI` / `ClearAI` / `RefreshAI`)**: works just like `Scenes`, refreshing on recorded frames or reactively when `Options.AI` reads NSGo signals. - **Steering guides**: inside `core.Canvas.Draw` while your camera transform is active, draw a 2D steering agent's body radius, velocity, desired velocity, target reticle, and waypoint path with `overlay.DrawSteering` (or `ShapeOverlay.DrawSteering`, `DrawVector`, `DrawPath`, `DrawTarget`): ```go overlay.DrawSteering(d, debug.SteeringDebug{ Agent: agent, DesiredVelocity: desiredVel, Target: targetPos, HasTarget: true, Path: waypoints, WaypointIndex: followState.Index, VelocityScale: 0.5, }) ``` All AI panel views and steering draw helpers compile to zero-cost no-ops under `-tags release`, so none of the inspection UI or drawing code is linked into release binaries. ## Stripping debug code in release builds Build release binaries with `-tags release`: ```sh go build -tags release ./... ``` Under `-tags release`, `debug.Enabled()` returns `false`, `Overlay.View(cx)` returns `nil`, and every `Overlay`, `FrameStats`, and `ShapeOverlay` method compiles to an empty no-op — so none of the overlay UI, frame graph, or wireframe drawing code is linked into your shipping binary. --- Source: https://game.nsgo.dev/docs/determinism/ # Determinism A deterministic simulation produces the exact same state from the same starting seed and inputs on every run, across macOS, iOS, Windows, Linux, Android and the web. Determinism makes replays, seeded daily runs, save/load continuity and automated gameplay tests under `nsgotest` reliable instead of flaky. This guide describes the rules that keep an NSGo game deterministic and how to verify them with `pkg/random`. ## 1. Advance time only with `game.Loop`'s fixed `dt` Move simulation state exclusively inside `game.Loop.Update(dt)` using the fixed step `dt` (or an integer tick counter). Never read `time.Now()`, `time.Since`, or frame-to-frame display intervals inside simulation logic. ```go loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { sim.Tick++ sim.Step(dt) // dt is always 1/60s }, Draw: func(alpha float64) { // Interpolate visuals only; never mutate simulation state here. render(sim.Prev, sim.Curr, alpha) }, } ``` - `Draw(alpha)` runs at the display's refresh rate and must be read-only with respect to gameplay state. - Count cooldowns and timers in integer ticks or exact multiples of `dt` rather than wall-clock deadlines. ## 2. Use seeded `random.Stream` per purpose Never call Go's global `math/rand` or `math/rand/v2` inside simulation code. Global generators share hidden mutable state across subsystems, and standard library helpers can change algorithms across Go releases. Import `github.com/nsgo-dev/game/pkg/random` instead: ```go import "github.com/nsgo-dev/game/pkg/random" streams := random.NewStreams(masterSeed) ai := streams.Stream("ai") loot := streams.Stream("loot") particles := streams.Stream("particles") ``` - Every `Stream` runs a self-contained SplitMix64 + Xoshiro256\*\* generator with fixed rejection sampling (`Intn`, `IntRange`, `Float64`, `Float32`, `Range`, `Range32`, `Bool`, `Chance`, `Pick`, `WeightedIndex`, `Shuffle`). The output sequence is bit-for-bit identical across Go versions, operating systems and CPU architectures (32-bit, 64-bit, ARM64, x64 and WebAssembly). - Forking by purpose (`root.Fork("loot")`, `root.Fork("level-1").Fork("spawns")`, or `streams.Stream("loot")`) derives independent child streams without advancing the parent or perturbing siblings. Adding particle effects or reordering stream creation will not change enemy AI or loot drops. - Keep cosmetic randomness (particles, camera shake, sound pitch variation) on its own stream so visual tweaks never alter gameplay. ## 3. Never depend on Go map iteration order Go intentionally randomizes `for k, v := range m` iteration order. Iterating a map directly in order-sensitive gameplay code—such as applying damage, resolving collisions, spawning waves or drawing from a `random.Stream`—causes runs to diverge. - Prefer slices ordered by creation or stable entity ID for anything `Update` iterates over. - When you must iterate a map, sort its keys first: ```go for _, id := range slices.Sorted(maps.Keys(enemies)) { enemies[id].Update(dt, ai) } ``` ## 4. Keep simulation single-threaded and order-independent of goroutines Run all simulation mutations sequentially on the engine's goroutine inside `Loop.Update`. - Do not let multiple goroutines mutate game state or draw from the same `random.Stream`. - Do not make gameplay decisions from `select` over multiple ready channels, because Go chooses among ready cases pseudo-randomly. - If background work (such as pathfinding or procedural chunk generation) runs off-thread, deliver its result at a deterministic tick boundary and apply queued results sorted by a canonical key rather than arrival order. ## 5. Keep floating-point evaluation order consistent (and prevent arm64 FMA drift) IEEE-754 floating-point addition and multiplication are not associative: `(a + b) + c` can differ in the last bit from `a + (b + c)`. On arm64, Go's compiler is also allowed by the language specification to contract `a*b + c` into a single fused multiply-add instruction (`FMADD`/`FMSUB`) with only one rounding instead of two, whereas amd64 executes separate multiply and add instructions. Over hundreds of ticks, even a 1-ULP difference between arm64 and amd64 can cross a collision or branch threshold and cascade. - Accumulate forces, velocities and scores in a fixed, deterministic entity order. - In custom simulation code that must match bit-for-bit across amd64 and arm64, wrap multiply-add products in an explicit conversion (`float32(a*b) + c` or `float64(a*b) + c`), which the Go specification guarantees forbids FMA contraction, and avoid standard library transcendentals (`math.Sin`, `math.Cos`, `math.Atan2`, `math.Hypot`) whose arm64 implementations emit FMA, and `math.Pow`, `math.Exp` and `math.Log`, which take different code on each architecture (`math.Exp` has its own assembly on amd64 and on arm64, `math.Log` is assembly on amd64 only) and round differently. - `pkg/physics`, `pkg/physics3d`, and `pkg/vehicle` already eliminate arm64 FMA instructions across their stepped simulation paths and verify cross-architecture golden trajectory hashes in CI on both Ubuntu amd64 and macOS arm64. In `pkg/physics` that covers the rigid world, the XPBD `SoftWorld`, the character controller and tile collision, and on arm64 its tests also disassemble the package with `go tool objdump` and fail on any `FMADD`, `FMSUB`, `FNMADD` or `FNMSUB` outside the debug drawing code. - Avoid mixing `float32` and `float64` inconsistently across code paths. - Use integer ticks or fixed-point values for exact counters, timers, grids and resource totals. ## 6. Save and restore PRNG and physics state for saves, replays, and rollback A `Stream`'s full state (its seed and 256-bit generator words) can be snapshotted with `State()` and restored with `SetState(state)`. `State` marshals cleanly with `encoding/json`, so a saved game resumes the exact same future random sequence after reload: ```go // Save data, err := json.Marshal(streams.States()) // Load var saved map[string]random.State if err := json.Unmarshal(data, &saved); err == nil { streams.Restore(saved) } ``` For a single stream, use `s.State()` and `s.SetState(state)`. Call `s.Reset()` or `streams.Reset()` to rewind to the start of a seed for replays or level restarts. For physics worlds, `physics.World`, `physics.RigidWorld`, `physics3d.World`, and `vehicle.Vehicle` all provide `Save()`, `Restore(snap)`, and `Checksum()` capturing every piece of private solver state (warm-start impulse caches, sleep timers, previous poses, active contact/trigger pair sets, and joint state). Snapshots marshal cleanly to plain-text JSON and pair directly with `net.RollbackSession` (`net.SimState`): ```go // Inside a net.SimState implementation: func (s *MatchSim) Save() []byte { data, _ := json.Marshal(s.world.Save()) return data } func (s *MatchSim) Load(b []byte) error { var snap physics3d.WorldSnapshot if err := json.Unmarshal(b, &snap); err != nil { return err } return s.world.Restore(snap) } func (s *MatchSim) Checksum() uint64 { return s.world.Checksum() } ``` ## 7. Verify determinism in tests under `nsgotest` The `random` package includes test helpers that execute a simulation multiple times from scratch and fail if any run diverges. Use `AssertDeterministic` to check a full run, including a real `game.Loop` driven by `nsgotest`: ```go func TestMain(m *testing.M) { nsgotest.Main(m) } func TestSimulationIsDeterministic(t *testing.T) { random.AssertDeterministic(t, 4, func() WorldSnapshot { streams := random.NewStreams(42) world := NewWorld(streams) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { world.Step(dt) }, } app := nsgotest.Start(t, func(cx *core.Scope) core.Node { loop.Run(cx) return core.View{} }) app.Advance(2 * time.Second) return world.Snapshot() }) } ``` When a multi-step simulation diverges, use `CheckSteps` or `AssertDeterministicSteps` to pinpoint the exact first step where two runs differ and inspect both states: ```go func TestStepByStepDeterminism(t *testing.T) { random.AssertDeterministicSteps(t, 300, func() func(step int) WorldSnapshot { world := NewWorld(random.NewStreams(42)) dt := time.Second / 60 return func(step int) WorldSnapshot { world.Step(dt) return world.Snapshot() } }, nil) } ``` Run the suite with: ```sh go tool nsgo test ./... ``` If `AssertDeterministicSteps` fails, it reports the first divergent step index along with both states (`run A` and `run B`), letting you narrow the cause directly to the tick that introduced nondeterminism. --- Source: https://game.nsgo.dev/docs/editor/ # Editor & Scene Format This document records the scope decision for NSGo's game editor ([#159](https://github.com/nsgo-dev/game/issues/159)) and specifies the version 1 YAML scene format ([#160](https://github.com/nsgo-dev/game/issues/160)) implemented in `github.com/nsgo-dev/game/pkg/sceneformat`. Prebuilt desktop installers for **NSGo Game Editor** (`cmd/editor`)—signed and notarized `.dmg` images for macOS (`arm64` / `x64`), `-setup.exe` installers for Windows (`x64` / `arm64`), and `.deb` / `.pkg.tar.gz` / `.AppImage` packages for Linux (`x64` / `arm64`)—are published on [GitHub Releases](https://github.com/nsgo-dev/game/releases/latest), alongside one-line installers (`install.sh` / `install.ps1`). You can also launch the editor directly via `nsgo game editor` or `go run ./cmd/editor`. ## Editor Scope Decision (#159) NSGo takes **option (b) growing into (c)**: keep Go code and Tiled first-class, define a clean human-editable YAML scene format shared by hand-authored scenes and tooling, and build a lightweight NSGo-native scene editor on top of it. ### Why this scope - **Code and Tiled stay first-class.** A game written purely in Go—or authored with Tiled `.tmj` maps and TexturePacker/Aseprite atlases—never has to go through an editor. `sceneformat` is an ordinary library package with zero runtime lock-in. - **One text format, readable diffs.** Scenes are plain versioned YAML (`version: 1`) with deterministic 2-space encoding. Hand-editing a scene in a text editor and saving it from a visual editor produce the same diff-friendly structure. - **Dogfooding NSGo.** Rather than wrapping a third-party desktop shell or building a monolithic IDE, the lightweight scene editor is an NSGo app built with NSGo's own `ui` views and `Canvas`. Every improvement to inspectors, tree views, shortcuts, or canvas tooling benefits NSGo itself. ### Planned lightweight editor capabilities The NSGo-native editor operates directly on `sceneformat.SceneDoc` files and focuses on the workflows where visual feedback beats hand-editing coordinates: 1. **Object placement & transforms**: place, drag, rotate, scale, flip and Z-order objects across world and screen layers. 2. **Tile painting**: paint inline tile grids, and the tile layers of layered grids with flipped tiles, or preview referenced Tiled `.tmj` and LDtk `.ldtk` maps. 3. **Typed property & component editing**: inspect and edit `components` and `properties` with validation against the scene schema. 4. **Undo / redo**: command-based editing history over scene documents. 5. **Play-in-editor**: run the live `game.Loop` and `BuiltScene` directly inside the editor's `Canvas` without leaving the tool. 6. **Asset browsing**: browse project atlases, frames, animations and tilemaps and drag them into layers. Out of scope for the initial editor: custom scripting languages, bespoke shader/material graphs, and proprietary binary project formats. --- ## Scene Format (`version: 4`) (#160) ```go import "github.com/nsgo-dev/game/pkg/sceneformat" ``` ### Top-level fields | Field | Type | Description | | --- | --- | --- | | `version` | `int` | Required schema version: `4` (`CurrentVersion`), `3` for a scene using version 3 parallax/repeat layers without version 4 3D lights/environment/cameras, `2` for version 2 features without version 3/4 fields, or `1` for none of the fields added in versions 2–4. `Encode` writes it back unchanged. | | `uid` | `string` | Optional stable ID that stays the same when the file is renamed or moved, written by `nsgo game index` (all versions; see [Stable references](https://game.nsgo.dev/docs/project/#stable-references)). `Resolve` keeps the scene's own uid, not its base's. | | `inherits` | `string` | Optional slash-separated path from the project root to a base scene this one inherits (version 2+, see Instancing and inheritance below). | | `name` | `string` | Optional human-readable scene name. | | `navMesh` | `string` | Optional slash-separated path from the project root to the scene's baked [navigation mesh file](https://game.nsgo.dev/docs/navbake3d/), which `nsgo game navmesh` writes (all versions). In a scene that inherits another, it replaces the base's. | | `virtualWidth`, `virtualHeight` | `float32` | Virtual viewport size in points. Must both be `0` or both positive. | | `backgroundColor` | `string` | Optional CSS color string parsed by `core.ParseColor` (for example `"#141824"`). Filled over `(0, 0, virtualWidth, virtualHeight)` before layers draw. | | `ambientColor` | `string` | Optional CSS color string parsed by `core.ParseColor` (for example `"rgba(12, 16, 30, 0.85)"`). Sets the ambient darkness tint of the scene's 2D lighting pass (`lights2d.Scene.Ambient`, both versions). | | `camera` | object | Optional default 2D camera for world-space layers (`x`, `y`, `zoom`, `rotation`, optional `bounds`). | | `environment` | object | Optional 3D scene environment (version 4): `sky` (`kind`: `color`, `gradient`, or `hdr` with `color` / `zenith`, `horizon`, `ground` / `hdr` path), `ambientColor`, `ambientIntensity`, `iblIntensity`, `fog` (`mode`: `off`, `linear`, `exp`, `exp2`; `color`, `start`, `end`, `density`, `maxOpacity`, height fog `heightEnabled`, `heightBase`, `heightFalloff`, `heightDensity`), `tonemapping` (`none`, `reinhard`, `aces`, `neutral`, `agx`), and `exposure`. | | `tilemaps` | map | Optional named tilemaps referenced from layers via `tilemap.ref`. | | `layerOverrides` | map | Changes to inherited layers by name: `space`, `order`, `visible`, `tilemap` (version 2+), plus `parallaxX`, `parallaxY`, `repeatX`, `repeatY`, `repeatWidth`, `repeatHeight` (version 3, requires `inherits`). | | `overrides` | map | Changes to inherited objects by ID (version 2+, requires `inherits`). | | `layers` | list | Ordered list of layers drawn lowest `order` first, preserving document order on ties. | | `connections` | list | Optional connections from one object's events to another object's handlers, written after the layers (all versions, see [Connections](https://game.nsgo.dev/docs/editor/#connections-490)). | ### Camera - `x`, `y`: world coordinates placed at the center of the virtual viewport `(virtualWidth/2, virtualHeight/2)` (or `(0, 0)` when virtual dimensions are `0`). - `zoom`: positive zoom factor; defaults to `1` when omitted. - `rotation`: camera rotation in radians (clockwise on screen); world layers rotate by `-rotation` around `(x, y)`. - `bounds`: optional `{x, y, width, height}` world rectangle clamping the visible area (`width > 0`, `height > 0`). - When `camera` is omitted, world layers draw with the identity transform. ### Tilemaps A tilemap entry (in top-level `tilemaps` or inline on a layer) uses exactly one mode: - **Reference** (`ref`, layers only): names an entry in top-level `tilemaps`. - **External map** (`source`): a slash-separated path from the project root to a Tiled map (`.tmj` or `.tmx`) or an LDtk project (`.ldtk`); for LDtk, `level` names the level to build (version 2), and without it the project's first level is built. - **Inline grid**: `tileWidth`, `tileHeight`, `width`, `height`, either `tileset` (atlas name whose frames are keyed `"1"`, `"2"`, …) or `tilesetFile` (version 2+, path of a YAML tileset `*.tileset.yaml`), optional `offsetX` / `offsetY` (version 3, shifting cell `(0, 0)` in layer points), and row-major `data` of length `width * height` (`0` is an empty tile; when using `tilesetFile`, ID `n` places local tile `n - 1`). - **Layered grid** (version 2): `tileWidth`, `tileHeight`, `width`, `height`, optional `offsetX` / `offsetY` (version 3), `tilesetFile`, the path of a YAML tileset (`*.tileset.yaml`, see [YAML tilesets](https://game.nsgo.dev/docs/tilemap/#yaml-tilesets)) whose tiles the cells place, and `tileLayers`, up to `MaxTileLayers` named layers drawn in order. The tileset of a layered grid defines each tile once, with its flags, properties, collision shapes, animation and terrain, so the map only places tiles, as a Godot TileSet does for its TileMapLayers. Each tile layer has a `name`, optional `visible` (default `true`) and `opacity` (default `1`), and `rows`: `height` rows from the top, each `width` cells separated by spaces. A cell is `.` when empty, or the tile's local ID in the tileset (`0`, `1`, …) followed by any of `h`, `v` and `d` to flip it horizontally, vertically or across its diagonal, as Tiled's flip bits do, so `3hv` is tile 3 turned half a turn. A row may align its cells with extra spaces and write the letters in any order; `Encode` writes single spaces and the order `h`, `v`, `d`, so each row is one line in a diff. ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/scene.v2.json version: 2 name: Cave virtualWidth: 320 virtualHeight: 180 layers: - name: ground tilemap: tileWidth: 16 tileHeight: 16 width: 4 height: 2 tilesetFile: tilesets/cave.tileset.yaml tileLayers: - name: floor rows: - 0 0 0 0 - . . 1h 3hvd - name: deco opacity: 0.5 rows: - 2 . . . - . . . . ``` `TileLayerDoc.Cell`, `SetCell` and `Cells` read and write a layer's cells as tile values, the GIDs they have once built: `0` for an empty cell, otherwise the local ID plus 1 with `tilemap.FlipHorizontal`, `FlipVertical` and `FlipDiagonal` set; `ParseTileRow` and `FormatTileRow` do the same for one row. `Build` turns a single grid of atlas frames into a sprite batch (`BuiltLayer.Tilemap`), and a layered grid, an inline grid with `tilesetFile`, or an external map into a `tilemap.Tilemap` (`BuiltLayer.Map`). The map carries the tileset's flags, properties, shapes, animations and terrains, so in the layer's coordinates it answers `FlagsAt`, `TileProperties`, `TilesInRect` and `Raycast`, collides directly with `physics.MoveAndSlide`, and serves `tileshape.New` for slopes and occluders. `BuiltScene.Draw` draws only the map tiles inside the virtual viewport, seen through the camera for a world-space layer, unless the scene has no virtual size or `DrawAllTiles` is set, as the editor sets it for its edit view; `BuiltScene.Update(dt)` advances animated tiles. `Build` reads YAML tilesets, Tiled maps with their external tilesets and LDtk projects through the resolver's `FileResolver` (`ReadFile`), with paths in a Tiled or LDtk file taken from that file's directory, and loads their images through an `ImageResolver` (`Image`) when the resolver has one, or names them by path (`core.ImageSource{URI: path}`) otherwise. `FSAssets` reads a project's files from an `fs.FS`, so a scene that names a `.tmj`, `.ldtk` or `.tileset.yaml` builds with no resolver of the game's own. A resolver that implements `TilemapResolver` still loads every `source` itself into a `TilemapDoc`, as before, except a source that names an LDtk `level`: `Tilemap(source)` cannot receive the level, so `Build` reads that one through the `FileResolver`. ### Layers and Objects Each layer has: - `name` (required, unique within the scene) - `space`: `"world"` (default when omitted, draws under camera) or `"screen"` (draws in canvas coordinates, ignoring camera) - `order`: integer draw order (lowest first) - `visible`: boolean, defaults to `true` when omitted - `parallaxX`, `parallaxY` (version 3): optional finite scroll factors applied to the camera position on `"world"` layers, matching `scene.Layer`; omitted defaults to `1`, `0` pins the layer against camera translation, `0.5` scrolls at half speed, and values above `1` scroll faster for foregrounds. `layerOverrides` can override them on inherited scenes. - `repeatX`, `repeatY` (version 3): optional booleans that tile a `"world"` layer seamlessly across the camera's visible region using `repeatWidth` / `repeatHeight` (non-negative layer points; `0` falls back to the layer's tilemap pixel size, then the scene's virtual viewport size). `layerOverrides` can override them on inherited scenes. - `tilemap`: optional tilemap drawn beneath the layer's objects - `objects`: placed objects in the layer Each object has: - `id` (required, unique across the entire scene) - `name`, `prefab` (optional) - Transform: `x`, `y`, `originX`, `originY`, `rotation` (radians, clockwise), `scaleX` (default `1`), `scaleY` (default `1`), `flipX`, `flipY`, `alpha` (`[0, 1]`, default `1`), `z` (layer-local draw order, lowest first) - `sprite`: optional `{atlas, frame}` referencing a `sprite.Atlas` and frame name - `particles`: optional `{file, atlas}` (version 2) placing a 2D particle emitter YAML file (`file` is a slash-separated path from the project root; optional `atlas` resolves the emitter's `frameNames`). `sceneformat.Build` loads `file` through `ParticlesResolver` when implemented, falling back to `FileResolver` + `particles.UnmarshalConfigYAML` (so `FSAssets` works automatically), creates `BuiltObject.Emitter` (collected in `BuiltLayer.Emitters`), positions it at the object's composed world transform (updated by `BuiltObject.Sync`), advances it in `BuiltScene.Update(dt)`, and draws it in Z-order interleaved with sprites in `BuiltScene.Draw(d)` - `material`: optional slash-separated path from the project root to a shared material file, such as `materials/stone.material.yaml`, resolved at build time through `MaterialResolver` (see [resource](https://game.nsgo.dev/docs/resources/)) - 3D look: `mesh`, one of the built-in primitives `box`, `sphere`, `plane`, `capsule` and `cylinder`, `model` (version 2), the slash-separated path from the project root to a glTF 2.0 file (`.gltf` or `.glb`), optionally narrowed to one of its nodes by `modelNode` or one of its meshes by `modelMesh`, or `gridMap` (version 2), the slash-separated path from the project root to a `*.gridmap.yaml` / `*.gridmap.yml` file; an object's `material` replaces the model's or grid map's materials or gives the primitive its surface; optional `occluder` (version 2) marks the object as a 3D occluder (`mode: model` or `mode: box` with optional `center`, `size`, and `doubleSided`). `scenemodel.Build` turns them into geometry, LODs, and occluders ([scenemodel](https://game.nsgo.dev/docs/scenemodel/)). `CheckObjectModel` checks these fields on one object, and the editor's `PlaceObject` refuses an object it refuses; the inspector's Mesh and GridMap fields are mutually exclusive with each other and with `model` - 3D light (`light`, version 4): optional 3D light attached to the object's transform (`kind`: `directional`, `point`, or `spot`; CSS `color`, `intensity`, `range`, spot `innerCone` and `outerCone` half-angles in degrees, and `shadows`). Directional and spot lights aim along the object's local `-Z` axis. `CheckObjectLight` validates one object's light. - 3D camera (`camera`, version 4): optional 3D camera attached to the object's transform (`projection`: `perspective` or `orthographic`, `fov` in degrees or `orthoHeight`, `near`, `far`, and `current`). At most one 3D camera in a scene may set `current: true`. `CheckObjectCamera3D` validates one object's camera. - `components`: optional mapping from a component type name to its fields; free-form unless a component registry is given (see [Component types](https://game.nsgo.dev/docs/editor/#component-types)) - `properties`: optional `map[string]any` for custom metadata - `scene`: optional slash-separated path from the project root to a scene file this object instances (version 2, see Instancing and inheritance below) - `overrides`: optional changes to the instanced scene's objects by ID (version 2, requires `scene`) - `children`: optional list of objects attached to this one (see Node tree below) ### Node tree (#484) An object can hold child objects under `children`, nested up to `MaxObjectDepth` (64) levels. A child's transform is local to its parent: `x`, `y`, `rotation`, `scaleX` and `scaleY` (and in 3D `posZ`, `rotX`, `rotY`, `rotZ` and `scaleZ`) compose with every ancestor's, and its `alpha` multiplies theirs. `originX`, `originY`, `flipX` and `flipY` stay the object's own, and `z` orders the whole layer, children included, with ties drawing each parent before its children. Children belong to their parent's layer, and their IDs share the scene-wide namespace, so an ID used anywhere in the tree is refused anywhere else. ```yaml layers: - name: ships objects: - id: ship x: 100 y: 50 rotation: 1.5707964 scaleX: 2 scaleY: 2 sprite: { atlas: actors, frame: hull } children: - id: turret x: 10 # lands at (100, 70): a quarter turn and twice the size of ship sprite: { atlas: actors, frame: turret } children: - id: barrel x: 5 # lands at (100, 80) ``` The same tree loads three ways: - `Build` links each `BuiltObject` to its `Parent` and `Children`, sets `World` to the composed 2D affine transform and `WorldAlpha` to the composed alpha, and draws each child's sprite at its world position, rotation and scale. A sprite whose composed transform is sheared (a rotated child under a non-uniformly scaled parent) cannot be drawn as a sprite, so `Validate` refuses it, and with it `Parse`, `Encode` and `Build`; `CheckObjectTree` makes the same check, and the nesting limit, for a single tree. A parent collapsed to zero size along one axis (such as `scaleX: 0`) is not a shear: its child sprites draw at zero scale. Objects without a sprite keep the exact matrix in `World`. `BuiltLayer.Objects` lists a layer's top-level objects, and `BuiltScene.Objects` indexes every object by ID. After changing a built object's document fields, `BuiltObject.Sync` recomposes its `World` and `WorldAlpha` and its sprite, and its descendants', and reports false for a sprite the change would shear. - `SpawnEntities(doc, world)` spawns one entity per object into an `entities.World`, parented in its `Hierarchy2D` as the objects nest, with the object's local `Transform2D` and an `ObjectRef` component naming the object and its layer. The top-level objects of a hidden layer spawn hidden, so their subtrees are not world-visible. - `BuildNodes3D(doc, scene.Root())` builds a `scene3d` node tree: one group node per layer (carrying the layer's visibility), and one node per object named by its ID, with `UserData` pointing at its `ObjectDoc`. `ObjectLocalTransform3D` gives each node's local transform; `rotX`, `rotY` and `rotZ` apply in that order about fixed axes, the same order the editor's 3D viewport uses. - `scenemodel.Build(doc, scene.Root(), assets)` builds the same tree and attaches to each object's node the geometry and materials of its `mesh`, `model` or `gridMap`, with the node's `LocalBounds` set from the geometry, ready for `render3d.Queue` ([scenemodel](https://game.nsgo.dev/docs/scenemodel/)). ```go spawned, err := sceneformat.SpawnEntities(doc, world) if err != nil { return err } world.Hierarchy2D().Sync() wt, _ := world.Hierarchy2D().WorldTransform(spawned["barrel"]) // wt.X == 100, wt.Y == 80 nodes, err := sceneformat.BuildNodes3D(doc, scene.Root()) if err != nil { return err } pos := nodes.Objects["barrel"].WorldTransform().Pos ``` Moving, deleting or undoing an object in the editor carries its children along, and the editor never hands out an ID that a nested child already uses. It refuses to place a tree deeper than `MaxObjectDepth` or holding a sheared sprite, and refuses a scale or rotation that would shear a sprite, the object's own or a descendant's, under the transforms of its ancestors. Both viewports draw, pick and edit nested children, and the [scene tree](https://game.nsgo.dev/docs/editor/#scene-tree-861) selects, reparents, reorders and renames them. ### Instancing and inheritance (#483) A version 2 scene reuses other scene files the way Godot's scenes do. Every reference is a slash-separated path from the project root, like a material's, and `Parse` and `Encode` keep references and overrides exactly as written: a level of instances saves as the same instances, never as copies of their objects. An object with `scene` instances that file. The top-level objects of every layer of the instanced scene, in document order, become the object's first children, ahead of its own `children`, so the object's transform places the whole instance. Their IDs are prefixed with the object's ID and a slash, so ten instances of one enemy hold `enemy_1/body` to `enemy_10/body`. `overrides` changes the instanced objects, keyed by their IDs inside the instanced scene; a scene instanced inside it is reached by its prefixed ID, such as `gun/barrel`. The instanced scene's layer settings, camera, background and virtual size do not carry over, and a scene whose layers hold a tilemap cannot be instanced. ```yaml # scenes/enemy.scene.yaml version: 2 name: Enemy layers: - name: root objects: - id: body sprite: { atlas: actors, frame: hero } properties: { health: 3, speed: 40 } children: - id: torch x: 6 sprite: { atlas: actors, frame: torch } # level.scene.yaml version: 2 layers: - name: actors objects: - id: enemy_1 x: 32 "y": 40 scene: scenes/enemy.scene.yaml overrides: body: alpha: 0.5 - id: enemy_2 x: 64 "y": 40 scene: scenes/enemy.scene.yaml overrides: torch: x: -6 ``` A scene with `inherits` starts as a copy of its base and changes only what it declares: - `name`, `backgroundColor`, the virtual size and `camera` replace the base's when set, and `tilemaps` entries are added or replaced by name. - `overrides` changes inherited objects by ID, nested children and instanced objects (`enemy_1/body`) included. - `layerOverrides` changes inherited layers by name. - A layer named like one of the base's adds its objects to that layer and may set nothing else; any other layer is added after the base's layers. An inherited object or layer cannot be removed, and its ID cannot change. ```yaml # scenes/fast_enemy.scene.yaml: the enemy above, twice as fast version: 2 inherits: scenes/enemy.scene.yaml overrides: body: properties: speed: 80 ``` An override sets any object field except `id`, `children`, `scene` and `overrides`; a field it leaves out keeps the base's value, and a value of `0` or `false` is still a change. `components` and `properties` are replaced key by key, keeping the object's other keys. `Resolve(doc, scenes)` loads the referenced files through a `SceneResolver`, such as `FSScenes{FS: os.DirFS(root)}`, and returns a self-contained copy in which no object instances anything and nothing is inherited. It loads each file once per call and never changes `doc` or the documents the resolver returns. It refuses a cycle of scenes that instance or inherit each other, a chain deeper than `MaxSceneNesting` files, a result of more than `MaxResolvedObjects` objects, an override that names no object or layer of the scene it changes, and a result that does not validate, such as one whose prefixed IDs collide with other IDs. `Build` resolves a scene itself when its `AssetResolver` also implements `SceneResolver`, and `BuiltScene.Doc` is then the resolved copy; `SpawnEntities` and `BuildNodes3D` refuse a scene that still refers to others, so resolve it first. ```go type assets struct { sceneformat.AtlasMap sceneformat.FSScenes } built, err := sceneformat.Build(level, assets{atlases, sceneformat.FSScenes{FS: os.DirFS("project")}}) ``` In the editor, `PlaceScene(layer, path, x, y)` places an instance of a scene file as an undoable command, with an ID named after the file (also triggered by dragging a scene file from the File Browser onto the viewport, clicking its `+` button, or pressing **Place** with a scene file selected; registered prefabs in the Asset Browser can likewise be clicked or dragged onto the viewport via `PlacePrefab`). The editor's `Resolver` must implement `SceneResolver`; `PlaceScene`, and `PlaceObject` for any object tree that names a `scene`, resolve the scene as it would be with the instance placed and refuse it when that fails: a missing or invalid file, an override that names no object or holds a bad value, or IDs that collide once instances are expanded. Set the editor's `ScenePath` to the open scene's path from the project root (`OpenYAML` clears it) so that an instance leading back to the open scene, directly or through other files, is refused as a scene cycle before the saved file instances itself. Placing an instance raises a version 1 scene to version 2 (which Undo restores). New IDs are checked against the IDs the scene gets from its base and its instances as well as its own. Both the 2D and 3D viewports and the scene tree (`SceneTreeView`) let you select any instanced child or inherited object directly (shown muted in the scene tree with an `inst`/`base` tag and an override dot when modified). Editing its transform, sprite, material, particles, 3D light/camera/occluder/mesh/model/GridMap, custom properties, or component fields records an undoable override on the owning instance (`ObjectDoc.Overrides`, keyed by its ID inside the instanced scene) or on the inheriting scene (`SceneDoc.Overrides`, leaving the base file unchanged), and refuses edits whenever `sceneformat.Resolve` fails. Editing an inherited layer's visibility, space, parallax, or repeat records `SceneDoc.LayerOverrides`. The inspector shows an instance/inherited bar with the source scene path, instance count, and override count, marks each overridden field with a warning dot (whose tooltip shows the source value) and a per-field **Revert** button (`RevertObjectOverrideField` / `RevertLayerOverrideField`), and offers **Revert All** (`RevertObjectOverrides` / `RevertLayerOverrides`, pruning empty override maps so the saved YAML stays clean), **Open Scene** / **Open Base Scene** (`OpenSourceScene` / `OpenInstancedScene` / `OpenBaseScene`), **Apply to Source** (`ApplyOverridesToSource`, writing an instance's overrides back to its source scene file and clearing them on the instance in one undo step that restores the source file on Undo), and **Make Local** (`MakeInstanceLocal`, replacing a scene instance with a local copy of its resolved objects and prefixed connections in one undo step). Play runs a resolved copy of the scene, so changes made through `BuiltObject.Doc` show in the editor's document until Stop restores it. ### Example ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/scene.v2.json version: 2 name: Cave Room virtualWidth: 320 virtualHeight: 180 backgroundColor: "#141824" camera: x: 160 y: 90 zoom: 1 bounds: x: 0 y: 0 width: 320 height: 180 tilemaps: floor_grid: tileWidth: 16 tileHeight: 16 width: 4 height: 2 tileset: cave_tiles data: [1, 2, 2, 1, 1, 0, 0, 1] layers: - name: floor space: world order: 0 tilemap: ref: floor_grid - name: actors space: world order: 10 objects: - id: hero name: Hero prefab: prefabs/hero x: 48 y: 40 originX: 8 originY: 8 z: 5 sprite: atlas: actors frame: hero components: collider: { w: 12, h: 14 } properties: spawn: true - name: hud space: screen order: 100 objects: - id: heart_1 x: 8 y: 8 sprite: atlas: ui frame: heart ``` ### Loading, building and drawing in Go ```go doc, err := sceneformat.Parse(yamlBytes) if err != nil { return err } built, err := sceneformat.Build(doc, sceneformat.FSAssets{ FS: os.DirFS(projectDir), // YAML tilesets, Tiled and LDtk maps Atlases: sceneformat.AtlasMap{ "cave_tiles": tilesAtlas, "actors": actorsAtlas, "ui": uiAtlas, }, }) if err != nil { return err } // Each update step: built.Update(dt) // In a core.Canvas's Draw callback: built.Draw(d) ``` `Parse` rejects unknown YAML keys, trailing documents, unsupported versions, newer-version fields in older scene versions (version 2 fields in version 1, version 3 parallax/repeat fields in versions 1 and 2, version 4 `environment`/`light`/`camera` fields in versions 1–3), multiple `current: true` 3D cameras, scene references that are not slash-separated paths from the project root, overrides without the `scene` or `inherits` they change, duplicate layer names or object IDs (nested children included), object trees deeper than `MaxObjectDepth`, invalid spaces, malformed colors, and non-finite or out-of-range transforms, light/camera/environment parameters, parallax factors, or repeat periods. `Encode` validates and emits deterministic 2-space YAML that round-trips through `Parse` without loss. ### Schema The scene format's JSON Schemas are published at `https://game.nsgo.dev/schemas/scene.v1.json` (`sceneformat.SchemaURL`), `https://game.nsgo.dev/schemas/scene.v2.json` (`sceneformat.SchemaURLV2`, for scenes that instance or inherit other scene files, name glTF models, or hold layered grids or LDtk levels), `https://game.nsgo.dev/schemas/scene.v3.json` (`sceneformat.SchemaURLV3`, for version 3 scenes with parallax and repeating layers), and `https://game.nsgo.dev/schemas/scene.v4.json` (`sceneformat.SchemaURLV4`, for version 4 scenes with 3D lights, environment, and 3D cameras). `Encode` starts every file with the `# yaml-language-server: $schema=…` line for its version (`sceneformat.SchemaCommentFor`), so VS Code's YAML extension and other editors with a YAML language server validate and complete a scene as it is written. See [Schemas for YAML files](https://game.nsgo.dev/docs/schemas/). ### Merging scene files in Git (#1058) `sceneformat.Merge(base, ours, theirs)` performs an identity-based three-way merge of scene documents: layers are matched by `name`, objects by `id` anywhere in the tree (including across reparenting and layer moves), tilemaps and overrides by key, and connections by `(from, event, to, handler)`. Individual fields—including nested `components`, `properties`, `overrides`, `camera` and `args` maps—merge one by one, and clean merges are validated with `Validate` and written with `Encode`. When both sides edit the same field differently, one side deletes what the other modified, both add different items under the same ID, reparenting conflicts or forms a cycle, or the combined scene fails `Validate`, `MergeResult.ConflictDoc(path)` produces a versioned, deterministic YAML `ConflictDoc` (`version: 1`, read and written with `ParseConflict` / `EncodeConflict`) naming every conflict's object, field, and `base`/`ours`/`theirs` values alongside the list of cleanly merged items. Projects wire this into Git through `.gitattributes` (`*.scene.yaml merge=nsgo-scene`) and `go tool game merge -setup` (see [`game merge`](https://game.nsgo.dev/docs/cli/#merge) and [Scene merge conflict report](https://game.nsgo.dev/docs/formats/#scene-merge-conflict-report)). ### Component types A `ComponentRegistry` declares, in Go and without reflection, the component types scene files may use: each type's name and documentation, and each field's name, kind (`FieldBool`, `FieldInt`, `FieldFloat`, `FieldString`, `FieldStringList`, `FieldPoint`, `FieldRect`, `FieldCircle` or `FieldPolygon`), optional allowed `Enum` values (for `FieldString` fields), default, optional inclusive range, optional `Step` for the inspector and documentation. `Register` refuses empty or duplicate names, ranges or steps on non-numeric fields, `Enum` on non-`FieldString` fields, a minimum above the maximum, a fractional range or step on a `FieldInt`, a negative step, and a default of the wrong kind or out of range. The four 2D shape kinds (`FieldKind.IsShape`) describe world geometry in an object's local coordinate space and are also published as `Point`, `Rect`, `Circle` and `Polygon` definitions in `scene.v1.json`, `scene.v2.json` and `scene.v3.json`: | Field kind | Go type | YAML form | Validation | | --- | --- | --- | --- | | `FieldPoint` | `sceneformat.Point` | `{x, y}` | Finite `x`, `y`; unknown keys refused | | `FieldRect` | `sceneformat.Rect` | `{x, y, width, height}` | Finite numbers, `width >= 0`, `height >= 0`; unknown keys refused | | `FieldCircle` | `sceneformat.Circle` | `{x, y, radius}` | Finite numbers, `radius >= 0`; unknown keys refused | | `FieldPolygon` | `[]sceneformat.Point` | `[{x, y}, ...]` | Sequence of valid finite points | `ParsePoint`, `ParseRect`, `ParseCircle` and `ParsePolygon` normalize decoded YAML values into their Go types, and `MarshalYAML` emits alphabetical keys so saved shape fields round-trip unchanged. ```go reg := sceneformat.NewComponentRegistry() reg.MustRegister(sceneformat.ComponentType{ Name: "body", Doc: "A moving body that collides with the level.", Fields: []sceneformat.Field{ {Name: "solid", Kind: sceneformat.FieldBool, Default: true, Doc: "Blocks other solid bodies."}, {Name: "speed", Kind: sceneformat.FieldFloat, Default: 32.0, Min: sceneformat.Float64(0), Max: sceneformat.Float64(500), Doc: "Top speed in points per second."}, {Name: "layer", Kind: sceneformat.FieldInt, Default: 1, Min: sceneformat.Float64(0), Max: sceneformat.Float64(31), Doc: "Collision layer."}, }, }) doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{File: "scenes/room.scene.yaml", Components: reg}) ``` With a registry, `ParseWith` checks the components of every object, nested children included, and refuses an unregistered component type, a misspelled or unknown field, a value of the wrong kind (a `FieldInt` refuses `3.0`; a `FieldFloat` accepts an integer), a non-finite number and a value out of range. The error is a `*ComponentError` carrying the file, line and column of the offending key or value, the object ID, component and field, and lists the registered names: ```text scenes/room.scene.yaml:11:13: sceneformat: object "hero" component "body" field "sped": unknown field (registered: solid, speed, layer) ``` Defaults are not written into the document, so loading and saving a scene changes nothing; `reg.Resolve("body", fields)` returns every field with its default filled in. `ValidateComponents` checks a document built in Go (without positions), and `CheckField` checks one value and normalizes it to `bool`, `int`, `float64` or `string`. `Parse` without a registry keeps `components` free-form. In the editor, `Editor.SetComponentRegistry(reg)` checks the open scene's components and, as `OpenFile` does, its connections, then makes `OpenFile` report component errors with the file and line, and makes `SetComponentField` and `PlaceObject` refuse fields the registry does not allow. Changing the registry clears undo/redo history, so an undone edit the new registry refuses cannot be redone. The inspector lists every registered field of a component in declaration order, including fields the scene leaves unset, which show their default; the label's tooltip gives the field's documentation, kind, range and default, enum fields show a selector, string-list fields edit comma-separated items, and numeric inputs are bounded by the range and step by the field's `Step` (1 for an int, 0.1 for a float when unset). Floats are shown at full precision, and an edit the registry refuses is reported in the status bar. Components without a registered type, or every component when no registry is set, are shown from the values in the file as before (with the built-in physics component schemas available automatically in the inspector). ### Built-in physics components (#817) `sceneformat` ships six versioned built-in physics components (`PhysicsComponentVersion = 1`), registered together with `RegisterPhysicsComponents(reg)` or `PhysicsComponentRegistry()`: | Component | Dimension | Key fields | | --- | --- | --- | | `body2d` | 2D | `version` (`1`), `kind` (`static`, `kinematic`, `dynamic`), `mass`, `gravityScale`, `vx`, `vy`, `friction`, `restitution`, `linearDamping`, `angularDamping`, `material` | | `collider2d` | 2D | `version` (`1`), `shape` (`box`, `circle`), `width`, `height`, `radius`, `offsetX`, `offsetY`, `layer`, `mask` (`[]string`), `isTrigger`; declares events `enter`, `stay`, `exit` | | `trigger2d` | 2D | `version` (`1`), `shape` (`box`, `circle`), `width`, `height`, `radius`, `offsetX`, `offsetY`, `layer`, `mask` (`[]string`); declares events `enter`, `stay`, `exit` | | `body3d` | 3D | `version` (`1`), `kind` (`static`, `kinematic`, `dynamic`, `trigger`), `mass`, `gravityScale`, `vx`, `vy`, `vz`, `friction`, `restitution`, `linearDamping`, `angularDamping`, `lockRotation`, `layer`, `mask` (`[]string`), `material`, `physicsMaterial`; declares events `enter`, `stay`, `exit` | | `collider3d` | 3D | `version` (`1`), `shape` (`box`, `sphere`, `capsule`, `cylinder`, `convex`, `trimesh`, `heightfield`), `width`, `height`, `depth`, `radius`, `offsetX`, `offsetY`, `offsetZ`, `rotX`, `rotY`, `rotZ`, `terrain`, `maxVertices`, `layer`, `mask` (`[]string`), `isTrigger`; declares events `enter`, `stay`, `exit` | | `trigger3d` | 3D | `version` (`1`), `shape` (`box`, `sphere`, `capsule`, `cylinder`, `convex`), `width`, `height`, `depth`, `radius`, `offsetX`, `offsetY`, `offsetZ`, `rotX`, `rotY`, `rotZ`, `maxVertices`, `layer`, `mask` (`[]string`); declares events `enter`, `stay`, `exit` | - **Named collision layers**: `layer` and `mask` reference human-readable layer names declared under `physics.layers` in [`game.yaml`](https://game.nsgo.dev/docs/project/) instead of raw bitmasks (on `collider2d`, `trigger2d`, `body3d`, `collider3d`, and `trigger3d`). Pass `ParseOptions{File: ..., PhysicsLayers: proj.PhysicsLayerTable()}` to `sceneformat.ParseWith` (done automatically by `project.File.LoadAutoloads` and `Editor.OpenProject`): any misspelled or unknown layer name fails to load with a `*loaderr.Error` carrying the exact file path, 1-based line, column, field path, and allowed layer names. - **Building and stepping (`BuildPhysics`)**: `ps, err := sceneformat.BuildPhysics(built, proj.PhysicsSettings(), lib)` constructs the matching `physics.World`, `physics.RigidWorld`, and `physics3d.World` (applying project gravity, solver iterations, named `Layer`/`Mask` bitmasks, optional `*.physics.yaml` files via `PhysicsMaterialResolver`, glTF/primitive meshes for `convex` and static `trimesh` colliders via `ModelResolver` or `FileResolver`, and `*.terrain.yaml` heightfields for static `heightfield` colliders via `TerrainResolver` or `FileResolver`, recorded in `ps.Bodies3D`, `ps.TriMeshes3D`, and `ps.Heightfields3D`). Calling `ps.Step(dt)` steps 2D kinematic and rigid bodies, 2D triggers, and 3D bodies and triggers, writes updated local poses back onto `BuiltObject.Doc`, and dispatches `PhysicsTriggerEvent` (`TriggerEnter`, `TriggerStay`, `TriggerExit`) to `ps.OnTrigger` and any attached `ps.Signals` (`enter` / `stay` / `exit`). - **Play-in-editor, viewport debug outlines, 3D collider handles & fit to bounds (#902)**: `Editor.PlayIn` automatically builds and steps `PhysicsScene` (`Editor.PlayPhysics`, `Editor.PlayTriggerEvents`, `Editor.OnPlayTrigger`) so a scene with a player body, wall colliders, and a coin trigger plays in the editor with collision and trigger events without writing game collision code. While `Editor.ShowPhysicsDebug` is enabled (the default; toggle with `SetShowPhysicsDebug`), both the 2D and 3D viewports render wireframe outlines for every `collider2d`, `trigger2d`, `collider3d`, and `trigger3d` (including cylinders, convex hulls, triangle meshes, and terrain heightfields). Switch the 3D gizmo to `Gizmo3DCollider` (toolbar **Collider**, `View > 3D Gizmo > Collider`, or shortcut `shift+c`) to drag collider size handles (`ColliderHandles3D`, `PickGizmo3D`, `BeginGizmoDrag3D`, `UpdateGizmoDrag3D`, `EndGizmoDrag3D`), committing each drag as a single undo step; press **Fit to Model Bounds** in the Inspector (or call `Editor.FitCollider3DToBounds`) to fit a collider's size and local offset to its mesh or glTF model bounds in one undo step. ### Built-in 2D lighting and occluder components (#887) `sceneformat` ships two versioned built-in 2D lighting components (`Lights2DComponentVersion = 1`), registered together with `RegisterLights2DComponents(reg)` or `Lights2DComponentRegistry()` (and available automatically in the editor's inspector): | Component | Key fields | | --- | --- | | `light2d` | `version` (`1`), `kind` (`point`, `spot`), `color` (CSS color), `radius`, `intensity`, `falloff`, `direction` (radians, added to object rotation), `angle` (spotlight cone spread in radians), `castShadows`, `enabled`, `offsetX`, `offsetY` | | `occluder2d` | `version` (`1`), `shape` (`rect`, `polygon`, `tilemap`), `width`, `height`, `offsetX`, `offsetY`, `points` (`[][2]float64`, flow YAML `[[x, y], ...]`), `layer`, `tileLayers` (`[]string`), `enabled` | - **Automatic `lights2d.Scene` build**: `sceneformat.Build` turns `SceneDoc.AmbientColor`, every `light2d` and `occluder2d` on visible world-space layers, and any `shape: "tilemap"` occluders (derived from tilemap collision shapes via [`tileshape.View`](https://game.nsgo.dev/docs/tileshape/)) into `BuiltScene.Lights2D` (`*lights2d.Scene`). `BuiltScene.Draw` renders `Lights2D` over world-space layers under the scene camera transform (before screen-space HUD layers) unless `SkipLights2D` is set; call `BuiltScene.SyncLights2D()` after moving lights or occluders at runtime. - **2D lighting preview & interactive handles**: The 2D viewport toolbar provides a **Lighting** toggle (`Editor.ShowLightingPreview`, `SetShowLightingPreview`, command `CmdToggleLightingPreview`) that previews the exact same `lights2d.Scene` shadows and ambient darkness live in edit mode. Selecting a `light2d` object shows interactive handles for its radius (`Handle2DLightRadius`), spotlight cone angle (`Handle2DLightSpotAngle`), and spotlight aim direction (`Handle2DLightSpotDirection`). Selecting an `occluder2d` object shows edge handles for `rect` occluders (`Handle2DOccluderRectN/E/S/W`) and draggable vertex (`Handle2DOccluderVertex`) and edge-midpoint insertion (`Handle2DOccluderEdgeMid`) handles for `polygon` occluders (`SetOccluderPolygonPoints`, `InsertOccluderVertex`, `RemoveOccluderVertex`, `ConvertOccluderToPolygon`). Every drag records one undoable step, Escape cancels it, and `SetAmbientColor` (or the Scene Lighting section in the Inspector) edits `ambientColor` undoably. ### Built-in 2D navigation region components (#888) `sceneformat` ships a versioned built-in 2D navigation region component (`NavRegion2DComponentVersion = 1`), registered with `RegisterNavRegion2DComponent(reg)` or `NavRegion2DComponentRegistry()` (and available automatically in the editor's inspector and `scene.v1.json` / `scene.v2.json` / `scene.v3.json`): | Component | Key fields | | --- | --- | | `navregion2d` | `version` (`1`), `mode` (`walkable`, `obstacle`), `points` (`[][2]float64`, flow YAML `[[x, y], ...]`), `offsetX`, `offsetY`, `subtractTileCollision` (`bool`), `tileLayer` (`string`), `tileLayers` (`[]string`), `agentRadius` (`float`, `>= 0`), `enabled` (`bool`) | - **Automatic `ai.NavMesh` build (`BuildNavMesh2D`)**: `sceneformat.Build` collects every enabled `navregion2d` on visible world-space layers (normalizing polygon winding so overlapping walkable regions union and obstacle cutouts subtract cleanly), optionally subtracts solid tile collision geometry from scene tilemaps (via [`tileshape.View`](https://game.nsgo.dev/docs/tileshape/) and non-rectangular solid tile shapes), attaches any authored 2D `nav_link` components, bakes convex polygons with [`game/navbake`](https://game.nsgo.dev/docs/navbake/), and populates `BuiltScene.NavBake2D` (`*navbake.Mesh`) and `BuiltScene.NavMesh2D` (`*ai.NavMesh`). Scenes with no `navregion2d` components keep both fields `nil`; call `BuiltScene.SyncNavMesh2D()` after runtime edits. - **2D NavMesh overlay, polygon handles & Test Path tool**: The 2D viewport renders the built `NavBake2D` convex polygons, shared portals, and authored `navregion2d` outlines whenever `Editor.ShowNavMesh2D` is enabled (default `true`, toggled via toolbar button `view-navmesh2d-overlay`, `SetShowNavMesh2D`, or `CmdToggleNavMesh2D`). Selecting a `navregion2d` object exposes draggable vertex handles (`Handle2DNavRegionVertex`) and edge-midpoint insertion handles (`Handle2DNavRegionEdgeMid`) plus `PlaceNavRegion2D`, `InitNavRegionPolygon`, `SetNavRegionPoints`, `InsertNavRegionVertex`, and `RemoveNavRegionVertex`; dragging updates the built mesh overlay live and commits one undoable step on release (Escape cancels). Selecting the **Test Path** tool (`ToolNavTestPath`, toolbar button `tool-nav-test-path`, command `CmdToolNavTestPath`) lets you press start and end points in the viewport to draw the exact path `BuiltScene.NavMesh2D.FindPath` finds (recomputed live as vertices or tiles change, and cleared with Escape or `ClearNavPathPreview2D`). ### Connections (#490) A scene file connects an event one object emits to a handler of another object, as Godot's `[connection]` entries in a `.tscn` file do, so a button opens a door with no Go code that names either of them: ```yaml layers: - name: props objects: - id: button components: button: {} - id: door components: door: {} connections: - from: button event: pressed to: door handler: open args: speed: 2.5 ``` | Field | Type | Description | | --- | --- | --- | | `from` | `string` | Required ID of the object that emits the event. | | `event` | `string` | Required event name, such as `pressed`, or `button.pressed` to say which component when several components of the object declare it. | | `to` | `string` | Required ID of the object whose handler runs; it may be `from` itself. | | `handler` | `string` | Required handler name, such as `open`, or `door.open`. | | `args` | map | Optional values for the handler's params by name, each a bool, a number or a string; a param left out takes its default. | | `once` | `bool` | Disconnects after the first time the event fires, as Godot's one-shot connections do. | The events and handlers come from the component registry: a `ComponentType` lists the `Events` an object with that component emits and the `Handlers` it can run, each handler with typed `Params` (declared and checked like fields) and the `Func` that runs it. The game registers what each kind of component does once; the scene files decide which objects are wired together. ```go reg.MustRegister(sceneformat.ComponentType{ Name: "button", Events: []sceneformat.Event{{Name: "pressed", Doc: "The player pressed the button."}}, }) reg.MustRegister(sceneformat.ComponentType{ Name: "door", Fields: []sceneformat.Field{{Name: "open", Kind: sceneformat.FieldBool}}, Handlers: []sceneformat.Handler{{ Name: "open", Params: []sceneformat.Field{{Name: "speed", Kind: sceneformat.FieldFloat, Default: 1.0, Min: sceneformat.Float64(0)}}, Func: func(c sceneformat.Call) { c.Target.Components["door"].(map[string]any)["open"] = true }, }}, }) doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{File: "scenes/hall.scene.yaml", Components: reg}) signals, err := sceneformat.Connect(doc, reg, game) // Where the game handles a press on an object with a button component: err = signals.Emit(objectID, "pressed", nil) ``` `Connect(doc, reg, ctx)` checks the scene's components and connections and returns a `*Signals`. `Signals.Emit(from, event, payload)` calls the handler of every connection from that event in the order the file lists them, skipping a `once` connection that has run. Each handler gets a `Call`: the `Signals` (so it can emit further events, nested at most `MaxEmitDepth` levels), the `ctx` given to `Connect` (such as the game's state or a `*BuiltScene`), the source and target `*ObjectDoc` in the scene, the components and names of the event and handler, `Args` holding every param (the connection's value or the default) and the `payload`. `Emit` refuses an object the scene does not hold, an event none of its registered components declares, and a bare name two of its components declare (write `component.event`). `Signals` is a snapshot of the scene's objects as `Connect` finds them: after adding or removing objects in `doc`, which may also move the others in memory, call `Connect` again. A scene that instances or inherits other scene files is connected after `Resolve` (or through `BuiltScene.Doc`), and `Signals` is not safe for concurrent use. `Parse` checks a connection's form: all four names set, `event` and `handler` written as a name or `component.name`, arguments that are bools, finite numbers or strings, no connection repeated, and, in a scene that refers to no other scene file, `from` and `to` naming its objects. With a registry, `ParseWith` also checks the names against it and reports a `*ConnectionError` with the file, line and column: an event or handler no registered component of the object declares, a bare name two of its components declare, an argument the handler has no param for, and an argument of the wrong kind or out of range. The error lists what the object does declare: ```text scenes/hall.scene.yaml:16:14: sceneformat: connection 0 ("button" pressed -> "door" opne): no registered component of object "door" declares handler "opne" (it has: door.open) ``` `ValidateConnections` makes the same checks on a resolved document without positions. `Register` refuses an event or handler with an empty name, a dot in its name or a name its type already uses, and handler params on the same terms as fields; a registry used only to check files, such as an editor's, may leave `Func` unset, which `Connect` refuses. `Resolve` carries connections along: an instanced scene's connections come with the instance, the objects they name prefixed like its objects' IDs (`door_1/button`), so every copy of a prefab keeps its own wiring; an inheriting scene keeps its base's connections and adds its own after them. A scene may connect objects of the scenes it instances or inherits, and those names are checked once it is resolved. In the editor, `DeleteObject` also removes the connections from or to the deleted object and its descendants, and undoing the delete puts them back. #### Queued events `Emit` runs the handlers before it returns, so a handler that emits runs the next handlers inside itself. To keep a step's order plain, emit with `Signals.Enqueue(from, event, payload)` instead and call `Signals.Flush()` once per step, such as at the end of `game.Loop`'s `Update`: ```go loop.Update = func(dt time.Duration) { updateSystems(dt) // the game's own input and systems, which call signals.Enqueue if err := signals.Flush(); err != nil { log.Print(err) } } ``` `Enqueue` refuses what `Emit` refuses before it holds anything, so a misspelled event fails where it is raised. `Flush` runs the events enqueued before it began, in the order they were enqueued, each as `Emit` runs it; an event a handler enqueues, its own included, waits for the next `Flush`, so one `Flush` always ends and a handler never re-enters itself. `Flush` from a handler is refused, and `Pending` says how many events wait. A handler's panic passes through `Flush`, and the events after the one that panicked stay queued for the next `Flush`. Once the queue has grown to a step's events, a step allocates nothing more than emitting them would. #### Spawning connected entities `SpawnConnected(doc, world, reg, ctx)` checks the scene as `Connect` does and spawns its objects as `SpawnEntities` does, then returns each object ID's entity and the `*Signals` that connects those entities. Every check runs before the first entity is spawned, so a scene whose connection names a missing object, event, handler or `Func`, or whose components break their types, spawns nothing. `EmitEntity(e, event, payload)` and `EnqueueEntity` address an object by its entity, `Entity(id)` returns an object's entity, and each `Call` carries `SourceEntity` and `TargetEntity`, so a handler reaches the target's components with `entities.Get`. A destroyed entity emits nothing: `Emit`, `Enqueue` and their entity forms refuse it, `Flush` drops the events it enqueued, and connections to it are skipped. A scene that instances or inherits others is spawned after `Resolve`, its instances' connections reaching the instances' entities (`west/door`). #### Checking connections `nsgo game check` resolves each scene that instances or inherits others. It fails on a scene that does not resolve, such as a cycle or an override naming no object, at the instance or `inherits` line, and on a connection whose `from` or `to` names no object of the resolved scene, at the line that names it. The events and handlers are declared in Go, which the command cannot load, so a game checks them in its own tests with `assetcheck.CheckWith` and its registry. That reports, at the file and line, a connection naming an event, handler or argument its objects do not declare and a component that breaks its type; in a scene that instances or inherits others, it also checks the components its overrides write and every connection of the resolved scene, so an override that breaks a connection the instanced or inherited scene brings, such as one adding a second component that declares the same event, fails at the override: ```go func TestScenesCheck(t *testing.T) { report, err := assetcheck.CheckWith(os.DirFS("."), assetcheck.Options{Components: Components}) if err != nil { t.Fatal(err) } for _, p := range report.Problems { t.Error(p) } } ``` ```text scenes/level.scene.yaml:12: sceneformat: connection 0 ("lever" held -> "west/door" open): no registered component of object "lever" declares event "held" (it has: button.pressed) ``` A fault that a scene brings unchanged from a scene it instances or inherits is reported on that file, and one that its overrides cause on the override, so each fault is reported once. Problems carry the line, not the column. ### Inspector (#865) The inspector sets up an object without editing YAML. Every edit it makes is one undoable step, and each has a method on `Editor` that does the same in Go; while Play is on, the methods return `ErrPlaying` and the controls are disabled. An edit the editor refuses is reported in the status bar. - **Sprite**: the Sprite field picks an atlas frame from those the asset browser lists (`Assets`), grouped by atlas and searchable, and its clear button unbinds it; the button beside it takes the frame selected in the asset browser. `SetObjectSprite(id, ref)` needs both an atlas and a frame, and with a resolver set the atlas must resolve and hold the frame; a nil `ref` unbinds the sprite. - **Origin and flip**: `originX` and `originY`, the pivot inside the sprite's frame, are set with `SetObjectOrigin(id, x, y)`, which refuses values that are not finite, and `flipX` and `flipY` with `SetObjectFlip(id, flipX, flipY)`. - **Material**: the Material field picks one of the open project's `*.material.yaml` files and its clear button names none; `SetObjectMaterial(id, path)` takes a slash-separated path from the project root, or an empty one. A material must load through the editor's resolver, which therefore has to implement `sceneformat.MaterialResolver` (as `resource.Library` does), since the scene could not be built otherwise; with any other resolver the field lists no files and stays enabled only to clear a material the object already names. - **Model (#893)**: in 3D the inspector shows a **MODEL** summary card (`ObjectModelSummary3D`: offscreen thumbnail, project-relative path, triangle count, and distinct material count) above the searchable Model field (`ProjectModels`: the project's `.gltf` and `.glb` files and the outputs of `game.yaml`'s model targets) whose clear button names none, a **MATERIAL** summary (`ObjectMaterialSummary3D`: material file name with roughness and metallic readouts), a **COLLIDER** summary (`ObjectColliderSummary3D`: e.g. `Convex hull · static`), a **CHILDREN** summary card (`ObjectChildrenSummary3D`) when inspecting a group, and **Ask to add a component…** (`OpenComponentAgentPrompt`). `SetObjectModel(id, path)` refuses a model that does not load and a model on an object that draws a built-in primitive, as the Mesh field is disabled on an object that draws a model; changing the model clears `modelNode` and `modelMesh`, which named parts of the old one, and naming one raises a version 1 scene to version 2, the first that has models, and leaves a later one as it is. Undo puts back all three fields and the version. - **Properties**: Add Property takes a key and a kind (`string`, `int`, `float` or `bool`) and adds the property holding that kind's zero value (`AddProperty(id, key, kind)`); the field trims the key, and an empty key, one with leading or trailing whitespace or one the object has, is refused. A whole-number float property is saved with a decimal point (`2.0`), so it opens again as a float. Each property's delete button removes it (`DeleteProperty`). - **Components**: the Add Component field filters the registered types the object lacks, and pressing one adds it holding every registered field at its default, so the file shows what the component does (`AddComponent(id, name)`). Enter adds the type the field names, or the one type it matches. A component the object already has, a name the registry does not know, and a name with leading or trailing whitespace or a `.` (which connections use in `component.event`) are refused; without a registry the field adds a component of any name with no fields. Adding a component is refused, too, when it would declare an event or handler that a connection names bare and another of the object's components declares as well, since the connection would no longer say which it means: write it as `component.event` first. In a scene that instances or inherits others, the check runs on the scene as resolved through the editor's resolver, the connections of the scenes it refers to included; it is skipped when the resolver cannot load scene files or the scene does not resolve and bind even without the new component. Each component's remove button removes it (`RemoveComponent(id, name)`) with every connection that needs it, from the object with an event the component declares or to the object with a handler it declares, named bare or as `component.name`; a bare name is attributed through the component's registered type, so without a registry, or for a type the registry does not know, only connections written as `component.name` are removed. `ComponentConnections(id, name)` lists them, and Undo puts the component and its connections back where they were. A component without a registered type keeps its fields editable from the values in the file; having no schema, a whole-number float in one of its fields is saved as `2` and opens again as an int. - **Connections (#872)**: the Connections section lists the events declared by the selected object's registered components (`ObjectEvents`) and every outgoing and incoming connection touching it (`ObjectConnections`). Pressing **Connect** opens an inline form to pick an event, choose a target object from the searchable object list (`SceneObjectIDs`) or pick it directly from the 2D/3D viewport or scene tree (`BeginConnectionPick` / `CancelConnectionPick` without losing the current selection), pick one of the target's registered handlers (`ObjectHandlers`), fill the handler's params with typed controls from the component registry, and toggle `once`. Each connection row lets you jump to its other end (`JumpToConnectionOtherEnd`), edit it (`UpdateConnection`), or remove it (`RemoveConnection`). Adding, editing and removing connections (`AddConnection`, `UpdateConnection`, `RemoveConnection`) are undoable commands checked with `sceneformat.Validate` and `sceneformat.ValidateConnections` before reaching `History`: an invalid connection (such as naming a handler the target lacks, a duplicate connection, or a wrong param type or out-of-range value) is refused with the reason shown in the status bar, leaving the scene and undo history unchanged. Without a component registry, existing connections remain visible, jumpable, editable and removable. - **Scene settings (#871, #884)**: when no object, room, layer, or asset file is selected (`ShowingSceneSettings`), the inspector displays the open scene's own settings instead of an empty state: scene `name` (`SetSceneName`), `virtualWidth` and `virtualHeight` (`SetVirtualSize`), `backgroundColor` via NSGo's color picker (`ui.ColorWell`) and CSS hex input with a clear button (`SetBackground`), and the default 2D `camera` (`SetCamera`, `SetCameraPosition`, `SetCameraZoom`, `SetCameraRotation`) with toggleable clamp `bounds` (`SetCameraBounds`, `ClearCameraBounds`). Each change is validated against `sceneformat.Validate` before touching the document or history—refusing non-positive virtual sizes, zoom, or bounds and invalid color strings in the status bar—updates the viewport live, saves and reloads unchanged, and participates in Undo/Redo. While scene settings are shown in 2D edit mode, the viewport highlights the camera's start view frame and dashed bounds, draws a draggable camera position handle (`CameraHandleCanvasPos`, `HitTestCameraHandle`, `BeginCameraDrag`, `UpdateCameraDrag`, `EndCameraDrag`, `CancelCameraDrag`), and draws 8 corner/edge resize handles on `camera.bounds` (`CameraBoundsHandleCanvasPos`, `HitTestCameraBoundsHandle`, `BeginCameraBoundsDrag`, `UpdateCameraBoundsDrag`, `EndCameraBoundsDrag`, `CancelCameraBoundsDrag`) so dragging a handle resizes `camera.bounds` (and dragging the border or empty interior moves it) live, cancels on Escape, and commits as a single undoable step. - **Room maps (`*.rooms.yaml`, #884)**: open an existing `*.rooms.yaml` file beside the scene from the file browser (`OpenRoomsProjectFile`, `OpenRoomsFile`, `OpenRoomsYAML`) or create one from the Scene Settings inspector (`NewRoomMap`). All rooms draw over the 2D scene viewport with their IDs, display names, transition tags, and 8 resize handles on the selected room. Create rooms by toggling **Draw Room** (`SetRoomCreateMode`) and dragging in the viewport or pressing **Add Room** (`AddRoom`, `AddRoomAtViewCenter`); select, move, and resize rooms with handles (`HitTestRoom`, `HitTestRoomHandle`, `BeginRoomDrag`, `UpdateRoomDrag`, `EndRoomDrag`, `CancelRoomDrag`) and delete them with the Delete button or Delete/Backspace key (`DeleteRoom`). When **Grid Snap** is enabled (default on, `SetRoomSnapToGrid`), room edges snap to the scene's tile grid (`RoomGridSize`, from the scene's inline or external tilemap or an explicit `SetRoomGridSize`). Selecting a room opens the Room Inspector to edit its `id` (`SetRoomID`), `name` (`SetRoomName`), bounds (`SetRoomRect`), and per-room `transition` (`SetRoomTransition`: inherit, `cut`, `slide`, or `fade` with duration, easing, and fade color), as well as the map-level default transition (`SetRoomMapTransition`). All room edits go through `Editor.History`, participate in `HasUnsavedChanges` and `Save`, and save deterministically via `rooms.Encode` (`SaveRooms`, `SaveRoomsFile`, `SaveRoomsYAML`) so files load with `rooms.Parse` and round-trip unchanged. - **Layer inspector (#885, #877)**: when a layer is selected with no object selected (for example after pressing a layer's row in the scene tree, choosing **Inspect Layer** in the layers panel context menu, pressing **Set Up Tilemap** in an empty tile palette, or calling `SetActiveLayer`), the inspector shows that layer's parallax factors (`Parallax X`, `Parallax Y`), tiling settings (`Repeat` X/Y, `Repeat W`, `Repeat H`), and **Tilemap** setup. In Go, `SetLayerParallax(layer, x, y)` and `SetLayerRepeat(layer, repeatX, repeatY, width, height)` edit parallax and repeat, and `AddLayerTilemap(layer, tileset, tileW, tileH, w, h)`, `SetLayerTilemapTileset(layer, tileset)`, `SetLayerTilemapTileSize(layer, tileW, tileH)`, `ResizeLayerTilemap(layer, left, right, top, bottom)`, `ExtractLayerTilemap(layer, refName)`, `InlineLayerTilemap(layer)`, and `RemoveLayerTilemap(layer)` set up and edit the layer's tilemap—all undoable through `History`. Growing or shrinking from the left or top edge shifts painted cells and updates `offsetX`/`offsetY` so every painted tile keeps its world position (raising version 1 or 2 scenes to version 3 when a non-zero offset is written, restored by Undo). Invalid sizes and tilesets missing frames for painted tile IDs are refused with a status message. Moving a tilemap into top-level `tilemaps` creates a `ref`, and moving it back inline removes the top-level entry once no other layer or `layerOverrides` references it. Parallax and repeat controls are disabled on screen-space layers; inherited base-owned layers disable all layer inspector edits. ### Projects The editor also opens a game's [project file](https://game.nsgo.dev/docs/project/): `OpenProject` reads `game.yaml` and opens its main scene, `EditProject` changes it as an undoable step, and `SaveProject` writes it with the `nsgo.yaml` beside it in step. `nsgo game editor ` opens a project directory. With `ProjectAssets` set, as the editor commands of package `editorcmd` set it, opening a project makes `Resolver` a `project.Resolver` over the project's directory: the scene draws the project's own sprite atlases, found by name nearest the open scene as `game check` finds them, the asset browser lists them, `PlaceScene` instances the project's scene files, and materials, physics materials, YAML tilesets and Tiled and LDtk maps load from the project, the tilesets and maps through its `ReadFile` as `FSAssets` reads them. An atlas a scene names is found nearest the file that names it, so a scene file instanced or inherited from another directory draws the atlas `game check` finds for it. The editor reads the atlases and material files again whenever it makes a change that may add, remove or rewrite them, such as installing or removing a pack, moving files, `ReloadAssets` or `RefreshSearch`; saving a scene keeps what it has read. `OpenProjectScene(path, scene)` opens the project with the scene file `scene` in place of its main scene, which `nsgo game editor` does for a scene file inside a project's directory, so `ScenePath` names it and an instance of it in itself is refused as a cycle. `MoveFile(from, to)` moves a file or directory of the project and rewrites every reference to it, on disk and in the open scene and project, as `nsgo game mv` does ([Stable references](https://game.nsgo.dev/docs/project/#stable-references)), as one step that Undo takes back and Redo makes again. Undo puts each file the move rewrote back byte for byte, unless it changed since, in which case only its references are rewritten back. While a project is open, the file browser below the asset browser (`FilesView`) lists its files and directories (`ProjectFiles`), leaving out the directories that `game index` and `game mv` skip too: those whose names start with `.` or `_` and those named `testdata`. Pressing one selects it and puts its path in the field below the list; edit the path and press Move to rename or move it through `MoveFile`, press Open Table on a `.yaml`/`.yml` file to open it in the Data Table editor (`OpenDataTableProjectFile`), or press Find Refs to list every reference to it across the project (`ShowReferences`). Refresh lists the files again and rescans the project search and references index (`RefreshSearch`) after something outside the editor changed them. ## Data Table editor (#918) The Data Table panel (`DataTablePanelView`) opens versioned YAML data tables ([`tooling/datatable`](https://game.nsgo.dev/docs/datatable/)) from the file browser as a spreadsheet-style grid below the viewport: - **Columns and kinds**: columns are the union of every row's keys in deterministic first-appearance order (plus any fields declared by a registered Go row type that no row currently sets). Each column's value kind (`string`, `number`, `bool`, `duration`, or `list`) is inferred from its cell values or taken from the registered Go row type; boolean cells render as toggle buttons and scalar/list cells commit on Enter or blur. - **Row operations and view controls**: add (`AddDataTableRow`), delete (`DeleteDataTableRow`), and reorder (`MoveDataTableRow`) rows, sort by clicking any column header (`SetDataTableSort`), and filter visible rows by case-insensitive substring match (`SetDataTableFilter`). Sorting and filtering affect only the view and never reorder or modify the underlying YAML document. - **Undo and lossless round-trip**: opening, closing, adding, deleting, reordering, and editing cells all go through the editor's shared `History`. Opening and saving a table without edits leaves the file byte-for-byte identical, and editing a single cell changes only that line while preserving comments, formatting, and each row's key order. - **Go row-type validation and panel states**: a game's own editor command can bind Go struct row types to slash-separated path or filename patterns with `editor.RegisterDataTableType[T](ed, pattern)` (or `Editor.RegisterDataTableRowType`). Matching tables are checked on open and on every cell or row edit with the exact same rules `datatable.LoadYAML` applies, refusing unknown columns, duplicate fields, and invalid cell values in the grid and showing the `*datatable.CellError` in the dismissible panel banner (`DataTableError` / `ClearDataTableError`) and status bar. Asynchronous table loaders can also toggle the loading card with `DataTableLoading` / `SetDataTableLoading`. ```go if err := editor.RegisterDataTableType[Enemy](ed, "data/enemies/*.yaml"); err != nil { log.Fatal(err) } ``` ### Reviewing an agent's data table changes (#1033) When an agent proposes changes to one or more data table files (through `Editor.OpenDataTableReview` or the `datatable_review_propose` MCP tool), the editor opens a full-window row-by-row Data Table review (`DataTableReviewView`) using exclusively the editor's design spec tokens: - **Turn files and empty tables**: the left sidebar lists every data table touched in the turn (`27 of 40 changed`, `new · 0 records`); selecting a newly created empty file shows `"No records — ask the agent to add some"`. - **Filter chips, search, and sorting**: switch between **All**, **Changed**, **Unchanged**, **Reverted**, and **Yours** chips with live counts (`SetDataTableReviewFilter`), search across all fields (`SetDataTableReviewSearch`), and click any column header (`CycleDataTableReviewSort`) to cycle ascending, descending, and back to file order (reporting `aria-sort` via `DataTableReviewAriaSort`). Numeric columns with changes show a `Δ` header and sort by percentage delta without mutating file order. - **Old → new cells, in-place edits, and drag-to-reorder**: changed cells render in the Spec `changed` dashed pill showing struck-through old value `→` new value and `Δ%`, while numeric zeros render as `—` (`FormatReviewCellValue`). Each changed record has its own **Revert** / **Restore** button (`ToggleDataTableReviewRecord`). Clicking a cell value edits it in place (`StartDataTableReviewCellEdit`, `SetDataTableReviewCellText`, `StepDataTableReviewCellNumber`) and dragging a row's grip handle reorders it (`ReorderDataTableReviewRecord`); both join the review under **Yours** with a solid accent border and a `you` tag in the right-hand YAML diff pane (`DataTableReviewFocusedYAML`). - **Agent's check figures**: the agent attaches named figures (`DataTableReviewCheck`: label, value, optional value before the request, and basis) via `SetDataTableReviewChecks` or the `datatable_review_checks` MCP tool. Any person revert, restore, in-place edit, or row reorder marks those figures **Out of date** (`DataTableReviewChecksOutOfDate`) until the agent refreshes them. - **Pause, lossless Keep, and single-step Undo**: pressing `Esc` or **Editor** pauses the review (`PauseDataTableReview`), keeping autosave paused (`HasOpenReview`) and showing a `"Review paused"` toast with **Resume** plus a pending review card in the Agent panel (`ResumeDataTableReview`). **Keep N of M** (`KeepDataTableReview`, `⌘↵`) starts from the original parsed `datatable.Document` bytes and patches only the kept and edited lines so untouched and reverted lines stay byte-for-byte identical, committing every file in **one atomic Undo step** (`Undo` restores all files byte for byte and removes newly created files). **Revert all** (`RevertAllDataTableReview`, `⌘⌫`) closes the review cleanly without modifying disk and stays undoable with `⌘Z`. ### 2D viewport navigation (#864) The 2D viewport's canvas fills its panel and shows the scene through the editor's own view (`View2D`: the world point at the canvas's center, a zoom and a rotation), separate from the scene's `camera`, so a level larger than one screen can be seen and edited anywhere. The view is never saved to the scene nor recorded in the undo history. - A mouse wheel, a pinch, or a touchpad scroll with Control or Command held zooms about the pointer, keeping the world point under it fixed (`ZoomView2DAt`), between `MinView2DZoom` and `MaxView2DZoom`. - A touchpad's two-finger scroll, a mouse wheel's sideways scroll (Shift+wheel or a tilting wheel), a middle-button drag, a drag with Space held or a two-finger drag on a touch screen pans (`PanView2D`). - F, or the Frame Selection button, frames the selected object (`FrameSelection2D`, which frames everything when nothing is selected); Home, or Frame All, frames every object of the visible layers, their inline tilemaps and the camera's frame (`FrameAll2D`); Mod+0, or Scene Camera View, returns to the scene camera's view (`ResetView2D`). Until the author pans or zooms, and again after `ResetView2D` or opening another scene, the view is the scene camera's view: the virtual screen centered in the canvas at the camera's zoom and rotation, following the camera as the scene changes (`View2DFollowsCamera`). In edit mode the whole canvas takes the scene's `backgroundColor`, so objects far from the camera are seen against the game's clear color; it outlines the camera's frame, the virtual screen as the player sees it, and draws the camera's `bounds` dashed. Screen-space layers draw inside that frame. In Play mode only the frame shows, centered at the camera's view whatever view the author left, as in the game; the view does not pan or zoom until Stop brings the author's view back. Hit testing, placing, moving, tile painting, the selection outline and plugin tools all go through the view, applying each world-space layer's parallax offset (and previewing its repeat tiling) smoothly as the 2D view pans. `CanvasToWorld` and `WorldToCanvas` convert between canvas points and the world; `CanvasToScreen` and `ScreenToCanvas` between canvas points and the scene's virtual screen, where screen-space layers live; `ScreenToWorld` and `WorldToScreen` apply the scene's camera alone, as the game does. `CanvasSize` is the canvas's laid-out size, the scene's virtual size until the viewport lays out (`SetCanvasSize`); the 3D viewport fills the same canvas. ### 2D transform gizmo (#863) With the Select or Move tool, the 2D viewport edits an object's transform by dragging, as Godot's and Unity's 2D transform tools do: - A drag on any object selects it and moves it, keeping the offset from where it was grabbed, so the object does not jump to the pointer. - The selected object carries a gizmo drawn at a fixed size on the canvas: a square at its origin moves it freely; a red and a green arrow move it along its own X and Y axes, which turn with its rotation; a ring around it turns it about its origin; and, once its outline is at least 24 points on a side on the canvas (zoom in on a small object), handles on its corners and edges scale it about its origin, the edges one axis and the corners both. A handle that sits on or next to the origin's line along an axis it scales is left out, as the top and left handles of a sprite whose origin is its top left corner are, and where the move square and a handle overlap, the square is taken. Holding Shift while scaling keeps the aspect ratio. Dragging a scale handle through the origin mirrors the object with a negative scale. - Each drag is one undoable step, recorded when it ends ("Move hero", "Rotate hero", "Scale hero"); Undo restores the object's fields exactly, an unset `scaleX` or `scaleY` staying unset, and an edge handle leaves the other axis's field alone. A drag that ends where it began records nothing. - Escape, a gesture the system cancels or a second finger coming down puts the object back as it was before the drag and records nothing; the rest of that gesture does nothing. Undo, Redo, Play, Save, Delete, Duplicate, or changing the tool or the view mode during a drag cancels it first. - A scale that would be zero or nearly so (below 0.001), or a scale or rotation that would shear a sprite in the object's tree, its ancestors included (a rotated child under a non-uniformly scaled parent, which `ScaleObject` and `RotateObject` refuse too), is not taken: the object keeps its last valid transform and the status bar says why. - A nested child carries the gizmo too and is dragged in its parent's space, so it follows the pointer under a turned or scaled parent. An object hidden or locked in the scene tree, or under one that is, has no gizmo and is not dragged, even while it is selected. Drags map through the object's layer: a world-space layer's objects move by the world distance the pointer travels, whatever the 2D view's or the scene camera's zoom and rotation, and a screen-space layer's by the distance on the virtual screen. A tap still selects, and with the Move tool still puts the selected object where it is pressed. A drag with Space held, or a middle-button drag, pans the view instead. In Go, `BeginDrag2D(x, y)` starts a drag at a canvas point and returns the handle it took (`GizmoHandle2D`), `UpdateDrag2D(x, y, keepAspect)` follows the pointer, and `EndDrag2D` or `CancelDrag2D` finishes it; `PickGizmo2D` names the handle under a canvas point, `Dragging2D` the one held, and `Gizmo2DShown` says whether the gizmo is drawn. ### 2D component shape handles (#882) In 2D edit mode, the viewport draws every registered shape field (`FieldPoint`, `FieldRect`, `FieldCircle` and `FieldPolygon`) of the selected object in its local space (accounting for parent transforms, rotation, scale, layer space and parallax). Toggling **Shapes** in the 2D view toolbar (`SetShowAllShapes`, `CmdToggleAllShapes`, `Editor.ShowAllShapes`) draws shape fields of all visible objects in the scene at once, keeping the selected object highlighted on top. With the Select or Move tool, interactive handles appear on the selected object's shape fields: - **Point**: drag the handle to move `(x, y)`. - **Rectangle**: drag any of the 4 corner or 4 edge handles to resize (dragging past the opposite edge flips smoothly while keeping `width >= 0` and `height >= 0`), or drag the center handle when it does not overlap the object's origin move square. - **Circle**: drag any of the 4 cardinal rim handles to change `radius` (clamped `>= 0`), or drag the center handle when offset from the object's origin. - **Polygon**: drag any vertex handle to move it; click or drag an edge midpoint handle to insert a new vertex (`AddPolygonVertex`); right-click or Alt+click a vertex handle to remove it (`RemovePolygonVertex`, keeping at least 3 vertices). - **Grid snapping**: toggle **Snap** in the 2D view toolbar (`SetSnapToGrid`, `CmdToggleSnapGrid`, `Editor.SnapToGrid`) or configure snapping in the Snap popover (`view-snap-settings`) to snap handle edits and inserted vertices to `EffectiveGridStep` (or whole points when pixel snapping is enabled; holding `Ctrl` / `Cmd` inverts snapping during a drag). Every drag, vertex addition, and vertex removal commits through `SetComponentField` as one undoable step, and Escape, a cancelled gesture, a second finger, Undo/Redo, Play, Save or switching tools cancels an in-progress drag and restores the pre-drag field unchanged. In Go, `VisibleShapes2D`, `ShapeHandles2D`, `PickShapeHandle2D`, `BeginShapeDrag2D`, `UpdateShapeDrag2D`, `EndShapeDrag2D`, `CancelShapeDrag2D`, `DraggingShape2D`, `ActiveShapeHandle2D`, `AddPolygonVertex`, `RemovePolygonVertex` and `HandleCanvasSecondaryPress` expose the same workflow, and the inspector displays editable controls for every shape field kind. ### Snapping and 2D grid overlay (#869) The editor provides unified snapping across object placement, dragging, 2D handles (transform gizmo, component shapes, 2D lights/occluders, and 2D navigation regions), and 3D gizmos (translate, rotate, and scale): - **Snap settings in the toolbar**: toggle grid snapping directly with the magnet button (`view-snap-grid`, `SetSnapToGrid`, `CmdToggleSnapGrid`) or open the compact Snap Settings popover (`view-snap-settings` in 2D, `view3d-snap-settings` in 3D) to switch each mode independently: - **Grid snap** (`SnapToGrid`, `SetSnapToGrid`): snaps positions to `EffectiveGridStep()`, which defaults to the active layer's tilemap tile size (supporting non-square tiles) when `GridSize` is `0`, falling back to `8` when the active layer has no tilemap. Setting an explicit step (`SetGridSize`) overrides the tile size until **Auto** (`ResetGridSize`) is pressed. - **Pixel snap** (`SnapToPixel`, `SetSnapToPixel`, `CmdToggleSnapPixel`): snaps positions to whole points (1-unit increments) when grid snap is off. - **Rotation snap** (`SnapRotation`, `SetSnapRotation`, `CmdToggleSnapRotation`): snaps 2D and 3D rotation drags to multiples of `RotationSnapDeg` degrees in radians (`SetRotationSnapDeg`, default `15°`). - **Scale snap** (`SnapScale`, `SetSnapScale`, `CmdToggleSnapScale`): snaps 2D and 3D scale drags to multiples of `ScaleSnapStep` (`SetScaleSnapStep`, default `0.25`) without collapsing scales to zero. - **Modifier inversion**: holding `Ctrl` or `Cmd` during a drag or placement press temporarily inverts snapping—disabling active snapping for free precision edits, or enabling snapping when it is off (`SetSnapInvert`). - **Optional 2D grid overlay** (`ShowGrid`, `SetShowGrid`, `CmdToggleShowGrid`): draws a hairline grid across the visible 2D canvas at the active snap step even outside tile tools, following `View2D` pan, zoom, rotation, and active-layer space/parallax, doubling drawn spacing automatically when zoomed far out so the grid never obscures the canvas. - **Multi-object selection moves as a whole**: select multiple objects with `SelectObjects`, `ToggleSelectObject`, or Shift-click in 2D `ToolSelect` (`SelectedIDs`). Dragging any selected object (or using the Move tool or 3D Translate gizmo) snaps the primary anchor and moves every other non-descendant selected object by the exact same snapped delta, preserving relative offsets and recording one undoable step (Escape cancels and restores all objects). - **Per-project preferences**: snap settings (`SnapSettings`, `SetSnapSettings`) are editor preferences saved per project in `.game/editor.yaml` (`ViewStateFile`), never written to scene files and never marking a scene dirty. Switching scenes within the same project keeps the project's snap settings; switching projects saves and restores each project's own preferences. ## 3D viewport (#890) In 3D the viewport shows the scene as the game draws it: a `gpu.View` fills the panel and draws the scene's 3D build with render3d, and the canvas over it draws the ground grid, the origin axes, the selection outline and the gizmo. The build is `scenemodel.Build`'s (`Scene3D`): every object's built-in primitive (`mesh`) or glTF model (`model`, `modelNode`, `modelMesh`) with its materials and textures, the objects that instanced scenes add included. Models, material files and images load through the editor's `Resolver` when it implements `scenemodel.ModelResolver`, `sceneformat.MaterialResolver` or `scenemodel.ImageResolver`, and from the open project's files otherwise. When the scene does not build, such as when a model it names does not load, a line in the viewport's corner says why (`Viewport3DError`) and every object keeps a box. - **Lights and sky**: when a version 4 scene defines lights or an `environment`, the viewport renders the scene's own lights, shadows, sky (solid color, gradient, or HDR cubemap via `scenemodel.HDRResolver`), ambient/IBL, fog, tonemapping, and exposure through `scenemodel.Renderer` (`PrepareScene`, `RecordShadows`, `DrawSky`, `ClearColor`), matching the game's render path pixel for pixel. When a scene defines neither lights nor an environment, the viewport falls back to `DefaultLights3D` under a gradient sky. An editor built on this package can still override lighting with `SetLights3D` (`Editor.Lights3D`), which draws over `backgroundColor`. - **Shading**: the toolbar's 3D Shading group, `View > 3D Shading` and the commands `view.shading.lit`, `view.shading.unlit` and `view.shading.wireframe` switch `Shading3D` (`SetShading3D`): Lit, Unlit (each surface's textured base color plus its emissive color, without lights), and Wireframe, which lights the geometry and draws the edges of its triangles over it. Shading is a view setting: it is not undoable and is not saved. - **Picking and nested children (#894)**: every nested object up to 64 levels deep—including children added by instanced and inherited scenes—draws at its composed world transform (`ObjectLocalTransform3D` composed up the parent chain, matching `BuildNodes3D` identically) across meshes, wireframes, light/camera/probe icons, physics debug wireframes, occluders, and component gizmos. A press selects the deepest hit object under the pointer: an object that draws a mesh or model is hit on its triangles through `scene3d` picking, while an object without geometry is hit on its world-space box only where no geometry is hit (with a hit descendant winning over its enclosing ancestor). Pressing a second time on an already-selected nested child steps selection up to its parent—and through to the owning scene instance root—before cycling back to the deepest child; holding `Alt`/`Option` while clicking (`Select3DAtWithModifiers`, `HandleViewport3DPressWithModifiers`, `HandleCanvasPressWithModifiers`) directly selects the owning scene instance root for an instanced child or the immediate parent for a locally nested child (and composes with `Shift` to add and `Mod` to toggle). Hidden and locked objects (with their descendants) are passed over. - **Parent-space gizmo editing and instance overrides (#894)**: when a nested child is selected, the 3D transform gizmo (`Translate`, `Rotate`, `Scale`, single- or multi-selection) draws at the child's composed world position and orientation; dragging moves or turns the child under the pointer in world space while inverting the parent chain to write the child's local transform in parent space. Dragging an object that comes from an instanced scene or base scene writes an override entry under the owning instance's `overrides` (or `SceneDoc.Overrides` for inherited scenes) without touching the source scene file, round-trips through YAML, and commits as one undoable step. - **Live edits**: the build is made again only when what the scene looks like changes (an object's look, its place in the tree, an instanced scene or an override, or the project's files). A gizmo drag, an undo of a move, the open animation clip's pose at the playhead and a playing game's changes move the built nodes in place, so a drag rebuilds and uploads no mesh. `ObjectCorners3D` and `ObjectAABB3D` give an object's box as the bounds of its geometry when it has any, and Frame Selection (`f`) frames those bounds, so a model a meter across fills the view. - **Without a GPU**: on a target where the GPU view is not supported, before its first frame and after a device loss, the canvas draws the whole wireframe view instead: the scene's background, the grid, a box around every object (its geometry's bounds when it has any) and the gizmo. `Viewport3DOnGPU` reports which one shows. `OrbitCamera3D.SceneCamera` turns the editor's orbit camera into the `scene3d.Camera` the GPU view draws through, with the same eye, projection and clip planes the canvas projects with, so the overlays line up with the geometry. ### Navigating the 3D view (#891) Navigating moves only the editor's camera (`Camera3D`, an `OrbitCamera3D`): it is never an edit, never goes into the undo history and never changes the scene file. The camera jumps where it is told without animating. | Do | With a mouse | With a touchpad or touch screen | With the keyboard or a button | | --- | --- | --- | --- | | Orbit about the target | Drag | Drag with one finger | The Orbit 15° left and right buttons under the axis widget | | Pan | Middle-button drag, or Shift+drag | Two-finger scroll, or a two-finger drag on a touch screen | | | Zoom toward the target | Wheel | Pinch, or scroll with Control or Command held | | | Fly | Hold the right button: move the pointer to look, W, A, S, D to move, Q and E down and up, Shift to go faster, the wheel to change the speed | | | | Focus the selection | | | `f` or the bottom bar's Focus `F` button, framing its bounds, or the whole scene with nothing selected | | Axis views | | Click an axis button (`X`, `Y`, `Z` or negative ends) on the orientation widget in the top right corner | `1` Front, `ctrl+1` Back, `3` Right, `ctrl+3` Left, `7` Top, `ctrl+7` Bottom, or Tab/Enter on the orientation widget | | Perspective or orthographic | | | `5`, or Persp and Ortho in the top-left viewport bar | | Shading mode | | | The top-left viewport bar's Shading menu (`Lit`, `Unlit`, `Wireframe`) | | Transform space (Local / Global) | | | `t`, Local / Global in the bottom bar, or command `gizmo.3d.space` | | Back to the default view | | | The top-left viewport bar's Reset view button | - **The viewport HUD and status bar** follow the editor's design spec tokens: the top-left bar pairs Persp/Ortho, the Shading menu (`Lit`, `Unlit`, `Wireframe`), the current view name (`ViewName3D`: an axis view name or `Perspective`, with ` · ortho` in orthographic and `User · ortho` when orbited off-axis), Reset view, and Camera/Env toggles, with the keycap help line (`Drag orbit · Middle pan · Right WASD fly · F focus`) directly underneath. The top-right circular orientation widget exposes clickable, keyboard-focusable buttons for all six axis ends above the Orbit 15° left and right buttons. The bottom bar holds the `Local` / `Global` transform space toggle (`GizmoSpace3D`, `SetGizmoSpace3D`), Snap settings popover, and `Focus F` button. The status bar adds the view's yaw and pitch in degrees (` · yaw N° · pitch M°`) and the active gizmo space (` · Local` or ` · Global`). - **Orthographic** (`SetOrthographic3D`, `OrbitCamera3D.Orthographic`) projects in parallel. The view is `OrthoHeight` high, the height the perspective view shows at the target, so switching keeps what lies there the same size, and zooming changes that height. `Project`, `ScreenRay`, `SceneCamera`, picking and the gizmo work the same in both: in orthographic every pixel's ray runs along the view, so a press picks what lies under it and a gizmo drag moves the object by the distance the pointer travels along the axis. An axis view in orthographic is a true plan or elevation. - **Flying** (`BeginFly3D`, `FlyLook3D`, `FlyMove3D`, `EndFly3D`) turns the camera about its eye and moves eye and target together. While it flies, W, A, S, D, Q and E, with or without Shift, move the camera instead of running their usual shortcuts (the gizmo's W and E, Erase Tile's E), and the pointer is locked to the viewport where the platform can lock it. A flight looks in perspective, so an orthographic view switches to perspective; a right-click that neither turns nor moves the camera leaves it orthographic. Its speed, `FlySpeed3D` in world units a second, starts at the camera's distance from its target and the wheel doubles or halves it (`AdjustFlySpeed3D`). - **Axis views** (`SetView3D`, the commands `view.3d.front`, `view.3d.back`, `view.3d.right`, `view.3d.left`, `view.3d.top` and `view.3d.bottom`, and `view.3d.orthographic` for the projection) keep the target and the distance. Front looks along -Z, Right along -X and Top straight down with -Z at the top of the view. - **Saved per scene**: each scene of a project opens at the camera it was left at. The editor writes the views to `.game/editor.yaml` in the project (`ViewStateFile`, described on [File Formats](https://game.nsgo.dev/docs/formats/)) as another scene opens, as the scene is saved and as the window closes, and an app that ends the editor another way calls `SaveViewState`. A scene it has no view of opens at `DefaultOrbitCamera3D`. Creating the `.game` folder, the editor writes a `.gitignore` there that ignores the folder, so the views stay out of version control. A file a newer editor wrote, with a higher `version`, is neither read nor written over. ### 3D transform gizmos (#892) The 3D viewport's transform gizmo reuses `render3d.Gizmo` for drawing, picking, and constrained drags in **Global** (world) or **Local** space: - **Modes and shortcuts**: press `w` (Translate, `Gizmo3DTranslate`), `e` (Rotate, `Gizmo3DRotate`), and `r` (Scale, `Gizmo3DScale`) in the 3D viewport (`ScopeViewport3D`, without clashing with 2D tile tools' `e`), or choose them in the 3D toolbar or `View > 3D Gizmo`. - **Global / Local space toggle**: toggle `Editor.GizmoSpace3D` (`GizmoSpaceGlobal` / `GizmoSpaceLocal`) via the 3D bottom bar's **Local** / **Global** toggle (`view3d-space-local` / `view3d-space-global`), shortcut `t` (`CmdGizmoSpace3D`), `View > 3D Gizmo > 3D Gizmo: Local / Global Space`, or `SetGizmoSpace3D` / `ToggleGizmoSpace3D`. In Local mode, handles orient to the selected object's Gram-Schmidt orthonormalized world orientation—including its ancestors for nested children (`GizmoOrientation3D`). - **Exact rotation about the drawn axis**: dragging any rotation ring (X, Y, or Z) composes the drag around the exact world-space axis the drawn ring represents and converts the child-local result (`RParentᵀ · RDeltaWorld · RWorldStart`) back to scene Euler XYZ (`Rz·Ry·Rx`), so even on an object already rotated about multiple axes or nested under a rotated or scaled parent, every ring turns strictly about the axis drawn. - **Plane handles, screen-space center handle, and uniform scale**: Translate exposes `Axis3DXY`, `Axis3DXZ`, and `Axis3DYZ` planar squares (moving strictly within the active two-axis plane, with grazing-ray guards) and a center `Axis3DAll` handle (translating in the camera view plane). Scale exposes a center `Axis3DAll` cube that scales all three axes proportionally. - **Snapping and live drag delta**: 3D translate, rotate, and scale drags share the editor's snap settings (`SnapSettings`, `EffectiveGridSize`, `EffectiveRotationSnapDeg`, `EffectiveScaleSnapStep`) and temporary `Ctrl`/`Cmd` modifier inversion (`SetSnapInvert`). While dragging, the status bar displays the live delta (`GizmoDragDelta3D`: `dx`/`dy`/`dz`, degrees `°`, or scale factor `x`) alongside the active space (`Global`/`Local`), and every completed drag commits as **one undo step** that round-trips cleanly through scene YAML (`Escape` cancels and restores the pre-drag transform). ### Placing models in 3D (#893) The asset browser lists, under its atlases, the models to place in 3D (`Models`): the built-in primitives, then the open project's glTF models by path, the outputs of `game assets` model targets included before they are built (`ModelEntry.Output`). Each has a thumbnail rendered offscreen (`ModelThumbnail`): the model alone, framed from above and in front and lit by `DefaultLights3D`, drawn through scenemodel on NSGo's software GPU. Each model loads on the UI goroutine the first time its thumbnail is drawn, as everything the editor's `Resolver` serves loads, and apart from the scene's own cache of models; the rendering runs off the UI goroutine, so the list shows at once and the pictures follow. A model that does not load gets none. - **Place tool**: pressing a model selects it (`SelectModel`, `SelectedModel`) and, in 3D, turns on the Place tool, which the 3D toolbar shows beside Select. In 3D a press then adds an object drawing the model, named after it, where the pointer's ray hits the scene's geometry, or where it crosses the ground plane, the horizontal plane at `PlaceHeight3D`, when it hits none (`PlacementAt3D`, `PlaceModelAt3D`). The object rests on that point: it is raised along the surface's normal by how far its geometry reaches below its origin, so a unit box on the floor sits on it rather than half under it. Hidden and locked objects are passed over, as picking passes over them. - **Snap and Align**: the toolbar's Snap snaps the X and Z of a point on the ground plane to the spacing of the grid the viewport draws (`PlaceSnap3D`); a point on the scene's geometry is not snapped, since the grid's spacing can be wider than the object under the pointer, Align turns a model placed on the scene's geometry so that its +Y axis follows the surface's normal (`PlaceAlign3D`), and the ground height field sets `PlaceHeight3D`. They are view settings, not edits (`SetPlaceOptions3D`). - **Drag and drop**: dragging a model from the asset browser onto the 3D viewport places it where it is dropped, through the Place tool's rules, whatever the active tool. A `.gltf` or `.glb` file dropped on the viewport from another app is placed when it lies inside the project's folder, outside the folders the asset browser leaves out (names starting with `.` or `_`, and `testdata`) (`DropModelFiles`), several files as one step; a file outside the project, of another kind or from the web, which names no path, is refused with the reason in the status bar. A file drop carries no position, so dropped files land where the view's middle points. - **Bottom MODELS strip**: in 3D view (outside Assets drawer mode), a **MODELS** strip (`Viewport3DModelsStripView`, `StripModels`) sits along the bottom of the 3D viewport (`"drag in"`), showing offscreen-rendered thumbnails of the project's models first followed by built-in primitives, each with the tooltip `"Drag into the viewport to place "`, click-to-select and drag-into-viewport placement, and a pinned **Or ask for one** button (`OpenModelAgentPrompt`) that opens an inline agent prompt (`"Describe a model… e.g. a low stone planter, 1 × 0.5 m, same stone as the walls"`) dispatching `Viewport3DAgentRequest` to `Editor.OnAskAgent3D` (`SubmitViewport3DAgentPrompt`). - **One step**: every placement is one undoable step, which Undo takes back and Redo makes again. It is refused while playing, on a locked active layer and on a screen-space one, and for a model that does not load; placing a model in a version 1 scene raises it to the current version, as `PlaceObject` does. ### 3D lights, environment and scene cameras (#895) Version 4 scenes carry their own 3D lighting, environment, and 3D camera objects, edited directly in the 3D viewport and panels: - **Icons and picking**: visible directional, point, and spot lights and 3D cameras draw crisp, color-tinted icons in the 3D viewport overlay instead of generic marker cubes; clicking an icon selects its object (`Pick3D`). - **Interactive undoable handles**: selecting a light or 3D camera reveals wireframe guides and draggable handles (`Handle3DKind`, `HandlePosition3D`, `PickHandle3D`, `BeginHandleDrag3D`, `UpdateHandleDrag3D`, `EndHandleDrag3D`, `CancelHandleDrag3D`): - Directional light: direction arrow and aim handle (`Handle3DLightDirection`). - Point light: three orthogonal range circles and range radius handle (`Handle3DLightRange`). - Spot light: aim handle (`Handle3DLightDirection`), range distance handle (`Handle3DLightRange`), and separate outer (`Handle3DLightOuterCone`) and inner (`Handle3DLightInnerCone`) cone rim handles. - 3D camera: frustum wireframe with vertical FOV / orthographic height handle (`Handle3DCameraFOV`) and far plane handle (`Handle3DCameraFar`). Every drag updates the live GPU viewport in place without rebuilding meshes and commits as one undoable step on `Editor.History`. - **Scene Environment panel (`EnvironmentPanelView`)**: toggled from the 3D viewport bar's **Env** button, `View > Scene Environment`, or `CmdEnvironmentPanel` (`EnvironmentPanelOpen` / `SetEnvironmentPanelOpen`), editing sky (`none`, `color`, `gradient`, `hdr`), ambient color and intensity, IBL intensity, distance and height fog, tonemapping (`none`, `reinhard`, `aces`, `neutral`, `agx`), and exposure through `SetEnvironment` (validated and undoable, upgrading scenes below version 4 to version 4 and restoring the prior version on Undo). - **Inspector and creation helpers**: in 3D view (or on any object with a light or 3D camera), the inspector exposes `LIGHT 3D` (`SetObjectLight`) and `CAMERA 3D` (`SetObjectCamera3D`, switching `current` atomically across cameras in one undo step). In Go, `AddLight3D(kind)` and `AddCamera3D(proj)` place pre-configured lights and 3D cameras on the active world layer, and `ProjectHDRs()` lists `.hdr`/`.pic` skies in the open project. - **Look Through Scene Camera**: press `0`, click **Camera** in the 3D viewport bar, or run `CmdView3DCamera` (`SetLookThroughCamera3D` / `ToggleLookThroughCamera3D`) to view the 3D viewport through the scene's active 3D camera (`ActiveSceneCamera3D`), matching the game's first frame pixel for pixel. Orbiting, panning, zooming, flying, or choosing an axis view exits camera preview cleanly. ### Reflection probes and light probe grids (#903) Version 4 scenes also support local 3D reflection probes (`ObjectDoc.ReflectionProbe`) and 3D light probe grids (`ObjectDoc.LightProbeGrid`) baked directly from the editor so runtime shading in `scenemodel` matches the editor 3D viewport pixel for pixel: - **Placement & inspector**: place probes with `AddReflectionProbe3D` / `AddLightProbeGrid3D` (or command palette `CmdAddReflectionProbe` / `CmdAddLightProbeGrid`) and edit their local box bounds (`center`, `size`), blend distance, intensity, priority, box projection, cubemap resolution, grid counts, and baked file paths in the inspector (`REFLECTION PROBE` via `SetObjectReflectionProbe`, `LIGHT PROBE GRID` via `SetObjectLightProbeGrid`) as undoable steps. - **Viewport icons, wireframes, and 3D bounds handles**: reflection probes draw a cyan chrome-sphere icon, outer influence wireframe box, and inner blend wireframe box; light probe grids draw an amber dot-grid icon, bounds wireframe box, and projected sample points. Selecting either exposes six draggable face-center bounds handles (`Handle3DProbeBoundsPosX`..`Handle3DProbeBoundsNegZ`) that resize the box while anchoring the opposite face, commit as a single undoable step (`EndHandleDrag3D`), and cancel cleanly with Escape (`CancelHandleDrag3D`). - **Baking**: click **Bake Cubemap** / **Bake Probes** in the inspector, **Bake Probes** in the Scene Environment panel, or run `CmdBakeProbes3D` (`BakeReflectionProbe3D`, `BakeLightProbeGrid3D`, `BakeAllProbes3D`). Reflection probes render the 3D scene from the probe origin and write a lossless 6×1 Radiance `.hdr` cubemap strip (`render3d.EncodeCubemapHDR`); light probe grids sample the scene at every grid point and write L2 spherical harmonic irradiance coefficients as deterministic versioned YAML (`*.probes.yaml`, `render3d.EncodeLightProbeGrid`, schema `https://game.nsgo.dev/schemas/lightprobes.v1.json`). Output paths are validated against traversal/symlinks/reserved filenames, written atomically, linked onto the probe undoably, and loaded by `scenemodel.Build` and `scenemodel.Renderer` so game and editor shading match identically. ## Tile palette (#874) While the Paint, Erase, Fill, Pick or Terrain tool is active in 2D, the tile palette shows right of the viewport. It shows the tiles of the active layer's tileset as a grid in tile ID order, each at the tilemap's tile size (a tile wider than the panel is scaled down to fit it). The tiles are the tileset atlas's frames whose names are tile IDs (`"1"`, `"2"`, …), as the scene format looks tiles up; other frames are left out. Pressing a tile, or moving between tiles with the arrow keys, makes it the tile Paint and Fill write (`SetActiveTileID`); every arrow key steps through the tiles in ID order, Left and Up to the previous tile and Right and Down to the next, not by rows of the grid. The selected tile is ringed, and with Paint or Fill the status bar shows its ID. Choosing a tile is not an edit and does not go into the undo history; the paint that follows is one undoable step. The palette follows the active layer: when it changes, the palette shows the new layer's tileset, and if that tileset has no tile with the selected ID, its first tile is selected. A layer with no inline tilemap (none, or an external Tiled or LDtk map), a tileset the resolver cannot resolve and a tileset without tile frames each show a message saying so instead of an empty grid. In Go, `TilePalette()` returns what the palette shows for the active layer: its tileset, tile size and tiles, or the message. For an inline or layered grid naming a `tilesetFile`, the palette shows the tiles of its YAML tileset, read through the resolver's `sceneformat.FileResolver` (such as `FSAssets`), with IDs from 1 as `PaintTile` takes them: tile ID `n` paints the tileset's local tile `n - 1`. The palette's labels and the status bar name each tile by its local ID, the number the rows and the tileset's `tiles[].id` write (`PaletteTile.Number`), and a footer note reminds you that collision, terrain and variant rules live in the tileset file. Above the tiles, a toggle per tile layer (for layered grids) picks the one Paint, Erase, Fill and Terrain change (`SetActiveTileLayer`, `ActiveTileLayer`, the first by default), the H, V and D toggles set the flips Paint and Fill place tiles with (`SetActiveTileFlip`, `ActiveTileFlip`), the terrain toggles pick the terrain set Terrain paints (`SetActiveTerrain`, `ActiveTerrain`), and **Edit Tileset** opens the layer's `*.tileset.yaml` in the Tileset Editor. While a 2D tile tool is active on a YAML tileset layer with no object selected, the right-side **Tile Inspector** shows the picked tile's swatch, display name and source cell, a `COLLISION` toggle (`Solid`, `One-way`, `None`), its terrain/collision/variant-weight rules, and a button to open the full Tileset Editor. The edits write the layer's rows in the form `Encode` saves, one undoable step each, and Fill joins cells whose tile and flips both match. ## Painting, erasing and picking tiles (#875) With Paint or Erase, a drag with the mouse or one finger paints or erases every cell it crosses, however fast it moves, and the whole stroke is one undoable step, so one Undo takes back a row painted in one drag. A click or tap paints or erases its one cell. With Paint, a right-button drag erases. A stroke that starts off the map paints once it reaches it, a stroke that changes nothing records nothing, and a drag with Space held pans the view instead. A second finger cancels a one-finger stroke and puts its cells back, so a two-finger pan never paints. While a tile tool is active, the cell under the mouse is outlined, snapped to the grid: with Paint and Fill it shows the selected tile faded in the cell, with Terrain it shows the autotiled tile faded in emerald, with Erase it is tinted red, and when a press would pick it is outlined in amber. Picking takes the tile in a cell as the tile to paint, and the palette selects it: Alt+click (or Alt+drag) with any tile tool, or the Pick tool, which then hands over to Paint. An empty cell leaves the selected tile as it was. Picking is not an edit and does not go into the undo history. In Go, `BeginTileStroke(mode, x, y)`, `ContinueTileStroke` and `EndTileStroke` draw a stroke (`TileStrokePaint`, `TileStrokeErase`, `TileStrokePick`, `TileStrokeTerrain` or `TileStrokeEraseTerrain`) at canvas points, `CancelTileStroke` puts it back and `TileStrokeActive` reports one under way; painting and erasing refuse locked or hidden layers, and choosing a tool or layer, changing layers, switching views, saving, Undo, Redo and Play end a stroke under way first (while Revert cancels it). `PickTile(layer, col, row)` picks, `SetTileHover` and `ClearTileHover` move the outline and `HoveredTile` returns the cell it is on. ## Terrain painting and tileset editor (#878, #879) Inline and layered tilemaps backed by `*.tileset.yaml` share their tile flags, collision shapes, animations, custom data and autotiled terrain sets between the runtime (`tilemap.ApplyTerrain`, `tilemap.SetTerrainTile`, `physics.MoveAndSlide`, `tileshape.New`) and the editor: - **Terrain brush (`ToolTerrain`, shortcut `t`)**: drags place terrain (`TileStrokeTerrain`) and right-button drags erase terrain (`TileStrokeEraseTerrain`), updating each touched cell and its surrounding neighbors with the exact same 4-bit cardinal (`cardinal`) and 8-bit corner-gated (`blob`) rules as `tilemap.Tilemap.SetAutotile`. The entire stroke — both placed/erased cells and every updated neighbor — is recorded as one undoable step, so one Undo restores the stroke cleanly. In Go, `PaintTerrain(layer, col, row, terrain)` and `EraseTerrain(layer, col, row, terrain)` perform single-cell edits. - **Tileset Editor (`TilesetEditorPanelView`)**: open any `*.tileset.yaml` from the tile palette's **Edit Tileset** button (`OpenActiveLayerTileset`), the Tile Inspector, double-clicking or pressing **Open** / **Edit Tileset** in the file browser (`OpenTilesetProjectFile`), or `OpenTilesetFile` / `OpenTilesetYAML`. The left atlas grid previews every tile with badges for solid/one-way collision, custom shapes, animation, terrain masks and default tiles, while four tabs edit each tile: - **Terrain**: create or delete 4-bit (`cardinal`) and 8-bit (`blob`) terrain sets (`AddTilesetTerrain`, `RemoveTilesetTerrain`, `SetTilesetTerrainMode`), set an explicit fallback default tile (`SetTilesetTerrainDefault`), and assign each tile's neighbor bitmask by clicking its center, edges (`N`, `E`, `S`, `W`) and — in 8-bit `blob` mode — corners (`NW`, `NE`, `SW`, `SE`) (`ToggleTilesetEdgeOrCorner`, `ToggleTilesetTileCenter`, `SetTilesetTileMask`). Corner clicks enforce corner-gating automatically (enabling a corner enables both adjacent edges; clearing an edge clears dependent corners). If an intermediate click matches a mask owned by another tile, the editor leaves that tile intact so you can keep clicking or press **Reassign** (`ReassignTilesetEditMask`). - **Collision**: toggle `Solid`, `One-way`, `None`, or custom flag bits (`SetTilesetTileCollision`, `SetTilesetTileFlags`, `ToggleTilesetTileFlagBit`), and draw rectangular (`rect`) or multi-vertex (`polygon`) collision shapes directly over the magnified tile canvas (`AddTilesetTileShape`, `UpdateTilesetTileShape`, `RemoveTilesetTileShape`, `AddTilesetDraftPolygonPoint`, `CommitTilesetDraftPolygon`). - **Animation**: build and reorder per-tile animation frames with durations (`AddTilesetTileAnimFrame`, `UpdateTilesetTileAnimFrame`, `RemoveTilesetTileAnimFrame`, `SetTilesetTileAnimation`) alongside a live playing/pausable frame preview (`SetTilesetAnimPlaying`, `TilesetAnimPreviewTile`). Animated tiles advance live in the 2D editor viewport as well as in Play mode and the game (`StepTileAnimations`). - **Data**: edit each tile's display `name`, variant `weight`, and typed custom properties (`bool`, `int`, `float`, `string`) (`SetTilesetTileName`, `SetTilesetTileWeight`, `SetTilesetTileProperty`, `DeleteTilesetTileProperty`). - Every tileset edit goes through the editor's `History` (undoable/redoable), takes effect immediately in the viewport, Play mode and Terrain brush before saving, and saves back as canonical YAML (`SaveTileset`, `SaveTilesetYAML`). Agents can read and edit the same fields atomically via the editor MCP tools `tileset_read` and `tileset_edit` ([MCP](https://game.nsgo.dev/docs/mcp/#tools)). ## 3D GridMap painting (#899) In 3D view (`ViewMode3D`), the editor opens and paints modular 3D [`*.gridmap.yaml`](https://game.nsgo.dev/docs/world3d/#modular-3d-gridmap) files directly on an editable floor grid: - **Opening and attaching**: set an object's `gridMap` field in the inspector (`SetObjectGridMap`) or open a `*.gridmap.yaml` file (`OpenGridMap`, `OpenGridMapFS`, `OpenGridMapDoc`, `NewGridMap`). Switching to a GridMap tool in the 3D toolbar (**Paint**, **Erase**, **Pick**, or **Box**) automatically opens the selected object's `gridMap` when none is open yet, and `MoveFile` tracks the open GridMap's path and `meshLibrary` reference. - **Palette with 3D thumbnails**: while a GridMap tool is active in 3D view, `GridMapPaletteView` (`GridMapPalette()`) appears right of the viewport, rendering an isometric shaded 3D thumbnail for every tile in the glTF `meshLibrary` alongside controls for the active floor height and 24-orientation index. - **Floor height and 24 orientations**: press `]` / `PageUp` and `[` / `PageDown` (`SetGridMapFloor`, `StepGridMapFloor`) to move the active horizontal painting plane up or down by one cell. Press `X`, `Y`, `Z` (with `Shift` for reverse) or `Q` / `Shift+Q` (`RotateGridMapOrientation`, `StepGridMapOrientation`, `SetGridMapOrientation`) to rotate the active tile through all 24 axis-aligned cube orientations (`world3d.RotateGridOrientation`). - **Painting, erasing, picking and box fill**: hovering in the 3D viewport projects the pointer ray onto the active floor (`ScreenToGridMapCell`) and draws a live hovered cell preview (and a dashed rectangular preview while dragging **Box** fill). Clicking or dragging paints or erases every cell crossed as a single undoable stroke (`BeginGridMapStroke`, `ContinueGridMapStroke`, `EndGridMapStroke`, `CancelGridMapStroke`, `Escape` cancels), **Pick** (or Alt+click) adopts the tile and orientation under the pointer, and **Box** drags out a filled rectangle on the active floor (`FillGridMapBox`). - **Undo and canonical save**: every paint stroke, erase stroke, box fill, and cell rotation (`PaintGridMapCell`, `EraseGridMapCell`, `FillGridMapBox`, `RotateGridMapCell`) goes through the editor's shared `History` (Undo/Redo). `Save` (`SaveGridMap`, `SaveGridMapFile`) writes canonical deterministic `.gridmap.yaml` via `world3d.GridMap.ToDoc` and `world3d.EncodeGridMap`, so saved files round-trip byte-for-byte and instance identically in `scenemodel.Build`. ## Rectangle, line, stamp and random tile brushes (#876) Four additional tile brushes extend inline and layered tilemap painting, each showing a live preview in the 2D viewport before release, cancelling cleanly on **Escape** (or a second touch) without mutating the scene, and committing every changed cell as **one undoable step** in `Editor.History`: - **Rectangle (`ToolRectTile`, shortcut `u`)**: drag between two cells to fill the rectangle with `ActiveTileID` (`TileStrokeRect`, `FillTileRect`), or right-drag to erase the dragged rectangle (`TileStrokeRectErase`, `EraseTileRect`). - **Line (`ToolLineTile`, shortcut `l`)**: drag between two cells to draw a Bresenham line of `ActiveTileID` (`TileStrokeLine`, `DrawTileLine`), or right-drag to erase along the line (`TileStrokeLineErase`, `EraseTileLine`). - **Stamp and region clipboard (`ToolStampTile`, shortcut `c`)**: paint a rectangular `TileStamp` pattern anchored to the click or pattern-aligned across a drag (`TileStrokeStamp`, `StampTiles`), preserving per-cell flip bits on layered tilemaps and empty (`0`) cells from copied regions. Build a stamp either by selecting a rectangle of tiles in the tile palette (`SelectPaletteStamp`, `SelectPaletteStampRange`, or clicking an anchor tile and pressing **Rect** or holding Shift before clicking the opposite corner) or by right-dragging a map region (`TileStrokeSelectRegion`, `SetTileSelection`) and using **Copy** (`mod+c`, `CopyTileRegion`, `CopySelectedTileRegion`), **Cut** (`mod+x`, `CutTileRegion`, `CutSelectedTileRegion`, one undo step) and **Paste** (`mod+v`, `PasteTileRegion`). - **Random (`ToolRandomTile`, shortcut `n`)**: paint a deterministic weighted pick from multiple tiles (`SetRandomBrushTiles`, `SetRandomBrushTileWeight`, `ToggleRandomBrushTile`) controlled by a fixed seed (`SetRandomBrushSeed`, `RandomBrushSeed`). In the tile palette, clicking tiles toggles them in the weighted pool with per-tile `-`/`+` weight controls and a Seed field; right-drag erases. In Go, `TilePreview()` inspects the live preview cells of an in-progress brush stroke before `EndTileStroke`, `TileStamp` / `TileClipboard` / `TileSelection` manage patterns and regions, and all four brushes work identically on single-grid and layered YAML tilemaps while keeping deterministic YAML round-trip saves. ## Agent tile tools and region-based tile edit review (#1064) Coding agents connected to the editor's MCP server ([MCP](https://game.nsgo.dev/docs/mcp/#tools)) can inspect and paint inline and layered tilemaps while the author reviews changes by connected region rather than individual cells: - **Query and paint tools**: `tile_query` (`Editor.QueryTiles`) finds matching cells or empty pockets by tile ID, YAML tileset `tileName`, or sub-rectangle (for example, `"an 11 × 5 pocket at columns 2–12, rows 12–16"`). `tile_paint` (`Editor.AgentPaintTiles`) paints explicit cells, inclusive rectangles, or deterministic seeded weighted tile picks (with optional `noAdjacentDuplicates`). `tile_autotile` (`Editor.AgentAutotile`) re-edges or places a YAML tileset terrain set using the same 4-bit `cardinal` / 8-bit `blob` rules as `ToolTerrain`. `tile_erase` (`Editor.AgentEraseTiles`) clears cells or rectangles. Each call applies as one undoable edit and joins the active tile review by default (`review: true`). - **Region-based review (`TileReviewPanelView`)**: pending agent changes are grouped into connected regions by kind — **painted** (`+`, green dashed outline), **replaced** (`~`, amber dashed outline), and **erased** (`−`, red solid outline) — each showing its cell count, bounding rect, and human-readable detail (such as `"from 4 cave tiles"`). Clicking a region focuses it in the 2D viewport; each region can be independently toggled between **Revert** and **Restore** (`SetTileReviewRegionReverted`, `ToggleTileReviewRegion`). **Before / After** and **hold `B`** (`SetTileReviewViewMode`, `SetTileReviewPeekBefore`, `TileReviewHandleKeyEvent`) preview the pre-review tilemap live. **Keep N of M** (`KeepTileReview`) commits all kept regions cleanly as **one** undoable `History` step (so one Undo restores the exact pre-review tilemap), and **Revert all** (`RevertAllTileReview`) restores the original tilemap immediately. Agents and tests can also drive reviews via `tile_review_status`, `tile_review_revert_region`, `tile_review_restore_region`, `tile_review_keep`, and `tile_review_revert_all`. - **Palette & viewport caption**: while a tile layer is selected in 2D, the viewport shows a top-left layer dimension caption (`ActiveTileLayerCaption`, e.g., `World · 24 × 20 cells · 16 px`), and the tile palette displays `TILESET ` with a selected-tile readout showing the picked tile's swatch, name, atlas cell coordinates, collision rule, and terrain set. ## Scene tree (#861) The scene tree panel (`SceneTreeView`), at the left of the editor, lists the open scene's layers and, under each, its objects with their children nested, as Godot's Scene dock and Unity's Hierarchy do. It follows every edit and every undo. Pressing an object's row selects it, and selecting an object in either viewport selects its row and opens the rows above it; pressing a layer's row makes it the active layer. Every object edit works on a nested child as on a top-level object: `FindObject` and `SelectObject` find an object by ID anywhere in the tree, the inspector edits the selected child, and its transform is edited in its parent's space, so the Move tool puts its origin under the press and the 3D gizmo moves it along the world axis. - **Moving in the tree**: drag a row onto another to make it that object's last child, or near the top or bottom edge of the row to put it before or after it; drop it on a layer's row to move it to the top level of that layer. A row's context menu moves it up or down among its siblings, makes it a child of the sibling above, moves it out of its parent, or moves it to another layer. In Go, `ReparentObject(id, parentID, index)`, `MoveObjectToLayer(id, layer, index)`, `ReorderObject(id, index)` and `DropObject(id, targetID, place)` do the same, each as one undoable step; an index below 0 or past the end puts the object last. - **World transform**: a moved object keeps its world transform. Its local transform is computed again under its new parent in 2D (`x`, `y`, `rotation`, `scaleX`, `scaleY`), and Undo puts every field back exactly; a flipped object keeps its negative scale on the axis it had. When the object or one of its old or new ancestors sets a 3D field, its depth (`posZ`, `scaleZ`) is kept too. When one of them sets a 3D rotation (`rotX`, `rotY`, `rotZ`), the 2D and 3D views no longer agree on where `x` and `y` lead, and only the 3D world transform is kept: the object stays in place in the 3D viewport, and may move in the 2D one. The move is refused when it would put an object under itself or one of its descendants, nest deeper than `MaxObjectDepth`, or leave a transform that cannot be written as a translation, rotation and scale under the new parent, as a sprite under a turned parent stretched along one axis would be. A move between a world and a screen layer keeps the numbers, not where the object appears on screen. - **Rename**: F2, a double press or the context menu's Rename edits the selected object's name in its row; Return or leaving the field keeps it, and Escape drops it. Change ID edits its ID through `SetObjectID(oldID, newID)`, which rewrites the scene's connections that name the object, and the objects of a scene it instances (`enemy_1/body` becomes `boss/body`), in the same step, as well as the open animation clip's target and the targets of its tracks, and refuses an ID the scene already uses, including one an instanced or inherited scene adds. Another scene file that instances or inherits this one and overrides the object by its old ID is not rewritten; move such references with `game mv` or edit them by hand. - **Eye and lock**: the eye button of a row hides the object, and with it its descendants, in both viewports, and the lock button stops a press in either viewport from picking it, so the press reaches what lies under it (`SetObjectHidden`, `SetObjectLocked`). Neither viewport moves a hidden or locked object: its 3D gizmo is not shown and the Move tool leaves it where it is. Both belong to the editing session: they are not edits, Undo does not touch them, they are never written to the scene file, Play draws every object, and opening another scene clears them. A hidden or locked object can still be selected from the tree and edited in the inspector. The 3D viewport draws and picks every object, nested children included: `Objects3D` lists them depth first, each with its parent's ID, and a child's geometry and box are placed by its ancestors' transforms ([3D viewport](https://game.nsgo.dev/docs/editor/#3d-viewport-890)). ### Object context menu (#1039) Secondary-clicking or Control-clicking an object in the 2D viewport, the 3D viewport, or a Scene Tree row—or pressing `Shift+F10` or the Context Menu key (`contextmenu`) on the active selection—opens a unified `ui.ContextMenu` headered with the object's display name and kind/layer subtitle (for example, `Sprite · layer actors`). Right-dragging in the 3D viewport still flies the camera, right-dragging with 2D tile tools still erases or selects a tile region, and right-clicking a polygon collider vertex still removes that vertex; actions whose feature does not apply to the target object or session are omitted rather than shown disabled. - **Copy as YAML (`mod+c`) and Paste (`mod+v`)**: `CopyObjectYAML` / `CopySelectedYAML` (`ObjectYAML`) encodes the object as a canonical `sceneformat` YAML document onto the clipboard (`core.Scope.SetClipboard` or `Editor.WriteClipboard`) that `sceneformat.Parse` round-trips back to the exact same object, and shows a floating viewport toast (`Copied as YAML · N lines`). `Paste` / `PasteObjectYAML` pastes from the clipboard onto the active layer with a fresh unique ID in one undo step. - **Duplicate (`mod+d`) and Group (`mod+g`)**: `DuplicateObjects` clones the selected object(s), and `GroupObjects` / `GroupSelected` wraps them under a new parent object in one undo step while preserving world transforms. - **Move under**: the submenu (`MoveUnderCandidates`, `MoveObjectUnder`) lists valid candidate parent objects—excluding the object itself, its descendants, and moves that would exceed `MaxObjectDepth`—annotated with current parent, locked state, child count, or layer, and reparents in one undo step so a single Undo puts the object back. - **Select same prefab**: when the object sets `prefab` or `scene`, `SelectSamePrefab` selects every object in the scene sharing that reference (`SelectedIDs`, `SelectObjects`, `IsObjectSelected`). - **Hide / Show (`h`), Lock / Unlock, Find usages (`shift+f12`), Rename (`f2`), and Ask the agent (`mod+l`)**: toggle session visibility (`ToggleObjectHidden`) and lock (`ToggleObjectLocked`), find usages in the open project (`FindObjectUsages` / `ShowObjectUsages`, opening the Find Usages review screen for scene/prefab-path targets or Search for plain IDs, omitted without an open project), start inline renaming in the Scene Tree (`RequestRenameObject`), or send an `AgentPromptRequest` draft to `Editor.OnAskAgent` (`AskAgentAboutObject`). Context menus read live custom shortcuts (`EffectiveShortcut`), expose scene-instance and inherited-object override actions (`Open Instanced Scene`, `Make Local`, `Apply Overrides to Source`, `Open Source Scene`, `Revert Overrides`) while guarding local-only structural edits on foreign objects, and retain Scene Tree order, Cut, Paste as Child, Ungroup, Change ID, Move to Layer, and Delete actions. - **MCP parity (`pkg/editor/editormcp`)**: every context menu action calls an exported `Editor` method that the editor MCP server exposes (`object_copy_yaml`, `object_paste_yaml`, `object_duplicate`, `object_group`, `object_move_under`, `object_select_same_prefab`, `object_visibility`, and `object_find_usages`, alongside `scene_edit` and `selection_get`'s `selectedIds`). ### Multi-object selection and batch editing (#867) The editor tracks an ordered selection set with `Editor.SelectedID` as the primary object (`SelectedIDs`, `SelectionCount`, `IsSelected`, `SelectedObjects`, `SelectObjectsWithPrimary`, `AddToSelection`, `RemoveFromSelection`, `ToggleSelection`, `ClearSelection`): - **Viewport selection and marquee**: In 2D and 3D, `Shift`+click adds an object to the selection and `Mod` (`Cmd`/`Ctrl`)+click toggles membership (`HandleCanvasPressWith`, `HandleViewport3DPressWith`). In 2D with Select, dragging on empty canvas draws a marquee box (`BeginMarquee2DWith`, `UpdateMarquee2D`, `EndMarquee2D`, `CancelMarquee2D`, `SelectMarquee2D`) that selects enclosed objects by default, or touching objects when `Alt` is held (`MarqueeEnclose`, `MarqueeTouch`); `Shift` adds and `Mod` toggles marquee matches. `Escape` cancels an active drag or marquee first, and clears selection at rest. - **Scene tree synchronization**: `SceneTreeView` follows and drives the same multi-selection set with `Shift`+click and `Mod`+click, expanding ancestors of selected objects. - **Common-center transforms, Delete and Duplicate**: Move, rotate, and scale gizmos in both 2D and 3D act on the whole selection about its combined bounding-box center (filtering out descendants whose ancestor is also selected so children never double-transform), and `DeleteSelected` / `DuplicateSelected` act on the whole selection; each operation records **one undo step** via `History.Group`. `FrameSelection` frames all selected objects together. - **Shared-field inspector**: When multiple objects are selected, `InspectorView` shows `"N selected"` and only the sections shared by every selected object (Transform, Sprite when all have sprites, shared Properties and shared Components). Differing values display as `"Mixed"` (or indeterminate for checkboxes), and editing any field writes every selected object in **one undo step** (`EditSelected`, `SetSelectedComponentField`, `SetSelectedProperty`, `SetSelectedX`, …) so a single Undo restores each object's own prior value. ### Copy, paste, duplicate and group objects (#868) The scene tree supports multi-object selection (`SelectObjects`, `SelectedIDs`, `ToggleSelectObject`, `IsObjectSelected`), and object clipboard, duplication, and grouping actions live in the Edit menu, Scene Tree context menu, Command Palette, and keyboard shortcuts: - **Copy (`mod+c`, `CopyObjects`, `CopySelected`) and Cut (`mod+x`, `CutObjects`, `CutSelected`)**: serialize the selected object(s) — including nested children, components, properties, `overrides`, and every connection whose endpoints both belong to the copied subtrees — as canonical `sceneformat` YAML onto the system clipboard (`core.Scope.SetClipboard`, or the injectable `Editor.WriteClipboard` hook), so they paste into another scene or a text editor. Cut removes the originals and their connections in one undoable step. When a 2D tile region selection is active under a tile tool, `mod+c` and `mod+x` continue to copy or cut the tile region instead. - **Paste (`mod+v`, `Paste`, `PasteWith`, `PasteYAML`, `PasteYAMLWith`) and Paste as Child (`mod+shift+v`, `PasteInto`)**: parse scene-format YAML from the system clipboard (`core.Scope.ReadClipboard` / `Editor.ReadClipboard`) and place the objects on `ActiveLayer` (or under `ParentID`) at the hovered viewport pointer (`SetViewportPointer2D` / `SetViewportPointer3D`) or offset next to originals when IDs are already taken in the scene. Original IDs are kept when unused in the target scene and allocated fresh unique IDs when taken, rewriting internal connections and scene overrides (including instanced `"enemy_1/body"` paths) to the new IDs and clearing duplicate `current` flags on pasted 3D cameras. Every paste runs `PlaceObject`'s checks (`sceneformat.Validate`, `ValidateComponents`, `ValidateConnections`, `ValidatePhysicsLayers`, and `Resolve` for instanced scenes) and commits as **one undo step**; unparseable or invalid YAML is refused in the status bar without modifying the scene or history. - **Duplicate (`mod+d`, `DuplicateObject`, `DuplicateObjects`, `DuplicateSelected`, `DuplicateSelectedObjects`)**: clones the selected object(s) next to the originals on the same layer and parent in **one undo step**, allocating unique IDs and rewriting internal connections and overrides to the copies without overwriting the system clipboard. - **Group (`mod+g`, `GroupObjects`, `GroupSelected`) and Ungroup (`mod+shift+g`, `UngroupObject`, `UngroupSelected`)**: Group wraps the selection under a new empty parent placed at their common 2D/3D world centre without moving any object on screen (converting child local transforms via `keepWorldTransform`), in **one undo step**. Ungroup lifts direct children out into the parent's slot while preserving their world transforms in **one undo step**, removing an empty unconnected group container automatically while keeping non-empty parents intact. ## 3D navigation mesh baking (#901) In 3D view mode, the editor can bake a Recast-style 3D navigation mesh directly from the open scene's static geometry (`navbake3d`) and preview it over the 3D viewport: - **NavMesh bake panel** (`NavMeshPanelView`, toggled by the 3D toolbar's **NavMesh** button, **View > 3D NavMesh Bake...**, or `CmdNavMeshPanel` / `SetNavMeshPanelOpen`): configures the agent name, radius, height, step height (`MaxClimb`), maximum walkable slope (`MaxSlope`), voxel cell size (`CellSize`), cell height (`CellHeight`), and output `.navmesh.yaml` path (`NavMeshBakeConfig` / `SetNavMeshBakeConfig`). When a project with a `navigation` section is opened, the panel seeds its defaults from `game.yaml`. - **Baking and scene link** (**Bake** button, `CmdBakeNavMesh3D`, or `BakeNavMesh3D`): collects static 3D geometry from the open scene's glTF models (including `modelNode` and `modelMesh`), built-in `mesh` primitives, static non-trigger `collider3d` shapes (skipping dynamic/kinematic `body3d` objects, triggers, and screen-space layers), plus any extra terrain heightmaps, `GridMap`s, or physics colliders supplied by `Editor.OnBakeNavMesh3DGeometry`. Writes a deterministic, byte-identical `.navmesh.yaml` atomically, updates `SceneDoc.NavMesh` as one undoable step (`SetSceneNavMesh`, also editable in the Scene Settings inspector), and loads the baked mesh for immediate viewport preview. Reopening a scene whose `navMesh` file exists on disk automatically loads it (`LoadNavMesh3D`). - **3D viewport overlay** (**Nav Overlay** toolbar toggle, **Overlay** panel switch, **View > Show 3D NavMesh**, `CmdNavMeshOverlay`, or `ShowNavMesh3D` / `SetShowNavMesh3D`): draws translucent cyan walkable polygons, detail edges, and crisp polygon boundary outlines over the 3D scene viewport through `Camera3D`. ## Scene tabs, scene files and unsaved changes (#866, #873) The editor keeps each open scene in its own tab in the tab bar above the viewport (`SceneTabsView`), so an author can edit an instanced or base scene beside the level that uses it without losing undo history: - **Per-tab state**: each tab (`Tabs`, `ActiveTab`, `TabCount`, `SelectTab`, `SelectTabByID`) keeps its own `SceneDoc`, `BuiltScene`, `History`, selection (`SelectedID`), active layer and tile selection, 2D and 3D view transforms (`View2D`, `Camera3D`), scene-tree visibility/lock session flags, `OnSave` callback, and dirty marker (`TabDirty`). Switching tabs never clears any tab's undo history; undoing in one tab never changes another. - **Opening and deduplicating tabs**: opening a scene from the file browser (a `*.scene.yaml` or `*.scene.yml` file, or one listed under `autoload.scenes`), the Problems panel, the Search and References panel, the Command Palette, `NewScene`, `OpenScene`, or `OpenFile` opens a new tab (replacing an untouched initial untitled tab) or switches to the existing tab when that scene is already open. **Open Instanced Scene** (`OpenInstancedScene`, available in the inspector for an instancing object, the scene tree context menu, the File menu, and the Command Palette) and **Open Base Scene** (`OpenBaseScene`, available in the Scene Settings inspector for an inheriting scene, the File menu, and the Command Palette) open the referenced scene in a tab or switch to it when already open. - **Live instance and inheritance updates on save**: saving a scene (`Save`, `SaveFile`, `SaveSceneAs`, `SaveTab`, `SaveAll`) rebuilds every other open tab that instances or inherits scenes (`BuiltScene` and `Scene3D`), so instances and inherited objects show the change immediately without reopening those tabs. `MoveFile` rewrites paths and references across every open tab. - **Shared project, plugins, Play, and closing tabs**: the project file (`game.yaml`), plugins, and Play mode stay shared across tabs, with plugins and Play acting on the active tab (tab switching and closing are disabled while Play runs). Closing a clean tab (`CloseTab`, `RequestCloseTab`, `CmdCloseTab` / `mod+w`, or the tab's close button) closes it immediately; closing a dirty tab prompts to Save (saving only that tab and rebuilding dependent tabs), Discard (discarding only that tab while keeping shared project edits intact), or Cancel. Closing the last remaining tab replaces it with a clean untitled scene. The toolbar's File menu holds New Scene, which writes a minimal valid scene (named after its file, as large as the project's display or window, with one world layer) to a path from the project's root (`NewScene`), Save As, which saves the active scene under another path and makes that file the tab's (`SaveSceneAs`), Revert, which puts back the active scene as its file holds it (`RevertScene`), Open Instanced Scene, Open Base Scene, and Close Tab. A path without a `.yaml` or `.yml` extension gets `.scene.yaml` (one ending in `.scene` gets `.yaml`), the name `game check` and `game index` find scenes by. Neither New Scene nor Save As overwrites another file or writes a scene under the project's own file names, `game.yaml` and `nsgo.yaml`. Revert is one undoable step, so Undo brings the reverted edits back. `SceneDirty` reports whether the active scene differs from what it was opened from or last saved to, comparing encodings as `ProjectDirty` does for `game.yaml` and `ClipDirty` does for the open animation clip, so undoing back to the saved state makes the scene, project or clip clean again; `TabDirty` checks a specific tab and `AnySceneDirty` reports whether any open tab is dirty. A `MoveFile` that rewrites an open scene's file leaves it as clean or dirty as it was; one that rewrites references in an open scene but not in its file, as for a scene `game mv` does not read (no `.scene.yaml` name and nothing names it), leaves the scene dirty so that saving it keeps the new paths. Each dirty tab displays a `*` marker, the toolbar shows the active scene's path (`SceneLabel`) and a `*` while any open tab, the project, open clip or another auxiliary document has unsaved edits (`HasUnsavedChanges`), and the window title follows (`WindowTitle`). `EditorView` owns the window title, so an editor built on the package, such as a game's own, names itself with `Editor.AppName` rather than setting the title, and the title ends with that name ("NSGo Scene Editor" while it is empty). The Save button, File > Save in the menu bar, the Command Palette's Save and Mod+S (`Save`, the `CmdSave` command) save what was edited in the active scene and the shared project; an unedited file is left as written, comments included. Switching projects (`RequestOpenProject`), quitting the editor, and closing its window ask first while any open tab, the project or open clip has unsaved edits: Save saves all dirty tabs and the project (`SaveAll`) and goes on, Discard drops them and goes on, and Cancel keeps them and stays. Discarding the project's edits puts back what follows from the project, as undoing them does: an audition through an audio bus the edits added stops, for example. A forced quit, as at logout, cannot wait for an answer and does not ask. ### Reloading files changed on disk and save conflict guard (#906) While a UI scope is attached, the editor watches the open scene (`FilePath`), the open animation clip (`ClipPath`), `game.yaml` (`ProjectPath`) and the project directory tree (`DiskWatchInterval`, default 250ms; `PollDiskChanges` performs an immediate check in Go): - **Clean files reload automatically**: when an open scene, clip or `game.yaml` changes on disk without unsaved edits, the editor reloads it automatically as one undoable `History` step (batching multi-file git branch switches such as `Switched branch · main → boss-room · 2 files`), updates the saved snapshot so the file stays clean, and shows a dismissible reload notice (`DiskReloadNotice`) with object-level diff details (**Show diff**). - **Dirty files never reload under the author**: when an open file with unsaved edits changes on disk, the editor keeps the in-memory edits intact and shows an external-change conflict bar (`DiskConflicts`, `PrimaryDiskConflict`) offering **Reload from disk** (`ReloadFromDisk`, keeping the author's edits in `History` as `"Unsaved edits before reload"`), **Keep mine** (`KeepLocalVersion`, keeping the disk version in `History` as `"Changed outside the editor"` and acknowledging the disk snapshot so a subsequent Save succeeds), and for scenes **Compare** (`SetDiskCompareOpen`, `SetSceneConflictChoice`, `ApplySceneConflictMerge`) to pick **Mine** or **Disk** per overlapping object while taking single-side changes automatically. - **Save conflict guard**: `Save`, `SaveFile`, `SaveProject` and `SaveClipFile` compare the on-disk SHA-256 snapshot recorded at open or last save before writing and refuse to overwrite externally modified files with `ErrDiskConflict` (`*DiskConflictError`). In `EditorView`, hitting a conflict opens a confirmation dialog (**Cancel**, **Reload from disk**, or **Overwrite** via `ConfirmOverwriteSave` / `ForceSave`). - **Automatic file browser refresh**: adding, removing or renaming files in the open project directory automatically updates the file browser (`FilesView`) and invalidates the project index and Problems check without pressing Refresh. ## Layers panel (#862) The layers panel (`LayersView`), under the scene tree, lists the open scene's layers in draw order, the first drawn at the top, each with its space (`world` or `screen`) and its tilemap: the tileset and size of an inline grid (`tiles 16x12`), the name of the top-level tilemap it refers to, or the path of an external Tiled map. Pressing a layer's row makes it the active layer, which the Place tool and the tile tools work on, the tile palette shows and the status bar names, with `hidden` and `locked` after it when they apply; pressing a layer's row in the scene tree does the same. In Go, `Layers()` returns what the panel shows. - **Add and remove**: the + button adds a world layer named `layer_N` that draws over every other layer and makes it active (`AddLayer(name, space)`, which takes the highest order of the layers the scene draws, those of a scene it inherits included, and puts the layer last in the file). The bin button removes the active layer (`RemoveLayer(name)`), with its objects and tilemap and with the scene's connections from or to its objects; Undo puts all of them back where they were, and the scene is saved byte for byte as before. When the active layer is removed, the layer that takes its place in the file, or the one before it, becomes active. - **Rename**: a double press or the context menu's Rename edits the name in the row; Return or leaving the field keeps it, and Escape drops it (`RenameLayer(oldName, newName)`). An empty name and one another layer has are refused. The active layer and the layer's lock follow the new name. - **Order**: drag a row onto the top or bottom half of another to put the layer before or after it, or use the context menu's Move Layer Up and Move Layer Down (`MoveLayer(name, index)`, where index is the position in the draw order). The layer moves in the file next to the layer it is to draw after or before, and its `order` changes only when the value it has would not draw it there, to that neighbour's value; the other layers keep their place and their orders. - **Space**: the context menu's World Space and Screen Space set the layer's `space` (`SetLayerSpace(name, space)`); its objects keep their coordinates. - **Visibility**: the eye button hides or shows the layer by writing its `visible` field (`SetLayerVisible(name, visible)`). Hiding writes `visible: false`; showing leaves the field unset, its default, so hiding and showing a layer gives back the same file. This is the scene's own setting, which the game reads too, and an undoable edit. A hidden layer is not picked in either viewport, and its objects are not moved there even when they are selected (no 3D gizmo, no Move-tool drag), as for an object hidden in the scene tree. - **Lock**: the lock button locks the layer against the viewports for the session (`SetLayerLocked(name, locked)`): a press passes over its objects to what lies under them, its objects are not moved there (no 3D gizmo, no Move-tool drag), and the Place, Paint, Erase and Fill tools change nothing while it is the active layer and say so in the status bar. Like the scene tree's object lock, it is not an edit, is not undone, is never written to the scene file, and opening another scene clears it; the panels and the inspector still edit the layer and its objects. In a scene that inherits another (`inherits`), a layer named like one of the base's extends it: its name and draw order belong to the base scene, so renaming or moving it, renaming a layer to a base layer's name, and adding one with a base layer's name are refused, while hiding it, changing its space, or editing its parallax and repeat records undoable entries under `layerOverrides` (with per-field Revert and Revert All in the inspector and layer context menu), and removing it removes only the objects the scene adds to it. Other scene files that inherit the open one and name its layers are not rewritten by a rename. Every layer edit that would leave a scene that does not validate, or does not resolve with the scenes it instances or inherits, is refused before it reaches the history. ## Animation editor The editor's animation panel keys any registered property on a timeline and saves the clip as an [`animation` resource file](https://game.nsgo.dev/docs/resources/#animation), played in the game by [animclip](https://game.nsgo.dev/docs/animclip/) (an AnimationPlayer equivalent). The panel shows below the viewport while a clip is open. - **Opening a clip**: the toolbar's Animate button starts a new one-second clip on the selected object. In Go, `NewClip(target, name, length)` does the same, `NewClipFromAsepriteTag(target, tag)` builds a clip matching an Aseprite tag's frames, exact durations and loop setting from the target object's atlas, `NewClipFromFrames(target, name, frames, fps, loop)` builds a flipbook clip from a run of atlas frames at a fixed frame rate, `OpenClipFile(path, target)` and `OpenClipYAML(data, target)` open a clip file, checked against the component registry (a misspelled property fails to open with the file name), and `CloseClip` closes it. The panel's Flipbook row also lets you pick an Aseprite tag (From Tag) or a frame rate (From Frames) directly when the target object has a sprite atlas. `nsgo game editor scene.yaml clip.animation.yaml [object-id]` opens a scene and selects the object `object-id` (the scene's first object when it is left out), opens the clip on it when the file exists, and the panel's Save Clip button writes that file. - **Keying**: pick a property (an object field such as `x`, `alpha` or `sprite.frame`, or a registered component field such as `body.speed`) and press Key to key the value it has in the scene at the playhead; `KeyProperty(target, property, at)` does the same. Choosing `sprite.frame` reveals a frame picker listing the target object's atlas frames (`ClipTargetFrames`) so you can key any frame directly (`KeySpriteFrame(target, frame, at)`). With another object selected, the key goes to a track that targets it. A track that names the clip's own object is the same track as one with an empty target, and a clip with two tracks driving the same property of one object is refused. A bool key holds its value until the next key, and `sprite.frame` always steps discretely without interpolation. - **Editing keys**: each track is a lane of its keys; a `sprite.frame` track displays each keyed frame as a thumbnail cell spanning its duration (`ClipFrameEntry`). Press a key to select it and move the playhead to it, then edit its time and value/interpolation (`linear`, `smooth` or `step`) for numeric tracks, or its atlas frame (`SetKeyFrame`) and duration (`-10ms` / `+10ms`, `FrameDuration`, `SetFrameDuration`) for `sprite.frame` tracks, or delete it; `SetKeyValue`, `MoveKey`, `SetKeyInterp`, `DeleteKey` and `RemoveClipTrack` do the same in Go. Values are checked against the property: 0 or 1 for a bool, a whole number for an int, inside the field's range, and a frame name present in the target's atlas for `sprite.frame`. - **Clip settings and events**: the panel edits the clip's name, length and loop (`SetClipName`, `SetClipLength`, `SetClipLoop`), and adds named events at the playhead (`AddClipEvent`, `DeleteClipEvent`). - **Scrubbing and preview**: the scrubber moves the playhead (`SeekClip`; at the end of a looping clip it shows the last keys) and Play plays the clip on a `game.Loop` (`PlayClip`, `PauseClip`, or `StepClip` to step it by hand). The viewport, in 2D and 3D, then shows a copy of the scene posed by the clip with the same `animclip.Player` and `BindScene` the game uses, so the scene being edited never takes animated values and a clip plays the same in the game. A clip the scene cannot play, such as one whose track targets a deleted object, stays open and `ClipError` says why. Asynchronous clip loaders can toggle the panel's loading card with `ClipLoading` / `SetClipLoading`. - **Undo**: every clip edit, opening and closing included, goes through the same undo/redo history as scene edits. `SaveClipYAML` and `SaveClipFile` write deterministic YAML, so a clip that is opened and saved again does not change. ### Sprite state machine graph (#1054) Opening a `*.states.yaml` file (from the file browser, command palette, or `OpenStatesFile` / `OpenStatesYAML` / `OpenStatesProjectFile`) opens the **State Machine** graph panel below the viewport: - **Graph and active state**: every state appears as a node card showing its name, clip metadata (frame count, frame duration, loop/once) and sprite thumbnail, with directed labelled transition edges and an `Any state` wildcard badge. During preview, the active state node highlights live and the preview card renders the active clip frame. - **Drive with keys**: toggling **Drive with keys** binds the preview to the project's input actions (such as `move_left`, `move_right`, `jump`, `attack`, `hurt`) through the same `animclip.InputDriver` and `animclip.StateMachine` the game uses, advancing on fixed steps on `game.Loop` so interactive preview and runtime playback match frame for frame. - **Outgoing transitions (`LEAVING `)**: selecting any state displays its outgoing transitions (including `Any state` interrupts) and their conditions, and graph edits (`AddStatesState`, `RemoveStatesState`, `AddStatesTransition`, `RemoveStatesTransition`, `SetStatesEntry`, `SetStatesNodePos`, `SetStatesDoc`) go through the editor's undo/redo history and save back to deterministic canonical YAML (`SaveStatesYAML` / `SaveStatesFile`). ## Editor plugins (#492, #898) A plugin extends the scene editor with its own panels, an inspector for its own component types, 2D and 3D viewport tools, and per-component 3D gizmos, as Godot's `EditorPlugin` does. Go cannot load code at run time on every platform, so a plugin is Go code built into the editor binary: the binary registers it with `Editor.RegisterPlugin`, and a project turns it on by naming it in its [project file](https://game.nsgo.dev/docs/project/): ```yaml editor: plugins: [health] ``` A registered plugin the open project does not name stays off, and the order of `editor.plugins` is the order its panels and tools appear in. `OpenProject` names in the status bar the plugins the project lists that this binary was built without (`MissingPlugins`). `nsgo game editor` registers no plugins and no component types, so a game that has its own builds its own editor command. `nsgo game generate editor` writes one into a game's `main` package, built with the `gameeditor` tag in place of the game, that calls `editorcmd.Main` with the game's `Components` and its plugins, and `nsgo game editor` runs it on the project ([Command Line](https://game.nsgo.dev/docs/cli/#generate)). Package `editorcmd` is the command line both share: `New(Options)` builds an editor with the component types, plugins, name and library given and `ProjectAssets` set, checking scenes against the component types together with the built-in physics components (`body2d`, `collider2d`, `trigger2d` and their 3D forms) the registry does not register itself, `Open(ed, args)` opens a project, a scene or a clip as `nsgo game editor` does, and `Main` and `Run` parse the command line, open the project in the working directory without arguments and show the window, 1120 by 680 points unless `Options.WindowWidth` and `Options.WindowHeight` set another size. An editor command written by hand calls `editorcmd.Main` the same way: ```go // cmd/editor/main.go: the game's own editor command. package main func main() { editorcmd.Main(editorcmd.Options{ Components: health.Components(), Plugins: []editor.Plugin{healthplugin.Plugin()}, AppName: "Field Medic Editor", RequirePlugins: true, // refuse a project that lists a plugin this command lacks }) } ``` An `editor.Plugin` has a `Name`, which follows the rule of other names in `game.yaml` (no spaces or control characters), and lists of extensions: - **Panels** (`Panel`): a view docked left of the viewport (`DockLeft`, after the asset browser), right of the inspector (`DockRight`) or below the viewport (`DockBottom`), under its `Title`. `View(cx, ed, rev)` builds it once when it appears, and the panel stays mounted, with its state, while its plugin is on, however other panels come and go; it reads `rev` inside reactive functions, as the editor's own panels do, to follow every change to the editor's state. A dock without panels takes no space. - **Inspectors** (`Inspector`): the inspector draws the component `Component` names with `View(cx, ed, rev, objectID)` below the component's title, in place of its generic fields. `Editor.ComponentField` reads a field, with its registered default when the scene leaves it unset, and reports false for an object without the component. Like the generic fields, the inspector's controls should be disabled while `Playing` reports true, and an edit the editor refuses should go to the status bar with `Editor.Report`. When two plugins that are on draw the same component, the one listed first in `editor.plugins` wins. - **Tools** (`PluginTool`): a button in the 2D and/or 3D viewport tool bar depending on which hooks the tool implements. While it is the active tool (`SetPluginTool`; `Tool` is then `ToolPlugin`): - **2D hooks**: a press on the 2D viewport calls `Press(ed, x, y)` with canvas coordinates (`CanvasToWorld` converts them to the world, `CanvasToScreen` to a screen-space layer), drags call `OnDragBegin(ed, x, y)` (returning `true` to claim the drag), `OnDragMove(ed, x, y)`, `OnDragEnd(ed, x, y)` and `OnDragCancel(ed)` (`BeginPluginDrag2D`, `UpdatePluginDrag2D`, `EndPluginDrag2D`, `CancelPluginDrag2D`, `PluginDragging2D`), pointer motion calls `OnHover(ed, x, y, active)` (`SetPluginHover2D`, `ClearPluginHover2D`), and `Draw`, when set, draws over the 2D scene in edit mode. - **3D hooks (#898)**: a press on the 3D viewport calls `Press3D(ed, ray)` with the camera's world-space `math3d.Ray` (`PickRay3D`), drags call `OnDragBegin3D(ed, ray)` (returning `true` to claim the drag instead of orbiting the camera), `OnDragMove3D(ed, ray)`, `OnDragEnd3D(ed, ray)` and `OnDragCancel3D(ed)` (`BeginPluginDrag3D`, `UpdatePluginDrag3D`, `EndPluginDrag3D`, `CancelPluginDrag3D`, `PluginDragging3D`), pointer motion calls `OnHover3D(ed, ray, active)` (`SetPluginHover3D`, `ClearPluginHover3D`), and `Draw3D(ed, d, proj)` draws over the 3D viewport using `Projection3D` (`Camera`, `Width`, `Height`, `ViewProj`, `Project`, `ProjectSegment`, `ScreenRay`, `GizmoLength`, `DrawPoint`, `DrawLine`, `DrawBox`). - A tool must provide at least one of `Press`, `OnDragBegin`, `Press3D`, or `OnDragBegin3D`. Tools with only 2D hooks appear only in the 2D tool bar and stay idle in 3D; tools with 3D hooks appear in the 3D tool bar and activate 3D view automatically when run from the Command Palette or menu bar. Choosing another tool, or turning the plugin off, ends it. - **3D Component Gizmos** (`Gizmos3D []ComponentGizmo3D`, #898): registers per-component-type 3D handles in object space (`GizmoHandlePoint3D`, `GizmoHandleLine3D`, `GizmoHandleBox3D`, optionally `DisplayOnly`) returned by `Handles(ed, objectID)` and an interactive `Drag(ed, drag GizmoDrag3D) error` function. The editor transforms handles from object space through the object's full ancestor hierarchy, hit-tests them in screen space (`PickComponentGizmo3D`, `BeginComponentGizmoDrag3D`, `UpdateComponentGizmoDrag3D`, `EndComponentGizmoDrag3D`, `CancelComponentGizmoDrag3D`), and passes `GizmoDrag3D` (with world and object-space rays plus `AxisDelta`, `PlanePoint`, `PlaneDelta`, and `ViewPlaneDelta` helpers). Edits written inside `Drag` through `Editor` (such as `SetComponentField` or `Editor.History`) preview live on every pointer move, roll back cleanly on `Escape` or cancel without polluting history, and commit as **one undo step** when the drag ends. When two active plugins register a 3D gizmo for the same component, the first in `editor.plugins` wins. The editor's built-in 3D transform gizmo (`Translate`, `Rotate`, `Scale`) and built-in `collider3d` / `trigger3d` handles share this same 3D handle API. A plugin changes the scene only through the editor's methods, such as `SetComponentField`, `PlaceObject` and `MoveObject`, or by executing its own `Command` on `Editor.History`, so every edit it makes is undone and redone with the rest. `History.Group(label, fn)` records the edits `fn` makes as one step that one Undo takes back, and when `fn` fails it undoes them and records nothing; the editor's MCP server ([mcp](https://game.nsgo.dev/docs/mcp/#editor-tools)) applies each agent request that way. `RegisterPlugin` refuses a plugin without a name or with a name already registered, a panel, inspector or tool missing its ID, title, label, component or function, an ID or component name with control characters, an unknown dock and two panels, inspectors or tools with the same ID or component. Test IDs join the plugin name and the ID with `-` (`plugin-panel--`, `tool--`, `inspector-plugin--`), so plugins used together should have names and IDs that do not join to the same string. `SetPluginEnabled(name, on)` adds a registered plugin to `editor.plugins` or removes it, as one undoable edit of the project that the toolbar's Save button writes; removing the last plugin removes the `editor` section when nothing else is left in it, including an `editor: {}` the author wrote, and Undo puts it back. `RegisteredPlugins`, `ActivePlugins` and `PluginEnabled` report which plugins the binary has and which are on. ### Shipping an editor with plugins A game ships its editor as one more command in its own module, beside the game, and runs it with `go run ./cmd/editor` from the project directory. Keep the plugin in a package of its own that only the editor command imports, so the shipped game does not link the editor, and the component types in a package that both import, so the game and the editor check scenes against the same fields: | Package | Imports | Holds | | --- | --- | --- | | the component package | `sceneformat` | the component types (`ComponentType`), a registry for `ParseWith` and `SetComponentRegistry`, and helpers that read a component with its defaults (`ComponentRegistry.Resolve`) | | the plugin package | `editor` and the component package | `Plugin()`, returning the `editor.Plugin` | | the game (`main`) | the component package | loads its scenes with `sceneformat.ParseWith` and the registry | | `cmd/editor` | `editor`, the component and plugin packages | registers the component types and the plugin, then opens the project | `game.yaml` names the plugin under `editor.plugins`, so the plugin is on whenever the game's editor opens the project. An editor command that should not start without its plugins sets `editorcmd.Options.RequirePlugins`, or checks `MissingPlugins` after `OpenProject` and fails when it is not empty. `nsgo game editor` on a project with a `cmd/editor` main package runs that command with `go run ./cmd/editor`, as it runs the one `game generate editor` writes, and passes it the same command line, `-library` and a project, scene file, clip and object ID, so a `cmd/editor` should parse it with `editorcmd.Main` or `editorcmd.Run`. A `cmd/editor` that does not import `editorcmd` is not run: `nsgo game editor` says so and opens the project itself. [Field Medic](https://github.com/nsgo-dev/game/tree/main/examples/fieldmedic) (`examples/fieldmedic`) is a runnable game laid out this way. Its patients carry a `health` component (package `health`), and its `cmd/editor` registers the `health` plugin (package `healthplugin`): a Ward panel docked right of the inspector that lists every patient's hit points, with a Heal All button that heals them all in one undoable step it executes on `Editor.History`; an inspector for the `health` component with hit point and max fields and a bar of what is left; and an Admit tool that places a patient where the viewport is pressed and outlines every patient while it is active. Its tests open the game's own project in the editor and drive the panel, the inspector and the tool. The editor's own tests hold a smaller `health` plugin as well (`pkg/editor/plugin_test.go`). ## Library panel (#493) With `Editor.Library` set to a pack library (`library.Open`), as `nsgo game editor -library ` sets it, a panel beside the asset browser lists every pack in the library, with its kind, version, description and the version the open project has installed. Its Install, Update and Remove buttons call `InstallPack` and `RemovePack`, which write the pack's files beside `game.yaml`, record the pack and the autoload entries and plugins it adds in the project, and save the project; a registered plugin a plugin pack names turns on at once. They refuse while playing, without a project and while the project has unsaved edits (`ErrProjectDirty`), and they empty the undo history, since the files they write cannot be undone. A pack from a library over https is fetched off the event loop, with its button busy until it arrives (`FetchingPack`). The library format and what an install writes are in [Asset and Plugin Library](https://game.nsgo.dev/docs/library/). ## Unified Settings pages: Agent, Project, Input map, Audio buses, Export, General, and Shortcuts (#907, #908, #909, #916, #1028, #1060, #1061) All per-computer agent controls, project-level `game.yaml` settings, and editor preferences share one unified **Settings** workspace (`SettingsView`, opened with `OpenSettingsPage(page)`, inspected with `SettingsOpen()` / `SettingsPage()`, and closed with `CloseSettings()` / `Escape`) laid out from `docs/design/editor/Settings.dc.html` and `Spec.dc.html` using `SpecPalette` tokens in both Dark and Light appearances. The left sidebar groups **`AGENT`** (**Models and connections**, **Tools**, **Usage and privacy** — all per-computer and **You only**), **`PROJECT · game.yaml`** (**Project**, **Input map**, **Audio buses**, **Export**), and **`EDITOR · THIS COMPUTER`** (**General**, **Shortcuts**); each row displays its label, help text, value control, and agent-policy badge (**Agent may change** or **You only**), and every interactive control across all pages uses real focusable `ui.Button` / `ui.*` widgets reachable via `Tab` with visible focus rings. ### Agent pages: Models and connections, Tools, and Usage and privacy (#1028, #1030) Stored per computer in `EditorSettings` (`editor.yaml` under `agent`, never inside the project) with every mutator refused when invoked by an agent (`ErrAgentSettingsYouOnly`): - **Models and connections (`SettingsPageModels`)**: shows connected local MCP agents (such as Claude Code), the built-in API connection (`Anthropic API`, whose key is stored exclusively in NSGo's `core.Secrets` under `AgentAPIKeySecretAccount` / the host OS keychain under `AgentKeychainServiceName` via `StoreAgentAPIKey`, `HasAgentAPIKey`, `DeleteAgentAPIKey`, and `AgentAPIKey` — never written to `editor.yaml`, project files, or logs), **+ Connect another agent or model** (opening `ConnectAgentDialogView`), and **WHO DOES WHAT** task routing (`AgentTaskRoute` / `SetAgentTaskRoute` / `ResolveAgentModelRoute`). The sidebar meta reports the active connection count (`AgentActiveConnectionCount`, e.g. `2 on`). - **Built-in agent runner (`SubmitAgentTaskPrompt`, `Editor.AgentTools`, `Editor.BuiltInAgentEndpoint`)**: routes each task kind (`AgentTaskSceneEdit`, `AgentTaskPlaytest`, `AgentTaskProblems`, `AgentTaskAskInPlace`, `AgentTaskArtSound`) to either a connected local MCP agent or the built-in Anthropic Messages API runner (`DefaultBuiltInModel` / `DefaultBuiltInFastModel`), validating that custom endpoints use `https://` (or loopback `http://` for local tests) and never forward `x-api-key` across redirect hosts. `editormcp.New` wires `Editor.AgentTools` automatically so built-in tool calls execute through the same `editormcp.Server` tool toggles, permission rules, `WithAgentActor` You-only guard, and symlink-aware outbound privacy enforcement as external MCP clients. - **Weekly limit queueing & model error failover (`AgentStatusLimitReached`, `AgentQueuedRequests`, `AgentModelErrorState`)**: reaching the person-only weekly request limit (`WeeklyRequestLimit` / `SetWeeklyRequestLimit`) transitions the Agent header chip to `Limit reached · resets 00:00` with a **Usage** link and queues subsequent requests (`SendQueuedAgentRequest`, `RemoveQueuedAgentRequest`) until `CheckAgentUsageReset` crosses the weekly reset or the person raises the limit. Transient model errors (`429`, `5xx`, `529` overloaded) retry on `AgentModelRetryDelays` (`4 s, 8 s, 16 s, 32 s`), rendering the model error card with **Retry now** (`RetryAgentTurn`) and **Use ``** (`SwitchAgentTurnToAlternative`) to update WHO DOES WHAT and run the request on another connected agent without double-counting usage. - **Tools (`SettingsPageTools`)**: lists every tool registered on the editor's MCP server (`RegisteredMCPTools`) with its monospace name, description, and an accessible `role="switch"` toggle (`IsMCPToolEnabled` / `SetMCPToolEnabled`), showing `"enabled / total"` in the sidebar (`EnabledMCPToolCount`). `game_delete_file` is off by default; turning any tool off removes it from the MCP server's client tool list (`tools/list_changed`) and returns a readable refusal if called. Below the editor's tools, **OTHER MCP SERVERS THE AGENT MAY USE** starts with **Running game · nsgo dev** (`nsgo-game` / `go tool nsgo mcp`) and provides **+ Add a server** (`AddAgentMCPServer`, `SetAgentMCPServerEnabled`, `RemoveAgentMCPServer`), syncing enabled servers into the open project's `.mcp.json` and `.codex/config.toml` (`editormcp.InstallWithServers`). - **Usage and privacy (`SettingsPageUsage`)**: displays **This week** requests against a user-configured weekly limit (`WeeklyRequestLimit` / `SetWeeklyRequestLimit` / `RecordAgentRequest`), **Kept** share of reviewed agent changes (`RecordAgentReviewOutcome`), and local **Playtests** run count (`RecordPlaytestRun`), followed by the four **WHAT MAY LEAVE THIS COMPUTER** switches (`AgentPrivacy` / `SetAgentPrivacy`): **Scene and data files** (on), **Viewport images** (on), **Go source code** (off), and **Art and audio files** (off). The editor's MCP server refuses, with the reason, any tool call or resource read whose result would carry switched-off content for every connected agent. ### Project page (#907, #1060) While a project is open, the toolbar's **Settings** button (`ProjectSettingsOpen` / `SetProjectSettingsOpen`, or `OpenSettingsPage(SettingsPageProject)`) opens the **Project** page in `SettingsView` (`ProjectSettingsPanelView`) to edit `game.yaml` exclusively through `EditProject`, so every change is validated by `project.Validate`, participates in Undo/Redo, and writes both `game.yaml` and the synced `nsgo.yaml` beside it on **Save** (`SaveProject`): - **General**: edits `name`, `id`, `window` width/height, `autoload.mainScene`, and `appVersion` directly on the overview page (`SetProjectName`, `SetProjectID`, `SetProjectWindowSize`, `SetProjectMainScene`, `SetProjectAppVersion`). - **Window**: edits `window.title`, `width`/`height`, `minWidth`/`minHeight`/`maxWidth`/`maxHeight` limits, `resizable`, and `appearance` (`SetProjectWindowTitle`, `SetProjectWindowSize`, `SetProjectWindowLimits`, `SetProjectWindowResizable`, `SetProjectWindowAppearance`). - **Display**: toggles the optional `display` section (`SetProjectDisplayEnabled`) and edits its virtual `width`/`height`, `mode` (`fit`, `fill`, `stretch`, `expand`), `integerScale`, `pixelSnap`, and `barColor` (`SetProjectDisplaySize`, `SetProjectDisplayMode`, `SetProjectDisplayIntegerScale`, `SetProjectDisplayPixelSnap`, `SetProjectDisplayBarColor`). - **Autoload**: selects `autoload.mainScene` (`SetProjectMainScene`) and adds, updates, or removes `autoload.scenes` and `autoload.resources` entries (`AddProjectAutoloadScene`, `UpdateProjectAutoloadScene`, `RemoveProjectAutoloadScene`, `AddProjectAutoloadResource`, `UpdateProjectAutoloadResource`, `RemoveProjectAutoloadResource`) with searchable file pickers populated from the open project's files (`ProjectSceneFiles`, `ProjectResourceFiles`). - **Physics**: edits `physics.gravity2D`, `physics.gravity3D`, `physics.solverIterations2D` / `solverIterations3D`, and named collision `physics.layers` (`SetProjectPhysicsGravity2D`, `SetProjectPhysicsGravity3D`, `SetProjectPhysicsSolverIterations`, `AddProjectPhysicsLayer`, `RemoveProjectPhysicsLayer`). - **Editor plugins**: shows every registered plugin (`RegisteredPlugins`) with a toggle switch backed by `SetPluginEnabled`, plus any plugins listed in `game.yaml` that this editor binary lacks (`MissingPlugins`) with an option to remove them. Any value `project.Validate` refuses displays its validation error inline on the offending row without mutating the project or history. Before the first save of the open project (`ProjectCanonicalSavePending`), the page displays a notice explaining that saving writes `game.yaml` in canonical YAML form, which does not preserve comments. ### Audio buses page (#909, #1060) While a project is open, the toolbar's **Audio** button (`AudioMixerOpen` / `SetAudioMixerOpen`, or `OpenSettingsPage(SettingsPageAudio)`) opens the **Audio buses** Settings page (`AudioMixerPanelView`) to edit `game.yaml`'s `audio` section directly through `EditProject`, so every edit validates against `project.Validate`, participates in the editor's Undo/Redo history, and writes cleanly on **Save** (`SaveProject`): - **Master and buses**: adjust the master volume slider with dB readout (`SetAudioMasterVolume`), add new buses (`AddAudioBus`), rename (`RenameAudioBus`), delete (`DeleteAudioBus`), reorder (`MoveAudioBus`), and adjust each bus's routing (`Into Master`) and volume slider (`SetAudioBusVolume`). Deleting the last bus when no master volume is set removes the empty `audio` section, and Undo restores it. - **Per-bus DSP effect chains**: add (`AddAudioBusEffect` / `AddAudioBusEffectKind`), remove (`RemoveAudioBusEffect`), reorder (`MoveAudioBusEffect`), and edit (`SetAudioBusEffect`) all six `project.Effect` types (`lowPass`, `highPass`, `delay`, `reverb`, `gain`, `bitcrush`). Numeric inputs bound parameters to `project.Validate`'s ranges (with `ClampAudioEffect`), and Go API calls refuse out-of-range values without altering the project or history. - **Live audition**: choose any audio file from the open project (`ProjectAudioFiles`, `SelectAudioFile`) and press **Audition** (`AuditionAudioBus`, `StopAudition`, `SetAuditionLoop`) to play it through the selected bus on an editor-owned `sound.Mixer` configured with `project.File.ConfigureMixer`. Volume changes apply live to the playing stream without restarting it, and effect chain edits or Undo/Redo immediately re-process through `sound.Mixer.ProcessSource` so changes are heard identically to runtime game playback. ### Input map page (#908, #1060) While a project is open, the toolbar's **Input** button (`InputMapOpen` / `SetInputMapOpen`, or `OpenSettingsPage(SettingsPageInput)`) opens the **Input map** Settings page (`InputMapPanelView`) to edit `game.yaml`'s `input` section directly through `EditProject` with full Undo/Redo and validation against `project.Validate`: - **Action overview & editor**: lists each configured action with its keyboard, gamepad, and touch triggers alongside a button that jumps directly into editing that action. Add (`AddInputAction`), rename (`RenameInputAction`), and delete (`DeleteInputAction`) actions, and add (`AddInputBinding`), edit (`SetInputBinding`), or remove (`RemoveInputBinding`) bindings of every `game/input` kind: `key`, `keyCode`, `gamepadButton`, `mouseButton`, `touchRegion`, and `mouseRegion`. Renaming an action atomically updates every axis in `input.axes` that reads it so references stay consistent across Rename, Undo, and Redo. - **Key capture**: pressing **Press a key** (`BeginKeyCapture` with `project.KindKey`) or **Press code** (`project.KindKeyCode`) enters capture mode and binds the next hardware key press (`CaptureKeyEvent`) directly to the selected action, with **Cancel** (`CancelKeyCapture`) to back out without changing the project. - **Regions over virtual display size**: the region canvas scales to the project's `display` resolution (falling back to `window` when `display` is unset; `InputMapDisplaySize`), draws all `touchRegion` and `mouseRegion` bounds, and lets you drag existing regions to move them, drag a selected region's bottom-right handle to resize it, or drag on empty space to draw a new region (`BeginRegionDrag` / `UpdateRegionDrag` / `EndRegionDrag` / `SetInputRegion`). Each drag commits as one undoable `EditProject` step. - **Axes, motion axes and gamepad sticks**: the **Axes** tab edits action axes (`AddInputAxis`, `SetInputAxis`, `DeleteInputAxis`), device motion sensor axes (`AddInputMotionAxis`, `SetInputMotionAxis`, `DeleteInputMotionAxis`), and controller analog stick axes (`AddInputGamepadAxis`, `SetInputGamepadAxis`, `DeleteInputGamepadAxis`). `BuildInputActions` binds the open project's map into a live `*input.Actions` via `project.File.BindInput`. ## Localization panel (#917) The Localization panel (`LocalizationPanelView`) edits per-locale YAML string tables side by side below the viewport, with message keys as rows and project locales as columns. - **Opening**: press the toolbar's **Strings** button (which opens `/locales` when a project is open, or starts an in-memory `"en"` table otherwise), or call `OpenLocalizations(dir)` / `NewLocalizations(dir, locales...)` in Go. `CloseLocalizations` closes the panel. - **Keys and locales**: add or remove locale columns (`AddLocalizationLocale`, `RemoveLocalizationLocale`) and message key rows (`AddLocalizationKey`, `RemoveLocalizationKey`), normalizing locale tags to canonical BCP-47 form (for example `zh_hans` -> `zh-Hans`). - **Simple strings and CLDR plurals**: toggle a key as plural (`SetLocalizationKeyPlural`) to edit all six CLDR categories (`zero`, `one`, `two`, `few`, `many`, `other`) via `SetLocalizationPlural` or `SetLocalizationPluralForm`, or edit simple strings via `SetLocalizationString`. - **Missing translations**: cells whose translation is empty (or whose plural `other` fallback is empty) are highlighted with a warning border and `Missing` indicator; `LocalizationMissing`, `LocalizationMissingCount`, and `LocalizationIsMissing` report them programmatically. Untranslated keys are omitted when saved so runtime `l10n.Catalog` lookups fall back along the BCP-47 chain. - **Undo, saving, and panel states**: every localization edit goes through `Editor.History` (Undo/Redo). **Save Strings** (`SaveLocalizations` / `SaveLocalizationsTo`) writes each locale's canonical YAML file to `/.yaml` using `l10n.EncodeYAML` and removes files for locales that were deleted from the workspace. Panel errors are surfaced in a dismissible banner (`LocalizationError` / `ClearLocalizationError`), and asynchronous loaders can toggle the loading state via `LocalizationLoading` / `SetLocalizationLoading`. ## Problems panel and live agent-proposed fixes (#913, #1036) While a project is open, the Problems panel (`ProblemsView`) below the viewport runs `assetcheck.CheckWith` (using the editor's component registry) and `project.Check` over the project directory overlaid with every open, unsaved editor document off the UI goroutine, and reports the live problem count in the status bar (`Problems: N`). It re-checks automatically (debounced via `ProblemCheckDebounce`, defaulting to 80 ms) after every edit in the editor—made by the person or the agent—without waiting for a save, as well as when a project opens (`OpenProject`), after saving (`SaveFile`, `SaveProject`, `SaveClipFile`), after moving files (`MoveFile`, including undo and redo), and when the component registry changes (`SetComponentRegistry`). The panel's Check button (`CheckProblems`) re-runs the check on demand after edits made outside the editor. Each row displays a problem's `file:line:column` location (`assetcheck.Problem.Location`, carrying the 1-based column wherever the scene or YAML format knows it), a Spec alert icon, and the message, matching `nsgo game check` on the same project plus any project-level issues reported by `project.Check` (such as an `nsgo.yaml` out of sync with `game.yaml`, a missing installed pack file, or an invalid non-`.scene.yaml` autoloaded scene). Pressing a row (`OpenProblem`) opens the scene in a tab without discarding unsaved edits in other tabs, or selects a non-scene file in the file browser (`SelectedFile`, `SelectFile`). Problems attributed to objects in the open scene also draw directly on live objects in the 2D viewport using the Spec Problem overlay (2 px solid problem outline plus a filled alert pill with icon and message, toggled via `SetProblemOverlayVisible`) and show a problem count badge on the object's row in the scene tree (`ObjectProblems`, `ObjectProblemCount`). - **Agent-proposed fixes (`ProposeProblemFix`, `ApplyProposedFix`, `ProblemAgentPanelView`)**: an agent inspecting live problems through MCP (`game_check`) can propose a fix via `problem_propose_fix` (providing the problem, an explanation, and a validated structured edit). Proposing a fix simulates the edit on a cloned scene document to verify validity and compute the exact `-`/`+` YAML diff, opens the right-hand **Agent** panel showing the problem card (`file:line:col`), explanation, diff, **Apply fix**, **Show me**, **Ignore**, and **"Ask about this problem…"**, and **never applies the edit or mutates any file**. Only the person pressing **Apply fix** (`ApplyProposedFix`) applies the change as a single undoable `History` step with a Spec toast and **Undo** action, so one Undo restores the previous YAML and brings the problem back. - **Show me, Ignore, and Ask about this problem (`ShowProblem`, `IgnoreProblem`, `AskAboutProblem`)**: **Show me** opens the problem's scene, selects and frames the offending object, and highlights the exact YAML line. **Ignore** hides that problem from the Problems panel, status bar, scene tree badge, and viewport overlay until its file changes again (tracked by live content hash); any subsequent edit to that file evicts the ignore entry so the problem reappears automatically if it still holds. Submitting **"Ask about this problem…"** delivers the question with the problem, attributed object, and proposed fix attached (`OnAskAboutProblem`). In Go, `Problems`, `ProblemCount`, `ProblemErr`, `CheckingProblems`, `WaitForProblems`, `IgnoreProblem`, `IsProblemIgnored`, `ProposeProblemFix`, `ProposedFixes`, `ApplyProposedFix`, `ShowProblem`, and `AskAboutProblem` manage live problems and proposed fixes safely. ## Export and release builds (#916, #1060) While a project is open, the toolbar's **Export** button (`ExportPanelOpen` / `SetExportPanelOpen`, or `OpenSettingsPage(SettingsPageExport)`) opens the **Export** Settings page (`ExportPanelView`) in `SettingsView` to edit `game.yaml`'s `export` section and run release builds directly from the editor: - **Presets, readiness, and output directory**: edit `export.output` (`SetExportOutput`) with inline validation and add, remove, or reorder per-platform presets (`AddExportPreset`, `RemoveExportPreset`, `MoveExportPreset`) with targets chosen strictly from each platform's valid `project.TargetsOf(platform)` (`SetExportPresetTargets`, `ToggleExportPresetTarget`). Each preset row displays its readiness (`ExportPresetReadiness`: **Ready** or **Set up** when signing/team configuration or credits are missing) and policy badge, and the **Export** sidebar item surfaces a warning badge (`ExportNavWarningMeta`) whenever a preset needs setup. Every change goes through `EditProject` (`project.Validate` + Undo/Redo), clears an empty `export` section automatically, and writes canonical YAML plus the synced `nsgo.yaml` on **Save** (`SaveProject`), matching `gameproject targets`. - **Credits pre-flight**: whenever the panel opens, refreshes (`CheckExportCredits`), or starts a build, it runs the same `tooling/credits` scan that `game release` uses. Any asset without a credit is listed with its expected `*.import.yaml` sidecar path and blocks building until credited; once credited, refreshing clears the warning and successful builds write `CREDITS.md` beside the packages. - **Builds, dry runs, and Output stream**: build all configured presets or toggle specific targets (`ExportSelectedTargets`), optionally selecting a distribution channel (`SetExportChannel`), release notes file (`SetExportReleaseNotes`), or **Dry Run** (`SetExportDryRun`). `StartExportBuild` / `RunExportBuild` share the release command planner with `nsgo game release`, so dry-run builds stream the exact same `nsgo build` command line into the panel's Output view off the UI goroutine, and successful non-dry-run builds open the resolved output folder (`OpenOutputFolder` / `OpenExportOutputFolder`). ### Build and release screen (#1048, #1050) For full release preparation, **Project > Build & Release...** (`CmdBuildRelease`, shortcut `mod+shift+r`, or `OpenBuildReleaseScreen` / `CloseBuildReleaseScreen` / `BuildReleaseScreenOpen`) opens the full-window `BuildReleaseScreenView` styled with Spec tokens: - **Header and pre-build checks**: shows `"Release · Version from on · last release "` with an editable version field (`SetReleaseVersion`), Dry Run toggle (`SetReleaseDryRun`), and **Build** / **Stop** / **Resume** controls (`StartReleaseBuild`, `StopReleaseBuild`, `ResumeReleaseBuild`). **BEFORE EVERY BUILD** summarizes `nsgo check` (problem count and elapsed time via `RefreshBuildPreflight`), the smoke playtest, and release budgets declared under `export.budgets` in `game.yaml` (`qualityProfile`, `downloadSizeMB`, `frameTimeP95Ms`, defaulting to Low profile / 80 MB / 16.7 ms). - **Export presets, ordered steps, and logs**: lists each preset with an include checkbox (`SetBuildPresetIncluded`), platform summary, live status (`Queued`, `Building`, `Notarizing`, `Done`, `Failed`, `Set up`), artifact size, and delta against the last release (`SetLastReleaseBaseline`). Selecting a running preset shows the 6 ordered steps (`Check project`, `Compile Go`, `Pack assets`, `Sign`, `Smoke playtest`, `Measure`) with elapsed times, exact `releaseplan` commands matching `game release -dry-run`, and its streaming log (`build/.log`). Presets build one at a time; **Stop** keeps completed steps and **Resume** continues from the interrupted step. - **Failure isolation and agent preset fixes**: if a preset fails (for example, a missing signing keystore at `Sign`), the screen shows the error, step and elapsed time, failing commands, and `"Other platforms keep building. Nothing was uploaded."` while continuing remaining checked presets. An agent-proposed preset fix diff (`SetBuildPresetFixProposal`) can be applied and rebuilt in one click (`ApplyBuildPresetFixAndRebuild`). - **Finished results and platform readiness**: completed presets show the artifact path, size and delta against the last release, a `code` / `textures` / `audio` / `other` breakdown highlighting what grew, download-size and frame-time p95 budget Met/Missed badges, smoke playtest summary, **Show in Finder** (`ShowBuildArtifactInFinder`), **Edit preset**, and (for Web builds) a local test-link QR card. Platforms that cannot build yet (such as iOS) open the **READINESS** checklist (`EvaluateBuildReadiness`: bundle ID, app icon, distribution certificate, provisioning profile, privacy manifest, touch controls) clearly separating what the agent can handle (`RunBuildReadinessAction` / `RunBuildReadinessAgentSetup`, such as writing `PrivacyInfo.xcprivacy`) from steps that require the person (Apple sign-in). - **Release notes drafted from commits and kept reviews (#1050)**: **RELEASE NOTES** reads git commits since the last release tag (or initial commit when untagged), kept review summaries (`SetReleaseKeptReviews` / `AddReleaseKeptReview`), and `changelog.d/*.md` fragments to draft player-facing Markdown (`DraftReleaseNotes`, `RedraftReleaseNotes`, `DefaultReleaseNotesDraft`, pluggable via `Editor.ReleaseNotesDrafter`, and `release_notes_draft` in `editormcp`), displaying `"Drafted from N commits since "`. Editing the notes in place (`SetReleaseNotesText` / `SaveReleaseNotes`) saves directly and atomically to the exact Markdown file read by `game release -release-notes` (`ReleaseNotesFile` / `SetReleaseNotesFile`, defaulting to `release-notes.md`), modifying only that file. - **Store uploads that always ask first and system keychain credentials (#1050)**: pressing **Review uploads…** (`ReviewReleaseUploads` / `OpenReviewUploads`, or `release_review_uploads` in `editormcp`) opens the **Review uploads** confirmation dialog listing every artifact (name, path, size), its destination (`itch.io`, `Google Play · internal testing`, `TestFlight`), version, and keychain credential status before anything is sent. A strict trust boundary ensures no upload can ever start without the person confirming in **Review uploads** (`ConfirmReleaseUploads` with a single-use session ID; `StartReleaseUpload` and agent-actor confirmation calls via `WithAgentActor` / `editormcp` are always refused, even under `PermissionProfileAutonomous`). Upload credentials are stored via the platform `Keychain` abstraction (`StorePublishCredential`, `HasPublishCredential`, `DeletePublishCredential` — backed by macOS Keychain, Linux Secret Service, Windows Credential Manager, or `NewMemoryKeychain` in tests) and are never written into project files or serialized into snapshots; confirmed uploads run through `Editor.ReleaseUploader` with per-artifact progress and error reporting. ### Try a build on a phone (LAN QR) or connected device (#1049) When a Web or Android build completes on the Build and Release screen, authors can test it directly on their computer, on a phone over local Wi-Fi, or on a USB-connected Android device: - **LAN-only HTTP server and pure-Go QR code**: finishing a non-dry-run Web build automatically starts a local-network HTTP server (`StartWebBuildServer` / `StopWebBuildServer` / `WebBuildServerState`) bound strictly to a private RFC 1918 LAN IPv4 address (or loopback when offline, customizable via `Editor.LANAddressResolver` and `Editor.WebBuildServePort`). Public bind addresses are refused (`ErrNonLANAddress`), non-LAN peer requests receive `403 Forbidden`, symlinks escaping the build directory are blocked, and stopping the server (via **Stop serving**, closing the editor `Close()`, switching projects, or unmounting `EditorView`) immediately closes the listener and frees the TCP port. The Web result card renders a deterministic scannable ISO/IEC 18004 QR code (`internal/qrcode`, `EncodeBuildQR`) on a high-contrast light quiet-zone card using Spec tokens alongside the LAN URL, **Copy URL** (`CopyWebBuildURL`), and **Stop serving** / **Start serving** controls. - **Play-mode MCP bridge over LAN**: served web builds retain exact `index.html` and asset bytes while advertising bridge discovery via `X-NSGo-MCP-Bridge: /__nsgo_mcp/info` and `X-NSGo-Play-Mode: debug` headers. A phone browser in Play mode reads `/__nsgo_mcp/info` (or loads `/__nsgo_mcp/bridge.js`), authenticates with the per-session token at `POST /__nsgo_mcp/session`, and exchanges JSON-RPC / inspection tool calls (`/__nsgo_mcp/rpc`, `/__nsgo_mcp/poll`, `/__nsgo_mcp/reply`, `Editor.WebBridgeSessions`, `Editor.CallWebBridgeTool`, `Editor.WebBridgeHandler`) so the editor and agent can inspect and debug the build running on the phone too. - **RUN ON DEVICE**: shows live device targets and states (`BuildDeviceState`) in the finished build rail: - **This Mac's / computer's browser** (`LaunchBuildOnDevice("browser")`, injectable `Editor.OpenBrowserURL`): opens the active LAN URL in the local browser (`ready` -> `running`). - **Phone · Wi-Fi** (`LaunchBuildOnDevice("phone-wifi")`): tracks `serving`, `connected` (showing the connected phone's name when attached to the MCP bridge), and `stopped` states. - **Connected Android device on USB** (`RefreshConnectedDevices`, `RunBuildOnAndroidDevice`, `WaitAndroidDeviceRun`, `StopAndroidDeviceRun`, injectable `Editor.DeviceDiscoverer` and `Editor.DeviceCommandRunner`): once the Android build finishes, installs and launches via `go -C tool nsgo build -target -run -device `, reporting `ready`, `installing`, `running`, `failed`, and `disconnected` states cleanly. ## Project search and Find References (#914) While a project is open, the file browser's **Search** button (`SearchOpen` / `SetSearchOpen`) toggles the Search & References panel (`SearchPanelView`) below the viewport to jump anywhere in the project or answer "what uses this file?": - **Project-wide search (`Search`, `SetSearchQuery`, `SearchResults`)**: indexes every project file (following the same walk rules as `ProjectFiles` and `refs.Scan`) and parses every scene file (`*.scene.yaml`, `*.scene.yml`, autoloaded scenes, and scenes referenced by other files). Case-insensitive queries (including space-separated multi-term queries) match file names and paths (`SearchFile`), file UIDs from file headers or `game.index.yaml` (`SearchUID`), scene titles, and inside scenes: object IDs and display names (`SearchObject`, including nested children), component types (`SearchComponent`, including overrides), prefab names (`SearchPrefab`), and instanced or inherited scene paths (`SearchSceneRef`). - **Jump-to-result (`OpenSearchResult`)**: activating a result for a non-scene file selects it in the file browser (`SelectedFile`). Activating a result for a scene file opens that scene (setting `ScenePath` and `SelectedFile`) and selects the matching object (`SelectedID`), nested children included, falling back to its top-level ancestor when the child cannot be selected. If the scene is already open, it selects the object in place without reloading from disk or discarding unsaved edits and undo history. - **Find References (`FindReferences`, `ShowReferences`, `ShowSelectedFileReferences`, `References`, `OpenReference`)**: selecting any file or directory in the file browser and pressing **Find Refs** queries `refs.Scan` for every incoming reference, listing each referring file, 1-based line, field, and written value in the exact order `refs.Scan` reports them. Pressing a reference row opens the referring scene (and selects the top-level object owning that line when applicable) or selects a non-scene referring file in the file browser. - **Live index updates (`RefreshSearch`)**: edits to the currently open scene (`PlaceObject`, `SetObjectName`, `DeleteObject`, Undo/Redo) immediately update active search results in memory; saving scenes, projects, clips, data tables, or localizations, installing/removing packs, and moving files (`MoveFile`, including Undo/Redo, which also follows `ReferencesTarget`) automatically invalidate and refresh the index; external edits on disk are detected via a lightweight directory fingerprint or refreshed explicitly via **Refresh** (`RefreshSearch`). Asynchronous callers can also toggle the panel's loading card with `SearchLoading` / `SetSearchLoading`. ## Running the game and Output panel (#910) Alongside the existing in-editor **Play** preview (`Play`, `PlayIn`, `Stop`), the editor can launch the open project itself on desktop via `go tool game dev` and stream its logs into a docked Output panel (`OutputPanelView`) below the viewport: - **Run and Stop**: press the toolbar's **Run** button (or **F5**) to launch `go tool game dev` in the open project directory (`RunGame` / `RunGameWith`). Enable the **Current Scene** toggle (`SetRunStartAtOpenScene`)—or pass `RunGameOptions{StartAtOpenScene: true}`—to pass `-scene ` and `NSGO_GAME_SCENE` (`hotreload.SceneEnv`) for the currently open scene. While the game is running, the button switches to **Stop Game (Running)** (**Shift+F5** / `StopGame`), which terminates the child process and its entire process tree cleanly (via its own process group on Unix and `taskkill /T /F` on Windows). Unmounting `EditorView`, switching projects (`OpenProject`), or calling `Close()` also stops any running game cleanly. Custom tools and tests can inject `Editor.RunGameCommand`. - **Output / Log panel**: docked below the viewport (`OutputPanelView`, toggleable via the toolbar's **Output** button or `SetOutputPanelOpen`), streaming the running game's standard output (`OutputStdout`) and standard error (`OutputStderr`) live off the UI goroutine alongside a timestamped history of the editor's own status and error messages (`OutputEditor`). Consecutive editor errors stay in the log instead of overwriting one another. - **Filter, Clear, and `file:line` navigation**: toggle **Errors** (`SetOutputErrorsOnly`) to show only error entries, press **Clear** (`ClearOutput`) to empty the log, and click any log line carrying a `file:line` location (`OpenOutputEntry`) to open that file in the editor when it is a scene (`*.scene.yaml`, `*.scene.yml`, or listed under `autoload.scenes`) or select it in the file browser otherwise. ## Keyboard shortcuts, menu bar, and command palette (#920) Every common editor action lives in a single command registry (`Editor.Commands`, `Editor.RegisterCommand`, `Editor.ExecuteCommand`) that drives keyboard shortcuts, the desktop application menu bar, and the Command Palette from one source of truth: - **Platform shortcuts and text-field guard**: shortcuts use NSGo's `"mod"` modifier (Command on macOS, Ctrl on Windows and Linux; formatted via `FormatShortcut`) and are bound with `core.KeyNotEditing` and `core.MenuNotEditing` so typing or pressing Delete/Backspace/Undo/Save while any text field has focus (such as the inspector's Name field or a search box) never triggers editor shortcuts: - File & Edit: `mod+s` (Save), `mod+z` (Undo), `mod+shift+z` (Redo), `mod+c` (Copy objects or active tile region), `mod+x` (Cut objects or active tile region), `mod+v` (Paste objects or tile region), `mod+shift+v` (Paste as Child), `mod+d` (Duplicate), `mod+g` (Group), `mod+shift+g` (Ungroup), `delete` / `backspace` (Delete selected objects). - 2D Tools: `v` (Select), `m` (Move), `p` (Place), `b` (Paint Tile), `e` (Erase Tile), `g` (Fill Tile), `t` (Terrain), `u` (Rectangle Tile), `l` (Line Tile), `c` (Stamp Tile), `n` (Random Tile). - 3D Gizmo & View: `w` (Translate), `e` (Rotate), `r` (Scale), `t` (Local / Global space), `shift+c` (Collider), `alt+2` (2D View), `alt+3` (3D View), the Lit, Unlit and Wireframe 3D shading commands under `View > 3D Shading` (no shortcut), `f` (Frame Selection, framing the independent 2D `View2D` via `FrameSelection2D` without mutating `Doc.Camera` and `Camera3D` in 3D), `1`, `ctrl+1`, `3`, `ctrl+3`, `7` and `ctrl+7` (the Front, Back, Right, Left, Top and Bottom 3D views), `5` (3D perspective or orthographic) and `0` (Look Through Scene Camera), which work in the 3D view only, `View > Scene Environment` (toggle the Environment panel), `mod+k` (Command Palette). - Project: `f5` (Play / Stop), `mod+r` (Run Game via `Editor.OnRunGame`, falling back to play-in-editor when a scope is attached), `mod+,` (Settings), `mod+shift+,` (Project Settings), `mod+shift+u` (HUD & Menu Layout), `mod+shift+e` (Export & Release panel), `mod+shift+r` (Build & Release screen), `mod+shift+m` (Profiler), `mod+shift+b` (Check Problems). - **Desktop menu bar**: `EditorView` registers the native application menu bar (`File`, `Edit`, `View`, `Project`) through `desktop.SetApplicationMenu` (`Editor.ApplicationMenu`), exposing the same registered commands with live enabled/checked states, formatted shortcut hints, active plugin tools under `View > Tools`, and active plugin commands under `Project > Plugins`. - **Command Palette (`ui.CommandDialog`)**: press `mod+k` (or the toolbar's **Commands** button / `View > Command Palette...`) to open `CommandPaletteView`, which lists every built-in and custom command, active plugin commands, active plugin tools (activating them via `SetPluginTool`), active plugin panels (focusing them via `FocusPluginPanel`), and the open project's scenes and files (opening scenes or selecting files via `OpenProjectFile`) with ranked substring and fuzzy matching. - **Plugin commands**: plugins can declare `Commands []PluginCommand` with an optional `Shortcut`. `RegisterPlugin` normalizes each shortcut (`NormalizeShortcut`) and refuses any shortcut that clashes with a built-in, custom, or other registered plugin command across macOS and Windows/Linux before mutating the editor. ## Asset import settings and rebuilding (#915) Selecting an image (`.png`, `.jpg`, `.jpeg`, `.webp`), sound (`.wav`, `.ogg`, `.mp3`, `.flac`), font (`.ttf`, `.otf`), or 3D model (`.gltf`, `.glb`) in the file browser (`SelectedFile`, excluding generated target outputs and `*.import.yaml` sidecars) displays its import settings and credit metadata in the Inspector (`InspectorView`): - **Sidecar and target defaults**: `InspectAssetImport` reads the asset's `*.import.yaml` sidecar when present and overlays it on the matching target's defaults in `game.yaml`'s `assets` section (image `filter`, `format`, `mipmaps`, `srgb`, sprite-sheet `slice`, and frame `pivot`; audio `format`, `rate`, `channels`, `bitrate`, `peakDB`/`rmsDB` normalization, and `loop`; font `size`, `padding`, and `chars`; model `scale`, `animations`, `lodHysteresis`, and `lods`), plus the shared `credit` section (`author`, `license` as an SPDX expression, `source`, and `notice`). - **Interactive sprite-sheet slice grid and frame pivots (#880)**: when an image is selected, the import panel shows an interactive preview canvas (`DrawImageImportPreview`) over a transparency checkerboard with the live slice grid (`width`, `height`, `margin`, `spacing`, `count`) and draggable pivot markers per cell (or a single marker when unsliced). Authors can drag any marker directly on the preview (`BeginImagePivotDrag` / `UpdateImagePivotDrag` / `EndImagePivotDrag` / `CancelImagePivotDrag`), pick default presets (`TL`, `Center`, `Bottom`), or edit/reset `pivot.default` and per-cell `pivot.cells` numerically (`SelectImportSliceCell`, `SetImageImportPivot`, `SetImageImportDefaultPivot`, `SetImageImportCellPivot`). Every drag commits once to the sidecar as a single undoable step, and running **Reimport** or **Build Assets** writes those pivots into the packed TexturePacker JSON so `sprite.LoadAtlas` loads exact `Frame.PivotX` and `Frame.PivotY` values immediately. - **Interactive glTF/GLB model preview and animation playback (#897)**: when a `.gltf` or `.glb` model is selected in the file browser, the import panel renders the model through an orbit camera (`DrawModelPreview`, `RenderModelPreview`, `OrbitModelPreview`, `PanModelPreview`, `ZoomModelPreview`, `ResetModelPreviewCamera`) reflecting the effective import `scale`, and inspects its contents (`InspectModelImport`): unscaled and scaled bounds, total triangle and vertex counts, and lists of its nodes, meshes, materials, and animations. Each animation can be selected, played, paused, stopped, looped, or scrubbed (`SelectModelPreviewAnimation`, `PlayModelPreviewAnimation`, `PauseModelPreviewAnimation`, `StopModelPreviewAnimation`, `SeekModelPreviewAnimation`, `StepModelPreviewAnimation`), supporting node TRS transforms, skeletal skinning, and morph targets. Editing `scale`, `animations`, `lodHysteresis`, or `credit` writes the deterministic sidecar through `importsettings.Encode` and shows which `game.yaml` model target reads the file, so the next `game assets` run rebuilds only that model. - **Validated undoable edits and field reset**: every change writes the sidecar atomically through `importsettings.Encode` as one undoable `Editor.History` step (`EditAssetImportSettings`, typed `SetImageImport*` / `SetAudioImport*` / `SetFontImport*` / `SetModelImport*` setters, and `SetAssetImportCredit`). **Undo** restores the exact previous sidecar bytes verbatim (or removes a newly created sidecar file), and **Reset** (`ResetAssetImportField`) clears an override back to the target's default, removing the sidecar once no overrides or credit remain. - **Reimport, Build Assets, and live reload**: the inspector's **Reimport** button (`ReimportAsset`) and the toolbar's **Build Assets** button (`BuildAssets` / `BuildAssetsWith`) run `nsgo game assets` off the UI goroutine, streaming stdout and stderr into the docked **Output** panel (`OutputPanelView`). On completion, `ReloadAssets` reloads changed atlases and textures from disk into `Editor.Resolver` (updating `sceneformat.AtlasMap` or existing `*sprite.Atlas` values in place and invoking `AssetReloader` / `OnReloadAssets` when set), refreshes the Asset Browser and Viewport immediately without restarting the editor, and re-runs the Problems check. Custom tools and tests can inject `Editor.AssetsCommandRunner`. ## Profiler panel and frame time strip (#912) While playing in the editor or connected to a running game over MCP (`game_perf_readout`, `game_perf_zones`, `game_perf_reset`), the editor displays a live frame-time strip beneath the viewport and opens a full Profiler panel styled with the editor's design spec tokens (`docs/design/editor/PlayMode.dc.html` and `Spec.dc.html`): - **Play-mode `FRAME TIME · LAST 60 S` strip (`ProfilerStripView`)**: always visible below the game view while Play mode is active or a remote game is connected (`ConnectProfiler`). It shows `avg`, `p99`, and `allocs/frame` from `game_perf_readout`, threshold lines and legend markers at `8.3 ms` (`over 8.3 ms`) and `16.7 ms` (`missed 16.7 ms`), the `−60 s`, `−30 s`, and `now` axis, and a callout pill labelling spikes with their cause when the game supplies one via `debug.Overlay.NoteFrameCause` (or `"GC pause"` on GC hitches). Pressing the strip's **Profiler** button opens the full Profiler panel. - **Connecting to a running game**: connect via `ConnectProfilerMCP` (official MCP Go SDK over any `mcp.Transport`), `ConnectProfilerCommand` (spawning `go tool nsgo mcp`), `ConnectProfilerScope` (an in-process `*core.Scope` with `mcp.Bridge` attached), or `NewBridgeProfilerClient`, and pass the client to `Editor.ConnectProfiler`. While attached to a scope, the editor polls `game_perf_readout` and `game_perf_zones` every `Editor.ProfilerPollInterval` (default `250 ms`), or on demand via `Editor.PollProfiler`. Built-in Play mode (`Play` / `PlayIn`) also instruments its loop with `debug.Overlay`, `debug.Profiler`, and `debug.GCMonitor` automatically when no external profiler client is connected. - **Full Profiler panel (`ProfilerPanelView`)**: toggleable from the strip, toolbar **Profiler** button, `Project > Profiler`, Command Palette, or `mod+shift+m` (`CmdProfiler` / `SetProfilerOpen`). It displays live KPI cards and switchable time-series charts (`SetProfilerMetric`) for **Frame** (stacked update, draw, total, and GC hitch markers with 8.3 ms / 16.7 ms lines), **FPS**, **Allocs & GC** (allocations per frame, live heap bytes, and GC hitches), and **Memory** (tracked asset memory against budget and per-group totals), alongside a scrollable table of named timing zones from `game_perf_zones` sorted by cost. - **Reset and Chrome/Perfetto trace export**: pressing **Reset** (`Editor.ResetProfiler`) invokes `game_perf_reset` on the connected game and clears the editor's recorded history and zone table. Pressing **Export Trace** (or calling `Editor.ExportProfilerTrace` / `Editor.ExportProfilerTraceFile`, or intercepting via `Editor.OnExportProfilerTrace`) writes the recorded frames and zones as Chrome/Perfetto Trace Event Format JSON through `debug.Profiler.WriteChromeTrace`. ## Start screen (#922) Running `go tool game editor` with no arguments opens the Start Screen (`StartScreenView`, toggled with `SetStartScreenOpen`), designed from `docs/design/editor/Start.dc.html`, step 1 of `FirstRun.dc.html`, and the `Spec.dc.html` tokens: - **Recent projects (`RecentProjects`, `ParseRecentProjects`, `EncodeRecentProjects`)**: opening a project records its name, directory path, and UTC RFC3339 `lastOpened` timestamp in a strict versioned per-user YAML file outside any project (`/nsgo-game/recent-projects.yaml` via `DefaultRecentProjectsPath`, or `Editor.RecentProjectsPath`). The sidebar's **RECENT** list appears once at least one project has been opened, displays relative times, marks entries whose folder or `game.yaml` is missing on disk (`Missing`) with a badge and remove action (`RemoveRecentProject`), and persists across restarts. - **Open folder (`BrowseAndOpenProject`)**: opens a project directory through NSGo's native folder picker (`core.Scope.PickDirectories`) or the injectable `Editor.PickProjectFolder` hook. - **New project from template (`ProjectTemplates`, `StartCreateProject`)**: template cards and `All` / `2D` / `3D` filter chips are populated dynamically from `game new`'s template registry, so newly added templates appear without editor changes. The project name, parent folder (defaulting to `~/games`), and optional module path are validated live as typed (`ValidateNewProjectInputs`): checking `a–z`, `0–9`, and `-` characters, write access to the parent folder, and existing folders (offering **Open it** or the next free sibling name such as `dungeon-run-2`). Pressing **Create** runs `game new` (including its `go get` and `go mod tidy` steps) off the UI goroutine while streaming stdout and stderr into the Start Screen, then opens the created `game.yaml`. - **Open Demo (`OpenDemo`, `NewDemo`)**: opens the built-in Demo Room scene without creating or opening a project on disk. - **Start with AI — from one sentence to the first review (#1051)**: pressing **Start with AI** (`StartWithAI`) implements the full five-stage flow in `docs/design/editor/FirstRun.dc.html` using Spec tokens: - **WHAT HAPPENS NEXT & Connect in place**: the Start Screen lists the three steps (**Connect an agent**, **Approve its plan**, **Review the first scene**). When no agent is connected yet, **Start with AI** opens **Connect an agent** (`FirstRunStageConnect`) in place on the Start Screen while preserving the idea and project name (with **Edit** and **Later** returning cleanly to Step 1). It detects `claude` and `codex` on `PATH` (or via `Editor.FirstRunDetectAgents`), verifies the connection (`Editor.FirstRunConnectAgent`, with a 30 s no-answer checklist and in-place **Copy diagnostics**), or validates a pasted API key immediately in memory (`Editor.FirstRunValidateAPIKey`, never written to YAML). - **The first plan (`FirstRunStagePlan`, `OpenFirstRunPlan`)**: opens a read-only template preview viewport with planned dashed-violet ghosts (`FirstRunGhost`) beside the Agent panel's **PLAN** card (`Editor.FirstRunPlanner` / `DefaultFirstRunPlan`), optional clarifying question with a suggested answer, **Just do it** (`JustDoItFirstRunPlan`), and **Approve ⌘↵** (`ApproveFirstRunPlan`). No project folder is created on disk until **Approve**. - **Building (`FirstRunStageBuilding`)**: after **Approve** creates the brand-new folder, the editor switches to the working layout with the 5-stage progress bar (`Template`, `Project`, `First scene`, `Check`, `Playtest`) and concrete object counts (`19 of 31 objects`, never a bare spinner). Pressing **Cancel** or `Esc` pauses and asks first (**Keep building**, **Stop, keep the files**, or **Stop and delete the folder** — offered and permitted only for the brand-new folder created by this flow, never touching sibling or pre-existing folders). A failed `Check` stops before the review with the agent's proposed fix (**Fix it** / **Review as is**). - **The first review & one-time tips (`FirstRunStageReview`)**: displays the plan summary on top (steps completed, with any differences from the plan highlighted in amber with their reason), **Before / After** toggle plus hold-`B` peek (`Before: an empty folder`), per-change revert/restore toggles, **Revert all**, and **Keep N of M** (`KeepFirstRunReview`). Three onboarding tips (**keep or revert each change**, **hold B**, **select then ⌘L**) show one at a time and once per person, stored under `seenTips` in `EditorSettings` (`editor.yaml`); **Skip tips** ends all three and **`Help › Replay tips`** (`CmdReplayTips` / `ReplayTips`) clears them and brings them back. - **Clean project switching and unsaved-edits prompt**: opening a project from the Start Screen or later through `File > Open Project...` (`mod+o`), `File > New Project...` (`mod+n`), or `File > Start Screen` replaces the current project, scene, clip, cutscene, data table, localization workspace, skeletal rig, and undo history cleanly. Whenever the open session has unsaved edits (`HasUnsavedChanges`), the editor's unified unsaved-changes dialog asks to **Save** (`ConfirmSaveAndSwitch`), **Discard** (`ConfirmDiscardAndSwitch`), or **Cancel** (`CancelPendingSwitch`) before replacing anything. ## 3D LOD and occluder visualization (#904) In 3D view (`View3D`), the viewport runs the same `scenemodel.Build` + `render3d.OcclusionBuffer` + `render3d.Queue` evaluation used at runtime (automatically backed by `scenemodel.NewAssets` when a project is open, or an injected `Editor.ModelResolver`): - **LOD overlay (`ShowLODOverlay` / `SetShowLODOverlay`)**: color-codes each multi-LOD object by its active level and draws a `LOD` badge beside it in the viewport; the 3D inspector also reports the selected object's active LOD (`ObjectLOD3D`, `ObjectLODCount3D`). Editing a model's `lods` or `lodHysteresis` in the asset import inspector invalidates the 3D build so switches take effect immediately. - **Occluder visualization and editing (`ShowOccluders` / `SetShowOccluders`, `SetObjectOccluder`)**: draws magenta wireframes with `OCC` / `OCC BOX` badges for every visible occluder (including explicit `box` occluders and `model` occluders), dims objects culled behind an occluder (`ObjectOccluded3D`), and exposes undoable Occluder mode (`none` / `model` / `box`), box size, and double-sided controls in the 3D inspector (raising version 1 scenes to version 2 automatically). - **RenderStats overlay (`ShowRenderStats` / `SetShowRenderStats`, `RenderStats3D`)**: displays the live `render3d.RenderStats` readout (`Draws`, `Visible`, `Occluded`, `Tris`, `Verts`, plus active per-object `LOD` levels) in the top-right corner of the 3D viewport, toggleable alongside the LOD and Occluders overlays from the 3D toolbar. ## Remote scene tree and live inspector (#911) While a game built with [`game/mcp`](https://game.nsgo.dev/docs/mcp/) runs with `-automation`, the editor connects as an MCP client (using `github.com/modelcontextprotocol/go-sdk/mcp` over `go tool nsgo mcp` on desktop, or any `mcp.Transport` passed to `ConnectRemote` / `Editor.RemoteTransport`) to inspect and tune the running game live: - **Connecting**: enable **Auto-connect on Run** in the **Remote** tab (`SetRunWithAutomation`) or call `RunGameWith(RunGameOptions{Automation: true})` to pass `-automation` to `nsgo game dev` and connect automatically once the game starts, or call `ConnectRemote` / `ConnectRemoteCommand` to attach to an already-running game. `NewRemoteBridgeServer(bridge, run)` wraps a `*mcp.Bridge` directly as an MCP server for deterministic in-process or pipe testing. - **Remote tab beside the Scene Tree**: switch between **Scene** (`SceneTreeLocal`) and **Remote** (`SceneTreeRemote`) in `SceneTreeView`. The Remote tab lists active scenes (`game_scenes_list`), layers in draw order (`game_layers_list`), and live entities with their parent-child hierarchy (`game_entities_list`), refreshed automatically while unpaused (interval `Editor.RemoteRefreshInterval`, default 250 ms) or on demand via `RefreshRemote`. Entities without a scene `ObjectRef` group under **SPAWNED AT RUNTIME**, and scene objects that are destroyed while running appear dimmed with the step they were taken at. - **Live Inspector and Live Changes**: selecting a live entity (`SelectRemoteEntity`) inspects its components (`game_entity_inspect`) in `InspectorView`. Read-only derived components (`world_transform2d`, `object_ref`) show live readouts, while editable components render typed controls that patch the running game immediately through `game_component_set` (`SetRemoteComponentField` / `SetRemoteComponentValue`) and display `"was X"` beside changed fields. Every live edit is recorded in **LIVE CHANGES** (`RemoteLiveChanges`), which stays after disconnecting or stopping the game: revert individual rows (`RevertRemoteLiveChange`), discard all (`DiscardRemoteLiveChanges`), or press **Keep in scene** (`KeepRemoteLiveChangesInScene`) to write all changes on scene-backed entities into the open scene as a single undoable `History.Group` step that one Undo restores. - **Live Play Bar, Tunables, and Console**: while connected, the Play Bar exposes **Pause / Resume** (`mod+shift+p`, `RemotePause` / `RemoteResume`), **Step** (`.` while paused) and **Step N** fixed updates (`RemoteStep`), **Time Scale** (`0.25×`, `0.5×`, `1×`, `2×`, `RemoteSetTimeScale`), and live frame/time/entity readouts in the status bar. When the game configures a `debug.Console`, the Remote Inspector also lists live **Tunables** (`game_tunables_list` / `RemoteSetTunable`) and a **Console** command line (`RemoteExecConsole` / `game_console_exec`). ## 3D terrain sculpting and painting (#900) In 3D view (`ViewMode3D`), press the toolbar's **Terrain** button (or open a `*.terrain.yaml` file from the file browser via double-click / **Terrain**, or call `NewTerrain`, `OpenTerrainFile`, `OpenTerrainProjectFile`, or `OpenTerrain` in Go) to edit a `world3d` terrain directly in the 3D viewport with the docked `TerrainPanelView` below it: - **Sculpt and paint brushes**: choose `TerrainBrushRaise`, `TerrainBrushLower`, `TerrainBrushSmooth`, `TerrainBrushFlatten` (targeting the height sampled where the stroke starts, or `TargetHeight` when `UseTargetHeight` is set), `TerrainBrushSetHeight` (`TargetHeight`), `TerrainBrushPaintLayer` (increasing the active texture layer's weight while keeping all layers normalized to 1), or `TerrainBrushPaintFoliage` (blending the active foliage layer's density toward `TargetDensity` in `[0, 1]`, where `0` erases). Configure `Radius`, `Strength`, and `Falloff` (`TerrainFalloffSmooth`, `TerrainFalloffLinear`, `TerrainFalloffFlat`) via `SetTerrainBrush` or the panel controls. - **3D raycast strokes and single-step Undo/Redo**: clicking or dragging across the terrain in the 3D viewport raycasts against the live `world3d.Heightmap` (`RaycastTerrain3D`, `BeginTerrainStrokeAt` / `ContinueTerrainStrokeAt` / `EndTerrainStroke`, or world-coordinate `BeginTerrainStroke` / `ContinueTerrainStroke`), interpolates continuous dabs along fast drags, draws a terrain-conforming brush radius ring overlay, and records each complete stroke as **one undo step** in `Editor.History` (with `Escape` / `CancelTerrainStroke` aborting an active stroke cleanly). Undo and Redo restore exact heightmap, layer-weight, and foliage-density samples and track `TerrainDirty()` / `HasUnsavedChanges()`. - **Lossless 16-bit saving**: **Save Terrain** (`SaveTerrain`, `SaveTerrainTo`, or `Save` when dirty) writes the 16-bit grayscale PNG heightmap (`*image.Gray16`, eliminating 8-bit slope banding), per-layer grayscale weight-map PNGs (or packed RGBA `splatMaps`), foliage density-map PNGs, and deterministic `*.terrain.yaml` atomically so `world3d.LoadTerrainFS`, `TerrainDoc.ScatterFoliage`, and `render3d.TerrainMaterialFromDoc` load and draw the exact same terrain in the game. ## Particle emitter editor (#883) The Particle Emitter Editor (`ParticleEditorPanelView`), opened from the toolbar's **Particles** button (`CmdParticleEditor`), by double-clicking a `*.particles.yaml` / `*.emitter.yaml` file or pressing **Open Emitter** in the file browser, or from the Inspector's **Edit Emitter** button on an object with `particles`, edits every field of a 2D `particles.Config` with live preview and full Undo/Redo: - **Live preview without restart**: the panel runs a live `*particles.Emitter` (`ParticlePreview`) on a preview canvas with **Play/Pause** (`PlayParticlePreview` / `PauseParticlePreview`), **Restart** (`RestartParticlePreview`), **Step** (`StepParticlePreview`), **Burst** (`BurstParticlePreview`), **Preview Atlas** (`SetParticlePreviewAtlas`), and an optional **Floor** collider (`SetParticlePreviewFloor`) to test bounce/stop/kill collisions. Editing rate, curves, motion, or other fields calls `Emitter.ReloadConfig` so the running preview reflects changes live without restarting or clearing live particles. When no atlas or frames are bound, the preview draws colored fallback discs so particles remain visible while tuning. - **Every emitter field & interactive curve widget**: edits `space`, position, rotation, `z`, `seed`, `shape` (`point`, `circle`, `ring`, `rect`), `rate`, `maxParticles`, scheduled `bursts` (add/edit/remove `time`, `count`, `cycles`, `interval`), `lifetimeMin`/`Max`, `speedMin`/`Max`, `angleMin`/`Max`, `gravityX`/`Y`, `initialRotationMin`/`Max`, `rotationSpeedMin`/`Max`, `collision`, `trail`, and recursive `subEmitters` (navigate into any child config via `SetParticleTargetPath` / **Edit Child**). The curve widget plots `sizeCurve`, `alphaCurve`, `rotationCurve`, `colorCurve`, `trail.widthCurve`, and `trail.colorGradient` on an interactive canvas where stops can be dragged, clicked to add, or edited numerically, and the atlas frame picker toggles `frameNames` directly from the resolver's atlases. - **Undo/Redo and deterministic save**: every edit goes through `Editor.History`, and **Save Emitter** (`SaveParticleEmitterFile` / `SaveParticleEmitterYAML` / `OnSaveParticleEmitter`) writes canonical versioned YAML (`particles.MarshalConfigYAML`) that round-trips unchanged and hot-reloads matching emitters already placed in the open scene. - **Scene placement**: bind any object's `particles` field via `SetObjectParticles`, `PlaceParticles`, or the Inspector's **PARTICLES** section (`file` and `atlas` pickers). Placed emitters animate live in the 2D edit viewport (`StepSceneEmitters`, hidden when the object is hidden), run in Play mode (`PlayIn`) and in the game (`sceneformat.Build`), are scanned by `refs` (`MoveFile` rewrites `particles.file`), and are validated by `assetcheck`. ## Language and appearance settings (#921) The editor UI is localized in English (`en`) and Simplified Chinese (`zh`) through embedded versioned `l10n` YAML string tables (`editor/locales/en.yaml`, `editor/locales/zh.yaml`), and per-user preferences are stored outside any project as deterministic versioned YAML: - **Per-user settings file (`EditorSettings`, `SettingsVersion = 1`, #921, #1005, #1006, #1028)**: stored at `DefaultSettingsPath()` (under `os.UserConfigDir()` as `nsgo-game/editor.yaml`, outside every game project) and loaded/saved with `ParseEditorSettings`, `EncodeEditorSettings`, `LoadEditorSettings`, `SaveEditorSettings`, `Editor.LoadSettings`, `Editor.LoadUserSettings`, and `Editor.SaveSettings`. It stores `version`, `language`, `appearance`, optional `autoSave` (defaults to `true` when omitted), optional `interfaceSize` (`compact`, `default`, or `large`), optional `snap` (per-person defaults for `grid`, `gridSize`, `pixel`, `rotation`, `rotationStepDeg`, `scale`, `scaleStep`, and `showGrid`, used when a project does not override snap in `.game/editor.yaml`), optional `showAgentChanges` (defaults to `true` when omitted), optional `navigation3D` (`default`, `blender`, or `maya`), optional `viewportOverlays` (canonical sorted list of enabled 2D viewport overlay IDs; omitted for defaults, `[]` for all off), optional `overlayLegend` (canonical sorted list of enabled Spec viewport overlay legend kinds: `selection`, `agent`, `added`, `changed`, `removed`, `problem`; omitted enables all six, `[]` hides all six), optional `shortcuts`, optional `seenTips`, and optional `agent` preferences (task routing, MCP tool toggles, external MCP servers, weekly request limit, outbound privacy switches, and local usage counters; secrets such as API keys are never stored in `editor.yaml`). Unknown keys, YAML anchors/aliases/merge keys, trailing documents, negative/non-finite snap steps, and invalid enum values are refused with `*loaderr.Error`. Output is deterministic 2-space YAML prefixed with `SettingsSchemaComment` so a load-save round trip changes nothing byte-for-byte. Its published JSON Schema is `https://game.nsgo.dev/schemas/editor-settings.v1.json` (`SettingsSchemaURL`). ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/editor-settings.v1.json version: 1 language: system appearance: system autoSave: true interfaceSize: default snap: grid: true gridSize: 16 rotation: true rotationStepDeg: 15 showGrid: true showAgentChanges: true navigation3D: default shortcuts: view.frame: g ``` - **Unified Settings window (`SettingsView`, `⌘,` / `Esc`, #1005)**: - **Opening, closing, and focus restoration**: pressing `⌘,` (`mod+,`, `CmdEditorSettings`) opens the full-window Settings view (with or without an open project) and pressing `Esc` closes it, returning keyboard focus to the exact control that had focus before opening. - **Grouped navigation and page anatomy**: the left navigation list is grouped into **`AGENT`** (Models and connections, Permissions, Game brief, Project rules, Tools, Usage and privacy), **`PROJECT · game.yaml`** (Project, Input map, Audio buses, Export — hidden when no project is open), and **`EDITOR · THIS COMPUTER`** (General, Viewport, Shortcuts), with a live meta line on each entry and no empty group headings. Each page shows its title, one-line subtitle, and scope chip (`"This computer"`, `"Project · shared"`, or `"Project · game.yaml"`), and each row renders a label, help text, value control, and `"Agent may change"` or `"You only"` policy column. - **Search and agent handoff**: typing into the top search field (`"Search settings, or tell the agent what you want"`) matches setting labels and help text across all pages, narrowing both the sidebar navigation (hiding non-matching pages and empty groups) and the rows on the active page. When no setting matches and the agent panel is enabled, Settings offers sending the query directly to the agent (`AskAgentFromSettings`). - **General page (`SettingsPageGeneral`)**: edits **Language** (`Editor.SetLanguage`), **Appearance** (`Editor.SetAppearance`), **Save automatically** (`Editor.SetAutoSave`, kept changes only after 2 s), and **Interface size** (`Editor.InterfaceSize`, `Editor.SetInterfaceSize`: `Compact`, `Default`, `Large`, scaling text and controls together). - **Viewport page (`SettingsPageViewport`, `OpenViewportSettings`)**: edits **Snap** (toggle + grid step in `px` + rotation angle in `°`, hold `⌘` to ignore), **Grid** (dots/grid every snap step, `SetShowGrid`), **Show agent changes** (`Editor.ShowAgentChanges`, `Editor.SetShowAgentChanges`: outlines in the viewport while a review is open), **3D navigation** (`Editor.Navigation3D`, `Editor.SetNavigation3D`: `Default`, `Blender`, or `Maya` mouse mapping), and every toggleable **Overlay legend** choice (`ViewportOverlays`, persisted per computer). - **Keyboard and accessibility**: `ArrowDown` / `ArrowUp` / `Home` / `End` move through the left navigation list; every on/off toggle uses `SpecSwitch` (`RoleSwitch` with `aria-checked` and a 2 px Spec accent focus ring); every row is reachable with `Tab`. - **Automatic saving and status bar save status (#1016)**: - **General › Save automatically (`Editor.AutoSave`, `Editor.SetAutoSave`)**: enabled by default and persisted as `autoSave` in `EditorSettings`. Kept changes to file-backed scenes and `game.yaml` save automatically after a 2-second debounce (`DefaultAutoSaveDelay`, configurable via `Editor.AutoSaveDelay`). Edits inside an open review (`Editor.HasOpenReview()`, including `BeginReview` / `KeepReview`, cutscene reviews, playtest metric reviews, safe rename reviews, merge conflicts, and unresolved disk conflicts) are not kept yet and pause autosave until kept. - **Status bar save item (`Editor.SaveStatus`, `SaveStatusSaved` / `SaveStatusSaving` / `SaveStatusFailed`)**: displays muted `Saved` (hover tooltip shows the last save time), transitions to `Saving…` only after a write has stayed in flight for at least 300 ms (`DefaultSavingIndicatorDelay`, configurable via `Editor.SavingIndicatorDelay`) so quick saves never flicker, and keeps failed autosaves in the status bar (never as a toast) with a human-readable cause (such as `"Couldn't save: folder is read-only"` or `"Couldn't save: disk is full · 12 MB free"`), plus **Retry** (`Editor.RetrySave`) and **Save as…** actions until fixed. - **While saving fails**: the unsaved dot beside the scene name and on the failing scene tab turns Spec problem red (`#FF6B6B`), quitting asks first (`Editor.HasUnsavedChanges()` remains `true`), and `editormcp` appends a warning to every tool result until a save succeeds. - **Live language switching**: `Language` accepts `LanguageSystem` (`"system"`), `LanguageEnglish` (`"en"`), or `LanguageChinese` (`"zh"`). Calling `Editor.SetLanguage` or picking a language on the **General** page under **`EDITOR · THIS COMPUTER`** in the unified **Settings** view (`SettingsView` / `EditorSettingsDialogView`, opened from the toolbar's **Preferences** button, `File > Editor Settings...`, or `mod+,`) updates the toolbar, desktop menu bar, file browser, asset browser, scene tree, layers, inspector, bottom panels, dialogs, command palette, and status bar immediately without restarting. `Editor.ResolvedLanguage()` reports the active locale (`"en"` or `"zh"`) and is exposed to connected MCP agents through `selection_get`. - **Appearance (`core.Scope.SetAppearance`) and Spec Dark/Light theme (#1062)**: `Appearance` accepts `AppearanceSystem` (`"system"`), `AppearanceLight` (`"light"`), or `AppearanceDark` (`"dark"`). `EditorView` installs the embedded YAML Spec theme (`spec_theme.yaml`, loaded via `core.ParseTheme` and exposed through `SpecTheme`, `DarkSpecPalette`, `LightSpecPalette`, `SpecPaletteFor`, and `Editor.SpecPalette`) onto the root scope so every NSGo `ui` widget, panel, viewport overlay, overlay legend (`SpecOverlayLegendView` / `SetOverlayLegendOpen`), and toast (`ShowToast` / `DismissToast` / `ToastView`) follows the Spec tokens in both Dark and Light appearances instead of falling back to NSGo's default theme. Every foreground/background, button-on-fill, warning-card, and viewport-overlay pair in both palettes is measured against the same WCAG 2.2 contrast table (`ContrastRatio`, `SpecContrastTable`: >= 4.5:1 AA for text, pill labels, and text on accent/agent/problem fills; >= 3:1 UI contrast for focus rings and viewport overlay edges). With `AppearanceSystem`, changing the OS appearance repaints the editor live without a restart; explicit `AppearanceLight` or `AppearanceDark` choices persist to `Editor.SettingsPath` across restarts. - **Shortcuts: searchable and rebindable within a scope (#1061)**: - **Command scopes**: every `EditorCommand` and `PluginCommand` carries a `Scope` (`ScopeGlobal`, `ScopeViewport`, `ScopeViewport2D`, `ScopeViewport3D`, `ScopeSceneTree`, `ScopeTile`, `ScopeAnimation`, `ScopePlay`, defaulting to `ScopeGlobal` when omitted). - **Settings › Shortcuts (`EditorSettingsTabShortcuts`, `OpenShortcutsSettings`, `CmdShortcutsSettings`)**: lists every registered built-in, custom, and active plugin command with its scope and live formatted key, searchable by command name, key/shortcut, or scope (`FilterShortcutCommands`). Pressing a command's key binding enters key-capture mode (`ShortcutFromKeyEvent`, cancelled cleanly with `Escape` without closing the dialog). Rebinding to a key already used in the **same** scope (`ShortcutConflict` / `*ShortcutConflictError`) flags the conflict in place with a **Swap** button (`SwapShortcut`, leaving both commands bound to each other's keys); binding a key used only in a **different** scope (`RebindShortcut`) succeeds immediately without a prompt. Per-row **Reset** (`ResetShortcut`) and **Reset all** (`ResetAllShortcuts`) restore defaults. - **Persistence and live surfaces**: custom bindings persist under `shortcuts` in `EditorSettings` (`editor.yaml`, outside any project) and immediately update `EffectiveShortcut`, toolbar tooltips/labels, the desktop menu bar (`ApplicationMenu`), Command Palette (`CommandPaletteView`), runtime key bindings, and the **`⌘/` Keyboard Shortcuts sheet** (`ShortcutsSheetView`, `CmdShortcutsSheet` / `mod+/`). - **Live language switching**: `Language` accepts `LanguageSystem` (`"system"`), `LanguageEnglish` (`"en"`), or `LanguageChinese` (`"zh"`). Calling `Editor.SetLanguage` or picking a language on the **General** page under **`EDITOR · THIS COMPUTER`** in the unified **Settings** view (`SettingsView` / `EditorSettingsDialogView`, opened from the toolbar's **Preferences** button, `File > Editor Settings...`, or `mod+,`) updates the toolbar, desktop menu bar, file browser, asset browser, scene tree, layers, inspector, bottom panels, dialogs, command palette, and status bar immediately without restarting. `Editor.ResolvedLanguage()` reports the active locale (`"en"` or `"zh"`) and is exposed to connected MCP agents through `selection_get`. - **Appearance (`core.Scope.SetAppearance`)**: `Appearance` accepts `AppearanceSystem` (`"system"`), `AppearanceLight` (`"light"`), or `AppearanceDark` (`"dark"`). `Editor.SetAppearance` applies the choice immediately via NSGo's `core.Scope.SetAppearance` (keeping the editor dark even on a light system, or light on a dark system) and persists it to `Editor.SettingsPath` when set, so the choice survives restarts. - **Plugin localization**: plugins may attach a `Catalog *l10n.Catalog` or versioned `LocaleYAML [][]byte` string tables (`RegisterPlugin` validates them strictly) and set optional `TitleKey` / `LabelKey` / `DescriptionKey` / `CategoryKey` on their panels, tools, and commands. Inside `Panel.View` and `Inspector.View`, plugins call `Editor.PluginT(pluginName, key, args...)` and `Editor.PluginPlural(...)` so all plugin UI follows the editor's active language live. ## 2D skeletal rig editor (#886) The editor opens, edits, previews, saves, and places version-1 `.skel.yaml` 2D skeletal rigs (`game/skeletal`) directly through `RigPanelView` below the viewport: - **Opening and lossless round-tripping**: select any `*.skel.yaml` or `*.skel.yml` file in `FilesView` and double-click it or press **Open Rig** (`OpenRigProjectFile`, `OpenRigFile`, `OpenRigYAML`), or start a fresh rig with `NewRig`. Opening and saving an existing rig without edits (or after undoing every edit back to the opened state) writes back the exact original bytes unchanged (`SaveRigYAML`, `SaveRigFile`, `Editor.OnSaveRig`); edited rigs serialize deterministically via `skeletal.Encode`. - **Interactive rig canvas and handles**: `DrawRigViewport` renders attachments through the runtime `skeletal.Skeleton.Draw` beneath the bone hierarchy and interactive handles: - **Bone Move (`RigHandleBoneMove`)**: drag a bone's joint circle to move it in its parent's local space (in Bind Pose) or key its `translate` offset at the current playhead when an animation is active. - **Bone Rotate (`RigHandleBoneRotate`)**: drag the rotation ring around a bone to rotate it (bind pose or active animation `rotate` keyframe). - **Bone Length (`RigHandleBoneLength`)**: drag the tip diamond to set `BoneData.Length`. - **Attachment Origin (`RigHandleAttachmentOrigin`)**: drag the pivot crosshair on the selected slot's active skin attachment to adjust `OriginX` and `OriginY`. - Every handle drag (`BeginRigDrag`, `BeginRigHandleDrag`, `UpdateRigDrag`, `EndRigDrag`) commits as one undoable `Editor.History` step, and `CancelRigDrag` (or pressing `Escape` during a drag) restores the pre-drag snapshot without touching history. - **Bones, slots, skins, and attachments**: add (`AddRigBone`), rename (`RenameRigBone`), delete (`DeleteRigBone`), move/rotate/scale (`MoveRigBone`, `RotateRigBone`, `ScaleRigBone`, `SetRigBoneLength`), and reparent bones (`ReparentRigBone`, optionally preserving bind-pose world transforms and refusing cycles); add, delete, rebind, fade, and reorder draw slots (`AddRigSlot`, `DeleteRigSlot`, `SetRigSlotBone`, `SetRigSlotAlpha`, `MoveRigSlotOrder`); manage skins (`AddRigSkin`, `DeleteRigSkin`, `SelectRigSkin`) and attach atlas frames with origin pivots (`AttachRigFrame`, `SetRigAttachment`, `SetRigAttachmentOrigin`, `SetRigAttachmentTransform`, `RemoveRigAttachment`). - **Timeline, playback, and crossfade preview**: create animations (`AddRigAnimation`, `DeleteRigAnimation`, `SelectRigAnimation`, `SetRigAnimationDuration`, `SetRigAnimationLoop`), key bone `translate`, `rotate`, `scale` and slot `attachment` and `alpha` tracks (`KeyRigBoneTranslate`, `KeyRigBoneRotate`, `KeyRigBoneScale`, `KeyRigSlotAttachment`, `KeyRigSlotAlpha`, `DeleteRigBoneKeyframe`, `DeleteRigSlotKeyframe`), scrub (`SeekRig`), play (`PlayRig`, `PauseRig`, `StopRig`, `StepRig`), and preview crossfade blends (`CrossfadeRig`, `RigBlending`) directly through the runtime `skeletal.Skeleton` (`RigSkeleton`). - **Placing rigs in scenes**: press **Place in Scene** (`PlaceOpenRig`, `PlaceRig`) to add a scene object carrying the built-in `"skeletal"` component (`sceneformat.SkeletalComponent`, `version: 1`, `rig`, `atlas`, `skin`, `animation`, `loop`). `sceneformat.Build` loads the rig through `SkeletonResolver` or `FileResolver` (`FSAssets`), builds a live `BuiltObject.Skeleton` with the chosen skin and animation, draws it in exact Z order in both `BuiltScene.Draw` and the 2D editor viewport, and advances it in `BuiltScene.Update(dt)`. `refs.Scan` tracks `components.skeletal.rig` (`refs.FieldSkeletalRig`) so `MoveFile` rewrites rig paths across scenes automatically. ## HUD and menu layout screen (#1047) Open the HUD and menu layout screen (`HUDLayoutView`) via the toolbar's **HUD** button, `Project > HUD & Menu Layout`, Command Palette (`mod+shift+u` / `CmdHUDLayout`), double-clicking or opening any `*.screen.yaml` file in the file browser, or clicking a screen diagnostic in the Problems panel (`OpenHUDScreen` / `OpenHUDScreenFile` / `OpenHUDScreenDoc`). Styled strictly with the editor's design spec tokens (`docs/design/editor/HUDLayout.dc.html` and `Spec.dc.html`), it previews every screen size and project language side by side while keeping manual layout edits focused and undoable: - **Header and Language switcher**: displays the ` / screens / ` breadcrumb (with a back button returning to the scene editor), a **Language** segmented control listing every locale from `locales/*.yaml` (and any unsaved `Editor.l10n` workspace edits) via `SetHUDLocale`, **Search ⌘K**, and **Play**. Switching languages immediately redraws all four screen sizes, the text-width table, the inspector's localized values and overflow zoom, and **GAME CHECK**. - **Left rail (`SCREENS` and `NODES`)**: lists all project `*.screen.yaml` files (`HUDScreens`) with each screen's node count and active-language problem count, plus the active screen's hierarchical node tree (`HUDTree`) with monospace anchor tags (`TL`, `TC`, `TR`, `CL`, `C`, `CR`, `BL`, `BC`, `BR`, `FILL`) and red problem dots. - **Four simultaneous device frames and overlays**: draws the active screen at **Phone 19.5:9 with a notch** (`780 × 360`), **Tablet 4:3** (`640 × 480`), **Desktop 16:9** (`640 × 360`), and **Ultrawide 21:9** (`840 × 360`) at once through real `gameui.BuildScreen` layout (`HUDLayoutFrames`), with switches for **Safe areas**, **Anchors**, **Touch areas**, and **Focus order** (`HUDOverlays` / `ToggleHUDOverlay`), plus a floating **TEXT WIDTH, PX** table (`HUDTextWidths`) comparing each text node's box width against its measured width in every locale with overflows highlighted. - **Inspector, zoomed overflow detail, and `GAME CHECK`**: inspects the selected node's **ANCHOR** (a 3×3 grid of buttons plus **Fill**, anchor and offset in words, and **Keep inside the safe area**), **SIZE** (**Fixed** / **Fit text** toggle and touch target size), **TEXT** (key, every locale's value, and a `1.5×` zoomed overflow detail card when localized text spills past its box), and live **GAME CHECK** diagnostics backed by `gameui.CheckScreen` (`HUDProblems`) with **Show** buttons to select offending nodes, **Ask the agent to fix N**, and an empty `"No problems at any size in this language"` state when clean. - **Manual edits and agent composer**: reordering children inside a container (`ReorderHUDNode`), adjusting container spacing (`SetHUDNodeSpacing`), changing anchor/safe-area/sizing (`SetHUDNodeAnchor`, `SetHUDNodeSafeArea`, `SetHUDNodeSizeMode`), and directly dragging touch controls (`BeginHUDTouchDrag`, `UpdateHUDTouchDrag`, `EndHUDTouchDrag`, `CancelHUDTouchDrag`) each record **one undo step** in `Editor.History` and write canonical YAML back to the `*.screen.yaml` file on disk (restored verbatim on Undo). A bottom composer (`SubmitHUDPrompt`, `AskAgentToFixHUDProblems`, `Editor.OnHUDPrompt`) forwards broader HUD changes to the agent. ## Cutscene timeline and agent review (#1056) Opening any `*.cutscene.yaml` / `*.cutscene.yml` file (from the file browser, Command Palette, `OpenCutsceneProjectFile`, `OpenCutsceneFile`, `OpenCutsceneYAML`, or an agent `cutscene_write` MCP call) opens the full-workspace cutscene timeline editor (`CutscenePanelView`), styled strictly with `Spec.dc.html` design tokens and laid out from Screen 2 of `docs/design/editor/Animation.dc.html`: - **Left rail (`CUTSCENES` and `LINES`)**: lists every project cutscene (`ProjectCutscenes`) with its length or `video` kind marker, plus every localized dialogue line (`CutsceneLines`) resolved from `loc/en.yaml` and `loc/zh.yaml` (or `Editor.CutsceneCatalog` / the open Localization workspace) showing its line ID, English text, and Chinese text. - **Live preview stage and thumbnail scrub strip**: runs a live `cutscene.TimelinePlayer` against an isolated copy of the scene (`CutscenePreviewScene`, `SeekCutscene`, `PlayCutscene`, `PauseCutscene`, `StepCutscene`) so scrubbing to any timestamp poses actors, camera, and subtitle identically to runtime playback. Displays the active camera caption (`CutsceneCameraLabel`), localized subtitle overlay (`CutsceneActiveDialogue`), Play/Pause transport, time readout, and a 24-frame clickable thumbnail strip (`CutsceneThumbs`). - **Track lanes and clip inspector**: displays ordered lanes for Camera, each actor, Dialogue, Sound, and Music tracks with positioned clip blocks. Selecting a clip (`SelectCutsceneClip`, `SelectCutsceneClipByID`) inspects and edits **Start** and **Duration** with `±0.1 s` steppers (`AdjustCutsceneClipStart`, `AdjustCutsceneClipDuration`, `SetCutsceneClipTiming`) and **Easing** (`Linear`, `In`, `Out`, `In-out`, `Hold` via `SetCutsceneClipEasing`) on camera and actor tracks. Selecting a dialogue clip displays its line ID, English and Chinese text, and the reminder that text lives in `loc/en.yaml` and `loc/zh.yaml` while the cutscene stores only the ID. - **Agent review mode (`OpenCutsceneReview`)**: compares the original cutscene (`Before`) against the agent's proposal (`After`) without overwriting the file on disk until accepted. Supports toggling **Before** / **After** (`SetCutsceneReviewViewMode`) or holding **B** to peek at Before (`SetCutsceneReviewPeekBefore`, `CutsceneHandleKeyEvent`), marks added and changed clips with dashed line styles (`added` green dashed, `changed` amber dashed, `selected` blue solid) alongside the legend, lists `N CHANGES` with per-change **Revert** / **Restore** (`ToggleCutsceneReviewChange`) and click-to-focus (`FocusCutsceneReviewChange`), lets manual clip edits join the active review with `⌘Z` undo (`"Your edit joins this review · ⌘Z undoes it"`), offers **Revert all** (`RevertAllCutsceneReview`), and commits the remaining kept changes and joined edits on **Keep N of M** (`KeepCutsceneReview`) in **one atomic undo step** (both in memory and on disk). ## Changes and commit panel (#1057) Open the full-window **Changes and commit** screen (`ChangesPanelView`) from the status bar's **Changes** entry (showing the live working-tree changed-file count), `Project > Changes & Commit`, or Command Palette (`CmdChanges` / `OpenChangesPanel` / `CloseChangesPanel`), matching `docs/design/editor/VersionControl.dc.html` (screen 1) using only `Spec.dc.html` design tokens: - **Branch switcher, upstream status, and Pull**: the header displays ` / `, a branch switcher dropdown (`GitSwitchBranch`) showing the active branch plus ahead/behind counts (`ahead N`, `behind M`), **Refresh** (`RefreshChanges`), **Pull** (`GitPull`, fast-forward only), and **Play**. - **CHANGES grouped by category**: working-tree changes against `HEAD` (`git status --porcelain=v1 -uall`) group under **SCENES**, **DATA**, **CODE**, and **ASSETS** (`ChangesCategory`), each file carrying an include checkbox (`SetChangeIncluded`, `ToggleChangeIncluded`), status badge (`M`, `A`, `D`, `R`), and a concise detail line (`4 added · 3 changed objects`, `+7 -4 lines`, or audio duration and file size). - **Per-file comparison with `HEAD` in the Review layout**: - **Scenes (`*.scene.yaml` / `*.scene.yml`)**: compares `HEAD` (`git show HEAD:`) with the working tree via side-by-side **HEAD** and **Now** 2D scene previews (plus single-view **HEAD** / **Now** toggles via `SetChangesSceneView`), outlining added objects in dashed green, changed objects in dashed amber, and removed objects in dashed red, with per-object change badges (`added · ...`, `changed · Door (x 584 → 560)`, `removed · ...`). - **Data and Go code**: displays the latest `nsgo check` and `nsgo test` status and relative timestamp (`RunChangesChecks`, injectable via `Editor.ChangesCheckRunner`) above a color-coded unified line-by-line diff (`git diff HEAD -- `, or full `+` lines for untracked files) and an **Open in editor** button (`OpenChangedFileInEditor`). - **Audio assets**: renders a playable audition card (`AuditionChangedAudio`, `StopChangedAudio`) with duration, format/sample-rate metadata, a 60-bar waveform, and incoming references (`Used by ...`) gathered from the project reference index and scene objects. - **Selective commit card and History milestones**: drafts a commit summary and description from the included files, review/playtest context (`SetChangesContext`), and checks via `Editor.CommitMessageDrafter` or deterministic `DefaultCommitDraft` with **Redraft** (`RedraftCommitMessage`), editable summary and description inputs (`SetCommitSummary`, `SetCommitDescription`), `"Made from N agent requests, reviewed and kept"` attribution when present, included `+/−` line counts, **Commit** (`CommitSelectedChanges`), **Commit and push** (`CommitAndPushSelectedChanges`), and **Push N commits** (`PushCommits`). Committing stages and commits **only** the checked files (`git add -A -- ` + `git commit --only -m ... -- `), leaving every unchecked file untouched and uncommitted, and records a `CommitMilestone` in `Editor.History` (`History.Milestones` / `CommitMilestones`). Nothing is ever committed or pushed automatically without user action. - **SHARE**: **Copy as PR description** (`CopyPRDescription` / `BuildPRDescription`, writing structured Markdown with summary, changed files, checks, and playtest numbers via `core.Scope.SetClipboard` or `Editor.ChangesClipboard`) and **Open pull request** (`OpenPullRequest`, enabled when `gh` is on `PATH` or `Editor.GHRunner` is set). ## Scene merge conflict resolution (#1059) When Git leaves an unmerged scene file (typically produced by the object-by-object `go tool game merge` driver from #1058), opening the project (`OpenProject`), pressing the status-bar conflict pill, or invoking `Project > Resolve Scene Merge Conflicts` (`CmdMergeConflicts` / `OpenMergeConflict`) opens the full-window **Scene merge conflict** screen (`MergeConflictView`, styled strictly with `docs/design/editor/Spec.dc.html` tokens matching `VersionControl.dc.html` screen 2): - **Header and progress**: displays `Merging into · N of M objects need you` (updating to `ready to finish` once every conflict is resolved), **Abort merge** (`AbortMerge`, running `git merge --abort` to restore the branch and working tree cleanly), and **Finish merge** (`FinishMerge`, enabled only once every conflict is resolved). - **Conflicts and MERGED BY ID**: groups `sceneformat.MergeResult.Conflicts` object by object under **CONFLICTS**, each row showing a status dot, object name, `Unresolved` / `Agent` / `Mine` / `Theirs` / `Custom` chip, and a plain-language summary (such as `Both moved it: x 560 here, x 600 on main` or `Your speed change; main deleted it`). Objects joined cleanly without conflicts appear under **MERGED BY ID** with which side added or changed them. **Take the agent's suggestion for all N** (`TakeAllAgentMergeSuggestions`) resolves every conflict in one click. - **MINE, THEIRS, and RESULT previews**: displays clickable **MINE** (branch, author, short commit SHA) and **THEIRS** 2D scene preview canvases over a larger **RESULT** canvas. Unresolved objects render at both Mine and Theirs positions with dashed amber outlines so overlapping moves are immediately visible; selecting a resolution updates **RESULT** live. - **Agent's suggestion, Mine, Theirs, and hand-edited YAML**: the right inspector shows three selectable cards for the focused object — **Agent's suggestion** (from `Editor.MergeSuggester` or deterministic `DefaultMergeSuggestion`, combining non-conflicting fields from both sides or explaining why a deletion or higher `z` holds), **Mine**, and **Theirs** — each with its YAML snippet and reason. **Edit the result YAML by hand** (`SetMergeCustomEditing`, `ApplyMergeCustomYAML`) validates custom object YAML with `KnownFields(true)` and `sceneformat.Validate` before applying it. - **Verification and merge commit (`FinishMerge`)**: writes canonical `sceneformat.Encode` YAML to the scene path, runs `game check` (`runProjectCheck` or `Editor.MergeCheckRunner`) and a short 10-second deterministic playtest (`sceneformat.Build` + `Update` + `PhysicsScene.Step` or `Editor.MergePlaytestRunner`), refuses to commit if either fails, and otherwise stages the scene and creates the Git merge commit (`git add` + `git commit --no-edit`), reporting `Merged as ` and reloading the resolved scene into the editor. - **MCP tools (`editormcp`)**: `merge_status`, `merge_resolve`, `merge_finish`, and `merge_abort` let coding agents inspect conflicted objects, supply or refine suggestions and reasons, apply choices or custom YAML, and finish or abort merges. ## Find usages and safe rename (#1041) Pressing `Shift+F12` (`CmdFindUsages`), choosing **Project > Find Usages** from the menu bar or Command Palette, right-clicking a file in the file browser (**Find Usages** / **Rename Safely…**), right-clicking an instanced scene or prefab object in the scene tree (**Find Usages**), or calling `OpenUsagesScreen(path)` opens the full-window **Find usages and safe rename** screen (`ReferencesScreenView`, styled strictly with `docs/design/editor/Spec.dc.html` tokens matching `References.dc.html`): - **Grouped usages (`FindUsages`)**: shows **Back to the editor** (`Esc`), `"Usages of "`, and `"N usages in M files"`, grouped into **SCENES** (each instanced object with its position and override count), **PREFAB VARIANTS** (files with `inherits:` targeting the file), **DATA TABLES** (rows referencing the path), and **GO CODE** (string literals and constants parsed from project `*.go` files via `go/parser` + `go/ast`, marked `not rewritten`). `↑`/`↓` moves through usages, clicking a scene card focuses that scene's instances on a plotted thumbnail grid, and `Enter` opens the scene with the referencing object selected and framed. - **Safe rename review (`PreviewSafeRename` / `StartSafeRename` / `SetSafeRenameInput`)**: pressing **Rename…** (`F2`) shows a **NEW NAME** field between the fixed folder prefix and compound file suffix, validating live against `game mv` / `MoveFile` path rules (non-empty, safe relative path, free destination) and computing the exact dry-run rename plan without touching disk. The review lists the moved file (`"content unchanged"`), every rewritten YAML file with exact `−` (old) and `+` (new) line diffs showing preserved instance overrides, and every non-rewritten Go reference as a problem (`" loads the old path and is not rewritten"`) with **Ask the agent to update it** (`AskAgentToUpdateUsage`, invoking `Editor.OnAskAgentUpdateRef`) and **Open ``** (`Editor.OnOpenSourceFile`). - **One-step Keep and Undo (`ApplySafeRename` / `UndoSafeRename`)**: clicking **Keep · Rename N files** (`Mod+Enter`) writes only YAML through `MoveFile` as one undoable `Editor.History` step and enters the done summary with **Undo · ⌘Z** and **Back to ``**. One Undo restores every moved and rewritten file on disk byte-for-byte along with all open tabs. - **MCP tools (`editormcp`)**: `refs_find` returns the grouped usages across scenes, prefab variants, data tables, and Go code (optionally opening the screen), and `refactor_rename` prepares the same safe-rename review in the editor with exact planned diffs and non-rewritten Go warnings without silently mutating disk unless `apply: true` is passed. ## Material editor (#896) Assign and edit shared `*.material.yaml` resource files ([resource](https://game.nsgo.dev/docs/resources/)) directly inside the editor with live preview and full Undo/Redo: - **Assigning and creating materials**: in the Inspector, the searchable **Material** selector (`SetObjectMaterial`) picks from the open project's `*.material.yaml` files; **New Material** (`CreateObjectMaterial` / `CreateMaterialFile`) creates a new canonical `.material.yaml` file written with `resource.Encode`, assigns it to the selected object, and opens it; **Edit Material** (`OpenMaterial` / `OpenMaterialProjectFile`), double-clicking a material file or pressing **Open** / **Edit Material** in the file browser, picking a material in the Command Palette (`OpenProjectFile`), or invoking `Project > Material Editor` (`CmdMaterialEditor`) opens the docked `MaterialEditorPanelView` below the viewport. - **Every material field**: edits `name` (`SetMaterialName`), `baseColor` and `emissive` via NSGo `ColorWell` / `ColorPicker` popups and CSS color inputs (`SetMaterialBaseColor`, `SetMaterialEmissive`), `texture` via a searchable project image picker (`SetMaterialTexture`, `ProjectTextures`), `metallic`, `roughness`, and `opacity` via bounded sliders and numeric inputs (`SetMaterialMetallic`, `SetMaterialRoughness`, `SetMaterialOpacity`), `blend` from `resource.BlendModes()` (`SetMaterialBlend`), and `doubleSided` / `unlit` checkboxes (`SetMaterialDoubleSided`, `SetMaterialUnlit`). Invalid values are refused by `resource.Encode` without mutating state or history. - **Live preview and viewport sync**: the panel renders a live preview (`MaterialPreviewImage`, `SetMaterialPreviewShape`) as a 3D **Sphere** or **Cube** lit with `render3d` (respecting `unlit`, PBR metallic/roughness, emissive, texture, opacity, and double-sidedness) or a 2D **Sprite** preview (defaulting to Sprite in 2D view and Sphere in 3D view). Every edit—including color-picker drags and Undo/Redo—pushes the updated material live through `resource.Library.Reload` (using `project.Resolver.Library()` and `scenemodel.Assets.Library()`), updating the preview, every 2D sprite (`BuiltScene.SyncMaterials`), and every 3D viewport object using that material immediately before saving. - **Undo/Redo and deterministic save**: every edit goes through `Editor.History` (`EditMaterial`), tracks unsaved state (`MaterialDirty`, `HasUnsavedChanges`), follows file renames (`MoveFile`), and **Save Material** (`SaveMaterial`, `SaveMaterialFile`, `Save`, `SaveAll`, or `Editor.OnSaveMaterial`) writes the exact deterministic YAML produced by `resource.Encode`. ## Playtest report screen (#1044) Open the full-window **Playtest Report** screen (`PlaytestReportView`) from `Project > Playtest Report`, Command Palette (`mod+shift+y` / `CmdPlaytestReport`), the status-bar playtest badge, double-clicking any `*.report.yaml` file in the file browser, programmatically via `OpenPlaytestReport` / `OpenPlaytestReportFile`, or from an agent calling `playtest_report`. Styled strictly with `docs/design/editor/Spec.dc.html` color and contrast tokens (including `#101216` text on `#3B7BFF` primary accent buttons) matching `docs/design/editor/Playtest.dc.html`: - **Header and replay hand-off**: displays `"Playtest · "`, the project name and runs summary (such as `"20 headless runs by the agent · 1 m 40 s"`), **Watch run N** (`WatchPlaytestRun` / `WatchPlaytestRunIn`, which loads that run's saved `.replay.yaml` file through `replay.LoadFile`, starts Play mode with a live `*replay.Player` via `PlayReplayIn`, and provides a **Back to Playtest** banner), and **Ask the agent to tune it** (`AskAgentToTunePlaytest` / `Editor.OnPlaytestPrompt`). - **BOT PROFILE strip and `playtest_define` review**: shows the bot profile switcher/name (`BotProfileDisplayName`), `"playtest.yaml from template "` with **Open** (`OpenPlaytestConfigPreview` / `Editor.OnOpenPlaytestConfig`), and a one-sentence strategy. When the agent proposes a metric through `playtest_define`, a violet banner (`"Proposed with playtest_define: …"`) appears with **Review**, opening an inline unified-diff drawer to **Apply** or **Dismiss** without touching `playtest.yaml` on disk until accepted (`ApplyPlaytestProposal`, `DismissPlaytestProposal`). - **Metric cards**: displays each metric's label, a text-and-icon **Met** or **Missed** badge (never color alone), formatted value, foot line, and `"Goal · "` paired with its monospace source file (`brief.yaml`, `game.yaml`, or `playtest.yaml`). - **Automatic chart selection (all 4 chart kinds)**: `SelectPlaytestChart` and `DrawPlaytestChart` choose and render one canvas chart per report from the report's metrics: 1. **Heat map over the level** (`PlaytestChartHeatMap`) for deaths or time per tile, with clustered density blobs and hotspot callout chips. 2. **Bars per wave against a goal line** (`PlaytestChartBars`) with a dashed target line and flagged standout bars. 3. **Line per level** (`PlaytestChartLine`) for per-level progression curves with flagged spike/dip markers. 4. **Win-rate matrix** (`PlaytestChartMatrix`) with cells above the threshold (default 60%) flagged by border, marker, and `"above 60%"` label. - **Agent's read, actionable suggestions, and footnote**: presents a concise diagnostic read (`DefaultPlaytestAgentRead` or custom `SetPlaytestAgentRead`) and clickable suggestion cards (`RequestPlaytestSuggestion`) that dispatch requests coming back as reviews, above the footnote noting that runs use the replay system and that metrics and the bot come from `playtest.yaml`. - **MCP integration (`editormcp`)**: `game_playtest` loads freshly generated reports into the editor, `playtest_define` pushes pending proposals directly onto the Playtest Report banner with synced Apply/Dismiss handlers, and `playtest_report` lets the agent open, inspect, annotate, or watch runs from the report screen. ## Asset drawer (#1052) Switch the top of the left rail between **Scene** (`LeftRailScene`) and **Assets** (`LeftRailAssets`, also reachable via Command Palette `CmdToggleAssetsMode`) to browse, filter, preview, and drag every kind of project asset directly into the scene, styled strictly with `docs/design/editor/Spec.dc.html` design tokens and laid out from `docs/design/editor/Assets.dc.html` (screen 1): - **Left rail (`AssetsLeftRailView`)**: switches between **Scene** and **Assets** (`LeftRailSwitchView`), lists project **FOLDERS** with live asset counts (including empty asset directories such as `audio/music`), provides **SHOW ONLY** filters with counts (**Unused**, **Missing files**, **Generated**, **Proposed**), and includes a file drop zone (`"Drop files anywhere to import"`). **Unused** and **Missing files** are computed directly from `refs.Project.UnreferencedAssets` and `refs.Project.MissingAssets`. - **Drawer under the viewport (`AssetDrawerView`)**: offers kind tabs (**All**, **Sprites**, **Tiles**, **Audio**, **Fonts**), a live **Name or path** filter (`SetAssetDrawerQuery`), a sort toggle defaulting to recently changed (`SetAssetDrawerSort`), **Import** (`TriggerAssetImport` / `ImportAssetFiles`), and **Generate** (`TriggerAssetGenerate`). Cards display a checkerboard preview, a status badge (`new`, `Missing`, `Generated`, `Not used`), the asset name, and a meta line (such as `"6 frames · used 31×"`). The footer reports `"N assets · M shown"` and any missing-file problem (`"1 problem · door_open.png missing"`). Empty folders display `"audio/music is empty · Drop .ogg or .wav files here, or ask the agent."` and empty filter results display `"Clear a filter to see more assets."`. - **Drag to viewport (place snapped or swap sprite)**: dragging a sprite card onto empty space in the 2D viewport shows a snapped drop ghost and pill (`"coin.png new Sprite on Actors · snapped to 16 px"`) and places a new sprite object on the active layer in **one undo step** (`DropAssetAt`). Dropping a sprite onto an existing object swaps that object's sprite in **one undo step**, so one **Undo** restores the previous sprite. Pressing **Escape** (`CancelAssetDrag`) cancels the drag cleanly without mutating the scene. - **Selected asset panel (`AssetInspectorView`)**: displays a checkerboard preview with dimensions/format metadata, frame-by-frame playable clip controls (`SetAssetPreviewPlaying`, `SetAssetPreviewClip`, `SetAssetPreviewFrame`, `StepAssetPreviewFrame`) for multi-frame sprites, playable sound controls (`ToggleAssetAudioPreview`, `StopAssetAudioPreview`) with waveform preview for audio files, a compact **IMPORT** summary from `InspectAssetImport`, and **USED BY** listing every referring file and usage from `refs.Project.UsedBy` (clicking a reference opens it). Unused assets display `"Nothing references it. The agent can propose deleting it; deleting files always asks you."`, and missing assets offer **Replace with a file** (`TriggerReplaceMissingAsset` / `ReplaceMissingAsset`) and **Ask the agent** (`AskAgentAboutAsset`). ## Viewport Overlays menu and agent viewport images (#1040) In 2D edit mode (`ViewMode2D`), a floating bar at the bottom-center of the viewport (`docs/design/editor/Inspector.dc.html`, styled strictly with `Spec.dc.html` tokens) pairs zoom (`−` / `%` / `+`), **Snap**, and **Fit** with an **Overlays N** button showing the count of active overlays: - **`SHOW IN VIEWPORT` popover (`ui.Popover`)**: opens above **Overlays N** (also reachable via `View > Overlays` and `CmdViewportOverlays`) with a swatch, localized label, live count in the current scene, and `ui.Switch` for each overlay, plus the footer note *"The agent's screenshots use the same set: `viewport_overlays`"*: - **Collision shapes** (`collision_shapes`): registered non-trigger component shape fields (#882) and non-trigger 2D physics colliders. - **Triggers** (`triggers`): trigger/sensor/area component shapes and 2D physics trigger volumes (amber dotted outline). - **Connections** (`connections`): arched arrows from emitting object to handler object labelled `"event → handler"` (such as `"pulled → open"`) from the scene's `connections`. - **Patrol paths** (`patrol_paths`): enemy/actor patrol ranges and waypoint paths, built on the same `ViewportOverlay` registry that plugins use. - **Navigation** (`navigation`): built 2D navigation mesh polygons, portals, and `navregion2d` outlines (#888), kept in sync with `ShowNavMesh2D`. - **Camera bounds** (`camera_bounds`): scene camera bounds rectangle and `"bounds W × H"` caption (#884). - **Labels** (`labels`): compact object name/ID pills below visible objects. - **Custom plugin overlays (`ViewportOverlay`)**: plugins add custom overlays via `Plugin.Overlays` (or directly on an editor with `Editor.RegisterViewportOverlay`), supplying an `ID`, `Name`/`NameKey`, optional `Count` callback, and `Draw func(*Editor, *core.Drawing, *sceneformat.BuiltScene)` function. Active plugin overlays appear in the popover, `View > Overlays`, and `editormcp`'s `viewport_image`. - **Per-user persistence**: toggling any overlay (`SetViewportOverlay`, `ToggleViewportOverlay`, `SetViewportOverlays`) writes `viewportOverlays` to `Editor.SettingsPath` (`EditorSettings` YAML outside the project), never to any project or scene file, so choices survive restarts (including an explicit empty list `[]` when all overlays are turned off). - **Shared with `editormcp`'s `viewport_image`**: `Editor.DrawViewportWithOverlays(d, size, overlayIDs)` renders the exact same overlay set into `viewport_image`. Omitting `viewport_overlays` uses the editor's active overlays; passing explicit names (or `[]`) overrides them for that image without mutating editor settings. ## Inspector titled sections, field filter, scrub fields, Open YAML, and Ask to add (#1038) The object Inspector (`InspectorView`), styled with `docs/design/editor/Spec.dc.html` tokens matching `Inspector.dc.html`, `Main.dc.html`, and `Viewport3D.dc.html`, organizes object editing into compact collapsible sections while keeping every control backed by an `Editor` method and matching `editormcp` tool: - **Header and Open YAML**: displays a kind-colored swatch, object ID, kind-and-layer subtitle (such as `Sprite · layer actors`), and **Open YAML** (`FindObjectYAMLLine` / `OpenSelectedObjectYAML`), which locates the object's exact 1-based line in the scene YAML (reading the file on disk when clean so comments and formatting match, or `SaveYAML` when dirty), invokes `Editor.OnOpenFileAtLine(path, line)` when set, and reports `Opened :` in the status bar. - **Field filter (`InspectorFilter` / `SetInspectorFilter`)**: the **Filter fields** search bar narrows visible sections and fields by case-insensitive substring match against field labels, component names, and section titles (for example, filtering `speed` leaves only fields matching `speed`), auto-expanding matching sections and hiding non-matching ones. - **Titled collapsible sections and compact transform rows**: sections render in Spec section-header style (uppercase title, chevron toggle via `ToggleInspectorSection`, field count badge, e.g. `TRANSFORM`, `SPRITE`, `PATROL`, `HEALTH`), with Position and Scale laid out as compact `X Y` rows (plus `Z` in 3D, alongside 3D Rotation `X Y Z`), Alpha, and Z order. - **Scrubbable number fields**: dragging any number field's label (`BeginInspectorScrub`, `UpdateInspectorScrub`, `EndInspectorScrub`, `CancelInspectorScrub`) previews changes live in the viewport and records **one undo step** per drag; pressing `Escape` during a scrub cancels and restores the original value without touching history. In 3D view, holding `Shift` while scrubbing steps in `0.01` increments. Focused numeric fields support `↑`/`↓` stepping, `Shift` ×10 stepping, `Enter` commit, and `Escape` restore. - **Grouped Add component and Ask to add**: registered components the object lacks are grouped under `GAMEPLAY`, `PHYSICS`, and `AUDIO AND VISUAL` (`ComponentCategoryOf`, `AddableComponentGroups`). Beside the input, **Ask to add** (`AskToAddComponent`, `ComposerDraft`, `SetComposerDraft`, `Editor.OnComposerPrompt`) stages `"Add a component to that "` in the agent composer. - **Review and problem indicators plus footer**: fields with active agent review changes (`SetInspectorReviewChanges`) show an amber accent bar and `"was · in review"`; fields failing a project check or schema bound (`SetInspectorFieldProblems` / `Editor.Problems`) show a problem pill beside the control and on the section header. The footer reminds authors: `"Everything else about this object is in its YAML. Ask the agent, or open the file."` - **Matching MCP tools (`editormcp`)**: `object_set_field` edits any single object field, component field, or custom property through the same `Editor` commands as one undo step; `object_locate_yaml` returns an object's 1-based YAML line and snippet (optionally triggering `OnOpenFileAtLine`); and `scene_edit` `set` supports all 2D/3D inspector fields including `particles`, `model`, `gridMap`, `occluder`, `light`, and `camera`. ## Generated assets through MCP generator servers (#1053) Open the full-window **Generated Assets** screen (`AssetGeneratorView`) from `Project > Generated Assets` or the Command Palette (`CmdGeneratedAssets` / `SetAssetGeneratorOpen`). Styled strictly with `docs/design/editor/Spec.dc.html` tokens matching Screen 2 of `docs/design/editor/Assets.dc.html`, it connects to external MCP image and sound generator servers, checks returned candidates against the game's `brief.yaml`, and keeps generated output off disk until a person explicitly picks a candidate: - **MCP generator servers (`GENERATORS · MCP`)**: configure servers (`GeneratorServerConfig`, `SetGeneratorServerConfigs`) under **Settings › Tools** (`EditorSettingsDialogView`) and connect via `ConnectAssetGenerator` (any `mcp.Transport`, mirroring `ConnectRemote`) or `ConnectAssetGeneratorCommand` (stdio process on desktop). `AssetGenerators` lists every connected or configured server (`images` or `sound`) with live connection status. - **Untrusted output decoded in memory only**: `GenerateAsset` strictly decodes image payloads to raster pixels in memory (re-encoding clean PNG bytes, enforcing bounds, and refusing SVG/HTML/non-image payloads) and validates WAV (`audioconv.DecodeWAV`) or OGG audio in memory. Nothing is written to disk before **Pick**. - **Preview backdrops, `brief.yaml` style checks, and sound audition**: image candidates preview side-by-side with their reference asset on selectable backdrops (`PREVIEW ON`: Floor 3, Floor 1, Checker via `SetAssetGenPreviewBackground`) with pass/fail checks for **Palette**, **Pixel grid**, **Size** against the reference asset, and **Contrast** against the selected wall (`LoadAssetStyleBrief`, `SetAssetStyleBrief`). Sound candidates display waveform bars, duration, RMS loudness (`dBFS`), peak loudness check against the reference sound or brief target, and in-memory audition (`PlayGeneratedSoundCandidate`, `StopGeneratedSoundCandidate`). - **Atomic undoable Pick and provenance sidecar (`.source.yaml`)**: **Pick** (`PickGeneratedCandidate`) writes **exactly** the picked media file and its deterministic version-1 `.source.yaml` sidecar (`importsettings.AssetSource`, `AssetSourceVersion = 1`, schema `https://game.nsgo.dev/schemas/source.v1.json`) recording `version`, `generator`, `model`, `prompt`, `seed`, `references`, `license`, `commercialUse`, and `approvedBy` in **one undoable `Editor.History` step**; one `Editor.Undo()` removes both files cleanly. **Vary this** (`VaryGeneratedCandidate`), **Refine** (`RefineGeneratedAsset`), and **Regenerate N** (`RegenerateAsset`) re-invoke the generator with the same references without writing to disk. - **Export license gate (`LICENSES · CHECKED AT EXPORT`)**: `credits.ScanGeneratedLicenses`, `credits.CheckGeneratedLicenses`, `credits.Collect`, `releaseplan.Build`, `game release`, and the editor's Export panel (`CheckExportCredits`) scan every `*.source.yaml` sidecar in the project. Any generated file with an empty or unknown license (`license: ""` or `license: unknown`) blocks release builds with `*credits.UnknownLicenseError` naming the asset's path until resolved (for example via `SetGeneratedAssetLicense` / **Set license**). ## Focus ring and keyboard regions (#1003) Every interactive control in the editor carries the `docs/design/editor/Spec.dc.html` focus ring on keyboard focus and is reachable via `Tab`, `F6`, or arrows: - **Keyboard-only focus ring (`:focus-visible`)**: `EditorView` installs `SpecTheme()` (also returned by `FocusTheme()`), mapping `info`, `focus`, and `ring` to Spec accent (`#3B7BFF` in Dark, `#1D5CE6` in Light) while preserving Spec Dark and Spec Light surfaces. Buttons, toggle buttons, selects, checkboxes, and `SpecIconButton` / `SpecSwitch` draw a 2 px accent ring with a +2 px offset on keyboard focus only—mouse clicks never draw it. - **Inset rings and `:focus-within`**: tree rows (`SceneTreeView`, `LayersView`), list rows (`AssetBrowserView`, `FilesView`), text fields (`ui.Input`, `ui.NumberInput`), and F6-focused regions draw an inset `-2 px` accent ring via `SpecPalette.FocusRing(-2)` so scrolling parents never clip them. Selected and focused rows keep both their selection fill and the inset ring. Composer and card containers (`SpecFocusWithinCard`, `hud-composer-card`) draw the +2 px accent ring on the card via `:focus-within`. - **Fixed-order keyboard regions (`F6` / `Shift-F6`)**: `F6` moves to the next visible region and `Shift-F6` moves to the previous region in fixed Spec order: **Header** (`RegionHeader`) → **Scene tree** (`RegionSceneTree`) → **Viewport** (`RegionViewport`) → **Agent and Inspector** (`RegionInspector`) → **Status bar** (`RegionStatusBar`) → **Toast** (`RegionToast`, included only while a toast is active in `ToastView` via `Editor.ShowToast`). Entering a region via `F6` / `Shift-F6` draws its inset `-2 px` ring and restores the last control focused in that region. `F6` / `Shift-F6` are suppressed during shortcut capture and full-window screens, and close any open object context menu. - **Viewport focus is the selection**: the viewport canvas draws no focus ring of its own; while focus is in the viewport (`editor-viewport-frame`), `Tab` (`Editor.SelectNextObject`) and `Shift-Tab` (`Editor.SelectPreviousObject`) cycle through visible, unlocked scene objects in order. - **Dialog focus trapping and opener restoration**: editor dialogs (`EditorSettingsDialogView`, `ShortcutsSheetView`, `CommandPaletteView`, unsaved-changes prompt, scene path dialog, and save-conflict dialog) trap `Tab` / `Shift-Tab` inside the topmost modal (respecting shortcut capture in `Settings › Shortcuts`), block global shortcuts behind the modal except `⌘.` / `Ctrl+.` (`Editor.OnStopAgent`) to stop an active agent, and return focus to the exact control that opened the dialog when dismissed with `Esc` or an action button. - **Focus stability**: nothing moves focus automatically during an active drag or inspector scrub (`Editor.IsDragging`) or while typing in a text field (`Editor.IsTyping`). Showing a toast never steals focus, and `Editor.ShouldFocusAgentPrompt` returns `true` only when no drag or text input is active and focus is already inside the agent panel (`Editor.SetAgentPanelRef`). ## Connect an agent and status chip (#1009) Connect an external coding agent (Claude Code, Codex, or any MCP client on your computer) directly from the editor or with `go tool game mcp install`, matching `docs/design/editor/Connect.dc.html`, `docs/design/editor/AgentStates.dc.html`, and `docs/design/editor/Settings.dc.html` using exclusively `docs/design/editor/Spec.dc.html` tokens: - **One-time project install (`go tool game mcp install`)**: writes `.mcp.json` (Claude Code) and `.codex/config.toml` (Codex) idempotently in the project root while preserving existing unrelated servers and settings, and prints each file written or left unchanged. - **Connect dialog (`ConnectAgentDialogView`)**: reachable from `Project > Connect an Agent...`, Command Palette (`CmdConnectAgent`), `Editor Settings > Models and connections` (`+ Connect another agent or model`), or the Agent panel header. Offers three choices (**An agent on this computer** — Recommended, **Built in, with your API key**, and **No agent**), shows `go tool game mcp install` with a **Copy** button, displays `"Waiting for an agent to connect…"` which turns to `"Connected · over "` as soon as the first MCP client attaches, provides four starting permission checkboxes (**Edit scenes and data (always reviewable)**, **Run game check**, **Run headless playtests**, **Edit Go code** -> `AgentPermissionRules`), keeps the Agent panel closed when **No agent** is chosen, and provides **Later** and **Done**. - **Agent tab panel (`AgentPanelView`)**: switches the right sidebar between **Inspector** (`RightTabInspector`) and **Agent** (`RightTabAgent`, `CmdAgentPanel`), showing the thread of requests (including turns made by terminal-started MCP clients), streamed steps, and a labelled multi-line composer (`Enter` sends, `Shift+Enter` adds a line, plus **Send** / **Stop**). Composer requests run through `Editor.AgentRunner` (defaulting on desktop to `CLIAgentRunner`, invoking Claude Code's `--print --output-format=stream-json --verbose` or Codex's `codex exec --json` with the project's MCP configuration). - **Status chip (`AgentStatusChipView`)**: announces transitions through `core.LiveRegionPolite` and renders all five states while keeping manual tools working in every state: - `Connected · MCP` (hover tooltip names the agent and transport, such as `Claude Code over stdio`) - `Working · step n of m` (violet dot pulses on a `1.2 s` cycle, staying still when `ReduceMotion` is enabled) - `Waiting for you · m:ss` (clicking focuses the open request card) - `Reconnecting · try n of 5` (retries after `1, 2, 4, 8, 16 s` using injectable `Editor.AgentScheduleAfter`) - `Disconnected` with **Reconnect** and **Troubleshoot** (reopens Connect directly at the failed step rather than the start) - `Disconnected · offline` when the editor is offline. ## Play mode marks, rolling replay, and frozen-frame agent questions (#1042) While playing a scene in Play mode (`Play`, `PlayIn`, `StepPlay`, `PlayTick`) or connected to a running game, the editor keeps a rolling 60-second input recording, supports marking moments without stopping, lets you freeze any frame to ask the agent what looks wrong, and adds panic triage with one-click replay up to the panic frame (`docs/design/editor/PlayMode.dc.html`, styled strictly with `Spec.dc.html` tokens): - **Rolling 60-second input recording**: every fixed Play step samples `Editor.PlayInputSource` (watching `Editor.PlayInputActions` / `Editor.PlayInputAxes`, defaulting to the project's input actions in `game.yaml`) into a bounded 60-second sliding buffer (`60 × PlayRateHz()`, 3,600 frames at 60 Hz; `PlayRollingFrameCount`, `PlayRollingSummary` showing `"Last 60 s kept · N frames"`). Marking, asking, or hitting a panic atomically writes a version 2 `replay` YAML file under `replays/-.replay.yaml` (`SavePlayRollingReplay`, `PlayLastReplayPath`) that rebases older windows cleanly while preserving held actions and axis values entering the window. - **Play mode bar and marks (`alt+f` / `CmdPlayMark`)**: local Play mode renders a Spec-styled Play control bar (`playModeBarView`, keeping the 2D edit toolbar compact) with live/paused status pill, Pause/Resume (`mod+shift+p`, `SetPlayPaused`), single-frame **Step** (`.` while paused, `StepPlay`), time scale (`0.25×`–`2×`, `SetPlayTimeScale`), **Mark `⌥F`** (`AddPlayMark`), **Something looks wrong `⌘L`**, and **Stop**. Pressing `alt+f` marks the current frame without stopping Play, saves its `.replay.yaml` under `replays/`, pins a flag on the 60-second frame-time strip, and lists it under **MARKS · N** in the Inspector's **Agent** tab (`PlayInspectorTab`, `PlayMarks`) with time, frame, and `"replay attached"`. Stopping Play (`Stop`)—or clicking **Send marks now** (`SendPlayMarks`) earlier—bundles all unsent marks into **one thread** dispatched to `Editor.OnPlayMarksThread` and stored in `LastPlayMarksThread`. - **Frozen-frame questions (`mod+l` / `CmdAskFrozenFrame`) and MCP replay stepping**: pressing `mod+l` or **Something looks wrong** (`OpenAskFrozenFrame`) pauses Play, captures the frozen viewport PNG, and opens **"Ask about frame N"** with the frame preview, attachment chips, prompt field (`"What looks wrong? e.g. the slime walks through the wall"`), `"A fix comes back as a review"`, **Cancel**, and **Ask**. Submitting (`SubmitAskFrozenFrame`) saves the rolling replay, attaches the frame image and live entity snapshot, dispatches `Editor.OnAskFrozenFrame`, and switches to the **Agent** tab. Connected agents inspect the frozen frame through `editormcp`'s `play_frozen_context` tool and step the replay through `play_replay_step` (`AgentStepPlayReplay`), showing the viewport agent pill (`"agent stepping frames A–B"`) and step log (`"Stepped frames A–B with game_loop_step…"`) while keeping the game paused until the person resumes. - **Output panel panic card and Replay up to the panic**: `ParsePanicTrace` detects Go panic messages and stack traces in run output or recovered Play panics (`OutputPanic`, `SetOutputPanic`). `OutputPanelView` displays a Spec-styled panic card with the message, clickable `file:line` links for game stack frames, folded runtime frames (`"N frames in the game runtime · Show"` / `"Hide"`, `SetOutputPanicRuntimeExpanded`), **Ask the agent to fix** (`AskAgentToFixPanic`, `Editor.OnAskPanicFix`), and **Replay up to the panic** (`ReplayUpToPanic`, `ReplayUpToFrame`), which resets the scene (calling `Editor.OnPlayReset` when set), replays the saved recording through `PlayActiveInput()`, and stops and pauses at `panicFrame - 1` without triggering the panic. ## Permissions and MCP enforcement (#1010) The editor governs every mutating and running MCP tool call with a tracked, versioned YAML rules file, `permissions.yaml`, stored beside `game.yaml` (keeping `.nsgo/` git-ignored for editor-local state while teams share and review permission rules in Git): - **Three profile presets**: - **Cautious** (`cautious`): asks before every content edit, config edit, code edit, file creation, `game check`, and playtest, and denies deleting files or running shell commands. - **Balanced** (`balanced`, default when `permissions.yaml` is absent): edits content (`scenes/**`, `prefabs/**`, `data/**`) and runs `game check` and playtests on its own; asks before `game.yaml`, `brief.yaml`, `**/*.go`, and creating files anywhere; denies deleting any file or running shell commands. - **Autonomous** (`autonomous`): lets the agent complete whole tasks end to end while keeping reviewable undo steps; deletes and shell commands remain denied unless explicitly relaxed. - **First-match-wins rule table**: each rule matches an action (`edit`, `create`, `delete`, `run`, `code`) and slash-separated file globs (`scenes/**`, `**/*.go`, `**`) or run targets (`game check`, `playtests`, `shell`) to a decision (`allow`, `ask`, `deny`). Every evaluation (`Editor.EvaluatePermission`) records the exact rule index or profile that decided it. - **Settings › Permissions (`PermissionsSettingsView`)**: reachable via `File > Permissions...`, the Command Palette (`CmdPermissionsSettings`), or a blocked step link. Displays the three profile cards (retaining the active profile's name with a **Changed** badge when rules are edited from the preset), the reorderable rule table with an arrow-key-navigable **Allow / Ask / Deny** radio group per row, add/remove controls, and an **Agent on this page** rail with blocked-step links and pending approval cards. - **Blocked step links and Always toast**: a `deny` rule never invokes the MCP tool and records a blocked step whose link (such as `"Settings › Permissions · rule 7 of 7"`) opens **Settings › Permissions** with the matching rule focused. Answering **Always** on an `ask` card inserts an `allow` rule ahead of the asking rule, saves `permissions.yaml`, and shows the `"Always permission rule saved"` toast with **Show** and **Undo**. - **MCP-only scope**: rules govern the editor's MCP server tools only. External agent edits directly on disk continue to surface via the editor's disk watcher. ## Ask the agent in place (`⌘L`) and Agent panel (#1037) Pressing `⌘L` (`Ctrl+L` on Windows and Linux, registered as `CmdAskAgent` in `ScopeGlobal` with `core.KeyNotEditing`) outside any text field opens an anchored in-place composer (`AskInPlaceComposerView`, styled strictly with `docs/design/editor/Spec.dc.html` tokens matching `AskInPlace.dc.html`) directly beside the selected object(s) in the viewport: - **Anchored placement and clamping (`OpenAskInPlace`, `AskInPlacePlacement`, `ComputeAskInPlacePlacement`)**: anchors below the selection's viewport bounds (flipping above when near the bottom edge) and clamps strictly inside the viewport container so it stays on screen and never overlaps the right panel (Inspector / Agent panel). Without a selection, it anchors inside the viewport asking about the open scene. Pressing `Esc` (`CloseAskInPlace`) closes without sending and restores focus to the control that held it before `⌘L`. Pressing `⌘L` while typing in the Inspector or any text input is ignored. - **Announced selection chip, multi-line field, and contextual suggestions**: displays an accessible `RoleStatus` / `LiveRegionPolite` chip announcing the selection count and object names (for example `"2 selected · slime_01, slime_02"`), a real labelled multi-line input (`⇧↵` inserts a newline, `↵` or `⌘↵` sends), up to two contextual suggestions (such as `"Make them a prefab variant"` and `"Space them evenly"` for multi-selection) navigable with `↑`/`↓` and `↵` without blocking free typing, and the localized hint `"⌘L asks about the selection · ⌘K searches · right-click 'Ask the agent'"`. - **Context menu wiring**: choosing **Ask the agent about this** (`AskAgentAboutObject`) from either the viewport context menu or the Scene Tree context menu opens the same anchored composer for the target object (or the full multi-selection when the object is part of one). - **Agent panel and MCP context delivery**: sending starts an `AgentTurn` (`SubmitAskInPlace`) flagged `SkipPlan: true` (matching `Plan.dc.html`: *"Small edits with ⌘L skip the plan."*), attaches the selection's object IDs and names, the open scene path and YAML, and a rendered viewport PNG (`RenderViewportPNG`), switches the right rail (`RightRailView` / `RightRailTab`, toggleable with `⌘1` / `⌘2`) to the **Agent** tab (`AgentPanelView`) showing the turn with context chips, and notifies connected MCP clients through `editormcp`'s `editor://agent/turn` resource and `agent_turn_get` / `agent_turn_reply` tools. ## Background task list with queued and parallel agent requests (#1022) Requests, plan steps, and automations share one background task list in the Agent panel (`TasksPanelView`, styled strictly with `docs/design/editor/Spec.dc.html` tokens matching `Tasks.dc.html`), toggled from the status bar indicator (`status-tasks`), `View > Background Tasks`, or `CmdToggleTasks` (`mod+shift+t`): - **Task model and plain-text thread persistence (`AgentTask`, `AgentThreadDoc`)**: tasks move across five visible groups—**Needs you** (`TaskNeedsYou`), **Running** (`TaskRunning`), **Ready to review** (`TaskReadyToReview`), **Queued** (`TaskQueued`), and **Failed** (`TaskFailed`)—plus completed (`TaskDone`) and stopped/reverted (`TaskStopped`) states. Each project persists its task list in plain-text YAML under `.nsgo/threads/.thread.yaml` (`AgentThreadVersion = 1`, deterministic output, unknown fields and duplicate keys refused via `ParseAgentThread` / `EncodeAgentThread`, round-trip lossless). - **Queue vs Run in parallel (`SubmitTask`)**: - **Queue** (`TaskStartQueue`): waits behind the running or unreviewed turn and starts **only after** that turn is kept (`KeepTask`) or reverted (`RevertTask`), so queued requests always build on the reviewed scene. - **Run in parallel** (`TaskStartParallel`): starts immediately as a separate agent session with its own numbered overlay (`1`, `2`, …). - **Object holds in `editormcp` (`Server.ConnectTask`, `CompleteTaskTurn`, `ReleaseTaskHolds`)**: each parallel task runs on its own MCP session bound to its task ID. Editing an object (via `scene_edit`, `object_set_field`, object menu tools, or tile edit tools) holds that object for the task's active turn; another parallel session trying to edit the same object holds cleanly in FIFO order, updates its step and overlay to `"waiting on "` naming the holding task, and automatically resumes once the first task finishes its turn or releases holds—producing separate `TaskReview` entries per turn. - **Numbered overlays in the viewport and scene tree**: active tasks draw solid violet (`SpecPalette.Agent`) outlines with numbered pills (`1 placing the jump arc`) on objects they are editing and 45%-opacity dashed outlines with a clock glyph and `"2 waiting on slime_02"` pill on objects they are holding, paired with a compact bottom-left viewport legend and `"1 · editing"` / `"2 · holding"` badges on scene tree rows (`ObjectTaskBadge`, `SceneTaskOverlays`). - **Bulk dismiss and summary badge counts**: multiple **Ready to review** tasks can be checked (`ToggleTaskDismissSelection`) and dismissed together (`DismissSelectedTasks` / `DismissTasks`) without reverting anything that was kept. `TaskSummary` and `TaskDockBadgeCount` expose counts for `NeedsYou`, `Running`, `Blocked`, `ReadyToReview`, `Queued`, `Failed`, `MostUrgent`, and `DockBadge = NeedsYou + ReadyToReview + Failed` (excluding running and queued) for both the status bar (`No tasks`, `1 running · 0:38`, urgent-first mixed counts, persistent `Failed`) and downstream notifications/Dock badges (#1023). - **Matching MCP tools (`editormcp`)**: `tasks_list` lists tasks, active holds, and summary counts; `tasks_submit` queues or starts parallel requests; and `tasks_control` runs `keep`, `revert`, `dismiss`, `stop`, `retry`, `open`, `focus`, `allow`, or `deny`. ## Game brief and project rules (#1026) Settings (`EditorSettingsDialogView`, matching `docs/design/editor/Settings.dc.html` and styled exclusively with `Spec.dc.html` tokens) adds two shared project pages under **AGENT** that the agent reads before every request: - **Game brief (`brief.yaml`, `OpenBriefSettings`)**: edits the versioned `brief.yaml` file at the project root (`project.Brief`, `project.ParseBrief`, `project.EncodeBrief`, JSON Schema `https://game.nsgo.dev/schemas/brief.v1.json`) with labelled fields for **Pitch**, **Genre**, **Tags**, **Platforms**, **Art direction**, **Feel and difficulty** (including structured playtest targets readable via `playtest.TargetsFromBrief` / `playtest.ApplyBriefTargets` / `Editor.BriefPlaytestTargets`), and **Tone and audio**. Projects without `brief.yaml` show an empty state; filling and saving writes a canonical `brief.yaml` that round-trips byte-for-byte unchanged, unknown fields are refused with their 1-based line number (`loaderr`), missing sections appear as `"1 gap"` / `"N gaps"` in the sidebar, and every edit records an undoable step in `Editor.History` (`EditBrief`). - **Project rules (`AGENTS.md`, `OpenRulesSettings`)**: edits the plain Markdown `AGENTS.md` file at the project root (shared by Claude Code, Codex, and the built-in agent) in a monospace code field as undoable steps (`SetProjectRules`), showing the bulleted rule count (`ProjectRulesCount`) in navigation. Patterns of consistently reverted reviews (`RecordReviewOutcome` / `SuggestedProjectRules`) surface suggested rules (such as `"Suggested from your last 30 reviews: you reverted every change that moved the camera bounds."`); pressing **Add as a rule** (`ProposeSuggestedRule`) opens a reviewable diff card (**Keep** / **Revert**) without modifying `AGENTS.md` on disk until kept. - **Reviewable agent edits**: agent proposals through `editormcp`'s `brief_edit` and `rules_edit` queue pending `DocReview` cards (`ProposeBriefReview` / `ProposeProjectRulesReview`, `KeepDocReview` / `RevertDocReview`) without touching disk until kept; kept reviews apply as one undoable step in `Editor.History`. - **Agent on this page and Settings search**: both Agent pages render the right-hand **Agent on this page** card with a contextual note, clickable suggested asks, and an inline composer; clicking a suggested ask or submitting a prompt in the top Settings search bar calls `AskAgentFromSettings`, staging the page-contextualized prompt in `ComposerDraft` and invoking `Editor.OnSettingsAgentRequest` (and `Editor.OnComposerPrompt`). ## History panel: your edits and the agent's turns on one timeline (#1017) The History panel (`HistoryPanelView`), styled with `docs/design/editor/Spec.dc.html` tokens matching `AskInPlace.dc.html` and `Checkpoints.dc.html`, brings manual edits, kept agent turns, external Git reloads, and saved points onto one chronological timeline: - **Rich timeline entries (`History.Entries`, `Editor.HistoryEntries`)**: each `HistoryEntry` records who made the change (`HistoryAuthorYou`, `HistoryAuthorAgent`, or `HistoryAuthorGit`), a concise headline and detail (such as `You · moved Knight` / `x 416 → 452` or `Agent · slimes and coins` / `6 changes · kept 5`), the list of touched files, change/kept counts, and a timestamp driven by an injectable clock (`Editor.SetHistoryClock` / `History.SetClock`) for deterministic testing. Saving records a `HistoryEntrySaved` marker (`Saved · level_01.scene.yaml`) capturing the saved snapshot. - **Unified multi-file agent turns (`Editor.RecordAgentTurn`)**: groups scene, project, and extra touched project files under one undoable `History` step tagged as `HistoryAuthorAgent`, alongside automatic agent attribution for `editormcp` edits (`EnterAgentContext` / `LeaveAgentContext`), `KeepTileReview`, and `KeepCutsceneReview`. - **Opening and filtering**: press `⌘Y` (`Ctrl+Y` on Windows/Linux, `CmdHistoryPanel`), choose **View > History**, or click the toolbar history icon button (tooltip `"History · ⌘Y"`). Entries appear newest-first grouped by day (`TODAY`, `YESTERDAY`, or date) below a **Now** row marked `unsaved` when dirty, with **All** / **You** / **Agent** filter tabs (`Editor.SetHistoryFilter`). - **Read-only point-in-time preview (`PreviewHistoryEntry`, `ExitHistoryPreview`)**: clicking any timeline entry renders that step's snapshot read-only in the 2D and 3D viewports with a `"Previewing · editing is off"` banner, without mutating `Editor.Doc` or moving `History`'s undo cursor. Pressing `Esc`, **Back**, or **Now** exits preview cleanly. - **Non-destructive Restore (`RestoreHistoryEntry`)**: clicking **Restore** rolls the active scene, project, and every extra touched file back to that point as **one new undoable step** in `History`. Later steps remain in the timeline and can still be previewed or restored, and a single `Undo` returns immediately to the latest state. - **Agent read access (`editormcp`)**: the read-only `history_list` tool (`ActionRead`) exposes the same newest-first timeline to connected agents with optional `author` (`all`, `you`, `agent`) and `limit` filters plus unsaved and active preview metadata. ## Persistent per-turn checkpoints (#1018) Agent turns, autonomous tasks, and automations persist across editor restarts inside the project's `.nsgo/checkpoints/` directory and appear alongside session edits in the unified History panel (`⌘Y`, `CmdHistoryPanel`): - **Lazy first-write capture (`.nsgo/checkpoints/`)**: before an agent turn (`BeginCheckpointTurn` / `RunCheckpointTurn`, or any file-mutating `editormcp` `ActionEdit` tool call) first modifies a project file—scenes, prefabs, data tables, `game.yaml`, Go code, or verbatim binary media—the editor snapshots its pre-turn bytes under `.nsgo/checkpoints//files/` and writes a strict versioned YAML manifest (`manifest.yaml`, `editor.CheckpointVersion = 1`, JSON Schema `https://game.nsgo.dev/schemas/checkpoint.v1.json`). Files created by the turn record `existed: false` so restoring deletes them. `.nsgo/checkpoints/.gitignore` and `.nsgo/.gitignore` are written automatically so checkpoints stay ignored by Git, and `Editor.CheckpointMaxBytes` (default `128 MiB`) prunes the oldest completed checkpoints when total size exceeds the cap. - **Tasks and automations**: autonomous background tasks (`TakeCheckpointBeforeTask`, `RunTaskWithCheckpoint`, and `SubmitTask` runners) and automations (`TakeCheckpointBeforeAutomation`, `RunAutomationWithCheckpoint`, `game_playtest`, and automation-mode MCP edits) always persist a checkpoint before they start. - **Security and integrity**: checkpoint capture, writes, and restores strictly exclude `.git/`, `.nsgo/`, and all You-only configuration files (`MatchYouOnlyPath` / `CheckYouOnlyTarget`), refuse symlinks along every path component, cap manifest and file sizes (`2 MiB` / `32 MiB`), and verify both byte length and SHA-256 digests before writing. - **Unified History preview and one-step undoable restore**: `OpenProject` reloads persisted checkpoints into `HistoryPanelView` (`UnifiedHistoryEntries`). Clicking a checkpoint previews its scene snapshot read-only (`PreviewCheckpoint`), and **Restore** (`RestoreCheckpoint`) atomically restores every touched file on disk, synchronizes open tabs and `game.yaml`, and records one undoable step (`checkpointRestoreCmd`) so `Undo` (`⌘Z`) puts the entire turn back byte-for-byte. - **Matching MCP tools (`editormcp`)**: `checkpoint_list` (`ActionRead`) lists unified history and persisted checkpoints; `checkpoint_restore` (`ActionEdit`) evaluates permission rules (`edit`, `code`, `delete`) and You-only boundaries against every file recorded in the checkpoint manifest before restoring as one undoable step. ## You-only trust boundary and proposed deletions (#1015) Settings that govern what an AI agent is allowed to touch — **Permissions** (`permissions.yaml`), **Tools** (`tools.yaml` / `mcp.yaml`), **Models** (`models.yaml`), and **Usage** (`usage.yaml`) — follow the **You-only rule** (`docs/design/editor/Permissions.dc.html`, `Settings.dc.html`): - **Hard MCP refusal (`editormcp`)**: Every non-read tool on the editor's MCP server refuses any write, rename (including bare-stem `refactor_rename`), or deletion targeting a You-only file (`permissions.yaml`, `.nsgo/permissions.yaml`, `tools.yaml`, `models.yaml`, `usage.yaml`, or per-user `editor.yaml`, including through symlinks and case-insensitive host aliases), returning a structured `*editormcp.YouOnlyError` even when the active profile is `Autonomous`. - **Permissions draft card (`permissions_draft` / `PermissionsDraftCardView`)**: The agent can only submit a draft via `permissions_draft` (`Editor.SubmitPermissionsDraft`). The draft opens as its own modal `ui.Dialog` with focus trapping and opener focus restoration, showing each rule's `NOW → DRAFT` decision, a live `permissions.yaml · if applied` YAML diff preview, per-rule checkboxes with **nothing ticked by default**, **Discard draft**, and **Apply n rules**. `⌘↵`, **Keep all**, automations, and every profile (`Autonomous` included) cannot apply the draft. Applied rules are recorded in `History` as the person's (`HistoryActorPerson`) and can be undone byte-for-byte with `⌘Z`. - **External disk changes to `permissions.yaml` (`ReconcileExternalPermissions`)**: When `permissions.yaml` changes on disk outside the editor (a clone, `git pull`, or another tool), **tightened profiles and rules apply at once**, while **loosened profiles or rules** (such as changing `Balanced` to `Autonomous`, turning `Deny` into `Allow`, or removing a `Deny` rule) are **held** and not enforced until the person explicitly confirms each entry in **Settings › Permissions** (`ConfirmHeldPermissionLoosening` / `RejectHeldPermissionLoosening`). - **Proposed deletions that Keep all never applies (`game_delete_file` / `AgentReviewPanelView`)**: `game_delete_file` is off by default (`Editor.ToolEnabled("game_delete_file") == false`) and always proposes a deletion in the **Review changes** panel (`Editor.ProposeFileDeletion`) showing the file's exact line count (or binary summary), a red-tinted preview, and whether any scene uses it (via `Editor.FindUsages`), while refusing symlinks, `.git/**`, `game.yaml`, open scene tabs, and files above 1 MiB. **Keep all** (`Editor.KeepAllReviewChanges` / `⌘↵`) keeps the other changes and leaves pending deletion files untouched on disk; confirming in place (**Delete this file** / `Editor.ConfirmProposedDeletion`) deletes the file through a reversible checkpoint command (`deleteFileCmd`), and **`⌘Z` (`Editor.Undo`)** restores the file byte-for-byte. ## Toasts and feedback channels (#1004) Passing feedback in the editor uses one Spec-styled toast component (`ToastView`, `WindowToastView`, and `SpecToastCard`, matching `docs/design/editor/Toasts.dc.html` and `Spec.dc.html` using exclusively `SpecPalette` tokens). Decisions never go in a toast: permission asks and questions stay in Agent panel cards, check failures go to Problems, and finished agent turns open Review. - **Five kinds on one 40 px, radius 12, single-line pill**: - `ToastSuccess` (check-in-circle icon, `Added.Fg`), `ToastInfo` (`i`-in-circle icon, `TextMuted`), `ToastWarning` (triangle icon, `Warning.Fg`, on `Warning.Fill` and `Warning.Edge`), `ToastError` (circle-with-bar icon, `Removed.Fg`), and `ToastProgress` (progress ring + bottom 2 px bar + live percent). - At most one verb action button (with its shortcut hint, such as `Undo ⌘Z`) and a dismiss button on every kind except `ToastProgress`. - **Canonical Spec event API (`Editor.EmitToastEvent`, `ToastHandle`, `SpecFeedbackChannels`)**: screens emit typed `ToastEvent` values (`ToastEventReviewKept`, `ToastEventReviewReverted`, `ToastEventFixApplied`, `ToastEventAgentStopped`, `ToastEventPermissionSaved`, `ToastEventCopied`, `ToastEventDiskChanged`, `ToastEventSaveFailed`, `ToastEventExportRunning`, `ToastEventExportFailed`) instead of inventing ad-hoc tones, durations, or queue keys. `EmitToastEvent` returns a `*ToastHandle` so long-running work such as `export_panel.go` exports can update completion (`SetProgress`), transition in place into a success toast (`Complete`, e.g. `"Exported "` with **Show in Finder**) or persistent error toast (`Fail` with **Retry**), or cancel the running work (`Cancel`). - **Placement**: bottom center of the viewport, 8 px above the viewport bar (never over the scene tree, inspector, or agent panel). When no viewport is on screen (Start screen, Settings, Export, or other full-window views), `WindowToastView` anchors at the bottom center of the window, 24 px up. - **Queue, waiting badge, merging, and ordering**: one toast is shown at a time; others wait in FIFO order and the visible toast displays a `+N` waiting count badge. Repeating the same event merges into the existing queued entry in place without changing order, and nothing jumps ahead of an active error or running progress toast. - **Timing, pause, motion, and accessibility**: - `ToastDuration` enforces Spec lifetimes: success and info stay for 4 s (6 s with an action), warning stays for 8 s, and error and progress stay until retried, dismissed, canceled, or completed. Hover, touch, keyboard focus inside `RegionToast`, or the window leaving `core.LifecycleActive` (going to the background) pauses the countdown (`Editor.ToastTimerPaused`, `Editor.ToastRemaining`). - Enter motion fades in and rises 8 px over 180 ms; exit fades out over 120 ms. With `ReduceMotion` enabled, toasts appear and leave immediately with no fade or movement. - Both toast hosts are polite live regions (`core.RoleStatus`, `core.LiveRegionPolite`). Showing a toast never steals focus; `F6` / `Shift-F6` reaches `RegionToast`, `Tab` moves between its action and dismiss buttons, and `Esc` while focused dismisses the toast and restores focus to the control focused before entering the toast. - **Spec Feedback channels table (`SpecFeedbackChannels`)**: | Event | Channel | Action / Notes | | --- | --- | --- | | Review kept or reverted | Toast | `Undo ⌘Z` | | Fix applied from Problems | Toast | `Undo ⌘Z` | | Agent stopped with `⌘.` | Toast | `Review` | | “Always” permission rule saved | Toast | `Show` | | Copied a config, path or snippet | Toast | Info (routed from Connect, copy YAML, copy objects, web URL, PR description, diagnostics) | | A file changed on disk outside the editor | Toast | Warning · `Show` (routed from disk watcher reload) | | Save or export failed | Toast | Error · `Retry`, stays (explicit `⌘S` / Save and export failures only; failed autosaves stay in the status bar per `Checkpoints.dc.html` and never toast) | | Export running | Progress toast | `Cancel`, stays until done then turns into `"Exported "` with `Show in Finder` | | Agent asks permission or a question | Agent panel card | Never a toast | | Agent finished a request | Review opens | Never a toast | | Check failed, broken reference | Problems | Never a toast | | Agent asks, finishes or stops while the editor is in the background | + System notification | Paired with its in-editor channel | ## Agent automations (#1029) Project automations (`automations.yaml` beside `game.yaml`, schema `https://game.nsgo.dev/schemas/automations.v1.json`) let the agent run follow-up checks and tasks after a change while keeping every result reviewable (`docs/design/editor/Settings.dc.html`, `Tasks.dc.html`, `Checkpoints.dc.html`): - **Versioned YAML format (`AutomationsFile`, `ParseAutomations`, `EncodeAutomations`)**: `version: 1` with an ordered `automations` list of `{id, name, enabled, trigger, instruction}`. Unknown fields, trailing documents, duplicate keys, YAML anchors/aliases, duplicate IDs, and invalid trigger options are refused with `*loaderr.Error` line/column diagnostics; encoding is deterministic and round-trips byte for byte. - **Five triggers**: - `file_changed` (`glob`): fires when a matching project file is saved (manual save, autosave, or tab save), supporting `*`, `**`, and `?`. - `review_kept` (optional `glob`): fires when an edit review is kept (`KeepReview`, `EndReview(true)`, `KeepTileReview`, `KeepCutsceneReview`, `KeepAllReviewChanges`, `KeepAgentTurnReview`), skipping the originating automation ID to avoid recursion. - `file_added` (`kind`, optional `glob`): fires when a new file of kind `prefab`, `scene`, `tileset`, `cutscene`, `material`, `particles`, `rig`, `screen`, `datatable`, `script`, `asset`, or `any` is created (`NewScene`) or detected by disk watching (`PollDiskChanges`). - `before_export` (optional `platform`): fires before `StartExportBuild` or `StartReleaseBuild`. - `daily` (`time` in 24-hour `HH:MM`): fires once per calendar day at or after `time` while the editor is open (driven periodically by the UI scope scheduler and deterministically via `Editor.StepAutomations`). - **Pre-run checkpoints, permissions, background tasks, and Ready to review**: before starting any automation task, the editor snapshots tracked project text/YAML/Go files (excluding You-only and internal state files, bounded by file count and total size, skipping symlinks) into `.nsgo/checkpoints//` (git-ignored, inspectable via `AutomationCheckpoints`, restorable via `RestoreAutomationCheckpoint` with symlink containment checks). Each run executes under bounded concurrency with a timeout, under `WithAgentActor` and the project's permission rules (`Editor.Permissions` / `CheckAutomationActionPermission`), appears in the shared background task list (`TaskSourceAutomation`) and as an `AgentTurn` in **Ready to review** (`AgentReviewReady`) inside the Agent panel with **Keep**, **Dismiss**, and **Restore checkpoint** controls. `automations.yaml` and `.nsgo/automations-state.yaml` are protected by the You-only trust boundary (`YouOnlyAutomations`), and automations can never apply You-only drafts (`PermissionsDraft`, `AutomationDraft`), confirm held loosenings or proposed deletions, or keep/modify their own reviews (`ErrAutomationYouOnly`). - **Settings › Automations (`SettingsPageAutomations`)**: lists `WHEN → THE AGENT` cards with weekly run counts (`AutomationWeeklyRuns`, stored locally in git-ignored `.nsgo/automations-state.yaml`) and `SpecSwitch` (`core.RoleSwitch`) toggles, **+ New automation, in words** (`DraftAutomationFromWords` -> reviewable YAML card -> human **Keep** via `KeepAutomationDraft`), **Pause all automations for today** (`PauseAutomationsForToday` / `ResumeAutomations` — stops every trigger until the next calendar day), and the **Agent on this page** card, styled exclusively with `SpecPalette` tokens in Dark and Light appearances. ## Change-by-change agent turn review (#1014) When an agent completes a turn (`Editor.StartTurnReview`), the full-window **Review** screen (`ReviewScreenView`, `docs/design/editor/Review.dc.html`, styled strictly with `Spec.dc.html` tokens in both Dark and Light appearances) lets the author inspect every change across scenes, prefabs, data tables, and Go files one by one before keeping them in a single undo step: - **Header and blockers**: displays **← Editor** (`Esc`), the quoted agent request, an optional blocker warning pill (when a conflict, YAML error, or other blocker prevents keeping), **Revert all** (`⌘⌫` / `Ctrl+Backspace`), and **Keep N of M** (`⌘↵` / `Ctrl+Enter`). When any blocker is active, **Keep** refuses to commit and jumps focus straight to the blocking change (`JumpToReviewBlocker`). - **Grouped left list and filters**: pairs a live search input (`SetReviewSearch`, matching name, field, detail, or file path), a `"N of M seen"` counter with progress bar and Previous/Next buttons, and six counted filter chips (**All**, **Added**, **Changed**, **Removed**, **Unseen**, **Notes** via `SetReviewFilter`). Changes are grouped by **file** (path, `+n ~n −n` counts, fold toggle, **Revert file** / **Restore file**), then by **kind** (**ADDED**, **CHANGED**, **REMOVED** with fold and **Revert n** / **Restore n**), then one card per change with a seen mark, semantic kind mark, title, detail, and **Revert** / **Restore** (`X`). Focusing any change marks it seen. - **Keyboard scope (`ScopeReview`) and navigation**: registers `J` (`CmdReviewNext`), `K` (`CmdReviewPrev`), `X` (`CmdReviewToggleRevert`, toggling the focused change, kind group, or file group), `B` (`CmdReviewPeekBefore`, hold `B` to peek at the scene as it was before the request), `⌘↵` (`CmdReviewKeep`), and `⌘⌫` (`CmdReviewRevertAll`) in `ScopeReview`. Every control shows the Spec 2 px focus ring and is reachable via `Tab`, `F6` / `Shift-F6` (cycling Header → List → Preview → Why & YAML), or arrows; typing in the filter field never triggers single-letter shortcuts. - **Adaptive center preview**: - **Scene files**: renders the focused change's scene (`BuiltScene`) with clickable top-left overlay legend toggles (`ToggleReviewOverlayLegend`), draws unfocused changes at `1.5 px` and the focused change in its **own** semantic color and dash at `2.5 px` with an outlined pill (never Spec accent, which remains reserved for selection), draws reverted changes as they were before the request, frames each focused object on `J`/`K`, and shows `"Before this request"` while holding `B`. - **Prefab files**: shows before → after field values with numeric `Δ%` and computes where the change applies across both scenes in the current review and existing project scenes via `Editor.FindUsages`. - **Small data tables**: renders the table (`ReviewDataTablePreviewFor`) with changed rows highlighted and modified cells showing `old → new Δ%`. - **Right pane (Why + YAML)**: shows the agent's reason (**WHY**) above the line-numbered YAML lines touched by the focused change with `+` / `−` signs. - **Esc / Resume pending state**: pressing `Esc` (`PauseReview`) returns to the editor while leaving the review pending—the main viewport renders pending change overlays (`drawPendingReviewOverlay`) and the right-rail **Agent** tab (`AgentPanelView`) shows `"Review waiting · N changes, F files"` with seen count, blockers, and **Resume review** (`ResumeReview`), which returns to the exact same focused change and seen state. - **Keep, Revert all, and one-step Undo**: **Revert all** asks in a focus-trapped confirmation dialog naming every file that goes back and reminding that `⌘Z` / `Ctrl+Z` brings everything back. Both **Keep** (`KeepTurnReview`) and **Revert all** (`ConfirmReviewRevertAll`) execute as **one `Editor.History` step**, update saved YAML files and the open scene, show a Spec toast with **Undo**, and record `"Kept K · reverted R · one undo step"` in the Agent panel; a single `Editor.Undo()` restores every touched file byte for byte. - **MCP read access (`editormcp`)**: the read-only `review_status` tool (`ToolReviewStatus`, `ActionRead`) lets connected agents inspect which changes have been seen or reverted, overlapping conflict choices (`mine`, `agent`, `both`), hand-edited YAML fields and lines tagged `"you"`, active blockers, and keep/revert outcomes (including after Keep for round 2) without granting the agent permission to keep or revert the turn (unsent draft notes are never exposed, and `SceneAndData` / `GoSource` privacy rules are enforced). ### Review notes and second-round redo (#1031) Instead of reverting everything or hand-editing YAML when one or two changes need adjustment, authors can leave change-scoped notes on the active turn and have the agent redo only those changes as **Round 2** within the same review (`docs/design/editor/Review.dc.html`): - **Inline note composer (`C` / `CmdReviewNote`) and viewport pins**: pressing `C` on a focused change (or clicking its speech-bubble button) opens an inline note composer under the card (`"Note for the agent · not sent"`) with **Add note** (`CommitReviewNote`), **Revert and redo with this note** (`RevertAndRedoReviewChange`), and **Cancel** (`CancelReviewNoteComposer`, or `Esc`). Saved notes appear on the card with **Edit** and **Remove** (`RemoveReviewNote`) and as Spec-token speech-bubble pins beside noted objects in both the Review viewport and the paused 2D viewport (`ReviewViewportPins`). Notes live strictly in memory on the turn, are bounded in length and count, and are never written to any scene, prefab, or data file; a note added and removed before sending never reaches the agent. - **Send notes and noted-only redo (`SendReviewNotes`, `ApplyReviewRedo`, `editormcp`)**: clicking **Send N notes** in the header (which becomes the primary accent button while unsent notes exist) dispatches all remaining notes to the agent over MCP (`review_notes_get`), naming each change's `change_id`, `file`, `object`, `field`, `kind`, and `note`. The agent revises only noted changes within the same turn via `review_redo` (un-noted changes and tampered un-noted objects in the same file are refused, You-only/permission/privacy rules are enforced). Redone changes appear unseen again in Round 2+ with `"Redone from your note: …"` in **WHY** and `"Revised in round N. Your note: …"` on the card. - **Round tabs, banner, filters, paused card, and single-step Undo**: once Round 2 exists, the header shows **Round 1 | Round 2** tabs (`SetReviewViewRound`) and a banner below the filter chips (`"Round 2 · the agent redid only the N changes you left notes on. Both rounds keep and undo as one step."`). **Round 1** is read-only (`ErrReviewReadOnlyRound` on edit/revert/note attempts) and shows the agent's first version for comparison; **Keep** (`⌘↵`) always applies the **latest round** as **one `Editor.History` step**, so a single **Undo** (`⌘Z`) restores every touched file to its exact pre-request bytes. The **Notes** chip filters to changes with notes, the paused **Agent** panel card shows unsent note counts (`"N notes not sent"`), and the **Revert all** dialog warns that pending notes will be dropped. ### Review conflicts and in-place YAML hand editing (#1032) Inside the change-by-change Review screen, two cases block **Keep** cleanly without losing either the author's or the agent's work: - **Three-way conflict resolution (`syncReviewAfterMutate`, `SyncReviewPersonEdits`, `ResolveReviewConflict`)**: manual edits made through editor commands (`MoveObject`, `SetProperty`, `SetComponentField`, and so on) while a review turn is pending automatically three-way merge against the turn baseline and agent snapshot via `sceneformat.Merge`. Edits to **different fields** of the same object merge cleanly without asking; overlapping edits to the **same field or list** (such as appending to `door_1`'s `on_open` list) display both sides inside the change card with line authors (`you`, `agent`) and a **Mine / Agent's / Both** segmented control (`ReviewConflictMine`, `ReviewConflictAgent`, `ReviewConflictBoth`), where **Both** keeps both entries with **yours first**. Until every unresolved conflict is chosen, **Keep** is disabled (`*ReviewBlockedError` wrapping `ErrReviewBlocked`) with `"Choose how merges"`, and pressing **Keep** or the header blocker jumps straight to that change. - **In-place YAML editing and live viewport preview (`BeginReviewYAMLEdit`, `SetReviewYAMLDraft`, `FinishReviewYAMLEdit`)**: clicking **Edit** on any non-reverted added or changed scene object makes the right-hand YAML pane editable in place without losing text-input focus or firing single-letter Review shortcuts while typing. Drafts are bounded (256 KiB), strictly decoded with `KnownFields(true)`, checked for duplicate keys and `sceneformat.Validate` (and component registry rules), and checked against You-only boundaries. Valid edits update the Review viewport live (`ReviewEffectiveSceneDoc`) and tag hand-edited lines `you`. - **Parse errors, mechanical one-step fixes, and Undo my typing (`ApplyReviewYAMLFix`, `UndoReviewYAMLTyping`)**: invalid YAML (such as typing `x 444` without a colon) marks the failing scene line, surfaces `"Fix YAML on line N"` in the header blocker and `"Line N isn't valid YAML"` in the alert card, disables **Done** (`ErrReviewYAMLInvalid`) and **Keep**, offers verified one-step fixes when the parser names what is missing (**Add the colon**, **Close the quote**, **Add the closing brace**, **Add the closing bracket**, **Replace tabs with spaces**), and always provides **Undo my typing**. - **Single undo step and round-2 MCP visibility**: conflict merge choices and valid hand edits land with the turn in **one `Editor.History` step** (`KeepTurnReview`)—one `Undo` reverts the agent turn, merge choice, and hand edit together while preserving any concurrent manual edits made outside the review—and remain readable through `editormcp`'s `review_status` tool (`Editor.ReviewStatus`) tagged `"you"` for round 2. ## System notifications, Dock badge, and Play-mode dot for agent tasks (#1023) Agent tasks (both background tasks managed via `tasks.go` / #1022 and foreground Agent panel runs) reach the person outside the editor through NSGo's native notification and badge APIs (`core.Scope.ShowNotification`, `core.Scope.RequestNotificationPermission`, `core.Scope.OnNotificationPress`, and `core.Scope.SetBadge`), matching `docs/design/editor/Tasks.dc.html`, `docs/design/editor/AgentStates.dc.html`, and `docs/design/editor/Spec.dc.html` using exclusively Spec design tokens: - **Only three events notify**: **waiting for permission** (`TaskNeedsYou`), **ready to review** (`TaskReadyToReview`), and **failed** (`TaskFailed`), formatted with `"NSGo Editor · "`, the task title, detail, and primary action (`Allow once`, `Review`, or `Open`) with control-character sanitization and length bounds. Finished steps, queued starts, restored thread entries on load, and agent replies never send system notifications. - **Permission on first need and 30 s rule**: `cx.RequestNotificationPermission` is called only the first time a notification is actually needed (preserving macOS Dock badges before any notification permission check). When the editor window is in the background (`cx.Env().Lifecycle() != core.LifecycleActive`), all three events notify immediately; in the foreground, an unanswered waiting request notifies after `AgentWaitingNotifyDelay` (`30 s`) unless answered first. - **Click opens the task in its scene**: `cx.OnNotificationPress` (delegating to `Editor.HandleNotificationPress` / `Editor.OpenAgentTask`) brings the editor window to the front (also calling `Editor.OnFocusWindow` when set), stops Play if running, dismisses obstructing panels (Settings, History, Problem agent panel, Ask-in-place, Assets mode), switches to or safely opens the task's scene tab strictly confined inside the project root (refusing traversal and symlink escapes), opens the Tasks or Agent panel, and focuses the task and any open request card. - **Dock badge (`cx.SetBadge`)**: `Editor.AgentDockBadgeCount` counts waiting (`TaskNeedsYou`), ready to review (`TaskReadyToReview`), and failed (`TaskFailed`) tasks (`AgentTaskCounts.BadgeCount()`); running and queued tasks never add to the badge, and `0` clears it (including on scope cleanup). - **Play-mode corner dot and deferred notifications (`PlayTaskDotView`)**: while Play mode is active (`Editor.Playing()`), agent task notifications do not pop over the running game and are held (`Editor.HeldAgentNotifications`) until `Editor.Stop()` flushes any tasks still needing attention. A single 8 pt dot with a 3 pt halo stays stably mounted in the top-right corner of the viewport in the Spec color of the most urgent state (**Failed** `Removed.Fg` > **Waiting** `Warning.Fg` > **Ready to review** `Accent.Fg`), revealing its label pill (such as `"1 task needs you · stop Play to open"`) only on hover or keyboard focus. ## Live agent edits in the viewport and scene tree (#1013) While an agent edits a scene through `editormcp` or an active agent turn (`Editor.BeginAgentTurn` / `Editor.RunAsAgent`), the editor shows its pending changes live in both the viewport and scene tree (`docs/design/editor/Working.dc.html`, `Main.dc.html`, and `Spec.dc.html`) without ever moving the 2D or 3D viewport camera on the agent's behalf: - **Live viewport overlays (`ViewportLiveOverlays` / `VisibleViewportLiveOverlays`)**: - **Added**: 1.5 px dashed green outline (`SpecPalette.Added`) and `"+ "` mono pill. - **Changed**: 1.5 px dashed amber outline (`SpecPalette.Changed`) and `" → "` mono pill (also synced into the Inspector's amber review markers). - **Removed**: 25% grey ghost at the object's pre-turn bounds, 1.5 px solid red outline (`SpecPalette.Removed`), and a `" removed"` pill with the object's name struck through. - **Agent working**: 1.5 px solid pulsing violet outline (`SpecPalette.Agent`, 1.6 s pulse between 45% and 100% opacity, held solid at 100% under reduced motion) with no resize handles and a pill carrying the violet sparkle glyph and activity text (for example `playing level_01 headless`). - **Problem**: 2 px solid red outline and filled alert pill for object-scoped diagnostics. - Non-overlapping pill placement automatically stacks colliding pills vertically so adjacent objects stay readable. - **Selection coexistence and read-only step guard**: when the user selects an object the agent is actively touching (`Editor.BeginAgentStep` / `editormcp.Server.BeginStep`), the selection keeps its resize/transform handles and the agent outline sits 3 px further out (`OutsetPx: 6`). Until the agent's step moves on (`EndAgentStep`), manual edits to that object are refused with `ErrAgentTouchingObject` across the viewport, 2D/3D gizmos, inspector (which shows a violet read-only banner), scene tree (rename and reparent), context menu, and direct `Editor` mutation methods, while untouched objects remain freely editable. - **Scene tree markers**: added nodes show a `NEW` badge, changed nodes show a `MOD` badge, removed nodes remain visible as struck-through ghost rows with a `DEL` badge, and currently touched nodes display a violet agent-working dot until **Keep** or **Revert**. - **Header pill**: follows the agent's state (`Editor.SetAgentState` / `Editor.AgentState`): violet working pill (`"Agent is · manual edits stay available"`), warning waiting pill (`"Waiting for you · "`), pending-review pill with **Keep** (`KeepAgentTurn`, collapsing the turn into one undo step) and **Revert** (`RevertAgentTurn`, undoing the turn and restoring removed objects), and hidden while idle. - **Interactive top-left Overlay Legend**: appears automatically whenever live overlays are active (or when `OverlayLegendOpen` is true). Each row (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**) is a `RoleSwitch` toggle (`ToggleOverlayLegendKind` / `SetOverlayLegendKind`) persisted per-user in `EditorSettings.HiddenOverlayKinds` (`hiddenOverlayKinds` in `editor.yaml`, schema `editor-settings.v1.json`) without modifying project files. ## Agent threads per line of work, grouped by scene (#1019) The right rail (`RightRailView`) switches between **Agent** (`AgentPanelView` / `AgentThreadsView`), **Inspector** (`InspectorView`, the default tab), and **History** (`AgentHistoryView`), using `docs/design/editor/Spec.dc.html` tokens matching `Threads.dc.html` across Dark and Light appearances: - **One YAML file per thread under `.nsgo/threads/` (`AgentThread`, `AgentThreadFileVersion = 1`)**: each thread is persisted as a strict versioned YAML document at `.nsgo/threads/.yaml` (with `.nsgo/.gitignore` automatically ignoring the directory from git), storing `id`, `title` (named from its first request), `scenePath`, external agent `sessionId` (`SetAgentThreadSessionID`), timestamps, and chronological `requests` with `steps`, `outcome` (`pending`, `kept`, `reverted`), change counts, changed `objects`, and `historyStep` links. Parsed with `ParseAgentThreadYAML` and written canonically with `EncodeAgentThreadYAML` (JSON Schema `https://game.nsgo.dev/schemas/agent-thread.v1.json`). - **Grouped thread switcher, search, and `⌘N` (`AgentThreadGroups`, `CmdNewAgentThread`)**: the switcher groups threads under ` · OPEN SCENE`, other scenes (``), and `PROJECT · NO SCENE`, each showing relative age and state (`now · 3 changes to review`, `1 h ago · kept 5 of 6`, `yesterday · reverted`, or changed files). Opening or switching scenes enters that scene's most recent thread (or a fresh draft) and never carries another scene's thread along; `⌘N` (`ScopeAgent`) starts a new empty thread. - **Folded earlier requests, History link, and Jump to latest**: earlier reviewed requests fold to one line each (`N EARLIER REQUESTS`) and expand on click to show the full prompt, changed fields, steps, and **Open this step in History** (`OpenHistoryStep`), which opens the unified History timeline highlighted on that step. Expanding an earlier request surfaces a floating **Jump to latest** pill (`JumpToLatestAgentRequest`). - **Empty-thread view (`AgentAlwaysReadItems`, `AgentBriefSuggestions`)**: an empty thread lists what the agent reads with every request (` · whole scene`, `brief.yaml`, `AGENTS.md`, `Viewport image`) and up to three starter prompts read safely from the project's `brief.yaml` (`FROM YOUR BRIEF`). - **Inspector footer attribution (`LastAgentChangeForObject`, `OpenAgentRequest`)**: when a selected object was changed by a non-reverted agent request (via `SendAgentRequestWith`, `RecordAgentStep`, or `editormcp`'s `scene_edit`), the Inspector footer displays `Changed in “” · ` and clicking it opens that thread and expands that request. ## Viewport sketch layer for the agent (#1025) Draw session-only numbered annotations directly over the 2D viewport to point at empty places in a level before asking the agent to build them (`docs/design/editor/Sketch.dc.html`, styled exclusively with `docs/design/editor/Spec.dc.html` tokens): - **Four sketch tools in scene coordinates**: press `D` (`CmdSketchToggle`, or `View > Sketch`) to toggle Sketch mode without adding extra buttons to the compact 2D `editor-toolbar`. Switch between **Pen** (`P`, freehand polyline), **Arrow** (`A`, start → end), **Box** (`B`, rect), and **Text** (`T`, point + label) in `ScopeSketch`, or place a mark at the cursor with `I` (`CmdSketchAddMarkAtCursor`). Every mark gets a sequential numbered badge (`1`, `2`, `3`, …) and an optional label (such as `"3 spikes"`, `"platform, back and forth"`, `"locked until the lever"`). All geometry is converted through `CanvasToWorld` and stored strictly in scene coordinates so marks scale and pan accurately across zoom levels and are **never** written into `SceneDoc`, `*.scene.yaml`, or scene undo `History`. - **Sketch bar, Scene Tree row, and status bar**: the floating sketch bar displays the four tools, **Undo last mark** (`⌘Z` in `ScopeSketch`), **Hide / Show marks** (`H`), `"N marks not saved"`, **Clear**, and **Done**. Pressing `Esc` finishes sketch mode while keeping drawn marks until sent, cleared, or kept. The Scene Tree displays a compact `SKETCH LAYER` row (`N marks · not saved`), and the status bar shows live scene coordinates and the active sketch tool. - **Sending a sketch to the agent (`SendSketch` / `Editor.OnSendSketch`)**: the composer attaches a `"Sketch · N marks"` context chip (clicking toggles a `"Sent with this request"` scene-coordinate preview). Sending delivers `SketchAgentRequest` with structured marks (`number`, `kind`, geometry in scene coordinates, `label`) and a rendered PNG of the viewport with numbered marks overlaid (`RenderSketchViewportPNG`). - **Agent reading card & `scene_edit` confirmation hold**: sending a sketch arms a hold gate (`SketchHoldActive() == true`) that causes `scene_edit` and other mutating scene MCP tools to refuse edits until the person confirms. The agent reads marks via `sketch_read` and posts its restatement (`"I read your sketch as: …"` with numbered items and assumptions) via `sketch_reading` (`PostSketchReading`). Clicking **Go ahead** (`ApproveSketchReading`, `⌘↵`) releases the hold; clicking **Correct a mark** (`CorrectSketchMark`, `⇧M`, or clicking any numbered item) reopens sketch mode with that exact mark selected while keeping the hold active; replying in words (`ReplyToSketchReading`) works too. - **Review overlay & Keep / Revert**: after approval, agent edits open a review card (`SketchReviewOpen`) with a **Sketch overlay** toggle (`O`, `ToggleSketchReviewOverlay`, also available in `TileReview`) that lays the faint dotted sketch over the result. **Keep** (`KeepSketchReview` / `KeepTileReview`) keeps the edits and clears the sketch layer; **Revert** (`RevertSketchReview` / `RevertAllTileReview`) undoes the edits while keeping the sketch marks intact to send again. ## Reference images in the agent composer and pinning to the brief (#1027) Attach PNG, JPEG, or WebP reference images to a single agent request or pin them to the project's game brief, matching `docs/design/editor/Sketch.dc.html` (*Paste or drop an image*, *Pin to brief*) using exclusively `docs/design/editor/Spec.dc.html` tokens: - **Drop, paste, or pick PNG, JPEG, and WebP**: dragging files over the Agent composer shows the Spec-styled **"Drop to attach"** overlay (`SetAgentComposerDragOver`, `DropAgentReferenceFiles`); pasting an image or image files into the composer (`HandleAgentComposerPaste` via `core.Input.OnPaste`, or `PasteAgentReferenceImage`) or clicking the **Attach an image** button (`PickAndAttachAgentReferenceImages` / `CmdAttachReferenceImage`) validates actual PNG, JPEG, or WebP headers and pixels in memory (`DecodeAgentReferenceImage`). Unsupported file types (such as GIF, SVG, BMP, text, or corrupted images) are refused with the exact reason in an accessible error banner (`AgentAttachError`). - **One-shot chips with hover preview**: each attached image appears as a chip with a thumbnail, filename, **Pin to brief** button, and **×** remove button (`RemoveAgentReferenceImage`). Hovering or focusing a chip displays a floating preview card above the composer with the decoded image, format, dimensions, and scope (`Sent with this request only`). Submitting a request (`SubmitAgentPrompt`) delivers attached images in `AgentRequest.AttachedImages` and `AgentRequest.Images` (and records thumbnails on `AgentTurn.Images`), then clears the one-shot chips so the next request does not carry them. - **Pin to brief (`PinAgentReferenceImage`)**: clicking **Pin to brief** copies the image to `art/reference/` (disambiguating collisions without overwriting different files) and adds an entry under `art.references` in `brief.yaml` via YAML AST editing (preserving existing keys and comments) as **one atomic, undoable `Editor.History` step**. Both files immediately appear in Review / Changes (`RefreshChanges`), a confirmation card displays the `+` YAML diff with an **Undo** button (`UndoLastBriefPin`), and a single Undo removes both the copied file and the YAML line (or deletes a freshly created `brief.yaml` and empty `art/reference/` folder). - **Always chip (`brief.yaml`)**: whenever `brief.yaml` exists, the composer shows the **Always** row with a locked `brief.yaml` chip (showing the pinned reference count when non-zero). Hovering or pressing the chip previews every pinned reference image, and every subsequent agent request automatically includes those images via `AgentRequest.BriefImages` and `AgentRequest.Images`. ## Agent turns: multi-file pending changes as one undo step (#1011) Every edit an agent makes through the editor's MCP server between the start and end of one request (started from the Agent panel or opened via `turn_start` and closed via `turn_end`) accumulates into **one pending agent turn** across every file it touches—scenes, prefabs, data tables, `game.yaml`, and animation clips: - **Live in memory, zero disk writes until Keep + Save**: edits apply in memory immediately so the viewport, scene tree, inspector, and `scene_read` show them live (`Editor.StagedFileYAML`), while nothing is written to disk until the person keeps the turn and saves. Saving (`Save` / `SaveAll`) refuses while a turn is still pending, and autosave pauses while a turn is open. - **Derived structural diff with `why`**: rather than logging raw commands, the editor structurally diffs each touched file between its pre-turn state and its current state (per object ID and field/component/property/layer/parent for scenes and prefabs, per record for data tables, per dotted key for `game.yaml`, per header/track/event for clips). Each derived `AgentTurnChange` carries `Kind` (`added`, `changed`, `removed`), `Title`, concise `Detail` (such as `z 10 → 12`), `File`, 1-based YAML `Line`, optional `Why` reason (from MCP edit tools' `why` argument), and `Reverted` flag, alongside exact per-file `+added −removed` line counts. - **Per-change and per-file Revert / Restore while pending**: while a turn is pending or stopped (`⌘.` / `CmdStopAgentTurn`), the person can revert or restore any individual change (`RevertAgentTurnChange` / `RestoreAgentTurnChange` / `ToggleAgentTurnChange`) or every change in a file (`RevertAgentTurnFile` / `RestoreAgentTurnFile`). Reverted changes leave in-memory state immediately and return cleanly on restore, leaving untouched edits (including concurrent person edits on other objects) intact. - **Keep and Revert as one Undo step + Spec toast**: - **Keep** (`KeepAgentTurn` / `⌘↵` / `CmdKeepAgentTurn`) commits all remaining changes across every touched file as **one** `Editor.History` command tagged `AuthorAgent` / `HistoryAuthorAgent` (`History.Entries()`, `History.UndoAuthor()`, `History.RedoAuthor()`). One `⌘Z` restores every touched file byte-for-byte, and `⇧⌘Z` redoes the entire kept turn. A Spec `ToastSuccess` appears with an **Undo (`⌘Z`)** action. - **Revert** (`RevertAgentTurn` / `⌘⌫` / `CmdRevertAgentTurn`) restores every touched file to its exact pre-request state and shows a Spec `ToastInfo` whose **Undo** action (`UndoRevertAgentTurn`) brings the turn back as pending. - **Checkpoints `⌘Z` rules**: while the agent is actively working (`AgentTurnWorking`), `⌘Z` undoes only the person's own edits; inside an open review (`AgentTurnReviewOpen`), `⌘Z` undoes the person's edits made inside the review first and then reverts the review; once kept or idle, `⌘Z` undoes the ordinary history stack. - **Right-panel Agent tab & Summary Card (`RightRailView` / `AgentPanelView`)**: switch between **Agent** (`mod+1` / `CmdAgentTab`) and **Inspector** (`mod+2` / `CmdInspectorTab`) in the right panel header (showing a live pending indicator dot and MCP connection status). Styled exclusively with `Spec.dc.html` tokens matching `Main.dc.html` (localized in English and Chinese), the Agent panel displays the request bubble, progress steps, working **Stop (`⌘.`)** control, completion summary, the small summary card (`"6 changes · 1 file · +38 −0"`, grouped changes with per-change and per-file Revert/Restore, **Keep**, **Review**, **Revert**), Kept/Reverted notes (`"one undo step (⌘Z)"`), and the composer with `"Edits stay unsaved until you keep them"`. - **Navigation, close, and boundary protection**: opening another scene (`RequestOpenScene`), switching scene tabs (`RequestSelectTab`), switching projects (`RequestOpenProject`), closing the window, or quitting with a pending turn prompts **Keep**, **Revert**, or **Cancel** (`pendingTurnDialog`), matching unsaved-changes behavior. Every staged file enforces project-root symlink containment, refuses `.git/**` and You-only files, enforces a 2 MiB per-file limit, and resets cleanly on `OpenProject` and `OpenDemo`. - **MCP surface (`editormcp`)**: `turn_start`, `turn_end`, `turn_status` (read-only, reporting reverted changes), and `file_edit` (validating `game.yaml`, data tables, clips, prefabs, and scenes in memory) work alongside `scene_edit` and `object_set_field`'s `why` support. By design there is no MCP tool that keeps or reverts a turn. ## Agent panel failure, recovery, and offline states (#1024) When an agent request does not simply succeed, `AgentPanelView` renders dedicated `docs/design/editor/AgentStates.dc.html` cards using exclusively `SpecPalette` tokens (both Dark and Light themes) while keeping every manual editing tool (Select, Move, Inspector, `CheckProblems`, and Play) working in every state: - **Partial (`AgentPartialState`)**: displays `"Done N of M · couldn't place "` with the explanation, **Keep these** (keeps partial edits as undoable changes), **Let me point** (`ToggleAgentPointing`, clicking in the 2D viewport picks world coordinates via `PickAgentPointWorld` and `Esc` cancels cleanly), **Try another way** (`TryAnotherWayAgentTurn`), and a change-count review strip (`N changes · 1 file | +X −Y | Review`). - **Stuck (`AgentStuckState`)**: when the same MCP tool (such as `scene_edit`) fails three times in a row (`AgentStuckFailureThreshold = 3`), the editor pauses/cancels the active request instead of guessing again, transitions the header chip to `Waiting for you`, lists all three refused calls with their errors in a recessed monospace log, and offers a **Hint for the agent** input with **Continue with hint** (`ContinueAgentWithHint`) or **Stop here** (`StopStuckAgentTurn`, leaving the scene and disk untouched since refused edits never mutate files). - **Lost (`AgentLostState`)**: when an MCP client disconnects or a model API fails mid-request, completed steps stay intact in an unkept `AgentTurnReview`, the interrupted step is marked `"cut off, nothing written"` with no partly written file on disk, and the card states when and at which step it failed alongside **Reconnect**, **Review N changes**, and **Troubleshoot** (or **Retry now** and fallback switching such as **Use Claude Code** for model errors like 529 overloaded). After reconnecting, the agent asks before picking up at the next step (`ConfirmResumeLostAgentTurn` / `DismissResumeLostAgentTurn`) instead of auto-resuming. - **Stopped (`AgentStoppedState`)**: stopping a running turn records `DONE` and `NOT DONE` step sections, **Resume** (`ResumeAgentTurn`, which starts strictly at the first not-done step and skips steps already done), and **Review N changes**; completed changes stay unkept until explicitly reviewed and kept. - **Mismatch (`AgentMismatchReport`)**: the editor automatically checks every turn summary against the actual diff (`CheckAgentSummaryAgainstDiff`) and displays a `WHAT · SUMMARY · REVIEW` table when they disagree, including the auto-derived reason when known (for example, an object added at step 3 and removed at step 5), **Ask why** (`AskAgentWhyMismatch`), and **Open review** (`OpenAgentTurnReview`). **Keep** always applies the actual review diff, never the prose summary. - **Offline (`AgentStatusOffline`, `SetAgentOffline`)**: displays `"You're offline"` and queues submitted requests with timestamps (`AgentQueuedRequests`, `QueueAgentRequest`, `RemoveQueuedAgentRequest`) while Select, Move, the Inspector, game check, and Play keep working. Returning online never runs queued requests on its own; each queued request waits for an explicit **Send** (`SendQueuedAgentRequest`). ## Spec viewport overlays and toggle legend (#1006) Every semantic overlay drawn over the 2D and 3D viewports passes through one shared helper (`DrawObjectOverlay`) using exclusively `SpecPalette` tokens (`docs/design/editor/Spec.dc.html`, "Overlay legend"), with a non-color second cue (corner handles, pill glyph/prefix, ghost fill, strikethrough, or filled alert badge) so every kind remains distinguishable in greyscale: | Kind (`OverlayKind`) | Token & line style | Second cue | | --- | --- | --- | | **Selection** (`selection`) | `Accent`, 1.5 px solid | Four 8×8 corner handles and an accent name tag (person's selection only) | | **Agent working** (`agent`) | `Agent`, 1.5 px solid, no handles | Pulsing 1.6 s between 100% and 45%, dark pill with 4-point agent glyph (or numbered task badge) saying what the agent is doing | | **Added** (`added`) | `Added`, 1.5 px dashed | Dark pill labelled `"+ "` | | **Changed** (`changed`) | `Changed`, 1.5 px dashed | Dark pill showing field, old, and new value (for example `"z 10 → 12"`) | | **Removed** (`removed`) | `Removed`, 1.5 px solid | 25% grey ghost fill and dark pill with struck-through object name + `"removed"` | | **Problem** (`problem`) | `Problem`, 2 px solid on the live object | Filled pill (`Problem.Fg` / `Problem.OnFill`) with alert triangle icon and message; never resembles a removed ghost | | **Focused change in Review** (`focused`) | Base change kind's own color and dash at 2.5 px (never `Accent`) | Bright outlined pill matching the change kind | - **Pairing, motion, and reduced motion**: When **Selection** and **Agent working** sit on the same object (`PairedWithSelection`), Selection keeps its four corner handles and the Agent outline sits 3 px further out (`OverlaySelectionAgentGap`) with its pill stacked above. Added, Changed, and Removed overlays fade in over 240 ms (`OverlayChangeFadeDuration` / `OverlayFadeAlpha`), and active Agent working outlines pulse on a 1.6 s cycle (`OverlayAgentPulsePeriod` / `OverlayAgentPulseAlpha`). With reduced motion enabled (`core.Environment.ReduceMotion` or `Editor.SetReduceMotion(true)`), change overlays appear immediately at 100% and Agent outlines stay solid at 100% with no animation timer running. - **Top-left toggle legend (`viewport-overlay-legend`)**: Every edit-mode viewport (both 2D and 3D) mounts the same top-left legend card (`viewportOverlayLegendView`) with six accessible `role="switch"` rows (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**), each showing its drawn line style and second cue. Toggling any row (`Editor.ToggleOverlayKind`, `Editor.SetOverlayKindVisible`, `Editor.SetOverlayLegendKinds`) hides or shows that kind across all viewports immediately and persists `overlayLegend` in the per-user `EditorSettings` YAML file (`Editor.SettingsPath`, outside the project, never modifying project or scene files). - **Live scene overlay API and Problems object attribution**: Live agent edits, reviews, and plans attach overlays to objects (or removed ghost bounds) via `Editor.SetSceneOverlays`, `AddSceneOverlay`, `RemoveSceneOverlay`, and `ClearSceneOverlays` (`SceneOverlayEntry`). `assetcheck.Problem` now carries `Object` (also returned by `editormcp`'s `game_check`) for scene object, component, override, and connection diagnostics so Problems naming a live object in the open scene automatically draw the Spec **Problem** overlay on that object in both 2D and 3D viewports. - **Neutral viewport guides**: The camera frame, camera bounds, camera tether, tile grid, and snap grid use neutral `SpecPalette` tokens (`TextMuted` / `TextFaint` 1 px hairline and `2, 4` dotted lines) that no semantic legend kind uses. ## Agent composer: @-mentions, context chips, and context meter (#1020) Inside the unified right-rail **Agent** tab (`RightRailView` / `AgentPanelView`, switchable with `⌘1` / `⌘2` via `CmdAgentTab` / `CmdInspectorTab`), `AgentComposerView` (`docs/design/editor/Threads.dc.html`, styled strictly with `Spec.dc.html` tokens) adds `@`-mentions, explicit context chips, exact hover previews, and a live context meter: - **`@`-mention picker over the project search index**: typing `@` in the composer opens a live picker backed by `search.go` (`ensureProjectIndex`), `Editor.Problems`, `PlaytestSession` / `AddComposerPlaytestRun`, and `Editor.History`, showing a match count and 8 groups (**Objects**, **Files**, **Prefabs**, **Assets**, **Problems**, **Playtest runs**, **History steps**, **Rules**) with 9 tabs (**All** plus each group). Navigate with `↑` / `↓` (`MoveMentionSelection`), add with `↵` (`AcceptActiveMention`), cycle groups with `Tab` / `Shift+Tab` (`CycleMentionPickerGroup`), and close with `Esc` (`CloseMentionPicker`). Already-attached items are filtered out. - **Context chips and exact hover preview**: above the composer, attached chips show what joins the request (removable by clicking `×` via `RemoveComposerChip` or pressing `⌫` in an empty composer via `RemoveLastComposerChip`), **Always** chips show `brief.yaml` and `AGENTS.md` when present in the project root, and **Viewport image** is a toggleable chip (`SetViewportImageIncluded` / `ToggleViewportImage`). Selecting an object in the viewport or scene tree only surfaces a dashed `+ · selected` suggestion chip (`SuggestedChip`)—nothing joins the request unless explicitly added (`AcceptSuggestedChip`). `TriggerAskAgentShortcut` attaches the selected object or, when nothing is selected, the whole open scene (`AttachWholeSceneChip`) and focuses the composer. Hovering any chip (`SetHoveredChip` / `HoveredChipPayload`) displays the exact header (`# level_01.scene.yaml · lines 72–78`) and YAML text or image bytes resolved by `ResolveChipPayload`. - **Single-source request assembly**: `AssembleAgentRequest` builds `AgentRequest` from the active chips and nothing else—calling the exact same `ResolveChipPayload` function used on hover—and feeds both `SendComposerPrompt` (`Editor.OnSendAgentComposerRequest`) and `SubmitAgentPrompt` (`Editor.AgentRunner`). - **Context meter ring, breakdown, Compact, and Start fresh**: a 20×20 circular progress ring reflects reported token usage (`SetAgentTokenUsage` or `AgentResponse.Usage`) across three Spec states (normal `≤ 70%`, amber warning `71–89%`, and critical `≥ 90%` `"compact now"`). Clicking the ring opens a 6-row breakdown (**Conversation**, **Open scene**, **Attached**, **Always**, **Tools and instructions**, **Viewport image**) with **Compact thread** (`CompactAgentThread`, folding earlier requests into a summary while keeping the last request whole and dropping the ring) and **Start fresh with summary** (`StartFreshAgentThread`, opening a new thread seeded with that summary). ## AI-first main layout (#1007) The editor's main window (`main_layout_ui.go`, `ui.go`, `agent_ui.go`, `overlays_ui.go`, `scenetree.go`) implements the AI-first workspace from `docs/design/editor/Main.dc.html` using exclusively `docs/design/editor/Spec.dc.html` tokens, sizing, and accessible controls: - **44 px header (`mainHeaderView`)**: displays the ` / ` breadcrumb (`ProjectDisplayName`, `SceneBreadcrumbName`) with a Scene file menu and unsaved dot (`aria-label: "unsaved changes"` / `"save failed"`), a centered tool `base.RadioGroup` (`Select V`, `Move W`, `Rotate E`, `Scale R`, `Pan Space` as icon-only Lucide 1.8 px@15 px `currentColor` icons with `"Label · key"` tooltips), a `2D / 3D` segmented radio group, `History (⌘Y)` icon button, `Search ⌘K` palette button, and `Play (⌘P)` as the single primary button. - **232 px left rail (`leftRailSceneView`)**: combines the `Scene / Assets` switcher with `SCENE · N nodes` (`SceneNodeCount`), a quick filter toggle (`SceneTreeFilter` / `SetSceneTreeFilter` / `SetSceneTreeFilterOpen`) that narrows the scene tree by name, ID, or kind with auto-expanded ancestors, a quick-add `+` menu (`AddSceneRailObject` for empty object, trigger, or light and `AddSceneRailLayer`, all undoable through `History`), scene tree rows carrying kind color dots (`ObjectKindColor`), kind tags (`SceneRailObjectKind`, `LayerKindLabel`), and `NEW` badges on pending-review proposed objects (`IsObjectProposedNew`, `SetProposedNewObjectIDs`) with ellipsis-safe layout so visibility/lock buttons never clip, and a bottom `FILES` section listing the open scene, prefabs/instanced scenes it uses (`SceneUsedPrefabs`), and `game.yaml`. Picking a scene tree row switches the right rail to **Inspector**. - **Viewport dot grid, non-sprite markers, caption, bottom bar, and overlay legend**: in 2D edit mode, `DrawViewport` draws the neutral Spec 16×16 dot-grid surround (`SpecPalette.ViewportDot`) when no scene background color is set and neutral Spec-token markers for visible non-sprite objects so empty nodes, prefabs without sprites, and triggers stay legible and clickable without colliding with semantic overlay legend hues. `viewportCameraCaptionView` subscribes to `Editor.SubscribeCanvasSize` (`CanvasSizeRevision`) so `Camera · W × H` tracks the camera frame on first layout and every resize and avoids the top-left overlay legend, paired with the bottom bar (`Zoom out`, zoom `%`, `Zoom in`, `Snap` as a `base.Switch` with `RoleSwitch` / `aria-checked`, `Fit`, and `Overlays N`). - **Command Palette (`⌘K`, `PaletteItems`, `ExecutePaletteItem`)**: searches built-in/custom/plugin commands, plugin tools and panels, project scenes and files, **open-scene nodes** (`node:`, selecting, switching to Inspector, and framing the object), and **Settings pages** (`setting:`), with prefix scopes (`>` commands, `@` nodes, `#` files), empty-query **Recent** history (`PaletteRecent`), and an **Ask the agent** entry (`ask:`) that stages natural-language queries directly in the Agent composer. - **380 px right panel (`RightRailView`)**: hosts the `Agent` (`⌘1`) and `Inspector` (`⌘2`) radio tabs alongside the thread History toggle and live agent connection chip (`Connected · MCP`, `Working`, `Waiting for you`, `Reconnecting`, `Disconnected`); choosing a tree row switches directly to **Inspector**. - **32 px status bar (`mainStatusBarView`)**: renders muted text on `bg` with the active layer button (toggling Layers), live 2D pointer coordinates, current tool readout, problem count pill (opening Problems), Output, and Debugger. Secondary views previously hosted on the old toolbar (Settings, Audio Mixer, Input Map, Localization/Strings, Export, Library, Data Table, Project Search, Files, Assets, Animation, Particles, Material, HUD Layout, Terrain, NavMesh) remain reachable through the Command Palette (`⌘K`), Menu bar, Settings, and Status bar. - **Designed empty, loading, and error states (`WorkspaceState`, `SceneOpenError`)**: every region renders a dedicated state for `WorkspaceNoProject`, `WorkspaceNoScene`, `WorkspaceLoading` (`SetProjectLoading`), and `WorkspaceSceneError` (`SceneOpenError`, `RetryOpenScene`, `ClearSceneOpenError`). Opening a missing or malformed scene YAML renders an alert card with file path, line/column, message, fix guidance, **Retry**, and **Dismiss** instead of a blank viewport. - **Spec controls and keyboard navigation**: preserves Spec heights (`28 px` rows/tool buttons, `30–32 px` buttons, `44 px` header, `32 px` status bar, no interactive hit area under `28 × 28`), spacing (`4 / 8 / 12 / 16 / 24`), radii (`6 / 8`), `base.RadioGroup` / `base.Radio` and `base.Switch` semantics, 2 px Spec focus rings, accessible names, and `F6` cycling across all five regions (`Header`, `Scene tree`, `Viewport`, `Agent / Inspector`, `Status bar`). ## Agent panel live steps, permission cards, and Stop (#1012) The **Agent** panel (`AgentPanelView` inside `RightRailView`, `⌘1` / `⌘2`) streams live progress, interactive permission cards, follow-up instructions, and global Stop cancellation using `docs/design/editor/Spec.dc.html` tokens (`Working.dc.html`, `Permissions.dc.html`, `Main.dc.html`, `AgentStates.dc.html`) on top of the project's `permissions.yaml` rules and You-only boundaries: - **Live steps and `agent_report_step`**: starting a request (`Editor.StartAgentRequest` or `Editor.SubmitAgentPrompt`) immediately renders a gray placeholder step (within 300 ms). As `editormcp.Server` executes tool calls, each step streams in plain words with a violet spinner on the single active step and a green check once done. Agents can also call `agent_report_step` (`text`, optional `objects`, optional `status`) to report steps in their own words, name touched scene object IDs, and receive queued `"Add to this request"` follow-ups. - **Interactive permission cards over `permissions.yaml`**: when a tool call evaluates to `ask` against `permissions.yaml` (after You-only boundary enforcement), `editormcp.Server` pauses that call on its goroutine without blocking the editor UI and renders an `alertdialog` permission card (`LiveRegionPolite`) in the Agent panel showing the title, why the agent wants it, its effect (such as *"Nothing is saved."*), the rule preview and source, and **Allow once**, **Always**, and **Deny**. - **Focus and keyboard rules (Spec rules 02, 04, 05)**: a permission card never steals focus unless focus is already inside the Agent panel (`Editor.ShouldFocusAgentPrompt`); clicking the header **Waiting for you** chip focuses it on demand. While focused, `⌘↵` allows once, `⌥↵` persists an **Always** rule to `permissions.yaml` via `Editor.ApproveAlwaysPermission` (with the **Always permission rule saved** toast offering **Show** and **Undo**) so future identical calls run without asking, `⌘⌫` denies, `↑`/`↓` cycle buttons, and `Esc` leaves the card unanswered while the agent keeps waiting. - **No automatic retry after denial**: denying a permission card records its `(action, target)` key on the active request, renders *"You denied … · continued without it"* with an explicit **Allow now** action, notes the unchecked item in the turn's review summary (such as *"Not playtested"*), and immediately returns a structured non-fatal `denied` response for any repeated identical call in the same request without re-opening a card. Starting a new request clears per-request denials. - **Add to this request, Stop (`⌘.`), and concurrent manual editing**: while the agent works or waits, manual edits stay available and the bottom status bar reports what the agent is doing (*"manual edits stay available"*). The working footer keeps the **Add to this request** input focus-stable while steps stream (`Editor.AddToAgentRequest`). Pressing **Stop** or `⌘.` from anywhere—modal dialogs included—cancels the running request and any waiting Ask (`Editor.StopAgent`), keeps completed steps and scene edits pending for review (pausing autosave until kept or reverted), and shows the **Agent stopped** toast with **Review**; `Esc` never stops the agent. ## Dockable panels and layout (#919) `EditorView` builds the workspace on NSGo's `ui.DockArea`, turning the Scene tree, Layers, Asset Browser, Files, Library, Inspector (including the right-rail Agent, Sketch, Tasks, History, Problem Fix, and Tile Review views), Problems, Output, Profiler, Animation, States, Tileset, Terrain, 2D Rig, Particle Emitter, Material Editor, Scene Environment, Data Table, Search, 3D NavMesh, Localization, and every active plugin panel into dockable, resizable panels around the viewport (with `SceneTabsView` above the viewport canvas): - **Drag to resize, move, and tab**: drag any split or dock handle to resize panels, drag any panel tab into another group to tab them together or onto a group's edge to split beside it, and close panels from their tab close button (the `viewport` panel stays open). - **Show, hide, and reset from the menu**: open **View > Panels** to check or uncheck any built-in or active plugin panel (`PanelVisible`, `SetPanelVisible`, `TogglePanel`, `Panels`), or choose **View > Reset Layout** / **View > Panels > Reset Layout** (`CmdResetLayout`, `ResetLayout`) to restore the default arrangement. - **Per-user saved layout (`LayoutFile`, `ParseLayout`, `EncodeLayout`)**: layout changes persist automatically as strict versioned YAML outside any project under `/nsgo-game/layout.yaml` (`DefaultLayoutPath`, configured via `Editor.LayoutPath` / `Editor.SetLayoutPath` and wired automatically by `game editor` and `editorcmd`). Starting the editor again restores saved splits, tab groups, active tabs, sizes, and hidden panels, dropping any panel that no longer exists (for example from a removed plugin). - **Plugin panel placement**: plugin panels (`Plugin.Panels`) appear at their declared default `Dock` (`DockLeft`, `DockRight`, or `DockBottom`) on first use; once moved or tabbed elsewhere by the user, subsequent launches restore them at their moved position. ## Reviewing the agent's Go changes file by file (#1034) When an agent turn proposes Go edits alongside scene, prefab, or data YAML changes, the editor opens a dedicated file-by-file code review (`CodeReviewView`, matching `docs/design/editor/ReviewCode.dc.html` and `Review.dc.html` with exclusively `SpecPalette` tokens in both Dark and Light appearances): - **Pending Go isolation and Go build overlay checks**: Go files proposed during a turn (`ProposeCodeReviewFiles` or `editormcp`'s `code_review_propose`) are held strictly in memory until confirmed and kept—until then, the project on disk and Play keep running the old code. `RunCodeReviewChecks` / `RunCodeReviewChecksAsync` builds a temporary Go build overlay JSON (`BuildGoOverlay`, mapping both cleaned and symlink-resolved project paths so macOS `/var` → `/private/var` works cleanly) and executes `go tool nsgo check ` and `go tool nsgo test -json -count=1` with `GOFLAGS=-overlay=` against the pending code without touching any project file on disk (injectable via `Editor.CodeReviewCheckRunner`). - **Split file list and Unified / Split diff**: the left sidebar splits into **PREFABS · IN KEEP** (YAML/prefab files included in Keep) and **GO · CONFIRM EACH FILE** (each Go file with `+n −n` line counts and a **Needs OK** / **OK** badge), above an explanation card (*"Why Go confirms on its own"*). Go diffs toggle between **Unified** (`u`) and **Split** (`s`) layouts with old and new line numbers, right-aligned line tags (`fails test`, `failed here`, `agent edited`, `round 2`), and **Open in ``** (`Editor.ExternalEditorName`, `OpenCodeReviewInExternalEditor` via `Editor.OnOpenSourceFile`, `Editor.OnOpenFileAtLine`, or the OS opener). - **Checks strip, failing test card, and Round 2 fixes in the same turn**: the live status strip (`RoleStatus` + `LiveRegionPolite`) shows `nsgo check`, `nsgo test` pass/fail counts, elapsed duration and package path, **Run again** (`r`), and live streaming progress (`"nsgo test running · M of N"` / `"Agent is fixing · nsgo test running · M of N"` with an `"Agent edited :"` badge). A failing test displays its name, `file:line` failure message, and the agent's explanation, with **Ask the agent to fix** (`AskAgentToFixCodeReview`, `Editor.OnAskCodeReviewFix`, keeping the fix inside the same turn as Round 2 and rerunning checks) and **Open the test** (`OpenCodeReviewTestFile`). - **Per-file confirmation, Keep, Waiting card, and single-step Undo**: **Confirm ``** (`ConfirmCodeReviewFile`) is disabled and refused with `ErrCodeReviewChecksNotPassed` until both `nsgo check` and `nsgo test` pass for the latest pending code, then toggles to **Confirmed · undo**. **Keep** (`KeepCodeReview` / `⌘↵`) writes kept YAML files and **confirmed** Go files atomically as **one undo step** in `Editor.History` so a single `Editor.Undo()` restores old YAML and Go files and removes newly created Go files. Keeping while Go files remain unconfirmed writes only the YAML changes and leaves a waiting card in the **Agent** panel (`"patrol.go is waiting for your OK"`, explaining what that means in Play, with **Review** to resume directly on the unconfirmed Go file). Pressing `Esc` (`CloseCodeReview`) pauses the review without discarding it, and **Revert all** (`RevertCodeReview` / `⌘⌫`) discards pending changes without touching disk. - **Command and MCP tools**: `CmdReviewCode` (`agent.reviewCode`) opens or resumes an active Go review. `editormcp` exposes `code_review_propose`, `code_review_status`, and `code_review_run_checks` so agents can propose pending Go files, inspect failures, submit Round 2 fixes in the same turn, and rerun overlay checks off the UI goroutine. ## Rewind an agent thread (#1021) Rewind an agent conversation to before any earlier sent message (`docs/design/editor/Checkpoints.dc.html`, styled exclusively with `docs/design/editor/Spec.dc.html` tokens): - **Per-turn file and scene checkpoints**: each composer request (`SubmitAgentPrompt`) snapshots the project's files on disk (skipping `.git`, `.nsgo`, `node_modules`, symlinks, and You-only settings files) alongside the open scene and `game.yaml` before the agent runs, and compacts the diff when the turn finishes (`AgentTurn.ChangedFiles`, `AgentTurn.SessionIDBefore`, `AgentTurn.SessionIDAfter`). - **Hover or focus "Rewind to here" and three choices**: hovering or focusing any sent user message in `AgentPanelView` reveals **Rewind to here** (`OpenAgentRewindPopover` / `ToggleAgentRewindPopover`), opening the `"Rewind to before this message"` popover (`AgentRewindPreview`) with three choices (`AgentRewindMode`), **Cancel** (or `Esc`), and **Rewind** (`ConfirmAgentRewind` / `RewindAgentTurn`): - **Files and conversation (`AgentRewindBoth`)**: restores all files touched by the target and later turns from their checkpoints (synchronizing the open scene, inactive scene tabs, `game.yaml`, and file tree), drops the target and later turns from the thread, and restores `AgentSessionID` to `SessionIDBefore` so the next request continues the session from before the rewound message. - **Files only (`AgentRewindFilesOnly`)**: restores the files from the turns' checkpoints while keeping the conversation thread and session unchanged. - **Conversation only (`AgentRewindConversationOnly`)**: drops the target and later turns and restores the session ID while leaving all files on disk untouched. - **Post-rewind banner, Redo, and composer return**: after rewinding, the rewound message returns to the composer highlighted with the Spec accent ring (`AgentComposerRewound`) so you can edit and ask it differently, and a status banner above the composer (`AgentRewindBanner`) summarizes what was rewound with a **Redo** button (`RedoAgentRewind` / `CanRedoAgentRewind`) that restores the files, conversation turns, session ID, and prior composer draft. ## Agent plans with clarifying questions and planned ghosts (#1035) For larger changes—such as edits touching Go code, creating files, or spanning multiple files under the project's `permissions.yaml` rules (`EvaluatePlanPermissions`, `PlanNeededForEdit`)—an agent proposes a structured plan before modifying any scene or file (`docs/design/editor/Plan.dc.html`, styled strictly with `Spec.dc.html` Dark and Light tokens): - **MCP plan proposal (`plan_propose` & `plan_step_update`)**: calling `editormcp`'s `plan_propose` tool (`ActionRead`, never mutating files before approval) stages an `AgentPlan` in `PlanPhaseDraft` with a title, dynamic summary (`"5 steps · 3 files · 10 objects · about 2 min · ~35k tokens"`), clarifying questions with visual option previews (`room` sketches or `strip` timelines), numbered steps (files, additions, editable numeric `PlanStepField` steppers with min/max limits, permission badges like `Edit Go` or `Run the game`, planned Scene Tree nodes, and viewport ghosts), and waits until the person approves or stops, returning the structured `AgentPlanDecision` (answers, updated step counts, custom step notes, and removed steps). `plan_step_update` reports per-step execution status and attaches the finished `AgentPlanReview` checklist to the turn's review. - **Interactive Plan card in the Agent panel (`agentPlanCardView`)**: - Clarifying questions render as radio option cards with optional previews; picking an option collapses the question to a single summary row with **Change** (`ReopenPlanQuestion`). **Approve (`⌘↵`)** stays disabled and refused (`ApproveAgentPlan`) until every question is answered; **Just do it** (`JustDoItAgentPlan`) selects each question's suggested option and records `"Picked for you: …"`. - Numbered steps support inline editing (`EditPlanStep`, `AdjustPlanStepField`, `SetPlanStepNote`) and removal/restoration (`RemovePlanStep`, `RestorePlanStep`), striking out exclusive files in **FILES IN THIS PLAN**. - The footer states `"Nothing changes until you approve."` along with the permission-derived reason and a clickable **Permissions** link opening **Settings › Permissions** (`SettingsPagePermissions`). - **Planned viewport ghosts and Scene Tree markers**: - `drawPlanGhostsOverlay` draws agent-violet dashed outlines with step-numbered pills (`ResolvedPlanGhosts`), updating live as question answers move ghosts (via `PlanGhostOverride`) or numeric steppers change repeat counts (`RepeatField`), with a top-left legend (`"planned · not in the file yet"`) and a **Plan ghosts** toggle in the bottom floating viewport bar (`TogglePlanGhosts`). - `SceneTreeView` displays a `"{N} planned"` count, step badges on touched existing layers, dashed planned node rows, and the **FILES IN THIS PLAN** footer (`ResolvedPlanFiles`). - **Running, manual-edit pause, Stop, and turn review**: - While `PlanPhaseRunning`, the top header pill shows `"Agent is working · step k of N · manual edits to planned objects are paused"`, the active step's ghost switches from dashed to solid, and manual edits to planned objects (`IsObjectPausedByPlan`) are paused until completion or stop. - Pressing **Stop**, `Esc`, or `⌘.` before step 1 writes anything (`StopAgentPlan`) leaves every file unchanged (`NothingWritten: true`) and shows `"Stopped before step 1. Nothing was written."` with **Edit plan** (`EditStoppedPlan`) and **Run again** (`RunStoppedPlanAgain`). - Once completed (`CompleteAgentPlan` / `plan_step_update` with `complete: true`), the turn's review (`AgentTurn.Plan`, `agentTurnPlanReviewView`) lists every plan step and marks which were done or skipped. Small edits started with `⌘L` continue to set `SkipPlan: true`. ## Design tokens (#1002) Every color, type size, spacing step, corner radius, height, and motion duration in the editor comes from the embedded YAML theme and constants defined in `pkg/editor/spec_theme.yaml` and `pkg/editor/spec_theme.go`, matching `docs/design/editor/Spec.dc.html` and `docs/design/editor/Viewport3D.dc.html`: - **Embedded YAML theme (`spec_theme.yaml`, `SpecTheme`, `SpecPalette`)**: loaded with `core.ParseTheme` and attached on `EditorView`'s root scope via `cx.SetTheme(SpecTheme())`. Every NSGo `core.Palette` and `ui.ColorsOf` role (`Background`, `Surface`, `Raised`, `Line`, `Border`, `Text`, `TextMuted`, `Accent`, `AccentText`, `Success`, `Warning`, `Danger`, `Focus`) maps directly onto the Spec palette in both dark and light appearances, while `Editor.SpecPalette(cx)` (`DarkSpecPalette()`, `LightSpecPalette()`, `SpecPaletteFor(dark)`) exposes the additional Spec roles (`TextPrimary` / text strong, `TextSecondary` / text, `TextMuted` / text secondary, `TextFaint` / text muted, `OnTextPrimary`, `Viewport`, `ViewportDot`, `PillBg`, `HoverOverlay`, `ActiveOverlay`, `PrimaryHover`, `AccentHover`, `AccentPressed`, `Viewport3DGround`, `Viewport3DGrid`, `Accent`, `Agent`, `Added`, `Changed`, `Removed`/`Problem`, `Warning` with dedicated `Fill` and `Edge`, and 3D axis tokens `AxisX`, `AxisY`, `AxisZ`). - **Dark palette tokens (`Spec.dc.html` & `Viewport3D.dc.html`)**: - Surfaces & borders: `bg #101216`, `panel #12141A`, `raised #171A21`, `line #1F232A`, `line raised #262B35`, `viewport #15181D`, `viewportDot #2A2F38`. - Text ladder: `text strong #FFFFFF`, `text #D9DDE5`, `text secondary #B4BAC6`, `text muted #8B92A0`. The retired `#6F7684`, `#5D6472`, and `#4A505C` are never used for text. - Semantic roles: `accent #3B7BFF` (on-fill ink `#101216` at weight 600; `#FFFFFF` on dark accent or agent is never used), `agent #9B7BFF`, `added #4FD38A`, `changed #E9A84A`, `removed · problem #FF6B6B`, `warning #F2C14E` (on fill `#2A2414`, edge `#4A3F1F`). - 3D axes (`Viewport3D.dc.html`): `axisX #FF6B6B`, `axisY #4FD38A`, `axisZ #3B7BFF` (with WCAG-passing light equivalents `#C92A2A`, `#0D7A43`, `#1D5CE6`). - **Measured WCAG 2.2 contrast table (`SpecContrastTable`, `ContrastRatio`)**: `TestSpecContrastTableDarkAndLight` computes the WCAG 2.2 luminance contrast ratio of every foreground/background, on-fill, warning-card, pill, overlay, and 3D axis pair directly from `spec_theme.yaml` for both dark and light palettes, failing below `4.5:1` for text/on-fill or `3.0:1` for UI/overlay edges. A dedicated regression test verifies that reverting dark `text_muted` to `#6F7684` fails the check. - **Type, spacing, shape, heights, and motion constants**: - Type scale: Inter title `14 / 600` (`SpecFontTitleSize`, `SpecFontTitleWeight`), body `12.5 / 400` (`SpecFontBodySize`, `SpecFontBodyWeight`), section `11 / 600` at `+6%` tracking (`SpecFontSectionSize`, `SpecFontSectionWeight`, `SpecFontSectionTrack`), JetBrains Mono `11.5` (`SpecFontCodeSize`, `SpecFontFamilyMono`). - Spacing: `4`, `8`, `12`, `16`, `24` px only (`SpecSpace4`–`SpecSpace24`). - Radii & geometry: `6` controls (`SpecRadiusControl`), `8` buttons (`SpecRadiusButton`), `12` cards and toasts (`SpecRadiusCard`), `18` dialogs (`SpecRadiusDialog`); heights `28` rows/tool buttons (`SpecRowHeight`, minimum hit area `SpecMinHitSize = 28`), `30`–`32` buttons (`SpecButtonHeight`, `SpecButtonTallHeight`), `44` header (`SpecHeaderHeight`); `1` px inner borders (`SpecBorderWidth`). - Motion: `120 ms` hover/press (`SpecMotionHover`), `180 ms` panels/popovers/toasts (`SpecMotionPanel`), `240 ms` agent overlays (`SpecMotionOverlay`), `1.6 s` agent pulse (`SpecMotionAgentPulse`, `100%` ↔ `45%` opacity). `SpecMotionDuration` and `SpecAgentPulseOpacity` disable all motion (`0` duration, solid `1.0` opacity) whenever `Env.ReduceMotion` is enabled. - **No hardcoded UI color literals or dark-only package aliases**: every non-test `.go` file in `pkg/editor` outside `spec_theme.go` draws UI chrome, gizmos, overlays, and debug views exclusively from reactive `SpecPalette` tokens (`ed.SpecPalette(cx)` / `e.activeSpecPalette()`, keeping scene content data such as `scene.BackgroundColor` as scene data). `TestSpecNoHardcodedColorLiteralsInEditor` rejects any `core.RGB`/`core.RGBA` call or hardcoded UI hex color literal outside `spec_theme.go`, and `TestSpecNoDarkOnlyPackageColorVarsInEditor` rejects package-level color variables initialized from `darkSpecPalette` or `lightSpecPalette` so every editor screen repaints live across Dark and Light appearances. --- Source: https://game.nsgo.dev/docs/effects/ # effects `game/effects` draws a game's frame through a chain of shader passes, in order, with uniforms animated on the platform's frame clock. The frame is usually a pixel buffer the game writes each frame (`core.ImageSource.Pixels`), which NSGo shaders read since [nsgo#1052](https://github.com/nsgo-dev/nsgo/issues/1052). ```go import "github.com/nsgo-dev/game/pkg/effects" ``` ## Write an effect An effect is a fragment program in Kage, Go's syntax for shaders (`core.CompileShader`). It defines `Effect`, which returns the premultiplied color of a point of the frame, in the frame's pixels from its top left corner, and reads the pass before it with `Input(pos)` and the frame's size with `InputSize()`. The first effect's `Input` reads the frame itself: the pixel under the point, transparent outside the frame. Exported package-level variables are the effect's uniforms. ```go const invert = `package main // Amount is how far the colors turn, 0 to 1. var Amount float func Effect(pos vec2) vec4 { c := Input(pos) turned := vec4(c.a-c.r, c.a-c.g, c.a-c.b, c.a) return c + (turned-c)*Amount } ` const smear = `package main // Offset is how far to the right, in the frame's pixels, the second tap reads. var Offset float func Effect(pos vec2) vec4 { p := vec2(min(pos.x+Offset, InputSize().x-0.5), pos.y) return (Input(pos) + Input(p)) * 0.5 } ` ``` An effect does not declare `Input`, `InputSize`, `Texture`, `TextureSize` or `Fragment`, imports nothing, reads the frame only through `Input` (not `image0At`), reads an optional extra texture through `Texture(pos)` and `TextureSize()` (up to 3 textured effects per chain, bound to `image1` through `image3`), works in the frame's pixels (not the view's `rectSize` or `pixelScale`), and uses no name that starts with `__`, which the shader compiler keeps, or with `p` or `P`, digits and `_`, which the chain gives its declarations. ## Chain effects `Compile` fuses effects into one program, the first drawn over the frame and each next over the one before it. Each effect's `Input` calls the effect before it, so the passes run in one draw with no texture between them. Each source is compiled on its own first, so an error names the effect and gives the line and column in its source. ```go var post = effects.MustCompile( effects.Effect{Name: "invert", Source: invert}, effects.Effect{Name: "smear", Source: smear}, ) ``` - Each effect keeps its own names: two effects may both declare `Amount`, a helper `func blend` or a `const half`, and their uniforms are set per effect. - A pass that reads its input at several points runs the passes before it at each of them: a 2-tap pass over a 2-tap pass reads the frame 4 times. Put the passes that read many points first, or keep chains short. - `Compile()` of no effects draws the frame as it is. `Chain.Source` returns the fused program, the same for the same effects. ## Draw the game view `effects.View` is a `core.Shader` whose image is the frame, stretched over its box. Give the box the frame's aspect ratio for square pixels, as `screen.Viewport` places a virtual canvas. `Uniforms` holds each effect's values in the chain's order; `FrameFunc` and `UniformsFunc` follow signals. ```go frame := image.NewRGBA(image.Rect(0, 0, 320, 180)) version := core.NewSignal(cx, uint64(0)) // Each frame: draw into frame, then version.Set(version.GetUntracked() + 1). return effects.View{ Chain: post, FrameFunc: func() core.ImageSource { return core.ImageSource{Pixels: frame, Version: version.Get()} }, Uniforms: []core.Uniforms{{"Amount": 0.6}, {"Offset": 1}}, Style: core.Style{Width: core.Pt(640), Height: core.Pt(360)}, } ``` A nil `Chain` draws the frame as it is. `Chain.Uniforms` maps per-effect uniforms onto the program's names when you build a `core.Shader` yourself, and panics on a name an effect does not declare. ## Animate on the frame clock A uniform set to a `core.AnimatedNode` follows the platform's frame clock with no commit per frame. `Clock(cx, period)` returns a value counting seconds from 0 up to `period` and from 0 again; pick a period after which the effect looks as it started, as the value jumps back to 0. ```go pulse := effects.Clock(cx, 2*time.Second) effects.View{Chain: post, Frame: src, Uniforms: []core.Uniforms{{"Amount": pulse}, {"Offset": 1}}} ``` Any other node works too, such as a `core.Timing` a game starts when the player is hit. Values that change only now and then can come from `UniformsFunc`, at the cost of a commit each change. ## Bloom `Bloom()` returns a ready effect that makes the frame's highlights glow in one pass, with no texture between passes: over each point it adds the bright part of its input at the point and at 16 points around it, on an inner ring at half the radius and an outer ring at the radius. Its uniforms are `Threshold`, the luminance from 0 to 1 above which a pixel glows, clamped to that range; `Intensity`, how much glow is added, where 0 or less, the default, passes its input through unchanged, 1 to 2 is a strong bloom and values above 1000 act as 1000; and `Radius`, how far in the frame's pixels the glow reaches. ```go post := effects.MustCompile(effects.Bloom(), effects.Effect{Name: "invert", Source: invert}) effects.View{Chain: post, Frame: src, Uniforms: []core.Uniforms{{"Threshold": 0.6, "Intensity": 1.5, "Radius": 4}}} ``` - The glow adds light: colors stay premultiplied, and a translucent pixel near a highlight becomes more opaque. - `Threshold` is compared with the luminance of the premultiplied color, so a translucent pixel glows in proportion to its alpha: white at half alpha has a luminance of 0.5 and stays below a threshold of 0.6. - Each point reads its input 17 times, and a chain runs the effects before it at each of them, so put `Bloom` first or after effects that read their input once. - It approximates a blurred bright pass: at a large radius the glow is a soft star rather than a smooth disc. Keep `Radius` to a few pixels of the frame, and animate `Intensity` for a pulse. - `Bloom` carries its own `Reference`, so a chain with it draws a reference picture headless. ## CRT and scanlines `CRT()` returns a ready effect that bends the frame onto a curved cathode-ray tube and draws horizontal scanlines along the curve in one pass. Its uniforms are `Curvature`, the barrel distortion strength, where 0 or less, the default, or NaN leaves the frame flat, 0.1 to 0.3 is a typical CRT curve and values above 4 act as 4; `Scanlines`, from 0 to 1, how dark the gaps between scanlines turn, where 0 leaves the brightness unchanged, 1 turns the troughs black and values outside 0 to 1 are clamped; and `Lines`, how many scanlines span the frame's height, where 0 or less, the default, draws one scanline per pixel row of the frame and values above 16384 act as 16384. ```go post := effects.MustCompile(effects.Bloom(), effects.CRT(), effects.VignetteEffect()) effects.View{ Chain: post, Frame: src, Uniforms: []core.Uniforms{{"Threshold": 0.6, "Intensity": 1.2, "Radius": 3}, {"Curvature": 0.25, "Scanlines": 0.35}}, Style: core.Style{Width: core.Pt(640), Height: core.Pt(360)}, } ``` - Setting `Curvature` without `Scanlines` curves the frame alone; setting `Scanlines` without `Curvature` draws flat scanlines; leaving both 0 or less passes the input through unchanged. - The four edge midpoints stay pinned to the frame border while the corners pull inward onto an opaque black bezel. Inside the screen, scanlines darken RGB while keeping each pixel's alpha, so colors stay premultiplied. - With `Lines` left 0, one scanline per pixel row shows as alternating bright and dark rows when the view scales the frame up (at 2x or higher); set `Lines` to half the frame's height or less when drawing a frame at 1:1. - Each point reads its input at most once, so `CRT` can follow multi-tap passes such as `Bloom` without multiplying their taps, and chains with `VignetteEffect` when darkened corners are also wanted. - `CRT` carries its own `Reference`, so a chain with it draws a reference picture headless. ## Vignette, flash and shake The package ships three effects with their `Reference` functions, so a chain of them draws reference pictures. Each returns a fresh `Effect` to put in a chain. | Effect | Uniforms | What it draws | | --- | --- | --- | | `VignetteEffect()` | `Strength`, `Radius`, `Softness`, `Color` | Turns the edges toward `Color` (black when left out), keeping each pixel's alpha. The distance runs from 0 at the center to 1 at the corners, round in the frame's pixels; the edges start to turn at `Radius` and turn all the way, eased, over `Softness`, as far as `Strength` (0 to 1). | | `FlashEffect()` | `Amount`, `Color` | Turns the whole frame toward the opaque `Color` by `Amount`, 0 to 1. | | `ShakeEffect()` | `Amplitude`, `Time`, `Frequency`, `Phase` | Moves the frame by up to `Amplitude` pixels along each direction, swaying `Frequency` times a second on `Time` (seconds), started by the four `Phase` angles, and reads the frame's edge where it moves off it. An offset that is not finite, or 1e30 pixels or more, leaves the frame in place. `ShakeOffset` gives the same offset in Go for uniforms set to plain numbers. | A uniform left out is 0, so each draws the frame as it is until it is set. Put the shake first, so the passes after it draw over the moved frame, and the flash last: ```go post := effects.MustCompile(effects.ShakeEffect(), effects.VignetteEffect(), effects.FlashEffect()) ``` `NewFlash` and `NewShake` animate the flash's and the shake's uniforms on the frame clock, with no commit per frame. `Trigger` starts one, in place of one still running, and `Stop` ends it at once: - `Flash.Trigger(peak, fade)` sets `Amount` to `peak` and fades it to 0 over `fade`, easing out. - `Shake.Trigger(amplitude, d)` sets `Amplitude` and decays it to 0 over `d`, easing out, while `Time` runs from 0. Each trigger takes its next four phases from `ShakeConfig.Seed`, so a replay with the same seed shakes the same way. `ShakeConfig.Frequency` is 12 when left 0. ```go assist := a11y.NewAssist(cx, "") flash := effects.NewFlash(cx, effects.FlashConfig{Color: core.RGB(0xffffff), ReduceMotion: assist.ReduceMotion}) shake := effects.NewShake(cx, effects.ShakeConfig{Seed: 42, ReduceMotion: assist.ReduceMotion}) vignette := core.Uniforms{"Strength": 0.8, "Radius": 0.4, "Softness": 0.6} onHit := func() { flash.Trigger(0.7, 300*time.Millisecond) shake.Trigger(6, 400*time.Millisecond) } return effects.View{ Chain: post, FrameFunc: func() core.ImageSource { return core.ImageSource{Pixels: frame, Version: version.Get()} }, Uniforms: []core.Uniforms{shake.Uniforms(), vignette, flash.Uniforms()}, Style: core.Style{Width: core.Pt(640), Height: core.Pt(360)}, } ``` Flashes and shakes follow reduced motion: `Trigger` does nothing and returns false while `ReduceMotion` reports true. Pass `a11y.Assist`'s `ReduceMotion`, which follows the player's choice and else the platform's; when `ReduceMotion` is nil, the platform's setting is asked. A peak, amplitude or duration of 0 or less does not start one either, and leaves a running one alone: `Stop` ends it, unlike `tilemap.Camera.Shake`, which a zero intensity cancels. ## Palette swap Two ready effects map colors through a palette texture, bound to `Effect.Texture` and read through `Texture(pos)` and `TextureSize()`. Both carry their own `Reference`, so a chain with them draws reference pictures headless whenever the palette has `Pixels` or PNG `Data`. - `PaletteSwap(palette)` swaps colors by key: row `0` holds up to 256 source colors (transparent cells are skipped), and each row from `0` to `height - 1` holds a target palette. Its uniforms are `Amount`, 0 to 1 (0 or less, the default, passes its input through unchanged); `Row`, from `0` to `height - 1`, where fractional values blend linearly between adjacent rows; and `Tolerance`, the largest per-channel difference in straight RGB that matches a key in row `0`. Values at or below `0.002/alpha` (including 0, the default) match exact 8-bit colors; larger values pick the nearest matching key in Euclidean RGB distance, and `1` snaps every non-transparent color to its nearest key. Unmatched colors and transparent pixels pass through unchanged. - `PaletteRamp(palette)` maps each pixel's straight Rec. 709 luminance into a dark-to-light palette row of any width (`0` at column `0`, `1` at column `width - 1`), with `Amount` (0 to 1) and `Row` (0 to `height - 1`, fractional values blending adjacent rows). `PaletteImage(rows...)` builds a premultiplied `*image.RGBA` palette texture from rows of `core.Color` values: ```go pal := effects.PaletteImage( []core.Color{core.RGB(0xd03030), core.RGB(0xf0c030), core.RGB(0x3060d0)}, // row 0: keys []core.Color{core.RGB(0x40c8f0), core.RGB(0xe0f8ff), core.RGB(0x205090)}, // row 1: ice theme []core.Color{core.RGB(0x8838c8), core.RGB(0xb8f040), core.RGB(0x386030)}, // row 2: poison theme ) post := effects.MustCompile(effects.PaletteSwap(core.ImageSource{Pixels: pal, Version: 1})) return effects.View{ Chain: post, Frame: src, Uniforms: []core.Uniforms{{"Amount": 1, "Row": 1}}, } ``` - Colors stay premultiplied: a matched pixel's alpha multiplies the target palette entry's premultiplied color, so translucent sprites keep their alpha and a palette entry may be translucent or transparent. - Animate `Amount` or `Row` with a `core.AnimatedNode` to fade or crossfade palettes on the frame clock with no texture re-upload. - To replace a textured effect's image per view without recompiling the chain, set `View.Textures` or `View.TexturesFunc` (or call `Chain.Images` when building a `core.Shader` yourself, and `Chain.ReferenceWithTextures` in headless tests). ## Reference pictures Headless tests have no GPU, so `Chain.Reference(frame, width, height, uniforms)` draws the chain on the CPU with each effect's `Reference` function, at the per-effect uniforms a `View` would set, mapping each output pixel's center onto the frame as the GPU does. `Float` reads a number uniform, and a uniform left out is 0, as on the GPU. Compare the result with a golden PNG from `gametest`: ```go invertRef := func(in effects.Input, u core.Uniforms, x, y float64) [4]float64 { c, amount := in.At(x, y), effects.Float(u, "Amount") for k := range 3 { c[k] += (c[3] - 2*c[k]) * amount } return c } chain := effects.MustCompile(effects.Effect{Source: invert, Reference: invertRef}, ...) got, err := chain.Reference(frame, 640, 360, []core.Uniforms{{"Amount": 0.6}, {"Offset": 1}}) ``` `Reference` returns an error when an effect has no `Reference`, for a uniform an effect does not declare, and for one set to an animated node such as `Clock`'s, whose value only the platform knows: pass the number to draw it at instead. A PNG stores straight colors, so convert the premultiplied picture to `*image.NRGBA` before `gametest.AssertGolden` when it has translucent pixels. --- Source: https://game.nsgo.dev/docs/entities/ # Entities A small, zero-reflection entity-component-system (ECS) for NSGo games: generational entities, typed sparse-set components, allocation-free queries, topologically ordered systems, prefabs and JSON world snapshots integrated with `game/save`. ```go import "github.com/nsgo-dev/game/pkg/entities" ``` `nsgo game generate component `, `system ` and `prefab ` write a new component, system or prefab into a game with its registration and a test; see [Command Line](https://game.nsgo.dev/docs/cli/#generate). ## Architectural decision Before implementing `entities` ([#136](https://github.com/nsgo-dev/game/issues/136)), three designs were compared for representing game objects in `github.com/nsgo-dev/game`: 1. **A small, zero-reflection, generational-index ECS with typed sparse-set storage** (chosen). 2. **An object-oriented scene tree** of heap-allocated nodes with virtual update methods. 3. **A reflection-driven archetype ECS** with dynamic component tables and query planners. Option (1) was chosen for five reasons: - **Zero-allocation hot loops**: entities are 64-bit generational handles (32-bit slot index + 32-bit generation) recycled through a free list, and each component type lives in a contiguous typed sparse set (`Store[T]`). Creating and destroying 100k entities in steady state, accessing components, and iterating queries perform zero heap allocations. - **Zero reflection**: Go generics identify component stores through zero-sized type tags and keep all component access, queries and prefab builders statically typed with no `reflect` imports. - **Safe handle lifetimes**: destroying an entity increments its slot generation before recycling it, so stale `Entity` handles never alias newly spawned entities. - **Explicit, deterministic execution**: systems declare `Before` and `After` constraints resolved once by Kahn's topological sort with registration-order tie-breaking. Cycles and missing targets fail cleanly, and `Order()` exposes the exact execution sequence for debug overlays. - **Clean serialization boundaries**: only component types registered with `RegisterCodec[T]` are written to deterministic `WorldSnapshot` JSON values and saved through `game/save`, keeping transient runtime handles (sprites, audio voices) out of save files while preserving entity IDs and cross-entity references. ## Entities and World An `Entity` is a `uint64` carrying a 32-bit slot index and a 32-bit generation (`entities.Zero` is the invalid handle and is never alive). `World` owns entities and their component stores. - `NewWorld()` returns a fresh world (the zero value of `World` is also ready to use). - `Spawn()`, `Destroy(e)`, `Alive(e)` and `Count()` manage entity lifetimes with free-list recycling. - `Clear()` removes all entities and components while bumping generations and keeping slice capacities for zero-allocation reuse. `Reset()` releases backing storage. - `Attach(cx)` binds the world to an NSGo `*core.Scope` so `Dispose()` runs automatically when the scope is disposed. ```go world := entities.NewWorld() world.Attach(cx) hero := world.Spawn() world.Alive(hero) // true world.Destroy(hero) world.Alive(hero) // false, even after the slot is recycled ``` ## Components and queries Each component type `T` is stored in a typed sparse set (`*Store[T]`). Top-level generic functions operate directly on a `*World`, and `Component[T](w)` returns the underlying `*Store[T]` for direct inner-loop access. - `Set[T](w, e, v)`, `Get[T](w, e)`, `Has[T](w, e)` and `Remove[T](w, e)` attach, read, check and detach components in O(1) time. - `Each1[A]`, `Each2[A, B]` and `Each3[A, B, C]` iterate over the smallest sparse set and check O(1) membership in the others, visiting exact matches in deterministic order with zero reflection and zero heap allocations. Returning `false` stops iteration early. The component pointers are valid only inside the callback and only until it adds a component of an iterated type: adding can grow the store and move its values, so collect entities and add components after the loop. A callback may destroy the entity it was handed, but not add or remove other entities of the iterated stores; collect those and act after the loop. ```go type Position struct{ X, Y float64 } type Velocity struct{ DX, DY float64 } entities.Set(world, hero, Position{X: 10, Y: 20}) entities.Set(world, hero, Velocity{DX: 60, DY: 0}) entities.Each2[Position, Velocity](world, func(e entities.Entity, p *Position, v *Velocity) bool { p.X += v.DX * dt.Seconds() p.Y += v.DY * dt.Seconds() return true }) ``` ## Systems and update order `Scheduler` runs named systems in a deterministic topological order on each `game.Loop` fixed step. - `AddSystem(name, fn, opts...)` registers a system with optional `Before(other)` and `After(other)` constraints. Targets may be registered in any order. - `Build()` validates constraints and resolves execution order with Kahn's algorithm, breaking ties by registration order. Unknown targets return `ErrUnknownSystem` and cycles return `ErrSystemCycle`. - `Order()` returns the resolved names and `String()` formats them as `"a -> b -> c"` for debug overlays. - `Step(w, dt)` resolves if needed and runs each system in order with zero steady-state allocations. ```go sched := entities.NewScheduler() _ = sched.AddSystem("input", readInput) _ = sched.AddSystem("physics", stepPhysics, entities.After("input")) _ = sched.AddSystem("render", syncSprites, entities.After("physics")) loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { _ = sched.Step(world, dt) }, } ``` ## Prefabs A `Prefab` is a named template that stamps a preset group of components onto newly spawned entities. - `NewPrefab(name)` creates a template, and `Clone(name)` derives a variant without mutating the original. - `With[T](p, v)` attaches a value component copied per entity. - `WithFunc[T](p, make)` invokes `make()` on each spawn so slices, maps and pointers are never shared across entities. - `Spawn(w)` and `SpawnN(w, n)` create independent entities from the template. ```go goblin := entities.NewPrefab("goblin") entities.With(goblin, Position{X: 10, Y: 20}) entities.WithFunc(goblin, func() Inventory { return Inventory{Items: []string{"dagger"}} }) squad := goblin.SpawnN(world, 5) ``` ## 2D transform hierarchy `world.Hierarchy2D()` (or `entities.NewHierarchy2D(world)`) attaches a parent-child 2D transform hierarchy to a World. Local transforms live in the `Transform2D` component (`X`, `Y`, `Rotation`, `ScaleX`, `ScaleY`, `Hidden`; build one with `NewTransform2D` or `IdentityTransform2D`, since the zero value has zero scale), and `Sync()` composes them into cached `WorldTransform2D` components that `Each1`/`Each2`/`Each3` can iterate directly. ```go h := world.Hierarchy2D() ship, turret := world.Spawn(), world.Spawn() h.SetLocal(ship, entities.NewTransform2D(100, 50)) h.SetLocal(turret, entities.NewTransform2D(0, -12)) _ = h.SetParent(turret, ship, false) h.SetRotation(ship, 0.5) h.Sync() wt, _ := h.WorldTransform(turret) _ = wt ``` - `SetLocal`, `SetPosition`, `SetRotation`, `SetScale`, `SetVisible` and `entities.Set` with a `Transform2D` mark the entity and its subtree dirty. After writing through a `*Transform2D` from `Get` or a store, call `h.MarkDirty(e)`. - Visibility is inherited: `WorldTransform2D.WorldVisible` is false when the entity or any ancestor is hidden. - `SetParent(child, parent, keepWorld)` and `Detach(child, keepWorld)` keep the child's local transform, or with `keepWorld` recompute it so the child stays where it is on screen. A keep-world reparent whose exact relative transform needs shear (a rotated child under a non-uniformly scaled parent) returns `ErrNotDecomposable` and changes nothing; cycles return `ErrCycle` and dead entities `ErrDeadEntity`. - Destroying a parent applies the hierarchy's `RemovePolicy` (`SetRemovePolicy`): `RemoveDetach` (default) detaches the children keeping their local transforms, `RemoveDetachKeepWorld` detaches them keeping their world transforms, and `RemoveCascade` destroys the whole subtree. `DestroyWithPolicy(e, policy)` overrides it for one call. - Snapshots only include registered components: call `RegisterCodec[entities.Transform2D](w, "transform2d")` to save local transforms. `WorldTransform2D` is derived, so it does not need a codec; the hierarchy reseeds from the restored local transforms. ## Saving and loading a world Worlds serialize to deterministic `WorldSnapshot` JSON values and integrate directly with `game/save`. - `RegisterCodec[T](w, typeName)` registers a JSON codec for component type `T`. Unregistered components are omitted from snapshots. - `w.Snapshot()` emits live entities in ascending slot-index order and components in ascending codec-name order, preserving exact indices and generations so cross-entity `Entity` references stay valid after restore. - `w.Restore(snap)` decodes into a temporary world first and commits atomically, leaving `w` untouched if any codec is missing or decoding fails. - `SaveWorld(store, slot, w)` and `LoadWorld(store, slot, w)` persist and restore worlds through `save.Store` (both `save.NewStorageStore` and `save.NewFileStore`, including schema versions and migrations). `LoadWorld` checks the snapshot while the slot decodes, so a snapshot it cannot restore (an unknown codec, a bad parent, a component that does not decode) falls back to the backup copy, and its error names the slot, the line and the field, such as `data.entities[2].parent`. ```go _ = entities.RegisterCodec[Position](world, "position") _ = entities.RegisterCodec[Velocity](world, "velocity") store := save.NewStorageStore(cx.Storage(), "game") if err := entities.SaveWorld(store, "slot1", world); err != nil { return err } fresh := entities.NewWorld() _ = entities.RegisterCodec[Position](fresh, "position") _ = entities.RegisterCodec[Velocity](fresh, "velocity") if err := entities.LoadWorld(store, "slot1", fresh); err != nil { return err } ``` --- Source: https://game.nsgo.dev/docs/errors/ # Errors an agent can act on Every loader and validator in this module returns the same error type when a file cannot be used: `*loaderr.Error` from `github.com/nsgo-dev/game/pkg/loaderr`. It names the file, the line and column, the field, what was wrong, what was expected and how to fix it, so a person, or an agent reading a test or build log, can open the file at that line and correct it without reading the loader's source. ```text levels/cave.scene.yaml:14:7: layers[1].space: layer "hud" has invalid space "iso"; expected "world" or "screen"; fix: set space to world or screen, or remove it for world ``` The message reads `file:line:column: field: problem; expected E; fix: F`, leaving out the parts that are not known. Editors and terminals turn the `file:line:column` prefix into a link. ## The fields | Field | Holds | | --- | --- | | `File` | The file's path or name. A loader that reads a path fills it in; one that is handed bytes leaves it to its caller (see below). | | `Line`, `Column` | 1-based position of the problem, 0 when it is not at one place, such as a file that cannot be read. | | `Field` | Where in the document, as a path: `layers[2].objects[0].id`, or `tilemaps["a.b"].ref` for a key that holds a dot. Empty for the document as a whole. | | `Problem` | What is wrong. | | `Expected` | What the loader expected there, when the problem does not already say it. | | `Fix` | What to change so the file loads. Every error a loader returns has one. | | `Err` | The underlying error: `errors.Is` and `errors.As` see through an `Error`, so sentinels such as `save.ErrCorrupt` and `modding.ErrInvalidManifest` still match. | `loaderr.As(err)` returns the `*Error` in a chain. ## Naming the file A loader that reads a path, such as `particles.LoadConfigFile`, `gltf.LoadFS`, `replay.LoadFile`, `datatable.LoadFile` or `editor.OpenFile`, names that path in its errors. A loader handed bytes, such as `sceneformat.Parse` or `tilemap.LoadTiled`, knows the line but not the file, and writes `` in its place; the code that read the file names it: ```go data, err := fs.ReadFile(assets, "levels/cave.scene.yaml") if err != nil { return err } doc, err := sceneformat.Parse(data) if err != nil { return loaderr.WithFile(err, "levels/cave.scene.yaml") } ``` `WithFile` names the file only on an error that is itself a `*loaderr.Error`, as every loader's entry point returns. An error that wraps one, such as `fmt.Errorf("level 3: %w", err)`, is returned unchanged, so its context and sentinels still match; call `WithFile` before wrapping. Values kept in `core.Storage`, such as input bindings, debug tunables and save slots, name their storage key as the file. A save slot in a `FileBackend` names its file, `/.json` or `/.json.bak` for the backup copy. ## What each loader reports | Package | Loader | Lines | | --- | --- | --- | | `sceneformat` | `Parse`, `ParseWith` | Decode errors and every schema rule, by field; the `*FieldError` `Validate` returns stays in the chain, and `ParseWith` names `ParseOptions.File` | | `particles` | `UnmarshalConfigYAML`, `UnmarshalConfigJSON`, `LoadConfigFile`, `LoadConfigFS`, `HotConfig` | Decode errors, durations, colors and enumerations, by field or at the value's line | | `skeletal` | `Load` | Bones, slots, skins and keyframes, by field | | `anim3d` | `LoadEventsSidecar`, `LoadEventsFromGLTFExtras` | Decode errors | | `sprite` | `LoadAtlas` | Frames, frame tags and nine-slices, by field | | `tilemap` | `LoadTiled`, `LoadLDtk`, `LoadLDtkAll` | Map, tilesets (an external tileset names its own file), layers, objects and properties, by field | | `l10n` | `Catalog.LoadJSON`, `ParseAssetManifest`, `AssetCatalog.LoadAssetManifestYAML` | Keys, asset variants and groups, by field | | `input` | `Actions.Load`, `Haptics.Load` | Stored bindings, by field, under the storage key | | `modding` | `ParseManifest`, `ModManifest.Validate`, `Manager.Discover`, `Manager.DiscoverFS`, `Manager.Reload` | Each manifest field, a game version the mod does not support and a duplicate id, naming `/mod.yaml` | | `replay` | `Decode`, `LoadFile` | Header and steps, by field, such as `steps[3].press[0]` | | `save` | `Store.Load`, `Store.LoadChecked`, `SettingsStore.Load` | Envelope, data and checks, naming the copy's file or storage key (a custom `Backend`'s copies by slot, `slot (backup)` for the backup) | | `entities` | `LoadWorld`, `World.Restore` | Entity indices, parents and components, by field | | `assets` | `ParsePackManifest`, `Manager.LoadAtlas`, `Group` atlases | Decode errors; atlases name their URI | | `world3d` | `LoadMeshLibraryFromGLTF` | Version, node meshes and accessors, by field | | `gltf` | `Load`, `LoadFS` | The top-level item at fault, such as `nodes[3]` | | `text` | `LoadBMFont`, `LoadBMFontImage` | The record at fault, in text and XML fonts | | `flow` | `ParseYarn` | The script line at fault | | `tooling/datatable` | `LoadCSV`, `LoadJSON`, `LoadYAML`, `LoadFile` | The cell at fault; `CellError` stays in the chain | | `tooling/devstate` | `Store.LoadSnapshot` | Decode errors in the snapshot file | | `debug` | `Console.LoadTunables` | The tunable at fault, under the storage key | | `tooling/bench`, `cmd/sizecheck` | `bench.LoadFile`, `LoadBudget`, `LoadMobileBudget` | Decode errors | A file that cannot be read has no line: its error names the file, keeps the read error in `Err` and still gives a fix. ## Writing a loader 1. Validate the decoded document with `loaderr.Errorf(field, fix, format, args...)`, building `field` with `loaderr.Path("layers", i, "objects", j)` or extending one with `loaderr.Join(at, "alpha")`. A validator does not know lines, so it names the field instead. 2. In the loader's entry point, pass every error through `loaderr.Locate(err, file, data, fix)` once (or `loaderr.LocateJSON(err, file, data, fix)` for JSON-only loaders that do not need YAML support). It finds the field's line and column in the YAML or JSON text, turns decode errors from `encoding/json` and YAML (syntax, unknown fields, wrong types, duplicate keys, an early end) into an `Error` with their line and a fix, names the file, and gives the loader's `fix` to an error that has none. 3. For a line-based format that is neither YAML nor JSON, such as BMFont text or Yarn, set `Line` directly. 4. Write a fix as an instruction: what to write, where, or which tool to export from again. "Set space to world or screen" helps; "invalid value" does not. 5. Walk maps in sorted key order, so the same problem is reported on every run when a file has several. 6. Test with `internal/loaderrtest`: `Expect(t, err, file, line)` checks that the error names the file and line and has a fix, and `ExpectField(t, err, file, data, field)` also checks the field. A custom `UnmarshalYAML` knows the node it was handed: return a `*loaderr.Error` with the node's `Line` and `Column`, as `particles` does for durations and colors, and `Locate` keeps them. A custom `UnmarshalJSON` cannot say where it failed: the `encoding/json` that `nsgo build` links returns its error without the field's path, so keep the value it refuses and report it from the validator with the field instead. --- Source: https://game.nsgo.dev/docs/fighting/ # fighting `github.com/nsgo-dev/game/pkg/fighting` buffers fighting-game input one fixed step at a time and recognizes motion inputs (quarter circles, dragon punches, charges, double taps), button presses, chords and combos described in a YAML move set. ## Numpad notation Directions use numpad notation, relative to a character facing right: ```text 7 8 9 up-back up up-forward 4 5 6 back neutral forward 1 2 3 down-back down down-forward ``` `Direction` holds one digit, `DirectionOf(x, y)` builds one from signs, and `Mirror` swaps left and right. When a character faces left (`FaceLeft`), the recognizer mirrors every direction before matching, so `6` always means toward the opponent and the same move set works on both sides. ## Move sets A move set is a versioned YAML file. Unknown fields are refused, and `Encode` writes a canonical form (block style, fields in schema order, motion entries as quoted strings), so parsing `Encode`'s output and encoding it again reproduces it byte for byte. ```yaml version: 1 input: up: up down: down left: left right: right axisX: move_x axisY: move_y moves: - name: lp press: - lp - name: hadoken motion: - "2" - "3" - "6" window: 12 press: - lp - hp buffer: 8 priority: 20 - name: sonic_boom motion: - "6" charge: dirs: "147" steps: 40 grace: 6 press: - lp buffer: 6 priority: 25 - name: forward_dash motion: - "6" - "5" - "6" window: 12 priority: 10 - name: throw press: - lp - lk pressAll: true pressWindow: 2 priority: 40 combos: - name: jab_fireball sequence: - lp - hadoken gap: 20 ``` `input` names the actions and axes that make up the stick. Digital actions add ±1 to their axis and analog axes add their value; an axis whose total reaches `deadzone` (default `0.5`) points that way, so holding left and right together is neutral. `axisY` is positive down unless `yUp` is set. Each move has a `name` and a `motion`, a `press`, or both: | Field | Meaning | | --- | --- | | `motion` | Direction entries matched on distinct, increasing steps. An entry is a string of one or more digits, any of which satisfies it, so `"23"` accepts down or down-forward. | | `window` | Most steps from the first to the last motion entry; only for motions of 2 or more entries. | | `charge` | `dirs` held for at least `steps` consecutive steps, ending no more than `grace` steps before the step that precedes the first motion entry. | | `press` | Button actions that finish the move; any one of them, pressed on the current step. | | `pressAll`, `pressWindow` | Require every `press` button within `pressWindow` steps (a chord). | | `buffer` | Most steps the finishing press may come after the last motion entry; needs both `motion` and `press`. | | `priority` | Orders moves finished on the same step, highest first. | All step counts are inclusive and at most `MaxSteps` (600). A motion without `press` finishes on the first step it fits, so holding the last direction does not repeat it. Inputs that finished a move cannot finish it again: a button pressed within `buffer` after a finished quarter circle is not a second fireball, and the next one needs a fresh motion. A move set may name up to 32 buttons. A combo lists at least two moves; each must follow the previous one within `gap` steps, and any other move in between breaks it. ## Recognizing input ```go set, err := fighting.LoadFile("moves.yaml") if err != nil { return err } rec, err := fighting.NewRecognizer(set) if err != nil { return err } loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { actions.Step() res := rec.Update(actions, player.Facing) if len(res.Moves) > 0 { player.Perform(res.Moves[0].Name) } for _, c := range res.Combos { hud.Announce(c.Name) } }, } ``` Call `Update` once per fixed step, after the source has stepped. `Result.Moves` holds every move finished on that step, highest priority first, so `Moves[0]` is the one to perform; only that move advances combos. Each `Match` carries the step its inputs started on and the step it finished. The slices are reused by the next call and allocate nothing. `Feed(raw, held, facing)` records a step from an already decoded direction and button mask (bit `i` for `Buttons()[i]`), such as inputs from netcode. Recognition depends only on the frames fed, so a re-simulation from the same inputs gives the same results. For rollback, `AppendState(dst)` appends the recognizer's complete state (buffered frames and the progress of every move and combo) to a snapshot, and `LoadState` restores it on a recognizer built from the same move set before re-simulating; it refuses state from a different move set and leaves the recognizer unchanged. The history itself is a `Buffer`, a ring of `Frame`s (absolute and relative direction, facing, held and newly pressed buttons) sized by `MoveSet.Lookback`, reachable through `Recognizer.Buffer` for input displays and training modes. ## Testing with replays `Recognizer.Update` takes any `Source` (`Pressed` and `Axis`), which `*input.Actions`, `*replay.Recorder` and `*replay.Player` all satisfy, so recorded inputs from [replay](https://game.nsgo.dev/docs/replay/) drive it directly: ```go recording, _ := replay.LoadFile("testdata/session.replay.yaml") p := replay.NewPlayer(recording) for !p.Done() { p.Step() res := rec.Update(p, fighting.FaceRight) // assert on res.Step and res.Moves } ``` The package's own tests record scripted inputs this way and check every motion one step inside and one step outside its window, buffer, charge time, grace and combo gap. --- Source: https://game.nsgo.dev/docs/flow/ # flow `game/flow` holds gameplay control-flow primitives driven exclusively by `game.Loop`'s fixed `dt`: game-clock `Timers`, typed finite state machines (`Machine[S]`), hierarchical state machines (`HSM[S]`), composable step sequences (`Seq`, `Parallel`, `Race`), and a zero-global-state typed event `Bus`. ```go import "github.com/nsgo-dev/game/pkg/flow" ``` Nothing in `flow` reads the wall clock, spawns goroutines, or holds package-level state — every primitive pauses with your loop, replays deterministically, and isolates cleanly per scene. ## Game-clock Timers `Timers` schedules one-shot (`After`) and drift-free repeating (`Every`) callbacks on the game clock. Its zero value is ready to use: ```go var timers flow.Timers // Fire once after 2 seconds of game time invuln := timers.After(2*time.Second, func() { player.Invulnerable = false }) // Repeat every 500ms, carrying overshoot so periods never drift spawner := timers.Every(500*time.Millisecond, spawnWave) // Inside Loop.Update: timers.Update(dt) ``` Pause timers during menus or hit-stop with `timers.SetPaused(true)` (or `timers.Paused = true`), inspect remaining time with `invuln.Remaining()` / `invuln.Active()`, cancel with `spawner.Cancel()`, or cancel all with `timers.Clear()`. ## Finite state machines (`Machine[S]`) `Machine[S]` models character, boss, or match states keyed by any comparable type `S`: ```go type HeroState int const ( StateIdle HeroState = iota StateRun StateHurt ) fsm := flow.NewMachine(StateIdle) fsm.AddState(StateIdle, flow.State{ Enter: func() { playAnim("idle") }, Update: func(dt time.Duration) { recoverStamina(dt) }, }) fsm.AddState(StateRun, flow.State{ Enter: func() { playAnim("run") }, Update: func(dt time.Duration) { moveHero(dt) }, Exit: func() { stopFootsteps() }, }) fsm.AddState(StateHurt, flow.State{ Enter: func() { knockback() }, }) fsm.AddTransition(StateIdle, StateRun, func() bool { return moveSpeed > 0 }) fsm.AddTransition(StateRun, StateIdle, func() bool { return moveSpeed == 0 }) fsm.AddAnyTransition(StateHurt, func() bool { return hitThisStep }) fsm.AddTransition(StateHurt, StateIdle, func() bool { return fsm.TimeInState() >= 400*time.Millisecond }) // Inside Loop.Update: fsm.Update(dt) ``` - `Update(dt)` starts the machine on its first call (or call `fsm.Start()` explicitly), evaluates transitions in declaration order (taking at most one per step), advances `TimeInState()`, and runs the active state's `Update`. - Force an immediate switch with `fsm.SetState(to)`. Inspect `fsm.Current()`, `fsm.Previous()`, `fsm.TimeInState()`, `fsm.Started()`, and `fsm.Step()`. - **Save and restore**: `snap := fsm.Snapshot()` returns a plain `MachineSnapshot[S]` struct (`Version`, `Current`, `Previous`, `TimeInState`, `Started`) that marshals cleanly to YAML and JSON. `fsm.Restore(snap)` validates that `Current` (and any non-zero `Previous`) belongs to the machine before replacing its state, refuses unknown states or invalid timings with `ErrInvalidSnapshot` without mutating the machine, and never runs `Exit` or `Enter` hooks. - **Bounded transition history**: `Machine[S]` keeps the most recent `DefaultHistoryLimit` (32) transitions in a fixed ring buffer (`TransitionRecord[S]{From, To, Step, Transition}`), tunable with `SetHistoryLimit(n)` (`0` disables recording) and cleared with `ClearHistory()`. Label transitions with `AddNamedTransition` / `AddNamedAnyTransition` (unnamed transitions default to `"from->to"` / `"*->to"`, and `SetState` records `"SetState"`). Read history with `History()` or zero-allocation `HistoryInto(dst)`. - **Inspection and `statedump` formatting**: every `*Machine[S]` implements the type-erased `MachineInspector` interface (`Inspect() MachineInspection`, `FormatState() string`) so you can pass any machine to [`game/debug`](https://game.nsgo.dev/docs/debug/)'s AI panel or record `fsm.FormatState()` in [`statedump`](https://game.nsgo.dev/docs/statedump/) `Values` to diff transitions between runs. ## Hierarchical state machines (`HSM[S]`) When character or enemy logic outgrows a flat machine, `HSM[S]` nests child machines inside parent states so shared interrupts (such as `stunned` or `dead`) apply across every descendant without duplicating transitions: ```go type EnemyState string const ( StatePatrol EnemyState = "patrol" StateCombat EnemyState = "combat" StateApproach EnemyState = "approach" StateAttack EnemyState = "attack" StateRecover EnemyState = "recover" StateStunned EnemyState = "stunned" ) type StunHit struct{ Poise float64 } combat := flow.NewHSM(StateApproach) combat.SetHistory(true) // re-entering combat resumes its last active sub-state combat.AddState(StateApproach, flow.State{Enter: func() { playAnim("approach") }}) combat.AddState(StateAttack, flow.State{Enter: func() { playAnim("attack") }}) combat.AddState(StateRecover, flow.State{Enter: func() { playAnim("recover") }}) combat.AddTransition(StateApproach, StateAttack, func() bool { return inRange }) combat.AddEventTransition(StateAttack, StateRecover, "attack_done") combat.AddTransition(StateRecover, StateApproach, func() bool { return combat.TimeInState() >= 400*time.Millisecond }) enemy := flow.NewHSM(StatePatrol) enemy.AddState(StatePatrol, flow.State{Enter: func() { playAnim("patrol") }}) enemy.AddState(StateCombat, flow.State{ Enter: func() { drawWeapon() }, Exit: func() { sheatheWeapon() }, }) enemy.AddChild(StateCombat, combat) enemy.AddState(StateStunned, flow.State{Enter: func() { playAnim("stunned") }}) enemy.AddTransition(StatePatrol, StateCombat, func() bool { return spotted }) flow.OnEvent(enemy, StateCombat, StateStunned, func(e StunHit) bool { return e.Poise >= 15 }) enemy.AddTransition(StateStunned, StateCombat, func() bool { return enemy.TimeInState() >= 800*time.Millisecond }) // Optional: forward typed events from a flow.Bus into the HSM queue. unsub := flow.BindBus[StunHit](enemy, &bus) defer unsub() // Inside Loop.Update: enemy.Update(dt) ``` - **Outside-in `Enter` / inside-out `Exit`**: entering `StateCombat` runs `combat`'s `Enter` before its active child's `Enter`; leaving `StateCombat` runs the child's `Exit` before `combat`'s `Exit`. Cross-branch transitions exit up to the lowest common ancestor and enter down to the target leaf. - **Innermost-first transitions**: transitions declared on a parent apply while any descendant is active, with the innermost active state checked first so child states can override parent transitions. - **Deterministic events**: send events with `enemy.Send(ev)` or subscribe a `flow.Bus` event type with `flow.BindBus[E](enemy, &bus)`. Register value-matched transitions with `AddEventTransition` / `AddAnyEventTransition` or typed payload transitions with `flow.OnEvent` / `flow.OnAnyEvent`. Queued events are processed once per `Update` step in FIFO send order; events sent during callbacks wait for the next step. - **Shallow history**: call `child.SetHistory(true)` so re-entering its parent resumes the last active direct child instead of `initial` (reset with `ClearHistory()`). - **Path inspection**: `enemy.Current()` returns the active path from root to leaf (`[]S`), `enemy.Leaf()` returns the innermost active state, `enemy.In(state)` checks whether a state is anywhere on the active path, and `enemy.TimeIn(state)` reports elapsed game time in an active state. ## Step sequences (`Runner`, `Seq`, `Parallel`, `Race`) Compose cutscenes, attack patterns, and scripted encounters without goroutines using `Runner` and `Step` combinators: ```go var runner flow.Runner bossIntro := flow.Seq( flow.Do(func() { lockPlayerInput(true) }), flow.Parallel( flow.Wait(600*time.Millisecond), flow.While(func() bool { return doorOpen < 1 }, func(dt time.Duration) { doorOpen += float32(dt.Seconds()) * 2 }), ), flow.Race( flow.WaitUntil(func() bool { return actions.JustPressed("skip") }), flow.Seq( flow.Do(func() { showBossTitle() }), flow.Wait(2*time.Second), ), ), flow.Do(func() { lockPlayerInput(false) }), ) handle := runner.Start(bossIntro) // Inside Loop.Update: runner.Update(dt) ``` Built-in `Step` combinators: | Combinator | Behavior | | --- | --- | | `Do(fn)` | Calls `fn` once and finishes immediately, passing all remaining `dt` onward. | | `Wait(d)` | Waits for `d` of game time to elapse. | | `WaitUntil(cond)` | Finishes on the first step where `cond()` returns `true`. | | `While(cond, update)` | Runs `update(dt)` each step while `cond()` is `true`. | | `Seq(steps...)` | Runs steps in order, carrying leftover `dt` from a finished step into the next on the same tick. | | `Parallel(steps...)` | Steps all branches each tick until every branch finishes. | | `Race(steps...)` | Steps branches in order until the first finishes, then cancels the rest. | | `Repeat(n, makeStep)` | Repeats the step from `makeStep()` `n` times sequentially. | | `Loop(makeStep)` | Repeats indefinitely until its `Handle` or enclosing `Race` cancels it. | Cancel an in-flight sequence cleanly with `handle.Cancel()` (or `runner.Clear()`), and check `handle.Done()`. ## Typed event Bus `Bus` decouples systems inside a scene without globals or string keys: ```go type EnemyDefeated struct { Kind string Score int } var bus flow.Bus unsub := flow.Subscribe(&bus, func(ev EnemyDefeated) { score += ev.Score }) defer unsub() // Immediate synchronous delivery in subscription order: flow.Publish(&bus, EnemyDefeated{Kind: "slime", Score: 50}) // Or buffer events during physics/collision and flush once per step: flow.Enqueue(&bus, EnemyDefeated{Kind: "bat", Score: 100}) bus.Flush() ``` Use `flow.SubscribeOnce(&bus, fn)` for one-shot listeners, and `bus.Clear()` when tearing down a scene. Subscribing or unsubscribing inside a handler never skips remaining listeners for the event in flight. --- Source: https://game.nsgo.dev/docs/fog/ # fog `game/fog` tracks fog of war for strategy games on orthogonal, isometric, staggered, and hexagonal tile grids: which cells each team can see now, which it has explored before, and which it has never seen. It draws the fog aligned to the tilemap's projection and saves it with the rest of a game. ```go import "github.com/nsgo-dev/game/pkg/fog" ``` ## Teams, sources and states A `Fog` covers a grid of cells. Each team (`fog.Team`, any `int`) sees through its vision sources: units, buildings or wards, each with a cell and a radius in cells. To each team a cell is one of three `State`s: | State | Meaning | Drawn as | | --- | --- | --- | | `Unseen` | The team has never seen the cell. | `Style.Unseen`, opaque black by default | | `Explored` | The team saw the cell before but cannot see it now. | `Style.Explored`, half-transparent black by default | | `Visible` | One of the team's sources sees the cell now. | Uncovered | ```go f := fog.NewFromTilemap(level, tilemap.TileSolid) // walls block sight scout := f.AddSource(fog.Source{Team: player, Col: 4, Row: 6, Radius: 7}) f.Update() ``` - `NewFromTilemap(m, mask)` copies the map's size, tile size, and projection (`Orientation`, `StaggerAxis`, `StaggerIndex`, `HexSideLength`), and makes every cell whose tilemap flags include a bit of `mask` opaque. `New(width, height, tileWidth, tileHeight)` starts from an empty orthogonal grid (it panics on a negative size, a grid with exactly one zero size, or more than `MaxCells` cells); set `Orientation` and stagger fields if building a non-orthogonal fog without a tilemap, and use `SetOpaque` to change one cell later, such as when a door opens. - On orthogonal and isometric grids, a cell `dx` columns and `dy` rows from a source is in range when `dx*dx+dy*dy <= Radius*Radius+Radius`, which rounds the disc (staggered grids evaluate the same rounded disc in their underlying diamond lattice). On hexagonal grids, a cell is in range when its `HexDistance` from the source is at most `Radius`. Radius 0 sees only the source's own cell, and a source outside the grid sees nothing. - Opaque cells block sight by symmetric shadowcasting with exact integer slopes (4 quadrants on orthogonal/isometric/staggered grids, 6 axial sextants on hexagonal grids): a floor cell A sees a floor cell B exactly when B sees A, and the result never depends on floating-point rounding, so every client in a lockstep match computes the same fog. An opaque cell is itself seen when sight reaches it, so walls show at the edge of vision. - Sources of the same team share vision; other teams' sources reveal nothing to it. ## Updating as units move Move sources during a fixed step and call `Update` once before reading or drawing the fog: ```go loop.Update = func(dt time.Duration) { moveUnits(dt) for _, u := range units { f.MoveTo(u.Vision, u.Pos) // or f.Move(id, col, row) } f.Update() } ``` - `Update` recomputes only the teams whose sources or opaque cells changed since the last call, adds what they see to what they have explored, and reports whether any team's fog changed. - `SetSource` changes a source's team, cell or radius at once; `RemoveSource` drops it when a unit dies, and the team keeps what it explored. - `State`, `Visible` and `Explored` answer for a cell, and `VisibleAt(team, p)` for a world point, such as to hide enemy units in the fog. `CellAt(p)` turns a world point into a cell using the fog's `TileWidth`, `TileHeight`, and projection (`Orientation`, `StaggerAxis`, `StaggerIndex`, `HexSideLength`), matching `tilemap.Tilemap.WorldToTile`. - `Explore`, `ExploreRect` and `ExploreAll` mark cells explored without making them visible (a scouting report or a revealed landmark), `Forget` clears everything a team explored except what it sees now, and `ExploredCount` counts its explored cells. - `Revision(team)` grows whenever a team's visible or explored cells change, and every team gets a fresh one when the fog is loaded, so a minimap or a cached fog image redraws only when it differs. Revisions come from one counter shared by every fog in the program, so a fog loaded in place of another, even through `save.Store.Load`, never repeats a revision a cache has already seen. ## Drawing over the map Draw the fog after the tilemap and the units, under the same camera transform: ```go d.Save() cam.Apply(d) level.Draw(d, cam) drawUnits(d) f.Draw(d, player, cam, fog.DefaultStyle()) d.Restore() ``` `Draw` fills one path over the unseen cells and one over the explored cells and leaves visible cells uncovered: horizontal runs of rectangles on orthogonal grids, aligned tile diamonds on isometric and staggered grids, and aligned pointy-top or flat-top hexagons on hexagonal grids matching `tilemap.Tilemap`'s projection. Like `Tilemap.Draw`, it uses the camera only to skip cells outside `cam.VisibleBounds()`, and a nil camera draws the whole grid. A `Style` color with zero alpha leaves those cells uncovered, such as `fog.Style{Unseen: core.RGB(0x000000)}` for a game without remembered terrain. ## Saving A `Fog` marshals to versioned JSON text, so it goes into a `save.Store` slot inside the game's own state: ```go type saved struct { Units []unitSave `json:"units"` // each unit keeps its fog.SourceID Fog *fog.Fog `json:"fog"` } store.Save("slot1", saved{Units: units, Fog: f}) var s saved store.Load("slot1", &s) // s.Fog sees and has explored exactly what f did ``` ```json {"version":1,"width":3,"height":2,"tileWidth":8,"tileHeight":8,"opaque":[".#.","..."],"nextSource":2,"sources":[{"id":1,"team":2,"col":2,"row":1,"radius":1},{"id":2,"team":1,"col":0,"row":0,"radius":0}],"teams":[{"team":1,"explored":["#..","..."]},{"team":2,"explored":[".##",".##"]}]} ``` - The snapshot holds the grid and tile size, optional projection fields (`orientation`, `staggerAxis`, `staggerIndex`, `hexSideLength`, omitted on orthogonal grids), the opaque cells, the sources with their IDs, and each team's explored cells as rows of `.` and `#`, one string per grid row, so a person reading the save sees each team's explored map. Visible cells are not stored: loading recomputes them from the sources and opaque cells. - The same fog always writes the same bytes: fields in a fixed order, sources by ID, teams in increasing order, and no timestamps. Loading and saving again changes nothing. - Loading keeps source IDs and the next ID to hand out, so a unit's saved `fog.SourceID` still moves its source. - Loading refuses unknown fields, a missing version, a newer version (`ErrFutureVersion`), rows that disagree with the grid size, sources or teams out of order or repeated, a source ID of 0 or above `nextSource`, a source whose team has no explored grid, grids larger than `MaxCells`, and grids with exactly one zero size; every other error wraps `ErrInvalidSnapshot`, and a refused snapshot leaves the fog unchanged. --- Source: https://game.nsgo.dev/docs/formats/ # File Formats Every file a game made with these packages reads or writes, with the names its files go by, the version it declares, the Go functions that read and write it, the guide that describes its fields and an example, so a person or an AI can edit one without reading the code. The files a game's author writes are YAML, apart from those under JSON files and Other tools' formats below. The tests check every example on this page: a YAML example is in its format's canonical form, the bytes its encoder writes, and loads and saves back unchanged, so none shows a key the format refuses or a layout it would rewrite; a JSON or Yarn example loads with the format's reader. ## What every YAML format does - **A version.** The document's top-level `version` key, an integer, says which version of the format it is in; a mod manifest calls it `manifestVersion`. A file without it, with `version: 0` or with a version newer than the code reads is refused. - **Strict keys.** A key the format does not define is refused, as are a second YAML document in the file and a key given twice, with an error that names the file, line and field and says how to fix it ([Errors](https://game.nsgo.dev/docs/errors/)). - **One canonical form.** Saving writes the keys in a fixed order, sorts what has no order of its own and writes no timestamp or random ID, so the same value always gives the same bytes and a file in that form loads and saves back unchanged. The first save of a hand-written file drops its comments and rewrites its layout into that form; every save after that changes only what changed. - **Schemas.** Scene files and import settings sidecars have published JSON Schemas, and a data table's schema is generated from its row type, so an editor completes and checks them as they are written ([Schemas for YAML files](https://game.nsgo.dev/docs/schemas/)). ## Project and assets ### Project file | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `game.yaml` at the project's root | `version: 1` | `project.Parse`, `project.Encode` | [Project File](https://game.nsgo.dev/docs/project/); schema `https://game.nsgo.dev/schemas/game.v1.json` | ```yaml version: 1 name: Cave Run id: dev.nsgo.caverun appVersion: 0.1.0 window: title: Cave Run width: 960 height: 540 display: width: 320 height: 180 mode: fit autoload: mainScene: title scenes: - name: title path: scenes/title.scene.yaml ``` ### Game brief | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `brief.yaml` at the project's root | `version: 1` | `project.ParseBrief`, `project.EncodeBrief` | [Editor](https://game.nsgo.dev/docs/editor/#game-brief-and-project-rules-1026); schema `https://game.nsgo.dev/schemas/brief.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/brief.v1.json version: 1 pitch: 'A short, tense dungeon platformer: a knight with one sword and three hearts dives through five floors, each ending in a door that only opens once its lever is found.' genre: [2D platformer, action] tags: [dungeon, pixel-art] platforms: [desktop, 'phones, touch', web] artDirection: 16 px pixel art, 4-colour shading, cold stone with warm torch light. No outlines on tiles; 1 px dark outline on characters. feel: summary: Snappy, forgiving jumps (coyote time). A first-time player clears floor 1 in under a minute and dies 2–4 times on floor 3. targets: - metric: median_time scene: floor_01 summary: first-time player clears floor 1 in under a minute unit: s max: 60 - metric: deaths scene: floor_03 summary: 2–4 deaths on floor 3 min: 2 max: 4 ``` ### Editor settings | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Per-user `editor.yaml` under the user config directory (`editor.DefaultSettingsPath`), outside any project | `version: 1` | `editor.ParseEditorSettings`, `editor.EncodeEditorSettings` | [Editor](https://game.nsgo.dev/docs/editor/#language-and-appearance-settings-921); schema `https://game.nsgo.dev/schemas/editor-settings.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/editor-settings.v1.json version: 1 language: system appearance: system autoSave: true viewportOverlays: - collision_shapes - connections - navigation - triggers overlayLegend: - added - agent - changed - problem - removed - selection shortcuts: view.frame: g seenTips: - first_review.ask_selection - first_review.hold_b - first_review.keep_revert agent: builtInProvider: Anthropic API tools: game_delete_file: false mcpServers: - name: nsgo-game title: Running game · nsgo dev description: inspect and drive the live game command: go args: - tool - nsgo - mcp enabled: true weeklyRequestLimit: 300 privacy: sceneAndData: true viewportImages: true goSource: false artAndAudio: false ``` ### Editor MCP permissions | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `permissions.yaml` beside `game.yaml` (tracked in Git and shared across the team) | `version: 1` | `editor.ParsePermissions`, `editor.EncodePermissions` | [Editor](https://game.nsgo.dev/docs/editor/#permissions-and-mcp-enforcement-1010); schema `https://game.nsgo.dev/schemas/permissions.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/permissions.v1.json version: 1 profile: balanced rules: - action: edit patterns: - scenes/** - prefabs/** - data/** decision: allow - action: run patterns: - game check - playtests decision: allow - action: edit patterns: - game.yaml - brief.yaml decision: ask - action: code patterns: - '**/*.go' decision: ask - action: create patterns: - '**' decision: ask - action: delete patterns: - '**' decision: deny - action: run patterns: - shell decision: deny ``` ### Agent background task thread | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.nsgo/threads/.thread.yaml` under a project root (default `default.thread.yaml`) | `version: 1` | `editor.ParseAgentThread`, `editor.EncodeAgentThread` | [Editor](https://game.nsgo.dev/docs/editor/#background-task-list-with-queued-and-parallel-agent-requests-1022) | ```yaml version: 1 id: default scene: scenes/level_01.scene.yaml tasks: - id: task-1 number: 1 title: slime_02 jumps the gap at x 360 source: you startMode: queue state: running scene: scenes/level_01.scene.yaml stepSummary: placing the jump arc editingObjects: - slime_02 - id: task-2 number: 2 title: Coin pickup sound a little higher source: you startMode: queue state: queued startsAfterTaskId: task-1 ``` ### Editor automations | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `automations.yaml` at the project's root beside `game.yaml` | `version: 1` | `editor.ParseAutomations`, `editor.EncodeAutomations` | [Editor](https://game.nsgo.dev/docs/editor/#agent-automations-1029); schema `https://game.nsgo.dev/schemas/automations.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/automations.v1.json version: 1 automations: - id: level-check name: A level file changes enabled: true trigger: event: file_changed glob: scenes/level_*.scene.yaml instruction: runs game check and 5 playtests, reports only problems - id: review-brief name: You keep a review enabled: true trigger: event: review_kept instruction: updates the brief's open questions if the change answers one - id: new-prefab-example name: A new prefab is added enabled: true trigger: event: file_added kind: prefab instruction: writes its example scene and a test - id: before-export-mobile name: Before export enabled: false trigger: event: before_export instruction: checks frame time and memory on a low-end phone profile - id: nightly-balance name: Every night enabled: false trigger: event: daily time: "02:00" instruction: plays all floors 50 times and leaves a balance report ``` ### Import settings sidecar | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.import.yaml` beside an image, sound, font or model, such as `hero.png.import.yaml` | `version: 1` | `importsettings.Parse`, `importsettings.Encode` | [Command Line](https://game.nsgo.dev/docs/cli/#assets); schema `https://game.nsgo.dev/schemas/import.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/import.v1.json version: 1 image: filter: nearest slice: width: 16 height: 16 count: 6 pivot: default: [0.5, 1] cells: - cell: 2 pivot: [0.25, 0.75] credit: author: Kenney license: CC0-1.0 source: https://kenney.nl/assets/kenney-fonts ``` ### Generated asset source sidecar | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.source.yaml` beside a generated image or sound, such as `slime_frost.png.source.yaml` | `version: 1` | `importsettings.ParseAssetSource`, `importsettings.EncodeAssetSource` | [Editor](https://game.nsgo.dev/docs/editor/); schema `https://game.nsgo.dev/schemas/source.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/source.v1.json version: 1 generator: pixel-gen model: pixflux-1 prompt: ice slime, 16 px pixel art, 4-colour shading, 1 px dark outline, facing right seed: 81515 references: - art/characters/slime.png - brief.yaml#art license: pixellab-commercial-1.2 commercialUse: true approvedBy: kim ``` ### Project index | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `game.index.yaml` beside `game.yaml`, kept by `game index`, `game mv` and the editor | `version: 1` | `refs.ParseIndex`, `refs.EncodeIndex` | [Stable references](https://game.nsgo.dev/docs/project/#stable-references) | ```yaml # The stable IDs of this project's files, kept by game index, game mv and the editor. Keep it in version control. version: 1 files: - path: art/hero.png sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 - path: scenes/room.scene.yaml uid: scene00000001 ``` ### Library pack manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `pack.yaml` at the root of an asset or plugin pack | `version: 1` | `library.ParseManifest`, `library.EncodeManifest` | [Asset and Plugin Library](https://game.nsgo.dev/docs/library/) | ```yaml version: 1 name: coins kind: asset packVersion: 1.0.0 description: A spinning coin. license: CC0-1.0 files: - coin.png autoload: resources: - name: coin path: coin.png ``` ### Library index | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `index.yaml` at the root of a pack library | `version: 1` | `library.ParseIndex`, `library.EncodeIndex` | [Asset and Plugin Library](https://game.nsgo.dev/docs/library/) | ```yaml version: 1 packs: - name: dungeon-tiles kind: asset packVersion: "1" description: Stone tiles. tags: [2d, tiles] license: CC0-1.0 source: b sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 ``` ### Localized asset manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `assets.yaml` | `version: 1` | `l10n.ParseAssetManifest`, `l10n.EncodeAssetManifest` | [l10n](https://game.nsgo.dev/docs/l10n/) | ```yaml version: 1 base_locale: en assets: ui/title_banner.png: en: ui/title_banner.png zh-Hans: ui/title_banner.zh-Hans.png voice/intro.wav: en: locales/en/voice/intro.wav ja: locales/ja/voice/intro.wav groups: voice: - voice/intro.wav ``` ### Localization string table (YAML) | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | One `.yaml` file per locale, such as `locales/en.yaml` | `version: 1` | `l10n.ParseYAML`, `l10n.EncodeYAML`, `l10n.Catalog.LoadYAML` | [l10n](https://game.nsgo.dev/docs/l10n/) | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/l10n.v1.json version: 1 locale: en strings: hud.score: 'Score: {score}' menu.play: Play menu.quit: Quit plurals: coins: zero: No coins one: '{count} coin' other: '{count} coins' ``` ### Mod manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `mod.yaml` at the root of a mod's directory | `manifestVersion: 1` | `modding.ParseManifest`, `modding.EncodeManifest` | [modding](https://game.nsgo.dev/docs/modding/) | ```yaml manifestVersion: 1 id: com.example.boss-rush name: Boss Rush version: 1.2.0 author: Example Studio description: Spawns a slime every five seconds and shows a HUD badge while the rush runs. entry: mod.tsx gameVersion: '>=0.2.0' capabilities: [readState, spawnEntity, emitEvent, ui] ``` ### Steam Workshop metadata | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `workshop.yaml` beside `mod.yaml` in a mod published to Steam Workshop | `version: 1` | `modding.ParseWorkshopMetadata`, `modding.EncodeWorkshopMetadata` | [modding](https://game.nsgo.dev/docs/modding/) | ```yaml version: 1 appId: 480 publishedFileId: 1001 title: Boss Rush description: Spawns a slime every five seconds. tags: [gameplay, survival] visibility: public preview: preview.png ``` ### 3D shader material | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.material.yaml`, hot-reloaded in `game dev` | `version: 1` | `hotreload.ParseMaterial`, `hotreload.EncodeMaterial` | [render3d](https://game.nsgo.dev/docs/render3d/) | ```yaml version: 1 name: Crate shader: shaders/lit.wgsl blend: opaque cull: back frontFace: ccw depthCompare: less scalars: roughness: 0.4 colors: tint: '#d9c6a5' textures: albedo: textures/crate.png ``` ### Voxel world | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.voxel.yaml` | `version: 1` | `voxel.Parse`, `voxel.Encode` | [voxel](https://game.nsgo.dev/docs/voxel/); schema `https://game.nsgo.dev/schemas/voxel.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/voxel.v1.json version: 1 name: hill chunkSize: 4 voxelSize: 1 palette: - id: 1 name: stone chunks: - x: 0 "y": 0 z: 0 runs: - 1*4 - 0*60 ``` ### 3D grid map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.gridmap.yaml` | `version: 1` | `world3d.ParseGridMap`, `world3d.EncodeGridMap`, `world3d.LoadGridMapFS` | [world3d](https://game.nsgo.dev/docs/world3d/); schema `https://game.nsgo.dev/schemas/gridmap.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/gridmap.v1.json version: 1 name: Stone Keep cellSize: - 2 - 2 - 2 meshLibrary: models/dungeon_tiles.gltf boxes: - min: - 0 - 0 - 0 max: - 4 - 0 - 4 tile: stone_floor cells: - at: - 0 - 1 - 0 tile: stone_pillar - at: - 4 - 1 - 0 tile: stone_pillar orientation: 1 ``` ### Terrain definition | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.terrain.yaml` | `version: 1` | `world3d.ParseTerrain`, `world3d.EncodeTerrain`, `world3d.LoadTerrainFS` | [world3d](https://game.nsgo.dev/docs/world3d/); schema `https://game.nsgo.dev/schemas/terrain.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/terrain.v1.json version: 1 name: Alpine Valley heightmap: terrain/alpine_height.png cellSize: 2 heightScale: 40 splatMaps: - terrain/alpine_splat0.png heightBlendContrast: 0.65 triplanar: enabled: true slopeThreshold: 0.7 slopeBlend: 0.15 sharpness: 4 scale: 0.25 layers: - name: grass albedo: textures/grass_albedo.png normal: textures/grass_normal.png height: textures/grass_height.png roughness: 0.85 uvScale: - 16 - 16 - name: dirt albedo: textures/dirt_albedo.png normal: textures/dirt_normal.png height: textures/dirt_height.png roughness: 0.9 uvScale: - 12 - 12 heightBias: -0.05 - name: rock albedo: textures/rock_albedo.png normal: textures/rock_normal.png height: textures/rock_height.png roughness: 0.8 uvScale: - 8 - 8 heightBias: 0.1 - name: snow albedo: textures/snow_albedo.png normal: textures/snow_normal.png roughness: 0.5 uvScale: - 10 - 10 heightBias: 0.05 ``` ### 3D foliage layers | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.foliage.yaml` | `version: 1` | `world3d.ParseFoliage`, `world3d.EncodeFoliage`, `world3d.LoadFoliageFS` | [world3d](https://game.nsgo.dev/docs/world3d/); schema `https://game.nsgo.dev/schemas/foliage.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/foliage.v1.json version: 1 name: Alpine Meadow terrain: terrain/alpine.terrain.yaml layers: - name: grass mesh: models/grass_clump.glb material: materials/grass.material.yaml density: 1.5 minScale: 0.8 maxScale: 1.3 alignToNormal: 0.6 maxSlopeDeg: 35 baseMaxDistance: 80 seed: 42 - name: pine_tree mesh: models/pine_tree.glb densityMap: terrain/forest_density.png spacing: 4 minScale: 0.85 maxScale: 1.25 maxSlopeDeg: 28 minHeight: 2 maxHeight: 32 baseMaxDistance: 160 boundingRadius: 3.5 seed: 108 ``` ## Scenes, resources and animation ### Scene | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.scene.yaml`, such as `scenes/cave_room.scene.yaml` | `version: 1`, `version: 2` (instancing, inheritance, glTF models, particle emitters, layered tilemaps, LDtk levels), `version: 3` (parallax and repeating layers, tilemap offsets), or `version: 4` (3D lights, scene environment, 3D cameras, reflection probes, light probe grids); built-in physics components `version: 1`; built-in 2D lighting components `version: 1`; built-in 2D navigation region component `version: 1` | `sceneformat.Parse`, `sceneformat.Encode` | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/); schemas `https://game.nsgo.dev/schemas/scene.v1.json`, `scene.v2.json`, `scene.v3.json` and `scene.v4.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/scene.v1.json version: 1 name: Cave Room virtualWidth: 320 virtualHeight: 180 layers: - name: actors space: world order: 10 objects: - id: hero x: 48 "y": 40 sprite: atlas: actors frame: hero ``` ### Game UI screen | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.screen.yaml`, such as `screens/hud.screen.yaml` and `screens/pause.screen.yaml` | `version: 1` | `gameui.ParseScreen`, `gameui.EncodeScreen`, `gameui.LoadScreenFS`, `gameui.BuildScreen` | [gameui](https://game.nsgo.dev/docs/gameui/); schema `https://game.nsgo.dev/schemas/screen.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/screen.v1.json version: 1 name: hud designWidth: 640 designHeight: 360 nodes: - id: status type: vbox anchor: top_left offset: x: 12 "y": 12 spacing: 4 children: - id: hearts type: sprite_row width: 52 height: 14 sprite: art/ui/heart.png spriteCount: 3 - id: coins type: label sizeMode: fit_text height: 16 textKey: hud.coins - id: touch type: container deviceClasses: - phone - tablet children: - id: jump type: touch_button anchor: bottom_right offset: x: 24 "y": 28 width: 52 height: 52 textKey: hud.jump touchHitSize: 64 ``` ### Scene merge conflict report | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Written by `game merge` (overwriting the unmerged `*.scene.yaml` or `-conflict-out`) when a three-way scene merge has conflicts | `version: 1` | `sceneformat.ParseConflict`, `sceneformat.EncodeConflict` | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/#merging-scene-files-in-git-1058), [Command Line](https://game.nsgo.dev/docs/cli/#merge) | ```yaml version: 1 path: scenes/level_01.scene.yaml merged: - scope: object target: slime_03 side: ours action: added conflicts: - kind: field scope: object layer: actors object: door field: x base: 584 ours: 560 theirs: 600 - kind: delete-modify scope: object layer: actors object: slime_02 message: modified on ours, deleted on theirs base: id: slime_02 x: 240 "y": 280 ours: components: patrol: speed: 30 id: slime_02 x: 240 "y": 280 theirs: null ``` ### 3D navigation meshes | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.navmesh.yaml`, such as `levels/level1.navmesh.yaml`, which a scene's `navMesh` names | `version: 1` | `navbake3d.Parse`, `navbake3d.Encode`; baked by `game navmesh` | [navbake3d](https://game.nsgo.dev/docs/navbake3d/) | ```yaml version: 1 settings: cellSize: 0.3 cellHeight: 0.2 minRegionArea: 1 maxEdgeLength: 12 maxSimplificationError: 0.4 maxVertsPerPoly: 6 detailSampleDistance: 1.8 detailSampleMaxError: 0.2 layerMask: 4294967295 meshes: - agent: name: humanoid radius: 0.6 height: 2 maxSlope: 45 maxClimb: 0.9 vertices: - [0, 0, 0] - [0, 0, 4] - [4, 1, 4] - [4, 1, 0] - [8, 1, 4] - [8, 1, 0] polygons: - vertices: [0, 1, 2, 3] detail: - [2, 0.75, 2] triangles: - [0, 1, 4] - [1, 2, 4] - [2, 3, 4] - [3, 0, 4] - vertices: [3, 2, 4, 5] triangles: - [0, 1, 2] - [0, 2, 3] ``` ### Baked light probe grids | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.probes.yaml`, such as `probes/room.probes.yaml`, which a scene object's `lightProbeGrid.data` names | `version: 1` | `render3d.ParseLightProbeGrid`, `render3d.EncodeLightProbeGrid`, `render3d.LoadLightProbeGridFS` | [render3d](https://game.nsgo.dev/docs/render3d/); schema `https://game.nsgo.dev/schemas/lightprobes.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/lightprobes.v1.json version: 1 boundsMin: [-4, 0, -4] boundsMax: [4, 4, 4] counts: [2, 1, 1] probes: - sh: - [0.5, 0.4, 0.3] - [0.1, 0.05, 0] - [0, 0, 0] - [0.15, 0.02, 0.02] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - sh: - [0.3, 0.4, 0.5] - [0.05, 0.05, 0.1] - [0, 0, 0] - [-0.02, 0.02, 0.15] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] - [0, 0, 0] ``` ### Tileset | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.tileset.yaml`, such as `tilesets/cave.tileset.yaml`, named by a scene's inline or layered tilemap (`tilesetFile`) | `version: 1` | `tilemap.ParseTileset`, `tilemap.EncodeTileset`, `tilemap.LoadTilesetFS`; `Tilemap.AddTilesetDoc` builds it | [tilemap](https://game.nsgo.dev/docs/tilemap/#yaml-tilesets); schema `https://game.nsgo.dev/schemas/tileset.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/tileset.v1.json version: 1 name: cave tileWidth: 16 tileHeight: 16 image: tiles/cave.png columns: 4 tileCount: 8 terrains: - name: rock mode: cardinal tiles: - id: 0 solid: true terrain: rock - id: 1 solid: true properties: friction: 0.5 terrain: rock neighbors: [east] - id: 2 shapes: - kind: polygon points: [[0, 16], [16, 0], [16, 16]] - id: 4 animation: - tile: 4 duration: 200ms - tile: 5 duration: 200ms ``` ### Shared resource | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `..yaml`, such as `stone.material.yaml`; `type` is `material`, `curve`, `gradient`, `animation`, `theme`, `busLayout` or `physicsMaterial` | `version: 1` | `resource.Parse`, `resource.Encode` | [resource](https://game.nsgo.dev/docs/resources/) | ```yaml type: material version: 1 uid: mat0000000004 name: Stone baseColor: '#8a8f99' texture: textures/stone.png opacity: 0.75 blend: multiply roughness: 0.9 ``` ```yaml type: curve version: 1 name: Jump height keys: - time: 0 value: 0 interp: smooth - time: 0.5 value: 1 - time: 1 value: 0 interp: step ``` ```yaml type: animation version: 1 name: Hero walk length: 0.4 loop: true tracks: - property: sprite.frame frames: - time: 0 frame: hero_walk_0 - time: 0.1 frame: hero_walk_1 - time: 0.2 frame: hero_walk_2 - time: 0.3 frame: hero_walk_3 events: - time: 0.1 name: footstep - time: 0.3 name: footstep ``` ### Sprite state machine | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.states.yaml`, such as `anim/knight.states.yaml` | `version: 1` | `animclip.ParseStateMachine`, `animclip.EncodeStateMachine` | [animclip](https://game.nsgo.dev/docs/animclip/#sprite-state-machines); schema `https://game.nsgo.dev/schemas/states.v1.json` | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/states.v1.json version: 1 name: Knight entry: idle parameters: - name: move.x type: float - name: velocity.y type: float - name: on_floor type: bool default: true - name: jump type: trigger - name: attack type: trigger - name: hurt type: trigger states: - name: idle clip: anim/knight_idle.animation.yaml x: 40 "y": 230 - name: run clip: anim/knight_run.animation.yaml x: 330 "y": 230 - name: jump clip: anim/knight_jump.animation.yaml x: 190 "y": 70 - name: fall clip: anim/knight_fall.animation.yaml x: 430 "y": 70 - name: attack clip: anim/knight_attack.animation.yaml x: 190 "y": 400 - name: hurt clip: anim/knight_hurt.animation.yaml x: 430 "y": 400 transitions: - from: idle to: run label: moving when: '|move.x| > 0.1' - from: run to: idle label: stopped when: '|move.x| <= 0.1' - from: idle to: jump label: jump pressed, on floor when: jump && on_floor - from: run to: jump label: jump pressed, on floor when: jump && on_floor - from: jump to: fall label: falling when: velocity.y > 0 - from: fall to: run label: lands when: on_floor - from: idle to: attack label: attack pressed when: attack - from: run to: attack label: attack pressed when: attack - from: attack to: idle label: clip ends onEnd: true - from: '*' to: hurt label: took damage when: hurt - from: hurt to: idle label: clip ends onEnd: true ``` ### Particle emitter | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.particles.yaml` / `*.emitter.yaml` (or any `.yaml` file the game loads, such as `sparks.yaml`) | `version: 1` | `particles.UnmarshalConfigYAML`, `particles.MarshalConfigYAML`; the same fields as JSON with `UnmarshalConfigJSON` and `MarshalConfigJSON` | [particles](https://game.nsgo.dev/docs/particles/); schema `https://game.nsgo.dev/schemas/particles.v1.json` | ```yaml version: 1 space: local shape: kind: circle radius: 6 rate: 45 maxParticles: 128 lifetimeMin: 300ms lifetimeMax: 700ms speedMin: 20 speedMax: 65 alphaCurve: - t: 0 value: 1 - t: 1 value: 0 frameNames: - spark_0 ``` ### Skeletal rig | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.skel.yaml` | `version: 1` | `skeletal.Load`, `skeletal.Encode` | [skeletal](https://game.nsgo.dev/docs/skeletal/) | ```yaml version: 1 name: waver bones: - {name: root} - {name: arm, parent: root, y: -14, length: 12} slots: - {name: arm, bone: arm} skins: default: arm: {frame: arm, originX: 3, originY: 2} animations: wave: duration: 0.8 loop: true bones: arm: rotate: - {time: 0, angle: 0.4} - {time: 0.4, angle: -0.4} - {time: 0.8, angle: 0.4} ``` ### Cutscene | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.cutscene.yaml` (or any `.yaml` file the game loads), such as `cutscenes/floor1_intro.cutscene.yaml` | `version: 1` (video), `version: 2` (video or timeline) | `cutscene.Parse`, `cutscene.Encode` | [cutscene](https://game.nsgo.dev/docs/cutscene/) | ```yaml version: 1 source: asset:cutscenes/intro.mp4 group: cutscenes skippable: true skipAfter: 1.5s fit: cover ``` ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/cutscene.v2.json version: 2 kind: timeline scene: scenes/level_01.scene.yaml length: 12s skippable: true skipAfter: 1s tracks: - id: camera name: Camera kind: camera clips: - id: cam1 start: 0s duration: 1.6s easing: hold action: hold target: door - id: cam2 start: 1.6s duration: 2.4s easing: easeInOut action: pan target: knight - id: cam3 start: 4s duration: 8s action: follow target: knight - id: knight name: Knight kind: actor target: knight clips: - id: kn1 start: 1s duration: 2.4s easing: easeOut action: walk fromX: 60 toX: 220 state: run - id: kn2 start: 3.4s duration: 4.6s action: state state: idle - id: dialogue name: Dialogue kind: dialogue clips: - id: dl1 start: 3.6s duration: 2.4s line: intro.knight.01 - id: sfx name: Sound kind: sound group: sfx clips: - id: sx1 start: 200ms duration: 600ms source: audio/door_slam.wav - id: music name: Music kind: music group: music clips: - id: mu1 start: 2s duration: 10s source: audio/cellar_theme.ogg fadeIn: 2s ``` ### Room map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `castle.rooms.yaml` | `version: 1` | `rooms.Parse`, `rooms.Encode` | [rooms](https://game.nsgo.dev/docs/rooms/) | ```yaml version: 1 transition: kind: slide duration: 300ms rooms: - id: entrance x: 0 "y": 0 width: 320 height: 180 - id: hall x: 320 "y": 0 width: 640 height: 180 transition: kind: fade color: '#102030' ``` ### World map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `castle.yaml` | `version: 1` | `worldmap.Parse`, `worldmap.Encode` | [worldmap](https://game.nsgo.dev/docs/worldmap/) | ```yaml version: 1 rooms: - id: entrance name: Castle Gate x: 0 "y": 0 width: 320 height: 180 links: [hall] - id: hall name: Great Hall x: 320 "y": 0 width: 320 height: 180 markers: - id: save-gate kind: save room: entrance x: 40 "y": 90 label: Gate shrine ``` ### Card board | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `board.yaml` | `version: 1` | `cards.ParseBoardDoc`, `cards.EncodeBoardDoc` | [cards](https://game.nsgo.dev/docs/cards/) | ```yaml version: 1 card_size: w: 63 h: 88 slots: - id: hand rect: x: 40 "y": 400 w: 560 h: 120 layout: fan: arc: 24 sag: 14 ``` ## Game data ### Data table | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.yaml` or `.yml`, such as `weapons.yaml`; `.csv` and `.json` exports load too, without a version | `version: 1` | `datatable.LoadYAML`, `datatable.MarshalYAML`; `datatable.LoadFile` picks the reader by extension | [datatable](https://game.nsgo.dev/docs/datatable/); schema generated per row type with `datatable.Schema` | ```yaml version: 1 rows: - id: sword damage: 12 cooldown: 400ms tags: [melee] - id: bow damage: 8 cooldown: 1s tags: [ranged, two-handed] ``` ### Stats | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `hero.yaml` | `version: 1` | `stats.Parse`, `stats.Encode` | [stats](https://game.nsgo.dev/docs/stats/) | ```yaml version: 1 stats: - name: health base: 100 min: 0 - name: attack base: 12 effects: - name: berserk steps: 300 modifiers: - stat: attack op: mul value: 1.5 ``` ### Ability set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `hero.abilities.yaml` | `version: 1` | `ability.Parse`, `ability.Encode` | [ability](https://game.nsgo.dev/docs/ability/) | ```yaml version: 1 abilities: - id: fireball name: ability.fireball action: cast costs: - resource: mana amount: 20 cooldown: 2s castTime: 500ms conditions: [grounded, '!silenced'] - id: dash action: dash cooldown: 250ms charges: 3 recharge: 4s ``` ### Item catalog | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `items.yaml` | `version: 1` | `inventory.Parse`, `inventory.Catalog.Encode` | [inventory](https://game.nsgo.dev/docs/inventory/) | ```yaml version: 1 items: - id: potion name: items.potion.name icon: asset:icons/potion.png maxStack: 20 tags: [consumable, healing] stats: heal: 25 - id: iron-helm name: items.iron-helm.name equip: head stats: armor: 3 ``` ### Quest book | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `village.yaml` | `version: 1` | `quest.Parse`, `quest.Encode` | [quest](https://game.nsgo.dev/docs/quest/) | ```yaml version: 1 quests: - id: welcome title: quest.welcome.title autoStart: true objectives: - id: meet-elder kind: talk target: elder - id: herbs title: quest.herbs.title requires: [welcome] objectives: - id: moonleaf kind: collect target: moonleaf count: 4 rewards: - kind: xp id: xp amount: 20 ``` ### Loot tables | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `chest.yaml` | `version: 1` | `loot.Parse`, `loot.Encode` | [loot](https://game.nsgo.dev/docs/loot/) | ```yaml version: 1 tables: - name: chest rolls: min: 1 max: 3 entries: - item: sword weight: 2.5 - nothing: true weight: 6.5 ``` ### Achievements | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game embeds, such as `achievements.yaml` | `version: 1` | `achievements.Parse`, `achievements.Encode` | [achievements](https://game.nsgo.dev/docs/achievements/) | ```yaml version: 1 achievements: - id: gem-collector title: Gem Collector description: Clear 500 gems. steps: 500 platforms: gameCenter: dev.nsgo.test.gem_collector playGames: CgkIabc123EAIQAg ``` ### Leaderboards | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game embeds, such as `leaderboards.yaml` | `version: 1` | `leaderboard.Parse`, `leaderboard.Catalog.Encode` | [leaderboard](https://game.nsgo.dev/docs/leaderboard/) | ```yaml version: 1 leaderboards: - name: high-score gameCenter: dev.nsgo.game.example.high_score playGames: CgkI6v7z8vQREAIQAQ ``` ### Move set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `moves.yaml` | `version: 1` | `fighting.Parse`, `fighting.Encode` | [fighting](https://game.nsgo.dev/docs/fighting/) | ```yaml version: 1 input: up: up down: down left: left right: right moves: - name: lp press: - lp - name: hadoken motion: - "2" - "3" - "6" window: 12 press: - lp buffer: 8 priority: 20 ``` ### Frame data | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `fighter.yaml` | `version: 1` | `framedata.Parse`, `framedata.Encode` | [framedata](https://game.nsgo.dev/docs/framedata/) | ```yaml version: 1 moves: - name: idle animation: idle length: 8 loop: true boxes: - kind: hurt start: 1 end: 8 x: -12 "y": -80 width: 24 height: 80 ``` ### Platformer controller | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `hero.yaml` | `version: 1` | `platformer.ParseConfig`, `platformer.EncodeConfig` | [platformer](https://game.nsgo.dev/docs/platformer/) | ```yaml version: 1 coyote_time: 100ms jump_buffer: 100ms jump_speed: 284 jump_cut: 0.55 jump_cut_min_speed: 110 gravity: 720 max_fall_speed: 320 run_speed: 98 ground_accel: 960 ground_decel: 1150 air_accel: 680 wall_slide_speed: 60 wall_coyote_time: 80ms wall_jump_speed_x: 150 wall_jump_speed_y: 260 wall_jump_lock: 150ms ``` ### Vehicle | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `car.yaml` | `version: 1` | `vehicle.ParseConfig`, `vehicle.EncodeConfig` | [vehicle](https://game.nsgo.dev/docs/vehicle/) | ```yaml version: 1 name: kart mass: 300 chassisHalfExtents: [0.6, 0.2, 1] chassisOffset: [0, 0, 0] engineForce: 2000 reverseForce: 0 maxSpeed: 20 maxReverseSpeed: 5 brakeForce: 4000 handbrakeGrip: 0 maxSteerAngle: 25 steerRate: 90 drag: 0 rollingResistance: 0 rollInfluence: 0 angularDamping: 0 wheels: - name: front anchor: [0, -0.1, -0.8] radius: 0.25 restLength: 0.2 stiffness: 20000 damping: 2000 maxForce: 10000 friction: 1.2 steer: true brake: true - name: rear anchor: [0, -0.1, 0.8] radius: 0.25 restLength: 0.2 stiffness: 20000 damping: 2000 maxForce: 10000 friction: 1.2 drive: true brake: true ``` ### Bullet patterns | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `patterns.yaml` | `version: 1` | `bullets.Parse`, `bullets.Encode` | [bullets](https://game.nsgo.dev/docs/bullets/) | ```yaml version: 1 patterns: - name: bloom kind: ring frame: orb count: 24 speed: 90 spin: 7.5 shots: 6 interval: 400ms lifetime: 6s radius: 4 ``` ### Formations | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `formations.yaml` | `version: 1` | `rts.ParseFormations`, `rts.Formations.Encode` | [rts](https://game.nsgo.dev/docs/rts/) | ```yaml version: 1 formations: - name: line shape: line spacing: 1.5 - name: wedge shape: wedge spacing: 1.5 ``` ### Utility AI | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `guard.utility.yaml` | `version: 1` | `ai.ParseUtility`, `ai.EncodeUtility` | [ai](https://game.nsgo.dev/docs/ai/#utility-ai) | ```yaml version: 1 momentum: 0.1 actions: - name: attack weight: 1.2 considerations: - name: target_close input: target_distance max: 200 curve: kind: linear slope: -1 shiftY: 1 - name: healthy input: health_ratio curve: kind: logistic slope: 1 exponent: 10 shiftX: 0.35 - name: heal weight: 1.1 considerations: - name: low_health input: health_ratio curve: kind: polynomial slope: -1 exponent: 2 shiftY: 1 - name: has_potion input: potion_count curve: kind: step slope: 1 shiftX: 0.5 ``` ### GOAP action set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `camp.goap.yaml` | `version: 1` | `ai.ParseGOAP`, `ai.EncodeGOAP` | [ai](https://game.nsgo.dev/docs/ai/#goal-oriented-action-planning-goap) | ```yaml version: 1 nodeBudget: 512 facts: bools: - has_axe - has_fire ints: - wood actions: - name: fetch_axe cost: 1 check: axe_available effects: bools: - fact: has_axe value: true - name: chop_wood cost: 1 preconditions: bools: - fact: has_axe value: true effects: ints: - fact: wood op: add value: 1 - name: gather_sticks cost: 3 effects: ints: - fact: wood op: add value: 1 - name: build_fire cost: 1 preconditions: ints: - fact: wood op: gte value: 2 effects: bools: - fact: has_fire value: true ints: - fact: wood op: add value: -2 goals: - name: light_campfire priority: 10 target: bools: - fact: has_fire value: true ``` ### Behavior tree | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.bt.yaml`, such as `guard.bt.yaml` | `version: 1` | `ai.ParseBehaviorTree`, `ai.EncodeBehaviorTree`, `ai.LoadBehaviorTreeFS`, `ai.BuildBehaviorTree` | [ai](https://game.nsgo.dev/docs/ai/#behavior-trees-in-yaml) · [schema](https://game.nsgo.dev/docs/schemas/) | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/bt.v1.json version: 1 name: guard blackboard: - key: enemy_seen type: bool default: false - key: enemy_distance type: float default: 999 root: type: selector children: - type: blackboard_condition key: enemy_seen op: eq value: true abort: both child: type: selector children: - type: blackboard_condition key: enemy_distance op: lte value: 32 abort: both child: type: cooldown duration: 500ms child: type: action action: attack params: damage: 15 - type: action action: chase params: speed: 120 - type: subtree path: patrol.bt.yaml params: wait: 200ms keys: home: home_pos ``` ### Navigation meshes | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `crypt.navmesh.yaml`, usually one per level and agent type | `version: 1` | `navbake.Parse`, `navbake.Mesh.Encode` | [navbake](https://game.nsgo.dev/docs/navbake/) | ```yaml version: 1 agent: small radius: 2 polygons: - [[2.0078125, 2.0078125], [37.992188, 2.0078125], [37.992188, 17.992188], [19.601562, 17.992188]] - [[2.0078125, 2.0078125], [19.601562, 17.992188], [18.863281, 18.296875]] - [[2.0078125, 2.0078125], [18.863281, 18.296875], [18.296875, 18.863281]] - [[2.0078125, 2.0078125], [18.296875, 18.863281], [17.992188, 19.601562]] - [[2.0078125, 2.0078125], [17.992188, 19.601562], [17.992188, 37.992188], [2.0078125, 37.992188]] ``` ### Tile rules | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `ruins.yaml` | `version: 1` | `procgen.ParseRules`, `procgen.EncodeRules` | [procgen](https://game.nsgo.dev/docs/procgen/) | ```yaml version: 1 tiles: - name: floor weight: 6 walkable: true - name: water weight: 2 neighbors: - left: floor right: floor - left: floor right: water - left: water right: floor - left: water right: water - up: floor down: floor - up: floor down: water - up: water down: floor - up: water down: water ``` ### Dungeon room templates | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `rooms.yaml` | `version: 1` | `procgen.ParseRoomTemplates`, `procgen.EncodeRoomTemplates` | [procgen](https://game.nsgo.dev/docs/procgen/) | ```yaml version: 1 rooms: - id: start_hub weight: 1 tags: - start doors: - side: north offset: 3 - side: south offset: 3 - side: east offset: 2 - side: west offset: 2 tiles: - '###.###' - '#.....#' - '.......' - '#.....#' - '###.###' - id: boss_vault tags: - goal width: 7 height: 5 source: rooms/boss_vault.tmj doors: - side: north offset: 3 - side: south offset: 3 - side: east offset: 2 - side: west offset: 2 ``` ### Visual novel cast | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `cast.yaml` | `version: 1` | `vn.ParseCast`, `vn.EncodeCast` | [vn](https://game.nsgo.dev/docs/vn/) | ```yaml version: 1 slots: - name: left x: 0.25 characters: - id: aiko name: Aiko color: '#e07a5f' slot: left defaultExpression: neutral expressions: - name: neutral frame: aiko_neutral - name: smile frame: aiko_smile ``` ### Beat map | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A `.yaml` file next to the track, such as `opening.beatmap.yaml` | `version: 1` | `rhythm.ParseBeatMap`, `rhythm.EncodeBeatMap` | [rhythm](https://game.nsgo.dev/docs/rhythm/) | ```yaml version: 1 title: Opening offsetMs: 120 tempos: - beat: 0 bpm: 120 - beat: 62.5 bpm: 140 meters: - beat: 0 beatsPerBar: 4 ``` ### Number locale | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `de.yaml` | `version: 1` | `idle.ParseLocale`, `idle.EncodeLocale` | [idle](https://game.nsgo.dev/docs/idle/) | ```yaml version: 1 name: de decimal: ',' group: . exponent: E units: - exp: 3 suffix: ' Tsd.' - exp: 6 suffix: ' Mio.' ``` ### Quality presets | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Any `.yaml` file the game loads, such as `quality.yaml` | `version: 1` | `quality.ParseConfig`, `quality.EncodeConfig` | [quality](https://game.nsgo.dev/docs/quality/) | ```yaml version: 1 presets: low: resolution_scale: 0.5 particle_scale: 0.25 effects: false shadows: false medium: resolution_scale: 0.75 particle_scale: 0.6 effects: true shadows: false high: resolution_scale: 1 particle_scale: 1 effects: true shadows: true devices: - model: Samsung SM-A os: android level: low adapt: target_fps: 30 window_frames: 120 upgrade_windows: 3 ``` ## Servers ### Account service | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `accounts.yaml`, passed to `accountsd -config` | `version: 1` | `accounts.ParseConfig`, `accounts.Config.Marshal` | [accounts](https://game.nsgo.dev/docs/accounts/) | ```yaml version: 1 issuer: https://accounts.example.com audience: my-game tokenTTL: 1h30m30s disableGuests: true password: minLength: 10 argon2id: time: 2 memoryKiB: 19456 threads: 1 ``` ### Token key set | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `keys.yaml`, written by `accountsd genkey` | `version: 1` | `token.ParseKeySet`, `token.KeySet.Marshal` | [accounts](https://game.nsgo.dev/docs/accounts/) | ```yaml version: 1 issuer: https://accounts.example.com audience: my-game keys: - id: 2317febd373fcbcd key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg= ``` ### Cloud save service | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `cloudsave.yaml`, passed to `cloudsaved -config` | `version: 1` | `cloudsave.ParseConfig`, `cloudsave.Config.Marshal` | [cloudsave](https://game.nsgo.dev/docs/cloudsave/) | ```yaml version: 1 maxSlotBytes: 1048576 maxSlots: 32 keepVersions: 5 allowedOrigins: - https://play.example.com ``` ### Leaderboard service | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `leaderboards.yaml`, passed to `leaderboardd -config` | `version: 1` | `selfhost.ParseConfig`, `selfhost.Config.Marshal` | [leaderboard/selfhost](https://game.nsgo.dev/docs/leaderboard-selfhost/) | ```yaml version: 1 proofTTL: 10m boards: - name: high-score order: descending reset: allTime - name: weekly-sprint order: ascending reset: weekly weekStart: sunday keep: 4 ``` ## Files programs write in YAML A program writes these for itself, but they are YAML for the same reasons: a person can read one, review its diff and, when needed, edit it. ### Editor view state | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.game/editor.yaml` (`editor.ViewStateFile`) | `version: 1` | The editor (`Editor.SaveViewState`, and opening a scene) | [Editor](https://game.nsgo.dev/docs/editor/#navigating-the-3d-view-891) | `scenes` lists each scene the editor has shown, sorted by `path`, the scene file's slash-separated path from the project's root. `camera3D` is the 3D viewport's camera when the scene was last left, saved or closed: the point it looks at (`target`), its `yaw` and `pitch` in radians, its `distance` from the target, its vertical field of view `fov` in radians, its `near` and `far` clip planes and, when set, `orthographic`. Optional `snap` holds the project's editor snapping preferences (`grid`, `gridSize`, `pixel`, `rotation`, `rotationStepDeg`, `scale`, `scaleStep`, `showGrid`), omitted when all values match their defaults. A scene listed twice, a path outside the project, a negative snap step, and a value that is not finite are refused; a file that does not parse is written afresh, while one with a newer `version` is left as it is. A camera holding a value that is not finite is saved as the default camera. ```yaml version: 1 scenes: - path: levels/courtyard.scene.yaml camera3D: target: [12, 0, -40] yaw: 0.61 pitch: 0.49 distance: 320 fov: 1.0471976 near: 0.5 far: 10000 orthographic: true ``` ### Editor recent projects | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `recent-projects.yaml` in the user config directory (`/nsgo-game/recent-projects.yaml`, outside any project) | `version: 1` | `editor.ParseRecentProjects`, `editor.EncodeRecentProjects` | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/#start-screen-922) | ```yaml version: 1 projects: - name: Dungeon Run path: /Users/alex/games/dungeon-run lastOpened: "2026-11-25T05:00:00Z" - name: Kart Test path: /Users/alex/games/kart-test lastOpened: "2026-11-24T12:30:00Z" ``` ### Editor agent threads | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.nsgo/threads/.yaml` (`editor.AgentThreadsDir`, ignored by `.nsgo/.gitignore`) | `version: 1` | `editor.ParseAgentThreadYAML`, `editor.EncodeAgentThreadYAML` | [Editor](https://game.nsgo.dev/docs/editor/#agent-threads-per-line-of-work-grouped-by-scene-1019); schema `https://game.nsgo.dev/schemas/agent-thread.v1.json` | Each line of work is one strict versioned YAML file storing its `id`, `title` (named from its first request), `scenePath` (empty for `Project · no scene` threads), `sessionId` (so follow-up requests continue the external agent's session), RFC3339 timestamps, and chronological `requests` with `steps`, review `outcome` (`pending`, `kept`, `reverted`), change counts, changed `objects` (driving the Inspector footer link), and `historyStep` references. ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/agent-thread.v1.json version: 1 id: door-lever-pulls title: Door opens after two lever pulls scenePath: scenes/level_01.scene.yaml sessionId: sess_claude_01 createdAt: "2026-11-26T13:40:00Z" updatedAt: "2026-11-26T14:18:00Z" requests: - id: req-001 title: Door opens after two lever pulls prompt: Keep the door shut until the lever is pulled twice, then let it open. createdAt: "2026-11-26T13:40:00Z" updatedAt: "2026-11-26T13:41:00Z" outcome: kept changesTotal: 3 changesKept: 3 files: - prefabs/door.prefab.yaml - scenes/level_01.scene.yaml objects: - Door - lever_01 detail: Door.locked, Door.opens_after_pulls, lever_01.pulls historyStep: 'Agent: Door opens after two lever pulls' historyIndex: 1 steps: - id: step-001 label: Read level_01.scene.yaml and door.prefab.yaml status: done ``` ### Editor turn checkpoints | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.nsgo/checkpoints//manifest.yaml` (`editor.CheckpointsDir`, `editor.CheckpointManifestFile`), with saved pre-turn file contents stored verbatim under `.nsgo/checkpoints//files/` and ignored by Git | `version: 1` | `editor.ParseCheckpointManifest`, `editor.EncodeCheckpointManifest`, `Editor.BeginCheckpointTurn`, `Editor.RestoreCheckpoint` | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/#persistent-per-turn-checkpoints-1018) | Each agent turn, autonomous task, or automation records the pre-turn bytes of every project file before its first write (scenes, prefabs, data tables, `game.yaml`, Go code, and binary media alike). `files` is sorted by slash-separated `path` relative to the project root. When `existed` is `true`, `size` and `sha256` describe the raw bytes stored under `files/`, with optional 4-digit octal `mode` when non-default; when `existed` is `false`, restoring deletes the file that the turn created. A size cap (`Editor.CheckpointMaxBytes`, defaulting to 128 MiB) drops the oldest completed checkpoints. ```yaml version: 1 id: 20261126T144100Z-0001 createdAt: "2026-11-26T14:41:00Z" who: agent kind: turn title: Coin spin, bob and sparkle detail: 2 files files: - path: fx/sparkle.particles.yaml existed: false - path: prefabs/coin.prefab.yaml existed: true size: 142 sha256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef - path: scenes/level_01.scene.yaml existed: true size: 512 sha256: fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210 ``` ### Editor panel layout | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `layout.yaml` in the user config directory (`/nsgo-game/layout.yaml`, outside any project) | `version: 1` | `editor.ParseLayout`, `editor.EncodeLayout`, `Editor.SetLayoutPath` | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/#dockable-panels-and-layout-919) | Stores the user's dockable panel arrangement across sessions: `center` (a tab group or split tree holding `viewport` and any panels docked beside it), optional `left`, `right` and `bottom` docks (each with `size` in points, optional `closed`, and `root`), and optional sorted `hidden` panel keys. Each node is either a tab group (`panels` and optional `active` tab index) or a split (`axis`: `"horizontal"` or `"vertical"`, optional `sizes` in points, and `children`). Built-in panels use keys such as `viewport`, `scene_tree`, `layers`, `assets`, `files`, `library`, `inspector`, `problems`, `output`, `profiler`, `animation`, `search`, `states`, `tileset`, `terrain`, `rig`, `particles`, `material`, `environment`, `datatable`, `navmesh`, and `localization`; plugin panels use `plugin::`. Unknown fields, duplicate keys, duplicate panel entries, and unsupported versions are refused; a saved panel that no longer exists when the editor starts is dropped on restore. ```yaml version: 1 center: panels: - viewport left: size: 444 root: axis: horizontal sizes: [220, 224] children: - axis: vertical sizes: [0, 200] children: - panels: - scene_tree - panels: - layers - axis: vertical children: - panels: - assets - panels: - files - inspector active: 1 bottom: size: 164 root: panels: - problems - output hidden: - layers ``` ### Asset build cache | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.game/assets-cache.yaml`, or the path `assets.cache` in `game.yaml` names | `version: 1` | `game assets` | [Command Line](https://game.nsgo.dev/docs/cli/#assets) | ```yaml version: 1 targets: - target: atlas:ui key: 3f79bb7b435b05321651daefd374cdc681dc06faa65e374e38337b88ca046dea outputs: - path: assets/atlases/ui.json sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 - path: assets/atlases/ui.png sha256: 60303ae22b998861bce3b28f33eec1be758a213c86c93c076dbe9f558c11c752 ``` ### Benchmark baseline | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `benchmarks/baseline.yaml`, written by `game bench -update` | `version: 1` | `bench.Decode`, `bench.Baseline.Encode` | [Command Line](https://game.nsgo.dev/docs/cli/) | ```yaml version: 1 note: Update with nsgo game bench -update. max_regression_pct: {ns_per_op: 25, bytes_per_op: 30, allocs_per_op: 12.5} benchmarks: BenchmarkBatchDraw1000: {ns_per_op: 3500000, bytes_per_op: 80128, allocs_per_op: 1000} BenchmarkRaycast: {ns_per_op: 420.5, bytes_per_op: 0, allocs_per_op: 0} ``` ### Achievement progress | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A key in `core.Storage`, kept by `achievements.Tracker.Persist` | `version: 1` | `achievements.ParseProgress`, `achievements.EncodeProgress` | [achievements](https://game.nsgo.dev/docs/achievements/) | ```yaml version: 1 achievements: - id: first-match steps: 1 - id: gem-collector steps: 120 reported: gameCenter: 120 playGames: 100 ``` ### Latency calibrations | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A key in `core.Storage`, kept by `rhythm.OffsetStore` | `version: 1` | `rhythm.ParseCalibrations`, `rhythm.EncodeCalibrations` | [rhythm](https://game.nsgo.dev/docs/rhythm/) | ```yaml version: 1 devices: android/Google Pixel 8: audioMs: 41.25 videoMs: -3 ``` ### Input recording | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.replay.yaml`, written by a `replay.Recorder` | `version: 2` | `replay.Decode`, `replay.Recording.Encode` | [replay](https://game.nsgo.dev/docs/replay/) | ```yaml version: 2 seed: 99537266 rate: 60 actions: [left, right, jump] axes: [move_x] total_steps: 140 steps: - {step: 6, press: [right], axes: {move_x: 1}} - {step: 85, press: [jump]} - {step: 95, release: [jump]} - {step: 130, release: [right], axes: {move_x: 0}} ``` ### Ghost lap | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.ghost.yaml`, written from a `vehicle.GhostRecorder` | `version: 1` | `vehicle.ParseGhost`, `vehicle.EncodeGhost` | [vehicle](https://game.nsgo.dev/docs/vehicle/) | ```yaml version: 1 name: reference lap rate: 60 interval: 2 lapSteps: 2 frames: - p: [0, 0.5, 0] r: [0, 0, 0, 1] - p: [0, 0.5, 1.25] r: [0, 0.0499792, 0, 0.99875] ``` ### Undo log | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Wherever the game keeps it, such as a save slot; the moves are the game's own move type | `version: 1` | `undo.DecodeLog`, `undo.EncodeLog` | [undo](https://game.nsgo.dev/docs/undo/) | ```yaml version: 1 applied: 2 moves: - dir: right - dir: down - dir: down ``` ### State dump | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `*.state.yaml`, written by `statedump.WriteFile` | `version: 1` | `statedump.Parse`, `statedump.Encode` | [statedump](https://game.nsgo.dev/docs/statedump/) | ```yaml version: 1 seed: 42 rate: 60 steps: 90 scene: depth: 1 current: level values: score: 40 entities: - index: 0 generation: 1 components: - type: pos data: x: 4 y: 12 ``` ### Playtest configuration | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `playtest.yaml`, read by `nsgo game playtest` and `game_playtest` | `version: 1` | `playtest.ParseConfig`, `playtest.EncodeConfig` | [playtest](https://game.nsgo.dev/docs/playtest/) | ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/playtest.v1.json version: 1 scope: project: dungeon-run scene: level_01 template: platformer2d runs: count: 20 seedStart: 1 rate: 60 speed: 1 maxDuration: 1m30s bot: profile: platformer-runner reactionMin: 120ms reactionMax: 220ms metrics: - name: finished label: Finished measure: kind: outcome key: finished aggregate: count goal: summary: most first-timers clear floor 1 source: brief.yaml min: 16 - name: deaths label: Deaths measure: kind: event key: death aggregate: sum heatMap: true ``` ### Playtest report | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `playtest.report.yaml`, written by `nsgo game playtest` and `playtest.SaveReportFile` | `version: 1` | `playtest.ParseReport`, `playtest.EncodeReport` | [playtest](https://game.nsgo.dev/docs/playtest/) | ```yaml version: 1 scope: project: dungeon-run scene: level_01 bot: profile: platformer-runner reactionMin: 120ms reactionMax: 220ms rate: 60 speed: 1 seedCount: 1 passed: false metrics: - name: finished label: Finished aggregate: count value: 0 goal: summary: most first-timers clear floor 1 source: brief.yaml min: 1 status: missed heatMaps: - metric: deaths event: death points: - seed: 1 step: 140 x: 300 "y": 144 tag: slime_pit runs: - index: 1 seed: 1 outcome: failed reason: out of lives steps: 140 durationSeconds: 2.3333333333333335 recording: recordings/run_001_seed_1.replay.yaml events: - kind: death step: 140 timeSeconds: 2.3333333333333335 x: 300 "y": 144 tag: slime_pit ``` ### Tilemap chunk | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `chunk__.yaml` (or `.json`), written by `tilemap.DirChunkStore` and `tilemap.EncodeChunkYAML` / `EncodeChunkJSON` | `version: 1` | `tilemap.DecodeChunkYAML`, `tilemap.EncodeChunkYAML`, `tilemap.DecodeChunkJSON`, `tilemap.EncodeChunkJSON` | [tilemap](https://game.nsgo.dev/docs/tilemap/#sparse-chunked-layers-and-streaming) | ```yaml version: 1 x: -2 "y": 1 size: 4 runs: - 0*5 - "1" - "2147483650" - 3*4 - 0*5 ``` ## JSON files These formats are JSON: a program writes most of them for itself, and the rest are what other services and tools exchange. Each guide shows their fields. ### Save slot | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.json` and `.json.bak` in a directory, or a key in `core.Storage` | the envelope's `version`, the game's own schema version, upgraded by its migrations | `save.Store.Save`, `save.Store.Load` | [save](https://game.nsgo.dev/docs/save/) | ```json {"version":2,"data":{"level":4,"coins":120,"name":"Ann"}} ``` `data` holds the game's own value as `encoding/json` writes it, such as a struct with a `quest.Snapshot` and an inventory snapshot. ### Player settings | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | The `settings` slot of a save backend, such as `settings.json`, or a key in `core.Storage`, apart from the save slots | the envelope's `version`, upgraded by the settings store's migrations | `save.SettingsStore` | `save.Settings`: `audio`, `bindings`, `display`, `locale`, `accessibility` and `custom`, or the game's own type | ```json {"version":1,"data":{"audio":{"master":1,"groups":{"music":1,"sfx":1,"ui":1},"muted":false},"bindings":{"jump":["Space"]},"display":{"fullscreen":false,"display_index":0,"scale_mode":"fit","integer_scale":false,"frame_cap":0,"vsync":true,"auto_drop_low_power":true,"quality":"auto"},"locale":"en","accessibility":{"captions":false,"caption_scale":1,"color_blind_mode":"none","reduce_motion":false,"high_contrast":false,"screen_shake":1,"game_speed":1}}} ``` ### World map discovery | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Inside a save slot | `version: 1` | `worldmap.State` as JSON | [worldmap](https://game.nsgo.dev/docs/worldmap/) | ```json {"version":1,"current":"hall","visited":["cave","hall"],"revealed":["crypt"],"markers":[{"id":"m1","kind":"pin","room":"hall","x":12,"y":4,"label":"Key"}]} ``` ### Quest progress | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Inside a save slot, as JSON or YAML | `version: 1` | `quest.Log.Snapshot`, `quest.Log.Restore` | [quest](https://game.nsgo.dev/docs/quest/) | ```json {"version":1,"quests":[{"id":"find-key","state":"active","progress":{"rats":3}},{"id":"intro","state":"completed"}]} ``` `state` is `active`, `completed`, `failed` or `abandoned`; a quest that has not started is left out, as is an objective with no progress. ### Fog of war | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Inside a save slot | `version: 1` | `fog.Fog` as JSON | [fog](https://game.nsgo.dev/docs/fog/) | ```json {"version":1,"width":3,"height":2,"tileWidth":8,"tileHeight":8,"opaque":[".#.","..."],"nextSource":2,"sources":[{"id":1,"team":2,"col":2,"row":1,"radius":1},{"id":2,"team":1,"col":0,"row":0,"radius":0}],"teams":[{"team":1,"explored":["#..","..."]},{"team":2,"explored":[".##",".##"]}]} ``` ### World snapshot | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | Inside a save slot; only components registered with `RegisterCodec` | none | `entities.World.Snapshot`, `entities.World.Restore` | [entities](https://game.nsgo.dev/docs/entities/) | ```json {"entities":[{"index":0,"generation":1,"components":[{"type":"health","data":{"hp":10}},{"type":"position","data":{"x":3,"y":4}}]},{"index":1,"generation":1,"components":[{"type":"position","data":{"x":-1,"y":0.5}}]}]} ``` `type` is the name a component's codec was registered under with `RegisterCodec`, and `data` is the component as `encoding/json` writes it. ### Input bindings | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A key in `core.Storage` | `version: 1` | `input.Actions.Save`, `input.Actions.Load` | [input](https://game.nsgo.dev/docs/input/) | ```json {"version":1,"actions":{"fire":[{"kind":"mouse_button","button":"left"}],"jump":[{"kind":"key","key":"space"},{"kind":"gamepad_button","button":"south"}]},"axes":{"move_x":{"negative":"left","positive":"right"}}} ``` ### Console tunables | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A key in `core.Storage`, `debug.console.tunables` by default | none | `debug.Console.SaveTunables`, `debug.Console.LoadTunables` | An object of each tunable's name and value | ```json {"cheat.god":false,"level.name":"cave_1","player.lives":3,"player.speed":1.5} ``` The names are those the game registered with `RegisterFloat`, `RegisterInt`, `RegisterBool` and `RegisterString`; `LoadTunables` skips a name nothing registered, refuses a value outside its range or of the wrong JSON type, and applies none of the values when it refuses one. ### Dev session snapshot | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A file or a key in `core.Storage` that a game restores its state from after a rebuild | a hash of the state's Go type, which skips the restore when it changed | `devstate.Store.Save`, `devstate.Store.LoadSnapshot` | `devstate.SessionSnapshot` | ```json {"scene_id":"level-1","schema_hash":"90b889efbda2b1fbe5fd7122b8919ac57b14cef258a4a60664a39e4ee3caee5b","loop_tick":1200,"loop_elapsed":20000000000,"payload":"eyJsZXZlbCI6Mn0=","saved_at":"2026-11-24T09:15:02Z"} ``` `payload` is the game's state as `encoding/json` writes it, in base64, and `loop_elapsed` is in nanoseconds. ### Cloud save payload | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `.json` in a platform's cloud storage, such as `save.main.json` | `version: 1` | `liveops.EncodeCloudSave`, `liveops.DecodeCloudSave` | [liveops](https://game.nsgo.dev/docs/liveops/) | ```json { "format": "nsgo-cloud-save", "version": 1, "revision": 3, "hash": "sha256:b30e459ab9ad862b330d89d42e3422a3e3193071345b1de6b9e4038b27f2ee01", "modified": "2026-11-24T09:15:02Z", "device": "phone-1", "data": "{\"version\":2,\"data\":{\"level\":4}}" } ``` `hash` is the SHA-256 of the save's bytes, which `data` holds as text, or `data_base64` in base64 when they are not UTF-8. ### Cloud sync state | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A key per slot in `core.Storage`, `.`, such as `liveops.cloudsync.main` | `version: 1` | `liveops.CloudSyncer`, which keeps it for itself | [liveops](https://game.nsgo.dev/docs/liveops/) | ```json {"version":1,"revision":3,"hash":"sha256:b30e459ab9ad862b330d89d42e3422a3e3193071345b1de6b9e4038b27f2ee01","local_modified":"2026-11-24T09:15:02Z","local_hash":"sha256:b30e459ab9ad862b330d89d42e3422a3e3193071345b1de6b9e4038b27f2ee01"} ``` It records the cloud revision and content hash both sides held after the last sync, and when this device last wrote the local copy. ### Leaderboard records | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `//.jsonl`, a line per new best score | none | `selfhost.FileStore` | [leaderboard/selfhost](https://game.nsgo.dev/docs/leaderboard-selfhost/) | ```json {"account":"3f9a...","score":4200,"achieved":"2026-11-24T09:15:02.5Z"} ``` ### String table | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A `.json` file per locale, flat, nested or with CLDR plural forms | none | `l10n.Catalog.LoadJSON` | [l10n](https://game.nsgo.dev/docs/l10n/) | ```json { "menu": {"play": "Play"}, "hud": {"score": "Score: {score}"}, "coins": {"zero": "No coins", "one": "{count} coin", "other": "{count} coins"} } ``` ### Clip events | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A JSON sidecar beside a model, or the `extras` of a glTF animation | `version: 1` in a sidecar | `anim3d.LoadEventsSidecar`, `anim3d.MarshalEventsSidecar`, `anim3d.LoadEventsFromGLTFExtras` | [anim3d](https://game.nsgo.dev/docs/anim3d/), [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/) | ```json { "version": 1, "clips": { "attack": [ { "time": 0.4, "name": "hit", "data": { "damage": 12 } } ], "run": [ { "time": 0.25, "name": "footstep", "payload": "left" }, { "time": 0.75, "name": "footstep", "payload": "right" } ] } } ``` ### DLC pack manifest | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A `.json` file the game downloads, listing the packs it can install | none; each pack has its own `version` | `assets.ParsePackManifest` | [assets](https://game.nsgo.dev/docs/assets/) | ```json {"packs": [{"id": "forest", "url": "https://cdn.example.com/forest.zip", "version": "1.0.0", "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"}]} ``` ### WebAssembly size budget | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A `.json` file passed to `sizecheck -budget` when it checks a `.wasm`, such as `benchmarks/web-budget.json` | none | the `sizecheck` command (`cmd/sizecheck`) | [Package Size Budgets](https://game.nsgo.dev/docs/package-size-budgets/) | ```json { "target": "./cmd/wasmprobe", "ldflags": "-s -w", "max_raw_bytes": 8388608, "max_gzip_bytes": 2359296, "note": "WebAssembly size budget for ./cmd/wasmprobe" } ``` ### Mobile package size budget | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | A `.json` file passed to `sizecheck -budget` when it checks an `.aab`, `.apk` or `.ipa`, such as `benchmarks/android-aab-budget.json` | none | the `sizecheck` command (`cmd/sizecheck`) | [Package Size Budgets](https://game.nsgo.dev/docs/package-size-budgets/) | ```json { "max_total_bytes": 52428800, "max_per_abi_bytes": 20971520, "max_category_bytes": { "native_libs": 36700160, "dex": 5242880 }, "note": "Release budget for MyGame Android AAB" } ``` ### API reference | Files | Version | Read and written by | Fields | | --- | --- | --- | --- | | `api.json`, published at `https://game.nsgo.dev/api.json` | `version: 1` | `apiref.Marshal`, `apiref.Unmarshal` | [Packages](https://game.nsgo.dev/docs/packages/) | ```json { "version": 1, "module": "example.com/mygame", "packages": [ { "importPath": "example.com/mygame/score", "name": "score", "dir": "score", "page": "score", "synopsis": "Package score keeps a player's score.", "doc": "Package score keeps a player's score.\n", "consts": [], "vars": [], "funcs": [ { "name": "Add", "anchor": "Add", "decl": "func Add(a, b int) int", "doc": "Add returns a plus b.\n", "file": "score/score.go", "line": 4 } ], "types": [] } ] } ``` ## Other tools' formats These are read as the tools that make them write them, never converted into a form of this repository's own. ### Tiled map | Files | Read by | Guide | | --- | --- | --- | | Tiled XML (`.tmx`) and JSON (`.tmj`) maps with embedded or external (`.tsx`, `.tsj`) tilesets and CSV, XML, or base64 (`uncompressed`, `zlib`, `gzip`) tile data | `tilemap.LoadTiled`; `rooms.FromTiledLayer` makes rooms from an object layer | [tilemap](https://game.nsgo.dev/docs/tilemap/), [rooms](https://game.nsgo.dev/docs/rooms/) | ### Tiled world | Files | Read by | Guide | | --- | --- | --- | | Tiled world files (`.world`), listing map placements and regex filename patterns with multipliers and offsets | `tilemap.ParseTiledWorld`, `tilemap.LoadTiledWorld` | [tilemap](https://game.nsgo.dev/docs/tilemap/) | ### LDtk project | Files | Read by | Guide | | --- | --- | --- | | LDtk projects (`.ldtk`) | `tilemap.LoadLDtk`, `tilemap.LoadLDtkAll`, `tilemap.LoadLDtkWorld`; `rooms.FromLDtk` makes rooms from a world's levels | [tilemap](https://game.nsgo.dev/docs/tilemap/), [rooms](https://game.nsgo.dev/docs/rooms/) | ### Sprite atlas | Files | Read by | Guide | | --- | --- | --- | | TexturePacker "JSON (Hash)" and "JSON (Array)", Aseprite `json-hash` and `json-array`; `game pack` writes TexturePacker's JSON (Hash) | `sprite.LoadAtlas` | [sprite](https://game.nsgo.dev/docs/sprite/) | ### Fonts | Files | Read by | Guide | | --- | --- | --- | | AngelCode BMFont in text, XML or JSON; msdf-atlas-gen JSON for signed-distance-field fonts | `text.LoadBMFont`, `text.LoadSDFFont` | [text](https://game.nsgo.dev/docs/text/) | ### glTF model | Files | Read by | Guide | | --- | --- | --- | | glTF 2.0 (`.gltf` with its buffers, or `.glb`), including Draco and meshopt compression | `gltf.Load`, `gltf.LoadFS` | [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/) | ### Grid map mesh library | Files | Read by | Guide | | --- | --- | --- | | A glTF 2.0 JSON document whose nodes with a mesh become the library's tiles, bounded by their `POSITION` accessors | `world3d.LoadMeshLibraryFromGLTF` | [world3d](https://game.nsgo.dev/docs/world3d/) | ### Profiler trace | Files | Written by | Guide | | --- | --- | --- | | Chrome's trace event JSON, opened in Perfetto or `chrome://tracing` | `debug.Profiler.WriteChromeTrace` | `debug.Profiler` | ### Yarn dialogue script | Files | Read by | Guide | | --- | --- | --- | | Yarn Spinner scripts (`.yarn`), written by hand: nodes of lines, `->` choices and `<>`, each under a `title:` header between `---` and `===` | `flow.ParseYarn`; `vn.Presenter` plays one | [vn](https://game.nsgo.dev/docs/vn/) | ```yarn title: Start --- Aiko: Welcome to the old observatory. #line:obs_01 -> Look through the telescope #line:obs_c1 Aiko: Careful, the lens is old. #line:obs_05 <> -> Leave #line:obs_c2 === title: Telescope --- <> Ren: The sky is the same size. #line:obs_06 === ``` ## Binary files Media that is binary by nature stays binary: images (PNG), sound (WAV, AAC, MP3), font pages, glTF buffers and `.glb` files, and KTX2 textures that `game assets` encodes. So do the packets of `net`, which are data on the wire, and a fighting recognizer's rollback state, which lives in memory. Every one of them is described by a text file above where it needs settings: an import settings sidecar, `game.yaml` or a glTF document. ## Keeping this page current Each entry starts with a line ``. Each YAML format's conformance test (`internal/formattest`) names its entry so and checks that every YAML example in it, on this page and its translation, loads and saves to the same bytes. `TestFormatsPage` at the repository root checks the rest: that the two languages list the same entries in the same order; that every other entry is listed in the test with the declaration that reads its format, which the package must still have, and that its JSON and Yarn examples load with the format's reader; that every package that decodes JSON has an entry unless the test says why it needs none; and that every exported integer constant whose name ends in `Version` is the version of a format listed here. A format none of these finds, such as an unversioned text format in a package that already has an entry, can still be missed, so a new format adds its entry here in the same change. --- Source: https://game.nsgo.dev/docs/framedata/ # framedata `github.com/nsgo-dev/game/pkg/framedata` gives fighting games per-frame hitboxes, hurtboxes and hit properties (damage, hitstun, blockstun, knockback, cancel windows) for their moves. A character's frame data is a YAML file, and a `World` resolves it into hits once per fixed step, the same way every time. ```go import "github.com/nsgo-dev/game/pkg/framedata" ``` ## Frame data files One file lists one character's moves. A move lasts `length` frames, one per fixed step of the [loop](https://game.nsgo.dev/docs/loop/), numbered from 1 as published frame data tables count them. Each box is active from frame `start` to frame `end` inclusive. ```yaml version: 1 moves: - name: idle animation: idle length: 8 loop: true boxes: - kind: hurt start: 1 end: 8 x: -12 "y": -80 width: 24 height: 80 - name: jab animation: jab length: 14 boxes: - kind: hurt start: 1 end: 14 x: -12 "y": -80 width: 24 height: 80 - kind: hit start: 4 end: 6 x: 12 "y": -66 width: 28 height: 12 damage: 30 hitstun: 14 blockstun: 9 knockbackX: 2.5 cancels: - start: 4 end: 10 when: contact into: [fireball] ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `moves[].name` | Unique name, used by `Start`, `Force`, `Neutral` and `into` | | `moves[].animation` | Optional sprite animation the game plays alongside, such as an entry of a [sprite](https://game.nsgo.dev/docs/sprite/) atlas's `Animations` | | `moves[].length` | Frames the move lasts, 1 to 3600 | | `moves[].loop` | Starts over after the last frame, for stances such as idle, walk and crouch | | `boxes[].kind` | `hurt` (can be hit) or `hit` (strikes) | | `boxes[].start`, `end` | First and last active frame | | `boxes[].x`, `"y"`, `width`, `height` | Rectangle in points from the fighter's origin when it faces right; Y grows downward | | `boxes[].group` | Hit group, 0 to 63: hitboxes of one hit share a group, each hit of a multi-hit move has its own | | `boxes[].damage`, `hitstun`, `blockstun` | Damage dealt and frames of stun on a hit or a block | | `boxes[].knockbackX`, `knockbackY` | Push on hit, positive X away from the attacker: toward whichever side of the attacker the victim stands on, so a cross-up pushes the right way, or the attacker's facing when they share an X | | `cancels[].start`, `end` | Frames the window is open on | | `cancels[].when` | Omitted (always), `hit`, `block` or `contact` (hit or block) | | `cancels[].into` | Moves the window may cancel into | `Parse` refuses unknown fields, a version other than 1, duplicate move names, boxes and windows outside their move, sizes that are not positive and finite, hit properties on hurtboxes and cancels into moves that do not exist. `Encode` writes the fields in the order above with 2-space indentation, so loading and saving a file changes nothing. It quotes the key `"y"` because YAML 1.1 reads a bare `y` as a boolean; `Parse` accepts it either way. `Move.FrameData` summarizes a move as a frame data table does: startup, active and recovery frames, and the advantage on hit and on block when its earliest hitbox connects on its first frame. For the jab above that is startup 4, 3 active, 8 recovery, +4 on hit and -1 on block. ## Fighters and hits ```go doc, err := framedata.Parse(data) if err != nil { ... } p1 := &framedata.Fighter{Moves: doc, Neutral: "idle", X: 100} p2 := &framedata.Fighter{Moves: doc, Neutral: "idle", X: 160, FacingLeft: true} world := &framedata.World{Fighters: []*framedata.Fighter{p1, p2}} loop := &game.Loop{Rate: 60, Update: func(time.Duration) { if actions.JustPressed("punch") { p1.Start("jab") } p2.Blocking = actions.Pressed("back") for _, h := range world.Step() { health[h.Victim] -= h.Damage h.Victim.X += h.KnockbackX spawnSpark(h.X, h.Y) } }} ``` - **`Start(name)`** begins a move when the fighter can act (no stun, and its move loops or is on its last frame) or when a cancel window of its current move is open on this frame and lists the move. `CanStart` asks without starting. **`Force(name)`** begins a move regardless, for hit reactions, throws and scripted moves. - **`World.Step`** advances every fighter one frame, then tests each active hitbox against every other fighter's active hurtboxes. A fighter returns to its `Neutral` move when a move that does not loop ends. - **Hits** are all found from the state before any of them applies, so fighters striking each other on the same frame trade. Fighters are visited in slice order and boxes in document order, so the same inputs give the same hits in the same order, which [replay](https://game.nsgo.dev/docs/replay/) and rollback [net](https://game.nsgo.dev/docs/net/) code rely on, together with saving and restoring a match (below). - **Once per group**: a move instance hits each opponent once per hit group and at most once per step; starting a move or looping one begins a new instance. - **Stun**: the victim takes the hitbox's `hitstun`, or its `blockstun` when `Blocking`, and returns to its `Neutral` move. A new hit replaces the stun left; several hits in one step take the longest. `Stun()` counts the steps left and `Actionable()` reports when it can act again. - **Teams**: fighters with the same non-zero `Team` never hit each other. - **Contact**: `Contact()` reports whether the current move hit or was blocked, which opens `when: hit`, `when: block` and `when: contact` windows. `Step` reuses its result slice and allocates nothing once warm: two fighters take about 0.1 µs a step. A hitbox whose `group` is outside 0 to 63, which only a `Doc` built in Go without `Validate` can have, never hits. ## Save and restore `World.Save` copies everything `Step` reads and changes into a `WorldState`: each fighter's position, facing, `Blocking`, move by name, frame, stun, contact and the hit groups its move has landed, with opponents named by their index in `Fighters`. `World.Restore` puts it back. A rollback session saves each tick and restores the last confirmed one when a late input arrives, then steps again to the same hits: ```go var state framedata.WorldState func (s *sim) Save() []byte { s.world.Save(&state) data, _ := json.Marshal(state) return data } func (s *sim) Load(data []byte) error { var st framedata.WorldState if err := json.Unmarshal(data, &st); err != nil { return err } return s.world.Restore(&st) } ``` `WorldState` holds no pointers, so it encodes as JSON or YAML and hashes for a checksum. `Save` reuses the slices of the state it is given and allocates nothing once warm, and the copy shares no memory with the `World`. `Restore` copies the state, and refuses one with a different number of fighters, a move the fighter's `Moves` does not have, a frame outside its move or a landed opponent that is not another fighter, changing nothing. The fighters' `Moves`, `Neutral` and `Team` are configuration and not part of the state. ## Debug overlay The [debug](https://game.nsgo.dev/docs/debug/) overlay draws a fighter's active boxes as wireframes, hurtboxes first and hitboxes on top, mirrored as the fighter faces: ```go overlay.DrawFighterBoxes(d, p1, core.RGB(0x38bdf8), core.RGB(0xef4444)) ``` `Fighter.Boxes(dst)` returns the same boxes in world points for a game's own drawing or tests. --- Source: https://game.nsgo.dev/docs/from-ebitengine/ # Coming from Ebitengine A map from Ebitengine's game loop, images, input, audio and builds to this layer, and to the scenes, nodes, resources, signals, input maps, physics and export it adds on top, with the page that covers each one. Both are Go, so most of your game logic moves over unchanged. What changes is the host: an Ebitengine game owns the whole window and draws everything on the GPU, while a game here is an NSGo component that draws into one `core.Canvas`, with its HUD and menus as native NSGo views on top. Ebitengine leaves scenes, entities, events and physics to you; this layer ships packages for each, which you can adopt one at a time. ## At a glance | Ebitengine | Here | Guide | | --- | --- | --- | | `ebiten.Game.Update` at `ebiten.TPS()` | `game.Loop.Update(dt)` at `Loop.Rate` | [Loop](https://game.nsgo.dev/docs/loop/) | | `ebiten.Game.Draw(screen)` | `core.Canvas.Draw(d, size)`, redrawn from `Loop.Draw(alpha)` | [Loop](https://game.nsgo.dev/docs/loop/) | | `Layout(outsideWidth, outsideHeight)` | `screen.Viewport` with `ModeFit`, `ModeFill`, `ModeStretch` or `ModeExpand` | [screen](https://game.nsgo.dev/docs/screen/) | | `*ebiten.Image`, `SubImage` | `sprite.Atlas` and its `Frame` values | [sprite](https://game.nsgo.dev/docs/sprite/) | | `DrawImageOptions.GeoM`, `ColorScale` alpha | `sprite.Sprite` position, origin, rotation, scale, flip and `Alpha` | [sprite](https://game.nsgo.dev/docs/sprite/) | | A hand-written scene switcher | `scene.Manager` with transitions | [scene](https://game.nsgo.dev/docs/scene/) | | A slice of structs you update yourself | `entities.World`, components and systems | [Entities](https://game.nsgo.dev/docs/entities/) | | `//go:embed` plus `ebitenutil.NewImageFromFile` | `"asset:"` URIs for images and sounds, `//go:embed` with `assets.WithFS` for data | [assets](https://game.nsgo.dev/docs/assets/) | | Channels or callbacks between systems | `flow.Bus`; `core.Signal` for UI state | [flow](https://game.nsgo.dev/docs/flow/) | | `inpututil.IsKeyJustPressed`, touch IDs | `input.Actions` with `JustPressed` and touch regions | [input](https://game.nsgo.dev/docs/input/) | | Your own AABB checks | `physics` shapes, `MoveAndSlide`, `RigidWorld` | [physics](https://game.nsgo.dev/docs/physics/) | | `audio.Context`, `audio.Player` | `sound.Mixer`, `Effect` and `Music` | [sound](https://game.nsgo.dev/docs/sound/) | | `go build`, `GOOS=js GOARCH=wasm`, `ebitenmobile bind` | `go tool nsgo build` for every target | [Building and Shipping](https://game.nsgo.dev/docs/shipping/) | ## The loop Ebitengine calls `Update` 60 times a second by default and `Draw` once per display frame. `game.Loop` keeps the same split: `Update` gets a fixed `dt` of `1/Rate` seconds (60 updates a second by default), and `Draw` runs once per display frame with `alpha`, how far the frame falls into the next update. Pass `alpha` to the canvas through a `core.Signal` and interpolate between the last two states, so motion stays smooth on 120 Hz displays without changing the update rate. `Loop` also pauses while the app is in the background and caps the updates one frame may run after a hitch. See [Loop](https://game.nsgo.dev/docs/loop/). `ebiten.ActualTPS` and `ActualFPS` have no direct counterpart; the [debug](https://game.nsgo.dev/docs/debug/) overlay draws a frame-time graph, and `nsgo dev -fps` shows NSGo's monitor. ## Drawing An Ebitengine `Draw` receives the screen image; a canvas `Draw` receives a `*core.Drawing` and the view's size in points. A sprite sheet becomes a `sprite.Atlas` loaded from a TexturePacker or Aseprite export, or written by hand, and `SubImage` rectangles become its named frames and animations. Where you set `GeoM` translate, rotate and scale, set the fields on a `sprite.Sprite`; a `sprite.Batch` draws many sprites from one atlas in `Z` order. See [sprite](https://game.nsgo.dev/docs/sprite/). `Layout` becomes a `screen.Viewport`: give it the virtual resolution, choose how it fits the window, and draw inside `vp.Draw`. Integer scaling for pixel art and safe-area rectangles live in the same package. See [screen](https://game.nsgo.dev/docs/screen/). For maps, `tilemap` loads Tiled `.tmj` files and draws only the visible tiles through a 2D camera. See [tilemap](https://game.nsgo.dev/docs/tilemap/). ## Scenes Ebitengine has no scene type, so games usually keep a `current Scene` field and swap it. `scene.Manager` does that with a stack: `Switch` replaces the scene with a fade, crossfade or wipe, `Push` lays an overlay such as a pause menu over it, and `Pop` returns. Each scene gets its own `*core.Scope`, and everything made on it is disposed when the scene exits. A `scene.Scene` inside it orders layers in world space (under a camera) and screen space (for the HUD), and hit-tests taps against sprites. See [scene](https://game.nsgo.dev/docs/scene/). A level's layout can live in a YAML scene file rather than in Go: `sceneformat.Parse` reads it and `sceneformat.Build` produces layers ready to draw. See [Editor & Scene Format](https://game.nsgo.dev/docs/editor/). ## Nodes Where an Ebitengine game keeps `[]*Enemy` and loops over it, `entities` keeps components in typed sparse sets on a `World` and runs systems in a declared order on each fixed step, with no allocations in steady state. `Prefab` stamps a template's components onto new entities, and a world saves to JSON through [save](https://game.nsgo.dev/docs/save/). See [Entities](https://game.nsgo.dev/docs/entities/). For 3D, `scene3d.Node` is a transform hierarchy with sockets, tags and picking. See [scene3d](https://game.nsgo.dev/docs/scene3d/). ## Resources Put images and sounds under `resources/`; NSGo packages them for every target, and `core.Src("asset:hero.png")` opens one anywhere, including the web, where Ebitengine needs files embedded or fetched. Data that `assets.Manager` reads itself, such as atlas JSON, raw bytes and level files, still comes from `//go:embed`: pass the embedded file system with `assets.NewManager(cx, assets.WithFS(fsys))`, or pass `WithReadAsset` for custom storage. `assets.Manager` loads atlases, sounds, images and your own parsed files in named groups off the engine goroutine, exposes progress for a loading screen and releases a group when its scene ends. See [assets](https://game.nsgo.dev/docs/assets/). ## Signals Systems that call each other or share channels can publish typed events on a `flow.Bus` instead: `flow.Subscribe` takes a function of the event's type, `flow.Publish` delivers at once and `flow.Enqueue` with `Bus.Flush` delivers once per step. `flow.Timers`, `flow.Machine` and `flow.Seq` replace frame counters, state switch statements and cutscene goroutines, and all of them advance only on the loop's `dt`, so they pause and replay with the game. See [flow](https://game.nsgo.dev/docs/flow/). State the HUD shows, such as a score, is a [`core.Signal`](https://pkg.go.dev/github.com/nsgo-dev/nsgo/core#Signal) that an NSGo view reads and re-renders on. ## Input maps Ebitengine asks about devices directly (`ebiten.IsKeyPressed`, `inpututil.IsMouseButtonJustPressed`, `ebiten.AppendTouchIDs`). `input.Actions` names actions instead and binds inputs to them, so the game code asks about `"jump"`, not a key: | Ebitengine | Here | | --- | --- | | `ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft)` | `actions.Bind("fire", input.MouseButton(core.MouseButtonLeft))`, then `actions.Pressed("fire")` | | `inpututil.IsMouseButtonJustPressed` | `actions.JustPressed` | | `inpututil.IsMouseButtonJustReleased` | `actions.JustReleased` | | Checking touch positions against a button's rectangle | `input.TouchRegion(rect)`, or a `VirtualPad` | | Two opposing inputs combined into a direction | `actions.BindAxis("move_x", "left", "right")` and `actions.Axis` | Call `actions.Step()` at the start of each `Update`; a tap that starts and ends between two updates still registers for one. `actions.Save` and `Load` keep remapped bindings in `core.Storage`. Key and gamepad bindings are tracked in [#3](https://github.com/nsgo-dev/game/issues/3); until they land, a key bound with NSGo's `cx.OnKey` can call `actions.Trigger(name)`, which registers the action for one step. See [input](https://game.nsgo.dev/docs/input/). ## Physics Ebitengine has no physics, so this is new rather than a port. [physics](https://game.nsgo.dev/docs/physics/) holds box and circle overlap tests, `MoveAndSlide` for platformer bodies against a tile grid with one-way platforms, trigger areas, and raycasts. [2D Rigid Bodies](https://game.nsgo.dev/docs/physics2d-rigid/) adds a deterministic rigid-body solver with distance, spring and revolute joints, and [physics3d](https://game.nsgo.dev/docs/physics3d/) covers 3D bodies and a capsule character controller. All of them step on the loop's fixed `dt`. The 2D packages work in the same Y-down screen space the drawing uses, while physics3d works in the 3D space: right-handed, Y up, units in metres. ## Export | Ebitengine | Here | | --- | --- | | `go run .` | `go tool nsgo dev`, which also reloads on save | | `GOOS=js GOARCH=wasm go build` and a `wasm_exec.js` page | `go tool nsgo build -target web` | | `ebitenmobile bind` and an Xcode or Android Studio project | `go tool nsgo build -target ios` or `android` | | Bundling a `.app` or installer yourself | `go tool nsgo build`, which writes `.dmg`, NSIS installers, `.deb`, `.AppImage`, `.apk` and `.ipa` | App name, identifier, version, icons and targets live in `nsgo.yaml`, and `-channel store` builds store packages. See [Building and Shipping](https://game.nsgo.dev/docs/shipping/), and [Getting Started](https://game.nsgo.dev/docs/getting-started/) for a first project. --- Source: https://game.nsgo.dev/docs/from-godot/ # Coming from Godot A map from Godot 4's scenes, nodes, resources, signals, input map, physics and export to this layer, with the page that covers each one. The biggest change is where a game lives. In Godot you assemble scenes in the editor and attach GDScript to nodes; here a game is Go code inside an NSGo component, and its scenes, prefabs and settings are YAML text files that you write by hand or save from the [editor](https://game.nsgo.dev/docs/editor/). Godot's habit of keeping scenes and resources as text (`.tscn`, `.tres`) carries over: every file you write is text you can read and diff in review. ## At a glance | Godot | Here | Guide | | --- | --- | --- | | `_physics_process(delta)`, physics ticks per second | `game.Loop.Update(dt)` with a fixed `dt`, `Loop.Rate` | [Loop](https://game.nsgo.dev/docs/loop/) | | `_process(delta)` | `game.Loop.Draw(alpha)` and the `core.Canvas` it redraws | [Loop](https://game.nsgo.dev/docs/loop/) | | `.tscn` scene, `PackedScene` | YAML scene document (`sceneformat`) built into layers | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/) | | `get_tree().change_scene_to_file()` | `scene.Manager.Switch` with a transition | [scene](https://game.nsgo.dev/docs/scene/) | | `Node2D` tree, `CanvasLayer` | `scene.Scene` layers in world or screen space | [scene](https://game.nsgo.dev/docs/scene/) | | `Node3D` tree, groups | `scene3d.Node` tree, `FindByTag` | [scene3d](https://game.nsgo.dev/docs/scene3d/) | | Instantiating a scene as a template | `entities.Prefab`, or a scene object's `prefab` field | [Entities](https://game.nsgo.dev/docs/entities/) | | `Resource`, `.tres`, `ResourceLoader` | YAML resource files in a `resource.Library`; images and sounds under `resources/`; data through `assets.Manager` with `WithFS` | [resource](https://game.nsgo.dev/docs/resources/), [assets](https://game.nsgo.dev/docs/assets/) | | Signals, `connect`, `emit` | `flow.Bus` with `Subscribe` and `Publish`; `core.Signal` for UI state | [flow](https://game.nsgo.dev/docs/flow/) | | `[connection]` in a `.tscn` | A scene file's `connections`, run by `sceneformat.Connect` and `Signals.Emit`, or deferred, as `CONNECT_DEFERRED` does, with `Signals.Enqueue` and `Flush`; `SpawnConnected` binds them to entities | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/#connections-490) | | `Timer` node, `await` on a signal | `flow.Timers`, `flow.Seq` and `flow.Wait` | [flow](https://game.nsgo.dev/docs/flow/) | | `Tween` | `tween.Tween`, `tween.Timeline` | [tween](https://game.nsgo.dev/docs/tween/) | | Input Map, `Input.is_action_just_pressed` | `input.Actions`, `JustPressed` | [input](https://game.nsgo.dev/docs/input/) | | `CharacterBody2D.move_and_slide()` | `World.MoveAndSlide` / `MoveAndSlideWith` against bodies, shapes, tiles and static rigid bodies (`physics.MoveAndSlide` for tiles alone; `platformer.Controller.StepWorld` for platformers) | [physics](https://game.nsgo.dev/docs/physics/), [platformer](https://game.nsgo.dev/docs/platformer/) | | `RigidBody2D`, joints | `physics.RigidWorld`, `RigidBody`, joints | [2D Rigid Bodies](https://game.nsgo.dev/docs/physics2d-rigid/) | | `CharacterBody3D`, `RigidBody3D` | `physics3d.CharacterController`, `physics3d.World` | [physics3d](https://game.nsgo.dev/docs/physics3d/) | | Export presets, export templates | `nsgo.yaml` and `go tool nsgo build` | [Building and Shipping](https://game.nsgo.dev/docs/shipping/) | ## Scenes A Godot scene is a saved node tree you instance or switch to. Here the two jobs are split: - **What a scene contains** is a YAML document with `version: 1`: a camera, tilemaps and ordered layers of placed objects, each with a transform, a sprite and free-form `components` and `properties` (the role of exported variables). `sceneformat.Parse` reads it and refuses unknown fields; `sceneformat.Build` turns it into layers ready to draw. See [Editor & Scene Format](https://game.nsgo.dev/docs/editor/). - **Which scene runs** is `scene.Manager`, which holds a stack of `scene.Controller` values. `Switch` replaces the current scene with a `Fade`, `Crossfade` or `Wipe` transition, `Push` lays a pause menu over it and `Pop` returns. See [scene](https://game.nsgo.dev/docs/scene/). `Controller.Enter` receives a child `*core.Scope` of its own. Loops, timers, sounds and signals made on it are disposed when the scene exits, which covers what `_ready`, `_exit_tree` and `queue_free` do for a scene's own objects. An autoload has no special form: make the value once in the root component and pass it to the scenes that need it. ## Nodes There is no single node class that everything inherits from. Pick the piece that fits: - **2D drawing**: a `scene.Scene` holds layers; a layer in `SpaceWorld` draws under the scene's camera (like `Node2D` under a `Camera2D`) and a layer in `SpaceScreen` draws in view space (like a `CanvasLayer`). Layers hold tilemaps, sprite batches and `scene.Drawable` values with their own `Draw`, `Update` and hit-test hooks. See [scene](https://game.nsgo.dev/docs/scene/), [sprite](https://game.nsgo.dev/docs/sprite/) and [tilemap](https://game.nsgo.dev/docs/tilemap/). - **3D hierarchy**: `scene3d.Node` has a parent, children, a local transform, tags (Godot's groups, found with `FindByTag`), named sockets for attachments and typed values set with `SetAttachment`. See [scene3d](https://game.nsgo.dev/docs/scene3d/). - **Game objects with behaviour**: instead of a script per node, keep data in components on an `entities.World` and write systems that run in a declared order each fixed step. `Prefab` stamps the same components onto new entities, as instancing a small scene does. See [Entities](https://game.nsgo.dev/docs/entities/). - **HUD and menus**: Godot's `Control` nodes become ordinary NSGo views layered over the canvas, or [gameui](https://game.nsgo.dev/docs/gameui/) widgets drawn inside it. 2D coordinates match Godot's: X right, Y down, rotation clockwise in radians. 3D matches too: right-handed, Y up, `-Z` forward, one unit a metre (see [math3d](https://game.nsgo.dev/docs/math3d/) and [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/)). ## Resources Godot's `.tres` resources map to [resource](https://game.nsgo.dev/docs/resources/) files: one YAML document each, with a `type` and `version` header, for materials, curves, gradients, animation clips, UI themes, sound bus layouts and physics materials. A `resource.Library` loads them from an `fs.FS` by path and keeps one value per path, as `ResourceLoader` caches a loaded resource. Images and sounds the game loads at runtime go in `resources/` and are opened by `"asset:"` URIs, such as `core.Src("asset:hero.png")`, on every target. Data that `assets.Manager` reads itself, such as atlas JSON, raw bytes and your own parsed files, comes from the file system you give it: embed it with `//go:embed` and pass `assets.NewManager(cx, assets.WithFS(fsys))`, or pass `WithReadAsset` for custom storage. Without either, the manager reads an `assets/` directory relative to the working directory, which works only for desktop runs from the project root. `assets.Manager` loads atlases, sounds, images, bytes and your own parsed files in named groups off the engine goroutine, reports progress as signals for a loading screen and releases a group when its scene ends. See [assets](https://game.nsgo.dev/docs/assets/). Files are read in the form the tool that made them writes, with no import step between them and the game, except where `game assets` builds them: it packs atlases, encodes KTX2 textures, converts sounds, bakes fonts into bitmap fonts and packs glTF models into GLB files, and the `.import` files map to its import settings sidecars, YAML files such as `hero.png.import.yaml` beside each image, sound, font or model that hold its compression, filter, sprite sheet slicing, loop points, font size and characters, or model scale ([Command Line](https://game.nsgo.dev/docs/cli/#assets)). Files the game reads as they are include TexturePacker and Aseprite atlases ([sprite](https://game.nsgo.dev/docs/sprite/)), Tiled maps ([tilemap](https://game.nsgo.dev/docs/tilemap/)) and glTF models ([3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/)). For your own `Resource` subclasses, write a YAML or JSON file and decode it into a Go struct, refusing unknown fields as the scene format does. Saved games take the place of `ConfigFile` and `FileAccess` writes: [save](https://game.nsgo.dev/docs/save/) keeps versioned JSON slots with migrations and a backup. ## Signals Godot's signals do two jobs here, each with its own tool: - **Gameplay events** between systems go through a typed `flow.Bus`. A struct type is the signal; `flow.Subscribe` connects, `flow.Publish` emits at once, `flow.Enqueue` with `Bus.Flush` emits later (Godot's deferred connection) and `flow.SubscribeOnce` is a one-shot connection. Nothing is keyed by a string, so a misspelt event does not compile. See [flow](https://game.nsgo.dev/docs/flow/). - **State a view shows**, such as a score in the HUD, is a [`core.Signal`](https://pkg.go.dev/github.com/nsgo-dev/nsgo/core#Signal). A view that reads it re-renders when it changes, without a handler wired by hand. Waiting with `await` becomes a step sequence: `flow.Seq(flow.Wait(d), flow.Do(fn))` run by a `flow.Runner` each fixed step, with no goroutines. The `Timer` node becomes `flow.Timers.After` and `Every`. Area callbacks such as `body_entered` are covered under physics below. ## Input map Godot's Input Map becomes an `input.Actions` value: bind names to inputs, call `Step` once at the start of each fixed update and ask about that step. | Godot | Here | | --- | --- | | Adding an action in Project Settings | `actions.Bind("jump", input.TouchRegion(rect), input.MouseButton(core.MouseButtonLeft))` | | `Input.is_action_pressed("jump")` | `actions.Pressed("jump")` | | `Input.is_action_just_pressed("jump")` | `actions.JustPressed("jump")` | | `Input.is_action_just_released("jump")` | `actions.JustReleased("jump")` | | `Input.get_axis("left", "right")` | `actions.BindAxis("move_x", "left", "right")`, then `actions.Axis("move_x")` | | `TouchScreenButton` | `input.TouchRegion`, or a `VirtualPad` of on-screen sticks and buttons | | Saving remapped controls | `actions.Save` and `actions.Load` in `core.Storage` | Bindings today are touch regions, mouse buttons and device motion. Key and gamepad bindings are tracked in [#3](https://github.com/nsgo-dev/game/issues/3); until they land, a key bound with NSGo's `cx.OnKey` can call `actions.Trigger("pause")`, which registers the action for one step. See [input](https://game.nsgo.dev/docs/input/). ## Physics The 2D physics package works in the same screen space as the drawing and steps on the loop's fixed `dt`. - **`CharacterBody2D`**: `World.MoveAndSlide(body, dt)` and `World.MoveAndSlideWith(body, dt, opts)` sweep a `Body`'s shape against static and kinematic bodies (including `Body.OneWay` platforms), solid and one-way tiles, and static `RigidBody` colliders, sliding along non-axis-aligned normals and returning `Collisions` plus `OnFloor`, `OnWall` and `OnCeiling` with configurable `UpX`/`UpY`, `FloorMaxAngle` and `MotionFloating` (top-down) mode — matching Godot's `move_and_slide()`, `is_on_floor()`, `get_slide_collision()`, `up_direction` and `motion_mode`. `physics.MoveAndSlide(body, grid, dt)` remains available for tile-only movement, and `CharacterBody.MoveWorld` / `platformer.Controller.StepWorld` add slopes and moving platforms. See [physics](https://game.nsgo.dev/docs/physics/) and [platformer](https://game.nsgo.dev/docs/platformer/). - **`Area2D`**: a `physics.Trigger` added with `World.AddTrigger` calls `OnEnter`, `OnStay` and `OnExit` from `World.StepTriggers`, as `body_entered` and `body_exited` do. - **`RayCast2D` and `intersect_ray`**: `World.RaycastFirst` and `World.Raycast`; `World.QueryOverlap` and `QueryPoint` cover shape and point queries. - **Collision layers and masks**: the `Layer` and `Mask` fields (`LayerMask`) on bodies and triggers. - **`RigidBody2D` and joints**: `physics.RigidWorld` with `RigidBody` boxes and circles; `RevoluteJoint` is a `PinJoint2D`, `SpringJoint` a `DampedSpringJoint2D` and `DistanceJoint` a fixed rod. See [2D Rigid Bodies](https://game.nsgo.dev/docs/physics2d-rigid/). - **3D**: `physics3d.CharacterController` walks a capsule over slopes and stairs as `CharacterBody3D` does, and `physics3d.World` steps rigid boxes, spheres and capsules. See [physics3d](https://game.nsgo.dev/docs/physics3d/). 2D shapes are boxes and circles; there are no concave polygon colliders in 2D. In 3D, bodies are boxes, spheres and capsules, and static level geometry can collide as a triangle mesh or a heightfield: `ConcavePolygonShape3D` maps to `physics3d.TriMeshCollider` added with `World.AddTriMesh`, and `HeightMapShape3D` to `physics3d.HeightfieldCollider` added with `World.AddHeightfield`. ## Export Export presets become `nsgo.yaml` at the project root: the app's name, identifier, version, icons and the targets to build. There are no export templates to download, because Go cross-compiles; only iOS and signed macOS builds need a Mac with Xcode. | Godot | Here | | --- | --- | | Running the project from the editor | `go tool nsgo dev`, with `-target web`, `ios_simulator` or `android` | | `export_presets.cfg` | `nsgo.yaml` (`build.targets`, `icon`, `id`, `version`) | | `godot --export-release` | `go tool nsgo build` | | Export for a store | `go tool nsgo build -channel store` | `go tool nsgo check -target all` vets the game for every target before a release. See [Building and Shipping](https://game.nsgo.dev/docs/shipping/), and [Getting Started](https://game.nsgo.dev/docs/getting-started/) for a first project. --- Source: https://game.nsgo.dev/docs/from-unity/ # Coming from Unity A map from Unity's scenes, GameObjects and components, assets, events, Input System, physics and builds to this layer, with the page that covers each one. A game here is Go code inside an NSGo component rather than C# scripts attached in an editor. Scenes, prefabs and settings are YAML text with a version field and readable object IDs such as `crate_3` that stay the same from save to save, where a `.unity` file refers to objects by opaque `fileID` numbers, so a change to a scene reads as a small diff. HUD and menus are native NSGo views over the game's canvas, where Unity would use uGUI or UI Toolkit. ## At a glance | Unity | Here | Guide | | --- | --- | --- | | `FixedUpdate`, `Time.fixedDeltaTime` | `game.Loop.Update(dt)` with a fixed `dt`, `Loop.Rate` | [Loop](https://game.nsgo.dev/docs/loop/) | | `Update`, `LateUpdate`, rendering | `game.Loop.Draw(alpha)` and the `core.Canvas` it redraws | [Loop](https://game.nsgo.dev/docs/loop/) | | `.unity` scene | YAML scene document (`sceneformat`) | [Editor & Scene Format](https://game.nsgo.dev/docs/editor/) | | `SceneManager.LoadScene`, additive loading | `scene.Manager.Switch`, `Push` and `Pop` | [scene](https://game.nsgo.dev/docs/scene/) | | GameObject with components, `MonoBehaviour` | `entities.World` entities, components and systems | [Entities](https://game.nsgo.dev/docs/entities/) | | `Transform` hierarchy | `scene3d.Node` tree | [scene3d](https://game.nsgo.dev/docs/scene3d/) | | Prefab, `Instantiate`, `Destroy` | `entities.Prefab`, `World.Spawn`, `World.Destroy` | [Entities](https://game.nsgo.dev/docs/entities/) | | `Resources.Load`, Addressables | `"asset:"` URIs for images and sounds, `assets.Manager` groups over an embedded file system | [assets](https://game.nsgo.dev/docs/assets/) | | C# events, `UnityEvent` | `flow.Bus`; `core.Signal` for UI state | [flow](https://game.nsgo.dev/docs/flow/) | | Coroutines, `Invoke`, `InvokeRepeating` | `flow.Seq`, `flow.Timers.After` and `Every` | [flow](https://game.nsgo.dev/docs/flow/) | | Input System action maps | `input.Actions` | [input](https://game.nsgo.dev/docs/input/) | | `Rigidbody2D`, `Collider2D`, joints | `physics` bodies, `RigidWorld`, joints | [physics](https://game.nsgo.dev/docs/physics/), [2D Rigid Bodies](https://game.nsgo.dev/docs/physics2d-rigid/) | | `Rigidbody`, `CharacterController` | `physics3d.World`, `physics3d.CharacterController` | [physics3d](https://game.nsgo.dev/docs/physics3d/) | | Build Settings, Player Settings | `nsgo.yaml` and `go tool nsgo build` | [Building and Shipping](https://game.nsgo.dev/docs/shipping/) | | `PlayerPrefs` | `core.Storage`, `save` slots | [save](https://game.nsgo.dev/docs/save/) | ## Scenes A scene document is YAML with `version: 1`: a virtual resolution, a background colour, a camera, tilemaps and ordered layers of objects. Each object has an `id`, a transform, an optional sprite, an optional `prefab` path and `components` and `properties` maps for the values you would show in the Inspector. `sceneformat.Parse` refuses unknown fields and bad transforms, `Encode` writes the same bytes for the same scene, and `Build` turns the document into layers ready to draw. See [Editor & Scene Format](https://game.nsgo.dev/docs/editor/). At runtime `scene.Manager` decides which scene runs. `Switch` is `LoadScene` with a `Fade`, `Crossfade` or `Wipe` transition; `Push` with a `Transparent` controller lays a pause menu over the current scene, as additive loading of a UI scene would; `Pop` unloads it. Each scene's `Enter` gets a child `*core.Scope`, and loops, timers, sounds and signals made on it are disposed when the scene exits, so a scene leaves nothing behind. See [scene](https://game.nsgo.dev/docs/scene/). ## GameObjects and components Unity attaches behaviour to objects; here data and behaviour are apart, as in Unity's DOTS: - An `entities.Entity` is a handle with a generation, so a destroyed one is never mistaken for a new one (Unity's "destroyed object" checks). - Components are plain Go structs: `entities.Set(world, e, Health{HP: 10})`, `Get`, `Has` and `Remove`. - A `MonoBehaviour`'s `FixedUpdate` becomes a system that runs over every entity with the components it needs (`entities.Each2[Position, Velocity]`). `Scheduler.AddSystem` with `Before` and `After` fixes the order, where Unity uses Script Execution Order. - A prefab is an `entities.Prefab`: `With` adds a component value, `Clone` makes a variant, `Spawn` and `SpawnN` instantiate. See [Entities](https://game.nsgo.dev/docs/entities/). For 3D transforms, `scene3d.Node` holds a parent, children and a local position, rotation and scale; sockets stand in for attaching a weapon to a bone, and `FindByName` and `FindByTag` for `GameObject.Find` and tags. See [scene3d](https://game.nsgo.dev/docs/scene3d/). Coordinates differ from Unity's. 2D drawing and 2D physics use screen space: X right, Y down, rotation clockwise, units in points. 3D is right-handed with Y up and `-Z` forward, while Unity is left-handed with `+Z` forward, so negate Z when you move positions and look directions across. One 3D unit is a metre in both. See [math3d](https://game.nsgo.dev/docs/math3d/) and [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/). ## Assets Images and sounds loaded at runtime live in `resources/` and open by `"asset:"`, such as `core.Src("asset:hero.png")`, on every target, as `Resources.Load` paths do. Data that `assets.Manager` reads itself, such as atlas JSON, raw bytes and your own parsed files, comes from the file system you give it: embed it with `//go:embed` and pass `assets.NewManager(cx, assets.WithFS(fsys))`, or pass `WithReadAsset` for custom storage. `assets.Manager` groups assets per scene, loads a group off the engine goroutine with progress you can bind to a loading screen, and releases it when the scene ends, the part of Addressables most games use. See [assets](https://game.nsgo.dev/docs/assets/). There is no asset database or `.meta` file. Files are read as their tools write them: TexturePacker and Aseprite atlases ([sprite](https://game.nsgo.dev/docs/sprite/)), Tiled maps ([tilemap](https://game.nsgo.dev/docs/tilemap/)) and glTF models ([3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/)). A `ScriptableObject` becomes a YAML file decoded into a Go struct. `PlayerPrefs` becomes `core.Storage`, and saved games are versioned JSON slots with migrations and a backup in [save](https://game.nsgo.dev/docs/save/). ## Events - **C# events and `UnityEvent`** become a typed `flow.Bus`. The event is a struct type: `flow.Subscribe(&bus, func(e EnemyDefeated) {...})` adds a listener and returns the function that removes it, `flow.Publish` raises the event at once, and `flow.Enqueue` with `Bus.Flush` holds events raised during physics until the end of the step. `SendMessage` and string-keyed messaging have no counterpart. See [flow](https://game.nsgo.dev/docs/flow/). - **Coroutines** become step sequences that a `flow.Runner` advances on each fixed step, with no goroutines: `flow.Seq(flow.Wait(time.Second), flow.Do(spawn))` is `yield return new WaitForSeconds(1)`, and `flow.WaitUntil` is `WaitUntil`. They pause with the game and replay the same way. `Invoke` and `InvokeRepeating` become `flow.Timers`. - **Animator state machines** for gameplay become `flow.Machine`; for 3D animation, [anim3d](https://game.nsgo.dev/docs/anim3d/) has state machines and blend spaces, and [tween](https://game.nsgo.dev/docs/tween/) covers what DOTween is used for. - **UI bindings**: a value the HUD shows is a [`core.Signal`](https://pkg.go.dev/github.com/nsgo-dev/nsgo/core#Signal), and a view that reads it re-renders when it changes. ## Input System An `input.Actions` value is an action map: names bound to inputs, read once per fixed step. | Unity Input System | Here | | --- | --- | | An action with bindings | `actions.Bind("jump", input.TouchRegion(rect), input.MouseButton(core.MouseButtonLeft))` | | `action.IsPressed()` | `actions.Pressed("jump")` | | `action.WasPressedThisFrame()` | `actions.JustPressed("jump")` | | `action.WasReleasedThisFrame()` | `actions.JustReleased("jump")` | | A 1D axis composite | `actions.BindAxis("move_x", "left", "right")`, then `actions.Axis("move_x")` | | On-Screen Stick and Button | `input.VirtualPad` | | Saving rebinding overrides | `actions.Save` and `actions.Load` in `core.Storage` | Call `actions.Step()` at the start of each update. Bindings today are touch regions, mouse buttons and device motion. Key and gamepad bindings are tracked in [#3](https://github.com/nsgo-dev/game/issues/3); until they land, a key bound with NSGo's `cx.OnKey` can call `actions.Trigger(name)`, which registers the action for one step. See [input](https://game.nsgo.dev/docs/input/). ## Physics Everything steps on the loop's fixed `dt`, in a fixed order, so the same inputs give the same result run after run (see [Determinism](https://game.nsgo.dev/docs/determinism/)). | Unity | Here | | --- | --- | | `Rigidbody2D` (dynamic) with `BoxCollider2D` or `CircleCollider2D` | `physics.RigidBody` in a `physics.RigidWorld` | | `PolygonCollider2D`, `CapsuleCollider2D`, `EdgeCollider2D` | `Polygon` (convex, up to 8 vertices), `Capsule`, `Segment` or `Chain` shapes, built with `NewRigidBody` | | `HingeJoint2D`, `SpringJoint2D`, `DistanceJoint2D` | `RevoluteJoint`, `SpringJoint`, `DistanceJoint` | | A kinematic platformer controller | `physics.MoveAndSlide` against a `TileGrid`, with `Grounded` and wall flags | | `isTrigger` and `OnTriggerEnter2D` | `physics.Trigger` with `OnEnter`, `OnStay` and `OnExit`, run by `World.StepTriggers` | | `Physics2D.Raycast`, `OverlapBox` | `World.RaycastFirst`, `World.QueryOverlap` | | Layers and the collision matrix | `Layer` and `Mask` (`LayerMask`) on each body and trigger | | `Rigidbody` with box, sphere or capsule colliders | `physics3d.World` with `Body` values | | `CharacterController.Move` | `physics3d.CharacterController.Move`, with slope limits and steps | See [physics](https://game.nsgo.dev/docs/physics/), [2D Rigid Bodies](https://game.nsgo.dev/docs/physics2d-rigid/) and [physics3d](https://game.nsgo.dev/docs/physics3d/). Moving colliders are boxes, circles, spheres and capsules. For static 3D level geometry, `MeshCollider` maps to `physics3d.TriMeshCollider` added with `World.AddTriMesh`, and `TerrainCollider` to `physics3d.HeightfieldCollider` added with `World.AddHeightfield`. ## Builds Build Settings and Player Settings become `nsgo.yaml` at the project root: product name, bundle identifier, version, build number, icons and the list of targets. There are no platform modules to install, because Go cross-compiles; iOS and signed macOS builds need a Mac with Xcode. | Unity | Here | | --- | --- | | Play mode | `go tool nsgo dev`, with `-target web`, `ios_simulator` or `android` | | Build and Run | `go tool nsgo build -run` | | Build for a platform | `go tool nsgo build -target macos,windows,linux,web,ios,android` | | Store builds (`.aab`, Mac App Store) | `go tool nsgo build -channel store` | `go tool nsgo check -target all` vets the game for every target before a release. See [Building and Shipping](https://game.nsgo.dev/docs/shipping/), and [Getting Started](https://game.nsgo.dev/docs/getting-started/) for a first project. --- Source: https://game.nsgo.dev/docs/gameui/ # gameui `game/gameui` builds stylized in-canvas menus and HUD widgets drawn directly into `core.Drawing`, with box layout, virtual-resolution scaling, 2D spatial action focus navigation, and world-anchored native NSGo overlays. ```go import "github.com/nsgo-dev/game/pkg/gameui" ``` ## Layout containers, widgets, and `Root` Compose a widget tree from layout containers (`Panel`, `VBox`, `HBox`) and widgets (`Label`, `Button`, `Toggle`, `Slider`, `List`, `ProgressBar`, `Spacer`), then wrap it in a `Root`: ```go theme := gameui.DefaultTheme() resumeBtn := &gameui.Button{Text: "Resume", OnClick: resumeGame} volumeSlider := &gameui.Slider{Label: "Volume", Min: 0, Max: 1, Value: 0.8, Step: 0.1, OnChange: setVolume} muteToggle := &gameui.Toggle{Label: "Mute", Style: gameui.ToggleSwitch, OnChange: setMuted} menu := &gameui.Panel{ Width: 320, Padding: core.EdgesAll(16), Child: &gameui.VBox{ Spacing: 10, Align: gameui.AlignStretch, Children: []gameui.Widget{ &gameui.Label{Text: "Paused", TextAlign: core.TextAlignCenter}, resumeBtn, volumeSlider, muteToggle, }, }, } uiRoot := gameui.NewRoot(menu) uiRoot.Theme = &theme ``` Inside your `Canvas.Draw`, call `uiRoot.Draw(d, bounds)` (which runs `Layout` and draws inside `Save`/`Restore` so caller canvas state stays untouched). Route pointer and keyboard events with `OnPointerMove`, `OnPointerDown`, `OnPointerUp`, `OnPress`, and `OnKeyDown`. Customize visuals with `Theme` fields, `NineSlice` frames (`NineSlice.FrameDrawer()`, `NineSliceStateFrame`), or custom `TextDrawer` and `TextMeasurer` hooks for bitmap fonts. ## Virtual-resolution scaling (`Viewport`) Attach a `Viewport` to `Root.Viewport` (or call `Root.DrawWithViewport`) so menus author against a fixed virtual resolution and scale cleanly across aspect ratios: ```go vp := gameui.NewViewport(1280, 720, gameui.ScaleFit) // ScaleFit, ScaleFill, ScaleStretch, ScaleInteger vp.LetterboxColor = core.RGB(8, 10, 16) uiRoot.Viewport = &vp // In Canvas.Draw: vp.SetWindowSize(canvasBounds.Size) uiRoot.Draw(d, canvasBounds) ``` `Root` automatically converts window-space pointer coordinates through `Viewport.WindowToVirtual` during hit-testing and draws letterbox bars when `ScaleFit` or `ScaleInteger` leaves margins. ## Spatial action focus navigation (`SpatialNavigator`) For gamepad and keyboard menus with grids or multi-column layouts, pair `Root` with `SpatialNavigator`: ```go nav := gameui.NewSpatialNavigator(uiRoot) nav.WrapAround = true nav.OnBack = closeMenu nav.SetOverrides(resumeBtn, gameui.NavOverrides{Up: muteToggle}) // Inside game.Loop.Update, bridge game/input actions: nav.StepActions(func(a gameui.NavAction) bool { switch a { case gameui.NavUp: return actions.JustPressed("ui_up") case gameui.NavDown: return actions.JustPressed("ui_down") case gameui.NavLeft: return actions.JustPressed("ui_left") case gameui.NavRight: return actions.JustPressed("ui_right") case gameui.NavConfirm: return actions.JustPressed("ui_confirm") case gameui.NavBack: return actions.JustPressed("ui_back") default: return false } }) ``` Customize focus outlines with `FocusRingStyle` on `Root.FocusRing`, `Theme.FocusRing`, or `SpatialNavigator.FocusRing` (including dashed outlines or a custom `Draw` callback). ## Ready settings menu (`SettingsMenu`) `SettingsMenu` provides a drop-in five-tab settings screen covering **Audio** (mute, master, and configurable bus volumes), **Video** (window mode, resolution, scale mode, integer scale, quality preset, VSync, and frame cap), **Controls** (keyboard and gamepad action rebinding with capture and reset), **Language** (locale picker), and **Accessibility** (subtitles/captions, text scale, high contrast, reduced motion, screen shake, flash reduction, color-blind mode, and game speed). It persists through `save.DefaultSettingsStore` and dispatches validated updates through `save.SettingsTargets` (`save.Apply`): ```go store := save.NewStorageSettingsStore(cx.Storage(), "mygame") menu := gameui.NewSettingsMenu(gameui.SettingsMenuConfig{ Store: store, Targets: save.SettingsTargets{ Sound: mixer, ApplyDisplay: video.Apply, ApplyBindings: func(b map[string][]string) error { gameui.ApplyBindingsToActions(actions, b, true); return nil }, ApplyLocale: setLocale, ApplyAccessibility: setAccessibility, }, OnBack: closeSettings, }) // In Canvas.Draw: menu.Draw(d, bounds) // Forward mouse, touch, keyboard, and gamepad input: // - Pointer: menu.OnPointerMove / OnPointerDown / OnPointerUp / OnPress // - Touch: menu.OnTouch(ev) // - Keyboard: menu.OnKeyDown(ev) // - Gamepad: menu.StepGamepad(gamepad.Pads(cx)) (D-pad / left stick, A confirm, B back, LB/RB tabs, button capture) ``` - Use `SettingsResolutionFrom` / `SetSettingsResolution` and `SettingsReduceFlashesFrom` / `SetSettingsReduceFlashes` to read or write the resolution and flash-reduction entries stored in `save.Settings.Custom`. - Use `FormatBindingToken`, `ParseBindingToken`, `FormatBindingLabel`, `GamepadButtonToken`, and `ApplyBindingsToActions` to bridge `save.Settings.Bindings` with `input.Actions`. - Call `SetText` with a translated `SettingsText` struct when the player switches language, and omit `Theme` (or call `HighContrastTheme()`) to automatically switch to high-contrast styling when `Accessibility.HighContrast` is enabled. - Call `SyncGamepad` when opening the menu so any button held to open it does not immediately trigger inside the screen. ## World-anchored native views (`AnchorOverlay`) Pin ordinary native NSGo views (name tags, speech bubbles, chat inputs) to 2D world coordinates over your game canvas using `AnchorOverlay`: ```go overlay := gameui.NewAnchorOverlay(cx) overlay.Add(&gameui.WorldAnchor{ ID: "npc-1", WorldX: 240, WorldY: 120, OffsetY: -28, AnchorX: 0.5, AnchorY: 1, Visible: true, View: func(cx *core.Scope) core.View { return core.Text(cx, "Blacksmith") }, }) // Each frame after camera update: proj := gameui.NewCameraViewportProjection(cam.X, cam.Y, cam.Zoom, 1280, 720, vp) overlay.Sync(proj) ``` Mount `overlay.View(cx)` above your `Canvas` inside a `core.Stack`. Anchors that project outside `ScreenBounds` are hidden automatically, and positions update via `SetWorldPosition` and `Sync` without rebuilding the surrounding view tree. ## Screen files (`*.screen.yaml`) Author HUDs and menus as plain-text versioned YAML files (`*.screen.yaml`, published schema `https://game.nsgo.dev/schemas/screen.v1.json`) rather than hand-coding every widget in Go. `ParseScreen`, `LoadScreenFS`, and `EncodeScreen` refuse unknown fields, duplicate node IDs or focus orders, YAML anchors/aliases, and unsupported versions, and round-trip losslessly in canonical 2-space YAML. A screen defines a `designWidth` × `designHeight` reference canvas (such as `640 × 360`), an optional `scaleMode` (`fit`, `fill`, `stretch`, or `integer`), and a tree of nodes (`vbox`, `hbox`, `label`, `button`, `sprite_row`, `color_rect`, `touch_stick`, `touch_button`, `container`): - **Anchors and safe areas:** set `anchor` to one of nine points (`top_left`, `top_center`, `top_right`, `center_left`, `center`, `center_right`, `bottom_left`, `bottom_center`, `bottom_right`) or `fill`, `offset` (`x`, `y` inset inward from right/bottom edges), and `safeArea` (defaults to `true` for non-fill anchors and `false` for `fill`). - **Sizing and localized text:** store localization keys in `textKey` (never literal strings), use `sizeMode: fixed` with `width` or `sizeMode: fit_text` to grow with localized text, and set `padding`, `spacing`, `fontSize`, `textColor`, `background`, and `cornerRadius`. - **Focus order, touch areas, and device classes:** declare explicit 1-based `focusOrder` for keyboard/gamepad traversal, `touchHitSize` for expanded circular touch targets (`TouchButton`, `TouchStick`, `Button`), and `deviceClasses` (`phone`, `tablet`, `desktop`, `ultrawide`) to show controls only on matching devices. Build a parsed screen into a `gameui.Root` and `SpatialNavigator` at runtime with `BuildScreen`: ```go doc, err := gameui.LoadScreenFS(assetsFS, "screens/hud.screen.yaml") if err != nil { return err } phone := gameui.ReferenceDevicesFor(doc.DesignWidth, doc.DesignHeight)[0] screen, err := gameui.BuildScreen(doc, gameui.ScreenBuildOptions{ SafeArea: phone.SafeArea, DeviceClass: phone.Class, ViewportWidth: phone.Width, ViewportHeight: phone.Height, Catalog: catalog, Locale: "zh", OnClick: map[string]func(){ "pause_button": openPauseMenu, "jump": triggerJump, }, }) ``` Call `screen.Draw(d, bounds)` inside `Canvas.Draw`, switch languages dynamically with `screen.ApplyCatalog(catalog, locale)`, update safe-area insets with `screen.SetSafeArea(insets)`, or switch device filters with `screen.SetDeviceClass(class)`. ### Validation (`game check`) and safe refactoring (`refs`, `game mv`) `game check` (and `gameui.CheckScreen`) checks every `*.screen.yaml` file in a project and reports the file, line, and node for: - touch areas under `44 pt` on phones and tablets; - localized text that overflows its box in any project locale at the four reference sizes (`Phone 19.5:9 (notch)`, `Tablet 4:3`, `Desktop 16:9`, `Ultrawide 21:9`), accounting for full-width CJK glyphs; - a `textKey` missing from any project locale string table; - text under `4.5:1` WCAG contrast against its fill; - missing `sprite` images or atlas frames. `refs` and `game mv` follow `sprite` paths and `textKey` references in `*.screen.yaml` files: `game mv art/heart.png art/ui/heart.png` rewrites `sprite:` in place, and `game mv -text-key hud.hint.lever hud.tip.lever` renames a localization key across both `*.screen.yaml` files and YAML string tables. --- Source: https://game.nsgo.dev/docs/gc-and-allocations/ # GC and Frame Allocations A 60 fps frame budget is 16.67 ms (8.33 ms at 120 fps). Go's garbage collector runs concurrently with low stop-the-world (STW) pauses, but steady per-frame heap allocations trigger frequent GC cycles, consume background CPU (mark assist), and can cause visible frame hitches. Keeping the update and draw hot paths at zero allocations per frame prevents GC work during active gameplay. ## Tuning `GOGC` and `GOMEMLIMIT` Go exposes two primary GC knobs, configurable via environment variables or `runtime/debug`: - **`GOGC`** (`debug.SetGCPercent`, default `100`): controls how much new heap may be allocated before the next GC cycle starts, as a percentage of live heap size. - Lower values (`50`–`100`) keep memory footprint tight at the cost of more frequent GC cycles. - Higher values (`200`–`400`, or `off` when paired with `GOMEMLIMIT`) reduce GC cycle frequency during gameplay, provided steady-state allocations stay near zero. - **`GOMEMLIMIT`** (`debug.SetMemoryLimit`, default unlimited): sets a soft total Go runtime memory limit. - Pairing a soft `GOMEMLIMIT` with a higher `GOGC` lets the game avoid unnecessary collections while staying safely below platform memory ceilings. - Never set `GOMEMLIMIT` below the live asset + scene working set, or the GC will thrash trying to stay under the limit. ```go import rdebug "runtime/debug" func configureGC() { // Example: keep a 256 MiB soft ceiling and relax cycle frequency. rdebug.SetMemoryLimit(256 << 20) rdebug.SetGCPercent(200) } ``` ## Zero-Alloc Hot-Path Guidelines Keep `Loop.Update`, `Loop.Draw`, and `Canvas.Draw` callbacks free of steady-state heap allocations: 1. **Pre-allocate and reuse slices and pools.** Keep slice backing arrays on structs and reset with `s = s[:0]` instead of allocating fresh slices each frame. 2. **Avoid `fmt.Sprintf` and string concatenation in hot loops.** Format HUD strings only when the underlying value changes, or inside reactive text callbacks gated on changed state. 3. **Avoid per-frame closure captures and interface boxing.** Prefer methods on pre-allocated structs and typed value tokens (such as `debug.ScopeToken`) over allocating closures or `any` wrappers per frame. 4. **Reuse `sprite.Batch` and fixed-size ring buffers.** Keep particle, bullet, and telemetry buffers fixed-capacity rather than growing/shrinking every tick. 5. **Load and decode assets between gameplay states.** Track per-group footprints with `debug.MemoryTracker` and call `ReleaseGroup` on level transitions; run an explicit `runtime.GC()` during loading screens rather than mid-frame. 6. **Build releases with `-tags release`.** All `pkg/debug` tooling compiles to zero-cost no-op stubs in release builds. ## Detecting GC Hitches and Testing in CI ### Runtime Overlay (`GCMonitor`) Wire `debug.NewGCMonitor` into `debug.Options.GC` to sample `runtime/metrics` (`/gc/pauses:seconds`, `/gc/cycles/total:gc-cycles`, `/memory/classes/heap/objects:bytes`, `/gc/heap/allocs:objects`, `/gc/heap/allocs:bytes`) once per frame with zero steady-state allocations: ```go gcMon := debug.NewGCMonitor(debug.FrameHistory) overlay := debug.New(debug.Options{ GC: gcMon, }) ``` Frames where a GC cycle or pause occurred are flagged (`GCFrameSample.Hitched == true`) and marked directly on the overlay's frame-time graph, alongside cycle count, last/max pause, live heap bytes, and recent hitch count. Each `GCFrameSample` also carries the heap objects and bytes allocated during that frame (`AllocsDelta`, `AllocBytesDelta`). `gcMon.AllocsPerFrame()` and `gcMon.AllocBytesPerFrame()` average them over the retained history, and the overlay shows them under the GC summary as `allocs 12.0/f (1.5 KB/f)`. A value that stays above zero in steady gameplay means a hot path allocates every frame. Call `gcMon.Reset()` after a loading screen or level change to drop the history and measure from that point. ### CI Regression Checks (`AssertZeroAllocs`) Use `debug.AssertZeroAllocs` (wrapping `testing.AllocsPerRun`) in unit tests to guard hot paths from accidental allocations in pull requests: ```go func TestPhysicsStepZeroAllocs(t *testing.T) { world := newTestWorld() // Warm up one frame so any one-time caches are initialized. world.Step(16 * time.Millisecond) debug.AssertZeroAllocs(t, 100, func() { world.Step(16 * time.Millisecond) }) } ``` Use `debug.MeasureAllocs` when you want to assert an explicit upper bound or log allocation counts during optimization. ## Platform Notes | Target | Memory & GC Considerations | | --- | --- | | **Desktop** (macOS, Windows, Linux) | Ample RAM and multi-core background marking; higher `GOGC` (e.g. `200`) with a conservative `GOMEMLIMIT` works well for smooth 60–120 fps pacing. | | **iOS** | Strict jetsam memory limits per device class (especially older or lower-RAM devices). Always set `GOMEMLIMIT` well below the app's jetsam ceiling after accounting for native GPU textures and decoded audio buffers outside the Go heap. | | **Android** | Wide variance in available RAM and thermal throttling across devices; background mark workers compete with rendering on low-core devices. Keep per-frame allocations at zero and size `GOMEMLIMIT` conservatively. | | **WebAssembly** (`js/wasm`) | Single-threaded execution means GC work cannot hide on separate CPU cores and linear memory only grows. Minimizing per-frame allocations is especially critical to avoid frame drops and browser tab memory pressure. | > **Hardware profiling status:** Physical-device GC pause and latency profiles across macOS, Windows, Linux, iOS, Android, and WebAssembly have not yet been recorded on target hardware. Numbers and platform defaults in this guide reflect Go runtime behavior and should be refined once hardware benchmarks are collected. --- Source: https://game.nsgo.dev/docs/idle/ # idle `game/idle` holds what idle and incremental games need: a `Number` that reaches far past float64's 1.8e308, progress earned while the game was closed, and formatting of very large numbers as 1.23K, 1.23e45 or 1.23万. ```go import "github.com/nsgo-dev/game/pkg/idle" ``` ## Numbers past float64 A `Number` is a plain float64 for magnitudes from 1e-300 to 1e300 and a float64 mantissa with an int64 power of ten beyond, up to 10^`MaxExponent` (10^(10^18)). Inside the plain range its arithmetic is float64 arithmetic, so integers up to 2^53 stay exact; past it a result keeps float64's 15 to 17 significant digits. ```go gold := idle.New(250) rate := idle.NewExp(1.5, 400) // 1.5e400 a second gold = gold.Add(rate.Mul(idle.Seconds(dt))) // in game.Loop's Update cost := idle.New(10).Mul(idle.New(1.15).Pow(owned)) // base × growth^owned if gold.Cmp(cost) >= 0 { gold = gold.Sub(cost) owned++ } ``` - `Add`, `Sub`, `Mul`, `Div`, `Scale`, `Pow` (an integer power by repeated squaring), `Neg`, `Abs`, `Min` and `Max` return new values; `Div` by zero panics. - `Cmp`, `Sign` and `IsZero` compare; equal values are also `==`, since every value has one representation. - `Mantissa` and `Exponent` give the decimal parts, `Float64` a float64 (±Inf past its range), and `Log10` a float for progress bars. Inside the plain range `New(f).Float64()` is exactly `f`; beyond it the decimal mantissa keeps `f` within one unit in the last place. - Results past 10^`MaxExponent` saturate to the largest value of that sign, and magnitudes below 10^-`MaxExponent` become zero. - Every operation is a plain IEEE-754 float64 operation with no fused multiply-add, so the same sequence gives the same bits on every platform; the package's tests pin one on linux/amd64 and darwin/arm64. `Log10` is the exception and is meant only for display. ### Text in saves and data files A `Number` reads and writes itself as text, so it is a string in a JSON save slot (`"gold":"1.23e45"`) and a plain scalar in YAML data a person writes (`cost: 7.5e400`). JSON also accepts a plain number (`"cost":1500`), and `null` leaves the field unchanged. `String` writes positional text for exponents from -6 to 20 (`1500`, `0.25`) and scientific beyond (`1.23e45`), with the shortest digits that read back exactly, so `Parse(n.String())` returns `n`. `Parse` takes an optional sign, digits with an optional point and an optional exponent. It refuses spaces, underscores, hexadecimal, `inf` and `NaN` with `ErrSyntax`, and values whose leading digit lies past the range with `ErrRange`; the range is judged after the digits, so `0.001e1000000000000000002` is 10^(`MaxExponent`-1) and zero is 0 whatever its exponent. ## Offline progress A game stores the time it was last seen, and on its next start, or on return from the background, `Offline` credits the time in between: ```go type Progress struct { Gold idle.Number `json:"gold"` Rate idle.Number `json:"rate"` // per second LastSeen time.Time `json:"last_seen"` } offline := idle.Offline{Cap: 8 * time.Hour, Min: time.Minute, Efficiency: 0.5} earned, away := offline.Earn(p.Rate, p.LastSeen, time.Now()) p.Gold = p.Gold.Add(earned) p.LastSeen = away.Seen store.Save("slot1", p) if away.Credited > 0 { showWelcomeBack(earned, away.Elapsed, away.Capped) } ``` - `Cap` is the longest absence credited (0 for none), `Min` the shortest (shorter credits nothing), and `Efficiency` the fraction of the online rate earned while away (0 means the full rate). Negative values, a non-finite `Efficiency` and a `Min` above a non-zero `Cap` panic. - `Earn` returns rate × credited seconds × efficiency; `Absence` returns only the `Away` record, for a game that computes its own rewards. - `Away.Steps(step)` splits the credited time into whole fixed steps and a remainder, for a game that replays its simulation step by step instead of multiplying a rate. - The difference is wall-clock time: monotonic readings are dropped, so time asleep counts and a timestamp read back from a save compares like one taken now. Time zones do not matter. - A zero last-seen time, as on a first launch, credits nothing. A clock set back before the last-seen time sets `Rewound` and credits nothing; `Seen` keeps the later of the two times, so storing it means that setting the clock back and forward again cannot credit the same hours twice. A clock set forward cannot be told from real time away, so a game that needs that guarantee measures the absence against a server's time. `Seconds(d)` converts a `time.Duration` to a `Number` of seconds. ## Formatting large numbers `Format` writes a `Number` in a notation and locale. The zero `Format` writes `Short` notation with three significant digits in English: | Value | `Short` en | `Short` zh-Hans | `Scientific` | `Engineering` | `Letters` | `Full` | | --- | --- | --- | --- | --- | --- | --- | | 999 | 999 | 999 | 999 | 999 | 999 | 999 | | 12345 | 12.3K | 1.23万 | 1.23e4 | 12.3e3 | 12.3K | 12,345 | | 123456789 | 123M | 1.23亿 | 1.23e8 | 123e6 | 123M | 123,456,789 | | 4.56e15 | 4.56Qa | 4560兆 | 4.56e15 | 4.56e15 | 4.56aa | 4,560,000,000,000,000 | | 1.23e45 | 1.23Qad | 12.3载 | 1.23e45 | 1.23e45 | 1.23ak | 1.23e45 | | 1e70 | 1e70 | 1e70 | 1e70 | 10e69 | 10as | 1e70 | ```go hud := idle.Format{Locale: idle.LocaleFor(localizer.Locale())} goldText := hud.Format(gold) var buf []byte buf = hud.Append(buf[:0], gold) // no allocation when buf has room ``` - `Short` divides by the locale's largest unit at or below the value: K, M, B, T, Qa, Qi, Sx, Sp, Oc, No, Dc, Ud, Dd, Td, Qad, Qid, Sxd, Spd, Ocd, Nod and Vg (10^3 to 10^63) in English, and the myriad units 万, 亿, 兆, 京, 垓, 秭, 穰, 沟, 涧, 正 and 载 (10^4 to 10^44) in Chinese. Values below the first unit are positional with grouping (`9,999`), and values past the last unit's range are scientific, as is any value that would need more than 21 integer digits, such as one in a wide gap between a custom locale's units. - `Scientific` writes one integer digit (`1.23e45`), `Engineering` a power of ten that is a multiple of three (`12.3e45`), and `Letters` K, M, B and T followed by aa, ab, … zz, aaa and so on, which never runs out. All three are positional below 1000. - `Full` writes every integer digit with grouping (`1,234,567`) up to 10^21, then scientific. - `Digits` is the number of significant digits (default 3, at most 17). Integer digits are never dropped: 123456 is `123K`, and 1234 in `Full` is `1,234`. - Trailing fraction zeros are trimmed unless `Fixed` is set: `1.2K`, or `1.20K` with `Fixed`, which keeps a counter's width steady. - Rounding happens before the unit is chosen, so 999999 is `1M` and 99999999 in Chinese is `1亿`, never `1000K` or `10000万`. - Magnitudes below 10^-6 are scientific in every notation. ## Locales `English()`, `ChineseSimplified()` and `ChineseTraditional()` return new built-in locales; `LocaleFor(tag)` picks one from a BCP 47 tag (zh with Hant, TW, HK or MO is Traditional, other zh is Simplified, anything else English). Each call returns a copy, so a game can change one, for example to name its own units. A game adds a language, or its own units, in a versioned YAML file: ```yaml version: 1 name: de decimal: ',' group: . exponent: E units: - exp: 3 suffix: ' Tsd.' - exp: 6 suffix: ' Mio.' ``` ```go de, err := idle.ParseLocale(data) if err != nil { return err } idle.Format{Locale: de}.Format(idle.New(1500)) // "1,5 Tsd." idle.Format{Notation: idle.Full, Digits: 6, Locale: de}.Format(idle.New(1234.5)) // "1.234,5" ``` - `version` must be 1, and unknown fields and trailing documents are refused. - `decimal` and `exponent` are required, and `group` may be empty for no grouping; none may contain an ASCII digit or sign, and all three must differ. - `units` lists units in ascending `exp` order, from 1 to 1000000, with distinct, non-empty suffixes that are neither separator and do not start with `exponent`. A suffix carries its own spacing, such as `' million'`. - `EncodeLocale` writes the canonical form: fields in a fixed order and 2-space indentation, so `ParseLocale` followed by `EncodeLocale` reproduces the same bytes. `Validate` checks a locale built in code. --- Source: https://game.nsgo.dev/docs/input/ # input `game/input` turns touch regions, mouse buttons, relative mouse motion under a pointer lock, keyboard keys and game controllers into named actions and axes, sampled once per `game.Loop` step and persisted across launches in `core.Storage`. ```go import "github.com/nsgo-dev/game/pkg/input" ``` All `Actions` methods run on the engine's goroutine, alongside `core.View` callbacks and `game.Loop.Update`. ## Defining actions and axes An `Actions` instance maps logical names (such as `"jump"`, `"left"`, `"right"`, or `"move_x"`) to one or more physical `Input` triggers. Its zero value is ready to use, or construct one with `input.NewActions()`: ```go actions := input.NewActions() // Touch zones in virtual canvas coordinates (e.g. 320×180) actions.Bind("left", input.TouchRegion(core.Bounds{X: 0, Y: 100, Width: 70, Height: 80}), input.Key("left"), // by name, following the keyboard layout input.KeyCode("KeyA"), // by physical position ) actions.Bind("right", input.TouchRegion(core.Bounds{X: 70, Y: 100, Width: 70, Height: 80}), input.Key("right"), input.KeyCode("KeyD"), ) actions.Bind("jump", input.TouchRegion(core.Bounds{X: 220, Y: 100, Width: 100, Height: 80}), input.MouseButton(core.MouseButtonLeft), input.Key("space"), ) actions.Bind("interact", input.MouseRegion(core.Bounds{X: 260, Y: 10, Width: 50, Height: 30}, core.MouseButtonLeft), ) // Combine two opposing actions into a [-1, 1] axis actions.BindAxis("move_x", "left", "right") ``` Physical `Input` constructors: | Constructor | Active when | | --- | --- | | `TouchRegion(rect)` | Any active touch finger lies inside `rect` (`core.Bounds.Contains`). | | `MouseButton(btn)` | `btn` is held down anywhere on the attached view. | | `MouseRegion(rect, btn)` | `btn` is held down and the pointer lies inside `rect`. | | `Key(name)` | The key `name` is held, named as `core.KeyEvent.Key` names it (`"a"`, `"space"`, `"left"`, `"shift"`), matched without regard to case. A letter follows the keyboard layout. | | `KeyCode(code)` | The key at physical position `code` is held, named as `core.KeyEvent.Code` names it (`"KeyW"`, `"ArrowLeft"`), the same key on every layout. | | `GamepadButton(btn)` | `btn` is pressed on a controller the `Actions` reads (see Game controllers below). | Calling `Bind(name, ...)` replaces previous bindings for `name`; calling `Bind(name)` with no inputs or `Unbind(name)` clears it. Inspect bindings with `Bindings(name)` and `AxisBinding(name)`, and remove an axis with `UnbindAxis(name)`. ## Attaching to a view and coordinate mapping Wire `Actions` onto your game's `core.View` with `Attach`, which chains onto any existing event handlers without overwriting them: ```go view := core.View{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, Children: []core.Node{gameCanvas}, } actions.Attach(&view) ``` You can also forward individual callbacks manually via `OnTouch`, `OnPressDown`, `OnPressUp`, `OnMouseMove`, `OnMouseLeave`, `OnContextMenu`, `OnPointerDelta`, `OnKeyDown`, and `OnKeyUp`. - `OnPressDown` ignores keyboard presses and synthetic presses fired while a touch finger is active so touches only trigger `TouchRegion` bindings. - `OnContextMenu` records a right click as a single-step pulse of `core.MouseButtonRight` at `ev.Position`. - `OnMouseLeave` releases held mouse buttons when the pointer exits the view. ### Mapping view coordinates to a virtual canvas When your game renders through a letterboxed [`screen.Viewport`](https://game.nsgo.dev/docs/screen/), set `MapPoint` so `TouchRegion` and `MouseRegion` bounds are evaluated in virtual game coordinates: ```go actions.MapPoint = func(p core.Point) (core.Point, bool) { return viewport.ViewToGame(windowSize, p) } ``` Returning `false` from `MapPoint` (for example, a tap on a letterbox bar) ignores that point for region tests. ## Hearing keys A view hears keys only while it has the keyboard focus, and a click presses a view without focusing it, so a game usually hears them on the whole window instead. Call `WatchKeys` once, from the scope that runs the loop: ```go actions.WatchKeys(cx) loop.Run(cx) ``` `WatchKeys` follows NSGo's `core.KeysDown` and `core.KeyCodesDown` until the scope is disposed or the returned `stop` is called. Keys typed into a text input or composed by an input method are never held. `Attach` also wires `OnKeyDown` and `OnKeyUp`, which hear keys while the view itself has the keyboard focus, such as a `Focusable` game view on a desktop. `OnKeyDown` consumes a key bound to an action, so the keymap's bindings and the view's own Return and Space do not take it too; an unbound key passes on. A held key's auto-repeat changes nothing. Either way: - A held key keeps its action `Pressed` on every step until it comes up, and a key that goes down and up between two steps is latched for one step, as a tap is. - Two actions bound to opposite keys drive an axis with `BindAxis`: `Axis` is `-1` with the negative key held, `+1` with the positive one, and `0` with both or neither. - Every held key comes up as the window loses the keyboard focus, firing `JustReleased` on the next step, so no action stays held while the player is in another window. - `Reset` releases every held key, and a key still held then stays released until it comes up and goes down again. A key held as the attached view leaves the tree stays held, because NSGo no longer sends that view its key-up: call `Reset` when you replace the game view, or use `WatchKeys`, which does not depend on a view. `Key` takes the names `core.KeyEvent.Key` reports, matched without regard to case. The aliases `core.KeyHeld` also accepts, such as `"mod"`, `"cmd"` or `"option"`, are never held; bind `"meta"` where `Env.AppleKeys` reports Command as the platform modifier and `"ctrl"` elsewhere. ## Game controllers Bind controller buttons with `GamepadButton` like any other `Input`, bind stick axes with `BindGamepadAxis`, and call `WatchGamepads` once so every `Step` reads the controllers connected to the app through NSGo's [`gamepad`](https://github.com/nsgo-dev/nsgo/tree/main/gamepad) package, on every target that has them (macOS, iOS, Windows, Linux, Android and the web): ```go actions.Bind("jump", input.GamepadButton(gamepad.ButtonSouth), input.TouchRegion(jumpRect)) actions.Bind("left", input.GamepadButton(gamepad.ButtonDPadLeft)) actions.Bind("right", input.GamepadButton(gamepad.ButtonDPadRight)) actions.BindAxis("move_x", "left", "right") // The left stick drives the same axis as the D-pad, with the default radial dead zone. actions.BindGamepadAxis("move_x", gamepad.AxisLeftX, input.GamepadAxisOptions{}) // Pushing the right stick up reads positive. actions.BindGamepadAxis("look_y", gamepad.AxisRightY, input.GamepadAxisOptions{DeadZone: 0.2, Invert: true}) actions.WatchGamepads(cx) ``` Buttons use the W3C Standard Gamepad layout; a button counts as pressed from 0.5, so the analog triggers `ButtonLT` and `ButtonRT` press halfway down. `Axis` adds a stick axis to anything else bound to the same name (`BindAxis`, `BindMotionAxis`, a `VirtualPad` stick) and clamps the sum to `[-1, 1]`. | `GamepadAxisOptions` field | Effect | | --- | --- | | `DeadZone` | Deflection below which the axis reads 0; the rest is rescaled to rise smoothly from 0 to 1. `0` uses `DefaultGamepadDeadZone` (0.15), a negative value turns it off. | | `Axial` | Applies the dead zone to this axis alone. By default it is radial over the whole stick, so a diagonal push keeps its direction. | | `Sensitivity` | Multiplies the dead-zoned value before clamping (1 when `<= 0`). | | `Invert` | Negates the value. | By default an `Actions` reads every connected controller: a button is pressed when it is pressed on any of them, and a stick axis takes the reading farthest from center. Call `SelectGamepad(id)` with an ID from `gamepad.Pads` to restrict one `Actions` to a single controller, or `SelectAnyGamepad` to go back to every controller; for multi-player setups, use `Players` below. Disconnecting a controller releases what it held, and reading stops once the scope passed to `WatchGamepads` is disposed. Controllers are polled once per step, so a press and release that both happen between two steps are not seen. Tests and replays can skip the live controllers and feed `[]gamepad.Pad` snapshots with `OnGamepads`, which latches presses between steps like touches; `Gamepads()` returns the state last read. ## Local multiplayer `Players` manages several player slots (`0` to `Len()-1`), each with its own `Actions`, routing every connected game controller to at most one player and forwarding keyboard or pointer events only to the players assigned to them: ```go players := input.NewPlayers(2) for _, p := range players.All() { a := p.Actions() a.Bind("jump", input.GamepadButton(gamepad.ButtonSouth)) a.Bind("left", input.GamepadButton(gamepad.ButtonDPadLeft)) a.Bind("right", input.GamepadButton(gamepad.ButtonDPadRight)) a.BindAxis("move_x", "left", "right") a.BindGamepadAxis("move_x", gamepad.AxisLeftX, input.GamepadAxisOptions{}) } players.AssignGamepad(0, pad1ID) players.AssignGamepad(1, pad2ID) players.WatchGamepads(cx) // In Loop.Update: players.Step() p0Move := players.Player(0).Axis("move_x") p1Jump := players.Player(1).JustPressed("jump") ``` - **Device isolation and exclusivity**: `AssignGamepad(index, padID)` assigns controller `padID` exclusively to player `index` (if another player owned `padID`, that player loses it and releases any held buttons). Assigning a controller ID before it connects remembers the slot; `p.GamepadConnected()` and `p.Gamepad()` report whether the assigned controller is currently present. - **Split keyboard and mixed devices**: Call `AssignKeyboard(index)` on one or more players and `WatchKeys(cx)` (or `Attach(&view)`) on `Players`. Several players can share one keyboard with disjoint key sets (such as WASD + Space for player 0 and arrow keys + Enter for player 1), or one player can use keyboard while another uses a gamepad — a gamepad-only player never reacts to keyboard events even when both players share the same binding template. Call `AssignPointer(index)` to route touch, mouse, and pointer-lock events to specific players (such as split-screen touch regions or player 0 on keyboard + mouse). - **Auto-assignment and drop-in lobbies**: Call `AssignUnassignedGamepads()` to assign unassigned connected controllers (in ascending ID order) to open slots with no device (`!p.HasDevice()`), or inspect `UnassignedGamepads()` and `NextUnassigned()` to implement press-to-join lobbies. Add slots dynamically with `Add()`, and clear assignments with `UnassignGamepad`, `UnassignKeyboard`, `UnassignPointer`, or `Unassign`. - **Single-step polling, reset, and persistence**: `players.Step()` polls `gamepad.Pads` once and steps every player's `Actions`; `players.Reset()` resets every player while preserving slots, bindings, and device assignments; tests and replays can feed snapshots with `players.OnGamepads(pads)`. Save and load each player's bindings independently through `p.Actions().Save` and `p.Actions().Load`. ### Controller disconnect, reconnect, and fallback Configure `Players.SetDisconnectPolicy` to handle controllers that disconnect mid-game cleanly for both single-player (`NewPlayers(1)`) and local multiplayer games: ```go players.SetDisconnectPolicy(input.DisconnectPolicy{ PauseOnDisconnect: true, AllowReassignOnPress: true, OnPause: loop.SetPaused, OnDisconnect: func(ev input.DisconnectEvent) { showReconnectPrompt(ev.PlayerIndex) }, OnReconnect: func(ev input.ReconnectEvent) { if !ev.ShouldPause { hideReconnectPrompt() } }, }) ``` - **Clean release and pause**: When a player's previously connected controller disappears from the snapshot, `Players` releases that player's held buttons and stick axes immediately on the step, remembers the lost controller ID, emits `OnDisconnect` (`DisconnectEvent`), and calls `OnPause(true)` when `PauseOnDisconnect` is set (and fallback is not active). While `WatchGamepads` has a live scope and any player is awaiting reconnect, `Players` polls controllers on display frames even while `game.Loop` is paused, so reconnecting or pressing a button on another pad resumes the loop automatically. Call `PollGamepads()` directly if you drive polling outside `game.Loop`. - **Reconnect and press-to-reassign**: Reconnecting the same controller automatically reclaims the player's slot and emits `OnReconnect` (`Reassigned: false`). When `AllowReassignOnPress` is enabled, newly pressing any button on an unassigned connected controller assigns it to the lowest-index disconnected player slot and emits `OnReconnect` (`Reassigned: true`). Once every disconnected required player has recovered (or been manually reassigned/unassigned), `Players` calls `OnPause(false)`. - **Single-player keyboard/touch fallback**: Set `FallbackToKeyboardTouch: true` so a controller disconnect continues without pausing (`DisconnectEvent.FallbackActive == true`, `ShouldPause == false`). `Players` temporarily enables keyboard and pointer/touch routing on that player (preserving any pre-existing keyboard or pointer assignments) and switches back cleanly when the original controller reconnects or another controller claims the slot. - **State queries**: Inspect `p.GamepadDisconnected()`, `p.FallbackActive()`, `players.DisconnectedPlayers()`, and `players.PausedByDisconnect()` to drive HUD prompts or pause overlays. ## Sampling once per fixed step Call `actions.Step()` once at the start of `game.Loop.Update`, then query `Pressed`, `JustPressed`, `JustReleased`, and `Axis` for that step's snapshot: ```go loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { actions.Step() vx := float32(actions.Axis("move_x")) * 140 if actions.JustPressed("jump") { startJump() } if actions.JustReleased("jump") { cutJumpShort() } movePlayer(vx, dt) }, Draw: func(alpha float64) { frame.Set(alpha) }, } ``` - **Tap latching**: a brief tap that both starts and ends between two fixed steps is latched so `Pressed` and `JustPressed` still register for one step, followed by `JustReleased` on the next step. - **`Axis(name)`**: returns `-1` when only the negative action is pressed, `+1` when only the positive action is pressed, and `0` when neither or both are pressed. For an unbound axis name, it falls back to `1` if an action of that name is pressed, else `0`. - **`Reset()`**: clears active touches, held buttons, held keys, the last controller state read, pending latches, relative mouse motion and the current snapshot, while keeping all bindings and any pointer lock, so mouselook survives a scene change. A controller button held across `Reset` stays inactive until it is released, as a held mouse button does. Call it on focus loss, backgrounding, or scene changes so inputs never stick. ## Mouselook through pointer lock For a first-person camera, bind pointer axes to relative mouse motion, lock the pointer from a press on the game view, and read each step's motion with `Delta`: ```go var gameRef core.Ref actions.BindPointerAxis("yaw", input.PointerX, input.PointerAxisOptions{Sensitivity: 0.003}) actions.BindPointerAxis("pitch", input.PointerY, input.PointerAxisOptions{Sensitivity: 0.003, Invert: true}) view := core.View{ Ref: &gameRef, OnPress: func(core.PressEvent) { actions.LockPointer(cx, &gameRef) }, } actions.Attach(&view) // In Loop.Update, after actions.Step(): camera.Yaw += actions.Delta("yaw") camera.Pitch += actions.Delta("pitch") ``` - `PointerX` reads motion to the right and `PointerY` motion down, in the units the view's `OnPointerDelta` reports. `Sensitivity` scales them (1 when zero) and `Invert` negates them. - `Delta(name)` returns the scaled motion heard since the previous `Step`, without a clamp, so a fast flick turns the camera further than a slow one. `PointerDelta()` returns the raw `(dx, dy)` of the step. `Axis(name)` adds the scaled motion to any other axis bound to `name` and clamps the sum to `[-1, 1]`, which suits steering with a small `Sensitivity`. - The view hears motion only while it holds the lock: `Attach` forwards its `OnPointerDelta` to `actions.OnPointerDelta`. - `LockPointer(cx, &ref)` returns `false` and does nothing when `cx.Env().CanLockPointer()` is false or the view has been removed. Call it from every press, since browsers grant the lock only during a user gesture; locking again replaces the previous lock. Linux on Wayland needs a compositor with pointer constraints and relative motion. - `UnlockPointer()` releases the lock, and the platform shows the pointer again where it was. Motion heard before the release still reaches the next step. `Reset()` keeps the lock. - Escape, the window losing focus and hiding or removing the view also release the lock, but NSGo does not report that to the app. `PointerLockRequested()` therefore reports only whether `actions` holds a request that `UnlockPointer` has not released, not whether the platform still holds the lock, so do not use it to decide whether to lock again or to show a resume prompt. The next press locks again. Pointer axes are saved and loaded with the other bindings. ## Saving and loading bindings Persist remapped bindings, including controller buttons and stick axes, in `core.Storage` as JSON with `Save` and `Load`: ```go // Save current action and axis bindings if err := actions.Save(cx.Storage(), "controls.v1"); err != nil { // Handles *core.StorageFullError log.Println("save controls:", err) } // Restore on startup (leaves defaults untouched when key is absent) found, err := actions.Load(cx.Storage(), "controls.v1") if err != nil { log.Println("corrupt saved controls, keeping defaults:", err) } _ = found ``` When `key` is absent, `Load` returns `(false, nil)` and leaves existing default bindings intact. If the stored JSON is invalid, has a field `Load` does not know or uses an unknown format, `Load` leaves bindings untouched and returns `(false, err)`. --- Source: https://game.nsgo.dev/docs/inventory/ # inventory `game/inventory` holds gameplay items: item definitions in versioned YAML, slot-based containers of stacks, typed equipment slots, and snapshots that round-trip through [`game/save`](https://game.nsgo.dev/docs/save/). ```go import "github.com/nsgo-dev/game/pkg/inventory" ``` ## Item definitions A game's items live in one YAML file. Every definition has an `id`; the other fields are optional: ```yaml version: 1 items: - id: potion name: items.potion.name description: items.potion.description icon: asset:icons/potion.png maxStack: 20 tags: [consumable, healing] stats: heal: 25 price: 12.5 - id: iron-helm name: items.iron-helm.name equip: head stats: armor: 3 - id: gold-ring equip: ring ``` | Field | Meaning | | --- | --- | | `id` | Unique ID that stacks and saves refer to; no whitespace or control characters. | | `name`, `description` | Display text or [l10n](https://game.nsgo.dev/docs/l10n/) keys. | | `icon` | Asset URI of the item's icon. | | `maxStack` | How many fit in one slot, from 1 to 2^30; omitted means 1. | | `equip` | The equipment kind the item fits, such as `head` or `ring`; omitted means it cannot be equipped. | | `tags` | Unique free-form labels; `ItemDef.HasTag` checks one. | | `stats` | Finite numbers such as damage, armor, weight or price. | `inventory.Parse(data)` returns a `*Catalog`. It refuses a missing or unsupported `version`, unknown fields, duplicate IDs or tags, invalid stack sizes, non-finite stats and trailing YAML documents. `Catalog.Encode` writes deterministic 2-space YAML (definitions in file order, stat names sorted) that `Parse` reads back unchanged, so an editor or tool can rewrite the file without noise in review. `inventory.NewCatalog(defs...)` builds a catalog in code with the same checks. A catalog is immutable: `Item(id)` and `Items()` return copies. ## Containers A `Container` is a fixed number of slots; each slot is empty or holds one `Stack{Item, Count}` no larger than the item's `maxStack`. ```go cat, err := inventory.Parse(itemsYAML) bag, err := inventory.NewContainer(cat, 24) left, err := bag.Add("potion", 30) // tops up potion stacks, then fills empty slots; left did not fit err = bag.AddAll("iron-helm", 1) // everything or nothing: ErrFull when it does not fit err = bag.Remove("potion", 5) // from the last slot holding potions backwards; ErrNotEnough otherwise n := bag.Count("potion") room := bag.Room("potion") ``` Moving items follows the rules players expect from a grid inventory: | Call | Behavior | | --- | --- | | `Move(from, to)` / `MoveTo(from, dst, to)` | Into an empty slot the stack moves; onto the same item as many as fit merge and the rest stay; onto a different item the stacks swap. | | `Split(from, to, n)` / `SplitTo(from, dst, to, n)` | Moves `n` items into an empty slot or onto the same item with room for all `n`; `ErrSlotOccupied` otherwise. | | `Transfer(from, dst)` | Quick-moves a stack into another container the way `Add` does; what does not fit stays. | | `RemoveAt(slot, n)` | Takes `n` items out of one slot and returns them. | `dst` may be another container (a chest, a shop) built from the same catalog; containers from different catalogs return `ErrCatalogMismatch`. Every call that returns an error leaves both containers unchanged. ## Equipment `Equipment` is a set of named slots, each accepting one kind. Several slots may share a kind: ```go gear, err := inventory.NewEquipment(cat, inventory.EquipSlot{Name: "head", Kind: "head"}, inventory.EquipSlot{Name: "ring-left", Kind: "ring"}, inventory.EquipSlot{Name: "ring-right", Kind: "ring"}, ) err = gear.Equip("head", bag, slot) // takes one item from bag[slot] err = gear.Unequip("head", bag) item, ok := gear.Equipped("head") ``` `Equip` checks that the item's `equip` matches the slot's kind (`ErrNotEquippable` otherwise) and takes one item from the container slot. An item already equipped goes back to the container: into the same slot when taking the item emptied it, otherwise wherever `AddAll` would put it. When the container has no room for it, `Equip` returns `ErrFull` and nothing changes; `Unequip` does the same. ## Saving `Container.Snapshot` and `Equipment.Snapshot` return plain JSON-tagged values listing only the occupied slots, in slot order. Store them in your save data with a `save.Store`, and `Restore` them into a container or equipment built the same way: ```go type Progress struct { Level int `json:"level"` Bag inventory.ContainerState `json:"bag"` Gear inventory.EquipmentState `json:"gear"` } err := store.Save("slot1", Progress{Level: 4, Bag: bag.Snapshot(), Gear: gear.Snapshot()}) var p Progress if err := store.Load("slot1", &p); err != nil { return err } if err := bag.Restore(p.Bag); err != nil { return err } if err := gear.Restore(p.Gear); err != nil { return err } ``` The saved JSON is deterministic: ```json {"level":4,"bag":{"slots":[{"slot":0,"item":"potion","count":20},{"slot":1,"item":"arrow","count":40}]},"gear":{"slots":[{"slot":"head","item":"iron-helm"}]}} ``` `Restore` validates the whole snapshot before replacing anything: an unknown item, a count above the item's `maxStack`, an out-of-range or repeated slot, or an item in an equipment slot of the wrong kind returns an error and leaves the container or equipment as it was. When an update renames or removes items, migrate the save with a `save.Migration` before restoring it. ## Errors | Error | Meaning | | --- | --- | | `ErrUnknownItem` | The catalog does not define the item. | | `ErrInvalidCount` | A count is not positive, or larger than the stack or the item's `maxStack`. | | `ErrSlotOutOfRange` | A container slot index is outside `[0, Len)`. | | `ErrEmptySlot` | The slot holds nothing. | | `ErrSlotOccupied` | The destination holds a different item, or lacks room for a split. | | `ErrFull` | The container has no room for all of the items. | | `ErrNotEnough` | The container holds fewer of the item than asked. | | `ErrCatalogMismatch` | The containers or equipment use different catalogs. | | `ErrUnknownEquipSlot` | The equipment has no slot with that name. | | `ErrNotEquippable` | The item's kind does not match the equipment slot. | Containers and equipment are deterministic and hold no global state, so the same code runs on a headless [server](https://game.nsgo.dev/docs/server/). They are not safe for concurrent use. --- Source: https://game.nsgo.dev/docs/l10n/ # l10n `game/l10n` provides game localization built on NSGo's `core` package and the Go standard library: versioned YAML and JSON string tables with BCP-47 fallback and CLDR plurals, script-aware `FontSet[F]`, RTL visual reordering and HUD mirroring, and per-language asset catalogs with selective group reloads. ```go import "github.com/nsgo-dev/game/pkg/l10n" ``` ## String tables, interpolation, and CLDR plurals Load per-locale versioned YAML string tables with `Catalog.LoadYAML` (or flat, nested, or CLDR plural JSON tables with `Catalog.LoadJSON`) into a `Catalog` with a fallback locale, then wrap it in a reactive `Localizer` bound to a `*core.Scope`: ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/l10n.v1.json version: 1 locale: en strings: hud.score: 'Score: {score}' menu.play: Play plurals: coins: zero: No coins one: '{count} coin' other: '{count} coins' ``` | Field | Meaning | | --- | --- | | `version` | Required; must be `1` (`StringTableVersion`). | | `locale` | Required; normalized BCP-47 locale tag (such as `en` or `zh-Hans`). | | `strings` | Optional map of message key to localized string template. | | `plurals` | Optional map of message key to CLDR plural categories (`zero`, `one`, `two`, `few`, `many`, `other`). | ```go cat := l10n.NewCatalog("en") _ = cat.LoadYAML(enYAML) _ = cat.LoadYAML(zhHansYAML) loc := l10n.NewLocalizer(cx, cat) loc.SetLocale("zh-Hans") // or omit to follow the system locale title := loc.T("menu.play") score := loc.T("hud.score", l10n.Param("score", 420)) coins := loc.Plural("coins", 3) _, _, _ = title, score, coins ``` YAML decoding is strict: unknown fields, invalid plural categories, duplicate keys, keys defined in both `strings` and `plurals`, empty keys or plural maps, null values, trailing YAML documents, YAML anchors/aliases/merge keys, missing or unsupported versions (or non-decimal forms like `0x1`), and non-canonical locales (such as `zh_hans` instead of `zh-Hans`) are refused without modifying the catalog. `EncodeYAML` and `Catalog.MarshalYAML` emit deterministic 2-space YAML prefixed with `# yaml-language-server: $schema=https://game.nsgo.dev/schemas/l10n.v1.json` (`SchemaComment`) and sorted keys, so `EncodeYAML(ParseYAML(b)) == b` byte for byte. `ParseYAML`, `ValidateStringTable`, `ApplyStringTable`, and `Catalog.StringTable` operate directly on `*StringTable` values for tooling such as the editor's Localization panel. Existing JSON string tables continue to load with `Catalog.LoadJSON`: ```go cat := l10n.NewCatalog("en") _ = cat.LoadJSON("en", []byte(`{ "menu": {"play": "Play"}, "hud": {"score": "Score: {score}"}, "coins": {"zero": "No coins", "one": "{count} coin", "other": "{count} coins"} }`)) _ = cat.LoadJSON("zh-Hans", []byte(`{ "menu": {"play": "开始游戏"}, "hud": {"score": "得分:{score}"}, "coins": {"other": "{count} 枚金币"} }`)) ``` Lookups walk the normalized BCP-47 fallback chain (for example `zh-Hans-CN` -> `zh-Hans` -> `zh` -> fallback locale) and return the key itself if missing everywhere. You can also populate entries programmatically via `cat.Set` and `cat.SetPlural`. ## Script-aware `FontSet[F]` Pair mixed-script text with per-script or per-locale fonts (any font type `F`, such as `*text.BitmapFont` or `core.Font`): ```go fonts := l10n.NewFontSet(latinFont) fonts.SetScript(l10n.ScriptCJK, cjkFont) fonts.SetScript(l10n.ScriptArabic, arabicFont) fonts.SetLocale("ja", jpFont) // Split mixed strings into contiguous runs, each paired with its resolved font: runs := fonts.RunsForText(loc.Locale(), "Score: 120 得分") for _, run := range runs { drawRun(run.Text, run.Font) } ``` Inspect scripts directly with `RuneScript`, `DetectScript`, `SegmentByScript`, and `LocaleScript`. ## RTL visual ordering and layout mirroring Query text direction from a locale (`LocaleDirection`), scope (`EnvDirection`), or string (`TextDirection`). For custom canvas text renderers that draw glyphs left-to-right, convert logical strings to visual order with `VisualOrder` (or `loc.Visual(s)`): ```go dir := loc.Direction() visual := loc.Visual(loc.T("hud.greeting")) aligned := l10n.LayoutAlignment("start", dir) // "left" in LTR, "right" in RTL x := l10n.MirrorX(16, iconW, screenW, dir) _, _, _ = visual, aligned, x ``` ## Per-language asset catalogs Manage localized voiceovers, textures, or title banners with `AssetCatalog`, discovered automatically from an `io/fs.FS` (`locales//`, `..`, or `_.`) or loaded from a YAML asset manifest: ```go assets, err := l10n.DiscoverFS(embedFS, "en") if err != nil { return err } assets.RegisterGroup("voice", "voice/intro.wav", "voice/boss.wav") // Reload only asset groups whose resolved paths actually change on language switch: stop := assets.OnReload(func(groups []string, locale string) { reloadAssetGroups(groups, locale) }) defer stop() assets.SetLocale("ja") resolved, ok := assets.Resolve("voice/intro.wav", assets.Locale()) _, _ = resolved, ok // Audit missing variants in tests or CI: for _, rep := range assets.CheckMissing("ja", "zh-Hans", "ar") { if !rep.Complete() { log.Printf("%s missing %v (%.0f%%)", rep.Locale, rep.Missing, rep.Coverage*100) } } ``` Use `assets.WatchLocale(cx, localeSignal, reloadFn)` to connect locale changes directly to a reactive `core.Signal[string]`. ### Asset manifests An asset manifest is a versioned YAML file that lists each logical asset's per-locale paths and the groups to reload on a language switch: ```yaml version: 1 base_locale: en assets: voice/intro.wav: en: locales/en/voice/intro.wav ja: locales/ja/voice/intro.wav zh-Hans: locales/zh-Hans/voice/intro.wav groups: voice: - voice/intro.wav ``` | Field | Meaning | | --- | --- | | `version` | Required; must be `1`. | | `base_locale` | Optional fallback locale; replaces the catalog's base locale when set. | | `assets` | Logical asset name to a map of locale to path. Each asset has at least one variant and no empty path. | | `groups` | Group name to the asset names it reloads, without duplicates. A group may name assets listed elsewhere, such as ones found by `DiscoverFS`. | Load one into a catalog with `LoadAssetManifestYAML`, which merges it over what the catalog already holds, and write a catalog back with `MarshalAssetManifestYAML`: ```go if err := assets.LoadAssetManifestYAML(data); err != nil { return err } out, err := assets.MarshalAssetManifestYAML() ``` Decoding is strict: an unknown field, a duplicate key, a second YAML document, a missing or unsupported version or one not written as `1` (such as `1.0` or `0x1`), YAML anchors, aliases and `<<` merge keys, an unclean asset name such as `./ui/a.png`, or a locale that is not a normalized BCP-47 tag such as `zh_hans` (write `zh-Hans`) is refused with an error that names it, and nothing is merged. Output is deterministic: fields in schema order, keys sorted, group members sorted and no timestamps, so a manifest that was saved this way loads and saves back byte for byte. Saving writes this canonical form rather than the input's text, so the first save of a hand-written manifest drops comments and rewrites flow style, quoting, ordering and empty `assets` or `groups` entries; every save after that leaves the file unchanged. `ParseAssetManifest`, `ValidateAssetManifest`, `EncodeAssetManifest`, `ApplyAssetManifest` and `AssetCatalog.AssetManifest` work on the `AssetManifest` value directly for tools that edit manifests. --- Source: https://game.nsgo.dev/docs/leaderboard-selfhost/ # leaderboard/selfhost ```go import "github.com/nsgo-dev/game/pkg/leaderboard/selfhost" ``` `leaderboard/selfhost` is a self-hostable leaderboard service for games that run on several platforms or on platforms without a game service (the web, Windows, Linux). Where [`leaderboard`](https://game.nsgo.dev/docs/leaderboard/) shows Game Center's and Play Games' own boards, this service keeps one board for every platform, keyed by the account the [account service](https://game.nsgo.dev/docs/accounts/) signs players in to, so a score from a browser and a score from a phone land on the same board. It is server-side code. It needs only the standard library, the YAML package and `accounts/token`, so it links none of the account service's password hashing or database drivers. | Package | What it holds | | --- | --- | | `leaderboard/selfhost` | `Service`, `Config`, the `Store` interface with `MemoryStore` and `FileStore`, `ProofSigner` and the HTTP `Handler` | | `leaderboard/selfhost/cmd/leaderboardd` | A standalone HTTP server with its scores in a directory | ## Declaring boards The service reads its boards from a versioned YAML file: ```yaml version: 1 proofTTL: 10m boards: - name: high-score order: descending reset: allTime - name: weekly-sprint order: ascending reset: weekly weekStart: monday keep: 4 validation: signed min: 1 max: 3600000 serverKeys: - id: 2317febd373fcbcd key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg= ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `proofTTL` | How old a game server's score proof may be, from `1s` to `24h`; `10m` when absent | | `boards` | The boards, in the order the service lists them | | `name` | The board's key in URLs and in the data directory: `a-z`, `0-9`, `.`, `_` and `-`, up to 64 characters, starting with a letter or digit | | `order` | `descending` ranks the highest score first (points), `ascending` the lowest (times) | | `reset` | `allTime`, `daily` (midnight UTC) or `weekly` (midnight UTC on `weekStart`) | | `weekStart` | The day a weekly board resets on, a lowercase English weekday; `monday` when absent | | `keep` | How many earlier periods of a daily or weekly board stay readable after a reset, 1 to 1000; 1 when absent | | `validation` | `signed` accepts a score only with a game server's proof; absent trusts the player's client | | `min`, `max` | The scores the board accepts; at most 2^53-1 either way, so every score survives a JSON number in JavaScript | | `serverKeys` | The Ed25519 public keys game servers sign proofs with; a `signed` board needs at least one | `ParseConfig` refuses unknown fields, duplicate keys, other versions and a second YAML document. Optional fields keep what the file says, and `Config.Marshal` writes the fields in the order above, so a file in that form parses and marshals back byte for byte. ## Ranking A board ranks each account's best score in its current period. A score only counts when it beats the account's best, by the board's order; an equal score keeps the earlier one. Equal scores rank by who reached them first, then by account ID, so every entry has its own rank. Periods are in UTC. A daily or weekly board starts a new, empty period at its reset, and the period before stays readable, with as many earlier ones as `keep` says. Each period has an ID: `all` for an all-time board, otherwise the UTC date it starts on, such as `2026-11-23`. A query names its period as `current` (the default), `previous`, or an earlier period's ID. ```go svc, err := selfhost.New(ctx, cfg, selfhost.Options{ Store: store, // selfhost.OpenFileStore("scores", selfhost.FileStoreOptions{}) Tokens: verifier, // a token.Verifier for the account service's key set Logger: slog.Default(), }) res, err := svc.Submit(ctx, selfhost.Submission{Board: "high-score", Account: claims.Subject, Score: 4200}) // res.Entry.Rank, res.Improved, res.Period.ID page, err := svc.Top(ctx, "high-score", "current", 0, 25) // ranks 1-25 near, err := svc.Around(ctx, "weekly-sprint", "previous", account, 5) // 5 above and 5 below pals, err := svc.Friends(ctx, "high-score", "", friendIDs) // these accounts, ranked ``` | Method | What it does | | --- | --- | | `Submit` | Records a score in the board's current period; `Result.Improved` reports whether it became the account's best | | `Top` | Up to `limit` entries (at most 100) from rank `offset+1` | | `Around` | The account's entry with up to `radius` entries (at most 50) each side, shifted at either end so the window keeps its size | | `Friends` | The entries of up to 200 accounts the game supplies (a platform friend list, its own social graph), each with its rank on the whole board | | `Rank` | One account's entry | | `Boards` | Every board with its current period and the earlier periods still readable | Errors are `ErrUnknownBoard`, `ErrUnknownPeriod` (no such period, or no longer kept), `ErrNotRanked`, `ErrInvalidAccount`, `ErrScoreOutOfRange`, `ErrProofRequired`, `ErrInvalidProof`, `ErrProofExpired` and `ErrInvalidQuery`. Each period is an order-statistic skip list in memory, so every query costs O(log n) plus the entries it returns. On a board of a million accounts the benchmarks take about 7 µs for the top 100, 60 µs for 100 entries deep in the board, 40 µs around an account and 10 µs to submit (`go tool nsgo test ./leaderboard/selfhost -run '^$' -bench .`); a benchmark fails when a query takes more than 50 ms, and CI runs the query benchmarks on every pull request. ## Server-validated scores A client can send any score it likes. A board with `validation: signed` accepts a score only with a proof from the game server: after the server decides a match or checks a replay, it signs the board, the account and the score, and hands the proof to that player's client, which submits it beside the score. ```go key, err := token.ParsePrivateKey(pemData) // from leaderboardd genkey prover, err := selfhost.NewProofSigner(key) proof, err := prover.Sign("weekly-sprint", claims.Subject, result.TimeMillis) // send proof to the player with the match result ``` A proof is `v1...`, an Ed25519 signature over the board, account, score and time. The service refuses a missing proof (`ErrProofRequired`), one signed by a key not in `serverKeys`, for another board, account or score, or issued in the future (`ErrInvalidProof`), and one older than `proofTTL` or, on a daily or weekly board, issued before the current period began (`ErrProofExpired`), so a score signed before a reset does not count after it. `Options.Leeway` allows for clock skew between the machines. Because a proof names the account, a player cannot submit someone else's. ## HTTP `Service.Handler` serves the service as JSON. Every request carries the player's account token as `Authorization: Bearer `; the handler verifies it offline with `Options.Tokens`, and its subject is the account a score is submitted for, so a player can only submit their own scores. | Request | Response | | --- | --- | | `GET /v1/boards` | `{"boards": [{"name", "order", "reset", "validation", "current", "previous"}]}` | | `POST /v1/boards/{board}/scores` `{"score", "proof"}` | `{"period", "entry", "total", "improved"}` | | `GET /v1/boards/{board}/top?period=&offset=&limit=` | a page; `limit` 25 when absent | | `GET /v1/boards/{board}/around?period=&radius=` | a page around the token's account; `radius` 5 when absent | | `POST /v1/boards/{board}/friends?period=` `{"accounts": [id]}` | a page of those accounts | A page is `{"board", "period", "total", "entries"}`, a period `{"id", "start", "end"}` (no `start` or `end` for an all-time board) and an entry `{"rank", "account", "score", "achieved"}`. Errors are `{"error": code}`: `invalid_token` 401; `proof_required`, `invalid_proof` and `proof_expired` 403; `unknown_board`, `unknown_period` and `not_ranked` 404; `bad_request`, `invalid_account` and `score_out_of_range` 400; `request_too_large` 413; `unavailable` 503; `internal` 500. Entries carry account IDs; a game that shows names looks them up in its own profiles. Put the handler behind TLS and a rate limiter. ## Storage The service keeps its records in a `Store`. `NewMemoryStore` is for tests. `OpenFileStore` keeps one JSON Lines file per board period at `//.jsonl`, a line per new best score: ```json {"account":"3f9a...","score":4200,"achieved":"2026-11-24T09:15:02.5Z"} ``` `New` loads the files. It cuts off a last line a crash left half written, rewrites a file whose lines are mostly superseded scores with one line per account, and deletes the periods that are older than the ones a board keeps; a reset deletes them as it happens. A failed write is taken back, so the file never holds a score the client was told was lost. `New` deletes only what it can place: scores of a board removed from the configuration, and of periods stored under a board's earlier `reset` or `weekStart`, stay on disk, are not served, and are logged as a warning. A period later than the current one, as a machine whose clock is behind at boot sees it, is kept and served once the clock reaches it. `FileStoreOptions.Sync` flushes every write to the disk, for a machine that may lose power. A `Store` of your own implements `Load`, `Save` and `Drop`. ## leaderboardd ```sh leaderboardd init -config leaderboards.yaml leaderboardd genkey -key server.pem leaderboardd serve -config leaderboards.yaml -keyset keys.yaml -data scores -addr :8081 ``` `init` writes a configuration with one all-time `high-score` board to edit. `genkey` writes a game server signing key and prints the `serverKeys` entry to paste into the configuration. `serve` verifies player tokens with the account service's key set file (`accountsd genkey` writes it), keeps scores under `-data`, and stops on SIGINT or SIGTERM. `-sync` flushes every score to the disk before acknowledging it, for a machine that may lose power. --- Source: https://game.nsgo.dev/docs/leaderboard/ # leaderboard ```go import "github.com/nsgo-dev/game/pkg/leaderboard" ``` `leaderboard` submits scores to and shows the platform's own leaderboards: Game Center on iOS, iPadOS, tvOS and macOS, and Play Games Services on Android. It is a thin layer over NSGo's [`gameservices`](https://github.com/nsgo-dev/nsgo/tree/main/gameservices) package that lets a game name its boards once in a YAML file instead of passing platform IDs around its code. ## Declaring boards A catalog maps each board's name in the game to its ID in every game service it is registered with: ```yaml version: 1 leaderboards: - name: high-score gameCenter: com.example.game.high_score playGames: CgkIxxxxxxxxxxEAIQAQ - name: fastest-run gameCenter: com.example.game.fastest_run ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `leaderboards` | The boards, in the order the game lists them | | `name` | The game's own key for the board; unique, no control characters or surrounding whitespace | | `gameCenter` | The leaderboard ID registered in App Store Connect; no two boards share one | | `playGames` | The leaderboard ID the Google Play Console generated; no two boards share one | A board needs at least one ID, and an ID is at most 100 ASCII letters, digits, `.`, `_` or `-`. Sort order, score format and reset period are set in App Store Connect and the Play Console, not in the catalog. `Parse` refuses unknown fields, duplicate keys, other versions and a second YAML document. `Catalog.Encode` writes the fields in schema order and leaves out absent IDs, so a file `Encode` wrote parses and encodes back byte for byte. ## Submitting and showing ```go //go:embed leaderboards.yaml var leaderboardsYAML []byte catalog, err := leaderboard.Parse(leaderboardsYAML) boards, err := leaderboard.New(cx, catalog) boards.SignIn(nil) // at launch; the platform may show its own sign-in // When a run ends: boards.Submit("high-score", int64(score), func(err error) { if err != nil { status.Set("Score not submitted") } }) // From a button: if err := boards.Show("high-score"); err != nil { ... } ``` - `SignIn` signs the local player in and keeps the result in a signal: `Player` and `SignedIn` update views that read them. - `Submit` sends a score for the signed-in player. The platform keeps each player's best by the board's own sort order, so a game can submit every finished run. - `Show` opens the platform's leaderboard UI. - `Scores` loads ranked rows for a game that draws its own board. `Query` chooses `Global` or `Friends`, `AllTime`, `Week` or `Today`, and a limit (25 by default, at most 100). Every callback runs on the engine goroutine after the call that started it has returned, so it can set signals directly. ## Platforms without a game service `Provider` names the service the game runs against (`ProviderGameCenter`, `ProviderPlayGames` or `ProviderNone`). `Available` reports whether that service can be used here, and `Supports(name)` whether a board can be submitted to and shown; both read the environment reactively, so a view can hide its leaderboard button with them. | Error | When | | --- | --- | | `ErrUnknownLeaderboard` | The name is not in the catalog. Reported on every platform, so a misspelt name shows up on a desktop too | | `ErrUnsupported` | No game service here: Windows, Linux, the web, watchOS and mini programs | | `ErrNoPlatformID` | The board has no ID for this platform's service | | `ErrUnauthenticated` | Nobody is signed in; `SignedIn` turns false | | `ErrCancelled` | The player dismissed the sign-in | | `ErrUnavailable` | The service could not be reached or is not enabled | `Submit`, `Show` and `Scores` check the first three before reaching the platform. A game that needs one board across platforms, or a board on platforms without a game service, runs the [self-hosted leaderboard service](https://game.nsgo.dev/docs/leaderboard-selfhost/) instead. ## Testing nsgotest gives every test app its own fake game service: ```go app := nsgotest.Start(t, root, nsgotest.Environment(core.Environment{CanUseGameServices: true, OS: core.OSIOS})) app.SetGameServicesPlayer(leaderboard.Player{ID: "p1", DisplayName: "Ada"}) boards.SignIn(nil) app.Settle() boards.Submit("high-score", 4200, nil) app.Settle() app.GameServicesSubmittedScores() // [{LeaderboardID: "com.example.game.high_score", Score: 4200, ...}] app.GameServicesShownLeaderboards() // IDs passed to Show ``` Set `OS` to `core.OSAndroid` to test the `playGames` IDs, and use `SeedLeaderboardScores`, `SetGameServicesFriends` and `SetGameServicesError` for `Scores` and failure paths. ## Example [Starburst](https://github.com/nsgo-dev/game/tree/main/examples/starburst) declares a `high-score` board in `leaderboards.yaml`, submits the score when a run ends, and shows a LEADERBOARD button on the game-over screen once the player is signed in, or a SIGN IN button that signs the player in and submits the run while signed out. --- Source: https://game.nsgo.dev/docs/library/ # Asset and Plugin Library `github.com/nsgo-dev/game/pkg/tooling/library` finds shared asset packs, editor plugin packs and templates in a library and installs them into a game project. A library is a text index anyone can add a pack to with a pull request; installing a pack writes its files into the project and records them, and the references they add, in `game.yaml`. `nsgo game library` runs it from the command line and the scene editor's library panel runs it from the editor. ## Finding and installing packs ```sh nsgo game library list nsgo game library list tiles nsgo game library -kind plugin list nsgo game library install dungeon-tiles nsgo game library remove dungeon-tiles ``` `list` prints the packs whose name, description or tags hold every word given, with the version the project in the working directory (or `-project`) has installed: ```text PACK KIND VERSION INSTALLED DESCRIPTION dungeon-tiles asset 1.0.0 - A 16x16 stone floor tile and brick wall tile with a TexturePacker atlas. ``` `install` fetches each pack named, checks it against the index and installs it into the project; `-dir` puts a pack's files in another directory of the project than the one its manifest names; installing the pack again later, to update it, keeps it in that directory unless `-dir` names another. `remove` takes an installed pack out again. The library is the shared one in this repository's [`library`](https://github.com/nsgo-dev/game/tree/main/library) directory unless `-index` names another: an https URL of an index file, an index file, or a directory holding `index.yaml`. ## What installing does Installing the sample asset pack into a project writes its files under `packs/dungeon-tiles` (the pack's `pack.yaml` included, so its license travels with its files) and adds this to `game.yaml`: ```yaml autoload: resources: - name: dungeon-tiles path: packs/dungeon-tiles/tiles.json packs: - name: dungeon-tiles kind: asset packVersion: 1.0.0 sha256: 69d89c016fc8eaf19a83ea7bf3f14800fc4b6fff1384cd4d9f2db29f6e5ab177 dir: packs/dungeon-tiles files: - pack.yaml - tiles.json - tiles.png resources: [dungeon-tiles] ``` The `packs` entry is the [project file](https://game.nsgo.dev/docs/project/)'s record of the install: the pack's version and digest, the directory and files it wrote, and the autoload `scenes` and `resources` and editor `plugins` it added. A plugin pack adds the editor plugins it names to `editor.plugins`, which turns them on in an editor built with them (see [Editor plugins](https://game.nsgo.dev/docs/editor/#editor-plugins-492)); a plugin the project already turned on stays the project's and is not recorded as the pack's. An install never overwrites a file the project already has, unless the pack wrote it or it holds what the pack would write, and never a file another pack wrote; it refuses an autoload scene or resource whose name the project already uses. It checks everything before it writes anything, and when a write fails it restores the files it had changed. A pack can only write where an asset belongs. The directory its files go to and every file it lists must stay inside the project and outside hidden directories (no path element may start with `.`, so a pack cannot write into `.github` or `.git`), with names every platform can hold: no control characters or any of `<>:"|?*`, no element ending in a dot or a space, no Windows device name such as `con` or `aux`, and no two files whose names differ only in case. A pack may not hold Go source or any other file the Go toolchain builds or reads (`.go`, `.s`, `.c`, `.h`, `.cc`, `.cpp`, `.m`, `.syso` and the like, `go.mod`, `go.sum`, `go.work`), so installing one never changes what compiles into the game; an editor plugin pack turns on plugins the editor is built with rather than shipping their code. `game.yaml` is then written in its canonical form, which keeps no comments, as the editor saves it. ## Updating and removing Installing a pack the project already has updates it, in the directory the installed release went to: the files the new release lacks are removed, the others replaced (a file may become a directory between releases, or a directory a file), and the autoload entries and plugins it added are replaced by the new release's, keeping their places in `game.yaml`. Installing the same release again changes nothing and writes nothing. Removing a pack removes the files it wrote, edited or not, the directories that leaves empty inside the pack's directory (and `packs` itself, for a pack in its default `packs/`), never a directory above it that the project may have had before, and the autoload entries and plugins it added, and unsets a main scene that was one of its scenes. `gameproject check` and `project.Check` report a file an installed pack wrote that is missing. ## In the editor `nsgo game editor -library ` shows a library panel beside the asset browser listing every pack in the library with its kind, version and description and the version the open project has installed. Install, Update and Remove do what the command does and then save `game.yaml`, so they are refused while the project has unsaved edits; save or undo them first. Installing writes files the undo history cannot take back, so it empties the history, as opening a project does. A pack from a library over https is fetched without blocking the editor; the panel's buttons wait until it arrives, and opening another project cancels the fetch. In Go, set `Editor.Library` to a `*library.Library` and call `Editor.InstallPack` and `Editor.RemovePack`. ## The index ```yaml version: 1 packs: - name: dungeon-tiles kind: asset packVersion: 1.0.0 description: A 16x16 stone floor tile and brick wall tile with a TexturePacker atlas. tags: [2d, tiles, dungeon, pixel-art] license: CC0-1.0 source: packs/dungeon-tiles sha256: 69d89c016fc8eaf19a83ea7bf3f14800fc4b6fff1384cd4d9f2db29f6e5ab177 ``` | Field | What it holds | | --- | --- | | `version` | The index schema version, `1`. | | `name` | The pack's name: 1 to 64 lower-case ASCII letters, digits and `-`, starting with a letter or digit; unique in the index. | | `kind` | `asset`, `plugin` or `template`. | | `packVersion` | The version of the pack the index offers. | | `description` | One line saying what the pack holds. | | `tags` | Lower-case words a search also matches. | | `license` | The license of the pack's files, as an SPDX expression such as `CC0-1.0` or `MIT OR Apache-2.0`. | | `source` | The pack's directory: a slash-separated path relative to the index that stays inside the library, or an https URL (plain http only to a loopback host). | | `sha256` | The pack's digest (below). | `library.ParseIndex` refuses unknown fields, other versions and duplicate names, and `EncodeIndex` writes the form `ParseIndex` reads back unchanged. A fetched pack whose manifest's name, kind or version differs from its entry, or whose digest differs from `sha256`, is refused. ## A pack A pack is a directory holding its manifest, `pack.yaml`, and the files the manifest lists: ```yaml version: 1 name: dungeon-tiles kind: asset packVersion: 1.0.0 description: A 16x16 stone floor tile and brick wall tile with a TexturePacker atlas. license: CC0-1.0 files: - tiles.json - tiles.png autoload: resources: - name: dungeon-tiles path: tiles.json ``` | Field | What it holds | | --- | --- | | `version` | The manifest schema version, `1`. | | `name`, `kind`, `packVersion`, `description`, `license` | As in the index, which repeats them. | | `into` | The project directory the pack's files go to; left out, `packs/`. | | `files` | The pack's files other than `pack.yaml`, as slash-separated paths inside its directory. A file not listed is not part of the pack. | | `autoload` | The `scenes` (`.yaml` or `.yml`) and `resources` among `files` that installing adds to `game.yaml`'s autoload section, each with the `name` it is autoloaded under. | | `plugins` | The editor plugins a plugin pack turns on; a plugin pack names at least one, and the other kinds none. | A pack's digest is the SHA-256 of the listing `sha256sum` prints for its files, `pack.yaml` included, named in byte order: one line per file of its SHA-256 in lower-case hexadecimal, two spaces and its path. `nsgo game library digest ` prints it. ## Adding a pack to the shared library 1. Add the pack's directory under `library/packs/` with its `pack.yaml` and files. Every file must be yours to share under the license the manifest names. 2. From the repository root, run `go run ./cmd/game library digest library/packs/` and add an entry with that `sha256` to `library/index.yaml`. 3. Open a pull request. The library's tests fetch every pack of the index, so a digest or a manifest that does not match its entry fails CI. A team can keep a library of its own anywhere it can serve files over https, or in a directory of its repository, and point `-index` at it. Plain http is accepted only for a loopback host, such as a local test server, for the index and for a pack's `source` alike, and every file is limited to 64 MiB. A server that does not connect within 30 seconds or answer within a minute, or a file that takes longer than 10 minutes, is given up on. ## In Go `library.Open(ctx, location)` reads an index and `Library.Fetch(ctx, name)` fetches and checks a pack; `Index.Search(kind, query)` finds packs. `library.Install(projectDir, pack, dir)` and `library.Remove(projectDir, name)` change a project directory. `PlanInstall` and `PlanRemove` work out the same change without writing, from an `fs.FS` and a `project.File`, and `Change.Apply` writes it. --- Source: https://game.nsgo.dev/docs/lights2d/ # lights2d `game/lights2d` adds 2D lighting to NSGo canvases: an ambient darkness layer, point and directional cone lights, exact 2D visibility-polygon shadows from occluders, and CPU tangent-space normal-mapped sprite shading. ```go import "github.com/nsgo-dev/game/pkg/lights2d" ``` ## Ambient layer, point lights, and spotlights Create a `Scene` with an `Ambient` color and a slice of `*Light`, then draw it over your 2D world inside `Canvas.Draw`: ```go torch := lights2d.NewLight(160, 120, 180, core.RGB(255, 196, 120)) torch.CastShadows = true flashlight := lights2d.NewLight(240, 140, 260, core.RGB(220, 235, 255)) flashlight.ConeAngle = 0 // radians: 0 = +X, pi/2 = +Y flashlight.ConeSpread = math.Pi / 3 flashlight.CastShadows = true lighting := &lights2d.Scene{ Ambient: core.RGBA(12, 16, 30, 0.85), Lights: []*lights2d.Light{torch, flashlight}, } // Inside Canvas.Draw, after drawing tiles and sprites: lighting.Draw(d, worldBounds) ``` - `NewLight(x, y, radius, color)` creates an enabled omnidirectional light with `Intensity: 1` and quadratic `Falloff: 2`. - Setting `ConeSpread` in `(0, 2*math.Pi)` turns a light into a directional spotlight with smoothstep angular falloff around `ConeAngle`. - Light glows default to additive `core.CompositeLighter` when `Scene.LightComposite` is unset (`0`). Assign a non-zero blend such as `core.CompositeScreen` for softer lights, or call `lighting.SetLightComposite(core.CompositeSourceOver)` for alpha-over glows (since `core.CompositeSourceOver` is the zero value). Query the active mode with `lighting.EffectiveLightComposite()`. - Query exact CPU illumination at any world coordinate with `light.AttenuationAt(x, y)` or `scene.EvaluateAt(x, y)`. ## Visibility-polygon shadow casters Populate `Scene.Occluders` from walls, pillars, or tile colliders using `RectOccluder`, `PolygonOccluder`, or `SegmentOccluder`: ```go lighting.Occluders = []lights2d.Occluder{ lights2d.RectOccluder(core.Bounds{Origin: core.Point{X: 200, Y: 90}, Size: core.Size{Width: 48, Height: 64}}), lights2d.SegmentOccluder(lights2d.Segment{ A: core.Point{X: 80, Y: 180}, B: core.Point{X: 160, Y: 180}, }), } ``` For a tilemap, a [`tileshape.View`](https://game.nsgo.dev/docs/tileshape/) merges solid cells and per-tile collision shapes into occluders that cast the same shadows with far fewer segments: assign `lighting.Occluders = view.Occluders()`, and again after the map changes. Set `Scene.DisableShadows` to skip occlusion for every light without touching each light's `CastShadows`, as a preset with shadows off does (`lights.DisableShadows = !preset.Shadows`, see [quality](https://game.nsgo.dev/docs/quality/)). `Draw`, `EvaluateAt`, `ShadeNormalMap` and `NormalSprite` all honor it, and toggling it re-shades a `NormalSprite`. When `light.CastShadows` is `true`, `Scene.Draw` clips that light against `VisibilityPolygon(origin, radius, occluders)`. You can also call the geometry helpers directly for stealth, line-of-sight, or fog-of-war checks: | Helper | Purpose | | --- | --- | | `VisibilityPolygon(origin, radius, occluders)` | Returns the ordered 2D polygon visible from `origin` within `radius`. | | `Visible(origin, target, occluders)` | Reports whether the segment from `origin` to `target` is unobstructed. | | `LineOfSight(&occluders)` | Returns `Visible` against the occluders as an `ai.LineOfSight`, so they block AI perception too ([ai](https://game.nsgo.dev/docs/ai/#perception)). | | `PointInPolygon(p, poly)` | Tests whether point `p` lies inside a visibility polygon. | ## Normal-mapped sprites Give 2D pixel art or painted sprites directional rim and bump highlights using a tangent-space normal map (`*image.NRGBA`): ```go knight := lights2d.NewNormalSprite(diffuseImg, normalMapImg) knight.X = 160 knight.Y = 120 knight.LightZ = 48 // virtual Z height of lights above the sprite plane // Inside Canvas.Draw: knight.Draw(d, lighting) ``` `NormalSprite` caches the CPU-shaded pixel buffer and only re-shades when the sprite position, `LightZ`, ambient color, or affecting lights/occluders change. Call `knight.Invalidate()` if you mutate `Diffuse` or `NormalMap` pixels in place, or use `ShadeNormalMap`, `ShadeNormalMapWithOccluders`, and `scene.ShadeNormalMap` directly when baking custom buffers. ## Authoring lights and occluders in scenes You can also declare `ambientColor`, `light2d` point/spot lights, and `occluder2d` rect/polygon/tilemap shadow casters directly in `*.scene.yaml` files and preview them live with interactive viewport handles in [`game/editor`](https://game.nsgo.dev/docs/editor/#built-in-2d-lighting-and-occluder-components-887). `sceneformat.Build` turns them into `BuiltScene.Lights2D`, which renders the same shadows in the editor preview and in the game. --- Source: https://game.nsgo.dev/docs/liveops/ # Live operations ```go import "github.com/nsgo-dev/game/pkg/liveops" ``` `liveops` holds provider-agnostic live operations primitives for NSGo games. It uses only Go's standard library, `github.com/nsgo-dev/game` and NSGo's public `core` and `cloud` APIs, and links no third-party crash, analytics, ad or payment SDKs. ## Scope decision ([#194](https://github.com/nsgo-dev/game/issues/194)) | Area | Status | Rationale | | --- | --- | --- | | **Crash reports** ([#195](https://github.com/nsgo-dev/game/issues/195)) | In scope | Provider-agnostic panic capture with a fixed-size step ring buffer, stack trace, metadata and optional state snapshot. | | **Analytics** ([#198](https://github.com/nsgo-dev/game/issues/198)) | In scope | Provider-agnostic, strictly consent-gated event API backed by `core.Storage`. Zero events are sent or buffered before explicit opt-in consent. | | **Cloud saves** ([#196](https://github.com/nsgo-dev/game/issues/196)) | In scope | Provider-agnostic `CloudSync` interface, `PlatformCloud` over NSGo's `cloud` package (iCloud on macOS/iOS, Google Play Games Saved Games on Android, in-memory store in `nsgotest`), `DirCloud` for Steam Auto-Cloud and other synced directories, `CloudClient` for the self-hosted [cloudsave](https://game.nsgo.dev/docs/cloudsave/) service ([#557](https://github.com/nsgo-dev/game/issues/557)), and `CloudSyncer` conflict resolution ([#539](https://github.com/nsgo-dev/game/issues/539)). | | **In-app purchases** ([#369](https://github.com/nsgo-dev/game/issues/369)) | In scope | `Purchases` over NSGo's purchase services: consumables credited into the save exactly once, unlocks and subscriptions from the store's entitlements, restore, Ask to Buy and an optional server check. | | **Ads** ([#199](https://github.com/nsgo-dev/game/issues/199)) | Out of scope | Ad networks (AdMob, AppLovin and similar) require proprietary native SDKs with heavy store-policy and privacy obligations. Keep them out of the core `game` module; games that need ads embed native SDK views directly via NSGo. | ## Crash reports `CrashReporter` keeps the most recent simulation steps in a pre-allocated ring buffer (`DefaultHistorySize` = 120, zero allocations in steady state) and guards `game.Loop` callbacks or arbitrary functions against panics. - `RecordStep(dt, summary)` and `RecordStepData(dt, summary, data)` append a `StepRecord` to the ring buffer and return its monotonic step number. - `WrapLoop(l)` returns a guarded `*game.Loop`; `GuardLoop(l)` wraps `l.Update` and `l.Draw` in place. When `Update` does not call `RecordStep` itself during a step, the guard records an `"update"` step automatically, including for the step that panicked. - `RunSafe(fn)` guards any callback and reports whether it panicked. - On panic, the reporter builds a JSON-marshalable `CrashReport` holding `Timestamp`, `Panic`, `Message`, `Stack` (`runtime/debug.Stack`), `Step`, chronological `LastSteps` (oldest to newest), optional `State` from `CaptureState`, and a copy of `Metadata`, then passes it to `Reporter`. - Set `Rethrow: true` when the process should still panic after `Reporter` finishes persisting or shipping the report. ```go reporter := liveops.NewCrashReporter(liveops.CrashOptions{ HistorySize: 120, Reporter: func(r liveops.CrashReport) { uploadOrSave(r) }, CaptureState: func() any { return world.Snapshot() }, Metadata: map[string]string{"version": appVersion, "scene": "level-1"}, Now: cx.Now, }) loop := reporter.WrapLoop(&game.Loop{ Update: func(dt time.Duration) { reporter.RecordStep(dt, "world.step") world.Step(dt) }, Draw: func(alpha float64) { world.Draw(alpha) }, }) loop.Run(cx) ``` ## Analytics `Analytics` gates every event on explicit opt-in consent (`ConsentGranted`) and ships no built-in telemetry backend. - Consent states are `ConsentUnknown` (default), `ConsentDenied` and `ConsentGranted`. - `NewAnalytics(store, key, provider)` persists the choice in `core.Storage` under `key` (`DefaultConsentKey` when empty) and fails closed to `ConsentUnknown` if the stored value is missing or unrecognized. `NewMemoryAnalytics(provider)` keeps consent in memory only. - `Track(name, props)` returns `false` and drops the event immediately whenever consent is `ConsentUnknown` or `ConsentDenied` — events are never sent and never buffered for retroactive replay. - When consent is `ConsentGranted`, `Track` defensively copies `props` and dispatches an `Event` to `AnalyticsProvider.Send`. - Calling `SetConsent(ConsentDenied)` immediately stops all subsequent `Track` and `Flush` calls. ```go analytics := liveops.NewAnalytics(cx.Storage(), "liveops.consent", myProvider) analytics.SetClock(cx.Now) // Dropped before explicit opt-in: analytics.Track("app_open", nil) // returns false, 0 events sent // After player opts in: _ = analytics.SetConsent(liveops.ConsentGranted) analytics.Track("level_complete", map[string]any{"level": 1}) ``` ## Cloud saves `CloudSync` defines the provider-agnostic slot interface (`Load`, `Save`, `Delete`, `List`, with sentinel errors `ErrSlotNotFound`, `ErrCloudUnavailable`, `ErrCloudConflict`, `ErrSlotTooLarge` and `ErrTooManySlots`). `ConditionalCloudSync` adds `SaveIf` and `DeleteIf`, which write only while the slot still holds the payload the caller read, identified by `PayloadHash`. Three built-in adapters implement `CloudSync` behind the same interface: | Adapter | Services / targets | Notes | | --- | --- | --- | | `PlatformCloud` | **iCloud** (macOS, iOS, iPadOS, tvOS), **Google Play Games Saved Games** (Android), isolated in-memory store (`nsgotest`) | Built on `github.com/nsgo-dev/nsgo/cloud`. Returns `ErrCloudUnavailable` on Windows, Linux, the web or when signed out / missing entitlements, and never silently drops writes. | | `DirCloud` | **Steam Auto-Cloud** and other directory-synced desktop stores (Windows, Linux, macOS) | `ConditionalCloudSync` keeping each slot as an atomically written `.json` file in a synced directory (such as `filepath.Join(cx.DataDir(), "cloud")`). | | `CloudClient` | Self-hosted [cloudsave](https://game.nsgo.dev/docs/cloudsave/) service ([#557](https://github.com/nsgo-dev/game/issues/557)) (every target, including the web) | `ConditionalCloudSync` over HTTPS signed in through the [account service](https://game.nsgo.dev/docs/accounts/), with size limits and version history (`Versions`, `LoadVersion`, `Restore`, `Purge`). | Games can also implement `CloudSync` over their own backend or an in-memory test double. ### Platform cloud saves: iCloud, Play Games and Steam Cloud ([#196](https://github.com/nsgo-dev/game/issues/196)) `PlatformCloud` stores each save slot as `.json` (default `DefaultCloudPrefix` = `"save."`, e.g. `save.main.json`) using NSGo's `cloud` file/snapshot API. The flat dot-separated name avoids path separators so both Apple iCloud ubiquity containers and Google Play Games `SnapshotsClient` accept it, while keeping save slots separate from other files in the container. ```go pc, err := liveops.NewPlatformCloud(cx, liveops.PlatformCloudOptions{}) if err != nil { return err } syncer, err := liveops.NewCloudSyncer(liveops.CloudSyncOptions{ Local: save.StorageBackend(cx.Storage(), "mygame"), Cloud: pc, State: cx.Storage(), Device: deviceID, Policy: liveops.PolicyKeepBoth, }) if err != nil { return err } // Re-sync when another device updates a save slot: pc.WatchChanges(func(ev liveops.CloudChange) { syncer.SyncAsync(cx, ctx, func(res liveops.SyncResult, err error) { /* update UI */ }) }) // Resolve native iCloud / Play Games file conflicts when the platform reports one: pc.OnConflict(func(c liveops.PlatformConflict) { chosen := c.Remote if c.LocalTime.After(c.RemoteTime) { chosen = c.Local } _ = c.Resolve(chosen) }) ``` - `CloudProviderFor(os)` and `pc.Provider()` report the target's built-in service (`CloudProviderICloud`, `CloudProviderPlayGames`, `CloudProviderNone`; `CloudProviderSteam` identifies Steam Auto-Cloud). `pc.Available()` reads `cx.Env().CanUseCloudStorage()` reactively so views update when iCloud or Play Games availability changes. - On real Apple and Android targets, NSGo's `cloud` delivers operation callbacks on `cx`'s engine goroutine via `cx.Post`, so run `PlatformCloud` syncs through `CloudSyncer.SyncAsync` (or call `PlatformCloud` off the engine goroutine) rather than blocking the engine goroutine with synchronous `Sync`. `SyncAsync`, `SyncSlotAsync` and `ResolveAsync` run cloud I/O on a worker goroutine while marshaling `Local`, `State`, `Summarize`, `Now` and `Ask` onto `cx`'s engine goroutine, serialize concurrent calls, and refuse to overwrite a local save made while a cloud read was in flight (`ErrConflictChanged`). - On macOS and iOS, declare iCloud entitlements in `nsgo.yaml` under `cloud:` (`kv_store` / `containers: [iCloud.com.example.myapp]`); Mac App Store builds require a provisioning profile carrying those entitlements, otherwise iCloud returns `ErrCloudUnavailable`. - If iCloud (`NSFileVersion`) or Google Play Games (`SnapshotsClient`) holds an unresolved native conflict for a slot, `PlatformCloud.Load` fails with an error wrapping `ErrCloudConflict`, `cloud.ErrConflict` and `*cloud.ConflictError`; `CloudSyncer` skips that slot while syncing other slots until `PlatformConflict.Resolve` (or a write) clears it. - On **Steam** (Windows, Linux, macOS), configure Steam Auto-Cloud to sync a directory under `cx.DataDir()`. Games that do not need `CloudSyncer`'s conflict envelopes can point Steam Auto-Cloud directly at `save.FileBackend(cx.DataDir())` (`*.json`); games that want the same `CloudSync` + `CloudSyncer` conflict-resolution flow across every platform pass `liveops.NewDirCloud(filepath.Join(cx.DataDir(), "cloud"))` as `Cloud`. `DirCloud` implements `ConditionalCloudSync` with atomic temp-file writes, directory sync and case-folding collision checks. - Under `nsgotest`, start apps with `nsgotest.CloudAvailable(true)` and drive cross-device updates, native conflicts and offline fallback with `app.SimulateCloudChange`, `app.SimulateCloudConflict` and `app.SetCloudAvailable`; `liveops/cloud_platform_test.go` and `liveops/cloud_dir_test.go` cover each. ### Resolving conflicts ([#539](https://github.com/nsgo-dev/game/issues/539)) `CloudSyncer` reconciles a device's `save.Backend` with a `CloudSync` and never silently loses progress when the same slot changed on two devices. ```go syncer, err := liveops.NewCloudSyncer(liveops.CloudSyncOptions{ Local: save.StorageBackend(cx.Storage(), "mygame"), Cloud: myCloud, State: cx.Storage(), Device: deviceID, // 1-64 ASCII letters, digits, '-' or '_' Policy: liveops.PolicyAsk, Ask: func(ctx context.Context, c liveops.Conflict) (liveops.Choice, error) { pending = append(pending, c) // shown by the game's conflict dialog return liveops.ChoiceDefer, nil }, Summarize: func(slot string, data []byte) string { return describeSave(data) }, // "Level 12, 3h 40m" }) if err != nil { return err } store := save.NewStore(syncer.Backend()) // stamps each local write with its time res, err := syncer.Sync(ctx) for _, r := range res.Conflicts() { log.Printf("%s: %s", r.Slot, r.Outcome) } // Later, when the player picks a copy in the dialog: r, err := syncer.Resolve(ctx, c, liveops.ChoiceLocal) // or ChoiceCloud, ChoiceBoth if errors.Is(err, liveops.ErrConflictChanged) { // A save or sync changed the slot while the dialog was open: sync again and ask about the new conflict. } ``` How a conflict is detected: - For each slot the syncer remembers the base: the content hash (`sha256:…`) and cloud revision both sides held after the last sync, kept as JSON text in `State` under `StateKey` (`DefaultSyncStateKey` when empty). - `Sync` visits every slot known locally, in the cloud or in the sync state, in name order. When only one side differs from the base, that side is copied to the other (`OutcomeUploaded`, `OutcomeDownloaded`, `OutcomeDeletedCloud`, `OutcomeDeletedLocal`). When both differ from the base and from each other, the slot is a conflict. A device that has never synced a slot and holds a different copy from the cloud is a conflict too, never an overwrite. - Before every cloud write the syncer reads the cloud copy again; if another device uploaded in between, the slot fails with `ErrCloudChanged`, nothing is written, and the next sync sees the new copy. When `Cloud` implements `ConditionalCloudSync`, as `CloudClient` and `DirCloud` do, the write itself is conditional on that copy, so an upload landing after the re-read fails the same way instead of being overwritten. - A slot that fails (a corrupt payload, an unsafe slot name, `Ask` returning an error) is skipped and its error joined into the result while the others still sync; `ErrCloudUnavailable` or a done context stops the sync. Each `Conflict` carries a `SaveVersion` for both sides: whether it exists (a side may have deleted the slot), its revision, hash, modified time, writing device, the game's `Summarize` text and the raw data. The policies: | Policy | Behaviour | | --- | --- | | `PolicyNewest` (default) | Keeps the copy with the later modified time and overwrites the other (`OutcomeKeptLocal` or `OutcomeKeptCloud`). When either time is unknown, such as a local copy written without `Backend()` (a recorded time counts only for the exact copy it was recorded with), or both are equal, it keeps both. When one side deleted the slot and the other changed it, it keeps the changed copy. | | `PolicyKeepBoth` | Keeps the cloud copy in the slot and moves the local copy to `.conflict-` (then `-2`, `-3`…) on both sides (`OutcomeKeptBoth`, `SlotResult.Fork`). When that name would exceed the 200-byte slot limit, the slot part is shortened and followed by `~` and 8 hex digits of its SHA-256. The fork and its sync state are written locally before anything is overwritten, so if the upload fails the next sync uploads the same fork rather than creating another. A deletion against a change keeps the change. | | `PolicyAsk` | Calls `Ask` with the conflict and applies its `Choice`: `ChoiceLocal`, `ChoiceCloud`, `ChoiceBoth` (as `PolicyKeepBoth`) or `ChoiceDefer`, which writes nothing and asks again on the next sync. An error from `Ask` leaves both copies untouched. | `Ask` runs inside the sync, on the app's thread, so it must not wait for the player. To ask through a dialog, keep the `Conflict`, return `ChoiceDefer`, show both summaries, and apply the answer with `Resolve(ctx, conflict, choice)`, as in the example above. `Resolve` reads both sides again and applies the choice only while they still hold the copies the player saw (the same existence, hash and cloud revision); otherwise it writes nothing and returns `ErrConflictChanged`. It works under every policy. Whenever a resolution replaces a copy, `SlotResult.Discarded` returns it so the game can show or archive it. When the replaced local copy is a valid save envelope and the cloud copy exists, the local backend also keeps it as its backup (`ReadBackup`); when the cloud copy is a deletion, or the local copy is not a save envelope, `Discarded` is the only copy left. Cloud payloads are JSON text with a fixed key order: `format` (`CloudSaveFormat`), `version` (`CloudSaveVersion`), `revision`, `hash`, `modified` (RFC 3339, UTC), `device` and `data`, a string holding the save as written (or `data_base64` for data that is not UTF-8). `DecodeCloudSave` refuses unknown fields, newer versions, trailing data and a hash that does not match the data with `ErrCorruptCloudSave`; decoding a payload `EncodeCloudSave` wrote and encoding it again gives back the same bytes. A cloud payload without the format marker, written by a game that used `CloudSync` directly, is read as revision 0 and upgraded on the next upload. Cloud slot names are checked with `save.ValidateSlot` before they reach the local backend. `Backend()` exposes the local backend through `Unwrap`, so a settings store built on it (`save.NewDefaultSettingsStore(syncer.Backend())`) keeps settings under the local backend's own settings key, and settings are never synced as a slot. A `CloudSyncer` is not safe for concurrent synchronous use; call `Sync`, `SyncSlot` and `Resolve` where the app's code runs, as `core.Storage` requires, or use `SyncAsync`, `SyncSlotAsync` and `ResolveAsync` to run cloud I/O off the engine goroutine while marshaling local storage and `Ask` back onto `cx` (required with `PlatformCloud` on Apple and Android devices, and recommended with `CloudClient`). With a plain `CloudSync`, which has no conditional write, an upload by another device that lands between the syncer's re-read and its own write can still be overwritten; the window is a single `Load` and `Save` apart. A `ConditionalCloudSync` closes it. ## In-app purchases `Purchases` sells a game's products over NSGo's purchase services (`cx.Purchase`, `cx.OnPurchaseUpdate`, `cx.CurrentEntitlements`, `cx.SyncPurchases`). It sells where `cx.Env().CanPurchase()` is true, which in NSGo v0.3.0 is the App Store on macOS, iOS and tvOS in a build whose `nsgo.yaml` sets `apple.purchases: true`; elsewhere `Buy` fails with `core.PurchasesUnavailable` and `Available` reports false. - A consumable is credited exactly once. Keep a `Ledger` inside the save, beside the state `Credit` changes: `Purchases` calls `Credit`, records the transaction ID in the ledger, calls `Save` and only then finishes the transaction. A kill before the save loses both the credit and its record, and the store hands the transaction to the app again at the next launch; a kill after the save finds the ID in the ledger and only finishes it. A failed `Save` leaves the transaction unfinished. - Non-consumables and subscriptions are owned, not credited: `Owned(product)` reads the store's entitlements, which `NewPurchases` loads at start and `Refresh` reloads, and checks a subscription's expiration date against `cx.WallTime()`. Read in a reactive computation, `Owned` and `Pending` update the view on purchases, refunds and restores; a subscription that expires while the app runs is noticed at the next read or `Refresh`, so call `Refresh` as the app returns to the foreground. An older transaction for a product, such as an expired renewal handed back unfinished at launch, never replaces a later one. - `Restore` runs the store's sync (call it only from a Restore Purchases button, as it may ask the user to sign in) and reloads the entitlements, which brings unlocks back after a reinstall that wiped the save. - `Buy` answers `Bought`, `BuyPending` (Ask to Buy and other approvals; `Pending(product)` stays true until the approved transaction arrives through the store's updates, which deliver it as `Buy` would have; a declined request produces no transaction, so `Pending` stays true until a later purchase of the product arrives or the app restarts), `BuyCancelled`, or `BuyFailed` with the error. - A refund or revocation removes an unlock, and runs `Revoke` once for a credited consumable when the game sets it. The ledger keeps the newest `LedgerLimit` (1024) IDs, so a refund of a consumable credited before that many newer ones is finished without `Revoke`. - `Verify` hands each transaction, whose `Signed` is the store's JWS, to the game's server before delivery and may answer from any goroutine; a refused transaction is neither delivered nor finished. Without `Verify`, only transactions the device verified are delivered. - `OnError` hears failures no `Buy` or `Restore` answers, such as an unfinished transaction at launch whose save failed. ```go type Progress struct { Coins int `json:"coins"` Purchases liveops.Ledger `json:"purchases"` } saves := save.NewStorageStore(cx.Storage(), "game") var p Progress _ = saves.Load("main", &p) shop := liveops.NewPurchases(cx, liveops.PurchasesOptions{ Ledger: &p.Purchases, Credit: func(t core.Transaction) { p.Coins += 100 * t.Quantity }, Revoke: func(t core.Transaction) { p.Coins -= 100 * t.Quantity }, Save: func() error { return saves.Save("main", &p) }, Verify: func(t core.Transaction, done func(error)) { go done(server.Verify(t.Signed)) }, }) shop.Buy("com.example.coins.100", 1, func(r liveops.BuyResult, err error) { /* bought, pending, cancelled or failed */ }) showNoAds := !shop.Owned("com.example.noads") ``` Tests drive purchases through `nsgotest`: start the app with `nsgotest.Environment(core.Environment{Purchases: true})`, set `app.Products`, and use `app.PurchaseAnswer` for a cancel or Ask to Buy, `app.UpdatePurchase` for an approval or a refund, `nsgotest.UnfinishedTransactions` together with `nsgotest.Storage` for a run killed before it finished a transaction, and `app.Entitlements` with `Restore` for a reinstall. `liveops/purchases_test.go` covers each. To check a restore by hand under StoreKit Testing, add a StoreKit configuration file with a non-consumable to the iOS app's Xcode scheme, build with `apple.purchases: true`, buy the product in the simulator, delete and reinstall the app, then press the game's Restore Purchases button: `Owned` reports the product again. Android has no store in NSGo v0.3.0 (Google Play Billing waits on [nsgo#1369](https://github.com/nsgo-dev/nsgo/issues/1369)). --- Source: https://game.nsgo.dev/docs/loot/ # loot `github.com/nsgo-dev/game/pkg/loot` rolls nested weighted drop tables with guaranteed drops and pity counters. Every roll draws from a [`random.Stream`](https://game.nsgo.dev/docs/determinism/), so a seed and a sequence of rolls give the same drops on every platform, in replays and on a dedicated server. ## Tables in YAML A game's drop tables are a versioned YAML document: ```yaml version: 1 tables: - name: boss rolls: {min: 1, max: 3} guaranteed: - item: gold count: {min: 50, max: 120} entries: - table: common weight: 80 - table: rare weight: 19 count: 2 - nothing: true weight: 1 - name: common entries: - item: potion weight: 3 - item: arrow weight: 1 count: 10 - name: rare entries: - item: amulet weight: 1 ``` - `rolls` is how many weighted picks one roll of the table makes (one when omitted). `guaranteed` entries drop every time the table is rolled, before its picks. - An entry drops an `item`, rolls another `table`, or drops `nothing`; a `nothing` entry's weight sets the chance of a miss. Weights are relative and positive; the chance of an entry is its weight over the table's total. - `count` is an item's quantity, or how many times a table entry rolls its table. `rolls` and `count` take an integer or a `{min, max}` range drawn uniformly. `loot.Parse` refuses unknown fields, any version but 1, duplicate names, unknown or cyclic table references, and tables whose worst-case roll would exceed `loot.MaxRollSteps` (65536 steps, where a weighted pick costs one step per entry and pity rule of its table, and every sub-table roll and drop costs one more). `loot.Encode` writes a document back as deterministic YAML: the fields in a fixed order, a range written as an integer when its ends are equal, and text that parses back to an equal document. ## Rolling ```go doc, err := loot.Parse(data) if err != nil { ... } lib, err := loot.New(doc) if err != nil { ... } streams := random.NewStreams(worldSeed) roller := loot.NewRoller(lib, streams.Stream("loot")) drops, err := roller.Roll("boss") // []loot.Drop{{Item: "gold", Count: 87}, {Item: "potion", Count: 1}, ...} ``` A `Library` is immutable and can be shared; a `Roller` belongs to one player or save and one goroutine. Drops come back in the order they were produced, with nested tables expanded in place. `AppendRoll(dst[:0], name)` reuses a slice and rolls without allocating. `Library.Chances(name)` returns each entry's chance on one pick, for drop-rate screens. ## Pity A pity rule raises the chance of one of its table's weighted entries after a run of picks without it: ```yaml - name: banner entries: - table: five-star weight: 0.6 - table: four-star weight: 5.1 - item: three-star weight: 94.3 pity: - name: five table: five-star softFrom: 74 softStep: 6 guaranteeAt: 90 - name: four table: four-star guaranteeAt: 10 ``` - `guaranteeAt: 90` forces the target on the 90th pick since it was last picked. - `softFrom: 74` with `softStep: 6` adds `(n - 74 + 1) * 6` to the target's weight on the n-th pick since it was last picked, from the 74th on. `softFrom` must be below `guaranteeAt` when both are set. - Each rule keeps a miss counter: the number of picks since its target was last picked, reset whenever the target is picked by chance or by force. `roller.Misses("banner", "five")` reads it for a pity meter. - When several rules force the same pick, the first one in the list wins and the others keep counting, so the next pick goes to the next rule. ## Saving The pity counters and the stream are saved together, so a loaded game continues with the same drops: ```go type LootSave struct { Pity loot.State `json:"pity"` Stream random.State `json:"stream"` } save := LootSave{Pity: roller.State(), Stream: roller.Stream().State()} // After loading: stream := random.New(0) stream.SetState(save.Stream) roller = loot.NewRoller(lib, stream) if err := roller.SetState(save.Pity); err != nil { ... } ``` `State` lists only non-zero counters, keyed by table and rule name, and marshals with sorted keys. `SetState` ignores counters for tables or rules the document no longer has, so a save survives edits to the loot file, and refuses negative counters. --- Source: https://game.nsgo.dev/docs/math2d/ # math2d `game/math2d` provides small, zero-allocation 2D value types shared across NSGo game packages: `Vec2`, axis-aligned `Rect`, `Circle`, and 3×2 `Affine` transforms, with lossless conversions to and from NSGo's `core` geometry types. ```go import "github.com/nsgo-dev/game/pkg/math2d" ``` All coordinates use `float32` to match `core.Points`, `core.Point`, `core.Size`, `core.Bounds`, and `core.Drawing`. Angles are in radians, turning from `+X` toward `+Y` (clockwise in NSGo's Y-down canvas coordinates). ## Vectors (`Vec2`) Construct vectors with `V2(x, y)`, `Zero()`, `One()`, `UnitX()`, `UnitY()`, or `FromAngle(rad)`, and convert losslessly to and from NSGo `core`: ```go pos := math2d.FromPoint(pointerPos) dir := target.Sub(pos).Normalize() vel := dir.Scale(220).ClampLen(240) next := pos.Add(vel.Scale(float32(dt.Seconds()))) // Convert back to NSGo core types with zero loss: pt := next.Point() sz := math2d.V2(32, 48).Size() _, _ = pt, sz ``` | Method | Behavior | | --- | --- | | `Add`, `Sub`, `Mul`, `Div`, `Scale`, `Neg` | Component-wise arithmetic and scalar scaling. | | `Dot`, `Cross`, `Len`, `LenSq`, `Dist`, `DistSq` | Products, lengths, and distances (`Cross` returns the 2D scalar `X*o.Y - Y*o.X`). | | `Normalize`, `ClampLen` | Unit vector (returns `Zero()` for zero-length) and magnitude clamping. | | `Lerp`, `MoveTowards` | Linear interpolation and fixed-step pursuit toward a target. | | `Angle`, `Rotate`, `Perp`, `Reflect`, `Project` | Polar angle, rotation in radians, 90° perpendicular, reflection, and projection. | | `Min`, `Max`, `Clamp`, `ApproxEqual` | Component-wise bounds and epsilon comparison. | ## Rectangles and circles (`Rect`, `Circle`) `Rect` stores `{X, Y, W, H}` using half-open containment `[X, X+W) × [Y, Y+H)`, matching `core.Bounds`. Any `Rect` with `W <= 0` or `H <= 0` (or `NaN`) is empty. ```go box := math2d.FromCenter(math2d.V2(160, 90), math2d.V2(40, 24)) expanded := box.Expand(4) if hit, ok := expanded.Intersection(math2d.FromBounds(viewBounds)); ok { coreRect := hit.Bounds() _ = coreRect } blast := math2d.Circle{Center: math2d.V2(180, 96), Radius: 36} if blast.OverlapsRect(box) { closest := box.ClosestPoint(blast.Center) _ = closest } ``` - Construct rectangles with `FromBounds(b)`, `FromCenter(center, size)`, or `FromMinMax(lo, hi)`, and convert back via `r.Bounds()`. - Query rectangles with `Min`, `Max`, `Center`, `Size`, `Normalized`, `Empty`, `Contains`, `ContainsRect`, `Overlaps`, `Intersection`, `Union`, `Expand`, `Translate`, `ClampPoint`, and `ClosestPoint`. - Query circles with `Contains`, `Overlaps`, `OverlapsRect`, `Bounds`, `Translate`, and `ApproxEqual`. ## 2D affine transforms (`Affine`) `Affine` stores a 3×2 matrix `{A, B, C, D, Tx, Ty}` in the same column order as `core.Drawing.Transform` and `core.Matrix3D.Affine` (`Canvas 2D` / SVG `matrix(a, b, c, d, e, f)`): ```go // Scale first, then rotate, then translate: m := math2d.TRS(math2d.V2(120, 80), 0.35, math2d.V2(2, 2)) worldPt := m.TransformPoint(math2d.V2(8, 0)) worldBox := m.TransformRect(localBounds) // Invert to map screen/world points back into local space: if inv, ok := m.Invert(); ok { localPt := inv.TransformPoint(worldPt) _ = localPt } // Lossless conversion to and from core.Matrix3D: mat3d := m.ToCore() back, ok := math2d.FromCore(mat3d) _, _, _ = worldBox, back, ok ``` Use `Identity()`, `Translate(x, y)`, `Scale(sx, sy)`, `Rotate(rad)`, `RotateAround(rad, cx, cy)`, `TRS(pos, rot, scale)`, and `m.Mul(other)` (right-to-left composition: `other` applied first, then `m`). `TransformVector(v)` applies only the linear part without translation. --- Source: https://game.nsgo.dev/docs/math3d/ # 3D Math Conventions `math3d` provides pure-Go `float32` vectors, matrices, quaternions, transforms, bounding volumes, rays, planes, and frustums with a single consistent set of conventions matching glTF 2.0, WebGPU, and Metal. ```go import "github.com/nsgo-dev/game/pkg/math3d" ``` ## Quick Reference | Property | Convention | Notes | | --- | --- | --- | | Handedness | Right-handed, Y-up | `+X` right, `+Y` up, `-Z` forward | | Angles | Radians | Right-handed CCW looking down `+axis`; `DegToRad` / `RadToDeg` | | Matrix storage | Column-major (`[9]float32`, `[16]float32`) | Matches WGSL `mat4x4`, Metal `simd::float4x4`, GLSL `mat4`, glTF 2.0 | | Vector convention | Column vectors (`M * v`) | Composition runs right-to-left: `(A * B) * v = A * (B * v)` | | Transform order | `TRS` (`T * R * S`) | Scale first, then rotate, then translate | | Clip-space depth (NDC) | `[0, 1]` default (`ZO`) | WebGPU / Metal / Vulkan; `[-1, 1]` available via `*NO` | | Quaternions | `(X, Y, Z, W)` | Identity `{0, 0, 0, 1}`; matches glTF 2.0 `[x, y, z, w]` | | Euler order | Intrinsic `YXZ` default | `Ry(yaw) * Rx(pitch) * Rz(roll)`; `XYZ` via `*XYZ` | ## Coordinate System `math3d` uses a **right-handed, Y-up** coordinate system: - `+X` points **right** (`Vec3Right()`). - `+Y` points **up** (`Vec3Up()`). - `-Z` points **forward** (`Vec3Forward()`). A camera at the origin with identity view looks down `-Z`, while `+Z` points out of the screen toward the viewer. Cross products obey the right-hand rule: ```text +X × +Y = +Z +Y × +Z = +X +Z × +X = +Y ``` All rotation functions take **radians**. A positive angle rotates **counter-clockwise** when looking from the positive tip of the rotation axis toward the origin (curl the fingers of your right hand with your thumb pointing along `+axis`): - `RotateX(+π/2)` rotates `+Y` to `+Z`. - `RotateY(+π/2)` rotates `-Z` (forward) to `-X` (left). - `RotateZ(+π/2)` rotates `+X` to `+Y`. ## Matrices and Storage Layout `Mat3` (`[9]float32`) and `Mat4` (`[16]float32`) are stored in **column-major** order. The element at `(row, col)` sits at `col*3 + row` for `Mat3` and `col*4 + row` for `Mat4`: ```text Mat4 indices: col 0 col 1 col 2 col 3 [ m[0] m[4] m[8] m[12] ] row 0 [ m[1] m[5] m[9] m[13] ] row 1 [ m[2] m[6] m[10] m[14] ] row 2 [ m[3] m[7] m[11] m[15] ] row 3 ``` Because WGSL (`mat4x4`), Metal (`simd::float4x4`), GLSL (`mat4`), and glTF 2.0 `node.matrix` are all column-major, a `Mat4` can be uploaded directly to a GPU uniform buffer with no transpose. Vectors are column vectors multiplied on the right (`M * v`). Matrix multiplication therefore composes **right-to-left**: ```go // Scale first, then rotate, then translate: M = T * R * S model := math3d.TRS(pos, rot, scale) // Model -> World -> View -> Clip: MVP = P * V * M mvp := proj.Mul(view).Mul(model) ``` For surface normals under non-uniform scale, transform with `NormalMatrix(model)` (the inverse-transpose of the upper-left 3×3) and re-normalize. ## Clip Space and Depth Range `Perspective` and `Ortho` default to **zero-to-one (`[0, 1]`)** NDC depth, matching **WebGPU**, **Metal**, **Vulkan**, and **Direct3D**: - View-space `z = -near` maps to NDC `z = 0`. - View-space `z = -far` maps to NDC `z = 1`. - View-space `x` and `y` map to `[-1, 1]`. Both depth conventions are provided explicitly so code targeting OpenGL or WebGL can opt into `[-1, 1]` without custom matrices: | Depth range | Perspective | Orthographic | Frustum extraction | | --- | --- | --- | --- | | `[0, 1]` (WebGPU / Metal / Vulkan) | `Perspective` / `PerspectiveZO` | `Ortho` / `OrthoZO` | `FrustumFromMat4` / `FrustumFromMat4ZO` | | `[-1, 1]` (OpenGL / WebGL) | `PerspectiveNO` | `OrthoNO` | `FrustumFromMat4NO` | ## Quaternions and Transforms `Quat` stores `{X, Y, Z, W}` with identity `QuatIdentity() = {0, 0, 0, 1}`, matching glTF 2.0's `[x, y, z, w]` ordering. - **Equivalence**: `q` and `-q` represent the same 3D rotation. `Slerp` and `Nlerp` automatically negate the target when `q.Dot(b) < 0` so interpolation always follows the **shortest arc**. - **Composition**: `q1.Mul(q2)` applies `q2` first and then `q1`, matching `q1.ToMat4().Mul(q2.ToMat4())`. - **Euler angles**: `QuatFromEuler(pitch, yaw, roll)` and `ToEuler()` use intrinsic **YXZ** (`Ry(yaw) * Rx(pitch) * Rz(roll)`), standard for cameras and characters. Intrinsic **XYZ** (`Rx(x) * Ry(y) * Rz(z)`) is available via `QuatFromEulerXYZ` and `ToEulerXYZ`. Both extract in float64, so yaw and roll stay separate right up to the ±90° gimbal pole; only an exact lock folds roll into yaw. - **Orientation vs. View**: `LookRotation(forward, up)` builds a world orientation quaternion whose local `-Z` points along `forward` and local `+Y` points toward `up`. For a camera at `eye` looking at `target`, `Transform{Pos: eye, Rot: LookRotation(target.Sub(eye), up), Scale: Vec3One()}.ToMat4()` is the exact inverse of `LookAt(eye, target, up)`. `Transform` pairs `Pos`, `Rot`, and `Scale` for scene hierarchies and interpolation (`Lerp` linearly interpolates position and scale and uses `Slerp` for rotation). `parent.Mul(child)` composes TRS directly; for hierarchies that combine non-uniform parent scale with rotated children (which introduces shear), compose as `Mat4`. Likewise `t.Inverse()` undoes `t` under `Mul` but is the geometric inverse only for rigid, uniformly scaled or unrotated transforms: the inverse of a non-uniform scale under a rotation shears, so it is not a TRS. `t.InverseMat4()` returns the exact inverse matrix for every transform (and `false` when a scale component is zero or the inverse would overflow `float32`), so use it to map world points back into a non-uniformly scaled local space. ## Bounds, Rays, Planes, and Frustums - **`AABB`**: Axis-aligned bounding box `{Min, Max}`. Start incremental bounds with `AABBEmpty()`, grow with `ExpandPoint` / `Union`, and transform tightly into world space with `Transform(m)`. - **`Sphere`**: `{Center, Radius}` with `Contains`, `IntersectsSphere`, and `IntersectsAABB`. - **`Plane`**: `{Normal, D}` representing `Normal · p + D = 0`. Call `Normalized()` so `SignedDist(p)` returns Euclidean signed distance (positive on the side `Normal` points toward). - **`Ray`**: Half-line `P(t) = Origin + t * Dir` (`t >= 0`) with `IntersectAABB` (slab test), `IntersectSphere`, `IntersectPlane`, and `IntersectTriangle` (double-sided Möller–Trumbore returning `(t, u, v, hit)`). Their parallel tests are relative to the vector lengths, so tiny triangles and short ray directions still hit. - **`Frustum`**: Six inward-pointing normalized planes (`FrustumLeft` through `FrustumFar`) extracted from any perspective or orthographic view-projection matrix via Gribb–Hartmann (`FrustumFromMat4` for `[0, 1]`, `FrustumFromMat4NO` for `[-1, 1]`), supporting `ContainsPoint`, `IntersectsSphere`, and `IntersectsAABB`. A point on a plane counts as inside, with a small slack relative to the plane's distance from the origin so float rounding does not cull geometry on a distant far plane. ```go view := math3d.LookAt(math3d.Vec3{X: 0, Y: 3, Z: 8}, math3d.Vec3Zero(), math3d.Vec3Up()) proj := math3d.Perspective(math3d.DegToRad(60), 16.0/9.0, 0.1, 200) frustum := math3d.FrustumFromMat4(proj.Mul(view)) if frustum.IntersectsAABB(worldBounds) { // Object is visible. } ``` ## Curves `QuadraticBezier3D`, `CubicBezier3D`, `CubicHermite3D`, `HermiteSpline3D` and `CatmullRom3D` share the `Curve3D` interface: `Point`, `Tangent`, `Length`, arc-length lookups (`DistanceToT`, `PointAtDistance`) and rotation-minimizing frames (`FrameAt`, `FrameAtDistance`) for cameras and objects that follow a path. - `NewHermiteSpline3D` uses the uniform Catmull-Rom tangent `(next - previous) / 2` for points without an entry in `tangents`; pass a zero tangent explicitly where the curve should stop. - `NewCatmullRom3DAlpha` with `alpha` 0 is the uniform spline, whose knots are evenly spaced even when neighboring points coincide; the default `NewCatmullRom3D` is centripetal (`alpha` 0.5). --- Source: https://game.nsgo.dev/docs/mcp/ # mcp `game/mcp` exposes a running game's scenes, layers, entities, components, fixed-step loop controls, game-coordinate input injection, tunables, debug console, loaded asset groups and hot reload controls to coding agents over MCP through NSGo's `github.com/nsgo-dev/nsgo/automation` package. NSGo's built-in `nsgo mcp` server sees native views only; a game draws into one `Canvas` or GPU view. Attaching an `mcp.Bridge` to a `core.Scope` registers game-specific tools on the engine's reactive graph so `nsgo mcp` serves them alongside the built-in tools whenever the app runs under `go tool nsgo dev -automation` or `go tool nsgo test`. In ordinary and release builds, `automation.Register` is a no-op and adds no runtime protocol. ```go import "github.com/nsgo-dev/game/pkg/mcp" ``` ## Attaching a bridge Call `mcp.Attach` (or `mcp.New` followed by `bridge.Attach`) on the engine goroutine with the subsystems you want agents to inspect. Every field in `mcp.Config` is optional; tools remain registered until `cx` is disposed or `bridge.Detach()` is called. ```go bridge, err := mcp.Attach(cx, mcp.Config{ Scenes: g.scenes, SceneName: func(c *scene.Controller) string { return g.sceneNames[c] }, SceneFunc: func() *scene.Scene { return g.activeScene }, NamedScenes: map[string]*scene.Scene{"title": g.titleScene}, WorldFunc: func() *entities.World { return g.world }, EntityName: func(e entities.Entity) string { return g.names[e] }, EntityTags: func(e entities.Entity) []string { return g.tags[e] }, EntityLayer: func(e entities.Entity) string { return g.layers[e] }, Loop: g.loop, RandomStreams: g.rng, Actions: g.actions, Viewport: &g.viewport, ViewSizeFunc: g.currentViewSize, Console: g.console, Overlay: g.debugOverlay, RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) }, Assets: g.assets, Resources: g.resources, Shaders: g.shaderReloader, Materials: g.materialReloader, ReloadAsset: g.reloadCustomAsset, PhysicsFunc: func() *physics.World { return g.physics }, ScreenshotDir: g.screenshotDir, }) if err != nil { return err } ``` - When a game replaces its `*scene.Scene`, `*entities.World`, `*game.Loop`, `*debug.Console` or `*physics.World` across level restarts, supply `SceneFunc` / `WorldFunc` / `LoopFunc` / `ConsoleFunc` / `PhysicsFunc` (or call `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop` / `bridge.SetConsole` / `bridge.SetPhysics`). - To support `game_loop_seed`, configure `Random` (`*random.Stream`), `RandomStreams` (`*random.Streams`) and/or a custom `SetSeed` callback; if none is set, `game_loop_seed` returns an actionable error. - When a `scene.Manager` controller draws via a custom `Controller.Draw` without setting `Controller.Scene`, `SceneFunc` / `Scene` provides the current scene's layers automatically. - When `EntityName` or `EntityLayer` is omitted (or returns `""`), `game/mcp` falls back to [`sceneformat.ObjectRef`](https://game.nsgo.dev/docs/editor/) if the entity carries one. - For `game_screenshot`, supply `CaptureFrame` (to composite overlays onto an already-rendered `*image.RGBA`), `DrawFrame` (to record custom `core.Drawing` ops), or let `game/mcp` render the active `Scenes`/`Scene` directly under `Viewport` / `ViewportFunc` (with optional `ScreenshotBackground`). Set `ScreenshotDir` so agents can pass a relative `.png` `path` and read the file; otherwise screenshots return `png_base64` inline, which an MCP client receives as JSON text rather than as an image. ## Inspecting and editing components Components registered on an [`entities.World`](https://game.nsgo.dev/docs/entities/) with `entities.RegisterCodec` are readable and editable automatically. In addition: - Built-in `entities.Transform2D`, `entities.WorldTransform2D` and `sceneformat.ObjectRef` components are surfaced automatically as `"transform2d"`, `"world_transform2d"` and `"object_ref"` unless that type or name is already registered. `"transform2d"` and `"object_ref"` are editable directly (with `"transform2d"` propagating `Hierarchy2D` dirty flags automatically); `"world_transform2d"` is derived from the hierarchy and read-only. - Transient or non-saved runtime components can be exposed read-only with `mcp.RegisterComponent[T](bridge, name)` or `mcp.RegisterComponentFunc(bridge, name, read)`, or exposed for both reading and editing with `mcp.RegisterMutableComponent[T](bridge, name)` or `mcp.RegisterComponentEditor[T](bridge, name, apply)`. `RegisterComponentEditor` can add editing to an earlier `RegisterComponent[T]` registration of the same type, but not to a `RegisterComponentFunc` reader, whose value need not be stored as `T`. - `game_component_set` decodes values strictly with `DisallowUnknownFields`, rejects non-finite floats (`NaN`, `±Inf`) and invalid nulls, and patches existing fields by default (preserving omitted fields unless `"replace": true` is passed) without leaving partially mutated state on error. A patch keeps every field it does not change exactly as it was, including unexported fields, fields tagged `json:"-"` such as callbacks and handles, and the identity of pointers, maps and slices; a field it changes gets a freshly allocated value, so an error or an editor that rejects the value leaves the live component untouched. A codec component whose decoded value cannot be encoded back, such as a `NaN` produced by a custom `UnmarshalJSON`, is refused before it is stored. - Component values are serialized with `encoding/json`; if a runtime value contains non-finite floats (`NaN`, `+Inf`, `-Inf`), callback fields, channels or cyclic pointers, `game/mcp` falls back to a safe sanitizer (`"NaN"`, `"+Inf"`, `"-Inf"`, `""`, `""`, `""`) so an agent can still diagnose broken runtime state. ```go if err := mcp.RegisterMutableComponent[AIState](bridge, "ai"); err != nil { return err } if err := mcp.RegisterComponentEditor[Health](bridge, "health", func(w *entities.World, e entities.Entity, h Health) error { if h.HP < 0 { return errors.New("hp cannot be negative") } entities.Set(w, e, h) return nil }); err != nil { return err } ``` ## Registering prefabs Prefabs can be registered on `mcp.Config.Prefabs` or on the `*mcp.Bridge` so agents can discover them with `game_prefabs_list` and spawn them with `game_entity_spawn`: - `bridge.RegisterPrefab(name, spawn)` (or `Config.Prefabs`) registers a custom `mcp.PrefabSpawner` (`func(w *entities.World, overrides map[string]any) (entities.Entity, error)`). - `bridge.RegisterEntityPrefab(p)` registers an [`*entities.Prefab`](https://game.nsgo.dev/docs/entities/) under `p.Name()`. - `bridge.RegisterScenePrefab(name, doc)` registers a validated, self-contained [`*sceneformat.SceneDoc`](https://game.nsgo.dev/docs/editor/) template spawned via `sceneformat.SpawnEntities`. The document must hold exactly one top-level object, the spawned root; nest the rest under it. Every spawn attaches the document's `sceneformat.ObjectRef` IDs unchanged, so repeated spawns produce entities with the same object IDs, which `game_entities_list` also shows as their names unless `EntityName` says otherwise. ```go if err := bridge.RegisterEntityPrefab(coinPrefab); err != nil { return err } if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { return err } ``` If `game_entity_spawn` fails while applying `parent` or `components`, or while reading the new entity's components back, the newly spawned entity (and any scene-prefab children) are rolled back automatically. `x` and `y` are validated before anything is spawned. ## Registered tools | Tool | Arguments | What it returns | | --- | --- | --- | | `game_scenes_list` | `{}` | Active scene stack (bottom to top), `current` scene name, `stack_depth`, transition state and `progress`, layer counts, camera state, and any inactive `NamedScenes`. | | `game_layers_list` | `scene` (optional), `include_hidden` (optional, default `true`) | Layers of the selected (or current active) scene in draw order (`draw_index`, slice `index`, `name`, `space`, `visible`, `order`, effective `parallax_x`/`parallax_y`, offsets, repeat periods, `depth_sort`, and item/batch/sprite/tilemap/drawable counts). | | `game_entities_list` | `component`, `layer`, `name` (substring), `tag`, `parent` (ref or `"root"`), `include_components` (default `false`), `offset`, `limit` | Live entities in ascending slot order with `total`, `returned`, stable `ref`, `index`, `generation`, metadata, `parent`, `child_count`, sorted `components` names, and optional inline `values`. | | `game_entity_inspect` | `ref` (required) | Full inspection of one live entity: `ref`, `index`, `generation`, metadata, `parent`, `children` refs, and every readable component value keyed by component name. | | `game_component_get` | `ref` (required), `component` (required) | One component's serialized `value` on a live entity. | | `game_loop_status` | `{}` | Current loop state: `paused`, effective `time_scale`, `step_seconds`, `step_hz`, total `steps`, `game_time_seconds` and `seed_configured`. | | `game_loop_pause` | `{}` | Pauses the loop (`Loop.SetPaused(true)`) without accumulating a catch-up backlog and returns the updated loop status. | | `game_loop_resume` | `{}` | Resumes the loop (`Loop.SetPaused(false)`) and returns the updated loop status. | | `game_loop_step` | `count` (optional, default `1`, `1..3600`) | Synchronously runs `count` fixed updates (`Loop.StepNow`) whether paused or running, returning `steps_advanced`, `total_steps`, `game_time_seconds`, `delta_seconds` and `paused`. Stepping 60 updates at 60 Hz advances exactly `1.0` second of game time. | | `game_loop_time_scale` | `time_scale` (required, finite `>= 0`) | Updates `Loop.TimeScale` (`0` resets to the default `1x` speed) and returns the updated loop status. | | `game_loop_seed` | `seed` (required, unsigned 64-bit integer) | Re-seeds `Config.Random`, `Config.RandomStreams` and/or calls `Config.SetSeed`, returning `{seed}`. | | `game_input_action` | `name` (required), `mode` (`"press"`, `"release"`, `"tap"`, default `"tap"`), `value` (optional float in `[-1, 1]`) | Injects a digital action hold/release/tap (or analog value) into `input.Actions` and returns the action's current step state. | | `game_input_axis` | `name` + `value`, `axes` map (`{name: value}`), and/or `clear` (`bool`) | Sets or clears 1D or multi-axis analog values in `[-1, 1]` on `input.Actions`. | | `game_input_pointer` | `x`, `y` (required), `action` (`"press"`, `"release"`, `"move"`, `"click"`, default `"click"`), `space` (`"game"` or `"world"`, default `"game"`), `button` (`"left"`, `"right"`, `"middle"`) | Maps coordinates through the active scene's `Camera` (when `space="world"`) and `screen.Viewport` into view space, forwards to `input.Actions`, runs `Scene.HitTest` / `Scene.DispatchPress`, invokes `Config.OnPointer`, and returns both game/view coordinates, `in_viewport`, and hit metadata (`hit`, `hit_layer`, `hit_kind`, `hit_frame`, `hit_batch_index`, `hit_sprite_index`, `hit_drawable_index`, `dispatched`). | | `game_input_actions_list` | `{}` | Lists configured action and axis names on `input.Actions` with their current step state (`pressed`, `just_pressed`, `just_released`, `binding_count`, `value`, `negative`, `positive`). | | `game_tunables_list` | `prefix` (optional) | Registered `debug.Console` tunables sorted by name with `type`, current `value`, registration `default`, and numeric `min`/`max` bounds. | | `game_tunable_get` | `name` (required) | One registered tunable's `name`, `type`, current `value`, registration `default`, and numeric `min`/`max` bounds. | | `game_tunable_set` | `name` (required), `value` (required), `clamp` (optional, default `false`) | Updates a registered tunable (`float`, `int`, `bool` or `string`) with strict type checking and range validation (or clamping when `clamp: true`), returning `old_value`, applied `value`, metadata and `clamped`. | | `game_console_commands_list` | `include_builtin` (optional, default `true`) | Built-in and custom `debug.Console` commands sorted by name with `help` text and `builtin` flag. | | `game_console_exec` | `command` (required) | Runs one command line through `debug.Console`, returning `command`, `ok`, `output`, `lines`, and `error` (when the console command fails). | | `game_prefabs_list` | `{}` | Sorted list of registered prefabs (`name` and `kind`: `"custom"`, `"entity_prefab"`, or `"scene"`). | | `game_entity_spawn` | `prefab`, `overrides`, `parent`, `x`, `y`, `components` (all optional) | Newly spawned live entity's stable `ref`, `index`, `generation`, `prefab`, metadata, `parent`, `children`, and initial `components` snapshot. | | `game_entity_destroy` | `ref` (required), `policy` (optional: `"cascade"`, `"orphan"`, `"keep_world"`, or `"reparent"`) | Confirmation of destruction with `ref`, the `policy` applied to children (the hierarchy's default, usually `"orphan"`, when omitted; `"none"` when omitted and the entity had no children), and count of `destroyed` entities. `"reparent"` keeps the children's world transforms. | | `game_component_set` | `ref` (required), `component` (required), `value` (required), `replace` (optional, default `false`) | Updated component `value` read back from the live entity; edits take effect on the next simulation step. If the write succeeded but the read-back failed, `value` is `null` and `read_error` says why; the edit still stands. | | `game_component_remove` | `ref` (required), `component` (required) | Whether the component was present and `removed` from the live entity. | | `game_replay_status` | `{}` | Current recording and playback state (`recording`, `replaying`, `replay_done`, `frames_recorded`, `replay_frame`, `replay_total_frames`), active names/metadata, and sorted `saved_recordings`. | | `game_replay_record_start` | `name`, `seed`, `actions`, `axes`, `metadata`, `reset` (all optional; `reset` defaults to `true` when `ResetFunc` or a seed target is configured) | Resets to `seed` (see below) and starts recording per-step inputs via `replay.Recorder` at the game's fixed step rate, returning the resolved recording name, seed, step rate, watched names and metadata. | | `game_replay_record_stop` | `name` (optional), `save_path` (optional, relative to `ReplayConfig.SaveDir`), `overwrite` (default `false`) | Stops the active recording, stores it in memory (and optionally writes it under `SaveDir`), and returns its summary plus deterministic version-2 YAML text (`yaml`). An existing stored name or file is refused unless `overwrite: true`, and the recording continues. | | `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps` (`1..3600`), `reset` (default `true` when `ResetFunc` or a seed target is configured) | Resets to the recording's seed and starts deterministic playback via `replay.Player`, optionally advancing all (`run_to_end`, recordings up to `3600` steps) or `steps` frames synchronously via `StepFunc` or the game loop's `StepNow`. A recording whose `rate` differs from the game's fixed step rate is refused. | | `game_replay_stop` | `{}` | Stops an active replay playback cleanly and reports how many frames were played. | | `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. | | `game_perf_readout` | `include_history` (optional, default `false`), `history_limit` (optional), `include_zones` (optional, default `false`), `zones_limit` (optional) | Live performance readout matching the debug overlay: `fps`, rolling average and latest `frame_ms`/`update_ms`/`draw_ms`, min/max/p50/p95/p99 frame times, draw stats (`draw_calls`, `sprites`, `batches`, `triangles`, `vertices`), per-frame heap allocations (`allocs_per_frame`, `alloc_bytes_per_frame`, `last_frame_allocs`, `last_frame_alloc_bytes`), `heap_bytes`, `gc_count`, GC pause/hitch metrics, optional `render3d` and `asset_memory` breakdowns, and optional chronological `history` and profiler `zones`. | | `game_perf_zones` | `limit` (optional) | Named timing zones from `debug.Profiler` sorted by recent frame cost (`name`, `last_ms`, `avg_ms`, `max_ms`, `calls`), plus `recording`, `recorded_frames` and `total`. | | `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zone timings, and `debug.GCMonitor` history. A profiler trace recording started with `StartRecording` keeps running and keeps its events. | | `game_assets_list` | `group` (optional), `state` (`loaded`/`loading`/`unloaded`/`failed`), `kind` (optional) | Deterministically sorted asset groups (`assets.Manager` groups, `resource.Library`, `hotreload.ShaderReloader`, `hotreload.MaterialReloader`, and custom registered assets) with load states, asset keys/kinds/URIs, frame counts, per-group estimated bytes, and `total_bytes`. | | `game_asset_reload` | `key` (name, URI or relative path), `group` (optional), `all` (boolean, optional) | Reloads a matching asset in place (or all loaded assets when `all: true`), returning `{reloaded, key, group, kind, bytes, duration_ms, revision, items, error}`; each item carries `skipped` when it was left unchanged without an error. Parse and compile errors are returned in the structured result while keeping the previously loaded working asset intact. `all: true` needs an asset manager, reloader or registered asset; `Config.ReloadAsset` only reloads a single key. | | `game_assets_reload_group` | `group` (required) | Reloads every loaded asset in the named group in place, reporting per-item results, `count` reloaded, `failed`, `skipped`, memory bytes, duration, and any item errors without crashing the running game. | | `game_screenshot` | `scene`, `width`, `height`, `format` (`"png"`), `path`, `bounds`, `collision_shapes`, `physics`, `grid`, `grid_step`, `camera`, `labels`, `overlays` (`{bounds, collision_shapes, physics, grid, grid_step, camera, labels}`) | Captures the game view as PNG (`width`, `height`, `format`, `bytes`, `png_base64` or relative `path`, an `overlays_drawn` summary, and `skipped_ops` / `skipped_images` when the software rasterizer left something out), optionally compositing pixel-aligned sprite bounds, 2D physics collision shapes, reference grid, camera frame and labels in the same camera and viewport transforms. | All tools reject unknown argument fields. ## Deterministic loop control Agents can drive reproducible test scenarios by pausing the loop, setting a deterministic seed, stepping an exact number of fixed updates, and inspecting entity state immediately afterward: - `game_loop_step` runs `Update` synchronously on the engine goroutine and calls `Draw` once afterward, so subsequent `game_entity_inspect` or `game_component_get` calls observe the updated state immediately without waiting for the next display frame. - Simulated time is accumulated per fixed-rate segment (`steps / rate`), so stepping 60 updates at 60 Hz advances `game_time_seconds` and `delta_seconds` by exactly `1.0` with no integer-nanosecond drift. - `game_loop_step` caps each call at `MaxLoopSteps` (`3600`, or one minute at 60 Hz) to guard against accidental hangs. ## Input injection and viewport mapping When `Actions`, `Viewport` / `ViewportFunc`, `ViewSizeFunc`, or `OnPointer` are set on `mcp.Config` (or updated via `bridge.SetActions` / `bridge.SetViewport`), agents can drive gameplay directly in virtual game coordinates without computing window letterbox offsets: - **Actions and axes**: `game_input_action` drives `Actions.Press`, `Actions.Release`, `Actions.Trigger` and `Actions.SetAxis`; `game_input_axis` sets or clears one or more analog axes in `[-1, 1]`. All injected inputs follow `Actions.Step()` snapshot semantics just like physical inputs, and `Actions.Reset()` clears them cleanly. - **Pointer coordinate pipeline**: `game_input_pointer` takes `(x, y)` in `"game"` space (virtual canvas points) or `"world"` space (converted to game space through the active scene's `Camera.WorldToView`), then maps game coordinates through `screen.Viewport.GameToView` using `ViewSizeFunc` (falling back to the attached scope's `Env().Window()` and then the viewport's virtual size). - **Delivery**: Mapped view coordinates are forwarded to `input.Actions` (so `Actions.MapPoint = viewport.ViewToGame` recovers the exact game position for `MouseRegion` bindings). When `in_viewport` is true, `Scene.HitTest` and primary `Scene.DispatchPress` run in game coordinates so pressing at a sprite's position hits that sprite and triggers its `OnPress` callback. `Config.OnPointer` receives every injected `PointerEvent` (a `"click"` emits `PointerPress` followed by `PointerRelease`). ## Tunables and debug console Pass a [`*debug.Console`](https://game.nsgo.dev/docs/debug/) via `Config.Console`, `Config.ConsoleFunc`, or `bridge.SetConsole` so agents can inspect and adjust live game variables and run custom debug commands: ```go console := debug.NewConsole() console.RegisterFloat("physics.gravity", 0, 2000, &g.gravity) console.RegisterInt("player.max_jumps", 1, 5, &g.maxJumps) console.RegisterBool("player.god_mode", &g.godMode) console.RegisterString("level.name", &g.levelName) console.RegisterCommand("spawn", "spawn [count]", g.handleSpawn) ``` - `game_tunables_list` and `game_tunable_get` read live values directly without adding entries to the console's interactive command history or output log. - `game_tunable_set` enforces each tunable's registered type (`float`, `int`, `bool` or `string`) and numeric `[min, max]` bounds by default without mutating the variable on error. Passing `"clamp": true` clamps out-of-range numeric values into `[min, max]` and sets `"clamped": true` in the response. - `game_console_exec` executes built-in commands (`help`, `list`, `get`, `set`, `clear`) and game-registered commands through `debug.Console.Exec`, returning `{command, ok, output, lines, error}`. Invalid MCP arguments or a missing `Console` return a tool error, while command execution failures (such as an unknown command name or invalid command arguments) return `ok: false` with the command's `error` message. ## Recording and replaying inputs Create a `*mcp.ReplayController` with `mcp.NewReplayController`, pass it to your simulation as its [`replay.ActionSource`](https://game.nsgo.dev/docs/replay/), and attach it on `mcp.Config.Replay`: ```go var ctrl *mcp.ReplayController ctrl = mcp.NewReplayController(mcp.ReplayConfig{ Source: g.actions, Actions: []string{"left", "right", "jump", "dash"}, Axes: []string{"move_x"}, StepRate: 60, SeedFunc: func() uint64 { return g.seed }, ResetFunc: func(seed uint64) error { g.actions.Reset() g.Reset(seed) return nil }, StepFunc: func(dt time.Duration) { g.Step(ctrl, dt) }, }) bridge, err := mcp.Attach(cx, mcp.Config{ WorldFunc: func() *entities.World { return g.world }, Replay: ctrl, }) ``` - Because `ReplayController` implements `replay.ActionSource`, your game loop reads input from `ctrl` identically during live play (forwarded to `Source`), recording (`replay.Recorder`) and playback (`replay.Player`). `Source` is required. It is still stepped during playback, so its previous-step snapshot is current when live input resumes. - Recording and playback share one reset: the Bridge's seed targets (`Config.Random`, `Config.RandomStreams`, `Config.SetSeed`, the same ones `game_loop_seed` uses) are re-seeded with the seed, then `ResetFunc(seed)` runs. `reset` defaults to `true` on both tools whenever there is something to reset, so a recording started mid-game with default arguments replays to the same state. Passing `reset: false` to `game_replay_record_start` records from the current state, and that recording only reproduces from the same state. - The recording's `rate` is the game's fixed step rate: the Bridge's loop (`Config.Loop` / `Config.LoopFunc`) `StepRate()` when there is one, otherwise `ReplayConfig.StepRate` (default `60`). `game_replay_play` refuses a recording made at another rate, because each step would get a different `dt`. - Recordings stopped via `game_replay_record_stop` are stored in memory under their name and returned as canonical deterministic [`game/replay`](https://game.nsgo.dev/docs/replay/) v2 YAML text. Set `ReplayConfig.SaveDir` if you also want agents to write recordings to relative paths on disk via `save_path`; the write goes through `os.Root`, so absolute paths, `..` and symbolic links cannot leave `SaveDir`. `metadata` stays only in the in-memory store: it is not part of the YAML, so a saved file or an inline `yaml` replay does not carry it. - `game_replay_play` accepts either a stored `name` or inline `yaml` text and replays either synchronously (`run_to_end: true` or `steps: N`) or frame by frame as the game loop advances. Without `StepFunc`, synchronous playback advances the Bridge's loop with `Loop.StepNow`, so `game_loop_status` counts the replayed steps and game time. Like `game_loop_step`, a single call advances at most `MaxLoopSteps` (`3600`) steps. - After the final recorded step, the next `ctrl.Step()` is a trailing playback step that releases actions still held at the end of the recording (firing `JustReleased` once); the step after it returns to live input and calls `OnReplayStop`. ## Performance readouts Pass your [`debug.Overlay`](https://game.nsgo.dev/docs/debug/) via `Config.Overlay` to expose the exact same frame timings, draw statistics (`debug.Options.DrawStats` or `Overlay.SetDrawStats`), GC/allocation counters (`debug.GCMonitor`), asset memory (`debug.MemoryTracker`) and timing scopes (`debug.Profiler`) shown by the on-screen debug HUD. - `Config.Profiler`, `Config.GC`, `Config.Memory` and `Config.DrawStatsFunc` override (or work standalone without) `Config.Overlay`. - `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](https://game.nsgo.dev/docs/render3d/) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. `mcp.PerfRender3DStats` has the same fields as `render3d.RenderStats`, so `mcp.PerfRender3DStats(stats)` converts one; `game/mcp` does not import `game/render3d`, so a 2D game that attaches the bridge does not link the 3D renderer. - `game_perf_readout` always includes a `sources` object indicating which telemetry providers are active (`overlay`, `profiler`, `gc`, `memory`, `draw_stats`, `render3d`). When the game annotates a frame spike via `Overlay.NoteFrameCause`, `history` entries include the optional `cause` string. ## Assets and hot reload Wire `Config.Assets` (or `Config.AssetsFunc` / `bridge.SetAssets`), `Config.Resources`, `Config.Shaders`, `Config.Materials`, and/or `Config.ReloadAsset` to let agents inspect memory usage and trigger live reloads without restarting the game: - **In-place atlas updates**: Reloading an atlas in `assets.Manager` (by asset name such as `"hero"`, full URI `"asset:sprites/hero.json"`, relative path `"sprites/hero.json"`, or image path `"sprites/hero.png"`) updates the existing `*sprite.Atlas` pointer in place and increments `assets.Manager.Revision()`, so sprites holding the atlas pointer and canvases reading `Revision()` update immediately. - **Standalone assets and atlases**: Games that hold a `*sprite.Atlas` or custom resource outside `assets.Manager` can register it with `bridge.RegisterAtlas(...)` or `bridge.RegisterAsset(mcp.CustomAsset{...})`. - **Safe failure handling**: Syntax, schema, or shader compilation errors leave the previous working atlas, shader, material, or resource active and return `reloaded: false` with the diagnostic message in `error`. - **Skipped assets**: Sounds are not replaced in place, images with no file behind them (such as generated textures) have nothing to reload, and a file at a density the screen does not show (the 1x file on a 2x screen) would change nothing on screen. These items carry `skipped` with the reason (`assets.SkippedSound`, `assets.SkippedNoFile`, `assets.SkippedDensity`) and count neither as reloaded nor as failed. A group reload also skips an image whose file the group's reader cannot find; reloading that image by key reports the read error. - **Off the engine goroutine**: `Manager.ReloadAsset` and `Manager.ReloadGroup` read files, parse atlases and run custom loaders on another goroutine, as `Group.Load` does, and apply the results on the engine goroutine once they finish. The tool call waits for them, so a custom reader or loader must not wait on the engine goroutine; when the call's context ends first, nothing is replaced and the tool returns the context's error. ## Screenshots and diagnostic overlays `game_screenshot` renders or captures the current game view and composites requested overlays in the exact same `screen.Viewport` clip/scale/letterbox and `tilemap.Camera` (including parallax and `SpaceScreen` HUD layers) transforms as the game itself: - **`bounds`**: Draws 1-pixel cyan (`#00e5ff`) bounding outlines around every visible sprite in the rendered scene(s). - **`collision_shapes` / `physics`**: Draws 2D collision shapes from `Config.Physics` (box, polygon, segment and chain bodies in green `#22c55e`, circle bodies with `+X` orientation tick and capsule bodies in sky blue `#38bdf8`, triggers in pink `#f472b6`, solid tiles in amber `#f59e0b`, one-way tiles in purple `#c084fc`) and `Config.RigidPhysics` (rotated rigid bodies), counted in `overlays_drawn` as `physics_boxes`, `physics_circles`, `physics_polygons`, `physics_capsules`, `physics_lines`, `physics_triggers` and `physics_tiles`. Box, circle, trigger and tile colors match `physics.DefaultDebugStyle()` and `mcp.DefaultOverlayStyle()`. - **`grid`**: Draws a world-space reference grid spaced by `grid_step` or `overlays.grid_step` (default `32` points). - **`camera`**: Draws the active camera's visible frame and center crosshair (`#facc15`). - **`labels`**: Draws compact bitmap labels for sprite frames and tagged physics bodies. - **`path`**: When set, writes the PNG to a relative `.png` path inside `Config.ScreenshotDir` through `os.Root`, so absolute paths, `..` and symbolic links cannot leave it, and omits `png_base64` from the response. When omitted, returns `png_base64` in the JSON result. An MCP client gets that result as text, so prefer `path` when the agent should look at the image. - **Size and pixel ratio**: Without `width` and `height`, the screenshot covers the view `game_input_pointer` maps through: `ViewSizeFunc`, else the attached window, else the viewport's virtual size, else the scene camera's size, in points at one pixel per point. A `CaptureFrame` image is taken to cover that view at the display's pixel ratio (an 800x450 frame of a 400x225-point view is 2x), so the viewport is laid out in points as the game does and the overlays are scaled to the image; an image with another aspect ratio is taken as one pixel per point. Inferred sizes are bounded like explicit ones (`8192` pixels a side, `4096x4096` pixels in all). - **`scene`**: Renders that scene on its own with the software rasterizer; `CaptureFrame` and `DrawFrame` are not used. A scene whose controller draws through a custom `Controller.Draw` without a `scene.Scene` is refused. - **Partial renders**: The software rasterizer draws rectangles, lines, arcs, quadratic and cubic curves, fills, strokes, rectangular clips, images and atlases whose pixels are in memory (`ImageSource.Pixels` or `Data`, read in the image's points when `Size` is set). It counts what it leaves out: `skipped_ops` by operation kind (text, rounded rectangles, ellipses, gradients, which fall back to their first color, blend modes, dashes, shadows, meshes) and `skipped_images` for images from a URI, an `asset:` file or an `Offscreen` canvas. Supply `CaptureFrame` when those matter. `overlays_drawn.sprite_bounds` counts sprites in layers' `Item.Batch`; sprites a `Drawable` item or a tilemap draws get no outline. ## Stable entity references Every live entity receives a generational reference formatted as `"entity::"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`: - A surviving entity keeps the exact same `ref` across simulation steps, even while other entities are spawned and destroyed. - When an entity is destroyed and its slot is later recycled, the new entity receives an incremented generation (for example `"entity:0:2"`). Calling `game_entity_inspect` or `game_component_get` with the stale `"entity:0:1"` returns a `"not alive"` error rather than silently reading the recycled entity. ## Testing with `nsgotest` In tests, attach the bridge inside `nsgotest.Start` and invoke tools through `automation.Call` inside `app.Post`: ```go var raw json.RawMessage var callErr error app.Post(func() { raw, callErr = automation.Call(cx, t.Context(), mcp.ToolEntitiesList, nil) }) app.Settle() ``` ## Rendering a drawing to PNG `mcp.RenderPNG(ops, width, height, background)` plays a recorded `core.Drawing`'s operations into a PNG with the software rasterizer `game_screenshot` uses when it draws a frame itself, and reports in `SkippedOps` and `SkippedImages` what it left out (text, and images that are not in memory as `Pixels` or `Data`). The editor's `viewport_image` uses it, so its picture is the same on every platform and headless. ## Editor tools The tools above reach a running game. The NSGo Game Editor has an MCP server of its own, package `game/editor/editormcp`, through which an agent reads and edits the project open in the editor: every edit goes through the same `Editor` methods the inspector, scene tree and viewport use, so it shows at once in the tree and the viewport, and the person takes it back with one Undo. ```go import "github.com/nsgo-dev/game/pkg/editor/editormcp" ``` ### Connecting an agent `nsgo game editor .` serves the open project on a local endpoint of its own: a Unix domain socket that only the user can open, named after a hash of the project's path, in `nsgo-game/editor` under the user's cache directory (`$NSGO_GAME_EDITOR_ENDPOINTS` when set). It is never a network port. When the editor opens another project, the endpoint follows it; a second editor on the same project leaves the first serving and says so on stderr. Run `go tool game mcp install` once in the project folder to write the project-level MCP configurations that both Claude Code (`.mcp.json`) and Codex (`.codex/config.toml`) read automatically: ```sh go tool game mcp install ``` `go tool game mcp install` is idempotent: running it again preserves unrelated MCP servers and Codex settings, leaves identical files untouched byte for byte, and prints what it wrote or left unchanged. You can also pass `-project ` from outside the project directory, or register `nsgo game mcp` manually: ```sh claude mcp add game-editor -- nsgo game mcp ``` `nsgo game mcp` is an MCP server on standard input and output that finds the editor with the project open and forwards every tool call, resource read and subscription to it, reporting the client's name and transport (such as `Claude Code over stdio`) to the editor's Connect dialog and status chip. It lists the editor's tools, including those other parts of the editor add, and connects again when the editor is closed and opened anew, so the agent's session outlives the editor's. While no editor has the project open, each call answers with an error that says so and how to open it: `no editor has the project open at /path/to/game: open it with nsgo game editor /path/to/game and try again`. ### Tools | Tool | Action | Arguments | What it does | | --- | --- | --- | --- | | `scene_read` | read | `file`, `offset`, `limit` (all optional) | Reads a scene, prefab, data table or other text file of the project, or `game.yaml`, as lines numbered from 1. While the editor holds unsaved edits to the open scene or `game.yaml`, or staged in-memory edits from a pending agent turn, that file is read as the editor holds it, and the reply says so and that its line numbers differ from the file's on disk; otherwise, and for any other file, it is read from disk, comments included, with the line numbers `game_check` reports. Without `file` it reads the open scene. A path must be relative to the project root and stay inside it. | | `scene_edit` | edit | `edits` (required), `file`, `label`, `why` (optional; each edit may also carry `why`) | Applies the edits, in order, to the open scene (or, while an agent turn is active, to any scene or prefab in the project in memory) without touching disk. Inside an active turn the edits join that single pending turn and record any `why` explanation on each derived change; outside a turn they record one ordinary undo step labeled `label`. The edits stay unsaved until kept and saved. | | `turn_start` | edit | `prompt`, `step` (optional) | Opens a pending agent turn so subsequent `scene_edit`, `object_set_field`, and `file_edit` calls across multiple files accumulate into one reviewable turn and one undo step when the person keeps it. | | `turn_end` | edit | `summary`, `step` (optional) | Marks the active working turn ready for the person's review with an optional completion summary (and optional progress step), returning the current derived turn snapshot. | | `turn_status` | read | none | Read-only snapshot of the current agent turn: status (`working`, `pending`, `stopped`, `kept`, `reverted`), prompt, progress steps, summary, per-file line counts (`+added`/`−removed`), and derived structural changes (with `kind`, `title`, `detail`, `file`, 1-based `line`, `why`, and `reverted`). There is intentionally no MCP tool that keeps or reverts a turn; only the person decides. | | `file_edit` | edit | `file` (required), `yaml` (required), `why`, `label` (optional) | Validates and applies a multi-file in-memory edit to `game.yaml`, a data table (`data/*.yaml` / `*.table.yaml`), an animation clip (`*.anim.yaml` / `*.clip.yaml`), a prefab (`*.prefab.yaml`), or a scene (`*.scene.yaml`) inside the active agent turn without writing to disk until kept and saved (enforcing symlink containment, You-only boundaries, `.git/**` refusal, and a 2 MiB size limit). | | `selection_get` | read | none | The open scene, the active layer, the selected object with its lines of YAML as `scene_read` numbers them, `selectedIds` for every selected object in multi-selection, the file selected in the file browser, the active tool and the view mode. | | `viewport_image` | read | `scale` (optional, 0.25 to 4), `viewport_overlays` (optional string array) | A PNG of the viewport as it shows now: the scene through the editor's view, with the camera frame, tile grid, selection outline and viewport overlays, at the viewport's size in points times `scale`. Omitting `viewport_overlays` uses the editor's active overlay set; passing overlay IDs (`collision_shapes`, `triggers`, `connections`, `patrol_paths`, `navigation`, `camera_bounds`, `labels`, or active plugin overlay IDs) overrides them for this image, and `[]` draws no overlays. Overlay labels (such as `"pulled → open"` on connection arrows) are rendered into the PNG; images not loaded in memory are left out and counted. | | `game_check` | run | none | Runs the Problems panel's check (`assetcheck` with the editor's component registry, and `project.Check`, including open unsaved documents in the editor) and returns its visible problems, each with file, 1-based line, 1-based column (where known), and message. | | `problem_propose_fix` | read | `problem` (required), `explanation` (required), `edit` (required) | Validates a proposed fix for a live problem on a cloned scene, computes the exact `-`/`+` YAML diff, and shows the review card (with Apply fix, Show me, Ignore, and Ask about this problem…) in the editor's Agent panel. Never applies the fix or modifies any file — no MCP tool applies a fix. | | `history_list` | read | `author` (`all`, `you`, `agent`), `limit` (1–500, default 50) (both optional) | Reads the editor's unified History timeline of manual edits, agent turns, external Git reloads, and saved points (newest first), with author, summary, detail, touched files, timestamps, change/kept counts, unsaved status, and active preview ID. | | `review_status` | read | none | Returns the active or most recent change-by-change agent turn review state: whether it is open or pending, the quoted request, round state, file summaries, every change's seen and reverted flags, overlapping edit conflicts and the person's merge choice (`mine`, `agent`, `both`), in-review YAML hand edits tagged `"you"` with edited fields and lines (preserved after Keep for round 2), active blockers (including YAML parse errors), and the last keep/revert outcome. Unsent draft notes are never exposed, privacy policies (`SceneAndData` and `GoSource`) are enforced, and keeping or reverting remains the person's decision. | | `review_notes_get` | read | none | Reads the active agent turn review's round state, changes, and the change-scoped notes explicitly sent by the author via **Send N notes** or **Revert and redo with this note** (`change_id`, `file`, `object`, `field`, `kind`, `note`, `revert_first`). Unsent draft notes and notes removed before sending are never returned. | | `review_redo` | edit | `changes` (required non-empty array of `{change_id, detail?, x?, y?, component?, fields?, file_content?, old_value?, new_value?, delta?, yaml_lines?}`) | Redoes only changes the author left notes on in the active review, advancing the same turn to Round 2+ while keeping earlier rounds intact and read-only. Un-noted changes (and any un-noted items in a supplied `file_content`) are refused atomically; redone changes become unseen again with `"Redone from your note: …"` as their Why, and **Keep** still applies the latest round as one undo step. | | `game_playtest` | run | `file`, `run`, `count`, `seeds`, `out`, `recordings` (all optional) | Validates `playtest.yaml`, runs the configured headless bot playtests with per-seed `.replay.yaml` recordings, writes the YAML report and returns each metric's value, goal status (`met` or `missed`) and heat-map position data. | | `playtest_define` | edit | `metric` (required), `file`, `rationale`, `replace` (optional) | Validates a proposed playtest metric, generates the canonical `playtest.yaml` diff and queues it as a pending review (`Server.PlaytestReviews` / `ApplyPlaytestReview` / `DismissPlaytestReview`) without modifying `playtest.yaml` on disk until reviewed. | | `playtest_report` | edit | `file`, `open`, `read`, `suggestions`, `watchRun` (all optional) | Opens or inspects the editor's Playtest Report screen, loads a `playtest.report.yaml` file, updates the Agent's read summary and actionable suggestions, or opens a 1-based run's saved `.replay.yaml` recording in Play mode. | | `play_frozen_context` | read | `includeImage` (optional, default `true`) | Reads the frozen Play mode context: the captured viewport frame PNG (when `includeImage` is true), the author's question, the saved or 60 s rolling input replay (version 2 YAML) with `windowStartFrame`, live entity states and changes, Play marks (`LastMarksThread`), any detected Output panel panic report, and the current Agent stepping log. | | `play_replay_step` | run | `from_frame`, `to_frame`, `steps` (1–3600, mutually exclusive with `to_frame`), `replay_file` (optional project-relative `.replay.yaml`), `note`, `includeImage` (all optional) | Steps Play mode across `from_frame..to_frame` (up to 3,600 frames per call) using the saved or rolling input replay while keeping Play paused, updating the viewport agent pill (`"agent stepping frames A–B"`) and Agent tab step log (`"Stepped frames A–B with game_loop_step…"`), and optionally returning the resulting paused frame PNG. | | `code_review_propose` | code | `files` (required array of `{path, content, delete?, note?}`), `prompt`, `round`, `summary`, `failure_explanation`, `suspect_file`, `suspect_line`, `play_impact`, `open` (default `true`), `run_checks` (default `true`) | Stages pending Go files (and optional companion YAML/prefab files) in the editor's file-by-file Go review without touching disk, updates an active review in place as Round 2 inside the same turn, and runs `nsgo check` and `nsgo test` against the pending Go build overlay off the UI goroutine. | | `code_review_status` | read | none | Returns the active Go code review state: round, pending YAML and Go files with line deltas and confirmation badges, `nsgo check` / `nsgo test` status and failures, `fixRequested` flag, and any unconfirmed Go files waiting after Keep. | | `code_review_run_checks` | run | `failure_explanation`, `suspect_file`, `suspect_line` (all optional) | Reruns `nsgo check` and `nsgo test` against the pending Go build overlay without modifying files on disk and returns the updated structured check/test status. | | `states_write` | edit | `file` (required), `yaml` (required), `target` (optional), `open` (optional, default `true`) | Validates a `*.states.yaml` sprite state machine against `animclip.ParseStateMachine` (refusing unknown fields, missing target states, or bad expressions without touching the file), writes canonical YAML to `file`, and optionally opens it in the editor's State Machine graph panel on `target`. | | `states_test` | run | `file` (optional), `durationSeconds` (optional, default `8`), `rate` (optional, default `60`), `script` (optional) | Drives a `*.states.yaml` state machine with scripted input through `animclip.SimulateStateMachine` on fixed steps and returns the state transition trace, visited states, stuck-state check and summary (such as `Played 8 s of scripted input · no stuck states`). | | `cutscene_write` | edit | `file` (required), `yaml` (required), `prompt` (optional), `review` (optional), `open` (optional, default `true`) | Validates a `*.cutscene.yaml` file against `cutscene.Parse` (refusing invalid YAML without modifying disk or editor) and opens an interactive Before/After review on the cutscene timeline without overwriting disk until kept (or writes canonical YAML directly when `review: false`). | | `cutscene_scrub` | read | `file` (optional), `timeSeconds` (optional), `view` (optional: `"before"` or `"after"`) | Opens (when `file` is provided) and scrubs the cutscene timeline playhead to `timeSeconds`, returning the posed camera, actor positions/states, active localized dialogue subtitle, and active review counts. | | `tileset_read` | read | `file` (optional) | Reads the open YAML tileset (`*.tileset.yaml`, or `file` relative to the project root, falling back to the active layer's `tilesetFile`) as canonical YAML and structured tile rules (collision flags, shapes, animation, terrain, name, weight, custom properties). | | `tileset_edit` | edit | `ops` (required), `file`, `save` (optional) | Applies tileset operations (`set_tile` for `name`/`solid`/`oneWay`/`flags`/`weight`/`shapes`/`animation`/`terrain`/`neighbors`, `set_property`, `remove_property`, `add_terrain`, `remove_terrain`) to the YAML tileset in one atomic undo step; edits stay unsaved unless `save: true` is passed. | | `refs_find` | read | `file`, `open` (optional) | Finds every usage of a prefab, scene, or project file grouped across scenes (with override counts), prefab variants (`inherits`), data tables (rows), and Go code (`go/parser` string constants marked `notRewritten`), and optionally opens the References screen in the editor. | | `refactor_rename` | edit | `from`, `to` (required), `apply` (optional) | Prepares the safe YAML-only rename review in the editor with exact `-`/`+` line diffs and non-rewritten Go warnings without writing to disk until Keep (or applies through `MoveFile` as one undo step when `apply: true`). | | `tile_query` | read | `layer`, `tileLayer`, `empty`, `tile`, `tiles`, `tileName`, `tileNames`, `rect`, `minCells`, `diagonal`, `includeCells` (all optional) | Queries cells and connected regions or empty pockets on an inline tilemap layer (such as `"an 11 × 5 pocket at columns 2–12, rows 12–16"`), returning bounding rectangles, cell counts, summaries, and coordinates. | | `tile_paint` | edit | `layer`, `tileLayer`, `tile`, `tileName`, `flipH`/`flipV`/`flipD`, `weighted`, `seed`, `noAdjacentDuplicates`, `rect`, `rects`, `cells`, `label`, `review` (default `true`) | Paints explicit cells, inclusive rectangles, or deterministic seeded weighted random tile picks on an inline tilemap layer as one undoable edit, tracked in the active region-based tile edit review by default. | | `tile_autotile` | edit | `layer`, `tileLayer`, `terrain`, `rect`, `rects`, `cells`, `place`, `label`, `review` (default `true`) | Re-edges (or places and re-edges) a region on a layered tilemap using a YAML tileset terrain set's 4-bit cardinal or 8-bit blob autotile rules in one undoable edit, tracked in the active tile edit review by default. | | `tile_erase` | edit | `layer`, `tileLayer`, `rect`, `rects`, `cells`, `label`, `review` (default `true`) | Erases explicit cells or inclusive rectangles on an inline tilemap layer as one undoable edit, tracked in the active tile edit review by default. | | `tile_review_status` | read | `view` (optional: `"before"` or `"after"`), `focus` (optional region ID) | Returns the active tile edit review's grouped regions (`painted`, `replaced`, `erased`), cell counts, bounding rectangles, revert flags, agent steps, and Before/After state; optionally switches view or focuses a region. | | `tile_review_revert_region` | edit | `id` or `index` | Marks one region in the active tile edit review as reverted and updates the live 2D viewport. | | `tile_review_restore_region` | edit | `id` or `index` | Restores a reverted region in the active tile edit review and updates the live 2D viewport. | | `tile_review_keep` | edit | none | Commits all non-reverted regions of the active tile edit review cleanly as one undoable step in `History` and closes the review. | | `tile_review_revert_all` | edit | none | Reverts all pending tile review changes back to the pre-review tilemap and closes the review. | | `object_copy_yaml` | read | `id` (optional) | Serializes an object (local or resolved) in the open scene as canonical `sceneformat` YAML, copies it to the editor clipboard, and shows the copy toast. | | `object_paste_yaml` | edit | `yaml`, `layer` (optional) | Parses canonical `sceneformat` object YAML (or the editor's current clipboard when `yaml` is omitted, capped at 4 MiB) and places a copy with fresh unique IDs on `layer` as one undo step. | | `object_duplicate` | edit | `id` (optional) | Clones an object (and its children) on the same layer with fresh unique IDs as one undo step. | | `object_group` | edit | `ids`, `name` (optional) | Creates a new parent group object and reparents the given object IDs (or the current selection) under it in one undo step while preserving world transforms. | | `object_move_under` | edit | `id`, `parent`, `listCandidates` (optional) | Reparents an object under `parent` (or to the top level of its layer when `parent` is empty) in one undo step while preserving world transform, or lists valid candidate parents without modifying the scene when `listCandidates: true`. | | `object_select_same_prefab` | read | `id` (optional) | Selects every object in the open scene sharing the same `prefab` or instanced `scene` reference as the target object and returns `selectedIds`. | | `object_visibility` | edit | `id`, `hidden`, `locked` (optional) | Sets a local or resolved object's session-only hidden and/or locked state in the editor viewports without modifying the scene file. | | `object_find_usages` | read | `id` (optional) | Finds project-wide references or search matches for an object's instanced scene, prefab, or ID in the open project (opening the Find Usages screen for scene/prefab targets or the Search panel for plain IDs). | | `release_notes_draft` | edit | `markdown`, `kept_reviews` (optional) | Drafts player-facing Markdown release notes from git commits since the last release tag (or initial commit), kept review summaries, and `changelog.d` fragments (or saves validated `markdown`, capped at 256 KiB), writing atomically and exclusively to the file read by `game release -release-notes`. | | `release_review_uploads` | run | none | Opens the Build and Release screen's **Review uploads** confirmation dialog listing every artifact, size, store destination (`itch.io`, `Google Play · internal testing`, `TestFlight`), and version. Never starts an upload: store uploads always require the person's explicit confirmation, whatever the permission profile. | | `agent_turn_get` | read | `turnId`, `includeScene`, `includeImage` (optional) | Reads the latest (or specified) agent turn submitted from the `⌘L` in-place composer or Agent panel, returning the prompt, `skipPlan` flag, selected object IDs and names, open scene path and YAML, and the captured viewport PNG as an image. | | `agent_turn_reply` | edit | `turnId`, `reply`, `status` (optional) | Updates an agent turn's status (`pending`, `running`, `done`, `stopped`) and/or appends the agent's reply text in the editor's Agent panel thread. | | `tasks_list` | read | `include_dismissed` (optional, default `false`) | Lists background agent tasks across Needs you, Running, Ready to review, Queued, and Failed (plus dismissed/completed tasks when `include_dismissed` is `true`), along with active per-object holds and `TaskSummary` badge counts (`dockBadge = needsYou + readyToReview + failed`). | | `tasks_submit` | edit | `prompt` (required), `title`, `mode` (`"queue"` or `"parallel"`, default `"queue"`), `scene` (optional) | Submits a background agent request to the editor's task list: `"queue"` waits behind the active or unreviewed turn and starts only after it is kept or reverted; `"parallel"` starts immediately (up to the concurrency cap) as a separate session with its own numbered overlay. | | `tasks_control` | edit | `action` (required: `"keep"`, `"revert"`, `"dismiss"`, `"stop"`, `"retry"`, `"open"`, `"focus"`, `"allow"`, or `"deny"`), `task_id`, `task_ids` (for bulk dismiss) | Controls background agent tasks: keeps or safely reverts a turn (preserving unrelated parallel/kept edits), bulk-dismisses Ready to review or Failed tasks without reverting kept work, stops or retries a task, focuses/opens a task's scene (confined to project root), or resolves a permission prompt. | | `project_context` | read | none | Returns the shared project context the agent reads before every request: `brief.yaml` (canonical YAML, parsed fields, missing sections/gaps, and structured playtest targets) and `AGENTS.md` (plain Markdown project rules and rule count), plus any pending document reviews. | | `brief_edit` | edit | `yaml` or structured fields (`pitch`, `genre`, `tags`, `platforms`, `artDirection`, `toneAndAudio`, `feel`), `summary`, `rationale` | Strictly validates a proposed `brief.yaml` edit (refusing unknown fields with line numbers) and queues a reviewable `DocReview` diff without touching disk until the person keeps it. | | `rules_edit` | edit | `markdown` or `appendRule`, `summary`, `rationale` | Proposes an edit or appended bullet rule for `AGENTS.md` as a reviewable `DocReview` diff without touching disk until the person keeps it. | | `history_list` | read | `author` (`"all"`, `"you"`, `"agent"`), `limit` (optional) | Lists the editor's unified History timeline of manual edits, agent turns, and saved points, newest first. | | `permissions_draft` | read | `request` (optional), `rules` (required) | Opens a You-only permissions draft card with nothing ticked by default; never modifies `permissions.yaml` directly. | | `game_delete_file` | delete | `file` (required), `reason` (optional) | Turned off by default in **Settings › Tools** (not offered to connected clients until enabled). When enabled, proposes deleting a project file in the Review changes panel with its line count and scene usages without touching disk until confirmed (refusing You-only files, symlinks, `.git/**`, `game.yaml`, open scene tabs, and >1 MiB files). | | `datatable_review_propose` | edit | `files` (required), `prompt`, `checks` (optional) | Validates one or more version-1 YAML data table files against `datatable.ParseDocument` (and any registered Go row type) and opens the row-by-row Data Table review screen with old → new, `Δ%`, per-record Revert/Restore, and optional named agent check figures without modifying disk until Keep. | | `datatable_review_checks` | edit | `checks` (required) | Attaches or refreshes named agent check figures (`label`, `value`, `before`, `basis`) on the active Data Table review and clears `checksOutOfDate` after the person reverts, edits, or reorders records. | | `datatable_review_status` | read | `file` (optional) | Reports the active Data Table review's files, kept/reverted/user-edited counts, active record states, attached check figures, and whether `checksOutOfDate` is true. | | `sketch_read` | read | `includeImage`, `scale` | Reads the active or sent viewport sketch marks (Pen, Arrow, Box, Text) with sequential badge numbers, exact scene coordinates, labels, prompt, hold state, and an optional rendered PNG of the viewport with numbered marks overlaid. | | `sketch_reading` | edit | `summary`, `items`, `assumptions` | Posts the agent's restatement card (`"I read your sketch as: …"`) and assumptions for a sent viewport sketch; while a sent sketch awaits confirmation, `scene_edit` and other mutating scene tools hold cleanly until the person chooses **Go ahead**, **Correct a mark**, or replies in words. | | `plan_propose` | read | `title`, `steps` (required); `id`, `turnId`, `prompt`, `summary`, `estimate`, `reason`, `files`, `questions`, `wait` (optional) | Proposes a structured plan with clarifying questions (with visual previews and ghost/title overrides), editable numbered steps, planned Scene Tree nodes, and agent-violet viewport ghosts before modifying any scene or file. Waits (when `wait` is not `false`) until the person approves (`Approve` or `Just do it`) or stops, returning the structured `AgentPlanDecision` with answers, edited step counts/notes, and removed steps. | | `plan_step_update` | read | `step`, `status`, `complete` (optional) | Updates an approved plan step's progress (`pending`, `running`, `done`, `failed`, `skipped`) or completes the plan so the turn's review lists every step and marks which were done, and reports whether the person pressed Stop. | Every tool registered on the editor's MCP server can be turned on or off per computer in **Settings › Tools** (`Editor.SetMCPToolEnabled`): disabling a tool removes it from the server's advertised tool list (`tools/list_changed`) and returns a readable refusal if called. Outbound content categories in **Settings › Usage and privacy** (**WHAT MAY LEAVE THIS COMPUTER**: Scene and data files, Viewport images, Go source code, Art and audio files) are enforced for every connected agent across all tools (including symlink-resolved file paths) and all resources (`editor://scene`, `editor://selection`, `editor://agent/turn`, `editor://brief`, `editor://rules`, `editor://context`), refusing calls with the reason whenever the requested content kind is switched off. Additional MCP servers configured in **Settings › Tools** (starting with `nsgo-game` for the running game via `go tool nsgo mcp`) are synced into `.mcp.json` and `.codex/config.toml` via `editormcp.InstallWithServers`. The edits `scene_edit` takes, each an object with `op`: | `op` | Fields | Editor method | | --- | --- | --- | | `add` | `object` (as the scene file writes it), `layer`, `parent` | `PlaceObject`, then `ReparentObject` under `parent` | | `remove` | `id` | `DeleteObject` | | `move` | `id`, `x`, `y` | `MoveObject` | | `set` | `id`, `fields` | the object's setters: `id`, `name`, `x`, `y`, `z`, `rotation`, `scaleX`, `scaleY`, `alpha`, `originX`, `originY`, `flipX`, `flipY`, `sprite`, `material`, `posZ`, `rotX`, `rotY`, `rotZ`, `scaleZ`, `depth`, `mesh` | | `set` | `id`, `component`, `fields` | `SetComponentField` for each field | | `add_component` | `id`, `component`, `fields` | `AddComponent`, then `SetComponentField` | | `remove_component` | `id`, `component` | `RemoveComponent` | | `set_property`, `remove_property` | `id`, `key`, `value` | `SetProperty`, `DeleteProperty` | | `reparent` | `id`, `parent`, `index` | `ReparentObject` | | `move_to_layer` | `id`, `layer`, `index` | `MoveObjectToLayer` | An `add`'s object is read by the scene format's own reader with the editor's component registry, so it is refused as opening the file would refuse it. When the editor refuses any edit of a call, none of them applies: the scene, its undo history and its file on disk stay as they were, and the tool error names the file, the edit, the object, the component and field, and the fix, as in `scene_edit: scenes/room.scene.yaml: edit 2 (set) on object "hero" component "body" field "sped": unknown field (registered: friction, layer, solid, speed); use a component and fields the project registers, as the message lists them. Nothing was changed.` The structured result holds the same as an `editormcp.EditError`. When an agent turn is active (`turn_start` through `turn_end`, or started from the editor's Agent panel), every edit made through `scene_edit`, `object_set_field`, and `file_edit` across scenes, prefabs, data tables, `game.yaml`, and clips is staged in memory into that one pending turn without writing to disk. The editor derives the turn's changes structurally by diffing each touched file against its pre-turn state (carrying any `why` explanation supplied on the tool call), lets the person revert or restore individual changes or whole files while pending, and commits all remaining changes across every touched file as one `AuthorAgent` undo step on **Keep** (or restores every touched file byte-for-byte on **Revert**). `turn_status` reports the derived changes and which ones the person reverted; by design there is no MCP tool that keeps or reverts an agent turn. Outside a turn, each `scene_edit` or `object_set_field` call remains one ordinary undo step on the open scene. While the editor's automatic saving is failing (for example into a read-only folder or a full disk), every tool result returned by `editormcp` appends a warning stating that edits are not on disk along with the failure reason (and attaches `nsgo.dev/editsNotOnDisk`, `nsgo.dev/saveError`, and `nsgo.dev/saveWarning` in `_meta`, plus `SaveWarning` on `Result` / `AutomationResult`) until a save succeeds, so the agent does not build on edits that have not landed on disk. ### The change stream The server exposes six resources: `editor://scene` (the open scene's YAML as the editor holds it), `editor://selection` (the selection as `selection_get` reports it in JSON), `editor://agent/turn` (the latest request started from the `⌘L` in-place composer or Agent panel: JSON metadata including `selectionIds`, `scenePath`, `sceneYaml`, and `skipPlan`, plus the captured `image/png` viewport blob), `editor://brief` (the open project's `brief.yaml` as canonical YAML), `editor://rules` (the open project's `AGENTS.md` as plain Markdown), and `editor://context` (the combined JSON project context returned by `project_context`). A client that subscribes to them is notified of each change, and the notice's `_meta` says who made it, `"nsgo.dev/by": "agent"` for a tool call and `"person"` for the editor's own controls, with the editor's revision under `"nsgo.dev/revision"` (and `"nsgo.dev/turnId"` / `"nsgo.dev/skipPlan"` on `editor://agent/turn` notices). A burst of changes may come as one notice. ### Adding tools The tools are a registry that other parts of the editor join with `Server.AddTool`, so that every action with a button or a shortcut has a tool. A `Tool` has a name, a description, a JSON Schema for its arguments, an `Action` (`ActionRead`, `ActionEdit`, `ActionCreate`, `ActionDelete`, `ActionRun`, or `ActionCode`, which the editor's permission rules decide on), an optional `Target` resolver, and a handler. The handler runs on one of the server's goroutines and reaches the editor with `Call.Editor`, which runs a function on the editor's goroutine and waits for it, so a tool may wait for work done elsewhere and return an image. Clients are told the tool list changed. ### Permissions enforcement Before running any mutating or running tool call (every action other than `ActionRead`), `editormcp.Server` evaluates the call against the open project's `permissions.yaml` (`editor.PermissionsFile`, defaulting to the `Balanced` profile when the file is absent) from top to bottom using first-match-wins rules: - **`allow`**: runs the tool immediately. - **`ask`**: invokes `Options.OnPermissionAsk` when configured, or queues a pending permission request on `Editor` (`PendingPermissionRequests`) and returns a structured `*editormcp.PermissionError` with `decision: "ask"` without running the tool. Answering **Always** (`PermissionAnswerAllowAlways` / `Editor.ApproveAlwaysPermission`) inserts an `allow` rule ahead of the matching rule, persists `permissions.yaml`, and shows the `"Always permission rule saved"` toast with **Show** and **Undo**. - **`deny`**: records a blocked step on `Editor` (`BlockedPermissions`), returns a structured `*editormcp.PermissionError` naming the exact rule index, rule summary, base profile, and Settings link (for example `"Settings › Permissions · rule 7 of 7"`), and never calls the underlying tool handler. Enforcement is fail-closed: `Server.AddTool` refuses empty or unrecognized `Action` values; a corrupt or unreadable `permissions.yaml` denies mutating/running calls until fixed; file targets are canonically cleaned and symlink-resolved against the project root before rule matching (refusing absolute paths, `..` traversal, and symlink escapes, and matching case-insensitively on macOS/Windows); and multi-target tools (`refactor_rename` checking `from`, destination `to`, and rewritten referencing files when `apply: true`; `merge_finish` checking both the resolved scene edit and `git merge` run) apply the strictest verdict (`deny > ask > allow`). Rules govern the editor's MCP server tools only. Files modified directly by an external agent outside MCP continue to surface through the editor's disk watcher. ```go s := editormcp.New(ed, editormcp.Options{Run: cx.Post}) _ = s.AddTool(editormcp.Tool{ Name: "scene_name", Action: editormcp.ActionRead, Handler: func(ctx context.Context, c *editormcp.Call) (*editormcp.Result, error) { var name string err := c.Editor(ctx, func(ed *editor.Editor) error { name = ed.Doc.Name; return nil }) return &editormcp.Result{Text: name}, err }, }) _ = s.Open() ``` `Options.Run` hands functions to the editor's goroutine (`cx.Post` for an editor in a window); without it the server runs them on the caller's goroutine one at a time, for an editor no window drives. `Server.Connect` serves one session on any MCP transport, as a test does with `mcp.NewInMemoryTransports`. ### Why its own server NSGo's `automation` registers app tools only in `nsgo dev -automation` and test builds, and `nsgo mcp` reaches only the app that `nsgo dev -automation` runs; an editor is an ordinary build. An app tool's handler also runs synchronously on the graph goroutine (nsgo-dev/nsgo#2342), which cannot wait for a project check without holding the editor, and returns JSON only, so a screenshot reaches the agent as base64 text rather than an image (nsgo-dev/nsgo#2343). The editor's server uses the official MCP Go SDK, which NSGo's own `nsgo mcp` is built on, so its tools wait off the editor's goroutine and `viewport_image` returns a real image. `Server.RegisterAutomation` still offers the same tools to `nsgo mcp` for an editor run under `go tool nsgo dev -automation`, each running on the graph goroutine from start to end and returning an `AutomationResult` with the PNG in base64. ## Editor MCP You-only rule and proposed deletions (#1015) In `pkg/editor/editormcp`, the editor's MCP server enforces two non-bypassable trust boundaries regardless of the active permission profile (`Cautious`, `Balanced`, or `Autonomous`): - **You-only refusal (`*editormcp.YouOnlyError`)**: Every non-read tool call (built-in or registered via `Server.AddTool`) is checked before its handler runs across explicit argument paths, derived targets (including bare-stem `refactor_rename` and `release_notes_draft`), and open document paths, and refused if any target resolves to `permissions.yaml`, `.nsgo/permissions.yaml`, `tools.yaml`, `mcp.yaml`, `models.yaml`, `usage.yaml`, or `Editor.SettingsPath`. - **`permissions_draft`**: Submits a You-only draft card (`Editor.SubmitPermissionsDraft`) with zero rules ticked by default. It never modifies `permissions.yaml` directly; only explicit person ticks + **Apply** can persist changes. - **`game_delete_file`**: Refuses You-only files, symlinks, `.git/**`, `game.yaml`, open scene tabs, and >1 MiB files; for ordinary project files it proposes a deletion in the Review changes panel with line count and scene usages (`Editor.ProposeFileDeletion`) without deleting the file on disk. **Keep all** never deletes pending files; confirming deletes via a checkpoint command that `⌘Z` restores byte-for-byte. --- Source: https://game.nsgo.dev/docs/modding/ # modding `game/modding` loads and runs capability-sandboxed TSX/JS game mods on top of NSGo's `tsx` runtime, with `mod.yaml` manifest validation, topological dependency resolution, fault isolation, persisted enable/disable state, and a `"game"` module API. ```go import "github.com/nsgo-dev/game/pkg/modding" ``` ## Mod manifest (`mod.yaml`) and capabilities Each mod lives in its own directory with a `mod.yaml` (`ModManifest`) and an entry script (`mod.tsx` or `mod.js`). The sample mod in [`pkg/modding/testdata/mods/boss-rush/`](https://github.com/nsgo-dev/game/blob/main/pkg/modding/testdata/mods/boss-rush/) is the manifest and script shown on this page, and the package's tests load it: ```yaml manifestVersion: 1 id: com.example.boss-rush name: Boss Rush version: 1.2.0 author: Example Studio description: Spawns a slime every five seconds and shows a HUD badge while the rush runs. entry: mod.tsx gameVersion: '>=0.2.0' capabilities: [readState, spawnEntity, emitEvent, ui] ``` | Field | Required | Meaning | | --- | --- | --- | | `manifestVersion` | yes | Schema version of the file, currently `1` (`modding.ManifestVersion`) | | `id` | yes | Unique ID of letters, digits, `.`, `-` and `_`, such as `com.example.boss-rush` | | `name` | yes | Human-readable name | | `version` | yes | The mod's own semantic version (`MAJOR.MINOR.PATCH[-prerelease]`) | | `author`, `description` | no | Free text | | `entry` | yes | Entry script relative to the mod directory: `.tsx`, `.ts`, `.jsx`, `.js` or `.mjs` | | `gameVersion` | no | Constraint on the host's `ManagerOptions.GameVersion`, such as `'>=0.2.0'` | | `capabilities` | no | Capability names the mod requests | | `dependencies` | no | Map of mod IDs to version constraints, such as `com.example.core-lib: ^1.0.0` | Constraints accept `*`, `=`, `>=`, `>`, `<=`, `<`, `^` and `~`, joined by spaces or commas. Quote a value that starts with `>` or `*` (`'>=0.2.0'`, `'*'`), since YAML reads those characters at the start of a value as a folded block and an alias. The format is strict: `ParseManifest` refuses unknown or misspelled fields, duplicate keys, a second YAML document, unknown or repeated capability names, and a `manifestVersion` that is missing, unsupported or not written as the plain integer `1`, all as `ErrInvalidManifest`. `EncodeManifest` writes a manifest in one canonical form (fields in the order above, capabilities in the order listed below, dependencies sorted by ID in byte order), so a file already in that form is unchanged by a read and a write. A `ModManifest` built in Go may leave `ManifestVersion` at 0: `Validate` and `ResolveOrder` accept it, and `EncodeManifest` writes `manifestVersion: 1`. `Manager` reads only `mod.yaml`; a mod directory that still has only the old `mod.json` is refused with a message asking for `mod.yaml`. Capabilities are bitflags on `Capability`: `CapReadState` (`readState`), `CapWriteState` (`writeState`), `CapSpawnEntity` (`spawnEntity`), `CapEmitEvent` (`emitEvent`), `CapUI` (`ui`), `CapAudio` (`audio`), and `CapStorage` (`storage`). Calls outside a mod's granted capabilities fail with `*PermissionError` without crashing the host. NSGo gives every sandbox the `"nsgo"` module's `Storage`, in a partition of its own, with no capability to withhold it. A mod without `CapStorage` therefore gets a partition quota of one byte, the smallest NSGo accepts, so it can keep at most one entry whose key and value total one byte (such as `setItem("a", "")`) and every larger `Storage.setItem` call fails; reading still sees what the partition already holds, such as what the mod wrote while it had the capability. ## The `"game"` TSX module Mods import `"game"` (`GameModule`) to hook fixed simulation steps, emit or listen for events, spawn prefabs, read/write scoped state, play audio, persist per-mod storage, and mount TSX UI panels. Export TypeScript definitions for mod authors with `modding.WriteGameAPIDTS("game.d.ts")`. ```tsx import { Text, View } from "nsgo"; import { onStep, onEvent, spawn, emit, getState, mountPanel, log } from "game"; let elapsed = 0; let wave = 0; onStep((dt) => { elapsed += dt; if (elapsed >= 5) { elapsed = 0; wave++; spawn("slime", 120, 80, { hp: 30 }); emit("boss-rush:wave", { wave }); } }); onEvent("boss_defeated", (payload) => { log("Defeated:", payload?.name, "score:", getState("score")); }); mountPanel("boss-timer", () => ( Boss Rush Active ), "hud"); ``` ## Managing mod lifecycle in Go (`Manager`) Create a `Manager` on your NSGo scope with a `GameBridge` connecting mod actions to your game engine, discover mods from disk or `io/fs.FS`, and step them from `game.Loop`: ```go mgr := modding.NewManager(cx, modding.ManagerOptions{ StorageKey: "mods", GameVersion: "0.2.0", Bridge: modding.GameBridge{ OnSpawn: func(req modding.SpawnRequest) (string, error) { return world.SpawnPrefab(req.Prefab, req.X, req.Y, req.Props) }, OnPlaySound: func(req modding.SoundRequest) error { return audioMgr.Play(req.Name, req.Volume, req.Rate, req.Loop) }, }, }) defer mgr.Close() if _, err := mgr.Discover("mods"); err != nil { return err } _ = mgr.LoadAll() // validates manifests, resolves topological dependency order, isolates faults // In game.Loop.Update: mgr.Step(dt) // Render mod-mounted HUD panels in your NSGo view tree: hudPanels := mgr.PanelsView("hud") _ = hudPanels ``` Control individual mods at runtime with `Enable`, `Disable`, `Install`, `InstallFS`, `Uninstall`, `Load`, `Unload`, `Reload`, `SetGrant`, `Emit`, `Call`, `List`, `Info`, and `Logs`. A panicking or throwing mod transitions to `StateFailed` while the host game and sibling mods keep running. `Reload` validates the updated `mod.yaml` (syntax, ID, game version and dependencies) before it unloads anything, so a broken manifest returns an error and the version already loaded keeps running. `SetGrant` on a loaded mod takes effect at once: the `"game"` module checks the new capabilities from the next call, revoking `CapUI` removes the panels the mod mounted, and when the grant changes `CapAudio` or `CapStorage`, which the sandbox itself enforces, the mod is unloaded and loaded again in a sandbox built for them, which runs its entry script again. `Close` unloads every mod, after which `Info` reports each as `StateDiscovered` (or `StateDisabled`), and an unsubscribe function a mod kept from `onEvent` or `onStep` does nothing once the mod is unloaded. Browsers cannot isolate a mod from the page: a mod running on the web can use the page's own APIs (`XMLHttpRequest`, `WebSocket`, `localStorage`) whatever its capabilities say. Loading a mod on the web therefore fails with `ErrWebUnisolated` unless you set `ManagerOptions.WebUnisolated`, which you should only do for mods you trust as much as your own code. Other targets isolate mods and ignore the option. ## Steam Workshop (`Workshop`) `Workshop` connects Steamworks `ISteamUGC` to `Manager` so authors can publish mods and custom levels and subscribed players automatically download, validate, install, update, and remove them. ### Workshop metadata (`workshop.yaml`) Publishing writes a deterministic `workshop.yaml` (`WorkshopMetadata`) beside `mod.yaml` so subsequent publishes update the same Steam Workshop item instead of creating duplicates: ```yaml version: 1 appId: 480 publishedFileId: 123456789 title: Boss Rush description: Spawns a slime every five seconds and shows a HUD badge while the rush runs. tags: [bosses, gameplay] visibility: public preview: preview.png ``` | Field | Required | Meaning | | --- | --- | --- | | `version` | yes | Schema version of `workshop.yaml`, currently `1` (`modding.WorkshopMetadataVersion`) | | `appId` | yes | Steam application ID that owns the Workshop item | | `publishedFileId` | no | Assigned Steam Workshop `PublishedFileID` (populated automatically on first publish) | | `title`, `description` | no | Override `mod.yaml`'s `name` and `description` on Workshop | | `tags` | no | Steam Workshop tags (encoded sorted in byte order; empty or duplicate tags are refused) | | `visibility` | no | One of `public`, `friendsOnly`, `private`, or `unlisted` (defaults to `public`) | | `preview` | no | Relative slash-separated path inside the mod directory to a preview image | Like `mod.yaml`, `ParseWorkshopMetadata` refuses unknown fields, duplicate keys, trailing YAML documents, invalid visibility/tag/preview values, and a missing or non-literal `version: 1` as `ErrInvalidWorkshopMetadata`. `EncodeWorkshopMetadata` emits canonical 2-space YAML with no timestamps or volatile fields so round trips are byte-for-byte stable. ### Publishing and syncing subscribed items Use `NewSteamWorkshop` on macOS, Linux, and Windows to bind `libsteam_api.dylib`, `libsteam_api.so`, or `steam_api64.dll` via `purego` (no CGo). When the Steamworks library or running Steam client is absent—or on web, iOS, and Android—`NewSteamWorkshop` returns `ErrWorkshopUnavailable`. For tests and offline tools, use `NewMemoryWorkshop`, which simulates multi-user publishing, querying, subscribing, downloading, and updates on disk. ```go backend, err := modding.NewSteamWorkshop(modding.SteamWorkshopOptions{}) if err != nil { // Fall back cleanly when Steam is not running (errors.Is(err, modding.ErrWorkshopUnavailable)). return err } defer backend.Close() ws := modding.NewWorkshop(backend, mgr, modding.WorkshopOptions{ AppID: 480, AutoLoad: true, }) // Author: validate mod.yaml and publish or update the Workshop item. res, err := ws.Publish(ctx, "mods/boss-rush", modding.PublishOptions{ Tags: []string{"gameplay", "bosses"}, Visibility: modding.VisibilityPublic, Preview: "preview.png", ChangeNote: "Initial release", }) if errors.Is(err, modding.ErrWorkshopLegalAgreementRequired) { // Item ID is already saved in workshop.yaml; prompt author to open res.LegalAgreementURL. _ = res.LegalAgreementURL } // Player: query, subscribe, and reconcile Manager with all subscribed Workshop items. if _, err := ws.SyncSubscribed(ctx); err != nil { return err } ``` - `Publish` validates `mod.yaml`, entry script, preview path, and `workshop.yaml` before creating or updating any Steam Workshop item. When Steamworks reports that the author must accept the Steam Workshop Subscriber Agreement, `Publish` still saves `publishedFileId` to `workshop.yaml` and returns `PublishResult{NeedsLegalAgreement: true, LegalAgreementURL: WorkshopLegalAgreementURL}` alongside `ErrWorkshopLegalAgreementRequired`. - `SyncSubscribed` unloads and uninstalls items that were unsubscribed, downloads missing or outdated items, checks path confinement (`WorkshopOptions.AllowedRoots` and escaping symlinks via `ErrWorkshopUnsafePath`), and installs valid mods in topological dependency order while isolating failures in broken sibling items. `InstallSubscribed` installs a single subscribed item on demand. --- Source: https://game.nsgo.dev/docs/navbake/ # navbake `game/navbake` bakes the 2D navigation meshes that `ai.NavMesh` searches: from a level's outline with concave obstacles and holes, or from a tilemap's solid cells, shrunk by each agent type's radius and divided into convex polygons. A baked mesh saves to a versioned YAML file beside the level, and `Draw` shows it as a debug overlay. ```go import "github.com/nsgo-dev/game/pkg/navbake" ``` `ai.BuildNavMesh` takes convex polygons that a game has already cut its level into, and its paths run along the polygons' corners. `navbake` does the cutting, and keeps the paths an agent's radius away from every wall, as Godot does when it bakes a navigation polygon and Recast does for 3D meshes. ## Baking from polygons A `Source` holds the walkable `Outlines`, such as a room's walls, and the `Obstacles` inside them, such as pillars, crates and pits. Polygons may be concave, may overlap each other or the outline, and may be wound either way: a point is walkable when it is inside the outlines and outside the obstacles under the nonzero winding rule. ```go src := navbake.Source{ Outlines: [][]core.Point{{{X: 0, Y: 0}, {X: 200, Y: 0}, {X: 200, Y: 150}, {X: 0, Y: 150}}}, Obstacles: [][]core.Point{ {{X: 40, Y: 40}, {X: 60, Y: 40}, {X: 60, Y: 60}, {X: 40, Y: 60}}, {{X: 120, Y: 30}, {X: 170, Y: 30}, {X: 170, Y: 40}, {X: 130, Y: 40}, {X: 130, Y: 90}, {X: 120, Y: 90}}, }, } mesh, err := navbake.Bake(src, navbake.Agent{Name: "guard", Radius: 6}, navbake.Options{}) if err != nil { return err } nav := mesh.NavMesh() // an *ai.NavMesh path, ok := nav.FindPath(from, to) ``` `Bake` inflates the obstacles, and shrinks the outline, by the agent's `Radius`, rounding every convex corner with a polygon that holds the true circle; triangulates the walkable area left over with a constrained Delaunay triangulation; and merges the triangles into convex polygons. The path `FindPath` finds on the result keeps at least `Radius` from every obstacle and outline edge, and is at most a little longer than the true shortest path for a round agent, around the polygonal corners. A radius of 0 gives the walkable area itself. The bake snaps every point to a grid of `Options.Precision` world units (`DefaultPrecision`, 1/256, when zero) and decides every geometric question exactly on that grid, so obstacles that touch, overlap or share edges never break it, and the same input gives the same polygons on every platform. Coordinates, and the obstacles once grown by an agent's radius, must stay within 2^24 grid steps of the origin, 65536 world units at the default precision, because that is the largest grid the mesh's `float32` coordinates hold exactly; a coarser precision allows more, and a bake past it is an error. A gap or a sliver of an obstacle thinner than one grid step may close or vanish, so pick a precision finer than the smallest feature that matters. ## Several agent types Agents of different sizes need different meshes: a narrow gap a rat slips through stops an ogre. `BakeAll` bakes one mesh per `Agent`, in order, from one source, sharing the work that does not depend on the radius; each `Agent` needs a unique `Name`, which the mesh keeps. ```go meshes, err := navbake.BakeAll(src, []navbake.Agent{ {Name: "rat", Radius: 2}, {Name: "ogre", Radius: 12}, }, navbake.Options{}) ``` ## Baking from a tilemap `FromTilemap` turns a `tilemap.Tilemap` into a `Source`: the map's area is the outline and every cell whose flags match the mask, as `Tilemap.FlagsAt` combines them across tile layers, is an obstacle. Tiled tiles with a `solid` property and LDtk IntGrid walls already carry `tilemap.TileSolid`. ```go m, err := tilemap.LoadTiled(data, tilemap.TilesetLoader{}) if err != nil { return err } src, err := navbake.FromTilemap(m, tilemap.TileSolid) if err != nil { return err } meshes, err := navbake.BakeAll(src, agents, navbake.Options{}) ``` The cells are the shapes the map's `Orientation` gives them, in world space: squares on an orthogonal map, diamonds on an isometric or staggered one and hexagons on a hexagonal one, so the mesh lines up with the tiles as drawn. Neighbouring solid cells merge into one obstacle, two that touch only at a corner leave no gap a round agent fits through, and an open pocket walled in by solid cells stays walkable but unreachable from outside. ## Mesh files A `Mesh` is the baked result: the format version, the agent's name and radius, and the convex polygons, each a list of `[x, y]` vertices in world units, counter-clockwise in a y-up frame (clockwise on a y-down screen) from its lowest vertex. ```yaml version: 1 agent: small radius: 2 polygons: - [[2.0078125, 2.0078125], [37.992188, 2.0078125], [37.992188, 17.992188], [19.601562, 17.992188]] - [[2.0078125, 2.0078125], [19.601562, 17.992188], [18.863281, 18.296875]] - [[2.0078125, 2.0078125], [18.863281, 18.296875], [18.296875, 18.863281]] - [[2.0078125, 2.0078125], [18.296875, 18.863281], [17.992188, 19.601562]] - [[2.0078125, 2.0078125], [17.992188, 19.601562], [17.992188, 37.992188], [2.0078125, 37.992188]] ``` `Mesh.Encode` writes it with the fields in a fixed order and one polygon per line, each coordinate in the shortest form that reads back as the same `float32`; `Parse` reads it, refusing unknown fields, another version, invalid off-mesh links, and polygons that are not convex, are wound clockwise, have fewer than three vertices or a coordinate that is not finite. Optional point-to-point off-mesh connections (jumps, drops, ladders, teleports) can be carried in `Source.Links` and stored under `links:` (`id`, `start: [x, y]`, `end: [x, y]`, `radius`, `bidirectional`, `cost`, `area`, `flags`, `userData`). Baking the same input twice gives byte-identical files, and loading a file and saving it again changes nothing, so a game can bake its meshes in a build step, commit them beside its levels and review each change as a diff. `Mesh.NavMesh` builds the `ai.NavMesh` to search at run time, registering all stored `Links` automatically without baking again. For runtime dynamic obstacles and per-tile rebuilding, call `Mesh.TiledNavMesh(tileSize)` to build an `*ai.TiledNavMesh`. ## Debug drawing `Draw` fills every polygon, outlines its edges and strokes the portals between neighbouring polygons, the edges a path crosses, each in its own color, under whatever camera transform the `core.Drawing` already has; a transparent color skips that layer. `Mesh.Portals` returns the portals themselves. `Mesh.Portals` buckets the polygons on a grid, so it takes time near linear in their number, but `Draw` still finds the portals on every call; a game that draws a large mesh every frame can keep the `Portals` result and stroke it itself. ```go navbake.Draw(d, mesh, core.RGBA(0x40a0ff, 0.2), core.RGB(0x2060c0), core.RGB(0xffc040), 1) ``` The CryptQuest sample game bakes its crypt's mesh with `FromTilemap` and draws it when `N` is pressed. ## Authoring navigation regions in scenes You can also author walkable and obstacle `navregion2d` polygon components directly in `*.scene.yaml` files (with optional tilemap collision subtraction) and edit them with polygon vertex handles, a live viewport overlay, and the **Test Path** tool in [`game/editor`](https://game.nsgo.dev/docs/editor/#built-in-2d-navigation-region-components-888). `sceneformat.Build` runs `navbake.Bake` automatically into `BuiltScene.NavBake2D` and `BuiltScene.NavMesh2D` so the editor's path preview and the game share the same `ai.NavMesh`. --- Source: https://game.nsgo.dev/docs/navbake3d/ # navbake3d `game/navbake3d` bakes 3D navigation meshes from a level's geometry, as Recast, Godot's `NavigationRegion3D` and Unity's `NavMeshSurface` do, so a 3D game no longer authors the convex polygons of a [world3d](https://game.nsgo.dev/docs/world3d/) `NavMesh` by hand. It reads the level from glTF models, scene files, terrain heightmaps, `GridMap`s and physics colliders, bakes one mesh per agent type, and saves them in a versioned YAML file that a scene names. For a 2D level, [navbake](https://game.nsgo.dev/docs/navbake/) bakes `ai.NavMesh` polygons instead. ```go import "github.com/nsgo-dev/game/pkg/navbake3d" ``` ## Baking a level Collect the level's triangles in a `Geometry`, then `Bake` it for each agent type: ```go var g navbake3d.Geometry g.AddGLTF(levelModel, math3d.Mat4Identity(), 1) // a *gltf.Document g.AddHeightmap(terrain, 1) // a *world3d.Heightmap g.AddPhysicsWorld(physicsWorld, navbake3d.LayerAll) // static physics3d colliders file, err := navbake3d.Bake(&g, navbake3d.Settings{CellSize: 0.2, CellHeight: 0.1}, []navbake3d.AgentType{ {Name: "humanoid", Radius: 0.4, Height: 1.8, MaxSlope: 45, MaxClimb: 0.4}, {Name: "rat", Radius: 0.1, Height: 0.3, MaxClimb: 0.1}, }) if err != nil { return err } data, err := navbake3d.Encode(file) // write it to levels/level1.navmesh.yaml ``` The bake follows Recast's pipeline: 1. It rasterizes the triangles into a heightfield of solid spans, columns `CellSize` wide and deep and `CellHeight` tall. 2. It keeps the tops of spans whose triangle is no steeper than the agent's `MaxSlope`, lets the agent step onto a low obstacle within `MaxClimb`, and drops tops at a ledge deeper than `MaxClimb` and tops with less than `Height` of clearance, so nothing is walkable under a ceiling lower than the agent. 3. It links each walkable top to its neighbours an agent can step to and erodes the walkable area by `Radius`, so the mesh keeps the agent's radius from walls and ledges. 4. It partitions the walkable area into monotone regions and drops islands smaller than `MinRegionArea`. 5. It traces each region's outline and simplifies it: edges between two regions keep only the corners where the neighbouring region changes, so both sides share them, and walls stay within `MaxSimplificationError` of the cells and no longer than `MaxEdgeLength`. 6. It triangulates each outline and merges the triangles into convex polygons of at most `MaxVertsPerPoly` vertices. 7. It adds height detail: samples every `DetailSampleDistance`, at least one `CellSize` (a zero takes 1.8 or the cell size when that is larger), along each polygon's edges and inside it, and adds the worst-fitting ones as vertices of the polygon's triangles until the triangles are within `DetailSampleMaxError` of the ground, so polygons follow terrain and stairs. Stairs whose risers are within `MaxClimb` bake into a ramp through the steps' edges, which the agent climbs; taller steps leave the floors above them unreachable. A bridge with `Height` of clearance under it bakes into a deck and a floor beneath it that are not linked, and a path between them goes round by the stairs or ramp that join them. A zero field of `Settings` or `AgentType` takes its default (`DefaultCellSize`, `DefaultAgentRadius` and so on), and the baked file records the value used. `BakeMesh` bakes one agent type. Baking the same geometry with the same settings always writes the same bytes, on any CPU architecture, so the file belongs in version control beside its scene and a bake that changes nothing shows no diff. Go lets a compiler fuse a multiply and an add into one rounding, which arm64 does and amd64 does not, so the bake rounds every product explicitly, and a test compares a bake of a reference level with a committed file on Linux x86 and macOS arm64. Geometry the game computes before adding it, such as node transforms from `math3d` or terrain from `world3d`, is outside the bake and can itself differ in a coordinate's last digit between architectures. ### Precision Walls, floors and the erosion are measured in whole cells, so the mesh keeps the agent's radius from a wall to within one cell, and heights are rounded up to a whole `CellHeight`. A smaller `CellSize` and `MaxSimplificationError` follow the level more closely and take longer to bake; a level of more than `MaxCells` cells is refused, asking for a larger `CellSize`, and so is an agent whose height, climb or radius spans more cells than the heightfield can hold. ## Level geometry A `Geometry` holds world-space triangles, each on layers a `Settings.LayerMask` selects from; a layer of 0 counts as every layer. Triangles wind counter-clockwise seen from their front, as glTF's and this module's meshes do: a triangle facing up is a floor, and every triangle is solid whatever way it faces. | Method | Adds | | --- | --- | | `AddTriangle`, `AddMesh` | Triangles, or an indexed triangle list at a world matrix; a mirroring matrix flips the winding back | | `AddPrimitive` | Built-in 3D primitive shapes (`box`, `plane`, `sphere`, `capsule`, `cylinder`) at a world matrix; closed shapes are baked as solids and `plane` as a surface | | `AddGLTF` | Every mesh of a glTF document's default scene at its node's world transform; strips and fans are expanded, points and lines skipped | | `AddScene` | Every enabled `scene3d` node outside a disabled node's subtree whose `Layer` shares a bit with the mask, its triangles from a `NodeMesh` (`ColliderMesh` reads a `*scene3d.MeshCollider`) | | `AddSceneFile` | A [scene file](https://game.nsgo.dev/docs/editor/): resolves instanced and inherited scenes, skips screen-space layers and dynamic or kinematic `body3d` objects (and their descendants), adds glTF models (respecting `modelNode` and `modelMesh`), built-in `mesh` primitives, and static non-trigger `collider3d` shapes, and extracts every authored `nav_link` off-mesh connection | | `AddOffMeshLink` | A point-to-point `OffMeshLink` (jump, drop, ladder, or teleport) carried into every baked `Mesh.Links` | | `AddHeightmap`, `AddTerrainFile` | A `world3d.Heightmap` (or a `*.terrain.yaml` file loaded through `world3d.LoadTerrainFS`), triangulated as its `BuildMesh` does | | `AddGridMap`, `AddGridMapFile` | The collider boxes of every occupied cell of a `world3d.GridMap` (or a `*.gridmap.yaml` file loaded through `world3d.LoadGridMapFS`) | | `AddPhysicsWorld` | The static bodies, triangle meshes, heightfields and voxel colliders of a `physics3d.World` whose layers share a bit with the mask; dynamic and kinematic bodies and triggers are left out, as is a voxel collider whose grid does not implement `physics3d.VoxelBoundsGrid`, since its solid voxels cannot be listed | Triangles are surfaces, as in Recast, so a closed mesh tall enough to stand in is hollow, and its inside floor is baked as an island no path reaches, unless it is smaller than `MinRegionArea`. The collider shapes `AddPhysicsWorld` and `AddGridMap` add, boxes, spheres, capsules and voxels, are filled instead: each column they cross is solid from their lowest to their highest point. ## The navigation mesh file A scene names its baked file in its `navMesh` field, a path from the project root, and `game navmesh` writes it there. The file holds the settings it was baked with and one mesh per agent type: ```yaml version: 1 settings: cellSize: 0.3 cellHeight: 0.2 minRegionArea: 1 maxEdgeLength: 12 maxSimplificationError: 0.4 maxVertsPerPoly: 6 detailSampleDistance: 1.8 detailSampleMaxError: 0.2 layerMask: 4294967295 meshes: - agent: name: humanoid radius: 0.6 height: 2 maxSlope: 45 maxClimb: 0.9 vertices: - [0, 0, 0] - [0, 0, 4] - [4, 1, 4] - [4, 1, 0] polygons: - vertices: [0, 1, 2, 3] detail: - [2, 0.75, 2] triangles: - [0, 1, 4] - [1, 2, 4] - [2, 3, 4] - [3, 0, 4] ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `settings` | The `Settings` the meshes were baked with, every field written | | `meshes[].agent` | The `AgentType` the mesh was baked for, every field written; names are unique | | `meshes[].vertices` | The polygons' corners in world space, `[x, y, z]`, shared between neighbouring polygons | | `meshes[].polygons[].vertices` | Indices of the polygon's corners in `vertices`, 3 to `maxVertsPerPoly` of them, around the polygon | | `meshes[].polygons[].detail` | Extra vertices sampled on the polygon's edges and inside it where the ground is uneven | | `meshes[].polygons[].triangles` | The triangles covering the polygon, counter-clockwise seen from above; index `i` below the polygon's vertex count names its `i`th corner, and index `n + i` names `detail[i]` | | `meshes[].links` | Optional point-to-point off-mesh links (`id`, `start: [x, y, z]`, `end: [x, y, z]`, `radius`, `bidirectional`, `cost`, `area`, `flags`, `userData`) registered on the `world3d.NavMesh` by `Mesh.NavMesh` | `Parse` refuses unknown fields, a missing or unsupported version, non-finite coordinates and indices out of range, with the line, field and a fix; `Encode` writes the fixed key order above, and loading then saving a file changes nothing. [File Formats](https://game.nsgo.dev/docs/formats/#3d-navigation-meshes) lists it with the others. ## Finding paths Load the scene's file and turn one agent type's mesh into a `world3d.NavMesh`: ```go file, err := navbake3d.LoadFS(assets, scene.NavMesh) if err != nil { return err } mesh, ok := file.Mesh("humanoid") if !ok { return errors.New("no humanoid navigation mesh") } nav := mesh.NavMesh() path, ok := nav.FindPath(start, goal) ``` `Mesh.NavMesh` makes each detail triangle a walkable polygon of the `NavMesh`, linked to its neighbours across shared edges, so `FindPath` follows ramps, stairs and terrain at the baked heights and keeps stacked floors apart. Its `VerticalTolerance` is the larger of the agent's height and climb, so `FindPolygon` snaps a point to the surface under or over it within that distance. For dynamic obstacles and chunk streaming, call `Mesh.TiledNavMesh(tileSize)` to build a `*world3d.TiledNavMesh`, or call `navbake3d.BakeTile(g, settings, agent, coord, tileSize, origin)` to voxel-bake a single `*world3d.NavTile` aligned to a `world3d.ChunkCoord` with an erosion border. ## Debug drawing `DrawDebug` strokes a mesh's polygon outlines and detail triangles onto a `core.Drawing` through a `[0, 1]` depth projection such as `math3d.Perspective` or a render3d camera's, clipped at the near plane; `DebugStyle` sets the colors, line width and how far the lines are lifted off the ground. `Mesh.DebugLines` returns the same segments for a renderer of your own. A release build draws nothing. ```go navbake3d.DrawDebug(d, viewProj, viewport, mesh, navbake3d.DefaultDebugStyle()) ``` ## From the command line ```sh nsgo game navmesh scenes/level1.scene.yaml ``` [`game navmesh`](https://game.nsgo.dev/docs/cli/#navmesh) bakes a scene's static 3D geometry (glTF models, built-in primitives, and static `collider3d` shapes) for every agent type in the `navigation` section of the [project file](https://game.nsgo.dev/docs/project/) and writes the file the scene's `navMesh` names. ## In the editor In 3D view mode, the [scene editor](https://game.nsgo.dev/docs/editor/#3d-navigation-mesh-baking-901) opens the **NavMesh** bake panel (`NavMeshPanelView`) to edit agent radius, height, step height, max slope, voxel cell size/height, and output path, bake the open scene into a deterministic `.navmesh.yaml` file (undoably updating `SceneDoc.NavMesh`), and toggle a live translucent polygon-and-edge overlay over the 3D viewport. --- Source: https://game.nsgo.dev/docs/net/ # net `game/net` provides cross-target multiplayer networking for NSGo games: a unified `Transport` across WebSocket (native + WebAssembly), native UDP, and simulated loopback; server-authoritative delta snapshot replication with client prediction and interpolation; and deterministic lockstep and rollback netcode. ```go import "github.com/nsgo-dev/game/pkg/net" ``` ## Cross-target transports (`Transport`) Every transport implements the same non-blocking `Transport` interface (`Send`, `Recv`, `LocalID`, `Peers`, `Close`) with `ChannelReliableOrdered` and `ChannelUnreliable` channels and `PeerBroadcast` (`PeerID(0)`): | Transport | Constructor | Targets & use case | | --- | --- | --- | | `WebSocketServer` / `WebSocketTransport` | `ListenWebSocket`, `DialWebSocket` | Native + browser (`js/wasm`); works across NATs and web builds. Clients authenticate with a token and the server assigns their IDs (see below). | | `UDPServer` / `UDPClient` | `ListenUDPServer`, `DialUDP` | Native targets (desktop/mobile) for low-latency datagrams to a server, with the same handshake as WebSocket and every datagram bound to its session. | | `UDPTransport` | `ListenUDP` + `AddPeer` | Native peer-to-peer datagrams between endpoints that know each other's addresses: a datagram is accepted only from the address registered for the ID it claims. | | `Relay` / `RelayTransport` | `NewRelay`, `NewRelayTransport` | Peer-to-peer sessions between players who cannot reach each other: each connects to a relay over WebSocket or UDP, and the relay forwards between members of the same session (see [the server guide](https://game.nsgo.dev/docs/server/#peer-to-peer-relay)). | | `LoopbackHub` / `LoopbackTransport` | `NewLoopbackHub` + `AddPeer` | In-memory deterministic tests with configurable `Latency`, `Jitter`, `LossRate`, and `Seed`. | UDP has no retransmission or ordering, so both UDP transports refuse `ChannelReliableOrdered` with `ErrUnsupportedChannel`; lockstep and rollback need a WebSocket or loopback transport, or a `RelayTransport`, which retransmits end to end and so runs them over UDP too. A transport has a single consumer. `Recv` hands each packet to one caller, and `ServerWorld`, `ClientWorld`, the lockstep and rollback sessions, `Relay` and `RelayTransport` all drain every waiting packet and discard the ones that are not theirs, so two of them on one transport steal each other's packets. Give each consumer its own transport, or put a demultiplexer in front of them that implements `Transport` for each. `Recv` costs the same however many packets are queued, so draining a burst stays linear. If the socket under a `UDPTransport` or `UDPServer` fails, `Err` returns `ErrReceiveFailed` wrapping the socket's error and `Send` returns it too; close the transport and listen again; after `Close`, `Err` returns nil. Errors about a single datagram, such as an ICMP port unreachable for an earlier send, do not stop it. A `UDPClient` likewise keeps reading after an ICMP error, for example while its server restarts, and leaves it to its idle timeout to decide whether the server is gone. ```go hub := net.NewLoopbackHub(net.LoopbackConfig{ Latency: 40 * time.Millisecond, Jitter: 10 * time.Millisecond, LossRate: 0.02, Seed: 7, }) serverTx := hub.AddPeer(1) clientTx := hub.AddPeer(2) _ = serverTx.Send(2, net.ChannelReliableOrdered, []byte("hello")) hub.Advance(60 * time.Millisecond) pkt, ok := clientTx.Recv() _, _ = pkt, ok ``` ### Inbox limits A transport keeps each packet that arrives until `Recv` takes it, and bounds what it keeps by channel and by peer. Each peer's `ChannelUnreliable` packets are capped at `DefaultUnreliableInbox` (4096): when one arrives from a peer that already has that many queued, that peer's oldest queued unreliable packet is dropped, so a game that falls behind keeps the newest state, a peer that floods a server evicts only its own packets, and `InboxStats().UnreliableDropped` counts the loss. `ChannelReliableOrdered` packets are never dropped, since that would break the channel's guarantee. A transport whose peers cannot be trusted caps each peer's reliable packets at `DefaultReliableInbox` (16384) instead and refuses the one that goes past it, counting it in `InboxStats().ReliableRefused`: a `WebSocketServer` ends that client's session, as if it had left, so the packets it did deliver stay in order, and a `RelayTransport` stops acknowledging that peer, which resends its messages once `Recv` has made room. The other transports receive reliable packets only from their server or from the same process and keep them all. Every transport also counts `InboxStats().ReliableWarnings` once each time its whole reliable backlog passes `DefaultReliableInboxWarning` (4096), and `ReliableBacklog` stays true until the backlog falls to half of it, so a queue hovering at the threshold does not warn on every packet. `Recv` still returns packets in arrival order across both channels and every peer. `UDPTransport` never sends reliable packets, so it drops a datagram that claims to be one. Every transport implements `InboxReporter`: `SetInboxLimits` changes the limits at any time (lowering the unreliable cap drops each peer's oldest unreliable packets at once), and `InboxStats` reads the counters, which only grow, so a game or a debug overlay compares them with the previous frame's. `LoopbackConfig.Inbox` sets the limits of the peers a hub adds, and `RelayTransportConfig.Inbox` those of a `RelayTransport`. In `InboxLimits`, zero uses the default and a negative value removes the cap or turns the warning off. A `RelayTransport`'s inner transport has its own limits, and every relayed peer arrives on it from the relay, so they share its per-peer cap; a reliable message it drops there is sent again. ```go tx.SetInboxLimits(net.InboxLimits{Unreliable: 512, ReliableWarning: 1024}) var lastWarnings, lastDropped uint64 // Each frame, after draining Recv: st := tx.InboxStats() if st.ReliableWarnings != lastWarnings { log.Printf("reliable backlog of %d packets", st.Reliable) } if st.UnreliableDropped != lastDropped { log.Printf("dropped %d stale unreliable packets", st.UnreliableDropped-lastDropped) } lastWarnings, lastDropped = st.ReliableWarnings, st.UnreliableDropped ``` ## Connection handshake and reconnect `WebSocketServer` and `UDPServer` admit a client only after a handshake: the client presents an app-defined token, `Auth.Verify` checks it, and the server assigns the client's `PeerID` and sends it back, or refuses with a reason. A refused client never reaches `Recv` or `Peers`. ```go auth := net.Auth{ // Check a signed token locally; the error text is sent to the client. Verify: func(peer net.PeerID, token []byte) error { if !validToken(token) { return errors.New("invalid token") } return nil }, GracePeriod: 15 * time.Second, // a dropped client keeps its ID this long } srv, _ := net.ListenWebSocket(":8080", 1, auth) // or net.ListenUDPServer(":7777", 1, auth) // Each server tick: for ev, ok := srv.NextEvent(); ok; ev, ok = srv.NextEvent() { switch ev.Kind { case net.PeerJoined: // new ID case net.PeerDropped: // connection lost; ID and state kept for GracePeriod case net.PeerResumed: // same ID back within GracePeriod case net.PeerLeft: // closed, or GracePeriod ran out rooms.Leave(roomOf(ev.Peer), ev.Peer) guard.Reset(ev.Peer) } } ``` ```go cli, err := net.DialWebSocket("wss://play.example.com/game", token) // or net.DialUDP(addr, token) if errors.Is(err, net.ErrRejected) { // err is a *net.RejectError carrying the server's reason } me := cli.LocalID() // assigned by the server // After a network drop (State() == net.ConnDisconnected): _ = cli.Reconnect() // cli.Resumed() reports whether it kept its ID ``` - `NextEvent` checks grace periods and idle timeouts when it is called, so a server polls it every tick alongside `Recv`. Queued lifecycle events (`PeerJoined`, `PeerDropped`, `PeerResumed`, `PeerLeft`) drain in FIFO order in constant amortized time per event without silently dropping any. While a peer is inside its grace period, `Send` to it returns `ErrDisconnected` and `Peers` leaves it out. - `Close` on a client is a goodbye: the server reports `PeerLeft` at once instead of holding the session. `Reconnect` is not, even while the connection is still open: the browser closes its old socket with a code the server counts as a drop. - A server holds at most `Auth.MaxPeers` sessions (1024 by default), counting peers inside their grace period; past it, clients are rejected with the reason `server full`. Without `Verify` anyone may join, so set it on any server reachable from the internet. - A resume proves itself with a secret from the previous welcome, which the server replaces on every handshake; an ID alone cannot take over a session. Past the grace period, `Reconnect` joins again as a new peer when the token is still valid. - In the browser, `DialWebSocket` returns at once: `State` is `ConnConnecting` and `LocalID` is 0 until the welcome arrives, and packets sent before then are queued. A refusal moves it to `ConnDisconnected` with the `*RejectError` in `Err`. - A `WebSocketServer` pings each client every third of `Auth.IdleTimeout` (10 seconds by default, never less than 3) and drops a client from which no byte arrives, not even a pong, for that long, so a client whose network vanished without closing the TCP connection does not hold its session and ID forever. Browsers answer pings on their own. A native `WebSocketTransport` pings the server every 2 seconds and moves to `ConnDisconnected` when no byte arrives for 10 seconds. A large frame that arrives slowly is read whole as long as its bytes keep coming. These timeouts use the wall clock, not `Auth.Now`. `WebSocketServer.Close` sends every client its close frame at once and waits at most a second for clients that do not read. - A WebSocket frame's payload is read as it arrives rather than allocated from the length the frame announces, and a hello may be no longer than a valid one, so a client that announces a large frame and then trickles it cannot reserve memory it has not sent. Control frames (`Close`, `Ping`, `Pong`) follow RFC 6455 §5.5: fragmented control frames, control frames over 125 payload bytes, and reserved control opcodes (`0xB`–`0xF`) are rejected. - After the UDP handshake, each client is bound to the address it shook hands from and to a per-session key: every datagram carries a truncated HMAC-SHA256 tag and a sequence number checked against a replay window, so a spoofed or replayed datagram is dropped and cannot move the peer. Datagrams are authenticated, not encrypted. A `UDPClient` pings every second while idle; a client silent for `Auth.IdleTimeout` (10 seconds by default, never less than 3) counts as dropped. The server answers only hellos of at least 128 bytes and never replies with more than it received. - The handshake is not encrypted: the hello carries the token, and the welcome carries the resume secret and, for UDP, the session key. Use `wss://` for WebSocket in production. UDP has no such layer, so its binding stops only attackers who cannot see the traffic: anyone who observes a handshake (shared Wi-Fi, any hop on the path) can forge that session's datagrams and resume it from their own address. Issue UDP tokens that are short-lived and single-use, and prefer WebSocket over `wss://` where an on-path observer is a concern. ## Server-authoritative delta replication Use `ServerWorld` and `ClientWorld` for action, co-op, or arena games where the server owns authoritative entity state. `ServerWorld.Step(tick)` tracks per-peer acknowledged snapshots and sends compact field-level deltas (falling back to full snapshots when needed): ```go // Server: server := net.NewServerWorld(serverTx) heroID := server.Spawn(net.EntityState{ ComponentState: net.ComponentState{Kind: 1, X: 100, Y: 50}, }) server.Update(heroID, updatedState) _ = server.Step(tick) // Client: client := net.NewClientWorld(clientTx, serverID) client.OnSpawn = func(e net.EntityState) { /* attach visuals */ } client.OnDespawn = func(id net.EntityID) { /* remove visuals */ } client.Poll() client.Predict(heroID, localCmd, applyInput) renderEntities := client.Interpolate(renderTick) // smooth remote entity motion _ = renderEntities ``` Inspect bandwidth and reconciliation behavior with `server.Stats()`, `client.PredictedState(id)`, `client.Reconciliations()`, and `client.LastReconcileError()`. - `Step` never passes `Transport.Send` a payload larger than `DefaultMaxSnapshotSize` (60000 bytes, which fits UDP, relay and WebSocket packets), or the size set with `server.SetMaxSnapshotSize(n)`. A larger full snapshot is split into parts that `ClientWorld` reassembles before applying, and a delta larger than the limit is replaced by a split full snapshot. A lost part costs that snapshot only: the client does not acknowledge it, so the next `Step` sends a whole one again. `Stats().PacketsSent` counts parts, `SnapshotsSent` whole snapshots. An entity that does not fit in a part on its own makes `Step` return `ErrPayloadTooLarge` naming it. - Ticks are `uint32` and compared in serial-number order, so replication keeps working when the counter wraps after 2^32 ticks (about 2.27 years at 60 Hz). `Interpolate` reads `renderTick` relative to the latest snapshot's tick, modulo 2^32, so `float64(latest) - delay` works on either side of the wrap. A server that starts its ticks over in the same epoch sends ticks the client takes as stale: call `client.Reset()`, which forgets every snapshot, prediction and the epoch and reports each known entity through `OnDespawn`, before the new match's first snapshot, or start the match with `server.SetEpoch` so clients follow on their own. ### Replication epoch Every snapshot carries the server's replication epoch, a number `NewServerWorld` picks at random, so a restarted server's snapshots are told apart from the previous run's even when their ticks overlap. A `ClientWorld` that receives a complete full snapshot of a new epoch forgets every snapshot, partial snapshot and prediction of the old one, reports each entity it knew through `OnDespawn`, and continues from the new epoch, without the game calling `Reset`. The snapshot is parsed whole first, so a corrupt packet cannot wipe the world. A delta of a new epoch cannot be applied to anything the client holds, so it only makes the client ask the server for a full snapshot of that epoch. The client remembers the last 16 epochs it left and ignores their snapshots, so a snapshot of the old run that arrives late cannot pull the client back. `client.Epoch()` returns the epoch the client follows. - A server that keeps running but starts a new match with its ticks back at zero calls `server.SetEpoch(server.Epoch() + 1)`: the next `Step` sends every peer a full snapshot, and clients drop the old match as they would after a restart. A server that numbers its runs itself, or a test that needs fixed epochs, sets one the same way. An epoch should not repeat, because clients ignore the epochs they have left until 32 of their snapshots arrive in a row. - Random epochs cannot be ordered, so a late snapshot of an epoch the client never saw, arriving after the live epoch's first one, moves the client to that dead epoch. A left epoch that keeps sending, 32 snapshots in a row with none of the current epoch between them, is therefore taken as the live one and followed again; a late burst of a finished run is far shorter. The same recovers a restart that draws one of the 16 left epochs. - Two runs pick the same random epoch with a chance of one in 2^32; such a restart looks like a server that went back in ticks, which `Reset` or `SetEpoch` handles. - Acknowledgments carry the epoch too, and the server ignores those of another epoch, so a client's ack of the old run never becomes a delta baseline in the new one. ### Wire format Replication speaks version 2 of its wire protocol (`ReplicationVersion`); version 2 added the epoch. Every message starts with one byte holding the protocol version in its high four bits and the message type in its low four, then the epoch as 4 little-endian bytes. `uv` is an unsigned varint as `encoding/binary` writes it. | Message | Type | Direction | Layout after the 5-byte header | | --- | --- | --- | --- | | Full snapshot | 1 | server to client | `tick(uv) count(uv) entity...` | | Delta snapshot | 2 | server to client | `tick(uv) baselineTick(uv) despawnCount(uv) id(uv)... updateCount(uv) entity...` | | Acknowledgment | 3 | client to server | `tick(uv)` | | Resync request | 4 | client to server | nothing | | Full snapshot part | 5 | server to client | `tick(uv) index(uv) total(uv) count(uv) entity...` | An entity is `id(uv) mask(1)` followed by the fields whose mask bit is set, in bit order: kind (uv), x, y, vx, vy and rotation (4-byte little-endian floats), flags (uv), and props (a uv length, then the bytes). A full snapshot sets the bit of every field that is not zero; a delta sets the bits of the fields that changed since the baseline, and of every non-zero field of an entity the baseline did not have. Version 1, from releases before the epoch, had no header: its messages start with the bare type 1 to 5, which reads as version 1. Peers of different versions cannot replicate to each other, and neither misreads the other's messages. A client refuses snapshots of another version and reports it through `client.Err()`, a server refuses acknowledgments and resync requests of another version and reports it through `server.PeerErr(peer)`; both errors wrap `ErrReplicationVersion` and name the two versions, so a game can tell the player to update instead of waiting for a world that never arrives. ## Deterministic lockstep and rollback netcode For fighting games, RTS titles, or tight arcade co-op, implement `SimState` (`Step`, `Save`, `Load`, `Checksum`) and drive it with `LockstepSession` or `RollbackSession`: ```go session := net.NewRollbackSession(net.RollbackConfig{ Transport: peerTx, Sim: sim, Peers: []net.PeerID{1, 2}, MaxRollback: 8, InputDelay: 1, ChecksumInterval: 30, OnDesync: func(ev net.DesyncEvent) { log.Printf("desync at tick %d: local=%x remote=%x", ev.Tick, ev.LocalChecksum, ev.RemoteChecksum) }, }) // Each fixed step in game.Loop.Update: if err := session.Poll(); err != nil { return err } if err := session.Step(net.InputFrame{Tick: session.Tick(), Peer: peerTx.LocalID(), Bits: buttons}); err != nil { return err } ``` - `RollbackSession` predicts missing remote inputs, saves snapshots per tick, and automatically rewinds and resimulates when a late remote input disagrees with prediction (returning `ErrRollbackWindowExceeded` if a peer falls beyond `MaxRollback`). - `LockstepSession` (`SubmitInput`, `Poll`, `Step`) advances only when every peer's input for the current tick has arrived, ideal for RTS or turn-synchronized play. `SubmitInput` ignores an input for a tick already run or more than 256 ticks ahead. - Both sessions exchange periodic checksums (use `ChecksumBytes` helper) to surface determinism bugs immediately via `OnDesync` and `Desyncs()`. - Both sessions compare `uint32` ticks in serial-number order (RFC 1982), including membership windows and pending joins/leaves, so long matches continue seamlessly across the 2^32 tick wraparound. `RollbackSession` keeps unconfirmed history until the first tick confirms, so a peer whose first input arrives more than `MaxRollback + 2` ticks late can still confirm and advance. ### Players joining and leaving mid-match A match's peers are not fixed when the session is created. One peer, the host (`Host` in the config, the lowest peer ID by default), admits and removes peers while the match runs, and every peer applies each change at the same tick: ```go // On the host, when its transport reports a new player (PeerJoined, or a new ID in RelayTransport.Peers): joinTick, err := session.AddPeer(newPeer) // On the new player's machine; Step it every frame as usual, it only polls until Active reports true: session := net.NewRollbackSession(net.RollbackConfig{Transport: peerTx, Sim: sim, Host: hostID, Join: true}) // On the host, once its transport reports the player gone (PeerLeft, or the ID missing from Peers): leaveTick, err := session.RemovePeer(oldPeer) ``` - The join tick is the one the host's next own input is for: the later of `Tick` and the tick after its latest submitted input for lockstep, `Tick + InputDelay` for rollback. No peer can have run (lockstep) or confirmed (rollback) that tick yet, since that takes the host's input for it, and the change travels on the reliable channel ahead of that input. A rollback peer that has already predicted past the tick rolls back to it. - Once the host's simulation stands at the start of the join tick (lockstep), or every tick before it is confirmed (rollback), the host sends the newcomer `Sim.Save()` at that tick together with the tick, the peers and, for each peer already leaving, the inputs the host declared for it from the join tick to its leave, in parts of 48000 bytes. The newcomer loads the state into its own `Sim`, its `Tick` starts at the join tick, and from then on it plays like the others, including the ticks of a peer the host removed before the newcomer had its state. A state larger than `MaxJoinStateSize` (16 MiB) makes `AddPeer` return `ErrPayloadTooLarge`, and one that has grown past it by the join tick turns the join into a leave, so nobody waits for the newcomer. - Inputs before the join tick are not expected from the newcomer. In rollback its first `InputDelay` ticks are zero inputs on every peer, as every peer's are at the start of a match. Each peer sends the newcomer the inputs it had already sent for the join tick and later, and an input from the newcomer that reaches a peer before the host's announcement is kept until the announcement arrives. - The leave tick is the host's next own input tick, or the peer's join tick if that is later. The change carries the inputs the host holds from the leaving peer for the ticks before it, and a zero input for each tick the host never received from it, so every peer runs those ticks alike; inputs arriving straight from the leaving peer are ignored from then on. Remove a peer after it has stopped sending: one removed while still sending may have reached another peer with an input the host never saw, which shows up as a desync. The removed peer's own session stops at the leave tick, and its `Active` reports false. - `Members` lists the peers taking part in the current tick. Only the host may call `AddPeer` and `RemovePeer` (`ErrNotHost` elsewhere), the host cannot leave (`ErrHostLeave`), and a peer that left comes back under a new ID (`ErrPeerRejoin`, however long ago it left), as relays and servers assign one. `RemovePeer` of a peer that left returns its leave tick. - A message the transport cannot deliver yet, because a relay has not told the sender of the newcomer or a peer is reconnecting, waits in the session and is sent again by the next `Poll`, in order with the messages that follow it. A session keeps up to 4096 such messages per peer; past that the peer has missed part of the match, every later message to it is dropped, and the next `SubmitInput` (lockstep) or `Step` or `Poll` (rollback) returns `ErrSessionBacklog` once for it, so the host removes it or the match ends. - A joining session finds its host in `Host`, or else as the lowest other ID in `Peers`; when neither names another peer it takes the lowest other ID its transport reports, on each `Poll`, until its join state arrives. Over a relay, whose peer list may still be empty or include other newcomers, set `Host` explicitly. --- Source: https://game.nsgo.dev/docs/package-size-budgets/ # Package Size Budgets `sizecheck` measures and enforces package size budgets for WebAssembly (`.wasm`), Android App Bundles (`.aab`), Android APKs (`.apk`), and iOS App Store Packages (`.ipa`) using Go's standard library (`archive/zip`), with no external tools or SDK dependencies. ## Why size budgets matter Mobile store download ceilings and cellular install thresholds directly affect whether players finish installing a game: - **Google Play (AAB)**: enforces a 200 MiB base-module compressed download limit per device configuration; every extra ABI in a universal APK multiplies native code footprint. - **Apple App Store (IPA)**: applies a 200 MiB cellular download threshold before App Thinning; keeping binaries, frameworks, and asset catalogs lean keeps installs fast on mobile networks. - **Web (Wasm)**: every megabyte of gzipped `.wasm` delays first paint and first playable frame. `sizecheck` inspects each archive's exact compressed and uncompressed sizes, categorizes every entry, splits Android native libraries by ABI, and surfaces the largest files so regressions are immediately actionable. ## Default mobile budgets Built-in defaults in `cmd/sizecheck` target typical 2D NSGo games and can be overridden with `-budget`, `-budget-mb`, or `-abi-budget-mb`: | Target | Function | Total archive | Per-ABI native libs | Category defaults (compressed) | | --- | --- | ---: | ---: | --- | | Android AAB (`.aab`) | `DefaultAndroidAABBudget` | 50 MiB | 20 MiB | `native_libs` 35 MiB, `dex` 5 MiB, `assets` 25 MiB, `resources` 15 MiB, `manifest_meta` 2 MiB | | Android APK (`.apk`) | `DefaultAndroidAPKBudget` | 40 MiB | 20 MiB | `native_libs` 30 MiB, `dex` 5 MiB, `assets` 20 MiB, `resources` 15 MiB, `manifest_meta` 2 MiB | | iOS IPA (`.ipa`) | `DefaultIOSIPABudget` | 50 MiB | - | `executable` 25 MiB, `frameworks` 15 MiB, `assets_car` 15 MiB, `resources` 25 MiB, `lproj` 5 MiB, `code_signature` 2 MiB | For this repository's minimal `./cmd/wasmprobe` CI probe, tighter baseline files live in [`benchmarks/`](https://github.com/nsgo-dev/game/blob/main/benchmarks/): - [`benchmarks/web-budget.json`](https://github.com/nsgo-dev/game/blob/main/benchmarks/web-budget.json): 8 MiB raw / 2.25 MiB gzipped `.wasm` - [`benchmarks/android-aab-budget.json`](https://github.com/nsgo-dev/game/blob/main/benchmarks/android-aab-budget.json): 6 MiB total `.aab` / 4 MiB per ABI - [`benchmarks/ios-ipa-budget.json`](https://github.com/nsgo-dev/game/blob/main/benchmarks/ios-ipa-budget.json): 6 MiB total `.ipa` / 4 MiB executable ## Package categories ### Android (`.aab` and `.apk`) | Category | Matched archive entries | | --- | --- | | `native_libs` | `base/lib//*` (or `/lib//*`) in AAB; `lib//*` in APK. Also aggregated per ABI (`arm64-v8a`, `armeabi-v7a`, `x86_64`, etc.). | | `dex` | `base/dex/*.dex` in AAB; `*.dex` in APK. | | `assets` | `base/assets/**` in AAB; `assets/**` in APK. | | `resources` | `base/res/**`, `base/resources.pb` in AAB; `res/**`, `resources.arsc` in APK. | | `manifest_meta` | `AndroidManifest.xml`, `BundleConfig.pb`, `BUNDLE-METADATA/**`, `META-INF/**`, `native.pb`, `assets.pb`. | | `other` | All remaining entries (such as `base/root/**` or Kotlin metadata). | ### iOS (`.ipa`) | Category | Matched archive entries | | --- | --- | | `executable` | Main Mach-O binary inside `Payload/.app/` (matched via `CFBundleExecutable` in `Info.plist`, falling back to ``). | | `frameworks` | `Frameworks/**`, `PlugIns/**`, `*.dylib`, and top-level `SwiftSupport/**`. | | `assets_car` | Compiled asset catalogs (`Assets.car`, `*.car`). | | `resources` | `Info.plist`, shaders/metallibs, images, audio, fonts, tilemaps, atlases, `*.storyboardc/**`, `*.bundle/**`, and `assets/**`. | | `lproj` | Localization bundles (`*.lproj/**`). | | `code_signature` | `_CodeSignature/**`, `embedded.mobileprovision`, `SC_Info/**`. | | `other` | `PkgInfo`, files outside `Payload/.app/` (`iTunesMetadata.plist`, `Symbols/**`), and unrecognized files. | ## CLI usage Run `sizecheck` from the repository root: ```sh # Inspect an Android App Bundle using built-in defaults go run ./cmd/sizecheck -kind aab path/to/app.aab # Enforce a tighter total and per-ABI budget on a multi-ABI APK and emit Markdown go run ./cmd/sizecheck -kind apk -budget-mb 35 -abi-budget-mb 15 -markdown path/to/app.apk # Inspect an iOS IPA and emit structured JSON go run ./cmd/sizecheck -kind ipa -json path/to/app.ipa # Check the WebAssembly probe against benchmarks/web-budget.json go run ./cmd/sizecheck -kind wasm -budget ../../benchmarks/web-budget.json -markdown ``` ### Flags | Flag | Description | | --- | --- | | `-kind` | Package format: `aab`, `apk`, `ipa`, or `wasm`. Inferred from the file extension when omitted; defaults to `wasm`. | | `-file` | Path to the package file (`.aab`, `.apk`, `.ipa`, or `.wasm`). May also be passed as a positional argument. | | `-budget` | Path to a JSON budget file. Defaults to `../../benchmarks/web-budget.json` for `wasm` and built-in platform defaults for mobile. | | `-budget-mb` | Override the total package size limit in MiB (`> 0`). | | `-abi-budget-mb` | Override the per-ABI native library compressed size limit in MiB (`> 0`, Android only). | | `-wasm` | Existing `.wasm` path in `wasm` mode (skips building `target`). | | `-json` | Write the structured report as JSON to stdout. | | `-markdown` | Write a GitHub-flavored Markdown report to stdout. | ### Exit codes - `0`: package inspected and all budgets passed. - `1`: one or more total, per-ABI, or per-category limits were exceeded (the full breakdown is still written to stdout). - `2`: invalid arguments, unreadable budget file, missing package, or corrupt ZIP archive. ### Custom mobile budget JSON You can check a custom JSON file with `-budget`: ```json { "max_total_bytes": 52428800, "max_per_abi_bytes": 20971520, "max_category_bytes": { "native_libs": 36700160, "dex": 5242880, "assets": 26214400 }, "note": "Release budget for MyGame Android AAB" } ``` Any omitted or `<= 0` field is left unbounded. ## CI enforcement [`.github/workflows/quality.yml`](https://github.com/nsgo-dev/game/blob/main/.github/workflows/quality.yml) runs three dedicated size budget jobs on every push to `main` and every pull request: 1. **`web-size-budget`** (`ubuntu-24.04`): builds `./cmd/wasmprobe` for `GOOS=js GOARCH=wasm` and checks `benchmarks/web-budget.json`. 2. **`android-size-budget`** (`ubuntu-24.04`): runs `go tool nsgo build -target android -channel store ./cmd/wasmprobe`, inspects the generated `.aab` against `benchmarks/android-aab-budget.json`, and appends the Markdown report to `$GITHUB_STEP_SUMMARY`. 3. **`ios-size-budget`** (`macos-15`): runs `go tool nsgo build -target ios ./cmd/wasmprobe`, inspects the generated `.ipa` against `benchmarks/ios-ipa-budget.json`, and appends the Markdown report to `$GITHUB_STEP_SUMMARY`. When a budget fails, `sizecheck` still renders the full violation list, category table, per-ABI table, and top-10 largest files into the job summary before exiting with code `1`. ## Keeping packages lean - Strip Go symbol and DWARF tables in release builds (`-ldflags="-s -w"` and `-trimpath`). - Ship `.aab` bundles to Google Play so users download only their device's ABI instead of every architecture. - Prefer compressed audio (`.m4a` / `.ogg`) for music and packed sprite atlases over loose uncompressed PNGs or WAVs. - Watch the `Largest Files` table in CI summaries whenever adding new dependencies or assets. --- Source: https://game.nsgo.dev/docs/particles/ # particles `game/particles` provides deterministic, seeded particle emitters for both 2D (`Emitter`, drawn through `sprite.Batch`) and 3D (`Emitter3D` + `GPUParticles3D`, drawn in a single instanced `gpu.View` draw call). ```go import "github.com/nsgo-dev/game/pkg/particles" ``` Two emitters configured with the same fields and `Seed` and stepped with identical `dt` produce bit-for-bit identical particles and draw operations. ## Configuring an Emitter Configure an `Emitter` with an `Atlas`, one or more `Frames`, spawn shape, motion parameters, and lifetime curves: ```go fire := &particles.Emitter{ Atlas: fxAtlas, Frames: []sprite.Frame{fxAtlas.Frames["spark_0"], fxAtlas.Frames["spark_1"]}, X: 160, Y: 120, Shape: particles.Circle(6), Rate: 45, // particles per second MaxParticles: 128, LifetimeMin: 300 * time.Millisecond, LifetimeMax: 700 * time.Millisecond, SpeedMin: 20, SpeedMax: 65, AngleMin: -math.Pi*0.75, AngleMax: -math.Pi*0.25, GravityY: -30, // rise upward SizeCurve: particles.FloatCurve{ {T: 0, Value: 0.6}, {T: 0.3, Value: 1.2}, {T: 1, Value: 0}, }, AlphaCurve: particles.FloatCurve{ {T: 0, Value: 1}, {T: 1, Value: 0}, }, Seed: 42, Z: 20, } ``` Step the emitter in `game.Loop.Update` and draw it in `core.Canvas.Draw`: ```go // In Loop.Update: fire.Update(dt) // In Canvas.Draw: fire.Draw(d) ``` - `MaxParticles` defaults to `256` when `<= 0`. - `LifetimeMin` and `LifetimeMax` default to `1s` when both are `0`. - `AngleMin` and `AngleMax` are in radians clockwise from `+X`. - `InitialRotationMin`/`Max` and `RotationSpeedMin`/`Max` control starting angle and angular velocity in radians / radians per second. ## Emission shapes `Emitter.Shape` determines where new particles spawn relative to `(X, Y)`: | Shape | Spawn distribution | | --- | --- | | `Point()` | Exactly at `(X, Y)` (the zero value of `Shape`). | | `Circle(radius)` | Uniformly over a disk of `radius` centered on `(X, Y)`. | | `Ring(radius)` | Uniformly on the circumference of a circle of `radius`. | | `Rect(width, height)` | Uniformly inside a `width × height` rectangle centered on `(X, Y)`. | Inspect an existing `Shape` with `Kind()` (`"point"`, `"circle"`, `"ring"`, `"rect"`), `Radius()`, `Width()`, and `Height()`. ## Lifetime curves Curves evaluate a particle's normalized age `t = Age / Lifetime` in `[0, 1]` by linear interpolation between stops ordered by `T`: - **`SizeCurve` (`FloatCurve`)**: uniform sprite scale over life (empty = `1`). - **`AlphaCurve` (`FloatCurve`)**: opacity over life (empty = `1`). - **`RotationCurve` (`FloatCurve`)**: additive rotation in radians over life (empty = `0`). - **`ColorCurve` (`ColorCurve`)**: linear RGBA interpolation stored on `Particle.Color` (empty = opaque white). `Draw` tints each particle's sprite by the color's RGB, and multiplies its alpha channel with `AlphaCurve`. ```go glow := particles.ColorCurve{ {T: 0, Color: core.RGBA(0xff, 0xd1, 0x66, 0xff)}, {T: 1, Color: core.RGBA(0xef, 0x47, 0x6f, 0x00)}, } ``` ## Bursts, inspection, and reset For one-shot impacts (explosions, coin pickups, dust puffs), leave `Rate: 0` and call `Burst(count)`: ```go sparks.X, sparks.Y = hit.X, hit.Y sparks.Burst(24) // emits immediately, stopping at MaxParticles ``` For timed or repeating bursts, configure `Bursts` (`[]Burst`, YAML key `bursts`) with `Time` (delay from start/reset), `Count` (particles per trigger), `Cycles` (`0` or `1` for one-shot, `> 1` for a fixed repeat count, `< 0` to repeat indefinitely), and `Interval` (time between cycles). `Update(dt)` fires due bursts deterministically, `ReloadConfig` updates burst schedules without clearing live particles, and `Clear()` / `Reset()` reset the schedule clock. Other methods on `*Emitter`: - `Count()`: number of currently live particles. - `Particles()`: live `[]Particle` slice in spawn order (backed by internal storage; copy if retaining a snapshot). - `Clear()`: removes live particles and resets the fractional emission accumulator without resetting the PRNG. - `Reset()`: clears live particles and re-seeds the PRNG from `Seed` for exact replay. ## Emitter definitions in YAML An emitter's configuration can live in a YAML file that people and tools edit and review as text. The keys are the `Config` field names in lower camel case, `version: 1` comes first, and fields left at their zero value are omitted. A few are always written even at their default: `space` and `shape`, a sub-emitter's `trigger` and `config` (whose `space` and `shape` are written too), and `collision.mode` when a `collision` block is present: ```yaml version: 1 x: 160 y: 120 space: world shape: kind: circle radius: 6 rate: 45 maxParticles: 128 lifetimeMin: 300ms lifetimeMax: 700ms gravityY: -30 sizeCurve: - t: 0 value: 0.6 - t: 1 value: 0 colorCurve: - t: 0 color: "#ffd166ff" - t: 1 color: "#ef476f00" seed: 42 frameNames: - spark_0 - spark_1 subEmitters: - trigger: death burstCount: 6 config: space: world shape: kind: ring radius: 8 lifetimeMin: 100ms lifetimeMax: 200ms ``` ```go cfg, err := particles.LoadConfigFS(assets, "fx/fire.yaml") if err != nil { return err } fire := &particles.Emitter{Atlas: fxAtlas} fire.ReloadConfig(cfg) // frameNames resolve against fire.Atlas ``` - `LoadConfigFile`, `LoadConfigFS` and `UnmarshalConfigYAML` read a definition; `SaveConfigFile` and `MarshalConfigYAML` write one. - Saving is deterministic: keys keep a fixed order, indentation is two spaces, and a definition loaded and saved again comes back byte for byte when it is already in that form. - Loading refuses a `version` other than `FormatVersion` or one inside a sub-emitter's `config`, unknown keys, duplicate keys, a key with no value, a second YAML document, a fraction in an integer field such as `maxParticles: 12.7`, and a shape size that does not apply to its kind, such as `width` on a `circle`. - Durations are strings in Go's `time.Duration` form, such as `500ms` or `1m30s`; a bare number is refused because its unit would be ambiguous. - Colors are quoted `"#rrggbb"` (opaque) or `"#rrggbbaa"` strings. Quote them: an unquoted `#` starts a YAML comment, and loading reports the key as having no value. - `shape.kind` is `point`, `circle`, `ring` or `rect`; `space` is `world` or `local`; `collision.mode` is `none`, `stop`, `bounce` or `kill`; a sub-emitter's `trigger` is `birth`, `death` or `collision`. - A runtime `Collider` is not part of the file, and a trail texture is saved by its URI (`trail.textureURI`). - `MarshalConfigJSON` and `UnmarshalConfigJSON` encode the same schema as JSON for programs that exchange definitions as JSON; files people write are YAML. - Its JSON Schema is published at `https://game.nsgo.dev/schemas/particles.v1.json` (`particles.SchemaURL`; see [Schemas for YAML files](https://game.nsgo.dev/docs/schemas/)). Emitter files (`*.particles.yaml` / `*.emitter.yaml`) can also be authored interactively with live preview in the [Particle emitter editor](https://game.nsgo.dev/docs/editor/#particle-emitter-editor-883) and placed directly on objects in version 2 scenes (`ObjectDoc.Particles`). ### Hot reload `HotConfig` keeps a definition and pushes changes to bound emitters without resetting live particles, the PRNG, attachments or runtime colliders. `ReloadBytes` takes the bytes a watcher such as `tooling/hotreload` delivers, and `ReloadHook` suits watchers that pass a path; a definition that fails to load returns an error and leaves the current one in place. ```go hot, err := particles.LoadHotConfigFile("fx/fire.yaml") if err != nil { return err } hot.Bind(fire) watcher.Watch("fx/fire.yaml", func(data []byte) { if err := hot.ReloadBytes(data); err != nil { log.Printf("fx/fire.yaml: %v", err) } }) ``` From a background goroutine, call `StageBytes` and apply the staged definition on the game loop with `Flush`. ## Performance Each live particle is one sprite in the emitter's `sprite.Batch`. Untinted particles, those without a `ColorCurve` or with a white one, draw in runs of one `DrawAtlas` call each ([nsgo-dev/game#28](https://github.com/nsgo-dev/game/issues/28)). A particle tinted by a non-white `ColorCurve` keeps its own image draw, which also allocates once inside NSGo's `Drawing`, so tinting thousands of particles costs more than fading them with `AlphaCurve`. `examples/fountain` is the stress scene for this: four seeded fountains topped up to 5000 live particles after every fixed step, all rotating and fading. Run it with NSGo's performance monitor and read the FPS line at the top right, with the window visible (a covered window pauses `game.Loop`): ```sh cd examples/fountain go tool nsgo dev -fps ``` The up and down arrow keys move the particle count by 1000 (from 1000 to 20000) to find where a machine drops below its display rate, and `R` restarts the scene from its seed. Two benchmarks track the CPU side of a frame, one for each way a particle is drawn: ```sh # One Update and one Draw of 5000 tinted particles, one image draw each go tool nsgo test ./pkg/particles -- -run '^$' -bench Emitter5000UpdateDraw # One step and one draw of the fountain scene's 5000 untinted particles, in DrawAtlas runs cd examples/fountain && go tool nsgo test -run '^$' -bench Scene5000 . ``` On an AMD Ryzen 9 3900X (Linux) they take about 1.7 ms with 5000 allocations and 1.8 ms with 25 allocations. That is only the CPU cost of stepping the particles and recording their draw operations: it leaves out the platform drawing about 5000 images per frame, and for tinted particles the garbage collector reclaiming the allocation each draw makes, so it is not evidence that a device holds 60 fps. A 60 fps reading on macOS with `--nsgo-fps` has not been recorded yet ([nsgo-dev/game#85](https://github.com/nsgo-dev/game/issues/85)). ## 3D GPU-friendly particles `Emitter3D` shares the 2D emitter model (`Rate`, `MaxParticles`, `LifetimeMin`/`Max`, `SpeedMin`/`Max`, `SizeCurve`, `AlphaCurve`, `RotationCurve`, `ColorCurve`, `SimulationSpace`, `Seed`, `Burst`, `Clear`, `Reset`) and adds 3D shapes, 3D gravity, linear drag, spread, billboard orientation modes, back-to-front depth sorting, and packed instanced GPU upload for `gpu.View`. ```go sparks := particles.NewEmitter3D(particles.Emitter3DConfig{ Position: math3d.Vec3{Y: 1}, Direction: math3d.Vec3Up(), Shape: particles.Cone(0.3, 0.4), Billboard: particles.BillboardStretched, Blend: particles.BlendAdditive, Rate: 4000, MaxParticles: 10000, LifetimeMin: 600 * time.Millisecond, LifetimeMax: 1400 * time.Millisecond, SpeedMin: 3, SpeedMax: 9, Spread: 0.2, Drag: 0.5, Gravity: math3d.Vec3{Y: -9.8}, SizeMin: 0.05, SizeMax: 0.15, ColorCurve: particles.ColorCurve{ {T: 0, Color: core.RGBA(0xffd166, 1)}, {T: 1, Color: core.RGBA(0xef476f, 0)}, }, Seed: 280, }) ``` ### 3D emission shapes `Emitter3D.Shape` (`Shape3D`) places spawned particles relative to `Position` in the emitter's `(side, Direction, forward)` frame: | Shape | Spawn distribution | | --- | --- | | `Point3D()` | Exactly at `Position` (the zero value of `Shape3D`). | | `Sphere(radius)` | Uniformly throughout a sphere of `radius`. | | `Hemisphere(radius)` | Uniformly throughout the upper hemisphere along `Direction`. | | `Box(width, height, depth)` | Uniformly inside a `width × height × depth` box centered on `Position`. | | `Cone(radius, angle)` | Uniformly on a base disk of `radius` perpendicular to `Direction`, firing outward up to half-angle `angle` (radians). | | `Ring3D(radius)` | Uniformly on a circle of `radius` perpendicular to `Direction`. | ### Billboard modes, blending, and depth sorting - **`BillboardSpherical`** (default): camera-facing quads parallel to the view plane, supporting per-particle roll (`InitialRotationMin`/`Max`, `RotationSpeedMin`/`Max`, `RotationCurve`). - **`BillboardCylindrical`**: quads locked to `Emitter3D.Axis` (defaults to `+Y`), rotating only around that axis toward the camera. - **`BillboardStretched`**: quads aligned and stretched along each particle's velocity vector (`length = size + speed * StretchFactor`, defaulting `StretchFactor` to `0.05`s). - **`BlendAdditive`** (`gpu.BlendAdditive()`): order-independent blending for fire, sparks, and magic; no depth sorting required. - **`BlendAlpha`** (`gpu.BlendAlpha()`, default) and **`BlendPremultiplied`** (`gpu.BlendPremultipliedAlpha()`): call `e.SortByDepth(camPos, camForward)` before packing/uploading to order particles back-to-front with a deterministic, zero-allocation 4-pass radix sort. ### Instanced GPU rendering (`GPUParticles3D`) `GPUParticles3D` owns a 4-vertex unit quad buffer (`StepVertex`) and a growable 40-byte-per-instance buffer (`StepInstance`: `center: vec3`, `right: vec3`, `up: vec3`, `color: unorm8x4`), drawing up to tens of thousands of particles in a single `DrawIndexedInstanced` call. It requires no compute shaders or storage buffers, so it runs identically on WebGL 2 / OpenGL ES 3.0 as well as Metal, Vulkan, D3D11, and WebGPU. `ParticleWGSL`, `ParticleSoftCircleWGSL`, and `ParticleTexturedWGSL` all bind the standard 3D camera uniform (`view`, `proj`, `view_proj`, `eye`) at `@group(0) @binding(0)`, matching `render3d.CameraBuffer`: ```go // In gpu.View OnReady: pipe, err := particles.NewParticlePipeline(cx, dev, particles.ParticlePipelineOptions{ CameraLayout: camBuf.Layout(), DepthFormat: gpu.FormatDepth24Plus, Blend: sparks.Blend, SoftCircle: true, }) gpuParticles, err := particles.NewGPUParticles3D(cx, dev, particles.GPUParticles3DOptions{ Capacity: sparks.MaxParticles, }) // In fixed Update: sparks.Step(dt) // In gpu.View OnFrame: if sparks.Blend != particles.BlendAdditive { sparks.SortByDepth(cam.Pos, cam.Forward()) } _ = gpuParticles.Upload(sparks, cam.Right(), cam.Up()) pass.SetPipeline(pipe) pass.SetBindGroup(0, camBuf.BindGroup()) gpuParticles.Draw(pass) // 1 DrawIndexedInstanced call for all live particles ``` ### 3D emitter definitions in YAML `Emitter3DConfig` uses the same versioned YAML (and JSON) conventions as 2D `Config`: `LoadConfig3DFile`, `LoadConfig3DFS`, `UnmarshalConfig3DYAML`, `SaveConfig3DFile`, `MarshalConfig3DYAML`, `UnmarshalConfig3DJSON`, and `MarshalConfig3DJSON`. Saving is deterministic with fixed key order, and loading refuses unknown fields, missing/wrong `version`, null values, non-finite floats, and shape parameters that do not apply to `shape.kind`. ### 3D 10k particle benchmarks `Emitter3D` stores particles in dense structure-of-arrays slices with swap-remove expiration and reusable radix-sort scratch buffers: ```sh go tool nsgo test ./pkg/particles -- -run '^$' -bench BenchmarkEmitter3D10k ``` On Apple Silicon (10,000 active particles with gravity, exponential drag, spin, and size/alpha/color/rotation curves): - `BenchmarkEmitter3D10kStepAndPack`: ~0.34 ms/frame, `0 B/op`, `0 allocs/op` (additive / unsorted path). - `BenchmarkEmitter3D10kStepSortAndPack`: ~0.44 ms/frame, `0 B/op`, `0 allocs/op` (alpha-blended path with back-to-front radix sort). Both leave over 97% of a 16.6 ms (60 fps) desktop frame budget available, and all 10,000 instances upload as a single 400 KB buffer write and render in one `DrawIndexedInstanced` call. --- Source: https://game.nsgo.dev/docs/perf/ # perf `game/perf` provides deterministic, zero-steady-state-allocation primitives for hot game loops: reusable object pools (`Pool`, `Arena`, `SlicePool`), 2D broad-phase spatial indices (`SpatialHash`, `Quadtree`), and viewport sprite culling (`CullBatch`, `BatchCuller`, `Cull`). ```go import "github.com/nsgo-dev/game/pkg/perf" ``` ## Deterministic object pools (`Pool`, `Arena`, `SlicePool`) Unlike `sync.Pool`, `perf` pools never drop entries on garbage collection, keeping frame times predictable across desktop, mobile, and WebAssembly targets: ```go // Pointer pool with explicit reset callback: bullets := perf.NewPool(128, func(b *Bullet) { *b = Bullet{} }) b := bullets.Acquire() b.X, b.Y = playerX, playerY bullets.Release(b) // Dense, cache-friendly Arena with generational Handles (stale handles safely return false): enemies := perf.NewArena[Enemy](64, nil) h, e := enemies.Alloc() e.HP = 100 for handle, item := range enemies.All() { stepEnemy(handle, item, dt) } enemies.Remove(h) // Reusable scratch slices: scratch := perf.NewSlicePool[uint32](16) ids := scratch.Acquire(64) defer scratch.Release(ids) ``` | Type | Best for | Key methods | | --- | --- | --- | | `Pool[T]` | Stable pointers to pooled structs (particles, projectiles) | `Acquire`, `Release`, `Prewarm`, `Active`, `Free`, `Cap`, `Reset` | | `Arena[T]` | Dense iteration + O(1) swap-remove with generational `Handle`s | `Add`, `Alloc`, `Get`, `Has`, `Remove`, `Slice`, `ForEach`, `All`, `Reset` | | `SlicePool[T]` | Per-frame temporary query or sorting buffers | `Acquire(minCap)`, `Release(s)`, `Free`, `Reset` | ## 2D spatial indices (`SpatialHash`, `Quadtree`) Replace O(n²) scans with O(k) area queries, point queries, and collision pair generation. Both indices reuse internal buckets/nodes and accept caller-owned output slices so steady-state queries allocate zero bytes: ```go grid := perf.NewSpatialHash[uint32](64) // cell size ~1-2x typical entity size grid.Insert(id, entityBounds) grid.Update(id, movedBounds) // Zero-alloc area query reusing caller slice: hits = grid.Query(cameraView, hits[:0]) // Deduplicated overlapping broad-phase pairs: grid.QueryPairs(func(a, b uint32) { resolveNarrowPhase(a, b) }) ``` Use `SpatialHash[ID]` for uniform entity sizes and unbounded or scrolling worlds; use `NewQuadtree[ID](worldBounds, maxItems, maxDepth)` when entities vary widely in size or cluster densely inside a known world rectangle. Both expose `Insert`, `Update`, `Remove`, `Clear`, `Len`, `Query`, and `QueryPoint`. ## Viewport culling (`CullBatch`, `BatchCuller`, `Cull`) Skip drawing off-screen sprites before submitting draw commands to `core.Drawing`: ```go var culler perf.BatchCuller // Inside Canvas.Draw: culler.Draw(spriteBatch, cameraViewBounds, d) ``` - `BatchCuller.Draw(batch, view, d)` reuses an internal scratch `sprite.Batch` for zero per-frame allocations (use the one-liner `perf.CullBatch(batch, view, d)` when convenience matters more than reusing scratch memory). - Use `perf.CullSprites(view, src, dst[:0])`, `perf.SpriteBounds(s)`, `perf.Intersects(a, b)`, or generic `perf.Cull(view, items, boundsOf, dst[:0])` to cull arbitrary world objects. --- Source: https://game.nsgo.dev/docs/physics/ # physics `game/physics` provides 2D collision shapes (`Box`, `Circle`, convex `Polygon`, `Capsule`, `Segment` and `Chain`), exact overlap contacts, anti-tunneling tile resolution with `MoveAndSlide`, and deterministic spatial queries and raycasts on `World`. ```go import "github.com/nsgo-dev/game/pkg/physics" ``` Coordinates follow NSGo's screen space: X increases to the right and Y increases downward. ## Shapes and overlap tests `Box{X, Y, W, H}` (top-left origin) and `Circle{X, Y, R}` (centered) unify under `Shape` (`BoxShape(b)`, `CircleShape(c)`). Test pairs directly with `TestBoxBox`, `TestCircleCircle`, `TestBoxCircle`, `TestCircleBox`, or `TestShapes`: ```go playerBox := physics.Box{X: 32, Y: 48, W: 14, H: 20} coin := physics.Circle{X: 44, Y: 54, R: 6} if c := physics.TestBoxCircle(playerBox, coin); c.Hit { // Normal points from B (coin) toward A (playerBox); // translating A by (NormalX*Depth, NormalY*Depth) separates them. _ = c } ``` Shapes that only touch along an edge or corner with zero penetration report `Hit == false`. Empty shapes (`W <= 0`, `H <= 0`, or `R <= 0`) never overlap anything. ## Polygons, capsules, segments and chains Ramps, wedges, rotated props, characters and terrain drawn as lines need more than boxes and circles. Four more shapes, modelled on Box2D's, share `Shape` and work everywhere a box does: `TestShapes`, `Body`, `Trigger`, `World` queries and raycasts, `RigidBody` and debug drawing. | Shape | Constructor | Use | | --- | --- | --- | | `Polygon` | `NewPolygon(points, radius)`, `NewBoxPolygon(cx, cy, w, h, angle)`, then `PolygonShape(p)` | Convex polygon of 3 to `MaxPolygonVertices` (8) vertices, optionally rounded by `Radius` so it slides over corners | | `Capsule` | `CapsuleShape(Capsule{X1, Y1, X2, Y2, R})` | A segment swept by a radius, for characters that should not snag on tile seams or step edges | | `Segment` | `SegmentShape(Segment{X1, Y1, X2, Y2})` | A line with no thickness, for ledges and walls | | `Chain` | `ChainShape(points, loop)` | A polyline, or a closed loop, for static terrain | `NewPolygon` computes the convex hull of any points, merges near duplicates, drops collinear vertices and winds the result clockwise on screen; it reports `false` for fewer than 3 or more than 8 hull vertices. Write a `Polygon` by hand only when it is already convex and wound that way. ```go ramp, _ := physics.NewPolygon([]core.Point{{X: 0, Y: 200}, {X: 300, Y: 200}, {X: 300, Y: 50}}, 0) hero := physics.CapsuleShape(physics.Capsule{X1: 120, Y1: 100, X2: 120, Y2: 130, R: 8}) if c := physics.TestShapes(hero, physics.PolygonShape(ramp)); c.Hit { // Push the hero out along the slope's normal. _ = c } ``` Every pair reports a hit with its normal and depth. Pairs of boxes and circles keep their own tests; every other pair runs the separating axis test on the shapes' cores (a polygon, a segment or a point) plus their rounding radii, and reports the contact point midway between the two surfaces. Segments and chains have no area: they collide with every shape that has one, from either side, but never with each other, and they contain no point, so `QueryPoint` never returns them. A chain reports its deepest segment contact. At an interior vertex it only uses the normals its neighbouring segments allow, so a box sliding or a ball rolling along a flat run of segments never catches on the seams between them, the ghost collisions Box2D's chains also remove. Its open ends behave like a lone segment's ends. `Shape.Area`, `Shape.Centroid` and `Shape.MomentOfInertia(mass)` give the mass properties a rigid body uses, approximating a rounded polygon by pushing its vertices out as Box2D does. `MoveAndSlide` resolves tiles against a body's bounding box, so a polygon or capsule `Body` moves as its bounds do and keeps its shape. `World.MoveAndSlide` and `World.MoveAndSlideWith` sweep the body's full shape (`Box`, `Circle`, `Polygon` or `Capsule`) against bodies, tiles and static rigid bodies. `DrawShape` outlines polygons (with rounded corners), capsules with their axis, segments and chains, in `PolygonColor`, `CapsuleColor` and `SegmentColor`. `RigidWorld` sweeps fast dynamic bodies against static bodies of every shape, segments and chains included, so a body that would cross one within a step stops at it ([2D rigid bodies](https://game.nsgo.dev/docs/physics2d-rigid/)). Fast dynamic bodies are not swept against each other. ## MoveAndSlide and TileGrid `MoveAndSlide` advances a `*Body` by `(VX*dt, VY*dt)` against any `TileGrid` on each fixed `game.Loop` step, resolving X before Y, zeroing velocity along blocked axes, and subdividing large displacements so fast bodies cannot tunnel through single-tile walls or platforms: ```go grid := physics.NewGrid(40, 20, 16, 16) grid.FillRect(0, 18, 40, 2, physics.TileSolid) grid.FillRect(10, 14, 6, 1, physics.TileOneWay) player := physics.NewBoxBody(32, 200, 12, 16) player.Tag = "player" // Inside game.Loop.Update: player.VY += 900 * float32(dt.Seconds()) // gravity player.OneWayDrop = actions.Pressed("down") && actions.JustPressed("jump") res := physics.MoveAndSlide(player, grid, dt) if res.Grounded && actions.JustPressed("jump") { player.VY = -320 } ``` - **Contact flags**: `MoveAndSlide` updates both the returned `MoveResult` and the body's `Grounded`, `OnCeiling`, `OnLeftWall`, and `OnRightWall` flags, plus per-tile `Contacts` (`Col`, `Row`, `Flags`, `NormalX`, `NormalY`). - **One-way platforms**: tiles marked `TileOneWay` and bodies with `Body.OneWay = true` block movement only from their upward-facing side when the mover starts on that side, unless `Body.OneWayDrop` is `true`. - **Tilemaps**: a [`*tilemap.Tilemap`](https://game.nsgo.dev/docs/tilemap/) (and `*tilemap.WorldStream`) satisfies `TileGrid` and `TileGridOrigin` directly, so pass a loaded tilemap straight to `MoveAndSlide`, `CharacterBody.Move`, `World`, and `RigidWorld` with no adapter. For maps with per-tile collision shapes (slopes, half tiles, bevels, rounded corners, and light occluders), wrap it in a [`tileshape.View`](https://game.nsgo.dev/docs/tileshape/), which is also a `TileGrid` and derives merged `Slope` segments and `StaticShapes` (`Box`, convex `Polygon`, and closed `Chain`) from per-tile shapes. - **Custom `TileGrid`**: implement `TileSize() (float32, float32)`, `GridSize() (int, int)`, and `TileFlagsAt(col, row int) TileFlags` to plug any other map into `MoveAndSlide` and `World`. - **Slopes and tiles together**: `CharacterBody.Move` lifts a character onto a walkable slope before testing tile walls, so the top of a slope that meets a solid tile's top walks onto the tile, and when the character walks off the lower end of a slope it snaps down onto a tile top within `SnapDist`. ## World.MoveAndSlide (bodies, shapes and tiles) `World.MoveAndSlide(body, dt)` and `World.MoveAndSlideWith(body, dt, opts)` sweep a body's actual shape (`Box`, `Circle`, `Polygon` or `Capsule`) against every static or kinematic `Body` in `World.Bodies` (including `OneWay` bodies), solid and one-way tiles in `World.Tiles`, and static `RigidBody` colliders in `World.RigidWorld` (or `MoveOptions.RigidBodies`), filtered by `Layer` and `Mask` (and optional `World.TileLayer` / `World.TileMask`). On each impact it slides the remaining displacement and velocity along the contact normal for up to `MaxSlides` iterations (default `DefaultMaxSlides` = 4), including non-axis-aligned normals such as angled walls, polygons, segments and chains: ```go world := &physics.World{Tiles: grid, RigidWorld: rigid} door := physics.NewBoxBody(80, 96, 8, 32) ledge := physics.NewBoxBody(20, 100, 48, 8) ledge.OneWay = true world.Add(player, door, ledge) // Side-view platformer (default MotionGrounded, Up = (0, -1), FloorMaxAngle = 45°): res := world.MoveAndSlide(player, dt) for _, c := range res.Collisions { // c.Body / c.RigidBody / c.Tile, c.NormalX, c.NormalY, c.Position, c.Remainder _ = c } // Top-down character sliding smoothly along a 30-degree wall: topDown := world.MoveAndSlideWith(hero, dt, physics.MoveOptions{ Mode: physics.MotionFloating, }) _ = topDown.OnWall ``` - **Surface classification**: `SlideResult` reports `OnFloor`, `OnWall`, `OnCeiling`, `OnLeftWall`, `OnRightWall`, `FloorNormal`, `WallNormal`, `CeilingNormal`, `Travel`, and the ordered `Collisions` list. Configure `MoveOptions.UpX`/`UpY` and `FloorMaxAngle` for custom gravity directions or steeper walkable floors, or set `Mode: MotionFloating` for top-down movement where every contact is a wall. - **One-way bodies**: set `Body.OneWay = true` on any body (not only tiles or `MovingPlatform`) so movers pass up or sideways through it, land on its upward-facing surface, and drop through it when `Body.OneWayDrop = true`. `Body.OneWay` is preserved in `WorldSnapshot` and `World.Checksum`. - **`CharacterBody` integration**: assign `CharacterBody.World = world` or call `CharacterBody.MoveWorld(world, slopes, platforms, dt)` so platformer characters collide with doors, blocks, one-way bodies and static rigid bodies while keeping slopes and moving platforms. ## World queries and raycasts `World` groups movable `Bodies` and an optional `Tiles` (`TileGrid`) for deterministic point, overlap, and raycast queries: ```go world := &physics.World{Tiles: grid} world.Add(player, enemy, trigger) // Point query (bodies in World.Bodies order) clicked := world.QueryPoint(mouseWorld.X, mouseWorld.Y) // Shape overlap against bodies and solid tiles hitbox := physics.BoxShape(physics.Box{X: attackX, Y: attackY, W: 24, H: 16}) hits := world.QueryOverlapMask(hitbox, physics.QueryBodies|physics.QueryTiles) for _, h := range hits { if h.Body != nil && h.Body.Tag == "enemy" { damageEnemy(h.Body) } } // Raycast for line of sight or hitscan weapons if hit, ok := world.RaycastFirst(gunPos, targetPos, physics.QueryAll); ok { spawnImpactSpark(hit.Point, hit.NormalX, hit.NormalY) } ``` `QueryMask` flags (zero value means `QueryAll`): | Mask | Targets included | | --- | --- | | `QueryBodies` | All bodies in `World.Bodies` (returned in slice order). | | `QueryTiles` | Solid tiles (`TileSolid`) in `World.Tiles`. | | `QueryOneWay` | One-way tiles (`TileOneWay`); raycasts hit them only when entering the top edge moving downward. | | `QueryAll` | `QueryBodies \| QueryTiles \| QueryOneWay`. | | `QuerySensors` | `RigidBody` sensors, in `RigidWorld` queries only; `QueryAll` leaves them out. | `World.Raycast` returns all hits along the segment sorted by ascending normalized distance `T` in `[0, 1]` (bodies before tiles on ties), while `RaycastFirst` returns the closest hit. A ray hits a segment or chain from either side with the normal facing its start, and misses one it runs along. Remove bodies cleanly with `world.Remove(b)`. `RigidWorld` has the same queries over its rigid bodies, at their true poses, and its `Tiles`: `Raycast(from, to, mask, layerMask)`, `RaycastFirst`, `QueryPoint(x, y, mask, layerMask)` and `QueryOverlap(shape, mask, layerMask)`, with hits that set `RigidBody` ([2D rigid bodies](https://game.nsgo.dev/docs/physics2d-rigid/)). ## Level geometry from Tiled `tilemap.Object.PhysicsShape` turns a Tiled rectangle, ellipse, polygon or polyline object into a shape, and `ObjectLayer.PhysicsBodies` returns a static `Body` for each object of a layer, so terrain drawn in Tiled collides without a hand-written converter: ```go for _, ground := range m.ObjectLayer("collision").PhysicsBodies() { world.Add(ground) // kinematic queries and triggers rigid.AddBody(physics.NewStaticRigidBody(ground.Shape)) // rigid bodies } ``` See [tilemap](https://game.nsgo.dev/docs/tilemap/) for how each object maps to a shape. ### Shape casts Sweep a `Box` or `Circle` along a displacement `(dx, dy)` to get exact analytic times of impact (Minkowski sweeps for box/circle against bodies, oriented `RigidBody` shapes, and tiles, including `TileGridOrigin`): - **`World`**: `ShapeCast(shape, dx, dy, mask)` returns the earliest `ShapeCastHit` (`Fraction`, `Point`, `NormalX`, `NormalY`, `Body`, or `Tile`/`Col`/`Row`/`TileFlags`) and `ShapeCastAll` returns all hits sorted by ascending `Fraction` (bodies in `World.Bodies` order before tiles in row-major `(Row, Col)` order on ties). Use `ShapeCastLayer`/`ShapeCastAllLayer` for `LayerMask` filtering or `ShapeCastWith`/`ShapeCastAllWith` (`ShapeCastOptions`) to combine `QueryMask`, `LayerMask`, and `IgnoreBody`. - **`RigidWorld`**: `ShapeCast(shape, dx, dy, layerMask)`, `ShapeCastAll`, `ShapeCastWith`, and `ShapeCastAllWith` sweep against static, kinematic and dynamic `*RigidBody` shapes (including rotated OBBs via exact 2D moving SAT) and `RigidWorld.Tiles`, supporting `ShapeCastOptions.IgnoreRigidBody`, and populate `ShapeCastHit.RigidBody` or the tile fields. Sensors are hit only when `ShapeCastOptions.QueryMask` has `QuerySensors`. - **Standalone**: `ShapeCastShape(moving, dx, dy, target)` tests a single pair directly. Initial overlaps return `Fraction == 0` with the overlap contact from `TestShapes`, while grazing parallel motion along walls or floors does not snag. ```go // Sweep a 16x16 box down a tile corridor without snagging on the floor or ceiling. probe := physics.BoxShape(physics.Box{X: 16, Y: 16, W: 16, H: 16}) if hit, ok := world.ShapeCast(probe, 160, 0, physics.QueryTiles); ok { // hit.Fraction in [0, 1], hit.Point, hit.NormalX/Y, hit.Col/Row _ = hit } ``` ## Ropes and Soft Bodies (XPBD) `SoftWorld` provides a deterministic, pure-Go Extended Position-Based Dynamics (XPBD) particle and constraint solver for 2D ropes, hanging chains, and deformable soft bodies: - **Particles & constraints**: `Particle` (position, velocity, `InvMass`, `Radius`, `Friction`, `Restitution`, `Pinned`, `Layer`/`Mask`), bilateral & unilateral `DistanceConstraint` (`AddDistance`, `AddTether`), 3-particle angular `BendingConstraint` (`AddBending`), pressurized polygon `AreaConstraint` (`AddArea`), and 2D rigid `ShapeMatchConstraint` (`AddShapeMatch`). - **Two-way rigid-body coupling**: `AttachRigidBody` couples any particle to a `*RigidBody` at a local anchor (`Compliance == 0` for rigid pins, `> 0` for elastic attachments), smoothly substepping attached poses and feeding linear and angular reaction impulses back into the `RigidBody`. - **World & tile collisions**: set `SoftWorld.World`, `SoftWorld.RigidWorld`, and/or `SoftWorld.Tiles` to collide particles against `Box`, `Circle`, oriented `RigidBody` shapes, `TileSolid`, and `TileOneWay` tiles with `LayerMask` filtering (`TileLayer`/`TileMask`). - **Builders & debug drawing**: `AddRope(RopeConfig)` builds inextensible ropes with automatic long-range tethers so heavy attached crates swing without over-stretching; `AddSoftBody(SoftBodyConfig)` builds pressurized or shape-matched soft rings; `DrawSoftWorld(d, sw, style)` renders debug overlays (compiled to a no-op under `-tags release`). ```go rw := &physics.RigidWorld{GravityY: 600} crate := physics.NewRigidBox(120, 12, 24, 24, 10) rw.AddBody(crate) sw := physics.NewSoftWorld() sw.RigidWorld = rw sw.GravityY = 600 rope := sw.AddRope(physics.RopeConfig{ StartX: 0, StartY: 0, EndX: 120, EndY: 0, Segments: 12, TotalMass: 0.5, PinStart: true, }) sw.AttachRigidBody(rope[len(rope)-1], crate, core.Point{Y: -12}, 0) // Inside game.Loop.Update: rw.Step(dt) sw.Step(dt) ``` ## Gravity Scale and Area Overrides `RigidBody` and `CharacterBody` support a per-body `GravityScale` (default `1`, set `0` with `SetGravityScale(0)` for weightless bodies, or negative values to invert gravity). Any `Trigger` (registered via `RigidWorld.AddTrigger` for rigid bodies or `World.AddTrigger` for queries and character controllers) can configure `Trigger.Area` (`AreaSettings`) to override gravity, damping, and fluid buoyancy/drag for overlapping bodies during `RigidWorld.Step` and `CharacterBody.Move`: - **Gravity overrides**: set `GravityMode` to `AreaOverrideCombine`, `AreaOverrideReplace`, or `AreaOverrideAdd` with `Priority` (higher priority wins; equal priority breaks ties by trigger slice order). Use directional `(GravityX, GravityY)` or set `PointGravity: true` with `(GravityPointX, GravityPointY)`, `GravityStrength`, `GravityFalloff` (`GravityFalloffNone`, `GravityFalloffLinear`, `GravityFalloffInverse`, `GravityFalloffInverseSquare`), and `GravityUnitDistance`. - **Damping overrides**: `LinearDampingMode` / `LinearDamping` and `AngularDampingMode` / `AngularDamping` override a `RigidBody`'s base damping using the same priority and combine/replace/add rules. - **Buoyancy and fluid drag**: set `FluidDensity` (mass per unit area) to apply Archimedes buoyancy from the submerged fraction of the body's bounds so a body of density `Mass / Area` floats at submerged fraction `(Mass / Area) / FluidDensity`, paired with `FluidLinearDrag`, `FluidAngularDrag`, and optional current velocity `(FluidVelX, FluidVelY)`. - **Character controllers**: set `CharacterBody.World` (with `World.GravityX` / `World.GravityY` and `World.Triggers`) so `CharacterBody.Move` automatically integrates area-resolved gravity (scaled by `CharacterBody.GravityScale`), fluid drag, and linear damping. Query resolved fields directly with `GravityAt(x, y)` and `AreaEffectAtShape(shape, layer, mask)`. ```go water := &physics.Trigger{ Shape: physics.BoxShape(physics.Box{X: 0, Y: 100, W: 400, H: 200}), Area: physics.AreaSettings{ FluidDensity: 1.0, FluidLinearDrag: 4.0, FluidAngularDrag: 2.0, FluidVelX: 30, }, } rigidWorld.AddTrigger(water) ``` ## Snapshots, Rollback, and Cross-Architecture Determinism `World` and `RigidWorld` support full state snapshots and bit-exact determinism across CPU architectures (amd64 and arm64): - **`Save() / Restore(snap) / Checksum()`**: `World.Save()` returns a versioned `WorldSnapshot` (`SnapshotVersion`) capturing gravity, tile grid, bodies, triggers, and per-trigger enter/stay/exit tracking state. `RigidWorld.Save()` returns a `RigidWorldSnapshot` capturing gravity, solver settings, bodies (including pending force/torque accumulators, gravity-scale flags, sleep state and timers, and the local-space geometry the solver rotates for `Polygon`, `Capsule`, `Segment`, and `Chain` shapes), kinematic and sensor flags and kinematic targets, the warm-start contact cache, a `*Grid` `Tiles` with its tile settings, the contact and sensor overlap state behind `ContactEvents` and `SensorEvents`, sleep settings, triggers/areas, joint-break events, and all built-in joints (`DistanceJoint` including rope/range mode, `SpringJoint`, `RevoluteJoint`, `PrismaticJoint`, `WeldJoint`, `WheelJoint`, and `MouseJoint`, with their limits, motors, springs, reaction impulses, and break thresholds; see [2D Rigid Bodies & Joints](https://game.nsgo.dev/docs/physics2d-rigid/)). - **JSON-serializable plain text**: `WorldSnapshot` and `RigidWorldSnapshot` marshal cleanly with `encoding/json` without `encoding/gob` or custom binary layouts. - **In-place pointer & callback preservation**: `Restore` mutates existing `*Body`, `*RigidBody`, `*Trigger`, and `Joint` instances in place when counts/kinds match, preserving gameplay entity references, `UserData`, and trigger callbacks (`OnEnter`/`OnStay`/`OnExit`) across rollbacks. - **Cross-architecture determinism**: all stepped solver, integration, joint, narrowphase, and area paths, as well as `SoftWorld`'s XPBD step, `CharacterBody` movement, `MoveAndSlide` and tile queries, avoid arm64 fused multiply-add (`FMADD`/`FMSUB`) contraction and FMA-using standard library transcendentals, so saving at step 100, stepping to 200, restoring, and re-stepping produces bit-identical positions, velocities, contacts, events, and `Checksum()` values on both amd64 and arm64. ```go snap := rigidWorld.Save() hashAtSave := rigidWorld.Checksum() // Persist or transmit as plain-text JSON (or keep in a rollback ring buffer): raw, _ := json.Marshal(snap) // Later, restore and re-simulate bit-identically: var restored physics.RigidWorldSnapshot _ = json.Unmarshal(raw, &restored) if err := rigidWorld.Restore(restored); err != nil { return err } _ = hashAtSave ``` ## Authoring in scene files 2D physics bodies, colliders, and triggers can be authored directly in `*.scene.yaml` files using the built-in `body2d`, `collider2d`, and `trigger2d` components from [`sceneformat`](https://game.nsgo.dev/docs/editor/#built-in-physics-components-817), with project-wide gravity, solver iterations, and named collision layers configured under `physics:` in [`game.yaml`](https://game.nsgo.dev/docs/project/). Calling `sceneformat.BuildPhysics(built, gameProject.PhysicsSettings(), lib)` constructs the matching `physics.World` and `physics.RigidWorld`, resolves named `layer` and `mask` lists against `physics.layers`, applies optional `*.physics.yaml` resources, and steps bodies and triggers in sync with `BuiltScene` (including automatically during editor Play mode). --- Source: https://game.nsgo.dev/docs/physics2d-rigid/ # 2D Rigid Bodies & Joints Architecture This document records the design decision for 2D rigid-body dynamics in `github.com/nsgo-dev/game/pkg/physics` ([#320](https://github.com/nsgo-dev/game/issues/320), [#321](https://github.com/nsgo-dev/game/issues/321), [#322](https://github.com/nsgo-dev/game/issues/322), [#804](https://github.com/nsgo-dev/game/issues/804), [#805](https://github.com/nsgo-dev/game/issues/805)). ## Decision Implement a lightweight, pure-Go, deterministic 2D rigid-body and constraint solver (`RigidWorld`, `RigidBody`, and `Joint` types) directly inside `pkg/physics`, rather than binding a C/C++ physics engine (such as Box2D or Chipmunk2D) via cgo or taking on an external Go dependency. ## Rationale 1. **Zero cgo and zero third-party dependencies**: NSGo games target macOS, iOS, Windows, Linux, Android, and Web (WASM). Wrapping Box2D or Chipmunk via cgo adds C/C++ cross-compilation toolchains, platform-specific static libraries, and WASM bridging complexity. A pure-Go solver builds identically on every target with standard `go tool nsgo`. 2. **Determinism on fixed steps**: `game.Loop` steps gameplay at a fixed `dt`. Keeping the solver free of map iteration, background threads, and platform-specific C math libraries ensures identical inputs produce repeatable simulation trajectories across runs and targets. 3. **Unified coordinate system and types**: `RigidBody` reuses `Shape` (`Box`, `Circle`, `Polygon`, `Capsule`, `Segment` and `Chain`), `LayerMask`, and NSGo's screen-space coordinates (+X right, +Y down, clockwise radians) directly, avoiding translation layers between kinematic physics, queries, sprites, and rigid bodies. 4. **Right-sized for 2D games**: Most 2D NSGo games need arcade dynamics—falling crates, stacks, projectiles, ragdolls, pendulums, ropes, and spring suspensions—rather than a full industrial CAD solver. ## Solver Design - **Integration**: Symplectic (semi-implicit) Euler. Forces, gravity, and linear/angular damping update velocities first; the constraint solver corrects velocities; updated velocities then advance positions and angles. - **Broadphase**: sort and sweep. Each pass sorts the bodies' bounding boxes along X, ties broken by body index, sweeps the sorted list for boxes that overlap on both axes, and sorts the pairs by `(i, j)`. That is exactly the set and order of pairs the old `i < j` double loop tested, with the same `LayerMask` filtering, so the contacts and their order do not change; only the work does, which now follows the number of overlapping pairs instead of the square of the number of bodies. Contact detection and every iteration of the positional pass use it. - **Contact generation**: Narrow-phase handles Circle–Circle, Circle–OBB, and OBB–OBB (2D SAT with Sutherland–Hodgman clipping to produce up to 2 contact points so flat box stacks remain stable). Every pair involving a polygon, capsule, segment or chain treats both shapes as rounded hulls, a convex core plus a radius, and runs the same SAT and clipping on the cores, as Box2D's `b2CollidePolygons` does: up to 2 points for faces lying on faces, one point otherwise. A chain yields one manifold per touching segment and drops the normals its interior vertices would wrongly add, so bodies slide and roll across its seams. A manifold of two overlapping shapes also keeps a clipped point that is still up to 1 px apart, which the solver lets close before pushing, so a box resting a hair off level keeps both corners in contact instead of rocking from one to the other. Every point carries a feature id naming the reference face and the incident vertex or clipping plane it came from, and the reference face only changes when another face separates clearly more, so the same physical contact keeps its id from step to step. - **Velocity resolution**: Sequential impulse solver (`RigidWorld.SolverIterations`, defaulting to 10) with accumulated normal and Coulomb friction clamping and a velocity threshold on restitution to prevent micro-bouncing in resting stacks. Solving is warm-started: the normal and friction impulses each contact point ends a step with are cached per pair of bodies, manifold and feature id, scaled by the ratio of step lengths, and applied before the next step's iterations, so a resting stack starts each step already holding its weight. - **Positional correction**: Direct linear projection with slop (`0.01`) after position integration, resolving residual overlap without injecting artificial bounce velocity. - **Continuous collision**: after positions are integrated, a dynamic body is swept from its start pose to its end pose against the static bodies its path crosses when any point of it moved farther than half its thickness that step, or always when it is a `Bullet`. Conservative advancement finds the time of impact, the earliest impact moves the body back to it, and the body's velocity into the surface is removed at every point where its face meets the surface there, the tiles of a flat floor included, with the same restitution the contact solver applies, so a box landing flat stays flat and comes to rest. The impact begins a contact that reports the speed it struck at. A static surface the body rests on at the start of the step does not stop it, and neither does a static piece lying wholly behind that surface, such as the next tile of a tiled floor or the next segment of a flat chain, so a body sliding fast along the ground keeps its speed over the seams. A body fired at a static body it already touches, with no contact with it yet, stops where it is. An impact that would leave a body that is not a `Bullet` only shallowly inside the shape is left to the regular contacts. Fast dynamic bodies are not swept against each other. - **Sleeping**: a dynamic body moving slower than `SleepLinearThreshold` (2 px/s) and turning slower than `SleepAngularThreshold` (2°/s) accumulates rest time. The bodies linked by this step's contacts and joints form an island, and once every body of an island has rested for `TimeToSleep` (0.5 s) the whole island sleeps: its velocities are zeroed and the world neither integrates nor solves it, nor tests contacts between sleeping and static bodies. A sleeping body wakes, with the rest of its island, on `Wake`, a force, torque or impulse, a change to its pose or velocity, a contact with an awake body, a joint to an awake body, the removal or movement of a body it rests on, or a change to the gravity, damping or fluid it rests in. A body that a `MouseJoint` holds, or that a joint with its motor on drives, stays awake while the drive is on, so writing a new `Target` or `MotorSpeed` takes effect on the next step. `RigidBody.Sleeping` reports the state and `RigidWorld.DisableSleep` turns it off. - **Joints**: - `DistanceJoint` (`NewDistanceJoint`, `NewRopeJoint`): fixed-length rod constraint with optional `Stiffness` and XPBD `Compliance`, plus unilateral rope / max-distance mode (`MaxOnly: true`) and slack range mode (`[MinLength, MaxLength]`). - `SpringJoint` (`NewSpringJoint`): damped Hooke's law spring using unconditionally stable implicit impulse integration. - `RevoluteJoint` (`NewRevoluteJoint`): 2-DOF pin/hinge constraint using a 2×2 effective-mass block matrix, with optional angular limits (`EnableLimit`, `LowerAngle`, `UpperAngle`), angular motor (`EnableMotor`, `MotorSpeed`, `MaxMotorTorque`), and `JointAngle()` / `JointSpeed()` readouts. - `PrismaticJoint` (`NewPrismaticJoint`): 1-DOF linear slider along `LocalAxisA` with locked relative rotation (`ReferenceAngle`), optional translation limits (`EnableLimit`, `LowerTranslation`, `UpperTranslation`), linear motor (`EnableMotor`, `MotorSpeed`, `MaxMotorForce`), and `JointTranslation()` / `JointSpeed()` readouts. - `WeldJoint` (`NewWeldJoint`): 3-DOF rigid weld solved with a coupled 3×3 block matrix, or a soft damped spring pose lock via `FrequencyHz`/`DampingRatio` (or direct `Stiffness`/`Damping`). - `WheelJoint` (`NewWheelJoint`): 2D vehicle suspension constraining a wheel hub along `LocalAxisA` with a soft suspension spring (`FrequencyHz`/`DampingRatio` or `Stiffness`/`Damping`), optional suspension travel limits (`EnableLimit`, `LowerTranslation`, `UpperTranslation`), and a rotational drive motor (`EnableMotor`, `MotorSpeed`, `MaxMotorTorque`). - `MouseJoint` (`NewMouseJoint`): single-body target joint pulling `Anchor` toward a settable world `Target` (`SetTarget`) with a damped spring capped at `MaxForce`. - **Connected collisions, reactions, and breaking**: two-body joints disable contact between their connected bodies by default (`CollideConnected: false`). Every built-in joint tracks per-step `ReactionForce() (fx, fy float32)`, `ReactionTorque() float32`, and `Broken() bool`, and supports optional `BreakForce` / `BreakTorque` thresholds. Joints that exceed a threshold are removed deterministically in insertion order before positional correction and reported via `RigidWorld.JointBreakEvents()` and `RigidWorld.OnJointBreak`. ## Trade-offs & Scope - **Supported shapes**: oriented `Box` and `Circle`, convex `Polygon` (up to 8 vertices, optionally rounded) and `Capsule` for dynamic bodies, and `Segment` and `Chain` for static ones. Concave terrain is a `Chain` (or several convex polygons); concave dynamic bodies are out of scope for the built-in solver. - **Continuous collision**: fast bodies are swept against static bodies and tiles only, so a fast body can still pass through a thin dynamic or kinematic body, and the impact ends the body's motion for that step rather than spending the rest of it sliding along the surface. Set `Bullet` on a body that must never end a step inside a static body. - **Sleeping**: an island sleeps as a whole, so one body kept moving (a character pushing against a pile, a body under a constant `ApplyForce`) keeps every body it touches awake. A body moved in place by setting its fields wakes on the next step; changing the shape of a sleeping body does not wake it, so call `Wake` after editing one. - **Scale**: the broadphase and sleeping keep a step proportional to the awake bodies and their contacts. In the performance scenario (`BenchmarkRigidWorld500Bodies` and `BenchmarkRigidWorld500BodiesPacked`), 500 boxes, circles, polygons and capsules falling into a bin take about 2 ms a step while they fall and 5 to 6 ms once the pile is packed and still awake, on one core of a Ryzen 9 3900X running Linux, inside the 16.7 ms of a 60 fps frame. Games requiring large-scale multi-thousand-body simulations can integrate a dedicated physics engine alongside `github.com/nsgo-dev/game`. ## Kinematic bodies, sensors, tiles and contact events - **Kinematic bodies**: `RigidBody.Kinematic` makes a body move only as it is told, by `VX`, `VY` and `AngularVel` (with no gravity, force, damping or area effect) or by `SetTargetPose(x, y, angle)`, which gives the body the velocity that reaches the pose in the next step and lands it exactly there, the way an animation drives a moving platform; a body given no new target stops. The solver treats it as having infinite mass, so it pushes the dynamic bodies in its way and carries the ones resting on it by friction, and nothing moves it. It never collides with static or other kinematic bodies or with tiles, never sleeps, and keeps the bodies it moves against awake. Assigning `X` and `Y` directly teleports it: bodies it lands in, asleep or awake, are pushed out but not given its motion. A kinematic body never uses its mass, but `NewRigidBox`, `NewRigidCircle` and `NewRigidBody` make a body with a mass that is not positive static, and `Static` wins over `Kinematic`, so build it with a positive mass, as below, or clear `Static` after building it with zero. - **Sensors**: `RigidBody.Sensor` makes a body of any kind detect overlaps instead of colliding. After each step, `RigidWorld.SensorEvents()` (and `OnSensor`) lists the bodies that began or ended overlapping a sensor at their final poses. A sensor never detects another sensor, and `World.MoveAndSlide` ignores static sensors. - **Tiles**: `RigidWorld.Tiles` takes any `TileGrid`, the same interface `World` and `MoveAndSlide` use. Each `TileSolid` cell collides with dynamic bodies as a box, and each `TileOneWay` cell as its top face only, catching a body that comes down onto it and letting one from below or the side pass. A face that a neighbouring solid tile covers never pushes: a contact leaning into it is clipped against the tile's open face instead, as a chain does at a flat vertex, so boxes slide and circles and capsules roll across tiled floors without catching on seams. The tiles of one flat surface correct a body's position once, by the deepest of them. `TileLayer` and `TileMask` filter tiles like a body's layers, `TileFriction` (zero means `DefaultTileFriction`, 0.4; negative is frictionless) and `TileRestitution` set their material, fast bodies are swept against them like any static body, and a sleeping body wakes when the tile under it is removed or the grid is moved or resized. - **Queries**: `RigidWorld.Raycast`, `RaycastFirst`, `QueryPoint` and `QueryOverlap` see each body at its true pose (`RigidBody.WorldShape`, a turned box as a polygon), and all but `QueryPoint`, which returns bodies only (read a tile with `TileFlagsAt`), see the tiles too. They return the `RaycastHit` and `OverlapHit` types of `World`'s queries with `RigidBody` set. `ShapeCast`, `ShapeCastAll` and their `With` forms sweep a shape against the same bodies and tiles. `QueryMask` selects bodies, sensors (`QuerySensors`, which `QueryAll` and a zero mask leave out; `QuerySensors` alone selects only sensors, in `ShapeCastOptions.QueryMask` too), solid and one-way tiles, and a `LayerMask` filters bodies by layer but never the tiles, whose `TileLayer` and `TileMask` only decide what they collide with. A ray with an end that is not finite hits nothing. Hits come in a fixed order: by distance for rays and shape casts, bodies in `Bodies` order before tiles in row-major order for overlaps and for ties. Unlike `World`, whose `Raycast`, `RaycastFirst`, `QueryPoint` and `QueryOverlap` leave the layer mask to `Layer` variants, the `RigidWorld` queries take the `QueryMask` and `LayerMask` as arguments, zero meaning all, because a rigid world also needs the mask to reach sensors; code moved between the two adds or drops those arguments. - **Contact events**: after each step, `RigidWorld.ContactEvents()` (and `OnContact`) lists the contacts that began, with their point, normal and `ApproachSpeed`, the speed at which the two closed before the step resolved the contact, and the contacts that ended because the bodies moved more than 0.25 px apart, one left the world or became a sensor, or both became static or kinematic. The normal points from `BodyA` toward `BodyB`, the opposite of `physics3d.ContactEvent`, whose normal points from `BodyB` toward `BodyA`. A body touching any number of tiles counts as one contact with the tiles, so a crate sliding over a tiled floor begins touching it once. A contact begins when the step first finds the bodies overlapping, or when continuous collision stops a fast body at a surface, and ends on the first step that finds them more than 0.25 px apart; contacts between bodies that are asleep carry over, so a resting pile reports nothing. Begin events come in the order the step finds contacts (pairs in `Bodies` order, then each body with the tiles), followed by end events, then the begin events of fast bodies stopped by continuous collision in `Bodies` order, so the same inputs give the same events in the same order on every run and after `Save` and `Restore`. - **Snapshots**: `RigidBodySnapshot` holds `Kinematic`, `Sensor` and a pending or last target, and `RigidWorldSnapshot` holds a `*Grid` `Tiles` (`GridSnapshot` now keeps the grid's origin too), the tile settings, tile entries of the contact cache, and the contacts and sensor overlaps the next step compares its own with. `Restore` clears `ContactEvents` and `SensorEvents`. Tiles of another `TileGrid` type cannot be saved: the snapshot records only that they were there (`CustomTiles`), and `Restore` keeps the caller's `Tiles`, while it clears `Tiles` for a snapshot of a world that had none. These fields raised `SnapshotVersion` to 2; `Restore` still reads version 1 snapshots, as worlds without tiles, and since those hold no contacts to compare with, the first step after restoring one reports a `ContactBegin` for every contact that was already touching. `Checksum` covers them all, so it gives a different digest than earlier releases for any world whose bodies touch. ```go level := physics.NewGrid(40, 12, 16, 16) level.FillRect(0, 10, 40, 1, physics.TileSolid) w := &physics.RigidWorld{GravityY: 600, Tiles: level} lift := physics.NewRigidBox(100, 120, 96, 12, 1) lift.Kinematic = true crate := physics.NewRigidBox(100, 90, 20, 20, 1) w.AddBody(lift, crate) w.OnContact = func(ev physics.ContactEvent) { if ev.Kind == physics.ContactBegin && ev.ApproachSpeed > 200 { playThud(ev.Point, ev.ApproachSpeed) } } // Each fixed step, the lift follows its animation and carries the crate. lift.SetTargetPose(liftX(t), 120, 0) w.Step(dt) if hit, ok := w.RaycastFirst(eye, target, physics.QueryAll, 0); ok && hit.RigidBody == crate { // The crate is in sight, at hit.Point, facing (hit.NormalX, hit.NormalY). } ``` ## Sleeping and fast bodies ```go w := &physics.RigidWorld{GravityY: 600} floor := physics.NewStaticRigidBox(100, 110, 400, 20) crate := physics.NewRigidBox(100, 90, 20, 20, 1) shot := physics.NewRigidCircle(0, 0, 4, 0.1) shot.Bullet = true // never ends a step inside a static body w.AddBody(floor, crate, shot) // ... after half a second at rest: if crate.Sleeping() { crate.ApplyImpulse(0, -100) // wakes it and every body it touches } ``` ## Bodies from any shape `NewRigidBody(shape, mass)` places the body's center of mass at `shape.Centroid()` and takes its inertia from `shape.MomentOfInertia(mass)`; `NewStaticRigidBody(shape)` makes level geometry. A `Box` or `Circle` gives the same body as `NewRigidBox` or `NewRigidCircle`. Segments and chains have no area, so their bodies are always static. A polygon, capsule, segment or chain body keeps its shape in local coordinates and writes `Shape` back rotated by `Angle` after each step, so `World` queries, triggers and `DrawShape` see it at its true pose. A polygon or capsule assigned to `Shape`, in a struct literal or between steps, stays where it is drawn: the next step moves `X` and `Y` to its centroid, so the body turns about its center of mass, and recomputes an `Inertia` the body derived itself (an `Inertia` you set to another value is kept). A segment or chain is anchored at the current `X` and `Y`. ```go ramp, _ := physics.NewPolygon([]core.Point{{X: 0, Y: 50}, {X: 0, Y: 200}, {X: 300, Y: 200}}, 0) rw.AddBody(physics.NewStaticRigidBody(physics.PolygonShape(ramp))) crate := physics.NewRigidBody(physics.PolygonShape(physics.NewBoxPolygon(64.5, 70.6, 20, 20, 0.4636)), 1) rw.AddBody(crate) // slides down the ramp ``` ## Example ```go var rw physics.RigidWorld rw.GravityY = 600 floor := physics.NewStaticRigidBox(160, 220, 320, 20) crate := physics.NewRigidBox(160, 100, 32, 32, 1) pendulum := physics.NewRigidCircle(240, 140, 12, 1) pivot := physics.NewStaticRigidBox(240, 60, 8, 8) rw.AddBody(floor, crate, pendulum, pivot) rope := physics.NewRopeJoint(pivot, pendulum, core.Point{}, core.Point{}, 80) rope.BreakForce = 4000 rw.AddJoint(rope) rw.OnJointBreak = func(ev physics.JointBreakEvent) { // Handle detached rope or destructible link deterministically. _ = ev } loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { rw.Step(dt) }, } ``` --- Source: https://game.nsgo.dev/docs/physics3d/ # physics3d ```go import "github.com/nsgo-dev/game/pkg/physics3d" ``` Compact, deterministic 3D collision detection, raycasting, rigid-body dynamics, and a kinematic character controller written in pure Go. ## Architectural Decision (#180) `physics3d` uses **option (a)**: a self-contained, zero-cgo Go implementation built only on the Go standard library. Why pure Go instead of wrapping a C/C++ physics engine (such as Jolt, Bullet, or PhysX): - **Every NSGo target compiles out of the box**: macOS, Windows, Linux, iOS, Android, and WebAssembly build with a plain `go build` / `go tool nsgo check` — no C/C++ toolchains, per-platform static libraries, or Emscripten/Wasm glue. - **No FFI overhead**: Queries, raycasts, rigid-body steps, and character moves operate directly on Go values with zero cgo boundary crossings. - **Bit-for-bit determinism**: Stepping a `World` with fixed durations from `game.Loop` runs broadphase, narrowphase, impulse solving, and positional correction in a fixed body and contact order with no map-order iteration or wall-clock input. The scope is intentionally focused: boxes (axis-aligned or oriented), spheres, capsules, convex hulls, cylinders, and compound shapes assembled from child colliders, static triangle meshes (`TriMeshCollider`, added with `World.AddTriMesh`), heightfields (`HeightfieldCollider`, added with `World.AddHeightfield`), and voxel grids (`VoxelCollider`, added with `World.AddVoxelCollider`) that collide with bodies and the character controller, exact overlap, raycast, and voxel sweep queries, rigid bodies with linear and angular dynamics, joints, ragdolls, and a capsule character controller. Single-primitive bodies use a scalar (isotropic) inertia, while compound bodies compute a combined `CenterOfMass` and 3×3 symmetric `InvInertiaTensor` (`SymMat3`) from their solid children via the parallel-axis theorem. Contacts between boxes, spheres and capsules use one representative point per collider pair; a pair that involves a convex hull or a cylinder gets up to four points spread over the touching area. ## Coordinate Convention `physics3d` uses a right-handed, Y-up coordinate system (`+X` right, `+Y` up, `+Z` toward the viewer). `NewWorld()` sets default gravity to `(0, -9.81, 0)`. ## Shapes, Overlaps, and Raycasts Five primitives and a compound assembly are wrapped by the tagged `Shape` value (`BoxShape`, `SphereShape`, `CapsuleShape`, `ConvexHullShape`, `CylinderShape`, `CompoundShape`): - `Box` — box defined by `Center` and `HalfExtents` (or constructed via `BoxFromMinMax(min, max)`). It is axis-aligned unless the wrapping `Shape` sets `Rot`, which orients it about its `Center`. `Shape.Transformed(pos, rot)` and `Body.WorldShape()` keep a rotated body's box oriented, so overlap tests, raycasts and debug drawing see its real corners; `Shape.Bounds()` returns the enclosing AABB for broad-phase use. - `Sphere` — `Center` and `Radius`. - `Capsule` — line segment from `A` to `B` swept by `Radius` (or `VerticalCapsule(center, radius, height)`). - `ConvexHull` — a convex polyhedron for props such as rocks, debris, furniture, wedges and low-poly vehicle hulls, built once by `NewConvexHull(points, maxVertices)` and then shared, read-only, by every shape and body that uses it. Its vertices are relative to `Center`, and the wrapping `Shape`'s `Rot` turns it about `Center` as it does a box. - `Cylinder` — a solid cylinder with flat caps whose axis runs from `A` to `B`, of the given `Radius` (or `VerticalCylinder(center, radius, height)`), for barrels, wheels and pillars. A cylinder whose `A` and `B` coincide or whose `Radius` is not positive has no volume, and collisions, raycasts and areas ignore it. - `ShapeCompound` — multiple `CompoundChild` colliders (`Box`, `Sphere`, `Capsule`, `ConvexHull`, `Cylinder`, or nested `ShapeCompound`) on one rigid body, each with its own local `Offset` and `Rot`, optional `Mass` or `Density`, and optional per-child `Trigger`, `Layer`, and `Mask`. ### Convex hulls `NewConvexHull` builds the hull with quickhull: it starts from a tetrahedron of extreme points and adds the point furthest outside the hull until none is left or the hull has `maxVertices` vertices (`DefaultHullVertices`, 64, for a limit of 0 or less, at most `MaxHullVertices`, 256, and at least 4, the fewest vertices a hull with volume has, for a limit of 1 to 3). When the limit stops it early, the hull keeps the most prominent corners and lies inside the full hull. Points inside the hull or within a small tolerance of a face are dropped, and coplanar triangles are merged into polygon faces, so a cube gives 8 vertices and 6 square faces. The result depends only on the points and their order, so the same input always gives the same hull. Points that do not span a volume (fewer than four, all on a plane or a line, or not finite) return `ErrDegenerateHull`. `ConvexHullFromMesh(positions, indices, maxVertices)` builds a hull from a triangle mesh, using only the vertices the indices reference, so a glTF primitive's or a `render3d.Mesh`'s `Positions` and `Indices` go in as they are: ```go doc, _ := gltf.LoadFS(assets, "rock.gltf") prim := doc.Meshes[0].Primitives[0] hull, err := physics3d.ConvexHullFromMesh(prim.Positions, prim.Indices, 32) if err != nil { return err } // Move the hull's centroid to the body's origin, so the body rotates about its center of mass. hull = hull.Recentered() pos := hull.Center hull.Center = physics3d.Vec3{} rock := world.AddBody(physics3d.NewDynamicBody(physics3d.ConvexHullShape(hull), pos, 40)) ``` A hull reports its `Vertices`, `Faces` (vertex indices counter-clockwise seen from outside), `FaceNormals`, `Edges`, `Volume`, `Centroid` and `InertiaTensor(mass)` for uniform density. A body's inertia comes from the hull's exact tensor (the mean of its principal moments, as the scalar inertia above), and a cylinder's from the solid-cylinder formula. ### Compound shapes `CompoundShape(children...)` combines several `CompoundChild` colliders onto a single rigid body so furniture, vehicles, or characters with separate hitboxes move and rotate as one body without fixed joints: ```go leg := physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.06, Y: 0.4, Z: 0.06}}) top := physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.75, Y: 0.05, Z: 0.35}}) tableShape := physics3d.CompoundShape( physics3d.CompoundChild{Shape: top, Offset: physics3d.Vec3{Y: 0.85}, Mass: 3}, physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: -0.69, Y: 0.4, Z: -0.29}, Mass: 1.5}, physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: 0.69, Y: 0.4, Z: -0.29}, Mass: 1.5}, physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: -0.69, Y: 0.4, Z: 0.29}, Mass: 1.5}, physics3d.CompoundChild{Shape: leg, Offset: physics3d.Vec3{X: 0.69, Y: 0.4, Z: 0.29}, Mass: 1.5}, ) // Passing mass 0 derives total mass, CenterOfMass, and InvInertiaTensor from the children. table := world.AddBody(physics3d.NewDynamicBody(tableShape, physics3d.Vec3{}, 0)) ``` - **Mass, center of mass, and inertia**: `ComputeCompoundMassProperties` (called automatically by `AddBody` and `Body.RecomputeMassProperties`) computes combined `Mass`, local `CenterOfMass`, and the 3×3 symmetric `InvInertiaTensor` (`SymMat3`) from all non-trigger children via the parallel-axis theorem. Children can specify explicit `Mass` or `Density`; passing a positive `mass` to `NewDynamicBody` distributes or scales child masses to match. `Body.WorldCenterOfMass()` returns the world-space center of mass, and `Body.ApplyImpulseAtPoint(impulse, worldPoint)` applies linear and angular impulses about it. - **Bounds and queries**: `Shape.Bounds()` encloses every child. Contacts (`ContactEvent.ChildIndexA`/`ChildIndexB`), raycasts (`RaycastHit.ChildIndex`), and overlaps (`OverlapHit.ChildIndex`) test every child and report its zero-based child index (`-1` for non-compound bodies and static colliders). - **Per-child triggers and layers**: setting `CompoundChild.Trigger = true` turns that child into a sensor volume (such as a head hurtbox on a solid character body) that emits `OnTrigger` events without applying impulses, blocking character controllers or CCD sweeps, or contributing to mass and inertia. Optional `CompoundChild.Layer` and `Mask` override the parent `Body.Layer` and `Body.Mask` when non-zero. Overlap tests return a `Contact` whose unit `Normal` points from `B` toward `A` (the direction to translate `A` by `Depth` to separate the shapes): - `TestBoxBox`, `TestOrientedBoxBox` (separating axis theorem over the 15 face and edge axes), `TestSphereSphere`, `TestCapsuleCapsule`, `TestBoxSphere`, `TestBoxCapsule`, `TestSphereCapsule`, and `TestShapes(a, b)`, which handles oriented boxes. - `TestShapes` tests every pair that involves a convex hull or a cylinder, against any other shape, with GJK for the distance and EPA for the penetration depth and normal, in float64 and a fixed iteration order, so the same shapes always give the same contact. `Point` is the center of the touching area (a face resting on a face reports the middle of the overlap, not a corner). The same test runs against each triangle of a `TriMeshCollider` and a `HeightfieldCollider`, and against voxel colliders. - When a capsule's segment passes through a box, `TestBoxCapsule` takes the axis of least penetration over the box faces and the edges crossed with the segment, so moving the box by `Normal*Depth` clears the whole capsule. Crossing capsules, and a sphere centered on a capsule's axis, get a normal perpendicular to the axes rather than an arbitrary one. - `world.QueryOverlap(shape)` returns all overlapping bodies in deterministic insertion order. Raycasts test a `Ray{Origin, Dir, MaxDist}` against standalone shapes (`RaycastBox`, `RaycastSphere`, `RaycastCapsule`, `RaycastConvexHull`, `RaycastCylinder`, `RaycastShape`) or cast a segment through a world (`world.Raycast(from, to)` and `world.RaycastFirst(from, to)`), returning `RaycastHit` entries sorted by ascending `T` in `[0, 1]` with world-space `Point`, `Distance`, and outward unit `Normal`. A ray that starts inside any shape hits it at `T` 0 with `Point` at the origin and `Normal` facing back along the ray (`-Dir`). ### Shape Casts Sweep any `Shape` (`Box`, `Sphere`, `Capsule`, or `ShapeCompound` composed of them) with a `Quat` orientation from `origin` along displacement `delta` against bodies, triangle meshes (`TriMeshCollider`), heightfields (`HeightfieldCollider`), and voxel colliders (`VoxelCollider`): - `world.ShapeCast(shape, origin, rot, delta)` returns the earliest `RaycastHit` (`Body`/`TriMesh`/`Heightfield`/`Voxel`, `ChildIndex`, `T`, `Distance`, `Point`, `Normal`); `world.ShapeCastAll(...)` returns all hits sorted by ascending `T` with the same deterministic tie-breaking order as `Raycast` (`Body` < `TriMesh` < `Heightfield` < `Voxel`, then ascending ID and `ChildIndex`). Compound bodies are tested per child with per-child `Layer` and `Trigger` filtering. - Use `world.ShapeCastLayer(shape, origin, rot, delta, mask, ignore)` and `ShapeCastAllLayer` for `LayerMask` filtering and excluding a `*Body`, or `ShapeCastWith` / `ShapeCastAllWith` (`ShapeCastOptions`) to also exclude `IgnoreBodyID` or triggers (`IgnoreTriggers`). - Standalone helpers `ShapeCastShape(moving, delta, target)`, `TriMeshCollider.ShapeCast(shape, delta)`, and `HeightfieldCollider.ShapeCast(shape, delta)` test individual colliders directly. Sphere, box/OBB, and box-triangle pairs use exact analytic sweeps (Minkowski sums and moving SAT); capsule-box, capsule-capsule, and capsule-triangle pairs use exact-distance conservative advancement (`<= 1e-4`). Initial overlaps return `T == 0`, `Distance == 0`, and the `TestShapes` separation normal. ```go // Third-person camera spring arm that pulls forward before clipping a wall. cameraProbe := physics3d.SphereShape(physics3d.Sphere{Radius: 0.25}) camPos := pivot.Add(armDelta) if hit, ok := world.ShapeCastLayer(cameraProbe, pivot, physics3d.QuatIdentity(), armDelta, physics3d.LayerAll, playerBody); ok { camPos = pivot.Add(armDelta.Scale(hit.T)) } ``` ## Rigid Bodies A `World` holds static (`Static: true` or zero mass) and dynamic `Body` values and advances them in `Step(dt)` using velocity-first symplectic Euler integration (with implicit midpoint gyroscopic Euler torque), deterministic collision detection with multi-point contact manifolds, per-point warm-started iterative impulse solving with symmetric block LCP normals and 3D Coulomb friction, non-linear Gauss-Seidel positional correction, and automatic sleeping for settled bodies. ```go world := physics3d.NewWorld() world.AddBody(physics3d.NewStaticBody( physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 20, Y: 1, Z: 20}}), physics3d.Vec3{Y: -1}, )) crate := world.AddBody(physics3d.NewDynamicBody( physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}}), physics3d.Vec3{Y: 3}, 1.0, )) loop := &game.Loop{ Update: func(dt time.Duration) { world.Step(dt) _ = crate.Pos }, } ``` ### Inertia tensors, gyroscopic motion, and per-body overrides Every dynamic `Body` computes a body-space inverse inertia tensor (`InvInertiaTensor SymMat3`) from its `Shape`, `Mass`, and `CenterOfMass`: exact diagonal principal moments for axis-aligned boxes, spheres, capsules, and cylinders, and full symmetric tensors (including the parallel-axis shift) for offset, rotated, convex-hull, and compound shapes. At each step the solver, all seven built-in `Joint3D` types, and `game/vehicle` rotate `InvInertiaTensor` into world space (`Body.WorldInvInertiaTensor()`), and free angular motion integrates Euler's gyroscopic torque term ($I\dot{\omega} + \omega \times (I\omega) = 0$) via an energy-conserving implicit midpoint update so asymmetric spinning bodies (such as a plank spun near its intermediate principal axis) exhibit realistic Dzhanibekov flips while symmetric cubes remain stable. Override mass distribution per body when needed: - `Body.SetInertia(diag Vec3)` sets diagonal body-space principal moments $(I_x, I_y, I_z)$ directly (zero axes lock rotation about that axis; `DiagSymMat3` constructs a diagonal `SymMat3`). - `Body.SetInertiaTensor(inertia SymMat3)` sets a full symmetric body-space inertia tensor and inverts it into `InvInertiaTensor`. - `Body.SetCenterOfMass(localCOM Vec3)` shifts the local center of mass and recomputes `InvInertiaTensor` about the new pivot unless inertia was explicitly overridden. - `Body.RecomputeMassProperties()` clears custom inertia and center-of-mass overrides and restores the shape-derived defaults. - `LockRotation` keeps a dynamic body from rotating. Inputs that are not finite (a NaN velocity or mass) fall back to defaults in `AddBody`, and a kinematic body without mass stays kinematic. ### Contact manifolds, warm starting, and stacking Face-to-face collisions generate persistent multi-point contact manifolds rather than a single contact point: - **Box-box and convex hull / cylinder faces**: Sutherland-Hodgman face clipping produces up to 4 contact points with persistent feature IDs and per-point penetration depths, reduced deterministically to maximize support area. - **Capsule on face**: capsules resting on boxes, convex hulls, cylinder caps, or triangles clip the centerline segment against the reference face prism to produce up to 2 contact points (collapsing to 1 when standing upright on an end cap). - **Per-point warm starting and friction**: each manifold point tracks its own accumulated normal and tangent impulses across steps (matched by feature ID first, then local-space proximity). Normal impulses for 2–4 point manifolds are solved simultaneously with a regularized float64 active-set Cholesky LCP so flat faces never incur corner-order tipping torque, followed by per-point 3D Coulomb friction and planar non-linear Gauss-Seidel positional/angular correction. Contact impulses act at each contact point, so friction makes a sliding sphere roll, a flat box rests without rocking, and a box standing on an edge tips over onto a face. ### Physics materials Attach a shared `*PhysicsMaterial` (`Friction`, `Restitution`, `LinearDamping`, `AngularDamping`) to `Body.Material`, or copy its values onto a body with `Body.ApplyMaterial(mat)`. When `Body.Material` is non-nil, contact resolution and velocity damping read the material's clamped surface properties directly (`Friction >= 0`, `Restitution` in `[0, 1]`, non-negative damping), so editing a shared material takes effect across every body referencing it. Shared `*.physics.yaml` files from [`game/resource`](https://game.nsgo.dev/docs/resources/#physicsmaterial) apply to 3D bodies with `mat.ApplyTo3D(body)`. Settled bodies sleep. A sleeping body wakes when a moving dynamic body or a kinematic body (moving by velocity or by setting `Pos`/`Rot` directly) touches it, when a body jointed to it moves, when one of its contacts ends (its support moved away), when a `VoxelCollider` block near it changes solidity or disappears under it, and on `Wake`, `WakeInBox`, `ApplyImpulse`, and the removal of bodies, meshes, voxel colliders, or joints. Ordinary stacks (such as a 10-box uniform tower) settle cleanly and stand without residual drift from multi-point manifolds and per-point warm starting alone. Scoped shock propagation stays active only for vertical support columns (within about 45° of `-Gravity`) that contain a large upper-to-lower mass ratio (`> 4:1`, such as a 100 kg box on 1 kg boxes) or more than 12 stacked dynamic bodies, making one bottom-up pass that treats the lower body as immovable and keeps overlap near 1 mm. A body still sunk more than 5 mm into a neighbor does not fall asleep, and a sleeping body pushed deeper than 1 cm wakes, so sleeping never freezes an overlap in place. With zero gravity there is no "up" and the shock pass is skipped. A shape that ends up below a heightfield's surface is pushed out upward, by the depth measured along the upward triangle normal, so it clears the surface in one correction rather than by the shallower distance to the nearest point underneath. A shape beside a cell, such as one at the foot of a step touching the plateau's edge, keeps the depth of its own contact, so it is not lifted onto the plateau. A dynamic body that moves more than half its smallest dimension in one step is swept in sub-steps against static, kinematic and sleeping bodies, triangle meshes, heightfields, and voxel colliders, and stops at the first new overlap, so fast bodies do not tunnel through thin geometry. Contacts the body already has when the step begins, such as the floor under a fast sliding or rolling body, do not stop it unless the body sinks clearly deeper into them. Fast dynamic bodies are not swept against each other. ### Broadphase `World` accelerates body-pair detection, raycasts (`Raycast`, `RaycastFirst`, `RaycastLayer`, `RaycastFirstLayer`), overlaps (`QueryOverlap`, `OverlapLayer`), CCD sweeps, `WakeInBox`, and `CharacterController` queries with separate deterministic static and dynamic AABB trees: - **Separate static and dynamic trees**: static non-trigger bodies, `TriMeshCollider`s, and `HeightfieldCollider`s live in the static tree (each triangle mesh and heightfield stays as a single broadphase entry, backed by its own internal BVH or grid), built top-down for tight spatial partitioning so stationary level geometry costs almost nothing until something moves near it. Dynamic, kinematic, and trigger bodies live in the dynamic tree with fattened AABBs, predictive displacement expansion, and SAH-minimizing rotations so sleeping or slowly moving bodies rarely update the tree. - **Deterministic order**: candidate pairs are sorted into body insertion order and raycast/overlap tie-breaking follows the same deterministic rules as a linear scan, so trajectories, events, and query hits remain bit-identical to a brute-force pass. - **Automatic sync**: `AddBody`, `RemoveBody`, `AddTriMesh`, `RemoveTriMesh`, `AddHeightfield`, `RemoveHeightfield`, `Restore`, and `Step` maintain the broadphase automatically. If you mutate a body's `Pos`, `Rot`, `Shape`, `Static`, or `IsTrigger` fields directly and run raycast or overlap queries before the next `Step`, call `world.SyncBroadphase()` first. ## Voxel Colliders `VoxelCollider` (created with `NewVoxelCollider(grid)` and added with `World.AddVoxelCollider`, or adapted from `game/voxel` via `voxel.NewCollider(w)` / `w.Collider()`) collides bodies, `CharacterController`, CCD, and world raycast/overlap queries directly against any `VoxelGrid` without building a triangle mesh: - **Direct queries**: `QueryBlocks`, `TestShape`, `CollectContacts`, `Raycast` (3D Amanatides & Woo DDA, accelerated when the grid implements `VoxelBoundsGrid`), and `Sweep` (exact Minkowski-sum swept AABB for axis-aligned boxes; sub-stepped binary-search TOI for spheres, capsules, and oriented boxes) visit solid voxels in deterministic `(y, z, x)` order. - **Internal-seam filtering**: faces occluded by adjacent solid blocks are filtered out so crates, spheres, capsules, and characters never snag on flat voxel floor or wall seams. - **Instant edit reflection & wakeup**: block changes take effect immediately with zero rebuild. Grids implementing `VoxelEditNotifier` automatically call `NotifyBlockChanged` / `NotifyReset` (which wake nearby sleeping bodies and stacked contacts via `World.WakeInBox`), while plain `VoxelGrid` implementations still wake bodies whose voxel support disappears on the next `World.Step`. ## glTF, GridMap, and Heightmap Colliders Build static level geometry directly from glTF scenes, `world3d` GridMaps, and standard Go heightmap images without manually unpacking vertices or cell boxes: - **glTF triangle meshes**: `NewTriMeshFromGLTFPrimitive(prim, worldMat)`, `NewTriMeshFromGLTFMesh(mesh, worldMat)`, and `NewTriMeshFromGLTFNode(doc, nodeIdx)` build BVH-accelerated `*TriMeshCollider` values from indexed or non-indexed `Triangles`, `TriangleStrip`, and `TriangleFan` primitives, applying full node world transforms and flipping winding automatically when the transform has a negative determinant. - **glTF collider conventions (`-colonly` & `extras.collider`)**: `World.AddGLTFColliders(doc, opts)` and `BuildGLTFColliders(doc, opts)` recognize Godot-style node name suffixes (`-col`, `-colonly`, `-boxcol`, `-boxcolonly`, `-spherecol`, `-spherecolonly`, `-capsulecol`, `-capsulecolonly`, `-convcol`, `-convcolonly`, case-insensitive and tolerating Blender `.001` duplicate numbering) as well as `node.Extras` (`{"collider": "box" | true | {"shape", "draw", "only", "trigger", "tag", "center", "halfExtents"|"size", "radius", "height", "friction", "restitution", "layer", "mask"}}`). Primitive box and capsule colliders preserve full node rotation as oriented boxes and rotated capsules; `-convcol` / `-convcolonly` build a `TriMeshCollider` until native convex hulls are added. Visual renderers filter out collider-only nodes with `doc.DrawableNodes()` or `node.IsDrawable()` in [`game/gltf`](https://game.nsgo.dev/docs/3d-models-blender/#collision-nodes--colonly-and-extrascollider). Call `GLTFColliders.RemoveFromWorld(world)` when unloading a streamed level. - **Greedy 3D box merging & `GridMap` bodies**: `MergeBoxes(boxes, eps)` greedily merges adjacent axis-aligned boxes along X, then Z, then Y within tolerance `eps` (default `1e-4`), preserving the exact solid volume in deterministic order. On a [`world3d.GridMap`](https://game.nsgo.dev/docs/world3d/#modular-3d-gridmap), `grid.AddCollidersToWorld(world, opts)` extracts cell `ColliderBoxes` and merges adjacent cells into minimal static bodies (set `DisableMerge: true` to emit one body per box). - **Heightfields from `image.Image`**: `NewHeightfieldFromImage(img, HeightfieldImageOptions{...})` builds a `*HeightfieldCollider` from any 8-bit/16-bit grayscale or color `image.Image` (`HeightmapLuminance`, `HeightmapRed`, `HeightmapGreen`, `HeightmapBlue`, `HeightmapAlpha`), with configurable `CellSize` or `WorldWidth`/`WorldDepth`, `MinHeight`/`MaxHeight`, `Origin`, `FlipZ`, and optional `(Cols, Rows)` resampling (`Bilinear: true` for smooth interpolation). For an existing `world3d.Heightmap`, call `hm.Collider()`. ```go doc, err := gltf.LoadFS(assetsFS, "levels/courtyard.glb") if err != nil { return err } levelCols, err := world.AddGLTFColliders(doc, physics3d.GLTFColliderOptions{}) if err != nil { return err } // Render only visual nodes (skips -colonly / draw:false collider nodes): for _, nodeIdx := range doc.DrawableNodes() { drawGLTFNode(doc, nodeIdx) } hf, err := physics3d.NewHeightfieldFromImage(heightImg, physics3d.HeightfieldImageOptions{ WorldWidth: 64, MinHeight: -2, MaxHeight: 18, }) if err == nil { world.AddHeightfield(hf) } _ = levelCols ``` ## Gravity Scale and Area Volumes `Body` and `CharacterController` each support a per-entity `GravityScale` (initialized to `1` by `NewDynamicBody` and `NewCharacterController`; use `SetGravityScale(0)` for weightless objects or negative values to invert gravity). Any trigger body (`Body.IsTrigger = true`) can configure `Body.Area` (`AreaSettings`) to override gravity, linear/angular damping, and fluid buoyancy/drag for overlapping dynamic bodies during `World.Step` and for `CharacterController.Move`: - **Gravity modes & priority**: set `GravityMode` to `AreaOverrideCombine`, `AreaOverrideReplace`, or `AreaOverrideAdd` ordered by `Priority` (higher priority first, deterministic insertion-order tie-breaking). Supports both directional `Gravity` and radial `PointGravity` toward `GravityPoint` with `GravityStrength`, `GravityFalloff` (`GravityFalloffNone`, `GravityFalloffLinear`, `GravityFalloffInverse`, `GravityFalloffInverseSquare`), and `GravityUnitDistance`. - **Damping overrides**: `LinearDampingMode` / `LinearDamping` and `AngularDampingMode` / `AngularDamping` override body damping using the same priority and combine/replace/add rules. - **Buoyancy and fluid drag**: set `FluidDensity` (kg/m³) to apply Archimedes buoyancy from the submerged fraction of each body's bounds so a body with density `Mass / Volume` settles at submerged fraction `(Mass / Volume) / FluidDensity`, alongside `FluidLinearDrag`, `FluidAngularDrag`, and optional `FluidVelocity` current. - **Area shapes**: an area can be any shape. A point is inside a convex hull or a cylinder area by its exact shape, not its bounds, and a hull's or cylinder's buoyant volume is its own (`ConvexHull.Volume`, or πr²h). - **Queries & characters**: call `world.GravityAt(point)` or `world.AreaEffectAtShape(shape, layer, mask)` to inspect the resolved field. `CharacterController.Move` automatically applies overlapping area gravity (scaled by `CharacterController.GravityScale`), fluid drag, and linear damping, and `CharacterController.EffectiveGravity(world)` reports the active gravity vector. ```go water := physics3d.NewStaticBody( physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 20, Y: 5, Z: 20}}), physics3d.Vec3{Y: -5}, ) water.IsTrigger = true water.Area = physics3d.AreaSettings{ FluidDensity: 1000, FluidLinearDrag: 5.0, FluidAngularDrag: 2.0, } world.AddBody(water) ``` ## Joints and Ragdolls `World.AddJoint` solves `DistanceJoint`, `BallJoint`, `SwingTwistJoint`, `HingeJoint`, `SliderJoint`, `FixedJoint`, and `SixDOFJoint` in deterministic insertion order: - `HingeJoint.Angle` is tracked across steps, so a hinge that keeps turning reports angles past ±π and `MinAngle`/`MaxAngle` can span more than one turn. Optional spring and position drives (`DriveTargetAngle`, `DriveStiffness`, `DriveDamping`, `DriveMaxTorque`) pull a hinge smoothly toward a target angle (for self-closing doors or active joints), alongside velocity motors (`MotorTargetVel`, `MotorMaxTorque`). - `SliderJoint` supports optional linear spring and position drives (`DriveTargetPos`, `DriveStiffness`, `DriveDamping`, `DriveMaxForce`) in addition to limits and velocity motors. - `DistanceJoint` is slack while its distance is inside `[MinDistance, MaxDistance]`; `Stiffness` and `Damping` soften the limits, so for a spring with rest length `L` set both limits to `L`. - `SwingTwistJoint` constrains a ball-and-socket pivot with a four-quadrant asymmetric elliptic swing cone (`SwingMin1`, `SwingMax1`, `SwingMin2`, `SwingMax2`) and an independent twist range (`MinTwist`, `MaxTwist`), readable via `SwingAngles()` and `TwistAngle()`. `BuildRagdoll` uses `SwingTwistJoint` for non-hinge limbs (shoulders, hips, spine, head) and `HingeJoint` for elbows, knees, and bones with an explicit `HingeAxis`; `SkeletonJoint` accepts optional asymmetric swing limits and `TwistLimit` / `MinTwist` / `MaxTwist` (defaulting to ±π/4 twist when `SwingLimit > 0` so limbs cannot spin freely around their own axis). - `SixDOFJoint` configures each of the 3 linear (`Linear[0..2]`) and 3 angular (`Angular[0..2]`) axes independently via `AxisConfig`: `Mode` (`AxisFree`, `AxisLocked`, `AxisLimited` with `Min`/`Max`), passive spring `Stiffness`/`Damping`, and `Drive` (`DriveNone`, `DrivePosition`, `DriveVelocity`) toward `TargetPos`/`TargetVel` clamped by `MaxForce`. - Every built-in joint reports its last-step world-space `ReactionForce()` (N) and `ReactionTorque()` (N·m) applied to `BodyB`, and supports optional `BreakForce` and `BreakTorque` thresholds. When a joint exceeds either threshold during `World.Step`, it is marked `Broken()`, removed from the world before positional correction, wakes dynamic bodies, and is reported deterministically in `World.JointBreakEvents()` and `World.OnJointBreak`. ## Character Controller `CharacterController` moves a kinematic capsule (`Pos` at the feet, `Radius`, `Height`) through a `World` via `Move(world, wishMove, dt)`: - Walks across flat ground and glides smoothly up and down slopes up to `MaxSlopeAngle` (default 45°), staying grounded on descents. - Prevents climbing slopes steeper than `MaxSlopeAngle` and slides down them under gravity. - Automatically steps up stairs up to `StepHeight` after verifying headroom clearance, forward progress, and a walkable landing tread. - Stops cleanly and slides tangentially along vertical walls without penetration. - Pushes dynamic bodies it walks into with `PushForce` newtons; with the default 0 they block it like walls. - Tracks the supporting body (`GroundBody`), its velocity at the contact point (`GroundVelocity`), and its per-step yaw rotation (`GroundYawDelta`) in both `CharacterController` and `MoveResult`. - Carries the character by the exact linear and angular motion of kinematic or dynamic ground bodies each step — rotating the capsule around the platform pivot without drift and adding `GroundYawDelta` to `Yaw` when `ApplyPlatformYaw` is enabled (the default in `NewCharacterController`). - Configures velocity inheritance on jump or walk-off via `PlatformOnLeave`: `PlatformLeaveAddVelocity` (default, inherits full ground velocity), `PlatformLeaveAddUpwardVelocity` (inherits horizontal and upward velocity while ignoring downward motion), or `PlatformLeaveDoNothing` (drops platform velocity). - Resolves moving kinematic bodies (sliding doors, walls, lifts) that sweep into the capsule by pushing it out along the separating normal, and reports `Crushed` in `MoveResult` (and `CharacterController.Crushed`) when squeezed between opposing surfaces with no valid depenetration. ```go cc := physics3d.NewCharacterController(physics3d.Vec3{Y: 0}, 0.3, 1.8) cc.PlatformOnLeave = physics3d.PlatformLeaveAddUpwardVelocity loop := &game.Loop{ Update: func(dt time.Duration) { res := cc.Move(world, physics3d.Vec3{X: 3.5}, dt) _, _, _ = res.Pos, res.GroundBody, res.Crushed }, } ``` The controller is not a body in the `World`, so dynamic bodies do not collide with it on their own. To let them, add a kinematic body that follows `Pos` and set `IgnoreBodyID` to its ID. ## Debug Drawing `DrawWorld`, `DrawBody`, `DrawShape`, `DrawCharacter`, `DrawContact` and `DrawRaycast` draw collider wireframes, contacts and rays onto a `core.Drawing` through a view-projection matrix, styled by `DebugStyle`; `DrawLine3D` draws one segment. Convex hulls draw every hull edge in `HullColor`, cylinders draw a ring around each cap and four side lines in `CylinderColor`, and compound shapes draw every child in its primitive's color (with `DrawWorld` marking contacts per colliding child pair); `ConvexHullEdges` and `CylinderEdges` return those segments for other renderers. Release builds compile them to no-ops. Segments are clipped to the camera frustum before projection. By default the near plane is clip `z >= -w`, which matches this package's `Mat4Perspective` and `Mat4Ortho` (`[-1, 1]` depth). For a `[0, 1]` depth projection, such as `math3d.Perspective`, `math3d.Ortho` or a `render3d` camera, set `DebugStyle.DepthZO` (and use `DrawLine3DZO` for single segments): it clips at `z >= 0`, as `render3d.ProjectSegment` does. Without it an orthographic `[0, 1]` camera, whose `w` is 1 everywhere, draws colliders behind the camera. ```go style := physics3d.DefaultDebugStyle() style.DepthZO = true // viewProj comes from math3d.Perspective or math3d.Ortho physics3d.DrawWorld(d, physics3d.Mat4(viewProj), viewport, world, style) ``` ## Ropes, Cloth, and Soft Bodies (XPBD) `SoftWorld` simulates 3D ropes, cloth meshes, and tetrahedral soft bodies using deterministic Extended Position-Based Dynamics (XPBD): - **Particles & constraints**: `Particle` (`Pos`, `Vel`, `InvMass`, `Radius`, `Friction`, `Restitution`, `Pinned`, `Layer`/`Mask`), bilateral & unilateral `DistanceConstraint` (`AddDistance`, `AddTether`), singularity-free dihedral `BendingConstraint` (`AddBending`), and tetrahedral `VolumeConstraint` (`AddVolume`). - **Two-way rigid-body attachments**: `AttachBody` couples particles to dynamic or kinematic `*Body` instances at local anchors (`Compliance == 0` for rigid pins, `> 0` for elastic tethers), returning linear and angular reaction impulses to the attached body and waking sleeping bodies automatically. - **Collisions & layer filtering**: setting `SoftWorld.World` collides particles against non-trigger `Body` shapes (oriented boxes, spheres, capsules), `TriMeshCollider`, and `HeightfieldCollider`, respecting `Layer`/`Mask` filtering. - **Builders & debug drawing**: `AddRope(RopeConfig)` builds inextensible 3D ropes with unilateral long-range tethers; `AddCloth(ClothConfig)` builds a triangulated cloth grid with structural, shear, and dihedral bending constraints (`ClothGrid.Index(col, row)`); `AddSoftBox(SoftBoxConfig)` builds an 8-vertex, 5-tetrahedron deformable cube; `Edges()` returns structural wireframe segments, and `DrawSoftWorld(d, viewProj, viewport, sw, style)` renders them (no-op in `-tags release` builds). ```go world := physics3d.NewWorld() world.AddBody(physics3d.NewStaticBody( physics3d.SphereShape(physics3d.Sphere{Radius: 1.0}), physics3d.Vec3{Y: 1.0}, )) sw := physics3d.NewSoftWorld() sw.World = world sw.AddCloth(physics3d.ClothConfig{ Origin: physics3d.Vec3{X: -1.1, Y: 2.25, Z: -1.1}, Width: 2.2, Height: 2.2, Cols: 10, Rows: 10, PinTopLeft: true, PinTopRight: true, }) // Inside game.Loop.Update: world.Step(dt) sw.Step(dt) ``` ## Snapshots, Rollback, and Cross-Architecture Determinism `World` supports full state snapshots, deterministic FNV-1a 64-bit checksums, and cross-architecture determinism across amd64 and arm64: - **`Save() / Restore(snap) / Checksum()`**: `World.Save()` captures all public and private solver state into a versioned `WorldSnapshot` (`SnapshotVersion`), including gravity and solver/sleep settings, bodies (with their full shape, including a `ConvexHull`'s geometry, `Cylinder`, and `ShapeCompound` children, `CenterOfMass`, `InvInertiaTensor`, custom center-of-mass/inertia override flags, private sleep timers, gravity-scale flags, residual depth, previous interpolation poses, and voxel resting state), sorted per-child multi-point (up to 4 points with feature IDs and local offsets) warm-start contact impulse cache, active contact/trigger pair sets, last-step contact and joint-break events (including compound child indices), ignored body pairs, all 7 built-in `Joint3D` types (`DistanceJoint`, `BallJoint`, `HingeJoint`, `SliderJoint`, `FixedJoint`, `SwingTwistJoint`, `SixDOFJoint`, including unwrapped angle state and last reaction impulses), plus `TriMeshCollider`, `HeightfieldCollider`, and `VoxelGrid` collider bindings. - **JSON-serializable plain text**: `WorldSnapshot` marshals cleanly with `encoding/json` (no `encoding/gob` or custom binary layout). - **In-place pointer & callback preservation**: `Restore` updates existing `*Body`, `Joint3D`, and collider instances in place when counts/kinds match, rebuilds the broadphase trees deterministically, and preserves gameplay pointers, `UserData`, and world callbacks (`OnContact`, `OnTrigger`, `OnJointBreak`). - **Cross-architecture determinism**: all stepped 3D integration, broadphase, narrowphase (GJK/EPA/SAT, OBB, mesh/heightfield, voxel), sequential impulse solver, joint, area, and `vehicle` suspension/tire paths avoid arm64 FMA contraction and FMA-using standard library transcendentals, ensuring bit-identical trajectories and `Checksum()` values on amd64 and arm64. ```go snap := world.Save() hash := world.Checksum() // Serialize to plain-text JSON (or store in a net.SimState rollback buffer): raw, _ := json.Marshal(snap) var restored physics3d.WorldSnapshot _ = json.Unmarshal(raw, &restored) if err := world.Restore(restored); err != nil { return err } _ = hash ``` ## Authoring in scene files 3D physics bodies, colliders, and triggers can be authored directly in `*.scene.yaml` files with the built-in `body3d`, `collider3d`, and `trigger3d` components from [`sceneformat`](https://game.nsgo.dev/docs/editor/#built-in-physics-components-817), using 3D gravity, solver iterations, and named collision layers defined under `physics:` in [`game.yaml`](https://game.nsgo.dev/docs/project/). `body3d` supports `static`, `dynamic`, `kinematic`, and `trigger` kinds, `layer`/`mask`, and `physicsMaterial` / `material` paths; `collider3d` supports `box`, `sphere`, `capsule`, `cylinder`, `convex` and static `trimesh` from the object's model or mesh, and static `heightfield` from a `*.terrain.yaml` file, with local `offsetX`/`offsetY`/`offsetZ` and `rotX`/`rotY`/`rotZ`. `sceneformat.BuildPhysics(built, gameProject.PhysicsSettings(), lib)` populates `physics3d.World` (`Bodies3D`, `TriMeshes3D`, `Heightfields3D`), resolves named `layer` and `mask` lists, applies `*.physics.yaml` files, and keeps body poses synchronized with `BuiltScene` and the editor's Play mode. In the 3D editor viewport, switch to `Gizmo3DCollider` (`shift+c`) to drag collider size handles as single undo steps or press **Fit to Model Bounds** (`Editor.FitCollider3DToBounds`) to match a collider to its model's bounds. --- Source: https://game.nsgo.dev/docs/pixelfx/ # pixelfx `game/pixelfx` is a Go port of [pixelfx](https://github.com/patch-gg/pixelfx), a library of pixel art effects and animations under the MIT license. Each effect is a small procedural program (fire, explosions, magic, weather, UI, pickups, transitions, critters, and character moves acted out with wind-up, hit-stop and recovery) that takes a palette, a seed and placement options and draws a frame with a back layer, a front layer and additive light. A game built on NSGo plays, recolors and mirrors them at run time and exports them as sprite sheets, with no JavaScript. ```go import ( "github.com/nsgo-dev/game/pkg/pixelfx" _ "github.com/nsgo-dev/game/pkg/pixelfx/fire" // registers fire/torch and the rest of its category ) ``` The port follows pixelfx at commit `5294518ce7c72e48b6100a744596e0acf57f2826` with the same math in float64 and in the same order, so it draws the same pixels: every category's tests compare its effects with frames pixelfx itself rendered (see [Parity with pixelfx](https://game.nsgo.dev/docs/pixelfx/#parity-with-pixelfx)). ## Packages | Package | What it holds | | --- | --- | | `game/pixelfx` | The core: frames and compositing, the painter, randomness and noise, particles, the simulation, colors and palettes, the two pixel fonts, the acting system (rig, poses, acts, chains), the effect registry, sprite sheet export and the view helper | | `game/pixelfx/arcane` | Arcane magic: arcane beam, arcane missiles, arcane orb, blink in, blink out, magic circle cast, mana burst, portal, rune circle, spell charge, star fall and time stop | | `game/pixelfx/fire` | Fire: brazier, campfire, candle, fire breath, fire ring, fire tornado, fireball, flame pillar, flamethrower, meteor, spirit flame and torch | | `game/pixelfx/explosions` | Explosions: barrel explosion, big explosion, cartoon POW, dirt explosion, firework burst, firework rocket, grenade, implosion, nuke, plasma explosion, small explosion and smoke bomb | | `game/pixelfx/holy` | Holy: blessing, divine shield, feather burst, halo, heal, healing ring, holy pillar, resurrection, smite and sunburst | | `game/pixelfx/impacts` | Impacts: blunt hit, bullet impact, critical hit, ground slam, heavy landing, hit flash, hit spark, impact frame, parry, ricochet and shield block | | `game/pixelfx/lightning` | Lightning: ball lightning, chain lightning, charge up, electrified, lightning strike, plasma ball, spark arc, storm cloud, tesla coil, thunderclap and zap hit | | `game/pixelfx/melee` | Melee attacks, each acted out by the stock character with its weapon: claw swipe, dagger flurry, double slash, hammer smash, heavy cleave, scythe reap, spear sweep, spin slash, sword slash, thrust, uppercut and whip crack. Their size options (`radius`, `reach`, `length`) are kept between 1 and 416 px | | `game/pixelfx/moves` | Moves acted out by a character: arrow shot, dash strike, earth stomp, fireball throw, ground pound, holy smite, ice lance throw, lightning call, meteor call, pistol shots, rocket launcher and sword combo | | `game/pixelfx/critters` | Critters: bat, bird, butterfly, eyeball, fish school, flying skull, frog, ghost, jellyfish, slime, snake and wisp | | `game/pixelfx/ice` | Ice: blizzard vortex, freeze, frost breath, frost nova, ice crystal, ice lance, ice shatter, ice spikes, icicle fall and snowflake burst | | `game/pixelfx/nature` | Nature: acid splash, boulder, earth spike, healing bloom, leaf storm, poison cloud, quake, root snare, spore burst, thorns, tornado, toxic puddle and vine whip | | `game/pixelfx/pickups` | Pickups: chest open, coin spin, collect burst, crystal shard, gem spin, heart pickup, key glint, loot beam, potion, power star and XP orb | | `game/pixelfx/projectiles` | Projectiles (13 effects): `arrow`, `bullet-tracer`, `cannonball`, `energy-disc`, `flare`, `homing-missile`, `laser-bolt`, `magic-missile`, `muzzle-pistol`, `muzzle-shotgun`, `muzzle-smg`, `plasma-shot`, `rocket` | | `game/pixelfx/scifi` | Sci-fi: `emp-blast`, `energy-core`, `force-field`, `glitch`, `hologram`, `jetpack`, `laser-grid`, `scanner`, `teleporter-pad`, `tractor-beam`, `warp-in`, `warp-out` | | `game/pixelfx/shadow` | Shadow: black hole, curse, dark explosion, eclipse, grasping hands, hex sigil, life steal, necro skulls, shadow flames, shadow tendrils, soul drain, void orb | | `game/pixelfx/spawn` | Spawn and death: coin drop, disintegrate, dissolve burn, egg hatch, poof, respawn beam, shatter death, soul rise, spawn portal and summon rise | | `game/pixelfx/status` | Status effects on a character: bleeding, burning, charmed, confused, cursed, frozen, haste, petrified, poisoned, rage, sleep, slowed and stunned | | `game/pixelfx/transitions` | Screen transitions (320 x 180): blinds, burn away, CRT off, diamond wipe, glitch wipe, iris, pixel dissolve, shatter wipe, slash wipe and star iris | | `game/pixelfx/ui` | UI: achievement, coin collect, combo counter, confetti, countdown, crit number, damage number, exclamation, health bar hit, heart lost, level up and quest complete | | `game/pixelfx/water` | Water: bubbles, drip, fountain, geyser, rain splash, ripples, splash, water jet, water orb, waterfall, wave crash and whirlpool | | `game/pixelfx/weather` | Weather loops: aurora, blizzard, cherry blossoms, clouds, falling leaves, fireflies, fog, god rays, rain, shooting stars, snow and storm | Effects live in one subpackage per category, which registers its effects as `"/"` when it is imported, so a game links only the categories it imports. See [Porting a category](https://game.nsgo.dev/docs/pixelfx/#porting-a-category) for how each category is structured. ## Playing an effect An `Effect` holds its `Meta` (name, description, tags, frame size, the origin its local (0, 0) sits at, duration, loop or one-shot, frame rate, preview backdrop, stock actor and its options with their defaults) and `New`, which starts it. `NewPlayer` starts one with `Options`: `X` and `Y` place its origin in the frame, `Flip` mirrors it, `Angle` turns it, `Light` scales its glow, and `Values` sets its own options by name over the defaults, such as `seed` and `palette`. A palette of a different length than the default is resampled to it, so any ramp recolors any effect. `Set` checks nothing itself: a value whose kind the option does not take (a number stands for a bool, and a color for a palette of that one color) or an empty palette is ignored and the default kept, so compare a value with `Meta.Default` first to report a mistake. ```go e, _ := pixelfx.Lookup("fire/torch") p := pixelfx.NewPlayer(e, pixelfx.Options{X: 36, Y: 94}. Set("palette", pixelfx.RampOf(pixelfx.Ramps["ice"])). Set("seed", pixelfx.Num(9))) frame := pixelfx.NewFrame(e.Meta.Size[0], e.Meta.Size[1], 0, 0) // each frame of the game: p.Update(dt) frame.Clear() p.Draw(frame, pixelfx.LayerBoth) ``` `Update` steps simulations at 120 Hz or finer whatever the game's frame rate, so an effect looks the same at any frame rate. `Draw` with `LayerBack` draws what goes behind a character and `LayerFront` what goes in front, so a character can stand between them. `Stop` lets a loop fade out over 0.3 seconds and cuts a one-shot short; `Done` reports when it has ended. A frame holds opaque color (`Color`) and additive light (`Light`). `Composite` puts them together as RGBA bytes over transparency, a flat color or a backdrop: over transparency, light becomes color with alpha, which reads as additive over dark backgrounds. ## Showing frames in NSGo `Image` turns frames into an NSGo image source: `Set` composites a frame over transparency into premultiplied pixels and steps the source's version, so the same `core.Image`, canvas or shader shows each new frame in place. `View` is a canvas that draws a source scaled up with smoothing off, as pixel art wants; any scale is accepted, and a whole number keeps every pixel the same size: ```go var img pixelfx.Image src := core.NewSignalFunc(cx, core.ImageSource{}, nil) // in the game's frame callback, after drawing the frame: src.Set(img.Set(frame)) // in the UI: pixelfx.View{Source: src.Get, Scale: 4} ``` `DrawScaled` draws one source the same way inside a canvas of your own. ## Sprite sheets `Render` renders every frame of an effect the way pixelfx renders a sprite sheet: at its own frame rate (or the one given), round(duration × fps) frames, one more for a one-shot so its last frame is its end, with light eased out over the 8 pixels at each edge unless the effect fills the screen. `Frames.Sheet` lays them out in a grid and writes Aseprite JSON (json-array) that `sprite.LoadAtlas` reads: each frame's rectangle, its duration (1000 / fps milliseconds, rounded) and its pivot at the effect's origin, one frame tag that loops a loop and plays a one-shot once, and pixelfx's own meta (`id`, `fps`, `loop`, `frameSize`, `pivot`, `columns`, and an act's timing). The sheet stores straight alpha, as PNG does. ```sh nsgo game pixelfx -out assets/fx fire/torch nsgo game pixelfx -set seed=4 -set palette=#102,#215,#43a,#8cf,#fff -flip -out assets/fx -name frost-torch fire/torch nsgo game pixelfx -act -out assets/fx moves/ground-pound nsgo game pixelfx -list ``` `game pixelfx` writes `.png` and `.json` into `-out` (the effect's name, such as `torch`, unless `-name` says otherwise). `-set name=value` sets one of the effect's options: a number, `true` or `false`, a color such as `#4a3f69`, a ramp of colors separated by commas, or text; `-list` lists the effects with their options and defaults. `-act` renders the effect acted out, the stock character performing it with its target, at 60 frames per second unless `-fps` says otherwise. ```go atlas, err := sprite.LoadAtlas(core.ImageSource{URI: "asset:fx/torch.png"}, torchJSON) anim := atlas.Animations["torch"] // loops, 30 fps, pivot at the torch's origin ``` ## Acting An effect a character acts out has an `Act`: the poses over time (`Key`s, each arriving smoothly, `"out"`, `"in"`, `"line"` or with a `"snap"`), the hits that freeze the picture, shake it and push the straw target, the dust kicked up, and where the targets stand. `Perform` plays it with the stock character, drawn from a 3D skeleton (`Rig`, `Pose`) down to pixels: a pose only says where the hands and feet go and how the body carries itself, and the solver works out every joint. Limbs move on 12 fps steps from each key, so they read as held drawings, while the feet move smoothly. ```go rig := pixelfx.NewRig() w, h, x, y := pixelfx.ActFrameSize(moves.GroundPound, rig) frame := pixelfx.NewFrame(w, h, 0, 0) pf := pixelfx.Perform(moves.GroundPound, pixelfx.Options{X: x, Y: y}, rig) for !pf.Done() { pf.Update(1.0 / 60) // holds still while a hit freezes the picture frame.Clear() pf.Draw(frame, true, true) sx, sy := pf.Shake() // how far to throw the picture _, _ = sx, sy } ``` A game with its own character reads the same timing as plain data with `ActTiming`: the wind-up before the effect starts, the recovery after it, each hit's freeze, shake and push, and the poses. A `Rig` caches the poses it draws as pixelfx does, keyed by every value rounded to a pixel, so give `ActBounds` and `Perform` the same one, as `ActFrameSize` and the sheet export do. `Chain` makes one effect of several, each started at its own time and place, with x and y either numbers or functions of the move's time: a projectile is an effect whose x moves. The moves category is chains of the other categories' effects with an act on top. ## Determinism An effect played with the same options and the same updates draws the same frames on every run: its randomness comes from `Rng` (pixelfx's mulberry32, the same sequence for the same seed) and `Hash`. The tests of each category render each effect twice and compare the bytes. JavaScript's 32-bit conversions (`x | 0`, `x >>> 0`, `Math.round`, `Math.hypot`) are reproduced by `ToInt32`, `ToUint32`, `Round` and `Hypot`. Frames can differ by a step of a channel between machines: Go may fuse a multiply and an add into one instruction on arm64, which amd64 does not, and its `math.Sin`, `math.Cos`, `math.Atan2`, `math.Exp` and `math.Pow` may differ from V8's in the last bit. ## Parity with pixelfx `tools/pixelfxref` renders effects with pixelfx itself, at the pinned commit, into reference PNGs, and `pixelfx/internal/pixelfxtest` renders the same effects with the port and compares them. Both sides render three cases of each effect: - `default`: the effect with its default options, as a sprite sheet renders it, at the frames 25%, 50% and 75% of the way through it; - `flip`: the same, mirrored; - `act`, for an effect a character acts out: the performance at 60 fps, at the first frames whose time reaches 25%, 50% and 75% of the way from the first pose to the end (two loops for a loop). The references are `-.png` in `testdata/ref/` of the effect's category package, and the core has references of its own: the rig drawing a set of poses (every weapon, both hands, turns, the air) in `testdata/ref/rig`, and every shape of the painter (placed plainly, mirrored and turned) and every particle, debris and light of the simulation in `testdata/ref/core`. A frame matches when at most 0.5% of its pixels differ from the reference by more than 2 in any channel; the tolerance is `pixelfxtest.MaxChannelDelta` and `pixelfxtest.MaxDifferingShare`, documented in one place, and only loosened with a written reason. On amd64 the ported effects match to the bit but for the odd pixel, and on arm64 within a step of a channel but for the odd pixel the fused instructions move across an edge. Set `PIXELFXTEST_OUT` to a directory to have frames that differ written there. ## Porting a category Each category is one change against its issue. To port one: 1. Clone pixelfx and move it to the pinned commit: `git clone https://github.com/patch-gg/pixelfx` and `git -C pixelfx switch --detach 5294518ce7c72e48b6100a744596e0acf57f2826`. Do not run its npm install scripts; the reference tool needs only Node 18 or newer, and pixelfx's render code has no dependencies. 2. Port the category's `_lib.js` into `lib.go` of `pkg/pixelfx/` (the subpackage may already hold a few of its functions from the core change) and each effect into a file of its own named after it (`fire-ring.js` becomes `fire_ring.go`), with the upstream file and commit, the MIT license and any Sprite Fusion notice the file carries at its top. Keep pixelfx's math, the order of its float operations and of its calls to the random generator: arguments and calls are evaluated left to right in Go as in JavaScript, but a JavaScript loop condition that draws a random number draws it on every pass, and a constant expression such as `Math.PI + 0.07` must use a variable for π (Go folds constants exactly at compile time, JavaScript rounds each step). 3. Export each effect as a variable of the package (`var FireRing = &pixelfx.Effect{...}`) and register it in an `init` as `"/"`. A JavaScript color or alpha that is a function becomes the painter's `...Fn` method; options become `Meta.Options` with their defaults; an `act` becomes `Act`, with `Opt` for a hit's values pixelfx defaults when they are left out. 4. Render the references: `node tools/pixelfxref/render.mjs --pixelfx `, and add the category's `parity_test.go` calling `pixelfxtest.CheckEffect` and `pixelfxtest.CheckDeterministic` for each effect, with a `pixelfxtest.BenchmarkFrames` benchmark, as `pixelfx/fire` does. 5. Import the category in `cmd/game/pixelfx.go` so `game pixelfx` renders it, keep its row in the stability tables and its `example_test.go`, update the table above and its Chinese twin, and add a changelog fragment. When a frame differs beyond the tolerance, write it out with `PIXELFXTEST_OUT` and compare it with the reference: a shape out of place is a porting mistake (often the order of random draws), a step of a channel here and there is floating point. ## License The port is under pixelfx's MIT license: `pkg/pixelfx/LICENSE` holds its text and `NOTICE.md` its notices, Sprite Fusion's for the simulation and the effects adapted from its VFX, and Hollow Crown's for the acting system. The Patch Pixel font of pixelfx's gallery is not MIT licensed and is not ported; the two pixel fonts drawn in code are. --- Source: https://game.nsgo.dev/docs/placeholder/ # Placeholder Assets `game/placeholder` is a small asset pack to prototype with: sprite sheets, a tileset with a Tiled tileset and a sample level, a pixel font, sound effects and a music loop, and three glTF models, each image and sound with its [import settings sidecar](https://game.nsgo.dev/docs/cli/#assets). Every file is an original work drawn, synthesized or modeled in Go for this repository, and all of them are dedicated to the public domain under [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/): a game may use, change and ship them, commercially or not, without asking and without giving credit. ```go import "github.com/nsgo-dev/game/pkg/placeholder" ``` The examples and the tutorial use only this pack or assets of their own whose license is written down; see [Credits in this repository](https://game.nsgo.dev/docs/placeholder/#credits-in-this-repository). ## What it holds The files live in `pkg/placeholder/pack`, which the package embeds and `placeholder.FS()` returns: | Folder | Files | What they are | | --- | --- | --- | | `sprites/` | `player`, `slime`, `bat`, `coin`, `items`, `effects`, `ui`, each `.png`, `.json` and `.png.import.yaml` | Rows of 16×16 pixel-art frames, an Aseprite JSON array export of each with its animations as frame tags, and a sidecar that slices the sheet on the same grid | | `tiles/` | `tileset.png`, `tileset.tsj`, `level.tmj`, `tileset.png.import.yaml` | 32 tiles of 16×16, their Tiled tileset with each tile's type, properties and animation, and a 40×15 sample level | | `fonts/` | `pixel.png`, `pixel.fnt`, `pixel.png.import.yaml` | Placeholder Pixel, a proportional font of printable ASCII, as an AngelCode BMFont | | `sounds/` | `jump`, `coin`, `hit`, `explosion`, `shoot`, `powerup`, `click`, `select`, `music_loop`, each `.wav` and `.wav.import.yaml` | 22050 Hz mono WAV effects and a four-bar music loop | | `models/` | `crate.glb`, `robot_arm.gltf`, `gem.glb` | glTF 2.0 models, +Y up, -Z forward, standing on the origin | | | `CREDITS.md` | Every file with its kind and license | The sprite sheets and their animations: | Sheet | Frames | Animations (frame tags) | | --- | --- | --- | | `player` | 8 | `idle` (0–1), `run` (2–5), `jump` (6), `hurt` (7) | | `slime` | 4 | `idle` (0–3) | | `bat` | 4 | `fly` (0–3) | | `coin` | 4 | `spin` (0–3) | | `items` | 8 | `gem`, `heart`, `key`, `star`, `potion`, `bomb`, `shield`, `flag`, one frame each | | `effects` | 8 | `explosion` (0–4, plays once), `sparkle` (5–6), `bullet` (7) | | `ui` | 4 | `panel`, `button`, `button_pressed`, `cursor`, one frame each; the panel and both buttons are also nine-slices with 4-pixel borders | Frame `i` of a sheet is named `_`, such as `player_2`. Every frame's pivot is its middle. The tileset's tiles, by id (Tiled's tile id, one less than the map's global id): | Ids | Tiles | Properties | | --- | --- | --- | | 0–4 | grass, dirt, stone, brick, wood | `solid` | | 5 | platform | `oneWay` | | 6 | ladder | `ladder` | | 7 | spikes | `hazard` | | 8–11 | water, animated through 8–11 | `water` | | 12–15 | lava, animated through 12–15 | `hazard` | | 16, 17 | ice, crate | `solid` | | 18–23 | bush, flower, sign, door top, door bottom, wall | | | 24–27 | metal, bonus block, sand, snow | `solid` | | 28, 29 | torch, animated through 28–29 | | | 30, 31 | chain, window | | Package `tilemap` turns the `solid` and `oneWay` properties into the tile flags `TileSolid` and `TileOneWay`; a game reads the others with `Tilemap.TileProperties`. The level has a `decor` and a `ground` tile layer and an `objects` layer: points of type `spawn` (named `player`), `coin`, `gem`, `slime` and `bat`, and an `exit` rectangle over the door. ## Loading it in code Each function reads the embedded files and returns what the matching package loads: ```go player, err := placeholder.Sheet("player") // *sprite.Atlas with Animations["run"] and the rest font, err := placeholder.Font() // *text.Font level, err := placeholder.Level() // *tilemap.Tilemap with its tileset loaded crate, err := placeholder.Model("crate.glb") // *gltf.Document jump, err := placeholder.Sound("jump") // core.AudioSource for audio.LoadSound ``` - `Sheet`, `Font` and `Level` give their images as `core.ImageSource` values holding the PNG's bytes and its size in points, one point a pixel. `Image` does the same for any PNG in the pack. - `FS()` returns the pack as a read-only `fs.FS`, for anything else, such as `fs.ReadFile(placeholder.FS(), "CREDITS.md")`. - `License` is `"CC0-1.0"`, the SPDX identifier of every file. The pack is embedded in a game's binary only when the game imports the package, and adds about 430 KB, two thirds of it the music. ## Copying it into a project To change the art, or to build it into a game's own atlases, copy `pkg/placeholder/pack` into the project, for instance as `art/placeholder`, and build it with [`game assets`](https://game.nsgo.dev/docs/cli/#assets) like any other art. This assets section of `game.yaml` uses every sidecar as it is meant to be read: ```yaml assets: atlases: - name: sprites in: art/placeholder/sprites out: assets textures: - in: art/placeholder/tiles/tileset.png out: assets/tileset.ktx2 - in: art/placeholder/fonts/pixel.png out: assets/pixel.ktx2 audio: - in: art/placeholder/sounds/jump.wav out: assets/jump.wav - in: art/placeholder/sounds/music_loop.wav out: assets/music_loop.wav # and the same for each other sound you use ``` - Each sprite sheet's sidecar slices it into 16×16 frames, which the atlas names `_.png`. The atlas holds frames only; the sheets' animations stay in their JSON files. - The sidecars of the tileset and the font page set the `nearest` filter, which keeps pixel art sharp when it is scaled. - Each effect's sidecar normalizes its peak to -3 dBFS; the music's normalizes it to -6 dBFS, keeps it WAV and loops all of it, which game assets writes into the output's `smpl` chunk. - `game assets` bakes fonts from TrueType and OpenType files, and the pack's font is already a bitmap font, so the font's `pixel.fnt`, like the Tiled `tileset.tsj` and `level.tmj` and the sheets' JSON files, is not a build target. Copy them into the game's bundled assets yourself, beside the PNG pages they name (`pixel.png`, `tileset.png`), and load them with `text.LoadBMFontImage` and `tilemap.LoadTiled`, whose `TilesetLoader.LoadImage` maps the tileset's image path to an image source, as `Font` and `Level` do. The KTX2 textures carry the `nearest` filter, which [`render3d.LoadKTX2`](https://game.nsgo.dev/docs/render3d/) applies to a texture it loads for 3D; `text` and `tilemap` draw from PNG pages, so a 2D game draws the font and the level from them. - A sidecar beside an image or sound that no target reads is refused, so a project that uses only some of the pack copies only those files and their sidecars. ## Regenerating it The generator in `pkg/placeholder/internal/gen` (with the models from `internal/samplegltf`) draws every file but `CREDITS.md`, and writes the same bytes on every run and architecture. A test compares the committed pack with it; after changing the generator, rewrite the pack from the repository root with: ```sh go tool nsgo test ./placeholder -run TestPackMatchesGenerator -update ``` and list any new file in `pack/CREDITS.md`, which a test also checks. ## Credits in this repository The examples, the tutorial, the docs and the project template use only this pack or assets of their own with a written license. A test in `game/placeholder` enforces it: every image, sound, font, model, map or tileset exported by another tool, and atlas exported as JSON beside its image, under `examples/`, `docs/` and `template/` must be listed, with its license, in a `CREDITS.md` in its folder or a folder above it, in a Markdown table with a `License` column. The license is an SPDX identifier such as `CC0-1.0` or `Apache-2.0`, written as it is or as the text of a link, and every file a `CREDITS.md` lists must exist: ```markdown | File | Kind | Author | License | | --- | --- | --- | --- | | `assets/hero.png` | 64×16 sprite sheet | Your name | CC0-1.0 | ``` An example that needs art it cannot draw in code uses the pack instead, or adds its files with such a table, as Cave Run's [`CREDITS.md`](https://github.com/nsgo-dev/game/blob/main/examples/caverun/CREDITS.md) does. --- Source: https://game.nsgo.dev/docs/platformer/ # platformer `github.com/nsgo-dev/game/pkg/platformer` turns a [`physics.CharacterBody`](https://game.nsgo.dev/docs/physics/) into a platformer character with coyote time, jump buffering, variable jump height, wall slides and wall jumps. Each helper's timing is a tunable in a YAML config. ```go import "github.com/nsgo-dev/game/pkg/platformer" ``` Coordinates follow `physics`: X increases to the right and Y increases downward. Speeds are in points per second and are written as positive numbers; the controller applies the direction. ## Controller ```go body := physics.NewCharacterBody(physics.NewBoxBody(32, 200, 12, 16)) ctl, err := platformer.NewController(body, platformer.DefaultConfig()) if err != nil { ... } loop := &game.Loop{ Update: func(dt time.Duration) { r := ctl.Step(platformer.Input{ Move: float32(actions.Axis("move")), JumpPressed: actions.JustPressed("jump"), JumpHeld: actions.Pressed("jump"), }, grid, slopes, platforms, dt) if r.Jump != platformer.JumpNone { playJumpSound() } showWallSlide(r.WallSliding) }, } ``` `Step` runs once per fixed step. It reads the contacts the body's previous `Move` left on it (`Grounded`, `OnLeftWall`, `OnRightWall`), sets the body's velocity from the `Input` and the config, and moves it with `CharacterBody.Move`, so slopes, one-way tiles and moving platforms work as they do for the body alone. To collide against static or kinematic bodies (such as doors, blocks and `Body.OneWay` platforms) and static `RigidBody` colliders alongside tiles, slopes and moving platforms, call `StepWorld(in, world, slopes, platforms, dt)` (or assign `body.World = world`). The `StepResult` reports the `MoveResult`, the jump the step started (`JumpGround`, `JumpWall` or `JumpNone`), whether it cut a jump short (`JumpCut`), slid on a wall (`WallSliding`), ignored horizontal input (`InputLocked`), and which wall the body could jump from (`WallSide`, -1 left, 1 right, 0 none). For a tilemap, pass a [`tileshape.View`](https://game.nsgo.dev/docs/tileshape/) as `grid` and its `Slopes()` (or `AppendSlopesIn` around the body) as `slopes`: the character then walks the slope, 2:1 and half-height tiles drawn in Tiled's collision editor with no hand-placed segments. `Reset` forgets every timer, such as after a respawn, and `SetConfig` swaps the tunables while the game runs. ## Timing Every timing is measured in step time. An event opens a window on the step it happens, and the window stays open on later steps while less than its duration has passed since that step. At a fixed `dt`, a duration `D` covers `ceil(D/dt)` steps counting the event's own step, and a zero duration covers only that step. With `coyote_time: 50ms` at 100 Hz, a jump pressed 1 to 4 steps after the last grounded step still leaves from the ground, and one pressed 5 steps after does not. `game.Loop` passes `dt` as `time.Second/Rate` truncated to whole nanoseconds, so each step is allowed 1ns of slack: at the default 60 Hz, `coyote_time: 100ms` covers 6 steps, not 7. | Helper | Window starts when | Config | | --- | --- | --- | | Coyote time | the body is on the ground | `coyote_time` | | Jump buffer | jump is pressed | `jump_buffer` | | Wall coyote time | the body touches a wall in the air | `wall_coyote_time` | | Wall-jump lock | a wall jump starts | `wall_jump_lock` | - **Coyote time and jump buffer**: a step jumps when a press is still buffered and the body is on the ground or still within coyote time, so a press shortly before landing jumps on landing and a press shortly after running off a ledge still jumps. A jump closes both windows, so one press jumps once. A body that is already rising in the air, such as from a spring, cannot use coyote time, so pressing jump does not replace that launch with a weaker ground jump. - **Variable jump height**: when the jump button is up during a step of a rising controller jump, the upward speed is multiplied by `jump_cut` once, if it is above `jump_cut_min_speed`. A tap that presses and lets go within one step gets the shortest jump. A launch the game sets itself, such as a spring, is never cut: when the body's `VY` differs from the one the previous `Step` left, the controller jump is over. - **Wall slide**: while falling against a wall and pushing into it, the fall speed is capped at `wall_slide_speed`. The contact comes from the previous step's `Move`, which reports a wall only when the body moved into it. - **Wall jump**: a buffered press in the air while touching a wall, or within `wall_coyote_time` of leaving it, starts `wall_jump_speed_x` away from the wall and `wall_jump_speed_y` up. A ground jump wins when both are possible. Horizontal input is then ignored for `wall_jump_lock`, so holding toward the wall does not cancel the push. Setting `wall_slide_speed` or `wall_jump_speed_y` to 0 turns that helper off, `jump_cut: 1` turns off variable height, and `run_speed: 0` leaves horizontal velocity to the game. ## Config file A `Config` is a versioned YAML document. `ParseConfig` refuses unknown fields, a missing or unsupported `version`, negative or non-finite values, `jump_cut` above 1 and trailing documents; durations are Go duration strings. `EncodeConfig` writes a canonical form: every field in a fixed order, durations as Go duration strings and numbers in their shortest form. Encoding a parsed config gives that form, and parsing and encoding the canonical form again gives the same bytes, so a hand-written file with comments, another key order or omitted fields is rewritten in canonical form. `DefaultConfig()` is: ```yaml version: 1 coyote_time: 100ms jump_buffer: 100ms jump_speed: 284 jump_cut: 0.55 jump_cut_min_speed: 110 gravity: 720 max_fall_speed: 320 run_speed: 98 ground_accel: 960 ground_decel: 1150 air_accel: 680 wall_slide_speed: 60 wall_coyote_time: 80ms wall_jump_speed_x: 150 wall_jump_speed_y: 260 wall_jump_lock: 150ms ``` `ground_accel` and `air_accel` move the horizontal speed toward `move * run_speed`, and `ground_decel` slows it on the ground without input; 0 reaches the target at once. `max_fall_speed: 0` leaves the fall uncapped. --- Source: https://game.nsgo.dev/docs/playtest/ # Playtest Define automated playtests in `playtest.yaml`, run bots headless across seeded runs with deterministic input recordings, and check measured metrics against the game's goals. ```go import "github.com/nsgo-dev/game/pkg/playtest" ``` ## `playtest.yaml` `playtest.yaml` is a versioned plain-text YAML file with a published JSON Schema (`https://game.nsgo.dev/schemas/playtest.v1.json`). Unknown fields, missing or unsupported versions, duplicate metric names and invalid goals are refused; `EncodeConfig` writes canonical deterministic YAML that round-trips without changes. ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/playtest.v1.json version: 1 scope: project: dungeon-run scene: level_01 template: platformer2d runs: count: 20 seedStart: 1 rate: 60 speed: 1 maxDuration: 1m30s bot: profile: platformer-runner strategy: Greedy route to the door, jumps at ledges and gaps, 120-220 ms reaction jitter reactionMin: 120ms reactionMax: 220ms params: jumpHoldMs: 220 metrics: - name: finished label: Finished measure: kind: outcome key: finished aggregate: count goal: summary: most first-timers clear floor 1 source: brief.yaml min: 16 - name: median_time label: Median time unit: s measure: kind: timer key: clear_time aggregate: median goal: summary: under a minute source: brief.yaml min: 40 max: 60 - name: frame_time label: Frame time unit: ms measure: kind: perf key: frame_ms aggregate: median goal: summary: 16.7 ms at 60 Hz source: game.yaml max: 16.7 - name: coins_taken label: Coins taken unit: '%' measure: kind: ratio key: coins_taken denomKey: coins_total aggregate: mean goal: summary: every coin on a route source: playtest.yaml min: 100 - name: deaths label: Deaths measure: kind: event key: death aggregate: sum heatMap: true ``` ### Sections - **`scope`**: the `project`, required `scene`, and optional `template`. - **`runs`**: `count`, optional explicit `seeds`, `seedStart` (defaults to `1`), fixed `rate` in steps per second (defaults to `60`), `speed` multiplier metadata (defaults to `1`), and `maxDuration` simulated time limit per run (defaults to `60s`). - **`bot`**: `profile` (such as `platformer-runner`, `topdown-explorer`, `shooter`, `puzzle-solver`, or `card-ai`), optional `strategy` text, `reactionMin` / `reactionMax` human reaction jitter durations, and optional scalar `params`. - **`metrics`**: each metric has a unique `name`, optional `label` and `unit`, a `measure`, and an optional `goal`: - `measure.kind` is `event`, `counter`, `timer`, `outcome`, `ratio` (requiring `denomKey`), or `perf` (`frame_ms`, `update_ms`, `draw_ms`, `p50_frame_ms`, `p95_frame_ms`, `p99_frame_ms`, `max_frame_ms`, `allocs_per_frame`). - `measure.aggregate` is `count`, `sum`, `mean`, `median`, `min`, `max`, `p95`, `p99`, or `rate`. - `measure.heatMap: true` on an `event` metric emits all recorded `(x, y)` coordinates into the report's `heatMaps` section. - `goal` specifies `source` (such as `brief.yaml`, `game.yaml`, or `playtest.yaml`), an optional `summary`, and `min`, `max` (or both for a range), or `equal`. ## Reporting metrics from Go During a run, the game receives a `*playtest.Collector` and calls it to report events, counters, timers and outcome. Every method is nil-safe, so game code can call it unconditionally in both live play and playtest runs: ```go metrics.StartTimer("clear_time") metrics.SetCounter("coins_total", float64(len(coins))) // When collecting a coin: metrics.Event("pickup", float64(cx), float64(cy), coin.ID) metrics.Inc("coins_taken") // When dying: metrics.Event("death", float64(px), float64(py), "slime_pit") // On win or loss: metrics.StopTimer("clear_time") metrics.Finish() // or metrics.Fail("out of lives") ``` Frame time comes from the perf readout: pass `FrameStats: stats` and `GC: gcMon` on `playtest.Sim` (or call `metrics.RecordPerf(stats, gcMon)`), which uses the same averaging and percentile calculations as `game/mcp`'s `game_perf_readout`. For bar charts and matchup matrices in `playtest.report.yaml`, call `metrics.ConfigureSeries` / `metrics.AddSeries` / `metrics.SetSeries` / `metrics.FlagSeries` (emitting `report.Series`, such as hits per wave or shortest solution per level) and `metrics.ConfigureMatrix` / `metrics.RecordMatchup` (emitting `report.Matrices`, such as win rate by deck pair). ## Built-in bot profiles Every built-in profile is deterministic for a given seed and registers itself via `playtest.RegisterBot`: - **`platformer-runner`** (`playtest.ProfilePlatformerRunner`, template `platformer2d`): runs greedily toward `PlatformerObservation.ExitX` and jumps at ledges, gaps and hazards with deterministic human reaction jitter sampled from the per-run `random.Stream` in `[reactionMin, reactionMax]`. Use `playtest.ObservePlatformerGrid` to build a `PlatformerObservation` from a `physics.TileGrid` and hazard boxes. - **`topdown-explorer`** (`playtest.ProfileTopDownExplorer`, template `rpg2d`): walks to the nearest unseen walkable tile via BFS, talks to every NPC once, opens every chest, and stops when finished or when `runs.maxDuration` is reached (configured at `8x` speed in `rpg2d`'s `playtest.yaml`). Supply `ExplorerObservation` and record `goal_time`, `tiles_seen`/`tiles_total`, and `tile_visit` events (`heatMap: true`) for the time-per-tile heat map. - **`shooter`** (`playtest.ProfileShooter`, template `shmup2d`): fires constantly, collects power-ups within `powerUpRange` (default `80` px), and dodges predicted incoming bullets through a reaction-delayed perception buffer (fixed `180ms` when `reactionMin == reactionMax == 180ms`). Use `RecordShooterWave`, `RecordShooterHit` and `RecordShooterPowerUp` to report hits per wave (`hits_per_wave` series) and power-ups taken. - **`puzzle-solver`** (`playtest.ProfilePuzzleSolver`, template `puzzle2d`): pairs `SolvePuzzleBFS` (exact breadth-first search for the shortest solution up to `stateLimit`, default 2,000,000 states) with a human-like player that undoes after `undoAfterBadMoves` (default `3`) consecutive bad moves. Use `EvaluatePuzzlePack` or `NewPuzzlePackSim` to report solvable levels, moves over par, difficulty order dips, and solutions shorter than intended. - **`card-ai`** (`playtest.ProfileCardAI`, template `cards2d`): two greedy 1-turn-lookahead players (`CardAI.ChooseAction`) play every unordered deck pair `matchesPerPair` times, alternating who goes first. Use `RunCardTournament` or `NewCardTournamentSim` to report first-player win rate, median match length, most lopsided pair, deterministic think time, and the `deck_win_rates` matrix. Register custom bot profiles with `playtest.RegisterBot(name, factory)`. The `rpg2d`, `shmup2d`, `puzzle2d`, and `cards2d` project templates each ship a canonical `playtest.yaml` configured for their matching profile. ## Running headless and replaying runs Call `playtest.Run(cfg, makeSim, opts)` directly or wire a test with `playtest.RunTest` so `nsgo game playtest` can execute it: ```go func TestLevel1Playtest(t *testing.T) { playtest.RunTest(t, "playtest.yaml", makeSim) } ``` Then run from the project directory: ```sh nsgo game playtest nsgo game playtest -config playtest.yaml -out playtest.report.yaml -recordings playtest-recordings nsgo game playtest -check ``` Each seeded run wraps the bot in a `replay.Recorder` and writes `/run_NNN_seed_.replay.yaml`, so any run can be replayed deterministically with `replay.NewPlayer` or turned into a `game replay` regression test. The YAML report (`playtest.report.yaml`, `version: 1`) records every run's outcome, metrics, goal statuses (`met`, `missed`, `info`), heat-map points and recording paths. ## Editor MCP tools The editor's MCP server (`game/editor/editormcp`, reached via `nsgo game mcp`) exposes two playtest tools: - `game_playtest` (`run`): validates `playtest.yaml`, runs the playtest headless with replays, writes the YAML report, and returns the structured report and summary. - `playtest_define` (`edit`): validates a proposed metric and returns a canonical `playtest.yaml` diff queued as a pending review (`Server.PlaytestReviews`, `Server.ApplyPlaytestReview`, `Server.DismissPlaytestReview`) without modifying `playtest.yaml` on disk until reviewed. --- Source: https://game.nsgo.dev/docs/presence/ # presence ```go import "github.com/nsgo-dev/game/pkg/presence" ``` `presence` publishes what the player is doing (level, game mode, party size, timestamps, artwork, and custom localization tokens) to Steam and Discord friend lists through a single provider-neutral API. Both built-in providers are pure Go with no cgo or hand-written C: `Discord` speaks Discord's local IPC v1 protocol directly over Unix domain sockets or Windows named pipes, and `Steam` dynamically loads the Steamworks shared library through `purego` to call `ISteamFriends::SetRichPresence` and `ClearRichPresence`. ## Activity An `Activity` describes the player's current state. Every field is optional; providers translate whichever fields are populated into their native representation. | Field | Discord mapping | Steam mapping | | --- | --- | --- | | `Level` | `state` (fallback when `Status` is empty; `details` if `Mode` and `Details` are empty) | `level` key (`%level%`) and `status` summary | | `Mode` | `details` (fallback when `Details` is empty) | `mode` key (`%mode%`) and `status` summary | | `Details` | `details` | `status` summary (when `Status` is empty) | | `Status` | `state` | `status` key | | `PartyID` | `party.id` | `steam_player_group` | | `PartySize`, `PartyMax` | `party.size` (`[size, max]`, clamped so `max >= size`) | `steam_player_group_size` | | `StartTime`, `EndTime` | `timestamps.start`, `timestamps.end` (Unix seconds) | — | | `LargeImage`, `LargeText`, `SmallImage`, `SmallText` | `assets.*` | — | | `JoinSecret` | `secrets.join` | `connect` (when `Custom["connect"]` is unset) | | `Custom` | — | Additional or overriding Steam keys (such as `steam_display`, `connect`, or localization token parameters); setting a key to `""` omits it | ## Updating presence across Steam and Discord A `Manager` fans updates out to every configured `Provider`, deduplicates unchanged activities, optionally throttles bursts with `MinInterval`, and degrades gracefully when one platform client is not running. ```go discord, err := presence.NewDiscord(presence.DiscordConfig{ ClientID: "123456789012345678", }) if err != nil { return err } steam := presence.NewSteam(presence.SteamConfig{ DisplayToken: "#Status_InLevel", }) mgr := presence.NewManager( presence.ManagerConfig{MinInterval: presence.DefaultMinInterval}, steam, discord, ) defer mgr.Close() // Set initial state when entering gameplay: _ = mgr.Update(ctx, presence.Activity{ Mode: "Campaign", Level: "Forest 1-2", PartyID: "squad-42", PartySize: 2, PartyMax: 4, LargeImage: "world_forest", }) // Changing level updates both Steam and Discord while keeping Mode, party and artwork: _ = mgr.SetLevel(ctx, "Cavern 2-1") // Flush throttled updates from your game loop when MinInterval > 0: _ = mgr.Poll(ctx) // Clear presence when returning to the title screen or exiting: _ = mgr.Clear(ctx) ``` - `SetLevel`, `SetMode` and `SetParty` update those fields on the current desired activity while preserving the remaining fields. - Calling `Update` or `SetLevel` with a state equal to what was already sent is a no-op. - When `ManagerConfig.MinInterval` is positive (such as `DefaultMinInterval`, 4 seconds), updates arriving inside the window are coalesced so only the latest state is kept pending; call `Poll(ctx)` once the interval elapses or `Flush(ctx)` to send immediately. - `Clear(ctx)` cancels any pending update and clears presence on every provider. ## Discord IPC `NewDiscord(DiscordConfig{ClientID: ...})` connects lazily on the first `Set` or `Clear` (or eagerly via `Connect(ctx)`): - **macOS and Linux**: scans `discord-ipc-0` through `discord-ipc-9` in `$XDG_RUNTIME_DIR` (including Flatpak `app/com.discordapp.Discord` and Snap `snap.discord`), `$TMPDIR`, `$TMP`, `$TEMP`, and `/tmp`. - **Windows**: opens `\\.\pipe\discord-ipc-0` through `\\.\pipe\discord-ipc-9` via `syscall.CreateFile`. - **Web, iOS and Android**: returns `ErrUnavailable`. Frames use Discord's v1 little-endian header (`[opcode uint32][length uint32][json payload]`). `Discord` performs the v1 handshake (`opcode 0`), responds to `PING` frames with `PONG`, sends `SET_ACTIVITY` (`opcode 1`) with `activity: null` on `Clear`, and automatically attempts one reconnect if an active socket breaks mid-session. Text fields longer than `DiscordMaxTextLength` (128 bytes) are truncated on UTF-8 rune boundaries. ## Steam Rich Presence `NewSteam(SteamConfig{})` loads the Steamworks shared library lazily on desktop targets (`libsteam_api.dylib` on macOS, `libsteam_api.so` on Linux, `steam_api64.dll` / `steam_api.dll` on Windows) next to the executable or on the system loader path, or from `SteamConfig.LibraryPath`. It probes `SteamAPI_SteamFriends_v018`, `v017`, `v015` and `SteamFriends` together with `SteamAPI_ISteamFriends_SetRichPresence` and `SteamAPI_ISteamFriends_ClearRichPresence`. - By default `Steam` assumes the game already initialized Steamworks; set `SteamConfig.AutoInit: true` to call `SteamAPI_Init` when `ISteamFriends` is null (and `SteamAPI_Shutdown` on `Close`). - Keys removed between consecutive `Set` calls are deleted via `SetRichPresence(key, "")` without calling `ClearRichPresence()`, while unchanged keys are skipped. - Keys are validated against Steamworks limits (`SteamMaxKeys = 30`, `SteamMaxKeyLength = 63` bytes; invalid keys return `ErrSteamKeyInvalid` or `ErrSteamTooManyKeys`). Values longer than `SteamMaxValueLength` (255 bytes) are truncated on UTF-8 rune boundaries. - On web, iOS, Android, or when the Steamworks library or client is absent, `Set` and `Clear` return `ErrUnavailable`. ## Graceful degradation If at least one provider in a `Manager` succeeds and the remaining providers return `ErrUnavailable` (for example Steam is running while Discord is closed), `Update`, `SetLevel`, `Clear`, `Poll` and `Flush` return `nil`. If every configured provider returns `ErrUnavailable`, they return `ErrUnavailable`. Real provider errors are joined and returned without short-circuiting healthy providers. Set `ManagerConfig.OnError` to observe every per-provider error, including `ErrUnavailable`. ## Testing Both providers accept injectable backends so tests run deterministically without Discord or Steam installed: - Pass `DiscordConfig.Dial` with a `net.Pipe()` connected to an in-process mock IPC server to verify raw wire frames, handshake, `SET_ACTIVITY`, and `Clear`. - Pass `SteamConfig.Driver` with a mock `SteamDriver` to assert every `SetRichPresence(key, value)` and `ClearRichPresence()` call. - Pass `ManagerConfig.Now` with a controllable clock to test `MinInterval` coalescing without sleeps. --- Source: https://game.nsgo.dev/docs/procgen/ # procgen `github.com/nsgo-dev/game/pkg/procgen` generates 2D levels on a tile grid with four generators: BSP rooms joined by corridors, cellular-automata caves, wave function collapse over a YAML rule file, and hand-made room templates placed on a dungeon layout graph. Every generator takes a [`random.Stream`](https://game.nsgo.dev/docs/determinism/) and draws all of its randomness from it, so the same seed and configuration give the same level, cell for cell, on every operating system and architecture. BSP, Cave and GenerateRooms always leave their walkable cells as one 4-connected region, and so does WFC unless `AllowDisconnected` is set or its rules have no walkable tile. ## Grid A `Grid` is `Width` by `Height` `uint32` values stored row by row in `Cells`. BSP and Cave write `procgen.Wall` (0) and `procgen.Floor` (1); WFC writes the index of each cell's tile in its rule set. ```go g.At(x, y) // Wall outside the grid g.Set(x, y, procgen.Floor) g.Fill(procgen.Rect{X: 2, Y: 2, W: 5, H: 3}, procgen.Floor) fmt.Print(g) // '#' Wall, '.' Floor, 'a'... for higher values ``` `Regions(passable)` flood-fills the cells that `passable` accepts and returns the 4-connected regions, largest first. `Connected(passable)` reports whether there is at most one. Use `procgen.IsFloor` for BSP and Cave levels and `rules.Walkable` for WFC levels, and run the same check after a game edits a level. `Paint` copies a grid into a [tilemap](https://game.nsgo.dev/docs/tilemap/) layer, mapping each value to a tile GID: ```go m := tilemap.New(g.Width, g.Height, 16, 16, tileset) m.Layers = append(m.Layers, tilemap.TileLayer{Name: "ground", Visible: true}) g.Paint(m, 0, 0, 0, func(v uint32) uint32 { if v == procgen.Floor { return floorGID } return wallGID }) ``` ## BSP rooms `BSP` splits the level into partitions, places one room in each leaf and joins sibling partitions with L-shaped corridors through their closest rooms, so every room is reachable. ```go streams := random.NewStreams(runSeed) d, err := procgen.BSP(streams.Stream("floor-3"), procgen.BSPConfig{ Width: 80, Height: 50, Loops: 3, // extra corridors so the level has cycles }) // d.Grid, d.Rooms (rooms as Rects), d.Corridors (From, To, Path) ``` | Field | Default | Meaning | | --- | --- | --- | | `MinLeaf` | 10 | Smallest partition side; a partition splits while a side is at least twice this | | `MinRoom` | 4 | Smallest room side | | `MaxRoom` | 0 | Largest room side; 0 lets rooms fill their partition | | `Padding` | 1 | Wall cells between a room and its partition's edges, so rooms never merge | | `Loops` | 0 | Extra corridors between random rooms | The outer ring of the level is always wall. Pick a spawn point in `d.Rooms[0]` and an exit in the room farthest from it. ## Cellular-automata caves `Cave` fills the inside of the level with random wall at `WallChance`, then smooths it `Steps` times: a cell with at least `WallAt` wall neighbours of 8 becomes wall, one with at most `FloorAt` becomes floor. The caves left over are then made into one: - By default only the largest cave is kept and the others are filled with wall. - With `Join`, every cave of at least `MinRegion` cells is tunnelled into the largest along the shortest path through rock. ```go g, err := procgen.Cave(random.New(seed), procgen.CaveConfig{ Width: 64, Height: 40, Join: true, MinRegion: 6, }) if errors.Is(err, procgen.ErrNoFloor) { // The noise smoothed into solid rock; try the next seed. } ``` Defaults are `WallChance` 0.45, `Steps` 5, `WallAt` 5 and `FloorAt` 3. `FloorAt` takes its default only when `WallAt` is unset too; once `WallAt` is set, `FloorAt` 0 means only cells with no wall neighbour become floor. Every generator refuses a level of more than `procgen.MaxCells` (2^24) cells or a side longer than `procgen.MaxSide` with an error wrapping `ErrInvalidConfig`. ## Wave function collapse `WFC` fills a grid with the simple tiled model: it collapses the cell with the fewest remaining tiles to one tile picked by weight and propagates the adjacency rules to its neighbours, restarting on a contradiction up to `Attempts` times (20 by default) before it returns `ErrNoSolution`. The tiles and their rules are a YAML file: ```yaml version: 1 tiles: - name: floor weight: 6 walkable: true - name: pillar weight: 1 - name: water weight: 2 neighbors: - {left: floor, right: floor} - {left: floor, right: pillar} - {left: pillar, right: floor} - {up: floor, down: floor} - {up: floor, down: pillar} - {up: pillar, down: floor} # ... ``` - `version` must be 1, and unknown fields are refused. - Each tile has a unique `name` and a positive `weight`, its relative frequency, and the weights must sum to a finite number; `walkable` marks the tiles the connectivity constraint joins up. - Each entry of `neighbors` allows one ordered pair, `left` next to `right` or `up` above `down`. A pair that is not listed is forbidden, so list both orders for a symmetric rule. ```go rules, err := procgen.ParseRules(data) g, err := procgen.WFC(random.New(seed), procgen.WFCConfig{Width: 32, Height: 24, Rules: rules}) // g.At(x, y) is an index into rules.Tiles ``` While the wave collapses, a path constraint keeps the walkable tiles connected: cells that can no longer reach the walkable area lose their walkable tiles, and a cell whose loss would split the walkable area loses its other tiles. A level WFC returns therefore has at least one walkable cell and passes `Connected(rules.Walkable)`. Set `AllowDisconnected` to turn the constraint off. Each collapse rescans the grid and, with the constraint on, searches the walkable area again, so a solve costs roughly the square of the cell count: tens of milliseconds for 32 by 24, about a second for 64 by 64, and more than ten for 128 by 128. `WFC` therefore accepts at most `procgen.MaxWFCCells` (64 by 64) cells; build a larger map from smaller pieces or use BSP or Cave for it. `EncodeRules` writes a rule set back as YAML with a fixed field order and the tiles and neighbors in their given order, so parsing and encoding a file it wrote reproduces it byte for byte. ## Room templates on a dungeon graph `GenerateRooms` builds roguelike levels from authored room templates placed on a generated `LayoutGraph` with a start room, a goal room, side branches, cycles and lock/key progression pairs. Room templates are defined in a versioned YAML file: ```yaml version: 1 rooms: - id: entry weight: 1 tags: - start doors: - side: north offset: 3 - side: south offset: 3 - side: east offset: 2 - side: west offset: 2 tiles: - '###.###' - '#.....#' - '.......' - '#.....#' - '###.###' - id: boss_vault tags: - goal width: 7 height: 5 source: rooms/boss_vault.tmj doors: - side: north offset: 3 - side: south offset: 3 ``` - `version` must be 1 (`RoomTemplatesVersion`), and unknown fields are refused. - Each room has a unique `id`, an optional positive `weight` (default 1), optional `tags` (such as `start`, `goal`, `key`, `combat`), optional `allowRotate` (enabling 90° clockwise rotations), and one or more `doors` (`side`: `north`/`south`/`east`/`west`, 0-based `offset`, optional `width` defaulting to 1, optional `channel` restricting which sockets can connect). - Each room defines either inline ASCII `tiles` (`#` for `Wall`, `.` for `Floor`, `a`..`z` for tile values `2..27`) or an external `source` path (such as a `.tmj` tilemap or scene file) together with `width` and `height`. - `ParseRoomTemplates` and `EncodeRoomTemplates` validate and round-trip canonical 2-space YAML byte for byte. ### Layout graph and lock/key progression `GenerateGraph` builds a `LayoutGraph` standalone, or `GenerateRooms` builds and embeds it in one call: | Field (`GraphConfig`) | Default | Meaning | | --- | --- | --- | | `CriticalPath` | 5 | Rooms on the main path from `Start` to `Goal` (at least 2) | | `Branches` | 0 | Side rooms attached off the critical path and earlier branches | | `BranchMaxDepth` | 2 | Maximum length of a branch chain | | `Loops` | 0 | Target count of extra cycle edges added within the same lock tier | | `Locks` | 0 | Lock/key pairs placed along the critical path (strictly less than `CriticalPath`) | | `MaxDegree` | 4 | Maximum passages per room | Locks split the graph into progression tiers `0..Locks`. Each lock's key is placed in a room whose tier strictly precedes the lock, and loops only connect rooms in the same tier (and opposite tree parity so cycles have even length). `graph.VerifyLocks()` confirms that every key is reachable from `Start` without crossing its lock and that `Goal` is reachable once keys are collected. ### Stitching and Spelunky-style grid placement ```go templates, err := procgen.ParseRoomTemplates(data) lvl, err := procgen.GenerateRooms(random.New(seed), procgen.RoomsConfig{ Templates: templates, Mode: procgen.PlacementGrid, // or procgen.PlacementStitch (default) GridCols: 4, GridRows: 4, Graph: procgen.GraphConfig{ CriticalPath: 6, Branches: 4, Loops: 2, Locks: 2, }, }) // lvl.Grid (Connected holds), lvl.Rooms (TemplateID, Source, Bounds, GridSlot, Rotation, Role, KeyID), // lvl.Doors (FromRoom, ToRoom, Cells, LockID), lvl.Graph ``` - `PlacementStitch` (default) places variable-sized room templates freely by aligning matching door sockets without overlap, closing same-tier loops where aligned sockets meet, and retrying deterministically from the `random.Stream` up to `Attempts` times (default 50) before returning `ErrNoLayout`. - `PlacementGrid` lays out uniform-sized templates on a coarse `GridCols × GridRows` Spelunky-style grid of room slots (auto-sized when both are 0), starting on row 0 and aligning every graph edge with adjacent slots. - `PlaceRooms` places an already-generated `LayoutGraph` in either mode. - For templates that reference a `.tmj` or scene via `source`, pass a `ResolveGrid` callback (using `procgen.GridFromTilemap` for Tiled maps loaded with `tilemap.LoadTiled`) to stamp its tiles into `Grid`; when `ResolveGrid` is nil, a walled floor footprint of `Width × Height` is stamped automatically. Unused door sockets are sealed with `Wall` and connected sockets are opened so `Grid.Connected` always holds. ## Seeds Fork a named stream for each level from the run's seed, so regenerating one floor does not change the others: ```go streams := random.NewStreams(runSeed) cave, _ := procgen.Cave(streams.Stream("cave-1"), caveCfg) ``` A generator advances the stream it is given. To regenerate the same level, pass a fresh stream with the same seed, or save the stream's `State()` before generating and restore it with `SetState`. --- Source: https://game.nsgo.dev/docs/project/ # Project File `github.com/nsgo-dev/game/pkg/project` reads, checks, writes and applies `game.yaml`, the one file at a game's root that holds its settings: its name, id and version, its window and virtual resolution, its input map, its audio buses, the scenes and resources it loads at startup, its export presets per platform, the editor plugins it turns on, its asset pipeline and the library packs installed into it. The game reads it at startup, the `gameproject` command checks and applies it, `game release` reads its export presets, `game assets` builds its asset targets, and the editor opens, edits and saves it. ## The file ```yaml version: 1 name: Cave Run id: dev.nsgo.caverun appVersion: 0.1.0 window: width: 960 height: 540 minWidth: 480 minHeight: 270 appearance: dark display: width: 320 height: 180 mode: fit integerScale: true pixelSnap: true barColor: '#0b0d17' input: actions: - name: left bindings: - kind: key key: left - kind: keyCode code: KeyA - kind: gamepadButton button: dpadLeft - kind: touchRegion region: {"y": 116, width: 72, height: 64} - kind: mouseRegion button: left region: {"y": 116, width: 72, height: 64} - name: right bindings: - kind: key key: right - kind: keyCode code: KeyD - kind: gamepadButton button: dpadRight - kind: touchRegion region: {x: 72, "y": 116, width: 72, height: 64} - name: fire bindings: - kind: mouseButton button: right - kind: gamepadButton button: south axes: - name: move negative: left positive: right motionAxes: - name: steer axis: tiltX deadZone: 0.1 gamepadAxes: - name: move axis: leftX deadZone: 0.15 audio: master: 0.9 buses: - name: music volume: 0.8 effects: - lowPass: {cutoffHz: 1200, q: 0.7} - reverb: {roomSize: 0.5, damping: 0.4, wet: 0.25} - name: sfx effects: - delay: {time: 250ms, feedback: 0.3, wet: 0.2} physics: gravity2D: "y": 980 gravity3D: "y": -9.81 solverIterations2D: 8 solverIterations3D: 8 layers: - name: player bit: 0 - name: walls bit: 1 - name: coins bit: 2 autoload: mainScene: title scenes: - name: title path: scenes/title.yaml resources: - name: level1 path: assets/level1.tmj export: output: dist presets: - platform: macos - platform: windows targets: [windows_x64] - platform: web editor: plugins: [health] assets: atlases: - name: ui in: art/ui out: assets/atlases textures: - in: art/albedo.png out: assets/albedo.ktx2 format: bc1 mipmaps: true audio: - in: sfx/jump.wav out: assets/jump.wav rate: 22050 peakDB: -1 manifest: in: assets out: assets/manifest_gen.go ``` | Field | What it holds | | --- | --- | | `version` | The schema version, `1`. | | `name`, `id`, `appVersion` | The game's display name, its reverse-DNS identifier and its release version. | | `window` | The main window's starting content size in points (`width`, `height`, both required), its resize limits (`minWidth`, `minHeight`, `maxWidth`, `maxHeight`; 0 is no limit), `resizable` (true when left out), an optional `title` and `appearance` (`light` or `dark`; left out, the app follows the system). | | `display` | The virtual resolution a `screen.Viewport` maps onto the window: `width`, `height`, `mode` (`fit` when left out, `fill`, `stretch` or `expand`), `integerScale`, `pixelSnap` and the CSS `barColor` of letterbox bars. Left out, the game draws at the window's size. | | `input` | Named `actions`, each with `bindings` of kind `touchRegion` (a `region`), `mouseButton` (a mouse `button`), `mouseRegion` (both), `key` (a layout key name `key`, such as `space` or `left`), `keyCode` (a physical key position `code`, such as `KeyW` or `ArrowLeft`), or `gamepadButton` (a W3C Standard Gamepad `button`: `south`, `east`, `west`, `north`, `leftShoulder`, `rightShoulder`, `leftTrigger`, `rightTrigger`, `back`, `start`, `leftStick`, `rightStick`, `dpadUp`, `dpadDown`, `dpadLeft`, `dpadRight` or `home`). Mouse `button` is `left`, `right`, `middle`, `back` or `forward` and regions are in virtual coordinates. `axes` read -1 for their `negative` action and +1 for their `positive` one; `motionAxes` read `tiltX`, `tiltY`, `tiltZ`, `gyroX`, `gyroY` or `gyroZ` with `input.MotionAxisOptions`' fields; `gamepadAxes` read controller sticks (`leftX`, `leftY`, `rightX` or `rightY`) with `input.GamepadAxisOptions`' fields (`deadZone`, `axial`, `sensitivity`, `invert`). A motion axis or gamepad axis may share its name with an axis, and `Actions.Axis` sums all of them and clamps to `[-1, 1]`. An action without bindings is declared for code to bind or an axis to read. | | `audio` | The default `master` volume and the `buses`, each a `sound.Mixer` group with a default `volume` and its DSP `effects` in order: `lowPass` and `highPass` (`cutoffHz`, `q`), `delay` (`time`, `feedback`, `wet`), `reverb` (`roomSize`, `damping`, `wet`), `gain` (`factor`) and `bitcrush` (`bits`, `downsample`). | | `physics` | Project-wide 2D and 3D physics defaults: `gravity2D` (`x`, `y`), `gravity3D` (`x`, `y`, `z`), `solverIterations2D`, `solverIterations3D`, named collision `layers` mapping human-readable `name`s (such as `player`, `walls`, `coins`) to unique bit indices `0..31` (`LayerMask`), and `ldtkIntGrid` rules mapping LDtk IntGrid identifiers/group names (`name`) or numeric values (`value`) to `solid`, `oneWay`, and custom `flags` bits (`File.LDtkOptions`, applied automatically by `project.Resolver` when `sceneformat.Build` loads `.ldtk` sources). | | `autoload` | The `scenes` (scene format YAML files) and other `resources` loaded at startup, each with a unique `name` and a slash-separated `path` inside the project, and the `mainScene` the game starts in. | | `export` | The build `output` directory and one preset per platform (`macos`, `windows`, `linux`, `ios`, `tvos`, `watchos`, `android`, `harmonyos`, `web`, `miniprogram`), each with the NSGo build `targets` of that platform to build; a preset without targets builds the platform name, which NSGo expands to its default targets. | | `editor` | The scene editor's settings: `plugins`, the [editor plugins](https://game.nsgo.dev/docs/editor/#editor-plugins-492) it turns on for this project, in the order their panels and tools appear. A plugin is Go code built into the editor binary; this list only turns it on. | | `assets` | The targets `game assets` builds, each list optional: `atlases` packed from a folder of PNG images (`name`, `in`, `out` and `padding`, `extrude`, `maxWidth`, `maxHeight`, `scale`, `trim`), `textures` encoded into KTX2 (`in`, `out`, `format` `rgba8`, `bc1`, `bc3` or `etc2`, `mipmaps`, `srgb`), `audio` converted from WAV (`in`, `out`, `format` `wav`, `aac` or `mp3`, `rate`, `channels`, `peakDB` or `rmsDB`, `bitrate`), `fonts` baked from TrueType or OpenType into AngelCode BMFonts (`in`, `out` a `.fnt` file, `size`, `chars`, `padding`), `models` packed from glTF into single GLB files (`in`, `out`, `scale`, `animations`), the `manifest` generated last (`in`, `out`, `package`, `prefix`, `embed`, `embedDir`), and the build `cache` path, `.game/assets-cache.yaml` when left out. Paths are slash-separated and inside the project. An image, a sound, a font or a model may also carry its own settings in an import settings sidecar beside it (`hero.png.import.yaml`), which override its target's, and any asset its author and license, which `game release` lists in the credits file it ships. [Command Line](https://game.nsgo.dev/docs/cli/#assets) says what each setting does. | | `navigation` | The settings and agent types [`game navmesh`](https://game.nsgo.dev/docs/cli/#navmesh) bakes a scene's [navigation meshes](https://game.nsgo.dev/docs/navbake3d/) with: the voxel `cellSize` and `cellHeight`, `minRegionArea`, `maxEdgeLength`, `maxSimplificationError`, `maxVertsPerPoly` (3 to 12), `detailSampleDistance` (at least `cellSize`) and `detailSampleMaxError`, and the `agents`, each with a unique `name` and its `radius`, `height`, `maxSlope` (degrees, below 90) and `maxClimb`. A size left out takes navbake3d's default, and without agents one called `default` is baked. | | `packs` | The packs installed from an [asset and plugin library](https://game.nsgo.dev/docs/library/), each with its `name`, `kind` (`asset`, `plugin` or `template`), `packVersion`, `sha256` digest, the `dir` its `files` were written to, and the autoload `scenes` and `resources` and editor `plugins` the install added, which must still be in the file. `game library` and the editor's library panel write it; no two packs may claim the same file, entry or plugin. | `Parse` refuses unknown fields, other versions, a trailing YAML document, duplicate names, actions an axis reads but nobody declares, a main scene that is not autoloaded, paths that leave the project, targets of another platform, values out of range, and asset targets that write the same file, write over `game.yaml` or a file a target reads, or write where another target's scan reads, and says which field is wrong. `Encode` validates a `File` and writes 2-space YAML in a fixed key order that `Parse` reads back unchanged. A person may write the file in any YAML style and with comments; `gameproject fmt` rewrites it in the canonical form, which keeps no comments. ## Reading it in a game A game embeds its `game.yaml` and parses it once: ```go //go:embed game.yaml var gameYAML []byte var gameProject = project.MustParse(gameYAML) func main() { nsgo.Run(Root, nsgo.WindowSize(gameProject.WindowSize()), nsgo.WindowConstraints(gameProject.WindowConstraints()), nsgo.Appearance(gameProject.Appearance()), ) } func Root(cx *core.Scope) core.Node { desktop.SetTitle(cx, gameProject.Title()) // ... } ``` `nsgo.Run` has no title option, so the root component sets the title with `desktop.SetTitle`: `Title()` is `window.title`, or `name` without one. The rest of the file applies to the game's own objects: - `Viewport()` returns the `screen.Viewport` of `display`, and false without one. - `BindInput(actions)` binds the input map into an `input.Actions`, replacing bindings of the same names and keeping others, such as ones that follow a layout computed in code. `Region(action)` returns the first region bound to an action, where the game draws its on-screen control. - `ConfigureMixer(mixer)` gives a `sound.Mixer` the default master volume and each bus's default volume (`SetDefaultMaster`, `SetDefaultVolume`) and DSP chain. A volume the player set and the mixer kept in storage wins over the default. A bus without effects leaves the chain the game set in code, as an action without bindings leaves its bindings. - `ConfigurePhysicsWorld(world)`, `ConfigureRigidWorld(world)`, and `ConfigurePhysics3DWorld(world)` apply `physics.gravity2D`, `physics.gravity3D`, and solver iterations to `physics.World`, `physics.RigidWorld`, and `physics3d.World`. `PhysicsLayerTable()` and `PhysicsSettings()` convert `physics:` for `sceneformat.ParseWith` and `sceneformat.BuildPhysics`, while `Physics.LayerBit(name)`, `Physics.LayerMask2D(names...)`, and `Physics.LayerMask3D(names...)` resolve named collision layers in Go. - `NewResolver(fsys)` returns a `Resolver` over an `fs.FS` rooted at the project, which loads what a scene names from the project's own files: its sprite atlases, scene files, materials, physics materials, and the YAML tilesets and Tiled and LDtk maps its tilemaps name. It is the `sceneformat.AssetResolver`, `SceneResolver`, `MaterialResolver`, `PhysicsMaterialResolver` and `FileResolver` (`ReadFile`) that `sceneformat.Build` and `sceneformat.BuildPhysics` take, and lists the project's atlases for the editor's asset browser (`AtlasNames`). A scene names an atlas as `game check` finds it (`NearestAtlases`): the path of an atlas JSON file without `.json`, from the project root or as its base name, the one nearest the scene winning among several (`ForScene` returns a resolver for one scene), with the image its `meta.image` names read from the project beside it. Tilesets and maps are read through `ReadFile`, as `sceneformat.FSAssets` reads them. Atlases are listed and loaded once, until `Refresh`, and scene files and the files `ReadFile` reads are read on every request. `AtlasNamed`, `SkipDir` and `IsAtlasJSON` are the rules the walk and the name lookup share with `game check`: which names name an atlas file, which directories are skipped, and which JSON files are atlases. - `LoadAutoloads(fsys)` reads every autoloaded scene, parsing and validating it as a scene document (including named physics layers against `physics.layers`), and every resource from an `fs.FS` rooted at the project, such as an `embed.FS`, and fails on the first file that is missing or invalid. `Loaded.Main()` is the main scene. ## game.yaml and nsgo.yaml NSGo's own `nsgo.yaml` sits beside `game.yaml` and repeats some of its settings. `game.yaml` owns them, and `nsgo.yaml` follows: | nsgo.yaml | game.yaml | | --- | --- | | `name`, `id`, `version` | `name`, `id`, `appVersion` | | `appearance` | `window.appearance` | | `build.output`, `build.targets` | `export.output`, the presets' targets in order | `SyncNSGo` writes these fields into an `nsgo.yaml`, keeping its other keys (`dev`, `icon` and the rest) and its comments, and `CheckNSGo` reports each field that disagrees. Both read an empty `build:` key as no build settings, as NSGo does. Everything else in `nsgo.yaml` stays NSGo's. ## The gameproject command ```sh go run github.com/nsgo-dev/game/cmd/gameproject check [dir] go run github.com/nsgo-dev/game/cmd/gameproject fmt [-check] [dir] go run github.com/nsgo-dev/game/cmd/gameproject sync [-check] [dir] go run github.com/nsgo-dev/game/cmd/gameproject targets [dir] ``` - `check` reports every problem of a project at once (`project.Check`): a `game.yaml` that does not parse, an `nsgo.yaml` that disagrees with it, an autoload that is missing or invalid, and a file an installed pack wrote that is missing. - `fmt` rewrites `game.yaml` in canonical form; with `-check` it fails instead when the file is not. - `sync` writes the fields `game.yaml` owns into `nsgo.yaml`, creating it when missing; with `-check` it fails instead when they disagree. Run it after editing `game.yaml`. - `targets` prints the export presets' build targets, comma-separated, for `nsgo build -target`. `dir` is the project root, the current directory when left out. ## In the editor `Editor.OpenProject(path)` opens a `game.yaml`, or the directory holding one, and the main scene it names, and empties the undo history. `EditProject(label, edit)` changes a copy of the project and keeps it when it validates, as one undoable step. `SaveProject()` writes the project in canonical form and syncs the `nsgo.yaml` beside it. The toolbar's Save button saves the project when it was edited, before the scene and even when the scene has no file to save to, and leaves an unedited `game.yaml` as written, comments included. `SetPluginEnabled(name, on)` adds a plugin to `editor.plugins` or removes it as such a step. With `Editor.ProjectAssets` set, opening a project makes the editor's resolver a `project.Resolver` over its directory, so its scenes draw its own atlases, and `OpenProjectScene(path, scene)` opens the project with another of its scenes in place of the main one. `nsgo game editor ` opens a project from the command line that way, through the project's own editor command when it has one (`game generate editor`, see [Command Line](https://game.nsgo.dev/docs/cli/#generate)). `MoveFile(from, to)` moves a file of the project and rewrites the references to it (see Stable references below). ## Stable references Files refer to each other by path: `game.yaml` autoloads scenes and resources and builds assets from files and folders, a scene inherits or instances other scenes and names materials, glTF models, Tiled and LDtk maps and YAML tilesets, a YAML tileset names its image, a material names its texture, Tiled and LDtk files name their tilesets and images (a Tiled tileset may be `.tsj` or `.json`), a `.gltf` model names the buffers and images it keeps in separate files (percent-encoded, as glTF writes them), and a sprite atlas names its page image in `meta.image`. Package `game/refs` keeps those references working when files are renamed or moved. It reads `game.yaml`'s paths through package `project` (`project.PathRefs`), so a `game.yaml` that does not validate is reported and nothing is moved until it is fixed. Every scene and resource file carries a stable ID in its header, a `uid` written once and never changed, so it travels with the file: ```yaml version: 2 uid: 4kq0w8m2c7d9x name: Cave ``` A uid is 13 characters of `0`-`9` and `a`-`z` without `i`, `l`, `o` and `u` (`resource.NewUID`), and `sceneformat` and `resource` refuse any other value; an empty or null `uid` is read as none, and `game index` fills it in where it is. A uid is unique within one project: two projects, such as two games made from one template, may share one, since each keeps its own index. The project index, `game.index.yaml` beside `game.yaml`, records where each file was the last time a tool looked: each scene and resource file's path with its uid, and every other file a reference names, such as an image or a Tiled map, with the SHA-256 of its contents. The tools keep it, in path order so that it changes only when files do; keep it in version control with the files it describes. ```yaml # The stable IDs of this project's files, kept by game index, game mv and the editor. Keep it in version control. version: 1 files: - path: art/stone.png sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 - path: materials/stone.material.yaml uid: 4kq0w8m2c7d9x ``` - `nsgo game mv ` moves or renames a file or a directory and rewrites every reference to what it moves, including the paths a moved Tiled or LDtk file writes relative to itself, and updates the index. `-dry-run` prints the changes without making them. The editor does the same with `Editor.MoveFile(from, to)`, which also updates the open scene, project and clip, unsaved edits included, and with the Move button of its file browser, which calls it. A move in the editor is one undoable step: Undo moves the files back, puts each file the move rewrote back byte for byte, the index included, and removes an index the move created and the directories it created when they are left empty, and Redo moves them once more. A file changed since the move has only its references rewritten back, and a file the move left alone, such as one that already named the destination, stays as it is; a step that a file now on disk blocks stays where it was, and the status bar says why. - `nsgo game index` gives every scene and resource file without a uid one, as a line after its `version`; points each reference to a file that was moved without the tools at the file's new path; gives a copied file that kept its original's uid a new one; and writes the index. Run it once to start, and again after moving files by hand or with Git. - `nsgo game check` fails on a reference to a file that is gone, at the file and line that holds it, and says where the file went when the index finds it again: the scene or resource file that now holds the uid the index lists for the old path, or the one other file with the same extension and contents. ``` scenes/room.scene.yaml:10: material "materials/stone.material.yaml": not found; it moved to "materials/rock.material.yaml"; run game index to update the reference ``` A reference is rewritten in place: its quotes are kept, and the rest of the file, comments and formatting included, is left byte for byte, so a move shows in review as the lines it changes. A move that would leave a reference broken is refused before anything changes: one that would lead out of the project root, one written over several lines, or one in a scene that does not parse. Atlas, tileset and prefab names in scenes are names the game's resolver looks up rather than paths, so they are not rewritten, and neither is an object's `mesh`, which names a built-in primitive, nor its `modelNode` or `modelMesh`, which name parts inside its model file ([scenemodel](https://game.nsgo.dev/docs/scenemodel/)). Nor are the shader and texture paths of a hot-reloaded shader material (`hotreload.MaterialDef`), which are relative to the asset directory the game passes its reloaders at run time, `resources` under `game dev` by default, rather than to the project root. What `game assets` writes (an `assets` target's `out`, the `cache`, and the manifest's `in` folder) is rewritten when it moves but need not exist, and is not listed in the index; nor are folders. A rename that changes only the case of a name, such as `a.png` to `A.png`, works on file systems that ignore case too. ## The starter and the examples The starter template and the four example games (`caverun`, `cryptquest`, `slidegem`, `starburst`) keep their settings in `game.yaml`: each its window, and where it has them its virtual resolution, input map, audio buses and export presets. Cave Run also autoloads its level from it. Each has a test that its `game.yaml` is canonical and its `nsgo.yaml` agrees with it. They are indexed too: Cave Run, whose `game.yaml` and maps name files, carries a `game.index.yaml`, and a test in `game/refs` fails when `game index` would change anything in the examples or the starter, so run `go run ./cmd/game index ` from the repository root after moving or editing a file they name. The others, and the starter, have no scene or resource file and name no file from one, so they have nothing to index until a game adds one. --- Source: https://game.nsgo.dev/docs/quality/ # quality `game/quality` picks a low, medium or high quality preset for the device a game runs on, moves it with the frame times the game measures, and holds whatever the player picks in settings instead. ```go import "github.com/nsgo-dev/game/pkg/quality" ``` ## Presets A `Preset` is what one level turns on and how far it scales the game's costs: | Field | Low | Medium | High | Meaning | | --- | --- | --- | --- | --- | | `ResolutionScale` | 0.5 | 0.75 | 1 | Scales buffers the game renders or rasterizes itself, such as `render3d.OcclusionBuffer` and procedurally drawn images; read it with `Scale` and `ScaleSize` | | `ParticleScale` | 0.25 | 0.6 | 1 | Scales particle budgets and burst counts; read it with `Particles` | | `Effects` | off | on | on | Effects that only decorate the frame: screen flashes, parallax backdrops, post effects, trails | | `Shadows` | off | off | on | Shadow casting, such as `lights2d.Scene.DisableShadows` | `DefaultPreset(level)` returns these values. `Particles(n)` and `Scale(n)` round and never return less than 1 for a positive `n`, so a scaled budget never switches an emitter off: ```go p := quality.DefaultPreset(quality.Low) emitter.MaxParticles = p.Particles(512) // 128 emitter.Burst(p.Particles(24)) // 6 lights.DisableShadows = !p.Shadows foliage := world3d.DefaultQualityProfile(world3d.QualityLevelFor(quality.Low)) ``` `ResolutionScale` does not lower the resolution of a `core.Canvas`: NSGo v0.3.0 draws a canvas at the display's full pixel density and has no setting to render it smaller and upscale it. Nothing in this repository applies `ResolutionScale` yet, Starburst included: it is a value for a game to apply to the buffers it sizes itself. ## The starting level `DeviceFromEnv(cx.Env())` reads the operating system, idiom, device model, OS version and CPU count. `Classify` places a device no rule names: | Device | Starts at | | --- | --- | | Android | Low; NSGo reports neither its memory nor its GPU, so measured frame times step it up | | iPhone | High from the iPhone 13 (`iPhone14,x`), Medium from the iPhone 11 (`iPhone12,x`), Low before | | iPad | High from `iPad13,x`, Medium from `iPad11,x`, Low before | | macOS, Windows, Linux | High with 8 or more CPUs, Medium with 4 to 7, Low with fewer | | TV and watch | Low | | Web and anything unknown | Medium | A configuration's device rules come first: the first rule whose model is a prefix of the device's model, ignoring case, and whose OS matches when it names one, gives the starting level. ## Adapting to frame times A `Selector` starts at the configured level and, while the setting is `auto`, judges frames a window at a time (90 by default), after skipping 30 frames each time it starts or changes level: - More than a quarter of a window's frames slower than the target frame rate (30 fps by default) step it down a level. - Several windows in a row (4 by default) with nine in ten frames inside 60% of the target frame time step it up a level. - It never steps back up to a level it stepped down from, so it settles instead of swinging between two levels. - Frames longer than half a second, such as loading or the first frame back from the background, do not count. Feed it the loop's raw frame lengths through `Loop.FrameTime`, and apply each new preset in `OnChange`: ```go sel, err := quality.NewSelector(quality.DefaultConfig(), quality.DeviceFromEnv(cx.Env())) if err != nil { panic(err) // DefaultConfig always validates } sel.OnChange = func(_ quality.Level, p quality.Preset) { arena.ApplyQuality(p) } arena.ApplyQuality(sel.Preset()) loop := &game.Loop{ FrameTime: func(dt time.Duration) { if !arena.Paused { sel.Observe(dt) } }, Update: arena.Step, Draw: draw, } ``` `FrameTime` keeps firing while the loop or the game is paused. Skip observing frames that simulate nothing, such as a pause or game-over screen: they are cheap and would step the level up toward one gameplay cannot hold. A `Selector` is not safe for concurrent use; call it from the scope that runs the loop. ## The player's setting `save.DisplaySettings.Quality` stores the player's choice: `"auto"` (the default) or `"low"`, `"medium"` or `"high"`. `Settings.Validate` normalizes it and turns anything else into `"auto"`. `Selector.SetSetting` applies it: a level's name holds that level whatever the frame times, and `"auto"` returns to the starting level and adapts again. `Selector.Setting` returns the value to store. ```go store := save.NewStorageSettingsStore(cx.Storage(), "mygame") if s, err := store.Load(); err == nil { _ = sel.SetSetting(s.Display.Quality) // Load has validated it } // From the settings menu: if err := sel.SetSetting("high"); err == nil { // Load returns the defaults when nothing is stored yet; any other error, such as settings a newer build wrote, keeps the setting for this run only. if s, err := store.Load(); err == nil { s.Display.Quality = sel.Setting() _ = store.Save(s) } } ``` ## The configuration file A game can keep its presets, device rules and adaptation in a YAML file. `ParseConfig` refuses unknown fields, a missing or other `version`, scales outside (0, 1], duplicate device rules, device models with leading or trailing spaces, unknown levels or operating systems, and trailing documents. `EncodeConfig` writes fields in a fixed order, so a file read and written back is unchanged. ```yaml version: 1 presets: low: resolution_scale: 0.5 particle_scale: 0.25 effects: false shadows: false medium: resolution_scale: 0.75 particle_scale: 0.6 effects: true shadows: false high: resolution_scale: 1 particle_scale: 1 effects: true shadows: true devices: - model: Google Pixel 8 os: android level: high adapt: target_fps: 30 window_frames: 120 upgrade_windows: 3 ``` | `adapt` field | Range | Default | | --- | --- | --- | | `off` | `true` keeps the starting level for the whole run | `false` | | `target_fps` | 3 to 240 (below 3 fps a slow frame would be over the half second the selector ignores) | 30 | | `window_frames` | 10 to 3600 | 90 | | `upgrade_windows` | 1 to 100 | 4 | ## In the Starburst example `examples/starburst` starts a low-end Android phone on the low preset: a quarter of the particles, and no parallax starfield, floor grid or screen flashes. The HUD's quality button steps through auto, low, medium and high and stores the choice in the player's settings. `BenchmarkArenaPresets` measures one stress-mode step and draw at each level: ```sh cd examples/starburst go tool nsgo test -bench BenchmarkArenaPresets ./... ``` --- Source: https://game.nsgo.dev/docs/quest/ # quest `game/quest` runs quests with objectives (collect, reach, defeat, talk), quest states and rewards. Quests are defined in a versioned YAML book, advanced by game events published on a `flow.Bus`, and saved as a small snapshot that round-trips through `save.Store`. ```go import "github.com/nsgo-dev/game/pkg/quest" ``` ## The quest book A designer writes every quest in one YAML file: ```yaml version: 1 quests: - id: welcome title: quest.welcome.title autoStart: true objectives: - id: meet-elder kind: talk target: elder - id: rat-problem title: quest.rats.title requires: [welcome] ordered: true objectives: - id: talk-innkeeper kind: talk target: innkeeper - id: find-cellar kind: reach target: cellar - id: kill-rats kind: defeat target: rat count: 5 - id: tails kind: collect target: rat-tail count: 3 optional: true - id: report kind: talk target: innkeeper rewards: - kind: gold id: coin amount: 50 - kind: item id: cellar-key ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` (`quest.FormatVersion`) | | `id` | Quest ID, unique in the book and used in saves | | `title`, `description` | Display text or localization keys; the package does not read them | | `requires` | Quests that must be completed before this one can start | | `autoStart` | Start as soon as the prerequisites are complete | | `repeatable` | Allow `Start` again after the quest completed | | `ordered` | Objectives advance one at a time, in list order | | `objectives` | At least one; the quest completes when every non-optional objective is complete | | `rewards` | Reported on completion for the game to grant | Each objective has an `id` (unique in its quest), a `kind` (`collect`, `reach`, `defeat` or `talk`), a `target` (the item, place, enemy or character ID events must name), an optional `count` (default 1), `optional` and `text`. A reward has an optional `kind` (such as `item`, `xp` or `gold`), an `id` and an `amount` (default 1). The package only reports rewards, so they can name anything a game defines, including inventory items or stats. `quest.Parse` and `quest.LoadFS` refuse unknown fields, a wrong version, duplicate or empty IDs, unknown kinds, negative counts, prerequisites that name a missing quest, and prerequisite cycles; every error wraps `quest.ErrInvalidBook`. `quest.Encode` writes the book back in canonical form: 2-space YAML with fields in a fixed order, `requires` in flow style and everything else in block style, empty lists and default values left out, and no generated values. Loading and saving a book in that form, like the example above, changes nothing, and `quest.Parse(quest.Encode(book))` always equals the parsed book. A file in another form comes back canonical, and YAML comments are not kept, so put designer notes in `description` or `text`. ## Running quests `quest.NewLog` tracks one player's progress through a book. Attach it to the game's event bus and publish events from wherever they happen: ```go book, err := quest.LoadFS(assets, "quests.yaml") if err != nil { return err } log, err := quest.NewLog(book) if err != nil { return err } log.OnUpdate = func(u quest.Update) { if u.Kind == quest.QuestCompleted { for _, r := range u.Rewards { grant(r.Kind, r.ID, r.Quantity()) } } } detach := log.Attach(&bus) defer detach() log.StartReady() // starts autoStart quests with no prerequisites flow.Publish(&bus, quest.Talked{Character: "elder"}) flow.Publish(&bus, quest.Defeated{Enemy: "rat", Amount: 2}) flow.Publish(&bus, quest.Collected{Item: "rat-tail"}) flow.Publish(&bus, quest.Reached{Place: "cellar"}) ``` `Collected`, `Reached`, `Defeated` and `Talked` are shorthands for `quest.Event{Kind, Target, Amount}`; an `Amount` below 1 counts as 1. Without a bus, call `log.Handle(event)` directly. Quests move through five states: | State | Meaning | | --- | --- | | `Inactive` | Not started | | `Active` | Objectives accept events | | `Completed` | Every required objective is complete | | `Failed` | The game called `Fail`; `Start` retries it | | `Abandoned` | The player called `Abandon`; `Start` takes it up again | - `Start(id)` begins a quest with no progress. It returns `ErrNotStartable` while a prerequisite is incomplete, while the quest is active, or after it completed unless it is `repeatable`. - `StartReady()` starts every `autoStart` quest that has never started and whose prerequisites are complete. A log calls it after each completion, so quest chains follow on by themselves. - `Fail(id)` and `Abandon(id)` end an active quest; abandoning drops its progress. Neither state is restarted by `StartReady`, so an `autoStart` quest the player abandoned stays abandoned, across saves too, until the game calls `Start`. - `SetProgress(quest, objective, n)` mirrors a value the game already tracks, such as how many of an item the inventory holds. - `State`, `Quests(state)`, `Objectives(id)` and `Objective(quest, objective)` feed a journal or HUD. An objective is `ObjectiveLocked`, `ObjectiveActive` or `ObjectiveDone`. In an `ordered` quest only the first incomplete required objective (and any optional ones before it) accepts events, and the event that completes one objective does not count toward the next, so talking to the innkeeper once does not also finish the final report. The same holds for a quest that an event's completion auto-starts. Every change is reported as an `Update` (`QuestStarted`, `ObjectiveProgressed`, `ObjectiveCompleted`, `QuestCompleted`, `QuestFailed`, `QuestAbandoned`), delivered to `OnUpdate` and, while attached, published on the bus. Handlers may call back into the log, for example to start a follow-up quest; updates raised that way arrive after the current ones, in order. ## Saving progress `log.Snapshot()` returns the progress as plain data: every quest that is not inactive, in book order, with its state and the objectives that have progress. Store it in a save slot next to the rest of the game's state: ```go type gameSave struct { Gold int `json:"gold"` Quests quest.Snapshot `json:"quests"` } err := store.Save("slot1", gameSave{Gold: gold, Quests: log.Snapshot()}) ``` which writes stable JSON such as: ```json {"version":1,"quests":[{"id":"welcome","state":"completed","progress":{"meet-elder":1}},{"id":"herbs","state":"active","progress":{"moonleaf":3,"sunroot":1}}]} ``` To load, build a log from the same book and restore: ```go var s gameSave if err := store.Load("slot1", &s); err != nil { return err } if err := log.Restore(s.Quests); err != nil { return err } log.StartReady() ``` `Restore` checks the whole snapshot before changing anything and delivers no updates. It refuses (with `ErrInvalidSnapshot`) a wrong version, quests or objectives the book no longer has, progress outside an objective's range, and progress a log cannot reach: a quest whose prerequisite is missing from the snapshot (or, unless the prerequisite is `repeatable`, not completed), an abandoned quest with progress, progress in an `ordered` quest past an incomplete required objective, and an active quest whose required objectives are already complete. When a content update removes or renames quests or objectives, lowers a count or adds a prerequisite, register a `save.Migration` that rewrites the old snapshot. A save slot written before the game tracked quests decodes its missing field to the zero `quest.Snapshot`; `Restore` takes that as no progress and resets every quest to `Inactive`. --- Source: https://game.nsgo.dev/docs/render3d/ # render3d `game/render3d` provides mesh buffers, textures and samplers, metallic-roughness PBR materials, directional, spot and point light shadow maps, camera uniforms, offscreen render-to-texture cameras and multi-viewport split-screen rendering, distance and height fog, and an HDR render target with a tone-mapping pass for the NSGo GPU view alongside the GPU-agnostic, zero-steady-state-allocation CPU 3D render pipeline and developer tools: frustum culling, opaque/transparent draw sorting, automatic instancing, LOD selection with hysteresis, camera-facing billboards and 3D ribbon trails, 3D debug wireframes and transform gizmos, frame profiling, and mobile/desktop GPU budgets. ```go import "github.com/nsgo-dev/game/pkg/render3d" ``` All matrices, bounding boxes, rays, and frustums follow [math3d](https://game.nsgo.dev/docs/math3d/) conventions. To composite 2D sprite batches and screen-space layers over a 3D `gpu.View`, see [`Overlay3D` in `game/scene`](https://game.nsgo.dev/docs/scene/#2d-layers-over-a-3d-view-overlay3d). ## Frustum culling, draw sorting, instancing, and LOD (`Queue`) Reuse a `Queue` across frames and pass your frame's `[]DrawItem` into `Queue.Build(viewProj, camPos, items)`: ```go queue := &render3d.Queue{ LODHysteresis: 0.1, // 10% deadband prevents LOD popping at thresholds } plan := queue.Build(cam.ViewProj(), cam.Pos, drawItems) // 1. Submit instanced opaque batches (contiguous Mat4 transform slices): for _, batch := range plan.Batches { submitInstanced(batch.PipelineID, batch.MaterialID, batch.MeshID, batch.Transforms) } // 2. Submit transparent draws strictly back-to-front: for _, draw := range plan.Transparent { submitDraw(draw) } ``` In one allocation-free steady-state pass, `Queue.Build` performs: 1. **Frustum culling**: extracts six planes via `math3d.FrustumFromMat4NO` and skips off-screen `WorldBounds`. The `[-1, 1]` form is exact for OpenGL-style projections (`math3d.PerspectiveNO`, `math3d.OrthoNO`) and conservative for `[0, 1]` ones, so one queue serves both; `Queue.FrustumNO` is kept for source compatibility and ignored. 2. **Occlusion culling** (optional): when `Queue.Occluder` is set, frustum-visible items whose `WorldBounds` fail `OcclusionBuffer.TestAABB` are skipped and counted in `RenderStats.Occluded`. See [Occlusion culling](https://game.nsgo.dev/docs/render3d/#occlusion-culling-occlusionbuffer). 3. **LOD selection with hysteresis**: evaluates each item's `LODs` (`[]LODLevel`, finest to coarsest) using distance and `ProjectScreenRatio`, remembering the prior LOD per `DrawItem.ID` (`SelectLOD`). Call `queue.ResetLODHistory()` on camera cuts. 4. **Opaque sorting & instancing**: orders `BlendOpaque` and `BlendAlphaMask` items by `(PipelineID, MaterialID, MeshID, Blend, front-to-back view depth)` to minimize state switches and early-Z overdraw, then groups adjacent matching items into `InstanceBatch`es (unless `DisableInstancing` is set). 5. **Transparent sorting**: places `BlendAlphaBlend` draws into `plan.Transparent`, ordered strictly back-to-front by view depth. Both sorts are stable, so draws whose keys tie keep their submission order from frame to frame. ## Occlusion culling (`OcclusionBuffer`) `OcclusionBuffer` is a small CPU depth buffer with a max-Z pyramid. Rasterize large static occluders (walls, floors, buildings) into it once per view, then let the queue skip items hidden behind them. It never culls a visible item: a box that crosses the near plane, or one tested against a view other than the one rasterized, is always reported visible. ```go occ := render3d.NewOcclusionBuffer(0, 0) // 128x72 by default walls := []render3d.Occluder{ render3d.NewBoxOccluder(wallBounds, wallTransform), render3d.NewQuadOccluder(a, b, c, d, true), render3d.OccluderFromMesh(vertices, indices, transform), } // Every frame, with the same viewProj the queue uses: occ.Clear() occ.Rasterize(viewProj, walls...) occ.BuildPyramid() plan := queue.BuildWithOcclusion(viewProj, camPos, drawItems, occ) ``` Set `OcclusionBuffer.DepthNO` for an OpenGL-style `[-1, 1]` projection so the near plane matches. Occluders must be opaque and closed or double-sided; only meshes that fully hide what is behind them belong here. ## Camera uniform on the GPU (`CameraBuffer`) `CameraBuffer` keeps one camera's uniform buffer on an NSGo `gpu.Device`, with the bind group layout and bind group that expose it to vertex and fragment shaders at `CameraGroup` (group 0). `CameraWGSL` declares the matching block, so a 3D shader prepends it and places vertices with `camera.view_proj`: ```wgsl struct Camera { view: mat4x4, proj: mat4x4, view_proj: mat4x4, eye: vec4, } @group(0) @binding(0) var camera: Camera; ``` `CameraUniform` is the block's data (`NewCameraUniform(cam)` fills it from a `scene3d.Camera`) and `Encode` writes its `CameraUniformSize` (208) bytes without allocating. Create the buffer once the device is ready, upload the frame's camera before recording draws, and list `Layout()` at `CameraGroup` in every 3D pipeline's `Layouts`: ```go camBuf, err := render3d.NewCameraBuffer(cx, dev) // ... layouts := []*gpu.BindGroupLayout{render3d.CameraGroup: camBuf.Layout()} pipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{Layouts: layouts /* shaders, vertex buffers, depth */}) // Each frame, in game.Loop.Draw: camBuf.WriteCamera(&drawn) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) ``` The reference tests render the same scene headless through `gpu.NewSoftwareRenderer` with a perspective and an orthographic camera orbiting on `game.Loop`, and compare each frame with `render3d/testdata/golden/camera_perspective.png` and `camera_orthographic.png`; `UPDATE_GOLDEN=1` rewrites them. ## Directional, point and spot lights in PBR shading (`LightRig`, `GPULightBuffer`) `LightRig` holds a scene's linear-RGB lighting: an `AmbientLight`, up to `MaxDirectionalLights` (4) `DirectionalLight`s, up to `MaxPointLights` (16) `PointLight`s, and up to `MaxSpotLights` (8) `SpotLight`s. One pass shades all of them together, so a scene can mix a sun, lamps and a flashlight. - **`DirectionalLight`**: parallel rays travelling along `Direction` (for example `{Y: -1}` shines straight down onto a `+Y` surface; normalized when shaded or packed), with linear `Color` and `Intensity`. - **`PointLight`**: omnidirectional emitter at `Position` with linear `Color`, `Intensity`, and optional cutoff `Range`. When `Range > 0`, distance falloff uses the glTF `KHR_lights_punctual` smooth windowing curve `max(min(1 - (d/Range)^4, 1), 0)^2 / max(d^2, 1e-4)` so contribution reaches zero smoothly at `Range`; `Range == 0` uses pure clamped inverse-square `1 / max(d^2, 1e-4)` (`PointLightAttenuation`). - **`SpotLight`**: a glTF `KHR_lights_punctual` cone at `Position` pointing along `Direction` (normalized when shaded or packed), with linear `Color`, `Intensity` and `Range` falloff exactly as for a `PointLight`, multiplied by the angular falloff between the half-angles `InnerConeAngle` and `OuterConeAngle` (radians, `0 <= inner < outer <= pi/2`): full intensity inside the inner cone, `clamp(cos(angle) * angleScale + angleOffset, 0, 1)^2` between the cones, and zero outside the outer cone or behind the light (`SpotConeAttenuation`, with `angleScale` and `angleOffset` from `SpotLight.ConeScaleOffset`, and `SpotLight.Attenuation` for the combined distance and cone factor). `Validate` refuses a zero outer cone, an outer cone past `pi/2` and an inner cone that is not smaller than the outer one. - **`AmbientLight`**: uniform isotropic linear fill applied as `Ambient.Color * Ambient.Intensity * BaseColor`. `GPULightBuffer` uploads a validated `LightRig` into a 1056-byte (`LightUniformSize`), 16-byte-aligned std140/WGSL uniform buffer bound at `LightGroup` (group 1), scoped to `*core.Scope` with optional `LightBufferOptions.Retained` survival across GPU device loss: ```go rig := render3d.LightRig{ Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.16, Y: 0.22, Z: 0.32}, Intensity: 0.22}, Directional: []render3d.DirectionalLight{ {Direction: math3d.Vec3{X: 0.55, Y: -0.8, Z: -0.45}, Color: math3d.Vec3{X: 1, Y: 0.96, Z: 0.9}, Intensity: 2.6}, }, Point: []render3d.PointLight{ {Position: math3d.Vec3{X: 1.6, Y: 1.15, Z: 1.5}, Color: math3d.Vec3{X: 0.25, Y: 0.72, Z: 1}, Intensity: 9, Range: 6.5}, }, Spot: []render3d.SpotLight{ { Position: math3d.Vec3{X: -1.8, Y: 3.6, Z: 1.2}, Direction: math3d.Vec3{X: 0.7, Y: -3.6, Z: -1.1}, Color: math3d.Vec3{X: 1, Y: 0.72, Z: 0.38}, Intensity: 28, Range: 9, InnerConeAngle: math3d.DegToRad(14), OuterConeAngle: math3d.DegToRad(26), }, }, } lightBuf, err := render3d.NewLightBuffer(cx, dev, rig, render3d.LightBufferOptions{Label: "scene", Retained: true}) drawBuf, err := render3d.NewPBRDrawBuffer(cx, dev, nil, render3d.NewPBRDrawUniform(model, render3d.PBRMaterial{ BaseColor: math3d.Vec3{X: 0.82, Y: 0.14, Z: 0.12}, Metallic: 0.0, Roughness: 0.22, }), true) pipe, err := render3d.NewLitPBRPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBuf.Layout(), gpu.FormatDepth24Plus) // Each frame: _ = lightBuf.Update(frame.Device(), rig) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lightBuf.Bind(pass) pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(pass) ``` Custom 3D shaders can prepend `CameraWGSL + LightWGSL` to read `@group(1) @binding(0) var lights: LightRigUniform` and call the portable WGSL helpers `point_light_attenuation`, `spot_cone_attenuation`, `pbr_brdf`, `shade_pbr`, and `linear_to_srgb`. `LitPBRWGSL` combines them with `MeshVertexLayout` and a per-draw `PBRDrawUniform` at `PBRDrawGroup` (group 2). For more local lights than the rig holds, bind a `ClusteredLightSystem` at `LightGroup` instead of a `GPULightBuffer`: it uploads the same rig and adds any number of clustered point and spot lights, shaded with the same BRDF ([Clustered forward lighting](https://game.nsgo.dev/docs/render3d/#clustered-forward-lighting-clusteredlightsystem-clustergrid)). The shading model follows glTF 2.0 metallic-roughness PBR (dielectric `F0 = 0.04`, Schlick Fresnel, Trowbridge-Reitz GGX normal distribution, height-correlated Smith-GGX visibility, energy-conserving Lambertian diffuse, perceptual roughness floored at `0.045`, and IEC 61966-2-1 linear-to-sRGB output). `EvaluatePBR`, `ShadePoint`, `PointLightAttenuation`, `SpotConeAttenuation`, and `LinearToSRGB` implement the exact same equations on the CPU; `LightRig.AppendUniformData` and `LightUniforms.Encode` pack the uniform block without allocating. Reference tests verify GPU output pixel-for-pixel against CPU `ShadePoint`, exercise both full and WebGL 2 / GLES 3.0 (`nsgotest.NoGPUCompute`) profiles plus `Retained` device loss, and compare lit scenes against `render3d/testdata/golden/lights_pbr_scene.png`, `lights_point_falloff.png` and `spot_lights_scene.png`. ## Distance and height fog (`Fog`, `GPUFogBuffer`) `Fog` configures distance fog (`FogOff`, `FogLinear`, `FogExp`, `FogExp2`), analytical exponential height fog along the view ray (`HeightEnabled`, `HeightBase`, `HeightFalloff`, `HeightDensity`), or both. `Color` is linear RGB (`math3d.Vec3`) and `MaxOpacity` caps the final blend factor in `(0, 1]` (zero means `1.0`). With both kinds enabled, their transmittances multiply: ```text factor = clamp(1 - (1 - f_dist) * (1 - f_height), 0, MaxOpacity) ``` Height fog integrates the vertical extinction `HeightDensity * exp(-HeightFalloff * (y - HeightBase))` analytically along the segment from the ray's start to the surface, switching to a four-term Taylor expansion near horizontal rays, so grazing and vertical rays stay smooth and a high camera looking down never overflows. `GPUFogBuffer` holds the 48-byte `FogUniforms` block (`FogUniformSize`) with optional `Retained` survival across device loss. Both lit pipelines take it: - **Lights**: `NewLitPBRFogPipeline` compiles `LitPBRFogWGSL`, the `LitPBRWGSL` lighting above with the fog buffer at `FogGroup` (group 3) after the camera, lights and per-draw groups. `GPUFogBuffer.Bind` binds it there. - **Materials**: set `MaterialPipelineOptions.FogLayout` and `NewMaterialPipeline` compiles `MaterialFogWGSL` with the fog buffer at `MaterialFogGroup` (group 2), after the camera and material groups. Fog blends the linear radiance before the material shader's tone mapping, so the fog color is tone-mapped with the scene. ```go fog := render3d.Fog{ Mode: render3d.FogExp, Color: math3d.Vec3{X: 0.62, Y: 0.72, Z: 0.86}, Density: 0.03, MaxOpacity: 0.9, HeightEnabled: true, HeightBase: 2, HeightFalloff: 0.25, HeightDensity: 0.05, } fogBuf, err := render3d.NewGPUFogBuffer(cx, dev, fog, render3d.FogBufferOptions{Label: "fog", Retained: true}) pipe, err := render3d.NewLitPBRFogPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBuf.Layout(), fogBuf.Layout(), gpu.FormatDepth24Plus) matPipe, err := render3d.NewMaterialPipeline(cx, dev, camBuf.Layout(), defaults.Layout(), render3d.MaterialPipelineOptions{ DepthFormat: gpu.FormatDepth24Plus, FogLayout: fogBuf.Layout(), }) // Each frame: _ = fogBuf.Update(frame.Device(), fog) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lightBuf.Bind(pass) fogBuf.Bind(pass) pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(pass) pass.SetPipeline(matPipe) pass.SetBindGroup(render3d.MaterialFogGroup, fogBuf.BindGroup()) gpuMat.Bind(pass) gltfMesh.Draw(pass) ``` The view ray starts at the eye for a perspective camera. For an orthographic camera it starts on the camera's plane, at the point the surface projects from, so fog grows with the distance from that plane rather than from the camera's position. `FogCameraWGSL`'s `fog_camera_pos(world_pos)` computes that start point in shaders, and `FogCameraPos(cameraUniform, worldPos)` computes the same point on the CPU. - **CPU reference**: `Fog.Factor(camPos, worldPos)` and `Fog.Apply(color, camPos, worldPos)` evaluate the shader's formulas, with `camPos` the ray's start from `FogCameraPos`. `Fog.Validate` rejects non-finite or out-of-range fields with `ErrInvalidFog`, and `Fog.Sanitized` replaces them with safe defaults. `AppendFogUniforms` packs the block without allocating. - **Custom shaders**: prepend `FogWGSL` for the `Fog` struct, `fog_factor(cam_pos, world_pos, fog)` and `apply_fog(color, cam_pos, world_pos, fog)`, then `FogBindingWGSL` (group 3) or `MaterialFogBindingWGSL` (group 2) for the binding, and `FogCameraWGSL` after `CameraWGSL` for the ray start. `FogWGSL` declares no binding of its own, so a shader can also embed `Fog` in its own uniform block. Reference tests check rendered pixels against `ShadePoint` and `EvaluateMaterial` blended by `Fog.Apply` on the software GPU and in `nsgotest` (`full` and `nsgotest.NoGPUCompute` profiles), cover orthographic cameras, `Update`, `Retained` device loss and scope disposal, and compare against `render3d/testdata/golden/fog_linear_distances.png` and `fog_height.png`. ## Skybox and image-based lighting (`Cubemap`, `SkyboxPipeline`, `GPUIBLBuffer`) `render3d` provides 6-face cubemaps (`Cubemap`, `GPUCubemap`), a fullscreen-triangle background skybox (`SkyboxPipeline`), and split-sum image-based lighting (`IrradianceSH`, `PrefilterEnvironment`, `GenerateBRDFLUT`, `EnvBRDFApprox`, `GPUIBLBuffer`, `IBLWGSL`, `LitPBRIBLWGSL`) that run on every NSGo GPU backend, including WebGL 2 and OpenGL ES 3.0 (`NoGPUCompute`). Build a `Cubemap` from six faces (`CubemapFromImages`), an equirectangular panorama (`CubemapFromEquirectangular`; pass `srgb = true` for a typical PNG or JPEG), or a procedural three-band sky (`GradientSkyCubemap`), then bake diffuse L2 spherical harmonic irradiance and a GGX-prefiltered specular mip chain on the CPU before uploading: ```go env, err := render3d.GradientSkyCubemap(zenith, horizon, ground, 64) sh, err := render3d.ComputeIrradianceSH(env) prefilter, err := render3d.PrefilterEnvironment(env, render3d.PrefilterOptions{ BaseSize: 64, MipLevels: 5, SampleCount: 64, }) skyCube, err := render3d.UploadCubemap(cx, dev, env, render3d.CubemapUpload{Label: "sky", Retained: true}) prefCube, err := render3d.UploadCubemap(cx, dev, prefilter, render3d.CubemapUpload{Label: "ibl", Retained: true}) skyPipe, err := render3d.NewSkyboxPipeline(cx, dev, render3d.SkyboxPipelineDesc{ ColorFormat: dev.SurfaceFormat(), DepthFormat: gpu.FormatDepth24Plus, Retained: true, }) skyGroup, err := skyPipe.BindCubemap(cx, skyCube) iblBuf, err := render3d.NewGPUIBLBuffer(cx, dev, prefCube, render3d.NewIBLUniform(sh, prefCube, 1.0), render3d.IBLBufferOptions{Label: "ibl", Retained: true}) pipe, err := render3d.NewLitPBRIBLPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBuf.Layout(), iblBuf.Layout(), gpu.FormatDepth24Plus) // Each frame: draw opaque lit meshes with the IBL buffer at IBLGroup (group 3), then the skybox, which skips the pixels they cover: pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lightBuf.Bind(pass) iblBuf.Bind(pass) pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(pass) skyPipe.WriteCamera(cam) skyPipe.Draw(pass, skyGroup) ``` - **Depth and translation**: `NewSkyboxUniform` strips camera translation so the sky stays infinitely distant as the viewer moves. `SkyboxWGSL` draws one fullscreen triangle from `@builtin(vertex_index)` with no vertex buffer, at depth `1.0`, the far plane, with `CompareLessEqual` and `DepthWrite: false`, so drawn after opaque geometry it shades only uncovered pixels and paints over nothing nearer than the far plane. - **Lit PBR with environment lighting**: `LitPBRIBLWGSL` is `LitPBRWGSL` plus `evaluate_ibl`: it adds diffuse spherical harmonic irradiance and prefiltered specular to the direct lighting before encoding to sRGB. Set the `LightRig`'s ambient light to zero when the environment supplies the ambient term. IBL and fog both use bind group 3 (`IBLGroup` and `FogGroup`), the last of the four groups every backend guarantees, so a lit pipeline has one or the other. - **Custom shaders**: prepend `IBLWGSL` (group 3) or `IBLWGSLForGroup(group)` and call `evaluate_ibl(normal, view_dir, base_color, metallic, roughness, ao)`. Diffuse lighting evaluates the 9 pre-convolved L2 coefficients (`evaluate_irradiance_sh`), and specular lighting samples the prefiltered cubemap at `roughness * ibl.max_lod` scaled by Karis's analytical `env_brdf_approx` (`EnvBRDFApprox`). Shaders that prefer a 2D lookup texture can bake the split-sum GGX table with `GenerateBRDFLUT` or `GenerateBRDFLUTWithSamples`. - **Buffer, validation and memory**: `GPUIBLBuffer` follows `GPULightBuffer` and `GPUFogBuffer`: `Update(dev, u)` writes new parameters, `Bind` sets it at `IBLGroup`, and `ByteSize` reports its uniform buffer for `RenderStats`, while `GPUCubemap.ByteSize` reports each cubemap. `IBLUniform.Validate` refuses non-finite spherical harmonic coefficients and non-finite or negative intensity or max LOD with `ErrInvalidIBL`. - **High dynamic range environments and `.hdr` loading (`HDRCubemap`, `UploadCubemapHDR`)**: `Cubemap` stores 8 bits per channel (`RGBA8Unorm` or `RGBA8UnormSRGB`), clamping radiance above 1. For physically based highlights above 1.0, use `HDRCubemap`, which stores linear `float32` RGB faces and mips: decode a Radiance `.hdr` (RGBE) equirectangular panorama directly with `CubemapFromHDR` (or `DecodeHDR` / `EncodeHDR` + `CubemapFromHDREquirectangular`), generate a procedural HDR sky with `GradientSkyHDRCubemap`, or promote an LDR cubemap with `HDRCubemapFromCubemap`. Bake HDR diffuse irradiance and prefiltered specular with `ComputeIrradianceSHHDR` and `PrefilterEnvironmentHDR`, then upload with `UploadCubemapHDR`, which produces a `GPUCubemap` in `gpu.FormatRGBA16Float` (clamping above `65504` to stay finite in half-float, and falling back to `RGBA8Unorm` only if the device lacks `FormatRGBA16Float`). Draw HDR scenes and skyboxes into an `HDRTarget` resolved by `ToneMapPass` (for example `ToneMapNeutral`), or set `SkyboxPipelineDesc.ToneMap` (`SkyboxToneMapWGSL`) to apply Reinhard + gamma 2.2 when drawing an HDR skybox directly to an LDR surface. - **Textured glTF PBR materials with IBL (`NewMaterialIBLPipeline`, `MaterialIBLWGSL`)**: `NewMaterialIBLPipeline` pairs `CameraGroup` (group 0), a textured glTF `GPUMaterial` at `MaterialGroup` (group 1 — base color, metallic-roughness, tangent-space normal, occlusion, and emissive maps, plus alpha masking/blending and double-sided normal flipping), and a `GPUIBLBuffer` at `MaterialIBLGroup` (group 2). Set `MaterialIBLPipelineOptions.LinearOutput` (`MaterialIBLLinearWGSL`) to write unclamped linear radiance into an `HDRTarget` for `ToneMapPass`; `EvaluateMaterialIBL` is the matching pure-Go CPU reference. - **CPU reference and device loss**: `EvaluateIBL` and `EvaluateIBLHDR` match `evaluate_ibl` on the CPU, `ShadePoint` plus `EvaluateIBL` matches `LitPBRIBLWGSL`, and `EvaluateMaterialIBL` matches `MaterialIBLWGSL`. With `Retained: true` on `CubemapUpload`, `SkyboxPipelineDesc`, `IBLBufferOptions`, and `MaterialIBLPipelineOptions`, NSGo restores textures, samplers, pipelines and uniform buffers after a device loss; call `SkyboxPipeline.SetDevice(dev)` in `OnReady` and pass the new device to `GPUIBLBuffer.Update`. - **Reference renders**: headless software-GPU tests compare a skybox behind a mesh and 2x2 metallic/roughness spheres with `render3d/testdata/golden/skybox_scene.png` and `ibl_spheres.png`, and render the Khronos `DamagedHelmet` (`render3d/testdata/damagedhelmet/reference_ibl.png`, skipped when the CC-BY-NC-4.0 fixture directory is absent) with all five glTF PBR maps under an `.hdr`-decoded `FormatRGBA16Float` HDR environment and skybox resolved through `ToneMapNeutral` (`UPDATE_GOLDEN=1` rewrites them), verifying measurably brighter specular highlights than an LDR-clamped environment, CPU reference parity, far-plane visibility, retained device-loss recovery, and both the full and `nsgotest.NoGPUCompute` profiles. ## Reflection probes and light probes (`ReflectionProbeSet`, `LightProbeVolume`, `GPUProbeIBLBuffer`) `render3d` extends its IBL pipeline with spatially varying local reflections and interpolated diffuse indirect lighting built directly on `Cubemap`, `GPUCubemap`, `PrefilterEnvironment`, and `IrradianceSH` — plugging into `LitPBRWGSL` at `IBLGroup` (group 3) so metallic, roughness, emissive, `LightRig` direct lights, inverse-transpose normal matrices, and sRGB output work in one pass across every backend including WebGL 2 and OpenGL ES 3.0 (`NoGPUCompute`). ```go var probes render3d.ReflectionProbeSet room := &render3d.ReflectionProbe{ ID: "hall", Position: math3d.Vec3{X: 0, Y: 1.5, Z: 0}, BoxMin: math3d.Vec3{X: -6, Y: 0, Z: -6}, BoxMax: math3d.Vec3{X: 6, Y: 4, Z: 6}, BlendDistance: 1.5, BoxProjection: true, } probes.Add(room) // Bake on load or on request (runtime-only; re-baking closes any previous GPUCubemap): render3d.BakeReflectionProbeGPU(cx, dev, room, render3d.ProbeBakeOptions{ Size: 64, ClearColor: core.RGB(0x101824), SRGB: false, // RGBA8Unorm target; set true for RGBA8UnormSRGB Prefilter: render3d.PrefilterOptions{BaseSize: 64, MipLevels: 5, SampleCount: 64}, }, func(pass *gpu.RenderPass, face gpu.CubeFace, faceCam render3d.CameraUniform) { camBuf.Write(faceCam) drawStaticRoom(pass) }, func(err error) { // Invoked asynchronously on the engine goroutine once all six face readbacks finish. }) // Bake a 3D light probe grid of IrradianceSH for dynamic objects: grid, _ := render3d.NewLightProbeGrid(roomBounds, 4, 2, 4) _ = grid.Bake(16, sampleRoomRadiance) lightProbes := &render3d.LightProbeVolume{Grid: grid, FallbackSH: skySH} // Bind per-object probe IBL at IBLGroup (group 3) alongside LitPBRWGSL: probeIBL, _ := render3d.NewGPUProbeIBLBuffer(cx, dev, render3d.ProbeIBLBufferOptions{Label: "hero-ibl"}) pipe, _ := render3d.NewLitPBRProbeIBLPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBuf.Layout(), probeIBL.Layout(), gpu.FormatDepth24Plus) // Each frame for a moving object: _ = probeIBL.UpdateForPoint(dev, heroPos, &probes, lightProbes, skyPrefCube, 1.0) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lightBuf.Bind(pass) pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) probeIBL.Bind(pass) heroMesh.Draw(pass) ``` - **Local reflection selection, parallax and blending**: `ReflectionProbeSet.SelectReflectionProbes` picks up to two ready (enabled, baked, non-dirty) probes covering a world position by `Priority`, smoothstep `Influence` (over `BlendDistance`), and volume, returning normalized `(Weight0, Weight1, SkyWeight)` summing to 1. Probes with `BoxProjection: true` apply `BoxProjectDirection` (`box_project_dir` in WGSL) to correct reflections against `[BoxMin, BoxMax]`. Unbaked, dirty, or disabled probes are skipped during selection, and any missing probe or `nil` sky binds a 1x1 black `(0, 0, 0, 255)` fallback cubemap so CPU `EvaluateProbeIBL` and GPU `LitPBRProbeIBLWGSL` match identically. - **Light probes (`LightProbe`, `LightProbeGrid`, `LightProbeVolume`)**: store `IrradianceSH` coefficients (baked via `ComputeIrradianceSH` or `ComputeIrradianceSHFromFunc` and combined with `Add`, `Scale`, `Lerp`). `LightProbeGrid.Sample` interpolates trilinearly and `LightProbeVolume.SampleLightProbes` blends scattered `LightProbe` points (with optional finite `Radius`) smoothly over the grid or `FallbackSH`. Both validate `Counts` against `len(Probes)` and non-finite coordinates without panicking. - **Asynchronous GPU baking and target formats**: `BakeReflectionProbeGPU` renders the six faces with `ProbeFaceCamera` into temporary `FormatRGBA8Unorm` (when `SRGB` is false) or `FormatRGBA8UnormSRGB` (when `SRGB` is true) plus `FormatDepth24Plus` offscreen render targets, reads back all six faces asynchronously via `gpu.Device.ReadTexture`, flips rows to canonical cubemap orientation, prefilters roughness mips with `PrefilterEnvironment`, uploads via `UploadCubemap`, closes any previous `probe.GPUCubemap`, and invokes `onDone` on the engine goroutine. `BakeReflectionProbe` provides the matching CPU sampler bake. - **Runtime-only bakes**: reflection probe cubemaps and light probe SH data are runtime-only caches generated on load or on request rather than persisted in text scene files. - **Custom shaders and HDR**: prepend `ProbeIBLWGSL` (`IBLGroup`) or `ProbeIBLWGSLForGroup(group)` and call `evaluate_probe_ibl(world_pos, normal, view_dir, base_color, metallic, roughness, ao)`. Share one `ProbeIBLBindGroupLayout` across multiple per-object `GPUProbeIBLBuffer` instances via `ProbeIBLBufferOptions.Layout`, and use `NewLitPBRProbeIBLPipelineWithOptions` with `LinearOutput: true` for `HDRTarget`. `ShadePoint` plus `EvaluateProbeIBL` (followed by `LinearToSRGB`) is the exact CPU reference for `LitPBRProbeIBLWGSL`. ## Mesh buffers (`Mesh`, `GPUMesh`) A `Mesh` is triangle-list geometry on the CPU: `Positions` (required), `Normals` and `UVs` (each empty or one per position) and `Indices` (empty for a non-indexed mesh). The fields have the same types as a glTF primitive's `Positions`, `Normals`, `TexCoords0` and `Indices`, and front faces wind counter-clockwise as in glTF and [math3d](https://game.nsgo.dev/docs/math3d/). `UploadMesh` validates the mesh and creates its vertex buffer and, when indexed, its index buffer on the [NSGo GPU view](https://github.com/nsgo-dev/nsgo/blob/main/docs/architecture/gpu.md)'s `gpu.Device`. The buffers belong to the scope you pass and are released when it is disposed or when you call `GPUMesh.Close`: ```go gpu.View(cx, gpu.ViewProps{ DepthFormat: gpu.FormatDepth24Plus, OnReady: func(dev *gpu.Device) { if mesh == nil { // OnReady runs again after a device loss; NSGo has already restored the retained buffers mesh, err = render3d.UploadMesh(cx, dev, render3d.Mesh{ Positions: prim.Positions, Normals: prim.Normals, UVs: prim.TexCoords0, Indices: prim.Indices, }, render3d.MeshUpload{Label: "crate", Retained: true}) } pipe, err = dev.CreatePipeline(cx, gpu.PipelineDesc{ Vertex: gpu.ShaderStage{Module: shader, EntryPoint: "vs_main"}, Fragment: gpu.ShaderStage{Module: shader, EntryPoint: "fs_main"}, VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList, FrontFace: gpu.FrontCCW, CullMode: gpu.CullBack}, DepthStencil: &gpu.DepthStencilState{Format: gpu.FormatDepth24Plus, DepthWrite: true, DepthCompare: gpu.CompareLess}, Targets: []gpu.ColorTargetState{{Format: dev.SurfaceFormat()}}, }) }, OnFrame: func(frame *gpu.Frame) { pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) pass.SetPipeline(pipe) mesh.Draw(pass) // or mesh.Bind(pass) and your own DrawIndexedInstanced pass.End() frame.Submit() }, }) ``` Every mesh uses one interleaved little-endian layout of 32 bytes per vertex, so one pipeline draws any of them; a missing normal or UV is written as zeros: | Attribute | `@location` | Format | Offset | | --- | --- | --- | --- | | position | 0 (`MeshPositionLocation`) | `float32x3` | 0 | | normal | 1 (`MeshNormalLocation`) | `float32x3` | 12 | | UV | 2 (`MeshUVLocation`) | `float32x2` | 24 | Indices are written as `uint16` while the mesh has at most 65,535 vertices and as `uint32` beyond that, so the index 0xFFFF, which WebGL 2 always treats as a primitive restart, is never used in a `uint16` buffer; index data is zero-padded to a multiple of four bytes as WebGPU requires. Only formats that every GPU view backend accepts are used: Metal on macOS and iOS, Direct3D 11 on Windows, OpenGL 3.3 on Linux, WebGPU or WebGL 2 on the web and OpenGL ES 3.0 on Android. The package's tests draw meshes on the software device of headless `nsgotest`, with both the full capabilities and those of the WebGL 2 and OpenGL ES 3.0 backends (`nsgotest.NoGPUCompute`); drawing on each hardware backend is not yet covered by an automated test. - `Mesh.Validate` rejects an empty mesh, attribute counts that do not match the positions, non-finite values, partial triangles and out-of-range indices; every error wraps `ErrInvalidMesh`, and `UploadMesh` creates nothing for an invalid mesh. - `Mesh.AppendVertexData` and `Mesh.AppendIndexData` write the buffer bytes into a slice you own without allocating when it has capacity, for streaming geometry through `Device.WriteBuffer` or a ring buffer. They do not validate: call `Mesh.Validate` first, since the bytes written for an invalid mesh are unspecified. - `MeshUpload.Retained` keeps a CPU copy so NSGo recreates the buffers after a device loss and the same `GPUMesh` draws again, so upload a retained mesh only once, as in the example; leave it off when `OnReady` uploads the meshes again. - `GPUMesh.Draw` and `GPUMesh.Bind` record nothing for a mesh that is not `Valid` (nil after a failed upload, closed, its scope disposed, or not retained across a device loss), so it never draws with buffers an earlier mesh left bound. - `GPUMesh.Bounds` is the object-space box to transform into `DrawItem.WorldBounds`, and `GPUMesh.ByteSize` the GPU memory for `RenderStats` and budgets. ## Textures and samplers (`GPUTexture`, `GPUSampler`) `UploadTexture` uploads any Go `image.Image` (including non-zero-origin sub-images) to a `gpu.Device` as a scope-owned `GPUTexture`, converting it to straight-alpha RGBA8 (`PixelBufferFromImage`; `*image.NRGBA` bytes are copied verbatim even when alpha is zero so packed data maps stay intact). `UploadTexturePixels` uploads raw `PixelBuffer` bytes in `FormatRGBA8Unorm`, `FormatRGBA8UnormSRGB`, `FormatRG8Unorm`, or `FormatR8Unorm`, with optional `Stride` row padding: ```go texLayout, err := render3d.TextureBindingLayout(cx, dev) albedo, err := render3d.UploadTexture(cx, dev, img, render3d.TextureUpload{ Label: "crate-albedo", SRGB: true, // color maps decode sRGB to linear on sample; leave false for normal/ORM data maps Mipmaps: true, // CPU area-weighted box chain (in linear light for sRGB) uploaded per level Retained: true, // survives device loss alongside retained samplers }) samp, err := render3d.NewGPUSampler(cx, dev, render3d.SamplerLinearRepeat()) bg, err := render3d.BindTexture(cx, dev, texLayout, albedo, samp) // In OnFrame, alongside CameraGroup (group 0): pass.SetBindGroup(1, bg) mesh.Draw(pass) ``` - **Mipmaps**: setting `TextureUpload.Mipmaps` builds a CPU area-weighted box mipmap chain (in linear light when `SRGB` is true, avoiding dark halos) and uploads every level via `Device.WriteTextureMip`. This works identically on every NSGo backend without depending on GPU mipmap generation, and every uploaded level is replayed automatically when `Retained` is true. Cap the level count with `TextureUpload.MaxMipLevels`. - **KTX2 textures**: `LoadKTX2` uploads a 2D KTX2 file such as `game assets` and `game tex` write, with every mip level it holds, in its sRGB or linear format, and returns the sampler to draw it with: `KTX2Upload.Sampler` with its filters set from the file's `game.filter` key (`KTX2FilterKey`), which the `filter` of the image's [import settings sidecar](https://game.nsgo.dev/docs/cli/#import-settings-beside-each-asset) writes, so `nearest` draws pixel art sharp and `linear` blends. BasisLZ, Zstandard and ZLIB supercompressed levels are decompressed first. BC1, BC3, BC7, ETC2 RGB8 and RGBA8, and ASTC 4x4 levels (including multi-partition, dual-plane and BISE-coded blocks written by `astcenc`) are uploaded compressed where `Device.SupportsCompressedFormat` allows and decoded to RGBA8 on the CPU elsewhere, so the texture loads on every backend; `KTX2Sampler` applies the filter to sampler options without a device. A file that is not such a texture, or names an unknown filter, returns an error wrapping `ErrInvalidTexture`: ```go data, err := fs.ReadFile(assets, "albedo.ktx2") albedo, opts, err := render3d.LoadKTX2(cx, dev, data, render3d.KTX2Upload{Label: "albedo", Retained: true, Sampler: render3d.SamplerLinearRepeat()}) samp, err := render3d.NewGPUSampler(cx, dev, opts) ``` - **Basis Universal (UASTC and BasisLZ/ETC1S)**: `LoadKTX2` takes both UASTC 4x4 (high-quality) and BasisLZ/ETC1S (`basisu`'s default mode, including alpha slices) KTX2 files, and transcodes them to the best block format the device supports: BC7, then BC1 for an opaque texture, BC3, ETC2 RGB8 or RGBA8 (linear only, as NSGo has no sRGB ETC2), then ASTC 4x4. It decodes to RGBA8 when the device has none of them, when the base level's width or height is not a multiple of 4, or when `KTX2Upload.ForceRGBA8` is set. Transcoding decodes every block and encodes it again on the goroutine that calls `LoadKTX2`: on a desktop CPU (Ryzen 9 3900X) a 1024×1024 level takes about 0.5 s to BC7, 0.8 s to ETC2 and 0.16 s to ASTC, and four times as long at 2048×2048 (`BenchmarkTranscodeUASTC` in `tooling/ktx2`), so load large universal textures during a loading screen. BC1 without alpha (`VK_FORMAT_BC1_RGB_*`) is refused, because an RGBA BC1 upload would draw its punch-through texels transparent. - **Dynamic updates**: `GPUTexture.UpdateImage` and `GPUTexture.UpdatePixels` replace texels in place for a matching dimension and format, regenerating and re-uploading the mip chain when the texture was created with mipmaps. - **Sampler presets and validation**: `SamplerLinearRepeat()`, `SamplerLinearClamp()`, `SamplerLinearMirror()`, `SamplerNearestRepeat()`, and `SamplerNearestClamp()` return customizable `SamplerOptions`. `SamplerOptions.Validate` rejects invalid filter/address modes, non-finite or inverted LOD bounds, and `MaxAnisotropy > 1` with non-linear filters (matching WebGPU's validation rule) with errors wrapping `ErrInvalidSampler`. - **Lifecycle and memory**: `GPUTexture.ByteSize` sums every uploaded mip level for `RenderStats.TextureBytes` and `Budget` checks. Both `GPUTexture` and `GPUSampler` are released when their owning `core.Scope` is disposed or earlier via `Close()`, and `Valid()` reports whether they belong to a live device. - **Reference renders**: `render3d`'s tests verify textured meshes, filtering, wrapping, sRGB/linear sampling, and mipmaps against golden reference PNGs (`render3d/testdata/golden/textured_mesh_scene.png` and `textured_filtering_wrapping.png`) as well as headless `gpu.View` tests on both the full and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles; `UPDATE_GOLDEN=1` rewrites the reference images. ### Morph target meshes (`MorphMesh`, `GPUMorphMesh`) `MorphMesh` pairs a base `Mesh` with per-vertex `MorphTarget` position and normal deltas (matching `gltf.MorphTarget`) and optional initial `Weights`. `UploadMorphMesh` validates the base mesh, targets, and weights (wrapping `ErrInvalidMesh` on malformed data) and creates a `GPUMorphMesh` backed by the same 32-byte `MeshVertexLayout` vertex buffer and optional index buffer as `GPUMesh`, so any existing 3D pipeline draws it without shader changes on every backend—including WebGL 2 and OpenGL ES 3.0 without compute shaders: ```go morph, err := render3d.UploadMorphMesh(cx, dev, render3d.MorphMesh{ Base: render3d.Mesh{ Positions: prim.Positions, Normals: prim.Normals, UVs: prim.TexCoords0, Indices: prim.Indices, }, Targets: targets, Weights: gltf.ResolveWeights(doc, nodeIdx), }, render3d.MeshUpload{Label: "character", Retained: true}) // Each frame before recording draws: if sampled, ok := gltf.SampleMorphWeights(anim, nodeIdx, animTime, weights); ok { weights = sampled } _ = morph.SetWeights(weights) // marks dirty only when a weight actually changes morph.Update(dev) // blends on CPU and calls dev.WriteBuffer only when dirty morph.Draw(pass) ``` - **Dirty tracking**: `SetWeights` compares against active weights and marks the mesh dirty only when at least one weight changes; `Update` skips both CPU blending and `Device.WriteBuffer` when clean. - **Live object-space bounds**: `GPUMorphMesh.Bounds` evaluates pending CPU blends on demand (caching the result so `Update` does not blend twice) and keeps the underlying `GPUMesh.Bounds` in sync for frustum culling. - **Device-loss restore**: with `MeshUpload.Retained`, NSGo recreates the vertex buffer with the last uploaded morphed bytes after a device loss; if `SetWeights` is called while the device is lost, the mesh stays `Dirty` so the first `Update` after restore uploads the pending pose. ## GPU skinning (`SkinnedMesh`, `GPUSkinnedMesh`, `GPUSkinPalette`) `SkinnedMesh` extends `Mesh` with per-vertex glTF skinning attributes (`Joints [][4]uint16` and `Weights []math3d.Vec4`) and optional `JointCount`. `SkinnedMeshFromGLTF` and `SkinnedMeshesFromGLTFNode` extract and validate triangle primitives from a loaded `gltf.Document`, checking joint bounds and normalizing each vertex's four weights so they sum to 1 (falling back to `(1, 0, 0, 0)` when all four weights are zero). `UploadSkinnedMesh` uploads the interleaved 64-byte vertex buffer and optional index buffer (`uint16` up to 65,535 vertices, `uint32` beyond) as a scope-owned `GPUSkinnedMesh` with optional `Retained` device-loss restoration. Every skinned mesh shares one interleaved little-endian layout (`SkinnedVertexLayout`), extending `MeshVertexLayout` at locations 0..2: | Attribute | `@location` | Format | Offset | | --- | --- | --- | --- | | position | 0 (`SkinnedPositionLocation`) | `float32x3` | 0 | | normal | 1 (`SkinnedNormalLocation`) | `float32x3` | 12 | | UV | 2 (`SkinnedUVLocation`) | `float32x2` | 24 | | joints | 3 (`SkinnedJointsLocation`) | `uint32x4` | 32 | | weights | 4 (`SkinnedWeightsLocation`) | `float32x4` | 48 | `GPUSkinPalette` stores up to `MaxSkinJoints` (128) joint matrices in a portable uniform buffer (`SkinUniformSize` = 8,192 bytes, fitting comfortably below WebGL 2 and OpenGL ES 3.0's 16 KiB `MAX_UNIFORM_BLOCK_SIZE` minimum). Unused joint slots are padded with identity matrices. `AppendJointMatrices` and `SkinJointMatrices` / `SkinJointMatricesWithTransform` (which compute glTF 2.0 `jointNode.WorldMatrix * InverseBindMatrices[i]` from `doc.Nodes[].WorldMatrix`) reuse caller storage with zero allocations. Three pipelines draw a `GPUSkinnedMesh`, each binding the palette at its own group, because WebGPU and WebGL 2 guarantee only four bind groups and the lit and material pipelines already use groups 0 to 2: | Pipeline | Shader | Palette group | Not combinable with | | --- | --- | --- | --- | | `NewSkinnedMeshPipeline` (unlit, colored by normal) | `SkinnedMeshWGSL` | `SkinGroup` (1) | | | `NewLitPBRPipelineWithOptions` with `LitPBRPipelineOptions.SkinLayout` (scene lights) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup` (3) | `FogLayout`, `IBLLayout`, `ShadowLayout`, `SpotShadowLayout`, `PointShadowLayout` | | `NewMaterialPipeline` with `MaterialPipelineOptions.SkinLayout` (glTF material with textures) | `MaterialSkinnedWGSL` | `MaterialSkinGroup` (2) | `FogLayout` | `SkinWGSL` declares the uniform block at group 1 and the portable `skin_position` / `skin_normal` vertex helpers matching CPU `SkinVertex`, for custom shaders that bind nothing else at group 1. Joint matrices come in two conventions. `SkinJointMatrices` returns world-space joints, so the skinned vertex is already in world space. anim3d's `Player.SkinMatricesForNode` returns mesh-local joints, `inverse(meshWorld) * jointWorld * IBM`, and the Player keeps its own world matrices instead of writing `doc.Nodes`. Upload mesh-local joints with `GPUSkinPalette.UpdateWithTransform` and the mesh node's world matrix (`Player.WorldTransform`), or pass that matrix as the lit PBR draw's model; otherwise the mesh node's own transform (CesiumMan's Z-up rotation) is lost. A lit CesiumMan animated by anim3d: ```go doc, _ := gltf.LoadFS(assetsFS, "CesiumMan.gltf") const meshNode = 2 meshes, _ := render3d.SkinnedMeshesFromGLTFNode(doc, meshNode) player, _ := anim3d.NewPlayer(doc) _ = player.Play(0) // In gpu.View OnReady: camBuf, _ := render3d.NewCameraBuffer(cx, dev) lights, _ := render3d.NewLightBuffer(cx, dev, rig, render3d.LightBufferOptions{}) draw, _ := render3d.NewPBRDrawBuffer(cx, dev, nil, render3d.NewPBRDrawUniform(math3d.Mat4Identity(), mat), true) palette, _ := render3d.NewGPUSkinPalette(cx, dev, render3d.SkinPaletteOptions{Label: "hero", Retained: true}) gpuMesh, _ := render3d.UploadSkinnedMesh(cx, dev, meshes[0], render3d.MeshUpload{Label: "hero", Retained: true}) pipe, _ := render3d.NewLitPBRPipelineWithOptions(cx, dev, camBuf.Layout(), lights.Layout(), draw.Layout(), render3d.LitPBRPipelineOptions{ DepthFormat: gpu.FormatDepth24Plus, SkinLayout: palette.Layout(), }) // Each frame: player.Step(dt) joints, _ := player.SkinMatricesForNode(meshNode) // mesh-local _ = palette.Update(frame.Device(), joints) draw.Write(frame.Device(), render3d.NewPBRDrawUniform(player.WorldTransform(meshNode), mat)) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lights.Bind(pass) pass.SetBindGroup(render3d.PBRDrawGroup, draw.BindGroup()) pass.SetBindGroup(render3d.LitPBRSkinGroup, palette.BindGroup()) gpuMesh.Draw(pass) ``` Without anim3d, pose the document with `doc.Animations[i].Apply(doc, t)` and `doc.ComputeWorldMatrices()`, then call `palette.UpdateFromGLTF(dev, doc, skinIndex)` (zero allocations) and draw with an identity model. - **Bounds**: `SkinnedMesh.Bounds` and `GPUSkinnedMesh.Bounds` cover the unskinned positions in the mesh's own space, not the drawn mesh. For culling and camera framing use `SkinnedBounds(gpuMesh.Bounds(), joints)`, the union of that box under every joint matrix, which contains the skinned mesh in any pose. - **Weights**: weights are divided by their largest component before they are summed, so large finite weights normalize instead of overflowing. - **Tests**: CesiumMan and RiggedSimple are drawn on the full and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles and compared with CPU `SkinVertex` renders; CesiumMan's bind pose is checked against the mesh node's world matrix, and the lit and material pipelines are checked with both joint conventions. ## Metallic-roughness materials (`Material`, `MaterialDefaults`, `GPUMaterial`) `Material` (aliased as `MetallicRoughnessMaterial`) represents a glTF 2.0 metallic-roughness PBR surface with base color (`BaseColorFactor`, `BaseColorTexture`), metallic-roughness (`MetallicFactor`, `RoughnessFactor`, `MetallicRoughnessTexture` using the glTF G = roughness, B = metallic channel packing), tangent-space normal mapping (`NormalTexture`, `NormalScale`), ambient occlusion (`OcclusionTexture`, `OcclusionStrength`), emissive (`EmissiveFactor`, `EmissiveTexture`), alpha modes (`AlphaOpaque`, `AlphaMask` with `AlphaCutoff`, `AlphaBlend`), and `DoubleSided` back-face normal flipping. Create one shared `MaterialDefaults` per `gpu.Device` to own the `MaterialGroup` (group 1) bind group layout (plus the unlit one, `UnlitLayout`, described under [Unlit materials and vertex colors](https://game.nsgo.dev/docs/render3d/#unlit-materials-and-vertex-colors-unlitmaterial-coloredmesh)), default linear-repeat sampler, and 1×1 fallback textures (white sRGB for missing base color, white linear for missing metallic-roughness/occlusion, flat `(128, 128, 255, 255)` for missing normal maps, and black for missing emissive maps). Because every `GPUMaterial` binds those fallbacks for omitted slots, all materials share one bind group layout with zero pipeline permutations: ```go defaults, err := render3d.NewMaterialDefaults(cx, dev, render3d.MaterialDefaultsOptions{Retained: true}) pipe, err := render3d.NewMaterialPipeline(cx, dev, camBuf.Layout(), defaults.Layout(), render3d.MaterialPipelineOptions{ DepthFormat: gpu.FormatDepth24Plus, AlphaMode: render3d.AlphaOpaque, }) mat := render3d.DefaultMaterial() mat.BaseColorFactor = [4]float32{0.95, 0.78, 0.34, 1} mat.MetallicFactor = 1.0 mat.RoughnessFactor = 1.0 mat.MetallicRoughnessTexture = mrTex // G = roughness, B = metallic mat.NormalTexture = normalTex // tangent-space normal map (+X right, +Y up, +Z out) gpuMat, err := render3d.NewGPUMaterial(cx, dev, defaults, mat, render3d.MaterialUpload{ Label: "brushed-gold", Retained: true, }) // In OnFrame, alongside CameraGroup (group 0): pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) gpuMat.Bind(pass) // binds at MaterialGroup (group 1) mesh.Draw(pass) ``` - **Zero-allocation uniform encoding and dynamic updates**: `MaterialUniforms.AppendUniformData` and `Encode` write the 16-byte-aligned 64-byte uniform block (`MaterialUniformSize`) with zero allocations when capacity is available. `GPUMaterial.Update(dev, m)` updates scalar factors and flags in place without recreating the bind group; passing `dev` explicitly lets retained materials stay updatable after a device loss and restore. - **Portable normal mapping and Cook-Torrance GGX shading**: `MaterialWGSL` (built from `CameraWGSL` + `MaterialBindingsWGSL`) derives an API-independent tangent frame from screen-space `dpdx`/`dpdy` derivatives (Cramer's rule across Metal, D3D11, OpenGL, WebGPU, WebGL 2, and GLES 3.0) and falls back to a deterministic orthonormal frame when derivatives or UVs are degenerate, so standard 32-byte `MeshVertexLayout` meshes get accurate normal mapping without extra vertex attributes. - **Vertex colors (`COLOR_0`) on metallic-roughness & lit PBR pipelines**: set `MaterialPipelineOptions.VertexColors: true` (compiles `MaterialColoredWGSL`, or its fog / linear-output variant) or `LitPBRPipelineOptions.VertexColors: true` (compiles `LitPBRColoredWGSL`, or its fog, IBL, shadow, spot/point shadow, CSM, or linear-output variant) to draw a `GPUColoredMesh` (`ColoredVertexLayout`, `@location(3)` linear RGBA). Per glTF 2.0 §3.7.2.1, the shader multiplies `base_color` (RGB and alpha) by the linear vertex color before `AlphaMask` cutoff and PBR shading. `VertexColors` cannot be combined with `SkinLayout` (`SkinnedVertexLayout` has no vertex color attribute). - **CPU reference and golden tests**: `EvaluateMaterial` (with `MaterialEvalInput.VertexColor` and `HasVertexColor`, defaulting to `[1, 1, 1, 1]` when unset) implements the exact same Cook-Torrance GGX BRDF, hemisphere ambient, normal perturbation, alpha cutoff, and Reinhard + sRGB tone mapping in pure Go; `PBRMaterial.WithVertexColor` folds a linear vertex color into `PBRMaterial` for `ShadePoint` / `EvaluatePBR` / `EvaluateIBL`. `render3d`'s tests verify GPU pixel readback directly against `EvaluateMaterial` and `ShadePoint`, render the Khronos `VertexColorTest` sample end-to-end, compare golden reference renders (`pbr_metallic_roughness_ramp.png` and `pbr_textured_normal_maps.png`), and check `gpu.View` execution on both the full and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles; `UPDATE_GOLDEN=1` rewrites the golden PNGs. ### glTF 2.0 materials and textures (`UploadGLTFMaterials`, `GLTFMaterialSet`) `UploadGLTFMaterials` maps every material, texture, image, and sampler in a loaded `*gltf.Document` onto `render3d`'s `Material`, `GPUMaterial`, `GPUTexture`, and `GPUSampler` types: ```go doc, err := gltf.LoadFS(assetsFS, "DamagedHelmet.gltf") matSet, err := render3d.UploadGLTFMaterials(cx, dev, defaults, doc, render3d.GLTFMaterialUpload{ Label: "DamagedHelmet", Retained: true, // recovers uploaded textures, samplers, and materials across device loss }) defer matSet.Close() // Resolve per-primitive material (with optional KHR_materials_variants support and -1 default fallback): gpuMat := matSet.MaterialForVariant(prim, "NightOps") // or matSet.MaterialForPrimitive(prim, -1) gpuMat.Bind(pass) gpuMesh.Draw(pass) ``` - **Automatic color-space separation & deduplication**: `baseColorTexture` and `emissiveTexture` upload with `SRGB: true` (`FormatRGBA8UnormSRGB`), while `metallicRoughnessTexture`, `normalTexture`, and `occlusionTexture` upload as linear (`FormatRGBA8Unorm`). Referenced glTF images are decoded once per image index and deduplicated on the GPU by `(imageIndex, sRGB)`, so packed ORM maps shared between `occlusionTexture` and `metallicRoughnessTexture` (or shared across multiple materials) upload only once; if the same image is used as both a color map and a data map, each color space receives its own GPU texture. - **glTF 2.0 samplers & mipmaps**: `SamplerOptionsFromGLTF` maps all six glTF filter modes and three wrap modes (`Repeat`, `ClampToEdge`, `MirroredRepeat`), defaulting omitted wrap modes to `AddressRepeat` (required by assets whose UVs wrap outside `[0, 1]`, such as `DamagedHelmet`'s `V ∈ [1, 2]`) and omitted filters to trilinear filtering with CPU-generated mipmaps. A texture without a sampler gets the same glTF default sampler as an empty sampler object. The non-mipmapped `NEAREST` and `LINEAR` min filters clamp the level of detail to the base level, so they stay sharp when the same image is also uploaded with mips for another sampler. `GLTFMaterialUpload.MaxAnisotropy` applies anisotropy only to all-linear samplers so nearest samplers stay WebGPU-valid; `DisableMipmaps` turns off mip chains when desired. - **Extensions, metadata & default material**: `GLTFMaterialSet` always uploads a glTF 2.0 default material returned by `DefaultMaterial()` and `Material(-1)` for unassigned primitives. `KHR_materials_emissive_strength` is folded into `EmissiveFactor`, and a negative `normalTexture.scale` flips the normal map's X and Y as the specification allows. `Info(i)` / `InfoForVariant(prim, name)` expose `GLTFMaterialInfo` with the `KHR_materials_unlit` flag (`Unlit`) and per-slot `GLTFTextureSlot` UV metadata (`EffectiveTexCoord`, `Transform` for `KHR_texture_transform`). - **What `MaterialWGSL` does not draw**: the shader lights every material and samples every texture with the mesh's `TEXCOORD_0` and no transform. Unlit materials, texture transforms and other UV sets are recorded but not applied, so such assets draw wrong unless you handle them. `GLTFMaterialInfo.Unsupported()` lists these cases for a material and `GLTFTextureSlot.NeedsUVBake()` reports a slot that needs its UVs baked into the mesh (for example with `Document.TransformTexCoords`) or a custom shader. - **Khronos reference verification**: `render3d`'s tests render the Khronos `DamagedHelmet` sample and check it against the asset's own base color image: a probe texture reads back the UV of every pixel, and the render must match the decoded JPEG under glTF's UV origin, sRGB color and channel order far better than under a flipped V, a linear upload or swapped channels. The tests also compare the render with `render3d/testdata/damagedhelmet/reference.png` to catch regressions and verify `gpu.View` parity across both the full and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles as well as `Retained` device-loss restoration. The model is licensed CC-BY-NC-4.0, so its directory is a separate module that is left out of the published `github.com/nsgo-dev/game` module, and these tests skip when it is absent. ### Extended PBR materials: emissive strength, clearcoat, and transmission (`GPUExtendedMaterial`, `TransmissionBackground`) `Material` also carries fields for `KHR_materials_clearcoat` (`ClearcoatFactor`, `ClearcoatRoughnessFactor`, `ClearcoatTexture`, `ClearcoatSampler`, `ClearcoatRoughnessTexture`, `ClearcoatRoughnessSampler`, `ClearcoatNormalTexture`, `ClearcoatNormalSampler`, `ClearcoatNormalScale`), `KHR_materials_transmission` (`TransmissionFactor`, `TransmissionTexture`, `TransmissionSampler`), and dielectric index of refraction (`IOR`, defaulting to `DefaultMaterialIOR = 1.5`), while `KHR_materials_emissive_strength` folds directly into HDR `EmissiveFactor` values (`> 1.0`, rendered cleanly into an `HDRTarget` with `LinearOutput: true`, `BloomPass`, and `ToneMapPass`). Plain `GPUMaterial` and `MaterialDefaults` keep their lean 11-binding layout unchanged for ordinary metallic-roughness assets. For surfaces that use clearcoat, transmission, or custom IOR, use `ExtendedMaterialDefaults`, `GPUExtendedMaterial` (or `UploadGLTFExtendedMaterials`), and `NewExtendedMaterialPipeline`: ```go extDefs, err := render3d.NewExtendedMaterialDefaults(cx, dev, render3d.MaterialDefaultsOptions{Retained: true}) transBG, err := render3d.NewTransmissionBackground(cx, dev, render3d.TransmissionBackgroundOptions{ Retained: true, SRGB: true, // true when sampling an sRGB-encoded RGBA8Unorm opaque pass; false for HDRTarget }) pipe, err := render3d.NewExtendedMaterialPipeline(cx, dev, camBuf.Layout(), extDefs.Layout(), render3d.ExtendedMaterialPipelineOptions{ DepthFormat: gpu.FormatDepth24Plus, LightLayout: lightBuf.Layout(), // optional LightRig at ExtendedLightGroup (2) TransmissionLayout: transBG.Layout(), // optional per-frame background at TransmissionBackgroundGroup (3) }) // Upload glTF materials (base PBR + clearcoat + transmission + emissiveStrength + IOR): matSet, err := render3d.UploadGLTFExtendedMaterials(cx, dev, extDefs, doc, render3d.GLTFMaterialUpload{ Label: "Sunglasses", Retained: true, }) // Each frame: render opaque scene to opaqueRT, update the single per-frame TransmissionBackground, then draw transmissive draws: _ = transBG.SetTexture(dev, opaqueRT.Color, true) // or transBG.SetDynamicResolution(dev, dynTarget, nil, 0, 0, true) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) pass.SetBindGroup(render3d.ExtendedLightGroup, lightBuf.BindGroup()) transBG.Bind(pass) // @group(3) TransmissionBackgroundGroup (or BindAt(..., MaterialTransmissionBackgroundGroup) without LightLayout) matSet.ExtendedMaterial(prim.Material).Bind(pass) // @group(1) MaterialGroup mesh.Draw(pass) ``` - **UV-aligned clearcoat normal mapping**: `ExtendedMaterialBindingsWGSL` reuses the same Cramer's-rule `dpdx`/`dpdy` cotangent-frame normal perturbation helper (with deterministic orthonormal fallback) on the geometric normal for `ClearcoatNormalTexture` independently of the base `NormalTexture`, honoring positive and negative `ClearcoatNormalScale`. - **Per-frame transmission background and dynamic resolution**: `TransmissionBackground` keeps the opaque scene color texture out of per-material bind groups so resizing the swapchain or scaling a `DynamicResolutionTarget` updates only one pass-level bind group. Screen UVs are derived from `frag_pos.xy / vec2(textureDimensions(transmission_bg_tex))`, scaled and half-texel clamped by `SetViewport` / `SetDynamicResolution` so unused padding texels never bleed. - **CPU parity and Khronos golden tests**: `EvaluateMaterial`, `EvaluatePBR`, `ShadePoint`, and `ShadePointWithBackground` evaluate clearcoat, transmission, and IOR on the CPU to match the GPU shaders. Tests verify GPU-vs-CPU parity, `DynamicResolutionTarget` resizes across 0.5×–1.0× scales, `gpu.View` execution on both full and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles, `Retained` device-loss restoration, and golden renders of the Khronos `EmissiveStrengthTest` (`khronos_emissive_strength.png`), `TextureTransformMultiTest` clearcoat panels (`khronos_clearcoat.png`), and `SunglassesKhronos` (`khronos_transmission.png`). ## Unlit materials and vertex colors (`UnlitMaterial`, `ColoredMesh`) `ColoredMesh` and `GPUColoredMesh` extend `MeshVertexLayout` (locations 0–2) with a linear RGBA vertex color attribute at `@location(3)` (`ColoredVertexLayout`, stride 48 bytes) for glTF `COLOR_0`. When `Colors` is empty, `AppendVertexData` writes linear opaque white `(1, 1, 1, 1)` per vertex so colored and uncolored meshes share one pipeline. `ColoredMeshFromGLTF` extracts triangle primitives from a `gltf.Document` including `COLOR_0` (expanding VEC3 RGB to alpha `1.0`) and `KHR_texture_transform` UVs on `baseColorTexture`. `UnlitMaterial`, `GPUUnlitMaterial`, `UnlitWGSL`, and `NewUnlitPipeline` implement glTF `KHR_materials_unlit` surfaces unaffected by scene lighting (`baseColorFactor * baseColorTexture * vertexColor` in linear space, followed by alpha handling and IEC 61966-2-1 linear-to-sRGB encoding). They share the metallic-roughness types where the two overlap: `AlphaMode`, `MaterialGroup` (group 1), `MaterialUpload`, `GLTFMaterialUpload`, `SamplerOptionsFromGLTF`, and the per-device `MaterialDefaults`, which also owns the unlit bind group layout (`MaterialDefaults.UnlitLayout`): ```go defaults, err := render3d.NewMaterialDefaults(cx, dev, render3d.MaterialDefaultsOptions{Retained: true}) cm, err := render3d.ColoredMeshFromGLTF(doc, 0, 0) gpuMesh, err := render3d.UploadColoredMesh(cx, dev, cm, render3d.MeshUpload{Label: "sign", Retained: true}) gpuMat, err := render3d.UploadGLTFUnlitMaterial(cx, dev, defaults, doc, 0, render3d.GLTFMaterialUpload{ Label: "sign-unlit", Retained: true, }) pipe, err := render3d.NewUnlitPipeline(cx, dev, camBuf.Layout(), defaults.UnlitLayout(), render3d.UnlitPipelineOptions{ AlphaMode: gpuMat.Material().AlphaMode, DoubleSided: gpuMat.Material().DoubleSided, DepthFormat: gpu.FormatDepth24Plus, Retained: true, }) // In OnFrame: pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) gpuMat.Bind(pass) // binds @group(1) (MaterialGroup) gpuMesh.Draw(pass) ``` - **Fallback texture and sampler**: when `UnlitMaterial.BaseColorTexture` or `BaseColorSampler` is nil, `NewGPUUnlitMaterial` binds the shared `MaterialDefaults.WhiteSRGB()` texture and `MaterialDefaults.Sampler()`, so textureless unlit materials allocate nothing beyond their 32-byte uniform buffer. - **Alpha modes and culling**: `AlphaOpaque` forces output alpha to `1.0` with depth writes enabled; `AlphaMask` discards fragments with combined alpha `< AlphaCutoff` (default `0.5`) and outputs `1.0`; `AlphaBlend` enables straight-alpha blending (`gpu.BlendAlpha`) with depth writes disabled. `DoubleSided` switches culling from `gpu.CullBack` to `gpu.CullNone`. `BaseColorFactor` must lie in `[0, 1]`, as for `Material`. - **Target color space and CPU parity**: `NewUnlitPipeline` selects `fs_main` (linear-to-sRGB in shader) for non-sRGB targets such as `FormatRGBA8Unorm`, and `fs_linear` (linear output) for sRGB targets (`ColorFormat.IsSRGB()`, where the hardware encodes on write) or when `LinearOutput` is set for an `HDRTarget`. `NewMaterialPipeline` and the lit PBR pipelines always encode in the shader and do not switch on an sRGB format, so when unlit and PBR draws share a pass, give them a non-sRGB target. `EvaluateUnlit` provides the matching pure-Go CPU reference (`Linear`, `SRGB`, `Discarded`, `RGBA8()`, `BlendOver()`). - **Vertex colors in both unlit and PBR pipelines**: `ColoredVertexLayout` and `GPUColoredMesh` work with `NewUnlitPipeline`, with `NewMaterialPipeline` when `MaterialPipelineOptions.VertexColors` is set (`MaterialColoredWGSL`), and with `NewLitPBRPipelineWithOptions` when `LitPBRPipelineOptions.VertexColors` is set (`LitPBRColoredWGSL` and its fog, IBL, shadow, and CSM variants). Without `VertexColors`, the metallic-roughness and lit PBR pipelines keep `MeshVertexLayout` unchanged. - **Zero-allocation uniform updates and device-loss recovery**: `AppendUnlitUniforms` writes the 32-byte uniform block with zero allocations when given capacity; `GPUUnlitMaterial.Update(dev, mat)` updates parameters in place without caching a `*gpu.Device` pointer, so materials created with `Retained: true` survive device loss and remain updatable after restoration. NSGo restores a bind group layout only when a restored bind group uses it, so `MaterialDefaults.UnlitLayout()` comes back only while a retained `GPUUnlitMaterial` exists; `MaterialDefaults.Valid` does not cover it. - **glTF helpers**: `UnlitMaterialFromGLTF` validates that a glTF material declares `KHR_materials_unlit` (returning `ErrInvalidUnlitMaterial` otherwise). `UploadGLTFUnlitMaterial` decodes and uploads embedded or external `baseColorTexture` images in sRGB with a sampler from `SamplerOptionsFromGLTF` (so a non-mipmapped `minFilter` stays on level 0 even when mipmaps exist) and applies `GLTFMaterialUpload`'s mipmap, anisotropy and `Retained` options as `UploadGLTFMaterials` does. A `baseColorTexture` whose image comes only through an extension such as `KHR_texture_basisu` returns `ErrInvalidUnlitMaterial` instead of drawing white. - **Reference renders**: `render3d`'s tests draw the Khronos `UnlitTest` sample end to end (loader, `ColoredMeshFromGLTF`, `UploadGLTFUnlitMaterial`, `NewUnlitPipeline`) and require every covered pixel to be the sample's flat `#FF7F00` or `#007FFF`, compare a multi-mode unlit + vertex-color scene against `render3d/testdata/golden/unlit_vertex_colors_scene.png`, and verify `gpu.View` pixel parity against `EvaluateUnlit` on both the full and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles. ## Toon shading (`ToonMaterial`, `ToonRenderer`) `ToonMaterial` and `ToonRenderer` draw cel/toon shading: quantized diffuse light bands (or a 1D color ramp texture), hard stepped Blinn-Phong highlights, Fresnel rim light, and inverted-hull outlines. The shaders (`ToonWGSL`, `ToonOutlineWGSL`) use only vertex and fragment stages, so they run on WebGPU, Metal, Vulkan, Direct3D 11, OpenGL 3.3, OpenGL ES 3.0, WebGL 2, and NSGo's software renderer: ```go defaults, err := render3d.NewMaterialDefaults(cx, dev, render3d.MaterialDefaultsOptions{Retained: true}) renderer, err := render3d.NewToonRenderer(cx, dev, render3d.ToonRendererOptions{ CameraLayout: camBuf.Layout(), DepthFormat: gpu.FormatDepth24Plus, Retained: true, }) spec := render3d.DefaultToonMaterial() spec.BaseColorFactor = [4]float32{0.94, 0.34, 0.24, 1} spec.OutlineWidth = 0.045 heroMat, err := renderer.NewMaterial(cx, dev, defaults, spec, "hero") // Hard-edged meshes (boxes, low-poly props) need shared corner normals for a closed outline: boxOutlineCPU, err := render3d.SmoothOutlineNormals(boxMesh) boxOutline, err := render3d.UploadMesh(cx, dev, boxOutlineCPU, render3d.MeshUpload{Label: "box-outline"}) // In OnFrame, inside a render pass with a depth attachment: light, err := render3d.ToonLightFromRig(rig) // or render3d.DefaultToonLight() err = renderer.Draw(dev, pass, camBuf.BindGroup(), light, render3d.ToonDraw{Mesh: sphereMesh, Material: heroMat, Transform: sphereXform}, render3d.ToonDraw{Mesh: boxGPU, OutlineMesh: boxOutline, Material: boxMat, Transform: boxXform}, ) ``` - **Bands and ramps**: `Bands` selects 2 to 8 diffuse steps (`0` means `3`), blending from `ShadowColor` to fully lit across `N·L`; `BandSmoothness` in `[0, 0.5]` softens the band edges (`0` gives hard steps). A `RampTexture`, sampled at `u = clamp(N·L, 0, 1)`, replaces the bands with an artist-drawn color ramp; without its own `RampSampler` the material creates a linear-clamp sampler so the ramp's ends do not wrap. - **Highlights**: `SpecularColor`, `SpecularPower` (`0` means `32`), `SpecularThreshold`, and `SpecularSmoothness` add a stepped Blinn-Phong highlight on lit surfaces; `RimColor`, `RimThreshold`, and `RimSmoothness` add a Fresnel rim based on `1 - N·V`. - **Lights**: `ToonLight` holds one `DirectionalLight` key light, whose `N·L` is banded, and an `AmbientLight` fill, with the same conventions as a `LightRig`: `Direction` is the way the rays travel, a zero direction is an error, intensity `0` turns a light off, and errors wrap `ErrInvalidLight`. `ToonLightFromRig` takes the first directional light and the ambient fill of a scene's rig; point lights are not used. - **Bind groups**: `CameraGroup` (0), `ToonMaterialGroup` (1, the same slot as `MaterialGroup`) and `ToonSceneGroup` (2, the per-draw model matrix and the key light, with a dynamic offset in `ToonRenderer`). - **Materials**: `NewGPUToonMaterial` and `ToonRenderer.NewMaterial` take a shared `MaterialDefaults` and bind its white textures and sampler for omitted ones, as `NewGPUMaterial` does. `GPUToonMaterial.Update` rewrites the uniform block without allocating but cannot swap textures or samplers. - **Outlines**: the outline pipeline (`NewToonOutlinePipeline`, `gpu.CullFront`) pushes back faces out along their normals by `OutlineWidth` and fills them with `OutlineColor`; an outline alpha of `0` or a width of `0` turns it off. The width is in world units, or with `OutlineClipSpace` in NDC y units, which gives `OutlineWidth × viewport height / 2` pixels in every direction at every distance as long as the camera's aspect ratio matches the viewport's. `SmoothOutlineNormals` averages the normals of vertices at the same position (coordinates equal after rounding to 1e-5), each corner weighted by its angle, and returns an error wrapping `ErrInvalidMesh` for an invalid mesh. - **Drawing**: `ToonRenderer.Draw` draws the outlines first and the cel-shaded surfaces second, opaque and with depth writes. It can run any number of times before a submission, into one pass or several: each call writes its per-draw uniforms after the slots earlier calls of the frame used. Inside a `gpu.Frame` the slots rewind on their own when `dev.FrameIndex()` advances; code that submits with `dev.Submit` directly calls `ToonRenderer.Begin` once per frame (at most `MaxToonDrawsPerFrame` draws between two calls). `Draw` returns a `gpu.Error` for a nil or closed renderer, device, pass, or camera bind group. For blended toon surfaces, build pipelines with `NewToonPipeline` and `NewToonOutlinePipeline` and a `ToonPipelineOptions.Blend`. - **CPU reference and tests**: `EvaluateToon` and `ToonQuantizeBand` evaluate `ToonWGSL` in Go. `render3d`'s tests compare a multi-object scene with `render3d/testdata/golden/toon_scene.png` (`UPDATE_GOLDEN=1` rewrites it), draw in a headless `gpu.View` on both the full and `nsgotest.NoGPUCompute` profiles, restore a `Retained` renderer after a device loss, draw twice before one submission, and measure the clip-space outline on a wide viewport. ## Custom shader materials (`CustomMaterial`) `NewCustomMaterial` compiles a custom 3D material written in **WGSL** (`ShaderWGSL`) or **Kage** (`ShaderKage`) with declared, strongly-typed parameters (`ShaderParamDesc`) onto an NSGo `gpu.Device`, managing its std140 uniform buffer, `@group(1)` bind group (`CustomMaterialGroup`, the same slot as `MaterialGroup`), 1×1 fallback textures, and render pipeline inside the owning `core.Scope`. Where `GPUMaterial` and `MaterialBindingsWGSL` give a custom shader the fixed glTF metallic-roughness bindings, `CustomMaterial` lets the shader declare its own parameters and textures: ```go mat, err := render3d.NewCustomMaterial(cx, dev, render3d.CustomShaderDesc{ Label: "hologram", Language: render3d.ShaderWGSL, // or render3d.ShaderKage CameraLayout: camBuf.Layout(), // binds CameraWGSL at @group(0); omit for clip-space shaders DrawLayout: draw.Layout(), // optional PBRDrawBuffer at @group(2) for a per-draw model matrix DepthFormat: gpu.FormatDepth24Plus, Cull: gpu.CullBack, Retained: true, // survives GPU device loss and restore Params: []render3d.ShaderParamDesc{ {Name: "intensity", Kind: render3d.ParamFloat, Default: float32(1.0)}, {Name: "light_dir", Kind: render3d.ParamVec3, Default: math3d.Vec3{X: 0.4, Y: 0.85, Z: 0.35}}, {Name: "tint", Kind: render3d.ParamColor, Default: core.RGB(0xf0c878)}, {Name: "albedo", Kind: render3d.ParamTexture}, }, Source: myWGSLSource, }) // Update parameters at runtime and flush dirty bytes before drawing: _ = mat.SetFloat("intensity", 1.5) _ = mat.SetColor("tint", core.RGB(0x55d0ff)) _ = mat.SetTexture("albedo", tex, samp) // nil tex restores 1x1 fallback; nil samp uses default linear-repeat _ = mat.Sync(dev) // 0 allocations when unchanged // In OnFrame: pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) pass.SetBindGroup(render3d.PBRDrawGroup, draw.BindGroup()) mat.Draw(pass, mesh) // sets pipeline, binds @group(1), and draws mesh ``` - **Declared parameter types and std140 layout**: `ParamFloat` (`f32`), `ParamVec2` (`vec2`), `ParamVec3` (`vec3`), `ParamVec4` / `ParamColor` (`vec4`), `ParamInt` (`i32`), `ParamBool` (`u32`, `0`/`1` for portable uniform structs), and `ParamTexture` (`texture_2d` + `_sampler`). Non-texture parameters are packed automatically in declared order with WGSL/std140 alignment (`ComputeUniformLayout`, `ParamOffset`, `UniformSize`) at `@group(1) @binding(0)` (`material`), followed by each texture/sampler pair (`ParamBinding`). A float, int or bool parameter cannot directly follow a `ParamVec3`, because NSGo's Metal backend pads `vec3` struct members to 16 bytes where WGSL packs the next scalar into the last 4; declare it before the vec3 or after a vec2/vec4, or use `ParamVec4`. Unset texture slots receive an automatic 1×1 fallback texture (opaque white by default, customizable via `ShaderParamDesc.Default`). - **WGSL and Kage shaders**: `ShaderWGSL` prepends `CameraWGSL` when `CameraLayout` is set and the source declares nothing in `@group(0)`, and prepends the generated `MaterialParams` / texture bindings unless `ManualBindings: true` (then the source declares `@group(1)` itself). `ShaderKage` parses Kage `var float|vec2|vec3|vec4|int|bool` declarations, helper functions, and `func Surface(uv vec2, normal vec3, worldPos vec3) vec4` (or `func Fragment(dst vec4, pos vec2) vec4`) and translates them into portable WGSL supporting `sample(, uv)` and `image0At(uv)`. Unlike Ebitengine's 2D Kage, `Fragment`'s `pos` is the mesh's normalized UV rather than a texel position, `dst` is the fragment's framebuffer position, and `imageNAt` samples with the texture's sampler (linear-repeat by default), so it wraps instead of returning transparent outside the image. - **Placement and lights**: without `DrawLayout`, the Kage vertex stage passes positions and normals through unchanged, so `worldPos` and `normal` are in object space and the mesh draws where its vertices are. Set `DrawLayout` to a `PBRDrawBuffer`'s layout and bind its bind group at `PBRDrawGroup` (group 2): a Kage shader then transforms positions by the `PBRDrawUniform` model matrix and normals by its normal matrix, so `worldPos` and `normal` are in world space, while a WGSL shader declares the block itself as `LitPBRWGSL` does. `ExtraLayout` adds group 3 for bindings the shader declares, such as a `GPULightBuffer` declared with `LightWGSLForGroup(3)` (`LightWGSL` uses group 1, which holds the material) or a `DirectionalShadowMap` with `ShadowWGSL`; it requires `DrawLayout`. `Bind` and `Draw` bind only group 1, so the caller binds groups 0, 2 and 3. - **Texture swaps**: `Sync` keeps the bind groups of the 8 most recently bound texture/sampler combinations, so alternating between a few textures (a flipbook, ping-pong render targets) reuses them without allocating; a material that cycles through more distinct textures than that creates a bind group per change. - **Strict validation and cross-backend checks**: Typed setters (`SetFloat`, `SetVec2`, `SetVec3`, `SetVec4`, `SetColor`, `SetInt`, `SetBool`, `SetTexture`) and atomic `ApplyMap` reject unknown parameter names, type mismatches, non-finite values (`NaN`/`Inf`), and out-of-range values against optional `Min`/`Max` bounds with `*CustomMaterialError`, which matches both `ErrInvalidCustomMaterial` and `ErrInvalidMaterial`. Its `Line` is the source line, also for WGSL errors in code translated from Kage. `ApplyMap` binds a texture with the default sampler, as `SetTexture` with a nil sampler does. `CompileCheck` / `CompileCheckDesc` verifies shader lowering and cross-backend pipeline compilation across MSL, HLSL, GLSL 3.30, GLSL ES 3.00 (WebGL 2 / Android), and WGSL without an active `gpu.View`. `ByteSize` reports the uniform buffer and fallback textures for `RenderStats` and `Budget`. - **Reference renders**: `render3d`'s tests verify both WGSL and Kage custom materials against golden reference PNGs (`render3d/testdata/golden/custom_material_wgsl.png` and `custom_material_kage.png`), cross-backend `PipelineCache` artifacts for all five targets, headless `gpu.View` rendering on both `full` and `nsgotest.NoGPUCompute` (WebGL 2 / GLES 3.0) profiles, `Retained` device-loss restoration, and zero-allocation steady-state updates; `UPDATE_GOLDEN=1` rewrites the reference images. ## Budgeted async GPU uploads (`Uploader`) `Uploader` runs the decoding and CPU packing of meshes, textures and raw GPU payloads on background worker goroutines, and `Uploader.Step`, called once per frame, writes the results to the `gpu.Device` in chunks within a per-frame byte budget, so loading a large 3D model does not stall a frame: ```go gpu.View(cx, gpu.ViewProps{ DepthFormat: gpu.FormatDepth24Plus, OnReady: func(dev *gpu.Device) { uploader = render3d.NewUploader(cx, dev, render3d.UploaderOptions{ BytesPerFrame: 2 * 1024 * 1024, // 2 MiB per frame (default 4 MiB) ChunkBytes: 256 * 1024, // 256 KiB per write Workers: 2, // background decode goroutines }) meshHandle = uploader.QueueMesh(ctx, render3d.PriorityHigh, func(ctx context.Context) (render3d.Mesh, error) { return loadAndDecodeMesh(ctx, "hero.glb") }, func(g *render3d.GPUMesh, err error) { if err == nil { heroMesh = g } }, render3d.MeshUpload{Label: "hero", Retained: true}) texHandle = uploader.QueueTexture(ctx, render3d.PriorityNormal, func(ctx context.Context) (image.Image, error) { return decodeTexturePNG(ctx, "hero_albedo.png") }, func(tex *render3d.GPUTexture, err error) { if err == nil { heroAlbedo, _ = render3d.BindTexture(cx, dev, texLayout, tex, sampler) } }, render3d.TextureUpload{Label: "hero_albedo", SRGB: true, Mipmaps: true, Retained: true}) }, OnFrame: func(frame *gpu.Frame) { stats := uploader.Step() // writes at most BytesPerFrame on the engine goroutine _ = stats // draw with whichever meshes and textures are ready... }, }) ``` - **Drop-in for the synchronous uploads**: `QueueMesh` takes the same `MeshUpload` options as `UploadMesh` and delivers a `GPUMesh`; `QueueTexture` and `QueueTexturePixels` take the same `TextureUpload` options as `UploadTexture` and `UploadTexturePixels` and deliver a `GPUTexture` with the same texels, the same straight-alpha conversion (`PixelBufferFromImage`) and the same mip chain (box-filtered in linear light for sRGB), so it works with `BindTexture` and counts in `GPUTexture.ByteSize`. Each `Queue*` call also takes an `UploadPriority`. - **Decode off-thread, upload on the engine goroutine**: decode callbacks, mesh validation and packing, image conversion and mip generation run on the workers. GPU resource creation, the chunked writes (`WriteBuffer`, `WriteTextureRegion`, `WriteTexture`) and the `onReady` callbacks run on the goroutine that calls `Step`. Errors a `Queue*` call can report at once (a nil decode function, a closed uploader, a full queue) call `onReady` before the call returns, on the caller's goroutine. - **Per-frame byte budget**: `UploaderOptions.BytesPerFrame` (default `DefaultUploadBytesPerFrame`, 4 MiB) and `ChunkBytes` (default `DefaultUploadChunkBytes`, 256 KiB) cap the bytes written per `Step`, and `SetBytesPerFrame` and `SetChunkBytes` change them at runtime, for example raising the budget on a loading screen and lowering it during play. The budget bounds the upload work in each frame; it is not a time limit. Buffers split at 4-byte aligned offsets; uncompressed textures split by mip level, row band and, when a row exceeds the remaining budget, part of a row; block-compressed textures split by block row. - **Raw buffers and textures**: `QueueRawBuffer` streams custom vertex, storage or uniform buffers (`RawBufferUpload`), and `QueueRawTexture` streams pre-encoded or block-compressed mip chains, array layers and cube faces (`RawTextureUpload`, `TextureMipData`) and delivers the `gpu.Texture`. - **Priority and cancellation**: `PriorityHigh`, `PriorityNormal` and `PriorityLow` order both the decode and the upload queue (FIFO within a priority), so a high-priority asset preempts a low-priority one that is partway through its upload at the next chunk. Each `Queue*` call returns an `*UploadHandle` whose `State()`, `Progress()`, `Err()`, `Done()` and `Cancel()` are safe from any goroutine. - **Lifecycle**: passing a `*core.Scope` to `NewUploader` closes the uploader when the scope is disposed. `Close` cancels pending decodes, joins every worker goroutine, releases partially uploaded GPU resources and calls the `onReady` of each unfinished upload with `ErrUploaderClosed`; call it on the goroutine that calls `Step`, as scope disposal does. Pass `nil` in headless tests and call `Close` yourself. `UploaderOptions.MaxPending` bounds the unfinished uploads, failing further ones with `ErrUploadQueueFull`. ## HDR rendering, tone mapping, and gamma (`HDRTarget`, `ToneMapPass`) Render the scene's linear radiance into an `HDRTarget` (`gpu.FormatRGBA16Float`, falling back to `gpu.FormatRGBA8Unorm` on devices where `SupportsHDR(dev)` is false), then resolve it to the display with `ToneMapPass`. render3d's own shaders tone-map and encode to sRGB by default, so draw into the HDR target with their linear output mode: `LitPBRPipelineOptions.LinearOutput` for lit PBR (with or without fog or IBL, through `NewLitPBRPipelineWithOptions`) and `MaterialPipelineOptions.LinearOutput` for materials. Without it the image is tone-mapped and gamma-encoded twice and the HDR target only stores values already clamped to `[0, 1]`. ```go var ( hdr *render3d.HDRTarget pipe *gpu.Pipeline tonePass *render3d.ToneMapPass setupErr error ) gpu.View(cx, gpu.ViewProps{ OnReady: func(dev *gpu.Device) { if tonePass != nil { tonePass.SetDevice(dev) // retained resources come back in place after a device loss return } w, h := dev.SurfaceSize() hdr, setupErr = render3d.NewHDRTarget(cx, dev, render3d.HDRTargetDesc{ Label: "scene-hdr", Width: uint32(w), Height: uint32(h), DepthFormat: gpu.FormatDepth24Plus, Retained: true, }) if setupErr != nil { return } pipe, setupErr = render3d.NewLitPBRPipelineWithOptions(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBuf.Layout(), render3d.LitPBRPipelineOptions{ ColorFormat: hdr.Format(), DepthFormat: gpu.FormatDepth24Plus, LinearOutput: true, }) if setupErr != nil { return } tonePass, setupErr = render3d.NewToneMapPass(cx, dev, render3d.ToneMapPassDesc{ Label: "tonemap", TargetFormat: dev.SurfaceFormat(), Retained: true, }) }, OnFrame: func(frame *gpu.Frame) { if setupErr != nil || tonePass == nil { return } w, h := frame.Size() if err := hdr.Resize(frame.Device(), uint32(w), uint32(h)); err != nil { return } // 1. Render the scene in linear HDR radiance (values above 1.0 are kept): scenePass := frame.BeginRenderPass(hdr.RenderPassDesc(core.RGB(0x0a0e18), 1)) scenePass.SetPipeline(pipe) scenePass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lightBuf.Bind(scenePass) scenePass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(scenePass) scenePass.End() // 2. Tone-map and encode to sRGB onto the swapchain: opts := render3d.DefaultToneMapOptions() opts.Operator = render3d.ToneMapAgX opts.Exposure = render3d.ExposureFromEV(0.5) displayPass := frame.BeginRenderPass(gpu.RenderPassDesc{Label: "tonemap"}) err := tonePass.DrawTarget(displayPass, frame.Device(), hdr, opts) displayPass.End() if err != nil { return } frame.Submit() }, }) ``` `ToneMapOptions.Operator` chooses the highlight compression curve: | Operator | Curve | Best for | | --- | --- | --- | | `ToneMapNone` | Linear clamp to `[0, 1]` | Debugging linear inputs | | `ToneMapReinhard` | Per-channel `c / (1 + c)` | Simple soft highlight roll-off | | `ToneMapACES` (`DefaultToneMapOptions`) | Narkowicz ACES filmic fit | High-contrast cinematic look | | `ToneMapNeutral` | Khronos PBR Neutral | Faithful mid-tone hues and PBR asset viewing | | `ToneMapAgX` | Troy Sobotka AgX default look | Smooth highlight desaturation without hue skew | - **Exposure**: `ToneMapOptions.Exposure` is a linear multiplier; derive it from photographic stops with `ExposureFromEV(ev)` (`0 -> 1.0`, `+1 -> 2.0`, `-1 -> 0.5`, clamped to `[-126, 126]` stops so it is always positive). Exposure `0` renders black, so a fade to black can interpolate it down to `0`; negative, NaN and infinite values count as `1.0`. Start from `DefaultToneMapOptions()` so the field's zero value does not leave the image black. - **Gamma and sRGB**: when `ToneMapOptions.Gamma <= 0` (the default) and `LinearOutput` is false, `ToneMapPass` applies the exact IEC 61966-2-1 linear-to-sRGB transfer function (`LinearToSRGBChannel` / `LinearToSRGB` on the CPU, with `SRGBToLinearChannel` / `SRGBToLinear` as their inverse); a positive `Gamma` (such as `2.2`) applies `pow(c, 1/Gamma)`. When `ToneMapPassDesc.TargetFormat.IsSRGB()` is true, the pass writes linear tone-mapped RGB so the sRGB framebuffer encodes it once, without double gamma. A material drawn with `LinearOutput` and resolved with `ToneMapReinhard` and `Gamma: 2.2` looks the same as the material pipeline's own output. - **Overflow**: an `RGBA16Float` target stores values above 65504, such as strong specular highlights, as `+Inf`. The pass clamps exposed radiance to `[0, 65504]` and maps NaN to `0` before the curve (`ApplyToneMap` does the same), so blown highlights stay white instead of turning black. - **Dynamic resolution**: create the `DynamicResolutionTarget` with an HDR `ColorFormat` (`PreferredHDRFormat(dev)`), draw the scene with `Begin3D`, and call `ToneMapPass.DrawDynamicResolution` in place of `Upscale`. It tone-maps only the scaled sub-viewport and upscales it with the pass's sampler in the same draw; the sharpen filter is not applied. - **One set of options per submission**: each `ToneMapPass` has one uniform buffer, and buffer writes are applied before the submission's commands, so every draw one pass records into a frame uses the options of its last `Draw`. To tone-map several views with different options in one frame (split screen, a picture-in-picture camera), create one `ToneMapPass` per view. - **Allocations and device loss**: `AppendToneMapUniforms` encodes the `ToneMapUniformSize` (48-byte) uniform block without allocating, and the pass reuses its bind group while the source texture stays the same; each draw still uploads the block with `gpu.Device.WriteBuffer`, which copies it. With `Retained: true` on `HDRTargetDesc` and `ToneMapPassDesc`, NSGo recreates the textures, sampler, uniform buffer, layout and pipeline after a device loss, and the pass rebuilds its bind group on the next draw. - **CPU reference and portability**: `ApplyToneMap` mirrors `ToneMapWGSL` on the CPU. `ToneMapWGSL` avoids the `exp` and `log2` builtins (AgX uses a range-reduced polynomial `log2`), because NSGo v0.3.0's software GPU returns 0 for them, and runs on both the full GPU profile and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0). - **Reference renders**: the tests draw a scene through the lit PBR pipeline's linear output mode, with emissive boxes and highlights well above 1.0, and compare it with `render3d/testdata/golden/tonemap_aces.png`, `tonemap_agx.png` and `tonemap_neutral.png`; `UPDATE_GOLDEN=1` rewrites them. Other tests check the lit PBR and material linear modes against `ShadePoint` and `EvaluateMaterial` through `ApplyToneMap`. ## Anti-aliasing (`MSAATarget`, `FXAAPass`) `render3d` supports hardware multisample anti-aliasing (MSAA) where the GPU device offers it and a full-screen FXAA 3.11 post-processing pass for single-sampled paths, post-FX chains, or devices without MSAA: | Mode (`AAMode`) | Behavior | | --- | --- | | `AANone` | Single-sampled (`1x`), no post-processing. | | `AAFXAA` | Single-sampled render into an offscreen target followed by `FXAAPass`. | | `AAMSAA2x` | Requests `2x` MSAA; `ClampSampleCount` promotes it to `4x` when `Features.MSAA4x` is true (WebGPU and NSGo expose `1x` and `4x` sample counts) and falls back to `1x` otherwise. | | `AAMSAA4x` | Requests `4x` MSAA; resolves to `4x` when `Features.MSAA4x` is true and falls back to `1x` otherwise. | `MSAATarget` wraps an offscreen color (and optional depth) `gpu.RenderTarget` whose sample count is clamped via `ClampSampleCount`. Call `Resize` on viewport size changes (redundant calls at the same dimensions are zero-allocation no-ops), pass `ColorAttachment` / `DepthStencilAttachment` (or `RenderPassDesc`) into `BeginRenderPass`, and read the single-sampled result from `OutputTexture` (the resolved texture when multisampled, or the color texture when single-sampled): ```go target, err := render3d.NewMSAATarget(cx, dev, render3d.MSAATargetDesc{ Label: "scene", Width: uint32(w), Height: uint32(h), ColorFormat: gpu.FormatRGBA8Unorm, DepthFormat: gpu.FormatDepth24Plus, SampleCount: mode.SampleCount(), // clamped automatically via ClampSampleCount Retained: true, }) // In OnFrame: desc, err := target.RenderPassDesc(clearColor, 1.0) if err != nil { return // the target is closed or its device is lost } pass := frame.BeginRenderPass(desc) // ... draw with a pipeline using SampleCount: target.SampleCount() ... pass.End() resolved := target.OutputTexture() ``` When MSAA is multisampled, `ColorAttachment` sets `ResolveTarget` to the resolve texture and `StoreOp` to `gpu.StoreDiscard` so tile GPUs avoid writing back the transient multisample buffer; when clamped to `1x`, it stores directly into the color texture with `gpu.StoreStore`. `ColorAttachment` and `RenderPassDesc` return an error for a closed target or a lost device rather than an attachment with a nil texture, which NSGo would draw into the view's swapchain. - **Depth**: the depth attachment is transient by default: it is cleared at the start of the pass and discarded at the end (and so is the stencil of a depth-stencil format). Set `KeepDepth: true` on `MSAATargetDesc` to store it, so later passes can read `DepthTexture()`; the depth texture of a `4x` target is multisampled. - **Sample count across devices**: the target keeps the requested sample count, and `Resize` clamps it against the current device, reallocating even at the same size when the clamped count changes. After `SetDevice` to a device with different MSAA support, call `Resize`, compare `SampleCount()` with its previous value, and rebuild the pipelines built with the old count. For post-process anti-aliasing, `FXAAPass` compiles `FXAAWGSL` (a bufferless full-screen triangle FXAA 3.11 Quality shader using only `textureSampleLevel(..., 0.0)`, so it runs without compute shaders on both full and `NoGPUCompute` / WebGL 2 / OpenGL ES 3.0 profiles) and keeps one bind group per source texture, so steady-state draws do not allocate. The shader reads the texel size from the source with `textureDimensions`, so one pass can filter sources of different sizes in the same frame: ```go fxaa, err := render3d.NewFXAAPass(cx, dev, render3d.FXAAPassDesc{ TargetFormat: dev.SurfaceFormat(), Options: render3d.DefaultFXAAOptions(), Retained: true, }) // Inside a single-sampled render pass (e.g. swapchain) or via fxaa.Encode(enc, src, dst): err = fxaa.Draw(swapchainPass, target.OutputTexture()) ``` - `FXAAOptions` tunes `SubpixelQuality` (default `0.75`, set `DisableSubpixel: true` for edge-only smoothing), `EdgeThreshold` (default `0.166`), and `EdgeThresholdMin` (default `0.0833`); non-finite or out-of-range fields are sanitized via `Sanitize()`. - **One set of options per submission**: the options are one uniform block, and buffer writes are applied before the submission's commands, so every draw one `FXAAPass` records into a frame uses the options of its last draw. To filter several views with different options in one frame, create one `FXAAPass` per option set. - `ApplyFXAA(src, opts)` runs the matching pure-Go CPU FXAA 3.11 reference on an `*image.RGBA`, leaving flat interiors below the contrast threshold untouched while smoothing diagonal edges. - If a `Retained` `MSAATarget` or `FXAAPass` survives a device loss, call `SetDevice(dev)` in `OnReady` / `OnDeviceRestored` so subsequent `Resize` or uniform/bind-group updates target the restored device. - **Color space**: FXAA's thresholds are tuned for perceptual, gamma-encoded luma, and `ApplyFXAA` works on the stored bytes. Feed the pass a non-sRGB source holding gamma-encoded (for example tone-mapped LDR) color, and draw into a target of the same kind. An sRGB source is sampled as linear values, so edge detection no longer matches `ApplyFXAA`, and a gamma-encoded source drawn into an sRGB target is encoded twice. `TargetFormat` defaults to `dev.SurfaceFormat()`, which is sRGB on some platforms, so set it explicitly. - **Reference renders**: the software-renderer tests compare the scene with `aa_baseline.png`, `aa_msaa4x.png`, and `aa_fxaa.png` under `render3d/testdata/golden/` (`UPDATE_GOLDEN=1` rewrites them) and check `FXAAPass` against `ApplyFXAA`. On both the full and `NoGPUCompute` profiles, the tests check the MSAA output against the software renderer's reference render and the `FXAAPass` output against `ApplyFXAA`. ## Directional light shadows (`DirectionalShadowMap`, `DirectionalShadowConfig`) `DirectionalShadowMap` manages an offscreen `FormatDepth32Float` shadow map render target, a depth-only caster pipeline (`ShadowDepthWGSL`) with a dynamic-offset caster transform buffer, a 96-byte `ShadowUniforms` buffer, and both nearest (hard) and linear (PCF) comparison samplers on an NSGo `gpu.Device`. `ShadowWGSL` declares the matching bindings at `ShadowGroup` (group 3, after `CameraGroup`, `LightGroup` and `PBRDrawGroup`) together with a portable `sample_directional_shadow(world_pos, world_normal)` helper. `NewLitPBRShadowPipeline` (or `LitPBRPipelineOptions.ShadowLayout`) builds the lit PBR pipeline with the shadow (`LitPBRShadowWGSL`): it shades a `LightRig` exactly like `LitPBRWGSL` and multiplies the rig's first directional light, `Directional[0]`, by the shadow, leaving the other lights, ambient and emission unshadowed. Group 3 is also where fog, IBL and skinning go, so a lit PBR pipeline takes one of them. ```go sm, err := render3d.NewDirectionalShadowMap(cx, dev, render3d.ShadowMapOptions{ Resolution: 1024, PCFKernel: render3d.ShadowFilterPCF3x3, // or ShadowFilterHard DepthBias: 2, DepthBiasSlopeScale: 2.0, CullMode: gpu.CullBack, Retained: true, // survives GPU device loss automatically }) litPipe, err := render3d.NewLitPBRShadowPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBuf.Layout(), sm.Layout(), gpu.FormatDepth24Plus) // Each frame in OnFrame(frame *gpu.Frame): dev := frame.Device() cfg := render3d.DefaultDirectionalShadowConfig() cfg.Direction = rig.Directional[0].Direction // the light the shadow attenuates cfg.Strength = 1 if !preset.Shadows { // quality.Preset from the quality package cfg.Strength = 0 // the shader then skips the shadow map } _, err = sm.UpdateBounds(dev, cfg, sceneBounds) // fits the orthographic frustum, texel-snapped // 1. Depth-only shadow pass (nil while the device is lost or after Close): if preset.Shadows { if shadowPass := sm.BeginShadowPass(dev, frame); shadowPass != nil { sm.DrawCaster(shadowPass, pillarMesh, pillarModel) sm.DrawCaster(shadowPass, crateMesh, crateModel) shadowPass.End() } } // 2. Main lit pass: mainPass := frame.BeginRenderPass(gpu.RenderPassDesc{}) mainPass.SetPipeline(litPipe) mainPass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) mainPass.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) mainPass.SetBindGroup(render3d.ShadowGroup, sm.BindGroup()) mainPass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) floorMesh.Draw(mainPass) mainPass.End() ``` - **Framing and texel snapping**: `DirectionalShadowConfig.LightViewProj()` builds an orthographic frustum `OrthoSize` wide and `DepthRange` deep, centred on `Target` (which sits at depth 0.5). `FitBounds(lightDir, sceneBounds)` encloses an `AABB`, extending toward the light by `CasterPadding`. With `TexelSnap: true` the shadow map's texel grid stays fixed in world space: the frustum is sized from the bounds' bounding sphere, rounded up to a coarse step, so the texel size does not change as the bounds move or the light turns, and the light-space center snaps to whole texels, so moving the framing (for example `UpdateBounds` following the camera) shifts static shadows by whole texels and their edges do not shimmer. Without `TexelSnap`, `FitBounds` hugs the bounds' light-space extent for the most texels per world unit, at the cost of shimmering when the bounds move. - **Hard 1-tap vs 3x3 PCF filtering**: `ShadowFilterHard` uses a nearest comparison sampler with a single `textureSampleCompareLevel` tap; `ShadowFilterPCF3x3` averages 9 comparison taps with a linear comparison sampler (combining hardware 2x2 PCF per tap with a 3x3 neighborhood) for soft penumbras. Switching `PCFKernel` via `WriteUniforms`, `Update`, or `UpdateBounds` swaps `BindGroup()` dynamically without allocating or recreating GPU resources. - **Acne control and portability**: `DepthBias` (slope-scaled in the shader by `1 + 2*(1 - NdotL)`), world-space `NormalBias`, and hardware rasterizer bias (`ShadowMapOptions.DepthBias` / `DepthBiasSlopeScale`) suppress shadow acne across flat and grazing surfaces. Custom shaders can prepend `ShadowWGSL` (or `ShadowWGSLForGroup(n)` when group 3 holds something else) and call `sample_directional_shadow(world_pos, world_normal)`; `LightWGSL`'s `shade_pbr_shadowed` takes that visibility for directional light 0. No compute shaders or storage buffers are used, so directional shadows run on every NSGo target including WebGL 2 and OpenGL ES 3.0. - **Quality presets**: to honour `quality.Preset.Shadows`, skip the shadow pass and set `Strength` to 0 when it is off, as in the example; with `Strength` 0 the shader returns full visibility without sampling the map. - **Zero-allocation uniforms and CPU reference**: `AppendShadowUniforms` and `ShadowUniforms.Encode` pack the 96-byte uniform block with zero heap allocations; a NaN or infinite matrix or `Strength` disables the shadow, non-finite biases become 0 and an unknown `PCFKernel` is treated as `ShadowFilterHard`, so uniforms built by hand cannot put NaN on screen. `EvaluateDirectionalShadow` is the matching pure-Go CPU reference over a `ShadowDepthGrid` (decoded from GPU depth readback via `ShadowDepthGridFromBytes`), and `ShadePointShadowed` is the CPU reference of the shadowed lighting. `render3d`'s tests check every open floor pixel of hard and 3x3 PCF renders, penumbras included, against these references, check where the shadow falls by projecting a caster along the light, and compare the renders with golden PNGs (`render3d/testdata/golden/shadow_directional_hard.png` and `shadow_directional_pcf.png`) on both `gpu.View` profiles (`full` and `nsgotest.NoGPUCompute`), across `Retained` device-loss restoration, and through scope disposal. ## Render-to-texture cameras and multiple viewports (`RenderTexture`, `ViewportRenderer`) `RenderTexture` allocates a scope-owned offscreen `gpu.RenderTarget` (color, optional depth/stencil, and optional 4x MSAA with automatic resolve) whose sampleable color output is exposed directly as a `*GPUTexture` via `RenderTexture.GPUTexture()`. Pass that handle to `BindTexture` (or any material texture slot) so mirrors, minimaps, security monitors, and portals render from a secondary camera and appear as textures on 3D geometry in the main pass: ```go rt, err := render3d.NewRenderTexture(cx, dev, render3d.RenderTextureDesc{ Label: "mirror", Width: 256, Height: 256, DepthFormat: gpu.FormatDepth24Plus, Retained: true, // survives device loss alongside retained samplers and bind groups }) mirrorBG, err := render3d.BindTexture(cx, dev, texLayout, rt.GPUTexture(), samp) ``` `ViewportRenderer` orchestrates frames with any mix of offscreen `RenderTexture` cameras and multiple viewports on the main surface (side-by-side split screen, stacked split screen, 4-player quad split, or overlapping picture-in-picture overlays): ```go renderer, err := render3d.NewViewportRenderer(cx, dev) // list renderer.CameraLayout() at CameraGroup halves := render3d.SplitScreenHorizontal(2) // left [0..0.5], right [0.5..1] views := []render3d.CameraView{ {Name: "mirror", Camera: mirrorCam, Target: rt, LayerMask: layerWorld, ClearColor: core.RGB(0x182030)}, {Name: "player1", Camera: p1Cam, Viewport: halves[0], LayerMask: layerWorld | layerMirror, ClearColor: core.RGB(0x0c1018)}, {Name: "player2", Camera: p2Cam, Viewport: halves[1], LayerMask: layerWorld | layerMirror}, } err = renderer.RenderFrame(frame, render3d.SurfaceDesc{HasDepth: true}, views, func(ctx render3d.ViewportContext) { visible = render3d.FilterLayeredItems(sceneItems, ctx.LayerMask, visible[:0]) plan := queue.Build(ctx.Uniform.ViewProj, ctx.Camera.Pos, visible) // ctx.Pass already has SetViewport, SetScissor, and CameraGroup bound for this view. drawPlan(ctx.Pass, plan) }) ``` - **Execution order**: `ViewportRenderer` always renders offscreen views (`Target != nil`) before main-surface views (`Target == nil`), ordering each phase stably by ascending `CameraView.Priority` (`OrderCameraViews`), so offscreen textures are up to date before any main-pass material samples them. - **Per-view camera uniforms & aspect ratio**: each active view gets its own retained uniform buffer slot at `CameraGroup` uploaded before pass recording so multiple views in one `gpu.Frame` or `gpu.Encoder` never clobber each other's matrices. Unless `CameraView.PreserveAspect` is set, a per-view copy of `Camera` adjusts `Projection.Aspect` to the resolved `PixelViewport` without mutating the caller's `*scene3d.Camera`. The slots are reused by every call, so call `RenderFrame` or `RenderEncoder` (which takes the device the encoder was begun on) at most once per submitted frame or command buffer, and use a separate `ViewportRenderer` for each call that shares one submission. - **Per-camera layer masks**: `CameraView.LayerMask` matches `scene3d.Node.Layer` bitmasks (zero defaults to `scene3d.LayerAll`). `LayerMatches`, `FilterLayeredItems`, and `FilterNodesByLayer` filter `LayeredDrawItem` and `*scene3d.Node` slices with zero steady-state allocations when reusing the destination buffer. In those functions, as in `scene3d.Decal.LayerMask`, a zero mask matches nothing, so pass `ViewportContext.LayerMask` (already the effective mask); set `CameraView.Disabled` for a camera that renders nothing. `FilterNodesByLayer` tests the layer only and keeps hidden or disabled nodes. - **Split-screen seams & overlays**: `SplitScreenHorizontal` (`SplitScreenSideBySide`), `SplitScreenVertical` (`SplitScreenStacked`), `SplitScreenQuad`, and `ViewportFromPixels` construct normalized `[0, 1]` `ViewportRect` values. `ViewportRect.Resolve` rounds both edges independently so adjacent split-screen viewports tile with zero pixel gaps or overlap, and `PixelViewport.Apply` sets both `SetViewport` and `SetScissor` so geometry never bleeds across seams. `PixelViewport` is in physical pixels; `PixelViewport.Bounds(pixelsPerPoint)` divides by the surface's content scale (its pixel width over the view's width in points) to give the logical-point `core.Bounds` that `DebugDraw.Flush`, `Gizmo.DrawGizmo` and `BillboardRenderer.Draw` take. Consecutive views on the same target share one GPU render pass, and only the view that opens a pass clears it, so a later view in that pass ignores its own `ClearColor` (draw a full-viewport quad for a distinct background); set `CameraView.ResetDepth` on an overlapping picture-in-picture view to preserve the underlying color while clearing depth. A view that returns to an offscreen target after views on another target (for example two halves of one atlas with a different target between them by `Priority`) loads that target's color and depth instead of clearing them, so the earlier views' output is kept. - **Resize & device loss**: `RenderTexture.Resize` is a no-op when dimensions match and swaps atomically on change, incrementing `Generation()` so callers know when to rebind `BindTexture` bind groups. With `Retained: true`, `RenderTexture` and `ViewportRenderer` restore automatically after GPU device loss and are released with their owning `core.Scope` or `Close()`. ## 3D debug draw and transform gizmos `DebugDraw` projects 3D wireframes with near-plane clipping directly into an NSGo `*core.Drawing` overlay: ```go var dbg render3d.DebugDraw dbg.Grid(math3d.Vec3Zero(), 10, 20, core.RGBA(120, 130, 150, 0.4)) dbg.AABB(enemyBounds, core.RGB(255, 80, 80)) dbg.Sphere(alertCenter, 4, core.RGB(255, 200, 60), 24) dbg.Axes(selectedPos, 1.5) dbg.Flush(d, cam.ViewProj(), viewportBounds) dbg.Clear() ``` For level editors and inspectors, `Gizmo` handles translate, rotate, and scale axes (`GizmoTranslate`, `GizmoRotate`, `GizmoScale`): ```go var gizmo render3d.Gizmo axis, _ := gizmo.PickAxis(ray, objPos, gizmoScale, render3d.GizmoTranslate) if axis != render3d.AxisNone { delta := gizmo.DragTranslate(objPos, axis, startRay, currentRay, 0.25) // 0.25m snap objPos = objPos.Add(delta) } gizmo.DrawGizmo(d, cam.ViewProj(), viewportBounds, objPos, gizmoScale, render3d.GizmoTranslate, axis) ``` Debug lines and gizmos clip at the near plane of a `[0, 1]` depth projection, which `math3d.Perspective` and `math3d.Ortho` produce. For an OpenGL-style `[-1, 1]` projection set `DebugDraw.DepthNO` and `Gizmo.DepthNO`, or call `ProjectSegmentNO`, so the near half of its depth range is not hidden. Each planar translate handle is drawn as the square that `PickAxis` tests. `DrawGizmo` allocates nothing; to read the segments yourself without allocating, reuse a slice with `gizmo.AppendSegments(buf[:0], objPos, gizmoScale, mode)`. ## Billboards and ribbon trails A `Billboard` is a quad that turns toward the camera, and a `Trail` is a ribbon through a moving object's recent positions that twists about its centerline to face the viewer. Both take a `CameraBasis`, the camera's position and unit axes, built from matrices or filled from a `scene3d.Camera`: ```go basis, _ := render3d.NewCameraBasis(cam.ViewMatrix(), cam.ProjMatrix()) // or: render3d.CameraBasis{Pos: cam.Pos, Right: cam.Right(), Up: cam.Up(), Forward: cam.Forward(), Orthographic: cam.Projection.Kind == scene3d.ProjectionOrthographic} ``` `Billboard.Mode` picks how the quad turns: | Mode | Faces | Use for | | --- | --- | --- | | `BillboardViewPlane` (default) | the view plane, along the camera's right and up | particles, sprites, impostors | | `BillboardViewPoint` | the camera's position, rolled by the camera's up | large quads near the screen edge | | `BillboardAxial` | the camera, rotating only about `Axis` (+Y when zero) | trees, grass, flames, beams | The view-plane and view-point modes face the camera at every angle, including looking straight up and down; an axial quad faces it as far as its axis allows and turns edge-on when the camera looks along the axis. `Pivot` places the quad relative to `Center` (`{Y: -0.5}` stands it on its bottom edge) and `Rotation` rolls it counter-clockwise on screen. ```go smoke := render3d.Billboard{Center: pos, Width: 1, Height: 1, Rotation: spin, Color: core.RGBA(200, 200, 200, 0.6)} tree := render3d.Billboard{Center: base, Width: 2, Height: 4, Pivot: math3d.Vec2{Y: -0.5}, Mode: render3d.BillboardAxial, Texture: treeImage} quad, ok := smoke.Quad(basis) // corners BL, BR, TR, TL, counter-clockwise toward the camera item := quad.DrawItem(render3d.DrawItem{ID: 7, MeshID: unitQuad}) // Transform maps the unit quad; Blend defaults to BlendAlphaBlend ``` Until GPU submission lands, `BillboardRenderer` fills billboards into a `*core.Drawing` back to front, clipping them against the near plane. Textured quads are mapped with an affine transform, which is exact under an orthographic camera and close for quads that are small on screen; a textured quad that crosses the near plane is skipped. ```go var billboards render3d.BillboardRenderer // reuse across frames billboards.Draw(d, []render3d.Billboard{smoke, tree}, basis, cam.ViewProj(), viewportBounds) ``` `Trail` mirrors the point-recording, lifetime, width and color options of `particles.Trail` in world units and reuses its `particles.Curve` and `particles.ColorCurve` for width and color from head (`u = 0`) to tail (`u = 1`). It has no `Texture` and no `Attach`, `Detach` or `Follow`: call `AddPoint` with the object's position each frame. Each point's edge runs along `tangent × toCamera`, and a trail heading straight at the camera keeps its previous edge direction instead of collapsing: ```go sword := render3d.NewTrail(render3d.TrailConfig{ Width: 0.3, Lifetime: 250 * time.Millisecond, WidthCurve: particles.Curve{{T: 0, Value: 1}, {T: 1, Value: 0}}, ColorGradient: particles.ColorCurve{{T: 0, Color: core.RGB(0xffe080)}, {T: 1, Color: core.RGBA(255, 80, 0, 0)}}, }) // In Update: sword.AddPoint(bladeTip) sword.Update(dt) // In Draw, or hand Build's triangle strip (two vertices per point, tail to head) to a GPU: verts := sword.Build(basis) sword.Draw(d, basis, cam.ViewProj(), viewportBounds) ``` `Build` reuses its storage and does not allocate; `Bounds` and `DrawItem` give the transparent queue a camera-independent box for sorting. ## Render stats, profiler, and GPU budgets `plan.Stats` (`RenderStats`) reports exact culled/visible counts, draw calls, instanced batches, triangles, vertices, material/pipeline switches, and GPU memory. Track rolling frame timing with `NewFrameProfiler(120)` (`Record`, `AverageFrameTime`, `P95FrameTime`, `FPS`, `PeakDrawCalls`, `PeakTriangles`) and assert budgets in dev builds or tests with `CheckBudget`: | Preset | MaxDrawCalls | MaxTriangles | MaxVertices | MaxMaterialSwitches | MaxPipelineSwitches | MaxTextureBytes | MaxBufferBytes | | --- | --- | --- | --- | --- | --- | --- | --- | | `MobileBudget()` | 150 | 150,000 | 300,000 | 60 | 32 | 128 MiB | 64 MiB | | `DesktopBudget()` | 2,000 | 2,000,000 | 4,000,000 | 500 | 200 | 1 GiB | 512 MiB | ```go if violations := render3d.CheckBudget(plan.Stats, render3d.MobileBudget()); len(violations) > 0 { for _, v := range violations { log.Println("budget exceeded:", v) } } ``` ## Hot-reloading shaders and materials Run the game with [`nsgo game dev`](https://game.nsgo.dev/docs/cli/#dev) and attach `hotreload.ShaderReloader` and `hotreload.MaterialReloader` (from `github.com/nsgo-dev/game/pkg/tooling/hotreload`) to `hotreload.NewDevWatcher` so edited WGSL (`.wgsl`), Kage (`.kage`), and material YAML (`.material.yaml`, `.mat.yaml`, `.material.yml`, `.mat.yml`) files reload within a second without restarting: ```go w := hotreload.NewDevWatcher(cx) // nil outside game dev and in release builds dir := hotreload.DevAssetsDir() shaders := hotreload.NewShaderReloader(cx, dev, hotreload.WithShaderDir(dir), hotreload.WithOnShaderError(func(re hotreload.ReloadError) { log.Printf("shader error (%s): %v", re.Name, re) }), ) materials := hotreload.NewMaterialReloader(cx, shaders, hotreload.WithMaterialDir(dir), hotreload.WithOnMaterialError(func(re hotreload.ReloadError) { log.Printf("material error (%s): %v", re.Name, re) }), ) w.WatchMaterials(materials) // watches both material YAML and referenced .wgsl/.kage shaders _, _, err := materials.Register("crystal", "materials/crystal.material.yaml", buildPipeline) ``` Every reload compiles a candidate `*gpu.ShaderModule` and builds a candidate `*gpu.Pipeline` before swapping: - **Safe fallback on errors**: if a shader edit fails to compile, misses an entry point, or fails pipeline creation — or if a material YAML has invalid syntax, an unknown field, or an out-of-range value — the previous working shader, material, and `*gpu.Pipeline` remain active without crashing. The failure is recorded as a `ReloadError` (unwrapping to `*loaderr.Error` with file, line, and column when reported) accessible via `LastError` and `Errors`, and clears automatically once a subsequent save compiles cleanly. When debouncing is enabled, `Watcher` also gives 0-byte reads extra time to settle so editors that save by truncating before writing do not emit a spurious empty-source error, while a file that genuinely stays empty still reports it. - **Shader-to-material dependencies**: editing a shader referenced by one or more materials automatically rebuilds and swaps every dependent material's pipeline, closing replaced pipelines cleanly. - **Text material format (`MaterialDef`)**: a versioned YAML document (`version: 1`, refusing unknown fields and round-tripping deterministically via `ParseMaterial` / `EncodeMaterial`) declaring `shader` (or split `vertexShader` / `fragmentShader`), entry points (`vertexEntry`, `fragmentEntry`), GPU render state (`blend`, `cull`, `frontFace`, `depthWrite`, `depthCompare`, applied via `ApplyToPipelineDesc`), and typed uniform parameters (`scalars`, `vec2`, `vec3`, `vec4`, `colors`, `textures`). For shared 2D/PBR `resource.Material` files (`type: material`), use `w.WatchResources` ([resource](https://game.nsgo.dev/docs/resources/#reloading-on-edit)). - **Direct shader watching**: for standalone pipelines without material YAML, use `ShaderReloader.RegisterPipeline` with `w.WatchShaders(shaders)`, or `w.WatchShader(relPath, onReload)` for a single `.wgsl` or `.kage` file. - **Release builds**: under `-tags release`, `NewDevWatcher` returns nil and `WatchShader`, `WatchShaders`, and `WatchMaterials` compile to no-ops while `ShaderReloader` and `MaterialReloader` continue serving initial loads. ## Dynamic resolution scaling (`DynamicResolutionScaler`, `DynamicResolutionTarget`) `DynamicResolutionScaler` adapts a linear 3D render scale in `[MinScale, MaxScale]` (default `[0.5, 1.0]`) to hold `TargetFrameTime` (default ~16.67 ms for 60 FPS), and `DynamicResolutionTarget` renders the 3D scene into a scaled sub-viewport of an offscreen `gpu.RenderTarget` and upscales it onto the native surface while keeping 2D HUD overlays at full native resolution: ```go target, err := render3d.NewDynamicResolutionTarget(cx, dev, render3d.DynamicResolutionTargetOptions{ TimingLabel: "world-3d", Config: render3d.DynamicResolutionConfig{ TargetFrameTime: time.Second / 60, MinScale: 0.5, MaxScale: 1.0, Filter: render3d.DynamicResolutionBilinear, // or DynamicResolutionNearest / DynamicResolutionSharpen }, }) // In gpu.ViewProps.OnFrame (with scene.Overlay3D mounted over gpu.View for a native-res HUD): w, h := frame.Size() pass3d, err := target.Begin3D(frame, w, h, core.RGB(0x10141c)) pass3d.SetPipeline(scenePipe) pass3d.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) mesh.Draw(pass3d) pass3d.End() _ = target.Upscale(frame, nil, w, h) // blits scaled 3D sub-viewport to native surface frame.Submit() target.RecordPassTimings(frame.PassTimings()) // or target.RecordFrameTime(gpuDuration) ``` - **Proportional fill-rate controller with hysteresis**: because fragment work scales with `scale²`, `DynamicResolutionScaler.RecordFrameTime` smooths GPU timings with an EMA (`SmoothingAlpha`), ignores loading/resume spikes above `HitchLimit`, holds steady inside `±Deadband`, steps down promptly on overload (`CooldownDown`, `StepDown`), and recovers smoothly under sustained headroom (`CooldownUp`, `StepUp`). Use `SetFixedScale`, `ClearFixedScale`, `SetEnabled`, and `SetScaleBounds` (for example capping `MaxScale` to `quality.Preset.ResolutionScale`) to override or bound adaptation. - **Zero-reallocation sub-viewport scaling**: `DynamicResolutionTarget` allocates its offscreen color+depth `gpu.RenderTarget` at native capacity and sets `SetViewport` and `SetScissor` to `[0, 0, scaledW, scaledH]` on each `Begin3D` call, so scale changes never churn GPU textures. `Upscale` clamps UVs to half-texel inset bounds of the active sub-rectangle so unused padding texels never bleed into the edges. - **Native-resolution HUD**: mount [`scene.Overlay3D`](https://game.nsgo.dev/docs/scene/#2d-layers-over-a-3d-view-overlay3d) over `gpu.View` so 2D HUD layers draw in a crisp 1:1 native `core.Canvas`, record a follow-up `gpu.LoadLoad` native HUD pass after `Upscale`, or call `UpscaleIntoPass` inside a single native color pass and draw GPU HUD elements right after it. - **Upscale filters**: switch between `DynamicResolutionBilinear`, `DynamicResolutionNearest`, and `DynamicResolutionSharpen` (a 5-tap contrast-adaptive sharpening pass clamped to the local neighborhood min/max) at runtime via `SetFilter` and `SetSharpness` without reallocating pipelines or textures. ## Baked lightmaps (`LightmapMesh`, `LightmapRenderer`) `LightmapMesh` and `GPULightmapMesh` add a dedicated secondary UV channel (`UV1`, matching glTF `TEXCOORD_1`) alongside primary material UVs (`UV0`, `TEXCOORD_0`) in a 40-byte interleaved vertex layout (`LightmapVertexLayout`, `LightmapVertex`). When `UV1` is empty, `UploadLightmapMesh` falls back cleanly to `UV0` and reports `GPULightmapMesh.UsedUV0Fallback()`. In `game/gltf`, `Document.MaterialLightmap` extracts baked lightmap bindings from `MOZ_lightmap`, `EXT_lightmap`, or `extras.lightmap` (including `KHR_texture_transform` / atlas `uvScale` and `uvOffset`), and `Document.LightmapTexCoords` / `PrimitiveLightmapUVs` resolve `TEXCOORD_1` with `TEXCOORD_0` fallback. ```go lmRef, err := doc.MaterialLightmap(prim.Material) lmUVs, _, err := doc.LightmapTexCoords(prim, lmRef) lmMesh, err := render3d.UploadLightmapMesh(cx, dev, render3d.LightmapMeshFromAttributes( prim.Positions, prim.Normals, prim.TexCoords0, lmUVs, prim.Indices, ), render3d.MeshUpload{Label: "room", Retained: true}) renderer, err := render3d.NewLightmapRenderer(cx, dev, camBuf.Layout(), render3d.LightmapRendererOptions{ DepthFormat: gpu.FormatDepth24Plus, Retained: true, }) // Each frame inside OnFrame: renderer.BeginFrame() camBuf.WriteCamera(cam) mat := render3d.DefaultLightmapMaterial() mat.BaseColorTexture = albedoTex mat.Lightmap = lightmapTex // RGBM / RGBD: upload with TextureUpload{SRGB: false} mat.Encoding, err = render3d.ParseLightmapEncoding(lmRef.Encoding) // "" is LightmapLinear mat.Intensity = lmRef.Intensity mat.RGBMMaxRange = lmRef.RGBMMaxRange // 0 uses DefaultRGBMMaxRange mat.SetUVTransform(render3d.UVTransform{Scale: lmRef.UVScale, Offset: lmRef.UVOffset}) mat.DirectLight = &rig.Directional[0] // optional: a LightRig light, Direction is the travel direction _ = renderer.Draw(pass, camBuf, lmMesh, worldMat, mat) ``` - **HDR and LDR encodings**: supports linear 8-bit or float16 HDR textures (`LightmapLinear`, with `UploadLightmapRGBA16F` for float16 upload), sRGB LDR textures (`LightmapSRGB`, avoiding double-decode when uploaded with `TextureUpload{SRGB: true}`), and 8-bit packed HDR formats (`LightmapRGBM` via `EncodeRGBM` / `EncodeRGBMImage` and `LightmapRGBD` via `EncodeRGBD` / `EncodeRGBDImage`) for full WebGL 2 and mobile compatibility. - **Shared lightmap atlases**: set `LightmapMaterial.UVScale` and `UVOffset` (or `SetUVTransform`) so multiple meshes sample distinct sub-rectangles of one baked lightmap atlas within a single render pass using dynamic uniform offsets. - **Fallback and dynamic light blend**: leave `LightmapMaterial.Lightmap` nil to shade with `AmbientFallback`, and optionally set `LightmapMaterial.DirectLight` to a `*DirectionalLight` (the same type as a `LightRig`'s, with `Direction` the way the light travels) to add its Lambertian N·L term to the baked irradiance. Normals go through the normal matrix, so non-uniformly scaled level geometry is lit correctly. `Intensity` 0 means no baked light; `DefaultLightmapMaterial` sets 1. - **Output encoding**: the shader encodes its linear result to sRGB, as `LitPBRWGSL` and the material pipeline do, so lightmapped geometry and PBR-lit props drawn into the same pass match. For an sRGB color format (`LightmapRendererOptions.ColorFormat` or the surface format) the encode is left to the hardware. - **Atlas transform**: `LightmapRef.UVScale` / `UVOffset` are the authoritative atlas transform; `LightmapRef.Texture` carries no scale or offset, so do not also apply it with `TransformTexCoords`. See [Baked lightmaps](https://game.nsgo.dev/docs/3d-models-blender/#baked-lightmaps) for where the values come from. - **Texture streaming**: `BeginFrame` drops cached bind groups of lightmap and albedo textures that have been closed, so streaming levels or hot-reloading lightmaps does not grow the cache. - **Scope**: `LightmapRenderer` is a standalone Lambertian path, albedo times (baked irradiance plus one optional `DirectionalLight`). It has no metallic-roughness, normal, occlusion, or emissive maps and does not read a `LightRig`. ### PBR lightmap path (`GPUPBRLightmap`, `NewPBRLightmapPipeline`, `UploadGLTFPBRLightmaps`) To keep full glTF 2.0 metallic-roughness PBR materials (base color, metallic-roughness, normal, occlusion, emissive, alpha modes, double-sided faces) and dynamic `LightRig` lighting (directional, point, and spot lights) on baked geometry, use `NewPBRLightmapPipeline` together with `GPUMaterial` and `GPUPBRLightmap`: ```go matSet, err := render3d.UploadGLTFMaterials(cx, dev, defaults, doc, render3d.GLTFMaterialUpload{Retained: true}) lmSet, err := render3d.UploadGLTFPBRLightmaps(cx, dev, doc, render3d.GLTFPBRLightmapUpload{Retained: true}) lmMeshData, err := render3d.LightmapMeshFromGLTF(doc, prim) lmMesh, err := render3d.UploadLightmapMesh(cx, dev, lmMeshData, render3d.MeshUpload{Retained: true}) pipe, err := render3d.NewPBRLightmapPipeline( cx, dev, camBuf.Layout(), lightBuf.Layout(), defaults.Layout(), lmSet.Layout(), render3d.PBRLightmapPipelineOptions{DepthFormat: gpu.FormatDepth24Plus, Retained: true}, ) // Inside OnFrame: pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) lightBuf.Bind(pass) pass.SetBindGroup(render3d.PBRLightmapMaterialGroup, matSet.Material(prim.Material).BindGroup()) lmSet.Lightmap(prim.Material).Bind(pass) // or a per-node instance from lmSet.NewInstance(...) lmMesh.Draw(pass) ``` - **Bind groups & vertex layout**: reuses `LightmapVertexLayout` (40 bytes: `Position`, `Normal`, `UV0`, `UV1`) with `CameraGroup` (0), `LightGroup` (1, `GPULightBuffer`), `PBRLightmapMaterialGroup` (2, `GPUMaterial` from `NewGPUMaterial` or `UploadGLTFMaterials`), and `PBRLightmapGroup` (3, `GPUPBRLightmap` carrying model/normal matrices, atlas `UVTransform`, `LightmapEncoding`, `Intensity`, `RGBMMaxRange`, and the lightmap texture/sampler). - **Shading equation**: the decoded lightmap replaces the ambient / indirect diffuse term as `(1 - metallic) * baseColor * decodedLightmap * intensity * occlusion` (so `LightRig.Ambient` is not double-counted on baked geometry), while `LightRig`'s directional, point, and spot lights supply the Cook-Torrance GGX direct term plus emissive, encoded with `linear_to_srgb` (or unclamped linear when `LinearOutput` is set or `ColorFormat` is sRGB). For a dielectric (`metallic = 0`), rough (`roughness = 1`), untextured material with no dynamic lights it matches `LightmapRenderer`; adding a `LightRig` light adds the exact direct term of `LitPBRWGSL`. `EvaluatePBRLightmap` is the CPU reference. - **glTF integration**: `UploadGLTFPBRLightmaps` reads `MOZ_lightmap`, `EXT_lightmap`, and `extras.lightmap` (including `KHR_texture_transform`, `scaleOffset`, `uvScale`, `uvOffset`, `intensity`, `encoding`, `rgbmMaxRange`), deduplicates lightmap textures/samplers, and returns a `GLTFPBRLightmapSet` matching `GLTFMaterialSet` (use `NewInstance` for multiple nodes sharing one material at different transforms). ### When to use `LightmapRenderer` vs the PBR lightmap path - **Use `LightmapRenderer`** for lightweight static architecture, low-end/mobile fill-rate budgets, or diffuse-only baked geometry that only needs an albedo texture (`UV0`), a baked lightmap (`UV1`), and at most one dynamic Lambertian directional sun light — it binds only 2 textures per draw and handles per-frame dynamic uniform ring offsets automatically via `BeginFrame` / `Draw`. - **Use the PBR lightmap path (`NewPBRLightmapPipeline` + `GPUPBRLightmap`)** whenever baked geometry also needs metallic-roughness maps, tangent-space normal maps, ambient occlusion maps, emissive maps, alpha masking/blending, double-sided surfaces, HDR `LinearOutput`, or dynamic directional/point/spot specular and diffuse lighting from a `LightRig` in a single pipeline. ## Point and spot light shadows (`SpotShadowMap`, `PointShadowMap`) `SpotShadowMap` and `PointShadowMap` shadow the first spot light (`rig.Spot[0]`) and the first point light (`rig.Point[0]`) of a `LightRig`. They render depth-only `FormatDepth32Float` maps from the rig's own `SpotLight` and `PointLight`, and the lit PBR pipelines multiply that light's contribution by the shadow, so a shadowed light is shaded exactly like the same light in `LitPBRWGSL` (Cook-Torrance GGX, energy-conserving Lambert, `PointLightAttenuation`, glTF cone falloff). Everything runs on every NSGo backend, the WebGL 2 / OpenGL ES 3.0 profile (`nsgotest.NoGPUCompute`) and the software renderer included: ```go spot, err := render3d.NewSpotShadowMap(cx, dev, render3d.DefaultSpotShadowConfig()) litPipe, err := render3d.NewLitPBRSpotShadowPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), spot.Layout(), gpu.FormatDepth24Plus) // Each frame in OnFrame: _ = spot.Update(dev, rig.Spot[0]) // the light the shadow attenuates if sp := spot.BeginShadowPass(dev, frame); sp != nil { spot.DrawCaster(sp, pillarMesh, pillarModel) // false when the pass is full sp.End() } mp := frame.BeginRenderPass(gpu.RenderPassDesc{ /* color + depth */ }) mp.SetPipeline(litPipe) mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) mp.SetBindGroup(render3d.LocalShadowGroup, spot.BindGroup()) for i, mesh := range meshes { mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup()) // per-draw model matrix and material mesh.Draw(mp) } mp.End() ``` For a point light, update from `rig.Point[0]`, draw with `NewLitPBRPointShadowPipeline`, and render the cube faces: ```go _ = point.Update(dev, rig.Point[0]) for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { if fp := point.BeginFacePass(dev, frame, face); fp != nil { point.DrawCaster(fp, blockerMesh, blockerModel) fp.End() } } ``` - **Spot projection**: a square `[0, 1]`-depth perspective from the light's `Position` along its `Direction` with a field of view of `2 * OuterConeAngle` (`SpotShadowViewProj`). The far plane is the light's `Range`, or `SpotShadowConfig.Far` (default `DefaultLocalShadowFar`, 50) for a light with `Range` 0; `Near` defaults to 0.1. A cone wider than `MaxSpotShadowConeAngle` (just under 90°) cannot be projected and `Update` returns `ErrInvalidLocalShadow`. - **Point atlas**: the six 90° cube faces are packed into one `(3 * FaceResolution) × (2 * FaceResolution)` 2D depth atlas, because NSGo cannot attach a single face of a depth cube map. `sample_point_shadow` picks the dominant face, computes the perspective depth `(far/(far-near)) * (1 - near/axisDist)` directly, and clamps every tap inside its tile so 3×3 PCF never bleeds into a neighboring face. `BeginFacePass` with face 0 clears the whole atlas and faces 1..5 keep what is there, so a partial refresh either includes face 0 with every other face or skips it. - **Casters**: `DrawCaster` writes each caster's `(lightViewProj, model)` into its own 256-byte dynamic-offset slot, so many casters draw in one pass. `MaxCasters` (default 256, at most `MaxLocalShadowCasters`) applies per spot pass and per point face; each face has its own slots, so faces can be refreshed in any order. `DrawCaster` returns false when the pass or face is full or `Update` has not run yet. - **Filtering and bias**: `LocalShadowFilterHard` (one nearest comparison tap) or `LocalShadowFilterPCF3x3` (nine linear taps), with a constant `DepthBias` and a world-space `NormalBias`. - **Bind group 3**: `LocalShadowGroup` is `ShadowGroup` (3), the group the directional shadow, fog, IBL and skinning also use, so a lit PBR pipeline takes one of them (`LitPBRPipelineOptions.SpotShadowLayout` or `PointShadowLayout`). A custom shader that needs both, or group 3 for something else, places the bindings with `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` and scales its lights with `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` from `LightWGSL`. - **Device loss and CPU references**: with `Retained: true` the depth target, sampler, buffers, bind groups and depth pipeline come back after a device loss. `EvaluateSpotShadow`, `EvaluatePointShadow` and `PointShadowSelectFace` mirror the WGSL, and `ShadePointVisibility` with a `LightVisibility` reproduces the lit pixel; the tests compare them with the GPU and with the golden renders `render3d/testdata/golden/local_shadow_spot.png` and `local_shadow_point.png` (`UPDATE_GOLDEN=1` rewrites them). ## Cascaded shadow maps (`CascadedShadowMap`, `CSMConfig`) `CascadedShadowMap` shadows the first directional light of a `LightRig` (`rig.Directional[0]`) with up to four cascades (`MaxCascades`), so shadows stay sharp near the camera and still reach the horizon. It is the large-scene alternative to `DirectionalShadowMap`: the lit PBR pipelines shade the rig exactly like `LitPBRWGSL` and multiply that one light by the cascaded shadow, leaving the other lights, ambient and emission unshadowed. Everything runs on every NSGo backend, the WebGL 2 / OpenGL ES 3.0 profile (`nsgotest.NoGPUCompute`) and the software renderer included: ```go cfg := render3d.DefaultCSMConfig() // 4 cascades, 1024 texels each, 3x3 PCF, texel snapping cfg.MaxShadowDistance = 80 cfg.Retained = true csm, err := render3d.NewCascadedShadowMap(cx, dev, cfg) litPipe, err := render3d.NewLitPBRCSMPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), csm.Layout(), gpu.FormatDepth24Plus) // Each frame in OnFrame(frame *gpu.Frame): shadowFrame := render3d.FitCascadesFromCamera(cam, rig.Directional[0].Direction, csm.Config()) // the light the cascades shadow _ = csm.Update(dev, shadowFrame) for i := range csm.CascadeCount() { if pass := csm.BeginCascadePass(frame, i); pass != nil { for j, mesh := range casterMeshes { csm.DrawCaster(pass, mesh, casterModels[j]) // false once MaxCasters distinct models are taken } pass.End() } } mp := frame.BeginRenderPass(gpu.RenderPassDesc{ /* color + depth */ }) mp.SetPipeline(litPipe) mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) mp.SetBindGroup(render3d.CSMGroup, csm.BindGroup()) for i, mesh := range meshes { mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup()) mesh.Draw(mp) } mp.End() ``` - **Splits (`ComputeCSMSplits`)**: `[near, min(far, MaxShadowDistance)]` is divided with the practical split scheme, blending logarithmic and uniform splits by `SplitLambda` (default 0.75). - **Fitting (`FitCascades`, `FitCascadesFromCamera`)**: each cascade's slice of the camera frustum is cut along the projection's own near and far planes, so perspective and orthographic cameras both work. `FitCascadesFromCamera` uses the near and far planes `Camera.ProjMatrix` uses; shadows start at view depth 0.1 when an orthographic camera's near plane is at or behind it. With `TexelSnap` (the default) each cascade is sized from a bounding sphere and snapped to whole texels, so shadow edges do not shimmer as the camera moves or turns. `CasterPadding` pulls each cascade's near plane toward the light so casters outside the view still cast into it. Fitting and `CSMFrame.EncodeUniforms` allocate nothing. - **One 2D depth atlas**: the cascades are tiles of one `FormatDepth32Float` texture (1x1 for one cascade, 2x1 for two, 2x2 for three or four), so no depth texture arrays are needed. `Update` refuses, with `ErrInvalidCSM`, a frame fitted with another cascade count, resolution or filter than the atlas, because its tiles, texel size and filter would not match the atlas and its sampler. The first `BeginCascadePass` after `Update`, whichever cascade it draws, clears the whole atlas; render every cascade after each `Update`, in any order. - **Casters**: `DrawCaster` writes each distinct model matrix into its own 256-byte dynamic-offset slot once per frame and reuses it in the other cascades, so `MaxCasters` (default 256) counts distinct models between two `Update` calls, not draws. When the slots run out it draws nothing and returns false. `DrawCasterGroup` draws with caller-owned transforms instead. - **Filtering and blending**: `ShadowFilterHard` (one nearest comparison tap) or `ShadowFilterPCF3x3` (nine linear taps clamped inside the cascade's tile), the same `ShadowFilter` the single directional shadow map uses. `CascadeBlendRange` cross-fades into the next cascade over that fraction of each cascade and fades the last one out toward `MaxShadowDistance`; `DebugCascades` tints surfaces by cascade (red, green, blue, yellow). - **Bind group 3**: `CSMGroup` is `ShadowGroup` (3), so a lit PBR pipeline takes the cascaded shadow map instead of the directional, spot or point shadow, fog, IBL or skinning (`LitPBRPipelineOptions.CSMLayout`). Custom shaders prepend `CameraWGSL` and `CSMWGSL` (or `CSMWGSLForGroup(n)` when group 3 holds something else) and pass `sample_csm_shadow(world_pos, world_normal)` to `shade_pbr_shadowed` from `LightWGSL`. - **Device loss and CPU references**: with `Retained: true` the atlas, sampler, buffers, bind groups and depth pipeline come back after a device loss. `EvaluateCSMShadow` mirrors the WGSL over an atlas read back with `ReadCSMDepthAtlas` / `ReadCSMDepthAtlasAsync`, and `ShadePointShadowed` with that visibility, times `CSMFrame.DebugTint`, reproduces the lit pixel; the tests compare them with the GPU on both profiles and with the golden render `render3d/testdata/golden/csm_large_scene.png` (`UPDATE_GOLDEN=1` rewrites it). ## 3D post-processing (`PostStack3D`, `BloomPass`, `SSAOPass`, `DepthOfFieldPass`) `PostStack3D` composes screen-space ambient occlusion (`SSAOPass`), depth-aware disc bokeh Depth of Field (`DepthOfFieldPass`), and HDR Bloom (`BloomPass`) over an offscreen 3D color+depth `gpu.RenderTarget` (`FormatRGBA16Float` + `FormatDepth32Float` by default) and writes the final image to the swapchain or a chosen destination texture: ```go stack, err := render3d.NewPostStack3D(cx, dev, render3d.PostStack3DOptions{ Width: uint32(w), Height: uint32(h), OutputFormat: dev.SurfaceFormat(), Retained: true, EnableSSAO: true, SSAO: render3d.SSAOConfigFromCamera(cam), EnableDoF: true, DoF: render3d.DepthOfFieldConfigFromCamera(cam, 5.0, 2.0, 5.0), EnableBloom: true, Bloom: render3d.DefaultBloomConfig(), }) // In OnFrame: pass := stack.BeginScenePass(frame, core.RGB(0x0c1018)) // ... draw 3D meshes into stack.SceneTarget() ... pass.End() _ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> Depth of Field -> Bloom -> swapchain frame.Submit() // When the view resizes (or the camera zooms), refresh the projection SSAO and DoF depend on: _ = stack.Resize(dev, uint32(w), uint32(h)) cam.SetViewport(float32(w), float32(h)) _ = stack.SetCamera(cam) ``` - **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). `SetSSAO`, `SetDepthOfField` and `SetBloom` toggle a stage; a zero config keeps its current settings, so `stack.SetSSAO(false, render3d.SSAOConfig{})` only turns SSAO off. Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `RenderPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`). - **Formats and destinations**: `ColorFormat` (scene and intermediate targets) is `FormatRGBA16Float` (default), `FormatRGBA8Unorm`, `FormatRGBA8UnormSRGB`, `FormatBGRA8Unorm` or `FormatBGRA8UnormSRGB`: four filterable channels, because Depth of Field stores its Circle of Confusion in alpha. A nil destination writes to the swapchain in `OutputFormat`; a destination texture must be in `ColorFormat` or `OutputFormat`, and the last stage draws with the pipeline built for that format. Every input and destination must have the pass or stack size, and the destination cannot also be an input; otherwise `Apply` returns `ErrInvalidPostProcess`. - **Camera projection**: `SSAOConfigFromCamera` captures `cam.ProjMatrix()` and `DepthOfFieldConfigFromCamera` reads the near and far planes and projection kind from that matrix, so the defaults `scene3d.Projection` fills in for zero fields (and an orthographic near plane at or behind the camera) match the depth buffer. Both are captured once; call `PostStack3D.SetCamera` (or `SetConfig` on a standalone pass) whenever the projection changes. With a zero `ProjMatrix`, SSAO falls back to a 60° perspective at the pass aspect ratio with the config's `Near` and `Far`. - **SSAO (`SSAOConfig`, `SSAOPass`)**: reconstructs view-space positions and edge-preserving normals from the 3D depth buffer, evaluates a deterministic 4–16-sample hemisphere kernel with stratified 4×4 tangent rotation, applies an optional depth-aware bilateral blur (`BlurRadius`, `DepthThreshold`), and multiplies ambient occlusion into the scene color (`AOTexture` exposes the AO map for inspection). - **Depth of Field (`DepthOfFieldConfig`, `DepthOfFieldPass`)**: linearizes perspective or orthographic `[0, 1]` depth to compute a signed Circle of Confusion around `FocusDistance` ± `FocusRange`, then gathers an 18-tap two-ring disc bokeh blur that prevents blurred background pixels from bleeding across sharp in-focus silhouettes. - **Bloom (`BloomConfig`, `BloomPass`)**: extracts bright LDR or HDR (`> 1.0`) pixels with a quadratic `Threshold` / `SoftKnee` curve, runs `BlurPasses` separable 9-tap Gaussian horizontal and vertical passes (optionally at half resolution via `HalfRes`), and composites the glow additively with `Intensity`. - **Portability, lifecycle, and reference renders**: every pass uses fragment-only portable WGSL with explicit `textureSampleLevel` and algebraic/precomputed weights (no compute shaders or `exp`/`log2` instructions), running on both full and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0) profiles, supporting `Resize(dev, w, h)` and `Retained` device-loss recovery. Golden reference renders (`render3d/testdata/golden/post3d_bloom.png`, `post3d_ssao.png`, `post3d_dof.png`, and `post3d_combined.png`) verify each pass and the combined stack; `UPDATE_GOLDEN=1` rewrites them. ## Clustered forward lighting (`ClusteredLightSystem`, `ClusterGrid`) A `LightRig` shades at most 16 point and 8 spot lights. For scenes with hundreds of local lights, `ClusteredLightSystem` takes the place of `GPULightBuffer` at `LightGroup`: it uploads the same `LightRig` (ambient, directional, and the rig's own point and spot lights) at binding 0, and bins any number of extra local lights (`ClusterLight`) into a 3D grid of screen tiles × logarithmic depth slices (default `16 × 9 × 24`, up to `512` visible lights and `64` per cluster). Each fragment then shades only the lights in its own cluster, with the same Cook-Torrance BRDF and glTF `KHR_lights_punctual` falloff as `shade_pbr`, so clustered and rig lights look identical. Because cluster assignment runs on the CPU, only fragment storage buffers (`Features.StorageBuffers` and `Limits.MaxStorageBufferBindingSize`) are required — compute shaders are not needed, so Apple Metal devices use the full clustered path. On targets without storage buffers (WebGL 2, OpenGL ES 3.0, Linux `GtkGLArea`, and headless tests using `nsgotest.NoGPUCompute`) it falls back to one uniform buffer holding the `FallbackMaxLights` (default `16`) most important visible lights: ```go sys, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus) // Convert scene lights once; a Range of 0 (unbounded) gets a derived cutoff range. local := make([]render3d.ClusterLight, 0, len(lamps)) for _, l := range lamps { cl, err := render3d.ClusterLightFromPoint(l) if err != nil { return err } local = append(local, cl) } // Each frame, before recording draws: camBuf.WriteCamera(cam) stats, err := sys.UpdateCamera(frame.Device(), cam, viewW, viewH, rig, local) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) sys.Bind(pass) pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup()) mesh.Draw(pass) ``` - **Lights**: `ClusterLight` is a point or spot record whose `Range` must be positive, because clustering needs a bounding sphere. `ClusterLightFromPoint` and `ClusterLightFromSpot` convert a `PointLight` or `SpotLight` and, for `Range == 0`, derive the distance at which `Intensity * max(Color) / d^2` falls to `ClusterRangeCutoff` (1/256). `Update` returns an error wrapping `ErrInvalidClusterLight` for a light that fails `Validate` (including `Range == 0`) or `ErrInvalidLight` for a malformed rig, instead of dropping it. `EvaluateLightAttenuation` reuses `PointLightAttenuation` and `SpotConeAttenuation`. - **Viewport size**: `viewW` and `viewH` must be the size of the area the pass renders, starting at its origin, because the shader finds a fragment's tile from `@builtin(position)`. Under a `DynamicResolutionTarget`, pass `ScaledSize()`, not the native size. - **Shaders**: `NewClusteredLitPBRPipeline` compiles `ClusteredLitWGSL` or `ClusteredFallbackWGSL` (whichever matches `sys.WGSL()`), the `LitPBRWGSL` module with `shade_pbr_clustered` in place of `shade_pbr`, writing sRGB. Custom shaders prepend `CameraWGSL` and `sys.BindingsWGSL()` (`ClusteredBindingsWGSL` or `ClusteredFallbackBindingsWGSL`, both of which include `LightWGSL`) and call `shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos)`, which has the same signature on both paths. - **CPU clustering (`ClusterGrid`)**: view-space cluster AABBs are cached by `(proj, near, far)` and reused across camera motion. `AssignLights` culls off-frustum lights, computes tight screen-tile and depth-slice bounds, tests sphere-vs-AABB (plus conservative cone-vs-AABB rejection for spot lights), and packs `Offsets` and `LightIndices` with zero steady-state allocations. Lights beyond `MaxLights`, and lights beyond `MaxLightsPerCluster` in one cell, are dropped in input order (`TruncatedLights`, `TruncatedClusters`), so put important lights first when a scene can exceed either cap. - **Fallback selection**: `SelectFallbackLights` drops lights whose bounding sphere is outside the view frustum, then ranks the rest by power, range and distance to the camera. In fallback mode `CulledLights` counts lights outside the frustum or without power, and `TruncatedLights` the visible lights the cap left out. - **Depth-slice lookup**: the shader finds a fragment's depth slice with a 6-step binary search over a uniform split-depth table rather than `log2` and `exp`, because NSGo v0.3.0's software GPU renderer evaluates those builtins to zero. - **CPU reference**: `ShadeClusteredPoint` is `ShadePoint` plus every clustered light, and `ShadeClusteredGridPoint` uses only the lights of the fragment's cluster, exactly as the GPU does. Tests compare GPU pixels against them on the full and `NoGPUCompute` profiles, including a 256-light scene. - **Limits**: `Validate` caps `MaxLights` at `MaxClusterLights` (65,536), keeps `MaxLightsPerCluster` at or below `MaxLights`, and caps index slots (`TilesX * TilesY * SlicesZ * MaxLightsPerCluster`) at `MaxClusterIndexEntries`; `NewClusteredLightSystem` returns `ErrInvalidClusterConfig` when a storage buffer would exceed the device's `MaxStorageBufferBindingSize`. - **Desktop GPU performance**: measured on a MacBook Pro (Apple M4 Pro, Metal 4, macOS arm64, `2560 × 1440` drawable, 120 Hz display) with 256 animated clustered point lights (~250 visible, ~475 active clusters): sustained `120.0 fps` on the clustered storage-buffer path, with CPU cluster assignment and buffer upload taking ~145 µs/frame. - **Lifecycle**: set `ClusterConfig.Retained` to restore buffers across GPU device loss; `ByteSize()` reports GPU buffer bytes for `RenderStats` and budgets, and `Close()` releases resources eagerly. ## Splat-map terrain materials (`TerrainMaterial`, `GPUTerrainMaterial`) Render multi-layer heightmap terrain ([world3d](https://game.nsgo.dev/docs/world3d/)) blending up to 8 PBR layers from 1 or 2 RGBA weight (splat) maps with per-layer UV tiling, optional height-based contrast blending, optional slope-driven triplanar projection on steep cliffs, and full scene lighting plus shadows: ```go gpuTerrain, err := render3d.NewGPUTerrainMaterial(cx, dev, render3d.TerrainMaterial{ Layers: layers, // 1..8 TerrainLayer values (albedo, normal, metallic-roughness, height, UVScale, HeightBias) SplatMap0: splatImg0, SplatMap1: splatImg1, // optional for <= 4 layers HeightBlendContrast: 0.65, Triplanar: render3d.DefaultTerrainTriplanar(), }, render3d.TerrainMaterialUpload{Label: "alpine", Mipmaps: true, Retained: true}) pipe, err := render3d.NewTerrainMaterialPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), gpuTerrain.Layout(), render3d.TerrainPipelineOptions{ DepthFormat: gpu.FormatDepth24Plus, ShadowLayout: shadowMap.Layout(), // or CSMLayout / FogLayout at group 3 }) pass.SetPipeline(pipe) pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) pass.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) gpuTerrain.Bind(pass) // TerrainMaterialGroup (group 2) pass.SetBindGroup(render3d.ShadowGroup, shadowMap.BindGroup()) terrainMesh.Draw(pass) ``` - **Texture-array layout**: `GPUTerrainMaterial` packs layer albedo (sRGB), tangent-space normal, and height/roughness/metallic maps into three `gpu.Dim2DArray` textures (`TerrainAlbedoArrayBinding`, `TerrainNormalArrayBinding`, `TerrainMRHeightArrayBinding`) plus the two RGBA splat maps at `TerrainMaterialGroup` (group 2). Total fragment texture bindings stay at 5 (6 with shadows), well within WebGL 2 / GLES 3 limits with zero pipeline permutations across 1–8 layers. - **Lighting, shadows, fog, and HDR**: `NewTerrainMaterialPipeline` compiles `TerrainMaterialWGSL`, `TerrainMaterialShadowWGSL` (`ShadowLayout`), `TerrainMaterialCSMWGSL` (`CSMLayout`), or `TerrainMaterialFogWGSL` (`FogLayout`), plus `LinearOutput` variants for `HDRTarget` / `ToneMapPass`. - **Live updates & CPU reference**: call `UpdateUniforms` to tweak transforms, blend contrast, triplanar settings, or per-layer factors/tiling without reallocating textures, `UpdateSplatMaps` to upload repainted splat maps in place, and `EvaluateTerrainMaterial` as the pure-Go CPU reference matching the WGSL shader. - **Loading directly from `*.terrain.yaml`**: `TerrainMaterialFromDoc(fsys, doc)` decodes either packed RGBA `splatMaps` or per-layer grayscale `weightMap` PNGs, resolves optional `resource.Material` files alongside explicit PBR overrides, and validates a `TerrainMaterial` ready for `NewGPUTerrainMaterial`; `MeshFromTerrainMesh` converts `world3d.TerrainMesh` chunks directly into `render3d.Mesh` geometry. --- Source: https://game.nsgo.dev/docs/replay/ # replay `game/replay` records fixed-step game inputs into delta-encoded YAML text files and replays them deterministically for bug reproduction, ghost runs, and automated regression tests. ```go import "github.com/nsgo-dev/game/pkg/replay" ``` ## ActionSource abstraction Write your simulation against the `ActionSource` interface (`Pressed`, `JustPressed`, `JustReleased`, `Axis`, `Step`): ```go type ActionSource interface { Pressed(name string) bool JustPressed(name string) bool JustReleased(name string) bool Axis(name string) float64 Step() } ``` `*input.Actions` satisfies `ActionSource` for live play, `*replay.Recorder` wraps any `ActionSource` to record it transparently, and `*replay.Player` satisfies `ActionSource` for playback — so your game update loop stays identical in all three modes. ## Recording live play Wrap your `*input.Actions` with `NewRecorder`, listing the seed, fixed step rate (`<= 0` defaults to `60`), and watched action and axis names: ```go rec := replay.NewRecorder( actions, seed, 60, []string{"jump", "attack"}, []string{"move_x"}, ) // Pass rec to your simulation instead of actions directly: loop := &game.Loop{ Rate: 60, Update: func(dt time.Duration) { sim.Step(rec, dt) // calls rec.Step() once at the start }, } // Snapshot and save as YAML text if err := replay.SaveFile("runs/boss-bug.replay.yaml", rec.Recording()); err != nil { return err } ``` `Recording` is delta-encoded: only steps where a watched action's pressed state or a watched axis's value changed from the previous step are written to `Events`, keeping long sessions small. Serialize in memory with `rec.Encode()` and `replay.Decode`, and on disk with `replay.SaveFile` and `replay.LoadFile`. ## The recording file A recording is a YAML text file you can read, diff in review and edit by hand. The header holds the format version, the seed, the step rate, the watched action and axis names and the total step count; after it comes one line per step on which input changed, naming the actions pressed and released and the new axis values: ```yaml version: 2 seed: 99537266 rate: 60 actions: [left, right, jump, dash] axes: [move_x] total_steps: 254 steps: - {step: 6, press: [right], axes: {move_x: 1}} - {step: 39, press: [left], release: [right], axes: {move_x: -1}} - {step: 85, press: [jump, dash]} - {step: 95, release: [jump, dash]} ``` Steps count from 0 and must be listed in increasing order below `total_steps`. An action stays pressed from the step that presses it until a step releases it, and an axis keeps its value until a later step sets another. An edited file replays as edited: move a press to another step, change an axis value or add a line, and `LoadFile` and `Player` follow it. `Decode` refuses unknown keys, a missing `seed` or `total_steps`, a line without `step`, names missing from the header and trailing YAML documents, and names the step or line at fault. `Encode` always writes the same bytes for the same recording, so loading a file it wrote and saving it again changes nothing; an axis value written as `-0.0` is read as `0`. Comments and block-style entries you add are read, but a program that saves the recording again writes the canonical one-line form without them. The conventional extension is `.replay.yaml`. Version 1, the earlier compact JSON form, is no longer read. ## Playing back a Recording Load a recording and feed `NewPlayer(recording)` into the same simulation: ```go recording, err := replay.LoadFile("runs/boss-bug.replay.yaml") if err != nil { return err } player := replay.NewPlayer(recording) sim := newGameSim(player.Seed()) for !player.Done() { sim.Step(player, recording.StepDuration()) } ``` Inspect playback progress with `player.StepIndex()`, `player.TotalSteps()`, `player.Done()`, and rewind with `player.Reset()`. Once `Done()` is `true`, a subsequent `Step()` releases any actions still held on the final step (firing `JustReleased` once) and leaves all inputs idle. ## Automated regression testing (`Run` and `AssertEndState`) Commit recorded runs (e.g. under `testdata/`) and verify deterministic behavior in `go test` using `replay.Run` and `replay.AssertEndState`: ```go func TestLevel1ClearReplay(t *testing.T) { rec, err := replay.LoadFile("testdata/level1-clear.replay.yaml") if err != nil { t.Fatal(err) } want := SimState{Score: 1200, Cleared: true} replay.AssertEndState(t, rec, want, nil, func(seed uint64, src replay.ActionSource) (func(time.Duration), func() SimState) { sim := newGameSim(seed) return func(dt time.Duration) { sim.Step(src, dt) }, func() SimState { return sim.Snapshot() } }) } ``` `Run` drives `step` exactly `rec.TotalSteps` times at `rec.StepDuration()` and returns the final state; `AssertEndState` compares it against `want` using your `equal` function (or `reflect.DeepEqual` when `nil`) and fails the test with a clear diagnostic on mismatch. To check the whole state rather than a hand-picked struct, dump it as text with [`statedump.Run`](https://game.nsgo.dev/docs/statedump/) and compare it against a golden file. ## Playing recordings in CI `nsgo game replay` plays a project's recordings headless: it checks that every `*.replay.yaml` file under the directories it is given can be played, then runs the tests with `Replay` in their names, such as `TestLevel1ClearReplay` above, and fails when a recording is broken, a run ends in another state than the test expects or no test passed, so a misnamed test cannot leave the recordings unplayed. See [Command Line](https://game.nsgo.dev/docs/cli/#replay). --- Source: https://game.nsgo.dev/docs/resources/ # resource `game/resource` reads and writes shared resource files: data that several scenes and pieces of code use, kept in a YAML file of its own and referenced by path instead of being repeated, as Godot's `.tres` files are. Materials, curves, gradients, animation clips, UI themes, sound bus layouts and physics materials are resource files. ```go import "github.com/nsgo-dev/game/pkg/resource" ``` ## The common header Every resource file is one YAML document that starts with the same fields: | Field | Description | | --- | --- | | `type` | The resource's type: `material`, `curve`, `gradient`, `animation`, `theme`, `busLayout` or `physicsMaterial`. | | `version` | The schema version. Must be `1`. | | `uid` | Optional stable ID that stays the same when the file is renamed or moved, 13 characters of `0`-`9` and `a`-`z` without `i`, `l`, `o` and `u`. `nsgo game index` writes it; see [Stable references](https://game.nsgo.dev/docs/project/#stable-references). | The fields of that type follow. `Parse` reads the header first, refuses an unknown type or a version other than `1` with a message that says so, then decodes the whole document into the matching Go type (`*resource.Material`, `*resource.Curve`, …) and refuses unknown fields, trailing documents and values out of range. `Encode` writes the header first and the other fields in a fixed order, leaving out fields at their defaults, so a file it wrote reads back and encodes to the same bytes and a diff shows only what changed. A file's name is free; `..yaml`, such as `stone.material.yaml`, keeps a folder readable. ## Types ### material How a surface draws. 2D sprites use `opacity` and `blend`; 3D renderers also read the PBR fields. ```yaml type: material version: 1 name: Stone baseColor: '#8a8f99' texture: textures/stone.png opacity: 0.75 blend: multiply roughness: 0.9 ``` | Field | Default | Description | | --- | --- | --- | | `name` | | Optional display name. | | `baseColor` | white | A CSS color. | | `texture` | | A slash-separated image path from the project root. | | `opacity` | `1` | Multiplies the alpha of what draws with the material, from `0` to `1`. | | `blend` | `sourceOver` | A canvas composite operation in camel case, such as `multiply`, `screen` or `lighter` (`resource.BlendModes`). | | `metallic` | `0` | PBR metalness, from `0` to `1`. | | `roughness` | `1` | PBR roughness, from `0` to `1`. | | `emissive` | | A CSS color the surface gives off. | | `doubleSided`, `unlit` | `false` | Draw back faces; skip lighting. | ### curve A value keyed over time, such as an easing or a particle's size over its life. Keys are in strictly increasing `time` order, and `interp` is how a key's value moves to the next: `linear` (the default), `step` or `smooth`. ```yaml type: curve version: 1 name: Jump height keys: - time: 0 value: 0 interp: smooth - time: 0.5 value: 1 - time: 1 value: 0 ``` `Curve.Eval(t)` returns the value at `t`, holding the end values beyond the first and last keys; its method value fits `tween.EaseFunc`. ### gradient Colors keyed over offsets from `0` to `1`, in non-decreasing order; two stops at one offset make a hard edge. ```yaml type: gradient version: 1 stops: - offset: 0 color: '#ffcc66' - offset: 1 color: '#331a4d' ``` `Gradient.At(t)` mixes the colors around `t`, and `Gradient.CoreStops()` returns `core.GradientStop` values for a canvas gradient. ### animation A clip of property tracks keyed from `0` to `length` seconds. `target` names the object a track drives, the ID of an object in the scene when [animclip](https://game.nsgo.dev/docs/animclip/) plays it (empty is the object the clip plays on), and each target and property pair has one track. A track sets either numeric `keys` (`time`, `value`, optional `interp`) or discrete sprite `frames` (`time`, `frame`), never both; `frames` steps through atlas frame names without interpolation, used for `sprite.frame` flipbook tracks. `events` are named cues in time order, each at a `time` from `0` to `length`, which a player reports as playback crosses them. ```yaml type: animation version: 1 name: Torch flicker length: 1.5 loop: true tracks: - target: flame property: alpha keys: - time: 0 value: 1 - time: 0.75 value: 0.6 interp: smooth - time: 1.5 value: 1 - property: sprite.frame frames: - time: 0 frame: torch_0 - time: 0.75 frame: torch_1 events: - time: 0.75 name: flare ``` `Animation.Sample(t, set)` wraps or clamps `t` to the clip (`ClipTime`) and calls `set` with each numeric track's target, property and value; `Animation.SampleFrames(t, set)` does the same for discrete frame tracks (`Track.IsFrameTrack`, `Track.EvalFrame`). [animclip](https://game.nsgo.dev/docs/animclip/) plays a clip on scene objects, with its properties checked against the registered component types, and the [editor's animation panel](https://game.nsgo.dev/docs/editor/#animation-editor) keys and saves clips. ### theme A `gameui` theme. Every field is optional, and `Theme.Apply(base)` replaces only the fields the file sets, so a file can restyle a few colors of `gameui.DefaultTheme()`. ```yaml type: theme version: 1 colors: panelBackground: '#10141c' accent: '#f97316' padding: 10 font: family: Inter size: 18 weight: semibold ``` `colors` has one key per `gameui.Theme` color (`panelBackground`, `panelBorder`, `background`, `hover`, `active`, `focusedBorder`, `disabled`, `border`, `text`, `disabledText`, `mutedText`, `accent`, `accentHover`, `accentActive`, `track`). The sizes are `padding`, `cornerRadius`, `borderWidth` and `focusWidth`, and `font.weight` is `light`, `normal`, `medium`, `semibold` or `bold`. ### busLayout The sound buses a `sound.Mixer` plays through and the effect chain on each. Each effect entry sets exactly one of `lowPass`, `highPass` (`cutoffHz`, `q`), `delay` (`seconds`, `feedback`, `wet`), `reverb` (`roomSize`, `damping`, `wet`), `gain` (`factor`) or `bitcrush` (`bits`, `downsample`). ```yaml type: busLayout version: 1 buses: - name: music effects: - lowPass: cutoffHz: 8000 - name: effects effects: - reverb: roomSize: 0.5 wet: 0.2 ``` `BusLayout.Apply(mixer)` sets each bus's chain with `SetGroupEffects`; a bus with no effects clears its chain. Volumes stay the player's own settings. ### physicsMaterial Surface properties of 2D and 3D rigid bodies: `friction`, `restitution` (from `0` to `1`), `linearDamping` and `angularDamping`. `PhysicsMaterial.ApplyTo(body)` sets the fields the file holds on a `physics.RigidBody` and `PhysicsMaterial.ApplyTo3D(body)` sets them on a `physics3d.Body`, leaving unset fields unchanged. `Library.PhysicsMaterial(path)` loads and shares one `*PhysicsMaterial` per path and implements `sceneformat.PhysicsMaterialResolver` for scene physics components. ```yaml type: physicsMaterial version: 1 friction: 0.02 restitution: 0.1 ``` ## Sharing resources with a Library A `Library` loads resource files from an `fs.FS` by slash-separated path, such as `materials/stone.material.yaml`, and keeps one value per path: every `Load` of a path returns the same pointer, so every scene and piece of code using the file holds one value. ```go lib := resource.NewLibrary(os.DirFS("project")) stone, err := lib.Material("materials/stone.material.yaml") jump, err := resource.LoadAs[*resource.Curve](lib, "curves/jump.curve.yaml") ``` `Library.Reload(path, data)` parses new contents and copies them into the loaded value in place, so everything holding it sees the edit. A file that no longer parses, or that changed its type, leaves the last good value and returns an error. `Library.Revision()` counts successful reloads, for code that derives values from resources, such as a `gameui.Theme` built with `Theme.Apply`. Call `Reload` on the goroutine that reads resources, usually the engine's. ## Materials in scenes A `sceneformat` object references a material file by path with `material`: ```yaml objects: - id: wall sprite: atlas: cave_tiles frame: "1" material: materials/stone.material.yaml ``` `sceneformat.Build` resolves it through a resolver that implements `sceneformat.MaterialResolver`; a `Library` does, so a resolver can embed one beside the atlases: ```go type resolver struct { sceneformat.AtlasMap *resource.Library } cave, err := sceneformat.Build(caveDoc, resolver{atlases, lib}) keep, err := sceneformat.Build(keepDoc, resolver{atlases, lib}) ``` The object's sprite draws with its own alpha times the material's opacity, and with the material's blend mode. `BuiltScene.Draw` copies the material's current state onto the sprites first (`SyncMaterials`), so when the file is reloaded both scenes draw the edit. ## Reloading on edit During development, `hotreload.Watcher.WatchResources` watches every `.yaml` and `.yml` file under its directory and passes changed files the library has loaded to `Library.Reload` on the engine goroutine. The watcher's directory must be the library's root, so their paths match: ```go lib := resource.NewLibrary(os.DirFS(root)) w := hotreload.NewWatcher(cx, root) w.WatchResources(lib, func(path string, err error) { if err != nil { log.Printf("reload %s: %v", path, err) } }) ``` In release builds (`-tags release`) `WatchResources` does nothing. --- Source: https://game.nsgo.dev/docs/rhythm/ # rhythm `game/rhythm` keeps a rhythm game in time with its music: a beat map read from YAML, a music clock that tells the track's position and beat at any engine time, and a calibration of each device's audio and video latency. ```go import ( "github.com/nsgo-dev/game/pkg/rhythm" "github.com/nsgo-dev/nsgo/audio" ) ``` The clock and the calibration run on the engine's goroutine, as `audio` does. They count on NSGo's audio clock: `audio.Now`, the time `audio.Voice.StartAt` starts a sound at, `audio.CanSchedule` and `audio.OutputLatency`. ## Beat maps A beat map is a track's tempo map, kept as a YAML file next to the track: ```yaml version: 1 title: Opening offsetMs: 120 tempos: - beat: 0 bpm: 120 - beat: 62.5 bpm: 140 meters: - beat: 0 beatsPerBar: 4 - beat: 64 beatsPerBar: 3 ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` | | `title` | The track's name, for people reading the file | | `offsetMs` | Where beat 0 plays, in milliseconds from the start of the audio; negative when the audio starts after beat 0 | | `tempos` | Tempo changes in beat order, the first at beat 0; a change may start between beats | | `meters` | Meter changes in beat order, the first at beat 0, each on a whole bar of the meter before it; none means 4 beats to a bar | `ParseBeatMap` refuses unknown fields, a second YAML document, YAML anchors and aliases, a fraction where a whole number belongs, and changes out of order or out of range (1 to 2000 bpm, at most 10,000 changes and beat 1,000,000). Those bounds keep every time a valid map gives finite and well inside a `time.Duration`; a beat asked for far past them saturates at the longest `Duration` rather than wrapping. `EncodeBeatMap` writes the fields in that fixed order with 2-space indentation, so a map loaded and saved again is unchanged. `BeatMap.Timing` turns a map into a `Timing`, which converts between track time and beats and bars: ```go m, err := rhythm.ParseBeatMap(data) if err != nil { return err } timing, err := m.Timing() if err != nil { return err } at := timing.Time(64) // when beat 64 plays, from the start of the audio beat := timing.Beat(at) // 64 bar, inBar := timing.Bar(65) // bar 16, 1 beat in ``` Each beat's time is computed in `float64` from the start of its own tempo change, so the error does not grow with the length of the track: hours of music with thousands of tempo changes stay within a microsecond of the map, far inside the millisecond a rhythm game needs. A beat before 0 or after the last change keeps the tempo nearest it. A `Timing` never changes, so goroutines may share one. ## The music clock A `Clock` reads a track's position at any engine time. Start it at the moment the track starts playing, and it extrapolates from the engine's clock, so it moves smoothly between a player's progress reports: ```go clock := rhythm.NewClock(timing) clock.SetOffsets(offsets) // from an OffsetStore player := audio.NewPlayer(cx, audio.Source{URI: "asset:music/opening.m4a"}, audio.PlayerOptions{ OnProgress: func(pos, _ time.Duration) { clock.Sync(pos, audio.Now(cx)) }, }) player.Play(func(err error) { if err == nil { clock.Start(audio.Now(cx), player.Position()) } }) ``` For a track loaded as an `audio.Sound`, start it with `audio.Voice{StartAt: at}` and the clock with `clock.Start(at, 0)`. `Sync` moves the clock to the position a player reports only when the two differ by more than `Tolerance` (30 ms by default), as after a seek, a loop or a stall, so progress jitter never makes notes jump. `Pause` and `Resume` follow the player. | Method | Use | | --- | --- | | `Track(now)` | The position the output plays, uncorrected | | `Position(now)`, `Beat(now)` | What the player hears: the position less the audio offset; judge input by it | | `Judge(at, beat)` | How early (negative) or late an input going down at `at` is for `beat` | | `DrawPosition(now)`, `DrawBeat(now)` | Where a frame drawn now puts the hit line: the position plus the video offset less the audio offset | | `BeatTime(beat)`, `TrackTime(pos)` | The engine time the output plays a beat, to pass to `audio.Voice.StartAt` for a hit sound or a metronome click; no offset applies, since both go through the same output | ## Calibration Every device delays sound and picture differently: the output's buffer, Bluetooth headphones, the display and the input all add their part. Calibration measures what reaches the player, as two offsets: - `Offsets.Audio`: how long after the engine starts a sound the player taps to it. - `Offsets.Video`: how long after the engine draws a frame the player taps to what it shows. A `Calibrator` matches taps with cues every `Interval` (750 ms by default) and takes the median of how late each is, after a few warm-up taps, with the median deviation as its `Spread`; a result is `Steady` when the spread is at most 30 ms. It keeps no clock of its own, so a test drives it with exact times. A `Calibration` runs one on the engine. For `CalibrateAudio` it clicks at each cue, scheduled ahead with `audio.Voice.StartAt` where `audio.CanSchedule` reports the platform can, and otherwise played on the first frame at or after the cue, measuring from when it played. It seeds the tap matching with `audio.OutputLatency`, so a tap hundreds of milliseconds late over Bluetooth still finds its cue. For `CalibrateVideo` it plays nothing, and the screen flashes at each cue, measuring from the first frame that shows it. `CalibrationScreen` is the screen a player calibrates on, drawn with `gameui` into a `core.Canvas`: ```go store := rhythm.NewOffsetStore(cx, "rhythm.calibration") device := rhythm.DeviceKey(cx) cal := rhythm.NewCalibration(cx, rhythm.CalibrateAudio, click) screen := rhythm.NewCalibrationScreen(cal, store, device) screen.OnSave = func(o rhythm.Offsets) { clock.SetOffsets(o) } core.View{ OnPressDown: func(ev core.PressEvent) { screen.OnPressDown(ev) }, OnPress: func(ev core.PressEvent) { screen.OnPress(ev) }, OnKeyDown: screen.OnKeyDown, Children: []core.Node{core.Canvas{ Draw: func(d *core.Drawing, size core.Size) { screen.Draw(d, core.Bounds{Size: size}) }, }}, } ``` Redraw the canvas every frame while the screen shows, as a `game.Loop` does. A tap is taken on the edge it goes down: `OnPressDown` off the buttons, or a key going down. A completed press (`OnPress`) only comes as the finger lifts, so measuring from it would add how long each tap is held, tens of milliseconds that vary from tap to tap. Judge gameplay input on the same edge, from `OnPressDown` or a key going down, or the offset calibration measured will not match it. A press on Retry or Save presses the button. Tab and the arrow keys move the focus between them and Return or Space presses the focused one; once the calibration is done the focus moves to Save, or to Retry for an unsteady result, so a player on a keyboard or a switch can save. Save is enabled once the result is steady. Call `Stop` when the screen goes away mid-run, which stops the clicks booked ahead; the clicks also stop as the last tap counts. Set `Text` to translate the words. ## Per-device offsets `OffsetStore` keeps each device's offsets as a YAML document in the app's storage (`core.Storage`) under one key: ```yaml version: 1 devices: ios/iPhone15,2: audioMs: 182.5 videoMs: 21 ``` `DeviceKey` names the device by its OS and hardware model, such as `ios/iPhone15,2` or `web/unknown` where the platform names no model. NSGo does not report the audio output route, so a game that keeps separate offsets for headphones and speakers adds its own suffix to the key, such as `/bluetooth`, chosen by the player. Devices are written in key order, so the same offsets always encode to the same text. `Set` replaces a document it cannot read, such as one a later schema wrote, and fails with `*core.StorageFullError` when the storage is full, keeping what it held. --- Source: https://game.nsgo.dev/docs/rooms/ # rooms `game/rooms` splits a 2D world into rooms with their own camera bounds, as metroidvania platformers do. When the player walks from one room into the next, a `Director` clamps the `tilemap.Camera` to the new room and plays its transition: a cut, a slide or a fade. ```go import "github.com/nsgo-dev/game/pkg/rooms" ``` ## Room maps Rooms live in a versioned YAML file. Each room is a rectangle in world points; the map's `transition` plays when entering any room, and a room's own `transition` overrides it. ```yaml version: 1 transition: kind: slide duration: 300ms rooms: - id: entrance name: room.entrance x: 0 "y": 0 width: 320 height: 180 - id: hall x: 320 "y": 0 width: 640 height: 180 - id: crypt x: 320 "y": 180 width: 320 height: 360 transition: kind: fade duration: 500ms easing: easeIn color: '#102030' ``` | Field | Meaning | | --- | --- | | `version` | Schema version, `1` (`rooms.FormatVersion`) | | `transition` | Played when entering a room that sets none; omitted means a cut | | `rooms[].id` | Unique, non-empty ID used in code and saves | | `rooms[].name` | Display name or localization key; not interpreted | | `rooms[].x`, `y`, `width`, `height` | The room's rectangle in world points; the size must be positive | | `rooms[].transition` | Played when entering this room | | `transition.kind` | `cut`, `slide` or `fade` | | `transition.duration` | A Go duration with a unit, such as `400ms`; omitted means 400 ms for a slide and 600 ms for a fade. A cut takes none | | `transition.easing` | `linear`, `ease`, `easeIn`, `easeOut` or `easeInOut`; omitted means `easeInOut` for a slide and `linear` for a fade. A cut takes none | | `transition.color` | A fade's cover as a CSS color; omitted means black. Only a fade takes one | `rooms.Parse` and `rooms.LoadFS` refuse unknown fields, other versions, missing or duplicate IDs, empty or non-finite rectangles, bare numbers as durations, unknown kinds or easings and malformed colors, with errors wrapping `rooms.ErrInvalidMap`. `rooms.Encode` writes the same map back byte for byte: fields in a fixed order, 2-space indentation and nothing generated. It quotes the `y` key because YAML 1.1 reads a bare `y` as `true`; hand-written files may leave it bare. A negative zero is written as `0`, so saving a loaded map twice gives the same bytes. A point belongs to a room when it is inside its left and top edges and before its right and bottom ones, so rooms sharing an edge never both hold it. `Map.RoomAt` returns the first room in list order holding a point. ## Laying rooms out in the editor, LDtk or Tiled You can edit `*.rooms.yaml` files visually right over your scene in the [scene editor](https://game.nsgo.dev/docs/editor/): open a `*.rooms.yaml` beside the scene from the file browser or Scene Settings inspector, create/move/resize/delete rooms with handles snapped to the scene's tile grid, edit each room's `id`, `name` and `transition` in the inspector with full Undo/Redo, and save deterministic YAML via `rooms.Encode`. Rooms can also come from an external level editor instead of being typed by hand. `rooms.FromLDtk` makes one room per level of an LDtk project in a Free or GridVania layout, named after the level, and `rooms.FromTiledLayer` makes one room per rectangle in a Tiled object layer, named after the object and moved by the layer's offset, including the offsets of the groups that hold it. Both refuse what cannot be a room, such as a Linear layout, an ellipse or an unnamed object, instead of skipping it. ```go data, _ := fs.ReadFile(assets, "world.ldtk") list, err := rooms.FromLDtk(data, "") // "" reads a single-world project if err != nil { return err } m := &rooms.Map{ Version: rooms.FormatVersion, Transition: &rooms.Transition{Kind: rooms.KindSlide}, Rooms: list, } if err := rooms.Validate(m); err != nil { return err } ``` ## Moving the camera between rooms A `Director` owns the camera's position and bounds. Call `Start` once where the player spawns, then `Update` on every fixed step with the player's position instead of `Camera.Follow`: ```go dir := rooms.NewDirector(m, cam) dir.Smoothing = 10 // Camera.Follow smoothing between transitions; 0 locks on the player dir.Start(player.Pos) // Inside game.Loop.Update: if !dir.Transitioning() { player.Update(dt) // freeze the player while the camera moves, as most metroidvanias do } if dir.Update(player.Pos, dt) { hud.ShowRoomName(dir.Room().Name) } cam.Update(dt) // screen shake still runs // Inside game.Loop.Draw: d.Save() cam.Apply(d) drawWorld(d) d.Restore() dir.DrawFade(d) // view space: the fade's cover over the whole view ``` Each step, `Update` keeps the current room while the player is still inside it, so standing where two rooms overlap never flickers between them, and keeps it too when the player is in no room. When the player enters another room, `Update` sets `Camera.Bounds` to that room, returns `true` and starts the room's transition: - **cut**: the camera snaps to the player, clamped to the new room. - **slide**: the camera pans from where it was to the player's clamped position in the new room along the easing curve, following the player if they keep moving, and lands clamped exactly when the duration ends. - **fade**: the view is covered with the fade's color over the first half while the camera holds, the camera cuts to the new room at the midpoint, and the view is uncovered over the second half. `FadeAlpha` returns the cover's opacity and `DrawFade` paints it over the `Camera.Width` by `Camera.Height` view. When the player changes room again during a fade, the cover never jumps: a new fade covers on from the same opacity, even with a different easing, and a slide or cut leaves the cover to clear as the interrupted fade would have while the camera moves. A slide interrupted by another room change pans on from wherever the camera is. A target with a NaN or infinite coordinate is ignored for that step, so a bad position never reaches the camera. `Room`, `Previous`, `Transition` and `Progress` report where the camera is going, where it came from, what is playing and how far it has run. Everything advances by the fixed `dt` only, so a replay produces the same camera path bit for bit. --- Source: https://game.nsgo.dev/docs/rts/ # rts `game/rts` is the unit-control layer of a real-time strategy game: flow fields that steer many units toward a goal over an `ai.Grid`, a `Crowd` that moves those units with push-apart separation or ORCA local avoidance and wall sliding, formations kept in versioned YAML, box and click selection, and numbered control groups. ```go import "github.com/nsgo-dev/game/pkg/rts" ``` Everything is deterministic and steps on `game.Loop`'s fixed steps with no background goroutines: the same orders on the same grid move the same units to the same places on every run on the same CPU architecture. Positions are `float32`, and Go may fuse a multiply and an add into one instruction on arm64 but not on x64, so the same orders can end a few ulps apart on different architectures; a lockstep multiplayer game across architectures should send state from an authoritative host rather than have each peer step its own `Crowd`. ## Flow fields A `FlowField` holds, for every cell of a grid, the cost of the cheapest path to the nearest of its goal cells (the integration field) and the direction a unit in that cell moves to follow it (the direction field). Building it is one Dijkstra search over the grid; after that, any number of units read their direction in constant time, so a thousand units heading for the same place cost one search instead of a thousand. ```go grid := ai.NewCostMap(160, 128) // or any ai.Grid / ai.CostGrid, such as an ai.GridFunc over a tilemap field := rts.NewFlowField(math2d.Vec2{}, 16) // cells 16 world units wide, cell (0, 0) at the origin field.Build(grid, ai.Cell{Col: 140, Row: 64}) dir, ok := field.Sample(unitPos) // unit vector, blended from the four cells around unitPos ``` - Movement is 8-way by default (`Diagonal`), with diagonal steps costing sqrt(2) and never cutting the corner of a blocked cell. Stepping into a cell costs its `ai.CostGrid` `MoveCost`, so a cell's `Cost` equals the cost `ai.AStar` finds from it to the nearest goal. - `Build` takes several goals at once; each cell then leads to the nearest of them. Blocked and out-of-bounds goals are ignored, and `Build` reports whether any goal was valid. - `Sample` blends the directions of the reachable cells around a point, so units turn smoothly instead of in 45-degree steps and are never pulled into a wall. `Cost`, `Reachable`, `Direction`, `CellAt` and `CellCenter` read the field cell by cell. - Rebuilding a field of the same size allocates nothing. `FieldCache` keeps the most recently used fields over one grid, keyed by their goal set, so units ordered to the same goals share a field. Its `Rebuild` integrates every cached field again in place and drops any field none of whose goals is walkable any more. A `Crowd` keeps its own cache: after changing the grid (a wall built, a bridge destroyed), call the crowd's `Rebuild`, which also rebuilds the fields its units still follow after the cache dropped them to make room, so every unit sees the change on its next step. Units whose order led only to cells that are now blocked stop where they stand. `Builds` counts the searches, which tells a test or a profiler whether fields are being shared. ### Sector-limited flow fields (`SectorFlowField`) On very large maps (such as 1024×1024), integrating a whole-grid `FlowField` scans every tile even when a squad only crosses a narrow corridor. `SectorFlowField` restricts Dijkstra integration and direction computation to an active subset of fixed-size square sectors—typically the cluster corridor returned by `ai.HPA.FindClusters`: ```go hpa := ai.NewHPA(grid, ai.HPAOptions{ClusterSize: 32, Diagonal: true}) sf := rts.NewSectorFlowField(math2d.Vec2{}, 16) sf.BuildAlongHPA(hpa, startCell, goalCell, 1) // padding=1 adds a 1-cluster border around the corridor dir, ok := sf.Sample(unitPos) // same Cost, Reachable, Direction, Sample API as FlowField ``` - Use `BuildSectors(grid, sectorSize, sectors, goals...)` to supply an explicit set of `ai.ClusterID` sectors and multiple goals. - Cells outside active sectors report `Unreachable`, and `Sample` ignores inactive sectors so units are never steered out of the corridor. - Internal buffers are reused across builds with zero allocations once grown. ## Crowds and move orders A `Crowd` moves units over a grid. Add units with `Add`, order them with `Move`, and call `Step` from the loop's `Update`: ```go crowd := rts.NewCrowd(grid, rts.CrowdOptions{CellSize: 16}) crowd.Add(rts.UnitSpec{Pos: math2d.V2(40, 650), Radius: 5, MaxSpeed: 96, Kind: kindRifleman}) crowd.Move(selection.IDs(), rts.MoveOrder{ Target: clickWorld, Formation: rts.Formation{Shape: rts.ShapeBox, Spacing: 14}, KeepPace: true, // move at the slowest unit's speed }) loop.Update = func(dt time.Duration) { crowd.Step(dt) } ``` `Move` lays the formation out around the target, facing from the group toward it unless `Facing` is set, and moves any slot that falls on a blocked cell or on a cell the group cannot reach to the nearest free cell that can be reached. When the units cannot reach the target at all, as when it lies on an island, the formation centers on the nearest cell they can reach. Units are matched to slots so their paths do not cross, and the whole group shares one flow field whose goals are the slots' cells. Each unit follows that field until it can see its own slot within `DirectRange`, then walks straight to it; a unit that reaches the formation with a wall between it and its slot follows its own `ai.AStar` path there for the rest of the order, planning it again whenever the crowd pushes it off it. Path searches run on one step in eight for each unit, staggered by ID, so their cost stays bounded when many units need one. `Step` runs in time linear in the number of units plus the number of neighbor buckets covering the units' bounding box, so its cost follows the units rather than the size of the map: neighbors come from that bucket grid, rebuilt each step without allocating once its buffers have grown, units push apart where their bodies overlap (`Separation`, `Gap`), and bodies slide along blocked cells and the grid's edge. Every unit's force is computed from the positions at the start of the step before any unit moves, so the result does not depend on the order units move in within a step. It does depend on the order units were added in, which sets their IDs and the order their pushes are summed, so a replay adds the same units in the same order. Set `CrowdOptions.Avoidance` to `AvoidanceORCA` (with optional `CrowdOptions.ORCA` tuning) to use `ai.ORCASolver` velocity obstacles instead of `AvoidancePush` overlap pushing so opposing units steer around each other before contact while keeping deterministic, zero-allocation stepping and grid wall sliding. Each `Unit` reports its `State`: `Idle` before any order and after `Stop`, `Moving`, and `Arrived` once within `ArriveRadius` of its slot. Arrived units hold their slots; one pushed well away walks back. `Units` returns every unit for drawing, `Unit(id)` one of them, and `Remove` deletes one. On an Apple M1 Max, `BenchmarkCrowdStep1000` steps 1000 units crowding through a maze in about 0.4 ms, under 3% of a 60 fps frame. A step allocates only when a unit's own detour path outgrows the buffer it kept from its earlier searches, so allocations stop once every unit has planned its longest detour. The order itself costs more: `BenchmarkMove1000` lays out, assigns and builds both flow fields for 1000 units on that maze in about 6.5 ms with an empty `FieldCache`, so issue orders on input rather than every step. `TestCrowdThousandUnitsReachTarget` deterministically moves 1000 units in a box formation across a 160 by 128 maze and fails if any unit does not arrive, if any ends inside a wall, or if flow fields are not shared; `BenchmarkCrowdThousandUnits` measures the full crossing (reporting average and 99th-percentile step times) and is tracked alongside `BenchmarkCrowdStep1000` by the CI performance baselines in `benchmarks/baseline.yaml`. ## Formations A `Formation` lays units out in rows across its facing direction, row 0 at the front: | Shape | Layout | `Width` | | --- | --- | --- | | `line` | Side by side | Slots per row; 0 for one row | | `column` | One behind another | Slots per row; 0 for one | | `box` | A filled square | Slots per row; 0 for a square | | `wedge` | One at the point, each row behind one wider | Ignored | `Spacing` is the distance between neighboring slot centers; keep it at least twice the largest unit radius. `Layout` returns the slots around the formation's center, `Place` turns them into world positions for a center and a facing, and `Assign` matches units to slots in O(n log n) so that front units take front slots and units on the left take left slots. `Move` uses all three; call them yourself to preview a formation under the cursor. A game's formations live in a YAML file, so a designer can edit them and review the diff: ```yaml version: 1 formations: - name: line shape: line spacing: 1.5 - name: block shape: box spacing: 1.2 width: 8 ``` `ParseFormations` refuses unknown fields, a second YAML document, a version other than 1, an empty or repeated name, an unknown shape, a spacing that is not a positive finite number and a negative width. `Encode` writes the fields in a fixed order with two-space indentation, so a file already in that form loaded and saved again comes back byte for byte; comments, other key orders, quoted values and fields at their zero value, such as `width: 0`, are normalized away. `Get` finds a formation by name. ## Selection `Selection` is the set of selected units in the order they were selected, with `Set`, `Add`, `Remove`, `Toggle` and `Retain` (to drop units that died). `BoxSelector` turns pointer input in world space into selections: ```go sel := &rts.Selection{} box := &rts.BoxSelector{ Picker: crowd, // Crowd implements rts.Picker Selection: sel, Filter: func(id rts.UnitID) bool { return owner[id] == me }, } view := core.View{ OnPressDown: func(ev core.PressEvent) { box.Press(toWorld(ev.Position), ev.Modifiers, ev.Clicks) }, OnMouseMove: func(ev core.MouseEvent) { box.Drag(toWorld(ev.Position)) }, OnPressUp: func(ev core.PressEvent) { box.Release(toWorld(ev.Position)) }, } ``` - A press and release that moves less than `DragThreshold` picks the unit under the pointer (within `ClickSlop`); a click on empty ground clears the selection. - A drag picks every unit its rectangle touches. While it is in progress, `Box` returns the rectangle and `DrawSelectionBox` draws it. - A double click picks every unit of the clicked unit's `Kind` inside `View`, the world area on screen. - `ModeFor` reads the modifiers held at the press: Shift adds to the selection, Control (Command on macOS) toggles units in and out, and no modifier replaces it. ## Control groups `ControlGroups` holds the ten groups bound to the digit keys. `HandleKey` applies the usual bindings to a `core.KeyEvent`: | Keys | Action | | --- | --- | | Control or Command + digit | `GroupAssigned`: the group becomes the selection | | Shift + digit | `GroupAdded`: the selection joins the group, and the whole group is selected | | Digit | `GroupRecalled`: the selection becomes the group | | Digit twice within `DoubleTapSteps` | `GroupFocused`: the game centers its camera on the group (`Crowd.Centroid`) | The double tap counts game steps rather than wall-clock time, so a replay recalls the same groups; pass the same step counter, such as `Crowd.Steps`, to every call. `Forget` and `Retain` drop dead units from every group. ## Debug drawing `DrawFlowField` strokes each reachable cell's direction, and a cross on each goal, as one path under whatever camera transform the `core.Drawing` already has; use it in a debug overlay to see how units will move. --- Source: https://game.nsgo.dev/docs/save/ # save `game/save` stores game save slots as versioned JSON envelopes in `core.Storage` or on disk (such as `cx.DataDir()`), with sequential schema migrations and atomic backup recovery. ```go import "github.com/nsgo-dev/game/pkg/save" ``` ## Choosing a store Pick a store based on your targets: - **`NewStorageStore(cx.Storage(), prefix, opts...)`**: stores each slot in `core.Storage` under `.slot.` and `.bak.`. Works on every target, including the web. - **`NewFileStore(cx.DataDir(), opts...)`**: stores each slot as `.json` and `.json.bak` in a directory. Ideal for larger saves on desktop and mobile (on the web, `cx.DataDir()` is empty, so fall back to `NewStorageStore`). - **`NewStore(backend, opts...)`**: accepts any custom `Backend` implementation (such as cloud sync). ```go type Progress struct { Level int `json:"level"` Coins int `json:"coins"` Name string `json:"name"` } store := save.NewStorageStore(cx.Storage(), "mygame", save.WithVersion(1)) if err := store.Save("slot1", Progress{Level: 3, Coins: 120, Name: "Hero"}); err != nil { return err } var p Progress if err := store.Load("slot1", &p); errors.Is(err, save.ErrNotFound) { p = Progress{Level: 1} } else if err != nil { return err } ``` Inspect and manage slots with `store.Exists(slot)`, `store.Slots()` (sorted slice of slot names), and `store.Delete(slot)` (removes the backup and then the primary, so an interrupted delete never leaves a backup that `Load` would resurrect; deleting an absent slot returns `nil`). `save.ValidateSlot(name)` checks a slot name from outside the game, such as a cloud listing, against the same rules before it reaches a `Backend`. A `Backend` that wraps another, such as `liveops.CloudSyncer.Backend()`, can expose it with an `Unwrap() Backend` method; a settings store built on the wrapper then keeps settings exactly where it would on the wrapped backend. ## Versioned envelopes and migrations Every slot is written inside a `{"version": N, "data": ...}` envelope. When your save schema evolves, bump `WithVersion(N)` and register one-step `Migration` functions (`v -> v+1`) with `WithMigration`, `WithMigrations`, or `RegisterMigration`: ```go store := save.NewFileStore(cx.DataDir(), save.WithVersion(2), save.WithMigration(1, func(raw json.RawMessage) (json.RawMessage, error) { var v1 struct { Level int `json:"level"` Gold int `json:"gold"` } if err := json.Unmarshal(raw, &v1); err != nil { return nil, err } return json.Marshal(Progress{ Level: v1.Level, Coins: v1.Gold, // renamed field Name: "Adventurer", }) }), ) ``` When `Load` reads an older version, it upgrades the JSON one version at a time (`1 -> 2 -> 3 ...`) before unmarshaling into `dst`. `Load` does not write the migrated save back, so migrations run again on every `Load` until the slot is saved: each one must be a pure function of its input that gives the same result every time. An envelope with any field besides `version` and `data`, or with either field given twice, is `ErrCorrupt`. Sentinel errors to check with `errors.Is`: | Error | Meaning | | --- | --- | | `ErrNotFound` | No primary or backup save exists for that slot. | | `ErrInvalidSlot` | Slot name is empty or unsafe for keys/file paths. | | `ErrFutureVersion` | Save was written by a newer schema version than `Store.Version`. | | `ErrMissingMigration` | Store lacks a migration step needed to reach `Store.Version`. | | `ErrCorrupt` | Stored payload is not a valid save envelope. | ## Atomic writes and backup recovery `Save` marshals the payload completely before touching the backend, so marshaling errors leave existing saves untouched. Before replacing a slot's primary copy, both built-in backends preserve the previous valid primary as a backup: - **`FileBackend`**: writes to a temporary file in the same directory, syncs it to disk, backs up the existing `.json` to `.json.bak`, atomically renames the temp file into place, and syncs the directory; a failed directory sync is returned as a write error, except on file systems that cannot sync a directory at all (`EINVAL` or `ENOTSUP`, as some network and FUSE mounts report), where the sync is skipped. The first write through a backend removes `.save-*.tmp` files an interrupted write left more than an hour ago. - **`StorageBackend`**: writes the backup key before updating the primary key, so a `*core.StorageFullError` leaves the last good save intact. On `Load`, if the primary copy is missing, unreadable, or corrupt, `Store` automatically falls back to the backup copy. It rewrites the primary from the backup only when the primary is missing or is not a JSON object at all (empty, truncated or garbage). A primary that failed to read for another reason, such as a permission or I/O error, or that is a JSON object `Load` cannot use, is left in place, since it may be newer than the backup. If the primary carries a version newer than `Store.Version`, even with envelope fields this build does not know, `Load` returns `ErrFutureVersion` without silently downgrading to an older backup. ## Load errors and checks An error about a copy's contents is a `*loaderr.Error` (see [Errors](https://game.nsgo.dev/docs/errors/)) that names the copy, the line in the stored JSON, the field, such as `data.items[1]`, and a fix. A `FileBackend` copy is named by its file, such as `saves/slot1.json` or `saves/slot1.json.bak` for the backup, and a `StorageBackend` copy by its storage key; a custom `Backend`'s copy by its slot, `slot1 (backup)` for the backup. The sentinels above still match it with `errors.Is`. `LoadChecked` is `Load` with a check of the decoded value. A copy the check refuses is treated as corrupt, so the backup is tried, decoded into the value `dst` held before the call rather than over what the refused copy left; when every copy fails, `dst` keeps that value; when the check returns a `*loaderr.Error` about a field of the value, the error gives that field's line in the stored copy, under `data`. `entities.LoadWorld` checks a world snapshot this way: ```go var snap Progress err := store.LoadChecked("slot1", &snap, func() error { if snap.Level < 1 { return loaderr.Errorf("level", "start levels at 1", "level %d is below 1", snap.Level) } return nil }) ``` --- Source: https://game.nsgo.dev/docs/scene/ # scene `game/scene` composes ordered world- and screen-space layers, hit-tests sprites and custom drawables in view coordinates, and manages scene lifecycles, overlay stacks, and animated transitions. ```go import "github.com/nsgo-dev/game/pkg/scene" ``` ## Scene, layers, and drawables A `Scene` holds a shared `*tilemap.Camera` and a slice of `*Layer` values drawn in stable ascending `Order`. Each layer operates in either `SpaceWorld` (drawn under `Scene.Camera`) or `SpaceScreen` (drawn directly in view space for HUD elements): ```go sc := scene.NewScene(cam) terrain := sc.AddLayer(scene.NewLayer("terrain", scene.SpaceWorld, 0)) terrain.AddTilemap(levelMap) actors := sc.AddLayer(scene.NewLayer("actors", scene.SpaceWorld, 10)) actors.AddBatch(actorBatch) hud := sc.AddLayer(scene.NewLayer("hud", scene.SpaceScreen, 100)) hud.AddDrawable(scene.NewDrawable(func(d *core.Drawing) { drawMinimap(d) })) ``` - **Items**: a layer accepts `AddTilemap`, `AddTileLayer`, `AddBatch`, `AddDrawable`, or an explicit `AddItem(scene.Item{...})`. Items inside a layer draw in stable ascending `Z`. - **Parallax & repeat**: `SpaceWorld` layers support `ParallaxX` / `ParallaxY` scroll factors (0 pins a layer against camera translation, 0.5 scrolls at half speed, 1.0 matches the camera, >1.0 scrolls faster for foregrounds; start with `scene.NewParallaxLayer` or `Layer.SetParallax`), `OffsetX` / `OffsetY`, and seamless tiling via `RepeatX` / `RepeatY` with `RepeatWidth` / `RepeatHeight`. YAML scenes (`game/sceneformat` version 3) expose `parallaxX`, `parallaxY`, `repeatX`, `repeatY`, `repeatWidth`, and `repeatHeight` with identical camera semantics ([Editor & Scene Format](https://game.nsgo.dev/docs/editor/)). - **Y-sorting (`DepthSort = scene.SortY`)**: sorts sprites, custom `Drawable`s, and tiles from any `tilemap.TileLayer` with `YSort: true` in one stable painter's-order list by ascending Y (with optional `SortKey` / `SpriteSortKey` overrides and per-tile `sort_origin_y` offsets). Non-Y-sorted tilemap layers before Y-sorted layers draw behind sprites, and trailing non-Y-sorted layers (such as roofs) draw above them; use `AddTileLayer(m, layer)` to bind a single tile layer to a specific scene layer. - **`Drawable`**: wraps custom `Draw`, `Update`, `Hit`, `OnPress`, and `OnTouch` hooks with its own `Z` and `Visible` flag. Its zero value has `Visible: false`; start with `scene.NewDrawable(fn)`. - **`Scene.Update(dt)`** advances `Camera`, tilemaps, and custom drawables in layer order; **`Scene.Draw(d)`** draws every visible layer while preserving `d`'s transform and paint state. ## Hit testing and input dispatch `Scene.HitTest(p)` tests view-space point `p` in reverse draw order (highest `Layer.Order`, then highest item/sprite `Z`), converting `p` via `Camera.ViewToWorld` on `SpaceWorld` layers and testing `p` directly on `SpaceScreen` layers: ```go if hit, ok := sc.HitTest(ev.Position); ok { if hit.Sprite != nil { selectUnit(hit.Sprite, hit.Point) } } ``` Use `HitTestAll(p)` to retrieve every overlapping target from topmost to bottommost. ### Custom hit shapes and callbacks By default, sprites hit-test against their transformed untrimmed frame bounds (`SpriteContains` / `SpriteToLocal`). Override hit geometry or attach direct press/touch handlers with `SetSpriteHit` (and remove with `ClearSpriteHit`): ```go sc.SetSpriteHit(&coinSprite, scene.HitOptions{ Hit: scene.SpriteLocalHit(&coinSprite, scene.CircleHit(core.Point{X: 8, Y: 8}, 7)), OnPress: func(hit scene.HitResult, ev core.PressEvent) { collectCoin() }, }) ``` Built-in `HitFunc` helpers: `RectHit(bounds)`, `CircleHit(center, radius)`, `PolygonHit(vertices...)`, and `SpriteLocalHit(sp, local)`. Set `HitOptions{Ignore: true}` to make a decorative sprite transparent to clicks and touches. Route view events directly to the topmost hit target with `sc.DispatchPress(ev)` and `sc.DispatchTouch(ev)` (when a target sets `OnPress` without `OnTouch`, `DispatchTouch` falls back to `OnPress` on `TouchStart`). ## Manager, stacks, and transitions `Manager` owns a stack of `*Controller` scenes under a parent `*core.Scope`. Every entered scene receives its own child `*core.Scope` in `Enter(cx)`, so loops, signals, timers, and audio created under `cx` are automatically disposed when the scene exits: ```go mgr := scene.NewManager(cx) play := &scene.Controller{ Scene: gameScene, Enter: func(scx *core.Scope) { // Resources owned by this scene's child scope startLevelMusic(scx) }, Pause: func() { pauseSimulation() }, Resume: func() { resumeSimulation() }, Exit: func() { cleanupLevel() }, Update: func(dt time.Duration) { gameScene.Update(dt) }, } pauseMenu := &scene.Controller{ Scene: pauseScene, Transparent: true, // draws the paused scene underneath } mgr.Switch(play, scene.Fade(400*time.Millisecond, core.RGB(0x000000))) // Later, push an overlay without exiting play: mgr.Push(pauseMenu) // Pop to resume play: mgr.Pop() ``` ### Transitions Pass a `*Transition` to `mgr.Switch(next, tr)`: | Helper | Visual behavior | | --- | --- | | `Fade(d, color)` | Fades outgoing scene to `color` over the first half, then reveals incoming scene over the second half (crossfades when `color` is transparent/0). | | `Crossfade(d)` | Crossfades directly from outgoing to incoming scene over `d`. | | `Wipe(d, dir)` | Clips scenes along an edge moving in `DirectionLeft`, `DirectionRight`, `DirectionUp`, or `DirectionDown`. | | `CustomTransition(d, draw)` | Calls your custom draw function with eased `progress` in `[0, 1]` plus `drawOld` and `drawNew`. | Set `tr.Curve` to any `core.Curve` easing function. While a transition runs (`mgr.Transitioning()`), the incoming scene enters immediately while the outgoing scene stays alive to render until completion, then exits and disposes its child scope. Drive the manager from your `game.Loop` and `core.Canvas`: ```go // In Loop.Update: mgr.Update(dt) // In Canvas.Draw (automatically subscribes to scene changes & transitions): mgr.Draw(d, size, alpha.Get()) ``` ## 2D layers over a 3D view (`Overlay3D`) `Overlay3D` renders 2D screen-space layers (`SpaceScreen`), standalone `*sprite.Batch`es, and custom draw callbacks in a transparent `core.Canvas` stacked directly over a 3D `gpu.View` (and beneath any native NSGo HUD views in `gpu.ViewProps.Children`): ```go ov := scene.NewOverlay3D(cx) ov.Scene = hudScene // draws visible SpaceScreen layers (SpaceWorld layers are skipped) ov.AddLayer(crosshair) // extra 2D layers merged by stable ascending Layer.Order ov.AddBatch(markerBatch) // standalone sprite batches drawn over the layers ov.Viewport = &screen.Viewport{Width: 320, Height: 180, Mode: screen.ModeFit} // Mount directly over a 3D gpu.View: return ov.View(cx, gpu.ViewProps{ DepthFormat: gpu.FormatDepth24Plus, OnReady: onReady, OnFrame: onFrame, Children: nativeHUDViews, // rendered above the 2D overlay canvas }) ``` - **Draw order**: visible `SpaceScreen` layers from `Scene` and visible `Layers` merge in stable ascending `Layer.Order`, followed by `Batches` in slice order and `OnDraw` (wrapped in `Save`/`Restore`). Call `Scene.DrawScreenLayers(d)` directly if you manage your own canvas. - **Transparency & virtual viewports**: the overlay canvas has no background fill so transparent regions reveal the 3D scene underneath and semi-transparent sprites alpha-blend over it. When `Viewport` is set with a zero `BarColor`, letterbox and pillarbox margins stay transparent instead of painting opaque black bars over the 3D view; set `BarColor` explicitly (such as `core.RGB(0x000000)`) to draw bars. - **Pointer pass-through & hit testing**: by default the overlay canvas sets `core.PointerEventsNone` so clicks and touches pass straight through to the 3D `gpu.View`. Set `Interactive: true` (or `OnPress`) to handle pointer events directly on the overlay canvas, or call `ov.HitTest`, `ov.HitTestAll`, `ov.DispatchPress`, and `ov.DispatchTouch` manually with the view size. - **3D-to-2D projection**: map a 3D world position through a column-major view-projection matrix (such as `cam.ViewProj()` from `game/scene3d`) into 2D overlay coordinates with `scene.ProjectToOverlay(cam.ViewProj(), p.X, p.Y, p.Z, viewW, viewH)` (or `ov.Project(cam.ViewProj(), p.X, p.Y, p.Z, windowSize)` to convert into `ov.Viewport`'s virtual coordinates) so 2D health bars, reticles, and markers track 3D objects accurately. Call `ov.Invalidate()` (or `ov.SetHidden(bool)`) whenever dynamic 2D overlay state changes. ## Native HUD over a 3D view (`HUD3D`) `HUD3D` composes native NSGo views (`ui.Button`, `ui.Card`, `ui.Badge`, `ui.Progress`, `ui.Switch`, `core.Text`, and custom `core.View` trees) over a 3D `gpu.View` with automatic safe-area insets, reactive visibility toggling, and mouse/touch pass-through: ```go hud := scene.NewHUD3D(cx) hud.Padding = core.All(12) // Decorative readout: mouse and touch pass straight through to the 3D scene. hud.AddPassThrough(scene.HUDTopLeft, ui.Badge{Text: "HP 100"}) // Interactive controls anchored to safe-area corners: hud.AddAt(scene.HUDTopRight, ui.Button{ Text: "Pause", OnPress: togglePause, }) hud.AddAt(scene.HUDBottomRight, ui.Button{ Text: "Jump", OnPress: triggerJump, }) // Mount directly over a 3D gpu.View: return hud.View(cx, gpu.ViewProps{ DepthFormat: gpu.FormatDepth24Plus, OnReady: onReady, OnFrame: onFrame, OnPress: pick3DObject, }) ``` - **Mouse and touch pass-through**: the HUD overlay container uses `core.PointerEventsBoxNone` so interactive HUD controls handle clicks and touches directly while open regions pass mouse and touch events unobstructed to the 3D view underneath. Mark decorative elements (such as crosshairs or score readouts) with `AddPassThrough` (or `HUDSlot{PassThrough: true}`) to apply `core.PointerEventsNone`. - **Anchors & custom layouts**: place widgets with `AddAt` / `AddPassThrough` / `AddSlot` at any of the 9 safe-area anchors (`HUDTopLeft`, `HUDTopCenter`, `HUDTopRight`, `HUDCenterLeft`, `HUDCenter`, `HUDCenterRight`, `HUDBottomLeft`, `HUDBottomCenter`, `HUDBottomRight`) or `HUDFull`, or add custom pass-through containers directly with `Add` / `Children`. - **Safe-area insets**: `core.EnvSafeArea` padding is applied automatically (combined with `HUD3D.Padding`) so HUD controls stay clear of notches, status bars, and home indicators and adapt reactively on rotation. Set `IgnoreSafeArea: true` or call `hud.SetSafeArea(false)` to disable it. - **Visibility toggle**: call `hud.SetHidden(true)`, `hud.SetVisible(false)`, or `hud.Toggle()` to hide the HUD (`core.DisplayNone` + `core.PointerEventsNone`) without remounting HUD state; while hidden, all clicks and touches reach the 3D view. - **Composing with 3D input wrappers or 2D overlays**: use `hud.Wrap(cx, view3D)` to Z-stack the HUD as a sibling over any already-built 3D view (for example a `gpu.View` wrapped in a `core.View` handling `OnMouseDown`, `OnMouseMove`, and `OnTouch` for 3D camera orbit), or mount `hud.Layer(cx)` directly inside `gpu.ViewProps.Children` above a 2D overlay canvas. ## Switching between 2D and 3D scenes `Manager.View(opts)` mounts a reactive view host that switches seamlessly between 2D canvas scenes (`Controller.Scene` / `Controller.Draw`) and 3D or native view scenes (`Controller.View`, such as `gpu.View` or `Overlay3D.View`) while every scene shares the same `*input.Actions` and the same `*sound.Mixer`: ```go mgr := scene.NewManager(cx) actions.WatchKeys(cx) // keys reach Actions whether or not the stage holds focus mgr.Actions = actions // set before mgr.View: attached to the persistent stage view, survives 2D <-> 3D switches mixer := sound.NewMixer(cx, "game.sound") // on the Manager's scope, not a scene's, so music plays on across switches mixer.Music("music").Play(theme, 0) // started once here, so no scene owns it var overworld2D, dungeon3D *scene.Controller overworld2D = &scene.Controller{ Scene: mapScene, Update: func(dt time.Duration) { if mgr.Actions.JustPressed("enter_3d") { mgr.Switch(dungeon3D, scene.Fade(400*time.Millisecond, core.RGB(0x000000))) } }, } dungeon3D = &scene.Controller{ View: func(scx *core.Scope) core.Node { return ov.View(scx, gpu.ViewProps{ Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, DepthFormat: gpu.FormatDepth24Plus, OnReady: onReady, OnFrame: onFrame, }) }, Update: func(dt time.Duration) { if mgr.Actions.JustPressed("exit_3d") { mgr.Switch(overworld2D, scene.Fade(400*time.Millisecond, core.RGB(0x000000))) } }, } mgr.Switch(overworld2D, nil) return mgr.View(scene.HostOptions{ Alpha: func() float64 { _ = frameTick.Get(); return alpha }, Viewport: &viewport, Children: persistentHUD, }) ``` - **Stable GPU view mounting**: each entered scene receives a unique instance ID rendered via `core.Each`. Mounted 3D `gpu.View` surfaces and GPU pipelines stay alive across transition frames and across `Push`/`Pop` of 2D overlays (transparent or opaque), and unmount cleanly when the scene exits. - **View scope**: the `cx` passed to `Controller.View` is the mounted row's scope, not the scope `Enter` receives. When a scene leaves, `Exit` runs and `Enter`'s scope is disposed first, then the row and everything created under `View`'s `cx` are unmounted in the same `Switch`, `Pop`, or transition step, so no frame or `OnFrame` callback runs in between. Create the state a 3D view reads every frame in `View` or on the Manager's scope. - **Transitions across 2D ↔ 3D**: `Fade(d, color)` fades the outgoing 2D or 3D scene to `color` on a top overlay canvas over the first half, reveals the incoming scene at the midpoint (`0.5`), and fades out over the second half; `Crossfade(d)` animates outgoing/incoming wrapper `Opacity`; `Wipe(d, dir)` uses exact path clipping between 2D scenes and smooth crossfade opacity when a `Controller.View` scene is involved; `CustomTransition`, or a built-in transition whose `Draw` you replaced, draws its own frames between 2D scenes and custom overlay effects above the active view otherwise. A `Transition` with a nil `Draw` shows the incoming scene for its whole `Duration`, as `Manager.Draw` does. - **Shared input**: `Manager.View` attaches `Manager.Actions` to its persistent stage view when `View` is called, so set `Actions` first. Key events reach the stage only while it holds focus: pass `HostOptions.Ref` and call its `Focus()` once mounted (focus and pointer lock then survive every switch), or call `Actions.WatchKeys` as above. `Switch`, `Push`, and `Pop` call `Actions.Reset()` by default so transient press edges and held keys do not leak into the next scene while all bindings, axes, and pointer lock stay intact (set `Manager.KeepInputOnSwitch = true` to preserve held inputs across transitions). - **Shared sound**: the Manager needs no mixer of its own. A `sound.Mixer` created on the Manager's scope (or an ancestor of it) is not disposed when scenes exit, so background music plays on and SFX groups stay live across every 2D ↔ 3D switch while each scene reaches the mixer through its own closures. A mixer created under a scene's `Enter` scope stops with that scene. - **2D overlays & invalidation**: pushing a `Transparent: true` 2D controller over a 3D scene keeps the 3D view visible underneath while pausing its `Update` and setting `PointerEventsNone` on the paused layer. When `HostOptions.Viewport` is set, transparent pushed 2D overlays treat a zero `BarColor` as `core.Transparent` so margins do not obscure the 3D scene. Call `mgr.Invalidate()` to redraw mounted 2D canvases on demand without remounting 3D views. For a complete runnable game that switches between a 2D courtyard overworld (`scene.Scene` + `sprite.Batch`) and a 3D glTF shrine (`gpu.View`), pushes a transparent 2D pause overlay over the 3D view, and shares one `*input.Actions` and `*sound.Mixer` across transitions, see [`examples/lantern3d`](https://github.com/nsgo-dev/game/tree/main/examples/lantern3d). ## Physics in scene files Scenes authored in YAML with [`game/sceneformat`](https://game.nsgo.dev/docs/editor/#built-in-physics-components-817) can declare 2D (`body2d`, `collider2d`, `trigger2d`) and 3D (`body3d`, `collider3d`, `trigger3d`) physics components directly on objects, using named collision layers from [`game.yaml`](https://game.nsgo.dev/docs/project/). Pass a built scene to `sceneformat.BuildPhysics` to instantiate its `physics.World`, `physics.RigidWorld`, and `physics3d.World` and step them each fixed tick alongside your scene. ## 2D lighting in scene files YAML scenes can also set `ambientColor` and attach built-in `light2d` and `occluder2d` components (rect, polygon, or tilemap collision). `sceneformat.Build` constructs `BuiltScene.Lights2D` (`*lights2d.Scene`) automatically so `BuiltScene.Draw` renders the same 2D lights and shadows in the game and in the editor's lighting preview ([`game/editor`](https://game.nsgo.dev/docs/editor/#built-in-2d-lighting-and-occluder-components-887)). ## 2D navigation regions in scene files YAML scenes can declare walkable and obstacle `navregion2d` polygons directly on objects, optionally subtracting solid tilemap collision geometry (`subtractTileCollision: true`). `sceneformat.Build` bakes them via [`game/navbake`](https://game.nsgo.dev/docs/navbake/) into `BuiltScene.NavBake2D` (`*navbake.Mesh`) and `BuiltScene.NavMesh2D` (`*ai.NavMesh`), so the editor's 2D NavMesh overlay and **Test Path** tool produce the exact same path as the game ([`game/editor`](https://game.nsgo.dev/docs/editor/#built-in-2d-navigation-region-components-888)). --- Source: https://game.nsgo.dev/docs/scene3d/ # scene3d `game/scene3d` provides a 3D scene graph with dirty-propagated transforms, named sockets and typed attachments, a dynamic fat-AABB / SAH `BVH` for fast spatial queries, perspective/orthographic cameras with Orbit/FPS/ThirdPerson controllers, screen-space 3D picking, and box-projected 3D decals for the mobile forward path. ```go import "github.com/nsgo-dev/game/pkg/scene3d" ``` All transforms, projections, frustums, and rays follow [math3d](https://game.nsgo.dev/docs/math3d/) conventions (right-handed Y-up, column-major, `[0, 1]` NDC depth). ## Node hierarchy, sockets, and attachments Build hierarchies with `NewScene()` and `NewNode(name)` so transforms, visibility, layers, and bounds initialize cleanly: ```go sc := scene3d.NewScene() hero := scene3d.NewNode("hero") hero.SetPosition(math3d.Vec3{X: 0, Y: 0, Z: -4}) hero.SetLocalBounds(math3d.AABB{Min: math3d.Vec3{X: -0.5, Y: 0, Z: -0.5}, Max: math3d.Vec3{X: 0.5, Y: 1.8, Z: 0.5}}) // Define a named socket and attach a weapon node: hero.DefineSocket("hand_r", math3d.Transform{ Pos: math3d.Vec3{X: 0.4, Y: 1.1, Z: -0.2}, Rot: math3d.QuatIdentity(), Scale: math3d.Vec3One(), }) sword := scene3d.NewNode("sword") _ = hero.Attach("hand_r", sword) // Store typed gameplay metadata on any node: hero.SetAttachment("hp", 100) hp, ok := scene3d.AttachmentAs[int](hero, "hp") _ = sc.Add(hero) _, _ = hp, ok ``` Use `Reparent` / `ReparentKeepWorld`, `Detach`, `FindByName`, `FindByTag`, `Walk`, `WorldTransform()`, `WorldMatrix()`, `WorldBounds()`, and `HierarchyBounds()`. Calling `sc.UpdateTransforms()` propagates only dirty subtrees and queues the changed nodes for the scene's internal BVH; every query applies the queue first, and `sc.SyncBVH()` applies it on demand. `ReparentKeepWorld` (and `SetParent(parent, true)`) solves the new local transform from the world matrices, so the node stays exactly where it is drawn. When that local transform would need shear, as for an unrotated child under a rotated, non-uniformly scaled parent, or the new parent's scale has a zero component, it returns `ErrNotDecomposable` and leaves the node where it was in the hierarchy. ## Dynamic fat-AABB / SAH `BVH` and spatial queries `Scene` maintains a dynamic fat-AABB Bounding Volume Hierarchy (`BVH`) for fast culling and spatial queries across large scenes (10k–50k+ nodes): ```go sc.UpdateTransforms() // Frustum culling (reusing caller slice with CullFrustumInto avoids allocations): visible = sc.CullFrustumInto(cam.Frustum(), visible[:0]) // Spatial volume and ray queries: nearby := sc.QuerySphere(math3d.Sphere{Center: heroPos, Radius: 12}) inBox := sc.QueryAABB(triggerBox) hit, ok := sc.RaycastFirst(ray, scene3d.LayerAll) _, _, _, _ = nearby, inBox, hit, ok ``` Call `sc.RebuildBVH()` after bulk level loads to run a top-down Surface Area Heuristic (SAH) rebuild. You can also use `scene3d.NewBVH()` standalone (`Insert`, `Update`, `Remove`, `Rebuild`, `QueryFrustum`, `QueryAABB`, `QuerySphere`, `Raycast`, `RaycastAll`). ## Cameras and controllers Create perspective or orthographic cameras with `NewPerspectiveCamera` / `NewOrthographicCamera` (or sync a camera to a scene node via `cam.SyncFromNode(node)`), and drive them with one of the three built-in controllers: | Controller | Constructor | Key methods | | --- | --- | --- | | `OrbitController` | `NewOrbitController(target, dist)` | `Orbit`, `Zoom`, `Pan`, `SetTarget`, `SetAngles`, `Snap`, `Update(cam, dt)` | | `FPSController` | `NewFPSController(pos)` | `Look(dYaw, dPitch)`, `Move(fwd, right, up, dt)`, `Apply(cam)` (`Grounded` locks horizontal motion to XZ) | | `ThirdPersonController` | `NewThirdPersonController()` | `Snap`, `Update(cam, targetPos, targetForward, dt)` with `ObstructionCheck` | ```go cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 3, Z: 8}, math3d.DegToRad(60), 16.0/9.0, 0.1, 300) tp := scene3d.NewThirdPersonController() tp.ObstructionCheck = scene3d.SceneObstructionCheck(sc, scene3d.LayerDefault, hero) // In game.Loop.Update: tp.Update(cam, heroPos, heroForward, dt) ``` ### Projection, viewport and interpolation A camera's `Projection` is either perspective (`FOVY`, in radians) or orthographic (`OrthoHeight`, the visible height in world units), with `Aspect`, `Near` and `Far`; `ViewMatrix`, `ProjMatrix` and `ViewProj` give the matrices with [0, 1] clip depth, as WebGPU, Metal and Direct3D expect. Call `cam.SetViewport(width, height)` when the drawable resizes so `Aspect` follows it; sizes that are not positive and finite (zero, negative, NaN or infinite) leave the camera unchanged. `cam.Eye()` returns the homogeneous eye point: `(Pos, 1)` for a perspective camera and `(-Forward, 0)` for an orthographic one, whose eye lies at infinity, so a shader finds the direction toward the viewer as `normalize(eye.xyz - p * eye.w)` under both. Step the camera in `game.Loop.Update` and draw it interpolated in `Draw`: keep the camera from the previous update and draw `prev.Lerp(cam, alpha)`. `Lerp` blends `Pos` linearly, `Rot` by shortest-path slerp and the projection's fields linearly between the values `Matrix` uses, so a field left at zero blends from its default rather than from zero; projections of different kinds do not blend, so the first holds until `t` reaches 1. ```go prev := *cam loop := &game.Loop{ Update: func(dt time.Duration) { prev = *cam orbit.Update(cam, dt) }, Draw: func(alpha float64) { drawn := prev.Lerp(cam, float32(alpha)) camBuf.WriteCamera(&drawn) // render3d.CameraBuffer // record and submit draws }, } ``` ## 3D picking Attach a `Collider` (`*MeshCollider` or `*SphereCollider`) to pickable nodes (or fall back to `LocalBounds`) and pick directly from pointer coordinates. A node's world bounds cover both its `LocalBounds` and its collider. `MeshCollider` caches its own bounds and notices when `Triangles` is replaced, but the node's world bounds and BVH entry refresh only when the node is marked dirty: after replacing `Triangles` call `node.MarkDirty()` (or assign the collider again with `node.SetCollider`), and after editing vertices in place call both `collider.MarkDirty()` and `node.MarkDirty()`. Visibility filtering is memoized per query, so hits deep in a hierarchy do not each walk every ancestor. ```go if hit, ok := scene3d.Pick(sc, cam, pointerX, pointerY, viewW, viewH, scene3d.LayerAll); ok { fmt.Printf("picked %s at %v (tri %d)\n", hit.Node.Name, hit.Point, hit.TriangleIndex) } ``` Use `PickAll` when you need every hit sorted front-to-back along `cam.ScreenRay(screenX, screenY, viewW, viewH)`, and `cam.WorldToScreen` to project 3D points into 2D viewport coordinates. ## Box-projected 3D decals Place impact marks, scorches, blob shadows, and splats onto scene geometry with `Decal`, `DecalPool`, `ProjectDecal`, and `GPUDecalRenderer`. Decals project along their local `-Z` axis onto surfaces facing `+Z`, using BVH box overlap and 6-plane Sutherland–Hodgman polygon clipping to emit forward-path triangle geometry—no deferred G-buffer, compute shaders, or depth-buffer readback are needed, so decals run identically on WebGPU, Metal, Vulkan, OpenGL ES 3.0, and WebGL 2. - **Normals and angle fade**: surfaces within `AngleFadeStart` receive full opacity; surfaces between `AngleFadeStart` and `AngleFadeEnd` fade smoothly by surface normal; perpendicular and back-facing surfaces are discarded so decals never bleed onto side or rear faces. `DepthFade` fades smoothly near the front and back faces of the projection box. - **Layer masks**: `Decal.LayerMask` filters receiver nodes against `Node.Layer` (`LayerAll` matches everything, `0` matches nothing); hidden and disabled subtrees are skipped automatically. Any node with a `*MeshCollider` or an attached `DecalReceiver` (`node.SetDecalReceiver(&scene3d.DecalReceiverMesh{...})`) can receive decals. - **Fixed-capacity pool**: `NewDecalPool(maxDecals)` caps the live decal count with deterministic eviction (lowest `SortOrder`, then oldest spawn order), ages and expires decals in `Step(dt)` with `FadeIn`/`FadeOut`, and reuses scratch buffers so steady-state `Spawn`, `Step`, and `BuildGeometry` allocate zero times per frame. ```go pool := scene3d.NewDecalPool(64) // Place a red impact mark from a raycast hit, excluding character layers: mark := scene3d.NewDecalOnSurface(hit.Point, hit.Normal, math3d.Vec3Up(), math3d.Vec3{X: 0.35, Y: 0.35, Z: 0.25}) mark.Albedo = core.RGB(0xdd2222) mark.LayerMask = scene3d.LayerDefault mark.Lifetime = 10 * time.Second mark.FadeOut = 2 * time.Second pool.Spawn(mark) // Each update & frame: pool.Step(dt) var geom scene3d.DecalGeometry pool.BuildGeometry(sc, &geom) _ = decalRenderer.Upload(&geom) // Inside the forward render pass after opaque geometry: decalRenderer.DrawWithCamera(pass, camBuf.BindGroup()) ``` Create `GPUDecalRenderer` once in `gpu.View`'s `OnReady` with `NewGPUDecalRenderer(cx, dev, opts)`. Pass `render3d.CameraBuffer.Layout()` as `CameraLayout` to share the frame's camera bind group (`DrawWithCamera`), or leave `CameraLayout` nil to use the renderer's own camera buffer (`WriteCamera` + `Draw`). Bind custom textures per `Decal.TextureID` with `SetTexture` or `UploadTextureRGBA`; consecutive batches sharing a texture merge into a single `DrawIndexed` call. --- Source: https://game.nsgo.dev/docs/scenemodel/ # scenemodel `game/scenemodel` gives the objects of a [scene file](https://game.nsgo.dev/docs/editor/) their 3D look, so a 3D level is a text file a person or an AI can edit and review, as a 2D one is, instead of being assembled in Go. An object names a built-in primitive in `mesh`, a glTF 2.0 model in `model`, or a modular 3D grid map in `gridMap`, and `scenemodel.Build` turns the scene into a `scene3d` node tree whose nodes carry their geometry, materials and bounds, ready for `render3d.Queue` or the package's own `Renderer`. ```go import "github.com/nsgo-dev/game/pkg/scenemodel" ``` ## Fields ```yaml version: 2 name: Courtyard layers: - name: level objects: - id: floor scaleX: 6 scaleZ: 6 mesh: plane material: materials/stone.material.yaml - id: crate x: -1 "y": 0.5 rotY: 0.4 model: models/crate.glb - id: lid x: 1.5 "y": 0.1 model: models/crate.glb modelNode: Lid - id: ball x: 0.9 "y": 0.5 mesh: sphere material: materials/teal.material.yaml ``` | Field | Meaning | | --- | --- | | `mesh` | A built-in primitive: `box` (1 on each side), `sphere` (1 across), `plane` (1 by 1 in the XZ plane, facing +Y), `cylinder` (1 across and 1 tall) or `capsule` (1 across and 2 tall), centered on the object's origin with the round axis along Y, sized like Godot's default meshes so that the object's scale reads as meters. Any other value is refused. | | `model` | Version 2. The glTF 2.0 model the object draws: a `.gltf` file, whose separate buffers and images are read from beside it, or a `.glb`, named by its slash-separated path from the project root. Without `modelNode` or `modelMesh` the object draws every node of the model's default scene (or of its first scene, or every parentless node when it has none), each as a child node of the object with its glTF transform. It cannot be combined with `mesh`. | | `modelNode` | Version 2, with `model`. The first node of the model with this name, drawn on the object's node with its descendants as child nodes; the object's transform replaces the node's own. | | `modelMesh` | Version 2, with `model`, not with `modelNode`. The first mesh of the model with this name, drawn at the object's origin. | | `gridMap` | Version 2. A modular 3D [`*.gridmap.yaml` file](https://game.nsgo.dev/docs/world3d/#modular-3d-gridmap), named by its slash-separated path from the project root. `Build` loads the grid map and its glTF `meshLibrary`, calls `world3d.GridMap.BuildInstances`, creates child nodes for each tile instance sharing `MeshID` and `MaterialID`, and sets the object node's `LocalBounds` from `GridMap.Bounds()`. Cannot be combined with `mesh` or `model`. | | `material` | A [material file](https://game.nsgo.dev/docs/resources/). On a primitive it is the surface, white, non-metallic and fully rough without one; on a model or grid map it replaces every material of the model or tile library. Its base color and emissive colors are sRGB and are converted to linear light, its opacity multiplies the base color's alpha and blends the surface when below 1, and its `metallic`, `roughness`, `doubleSided` and `texture` are used as written. Its 2D blend mode and `unlit` do not apply in 3D. | | `occluder` | Version 2. Marks the object as a 3D occluder for `render3d.OcclusionBuffer`: `{ mode: model }` uses the object's `mesh` or `model` geometry (at its coarsest LOD when available), and `{ mode: box, center: [x, y, z], size: [w, h, d] }` uses an explicit box in the object's local space (defaulting to centered `[1, 1, 1]`). Optional `doubleSided: true` rasterizes both faces. | An override (`overrides`) can replace each of these fields on an object of an instanced or inherited scene. The merged object must still follow the rules above, so an override that turns a primitive into a model or grid map writes `mesh: ""` beside its `model` or `gridMap`, and one that keeps a `modelNode` or `modelMesh` while it changes `model` needs that part in the new model. `scene.v2.json` describes them for editors and AI tools ([schemas](https://game.nsgo.dev/docs/schemas/)). ## LOD levels and occluders (#904) `scenemodel.Build` populates `DrawItem.LODs` and extracts occluder geometry so a level authored in YAML gets both level-of-detail switching and software occlusion culling without Go glue code: - **Naming convention**: sibling glTF nodes or meshes sharing a base name with `_LOD1`, `_LOD2`, … suffixes (parsed by `gltf.ParseLODNodeName`, case-insensitive and ignoring Blender `.001` suffixes) are paired with the base (`_LOD0` or unsuffixed) mesh automatically. Unconfigured thresholds default to `scenemodel.DefaultLODScreenRatio` (`0.25`, `0.10`, `0.04`, `0.015`, with the coarsest level at `0`). - **Import sidecar (`*.import.yaml`)**: when the resolver implements `ImportSettingsResolver` (as `scenemodel.Assets` does), `Build` reads `.import.yaml` (`importsettings.Model.LODs` and `LODHysteresis`). Each LOD entry sets `minScreenRatio` (projected bounding-sphere diameter / viewport height) and/or `maxDistance`, and may either override thresholds for discovered `_LODn` siblings or point explicitly at a `node`, `mesh`, or separate `.gltf`/`.glb` `model` file. - **Occluders**: objects with `occluder` become `Built.Occluders`. Call `Built.AppendOccluders(dst)` or `Built.RasterizeOccluders(buf, viewProj)` to feed a `render3d.OcclusionBuffer` directly; `scenemodel.Renderer` automatically rasterizes `Built.Occluders` into an internal `render3d.OcclusionBuffer` in `Prepare` (unless `RendererOptions.DisableOcclusion` is set) and exposes the resulting `render3d.RenderPlan` (including `Stats.Occluded`) via `Renderer.Plan()`. ## Building ```go assets := scenemodel.NewAssets(os.DirFS(projectRoot)) // or an embed.FS rooted at the project doc, err := sceneformat.ParseWith(data, sceneformat.ParseOptions{File: "scenes/level.scene.yaml"}) if err != nil { return err } world := scene3d.NewScene() built, err := scenemodel.Build(doc, world.Root(), assets) if err != nil { return err } ``` `Build` builds the layers and objects as `sceneformat.BuildNodes3D` does and then gives each object its look, lights, cameras and scene environment. It loads models through a `ModelResolver`, as `sceneformat.Build` loads materials through a `MaterialResolver`; the resolver must also be a `GridMapResolver` when an object names a `gridMap` file, a `sceneformat.MaterialResolver` when an object names a material file, an `ImageResolver` when that file names a texture, an `ImportSettingsResolver` for model LOD sidecars, and an `HDRResolver` when `environment.sky.kind` is `hdr`. `Assets` implements all six over a project's files: models load with `gltf.LoadFS`, grid maps with `world3d.ParseGridMapWith`, material files through a `resource.Library`, images decode as PNG or JPEG, sidecars parse with `importsettings.Parse`, and Radiance HDR skies decode with `render3d.DecodeHDR`, each once. A scene that instances or inherits others must go through `sceneformat.Resolve` first. On any error, such as a model that does not load, an HDR sky that fails to decode, a `modelNode` it does not have, or a grid map referencing an unknown tile, `Build` returns it with the layer and object and leaves the parent untouched. The result, a `Built`, holds the layer and object nodes (`Layers`, `Objects`), any built `*world3d.GridMap` instances keyed by object ID (`GridMaps`), any built `Occluders`, the `Drawables`, any 3D `Lights`, any 3D `Cameras`, and the built `Environment` (sky cubemap or clear color, prefiltered IBL and spherical harmonics, fog, exposure and tone mapping): every node that draws is an object's node, a node made for a node of its model, or an instanced tile of its grid map. `Built.ActiveCamera(aspect)` builds the `scene3d.Camera` for the active visible 3D camera (`current: true`, or the first visible 3D camera), `Built.LightRig()` collects the visible lights' current world positions and `-Z` directions into a `render3d.LightRig`, and `Built.HasSceneLighting()` reports whether the scene defines its own lights or environment. Each drawable lists its `Parts`, one per glTF triangle primitive or one for a primitive shape, with the triangle `Mesh` in the node's space and its `Material`. Parts that draw the same geometry share a `MeshID` and parts with the same material a `MaterialID`, so a renderer uploads each once. Each drawing node's `LocalBounds` is set from its geometry, and its `*Drawable` is stored as the attachment `scenemodel.AttachmentKey`, so picking or an editor can find what a node draws. A model draws in its bind pose with its meshes' default morph weights applied. Triangle strips and fans are unrolled into lists, a primitive without normals is flat-shaded as glTF says, and the base color texture's UV set and `KHR_texture_transform` are applied to the UVs. Skins, cameras, lights, animations, vertex colors, points and lines are not used. ## Drawing `Built.AppendDrawItems` appends a `render3d.DrawItem` for every part of every visible, enabled node, with the node's world matrix, the part's world bounds and its mesh, material and pipeline IDs, for a game's own `render3d.Queue`. `Built.Part` maps an item's ID back to its drawable and part. `Renderer` draws a `Built` on a `gpu.Device`: it uploads every mesh, texture, sky cubemap, IBL prefilter and shadow map once. Each frame, call `PrepareScene(cam)` to upload the camera, the scene's lights (`Built.LightRig`), shadows, fog, IBL and tonemapping (or `Prepare(cam, lights)` to override with a custom `render3d.LightRig`), call `RecordShadows(frame)` before the main render pass when any light casts shadows, clear with `ClearColor(fallback)`, and call `DrawSky(pass)` followed by `Draw(pass)` inside the render pass: ```go r, err := scenemodel.NewRenderer(cx, dev, built, scenemodel.RendererOptions{}) if err != nil { return err } // Each frame: cam, _ := built.ActiveCamera(aspect) if _, err := r.PrepareScene(cam); err != nil { return err } r.RecordShadows(frame) pass := frame.BeginRenderPass(gpu.RenderPassDesc{ ColorAttachments: []gpu.ColorAttachment{{LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: r.ClearColor(core.RGB(0x10141c))}}, DepthStencil: &gpu.DepthStencilAttachment{DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreDiscard, ClearDepth: 1}, }) r.DrawSky(pass) r.Draw(pass) pass.End() ``` Its shader (`ShaderWGSL`) combines render3d's metallic-roughness direct lighting, directional/spot/point shadow maps, image-based lighting (IBL), distance and height fog, and scene tone mapping and exposure (`none`, `reinhard`, `aces`, `neutral`, `agx`), with base color textures, alpha cutouts, double-sided surfaces lit from the side the viewer sees, and alpha blending. Moving, hiding or showing a node (including a light or camera node) takes effect on the next `PrepareScene` or `Prepare`. The editor's 3D viewport draws a scene's build with the same `Renderer` pipeline so lights, shadows, sky, fog, tonemapping and the active 3D camera match the game's first frame ([Editor](https://game.nsgo.dev/docs/editor/#3d-viewport-890)). `SetShading` switches how `Draw` shades the parts: `ShadingLit`, the default, or `ShadingUnlit`, which draws each surface at its textured base color plus its emissive color and ignores the lights, as an editor's unlit view does; its pipelines are created on the first switch to it. ## Checking and moving - `game check` reports a model or grid map that is missing or does not load, a `modelNode` or `modelMesh` the model does not have, and a missing or undecodable `environment.sky.hdr` image, at the scene file and line that names it, including what an override of an instanced or inherited scene changes, at the override; a model's load error, a buffer or image a `.gltf` file names that is missing, or an invalid `meshLibrary` / unknown tile in a `.gridmap.yaml` file is reported against that asset file ([CLI](https://game.nsgo.dev/docs/cli/)). - `game mv`, `game index` and the editor's `MoveFile` treat `model`, `gridMap`, a grid map's `meshLibrary` and `environment.sky.hdr` as references: moving a model, grid map or HDR sky rewrites every scene, override and `.gridmap.yaml` file that names it, and moving a `.gltf` file's buffer or image rewrites the `.gltf` file, percent-encoding the new name as glTF requires ([Project File](https://game.nsgo.dev/docs/project/)). ## Example [Lantern 3D](https://github.com/nsgo-dev/game/tree/main/examples/lantern3d) loads its level from `assets/shrine.scene.yaml`, which names its glTF diorama, builds it with `Build`, animates two of the model's nodes through the `scene3d` nodes `Build` made for them and draws the parts with its own fog shader. --- Source: https://game.nsgo.dev/docs/schemas/ # Schemas for YAML files Every file a game's author writes is YAML text, and each format has a JSON Schema so editors and AI tools can complete keys, show each field's description on hover and flag mistakes while the file is being written, before the game loads it. ```go import "github.com/nsgo-dev/game/pkg/tooling/jsonschema" ``` ## Published schemas | Format | Schema | Files | | --- | --- | --- | | Scene, version 1 | `https://game.nsgo.dev/schemas/scene.v1.json` | `*.scene.yaml`, read by `sceneformat.Parse` | | Scene, version 2 | `https://game.nsgo.dev/schemas/scene.v2.json` | `*.scene.yaml` that instance or inherit other scene files, name glTF models, place particle emitters, or hold layered tilemaps or LDtk levels, read by `sceneformat.Parse` | | Scene, version 3 | `https://game.nsgo.dev/schemas/scene.v3.json` | `*.scene.yaml` with parallax or repeating layers or tilemap offsets (and all version 2 features), read by `sceneformat.Parse` | | Scene, version 4 | `https://game.nsgo.dev/schemas/scene.v4.json` | `*.scene.yaml` with 3D lights, scene environment (sky, ambient/IBL, fog, tonemapping, exposure), 3D cameras, reflection probes, or light probe grids (and all version 3 features), read by `sceneformat.Parse` | | Light probe grid, version 1 | `https://game.nsgo.dev/schemas/lightprobes.v1.json` | `*.probes.yaml` baked by the editor and named by `lightProbeGrid.data`, read by `render3d.ParseLightProbeGrid` and `render3d.LoadLightProbeGridFS` | | Tileset, version 1 | `https://game.nsgo.dev/schemas/tileset.v1.json` | `*.tileset.yaml`, read by `tilemap.ParseTileset` and `tilemap.LoadTilesetFS` | | Import settings, version 1 | `https://game.nsgo.dev/schemas/import.v1.json` | `*.import.yaml` beside an asset, read by `importsettings.Parse`, by `game assets` and, for its credit, by `game release` and `game credits` ([Command Line](https://game.nsgo.dev/docs/cli/#assets)) | | Generated asset source, version 1 | `https://game.nsgo.dev/schemas/source.v1.json` | `*.source.yaml` beside a generated asset, written when picking a candidate in the editor and checked for licenses by `credits` and `game release`, read by `importsettings.ParseAssetSource` | | Voxel world, version 1 | `https://game.nsgo.dev/schemas/voxel.v1.json` | `*.voxel.yaml`, read by `voxel.Parse` and `voxel.LoadYAML` | | Localization string table, version 1 | `https://game.nsgo.dev/schemas/l10n.v1.json` | per-locale `*.yaml` files such as `locales/en.yaml`, read by `l10n.ParseYAML` and `l10n.Catalog.LoadYAML` | | Terrain definition, version 1 | `https://game.nsgo.dev/schemas/terrain.v1.json` | `*.terrain.yaml`, read by `world3d.ParseTerrain` and `world3d.LoadTerrainFS` | | 3D grid map, version 1 | `https://game.nsgo.dev/schemas/gridmap.v1.json` | `*.gridmap.yaml`, read by `world3d.ParseGridMap` and `world3d.LoadGridMapFS` | | 3D foliage layers, version 1 | `https://game.nsgo.dev/schemas/foliage.v1.json` | `*.foliage.yaml`, read by `world3d.ParseFoliage` and `world3d.LoadFoliageFS` | | Navigation mesh, version 1 | `https://game.nsgo.dev/schemas/navmesh.v1.json` | `*.navmesh.yaml` that `game navmesh` bakes and a scene's `navMesh` names, read by `navbake3d.Parse` and `navbake3d.LoadFS` ([navbake3d](https://game.nsgo.dev/docs/navbake3d/)) | | Project file, version 1 | `https://game.nsgo.dev/schemas/game.v1.json` | `game.yaml` at the project's root, read by `project.Parse` | | Behavior tree, version 1 | `https://game.nsgo.dev/schemas/bt.v1.json` | `*.bt.yaml`, read by `ai.ParseBehaviorTree` and `ai.LoadBehaviorTreeFS` | | Cutscene, version 1 | `https://game.nsgo.dev/schemas/cutscene.v1.json` | `*.cutscene.yaml` video cutscenes, read by `cutscene.Parse` | | Cutscene, version 2 | `https://game.nsgo.dev/schemas/cutscene.v2.json` | `*.cutscene.yaml` video or timeline cutscenes, read by `cutscene.Parse` | | Playtest configuration, version 1 | `https://game.nsgo.dev/schemas/playtest.v1.json` | `playtest.yaml`, read by `playtest.ParseConfig`, `nsgo game playtest` and `game_playtest` ([playtest](https://game.nsgo.dev/docs/playtest/)) | | Game UI screen, version 1 | `https://game.nsgo.dev/schemas/screen.v1.json` | `*.screen.yaml`, read by `gameui.ParseScreen` and `gameui.LoadScreenFS` | | Sprite state machine, version 1 | `https://game.nsgo.dev/schemas/states.v1.json` | `*.states.yaml`, read by `animclip.ParseStateMachine` and `animclip.FSStates` | | Particle emitter (2D), version 1 | `https://game.nsgo.dev/schemas/particles.v1.json` | `*.particles.yaml` / `*.emitter.yaml`, read by `particles.UnmarshalConfigYAML` and `particles.LoadConfigFS` | | Data table | generated per row type with `datatable.Schema[T]` | `*.yaml`, read by `datatable.LoadYAML` | The other formats get their schemas as their YAML loaders land: mod manifests (#474), the project file (#488), shared resources (#485), skeletal rigs (#475) and localization tables (#473). A schema's URL names its format's version. A file that says `version: 1` keeps validating against `scene.v1.json` (which refuses keys versions 2, 3 and 4 added), a `version: 2` file validates against `scene.v2.json` (which refuses keys versions 3 and 4 added), and a `version: 3` file validates against `scene.v3.json` (which refuses keys version 4 added), now that `scene.v4.json` is published beside them; `Encode` names the schema of the document's own version. ## Pointing an editor at a schema A scene file names its schema on its first line, and `sceneformat.Encode` writes that line on every save: ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/scene.v1.json version: 1 name: Cave Room ``` The comment is read by the YAML language server (`yaml-language-server`) that VS Code's YAML extension (`redhat.vscode-yaml`) runs, as do Neovim, Helix and Zed when set up with it, so the file validates with nothing else to set up. `Parse` ignores it like any other comment. `importsettings.Encode` writes the same kind of line, naming `import.v1.json`, at the top of an import settings sidecar. For files without the comment, map a pattern to the schema in the editor's settings instead, such as VS Code's `.vscode/settings.json`: ```json { "yaml.schemas": { "https://game.nsgo.dev/schemas/scene.v1.json": "*.scene.yaml" } } ``` ## What a schema checks The scene schema is generated from the Go types `sceneformat.Parse` decodes into, so its keys, types and descriptions are the code's: - `version` is required and must be `1`. - Every object refuses keys it does not define, as `Parse` does, so a misspelt key is flagged where it is written. - Each property's description is its Go doc comment. - Each number stays within what its Go type holds, such as a `float32` coordinate below about 3.4e38 and an `int` `order` within 64 bits, so a value `Parse` would overflow is flagged. - The constraints a type cannot say come from a `schema` struct tag on the field: required keys (`version`, a layer's `name`, an object's `id`, a sprite's `atlas` and `frame`, camera bounds' `width` and `height`), the allowed `space` values, and number ranges such as `alpha` in [0, 1] and a positive `zoom`. A schema sees one file at a time, so `Parse` still checks what spans the document: unique layer names and object IDs, tilemap `ref`s that name an entry of `tilemaps`, one tilemap mode at a time, inline grid sizes, and colors `core.ParseColor` accepts. In a few places the schema is stricter than `Parse`, such as refusing `null` for a field `Parse` reads as its zero value; every scene `Encode` writes validates against it, which a fuzz test holds. The import settings schema likewise checks each field on its own: known keys, the allowed `filter`, `format` and audio `format` values, non-negative sizes, rates, paddings and model scales, and a credit's required `author` and `license`. It does not say which fields go together, since the schema generator emits no `oneOf`, `not` or dependency keywords and a loop's end cannot be compared with its start in JSON Schema, so `importsettings.Parse` and `game assets` still refuse a sidecar with no section or with more than one of `image`, `audio`, `font` and `model`, `peakDB` together with `rmsDB`, a font's `chars` holding a control character, a loop whose end is not after its start, a loop with `aac` or `mp3` output, and a `license` that is not an SPDX license expression, while an editor shows such a file as valid. ## Checking schemas in CI `cmd/gameschema` writes the published schemas into `apps/website/public/schemas`, which the website serves at `https://game.nsgo.dev/schemas/`. After changing a format's Go types or doc comments, regenerate them from the repository root: ```sh go run ./cmd/gameschema ``` The Check workflow runs `go run ./cmd/gameschema -check`, which fails when a committed schema differs from what the Go types generate, when one is missing, or when the directory holds a schema it no longer generates. A test in `cmd/gameschema` does the same check under `go tool nsgo test`. ## Checking formats in CI A schema checks a file someone writes; a format's tests check the code that reads and writes it. Every package that reads a YAML format runs the shared checks of `internal/formattest` from a `conformance_test.go`, on testdata files in the format's canonical form, the bytes its encoder writes: ```go func TestFormatConformance(t *testing.T) { formattest.Run(t, formattest.Format[*quest.Book]{ Decode: quest.Parse, Encode: quest.Encode, Files: []string{"testdata/*.yaml"}, Doc: "quest", }) } ``` For each file, the checks require that: - loading and saving it gives back the same bytes; - saving the same value again, saving a second load of the file and saving a load of what was saved all give the same bytes, so the output never depends on map order, the time or randomness; - loading refuses the file with an extra top-level key, without its `version`, with `version: 0` and with the version after the newest one the format reads, with an error that names the key. `Doc` names the format's entry on [File Formats](https://game.nsgo.dev/docs/formats/), the line `` before its heading in `docs/en/formats.md` and `docs/zh/formats.md`, and `Run` fails when either page lacks the entry or the entry has a YAML example that does not load and save to the same bytes, printing what the format saves for it. The path before an optional `#name` must be the package's, and a package with two formats names the second one, as in `achievements#progress`. `TestFormatsPage` at the repository root checks the rest of the page: that both languages list the same entries in the same order; that every entry that is no `Doc` is in its `codeFormats` list with the declaration that reads the format, which the package must still declare, and that the entry's JSON or Yarn examples load with that reader; that every package that decodes JSON has an entry unless its `notJSONFormats` list says why; and that every exported integer constant whose name ends in `Version` maps to an entry in its `formatVersions` list. `Doc` may be a string literal or a string constant, so the test can read it. `TestFormatPackagesRunConformance` at the repository root fails when a package decodes YAML with `go.yaml.in/yaml/v3`, however leniently, and none of its tests calls `formattest.Run`, so `go tool nsgo test` in CI fails a new format that skips the checks. A package that decodes YAML without defining a format of its own, such as `loaderr`, is listed in the test's `notFormats` with the reason. The test looks at whole packages, so a package with a second format must run the checks on that one too; one call satisfies it. A hand-written fixture whose comments or layout other tests rely on stays as it is, and its canonical form goes in a file of its own, such as `testdata/canonical/`, for the checks. A format whose version is under another key, such as a mod manifest's `manifestVersion`, sets `VersionField`, and one that reads several versions sets `MaxVersion`. To add a testdata file, write the document, then run the test once with `FORMATTEST_UPDATE=1`, which rewrites each file with what the format saves for it before checking it; comments the encoder does not write are dropped. ## Data table schemas A data table's rows are a game's own Go type, so `datatable.Schema[T]` builds the schema for it, for the game to write next to its tables: ```go docs, err := jsonschema.PackageDocs("internal/tables") // the doc comments of the package that declares Enemy if err != nil { return err } s, err := datatable.Schema[tables.Enemy](jsonschema.Options{ ID: "https://example.com/schemas/enemies.json", Title: "Enemies", Docs: docs, }) if err != nil { return err } data, err := s.Marshal() ``` The schema describes the [YAML data table format](https://game.nsgo.dev/docs/datatable/): a mapping with a required `version`, which must be `1`, and `rows`, a list of rows that may be left out or `null` for an empty table; any other top-level key is flagged. Each row is keyed by the columns `LoadYAML` matches: a field's `table` tag, else its `json` tag, else its Go name, spelled as `MarshalYAML` writes them, and the row schema is at `#/definitions/`. A row type in which two fields share a column is an error, as it is for `LoadYAML`. A `time.Duration` cell is a string such as `"1.5s"` or an integer of nanoseconds. The schema flags a column that matches no field and a cell of the wrong type; `LoadYAML` also refuses merge keys (`<<`), which a YAML language server resolves before validating, so the schema cannot flag them. ## Building and checking schemas in Go - `jsonschema.Reflect(t, opts)` builds a draft-07 schema from a Go type: struct fields become properties named by their `yaml` tags (or by `Options.FieldName`), named structs become `definitions` shared through `$ref`, integers and `float32` are bounded by their Go type's range, and unknown keys are refused unless `Options.AllowUnknown` is set. Two fields under one key are an error unless `Options.FirstFieldWins` keeps the first. A field's `schema` tag takes `required`, `const=V`, `enum=A|B`, `minimum=N`, `maximum=N`, `exclusiveMinimum=N`, `exclusiveMaximum=N`, `minLength=N` and `minItems=N`. - `jsonschema.PackageDocs(dir)` reads a package's doc comments into `Options.Docs`, so each property is described by its field's comment. - `Schema.Marshal()` writes indented JSON with a fixed key order, so the same types always give the same bytes. - `Schema.Validate(v)` and `Schema.ValidateYAML(data)` check a value against the keywords `Reflect` writes and return a `*ValidationError` listing every issue with its JSON Pointer path, for example `/layers/0/objects/1/alpha: 1.5 is greater than the maximum 1`, or `/layers/0/nmae: unknown key "nmae" (known keys: name, space, …)`. `ValidateYAML` reads YAML as a language server does: keys are strings, timestamps are strings, merge keys are merged, a key repeated within one mapping is an error, and aliases are expanded up to a bound. --- Source: https://game.nsgo.dev/docs/screen/ # screen `game/screen` maps a fixed virtual canvas onto any window size and aspect ratio, converts pointer input between view and virtual coordinates, snaps pixel-art coordinates, computes safe-area rectangles for HUD layers, and applies the player's video settings. ```go import "github.com/nsgo-dev/game/pkg/screen" ``` ## Viewport and scaling modes Define a `Viewport` with your game's virtual resolution (for example, `320×180`) and choose how it adapts to different window aspect ratios via `Mode`: ```go vp := screen.Viewport{ Width: 320, Height: 180, Mode: screen.ModeFit, BarColor: core.RGB(0x0b0e14), } ``` | Mode | Behavior | | --- | --- | | `ModeFit` | Scales uniformly so the entire virtual canvas fits inside the window, centered, with letterbox or pillarbox bars (default). | | `ModeFill` | Scales uniformly so the virtual canvas covers the whole window, centered, clipping overflow. | | `ModeStretch` | Scales X and Y independently to fill the window with no bars or clipping. | | `ModeExpand` | Scales uniformly to match the tighter axis and expands `VirtualSize` along the longer axis so the window fills with no bars or cropping. | Wrap your canvas drawing in `vp.Draw(d, size, fn)`: ```go return core.Canvas{ Style: core.Style{FlexGrow: 1, FlexShrink: 1}, Draw: func(d *core.Drawing, window core.Size) { vp.Draw(d, window, func(d *core.Drawing, virtualSize core.Size) { gameScene.Draw(d) _ = virtualSize // equals (320, 180) except in ModeExpand }) }, } ``` `vp.Draw` draws any letterbox/pillarbox bars (`BarColor` defaults to opaque black; use `core.Transparent` to skip drawing bars), clips overflow when needed, applies translation and scale, runs `fn`, and restores `d`'s state. Inspect the computed `Rect`, `VirtualSize`, `ScaleX`, `ScaleY`, and `Bars` directly with `vp.Layout(window)`. ## Pixel-art integer scaling and snapping For crisp pixel art without shimmer or uneven texels, enable `IntegerScale` and `PixelSnap`: ```go vp := screen.Viewport{ Width: 320, Height: 180, IntegerScale: true, // uses largest integer scale >= 1 that fits; falls back to fractional Fit if window < 1x PixelSnap: true, // aligns viewport offsets and rounds Snap/SnapPoint to whole virtual pixels } // Round interpolated sprite or camera coordinates when PixelSnap is enabled: drawX, drawY := vp.Snap(lerpX, lerpY) camPos := vp.SnapPoint(targetPos) ``` Unconditional helpers `screen.Snap(x, y)` and `screen.SnapPoint(p)` round to whole virtual pixels regardless of viewport flags. ## Converting pointer coordinates Convert view-space pointer coordinates (from `core.PressEvent`, `core.TouchEvent`, or `core.MouseEvent`) into virtual game coordinates with `ViewToGame`, and back with `GameToView`: ```go if pt, ok := vp.ViewToGame(windowSize, ev.Position); ok { // pt is inside the virtual canvas; ok is false on letterbox bars or outside the window handleClick(pt) } ``` `ViewToGame` pairs directly with [`input.Actions.MapPoint`](https://game.nsgo.dev/docs/input/#mapping-view-coordinates-to-a-virtual-canvas). ## Safe area for mobile HUDs Keep screen-space HUD buttons and readouts clear of notches, rounded corners, status bars, and home indicators using `SafeGameRectForEnv` (or `SafeGameRect` with explicit `core.Edges`): ```go safe := vp.SafeGameRectForEnv(cx.Env()) // safe is clamped to the visible virtual canvas in virtual game coordinates scoreX := safe.X + 8 scoreY := safe.Y + 8 ``` Called inside a reactive computation or `core.Canvas.Draw`, `SafeGameRectForEnv` and `SafeRectForEnv` subscribe automatically to window resize and safe-area inset changes. For native NSGo overlay views in view coordinates, use `screen.SafeRect(window, insets)` or `screen.SafeRectForEnv(cx.Env())`. ## Orientation on phones A game declares the orientation it plays in by calling NSGo's `cx.RequestOrientation` in the scope that shows it, usually the app's root. A wide virtual canvas asks for landscape, a tall one for portrait: ```go func Root(cx *core.Scope) core.Node { cx.RequestOrientation(core.OrientationLandscape) // either landscape direction // ... } ``` On an iPhone or an Android phone the interface turns to one of the requested orientations and stays there while that scope lives; when the scope ends, the app returns to the system's usual policy. The newest live request wins, so a portrait menu or a landscape mini-game can request its own orientation in its scope. Use `core.OrientationLandscapeLeft` or `core.OrientationLandscapeRight` alone to pin one direction, and `core.OrientationPortrait` (optionally with `core.OrientationPortraitUpsideDown`) for a portrait game. The request does nothing on desktops. Android may disregard it in multi-window or large-screen modes, and a browser locks orientation only in full screen, which a press must enter (`desktop.ToggleFullScreen(cx)`); a refusal goes to the browser console. In `nsgotest`, `App.Orientation` holds the current request. The [Cave Run example](https://github.com/nsgo-dev/game/tree/main/examples/caverun) locks landscape this way. NSGo documents the API under [Interface orientation](https://github.com/nsgo-dev/nsgo/blob/main/docs/public/en/services.md#interface-orientation). ## Video settings `Video` applies the display part of the player's settings (`save.DisplaySettings`) to the window and a `game.Loop`: windowed or full screen on a chosen display, a cap on how many frames the loop draws a second, and, with `AutoDropLowPower`, a lower cap while the system is in low-power mode or under serious or critical thermal pressure. It ships no UI: a settings screen edits `save.Settings`, saves it and applies it again, and the game applies the saved settings at start: ```go loop := &game.Loop{Update: update, Draw: draw} video := &screen.Video{Loop: loop} store := save.NewStorageSettingsStore(cx.Storage(), "mygame") loop.Run(cx) video.Run(cx) settings, err := store.LoadAndApply(save.SettingsTargets{ApplyDisplay: video.Apply}) ``` | Field | Effect | | --- | --- | | `Fullscreen` | Full screen on the chosen display, or windowed. | | `DisplayID` | The display, by its ID in `cx.Env().Displays()`; stays the same across launches and display changes, so a UI that offers displays sets it. | | `DisplayIndex` | The display by position in `Displays()` when `DisplayID` is empty or not connected; out of range keeps the window's current display. | | `FrameCap` | Most frames drawn a second (the loop's `DrawRate`), uncapped when 0. Updates keep to `Loop.Rate`. | | `AutoDropLowPower` | Lowers the cap to `Video.LowPowerCap` (30 when 0) while `cx.Env().LowPowerMode()` is on or `ThermalState()` is serious or critical, keeping a lower `FrameCap`, and restores it once the condition clears. | `Video` asks the window to change full screen or display only when the settings change them, or on the first `Apply` when they differ from the window, so applying other settings does not undo a player leaving full screen with the system's own controls. Settings applied before `Run` take effect when it starts, and disposing the owner that called `Run`, like calling the `stop` it returns, restores the cap and stops sending window requests. `Video.FrameCap()` returns the cap in effect and `Video.Dropped()` whether it is lowered; read inside a component or effect while `Run` is active, both update when the power state changes, and settings changes arrive through the screen's own `Apply` call; `screen.DisplayID` and `screen.Constrained` expose the display choice and the power rule for a settings screen. Full screen applies on macOS (as native full screen in its own Space), Windows and Linux. On the web it asks the browser, which grants full screen only during a user gesture such as the click that changes the setting, so a saved full-screen setting applied at start stays windowed there. Android and iOS ignore it. The frame cap applies everywhere. --- Source: https://game.nsgo.dev/docs/server/ # server `github.com/nsgo-dev/game/pkg/server` runs a game's fixed-step updates in a plain Go process, without an NSGo app, window, [`core.Scope`](https://game.nsgo.dev/docs/loop/) or cgo. The `Update` function a game hands to [`game.Loop`](https://game.nsgo.dev/docs/loop/) runs unchanged on the server: both step it with the same fixed `1/Rate` duration, so a dedicated server and the client share one simulation. ## Runner ```go r := &server.Runner{ Matches: []*server.Match{ {Name: "match-1", Rate: 60, Update: update}, {Name: "match-2", Rate: 30, Update: update}, }, OnOverrun: func(m *server.Match, lag time.Duration, missed int) { log.Printf("%s overran by %v (%d ticks missed)", m.Name, lag, missed) }, } if err := r.Run(ctx); err != nil { ... } ``` `Runner.Run` blocks until its context is canceled, then waits for each match's in-flight tick and runs its `OnStop` before returning. Each match runs on its own goroutine at its own rate. ## Ticks and overruns A match's step is `1/Rate` seconds (60 Hz when `Rate` is zero or negative). When `Update` runs longer than one step, `Runner` calls `OnOverrun` with the lateness and the number of whole steps it covers. Missed ticks are **not** caught up: the next tick is scheduled from the moment the slow update returns, so a slow update slows the match rather than producing a burst. ## Stopping A dedicated server usually runs under `signal.NotifyContext`: ```go ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() ``` On SIGTERM/SIGINT the context ends; the runner lets the current tick finish, then calls `OnStop` (for example to notify peers and flush state) and returns. `Update` must return promptly for the stop to stay bounded. The runnable example is `server/cmd/dedicatedserver`: ```sh go build ./server/cmd/dedicatedserver ``` It builds with the plain Go toolchain and no NSGo runtime. ## Matchmaking `Matchmaker` queues `Ticket`s by mode and region and fills rooms of `RoomSize` players: ```go mm := server.NewMatchmaker(4) mm.BaseWindow = 100 // rating difference allowed at enqueue time mm.WindowGrowthPerSecond = 10 mm.MaxWindow = 400 mm.Enqueue(server.Ticket{ID: 7, Mode: "coop", Region: "eu", Rating: 1200, Party: []string{"ada", "lin"}}) rooms := mm.Match() // []server.Matchup with TicketIDs and Players ``` A ticket's party is placed whole or not at all. The default rule fills rooms oldest-first and adds a ticket only when its rating difference from the room's oldest ticket fits within **both** tickets' current windows: `BaseWindow + WindowGrowthPerSecond * waited`, capped by `MaxWindow`. Matches never mix beyond the newer ticket's window, and an old ticket's window widening lets it meet a later arrival. `Cancel(id)` removes a waiting ticket without disturbing the rest; `Waiting` lists the queue oldest-first. Set `Rule` to replace the matching function; it receives a group of tickets with the same mode and region, the room size and a `window` function, and returns `Matchup`s. The matchmaker removes the tickets listed in each returned room. ## Rooms `Rooms` groups peers into independent rooms with a per-match lifecycle and its own packet inboxes: ```go rs := server.NewRooms() rs.EmptyTimeout = 30 * time.Second rs.Snapshot = func(r *server.Room) []byte { return encodeWorldState(r) } room, _ := rs.Create(4, true) // capacity 4, private with a code join, _ := rs.JoinCode(room.Code(), peer) // or rs.Join(room.ID(), peer) room.Start() // epoch 1, tick 0 room.Advance() // tick 1 while running room.End() room.Start() // epoch 2, tick 0: a fresh match rs.Leave(room.ID(), peer) rs.Tick() // close rooms empty for EmptyTimeout ``` - A room's `Deliver`/`Recv` only accept and expose packets of its own members, so two rooms never see each other's traffic. - `Join` on a running match calls `Snapshot` and returns it with the current epoch and tick; the joiner applies that full state before deltas. - `Start` after `End` advances the epoch and resets the tick, so clients can drop the old match's tick state without waiting for the counter to wrap. - A private room's `Code` is accepted by `JoinCode`; a full room returns `ErrRoomFull`, an unknown code `ErrRoomNotFound`. - A room that loses its last member closes after `EmptyTimeout` when `Tick` runs. ## Rate limits and input validation `Guard` enforces a per-peer policy before packets reach a room or simulation: ```go g := server.NewGuard(server.Limits{ PacketsPerSecond: 60, BytesPerSecond: 64 << 10, MaxMessageSize: 8 << 10, MaxPendingReliable: 256 << 10, }, server.LimitDisconnect) g.Validate = func(peer net.PeerID, p net.Packet) error { return checkInput(p) } action, err := g.Check(peer, packet) ``` - Token buckets for packets and bytes with optional bursts; `LimitThrottle`/`LimitDrop` refuse the packet and keep the peer connected, `LimitDisconnect` refuses the peer from then on (`GuardDisconnect`). - `MaxMessageSize` rejects an oversized packet before it is buffered; `ReserveReliable`/`ReleaseReliable` bound reserved reliable bytes. - `Validate` runs only for an admitted packet; a non-nil error drops it with `ErrInvalidInput`, increments that peer's `Violations`, and never reaches the simulation. - `Stats(peer)` reports packets, bytes, dropped, violations and pending reliable bytes per peer; `Reset` forgets a reconnecting peer. Per-peer state and O(1) checks leave other peers' ticks unaffected. The guard is transport-agnostic: call `Check` at the packet loop and act on the returned `GuardAction`. ## Peer-to-peer relay Lockstep and rollback sessions are peer-to-peer, but players behind NAT or in a browser cannot reach each other. `net.Relay` forwards their packets: each player connects to the relay with a `net.RelayTransport`, and the relay passes each frame to the member of the player's session it is addressed to. ```go relay, err := gamenet.NewRelay(gamenet.RelayConfig{ // Check the player's token and name the match it joins; the error text is the rejection reason. Join: func(peer gamenet.PeerID, token []byte) (string, error) { return matchOf(token) }, MaxSessionPeers: 2, }) auth := relay.Auth(gamenet.Auth{GracePeriod: 15 * time.Second}) srv, err := gamenet.ListenWebSocketTLSFiles(":443", 1, auth, "cert.pem", "key.pem", nil) // or gamenet.ListenUDPServer(":7777", 1, auth) go relay.Serve(ctx, srv) ``` ```go cli, err := gamenet.DialWebSocket("wss://relay.example.com/", token) // or gamenet.DialUDP(addr, token) peerTx := gamenet.NewRelayTransport(cli, gamenet.RelayTransportConfig{}) // Once peerTx.Peers() lists the opponent: session := gamenet.NewRollbackSession(gamenet.RollbackConfig{Transport: peerTx, Sim: sim}) ``` - The relay runs on a `WebSocketServer` or `UDPServer`, so every player passes [the connection handshake](https://game.nsgo.dev/docs/net/#connection-handshake-and-reconnect) first. `relay.Auth` runs the base `Auth.Verify`, when set, and then `Join`; an empty session name is rejected with `no session`, and a session that already holds `MaxSessionPeers` (8 by default) with `session full`. - Frames go only between members of one session. A frame addressed to another session's peer, to the relay, to its sender, or malformed is dropped and counted in `Stats().Dropped`; `RelayTransport.Send` refuses an ID outside the session with `ErrUnknownPeer`. - `Peers` lists the other members, including members inside the grace period, so a session does not lose a player who is reconnecting. The relay sends the membership again every second, so a client whose update was lost on UDP catches up. - A player who joins the relay session while a match runs takes part once the match's host admits them with `AddPeer`, and one who leaves is no longer waited for once the host calls `RemovePeer` (see [the net guide](https://game.nsgo.dev/docs/net/#players-joining-and-leaving-mid-match)). - `ChannelReliableOrdered` is reliable end to end: each message is numbered per peer, the receiver acknowledges it (with a selective acknowledgement of the next 64), and the sender resends what is missing after a timeout adapted to the measured round trip. It works over UDP, and a message the relay could not deliver while a player reconnected with the inner transport's `Reconnect` arrives once the player is back. At most 1024 messages may wait for acknowledgement per peer; past that `Send` returns `ErrRelayBacklog`. A receiver holds at most 4 MB of one peer's messages that arrived ahead of a missing one and drops the rest until they are resent. `ChannelUnreliable` packets are sent once. - When the inner transport's `Reconnect` admits the player as a new peer instead of resuming, because the grace period passed or the relay restarted, the `RelayTransport` starts over: it forgets the old members and unacknowledged messages, even when the relay hands out the same ID again, and waits for the new session's membership. - Acknowledgements and resends happen inside `Recv`, which the sessions call every tick through `Poll`. - The relay never reads payloads. It writes to each member on that member's own goroutine through a queue of `QueueSize` frames (256 by default), so a slow player delays only itself; frames past the queue are dropped, and reliable ones are resent by their sender. - A relay serves one server for its lifetime, so WebSocket and UDP players cannot share a session; run one relay per protocol. `Serve` may be called again on the same server after it returns, and the players still connected keep their sessions. A payload is at most `MaxRelayPayload` bytes. - The relay sees payloads in the clear unless the connection is `wss://`; the handshake caveats for UDP in [the net guide](https://game.nsgo.dev/docs/net/#connection-handshake-and-reconnect) apply. ### Relay latency `BenchmarkRelayRoundTrip` in `game/net` measures the round trip of a 48-byte message on one machine over the loopback interface. "Direct" is a client and its server, one hop each way; "relay" is two `RelayTransport`s through a local relay, two hops each way, sending reliably as rollback does: | Path | Linux x86-64, 24 cores | macOS arm64, 10 cores | | --- | --- | --- | | UDP direct | 63 µs | 34 µs | | UDP through the relay | 188 µs | 94 µs | | WebSocket direct | 44 µs | 33 µs | | WebSocket through the relay | 187 µs | 87 µs | A local relay adds roughly 55 to 145 µs to a round trip, well under a millisecond and under a tenth of a 60 Hz tick. Over the internet the relay's cost is the extra network distance of the detour, so run relays in the regions where players are. Reproduce the numbers with: ```sh go tool nsgo test ./net -run '^$' -bench BenchmarkRelayRoundTrip ``` ### WebRTC data channels Decision: `game/net` does not build WebRTC data channels with STUN now; the relay is the path for every peer-to-peer session. - WebRTC needs ICE with STUN and TURN, DTLS and SCTP. Browsers provide them through `RTCPeerConnection`, but native targets would need all of them in Go; NSGo does not expose a platform WebRTC stack, and the only complete Go implementation is a large third-party stack that every native build would carry. - A relay is needed anyway: STUN fails behind symmetric NATs, common on mobile carriers, and TURN is itself a relay. Signaling also needs a server. - Rollback traffic is small, and a nearby relay adds little latency (see above). Revisit it when measurements show players near each other but far from every relay region, or when NSGo exposes WebRTC on native targets. The design then is a WebRTC transport behind the same `Transport` interface that tries a direct path with STUN and falls back to `RelayTransport`, so sessions do not change. ## TLS, origins, health and metrics A browser on an HTTPS page needs `wss://`. `net.ListenWebSocketTLS` wraps the WebSocket listener in TLS and checks the browser Origin during the upgrade; `ListenWebSocketTLSFiles` loads a PEM certificate and key. Both take the same `Auth` as `ListenWebSocket` (see [the connection handshake](https://game.nsgo.dev/docs/net/#connection-handshake-and-reconnect)): ```go srv, err := gamenet.ListenWebSocketTLSFiles(":443", 1, auth, "cert.pem", "key.pem", []string{"https://game.example.com"}) ``` An `Origin` outside the allow-list is refused with `403` before the WebSocket handshake; an empty allow-list accepts any Origin and `"*"` accepts all, while an empty Origin (native game clients) is allowed. Each entry is a `scheme://host` Origin such as `https://game.example.com`; a trailing slash is ignored, and an entry that names a path or query makes the listener fail at start-up. `server.Health` serves deployment endpoints: ```go health := server.NewHealth(func() bool { return worldReady() }, func() server.Metrics { return server.Metrics{Peers: peers, Rooms: rooms, BytesIn: in, BytesOut: out} }) http.ListenAndServe(":8080", health) ``` - `GET /healthz` — process liveness; - `GET /readyz` — 200 while `Ready` returns true, else 503; - `GET /metrics` — Prometheus gauges/counters for peers, rooms, last tick duration and bytes. Observe each server tick with `health.ObserveTick(time.Since(start))`. ### Container and draining Build the example as a static, cgo-free binary and run it as a small container: ```dockerfile FROM golang:1.27 AS build WORKDIR /src COPY . . RUN CGO_ENABLED=0 go build -o /out/server ./pkg/server/cmd/dedicatedserver FROM gcr.io/distroless/static-debian12 COPY --from=build /out/server /server EXPOSE 8080 ENTRYPOINT ["/server"] ``` Run it with `SIGTERM` as the stop signal (`docker stop` sends SIGTERM by default). The example uses `signal.NotifyContext`; `Runner.Run` lets the current tick finish, runs each match's `OnStop` to notify peers and flush state, then exits, so the container drains instead of losing a tick. ## Player tokens A dedicated server learns who a player is from a token the player's device got from the [account service](https://game.nsgo.dev/docs/accounts/). It loads the service's key set file once and verifies each token offline with `accounts/token`, which links none of the account service's password hashing or database drivers: ```go ks, err := token.ParseKeySet(keysYAML) v, err := token.NewVerifier(ks) claims, err := v.Verify(tok) // claims.Subject is the account ID ``` --- Source: https://game.nsgo.dev/docs/skeletal/ # skeletal ```go import "github.com/nsgo-dev/game/pkg/skeletal" ``` 2D skeletal rigs, forward kinematics, skins, keyframe animation and crossfade blending, drawn into a `core.Drawing` through `sprite.Batch`. ## Format decision `skeletal` defines an open, versioned YAML format (`.skel.yaml`, version `1`), read by `Load` and written by `Encode` with `go.yaml.in/yaml/v3`: - **No proprietary runtime license**: Spine's official runtimes and export format are governed by the Spine Runtimes License, which requires every user of the runtime to hold a paid Spine license. An open schema keeps NSGo games unencumbered under MIT. - **Text for review**: Like every file a game's author edits in this repository, a rig is plain YAML with one bone, slot, attachment or keyframe per line, so a person or an AI can edit it by hand and a diff shows exactly what moved. - **No extra dependencies**: The YAML library is the one `sceneformat` and the data tables already use; there is no binary decoder or code generation. - **Native screen coordinates**: Uses the same coordinate system as `sprite` and `core.Drawing` (`+X` right, `+Y` down, rotations in radians clockwise on the screen), so rig data and runtime transforms match without axis flips or unit conversion. - **Simple to export**: The flat layout (bones, slots, skins, animations) makes writing a short exporter from DragonBones, Blender or custom tools — or authoring rigs by hand — straightforward. - **Strict and versioned**: Every file carries `version: 1`; `Load` rejects missing or unsupported versions, unknown fields, duplicate keys, trailing documents and non-finite numbers (`.nan`, `.inf`). - **JSON still loads**: A version-1 rig written as JSON, as earlier releases read it, loads too when the JSON is also valid YAML: keys spelled exactly as the schema spells them (matching is case-sensitive) and no `\/` escape, which YAML does not have. `Encode` writes it back as YAML. ## Coordinates and units - **Position (`x`, `y`, `originX`, `originY`)**: points in NSGo's 2D drawing space (`+X` right, `+Y` down). - **Rotation (`rotation`, `angle`)**: radians, clockwise on the screen. - **Scale (`scaleX`, `scaleY`)**: multipliers about the bone or attachment origin, defaulting to `1` when omitted. - **Time (`duration`, `time`)**: seconds as YAML numbers in `[0, MaxSeconds]` (one million seconds), converted to `time.Duration` to the nearest nanosecond on load. ## YAML schema (version 1) | Field | Type | Description | | --- | --- | --- | | `version` | `int` (required) | Schema version. Must be `1`. | | `name` | `string` | Optional rig name. | | `bones` | `[]Bone` | Bone hierarchy in bind pose. Parents may appear in any order; cycles and unknown parents are rejected. | | `slots` | `[]Slot` | Draw-ordered slots, back to front. Each binds to a bone. | | `skins` | `map[string]map[string]Attachment` | Maps skin name (default `"default"`) to a map of slot name to attachment. | | `animations` | `map[string]Animation` | Maps animation name to its bone and slot timelines. | ### Bone | Field | Type | Default | Description | | --- | --- | --- | --- | | `name` | `string` (required) | — | Unique bone name. | | `parent` | `string` | `""` | Parent bone name, or empty for a root bone. | | `x`, `y` | `float32` | `0` | Local bind-pose offset in the parent's space. | | `rotation` | `float32` | `0` | Local bind-pose rotation in radians, clockwise. | | `scaleX`, `scaleY` | `float32` | `1` | Local bind-pose scale. | | `length` | `float32` | `0` | Optional bone length for editors and debug views. | ### Slot | Field | Type | Default | Description | | --- | --- | --- | --- | | `name` | `string` (required) | — | Unique slot name. | | `bone` | `string` (required) | — | Name of the bone whose world transform the slot follows. | | `attachment` | `string` | `""` | Optional default atlas frame name when no skin supplies one. | | `alpha` | `float32` | `1` | Bind-pose slot opacity in `[0, 1]`. | ### Attachment (inside `skins[skin][slot]`) | Field | Type | Default | Description | | --- | --- | --- | --- | | `frame` | `string` | `""` | Atlas frame name in `sprite.Atlas.Frames`; empty hides the slot. | | `x`, `y` | `float32` | `0` | Local offset from the slot's bone. | | `rotation` | `float32` | `0` | Local rotation in radians, clockwise. | | `scaleX`, `scaleY` | `float32` | `1` | Local scale. | | `originX`, `originY` | `float32` | `0` | Pivot point in the untrimmed atlas frame (matches `sprite.Sprite`). | When the active skin does not define an entry for a slot, the skeleton falls back to the `"default"` skin. Setting `frame: ""` explicitly hides the slot in that skin. ### Animation | Field | Type | Default | Description | | --- | --- | --- | --- | | `duration` | `float64` | last keyframe | Duration in seconds. Derived from the latest keyframe when omitted. | | `loop` | `bool` | `false` | File-level default looping preference. | | `bones` | `map[string]BoneTimeline` | — | Per-bone `translate`, `rotate`, and `scale` tracks. | | `slots` | `map[string]SlotTimeline` | — | Per-slot `attachment` and `alpha` tracks. | Bone timelines apply relative to the bone's bind pose: `translate` (`x`, `y`) and `rotate` (`angle`) add to the bind pose, while `scale` (`x`, `y`, each defaulting to `1`) multiplies it. Rotation tracks interpolate along the shortest arc across `±π`. Slot `attachment` keyframes (`{time, frame}`) step immediately to `frame` at `time` (empty hides the slot). Slot `alpha` keyframes (`{time, value}`) interpolate opacity in `[0, 1]`. Every continuous keyframe accepts an optional easing curve applied to the segment starting at that keyframe: - `"linear"` (default): constant speed to the next keyframe. - `"stepped"`: holds the keyframe's value until the next keyframe's time. - `"bezier"`: cubic Bezier easing with `bezier: [cx1, cy1, cx2, cy2]`, where `cx1` and `cx2` lie in `[0, 1]` (`cy1` and `cy2` may overshoot). Control points on any other curve are rejected. ### Sample rig A complete 7-bone character with two skins (`"default"` and `"armored"`) and three animations (`"walk"`, `"run"`, `"jump"`) lives in [runner.skel.yaml](https://github.com/nsgo-dev/game/blob/main/pkg/skeletal/testdata/runner.skel.yaml). A minimal excerpt: ```yaml version: 1 name: runner bones: - {name: root} - {name: torso, parent: root, y: -18, length: 16} - {name: head, parent: torso, y: -16, length: 12} slots: - {name: torso, bone: torso} - {name: head, bone: head} skins: armored: head: {frame: helmet, originX: 6, originY: 12} torso: {frame: torso_armor, originX: 6, originY: 16} default: head: {frame: head, originX: 6, originY: 12} torso: {frame: torso, originX: 6, originY: 16} animations: walk: duration: 0.8 loop: true bones: torso: translate: - {time: 0, x: 0, y: 0, curve: bezier, bezier: [0.25, 0.1, 0.25, 1]} - {time: 0.2, x: 0, y: -2} - {time: 0.4, x: 0, y: 0} ``` ### Canonical form `Encode` writes one canonical form, so saving a rig never produces a diff by itself: - Keys follow the schema order above; skins, attachments, animations and timelines are sorted by name in plain byte order, as `sort.Strings` sorts them (`B` before `a`, `a10` before `a2`); bones and slots keep their order. - Every bone, slot, attachment and keyframe is one flow mapping on its own line. - Fields equal to their defaults are left out, except that a keyframe always writes its `time` and values and an animation always writes its `duration`. - Numbers use the shortest digits that read back to the same value, in plain decimal notation without an exponent (`1000000`, `0.0000001`), so YAML 1.1 readers such as PyYAML read them as numbers; times read back to the same nanosecond. - Comments, anchors and other formatting are not kept. Loading a file already in this form and encoding it gives the same bytes back, and loading what `Encode` wrote gives the same rig. `Encode` refuses, with the same errors as `Load`, any rig `Load` would refuse. ## Runtime API ### Loading and setup - `Load(data []byte) (*SkeletonData, error)` parses and validates the rig, rejecting cycles, missing parents, duplicate names, unknown targets and invalid curves. One `*SkeletonData` can be shared across any number of live skeletons. - `Encode(sd *SkeletonData) ([]byte, error)` writes the rig as a canonical `.skel.yaml` document, for editors and exporters that save rigs. - `NewSkeleton(data *SkeletonData, atlas *sprite.Atlas) *Skeleton` creates a live skeleton at scale `(1, 1)` and alpha `1` in its bind pose, activating `"default"` if defined. ### Root transform, skins and attachments - Root fields `X`, `Y`, `Rotation`, `ScaleX`, `ScaleY`, `FlipX`, `FlipY`, `Alpha` and `Z` position, orient, mirror and fade the whole rig. - `SetSkin(name string) error` switches the active skin (falling back to `"default"` for slots not overridden by `name`). - `SetAttachment(slot, frame string)` overrides a slot's atlas frame (empty hides it); `ClearAttachment(slot string)` removes the override. - `UpdateWorldTransforms()` runs forward kinematics down the bone tree; `WorldBone(name string) (BoneTransform, bool)` reads any bone's world position, rotation and scale for attaching weapons, hitboxes or particles. - `Draw(d *core.Drawing)` updates world transforms and draws every visible slot in slot draw order through a reusable `sprite.Batch`. ### Animation and crossfade blending - `Play(anim string, loop bool) error` starts `anim` at time `0`, cancels any crossfade and updates world transforms immediately. - `Crossfade(anim string, duration time.Duration, loop bool) error` blends smoothly from the outgoing animation pose into `anim` over `duration` using shortest-angle rotation blending and linear translation, scale and alpha blending. Interrupting an in-progress crossfade snapshots the current blended pose so transitions never pop. - `Update(dt time.Duration)` advances active playback and crossfades deterministically and refreshes world transforms. - `Animation() string`, `Done() bool` and `Blending() bool` report playback state. ```go data, err := skeletal.Load(runnerYAML) // the bytes of runner.skel.yaml if err != nil { return err } hero := skeletal.NewSkeleton(data, atlas) hero.X, hero.Y = 200, 300 _ = hero.Play("walk", true) loop := &game.Loop{ Update: func(dt time.Duration) { if sprinting && hero.Animation() != "run" { _ = hero.Crossfade("run", 200*time.Millisecond, true) } hero.Update(dt) if hand, ok := hero.WorldBone("arm_r"); ok { emitSpark(hand.X, hand.Y) } }, } // In a core.Canvas's Draw: hero.Draw(d) ``` ## Editing and placing rigs in scenes `.skel.yaml` rigs can be authored visually in `game/editor` (bone handles, slot attachment origin handles, skin switching, timeline keying, and runtime playback/crossfade preview) and placed in `.scene.yaml` files via the built-in `skeletal` component (`sceneformat.SkeletalComponent`, fields `version`, `rig`, `atlas`, `skin`, `animation`, `loop`). See [2D skeletal rig editor](https://game.nsgo.dev/docs/editor/#2d-skeletal-rig-editor-886). --- Source: https://game.nsgo.dev/docs/statedump/ # statedump `game/statedump` runs a game headless for a fixed number of steps and writes its entities, components and scene state as deterministic YAML. Two runs with the same seed and inputs write identical files, so an agent or a test checks its work by diffing one run against another, and a change shows as a few changed lines. The files match byte for byte on the same CPU architecture. A game's own float math can differ between arm64 and amd64, because the Go compiler may fuse a multiply and an add into one FMA instruction on arm64; a golden dump shared across machines needs an explicit conversion on such products, as in `x += float64(v * speed * dt)`, which rounds the product and stops the fusion. ```go import "github.com/nsgo-dev/game/pkg/statedump" ``` ## Running headless `Run` plays a [`replay.Recording`](https://game.nsgo.dev/docs/replay/) against a simulation and captures its state after `rec.TotalSteps` steps. Like `replay.Run`, `makeSim` receives the recording's seed and a `*replay.Player` as its `ActionSource`; unlike it, `Run` needs no `testing.TB`, so a command or an agent's tool can call it too. `Run` returns an error when `Step` did not call `src.Step()` once per step, since a sim that never reads the recording would dump the same state for any input. ```go rec, err := replay.LoadFile("runs/boss-bug.replay.yaml") if err != nil { return err } dump, err := statedump.Run(rec, func(seed uint64, src replay.ActionSource) (statedump.Sim, error) { g := newGame(seed) return statedump.Sim{ Step: func(dt time.Duration) { g.Update(src, dt) }, // calls src.Step() once, as game.Loop's Update does Source: statedump.Source{ World: g.World, Scenes: g.Scenes, SceneName: func(c *scene.Controller) string { return g.SceneNames[c] }, Values: func() map[string]any { return map[string]any{"score": g.Score, "level": g.Level} }, }, }, nil }) if err != nil { return err } return statedump.WriteFile("runs/boss-bug.state.yaml", dump) ``` To run N steps with no input, pass a recording without events: `&replay.Recording{Version: replay.FormatVersion, Seed: seed, Rate: 60, TotalSteps: n}`. `Capture(src)` takes the same state at any moment, with the seed, rate and step count left for the caller to fill in. ## What a dump holds - `version`, `seed`, `rate` and `steps`: the schema version (1) and how the run was made. - `scene`: the `scene.Manager` stack's `depth`, the `current` scene's name when `SceneName` is set, and `transitioning` with its eased `progress` while a `Switch` transition runs; a curve that overshoots, such as an ease-out-back, takes `progress` past 1 for part of the transition. It is left out without a manager. - `values`: game-wide state outside the entity world, such as score, level or an RNG position, each encoded with `encoding/json` and keyed by name, in ascending byte order of the names. - `entities`: every live entity in ascending slot index, with its `generation`, its hierarchy `parent` and its components in ascending codec name. Only components registered with [`entities.RegisterCodec`](https://game.nsgo.dev/docs/entities/) appear, as in a world snapshot. ```yaml version: 1 seed: 42 rate: 60 steps: 90 scene: depth: 2 current: pause values: score: 40 entities: - index: 0 generation: 1 components: - type: health data: hp: 100 - type: pos data: x: 12.5 y: 12 - index: 1 generation: 1 parent: 0 components: - type: name data: sword ``` Component and value data become YAML mappings and sequences rather than embedded JSON strings, so one changed field is one changed line. They keep the JSON field order of the Go struct and the exact text `encoding/json` writes for each number. Strings that YAML 1.2 or a YAML 1.1 reader would read as another type (`"1"`, `"true"`, `"yes"`, `"2001-12-14"`, `"1:20"`) are quoted, and a JSON `null` stays `null`. ## Reading and diffing `Encode` writes a dump, `Parse` reads one, and `WriteFile` and `ReadFile` do the same on disk. `Encode(Parse(b))` returns `b` for every `b` that `Encode` wrote. `Parse` refuses unknown fields, other versions, trailing documents, entities out of slot order, components out of name order, parents missing from the dump, and data JSON cannot hold: non-string keys, anchors and aliases, binary, NaN and infinities. `Diff(a, b)` returns a unified line diff with three lines of context, or `""` when the dumps are equal: ```diff --- a +++ b @@ -28,7 +28,7 @@ second line - type: pos data: - x: 4.0000009393637015e-7 + x: 119.99999559999982 y: 12 - index: 1 generation: 1 ``` A test keeps a golden dump under `testdata/` and fails with this diff when a run no longer matches it: ```go got, err := statedump.Encode(dump) if err != nil { t.Fatal(err) } want, err := os.ReadFile("testdata/boss-bug.state.yaml") if err != nil { t.Fatal(err) } if diff := statedump.Diff(want, got); diff != "" { t.Fatalf("state differs from the golden dump:\n%s", diff) } ``` `dump.Snapshot()` returns the entities as an `entities.WorldSnapshot`, so `World.Restore` loads a dump back into a world that registers the same codecs. --- Source: https://game.nsgo.dev/docs/stats/ # stats `game/stats` keeps an entity's gameplay stats: named base values changed by additive, multiplicative and override modifiers that come from sources such as equipment and buffs. Values are recomputed the moment anything changes, and timed modifiers count fixed steps, so a buff that lasts 300 steps ends on exactly the 300th. ```go import "github.com/nsgo-dev/game/pkg/stats" ``` ## A sheet of stats A `Sheet` holds one entity's stats in the order they were defined: ```go hero, err := stats.NewSheet( stats.Def{Name: "health", Base: 100, Min: stats.Float(0)}, stats.Def{Name: "attack", Base: 12}, stats.Def{Name: "speed", Base: 5, Min: stats.Float(0), Max: stats.Float(20)}, ) hero.Value("attack") // 12 hero.SetBase("attack", 14) ``` `Value` is a cached read; it never recomputes. `Lookup` also reports whether the stat exists, `Base` returns the value before modifiers, and `Stats` lists the names. The zero `Sheet` is ready to use with `Define`. ## Modifiers and how they stack A `Modifier` names a stat, an `Op` and a value. Each one is added from a source, a free-form tag such as `"equip:weapon"` or `"buff:haste"`: | Op | YAML | Effect | | --- | --- | --- | | `OpAdd` | `add` | Adds its value to the base | | `OpMul` | `mul` | Multiplies by its value after every addition | | `OpOverride` | `override` | Replaces the result, ignoring adds and muls | A stat's value is: ``` clamp((base + sum of add values) × product of mul values) ``` While any override is on the stat, the value is instead `clamp(override value)`, where the override with the highest `Priority` wins and, among equal priorities, the one added last. `clamp` applies the stat's `Min` and `Max` when they are set, to overrides too. Apart from breaking a tie between overrides, the order modifiers are added in matters only for floating-point rounding: adds and muls are applied in that order, so `0.1 + 0.2 + 0.3` and `0.3 + 0.1 + 0.2` can differ in the last digit. Compare values with a tolerance when that matters. A sum or product that overflows `float64` saturates at the largest finite value of its sign, so a value is always finite and within its bounds. | Base | Modifiers | Value | | --- | --- | --- | | 10 | add 5, add 3, add −2 | 16 | | 10 | mul 2, mul 1.5 | 30 | | 10 | mul 2, add 5, mul 1.5, add 3 | (10 + 8) × 3 = 54 | | 10 | add 5, override 7, mul 3 | 7 | | 10 | override 1 (priority 5), override 2 (priority 9) | 2 | | 10, max 25 | mul 3 | 25 | ```go sword, _ := hero.Add("equip:weapon", stats.Modifier{Stat: "attack", Op: stats.OpAdd, Value: 8}) hero.Add("equip:ring", stats.Modifier{Stat: "attack", Op: stats.OpMul, Value: 1.5}) hero.Value("attack") // (14 + 8) × 1.5 = 33 hero.Remove(sword) // one modifier by its ID hero.RemoveSource("equip:ring") // every modifier from a source hero.Clear() // all of them ``` `Add` refuses an unknown stat (`ErrUnknownStat`), an unknown op (`ErrInvalidOp`) and a NaN or infinite value (`ErrInvalidValue`). `Modifiers` lists what is on the sheet in the order it was added, with each modifier's ID, source and remaining steps. ## Timed modifiers on the fixed step `AddTimed` adds a modifier that lasts a number of calls of `Step`. Call `Step` once from each `game.Loop` update; the modifier is removed by exactly the n-th `Step` after it was added, and the stat is recomputed in that same step: ```go hero.AddTimed("buff:haste", stats.Modifier{Stat: "speed", Op: stats.OpMul, Value: 2}, 180) loop := &game.Loop{Rate: 60, Update: func(dt time.Duration) { hero.Step() // haste ends on the 180th update: 3 seconds at 60 Hz }} ``` Because time is counted in steps rather than durations, a paused loop pauses every buff, and a replay ends them on the same step. `Remaining(id)` returns how many steps a modifier has left (0 for one without a limit). `Steps` returns how many times `Step` has run. ## Effects An `Effect` is a named group of modifiers applied together, such as an item's bonuses or a buff that touches several stats. Its `Steps` (0 for no limit) applies to all of its modifiers: ```go berserk := stats.Effect{Name: "berserk", Steps: 300, Modifiers: []stats.Modifier{ {Stat: "attack", Op: stats.OpMul, Value: 1.5}, {Stat: "speed", Op: stats.OpAdd, Value: 2}, }} ids, err := hero.Apply("buff:berserk", berserk) ``` `Apply` adds all of the effect's modifiers or none of them. Applying an effect again stacks a second copy; to refresh a buff's duration instead, call `Refresh` with its source: ```go hero.Refresh("buff:berserk", berserk) // a full 300 steps again ``` `Refresh` removes every modifier from the source and applies the effect in their place as one change, so `OnChange` sees only the net difference, never the buff ending and starting again. Calling `RemoveSource` and then `Apply` does the same in two changes, and listeners see the value drop back to the unbuffed one in between. ## Change notifications `OnChange` is called once for each stat whose value changed, after the change that caused it, in definition order: ```go hero.OnChange = func(c stats.Change) { if c.Stat == "health" && c.New == 0 { die() } } ``` A stat whose modifiers changed but whose value did not is not reported. `OnChange` may change the sheet itself, for example to keep one stat in step with another; those changes are recomputed and reported before the call that started them returns. ## Stats files Stat definitions and effects are written in a versioned YAML file, so designers can tune numbers in review: ```yaml version: 1 stats: - name: health base: 100 min: 0 - name: attack base: 12 - name: speed base: 5 min: 0 max: 20 effects: - name: iron-sword modifiers: - stat: attack op: add value: 8 - name: berserk steps: 300 modifiers: - stat: attack op: mul value: 1.5 - stat: speed op: add value: 2 - name: frozen steps: 90 modifiers: - stat: speed op: override value: 0 priority: 10 ``` ```go file, err := stats.Parse(data) hero, err := file.NewSheet() sword, _ := file.Effect("iron-sword") hero.Apply("equip:weapon", sword) ``` `Parse` refuses unknown fields, a missing or different `version`, trailing documents, duplicate or empty names, non-finite numbers, `min` above `max`, negative `steps`, effects without modifiers, unknown ops and modifiers on undefined stats. `Encode` writes the fields in a fixed order with 2-space indentation and keeps lists in their given order, so parsing and encoding an encoded file reproduces it byte for byte. | Field | Type | Meaning | | --- | --- | --- | | `version` | int | Schema version, `1` | | `stats[].name` | string | Unique stat name | | `stats[].base` | number | Value before modifiers | | `stats[].min`, `stats[].max` | number, optional | Bounds applied after modifiers | | `effects[].name` | string | Unique effect name | | `effects[].steps` | int, optional | Fixed steps the effect lasts, 0 or absent for no limit | | `effects[].modifiers[].stat` | string | A stat defined above | | `effects[].modifiers[].op` | `add`, `mul` or `override` | How it changes the stat | | `effects[].modifiers[].value` | number | The amount, factor or override value | | `effects[].modifiers[].priority` | int, optional | Override priority, highest wins | --- Source: https://game.nsgo.dev/docs/template-action3d/ # Action Adventure Template `action3d` is a third-person 3D action adventure: a knight crosses a walled courtyard, fights the guards, jumps onto a ledge for the key, and the key opens the gate to the shrine. Reaching the shrine wins the run; losing all health loses it. Create a project from it with: ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template action3d mygame cd mygame go tool nsgo dev ``` or, without the `game` tool, `nsgo init -template github.com/nsgo-dev/game/template/action3d -module example.com/mygame mygame` ([Templates](https://game.nsgo.dev/docs/templates/)). ## What it shows - **Orbit camera.** A [`scene3d.OrbitController`](https://game.nsgo.dev/docs/scene3d/) follows the hero at a fixed height and distance, turns when the player turns it, and moves in front of any wall between it and the hero, found with a [physics3d](https://game.nsgo.dev/docs/physics3d/) raycast. - **Character movement.** Each actor is a `physics3d.CharacterController` capsule in a world of static boxes: running relative to the camera, jumping onto a ledge too high to step up, and a door whose body leaves the world when it opens. - **Animation blended by a state machine.** Run, jump, attack, flinch and fall clips play on a rig of boxes through an [`anim3d.StateMachine`](https://game.nsgo.dev/docs/anim3d/). Its locomotion state blends idle into run by the actor's speed with an `anim3d.BlendSpace1D`, conditional transitions start the jump when the actor leaves the ground and return to locomotion when a swing ends, and each blow lands on the attack clip's `hit` event, so the animation decides when a hit happens. - **Melee enemies.** Enemies chase the hero inside their sight and leash, wind up a slow swing that a hit from the hero interrupts, and walk home when the hero gets away. - **A level that is a scene file.** Blocks, the spawn, the enemies, the key, the door, the goal and the lamps are objects with components in a [scene file](https://game.nsgo.dev/docs/editor/), and a connection in that file, not Go code, makes picking up the key unlock the door. - **Rendering.** [render3d](https://game.nsgo.dev/docs/render3d/)'s lit PBR pipeline draws every box from one cube mesh, lit by a moon, an ambient fill and the scene's lamps, on every GPU backend NSGo has, WebGL 2 included. - **Every kind of input.** Keyboard and mouse, game controllers and touch all go through one [`input.Actions`](https://game.nsgo.dev/docs/input/) bound from the input map in `game.yaml`; on-screen sticks and buttons (`input.VirtualPad`) appear once the screen is touched. - **Tests that play it.** Headless nsgotest tests play the whole run to a win with a game controller and to a loss with the keyboard, drive the touch controls and the mouse, check every data file is valid and canonical, and draw the level on a software GPU. ## Controls | | Keyboard and mouse | Game controller | Touch | | --- | --- | --- | --- | | Move | W A S D or the arrow keys | Left stick or D-pad | Drag on the left half | | Turn the camera | Q and E, or drag with the mouse | Right stick or the shoulder buttons | Drag on the right half | | Jump | Space | A (south) | Jump button | | Attack | J or Enter | X (west) or the right trigger | Attack button | | Play again | R | Start | Play again button | ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The [project file](https://game.nsgo.dev/docs/project/): name, id, window, the input map, the scene and data files it autoloads, and export presets. | | `scenes/keep.scene.yaml` | The level. Each object's `x`, `y` (up) and `posZ` place it in meters, its scale sizes a box, and its components say what it is: `block`, `spawn`, `enemy`, `key`, `door`, `goal` or `lamp`. The `connections` wire the key's `collected` event to the door's `unlock` handler. | | `data/actors.yaml` | The hero's and the enemies' tuning, the rig of boxes both share, and the animation clips, in meters, degrees and seconds. | | `actors.go` | The format of `data/actors.yaml`: version 1, unknown fields refused, and an encoder whose output reads back to the same bytes. | | `level.go` | The level's component types and how the scene becomes boxes, spawns and lamps. | | `game.go` | The simulation: the physics world, the hero's and the enemies' rules, the key, the door, winning and losing. It knows nothing of devices or the GPU, so tests step it directly. | | `rig.go` | Turns the rig and clips into anim3d clips, builds each actor's state machine and poses its boxes. | | `render.go` | The camera, the lights and the GPU renderer. | | `view.go` | The root component: the fixed-step [`game.Loop`](https://game.nsgo.dev/docs/loop/), input, the HUD and the touch controls. | | `*_test.go` | The playthroughs and the input, rendering and file-format tests. | ## Where to change it - **The level.** Move walls, add enemies or lamps, or draw a new level in `scenes/keep.scene.yaml`, by hand or in the scene editor (`go run github.com/nsgo-dev/game/cmd/game editor .`). Every object sits at the top of its layer, and only the spawn is rotated (by `rotY`): the level refuses an object nested inside another or a rotated block, since it reads positions as world values and blocks as boxes aligned with the axes. The tests check that it still loads; the bot's route in `game_test.go` says how a run is won, so a new layout needs a new route. - **The fight.** `data/actors.yaml` holds every number: an enemy's `attackSpeed` below 1 slows its swing, and `health`, `reach`, `damage`, `cooldown` and `knockback` change the difficulty without touching code. - **Animation.** Edit the clips' keys in `data/actors.yaml`, or add a clip and a state for it in `newAnimator` in `rig.go`. - **New objects.** Register a component type in `levelComponents` in `level.go`, such as a moving platform or a lever, read it in `buildLevel`, and connect its events to handlers in the scene. - **Models.** Replace the boxes with glTF models: load them with package `gltf` ([3D models from Blender](https://game.nsgo.dev/docs/3d-models-blender/)), upload their meshes with `render3d.UploadMesh` and draw them in `renderer.draw`. After editing `game.yaml`, `go run github.com/nsgo-dev/game/cmd/gameproject sync` writes what `nsgo.yaml` shares with it, and after moving or adding files `go run github.com/nsgo-dev/game/cmd/game index` keeps `game.index.yaml`, the project's index of stable file IDs, up to date. --- Source: https://game.nsgo.dev/docs/template-cards2d/ # The cards2d template `cards2d` is Suit Ladders, a single-player card game of an original design. Each suit has a ladder that climbs from 1 to 9. The player holds a hand of five cards, draws from a draw pile, climbs a ladder with a card that is the next rank there and throws the others on a discard pile, which can be turned over into a new draw pile twice a game. The game is won when every ladder reaches 9 and lost when the draw pile is empty, cannot be dealt again, and no card in the hand fits a ladder. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template cards2d mycards cd mycards go tool nsgo dev ``` `nsgo init -template github.com/nsgo-dev/game/template/cards2d` writes the same project, as [Templates](https://game.nsgo.dev/docs/templates/) describes. ## What it shows - [`game/cards`](https://game.nsgo.dev/docs/cards/): a `Board` loaded from `board.yaml`, cards dragged with the mouse or a finger and dropped where the rules allow, the others flying back, and the board's `Accept` as the rule every drop and every play or throw of a hand card goes through, whether by key, button, tap or drag; drawing and turning the discard pile over go through `canDraw`. - [`game/random`](https://game.nsgo.dev/docs/determinism/): deal *n* is shuffled by a `random.Stream` seeded with *n*, so every player's deal *n* is the same game and the tests can name the deals they win and lose. - [`game/save`](https://game.nsgo.dev/docs/save/): the game in progress and the record of wins and losses kept in `core.Storage` after every move, checked on load so a damaged or impossible save deals a new game, and left alone when a newer version of the game wrote it. - [`game/project`](https://game.nsgo.dev/docs/project/) and [`game/input`](https://game.nsgo.dev/docs/input/): `game.yaml`'s input map binds keys and gamepad buttons to the actions `left`, `right`, `play`, `discard`, `draw` and `deal`, and `Project.BindInput` reads it into `input.Actions`. - [`game/screen`](https://game.nsgo.dev/docs/screen/): the table is laid out in a virtual resolution of 360 by 640 points and scaled into any window, with the pointer mapped back through the same viewport. - A fixed-step `game.Loop`, card art drawn by code on a `core.Canvas`, and native views for the counts and the buttons. ## Controls | | Keyboard | Gamepad | Touch and mouse | | --- | --- | --- | --- | | Select a card of the hand | Left, Right (A, D) | D-pad | Tap a card that does not fit | | Climb with it | Enter or Up | South | Tap it, or drag it onto its ladder | | Throw it away | X or Down | West | Drag it onto the discard pile | | Draw, or turn the discard pile over | Space | North | Tap the draw pile, drag its top card into the hand, or press Draw | | New deal | N | Start | New deal, or Next deal once a game is over | Starting a new deal before a game is over counts as a loss. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window, the display of 360 by 640 points, the input map and the export presets. | | `rules.yaml`, `rules.go` | The deck: its suits and their colors, the highest rank and the number of redeals, read with unknown fields refused and checked to round-trip unchanged. | | `board.yaml` | The table as a `cards.BoardDoc`: a ladder per suit named `ladder-` that accepts only that suit, the draw pile, the discard pile, and the hand with its capacity. | | `table.go` | The rules on the board: dealing, drawing, climbing, throwing away, redealing and judging the win and the loss. | | `save.go` | The save slots `records` and `table`, and the checks a saved game passes before it is restored. | | `game.go` | `Root`, the loop and the actions of the input map. | | `render.go`, `hud.go` | The card art and the table drawn through the viewport, and the native views over it. | | `*_test.go` | Playthroughs with the keyboard, a gamepad and touch to a win and a loss, and tests of the rules, the saves and the data files, with a fuzz test of `rules.yaml` and a benchmark of a whole game. | ## Where to change it - The deck and the difficulty are in `rules.yaml`. `TestSomeDealsAreWon` fails when a careful player, as the tests play, wins fewer than a tenth or more than nine tenths of 200 deals, and `winDeal` and `loseDeal` in `table_test.go` are the deals the playthroughs win and lose; after changing the rules, pick them again. - The table's layout is in `board.yaml`, in the display's coordinates. `newTable` refuses a board that lacks a slot the rules need. - The moves are in `table.go`: `allows` says which card may go where, `canDraw` when a card may be drawn or the discard pile turned over, and `judge` when a game is won or lost. - The controls are in `game.yaml`'s input map, which `go run github.com/nsgo-dev/game/cmd/gameproject check` validates. - The card art is `drawCard` and `drawSuit` in `render.go`. ## Limits The playthroughs drive the game with nsgotest's keyboard, gamepad and touch from a strategy that reads the table, rather than recording a human player; [`game/replay`](https://game.nsgo.dev/docs/replay/) records and replays real input when a game needs that. --- Source: https://game.nsgo.dev/docs/template-fighting2d/ # The fighting game template `fighting2d` is a one-on-one 2D fighting game to start a fighter from: two original characters, special moves from motion inputs, cancels and combos, guarding high and low, best-of-three rounds on a timer, a CPU opponent, and a second player on the same keyboard, on a second game controller or, against the CPU, on touch. It is built mainly on [fighting](https://game.nsgo.dev/docs/fighting/), which recognizes the inputs, and [framedata](https://game.nsgo.dev/docs/framedata/), which resolves the hits, with [input](https://game.nsgo.dev/docs/input/), [sound](https://game.nsgo.dev/docs/sound/), [screen](https://game.nsgo.dev/docs/screen/) and the [placeholder pack](https://game.nsgo.dev/docs/placeholder/)'s sounds. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template fighting2d myfighter cd myfighter go tool nsgo dev ``` `nsgo init -template github.com/nsgo-dev/game/template/fighting2d` writes the same project ([Templates](https://game.nsgo.dev/docs/templates/)). ## What it shows - **Motion inputs and combos.** Each fighter's move set (`data/.moves.yaml`) is a `fighting.MoveSet`: Kestrel's gale is a quarter circle forward, its talon a dragon punch, Basalt's ram a charge back then forward, and both have a double-tap dash or backstep. A `fighting.Recognizer` per player reads the input every step, mirrored as the fighter turns, and its combos name the strings that land. - **Frame data is the game and the art.** Every move's hurtboxes, hitboxes, damage, hitstun, blockstun, knockback and cancel windows are a `framedata.Doc` (`data/.frames.yaml`), stepped by a `framedata.World` that finds the hits. The fighters are drawn from the same boxes, the first hurtbox as the head, so what is seen is what can hit and be hit; F1 shows the boxes themselves in debug builds. - **Guarding.** Holding back while the opponent attacks within reach, or a projectile closes in, guards; holding down-back guards crouching. Lows must be guarded crouching and overheads standing, and a guarded special still deals chip damage. - **Rounds.** A round ends on a knockout or when the 60 second timer runs out, when the fighter with the larger share of its health left wins it, so the sturdier fighter gains nothing from its larger health bar. A double knockout or a time-up with equal shares is a drawn round, which counts as a win for both fighters: the first to two rounds wins the match, so a draw after one fighter has won a round ends the match in that fighter's favour, and a draw that brings both to two wins makes the match a draw. Hitstop, combo damage scaling and pushback against the wall are rules in `data/match.yaml`. - **A CPU opponent** that decides every few steps from the distance, the opponent's attacks and jumps, and plays its decisions as input through the same recognizer and rules as a person, from per-fighter input scripts, with a seeded random source so a match replays the same way. - **Two local players.** Both players' keys, game controller buttons and sticks are one input map in `game.yaml`, its actions prefixed `p1_` and `p2_`. Each player has an `input.Actions` of its own; with two controllers connected, the first goes to player 1 and the second to player 2. Touch gives player 1 an on-screen stick and two attack buttons, whose regions are also in `game.yaml`. - **Tests that play it.** `nsgotest` playthroughs lose a match against the CPU by standing still, win one from the keyboard with special moves, guards and combos, win a versus match with two game controllers, and play with touch; unit tests check each rule and that every data file is canonical. ## Controls | | Player 1 | Player 2 | Game controller | Touch | | --- | --- | --- | --- | --- | | Move, jump, crouch | W A S D | Arrows | D-pad or left stick | A stick on the left half of the screen | | Light | J | . | X / Square, A / Cross | L | | Heavy | K | / | Y / Triangle, B / Circle | H | | Start, pause | Enter | Right Shift | Start | Pause | On the title screen, each player's left and right pick a fighter, player 1's Start fights the CPU and player 2's starts a versus match. Escape pauses, and on the result screen Enter asks for a rematch and Escape goes back to the title screen. Against the CPU, player 1 may use either side of the keyboard. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window, the 480 by 270 virtual resolution, both players' input map, the sound bus and the export presets. | | `data/match.yaml` | The rules, the CPU's tuning and the roster. For each fighter: its name, colors, health, speeds, its two data files, and what frame data does not say about some moves: their hit level, whether they are special, how they move the fighter, the projectile they throw, and the CPU's input scripts. | | `data/.moves.yaml` | The fighter's move set (`fighting`). | | `data/.frames.yaml` | The fighter's frame data (`framedata`). | | `data.go` | Reads and checks the data; `match.yaml`'s format, versioned, refusing unknown fields and written back unchanged, is defined here. | | `match.go` | A match: rounds, the timer, hits and damage, projectiles and spacing, stepped with both players' input and knowing nothing of devices or the screen. | | `player.go` | One fighter: turning recognized moves into frame data moves standing, crouching or in the air, stances, guards, walking, jumping and falling. | | `cpu.go` | The CPU opponent. | | `controls.go` | Both players' input devices. | | `game.go`, `hud.go`, `draw.go` | The loop and the screens, the native HUD and menus, and the Canvas drawing. | A move named in a move set plays the frame data move of the same name, `crouch_` while crouching if the frame data has one, and `air_` in the air. The stance moves `idle`, `walk`, `crouch`, `jump`, `guard`, `crouch_guard`, `hurt` and `ko` loop, and every fighter has them; the game checks all of this when it loads the data, and its tests do too. ## Where to change it - **A move's speed, reach and damage**: its boxes in `data/.frames.yaml`. Startup is the first frame a hitbox is active on, recovery the frames after the last, and `cancels` the windows where it may be cut short. - **A move's input**: `data/.moves.yaml`, such as a longer `window` for an easier motion or a `charge` for a charge move. - **How a move moves, its hit level and its projectile**: its entry in `data/match.yaml`'s `moves`. - **A new fighter**: a move set, frame data and an entry in `data/match.yaml`'s `fighters`, with the CPU scripts it plays that fighter with. The title screen offers every fighter of the roster. - **The rules and the CPU's difficulty**: `data/match.yaml`'s `rules` and `cpu`, such as `roundsToWin`, `roundSeconds`, `hitstop` or the CPU's `block` chance and `reaction` time. - **Keys and buttons**: the `input` of `game.yaml`. - **Art**: `draw.go` draws shapes from the boxes; replace them with sprites chosen by the move and frame each fighter plays, which `framedata.Move.Animation` can name. ## What it leaves to the game `framedata` resolves hits but leaves movement and hit levels to the game, so `data/match.yaml` adds them: `motion` moves a fighter on a range of a move's frames, `level` makes a move low or overhead, and `projectile` throws a looping move of the same frame data as a fighter of its own on the thrower's team. A game that grows throws, knockdowns or a super meter adds them the same way: frame data for the boxes, and the match file for the rest. --- Source: https://game.nsgo.dev/docs/template-fps3d/ # The fps3d template `fps3d` is a first-person shooter arena, Relay Yard: the player holds a walled yard against three waves of drones and wardens with a hitscan rifle and a projectile launcher, picking up health and ammo between fights. Clearing the last wave wins; reaching 0 health loses. It is the template to start from for a 3D shooter, and a working example of the 3D packages together: `physics3d`, `render3d`, `ai` and `input`. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template fps3d mygame cd mygame go tool nsgo dev ``` ## What it shows - Movement: the player and every enemy are `physics3d.CharacterController` capsules in one `physics3d.World`, so they slide along walls, step and jump. Walls and crates are static boxes, and enemies are kinematic bodies the player bumps into and shots hit. - Shooting: the rifle is hitscan, a `RaycastFirstLayer` through the wall and enemy layers the moment it fires; the launcher fires a round that flies a segment each step and bursts with splash damage. Magazines, reserves, reloads and fire rate come from the arena file, and an empty magazine reloads by itself. - Enemies: each one runs an `ai` behavior tree, a selector of guarded branches that attacks the player in sight, hunts the place the player was last seen or heard (a shot alerts every enemy within earshot), and otherwise patrols the arena's route. It walks A* paths over an `ai.BoolGrid` of the layout, smoothed with `ai.SmoothGridPath`, and fires bolts the player can dodge. An enemy sees along a line that clears every wall edge by a margin, so it never shoots at the player through a corner the player cannot see back around. - Waves: a countdown, then each wave's enemies enter at the spawns one at a time, with a pause between waves. - Rendering: `render3d`'s lit PBR pipeline draws the level as three baked meshes (floor, walls and crates) and every moving thing, the enemies, rounds, tracers, pickups and the weapon, as one unit cube scaled and placed per draw, under a `render3d.LightRig` of a sky fill, a key light and glows over the spawns and pickups, inside a `gpu.View`. The weapon is drawn in view space and kicks back on each shot. A native HUD and an overlay `core.Canvas` with the crosshair, the hit marker, the hurt flash and the touch controls sit on top. - Input: one `input.Actions` hears all three devices. `game.yaml`'s input map binds the keys, the mouse button and the controller's buttons and sticks; mouselook reads locked pointer motion (`BindPointerAxis` and `LockPointer`, requested on each press of the arena); an `input.VirtualPad` adds a floating move stick, a floating look stick and fire, jump, reload and swap buttons on touch screens. | | Keyboard and mouse | Game controller | Touch | | --- | --- | --- | --- | | Move | W A S D | Left stick | Left stick | | Look | Mouse with the pointer locked, or the arrow keys | Right stick | Look stick (drag in the lower middle) | | Fire | Left button or F | Right trigger | Fire | | Jump | Space | South | Jump | | Reload | R | West | Reload | | Next weapon | Q, or 1 and 2 | North | Swap | | Pause, play again | P or Enter | Start | Play again | ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: name, id, window, export presets and the input map. | | `arena.yaml` | The level and every gameplay number: the layout drawn in characters, the player, the weapons, the enemy kinds, the pickups, the waves, the countdown and the intermission. | | `arena.go` | The arena file's schema: each field documented, a version field, unknown fields refused, validation (a walled border, one start, a patrol route without gaps, every open cell reachable) and an encoder whose output reads back unchanged. | | `match.go` | One match: the world, the player's movement and weapons, rounds in flight, pickups and waves. It takes a `controls` value each step and never reads a device, so it is deterministic and tests drive it directly. | | `enemy.go` | An enemy's body, behavior tree, sight and path following. | | `controls.go` | The actions, the touch pad's layout and how a step's input becomes `controls`. | | `render.go` | The renderer: the baked level meshes, the unit cube, the materials, the lights and the per-frame draws. | | `game.go` | The root component, the 60 Hz `game.Loop`, pause and play again, the HUD, the overlay and the end panel. | | `*_test.go` | The arena file's round trip, refusals and fuzz test; the rules of the match; a bot that aims, fires, strafes and heals; playthroughs that win with the keyboard and mouse and with a controller and lose by standing still; the touch controls; and a frame rendered on the headless GPU. | The arena file is the place to start reading: everything `match.go` does is tuned by it, and the layout is readable as a map. ```yaml layout: - '#################' - '#S......#......S#' - '#.##.........##.#' - '#.#..1..c..2..#.#' - '#.....#####.....#' - '#..c....H....c..#' - '#...#...P...#...#' ``` `#` is a wall, `c` a crate low enough to shoot over, `P` the start, `S` an enemy spawn, `1` to `9` the patrol route in order, and each pickup's `symbol` (`H` and `A` here) places that pickup. ## Where to change it - A level: edit `layout`. `ParseArena` refuses a layout it cannot run, with the row and column of the problem. - Balance: weapon damage, fire interval, magazine and reserve; enemy health, speed, sight range, field of view, attack range and bolts; the size and order of the waves. All of it is in `arena.yaml`, and the playthrough tests show at once whether the game can still be won and lost. - Weapons: add one to `weapons` as `hitscan` or `projectile`. Slots 1 and 2 are bound in `game.yaml`; bind `weapon3` and read it in `readControls` for a third. - Enemy behavior: add a guarded branch to the selector in `newEnemy`, such as retreating to cover when hurt with `ai`'s tactical queries, ahead of the patrol. - Controls: rebind actions in `game.yaml`'s input map, or move the touch controls in `layoutTouchPad`. - Looks: change the materials and lights at the top of `render.go`, or draw meshes loaded with `gltf` in place of the cube. The template's tests run with `go tool nsgo test ./...` and need no GPU except for the one rendered frame, which uses the headless GPU `nsgotest` provides. --- Source: https://game.nsgo.dev/docs/template-idle/ # The idle template `idle` is Hearthkeeper, a small idle game: a fire to keep alive, generators and upgrades bought with the embers it makes, progress while the game is closed, a prestige reset and a goal that wins. Create a project from it with: ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template idle mygame ``` or with NSGo's own command, `nsgo init -template github.com/nsgo-dev/game/template/idle -module example.com/mygame mygame`. [Templates](https://game.nsgo.dev/docs/templates/) lists the others. ## What it shows - **Large numbers.** Every amount is an [`idle.Number`](https://game.nsgo.dev/docs/idle/), so prices and production keep working past float64's range, and the HUD writes them with `idle.Format` in short (1.23M), letter, scientific or engineering notation, which the player switches and the save keeps. - **Offline progress.** When the game starts or comes back from the background it credits the time since it was last seen with `idle.Offline`: at least a minute, at most eight hours, at half rate. The absence is replayed in one-second steps (`idle.Away.Steps`) through the same rules as online play, so a fire left without fuel goes out while the player is away, and a clock set back credits nothing. - **Generators, upgrades and prestige.** Generators cost `Cost × Growth^owned` (`idle.Number.Pow`), upgrades multiply one generator, all of them or a stoke, or feed the fire, and scattering the ashes restarts the run for `⌊√(earned / threshold)⌋` ash, each a lasting +10%. - **Win and loss.** Buying the Everflame wins, and play goes on after it. Letting the fuel gauge empty, online or away, loses the run; rekindling starts a new one and keeps the ash. The fire waits while a card is up, and a card changes with the game, so a win card turns into the loss when the fire went out during an absence. - **Saves.** [`save.Store`](https://game.nsgo.dev/docs/save/) keeps a versioned JSON save with a backup copy in the app's storage. Generators and upgrades are saved by id, numbers as text, and a save the game cannot use is refused rather than overwritten. - **One shop for every input.** The shop is a [`gameui`](https://game.nsgo.dev/docs/gameui/) tree on the canvas: touch and mouse press its buttons, and the keyboard and controllers move a focus over them with `SpatialNavigator`, through actions [`game.yaml`](https://game.nsgo.dev/docs/project/) binds. | | Keyboard | Controller | Touch and mouse | | --- | --- | --- | --- | | Stoke | Space | West | Tap the hearth | | Move the focus | Arrow keys, W A S D | D-pad | | | Press the focused control | Enter | South | Tap the control | | Close a card | Enter, Escape | South, East | Its button | | Switch the notation | N | North | The notation button | ## How it is organised | File | What it holds | | --- | --- | | `hearth.yaml` | The balance: fuel, generators, upgrades, prestige, the goal and the offline rules, in a versioned YAML file that refuses unknown fields and is checked when the game starts. | | `data.go` | Reads, validates and writes `hearth.yaml` deterministically. | | `sim.go` | The rules, with no view and no clock, so the loop, the offline replay and the tests all run the same code. | | `save.go` | The save slot and the notation choice. | | `game.go` | The NSGo side: the fixed-step loop, input actions, autosave, background and return, and the native HUD and cards. | | `shop.go` | The `gameui` shop and the drawn hearth. | | `game.yaml`, `project.go` | The project file, with the virtual resolution and the input map. | | `sim_test.go`, `data_test.go`, `game_test.go`, `project_test.go` | The rules and the balance, the data file with a fuzz test, a touch playthrough to the win, losses with the mouse, the keyboard and the controller, every input playing the game, and the project file. | ## Where to change it - **Numbers.** Edit `hearth.yaml`; a new generator or upgrade shows in the shop with no code. `TestBalanceReachesTheGoal` plays the game with a simple strategy and fails when the goal comes too early or too late, so it reports what a change did to the pace. - **A new kind of upgrade.** Add an effect constant and its rule to `data.go`, and apply it in `sim.go`. - **Saved state.** Add a field to `savedGame`, raise `saveVersion` and register a `save.WithMigration` for older saves. - **Offline rules.** `offline` in `hearth.yaml` sets the minimum, the cap, the rate and the replay step. - **Look.** `drawFlame` in `shop.go` draws the hearth, and `newShop` sets the `gameui` theme. --- Source: https://game.nsgo.dev/docs/template-platformer2d/ # The platformer2d template `platformer2d` is a small side-scrolling platformer: a lantern bearer runs and jumps through the three rooms of Lantern Hills, collects sparks, lights a lamp that becomes the respawn point and reaches the beacon to win. Spikes and pits cost a life, and losing the last one loses the run. It is built on [`platformer`](https://game.nsgo.dev/docs/platformer/), [`physics`](https://game.nsgo.dev/docs/physics/), [`tilemap`](https://game.nsgo.dev/docs/tilemap/), [`rooms`](https://game.nsgo.dev/docs/rooms/), [`input`](https://game.nsgo.dev/docs/input/), [`sprite`](https://game.nsgo.dev/docs/sprite/) and [`screen`](https://game.nsgo.dev/docs/screen/), and its art is drawn by code. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template platformer2d mygame cd mygame go tool nsgo dev ``` `nsgo init -template github.com/nsgo-dev/game/template/platformer2d` writes the same project, as [Templates](https://game.nsgo.dev/docs/templates/) describes. ## What it shows - A [`platformer.Controller`](https://game.nsgo.dev/docs/platformer/) over a `physics.CharacterBody` with variable-height jumps, coyote time, jump buffering, one-way ledges, wall slides and wall jumps, all tuned by `data/player.yaml`. - A level drawn as text in `data/level.yaml`, built into a `physics.Grid` to collide with, a `tilemap.Tilemap` to draw and `physics.Trigger` sensors for the spikes, sparks, lamp and beacon. - Rooms with their own camera bounds from `data/rooms.yaml`: a [`rooms.Director`](https://game.nsgo.dev/docs/rooms/) slides the camera from one room to the next, and the player waits until it lands. - One input map in `game.yaml` for the keyboard, game controllers, touch and the mouse, bound with `Project.BindInput`, with on-screen controls drawn over the touch regions on phones and tablets, and anywhere once the game view has been touched or clicked. - A 320 by 180 virtual screen scaled by whole multiples, with a native HUD and an end-of-run panel over the canvas. - Tests that play the level through to a win with the keyboard, a controller and two-finger touch, run into the spikes until the run is lost, and check the rules, the controller's timing and that every data file is canonical. ## Controls | | Keyboard | Controller | Touch | | --- | --- | --- | --- | | Run | Left and right arrows, A and D | Left stick, d-pad | The left and right arrows at the bottom left | | Jump (hold to jump higher) | Space, up arrow, W | South button | The arrow at the bottom right | | Play again after the run ends | R, Enter | Start | The Play again button | Holding the left mouse button over an on-screen control plays like touching it; on a desktop the controls appear after the first click in the game view. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window, the virtual screen, the input map and the export presets. | | `data/level.yaml` | The level: one character per tile, its tile size and the lives a run starts with. | | `data/rooms.yaml` | The rooms in world points and the camera transition into them, in the format of [`rooms`](https://game.nsgo.dev/docs/rooms/#room-maps). | | `data/player.yaml` | The controller's tuning, in the format of [`platformer`](https://game.nsgo.dev/docs/platformer/). | | `level.go` | The level format: parsing, validation and canonical encoding. | | `world.go` | One run of the level: the collision grid, the player, the sensors, the lives, the checkpoint, the goal and the rooms, stepped once per fixed step without knowing about devices or drawing. | | `game.go` | The root component, the fixed-step loop, input sampling, the HUD and the end-of-run panel. | | `draw.go`, `art.go` | Drawing a run, and the tileset and player frames drawn by code. | | `*_test.go` | The playthroughs, the rules, the controller's timing and the data files. | The level is plain text, one row per line: ```yaml version: 1 name: Lantern Hills tileSize: 16 lives: 3 tiles: | #....................# #.P....^^....o.......# ###################### ``` | Glyph | Tile | | --- | --- | | `.` | Empty | | `#` | Ground, solid from every side | | `=` | A ledge you can jump up through | | `^` | Spikes, which cost a life | | `o` | A spark to collect | | `C` | A checkpoint lamp | | `G` | The goal beacon, exactly one | | `P` | Where the player starts, exactly one | `name` is shown on the panel at the end of a run. Every row has the same width, and every `P` and `C` has ground or a ledge under it. Unknown fields, unknown glyphs and a version other than 1 are refused, and the game writes the file back byte for byte, so a review shows only real edits. ## Where to change it - **A new level**: edit the tiles in `data/level.yaml` and keep `data/rooms.yaml` covering every column; `parseLevel` refuses a start (`P`) or lamp (`C`) with nothing to stand on, and `TestDataFilesAreCanonical` and `TestRoomsCoverTheLevel` report what is wrong. The playthrough test jumps at spikes, pits and walls ahead of the player, so a route that needs more than that needs a change to `obstacleAhead` in `game_test.go`. - **How the jump feels**: `data/player.yaml`. A longer `coyote_time` or `jump_buffer` forgives late and early presses, and `wall_jump_speed_y: 0` turns wall jumps off. - **A new tile kind**: a glyph in `level.go`, a case in `newWorld` for what it does and one in `newTilemap` for how it looks. - **Enemies and moving platforms**: give each a `physics.Body`, move it in `world.step`, pass moving platforms to `Controller.Step`, and add a sensor that sets `hurt`. - **Controls**: the `input` section of `game.yaml`; touch regions are in virtual screen points. - **Art**: load an atlas with `sprite.LoadAtlas` in `newPlayerAtlas` and a tileset image in `newTilemap`, or load the whole level from a Tiled map with `tilemap.LoadTiled`. - **Sound**: a `sound.Mixer` configured from an `audio` section in `game.yaml`. --- Source: https://game.nsgo.dev/docs/template-racing3d/ # Racing 3D Template The `racing3d` template is a small 3D racing game: two laps of a closed circuit against two computer-driven rivals, from the back of the grid, with a countdown, checkpoints, a ghost of your best lap and a results screen. It plays with a keyboard, a gamepad or touch, on the desktop, phones and the web. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template racing3d myracer cd myracer go tool nsgo dev ``` [Templates](https://game.nsgo.dev/docs/templates/) describes `game new` and `nsgo init -template`, which writes the same project from the module `github.com/nsgo-dev/game/template/racing3d`. ## What it shows - Raycast cars from [`vehicle`](https://game.nsgo.dev/docs/vehicle/) on a [`physics3d`](https://game.nsgo.dev/docs/physics3d/) world, every car tuned by one `vehicle.Config` file. - Laps and checkpoints with `vehicle.Race`: a lap counts only when a car passes every checkpoint in order, so cutting the track does not pay. - A three-second countdown, a HUD with the lap, the position and the lap clock, and a results screen. Finishing first wins; finishing lower, or not finishing before both rivals do, loses. - Rivals that follow a racing line: they steer toward a point ahead on the line and hold a speed planned to brake for every corner, scaled by each rival's pace. - A ghost of your best flying lap, recorded with `vehicle.GhostRecorder`, raced against on every lap after the first and kept between launches in the app's storage as the YAML `vehicle.EncodeGhost` writes. Lap 1 starts on the grid behind the line, so it is neither saved as the ghost nor raced against one, and a one-lap race has no ghost. The saved ghost names a hash of the track file, so editing anything in `data/track.yaml` retires it. - A scene on a GPU view drawn with [`render3d`](https://game.nsgo.dev/docs/render3d/)'s lit PBR pipeline: the road, curbs, posts and cars are meshes built in code, and the crates beside the road are the [placeholder pack](https://game.nsgo.dev/docs/placeholder/)'s `crate.glb`, read with `gltf`. - One input map in `game.yaml` for the keyboard, gamepads and touch, read with `input.Actions` and `vehicle.Controls`, and an `input.VirtualPad` for the on-screen stick and pedals. - Tests that play whole races through the app with each kind of input, reaching a win and a loss. ## Controls | | Keyboard | Gamepad | Touch | | --- | --- | --- | --- | | Accelerate | Up or W | Right trigger or A | GAS | | Brake, then reverse | Down or S | Left trigger or X | BRAKE | | Steer | Left and Right, or A and D | Left stick or the D-pad | the stick, anywhere on the lower left | | Handbrake | Space | B | | | Back on the road | R | Y | R | | Race again | Enter | Start | Race again | ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window and the input map, with the actions `throttle`, `brake`, `steerLeft`, `steerRight`, `handbrake`, `respawn` and `confirm` and the `steer` axis over the keys and the left stick. | | `data/track.yaml` | The circuit: its centerline points, width, laps, checkpoints, starting grid, and the rivals' names, colors, pace and lanes. | | `data/car.yaml` | The car's tuning, a `vehicle.Config`. | | `track.go` | The track file's format: `ParseTrack` refuses unknown fields and out-of-range values, and `EncodeTrack` writes it back unchanged. | | `course.go` | The track turned into geometry: samples every couple of meters along the centerline, the checkpoints, the grid, and the racing line's speed at each sample. | | `race.go` | The race, with no drawing: the physics world, the cars, the countdown, the laps, the standings, the results and the ghost. | | `driver.go` | The racing-line driver the rivals use. | | `scene.go`, `meshes.go`, `renderer.go` | The meshes, the lights and the GPU drawing. | | `game.go` | The root component: the GPU view, the HUD, the results screen, the touch controls, the chase camera and the `game.Loop`. | | `game_test.go`, `race_test.go`, `track_test.go` | Races played through the app with a gamepad, the keyboard and touch; races run on the simulation alone; the track format. | The race is plain Go over `physics3d` and `vehicle` with no drawing, so `race_test.go` runs whole races in milliseconds. The app's tests start it with `nsgotest.NoGPU`, as `nsgotest` draws a GPU view with a software rasterizer far too slow for minutes of racing; `TestRaceViewDraws` checks the drawing on its own at a small size. ## Where to change it - **The circuit**: edit `points`, `width` and `start` in `data/track.yaml`, keeping every point within 300 m of the origin, where the ground is. The road, curbs, checkpoints, grid and racing line all follow the points, and `TestCourseGeometry` checks the result. - **The rivals**: each rival's `pace` makes it faster or slower, and the file takes up to seven rivals. `laps` sets the race's length. - **The car**: edit `data/car.yaml`; [vehicle](https://game.nsgo.dev/docs/vehicle/) describes each field. - **Collisions between cars**: the cars pass through each other so that a crowded corner never wrecks the race. Add `layerCar` to the chassis mask in `newRace`, in `race.go`, to make them collide. - **The controls**: change the bindings in `game.yaml`; the code reads only the action and axis names. - **The art**: load your own glTF models with `gltf.LoadFS` in `sceneMeshes` and add their primitives as parts, as the crates are. --- Source: https://game.nsgo.dev/docs/template-roguelike2d/ # The roguelike2d template `roguelike2d` is a small turn-based roguelike: a delver descends the five floors of the Glimmerdeep, fights the monsters that live there, gathers weapons, armor, draughts, tonics and shards, and lifts the Heart Ember from the last floor, where the Vault Warden stands on it. Every floor is generated from the run's seed, and death is permanent: the run's save is deleted the moment the run ends, and a summary and the records of every run are kept. It is built on [`procgen`](https://game.nsgo.dev/docs/procgen/), [`entities`](https://game.nsgo.dev/docs/entities/), [`loot`](https://game.nsgo.dev/docs/loot/), [`stats`](https://game.nsgo.dev/docs/stats/), [`ability`](https://game.nsgo.dev/docs/ability/), [`save`](https://game.nsgo.dev/docs/save/), `random`, [`input`](https://game.nsgo.dev/docs/input/) and [`screen`](https://game.nsgo.dev/docs/screen/), and its art is drawn by code. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template roguelike2d mygame cd mygame go tool nsgo dev ``` `nsgo init -template github.com/nsgo-dev/game/template/roguelike2d` writes the same project, as [Templates](https://game.nsgo.dev/docs/templates/) describes. ## What it shows - Floors generated by [`procgen`](https://game.nsgo.dev/docs/procgen/) from streams forked off the run's seed: BSP rooms joined by corridors and cellular-automaton caves, with the exit on the floor cell farthest from the start, so the same seed builds the same floor on every platform. - Actors as entities: every monster and every item lying on a floor is an entity in the floor's [`entities`](https://game.nsgo.dev/docs/entities/) world, made of `Position`, `Foe`, `Guard` and `Loot` components, and the monsters' part of each turn is two systems on an `entities.Scheduler`, notice and then hunt. - Turns: each action of the player is followed by every monster's. Monsters notice the player within their sense, hunt down a breadth-first distance map and strike when next to the player; walking into one attacks it. The player sees along lines of sight, and cells seen before stay drawn, dimmer. - Weighted loot from [`loot`](https://game.nsgo.dev/docs/loot/): each floor's item cells and each monster's drops are rolled from `data/loot.yaml`, with a soft pity ramp on draughts and a hard one on the best weapon, whose counters carry from floor to floor. - Stats from [`stats`](https://game.nsgo.dev/docs/stats/): health, attack and defense with an equipment slot each for a weapon and armor, which `Sheet.Refresh` swaps, timed tonic modifiers that `Sheet.Step` counts down once a turn, and levels that raise the bases. - Abilities from [`ability`](https://game.nsgo.dev/docs/ability/): a quaff that spends a draught and a cleave that strikes every neighbour, gated by conditions and cooldowns. The caster runs at one step a second, so every duration in `data/abilities.yaml` counts turns. - Permadeath with [`save`](https://game.nsgo.dev/docs/save/): the run is saved as the player arrives on each floor and after every turn, with the floor's world of actors as an `entities` snapshot and the state of its random streams, so closing the app and opening it again resumes the run exactly where it stood. Quitting before a blow lands undoes nothing, and the slot is deleted when the run is won or lost. A records slot counts every run, and the end-of-run panel shows the summary and the records. - One input map in `game.yaml` for the keyboard, game controllers, touch and the mouse, with on-screen controls on phones and tablets, and anywhere once the game has been touched or clicked. - Tests that play the game through to a win with the keyboard, a controller and touch, and to a death, check that the run slot is gone and the records count it, resume a run from storage mid-floor and play it out the same as the run that was never closed, refuse run slots with numbers out of range, generate every floor of forty seeds, check the balance with two bots over those seeds, check the rules one by one and check that every data file is canonical. ## Controls | | Keyboard | Controller | Touch | | --- | --- | --- | --- | | Move, or attack what is in the way | Arrows, WASD | Left stick, d-pad | The arrows at the bottom left | | Wait a turn | Space, `.` | South button | The dot between the arrows | | Quaff a draught | Q | West button | `!` at the bottom right | | Cleave everything next to you | E | North button | `C` at the bottom right | | Play again after the run ends | R, Enter | Start | The Play again button | Holding a direction keeps walking, one step and then one every few frames. Holding the left mouse button over an on-screen control plays like touching it. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window, the 320 by 180 virtual screen, the input map and the export presets. | | `data/dungeon.yaml` | The player's progression, the floors, the monsters and the items, in the format below. | | `data/stats.yaml` | The player's stats and the effects weapons, armor and tonics apply, in the format of [`stats`](https://game.nsgo.dev/docs/stats/). | | `data/loot.yaml` | The drop tables floors and monsters roll, in the format of [`loot`](https://game.nsgo.dev/docs/loot/). | | `data/abilities.yaml` | The quaff and the cleave, in the format of [`ability`](https://game.nsgo.dev/docs/ability/). | | `dungeon.go`, `data.go` | The dungeon format, and loading the four files with a check of every name one uses from another. | | `floor.go` | Generating a floor: its cells, start, exit, monsters and items, the distance map and line of sight. | | `actors.go` | The components of the floor's monsters and items, and the notice and hunt systems that play the monsters' turn. | | `run.go` | One run's rules, one turn at a time, without knowing about devices or drawing. | | `records.go` | The run and records save slots, the checks a resumed run slot must pass, and the run summary. | | `game.go`, `draw.go` | The root component, the fixed-step loop, input, the HUD, the end-of-run panel and drawing. | | `*_test.go` | The playthroughs, the bots, the rules, floor generation and the data files. | The dungeon file lists the floors in the order a run descends them; every floor but the last has stairs down, and the last holds the relic: ```yaml version: 1 name: The Glimmerdeep player: weapon: rusty-pick draughts: 2 draughtHeal: 15 levelXP: 10 levelHealth: 5 levelAttack: 1 regenTurns: 5 floors: - name: The Mossy Galleries generator: bsp width: 40 height: 30 monsters: 6 items: 5 loot: floor-shallow monsters: - id: moss-rat name: Moss Rat glyph: r color: '#84cc16' health: 5 attack: 3 defense: 0 xp: 2 sense: 5 drops: rat from: 1 to: 2 weight: 3 items: - id: rusty-pick name: rusty pick kind: weapon effect: rusty-pick rank: 1 color: '#a8a29e' ``` | Field | Meaning | | --- | --- | | `player` | The starting weapon and draughts, the health a draught restores, the experience each level costs (level n needs n times `levelXP`), what a level adds to the `maxHealth` and `attack` bases, and how many turns recover 1 health (0 for none). | | `floors` | Each floor's `generator` (`bsp` or `cave`), size in cells (16 to 96 a side), how many monsters it spawns, how many times it rolls its `loot` table, and an optional `guardian`, a monster that stands on the exit and never leaves it. | | `monsters` | Each monster's display name, the letter and `#rrggbb` colour it is drawn in, its combat numbers, the experience it gives, the walking distance at which it starts to hunt, an optional `drops` table, and the floors it spawns on with its weight among them; a monster without `from` and `to` spawns only as a guardian. | | `items` | Each item's `kind`: a `weapon` or `armor` is equipped when its `rank` beats the one held and applies its stats `effect`, a `draught` adds to the draughts, a `tonic` applies its timed `effect`, and `shards` are the run's score. Loot drop counts are how many draughts or shards one drop gives. | Unknown fields, unknown kinds and generators, names that are not defined, and a version other than 1 are refused. The file is kept canonical: `TestDataFilesAreCanonical` fails when it is not in the form `encodeDungeon` writes, and loading a file and encoding it again changes nothing, so a review shows only real edits. `TestDataFilesAgree` checks the names the four files use from each other, including every condition and resource in `data/abilities.yaml`, which must be ones `run.condition` and `draughtPool` answer. ## Where to change it - **Floors**: edit `floors` in `data/dungeon.yaml`. `TestFloorsAreSound` generates every floor of forty seeds and reports a floor that is not connected, whose exit is too close or whose spawns overlap; `procgen.BSPConfig` and `procgen.CaveConfig` in `generateFloor` shape the rooms and caves further. - **Balance**: monsters' numbers, the player's progression and the loot weights. `TestBotsWinAndLose` plays forty seeds with a bot that clears each floor and one that dives for the exits, and fails when the first stops winning or the second stops dying; it logs both counts. - **A new monster or item**: an entry in `data/dungeon.yaml`, its stats effect in `data/stats.yaml` for gear and tonics, and a line in a loot table for items. A new item kind needs a case in `run.take`. - **A new ability**: an entry in `data/abilities.yaml` with an `action`, a binding for that action in `game.yaml`, and a case in `run.abilityEvent` for its effect. `roguelikeGame.update` activates every ability by the `action` its entry names, and `run.act` uses whichever ability the action carries. A new condition or resource also needs a case in `run.condition` or `draughtPool` and its name in the data check. - **Smarter monsters**: the hunt system in `actors.go` walks down one distance map. A new behaviour is a new component and one more system on the scheduler `run.newMonsterTurn` builds, ordered with `entities.Before` and `entities.After`; [`ai`](https://game.nsgo.dev/docs/ai/) has behaviour trees and pathfinding for monsters that flee, keep their distance or patrol. - **Controls**: the `input` section of `game.yaml`; touch regions are in virtual screen points. `repeatDelay` and `repeatEvery` in `game.go` set how fast a held direction walks. - **Art**: `draw.go` draws letters and shapes; load an atlas with `sprite.LoadAtlas` and draw a `tilemap.Tilemap` painted with `procgen.Grid.Paint` instead. - **Saving**: `runSave` in `records.go` is the run slot, and the codecs `newActors` registers name the components in it. When either changes shape, raise `saveVersion` and give `newSaveStore` a `save.WithMigration`. --- Source: https://game.nsgo.dev/docs/template-rpg2d/ # The rpg2d template `rpg2d` is a small top-down RPG called Hollowbrook: a town and the meadow beyond its gate, three people to talk to, a pack of items and equipment, one quest, turn-based battles and three save slots. It is one of the [templates](https://game.nsgo.dev/docs/templates/), and the starting point for a game of that kind. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template rpg2d mygame cd mygame go tool nsgo dev ``` `nsgo init -template github.com/nsgo-dev/game/template/rpg2d -module example.com/mygame mygame` writes the same project. ## What it shows The shrine lamp of Hollowbrook has gone out. Mira the healer needs three glowcaps from Whisper Meadow to light it again, and Thornhide, an old bramble boar, keeps the gatherers away. The starting stick cannot beat Thornhide: the player earns the coins for Bram's iron sword from the moss slimes, finds a leather vest in the meadow, equips both, drives Thornhide off and brings the glowcaps back to win. Losing every HP in a battle ends the game, with a save to load or a new game to start. | Part of the genre | How the template does it | Package | | --- | --- | --- | | Maps | Two maps drawn as rows of characters in `data/world.yaml`, built into tile maps with solid tiles flagged for collision and a camera that follows the player | [tilemap](https://game.nsgo.dev/docs/tilemap/) | | Walking | Tile-by-tile movement on a fixed-step loop, exits between maps, items picked up by walking onto them and foes that patrol | [loop](https://game.nsgo.dev/docs/loop/) | | Dialogue | A Yarn Spinner script with branching options, conditions on what the player has, and commands that give and take items, start the quest and heal, played with portraits and a typewriter | [vn](https://game.nsgo.dev/docs/vn/), [flow](https://game.nsgo.dev/docs/flow/) | | Items and equipment | A bag of slots, and weapon, armor and charm slots whose bonuses come from named effects | [inventory](https://game.nsgo.dev/docs/inventory/), [stats](https://game.nsgo.dev/docs/stats/) | | Quest | One quest with objectives to gather, defeat and report, and rewards granted when it completes | [quest](https://game.nsgo.dev/docs/quest/) | | Battles | Turn-based fights with Attack, Potion and Flee, where a boss cannot be fled from | | | Saves | Three slots in the app's storage holding the bag, equipment, quest, dialogue state and the map | [save](https://game.nsgo.dev/docs/save/) | | Screens | Title, map, battle, defeat and victory scenes with fades between them | [scene](https://game.nsgo.dev/docs/scene/) | Every control is bound in `game.yaml`'s input map: the arrows, WASD, Enter, Escape and Tab on a keyboard; the D-pad, left stick, South, East and Start on a gamepad; and an on-screen pad with A and B buttons for touch and the mouse, drawn on phones and tablets and, on other devices, once the map is touched or clicked. Menus are native buttons, so a tap or a click picks an entry, and the keyboard and gamepad move an outline through them. The tests play the game through the app: to the victory screen with the keyboard, and to the defeat screen with a gamepad and with the touch pad, saving and loading on the way. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window, the 480×270 virtual resolution, the input map and the export presets | | `data/world.yaml` | The tiles, the foes' stats, where a new game starts, and each map's rows, exits, people, foes with their patrols, and items. The format is defined in `world.go`: it has a version, refuses unknown fields and is written back unchanged | | `data/items.yaml`, `data/stats.yaml`, `data/quests.yaml` | The item catalog, the player's stats and the equipment's effects, and the quest book | | `data/cast.yaml`, `data/dialogue.yarn` | The people's names, colors and portraits, and what they say | | `data.go` | Loads the data files and checks that they agree: that every item, foe, person, dialogue node, effect and picture they name exists | | `game.go`, `menu.go`, `save.go` | The rules, the menus and the save slots, with no drawing or input devices, so tests drive them directly | | `input.go`, `draw.go`, `art.go`, `ui.go` | The input map read into one step's intent, the drawing of each screen, the pixel art painted at start-up, and the app with its HUD | A data file that does not load shows its error in the window instead of the game, so it can be fixed under `go tool nsgo dev`. ## Where to change it - **A map**: add one to `maps` in `data/world.yaml`, with an exit to it from another map. A new kind of tile or foe goes in `tiles` or `foes`, and its picture in `art.go`. - **A person**: add them to a map's `people`, to `data/cast.yaml` with their portraits, and give them a node in `data/dialogue.yarn`. - **An item**: add it to `data/items.yaml`. A piece of equipment also needs an effect of the same name in `data/stats.yaml`. - **A quest**: add it to `data/quests.yaml` and start it from a conversation with `<>`. `mainQuest` in `data.go` is the quest whose completion wins the game. - **Balance**: the foes' stats are in `data/world.yaml`, the player's in `data/stats.yaml`. `TestThornhideNeedsTheIronSword` checks the fight the game is built around. - **Controls**: edit the input map in `game.yaml`; the touch pad is drawn where its regions are. - **Art**: replace `newAtlas` in `art.go` with `sprite.LoadAtlas`, keeping the frame names the data files use. --- Source: https://game.nsgo.dev/docs/template-rts2d/ # The rts2d template `rts2d` is a 2D real-time strategy skirmish, Shardfront: two bases on one map, crystals to mine, barracks to build, three unit types, fog of war, box selection, control groups and a computer opponent. The side whose headquarters falls first loses; both falling in the same step is a draw. It is small enough to read in an afternoon and laid out the way a strategy game grows: the rules, the map and the opponent's priorities are YAML data files, the simulation knows nothing of views or input, and the player and the opponent give their orders through the same functions. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template rts2d mygame cd mygame go tool nsgo dev ``` Or, with NSGo's own command, `nsgo init -template github.com/nsgo-dev/game/template/rts2d -module example.com/mygame mygame` ([Templates](https://game.nsgo.dev/docs/templates/)). ## What it shows - [rts](https://game.nsgo.dev/docs/rts/): one `rts.Crowd` moves every unit of both sides over the map's grid on shared flow fields; `rts.BoxSelector` and `rts.Selection` turn clicks, drags, taps and the gamepad cursor into selections; `rts.ControlGroups` keeps the ten numbered groups; and ordered groups take the formation `data/formations.yaml` defines. - [fog](https://game.nsgo.dev/docs/fog/): each side sees from its units and buildings, rocks block sight, the opponent's base is hidden until scouted, and explored ground stays dimmed. An enemy building out of sight shows as it was when last seen, and one put up since stays hidden until it is seen. - [ai](https://game.nsgo.dev/docs/ai/): the opponent scores its actions (train a worker, build a barracks, train a soldier or a ranger, attack, defend) with a utility reasoner built from `data/opponent.yaml` once a second, and carries out the best one. It sees through its own side's fog of war, as the player does, and knows the map, so it knows where the player's headquarters stands. - [input](https://game.nsgo.dev/docs/input/) and the [project file](https://game.nsgo.dev/docs/project/)'s input map: keys and gamepad buttons are named actions in `game.yaml`, the gamepad's stick and the arrow keys drive one cursor, and the mouse and fingers act on the battlefield view directly. - A fixed-step [game loop](https://game.nsgo.dev/docs/loop/) at 60 steps a second, the battlefield drawn by code on a `core.Canvas` through the [screen](https://game.nsgo.dev/docs/screen/) viewport `game.yaml`'s `display` sets, and native NSGo buttons for the HUD and the command bar. - Headless tests that play whole skirmishes to a win and a loss through the keyboard and mouse, test the gamepad and touch controls, and check that every data file is canonical. ## Controls | | Keyboard and mouse | Gamepad | Touch | | --- | --- | --- | --- | | Select | Click a unit; drag a box; double-click for every unit of that type; Shift adds, Ctrl or Command toggles | Left stick or D-pad moves the cursor; South picks, hold it and move to drag a box | Tap a unit; drag a box | | Command | Right-click an enemy to attack it, crystals to mine them, or ground to go there, fighting on the way | East at the cursor | Tap with units selected | | Control groups | Ctrl or Command with a digit binds, Shift with a digit adds, a digit recalls, twice highlights | Keyboard only | Keyboard only | | Train worker, soldier, ranger | Q, W, E | West, North, right shoulder | Command bar | | Build barracks | B | Left shoulder | Command bar | | Select army, workers | A, S | Left trigger, right trigger | Command bar | | Clear selection | Escape | Back | Clear button | | Pause, play again | P; Enter on the result screen | Start | Pause button | The arrow keys, Space and Enter drive the gamepad's cursor too, so the keyboard alone plays. A barracks goes on a free build pad of the player's base, and workers mine on their own once trained. Combat units left idle attack the enemies they see, so units at home defend it. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: the window, the 480 by 264 virtual resolution, the input map and the export presets. | | `data/rules.yaml` | Units, buildings and the economy: health, speed, damage, range, sight, costs, training and build times, the starting units, the queue and unit limits. | | `data/map.yaml` | The battlefield as rows of characters: `.` ground, `#` rock, `*` crystals, `A` and `B` the headquarters, `a` and `b` the build pads. | | `data/formations.yaml` | The formation ordered groups take, in rts's format. | | `data/opponent.yaml` | The opponent's actions and the considerations that score them, in ai's utility format. | | `data.go` | Reads and checks the data files. | | `world.go`, `orders.go` | The simulation and the orders both sides give. | | `opponent.go` | The computer player. | | `control.go` | The player's selection, control groups, cursor, and mouse, touch, keyboard and gamepad handling. | | `view.go`, `draw.go` | `Root`, the HUD, the command bar, the pause and result screens, and the drawing. | `data/rules.yaml` and `data/map.yaml` are schemas of the template's own: each has a `version`, refuses unknown fields, and writes back the bytes it read, which `TestDataFilesAreCanonical` checks along with the two files in the packages' formats. ## Where to change it - Balance: `data/rules.yaml`. The opponent's priorities and the army it attacks with: `data/opponent.yaml`. The playthrough tests play real skirmishes, so a large change may need the strategy in `playthrough_test.go` adjusted. - The map: `data/map.yaml`, with one `A` and one `B`, ground under each footprint, and no two footprints sharing a cell. - A unit type: the controls, the command bar and the opponent train `worker`, `soldier` and `ranger` by name, so `data/rules.yaml` must keep those three (loading it fails otherwise). To add one, add it to `data/rules.yaml`, then a shape in `drawUnit`, a key and a gamepad button in `game.yaml` read in `readActions`, and a button in `commandBar`. - A plain move, to retreat: a ground command is an attack-move, so units fight on the way. Give `command` a modifier or a second button that calls `moveGroup` with `orderMove` instead, which ignores enemies until the units arrive. - Art: `draw.go` draws everything by code; swap one kind of thing at a time for sprites from [sprite](https://game.nsgo.dev/docs/sprite/). - A map larger than the screen: draw under a `tilemap.Camera` and center it on a control group recalled twice, which `focus` highlights now. - Sound, a title screen, saves and replays: the world steps deterministically, so [sound](https://game.nsgo.dev/docs/sound/), [scene](https://game.nsgo.dev/docs/scene/), [save](https://game.nsgo.dev/docs/save/) and [replay](https://game.nsgo.dev/docs/replay/) fit around `skirmish.update` without changing the simulation. --- Source: https://game.nsgo.dev/docs/template-towerdefense2d/ # Tower defense template The `towerdefense2d` [template](https://game.nsgo.dev/docs/templates/) is Bramble Gate, a small 2D tower defense game: enemies walk a road from a spawn to a gate, and the player builds towers on the grass beside it, upgrades them with the money the enemies drop and calls each wave when ready. Stopping all five waves wins; letting ten lives' worth of enemies through the gate loses. It plays with a keyboard, a gamepad or touches on desktop, mobile and the web, and all of its art is drawn in code. ```sh go run github.com/nsgo-dev/game/cmd/game@latest new -template towerdefense2d mygame cd mygame go tool nsgo dev ``` `nsgo init -template github.com/nsgo-dev/game/template/towerdefense2d -module example.com/mygame mygame` writes the same project. ## What it shows - The level, its waves and enemies, the towers with their upgrades, and the projectiles are three YAML files that `game.yaml` [autoloads](https://game.nsgo.dev/docs/project/), checked against each other when the game starts. - The road is the shortest path over the map's road tiles, found with `ai.AStar` ([ai](https://game.nsgo.dev/docs/ai/)); the map is a [tilemap](https://game.nsgo.dev/docs/tilemap/) whose cells are flagged road, buildable or solid. - Towers and enemies keep their numbers on [stats](https://game.nsgo.dev/docs/stats/) sheets: an upgrade is a permanent stat effect, and a frost tower's slow is a timed modifier on the enemy's speed. - Towers fire [bullets](https://game.nsgo.dev/docs/bullets/) patterns at the enemy furthest along the road, leading it by the projectile's flight time; a mortar's hit splashes, a frost bolt slows. - A fixed-step [loop](https://game.nsgo.dev/docs/loop/) runs the world at 60 steps a second, up to three steps an update at the fastest speed, and a [screen](https://game.nsgo.dev/docs/screen/) viewport fits the 480 by 320 map to any window under a native HUD. - The [input](https://game.nsgo.dev/docs/input/) map in `game.yaml` binds every action to a key and all but the number-key tower shortcuts and a mid-game restart to a gamepad button too, and the cursor to the arrow keys, the d-pad and the left stick; a tap on the battlefield moves the cursor and a second tap builds. - Headless `nsgotest` playthroughs play one plan to a win and another to a loss with the keyboard, a gamepad and touches. ## How it is organised | File | What it holds | | --- | --- | | `game.yaml` | The project file: window, virtual resolution, input map, autoloaded data files, export presets. | | `data/level.yaml` | The level: tile size, starting money and lives, the map, enemy kinds and waves. | | `data/towers.yaml` | The tower kinds: cost, color, stats, upgrades, the pattern each fires, and the share selling refunds. | | `data/projectiles.yaml` | The projectiles, a [bullets](https://game.nsgo.dev/docs/bullets/) pattern file. | | `data.go` | The level and tower formats, their validation, and `LoadData`. | | `world.go` | The simulation: the road, spawning, walking, targeting, hits, money, lives and the outcome. | | `game.go` | The controller: the loop, the input actions, the cursor and the HUD's state. | | `view.go` | The status bar, the battlefield canvas, the toolbar and the end banner, and the battlefield's drawing. | | `art.go` | The ground tiles and projectiles, painted in code. | | `*_test.go` | Format, simulation and playthrough tests. | `World` has no clock or randomness of its own: the same calls give the same game, so its tests drive it directly and the playthroughs drive the whole app through `nsgotest`. ## The data files `data/level.yaml` and `data/towers.yaml` are the template's own formats, each with a `version` field; they refuse unknown fields and are written back unchanged, which `TestDataFilesAreCanonical` checks. The level's `map` is one string per row, one character per tile: | Character | Tile | | --- | --- | | `.` | Grass, where towers are built | | `=` | Road | | `S` | The spawn, on the road; exactly one | | `G` | The gate, on the road; exactly one | | `^` | Rock | | `~` | Water | Every row has the same length and road must join the spawn to the gate. Enemies have `health`, `speed` and an optional `armor` stat, a `reward` and the lives a `leak` costs. A wave is groups that spawn side by side, each a `count` of one enemy every `interval` after a `delay`, and a `bonus` paid when the wave is cleared. A tower needs `damage`, `range` (game points) and `cooldown` (seconds) stats; `splash` damages everything within that radius of a hit, and `slow` with `chill` takes a share of a hit enemy's speed for that many seconds. An upgrade is a `cost` and stat `modifiers` as [stats](https://game.nsgo.dev/docs/stats/) writes them. A tower's `pattern` names a pattern in `data/projectiles.yaml` that fires one shot. ## Where to change it - Draw a new map, add enemies or waves, or retune the economy in `data/level.yaml`. The map's size in game points, `tileSize` times its columns by `tileSize` times its rows, must equal `width` and `height` under `display` in `game.yaml`, so change both together; `LoadData` refuses a map that does not match. - Add a tower kind or an upgrade in `data/towers.yaml`, with its projectile in `data/projectiles.yaml`; the HUD offers every kind, and the number keys choose the first three. - Give a tower a new behavior by reading a new stat in `World.fire` or `World.hit` in `world.go`. - Replace the painted art in `art.go` with `sprite.LoadAtlas` and image files. - Rebind a control in the `input` section of `game.yaml`. After a change, `go tool nsgo test ./...` shows whether the files still load and whether `winningPlan` in `plan_test.go` still wins; after changing a data file, `go run github.com/nsgo-dev/game/cmd/game index` updates `game.index.yaml`. --- Source: https://game.nsgo.dev/docs/templates/ # Templates A new project starts from a template: a small, complete game that builds, runs and passes its tests before you change a line. `game new` writes one into a new directory, and NSGo's `nsgo init -template` writes the same files from the template's Go module. ## The templates | Template | What it is | `nsgo init -template` module | | --- | --- | --- | | `starter` | A tap-to-score 2D game: an animated sprite on a fixed-step loop, a native HUD and headless tests, the smallest project to grow from. The default. | `github.com/nsgo-dev/game/template` | | `action3d` | A third-person 3D action adventure: an orbit camera, run, jump and attack animations blended by a state machine, melee enemies, and a key that opens the gate to the goal ([guide](https://game.nsgo.dev/docs/template-action3d/)). | `github.com/nsgo-dev/game/template/action3d` | | `cards2d` | [Suit Ladders](https://game.nsgo.dev/docs/template-cards2d/), a single-player card game: cards dragged between a draw pile, a hand, a discard pile and four ladders, rules in code, the deck and the table in YAML, numbered deals and saves. | `github.com/nsgo-dev/game/template/cards2d` | | `fighting2d` | A one-on-one 2D fighting game: two original fighters with special moves from motion inputs, combos, guards high and low, rounds and a timer, against a CPU opponent or a second player, played with the keyboard, game controllers or touch. [The fighting game template](https://game.nsgo.dev/docs/template-fighting2d/) describes it. | `github.com/nsgo-dev/game/template/fighting2d` | | `fps3d` | A first-person shooter arena in 3D: hitscan and projectile weapons, enemies that patrol, hunt and shoot with `ai` and `physics3d`, health and ammo pickups and three waves to clear, played with the keyboard and mouse, a game controller or touch. [The fps3d template](https://game.nsgo.dev/docs/template-fps3d/) describes it. | `github.com/nsgo-dev/game/template/fps3d` | | `idle` | An idle game: generators, upgrades, large numbers, offline progress on return and prestige, with a win and a loss; [The idle template](https://game.nsgo.dev/docs/template-idle/) describes it. | `github.com/nsgo-dev/game/template/idle` | | `platformer2d` | A side-scrolling platformer ([guide](https://game.nsgo.dev/docs/template-platformer2d/)): a controller with coyote time and jump buffering, three rooms with camera bounds, spikes, pits, sparks to collect, a checkpoint and a goal, played with the keyboard, a controller or touch. | `github.com/nsgo-dev/game/template/platformer2d` | | `puzzle2d` | Spark Slide, a 2D grid puzzle: slide a spark across the board to light every lamp, with levels in YAML, undo and redo, a move limit, stars per level and a level select that saves progress; plays with the keyboard, a game controller, touch and the mouse. | `github.com/nsgo-dev/game/template/puzzle2d` | | `racing3d` | A 3D racer: two laps of a closed circuit against racing-line rivals, with raycast cars, checkpoints, a countdown, a best-lap ghost and a results screen, played with keyboard, gamepad or touch. [Racing 3D template](https://game.nsgo.dev/docs/template-racing3d/) | `github.com/nsgo-dev/game/template/racing3d` | | `rhythm` | Pulse Lanes, a four-lane rhythm game: charts in YAML on a beat map, a music clock that keeps the notes in time with the music, Perfect, Great, Good and Miss judgements, combo, score, rank and an energy bar to clear or fail by, audio and video latency calibration kept per device, and best clears saved; plays with the keyboard, a game controller, touch and the mouse. | `github.com/nsgo-dev/game/template/rhythm` | | `roguelike2d` | A turn-based roguelike ([guide](https://game.nsgo.dev/docs/template-roguelike2d/)): five floors generated from the run's seed as BSP rooms and caves, bump-to-attack combat, weighted loot with pity, stats with equipment and timed tonics, a quaff and a cleave on turn cooldowns, permadeath and a run summary, played with the keyboard, a controller or touch. | `github.com/nsgo-dev/game/template/roguelike2d` | | `rpg2d` | A top-down RPG: a town and a meadow to walk, people with branching dialogue, an inventory with equipment, one quest, turn-based battles and three save slots. [Guide](https://game.nsgo.dev/docs/template-rpg2d/). | `github.com/nsgo-dev/game/template/rpg2d` | | `rts2d` | A 2D real-time strategy skirmish: gather crystals, build barracks, train three unit types and destroy a computer opponent's headquarters, with fog of war, box selection, control groups and keyboard, gamepad and touch controls ([guide](https://game.nsgo.dev/docs/template-rts2d/)). | `github.com/nsgo-dev/game/template/rts2d` | | `shmup2d` | A vertical scrolling shooter: enemy waves and a stage in YAML, bullet patterns, power-ups, bombs, a boss with three phases, lives and a score, played with the keyboard, the mouse, a controller or touch. | `github.com/nsgo-dev/game/template/shmup2d` | | `towerdefense2d` | A 2D tower defense game: towers with upgrades beside a road enemies follow, waves defined in YAML, money and lives, played with keyboard, gamepad or touch; [Tower defense template](https://game.nsgo.dev/docs/template-towerdefense2d/) describes it. | `github.com/nsgo-dev/game/template/towerdefense2d` | | `visualnovel` | A short branching visual novel: two characters, drawn backgrounds, choices that change the ending, a backlog, auto and skip modes, save slots and two languages. | `github.com/nsgo-dev/game/template/visualnovel` | `nsgo game new -list` prints the same list from the command itself, the default first. ### puzzle2d A spark slides until a wall stops it and lights every lamp it passes; lighting all of a level's lamps within its moves wins the level, and a slide into a void or running out of moves loses it. The template shows how a puzzle game grows: the rules in `board.go`, where each move is an `undo.History` move that undoes and redoes exactly; the levels in `levels.yaml`, a versioned YAML file with unknown fields refused and a canonical form, which `levels.go` reads and writes; the input map in `game.yaml`, bound into `input.Actions` with swipes from `input.GestureRecognizer`; moves animated with `tween` on a fixed-step `game.Loop`; and the stars of each level kept with `save`. To change the game, add or edit levels in `levels.yaml`, whose tests check that every level can be won in its par; rebind the controls in `game.yaml`; add a tile in `board.go` and draw it in `draw.go`. The template's README lists the controls, the level format and every file. ### rhythm Notes fall down four lanes to the beat of a song, and the player hits each lane as its note reaches the line; hits build a combo and fill the energy bar, misses drain it, and the chart is cleared by reaching the song's end with energy left and failed by running out. The template shows how a rhythm game grows: the song list, the judgement windows and the energy rules in `songs.yaml`, a versioned YAML file with unknown fields refused and a canonical form, which `songs.go` reads and writes, with each song's tempo in a `rhythm` beat map beside it; the rules in `run.go`, a `Run` that judges hits by track position and knows no clock, so its tests drive it exactly; the music played through an `audio.Player` and followed by a `rhythm.Clock`, with the template unwrapping the position a looping track shorter than the song reports (`unwrapLoop`) before passing it to `rhythm.Clock.Sync`; hits judged by when the key or the finger went down rather than by the game step that reads them; latency calibration on `rhythm.CalibrationScreen`, through the same input as the charts, kept per device by `rhythm.OffsetStore`; the input map in `game.yaml`, bound into `input.Actions` with each lane's column bound to touches and the mouse; and the best clear of each chart kept with `save`. To change the game, chart a new song in `songs.yaml` with its beat map and music under `songs/`, whose tests check the file is canonical and every chart fair; tune the windows and the energy there too; rebind the controls in `game.yaml`; and change how the playfield looks in `draw.go`. The template's README lists the controls, the songs format and every file. ### shmup2d `shmup2d` is one stage of a vertical shooter on a 270×480 portrait playfield. Enemy waves fly in on dive, weave, cross and hover paths and fire [`bullets`](https://game.nsgo.dev/docs/bullets/) patterns; destroying a whole wave drops a power, bomb or life item; a boss with three phases ends the stage. Defeating the boss is the win, losing the last life the loss. It plays with the keys or WASD, a controller's stick, D-pad and buttons, and by dragging with a finger or the mouse, with a bomb button on touch screens. - `data/stage.yaml` is the stage: the ship's speeds, lives, bombs and weapons, the enemy kinds with their paths and patterns, the waves with their times, places and drops, and the boss with its phases. `stage.go` defines the format, with a version, unknown fields refused and a canonical encoding, which a test and a fuzz test hold to. - `data/patterns.yaml` holds every bullet pattern in the `bullets` format and `data/explosion.yaml` the explosion in the [`particles`](https://game.nsgo.dev/docs/particles/) format. - `world.go` is a run of the stage: the ship, enemies, waves, items and boss, and the systems that step them, which take one step's controls and report the events the game plays sounds for. `controls.go` turns the input map and the drag into those controls, `game.go` and `hud.go` hold the loop, the title, play and end screens and the native HUD. - The sprites are painted in code and the sounds come from the [placeholder pack](https://game.nsgo.dev/docs/placeholder/); `CREDITS.md` lists them. - The tests play the stage through `nsgotest`: a pilot that dodges and shoots clears it with a controller, and a ship left idle is shot down through the keyboard. Other tests cover touch, the mouse, pausing, every system of the world and the data files. Its `README.md` lists the controls and where to change the stage, the patterns, the paths, the items, the art and the sound. ### visualnovel *Lantern Crossing*: a cartographer has to get her map across a foggy river before dawn, and the ferryman decides how far to trust her. Two choices earn or lose his trust and the third, at a fork in the river, reaches the harbor or the fog, so the story has a good ending and a lost one. It is built on [`vn`](https://game.nsgo.dev/docs/vn/), which presents the script: portraits with expressions, a text box with name plates and a typewriter, choices, the backlog, and auto and skip modes; [`flow`](https://game.nsgo.dev/docs/flow/), whose dialogue runner plays the [Yarn Spinner](https://www.yarnspinner.dev/) script and keeps its variables; [`save`](https://game.nsgo.dev/docs/save/), for three save slots and the player's settings; and [`l10n`](https://game.nsgo.dev/docs/l10n/), for English and Simplified Chinese string tables. The backgrounds and portraits are drawn in code, so it needs no image files. The keyboard, a controller and touch each play all of it, from the input map in `game.yaml`. | File | What it holds | | --- | --- | | `story/story.yarn` | The story. Speakers are cast ids, every line and option has a `#line:` id, `<>` changes the background, `<>` names the ending, and each node's `chapter:` header names what a save slot shows. | | `story/cast.yaml` | The characters: name plate colors, stage slots and expressions, in `vn`'s cast format. | | `strings/en.yaml`, `strings/zh-Hans.yaml` | The interface's strings and the names, chapters and endings in each language. English lines are the script's own text; another language translates each line as `line.`. | | `story.go` | Loads the story files and shows lines and name plates in the player's language. | | `novel.go` | The game: the title screen, the story and its menus, input, save slots and settings. | | `ui.go`, `stage.go` | The buttons and menus over the stage, and the drawn backgrounds and portraits. | | `story_test.go`, `game_test.go` | Checks that the story files agree (every line translated, every background and ending known, every path ending in an ending), and plays both endings with the keyboard, a controller and touch, saving and loading on the way. | A save slot keeps the options chosen since the start, the id of the line shown and how many times that line had shown since the last choice, and loading replays that path, because the dialogue runner's saved state holds its variables and visited nodes but not where in a node it stopped. Saving over a used slot asks first. The lines read and the endings found are player settings, kept apart from the slots and saved again when the app leaves the front or quits, so skip mode knows the lines read in every playthrough. The text box keeps clear of a phone's notch and home indicator, and the backlog's Older and Newer buttons scroll it for touch and the mouse. To make the template your own, write a story in `story/story.yarn` and run its tests, which name every line without a translation and every background, ending or chapter the game does not know; add characters to `story/cast.yaml` with a look in `stage.go`, backgrounds to `backgrounds` in `stage.go`, endings to `endings` in `story.go`, and a language as a string table listed in `story.go`. The template's `README.md` lists the controls. ## Create a project from a template ```sh nsgo game new -list nsgo game new -template starter mygame ``` Outside a project, install `nsgo-game` once (`go install github.com/nsgo-dev/game/cmd/nsgo-game@latest`) for `nsgo game` ([Command Line](https://game.nsgo.dev/docs/cli/#install)), or run `go run github.com/nsgo-dev/game/cmd/game@latest new` directly with nothing to install. Without `-template`, `game new` uses `starter`. A name that is not in the list is refused with the names that are. Shell completion for `game` ([Command Line](https://game.nsgo.dev/docs/cli/#completion)) completes `-template` with the same names. [Command Line](https://game.nsgo.dev/docs/cli/#new) describes the other flags. NSGo's own command writes a template from its module without the `game` tool, with an NSGo command that supports [Go module templates](https://nsgo.dev/docs/getting-started/#templates-from-go-modules), such as the installed `nsgo` of v0.3.4 or later ([Command Line](https://game.nsgo.dev/docs/cli/#install)): ```sh nsgo init -template github.com/nsgo-dev/game/template -module example.com/mygame mygame ``` Use the module the table names for each template, and add `@` to pin one. The project's `game.yaml` and `nsgo.yaml` keep the template's own game name and identifier until you edit them, where `game new` sets them from the directory or `-name`. ## How the templates are laid out Each template is a Go module of its own in this repository, because `nsgo init -template` writes the `template` directory at the root of the module it is given. `starter` is the `template/` module itself; every other template is the module `github.com/nsgo-dev/game/template/` in `template//`: ```text template/ ├─ go.mod module github.com/nsgo-dev/game/template ├─ template/ starter └─ / ├─ go.mod module github.com/nsgo-dev/game/template/ └─ template/ the template ├─ go.mod.tmpl ├─ go.sum ├─ game.yaml ├─ nsgo.yaml ├─ main.go ├─ …_test.go ├─ README.md └─ .gitignore internal/gamecli/ ├─ templates.go the registry: one entry per template └─ _templates/projects/ ├─ starter/ a copy of template/template └─ / a copy of template//template ``` `game new` embeds the copies under `_templates/projects`, so it works from the module cache without this repository. The repository's `go.work` uses every template module, so from a checkout `go tool nsgo dev ./template//template` runs a template and `go tool nsgo test ./template//template` tests it against the local game layer. ## Add a template A template is added in one pull request of its own: 1. Create the module: `template//go.mod` declaring `module github.com/nsgo-dev/game/template/` with the `go` line of `template/go.mod`, and the project in `template//template/`. Its name is lower-case letters, digits and `-`, starting with a letter, and not `template`. 2. Add `./template/` to the `use` list of `go.work`. 3. Copy the project into the `game` CLI package, from `internal/gamecli`: `cp -R ../../template//template _templates/projects/`. 4. Add one entry to `projectTemplates` in `internal/gamecli/templates.go`: `newProjectTemplate("", templateModuleRoot+"/", "")`. 5. Add a row for the template to the table above, in `docs/en/templates.md` and `docs/zh/templates.md`, and a fragment under `changelog.d/`. The project in `template//template/` follows these rules, which the tests check where they can: - `go.mod.tmpl` starts with `module {{.Module}}`, requires a published version of `github.com/nsgo-dev/game` that has every package the template uses, and has `tool github.com/nsgo-dev/nsgo/cmd/nsgo`. It is the only file with a template action: `game new` and `nsgo init` render `nsgo.yaml`, `main.go` and any other `.tmpl` file too, but CI renders only `go.mod.tmpl` and the template must also build as it is in the workspace, so each of those must render to itself, and `main.go` cannot hold `{{`, as a composite literal such as `[]T{{...}}` does; put such code in another Go file. Other files are copied as they are and may hold any bytes. A file named `go.mod` would make the directory a module of its own, which neither `go:embed` nor the workspace can include. - `go.sum` holds the sums of the pinned modules. Write it by turning `go.mod.tmpl` into a `go.mod` in a copy of the template outside the repository and running `GOWORK=off go mod tidy` there. - `game.yaml` is canonical, as `go run github.com/nsgo-dev/game/cmd/gameproject check` reports, and `nsgo.yaml` agrees with it; `game new` replaces the `name` and `id` of both. - `main.go`, `README.md`, `.gitignore` and tests are there, and `go run ./cmd/game index template` from the repository root has nothing left to do. - Every file the template's author writes is text, as for any project in this repository. The tests of `internal/gamecli` fail when any of these steps is missing: when the copy under `_templates/projects` differs from the module's `template` directory by a byte, when a `template/*/template` directory has no registry entry, when a registry entry has no copy, module or `go.work` entry, and when this page or its Chinese counterpart has no row naming a template and its module. They also create a project from every template, build it against the local game layer and run its tests. CI's `templates` job needs no edit for a new template: it lists `template/template` and every `template/*/template` directory and tests each template the way a developer's project gets it: it copies the template out of the workspace, renders `go.mod` for `example.com/game`, and runs `go tool nsgo test ./...` with `GOWORK=off`, so the project builds against the game layer version `go.mod.tmpl` pins rather than this checkout. A template that needs a package not yet published bumps that pin once the package is on `main`. --- Source: https://game.nsgo.dev/docs/text/ # text `game/text` renders AngelCode BMFont bitmap fonts through `sprite.Batch` (with kerning, word wrapping, and alignment), signed-distance-field fonts that stay sharp at any size, on the screen or in 3D world space, and platform-rendered Unicode/CJK text through `core.Drawing.FillText`. ```go import "github.com/nsgo-dev/game/pkg/text" ``` ## Bitmap fonts (AngelCode BMFont) `LoadBMFont` and `LoadBMFontImage` parse AngelCode BMFont `.fnt` files in both **plain-text** and **XML** formats, building one `*sprite.Atlas` per texture page and indexing glyph metrics and kerning pairs. `game assets` bakes such a font from a TrueType or OpenType file with a font target, at the size and with the characters its `game.yaml` entry or its font's import settings sidecar names ([Command Line](https://game.nsgo.dev/docs/cli/#assets)): ```go //go:embed resources/pixel.fnt var pixelFNT []byte // Single-page font shortcut: font, err := text.LoadBMFontImage(core.Src("asset:pixel_0.png"), pixelFNT) if err != nil { return err } // Multi-page font: multiFont, err := text.LoadBMFont(multiFNT, func(id int, file string) core.ImageSource { return core.Src("asset:fonts/" + file) }) ``` ### Drawing, wrapping, and alignment Draw bitmap text inside `core.Canvas.Draw` with `font.Draw(d, s, x, y, opts)`: ```go font.Draw(d, "PRESS START TO CONTINUE", 160, 120, text.Options{ MaxWidth: 200, Align: text.AlignCenter, Scale: 1, Alpha: 0.95, LineSpacing: 2, Z: 10, }) ``` `Options` fields (its zero value draws left-aligned at scale `1`, full opacity, no wrapping): | Field | Behavior | | --- | --- | | `MaxWidth` | When `> 0`, wraps lines to fit within `MaxWidth` points and aligns `AlignCenter`/`AlignRight` inside `[x, x+MaxWidth]`. When `<= 0`, aligns relative to `x` directly (centered at `x`, or right edge at `x`). | | `Align` | `AlignLeft` (default), `AlignCenter`, or `AlignRight`. | | `Scale` | Multiplies glyph positions and sizes (`0` means `1`; negative draws nothing). | | `Alpha` | Opacity in `[0, 1]` (`0` means `1`; negative draws nothing). | | `LineSpacing` | Extra vertical spacing between lines, in points. | | `Z` | Passed to each glyph sprite in the underlying `sprite.Batch`. | ### Measuring and custom glyph effects Use `font.Measure(s, opts)` to compute bounding `core.Size` for speech bubbles or layout boxes, `font.Kerning(a, b)` for kerning offsets, and `font.Layout(s, x, y, opts)` to get exact `[]GlyphPlacement` positions for custom effects (such as typewriter reveals or wavy text): ```go size := font.Measure(dialogue, text.Options{MaxWidth: 220}) placements := font.Layout(dialogue, boxX, boxY, text.Options{MaxWidth: 220}) for i, g := range placements { if i >= visibleChars { break } _ = g // g.Rune, g.Glyph, g.X, g.Y, g.W, g.H, g.Line } ``` ## Signed-distance-field fonts A bitmap font is sharp only at the size it was drawn at; stretched, its edges blur. An `SDFFont` keeps a distance field instead (how far each atlas pixel is from the glyph's outline), and each glyph is resolved from it at the size it is drawn at, so its edge is one pixel wide at any size: right for text that zooms, labels in a 3D world and damage numbers that fly toward the camera. `LoadSDFFont` and `LoadSDFFontImage` read the forms the common generators write, as they write them: - [msdf-atlas-gen](https://github.com/Chlumsky/msdf-atlas-gen)'s JSON (`-json`, with `-charset` so glyphs are named by code point); - AngelCode BMFont in plain text, XML or JSON with a `distanceField` record, as [msdf-bmfont-xml](https://github.com/soimy/msdf-bmfont-xml) writes. The field type (`sdf`, `psdf`, `msdf` or `mtsdf`), the distance range and, for msdf-atlas-gen, the range's middle (`distanceRangeMiddle`, for an asymmetric `-apxrange`) and the atlas's `yOrigin` (either `bottom` or `top`) come from the file. A multi-channel field keeps corners sharp; an `mtsdf` atlas also gives outlines round corners. The loader reads the distance out of the decoded page images, so it takes `image.Image`s rather than `core.ImageSource`s: ```go //go:embed fonts/title.json fonts/title.png var fontFiles embed.FS data, _ := fontFiles.ReadFile("fonts/title.json") pngData, _ := fontFiles.ReadFile("fonts/title.png") img, err := png.Decode(bytes.NewReader(pngData)) if err != nil { return err } font, err := text.LoadSDFFontImage(img, data) ``` `font.Draw(d, s, x, y, opts)`, `font.Measure` and `font.Layout` work as a bitmap font's do, with `SDFOptions`: | Field | Behavior | | --- | --- | | `Size` | Em size in points (`0` means the font's own `Size`, the atlas's pixels an em). | | `MaxWidth`, `Align` | Wrapping and alignment, as `Options`'s. | | `LineSpacing` | Extra space between lines, in ems. | | `Color` | Fill color (`0` means opaque white). | | `Alpha` | Opacity (`0` means `1`, negative draws nothing). It is applied when drawing, so a fading label reuses its resolved glyphs. | | `Outline`, `OutlineColor` | An outline around each glyph, its width in ems, up to the field's reach (`DistanceRange/2 - DistanceRangeMiddle` atlas pixels). | | `PixelScale` | Device pixels a point covers, so glyphs are resolved at the screen's density (`0` means `1`). | NSGo's `core.Drawing` has no per-draw shader, so the threshold runs on the CPU: a glyph is resolved once per size step (sizes 2% apart share one) and color, kept in a cache bounded by `SDFFont.CacheBytes` (16 MiB by default; `CachedGlyphs` and `ClearCache` inspect and empty it), and drawn as an image. A glyph image is at most 1024 pixels a side. The font's exported fields (metrics, glyphs, kernings and field settings) are read on every call, so they can be changed after loading; a changed glyph or field setting resolves its glyphs afresh. An `SDFFont` is not safe for concurrent use; draw with it from the canvas's `Draw`. ## Text in 3D world space `font.DrawWorld(d, cam, viewport, t)` draws a `WorldText` through a `scene3d.Camera` into a canvas, with `viewport` the camera's view in the canvas's points (as `render3d.ProjectSegment`'s): ```go // A damage number that faces the camera and shrinks with distance. font.DrawWorld(d, cam, viewport, text.WorldText{ Text: "128", Pos: enemy.Pos.Add(math3d.Vec3{Y: 2}), Size: 0.5, // world units an em AnchorX: 0.5, AnchorY: 1, // bottom middle at Pos Options: text.SDFOptions{Color: core.RGB(0xffd23f), Outline: 0.08, OutlineColor: core.RGB(0x000000), Alpha: fade, PixelScale: 2}, }) // A sign fixed on a wall, read from the wall's front only. font.DrawWorld(d, cam, viewport, text.WorldText{ Text: "ARMORY", Pos: math3d.Vec3{X: 4, Y: 3}, Facing: text.FacingFixed, Rot: math3d.QuatFromAxisAngle(math3d.Vec3Up(), -math.Pi/2), Size: 0.6, CullBackFace: true, }) ``` | Field | Behavior | | --- | --- | | `Facing` | `FacingBillboard` (default) turns the text to face the camera, upright on the screen. `FacingFixed` lays it in the plane `Rot` sets: lines along `Rot`'s +X, glyphs up its +Y, read from +Z (the zero `Quat` is the identity). | | `Size` | Em size in world units, so the text shrinks with distance. | | `ScreenSize` | For a billboard, an em of this many points at any distance, in place of `Size`. | | `AnchorX`, `AnchorY` | The point of the text's box at `Pos`, as fractions from its top left. | | `CullBackFace` | Hides fixed text seen from behind; without it, it is drawn mirrored. | | `Options` | Color, outline, alignment, opacity and pixel density; `MaxWidth` is in world units (in points with `ScreenSize`), and `Size` is ignored. | A billboard is hidden when its anchor is behind the camera or past the far plane. Fixed text is hidden glyph by glyph, so a long sign the camera stands beside keeps the glyphs in view. Each fixed glyph is drawn with the affine transform closest to the perspective at its center, and every glyph is resolved at the scale it covers on the screen, so text stays sharp from up close to far away. To draw overlapping labels back to front, lay each out with `font.LayoutWorld`, sort the `WorldLayout`s by `Depth` (highest first) and draw them with `font.DrawLayout`. `Depth` is the anchor's, or, for fixed text whose anchor is behind the camera or past the far plane, the mean of its visible glyphs' centers. ## Platform text with DrawPlatform For localized prose, CJK/RTL scripts, or crisp vector labels drawn inside the game canvas, use `DrawPlatform` and `MeasurePlatform`. They draw via `core.Drawing.FillText` under the canvas's active transform (so they scale cleanly with `screen.Viewport` or `tilemap.Camera`) and wrap paint state in `Save`/`Restore`: ```go style := text.PlatformStyle{ Font: core.Font{Size: 14, Weight: core.FontBold}, Color: core.RGB(0xf8fafc), Align: text.AlignCenter, MaxWidth: 240, LineSpacing: 4, } boxSize := text.MeasurePlatform(d, "Victory! 胜利!", style) text.DrawPlatform(d, "Victory! 胜利!", 40, 24, style) _ = boxSize ``` `PlatformStyle` supports `Font`, `Color` (`0` keeps the drawing's current fill color), `Alpha` (`0` means `1`), `Align`, `Baseline` (defaults to `core.BaselineAlphabetic`), `MaxWidth`, `LineHeight` (`<= 0` uses `d.TextMetrics`), and `LineSpacing`. --- Source: https://game.nsgo.dev/docs/tilemap/ # tilemap `game/tilemap` draws orthogonal, isometric, staggered, and hexagonal tiled worlds with camera frustum culling, loads Tiled `.tmx`/`.tmj` maps (with embedded or external `.tsx`/`.tsj` tilesets and animated tiles) and YAML tilesets (`*.tileset.yaml`), queries tile collision flags and rays, and drives a 2D camera with smoothing, clamping, and screen shake. ```go import "github.com/nsgo-dev/game/pkg/tilemap" ``` ## Camera `Camera` maps world coordinates onto a view of `Width` by `Height` points centered on `(X, Y)`, scaled by `Zoom` (`<= 0` behaves as `1`), and rotated clockwise by `Rotation` radians: ```go bounds := m.WorldBounds() cam := &tilemap.Camera{ Width: 320, Height: 180, Zoom: 1, Bounds: &bounds, } ``` ### Following, clamping, and shaking Advance camera follow and shake inside `game.Loop.Update`: ```go // Exponentially smooth toward player (smoothing <= 0 snaps immediately) cam.Follow(playerPos, 8, dt) // Advance active screen shake cam.Update(dt) // Trigger a deterministic shake on impact if tookDamage { cam.Shake(6, 250*time.Millisecond) } ``` - `Clamp()` keeps `VisibleBounds()` inside `Bounds` when set; if the world is smaller than the view on an axis, the camera centers on `Bounds` along that axis. `Follow` calls `Clamp` automatically. - `Shake(intensity, duration)` applies a deterministic displacement seeded by `ShakeSeed` (decays linearly to zero over `duration`; non-positive arguments cancel any active shake). Inspect the current offset with `ShakeOffset()`. - Convert coordinates with `WorldToView(p)` and `ViewToWorld(p)`, and inspect the axis-aligned visible world box with `VisibleBounds()`. ### Applying the camera during draw Wrap world-space drawing in `d.Save()` / `d.Restore()` and call `cam.Apply(d)` before drawing tilemaps and world sprites: ```go d.Save() cam.Apply(d) m.Draw(d, cam) actorsBatch.Draw(d) d.Restore() ``` Passing `cam` to `m.Draw(d, cam)` or `m.DrawLayer(d, layer, cam)` visits only the columns and rows intersecting `cam.VisibleBounds()`. ## Loading Tiled maps `LoadTiled` parses Tiled XML (`.tmx`) and JSON (`.tmj`) maps into the same `*Tilemap`, auto-detecting the format from the input bytes. It supports embedded and external `.tsx`/`.tsj` grid and image-collection tilesets (including per-tile images, optional sub-rectangles, `tileoffset`, `objectalignment`, and cross-format references such as a `.tmx` map using a `.tsj` tileset or a `.tmj` map using a `.tsx` tileset), CSV, legacy XML ``, and base64 tile data (uncompressed, `zlib`, and `gzip`) on both finite layers and infinite-map chunks, image layers, nested group layers, layer `tintcolor` (multiplied across nested groups), Tiled JSON Wang sets (`wangsets` in `.tmj`/`.tsj`) and per-tile probabilities, GID flip bits (`FlipHorizontal`, `FlipVertical`, `FlipDiagonal`), object layers (including drawn tile objects, text objects as data, and external `.tx`/`.tj` object templates), typed custom properties, animated tiles, and the collision shapes drawn on tiles in Tiled's collision editor. `zstd` compression is refused with a `*loaderr.Error` pointing at the file, line, and fix hint. ```go //go:embed resources/maps/*.tmx resources/maps/*.tsx resources/maps/*.tx var mapFS embed.FS raw, err := mapFS.ReadFile("resources/maps/level1.tmx") if err != nil { return err } m, err := tilemap.LoadTiled(raw, tilemap.TilesetLoader{ LoadTileset: func(source string) ([]byte, error) { return mapFS.ReadFile("resources/maps/" + source) }, LoadTemplate: func(source string) ([]byte, error) { return mapFS.ReadFile("resources/maps/" + source) }, LoadImage: func(imagePath string) (core.ImageSource, error) { return core.Src("asset:maps/" + path.Base(imagePath)), nil }, }) if err != nil { return err } ``` Existing callers that set `TilesetLoader.LoadJSON` continue to work for both `.tsj` and `.tsx` tilesets when `LoadTileset` is nil. ### Image-collection tilesets, tile objects, templates, and text objects - **Image-collection tilesets**: tilesets with per-tile `` entries load into `Tileset.TileImages` (`map[uint32]TileImage`, keyed by 0-based local tile ID), preserving each tile's own width, height, and optional sub-rectangle (`X`, `Y`, `Width`, `Height`) with paths resolved relative to external tilesets. `Tileset.TileOffsetX`/`TileOffsetY` shift rendered tiles on both tile layers and tile objects, and `Tileset.ObjectAlignment` (`ObjectAlignmentUnspecified`, `TopLeft`, `Top`, `TopRight`, `Left`, `Center`, `Right`, `BottomLeft`, `Bottom`, `BottomRight`) controls tile-object anchoring (`BottomLeft` by default on orthogonal/staggered/hex maps, `Bottom` on isometric maps). - **Drawing tile objects and layer tints**: `m.Draw(d, cam)` interleaves `ObjectLayer`s with tile and image layers in Tiled's layer order, drawing every visible `ObjectTile` via `m.DrawObjectLayer(d, layer, cam)` with layer visibility, opacity, `TintColor`, offset, parallax, object size, clockwise `Rotation`, GID flip bits, `tileoffset`, `objectalignment`, and camera frustum culling. `TileLayer.TintColor`, `ImageLayer.TintColor`, and `ObjectLayer.TintColor` multiply each layer's pixels when set (set `Tinted: true` alongside `TintColor: 0` to distinguish transparent `#00000000` from untinted). - **Object templates (`.tx` / `.tj`)**: when an object references a template, `LoadTiled` loads it through `TilesetLoader.LoadTemplate` (caching each template once per map), merges the template's fields, shape, and custom properties with the instance's overrides, and remaps any template tileset GIDs into the map's tilesets (reusing an already-loaded external tileset when the canonical path matches). - **Text objects**: Tiled `` / `"text"` objects load with `Shape == ObjectText` and `Object.Text` (`*TextObject`: `Text`, `FontFamily`, `PixelSize`, `Wrap`, `Color`, `Bold`, `Italic`, `Underline`, `Strikeout`, `Kerning`, `HAlign`, `VAlign`) as structured data for game-side rendering. ### Building tilemaps in code For procedural maps or tests, build a tileset with `NewGridTileset` or `NewAtlasTileset` and populate a `Tilemap` directly: ```go ts := tilemap.NewGridTileset(1, core.Src("asset:tiles.png"), 16, 16, 8, 64) m := tilemap.New(40, 20, 16, 16, ts) ground := tilemap.NewTileLayer("ground", 40, 20, nil) m.Layers = append(m.Layers, ground) m.SetTile(0, 5, 19, 1) // layer 0, col 5, row 19 -> GID 1 ``` Look up layers and objects by name with `m.Layer("ground")` and `m.ObjectLayer("spawns")`. Read typed custom properties on maps, layers, tilesets, tiles (`m.TileProperties(gid)`), and objects via `Properties` helpers (`Bool`, `Int`, `Float`, `String`, `Color`, `File`, `ObjectID`, `Has`). For polygon/polyline objects, `obj.WorldPoints()` returns vertices translated by `(obj.X, obj.Y)`. Objects drawn as collision geometry become [physics](https://game.nsgo.dev/docs/physics/) shapes with `obj.PhysicsShape()`, and `layer.PhysicsBodies()` returns a static `physics.Body` per object, moved by the layer's offset, with the object's ID, its type as `Tag` and the object itself as `UserData`. Hidden objects count, since collision layers are often hidden: | Tiled object | Shape | | --- | --- | | Rectangle | `Box`, or a `Polygon` when rotated | | Ellipse | `Circle` when round, otherwise an 8-vertex `Polygon` inscribed in it | | Polygon | `Polygon` when convex with at most 8 vertices, otherwise a closed `Chain` along its outline | | Polyline | `Segment` for two points, otherwise an open `Chain` | | Point, tile | none | ```go for _, ground := range m.ObjectLayer("collision").PhysicsBodies() { rigid.AddBody(physics.NewStaticRigidBody(ground.Shape)) } ``` A missing layer returns no bodies. Like the objects themselves, the bodies are in the map's local coordinates; for a map placed by `Origin`, move each shape with `ground.Shape.Translated(float32(m.Origin.X), float32(m.Origin.Y))`. ## Tiled Wang sets and multi-terrain autotiling `LoadTiled` parses Tiled `wangsets` (`corner`, `edge`, and `mixed`) from embedded `.tmj` and external `.tsj` tilesets into `Tileset.WangSets`, together with each terrain color (`WangColor`: `Name`, `Color`, `Tile`, `Probability`, `Properties`), each tile's 8-slot clockwise `WangID` (`[Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, TopLeft]`), and per-tile selection weights (`Tileset.TileProbabilities` / `Tileset.TileProbability`). Use `m.SetTerrain` and `m.SetTerrainRect` to paint multi-terrain transitions (such as grass, dirt, water, and cliffs) with Tiled's terrain brush semantics across orthogonal and isometric maps as well as dense and sparse chunked layers: ```go ws := m.WangSet("Terrains") // or ts.WangSet("Terrains") / ts.WangSetAt(0) grass, _ := ws.ColorIndex("Grass") dirt, _ := ws.ColorIndex("Dirt") water, _ := ws.ColorIndex("Water") rng := random.New(42) m.SetTerrainRect(0, 0, 0, m.Width, m.Height, ws, grass, rng) m.SetTerrain(0, 4, 3, ws, dirt, rng) m.SetTerrainRect(0, 6, 2, 3, 3, ws, water, rng) ``` - **Corner, edge, and mixed sets**: `WangCorner` matches the four tile corners, `WangEdge` matches the four tile edges, and `WangMixed` matches all eight slots. Existing neighbors whose shared corners or edges change are updated automatically, including multi-hop transitions (for example creating a dirt shoreline ring when painting water onto grass in a tileset without direct grass-to-water tiles). - **Deterministic probability selection**: when multiple tiles tie for the best match, `SetTerrain` and `SetTerrainRect` choose weighted by tile probability from `*random.Stream` (or any `TerrainRand`, so the same seed always picks the same variants). Pass `rng == nil` for deterministic lowest-`TileID` selection. - **Code-defined blobs**: `AutotileSet`, `ApplyAutotile`, and `SetAutotile` remain available for code-defined 4-bit (16-tile) and 8-bit corner-gated (47-tile) single-terrain blobs. ## YAML tilesets A YAML tileset (`*.tileset.yaml`, `TilesetDoc`) is the text counterpart of Godot's TileSet resource: it says once what each tile is, and the maps that use it only place tiles. Scene files place its tiles in layered grids or single-grid inline tilemaps ([Editor & Scene Format](https://game.nsgo.dev/docs/editor/#tilemaps)). It cuts its tiles from a grid image (`image`, `columns`, `tileCount`, optional `spacing` and `margin`) or takes them from frames of a sprite atlas (`atlas`, `frames` in local ID order). A tile's local ID is its index in the grid, row by row from the top left, or in `frames`, from 0. ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/tileset.v1.json version: 1 name: cave tileWidth: 16 tileHeight: 16 image: tiles/cave.png columns: 4 tileCount: 8 terrains: - name: rock mode: cardinal tiles: - id: 0 solid: true terrain: rock - id: 1 solid: true properties: friction: 0.5 terrain: rock neighbors: [east] - id: 2 shapes: - kind: polygon points: [[0, 16], [16, 0], [16, 16]] - id: 4 animation: - tile: 4 duration: 200ms - tile: 5 duration: 200ms ``` `tiles` lists the tiles that carry more than their picture, in ascending ID order: | Field | Meaning | | --- | --- | | `name` | Optional human-readable tile name shown in inspectors and tools | | `solid`, `oneWay`, `flags` | `TileSolid`, `TileOneWay` and any further `TileFlags` bits the game defines, set on the tile with `SetFlags`; `*Tilemap` implements `physics.TileGrid` and `physics.TileGridOrigin`, so a tile marked `solid` collides through `physics.MoveAndSlide` directly | | `weight` | Optional non-negative variant weight loaded into `Tileset.TileProbabilities` | | `properties` | Custom properties, each a bool, an integer, a number or a string, as `TileProperties` returns them; the tileset has its own `properties` too | | `shapes` | Collision shapes in the tile's coordinates: `rect` and `ellipse` by `x`, `y`, `width` and `height`, `polygon` (3 points or more) and `polyline` (2 or more) by `points`, each with optional `name`, `type` and `properties`; they load into `Tileset.Shapes` as Tiled's collision editor's do, for [tileshape](https://game.nsgo.dev/docs/tileshape/) | | `animation` | Frames of `tile` and positive `duration` (such as `150ms`) that `Update` cycles through | | `terrain`, `neighbors` | The terrain set from `terrains` the tile belongs to, and the directions (`north`, `east`, `south`, `west`, and for a `blob` terrain also `northeast`, `southeast`, `southwest`, `northwest`) in which a cell of the same terrain lies next to it; a corner is listed only with both edges beside it (`northeast` with `north` and `east`), since it matches only when they do | A terrain's `mode` is `cardinal`, which matches the four edge neighbours (16 tiles, `Autotile4`), or `blob`, which also matches a corner when both edges beside it match (47 tiles, `Autotile8`). Optional `default` names the local tile ID used when a cell's neighbour mask has no mapped tile; when omitted, the tile of the terrain that lists no neighbours (mask `0`) is the default. No two tiles of a terrain may list the same neighbours. `ParseTileset` refuses unknown keys and every rule above with a `*loaderr.Error` at the line at fault, and `EncodeTileset` writes the canonical form, so loading and saving a tileset changes no byte; `LoadTilesetFS` reads one from an `fs.FS`. `m.AddTilesetDoc(doc, firstGID, assets)` builds it into a `Tileset` of `m` whose GIDs start at `firstGID`, resolving its image through `TilesetAssets.Image` (a `core.ImageSource{URI: path}` when nil) or its atlas through `TilesetAssets.Atlas`, and sets its tiles' flags on the map: ```go doc, err := tilemap.LoadTilesetFS(os.DirFS(projectDir), "tilesets/cave.tileset.yaml") if err != nil { return err } m := tilemap.New(40, 23, 16, 16) if _, err := m.AddTilesetDoc(doc, 1, tilemap.TilesetAssets{}); err != nil { return err } // Autotile a layer with the rock terrain, or paint a single terrain cell with neighbor updates. m.ApplyTerrain(0, "rock") m.SetTerrainTile(0, 4, 3, "rock", true) ``` Each terrain becomes a `Terrain` in `Tileset.Terrains` (also buildable directly from a `TilesetDoc` via `doc.Terrain(name, firstGID)`), whose `Autotile` maps neighbour masks to GIDs for `ApplyAutotile` and `SetAutotile` and whose `Contains` tells its tiles apart. `ApplyTerrain` and `SetTerrainTile` look up the named terrain on the map and run `ApplyAutotile` / `SetAutotile` directly. `ValidTerrainMask`, `ToggleTerrainMask`, `TerrainMaskNeighbors` and `TerrainNeighborsMask` convert and edit neighbour bitmasks while preserving 4-bit and 8-bit corner-gating rules. `TilesetFrame(doc, atlas, id)` gives where a tile lies in its image, as an editor's palette shows it. ## Animated tiles Tiled tile animations load into `Tileset.Animations`, keyed by 0-based local tile ID. Call `m.Update(dt)` on every `game.Loop.Update` step to advance all animated tiles cleanly across cycles: ```go m.Update(dt) ``` You can also attach a `TileAnimation` manually to a tileset by setting `ts.Animations[localID] = &tilemap.TileAnimation{Frames: ...}`. ## Y-sorting tiles with sprites Enable per-layer Y-sorting on any `TileLayer` (`layer.YSort = true` or `m.SetLayerYSort(index, true)`, or via a boolean Tiled layer custom property named `y_sort`, `ysort`, `ySort`, or `y-sort`) so tall tiles such as trees, walls, and pillars interleave with scene sprites and custom drawables by depth: ```go m.Layer("trees").YSort = true // Optional: shift a tree tile's sort line upward from its bottom edge to its trunk base. // Equivalent to setting a float/int tile custom property "sort_origin_y" = -8 in Tiled. m.SetTileSortOriginY(treeGID, -8) world := sc.AddLayer(scene.NewLayer("world", scene.SpaceWorld, 0)) world.DepthSort = scene.SortY world.AddTilemap(m) world.AddBatch(actorsBatch) ``` - **Default sort line**: each visible tile sorts by its world-space bottom edge (`offY + tileOriginY + TileHeight`), which works across orthogonal, isometric, staggered, and hexagonal orientations and matches bottom-pivoted character sprites (`OriginY = height`). - **Per-tile sort origin**: attach the custom tile property `sort_origin_y` (`tilemap.PropSortOriginY`, aliases `y_sort_origin` and `ysort_origin`) in Tiled or call `m.SetTileSortOriginY(gid, offsetY)` to offset a tile's sort line vertically (negative moves it up into a tree trunk or isometric diamond center; positive moves it down). Inspect it with `m.TileSortOriginY(gid)`. - **Layer ordering & culling**: inside a `scene.SortY` layer, non-Y-sorted layers before the first Y-sorted layer draw behind sprites (keeping any `CacheStaticLayer` fast path), Y-sorted layers interleave individual visible tiles with sprites and drawables, and trailing non-Y-sorted layers (such as roofs or canopies) draw above them. Camera frustum culling (including tall tiles and atlas frames), animated tiles, flip flags, and layer opacity are all respected. - **Custom draw loops**: use `m.AppendYSortTiles(dst[:0], layer, cam)`, `tilemap.SortYSortTiles(tiles)`, and `tilemap.YSortDrawer` (or `YSortTile.Draw(d)`) to collect, sort, and draw Y-sorted tiles with reusable scratch buffers and zero allocations in `tilemap` once warmed up. ## Tile flags, overlap queries, and raycasts Associate collision or gameplay `TileFlags` (`TileSolid`, `TileOneWay`, or custom bitflags) with global tile IDs or individual map cells: ```go m.SetFlags(1, tilemap.TileSolid) m.SetFlags(2, tilemap.TileOneWay) // Override a single cell (e.g. a breakable wall cleared at runtime) m.SetCellFlags(10, 6, 0) // Restore tile-ID flags later m.ClearCellFlags(10, 6) ``` Query the grid without allocating unnecessary geometry: - `FlagsAt(col, row)` returns the combined `TileFlags` across all layers (or the cell override if set). - `TilesInRect(r, mask)` returns every cell overlapping `r` matching `mask` (or any non-empty cell when `mask == 0`) in row-major order as `[]TileHit`. Cells are half-open `[col*TileWidth, (col+1)*TileWidth) × [row*TileHeight, (row+1)*TileHeight)`. - `Raycast(from, to, mask)` traces the segment `from -> to` and returns the first matching `RaycastHit` (`Col`, `Row`, `TileID`, `Flags`, `Point`, `Normal`, and fraction `T` in `[0, 1]`). ```go if hit, ok := m.Raycast(enemyEye, playerPos, tilemap.TileSolid); ok { // Line of sight blocked at hit.Point with surface normal hit.Normal _ = hit } ``` ## Isometric, staggered, and hexagonal maps Set `Orientation` (`OrientationOrthogonal`, `OrientationIsometric`, `OrientationStaggered`, or `OrientationHexagonal`) together with `StaggerAxis` (`StaggerY` / `StaggerX`), `StaggerIndex` (`StaggerOdd` / `StaggerEven`), and `HexSideLength` to project and draw diamond isometric, staggered isometric, and pointy-top or flat-top hexagonal maps: - `TileOrigin(col, row)` and `TileToWorld(col, row)` return each cell's bounding-box origin and center in world coordinates, and `WorldToTile(p)` round-trips any interior world point back to `(col, row)`. - `HexNeighbors(col, row)` and `HexDistance(c1, r1, c2, r2)` compute exact 6-neighbor adjacency and cube distance for both stagger axes and indices. - For pathfinding and tactics movement ranges on these projections, pass `ai.TopologyFromTilemap(m)` to [`game/ai`](https://game.nsgo.dev/docs/ai/#hexagonal-and-staggered-topologies) (`AStar.Topology`, `AStar.MovementRange`, `ReachableCells`), or wrap a hex map directly with `ai.NewHexGrid(m)` for [`ai.GraphSearch`](https://game.nsgo.dev/docs/ai/#generic-graph-search-hex-adapters-and-waypoint-graphs) (including reconstructed paths to every cell in range). - For line-of-sight visibility and tile-aligned fog rendering over isometric, staggered, and hex maps, build a [`game/fog`](https://game.nsgo.dev/docs/fog/) with `fog.NewFromTilemap(m, tilemap.TileSolid)`. ## Sparse chunked layers and streaming For unbounded 2D sandbox or open-world maps (negative and arbitrarily large coordinates), use a sparse chunked `TileLayer` created with `NewChunkedTileLayer(name, chunkSize)` inside `NewInfinite(tileWidth, tileHeight, tilesets...)`. Chunk sizes are fixed powers of two in `[MinChunkSize, MaxChunkSize]` (default `DefaultChunkSize = 16`), allowing branch-free shift/mask coordinate lookup (`TileToChunk`) across negative and positive coordinates: ```go m := tilemap.NewInfinite(16, 16, ts) m.Layers = []tilemap.TileLayer{ tilemap.NewChunkedTileLayer("world", tilemap.DefaultChunkSize), } m.SetFlags(1, tilemap.TileSolid) // Arbitrary negative and positive coordinates work through the exact same APIs: m.SetTile(0, -17, -16, 1) gid := m.TileAt(0, -17, -16) hits := m.TilesInRect(rect, tilemap.TileSolid) rayHit, ok := m.Raycast(from, to, tilemap.TileSolid) ``` - **Infinite Tiled maps**: `LoadTiled` loads infinite `.tmj` layers (`"infinite": true` or layers carrying `"chunks"`) directly into sparse chunked `TileLayer`s, preserving negative chunk coordinates instead of flattening into a giant dense array. - **Per-chunk static caches and dirty tracking**: editing a tile with `SetTile` or `FillRect` marks only the affected chunk `Dirty` and `Modified` without invalidating other chunks. Bake static chunks with `m.CacheStaticChunk(layerIndex, coord, images)` or rebake only dirty chunks with `m.CacheDirtyChunks(layerIndex, images)`; inspect and invalidate individual chunks via `ChunkCache`, `InvalidateChunkCache`, `ClearChunkCache`, `layer.DirtyChunks()`, and `layer.ModifiedChunks()`. - **Deterministic plain-text chunk persistence**: `Chunk.ToDoc()` / `ChunkFromDoc` and `EncodeChunkYAML` / `DecodeChunkYAML` (or `EncodeChunkJSON` / `DecodeChunkJSON`) encode chunks as versioned (`ChunkFormatVersion = 1`) run-length encoded YAML or JSON that preserves all 32-bit GIDs including flip flags and round-trips byte for byte. Built-in stores include `NewMemoryChunkStore()` and `NewDirChunkStore(dir, format)` (writing `chunk__.yaml` or `.json`). - **Bounded streaming**: - Use `tilemap.NewChunkStream(tilemap.ChunkStreamConfig{...})` for synchronous 2D streaming with a `Generator`, `LoadRadius`/`UnloadRadius` hysteresis, `MaxLoadsPerUpdate`, and automatic save/restore of modified chunks through a `ChunkStore`. - For multi-threaded background chunk loading on top of `world3d.ChunkStreamer`, use `world3d.NewTilemapStreamer(world3d.TilemapStreamerConfig{...})` (in `game/world3d`), which streams `*tilemap.Chunk` values with background workers, cancellation, per-frame integration budgets, and modified-chunk YAML/JSON persistence. ```go store := tilemap.NewDirChunkStore(saveDir, tilemap.ChunkFormatYAML) stream := tilemap.NewChunkStream(tilemap.ChunkStreamConfig{ Map: m, LayerIndex: 0, LoadRadius: 2, UnloadRadius: 3, Format: tilemap.ChunkFormatYAML, Store: store, Generator: func(coord tilemap.ChunkCoord, ch *tilemap.Chunk) error { // Populate procedural terrain for coord... return nil }, }) defer stream.Close() // Inside your update loop: stream.Update(playerPos) ``` ## Multi-level worlds (LDtk and Tiled `.world`) Place multiple tilemaps into one shared world coordinate space using `Tilemap.Origin`, LDtk world layouts, Tiled `.world` files, and region-based streaming with `WorldStream`: - **World origin (`Tilemap.Origin`)**: every `Tilemap` carries `Origin core.Point` (defaulting to `(0, 0)` with zero overhead). `Draw`, `DrawLayer`, `DrawImageLayer`, `CacheStaticLayer`, `AppendYSortTiles`, `WorldBounds`, `TileOrigin`, `TileToWorld`, `WorldToTile`, `TilesInRect`, and `Raycast` all honor `Origin`, as do `fog.NewFromTilemap` (`fog.Fog.Origin`) and `physics.TileGridOrigin`: both `*Tilemap` and `*WorldStream` implement `physics.TileGrid` (`TileSize`, `GridSize`, `TileFlagsAt`) and `physics.TileGridOrigin` (`GridOrigin`) directly via `TileFlags.PhysicsFlags()`. - **LDtk multi-level worlds and IntGrid flags**: `LoadLDtk` and `LoadLDtkAll` populate each level's `Origin` from `(worldX, worldY)` (for `Free` and `GridVania` layouts) and its `Neighbours` list (`[]LevelNeighbour`, resolving `Identifier`, `IID`, `UID`, and direction `n`/`s`/`e`/`w`/`ne`/`nw`/`se`/`sw`/`o`/`<`/`>`), and honor LDtk's `intGridValuesGroups` when mapping IntGrid values to `TileFlags`. Use `LoadLDtkWith`, `LoadLDtkAllWith`, and `LoadLDtkWorldWith` with `LDtkOptions` (or `project.File.LDtkOptions` from `physics.ldtkIntGrid` in [`game.yaml`](https://game.nsgo.dev/docs/project/)) to map IntGrid identifiers, group names, or numeric values to `TileFlags` (including mapping decorative values to `0`). `LoadLDtkWorld(data, worldIdentifier, resolveImage)` returns a lazy `*LevelWorld` supporting both single-world and multi-world `.ldtk` projects (refusing `LinearHorizontal` and `LinearVertical` layouts that assign no 2D world coordinates). - **Tiled `.world` files**: `ParseTiledWorld(data)` parses Tiled `.world` JSON files — both explicit `maps` entries (`fileName`, `x`, `y`, optional `width`/`height`) and regex `patterns` (`regexp`, `multiplierX`, `multiplierY`, `offsetX`, `offsetY`, `mapWidth`, `mapHeight`) — returning `*loaderr.Error` with line, field, and fix guidance on malformed JSON or invalid patterns. `TiledWorld.Resolve(fileNames)` expands patterns deterministically without duplicating explicit entries, and `LoadTiledWorld(data, loader)` builds a lazy `*LevelWorld` that sets each loaded `.tmj`'s `Origin` to its `.world` placement. - **Region-based level streaming (`WorldStream`)**: keeps only the levels overlapping a camera or query rectangle (expanded by `LoadMargin`) loaded at their world origins and unloads levels outside `UnloadMargin`, firing `OnEnter`/`OnLeave` and returning `[]WorldStreamEvent` in deterministic world order. `WorldStream` also provides seamless multi-level `Draw`, `UpdateAnimations`, `LevelAt`, `FlagsAtWorld`, `TilesInRect`, `Raycast`, and direct `physics.TileGrid` + `physics.TileGridOrigin` methods (`TileSize`, `GridSize`, `GridOrigin`, `TileFlagsAt`, `GridFlagsAt`), so a `physics.Body` or `physics.CharacterBody` walks across seams between adjacent levels without snagging. ```go world, err := tilemap.LoadLDtkWorld(ldtkBytes, "", func(relPath string) core.ImageSource { return core.Src("asset:" + relPath) }) if err != nil { return err } stream := tilemap.NewWorldStream(tilemap.WorldStreamConfig{ World: world, LoadMargin: 64, UnloadMargin: 128, OnEnter: func(lvl *tilemap.WorldLevel, m *tilemap.Tilemap) { // Spawn entities or attach fog for lvl.ID... }, OnLeave: func(lvl *tilemap.WorldLevel, m *tilemap.Tilemap) { // Clean up entities belonging to lvl.ID... }, }) defer stream.Close() // Inside update: stream.UpdateCamera(cam) stream.UpdateAnimations(dt) // Inside draw (after cam.Apply(d)): stream.Draw(d, cam) ``` ## Collision shapes, round-tripping, and change tracking The collision object group authored on each tile in Tiled's collision editor (`.tmj`, `.tsj`, `.tmx`, or `.tsx`) is preserved verbatim in `Tileset.TileCollisions` (`map[uint32]*ObjectLayer`, keyed by local tile ID, queried with `m.TileCollisionGroup(gid)`), and its rectangles, polygons, ellipses and polylines also load into `Tileset.Shapes` as `TileShape` values in the tile's own coordinates: an ellipse becomes `EllipseShapeSegments` points, and an object's rotation is applied. `m.TileShapes(gid)` returns a placed tile's shapes flipped and rotated by its GID's flip bits, the same transform `DrawLayer` draws the tile with, and `m.TileBox(gid)` the size of the tile they are measured in. `EncodeTiled(m)` writes a deterministic Tiled JSON (`.tmj`) document that preserves tilesets, layers, properties, animations, and per-tile collision object groups across round trips through `LoadTiled`. `*Tilemap` satisfies `physics.TileGrid` and `physics.TileGridOrigin` directly (`TileSize`, `GridSize`, `GridOrigin`, `TileFlagsAt`), so `physics.MoveAndSlide(body, m, dt)`, `physics.World{Tiles: m}`, and `physics.RigidWorld{Tiles: m}` work with no adapter. `m.TileRevision()` and `m.TileChangesSince(rev, fn)` track collision flag edits as well as tile edits: `SetCellFlags` and `ClearCellFlags` log the cell they change, and `SetFlags`, which can change every cell showing the tile, asks callers for a full rebuild. Calls that change nothing log nothing. `m.Flags(gid)` returns the flags set on a tile ID, and `m.CellFlags(col, row)` the per-cell override, if any. [tileshape](https://game.nsgo.dev/docs/tileshape/) builds on both: its `View` is also a `physics.TileGrid`, derives slopes from tile shapes, merges solid cells and partial tile shapes into `Boxes`, `StaticShapes`, `Outline`, and light occluders, and rebuilds only around each change. --- Source: https://game.nsgo.dev/docs/tileshape/ # tileshape `github.com/nsgo-dev/game/pkg/tileshape` derives collision and lighting geometry from a [`tilemap.Tilemap`](https://game.nsgo.dev/docs/tilemap/): a `View` that [physics](https://game.nsgo.dev/docs/physics/) and the [platformer](https://game.nsgo.dev/docs/platformer/) controller take as their `TileGrid`, slopes from slanted and partial tiles, the merged outline of solid cells and tile shapes, static boxes, and [lights2d](https://game.nsgo.dev/docs/lights2d/) occluders. It plays the part of the physics and occlusion polygons of Godot's TileSet. ```go import "github.com/nsgo-dev/game/pkg/tileshape" ``` ## Tile shapes Draw a tile's collision shapes in Tiled's collision editor: rectangles, polygons, ellipses and polylines. `tilemap.LoadTiled` reads them into `Tileset.Shapes`, keyed by local tile ID, as `TileShape` values with their points in the tile's own coordinates; an ellipse becomes a 16-sided polygon (`EllipseShapeSegments`), and an object's rotation is applied. Points and tile objects in the collision editor are skipped. Maps built in code set `Tileset.Shapes` directly. A placed tile's shapes follow the flip bits of its GID, the same transform its image is drawn with, so a flipped or rotated slope tile is a mirrored or rotated slope. `m.TileShapes(gid)` returns them already flipped, and `TileShape.Flipped` applies the bits to one shape. ## View ```go m, err := tilemap.LoadTiled(data, loader) if err != nil { return err } v := tileshape.New(m, tileshape.Options{LayerNames: []string{"ground"}}) player := physics.NewCharacterBody(physics.NewBoxBody(32, 200, 12, 16)) ctl, _ := platformer.NewController(player, platformer.DefaultConfig()) // Inside game.Loop.Update: near := player.Body.Bounds() slopes = v.AppendSlopesIn(slopes[:0], core.Bounds{ Origin: core.Point{X: core.Points(near.X - 64), Y: core.Points(near.Y - 64)}, Size: core.Size{Width: core.Points(near.W + 128), Height: core.Points(near.H + 128)}, }) ctl.Step(in, v, slopes, platforms, dt) ``` `View` implements `physics.TileGrid` and `physics.TileGridOrigin`, and every segment, slope and box it returns is in world coordinates that include the map's `Origin`, so the same value goes to `physics.MoveAndSlide`, `CharacterBody.Move`, `platformer.Controller.Step` and `physics.World{Tiles: v}`. `Options.Layers` and `Options.LayerNames` choose the tile layers that collide; with neither, every tile layer does, including layers added to `m.Layers` later. A cell collides as a whole when its tiles carry `TileSolid` or `TileOneWay` (from `SetFlags`, a `solid` or `oneWay` tile property, or a `SetCellFlags` override, which takes precedence over every tile in the cell), or when one of its tiles has a shape that fills the cell. A tile whose shapes do not fill the cell collides through them: `TileFlagsAt` reports neither `TileSolid` nor `TileOneWay` for that cell, and the shapes' edges become slopes. Set `Options.ShapedSolid` to report such cells as whole solid cells instead, for code that knows only whole cells, such as `MoveAndSlide` alone or `World` raycasts. A polyline is an open edge a character stands on: it is a slope, but not part of the outline or the occluders, and never makes its cell solid. | Method | Returns | | --- | --- | | `TileFlagsAt(col, row)` | The cell's collision flags for physics | | `Slopes()` | The upward-facing and vertical edges of solid shapes, the upward-facing edges of one-way shapes, and every polyline, as `physics.Slope` segments | | `AppendSlopesIn(dst, r)` | The slopes of the chunks around `r`, for passing only nearby slopes to `CharacterBody.Move` on a large map | | `Outline()` | The boundary of every solid cell and solid shape, with shared edges removed and collinear edges merged, solid side on the right | | `Boxes()` | Solid cells and axis-aligned rectangular solid shapes (such as half tiles) merged across neighbours into maximal rectangles, for `physics.NewStaticRigidBox` | | `StaticShapes()` | All solid geometry as static `physics.Shape` values merged across neighbours: maximal `Box` shapes for solid cells and rectangular partial tiles, merged convex `Polygon` shapes for adjacent convex partial tiles (such as multi-tile slopes), and closed `Chain` shapes for concave or >8-vertex partial tiles (such as ellipses), for `physics.NewStaticRigidBody` or `physics.World` | | `AppendStaticShapesIn(dst, r)` | Static shapes of the chunks around `r`, merged across those chunks | | `Occluders()` | `Outline` as `lights2d` occluders, one per chunk | With these slopes, `CharacterBody` walks 45 degree, 2:1 (about 26.6 degree, the tiles tilesets often call 22.5 degree), true 22.5 degree and half-height tiles, steps from a slope onto the solid tiles at its top, and snaps onto the floor tiles past a slope's lower end, with no hand-placed segments. `CharacterBody` has no ceiling segments, so the underside of a partial shape does not stop a jump; use whole cells, or `ShapedSolid`, where a ceiling matters. ## Lights ```go lighting := &lights2d.Scene{Ambient: core.RGBA(12, 16, 30, 0.85)} lighting.Occluders = v.Occluders() // After the map changes: m.SetTile(0, col, row, 0) lighting.Occluders = v.Occluders() ``` The derived occluders cast the same shadows as a `RectOccluder` per solid cell and a `PolygonOccluder` per solid shape, with far fewer segments. One-way cells and shapes cast none. ## Changes at runtime Geometry is cached in chunks of 16 by 16 cells and built on first use. A `View` follows the map's change log, `Tilemap.TileRevision` and `Tilemap.TileChangesSince`, so after `SetTile`, `FillRect`, `SetCellFlags` or `ClearCellFlags` its next call rebuilds only the chunks around the cells that changed. `SetFlags`, a large `FillRect`, or more edits than the log holds rebuild every cell instead. After writing a layer's `Data` directly call `v.Invalidate(col, row, w, h)`. After editing a tileset's `Shapes` call `v.InvalidateAll()`: `Invalidate` keeps the geometry already derived from each tile's shapes. A tile larger than a map cell is placed bottom-aligned in its cell, so its shapes can reach into the cells above it and to its right. A `View` widens the neighbourhood it compares edges in, and the chunks it rebuilds around a change, by as many cells as the largest tile reaches. The slices a `View` returns are shared with its cache: they stay valid, and must not be modified, until the map changes. Only bounded orthogonal maps are supported: a `View` of an unbounded map (`Tilemap.Infinite`, or a sparse chunked layer such as an infinite Tiled map loads into) has no cells. Layer offsets are ignored, as they are by the tilemap's own collision queries. --- Source: https://game.nsgo.dev/docs/tutorial-01-empty-project/ # Tutorial 1: An Empty Project Create the Go module for Star Catcher, describe the app in `nsgo.yaml`, open a window that paints the playfield in a `Canvas`, and test it without a window. The finished code is in [`examples/tutorial/ch01-empty-project`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch01-empty-project/). ## Create the module A game is an ordinary Go module that requires the game library and NSGo, with the `nsgo` command as one of its tools: ```sh mkdir starcatcher && cd starcatcher go mod init example.com/starcatcher go get github.com/nsgo-dev/game go get -tool github.com/nsgo-dev/nsgo/cmd/nsgo@v0.3.4 ``` `go tool nsgo` now runs the `nsgo` command at the version the module pins, so everyone who builds the game builds it with the same one. ## Describe the app `nsgo.yaml`, next to `go.mod`, names the app and says how `nsgo dev` runs it: ```yaml name: Star Catcher 1 id: dev.nsgo.starcatcher.ch01 version: 0.1.0 dev: target: native ``` `id` is the app's bundle identifier on Apple platforms and its application ID on Android. Each chapter has its own, so two chapters installed side by side on a phone do not replace each other. [Chapter 9](https://game.nsgo.dev/docs/tutorial-09-ship/) sets the name, version and icon the stores will show. ## Open a window `main.go` hands NSGo the root component: ```go package main import "github.com/nsgo-dev/nsgo" func main() { nsgo.Run(Root) } ``` `Root` is an NSGo component: a function of a `*core.Scope` that returns the views to show. Star Catcher draws its playfield in a `core.Canvas` that fills the window, and shows the title in a native `core.Text` above it: ```go func Root(cx *core.Scope) core.Node { return core.View{ Style: core.Style{FlexGrow: 1, FlexShrink: 1, Background: skyColor}, Children: []core.Node{ core.Canvas{ TestID: "game-canvas", Label: "Star Catcher playfield", Style: fill(), Draw: drawPlayfield, }, core.View{ PointerEvents: core.PointerEventsNone, Style: core.Style{ Position: core.Absolute, Top: core.Pt(0), Left: core.Pt(0), Right: core.Pt(0), AlignItems: core.AlignCenter, Padding: core.All(24), PaddingEnv: core.EnvAll(core.EnvSafeArea), }, Children: []core.Node{ core.Text{ TestID: "title", Content: "Star Catcher", Style: core.Style{Color: textColor, FontSize: 28, FontWeight: core.FontWeightBold}, }, }, }, }, } } ``` - `fill()` returns a style that pins a child to all four edges of its parent, so the canvas covers the window at any size. - `PaddingEnv: core.EnvAll(core.EnvSafeArea)` keeps the title clear of a phone's notch and home indicator. - `PointerEventsNone` lets touches pass through the title to the playfield, which [chapter 3](https://game.nsgo.dev/docs/tutorial-03-input/) starts listening to. - `TestID` names a view for tests, and `Label` names it for screen readers. The canvas calls `Draw` with a `*core.Drawing` and its own size in points, and draws again whenever the size changes: ```go func drawPlayfield(d *core.Drawing, size core.Size) { w, h := float32(size.Width), float32(size.Height) d.SetFillColor(skyColor).FillRect(0, 0, w, h) d.SetFillColor(groundColor).FillRect(0, h-groundHeight, w, groundHeight) } ``` Run it: ```sh go tool nsgo dev ``` A dark sky fills the window, with the ground along its bottom and the title at its top. Resize the window, and the ground stays at the bottom. ## Test it NSGo's `nsgotest` package runs an app without a window: `nsgotest.Start` mounts it in a window of a size the test picks, `Find` looks up a view by its `TestID` or text and fails the test if there is none, and a canvas's `Ops` are the drawing operations it recorded. ```go func TestMain(m *testing.M) { nsgotest.Main(m) } func TestShowsTitleOverPlayfield(t *testing.T) { app := nsgotest.Start(t, Root, nsgotest.Size(360, 640)) app.Find("text:Star Catcher") ops := app.Find("game-canvas").Ops if !hasFillColor(ops, skyColor) { t.Fatal("canvas did not paint the sky") } if !hasFillColor(ops, groundColor) { t.Fatal("canvas did not paint the ground") } } ``` `TestMain` hands the main thread to the platform when the tests run on a real one, as `go tool nsgo test -target macos` does. The chapter's second test resizes the window with `app.Resize` and checks that the ground moved to the new bottom edge. Run the tests with: ```sh go tool nsgo test ./... ``` ## Next The playfield is still a picture. [Chapter 2](https://game.nsgo.dev/docs/tutorial-02-game-loop/) makes it move with a fixed-step game loop. --- Source: https://game.nsgo.dev/docs/tutorial-02-game-loop/ # Tutorial 2: The Game Loop Give the game a world that moves in fixed steps, drive it with a `game.Loop`, draw it at a virtual resolution that `screen.Viewport` scales to any window, and test the world without one. The finished code is in [`examples/tutorial/ch02-game-loop`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch02-game-loop/). ## A world that only steps change Put the game's state in a type of its own, and change it only in one method, `step`, that moves it on by a fixed time: ```go type world struct { basketX float32 starLane int starY, prevY float32 } func (w *world) step(dt time.Duration) { w.prevY = w.starY w.starY += fallSpeed * float32(dt.Seconds()) if w.starY > virtualHeight+itemSize { w.respawn((w.starLane + 2) % laneCount) } } ``` The world knows nothing about windows or frames, which pays off three ways: a test can step it a thousand times in a millisecond, the game plays the same on a 60 Hz and a 120 Hz display, and in [chapter 5](https://game.nsgo.dev/docs/tutorial-05-rules/) the same seed and moves will always play the same game. `prevY` keeps where the star was a step ago. Drawing uses it to place the star between steps: ```go func (w *world) starAt(alpha float32) float32 { return w.prevY + (w.starY-w.prevY)*alpha } ``` ## Drive it with game.Loop `game.Loop` runs `Update` at a fixed rate on the display's frames, and `Draw` once a frame in between: ```go func newStarCatcher(cx *core.Scope) *starCatcher { s := &starCatcher{world: newWorld(), frame: core.NewSignal(cx, uint64(0))} loop := &game.Loop{ Rate: 60, Update: s.update, Draw: func(alpha float64) { s.alpha = alpha s.frame.Update(func(n uint64) uint64 { return n + 1 }) }, } loop.Run(cx) return s } func (s *starCatcher) update(dt time.Duration) { s.world.step(dt) } ``` - Each display frame, the loop adds the time since the last one and runs `Update` once for every whole sixtieth of a second it holds, so `dt` is always 1/60 s. - `Draw` gets `alpha`, how far the frame falls between the last step and the next, from 0 up to 1. - The canvas reads `frame` in its `Draw`, so setting it each frame redraws only the canvas, without rebuilding any views. - The loop stops when the component goes, and runs no updates while the app is in the background. ## A virtual resolution Phones, tablets, desktop windows and browser tabs all have different sizes and shapes. Rather than lay the game out for each one, Star Catcher plays on a virtual canvas 240 points wide and 320 tall, split into five lanes, and lets a `screen.Viewport` fit it to the window: ```go var viewport = screen.Viewport{ Width: virtualWidth, Height: virtualHeight, Mode: screen.ModeFit, BarColor: barColor, } func (s *starCatcher) draw(d *core.Drawing, size core.Size) { _ = s.frame.Get() viewport.Draw(d, size, s.drawWorld) } ``` `ModeFit` scales the playfield as large as fits, keeps its shape, and fills the rest with bars of `BarColor`. `viewport.Draw` scales and clips the drawing, then calls `drawWorld`, which draws in virtual points only: ```go func (s *starCatcher) drawWorld(d *core.Drawing, _ core.Size) { w := s.world d.SetFillColor(skyColor).FillRect(0, 0, virtualWidth, virtualHeight) // The lanes and the ground… d.SetFillColor(basketColor).FillRect(w.basketX-basketWidth/2, basketY, basketWidth, basketHeight) y := w.starAt(float32(s.alpha)) d.SetFillColor(starColor).BeginPath().Ellipse(laneX(w.starLane), y, itemSize/2, itemSize/2).Fill() } ``` Run the chapter. A star falls down a lane, and starts again two lanes over once it has passed the ground. Make the window wide, and bars appear beside the playfield. ## Test the world and the loop The world's tests step it by hand. A second of steps must move the star by `fallSpeed`: ```go func TestStarFallsAtFallSpeed(t *testing.T) { w := newWorld() start := w.starY for range 60 { w.step(step) } if got, want := w.starY-start, float32(fallSpeed); !near(got, want) { t.Fatalf("star fell %v points in a second, want %v", got, want) } } ``` An app test checks that the loop really runs: `app.Advance` moves the test's clock on and runs the display frames in that time, so after a second the star the canvas drew is lower: ```go func TestLoopMovesTheStarOnScreen(t *testing.T) { app := nsgotest.Start(t, Root, nsgotest.Size(240, 320)) before := starEllipse(t, app.Find("game-canvas").Ops) app.Advance(time.Second) after := starEllipse(t, app.Find("game-canvas").Ops) if after.Y <= before.Y { t.Fatalf("star at y %v after a second, want below %v", after.Y, before.Y) } } ``` Neither test sleeps: the test's clock moves only when the test says so, so the tests are as fast and as repeatable as the world. ## Next The basket sits still. [Chapter 3](https://game.nsgo.dev/docs/tutorial-03-input/) lets the player move it. --- Source: https://game.nsgo.dev/docs/tutorial-03-input/ # Tutorial 3: Input Let the player move the basket from lane to lane by touching or clicking a side of the playfield, or with the arrow keys, through `game/input`'s named actions, sampled once per step. The finished code is in [`examples/tutorial/ch03-input`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch03-input/). ## Moves in the world The world takes the player's move as an argument of `step`: -1 for a lane to the left, 1 for a lane to the right, 0 to stay. The basket heads for its lane and glides there at `basketSpeed`: ```go func (w *world) step(dt time.Duration, move int) { secs := float32(dt.Seconds()) w.basketLane = min(max(w.basketLane+move, 0), laneCount-1) w.prevX = w.basketX target := laneX(w.basketLane) if d := target - w.basketX; d > 0 { w.basketX = min(w.basketX+basketSpeed*secs, target) } else if d < 0 { w.basketX = max(w.basketX-basketSpeed*secs, target) } // The star falls as before… } ``` The world still knows nothing about touches or keys, so tests move the basket by passing moves, and so will the bot in [chapter 9](https://game.nsgo.dev/docs/tutorial-09-ship/). ## Actions from touches and clicks `input.Actions` maps names, such as `"left"`, to the touches and mouse buttons that press them. Star Catcher binds each half of the playfield: ```go var ( leftHalf = core.Bounds{Size: core.Size{Width: virtualWidth / 2, Height: virtualHeight}} rightHalf = core.Bounds{Origin: core.Point{X: virtualWidth / 2}, Size: core.Size{Width: virtualWidth / 2, Height: virtualHeight}} ) s.actions.MapPoint = func(p core.Point) (core.Point, bool) { return viewport.ViewToGame(s.size, p) } s.actions.Bind("left", input.TouchRegion(leftHalf), input.MouseRegion(leftHalf, core.MouseButtonLeft)) s.actions.Bind("right", input.TouchRegion(rightHalf), input.MouseRegion(rightHalf, core.MouseButtonLeft)) ``` - The regions are in virtual points, the same on every screen. `MapPoint` converts a touch from the view's points with the viewport, and reports `false` for one on a bar, which then presses nothing. - `s.size` is the canvas's size, which `draw` records each frame. - `Attach` wires the actions to the view's touch, press and mouse handlers: ```go v := core.View{TestID: "game-view", /* … */} s.actions.Attach(&v) ``` ## Keys A hardware keyboard reaches the game through key bindings on its scope. Each one triggers an action, which latches it for the next step, so a key and a touch move the basket the same way: ```go repeat := core.KeyOptions{Repeat: true} for _, key := range []string{"left", "a"} { cx.OnKeyWith(key, repeat, func() { s.actions.Trigger("left") }) } for _, key := range []string{"right", "d"} { cx.OnKeyWith(key, repeat, func() { s.actions.Trigger("right") }) } ``` `Repeat` fires the binding again on the keyboard's auto-repeat, so holding an arrow sweeps the basket across the lanes. ## Sample once per step `Step` takes a snapshot of the actions at the start of each update, and `JustPressed` reports an action that went down since the last one. Each new press moves the basket one lane: ```go func (s *starCatcher) update(dt time.Duration) { s.actions.Step() move := 0 if s.actions.JustPressed("left") { move-- } if s.actions.JustPressed("right") { move++ } s.world.step(dt, move) } ``` Sampling in the step, not in the touch handler, keeps input in time with the simulation: a tap that starts and ends between two steps is still latched for one step, and a touch held for a second moves the basket once, not sixty times. Run the chapter, and move the basket with a click or a touch on each side, or with the arrow keys. ## Test touches and keys `nsgotest` sends the same events a platform would. `app.Key` presses a key; `app.Touch` puts a finger down on a view and returns it, so the test can hold it while time passes and lift it later: ```go func TestTouchingASideMovesTheBasket(t *testing.T) { var s *starCatcher app := nsgotest.Start(t, func(cx *core.Scope) core.Node { s = newStarCatcher(cx) return s.view() }, nsgotest.Size(480, 640)) // The 480 by 640 window shows the playfield at twice its size, so x 400 is in its right half. finger := app.Touch("game-view", core.Point{X: 400, Y: 300}) app.Advance(time.Second / 2) finger.Lift() app.Advance(time.Second / 4) if s.world.basketLane != laneCount/2+1 { t.Fatalf("after a held touch the basket heads for lane %d, want one lane right, %d", s.world.basketLane, laneCount/2+1) } } ``` The test builds the game itself instead of calling `Root`, so it keeps the `*starCatcher` and can look at its world. Holding the finger for half a second still moves the basket a single lane, which is what `JustPressed` promises. ## Next The game is drawn with rectangles and circles. [Chapter 4](https://game.nsgo.dev/docs/tutorial-04-sprites/) draws it with sprites. --- Source: https://game.nsgo.dev/docs/tutorial-04-sprites/ # Tutorial 4: Sprites Draw the basket and the star as sprites: paint a sprite sheet, describe its frames in a `sprite.Atlas`, play the star's twinkle with a `sprite.Animation`, and draw everything with one `sprite.Batch`. The finished code is in [`examples/tutorial/ch04-sprites`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch04-sprites/). ## An atlas An atlas is one image that packs many pictures, and the frames that say where each one is. Games usually export it from a packer such as TexturePacker or Aseprite and load it with `sprite.LoadAtlas`, as the [sprite guide](https://game.nsgo.dev/docs/sprite/) shows. So that the tutorial needs no image files, Star Catcher paints its sheet in Go instead, in `art.go`, and writes the table by hand: ```go func makeAtlas() *sprite.Atlas { sheet := image.NewRGBA(image.Rect(0, 0, sheetWidth, sheetHeight)) paintBasket(sheet, 0) paintStar(sheet, basketWidth, 1, color.RGBA{R: 0xfd, G: 0xe0, B: 0x47, A: 0xff}) paintStar(sheet, basketWidth+itemSize, 0.8, color.RGBA{R: 0xfa, G: 0xcc, B: 0x15, A: 0xff}) basket := frame("basket", 0, basketWidth, basketHeight) star0 := frame("star_0", basketWidth, itemSize, itemSize) star1 := frame("star_1", basketWidth+itemSize, itemSize, itemSize) return &sprite.Atlas{ Image: core.ImageSource{Pixels: sheet}, Frames: map[string]sprite.Frame{basket.Name: basket, star0.Name: star0, star1.Name: star1}, Animations: map[string]sprite.Animation{ "twinkle": { Loop: true, Frames: []sprite.AnimationFrame{ {Frame: star0, Duration: twinkleFrame}, {Frame: star1, Duration: twinkleFrame}, }, }, }, } } ``` - The sheet is one row: the basket, a bright star and a dimmer, smaller one. `paintStar` fills the pixels inside a five-pointed star; `paintBasket` a woven bowl. - `core.ImageSource{Pixels: sheet}` hands the pixels to the platform, which uploads them once. - `frame` makes an untrimmed frame with its pivot in its middle, so a sprite of it turns about its center. To try art from files without drawing any, start from the CC0 [placeholder pack](https://game.nsgo.dev/docs/placeholder/): `placeholder.Sheet("player")` loads a sprite sheet and its Aseprite export through `sprite.LoadAtlas`, animations included, and the pack's files can be copied into a game and replaced one by one. ## Sprites and a batch A `sprite.Sprite` places a frame: where its origin goes, how it turns, scales, flips and fades. A `sprite.Batch` draws sprites of one atlas, in order: ```go atlas := makeAtlas() s.twinkle = atlas.Animations["twinkle"] s.basket = sprite.NewSprite(atlas.Frames["basket"]) s.basket.OriginY = 0 s.star = sprite.NewSprite(s.twinkle.Frame()) s.batch = sprite.Batch{Atlas: atlas, Sprites: []*sprite.Sprite{&s.basket, &s.star}} ``` `NewSprite` puts the origin at the frame's pivot. The basket moves its origin to its top edge, so its `Y` is the top of the basket, as in the world. Drawing now places the two sprites and draws the batch: ```go s.basket.X, s.basket.Y = w.basketAt(a), basketY s.star.X, s.star.Y = laneX(w.starLane), w.starAt(a) // The star turns a little as it falls. s.star.Rotation = s.star.Y / 60 s.batch.Draw(d) ``` ## Animation An `Animation` is a value that keeps its own place in its frames. Copy one out of the atlas, move it on with the loop's `dt` in `update`, and show its current frame: ```go s.world.step(dt, move) s.twinkle.Update(dt) s.star.Frame = s.twinkle.Frame() ``` Because it moves with the fixed step, the twinkle keeps time with the game, and stops when the game pauses in [chapter 6](https://game.nsgo.dev/docs/tutorial-06-screens/). Run the chapter: the basket is a basket now, and the star twinkles and turns as it falls. ## Test the art The tests check the atlas itself, that every frame is painted in its middle and transparent in its corner, and that the star changes frame after one twinkle and comes back after two: ```go func TestStarTwinkles(t *testing.T) { var s *starCatcher nsgotest.Start(t, func(cx *core.Scope) core.Node { s = newStarCatcher(cx) return s.view() }, nsgotest.ManualFrames()) first := s.star.Frame.Name s.update(twinkleFrame) if s.star.Frame.Name == first { t.Fatalf("star still shows %s after a twinkle frame", first) } s.update(twinkleFrame) if s.star.Frame.Name != first { t.Fatalf("star shows %s after two twinkle frames, want %s again", s.star.Frame.Name, first) } } ``` `nsgotest.ManualFrames` runs display frames only when the test advances the clock, so the loop does not call `update` on its own while the test calls it. An app test also reads the images the canvas draws with `gametest.ImageDraws`, which sees each sprite of the batch's single `DrawAtlas`: two, the basket and the star. ## Next One star falling forever is not yet a game. [Chapter 5](https://game.nsgo.dev/docs/tutorial-05-rules/) adds its rules. --- Source: https://game.nsgo.dev/docs/tutorial-05-rules/ # Tutorial 5: Rules Turn the falling star into a game: drop stars and rocks from a seeded `random.Stream`, decide what the basket catches with `physics` boxes, keep score and lives, end the game with the last life, and prove that the same seed always plays the same game. The finished code is in [`examples/tutorial/ch05-rules`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch05-rules/). ## The rules All of the rules are constants at the top of `world.go`, so tuning the game means changing numbers in one place: ```go const ( startLives = 3 rockChance = 0.25 fallSpeed = 90 // points a second, at a score of 0 fallPerScore = 6 // points a second more for each star caught maxFallSpeed = 220 // points a second firstSpawn = 600 * time.Millisecond slowSpawn = 1100 * time.Millisecond fastSpawn = 400 * time.Millisecond spawnPerStar = 25 * time.Millisecond ) ``` The world now holds a list of falling items, each a star or a rock, and the score, the lives and whether the game is over: ```go type item struct { kind itemKind lane int y, prevY float32 speed float32 } type world struct { basketLane int basketX, prevX float32 items []item rng *random.Stream spawnIn time.Duration score, lives int over bool // events are what happened in the last step, oldest first. events []event } ``` ## Seeded spawns `random.Stream` is the game library's random number generator. Its numbers depend only on its seed, the same on every operating system, architecture and Go version, which `math/rand` does not promise. Every spawn draws from it: ```go func (w *world) spawn() { lane := w.rng.Intn(laneCount) kind := kindStar if w.rng.Chance(rockChance) { kind = kindRock } speed := min(float32(fallSpeed+fallPerScore*w.score), maxFallSpeed) w.items = append(w.items, item{kind: kind, lane: lane, y: -itemSize, prevY: -itemSize, speed: speed}) } func (w *world) spawnInterval() time.Duration { return max(slowSpawn-spawnPerStar*time.Duration(w.score), fastSpawn) } ``` The game seeds the world from the clock, so each launch plays differently, while a test passes a seed of its own: ```go func Root(cx *core.Scope) core.Node { return newStarCatcher(cx, uint64(cx.WallTime().UnixNano())).view() } ``` ## Catching, missing and the end Each step moves every item, then sorts out what it touched. `physics.TestBoxBox` reports whether two boxes overlap; an item's box is a little smaller than its picture, so a catch needs more than a touch of a point: ```go basket := w.basketBox() kept := w.items[:0] for _, it := range w.items { it.y += it.speed * secs switch { case physics.TestBoxBox(basket, it.box()).Hit: if it.kind == kindStar { w.score++ w.events = append(w.events, eventCaught) } else { w.lives-- w.events = append(w.events, eventHit) } continue case it.y-itemSize/2 >= groundY: if it.kind == kindStar { w.lives-- w.events = append(w.events, eventMissed) } continue } kept = append(kept, it) } clear(w.items[len(kept):]) w.items = kept if w.lives <= 0 { w.lives = 0 w.over = true w.events = append(w.events, eventOver) } ``` - Filtering into `w.items[:0]` reuses the slice's array, so a step allocates nothing once the list has grown. - An item moves less than four points a step at most, less than the basket is tall, so no star can pass through the basket between two steps. - `events` record what happened in the step. The screen reads them to update the score now, and [chapter 7](https://game.nsgo.dev/docs/tutorial-07-sound/) plays a sound for each. Once the game is over, `step` moves nothing until `reset` starts the next game. ## The score on screen The score and lives are native `core.Text` views over the canvas. Each reads a signal, which the game sets from the world after a step that had events: ```go core.Text{TestID: "score", ContentFunc: func() string { return fmt.Sprintf("Score: %d", s.score.Get()) }, Style: label}, core.Text{TestID: "lives", ContentFunc: func() string { return fmt.Sprintf("Lives: %d", s.lives.Get()) }, Style: label}, ``` Drawing a falling item takes a sprite each: the twinkling star or the rock, a new frame painted into the atlas. The game keeps a slice of sprites and reuses it from frame to frame. When the game ends, a `core.Show` shows a panel until the player taps or presses Enter, which starts the next game. ## Test the rules The rules' tests set up exactly the case they test. `quiet` makes a world that spawns nothing by itself, and `drop` places an item: ```go func TestCatchingARockCostsALife(t *testing.T) { w := quiet() w.drop(kindRock, w.basketLane, basketY-itemSize) if got := stepUntil(t, w); !slices.Equal(got, []event{eventHit}) { t.Fatalf("events = %v, want a hit", got) } if w.score != 0 || w.lives != startLives-1 { t.Fatalf("score %d, lives %d; want 0, %d", w.score, w.lives, startLives-1) } } ``` `random.AssertDeterministic` runs a whole minute of play three times from scratch and fails if any run ends differently from the first: ```go func TestSameSeedPlaysTheSameGame(t *testing.T) { random.AssertDeterministic(t, 3, func() snapshot { return play(42, 3600) }) } ``` A fuzz test, `FuzzWorldKeepsItsRules`, plays twenty seconds of any seed and any moves, and checks after every step that lives stay between 0 and 3, the score never falls, the basket stays on the playfield and nothing falls through the ground. `nsgo test` runs its seed cases; to search for more, pass Go's fuzzing flags after `--`: ```sh go tool nsgo test ./ch05-rules -- -run '^$' -fuzz FuzzWorldKeepsItsRules -fuzztime 1m ``` ## Next The game starts the moment the app opens and cannot be paused. [Chapter 6](https://game.nsgo.dev/docs/tutorial-06-screens/) adds a title screen, a pause menu and a proper end. --- Source: https://game.nsgo.dev/docs/tutorial-06-screens/ # Tutorial 6: Screens Give the game a title screen, a pause menu and a game-over screen. They are native NSGo views over the canvas, shown by phase, with real buttons that screen readers, keyboards and game tests can all press. The finished code is in [`examples/tutorial/ch06-screens`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch06-screens/). The views move to their own file, `screens.go`. ## Phases The game is always in one of four phases, held in a signal so the views follow it: ```go type phase uint8 const ( phaseTitle phase = iota phasePlaying phasePaused phaseOver ) ``` Every change of phase goes through one method: ```go func (s *starCatcher) setPhase(p phase) { s.phase.Set(p) s.loop.SetPaused(p == phasePaused) s.actions.Reset() } ``` - `Loop.SetPaused` stops the loop's updates while the game is paused, and resumes without making up the time away, so nothing jumps when the player comes back. - `Actions.Reset` drops held touches and latched presses, so the tap on a menu's button does not also move the basket. The other transitions are short: ```go func (s *starCatcher) start() { s.world.reset() s.sync() s.setPhase(phasePlaying) } func (s *starCatcher) togglePause() { switch s.phase.GetUntracked() { case phasePlaying: s.setPhase(phasePaused) case phasePaused: s.setPhase(phasePlaying) } } ``` `GetUntracked` reads a signal without subscribing whoever reads it, which is what a key or button handler wants. The world now steps only while the game is being played, and the end of a game moves to `phaseOver`: ```go func (s *starCatcher) update(dt time.Duration) { s.actions.Step() if s.phase.GetUntracked() != phasePlaying { return } // Read the moves and step the world as before… if s.world.over { s.setPhase(phaseOver) } } ``` ## A screen for each phase `view` puts the screens over the playfield, each built only while its phase is on: ```go return core.View{ Style: core.Style{FlexGrow: 1, FlexShrink: 1, Background: barColor}, Children: []core.Node{ field, s.when(phasePlaying, s.hud), s.when(phaseTitle, s.title), s.when(phasePaused, s.paused), s.when(phaseOver, s.gameOver), }, } func (s *starCatcher) when(p phase, screen func() core.Node) core.Node { return core.Show{ When: func() bool { return s.phase.Get() == p }, Then: func(*core.Scope) core.Node { return screen() }, } } ``` Each menu is a centered panel of a heading and buttons: ```go func (s *starCatcher) paused() core.Node { return panel("paused", heading("Paused"), button("Resume", s.togglePause), button("Quit", s.quit), ) } ``` `button` is a `base.Button` with a label and a text inside. Because the menus are native views rather than pictures in the canvas, they get the platform's text rendering and accessibility for free: a screen reader reads "Resume, button", Tab moves between the buttons, and Return or Space presses the focused one. The HUD keeps `PointerEventsBoxNone`, so touches between its score, pause button and lives still reach the playfield. ## Keys Enter starts a game from the title or the end of one, and Escape or P pause and resume: ```go cx.OnKey("enter", func() { if p := s.phase.GetUntracked(); p == phaseTitle || p == phaseOver { s.start() } }) for _, key := range []string{"escape", "p"} { cx.OnKey(key, s.togglePause) } ``` Run the chapter. It opens on the title screen; Start begins a game, Pause or Escape stops it, and the end of a game says how many stars you caught. ## Test the screens The tests press the buttons by their role and label, as a user would find them: ```go func TestPauseStopsTheWorld(t *testing.T) { app, s := startPlaying(t) s.world.spawnIn = time.Hour s.world.drop(kindStar, 0, 40) app.Advance(step) app.Press("role:button Pause") app.Find("text:Paused") y := s.world.items[0].y app.Advance(time.Second) if got := s.world.items[0].y; got != y { t.Fatalf("star fell from %v to %v while paused", y, got) } app.Press("role:button Resume") app.Advance(time.Second / 2) if got := s.world.items[0].y; got <= y { t.Fatalf("star at %v after resuming, want below %v", got, y) } } ``` Others check that nothing falls on the title screen, that Escape and P toggle the pause, that the end of a game offers Play again, and that Quit returns to the title with an empty playfield. The rules' tests from chapter 5 carry over unchanged, because the world did not change. ## Next The game is silent. [Chapter 7](https://game.nsgo.dev/docs/tutorial-07-sound/) gives it sound. --- Source: https://game.nsgo.dev/docs/tutorial-07-sound/ # Tutorial 7: Sound Play a sound for each catch, hit, miss and the end of a game: synthesize the effects in Go, load them with NSGo's `audio`, play them through a `sound.Mixer`, and give the player a mute switch the game remembers. The finished code is in [`examples/tutorial/ch07-sound`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch07-sound/). ## Effects made in Go A game with recorded sounds puts WAV, AAC or MP3 files under `resources/` and loads them by `"asset:"` URI, as [Getting Started](https://game.nsgo.dev/docs/getting-started/#play-sound-with-soundmixer) shows. Star Catcher makes its four effects in code instead, in `audio.go`, so the tutorial needs no audio files. Each is a few tones or a burst of noise, encoded with `sound.EncodeWAV`: ```go func makeSounds() (map[event]audio.Source, error) { clips := map[event][]float64{ eventCaught: join(tone(880, 880, 0.06, 0.5), tone(1320, 1320, 0.09, 0.5)), eventHit: thud(0.22, 0.7), eventMissed: tone(440, 220, 0.25, 0.45), eventOver: join(tone(660, 660, 0.15, 0.45), tone(495, 495, 0.15, 0.45), tone(330, 300, 0.35, 0.45)), } sources := make(map[event]audio.Source, len(clips)) for e, samples := range clips { wav, err := sound.EncodeWAV(samples, sampleRate, 1) if err != nil { return nil, err } sources[e] = audio.Source{Data: wav} } return sources, nil } ``` `tone` glides a sine wave from one pitch to another; `thud` smooths random noise into a rumble, from a `random.Stream` with a fixed seed so it sounds the same every launch. Both shape the clip with a short fade in and a fade out to silence, so it neither clicks in nor stops short. ## A mixer `sound.Mixer` sets how loud groups of sounds play, keeps the volumes in the app's storage, and plays nothing while the app is in the background. The game makes one, and loads each effect into it: ```go s.mixer = sound.NewMixer(cx, "starcatcher.sound") func (s *starCatcher) loadSounds(cx *core.Scope) { sources, err := makeSounds() if err != nil { return } for e, src := range sources { audio.LoadSound(cx, src, func(snd *audio.Sound, err error) { if err == nil { s.effects[e] = s.mixer.Effect(snd, effectsGroup, 4) } }) } } ``` `audio.LoadSound` has the platform decode the sound once, and calls back when it has. `mixer.Effect` puts it in the `"effects"` group, playing at most four copies at once. A sound that fails to load stays silent rather than stopping the game. The world's events from [chapter 5](https://game.nsgo.dev/docs/tutorial-05-rules/) say what to play: ```go for _, e := range s.world.events { if fx := s.effects[e]; fx != nil { fx.Play(audio.Voice{Volume: 1}) } } ``` The effects play from the fixed step, so they are in time with what the world did, and do not play while the game is paused. ## A mute switch The mixer's master volume is the switch. It is stored under `starcatcher.sound.master`, so a game muted last time starts muted, and reading it in a view subscribes the view to it: ```go func (s *starCatcher) muted() bool { return s.mixer.Master() == 0 } func (s *starCatcher) toggleSound() { master := float32(0) if s.muted() { master = 1 } _ = s.mixer.SetMaster(master) } func (s *starCatcher) soundButton() core.Node { return buttonWith("Sound", s.toggleSound, func() string { if s.muted() { return "Sound: off" } return "Sound: on" }) } ``` The button is on the title screen and in the pause menu. `SetMaster` fails only when the storage is full, and then the sound stays as it was. On the web, browsers play no sound before the page's first user gesture. The first sound in Star Catcher follows a press of Start, so it is always allowed. ## Test the sound The test platform plays sounds only in an environment that has audio, and decodes only the sources the test gives lengths to. `withSounds` sets both up: ```go func withSounds(t *testing.T) (nsgotest.Option, map[event]audio.Source) { t.Helper() sources, err := makeSounds() if err != nil { t.Fatal(err) } return func(a *nsgotest.App) { nsgotest.Environment(core.Environment{Audio: true})(a) a.AudioDurations = map[string]time.Duration{} for _, src := range sources { a.AudioDurations[string(src.Data)] = time.Second / 2 } }, sources } ``` `app.Sounds` then lists every sound the game loaded, with each time it played. The tests catch a star and a rock and check that the catch, hit and end sounds each played once and the miss sound not at all; start a second app with `nsgotest.Storage` holding a master volume of 0 and check that it starts muted and plays nothing; and decode every effect with `sound.DecodeWAV` to check that it is short and ends in silence. ## Next The best score is forgotten when the app closes. [Chapter 8](https://game.nsgo.dev/docs/tutorial-08-save/) keeps it. --- Source: https://game.nsgo.dev/docs/tutorial-08-save/ # Tutorial 8: Saving Keep the player's best score and the number of games they played across launches, in a versioned save slot from `game/save`, and show the best on the title and game-over screens. The finished code is in [`examples/tutorial/ch08-save`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch08-save/). ## What to keep The records are a small struct with JSON tags, in `records.go`: ```go type records struct { Best int `json:"best"` Games int `json:"games"` } func (r *records) add(score int) (best bool) { r.Games++ if score > r.Best { r.Best = score return true } return false } ``` ## A save store `save.NewStorageStore` keeps save slots in the app's `core.Storage`, which every target has, the web included: ```go const ( savePrefix = "starcatcher" recordsSlot = "records" recordsVersion = 1 ) func newRecordsStore(store core.Storage) *save.Store { return save.NewStorageStore(store, savePrefix, save.WithVersion(recordsVersion)) } ``` `Save` writes the slot as JSON inside a versioned envelope, `{"version":1,"data":{"best":12,"games":5}}`, under the key `starcatcher.slot.records`, and keeps the previous good copy as a backup, which `Load` falls back to if the latest copy is damaged. When `records` changes shape in a later release, raise `recordsVersion` and give the store a `save.WithMigration` from the old version; `Load` then upgrades old saves as it reads them. The [save guide](https://game.nsgo.dev/docs/save/) covers migrations and file-backed stores. ## Load at launch, save at the end Loading happens once, when the game starts: ```go func loadRecords(st *save.Store) (r records, newer bool) { if err := st.Load(recordsSlot, &r); err != nil { return records{}, errors.Is(err, save.ErrFutureVersion) } return r, false } ``` On a first launch `Load` returns `save.ErrNotFound`, and the game starts with no records. A slot that cannot be read even from its backup also starts afresh rather than keeping the player out of the game, and the next save replaces it. A slot written by a newer version of the game is different: this build cannot read it, but it holds the player's records, as when an older web bundle is still cached after a newer one ran. The game plays without records, and `loadRecords` reports `newer`, which the game keeps as `keepSlot`. When a game ends, the game counts it and saves: ```go func (s *starCatcher) finish() { s.newBest.Set(s.records.add(s.world.score)) s.best.Set(s.records.Best) if !s.keepSlot { _ = s.store.Save(recordsSlot, s.records) } s.setPhase(phaseOver) } ``` `Save` fails only when the storage is full, and then loses no more than this game's record. While `keepSlot` is set, the game does not save at all, so the newer version finds its records as it left them. ## Show the best The title screen shows the best once there is one, and the game-over screen says "New best!" when the player beat it: ```go core.Show{ When: s.newBest.Get, Then: func(*core.Scope) core.Node { return core.Text{TestID: "new-best", Content: "New best!", Style: core.Style{Color: bestColor, FontSize: 16, FontWeight: core.FontWeightBold}} }, Else: func(*core.Scope) core.Node { return s.bestLine() }, }, ``` Run the chapter, play a game, close the app and open it again: the title shows your best. ## Test the save `nsgotest` gives every app its own storage, empty unless the test fills it with `nsgotest.Storage`, and `app.Storage()` lets the test read what the game wrote. The tests save and load records across two stores, check the exact envelope in storage, and check that a corrupt slot and one from a future version both start afresh, and that only the future one is reported as newer: ```go func TestUnreadableRecordsStartAfresh(t *testing.T) { for _, tc := range []struct { name, raw string newer bool }{ {"corrupt", "{not json", false}, {"future", `{"version":99,"data":{"best":5,"games":1}}`, true}, } { t.Run(tc.name, func(t *testing.T) { app := nsgotest.Start(t, empty, nsgotest.Storage(map[string]string{recordsKey: tc.raw})) got, newer := loadRecords(newRecordsStore(app.Storage())) if got != (records{}) || newer != tc.newer { t.Fatalf("records = %+v, newer %v; want none, newer %v", got, newer, tc.newer) } }) } } ``` App tests play two games, check that the first is a new best and the second, lower one is not, start an app whose storage already holds a best of 12 to check that the title shows it, and play a game over a slot from a future version to check that the slot is left untouched. ## Next The game is complete. [Chapter 9](https://game.nsgo.dev/docs/tutorial-09-ship/) gets it ready for players. --- Source: https://game.nsgo.dev/docs/tutorial-09-ship/ # Tutorial 9: Shipping Get Star Catcher ready for players: give it a name, version and icon for the stores, pause it when the app loses the focus, play whole games in a test before each release, check every target, and build release packages. The finished game is in [`examples/tutorial/ch09-ship`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch09-ship/). [Building and Shipping](https://game.nsgo.dev/docs/shipping/) covers each step below in more depth, signing and store uploads included. ## Name, version and icon `nsgo.yaml` now says what the stores show: ```yaml name: Star Catcher id: dev.nsgo.starcatcher version: 1.0.0 build_number: 1 copyright: "© 2026 Star Catcher authors" icon: png: assets/Icon.png dev: target: native build: output: dist targets: [macos, windows, linux, android, web, ios] ``` - `id` must stay the same in every release: the App Store, Google Play and the Microsoft Store know the app by it. Use a reverse-DNS name of a domain you own. - `version` is what players see; `build_number` goes up by one for every upload to a store. - `icon.png` is a 1024-pixel square PNG, which `nsgo build` turns into every size each platform wants. Add `icon.apple`, an Icon Composer `.icon`, for the layered icons of macOS and iOS. ## An icon from code The icon is drawn by the same kind of code as the sprites, in `internal/icon`, and written by a small tool: ```go //go:generate go run ./tools/genicon assets/Icon.png ``` `go generate ./...` draws it again after a change. The PNG is checked in, because `nsgo build` reads it from `assets/`; a test keeps the two from drifting apart: ```go func TestIconIsUpToDate(t *testing.T) { data, err := os.ReadFile("assets/Icon.png") if err != nil { t.Fatal(err) } got, err := png.Decode(bytes.NewReader(data)) if err != nil { t.Fatalf("assets/Icon.png: %v", err) } if b := got.Bounds(); b.Dx() != 1024 || b.Dy() != 1024 { t.Fatalf("icon is %dx%d, want 1024x1024", b.Dx(), b.Dy()) } want := icon.Render(1024) // Compare every pixel of got and want… } ``` A game with drawn art keeps its icon in `assets/` and skips the generator. ## Pause when the app loses the focus `game.Loop` already runs no updates while the app is in the background, but it keeps stepping while the app is only inactive: while a call rings, while the app switcher is open, or while another window has the focus on a desktop. A player who looks away should come back to the pause menu, not to stars that fell while they were gone. An effect watches the app's lifecycle and pauses a game in play whenever the app is not active: ```go cx.Effect(func() { if cx.Env().Lifecycle() != core.LifecycleActive && s.phase.GetUntracked() == phasePlaying { s.setPhase(phasePaused) } }) ``` `cx.Effect` runs its function again whenever a signal it read changes. It reads the lifecycle and nothing else: the phase is read untracked, so starting or pausing a game does not run it. `TestLosingTheFocusPausesTheGame` makes the app inactive, then sends it to the background, with `app.SetEnvironment`, brings it back each time, and finds the pause menu. ## Play whole games before a release Unit tests check one rule at a time. Before a release, it is worth knowing that the rules add up to a game: one that can be played, gets harder, and ends. `TestAWholeGame` plays whole games of three seeds with a simple bot, which heads for the lowest star and steps aside from a rock about to land in the basket: ```go func TestAWholeGame(t *testing.T) { for _, seed := range []uint64{1, 2, 3} { w := newWorld(seed) steps := 0 for !w.over && steps < 60*60*20 { w.step(step, bot(w)) steps++ } if !w.over { t.Fatalf("seed %d: a game lasted over 20 minutes", seed) } if w.score < 20 { t.Fatalf("seed %d: the bot caught only %d stars", seed, w.score) } } } ``` Because the world is deterministic, each seed plays the same game every run, so the test never flakes; and because it steps the world directly, twenty minutes of play take milliseconds. If a change to the rules makes the game unwinnable or endless, this test says so before the players do. ## Check every target `nsgo check` vets the code for each target, catching a call that does not build on one of them: ```sh go tool nsgo check -target macos,windows,linux,android,web go tool nsgo check -target ios,ios_simulator # on a Mac with Xcode ``` The repository's CI runs both for every chapter on each change, with every chapter's tests on Linux and macOS, as `.github/workflows/examples.yml` shows. ## Build release packages `nsgo build` builds the targets `nsgo.yaml` lists, into one directory per target under `dist/`, with installers and archives beside them: ```sh go tool nsgo build go tool nsgo build -target web go tool nsgo build -channel store -target macos,windows,ios,android ``` The web build is a folder to put on any static host. Try it locally with `go tool nsgo build -target web -run`, which serves it and opens a browser. The `store` channel makes the packages the Mac App Store, Microsoft Store, App Store and Google Play take; [Building and Shipping](https://game.nsgo.dev/docs/shipping/) explains signing and uploading them. ## Where next Star Catcher is finished: it opens on any of six platforms, plays the same at any frame rate, takes touch, mouse and keyboard, sounds, remembers, pauses, and is tested from its rules to its whole games. To grow it, or to start a game of your own: - Load drawn art with `sprite.LoadAtlas` and recorded sounds by `"asset:"` URI, as [Getting Started](https://game.nsgo.dev/docs/getting-started/) shows. - Add bursts when a star is caught with [particles](https://game.nsgo.dev/docs/particles/), and a pop on the score with [tween](https://game.nsgo.dev/docs/tween/). - Let players remap the controls, and save them, with [input](https://game.nsgo.dev/docs/input/)'s `Save` and `Load`. - Record a game's inputs and replay it in a test with [replay](https://game.nsgo.dev/docs/replay/). --- Source: https://game.nsgo.dev/docs/tutorial/ # Tutorial: Star Catcher Build a whole game, Star Catcher, from an empty project to a release you can ship, in nine chapters. Each chapter adds one idea to the game, and each chapter's finished code is in the repository, where CI builds it for every target and runs its tests. In Star Catcher, stars and rocks fall down five lanes. The player moves a basket from lane to lane to catch the stars and dodge the rocks. A missed star or a caught rock costs one of three lives, and the game speeds up as the score grows. ## Chapters | Chapter | You add | Packages | Code | | --- | --- | --- | --- | | [1. An empty project](https://game.nsgo.dev/docs/tutorial-01-empty-project/) | A module, `nsgo.yaml`, a `Canvas` and a first test | `core`, `nsgotest` | [`ch01-empty-project`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch01-empty-project/) | | [2. The game loop](https://game.nsgo.dev/docs/tutorial-02-game-loop/) | A fixed-step loop, a virtual resolution and a world that tests can step | `game`, `screen` | [`ch02-game-loop`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch02-game-loop/) | | [3. Input](https://game.nsgo.dev/docs/tutorial-03-input/) | Touch, mouse and keyboard moving the basket through named actions | `input` | [`ch03-input`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch03-input/) | | [4. Sprites](https://game.nsgo.dev/docs/tutorial-04-sprites/) | A sprite atlas painted in code, sprites, a batch and an animation | `sprite` | [`ch04-sprites`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch04-sprites/) | | [5. Rules](https://game.nsgo.dev/docs/tutorial-05-rules/) | Random spawns, collisions, score, lives and the end of a game | `random`, `physics` | [`ch05-rules`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch05-rules/) | | [6. Screens](https://game.nsgo.dev/docs/tutorial-06-screens/) | A title screen, a pause menu and a game-over screen in native views | `core`, `base` | [`ch06-screens`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch06-screens/) | | [7. Sound](https://game.nsgo.dev/docs/tutorial-07-sound/) | Effects synthesized in Go, a mixer and a mute switch that is remembered | `sound`, `audio` | [`ch07-sound`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch07-sound/) | | [8. Saving](https://game.nsgo.dev/docs/tutorial-08-save/) | The best score kept across launches in a versioned save slot | `save` | [`ch08-save`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch08-save/) | | [9. Shipping](https://game.nsgo.dev/docs/tutorial-09-ship/) | An icon, store metadata, a pause when the app loses the focus and release builds | `nsgo build` | [`ch09-ship`](https://github.com/nsgo-dev/game/blob/main/examples/tutorial/ch09-ship/) | Every chapter is a complete program. Its directory holds the whole game as it stands at the end of the chapter, so you can run any chapter on its own, or compare two to see exactly what a chapter changed: ```sh git diff --no-index examples/tutorial/ch04-sprites examples/tutorial/ch05-rules ``` ## Before you start You need Go 1.27 and NSGo v0.3.4 or later, as [Getting Started](https://game.nsgo.dev/docs/getting-started/) describes. The tutorial explains each API it uses as it goes; the package guides, such as [Loop](https://game.nsgo.dev/docs/loop/) and [input](https://game.nsgo.dev/docs/input/), cover the rest of each package. To follow along in your own module, start with chapter 1, which creates one. To run the chapters from a checkout of this repository instead, work in `examples/tutorial`, a Go module that holds all nine: ```sh cd examples/tutorial go tool nsgo dev ./ch05-rules go tool nsgo test ./ch05-rules go tool nsgo test ./... ``` `nsgo dev` runs a chapter on this machine and reloads it when you save; add `-target web`, `-target ios_simulator` or `-target android` to run it elsewhere. `nsgo test` runs a chapter's tests, or every chapter's with `./...`. ## How the game is built Every chapter keeps the same split, which is worth knowing before you start: - **`world.go`** holds the game's state and rules, and only its `step` method changes them. It knows nothing about windows, so tests step it directly, and the same seed and moves always play the same game. - **`game.go`** ties the world to the screen. A `game.Loop` calls `step` sixty times a second with the player's input, and a `Canvas` draws the world in between. - **`screens.go`**, from chapter 6, builds the native NSGo views over the canvas: the score, the menus and their buttons. - **`*_test.go`** tests both: the rules through `world`, and the whole app through `nsgotest`, which runs it without a window and lets a test press buttons, type keys, touch the screen and advance time. Start with [chapter 1](https://game.nsgo.dev/docs/tutorial-01-empty-project/). --- Source: https://game.nsgo.dev/docs/tween/ # tween `game/tween` animates numbers, points, colors, custom types, timelines, and `tilemap.Camera` moves deterministically on `game.Loop`'s fixed steps using NSGo's `core.Curve` easing functions. ```go import "github.com/nsgo-dev/game/pkg/tween" ``` ## Creating and stepping a Tween Construct a `*Tween` with `Float32`, `Float64`, `Point`, `Color`, or generic `New[T]`, optionally chain `Delay`, `Repeat`, and `OnComplete`, and step it via `Update(dt)` (or a `Group`): ```go var group tween.Group popup := tween.Float32(0, 1, 300*time.Millisecond, core.EaseOut, func(v float32) { banner.ScaleX, banner.ScaleY = v, v }).Delay(100 * time.Millisecond). OnComplete(func() { bannerReady = true }) bob := tween.Float32(0, -6, 600*time.Millisecond, core.EaseInOut, func(y float32) { coin.Y = baseY + y }).Repeat(tween.RepeatForever, true) // yoyo forever group.Add(popup, bob) // Inside game.Loop.Update: group.Update(dt) // finished tweens are removed automatically ``` - **Easing**: a zero `core.Curve` defaults to `core.Linear`. - **`Repeat(count, yoyo)`**: runs `count` extra passes after the first (`0` plays once; `tween.RepeatForever` or any negative value repeats forever). When `yoyo` is `true`, alternating passes run back from `to` to `from`. - **Seeking and resetting**: `tw.Seek(at)` jumps to timestamp `at` and applies that exact value without firing `OnComplete`; `tw.Reset()` rewinds to `0`. Inspect `tw.Done()` and `tw.Duration()`. - **Custom types**: use `tween.New[T](from, to, d, curve, lerp, set)` for vectors, transforms, or domain structs. ## Coordinating cutscenes with Timeline `Timeline` places multiple tweens and callback cues on one deterministic clock with play, pause, reverse, loop, and scrub (`Seek`) support: ```go tl := tween.NewTimeline(). Add(0, tween.Float32(0, 1, 400*time.Millisecond, core.EaseOut, setFade)). Append(tween.Point(startPos, endPos, 800*time.Millisecond, core.EaseInOut, setPos)). Call(600*time.Millisecond, func() { playSfx("whoosh") }) tl.Play() // Inside game.Loop.Update: tl.Update(dt) ``` - `Add(at, tw)` places `tw` starting at offset `at`; `Append(tw)` places `tw` at the timeline's current `Duration()`. - `Call(at, fn)` fires `fn` whenever playback crosses `at` (and never fires during `Seek`). - Control playback with `Play()`, `Pause()`, `Restart()`, `Reverse(bool)`, `SetLoop(bool)`, and `Seek(at)` (which places every track — before, during, and after its window — at its exact state at `at`). ## Camera choreography Built-in camera tween helpers animate a `*tilemap.Camera` directly and clamp to `cam.Bounds` whenever set: ```go // Pan to a boss arena, zoom in, then smoothly hand back to following the player intro := tween.NewTimeline(). Add(0, tween.CameraPan(cam, boss.X, boss.Y, 900*time.Millisecond, core.EaseInOut)). Add(200*time.Millisecond, tween.CameraZoom(cam, 1.5, 700*time.Millisecond, core.EaseOut)). Append(tween.CameraZoom(cam, 1.0, 500*time.Millisecond, core.EaseInOut)). Append(tween.CameraFollowTransition(cam, func() core.Point { return player.Pos }, 600*time.Millisecond, core.EaseInOut)) intro.Play() ``` Available camera tweens: | Helper | Animates | | --- | --- | | `CameraPan(cam, toX, toY, d, curve)` | `cam.X`, `cam.Y` from start position to `(toX, toY)`. | | `CameraZoom(cam, toZoom, d, curve)` | `cam.Zoom` (treating `<= 0` as `1`) to `toZoom`. | | `CameraRotate(cam, toRot, d, curve)` | `cam.Rotation` (in radians) to `toRot`. | | `CameraMove(cam, toX, toY, toZoom, toRot, d, curve)` | Position, zoom, and rotation simultaneously. | | `CameraFollowTransition(cam, targetFn, d, curve)` | Blends smoothly from the camera's starting position onto a live moving `targetFn()`, ending directly on `targetFn()`. | --- Source: https://game.nsgo.dev/docs/undo/ # undo `game/undo` records the reversible moves of puzzle and turn-based games, with unlimited undo and redo. ```go import "github.com/nsgo-dev/game/pkg/undo" ``` Nothing in `undo` reads the clock, spawns goroutines or keeps package-level state. ## Moves A `Move[S]` is one reversible change to the game's state `S`, usually a pointer to the board: ```go type Move[S any] interface { Apply(state S) Revert(state S) } ``` `Revert(s)` after `Apply(s)` must leave `s` exactly as it was. A move may store what its `Apply` changed in its own fields (a move with a pointer receiver) and read it back in `Revert`, such as whether a step pushed a crate: ```go type Push struct { Dir string `yaml:"dir"` moved, pushed bool // recorded by Apply, read by Revert } func (p *Push) Apply(b *Board) { p.moved, p.pushed = b.Step(p.Dir) } func (p *Push) Revert(b *Board) { b.Unstep(p.Dir, p.moved, p.pushed) } ``` Two helpers build moves without a type of their own: - `Func[S]{Do: ..., Undo: ...}` is a move made of two functions. - `Group[S]{a, b, c}` undoes and redoes several moves as one, such as a turn that moves a piece and captures another. It applies them in order and reverts them in reverse order. A nil or empty group is a move that changes nothing; `Do` panics, before applying anything, on a group that holds a nil move. ## History `New[S, M](state)` returns an empty `History` over the game's starting state. `M` is the type of its moves: `Move[S]` for moves of several kinds, or one concrete type such as `*Push`, which also lets the history be saved. ```go board := level.Board() h := undo.New[*Board, *Push](board) h.Do(&Push{Dir: "left"}) // applies the move and records it h.Undo() // reverts the latest applied move h.Redo() // applies the latest undone move again h.Seek(0) // back to the starting state ``` - `Do(m)` applies `m` and records it. A move made after an undo discards the moves that could have been redone. - `Undo` and `Redo` report whether there was a move to revert or apply, and `CanUndo` and `CanRedo` say so beforehand, for a game's buttons. - `Seek(n)` undoes or redoes moves until `n` are applied: `Seek(0)` restarts the level and `Seek(h.Len())` redoes every move. - `Len` is the number of moves recorded, `Applied` the number applied, and `Moves` a copy of them in order. - `Clear` forgets every move and keeps the state, which becomes the new starting state. A log saved after `Clear` holds only the later moves, so save the state at the `Clear` with it and restore onto that state. - `OnChange`, when set, is called after each call that applies, reverts or forgets moves. History is unlimited: every move is kept until `Clear`. Because each move reverts its own change, undoing every move returns the state to exactly the starting state, and redoing them returns it to exactly the latest one. The package's tests check this on random walks of hundreds of moves and fuzz arbitrary sequences of `Do`, `Undo`, `Redo`, `Seek` and `Clear` against a copy of the state after every move. A move's methods must not call the `History` that holds it, and a `History` is not safe for concurrent use. ## Saving a history A history whose moves are one concrete type can be saved as a `Log` and restored, so a player who quits mid-level can still undo after loading. The log is YAML text: ```yaml version: 1 applied: 2 moves: - dir: right - dir: down - dir: down ``` - `version` is `LogVersion` (1); `applied` is how many of the `moves` are applied, and the rest are the moves `Redo` can bring back. - `h.Log()` returns the log and `EncodeLog` writes it in this field order with 2-space indentation, so the same history always writes the same text. - `DecodeLog[M](data)` reads it back, refusing a missing `version`, `applied` or `moves` key, a null `moves`, unknown fields (in the log or in a move), another version, an `applied` outside the moves, a null move and trailing YAML documents. - `Restore(start, log)` returns a `History` over the starting state the log was recorded from, which is the state given to `New` or, after a `Clear`, the state at that `Clear`: it applies the first `applied` moves in order and keeps the rest for `Redo`. Keep what a move records during `Apply` in unexported fields or fields tagged `yaml:"-"`, so the log holds only what the player chose; `Restore` applies the moves again, which records it anew. Store the log with the game's save, for example in a [save](https://game.nsgo.dev/docs/save/) slot or a file of its own. ```go data, err := undo.EncodeLog(h.Log()) // ...later, with the board the history started from (the level's start, or the board saved at the last Clear): log, err := undo.DecodeLog[*Push](data) h, err = undo.Restore(level.Board(), log) ``` --- Source: https://game.nsgo.dev/docs/vehicle/ # vehicle ```go import "github.com/nsgo-dev/game/pkg/vehicle" ``` Raycast cars on a [`physics3d`](https://game.nsgo.dev/docs/physics3d/) world: wheel colliders, spring-damper suspension, longitudinal and lateral tire friction and a car controller, plus race checkpoints, lap times and ghost replays. ## Model A `Vehicle` is one dynamic `physics3d.Body`, the chassis, whose `Pos` is the center of mass, plus a list of wheels. Wheels have no bodies of their own: every fixed step, `Vehicle.Step` casts one ray per wheel from its anchor along the chassis' down axis, so a wheel costs one raycast and cannot snag on geometry. For each wheel that touches the ground, a step: 1. **Suspension**: turns the ray's compression into a spring-damper force, `Stiffness * compression - Damping * extension speed`, never pulling and capped by `MaxForce`, and pushes the chassis up at the anchor. 2. **Tires**: computes a longitudinal impulse (engine on drive wheels, brakes on brake wheels, rolling resistance) and a lateral impulse that cancels the wheel's share of sideways slip, then limits their sum to a friction circle of `Friction * load`. A wheel that hits the limit reports `Sliding`, for skid marks or tire squeal. 3. **Reaction**: applies the opposite impulses to a dynamic body under the wheel, so a car can push a crate or a platform it drives over. Every wheel's tire impulse is computed from the same chassis state and applied afterwards, so the result does not depend on wheel order and a symmetric car drives straight. Aerodynamic drag, `Drag * speed²`, then acts on the chassis, and `World.Step` integrates it. Cars face `-Z` in local space, with `+X` to the right and `+Y` up, matching [3D Models from Blender](https://game.nsgo.dev/docs/3d-models-blender/). ## Driving a car ```go world := physics3d.NewWorld() world.AddBody(physics3d.NewStaticBody( physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 200, Y: 1, Z: 200}}), physics3d.Vec3{Y: -1}, )) car, err := vehicle.New(world, vehicle.ReferenceConfig(), physics3d.Vec3{Y: 0.65}, physics3d.QuatIdentity()) if err != nil { ... } controls := vehicle.DefaultControls() loop := &game.Loop{Update: func(dt time.Duration) { actions.Step() car.SetInput(controls.Read(actions)) car.Step(world, dt) world.Step(dt) }} ``` Call `Vehicle.Step` once per fixed step, before `World.Step`. `Input` holds `Throttle` in `[-1, 1]` (negative reverses), `Brake` in `[0, 1]`, `Steer` in `[-1, 1]` (positive steers right) and `Handbrake`; `SetInput` clamps each axis and treats NaN as 0, and the input stays in effect until it is set again. Steering eases toward the requested angle at `SteerRate`, and the engine force fades to zero at `MaxSpeed`. `Controls` names the axes and action a car reads (by default `"throttle"`, `"brake"`, `"steer"` and `"handbrake"`), so the same code drives a car from live `*input.Actions`, a `replay.Recorder` while recording, or a `replay.Player` while playing back. To read the car's state: - `Speed()` is the signed speed along `Forward()`, negative while reversing; `Up()` is the chassis' up axis, such as to detect a roll-over. - `Grounded()` counts the wheels touching the ground, and each `Wheels[i]` reports `Contact`, `ContactPoint`, `ContactNormal`, `Ground`, `SuspensionLength`, `SuspensionForce`, `SteerAngle`, `SpinSpeed`, `SpinAngle` and `Sliding`. - `WheelTransform(i)` returns wheel `i`'s world-space center and orientation, including steering and spin, for drawing its mesh, whose axle is its local X axis. - `Reset(pos, rot)` teleports the car, stops it and clears its wheels, such as to respawn at a checkpoint. - `Config()` returns a copy of the car's tuning. The tuning is fixed for the car's lifetime, and each `Wheels[i].Config` is a copy for reading; to drive with different tuning, create a new `Vehicle`. `RayMask` selects the layers wheel rays hit; trigger bodies and the chassis itself are always skipped, so checkpoints do not hold a car up. A settled car sleeps like any other body and wakes when `SetInput` gives it throttle, brake, steering or handbrake. A held throttle keeps it awake, such as while pushing against a wall, while a held brake or handbrake lets it sleep. ## Car files A car's tuning is a `Config`, written as versioned YAML. `ParseConfig` decodes and validates it, refusing unknown fields and trailing documents; `EncodeConfig` writes deterministic 2-space YAML that `ParseConfig` reads back unchanged. Lengths are meters, masses kilograms, forces newtons and angles degrees, and positions are in chassis space relative to the center of mass. ```yaml version: 1 name: reference mass: 1200 chassisHalfExtents: [0.9, 0.3, 2] chassisOffset: [0, 0.2, 0] engineForce: 6000 reverseForce: 3000 maxSpeed: 40 maxReverseSpeed: 8 brakeForce: 12000 handbrakeGrip: 0.4 maxSteerAngle: 30 steerRate: 120 drag: 0.4 rollingResistance: 0.015 rollInfluence: 0.1 angularDamping: 0.5 wheels: - name: front-left anchor: [-0.8, -0.1, -1.3] radius: 0.35 restLength: 0.3 stiffness: 30000 damping: 4000 maxForce: 20000 friction: 1.2 steer: true brake: true # front-right, rear-left and rear-right follow; the rear wheels set drive and handbrake instead of steer. ``` | Field | Meaning | | --- | --- | | `mass`, `chassisHalfExtents` | Chassis mass and collision box half sizes, all `> 0` | | `chassisOffset` | Moves the box relative to the center of mass; a positive Y lowers the center of mass inside the box, which steadies the car | | `engineForce`, `reverseForce` | Total drive force at full throttle and standstill, split over the drive wheels | | `maxSpeed`, `maxReverseSpeed` | Speeds in m/s at which the drive force fades to zero | | `brakeForce` | Total braking force at full brake, split over the brake wheels | | `handbrakeGrip` | Lateral grip of handbrake wheels while the handbrake is held, in `[0, 1]`; lower values slide more | | `maxSteerAngle`, `steerRate` | Largest steering angle in `[0, 80]` degrees and how fast steered wheels turn, in degrees per second | | `drag`, `rollingResistance` | Aerodynamic drag coefficient and rolling resistance as a fraction of each wheel's load | | `rollInfluence` | How much lateral tire force rolls the chassis, in `[0, 1]`: 0 at the center of mass' height, 1 at the contact point | | `angularDamping` | The chassis' `physics3d.Body.AngularDamping` | | `wheels` | 1 to 32 wheels with unique names, in a fixed order | | `anchor`, `radius`, `restLength` | Top of the suspension, wheel radius and unloaded suspension length; the ray is `restLength + radius` long | | `stiffness`, `damping`, `maxForce` | Spring rate in N/m, damper rate in N·s/m and an optional force cap (0 leaves it uncapped) | | `friction` | Tire friction coefficient: the combined tire force stays within `friction` times the wheel's load | | `steer`, `drive`, `brake`, `handbrake` | Which inputs the wheel receives | `ReferenceConfig()` returns the reference car: a 1200 kg rear-wheel-drive hatchback with about 0.5 g of acceleration, 1 g of braking and a 40 m/s top speed. Its file is `vehicle/testdata/reference_car.yaml`. ## Races and laps A race is an ordered list of checkpoint triggers. `AddCheckpoint` adds a static trigger body to the world, and `NewRace` tracks racers through them for a number of laps: ```go gate := physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 7, Y: 2, Z: 0.5}}) race, err := vehicle.NewRace(3, vehicle.AddCheckpoint(world, gate, start), vehicle.AddCheckpoint(world, gate, sector1), vehicle.AddCheckpoint(world, gate, sector2), ) world.OnTrigger = race.Observe racer := race.AddRacer(car.Body, "player") race.OnLap = func(ev vehicle.LapEvent) { ... } // Each fixed step: race.Tick() car.Step(world, dt) world.Step(dt) ``` Checkpoint 0 is the start/finish line, and each checkpoint must be a different trigger body: a track that passes the same place twice, such as a figure eight's crossing, needs a trigger for each pass. A racer's first lap starts on the step it is added; it must enter checkpoints 1, 2, ... in order and then checkpoint 0 to complete a lap, and entering any other checkpoint is ignored, so cutting the track does not count. Times are counted in fixed steps: call `Tick` once per step, before `World.Step`, and multiply by the step duration for wall time. Each `Racer` reports `Laps`, `Next`, `LastLap`, `BestLap`, `Finished` and `FinishStep`; `OnLap` receives a `LapEvent` for every completed lap, with whether it was the racer's best and final. `Standings()` orders racers: finished racers by finish step, then the rest by laps and checkpoints passed, ties in the order they were added. `Observe` ignores events that are not a checkpoint entry, so it can sit behind other trigger handlers. ## Ghosts A `Ghost` is a recorded lap: the chassis pose sampled every `Interval` steps, played back as a translucent rival. It is pose data, so playing it needs no physics. ```go rec := &vehicle.GhostRecorder{Interval: 2} // When the racer is added, the first lap's first frame: rec.Record(car.Body.Pos, car.Body.Rot) race.OnLap = func(ev vehicle.LapEvent) { rec.Finish(car.Body.Pos, car.Body.Rot) // the finish line, even between samples if ev.Best { best = rec.Ghost(60, ev.Steps) } rec.Reset() } // After each World.Step: rec.Record(car.Body.Pos, car.Body.Rot) // Drawing the ghost, with game.Loop's draw alpha: pos, rot := best.Pose(float64(step) + alpha) ``` Frame `i` is at step `i * Interval`, except that the last frame is at step `LapSteps` when it is set, so `Finish` ends a ghost exactly on the finish line even when the lap's step count is not a multiple of `Interval`. `Pose` interpolates positions linearly and orientations spherically between frames, and clamps steps outside the recording to its first or last frame. Ghosts are text, like every file in this repository: `EncodeGhost` writes versioned YAML with each frame's position and rotation on a flow-style line of its own, and `ParseGhost` reads it back unchanged, refusing unknown fields, more than an hour of frames at 60 Hz, and a `lapSteps` that does not fall within the last `interval` before the last frame. ```yaml version: 1 rate: 60 interval: 2 lapSteps: 812 frames: - p: [0, 0.62, 14] r: [0, 0, 0, 1] - p: [0, 0.62, 13.98] r: [0, 0, 0, 1] # ... 405 more frames, the last at step 812 ``` To reproduce a drive exactly, such as for a bug report, record the car's input instead with `replay.NewRecorder(actions, seed, rate, controls.Actions(), controls.Axes())` and play it back through `replay.Player` into `Controls.Read`. ## Determinism `Vehicle.Step` uses no maps, wall clock or randomness and visits wheels in `Config` order, and `physics3d` steps in a fixed order, so the same `Config`, start pose and per-step `Input` on the same world produce bit-identical poses, lap times and ghosts across runs on one platform. The package's acceptance test drives the reference car two laps around a test track (two 40 m straights joined by 15 m hairpins, with a speed bump) and checks that two runs end bit-identical; a second test records the drive with `replay`, round-trips the recording through its file format and replays it into a fresh world to the same end state. ## Limits - The chassis collides as one box, and `physics3d` treats its inertia as isotropic, so pitch, roll and yaw respond alike to the same torque; tune `rollInfluence`, `chassisOffset` and `angularDamping` for handling. - Tires use a friction circle rather than a slip-curve tire model such as Pacejka's, and the engine is a force that fades with speed rather than a torque curve with gears. - Wheel rays test every body in the world in turn, as `physics3d` raycasts do; keep large static scenery in triangle meshes or heightfields. --- Source: https://game.nsgo.dev/docs/vn/ # vn `github.com/nsgo-dev/game/pkg/vn` plays a dialogue script as a visual novel: character portraits with expressions, a text box with name plates and a typewriter, choices, a backlog, auto and skip modes, and voice lines. A `Presenter` runs a Yarn Spinner script with [`flow`](https://game.nsgo.dev/docs/flow/)'s `DialogueRunner` and a cast read from a YAML cast file. `Update` moves it on by [`game.Loop`](https://game.nsgo.dev/docs/loop/)'s fixed step and `Draw` draws it into a `Canvas`, so a scene plays alike every time and under `nsgotest`. ## Cast file A cast file names the stage slots portraits stand in and the characters, each with a name plate and a portrait frame per expression: ```yaml version: 1 slots: - name: left x: 0.25 - name: center x: 0.5 - name: right x: 0.75 characters: - id: aiko name: Aiko color: '#e07a5f' slot: left expressions: - name: neutral frame: aiko_neutral - name: smile frame: aiko_smile ``` - `version` must be `1`; unknown fields and a second YAML document are refused. - A slot's `x` is the portrait's center as a fraction of the stage's width. Without `slots`, the cast uses left (0.2), center (0.5) and right (0.8). - A character's `id` is what commands name; a line's speaker matches the `id` first, then `name`. `name` is the name plate's text (the `id` when empty) and `color` the plate's color as a CSS color. - `slot` is where the portrait enters (the middle slot when empty) and `defaultExpression` the expression it enters with (the first when empty). - Each expression's `frame` names a frame in the portrait atlas; `Cast.CheckFrames(atlas)` reports a missing one as the game loads. An expression may not share a slot's name, so `<>` reads its arguments one way. `ParseCast` reads and validates a file and `EncodeCast` writes one with fields in schema order and lists in their order, so a load and a save change nothing. ## Scripts Lines steer the stage with tags after the line: | Tag | Effect | | --- | --- | | `#expr:smile` | Sets the speaker's expression | | `#at:center` | Moves the speaker's portrait to a slot | | `#voice:aiko_001` | Plays a voice line | | `#offstage` | Speaks the line without bringing the speaker's portrait on the stage | A line by a cast member brings their portrait on the stage and marks it speaking; the others dim. A narration line has no name plate. A speaker not in the cast shows the name as written and takes no `#expr:` or `#at:` tag. Three commands are the presenter's own; every other command reaches `DialogueOptions.OnCommand` as before, and all of them reach `DialogueOptions.Bus`: ```text <> // enters in its slot with its default expression <> // slot and expression in either order <> <> <> // every portrait ``` A portrait shown in a slot another character holds sends that character off the stage. An unknown character, slot or expression is an error the call that ran it returns. ```yarn title: Start --- <> <> Aiko: Welcome to the old observatory. #line:obs_01 #voice:aiko_01 Ren: It is smaller than I pictured. #line:obs_02 Aiko: Small, but the sky is the same size. #expr:smile #line:obs_03 -> Look through the telescope #line:obs_c1 Aiko: Careful, the lens is old. #expr:worry #line:obs_05 -> Ask about the logbook #line:obs_c2 Ren: Who kept this logbook? #at:center #line:obs_07 === ``` ## Presenter ```go p := vn.New(script, cast, vn.Options{ Voices: voices, AutoDelay: time.Second, SkipInterval: 80 * time.Millisecond, }) if err := p.Start("Start"); err != nil { ... } loop := &game.Loop{Update: func(dt time.Duration) { if err := p.Update(dt); err != nil { ... } }} ``` - `Advance` is the player's tap: it shows the rest of a line still appearing, or goes on. It stops skip mode, and returns `flow.ErrChoiceRequired` while choices wait. - `Choices` lists the options waiting and `Choose(index)` picks one. - `Line` is the line shown with its name plate's `Name` and `Color`, its `Voice`, and `Read`, whether the player had read it before. - `Portraits` lists the portraits on the stage in the order to draw them, each with its slot, expression, frame and whether its character speaks. - `Runner` gives the `flow.DialogueRunner` for variables and its save state. - `Start` on a node the script lacks returns `flow.ErrUnknownNode` and leaves the stage and the line as they were. `Options.CharsPerSecond` sets the typewriter's speed (40 when 0; negative shows a line at once). ## Auto and skip `SetAuto(true)` goes on by itself once a line's text has appeared, its voice line has ended and `AutoDelay` has passed (1.5 s when 0), plus `AutoDelayPerRune` for each character. It waits at choices. `SetSkip(true)` shows a line every `SkipInterval` (each `Update` when 0) at once and without its voice. It stops at choices, at the end, on `Advance` and on a line the player had not read before, which shows as usual; `SkipUnread` lets it run through those too. A line counts as read once it has been shown. Its key is its `#line:` id, or the node, speaker and text of an untagged line, taken after string table lookup and `{$var}` interpolation, so an untagged line counts as unread again after a language switch or with a changed variable; give lines `#line:` ids to keep skip working across both. `ReadKeys` returns the keys for a save to keep and `MarkRead` restores them, so skip knows read lines across sessions. ## Backlog `Backlog` returns the lines shown and the options chosen (`Choice` set), oldest first, up to `BacklogSize` entries (200 when 0; negative keeps none). `ReplayVoice(i)` plays entry `i`'s voice line again. ## Voice lines A `VoicePlayer` plays a voice line by id and returns how long it plays, which auto mode waits for. Going on stops the line playing. `EffectVoices` plays lines through a [`sound.Mixer`](https://game.nsgo.dev/docs/sound/): ```go voices := &vn.EffectVoices{Clips: map[string]vn.VoiceClip{}} audio.LoadSound(cx, src, func(snd *audio.Sound, err error) { if err == nil { voices.Clips["aiko_01"] = vn.VoiceClip{Effect: mixer.Effect(snd, "voice", 1), Length: snd.Duration()} } }) ``` With `VoiceFromLineID`, a line without a `#voice:` tag plays its `#line:` id. ## Drawing ```go style := vn.Style{Atlas: portraits, PortraitHeight: 300, InactiveAlpha: 0.55} core.Canvas{Draw: func(d *core.Drawing, size core.Size) { if showLog { p.DrawBacklog(d, size, style, scroll) return } p.Draw(d, size, style) }} ``` `Draw` draws the portraits standing on the stage's bottom edge, the text box with the name plate and the revealed text, and the choice buttons. A zero `Style` field uses a default; `Box` takes a `sprite.NineSlice` for the text box and `Font` a bitmap font for the text, which is platform text otherwise. `DrawBacklog` draws the backlog newest at the bottom, skipping the newest `scroll` entries; an entry taller than the stage is drawn alone from the top and cut off at the bottom. The choice buttons are drawn whenever choices wait, also in a node that opens with them before any line. `Style.Layout(size, n)` returns the text box's and the choice buttons' bounds, and `ChoiceAt(size, style, point)` the choice under a tap: ```go if i, ok := p.ChoiceAt(size, style, ev.Position); ok { err = p.Choose(i) } ``` ## Sample `pkg/vn/cmd/vnsample` plays a short scene with two characters whose portraits and voices are drawn and synthesized in code. Tap to go on, pick a choice, and use Auto, Skip and Log; watch the scene again and Skip runs through the lines already read. ```sh go tool nsgo dev ./pkg/vn/cmd/vnsample ``` --- Source: https://game.nsgo.dev/docs/voxel/ # voxel `game/voxel` provides chunked 3D voxel worlds for sandbox games: dense cubic chunks, per-voxel sky and block light propagation (0..15) across chunk borders, greedy face meshing into [render3d](https://game.nsgo.dev/docs/render3d/) buffers, cross-chunk neighbor culling and ambient occlusion, minimal dirty-chunk tracking on edit, 3D DDA voxel raycasting, direct solid-block collision for [physics3d](https://game.nsgo.dev/docs/physics3d/) bodies and characters (plus an axis-separated AABB move-and-slide character mover), and deterministic versioned YAML saves. ```go import "github.com/nsgo-dev/game/pkg/voxel" ``` ## Blocks and registry Register block types in a `Registry` to configure transparency, solidity, `MaterialID` sub-mesh grouping, `Emissive` block light level (`0..15`), and `LightOpacity` attenuation (`0..15` for transparent blocks). Block ID `0` (`voxel.Air`) is reserved for empty space; unregistered non-zero IDs default to opaque (`LightOpacity: 15`), solid, non-emissive, and `MaterialID: 0`: ```go reg := voxel.NewRegistry() stone := reg.MustRegister(voxel.BlockDef{Name: "stone", MaterialID: 0}) grass := reg.MustRegister(voxel.BlockDef{Name: "grass", MaterialID: 1}) glass := reg.MustRegister(voxel.BlockDef{Name: "glass", Transparent: true, MaterialID: 2}) water := reg.MustRegister(voxel.BlockDef{Name: "water", Transparent: true, NonSolid: true, LightOpacity: 2, MaterialID: 3}) torch := reg.MustRegister(voxel.BlockDef{Name: "torch", Transparent: true, NonSolid: true, Emissive: 14, MaterialID: 4}) ``` Face culling follows standard opaque/transparent rules: - Opaque blocks emit faces toward `Air` and transparent blocks. - Transparent blocks emit faces toward `Air` and *different* transparent block IDs, culling faces pressed against opaque blocks or identical transparent neighbors. ## Sky and block light propagation Each voxel stores two 4-bit light channels (`0..15`, packed into one byte per voxel): - **Sky light**: unobstructed columns directly exposed to the sky carry level `15` straight down through `Air` and zero-opacity transparent blocks (such as glass). Hitting a light-attenuating block (`LightOpacity > 0`, or an opaque block with effective opacity `15`) shadows the column below, and sky light diffuses horizontally and vertically from brighter neighbors by `max(1, LightOpacity)` per voxel. - **Block light**: blocks with `Emissive > 0` (such as torches or glowstone) seed block light at their emission level and flood fill outward across chunk boundaries, attenuating by `max(1, LightOpacity)` per voxel. `World.SetBlock` updates both light channels incrementally using flood-fill addition and removal BFS across chunk borders—matching `World.RecomputeLight()` identically while marking only chunks whose mesh geometry or border lighting actually changed as dirty. Query light levels at any world coordinate with `w.SkyLight(pos)`, `w.BlockLight(pos)`, or `w.Light(pos)` (or locally on a chunk via `ch.SkyLight`, `ch.BlockLight`, `ch.Light`). ## Chunked worlds and dirty tracking Create a `World` with a power-of-two `ChunkSize` (`4` to `64`, default `16` for 16×16×16 chunks) and a world-space `VoxelSize` (default `1`): ```go w, err := voxel.NewWorld(voxel.WorldConfig{ ChunkSize: 16, VoxelSize: 1, Registry: reg, }) if err != nil { return err } w.FillBox(voxel.BlockCoord{X: 0, Y: 0, Z: 0}, voxel.BlockCoord{X: 31, Y: 3, Z: 31}, stone) w.SetBlock(voxel.BlockCoord{X: 8, Y: 4, Z: 8}, grass) ``` `SetBlock` marks the edited block's chunk dirty, and marks adjacent existing chunks dirty only when the edit changes neighbor face visibility, cross-chunk ambient occlusion, or cross-chunk sky/block lighting. Replacing one opaque non-emissive block with another never dirties neighboring chunks. Call `w.PruneEmptyChunks()` after remeshing if you want to release chunks that have been emptied back to all `Air` (non-default light passing through a pruned chunk is preserved). ## Greedy meshing Keep a reusable `Mesher` to avoid temporary buffer allocations across frames. `RemeshDirty` meshes only dirty chunks in deterministic `CompareChunkCoords` order and clears their dirty flags: ```go mesher := voxel.NewMesher() opts := voxel.MeshOptions{ AmbientOcclusion: true, // per-vertex AO in ChunkMesh.AO + diagonal flip Lighting: true, // per-vertex SkyLight, BlockLight, and linear RGBA Colors SmoothLighting: true, // 4-voxel smooth corner interpolation across chunk borders UVMode: voxel.UVWorld, } for _, cm := range mesher.RemeshDirty(w, opts) { if cm.Empty() { releaseChunkGPU(cm.Coord) continue } // cm.Mesh is a CCW render3d.Mesh ready for render3d.UploadMesh. // cm.ColoredMesh() returns a render3d.ColoredMesh with linear RGBA light+AO // vertex colors ready for render3d.UploadColoredMesh and colored render3d pipelines. // cm.SubMeshes partitions cm.Mesh.Indices by BlockDef.MaterialID. uploadChunkGPU(cm.Coord, cm.Origin, cm.ColoredMesh(), cm.SubMeshes) } ``` Key options in `MeshOptions`: - `AmbientOcclusion`: computes per-vertex AO levels (`0..3`) in `ChunkMesh.AO` (convert with `AOFactor`) across chunk boundaries, flips quad diagonals to avoid interpolation seams, and merges faces only when all four AO corners match. - `Lighting` / `SmoothLighting` / `LightStyle`: populates per-vertex `ChunkMesh.SkyLight` (`0..15`), `ChunkMesh.BlockLight` (`0..15`), and linear RGBA `ChunkMesh.Colors` (combining `LightFactor` of sky/block light tinted by `LightStyle` with `AOFactor` when AO is enabled). Greedy meshing merges faces only when lighting matches so there are no chunk-border seams. Call `cm.ColoredMesh()` to hand the mesh straight to `render3d.UploadColoredMesh` (compatible with `render3d.NewUnlitPipeline` and `render3d.NewMaterialPipeline` with `VertexColors: true`). - `WorldSpace`: emits vertices offset by `ChunkMesh.Origin` instead of chunk-local `[0, ChunkSize*VoxelSize]`. - `UVMode`: `UVWorld` (default) scales UVs by merged quad width and height for seamless texture tiling; `UVUnit` assigns `[0, 1]` per quad. - `DisableGreedy` / `IgnoreNeighbors`: disable greedy rectangle merging or cross-chunk culling/lighting for debugging or comparisons. ## Voxel raycasting and editing Use `World.Raycast` (3D Amanatides & Woo DDA traversal) to pick blocks and place neighbors against the struck face: ```go if hit, ok := w.Raycast(ray, 64); ok { // Break the struck block: // w.SetBlock(hit.Block, voxel.Air) // Or place a new block on the struck face: w.SetBlock(hit.Adjacent, stone) } ``` By default `Raycast` skips `NonSolid` blocks (such as water); pass `RaycastOptions{IncludeNonSolid: true}` to `RaycastWith` to hit any non-air voxel. ## Voxel collision and character movement Use `w.Collider()` (or `voxel.NewCollider(w)`) to attach a voxel world directly to [physics3d](https://game.nsgo.dev/docs/physics3d/) without generating or rebuilding a triangle mesh: ```go phys := physics3d.NewWorld() phys.AddVoxelCollider(w.Collider()) crate := phys.AddBody(physics3d.NewDynamicBody( physics3d.BoxShape(physics3d.Box{HalfExtents: physics3d.Vec3{X: 0.4, Y: 0.4, Z: 0.4}}), physics3d.Vec3{X: 4.5, Y: 8.0, Z: 4.5}, 1.0, )) cc := physics3d.NewCharacterController(physics3d.Vec3{X: 1.5, Y: 4.0, Z: 1.5}, 0.3, 1.8) cc.StepHeight = w.VoxelSize() + 0.05 ``` - **Zero rebuild on edit**: overlap, raycast, and sweep queries read `World.IsSolid` directly (skipping `Air` and `NonSolid` blocks such as water), so `SetBlock` and `Clear` take effect immediately and automatically wake sleeping dynamic bodies near edited voxels so resting crates fall when their support block is removed. - **No internal seam snagging**: occluded faces shared between adjacent solid blocks are filtered out so sliding boxes, spheres, capsules, and `CharacterController` glide smoothly across flat voxel floors and step up single-block ledges. For games that only need simple box characters against voxel terrain without a full `physics3d.World`, use `MoveAndSlideAABB` or `CharacterMover`: ```go mover := voxel.NewCharacterMover(math3d.Vec3{X: 1.5, Y: 4.0, Z: 1.5}, 0.3, 1.8) mover.StepHeight = w.VoxelSize() res := mover.Move(w, math3d.Vec3{X: 4.0}, dt) // axis-separated Y -> X -> Z sweep + 1-block step-up _ = res ``` ## Saving and loading YAML Worlds serialize to deterministic, versioned YAML text with run-length encoded chunks (`"id*count"` or `"id"` in `(y, z, x)` order), sorted palette entries, and sorted chunk coordinates. Unknown YAML fields and trailing documents are refused, and errors are returned as `*loaderr.Error` values with file, line, column, field path, and fix hints: ```go data, err := voxel.SaveYAML(w, "Overworld") if err != nil { return err } loaded, name, err := voxel.LoadYAML(data) if err != nil { return err } _ = name // Every loaded chunk starts dirty so RemeshDirty builds initial meshes: initialMeshes := mesher.RemeshDirty(loaded, opts) _ = initialMeshes ``` Saved files start with the schema comment `# yaml-language-server: $schema=https://game.nsgo.dev/schemas/voxel.v1.json`; see [Schemas for YAML files](https://game.nsgo.dev/docs/schemas/). --- Source: https://game.nsgo.dev/docs/world3d/ # world3d `game/world3d` provides 3D world-building primitives built on [math3d](https://game.nsgo.dev/docs/math3d/): heightmap terrain, multi-level 3D navigation meshes, modular 3D mesh `GridMap`s, procedural scattered foliage with frustum/distance culling, and floating-origin chunk streaming. ```go import "github.com/nsgo-dev/game/pkg/world3d" ``` ## Heightmap terrain (`Heightmap`) Load a 16-bit (or 8-bit) grayscale PNG heightmap (`LoadHeightmapGray`, `DecodeHeightmapPNG`) or create one with `NewHeightmap`, then sample bilinear heights and normals, raycast against triangles, build chunked `TerrainMesh` geometry, and write back lossless 16-bit grayscale PNGs (`ToGray16`, `EncodePNG`, `EncodeHeightmapPNG`) without 8-bit slope banding: ```go hm := world3d.LoadHeightmapGray(grayImg, 2.0, 40.0) y, ok := hm.HeightAt(player.X, player.Z) normal := hm.NormalAt(player.X, player.Z) hit, hitOK := hm.Raycast(ray, 500) // Build a 32x32 cell mesh chunk for GPU upload: chunkMesh := hm.BuildMesh(0, 0, 32, 32) // Or bridge directly to a physics3d.HeightfieldCollider: hfCollider := hm.Collider() _, _, _, _, _, _ = y, ok, normal, hit, chunkMesh, hfCollider _ = hitOK ``` ## Terrain level of detail (`TerrainLOD`) Large terrains can contain tens of millions of triangles at full resolution. `TerrainLOD` partitions a `Heightmap` into chunks (default 64×64 cells), selects per-chunk power-of-two vertex strides (`1, 2, 4, ...`) from camera-to-AABB distance with hysteresis, applies bias from the game-wide [quality](https://game.nsgo.dev/docs/quality/) preset (`TerrainLODBiasFor`), culls chunk AABBs against the camera frustum, and caches crack-free stitched `TerrainMesh` geometry per chunk: ```go terrain := world3d.NewTerrainLOD(hm, world3d.TerrainLODConfig{ ChunkCells: 64, Hysteresis: 0.10, // 10% deadband around each LOD threshold LODBias: world3d.TerrainLODBiasFor(sel.Level()), }) // Each frame (or use UpdateWithOrigin with a *FloatingOrigin): visibleChunks := terrain.Update(camPos, &frustum) for _, ch := range visibleChunks { if ch.Changed { uploadChunkMesh(ch.Coord, ch.Mesh, ch.Revision) } drawTerrainChunk(ch.Coord, ch.Transform) } ``` - **Crack-free seams**: whenever a chunk borders a coarser neighbor along North, South, West, or East, `BuildMeshLOD` re-triangulates that border strip to connect directly to the neighbor's coarse edge vertices, avoiding both height cracks and T-junctions at every LOD pair (including partial heightmap border chunks). - **Quality presets**: call `terrain.SetQualityLevel(level)` (or `terrain.SetLODBias(bias)`) when the player's quality tier changes. `TerrainLODBiasFor` returns `+1.0` for `quality.Low`, `+0.5` for `quality.Medium`, and `0.0` for `quality.High`, scaling distance thresholds by `2^(-bias)`. - **Floating origin & streaming**: set `WorldOrigin` and call `UpdateWithOrigin(camLocal, &frustumLocal, origin)` so LOD distances stay invariant in `float64` world space across rebases while returned `Bounds` and `Transform` track local space without rebuilding cached meshes. Set `StreamManaged: true` and hook `SetChunkActive` to `ChunkStreamerConfig.OnLoad` / `OnUnload` (with `ChunkSize: terrain.ChunkWorldSize()`) to stream chunks on demand. - **Direct meshing**: `hm.BuildMeshLOD(col, row, cols, rows, lod, neighbors)` and `hm.ChunkBounds(col, row, cols, rows)` are read-only and safe to call directly from background streaming workers. ## Terrain material layers and splat maps (`TerrainSplatMap`, `TerrainDoc`) Blend up to 8 PBR material layers across a heightmap using 1 or 2 RGBA weight (splat) maps (channels R, G, B, A of map 0 drive layers 0..3; map 1 drives layers 4..7), author the layers in a versioned YAML terrain definition (`*.terrain.yaml`), query the surface underfoot for gameplay via `Heightmap.LayerAt(x, z)`, and render the terrain with [render3d](https://game.nsgo.dev/docs/render3d/)'s `TerrainMaterial` / `GPUTerrainMaterial`: ```go doc, err := world3d.ParseTerrain(yamlBytes) // strict version 1 YAML (EncodeTerrain writes canonical form) if err != nil { return err } splat, err := world3d.LoadTerrainSplatMap(doc.LayerInfos(), splatImg0) // pass splatImg0, splatImg1 for 5..8 layers if err != nil { return err } splat.HeightBlendContrast = doc.HeightBlendContrast hm.Splat = splat // Zero-allocation gameplay query for footsteps, particles, and traction: sample, inBounds := hm.LayerAt(player.X, player.Z) playFootstep(sample.Name, sample.Dominant, sample.Weight(sample.Dominant)) _ = inBounds ``` - **Bilinear sampling & clamping**: `TerrainSplatMap.SampleUV` and `Heightmap.LayerAt` use texel-center bilinear filtering with edge clamping, matching GPU linear clamp-to-edge splat sampling. Outside the heightmap footprint, `Heightmap.LayerAt` returns `ok = false` alongside the clamped edge sample. - **Height-based blending**: attach per-layer grayscale height maps (`LoadTerrainHeightLayer`) and set `HeightBlendContrast` in `(0, 1]` to sharpen layer transitions (such as rock protruding through dirt) using the same algebraic `BlendTerrainWeights` formula as `render3d`'s terrain shader. - **Text definition**: `ParseTerrain` / `EncodeTerrain` read and write version 1 YAML (`https://game.nsgo.dev/schemas/terrain.v1.json`) declaring `size` (`[cols, rows]`), `heightmap` (16-bit grayscale PNG), `cellSize`, `heightScale`, `origin`, `chunkSize` (default `64` cells per LOD chunk), either packed RGBA `splatMaps` or per-layer grayscale `weightMap` PNGs (`PackLayerWeightMaps`, `LoadTerrainSplatMapFromWeights`), `heightBlendContrast`, `triplanar`, 1–8 `layers` (each with optional `material` resource path, `weightMap`, `uvScale`, PBR maps/factors, and `heightBias`), and optional embedded `foliage` scatter layers with grayscale `densityMap` PNGs (`DensityMap.EncodePNG`, `Heightmap.FoliageDensityAt`, `TerrainDoc.ScatterFoliage`). Unknown fields, duplicate layer names, mixing `splatMaps` with per-layer `weightMap` paths, size mismatches, and mismatched splat-map counts are refused with `*loaderr.Error`. Call `doc.BuildHeightmap(imgs)` / `doc.BuildLOD(hm)` (or `world3d.LoadTerrainFS(fsys, path)`) to build the runtime `*Heightmap`, attached `*TerrainSplatMap`, attached foliage density maps, and `*TerrainLOD` directly from YAML. `game check` validates every `*.terrain.yaml` file and its referenced heightmap, splat/weight maps, material resources, layer textures, and foliage meshes and density maps. ## Multi-level 3D NavMesh Build a 3D `NavMesh` from convex walkable polygons (ramps, bridges, and stacked floors). `BuildNavMesh` filters polygons steeper than `maxSlopeRad`, links shared edges in 3D, and runs portal A* with 3D string-pulling in `FindPath`: ```go nav := world3d.BuildNavMesh(walkablePolys, math3d.DegToRad(45)) if path, ok := nav.FindPath(startPos, goalPos); ok { follow3DWaypoints(path) } ``` Use `nav.FindPolygon(p)` to locate the closest walkable polygon vertically within `VerticalTolerance` (supporting stacked floors and overpasses), `Contains(p)` and `NearestPolygon(p)` for membership and closest-surface queries, `FindCorridor(start, goal)` to query polygon corridors, `AddOffMeshLink(NavOffMeshLink{...})` / `OffMeshLinks()` / `ClearOffMeshLinks()` for jumps, ladders, and teleports, and `SetEdgeFlags(fromPoly, toPoly, flags)` for special portal edges. ### Off-mesh links (jumps, ladders, and teleports) Connect vertically separated ledges, disconnected islands, ladders, or teleporters across a 3D `NavMesh` with `AddOffMeshLink`: ```go nav.AddOffMeshLink(world3d.NavOffMeshLink{ Start: math3d.Vec3{X: 9, Y: 4, Z: 5}, End: math3d.Vec3{X: 13, Y: 0, Z: 5}, Radius: 0.5, // snaps off-edge endpoints within Radius while respecting stacked levels Bidirectional: false, Cost: 0, // <= 0 uses 3D Euclidean distance Area: world3d.NavAreaJump, Flags: uint32(world3d.NavFlagJump), ID: 7, UserData: "drop", }) res := nav.FindPathWithOptions(startPos, goalPos, ai.PathOptions{}) if res.Found { for i := 0; i+1 < len(res.Path); i++ { if link, ok := res.LinkAt(i); ok { // Segment Path[link.StartIndex] -> Path[link.EndIndex] traverses a 3D off-mesh link. _ = link.UserData } } } ``` - **Path segment metadata**: `NavPathResult.Links` records every traversed 3D off-mesh link (`StartIndex`, `EndIndex == StartIndex + 1`, `FromPoly`, `ToPoly`, `Start`, `End`, `Radius`, `Area`, `Flags`, `LinkID`, `UserData`), with `HasLinks()` and `LinkAt(segmentIndex)`. `NavAgent` delivers the same `Radius`, `Area`, and `UserData` in `NavLinkEvent` and triggers link entry within `Radius`. - **Shortcut-aware 3D search & filtering**: A\* filters off-mesh links by `NavFilter` (`Area` and `Flags`), scales traversal cost by `filter.AreaCost(link.Area)`, and uses a shortcut-aware admissible 3D heuristic so cheap teleporters are chosen only when strictly cheaper than walking. - **YAML storage and scene placement**: place `"nav_link"` components on scene objects (`sceneformat.RegisterNavLink`, `sceneformat.ExtractNavLinks3D`, `sceneformat.ExtractBuiltNavLinks3D`); `navbake3d.Geometry.AddSceneFile` bakes them into `meshes[].links` in `*.navmesh.yaml`, and `navbake3d.Mesh.NavMesh` restores them automatically. ### Polygon areas, runtime flags, and query filters Tag 3D polygons at build time with `BuildNavMeshWithAreas` using `NavPolygonInput{Vertices, Area, Flags}`. `world3d.NavArea`, `world3d.NavFlags`, and `world3d.NavFilter` alias the types in [ai](https://game.nsgo.dev/docs/ai/), so the same filter and area/flag constants work seamlessly across 2D and 3D navigation meshes: ```go nav := world3d.BuildNavMeshWithAreas([]world3d.NavPolygonInput{ {Vertices: grassQuad, Area: world3d.NavAreaGrass}, {Vertices: roadQuad, Area: world3d.NavAreaRoad}, {Vertices: waterQuad, Area: world3d.NavAreaWater, Flags: world3d.NavFlagSwim}, {Vertices: gateQuad, Area: world3d.NavAreaDoor, Flags: world3d.NavFlagWalk | world3d.NavFlagDoor}, }, math3d.DegToRad(45)) filter := world3d.DefaultNavFilter() filter.SetAreaCost(world3d.NavAreaRoad, 0.5) filter.ExcludeFlags |= world3d.NavFlagSwim path, ok := nav.FindPathWithFilter(startPos, goalPos, filter) // Toggle a gate or drawbridge polygon at runtime without rebuilding: nav.AddPolygonFlags(gatePolyIndex, world3d.NavFlagDisabled) detour, ok := nav.FindPathWithFilter(startPos, goalPos, filter) nav.ClearPolygonFlags(gatePolyIndex, world3d.NavFlagDisabled) _, _, _ = path, detour, ok ``` - **Default compatibility**: `BuildNavMesh` assigns `NavAreaDefault` and `NavFlagWalk` to every walkable `NavPoly`, and `FindPath` delegates to `FindPathWithFilter` with `DefaultNavFilter()`. - **Admissible 3D weighted portal A\***: traversal inside each polygon is weighted by `filter.AreaCost(poly.Area)` with an admissible 3D heuristic scaled by the minimum allowed area cost across the mesh, followed by exact 3D funnel smoothing across ramps and stacked levels. - **Runtime mutation & filtered queries**: inspect or update polygons in O(1) via `PolygonCount`, `PolygonArea`, `SetPolygonArea`, `PolygonFlags`, `SetPolygonFlags`, `AddPolygonFlags`, and `ClearPolygonFlags`, and run filtered lookups with `FindPolygonWithFilter`, `ContainsWithFilter`, `NearestPolygonWithFilter`, `NearestPointWithFilter`, `RaycastWithFilter`, `MoveAlongSurfaceWithFilter`, `RandomPointWithFilter`, and `RandomPointAroundWithFilter`. ### Spatial queries, surface movement, and zero-allocation path reuse `world3d.NavMesh` builds a flat 3D AABB BVH spatial index at construction time so `FindPolygon`, `NearestPolygon`, `NearestPoint`, and pathfinding endpoint lookups scale logarithmically on large multi-level worlds without scanning every polygon: ```go rng := random.New(42) // Snap a 3D click or spawn position within 3D half-extents (cleanly separating stacked floors): snapped, poly, ok := nav.NearestPoint(spawnPos, math3d.Vec3{X: 3, Y: 1.5, Z: 3}) // Cast a surface ray across ramps and bridges (stops at bridge edges instead of dropping levels): hit, obstructed := nav.Raycast(agentPos, targetPos) // Slide an agent along the 3D mesh surface while tracking ramp elevation and staying off ledges: moved, onMesh := nav.MoveAlongSurface(agentPos, desiredPos) // Pick deterministic 3D surface-area-weighted random points (anywhere or reachable within 3D radius): patrolPt, _, _ := nav.RandomPoint(rng) wanderPt, _, _ := nav.RandomPointAround(agentPos, 12, rng) // Reuse buffers via NavMeshQuery for zero-allocation path and corridor queries: query := world3d.NewNavMeshQuery(nav) pathBuf, ok = query.FindPathInto(pathBuf, snapped, wanderPt) corridorBuf, _ = query.FindCorridorInto(corridorBuf, snapped, wanderPt) _, _, _, _, _, _, _ = poly, hit, obstructed, moved, onMesh, patrolPt, ok ``` - **3D extent-bounded snapping**: `NearestPoint(p, extent)` and `NearestPointWithFilter(p, extent, filter)` restrict matches to `[p - extent, p + extent]` in full 3D (clipping sloped polygons to the extent box when needed), keeping stacked floors and overpasses cleanly separated by `extent.Y`. - **3D surface raycast and sliding**: `Raycast` / `RaycastWithFilter` traverse only shared 3D polygon edges, returning `NavRaycastHit{Point, Normal, Poly, T, Hit}` with exact `HeightAt` elevation and a 3D surface-tangent inward normal; `MoveAlongSurface` / `MoveAlongSurfaceWithFilter` slide along boundary edges across ramps and bridges without dropping between stacked levels (`NavMoveResult{Point, Poly, Visited, HitBoundary}`). - **Deterministic 3D surface-area random points**: `RandomPoint` / `RandomPointWithFilter` weight polygons by true 3D surface area (not just XZ projection); `RandomPointAround` / `RandomPointAroundWithFilter` sample only reachable polygons within 3D Euclidean `radius` of the snapped center (never jumping to unconnected floors overhead). Results are bit-identical across runs and architectures for the same `*random.Stream` seed. - **Zero-allocation path reuse & concurrent queries**: `nav.FindPathInto`, `nav.FindPathWithFilterInto`, `nav.FindPathWithFilterAndOptionsInto`, and `nav.FindCorridorInto` reuse generation-stamped scratch buffers with `0` heap allocations after warm-up; allocate one `NewNavMeshQuery(nav)` per worker goroutine for concurrent read-only queries over a shared `NavMesh`. For unreachable targets or frame-budgeted multi-agent queries, pass `ai.PathOptions{MaxExpansions, AllowPartial}` to `nav.FindPathWithOptions(startPos, goalPos, opts)` (returning a `NavPathResult` with `Partial`, `Exhausted`, and `Expansions`), or create a deterministic multi-frame `*world3d.NavMeshSearch` via `nav.StartSearch(startPos, goalPos, opts)`: ```go search := nav.StartSearch(startPos, goalPos, ai.PathOptions{ MaxExpansions: 128, AllowPartial: true, }) // Step directly, or schedule alongside 2D searches in an ai.PathQueue: queue.Submit(search, 0, func(_ ai.PathRequestID, _ ai.SearchStatus) { res := search.Result() if res.Found { follow3DWaypoints(res.Path) // res.Partial is true if goal was unreachable or budgeted out } }) ``` Stepping `NavMeshSearch` across any positive per-step budget returns the exact same 3D surface path as `FindPathWithOptions`, and partial paths end at the closest reachable 3D point on the explored polygons. To bake the polygons from the level's geometry instead of writing them by hand, use [navbake3d](https://game.nsgo.dev/docs/navbake3d/): it rasterizes glTF models, terrain, `GridMap`s and physics colliders for each agent type and `Mesh.NavMesh` returns the `NavMesh`. ### 3D navigation agents (`NavAgent`, `NavAgentGroup`) `world3d.NavAgent` follows and locally repairs 3D polygon corridors over a `world3d.NavMesh`, steering smoothly on XZ toward the next funnel corner while tracking exact 3D surface elevation (`NavPoly.HeightAt`) across sloped ramps and multi-level bridges, slowing inside `ArrivalRadius` to stop within `StoppingDistance`, and exposing explicit state (`NavAgentIdle`, `NavAgentMoving`, `NavAgentArrived`, `NavAgentUnreachable`): ```go group := world3d.NewNavAgentGroup(world3d.NavAgentGroupConfig{ MaxReplansPerStep: 4, ReplanInterval: 100 * time.Millisecond, }) agent := group.Add(nav, startPos, world3d.NavAgentConfig{ MaxSpeed: 6, MaxAcceleration: 30, Radius: 0.4, ArrivalRadius: 1.5, StoppingDistance: 0.35, OnLink: func(a *world3d.NavAgent, ev world3d.NavLinkEvent, dt time.Duration) bool { // Drive custom jump/ladder traversal and return true when done. return true }, }) agent.SetTarget(goalPos) // Inside game.Loop.Update: agent.SetTarget(movingTargetPos) group.Step(dt) ``` - **Local corridor repair & vertical separation**: `NavAgent` checks connected shared-edge neighbors first so agents on upper bridges never snap down to floors underneath, and repairs pushed start positions (`SetPosition`) or shifted targets locally within `MaxRepairDepth` (default 2) without a full A* replan. - **Throttled & staggered replanning**: `NavAgentGroup.Step(dt)` strictly bounds full A* replans to `MaxReplansPerStep` per fixed step in deterministic round-robin order (optionally staggered by `StaggerStride`), and automatically detects mesh changes (including runtime area/flag updates and off-mesh links) via `NavMesh.Revision()`. - **Deterministic fixed-step replay**: replaying the same inputs produces bit-identical 3D positions every step. ### Tiled 3D NavMesh, dynamic obstacles, and chunk streaming (`TiledNavMesh`, `NavTileStreamer`) For open worlds, doors, placed buildings, and destructible cover, `world3d.TiledNavMesh` partitions 3D walkable polygons into fixed-size XZ tiles aligned 1:1 with `ChunkCoord`, linking polygons in full 3D across tile borders (preserving ramps and stacked levels), rebuilding only touched tiles when dynamic obstacles change, and invalidating paths that crossed modified or unloaded tiles: ```go tm := world3d.NewTiledNavMesh(world3d.TiledNavMeshConfig{TileSize: 64}) // Follow world3d chunk streaming: bake tiles on background workers and load/unload with chunks: streamer, err := world3d.NewNavTileStreamer(world3d.NavTileStreamerConfig{ Mesh: tm, LoadRadius: 2, UnloadRadius: 3, Workers: 2, Bake: func(ctx context.Context, coord world3d.ChunkCoord, bounds math3d.AABB) (*world3d.NavTile, error) { return bakeChunkNavTile(ctx, coord, bounds) // e.g. world3d.BakeNavTile or navbake3d.BakeTile }, }) if err != nil { return err } defer streamer.Close() streamer.Update(world3d.WorldPos64{X: float64(player.X), Z: float64(player.Z)}) // Drop a 3D box, cylinder, or extruded polygon obstacle (rebuilds ONLY touched tiles): obsID, _ := tm.AddObstacle(world3d.NavBoxObstacle(minPos, maxPos)) detour, _ := tm.FindPath(startPos, goalPos) // detours around box; vertical Y bounds keep bridges above unaffected tm.RemoveObstacle(obsID) // restores original geometry and path _, _ = detour, obsID ``` - **Independent tile lifecycle**: bake standalone tiles off-thread with `world3d.BakeNavTile` (or voxel-bake directly from `navbake3d.Geometry` via `navbake3d.BakeTile`), then call `AddTile`, `ReplaceTile`, `SetTile`, `RemoveTile`, or `RebuildTile`; `BuildTiledNavMesh` / `BuildTiledNavMeshWithAreas` and `navbake3d.Mesh.TiledNavMesh(tileSize)` build a tiled mesh from existing polygons or baked meshes. - **3D dynamic obstacles**: `NavBoxObstacle`, `NavOrientedBoxObstacle`, `NavCylinderObstacle`, and `NavPolygonObstacle` check vertical Y overlap so obstacles on a ground floor never carve bridges overhead. Both `NavObstacleCarve` (exact planar subtraction) and `NavObstacleMark` (splitting and setting `NavFlagDisabled` or custom `Area`/`Flags`) are supported; group multi-obstacle edits inside `tm.Batch(func() { ... })`. - **Two-level 3D spatial index & path invalidation**: `FindPolygon`, `NearestPoint`, `NearestPolygon`, and `Raycast` use O(1) XZ tile lookup + per-tile 3D flat BVHs (plus a coarse 3D tile BVH for unbounded nearest lookups). Track path validity with `tm.IsPathValid(res)` (`TiledNavPathResult.Tiles`), register per-tile invalidation callbacks with `tm.WatchPath(res.TileCoords(), fn)`, or observe all tile changes via `tm.AddTileListener`. ## Modular 3D `GridMap` Place reusable 3D mesh tiles on an integer `GridCoord{X, Y, Z}` lattice with 24 axis-aligned cube orientations (`GridOrientationMat4`, `RotateGridOrientation`, `FindGridOrientation`), fast collision box extraction, chunk-culled raycasting (chunks are sorted along the ray and the occupied cells of each are tested), cell enumeration (`EachCell`), sorted library inspection (`MeshLibrary.Items`), and frustum-culled instanced batches. `LoadMeshLibraryFromGLTF` reads both `.gltf` JSON and binary `.glb` mesh libraries: ```go lib, err := world3d.LoadMeshLibraryFromGLTF(gltfBytes) // or world3d.NewMeshLibrary() if err != nil { return err } grid := world3d.NewGridMap(math3d.Vec3{X: 2, Y: 2, Z: 2}, lib) floorDef, _ := lib.ByName("stone_floor") grid.FillBox(world3d.GridCoord{X: 0, Y: 0, Z: 0}, world3d.GridCoord{X: 15, Y: 0, Z: 15}, floorDef.ID, 0) batches = grid.BuildInstances(&frustum, batches[:0]) colliders := grid.CollisionBoxesIn(playerAABB) hit, ok := grid.Raycast(ray, 100) _, _, _, _ = batches, colliders, hit, ok ``` To populate a [`physics3d.World`](https://game.nsgo.dev/docs/physics3d/) from a `GridMap`'s `ColliderBoxes`, call `grid.AddCollidersToWorld(world, opts)` (or `grid.BuildStaticBodies(opts)` / `grid.MergedColliderBoxes()`). Adjacent aligned cell boxes are greedily merged along X, then Z, then Y via `physics3d.MergeBoxes`, cutting static body counts and removing internal cell seams while producing identical collision outcomes (set `GridColliderOptions{DisableMerge: true}` to emit one body per cell box). Grid maps can also be authored and saved as version 1 YAML (`*.gridmap.yaml`, schema `https://game.nsgo.dev/schemas/gridmap.v1.json`) with `origin`, `cellSize`, `meshLibrary`, non-overlapping filled box runs (`boxes`), and individual cells (`cells`), all written in canonical `(y, z, x)` order: ```go grid, doc, err := world3d.LoadGridMapFS(projectFS, "levels/dungeon.gridmap.yaml") if err != nil { return err } exported, err := grid.ToDoc(doc.Name, doc.MeshLibrary) if err != nil { return err } yamlBytes, err := world3d.EncodeGridMap(exported) // deterministic, refuses unknown fields on ParseGridMap _, _ = exported, yamlBytes ``` `game check` validates every `*.gridmap.yaml` file (and every scene object `gridMap` reference), checks that its `meshLibrary` exists and loads (`.gltf` or `.glb`), and verifies that every `boxes[*].tile` and `cells[*].tile` name exists in that library. Scene objects can attach a `.gridmap.yaml` file via `gridMap` for automatic instancing in [scenemodel](https://game.nsgo.dev/docs/scenemodel/) and interactive painting in the [3D editor](https://game.nsgo.dev/docs/editor/#3d-gridmap-painting-899). ## Procedural foliage culling (`FoliageField`) Deterministically scatter grass, rocks, or trees across a `Heightmap` constrained by slope, height, and an optional `DensityMap`, then collect frustum- and distance-culled instances scaled by a `QualityProfile`: ```go field := world3d.Scatter(hm, world3d.FoliageLayer{ Name: "grass", MeshID: grassMeshID, MaterialID: grassMatID, Density: 1.5, MinScale: 0.8, MaxScale: 1.3, AlignToNormal: 0.6, MaxSlopeDeg: 35, BaseMaxDistance: 80, Seed: 42, }, hm.Bounds()) quality := world3d.DefaultQualityProfile(world3d.QualityHigh) visible = field.CollectVisible(camPos, frustum, quality, visible[:0]) ``` Foliage layers can also be authored in version 1 YAML (`*.foliage.yaml`, schema `https://game.nsgo.dev/schemas/foliage.v1.json`) specifying each layer's `mesh`, optional `material` and `densityMap`, either `density` (instances/m²) or `spacing` (average distance in meters, where `density = 1 / spacing²`), scale range (`minScale`, `maxScale`), `alignToNormal`, slope limits (`minSlopeDeg`, `maxSlopeDeg`), height limits (`minHeight`, `maxHeight`), `baseMaxDistance`, `boundingRadius`, and `seed`: ```go foliageDoc, err := world3d.LoadFoliageFS(projectFS, "terrain/meadow.foliage.yaml") if err != nil { return err } fields, err := foliageDoc.ScatterAll(hm, hm.Bounds(), world3d.FoliageBuildOptions{ ResolveMesh: resolveMeshID, ResolveMaterial: resolveMaterialID, FS: projectFS, }) ``` `ParseFoliage` refuses unknown fields and contradictory settings (such as setting both `density` and `spacing`), `EncodeFoliage` writes deterministic canonical YAML, and `game check` validates every `*.foliage.yaml` file and its referenced terrain, meshes, materials, and density map images. `world3d.QualityLevelFor(level)` maps a game-wide [quality](https://game.nsgo.dev/docs/quality/) level to the foliage tier of the same name, so `DefaultQualityProfile(QualityLevelFor(sel.Level()))` follows the player's preset. `QualityUltra` stays an explicit choice above every preset. Each returned `FoliageInstance` provides its world `Transform` and a smooth distance `Fade` factor in `[0, 1]`. Set `FoliageLayer.BoundingRadius` to the radius of a sphere around the mesh pivot that encloses the mesh at scale 1: culling and the draw distance then use each instance's scaled sphere and measure from its nearest point, so large trees stay visible while any part of them is in range. Without it, culling assumes a unit-radius mesh and distances are measured from the pivot. `Heightmap.Raycast` walks only the cells under the ray and never scans the whole height grid. ## Floating-origin chunk streaming Prevent `float32` jitter far from the world origin with `FloatingOrigin` (`WorldPos64` in `float64`) and load/unload surrounding world chunks asynchronously with `ChunkStreamer[T]`: ```go origin := world3d.NewFloatingOrigin(512) // rebase when player exceeds 512m from local origin streamer := world3d.NewChunkStreamer(world3d.ChunkStreamerConfig[*ChunkData]{ ChunkSize: 64, LoadRadius: 3, UnloadRadius: 5, MaxIntegrationsPerFrame: 2, Workers: 2, Loader: loadChunkAsync, OnLoad: attachChunk, OnUnload: releaseChunk, }) defer streamer.Close() // Each frame: if rebased, shift := origin.Update(playerLocalPos); rebased { rebaseSceneObjects(shift) // shift Mat4 transforms with world3d.RebaseMat4(m, shift) playerLocalPos = playerLocalPos.Add(shift) // the player moves with everything else } streamer.Update(origin.LocalToWorld(playerLocalPos)) ``` --- Source: https://game.nsgo.dev/docs/worldmap/ # worldmap `game/worldmap` remembers which rooms of a game world the player has discovered and draws them as a minimap of the current area and a world map, with markers. What the player has discovered goes into a save slot and comes back on load. ```go import "github.com/nsgo-dev/game/pkg/worldmap" ``` ## Map definitions A map is a YAML file with a `version` field. Each room has an ID, world-space bounds and, optionally, a display name, an area (a floor or region drawn as its own map) and links to neighbouring rooms. Fixed markers, such as save points or bosses, sit inside a room and appear once that room is discovered. ```yaml version: 1 rooms: - id: entrance name: Castle Gate x: 0 "y": 0 width: 320 height: 180 links: [hall, cellar] - id: hall x: 320 "y": 0 width: 320 height: 180 - id: cellar area: crypt x: 0 "y": 0 width: 320 height: 180 markers: - id: save-gate kind: save room: entrance x: 40 "y": 90 label: Gate shrine ``` `Parse` refuses unknown fields, other versions, duplicate IDs, links to missing rooms (or the same pair listed twice), sizes that are not positive (or that float32 rounding erases at the room's position), areas too large for float32 and rooms that overlap inside one area; rooms in different areas may overlap. `Encode` writes canonical YAML with a fixed key order: it parses back to the same `Doc` and encodes again to the same bytes. Comments, flow style and other formatting of a hand-written file are not kept, so a file saved with `Encode` loses them. The encoder quotes the key `"y"` because YAML 1.1 reads a bare `y` as a boolean; both forms parse. `Load(data)` parses a file and builds a `*Map`; `New(doc)` builds one from a `Doc` you made in code. ## Discovery ```go m, err := worldmap.Load(data) // Each fixed step, with the player's world position: if id, first := m.Visit(math2d.Vec2{X: px, Y: py}); first { toast("Discovered " + id) } m.Enter("hall") // a room transition moved the player into hall m.Reveal("tower") // a map item shows a room without visiting it m.RevealArea("crypt") // or a whole area ``` | Method | Result | | --- | --- | | `Visit(p)` | Marks the room under `p` visited and current; returns its ID and whether this is the first visit. Outside every room it keeps the current room. | | `Enter(id)` | Same by ID; `ErrUnknownRoom` for an unknown ID. | | `Reveal(ids...)`, `RevealArea(area)` | Unknown rooms become `Revealed`; visited rooms stay `Visited`. A bad ID changes nothing. | | `Status(id)` | `Unknown`, `Revealed` or `Visited`. | | `Visited()`, `Revealed()` | Sorted room IDs. | | `Explored(area)` | Visited and total rooms of an area, for a completion percentage. | | `RoomAt(p)` | The room containing `p`. Where areas overlap, the current room wins, then the current area, then definition order; with no current room, definition order alone decides. `Visit` picks its room the same way. | ## Markers Players can place their own markers. A marker needs an unused ID, a kind and a position inside an existing room (edges count): ```go err := m.AddMarker(worldmap.Marker{ID: "pin-1", Kind: "note", Room: "hall", X: 400, Y: 90, Label: "locked door"}) m.RemoveMarker("pin-1") ``` `Markers()` returns fixed and player markers sorted by ID, `VisibleMarkers()` only those whose room is revealed or visited, and `PlayerMarkers()` only the player's. Fixed markers cannot be removed. Invalid markers return `ErrInvalidMarker`. ## Saving `m.State()` returns a `State`: the version, the current room, the sorted visited and revealed room IDs and the player's markers. Equal states encode to equal JSON. Store it in a `save.Store` slot with the rest of the game and hand it back with `Restore`: ```go type Slot struct { Gold int `json:"gold"` Map worldmap.State `json:"map"` } store.Save("slot1", Slot{Gold: gold, Map: m.State()}) var s Slot if err := store.Load("slot1", &s); err == nil { err = m.Restore(s.Map) } ``` `Restore` checks the whole state first and returns `ErrInvalidState` without changing the map when the version differs, a room is unknown or listed twice, the current room was not visited or a marker is invalid. Decoding a `State` from JSON or YAML refuses unknown fields. A save that names a room the definition no longer has is refused, so when a game renames or removes rooms, add a `save.WithMigration` step that rewrites the saved IDs. `Reset` forgets everything discovered. ## Drawing Both views draw into a `core.Drawing`, clipped to a destination rectangle, and show only revealed and visited rooms of one area; unknown rooms and their markers are never drawn. ```go style := worldmap.DefaultStyle() core.Canvas{ Style: core.Style{Width: core.Pt(160), Height: core.Pt(160)}, Draw: func(d *core.Drawing, size core.Size) { // The current room's area around the player, 0.2 map points per world unit. m.DrawMinimap(d, core.Bounds{Size: size}, player, 0.2, &style) }, } // A pause-menu world map of one area, fitted to the canvas. m.DrawWorldMap(d, core.Bounds{Size: size}, "", &player, &style) ``` - `DrawMinimap` centers the player in the rectangle at a fixed scale and draws the current room's area. A scale that is not positive and finite counts as 1; a NaN or infinite player position draws nothing. - `DrawWorldMap` fits every room of the area, discovered or not, into the rectangle inset by `Style.Padding`, so the layout does not shift as the player explores. The player is drawn only when the current room is in that area and the position is finite. - `Style` sets the background, the fills of visited, revealed and current rooms, borders, links between discovered rooms, marker colors (`MarkerKinds` per kind) and sizes. A transparent color leaves that part out, except `Current`: a transparent `Current` fills the current room with `Visited`. `nil` uses `DefaultStyle()`. - `WorldMapProjection` and `MinimapProjection` return the `Projection` a view uses. `ToWorld` turns a tap on the map into a world point, for example to place a marker with `RoomAt` and `AddMarker`. Drawing the same map twice records the same operations, and a map restored from a save draws exactly as the one that was saved. ## Tile minimap `TileMinimap` renders a `tilemap.Tilemap`'s layers as a compact minimap image for RTS, strategy, roguelike and top-down RPG games, with optional `fog.Fog` compositing, unit and point-of-interest markers, the camera's visible rectangle, and click-to-pan. ```go mm := worldmap.NewTileMinimap(tm, nil) style := worldmap.DefaultTileMinimapStyle() // Inside a Canvas Draw callback: mm.Draw(d, core.Bounds{Size: size}, &worldmap.TileMinimapOverlay{ Fog: f, Team: playerTeam, Camera: cam, Markers: []worldmap.TileMarker{ {Position: heroPos, Kind: "ally"}, {Position: enemyPos, Kind: "enemy", RequireVisible: true}, {Position: shrinePos, Color: core.RGB(0xf2c14e)}, }, }, &style) // On pointer click at clickPos (in the same coordinates as dst): mm.PanCamera(cam, core.Bounds{Size: size}, clickPos, &style) ``` ### Tile colors and incremental updates Each cell is composited from bottom to top across every visible tile layer (respecting layer opacity, or the subset listed in `TileMinimapOptions.Layers`). A tile's color comes from: 1. `TileMinimapOptions.TileColor(tileID)` when provided and returning `ok = true`. 2. The tile's custom color property (`TileMinimapOptions.ColorProperty`, defaulting to `DefaultTileColorProperty`, `"minimap_color"`), parsed via `tilemap.Properties.Color`. 3. Otherwise, the alpha-weighted average color of the tile's non-transparent pixels from its tileset image (`Image.Pixels`, embedded `Image.Data`, or `TileMinimapOptions.Images` matched by URI, URI without `"asset:"`, or tileset name). Ignoring fully transparent pixels preserves opaque terrain colors for diamond isometric tile sprites. Edits made through `Tilemap.SetTile` (and small `Tilemap.FillRect` calls) are tracked by `Tilemap.TileRevision` / `Tilemap.TileChangesSince`, so `Sync` and `Draw` recompute only the changed cells rather than redrawing the whole map. Call `Invalidate` after mutating `layer.Data`, `layer.Visible`, `layer.Opacity` or tile properties directly. ### Fog, markers, camera and click-to-pan - **Fog of war**: when `TileMinimapOverlay.Fog` is non-nil, `TileMinimap` composites `TileMinimapStyle.Fog` (`fog.DefaultStyle()` when both colors are transparent) over `Unseen` and `Explored` cells and caches the result against `Fog.Revision(Team)`. Unchanged frames skip recompositing completely, and single-tile `SetTile` edits patch only the changed cells in the composited image when the fog revision has not changed. - **Markers**: each `TileMarker` draws a square at its world `Position` using `Color`, `TileMinimapStyle.MarkerKinds[Kind]`, or `TileMinimapStyle.Marker`. Set `RequireVisible: true` to hide enemy blips unless their map cell is currently `fog.Visible` to the drawn team. - **Camera rectangle**: when `TileMinimapOverlay.Camera` is non-nil, `Draw` outlines the camera's visible region (axis-aligned for unrotated cameras, rotated quad when `Camera.Rotation != 0`). - **Orthogonal and isometric maps**: orthogonal maps render 1 pixel per tile; `tilemap.OrientationIsometric` maps render as a solid `(W+H) x (W+H-1)` diamond aligned with `Tilemap.WorldBounds`, with transparent corners outside the diamond. - **Click-to-pan**: `Projection`, `WorldToMinimap`, and `MinimapToWorld` convert between world and minimap coordinates for both orthogonal and isometric maps. `PanCamera(cam, dst, click, style)` centers `cam` on the clicked world point when `click` lies inside `dst` and calls `cam.Clamp()`.