Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Agent Note: MCP game-view screenshots with aligned diagnostic overlays

Status: implemented

## Problem

Under `nsgo dev -automation` and `nsgo test`, `game/mcp` (introduced in [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md)) exposes structured scene, layer, entity and component state, but coding agents cannot visually verify rendered frames or check whether sprites align with their bounds and 2D physics collision shapes (#99). Capturing a native OS screenshot also misses games running headlessly and cannot inject sprite-bounds or physics-shape overlays aligned with the game's camera and viewport transforms.

## Decision

Add a `game_screenshot` tool in `packages/game/mcp/screenshot.go` (registered alongside existing tools via `Bridge.Tools()`) that captures the game view into a deterministic `*image.RGBA` and composites optional pixel-aligned diagnostic overlays (`bounds`, `collision_shapes`/`physics`, `grid`, `camera`, `labels`) using the exact same `screen.Viewport` and `tilemap.Camera` transforms as the rendered frame, returning PNG bytes inline as `png_base64` or writing them confined inside `Config.ScreenshotDir`.

## Architecture and contracts

- **Frame acquisition**: `Config` adds optional `CaptureFrame`, `DrawFrame`, `Physics`/`PhysicsFunc`, `RigidPhysics`/`RigidPhysicsFunc`, `ScreenshotDir`, and `ScreenshotBackground` fields. When `CaptureFrame` is configured, `game_screenshot` clones the returned `*image.RGBA` (never mutating the caller's buffer) before compositing overlays. Otherwise it records the frame into a `core.Drawing` via `DrawFrame` or the active `Scenes`/`Scene` wrapped in `Viewport.Draw` when set, and rasterizes the ops with a self-contained software rasterizer.
- **Self-contained software rasterizer (no `gametest` import)**: `game/mcp` rasterizes `core.DrawOp` (transforms, `Save`/`Restore`, rectangular `Clip`, rects, lines, arcs, fills, strokes, `DrawImage` with tint, and `DrawAtlas`) directly in `screenshot.go` instead of importing `packages/game/gametest`. Importing `gametest` from non-test game packages would transitively import `testing` and register the `-update-golden` CLI flag in game binaries, and `gametest.RenderOps` does not clip `screen.Viewport` bars or rasterize path lines/arcs.
- **Exact pixel-aligned overlay geometry**:
- The viewport comes from the same `Viewport` / `ViewportFunc` and view size (`ViewSizeFunc`, the attached window, the virtual size) that `game_input_pointer` maps through. `Viewport.Layout` runs on the view size in points and is scaled by the image's pixels per point, so a `CaptureFrame` image in device pixels (HiDPI) gets the scale the game used, not the one `Layout` would pick for the pixel size. Overlays are clipped out of letterbox/pillarbox bars.
- Camera transform folds `tilemap.Camera.Apply` ops into the same 2D affine matrix (`cameraAffine2D`), so shake, zoom, rotation, parallax (`cam.Parallax(px, py)` plus layer `OffsetX`/`OffsetY` and repeat ranges) and `SpaceScreen` HUD layers match `scene.Scene.Draw` identically.
- Axis-aligned rectangles (`sp.Bounds()`, `physics.Box`, solid tiles) compute exact inclusive pixel edges (`Ceil(min - 0.5)` to `Ceil(max - 0.5) - 1`) matching pixel-center `(px + 0.5, py + 0.5)` rasterization coverage so 1-pixel outlines sit cleanly on sprite/box borders without asymmetric 2-pixel bleed.
- Collision shape colors match `physics.DefaultDebugStyle()` with explicit hex fallbacks so overlays remain visible regardless of build tags (even when `physics`'s debug draw stubs out under `-tags release`).
- **Strict argument decoding and confined disk writes**: Both top-level flags (`bounds`, `collision_shapes`, `physics`, `grid`, `camera`, `labels`) and the nested `overlays` object refuse unknown fields (`DisallowUnknownFields()`), invalid dimensions, unsupported formats, and non-positive `grid_step`. When `path` is supplied, `Config.ScreenshotDir` must be configured, relative slash paths are validated against absolute/traversal segments, and writes go through `os.OpenRoot` so symlinks cannot escape `ScreenshotDir`.

## Alternatives considered

### Reusing `gametest.RenderOps` directly from `packages/game/mcp`

Reusing `gametest.RenderOps` would avoid duplicating basic affine image/rect rasterization code. It was rejected for two reasons: `packages/game/gametest` imports `testing` and defines a global `flag.Bool("update-golden", ...)`, which would pollute any game binary importing `game/mcp`, and `RenderOps` omits `DrawClip`, `DrawMoveTo`/`DrawLineTo`/`DrawArc`, and `DrawTintedImage` needed for `screen.Viewport` letterbox clipping and custom drawables.

### Calling `physics.DrawWorld` and `debug.ShapeOverlay` into a `core.Drawing` for overlays

Recording overlays through `physics.DrawWorld` and `debug.ShapeOverlay` would delegate shape geometry directly to existing debug packages. It was rejected because both `physics/debugdraw_release.go` and `debug/release.go` compile to no-ops under `-tags release`, `debug` carries heavy UI/profiler dependencies, and generic centered `StrokeRect` rasterization produces asymmetric 2px left/top vs 1px right/bottom borders on integer pixel grids; matching `physics.DefaultDebugStyle()` colors while computing exact inclusive border pixels keeps overlays crisp, aligned, and dependency-light.

### Stateful `game_overlays_config` tool mutating persistent bridge flags

Exposing a separate stateful toggle tool would let agents turn overlays on once and call `game_screenshot` without repeating flags. It was rejected in favor of stateless per-call arguments (supporting both flat booleans and an `overlays` object) so concurrent or multi-step agent inspections never suffer hidden cross-call overlay state leakage.

## Consequences

- **Benefits**: Coding agents can capture PNG screenshots of headless or windowed games with pixel-accurate sprite bounds, physics collision shapes, triggers, tiles, rigid bodies, grids, camera frames and labels aligned across camera pan/zoom/parallax and viewport scaling/letterboxing. Parallel MCP tool PRs remain isolated because `mcp.go` only receives additive `Config` fields and one append in `Bridge.Tools()`.
- **Costs**: `packages/game/mcp/screenshot.go` maintains a focused software rasterizer for common 2D `core.DrawOp` primitives. Text, ellipses, rounded rectangles, gradients, blend modes, dashes, shadows, meshes and images that are not in memory (URI, `asset:`, `Offscreen`) are not drawn; the result counts them in `skipped_ops` and `skipped_images` so an agent knows the image is partial, and `Config.CaptureFrame` supplies the real pixels. App tools' results reach an MCP client as JSON text (NSGo's `mcpResult` returns image content only for its built-in screenshot), so `png_base64` is text to the agent; `path` inside `ScreenshotDir` is the mode to prefer until NSGo lets app tools return images. The sprite-bounds overlay mirrors `scene`'s unexported parallax camera and repeat ranges; it covers `Item.Batch` sprites only.

## Verification

Verified with `go tool nsgo test ./mcp`, `go tool nsgo test -run TestStabilityTable .`, `go tool nsgo check -target macos,windows,linux,android,web`, `go run ./cmd/gameschema -check`, `go run ./tools/changelog check`, `gofmt`, and `bun run verify-notes`.
3 changes: 3 additions & 0 deletions changelog.d/mcp-screenshots-overlays-465.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/mcp`: `game_screenshot` tool captures the game view as PNG (written to a relative `.png` path inside `Config.ScreenshotDir`, or returned as `png_base64` text) with optional pixel-aligned overlays for sprite bounds (`bounds`), 2D physics collision shapes (`collision_shapes` / `physics`, covering `physics.World` boxes, circles, triggers, solid/one-way tiles and `physics.RigidWorld` bodies), world-space reference grid (`grid`, `grid_step`), camera frame (`camera`) and bitmap labels (`labels`), aligned across `tilemap.Camera` pan/zoom/parallax and the same `screen.Viewport`, `ViewportFunc` and view size `game_input_pointer` uses, including `CaptureFrame` images at a HiDPI pixel ratio. Frames the software rasterizer draws report what it left out in `skipped_ops` and `skipped_images` (#465).
20 changes: 19 additions & 1 deletion docs/en/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,19 @@ bridge, err := mcp.Attach(cx, mcp.Config{
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` or `*debug.Console` across level restarts, supply `SceneFunc` / `WorldFunc` / `LoopFunc` / `ConsoleFunc` (or call `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop` / `bridge.SetConsole`).
- 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`](editor.md) 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

Expand Down Expand Up @@ -130,6 +133,7 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r
| `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.

Expand Down Expand Up @@ -218,6 +222,20 @@ Wire `Config.Assets` (or `Config.AssetsFunc` / `bridge.SetAssets`), `Config.Reso
- **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 bodies in green `#22c55e`, circle bodies with `+X` orientation tick 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). 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:<index>:<generation>"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`:
Expand Down
Loading
Loading