diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-screenshots-and-overlays.md b/.agents/notes/implemented/feature/2026-11-24-mcp-screenshots-and-overlays.md new file mode 100644 index 00000000..d0d57bbd --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-screenshots-and-overlays.md @@ -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`. diff --git a/changelog.d/mcp-screenshots-overlays-465.md b/changelog.d/mcp-screenshots-overlays-465.md new file mode 100644 index 00000000..e74715bb --- /dev/null +++ b/changelog.d/mcp-screenshots-overlays-465.md @@ -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). diff --git a/docs/en/mcp.md b/docs/en/mcp.md index 581b9f40..b8e7eddb 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -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 @@ -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. @@ -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::"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`: diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 7f2143af..ca729860 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -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 } ``` -- 如果游戏在重开关卡时会替换 `*scene.Scene`、`*entities.World`、`*game.Loop` 或 `*debug.Console`,可以提供 `SceneFunc` / `WorldFunc` / `LoopFunc` / `ConsoleFunc`(或调用 `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop` / `bridge.SetConsole`)。 +- 如果游戏在重开关卡时会替换 `*scene.Scene`、`*entities.World`、`*game.Loop`、`*debug.Console` 或 `*physics.World`,可以提供 `SceneFunc` / `WorldFunc` / `LoopFunc` / `ConsoleFunc` / `PhysicsFunc`(或调用 `bridge.SetScene` / `bridge.SetWorld` / `bridge.SetLoop` / `bridge.SetConsole` / `bridge.SetPhysics`)。 - 若要启用 `game_loop_seed`,可配置 `Random`(`*random.Stream`)、`RandomStreams`(`*random.Streams`)和/或自定义 `SetSeed` 回调;若都未配置,调用 `game_loop_seed` 会返回明确的可操作错误。 - 如果 `scene.Manager` 的控制器通过自定义 `Controller.Draw` 绘制而没有设置 `Controller.Scene`,`SceneFunc` / `Scene` 会自动作为当前场景的图层来源。 - 未提供 `EntityName` 或 `EntityLayer`(或其返回 `""`)时,若实体带有 [`sceneformat.ObjectRef`](editor.md),`game/mcp` 会自动回退到其中的 `ID` 和 `Layer`。 +- 对于 `game_screenshot`,可以提供 `CaptureFrame`(将诊断叠加层合成到已渲染的 `*image.RGBA` 上)、`DrawFrame`(录制自定义的 `core.Drawing` 绘制指令),或直接由 `game/mcp` 在 `Viewport` / `ViewportFunc`(及可选的 `ScreenshotBackground`)下渲染当前活跃的 `Scenes`/`Scene`。设置 `ScreenshotDir` 后,智能体可以传入相对的 `.png` 路径 `path` 并读取该文件;否则响应会内联返回 `png_base64`,而 MCP 客户端收到的是 JSON 文本,不是图片。 ## 检查与编辑组件 @@ -130,6 +133,7 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_assets_list` | `group`(可选)、`state`(`loaded`/`loading`/`unloaded`/`failed`)、`kind`(可选) | 按确定顺序排列的资源组列表(涵盖 `assets.Manager`、`resource.Library`、`hotreload.ShaderReloader`、`hotreload.MaterialReloader` 与自定义注册资源),包含加载状态、资源键/类型/URI、图集帧数、各组估算内存字节数及 `total_bytes`。 | | `game_asset_reload` | `key`(资源名、URI 或相对路径)、`group`(可选)、`all`(布尔值,可选) | 就地重载匹配的单个资源(或在 `all: true` 时重载全部已加载资源),返回 `{reloaded, key, group, kind, bytes, duration_ms, revision, items, error}`;未报错但保持不变的条目会带有 `skipped`。解析或编译错误会以结构化结果返回,同时保留原先正常的资源不变。`all: true` 需要配置资源管理器、重载器或已注册资源;`Config.ReloadAsset` 只用于重载单个 key。 | | `game_assets_reload_group` | `group`(必填) | 就地重载指定资源组内的所有已加载资源,返回逐项结果、重载数 `count`、失败数 `failed`、跳过数 `skipped`、内存字节数、耗时及错误详情,不会导致运行中的游戏崩溃。 | +| `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}`) | 将游戏画面截取为 PNG(返回 `width`、`height`、`format`、`bytes`、`png_base64` 或相对路径 `path`、`overlays_drawn` 汇总,以及软件光栅化器有遗漏时的 `skipped_ops` / `skipped_images`),可选在同一相机与视口变换下叠加像素级对齐的精灵包围盒、2D 物理碰撞形状、参考网格、相机边框和标签。 | 所有工具都会拒绝未知的参数字段。 @@ -218,6 +222,20 @@ bridge, err := mcp.Attach(cx, mcp.Config{ - **跳过的资源**:音效不会就地替换;没有对应文件的图片(如程序生成的纹理)无从重载;屏幕不显示的密度对应的文件(如 2x 屏幕上的 1x 文件)即使替换也不会改变画面。这些条目会在 `skipped` 中给出原因(`assets.SkippedSound`、`assets.SkippedNoFile`、`assets.SkippedDensity`),既不计入重载成功,也不计入失败。按组重载时,组的读取器找不到文件的图片同样会被跳过;按 key 单独重载该图片则会返回读取错误。 - **不在引擎 goroutine 上读取**:`Manager.ReloadAsset` 与 `Manager.ReloadGroup` 与 `Group.Load` 一样,在其他 goroutine 上读取文件、解析图集并运行自定义加载器,完成后再在引擎 goroutine 上应用结果。工具调用会等待这些工作完成,因此自定义读取器或加载器不能等待引擎 goroutine;若调用的 context 先结束,则不会替换任何资源,工具返回该 context 的错误。 +## 截图与诊断叠加层 + +`game_screenshot` 会渲染或捕获当前游戏画面,并在与游戏完全一致的 `screen.Viewport` 裁剪/缩放/黑边以及 `tilemap.Camera`(含视差图层与 `SpaceScreen` HUD 图层)变换下合成所请求的叠加层: + +- **`bounds`**:为渲染场景中每个可见精灵绘制 1 像素青色(`#00e5ff`)包围盒边框。 +- **`collision_shapes` / `physics`**:绘制来自 `Config.Physics` 的 2D 碰撞形状(矩形刚体绿色 `#22c55e`、带 `+X` 朝向刻度的圆形天蓝色 `#38bdf8`、触发器粉色 `#f472b6`、实心瓦片琥珀色 `#f59e0b`、单向平台瓦片紫色 `#c084fc`)以及 `Config.RigidPhysics` 中的旋转刚体。配色与 `physics.DefaultDebugStyle()` 及 `mcp.DefaultOverlayStyle()` 一致。 +- **`grid`**:按 `grid_step` 或 `overlays.grid_step`(默认 `32` 点)绘制世界空间参考网格。 +- **`camera`**:绘制当前活跃相机的可见范围边框与中心十字线(`#facc15`)。 +- **`labels`**:为精灵帧名和带标签的物理体绘制紧凑点阵文字标签。 +- **`path`**:指定后通过 `os.Root` 将 PNG 写入 `Config.ScreenshotDir` 内的相对 `.png` 路径,绝对路径、`..` 和符号链接都无法离开该目录,并在响应中省略 `png_base64`。未指定时在 JSON 结果中返回 `png_base64`。MCP 客户端收到的这份结果是文本,因此需要智能体查看图片时,优先使用 `path`。 +- **尺寸与像素比**:未传 `width` 和 `height` 时,截图覆盖 `game_input_pointer` 所映射的视图:依次取 `ViewSizeFunc`、已挂载的窗口、视口的虚拟尺寸、场景相机的尺寸,单位为点,每点一个像素。`CaptureFrame` 的图像被视为以显示器像素比覆盖该视图(400x225 点视图的 800x450 帧即 2x),因此视口像游戏一样按点布局,叠加层再缩放到图像上;宽高比不同的图像按每点一个像素处理。推断出的尺寸与显式尺寸受同样的上限约束(每边 `8192` 像素,总计 `4096x4096` 像素)。 +- **`scene`**:用软件光栅化器单独渲染该场景,不使用 `CaptureFrame` 和 `DrawFrame`。若该场景的控制器通过自定义 `Controller.Draw` 绘制而没有 `scene.Scene`,则会拒绝。 +- **部分渲染**:软件光栅化器可以绘制矩形、直线、圆弧、二次与三次曲线、填充、描边、矩形裁剪,以及像素在内存中的图像和图集(`ImageSource.Pixels` 或 `Data`,设置了 `Size` 时按图像的点读取)。它会统计未绘制的内容:`skipped_ops` 按操作类型计数(文字、圆角矩形、椭圆、回退为首个颜色的渐变、混合模式、虚线、阴影、网格),`skipped_images` 计数来自 URI、`asset:` 文件或 `Offscreen` 画布的图像。这些内容重要时请提供 `CaptureFrame`。`overlays_drawn.sprite_bounds` 统计图层 `Item.Batch` 中的精灵;`Drawable` 条目或瓦片地图绘制的精灵不会画出包围框。 + ## 稳定的实体引用 每个存活实体都会获得一个格式为 `"entity::"`(例如 `"entity:0:1"`)的代数引用,由 `FormatEntityRef` 格式化并由 `ParseEntityRef` 解析: diff --git a/packages/game/mcp/doc.go b/packages/game/mcp/doc.go index 11913bdf..8dae1c66 100644 --- a/packages/game/mcp/doc.go +++ b/packages/game/mcp/doc.go @@ -39,6 +39,7 @@ // - game_assets_list: list loaded asset groups, asset keys/types, load states, and estimated memory usage in bytes. // - game_asset_reload: reload a named asset, URI, or path (or all loaded assets) in place and report structured reload diagnostics. // - game_assets_reload_group: reload every loaded asset in a named asset group in place. +// - game_screenshot: capture the game view as PNG, optionally with aligned sprite bounds, physics collision shapes, reference grid, camera frame and labels drawn on top. // // Components registered on an [entities.World] with [entities.RegisterCodec] are readable and editable automatically. Transient or non-saved components can also be exposed with [RegisterComponent], [RegisterComponentFunc], [RegisterMutableComponent] or [RegisterComponentEditor], and built-in [entities.Transform2D], [entities.WorldTransform2D] and [sceneformat.ObjectRef] components are surfaced automatically when present and not already registered under another name. Prefabs can be registered via [Config.Prefabs], [Bridge.RegisterPrefab], [Bridge.RegisterEntityPrefab] or [Bridge.RegisterScenePrefab]. // diff --git a/packages/game/mcp/example_test.go b/packages/game/mcp/example_test.go index 3b05b518..5787d9b8 100644 --- a/packages/game/mcp/example_test.go +++ b/packages/game/mcp/example_test.go @@ -72,4 +72,5 @@ func ExampleNew() { // game_assets_list // game_asset_reload // game_assets_reload_group + // game_screenshot } diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index 9421ce1a..a09600df 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "image" "io" "math" "reflect" @@ -19,6 +20,7 @@ import ( "github.com/nsgo-dev/game/packages/game/debug" "github.com/nsgo-dev/game/packages/game/entities" "github.com/nsgo-dev/game/packages/game/input" + "github.com/nsgo-dev/game/packages/game/physics" "github.com/nsgo-dev/game/packages/game/random" "github.com/nsgo-dev/game/packages/game/resource" "github.com/nsgo-dev/game/packages/game/scene" @@ -106,7 +108,7 @@ type Config struct { // ActionsFunc dynamically resolves the active input.Actions on each tool call. When non-nil and returning a non-nil *input.Actions, it overrides Actions. ActionsFunc func() *input.Actions - // Viewport maps virtual game coordinates to view coordinates for game_input_pointer. + // Viewport maps virtual game coordinates to view coordinates for game_input_pointer, and maps the game's virtual canvas onto the image when game_screenshot renders the game view and aligns overlays. Viewport *screen.Viewport // ViewportFunc dynamically resolves the active screen.Viewport on each tool call. When non-nil and returning a viewport with positive dimensions, it overrides Viewport. @@ -166,6 +168,30 @@ type Config struct { // ReloadAsset is an optional custom reload callback invoked by game_asset_reload when no configured asset manager, reloader or custom asset owns key. ReloadAsset func(ctx context.Context, key string) error + + // Physics is the game's 2D physics world used to draw collision shape overlays in game_screenshot. + Physics *physics.World + + // PhysicsFunc dynamically resolves the active 2D physics world on each screenshot call. When non-nil and returning a non-nil world, it overrides Physics. + PhysicsFunc func() *physics.World + + // RigidPhysics is an optional 2D rigid-body physics world whose bodies are drawn alongside Physics when collision shape overlays are enabled. + RigidPhysics *physics.RigidWorld + + // RigidPhysicsFunc dynamically resolves the active 2D rigid-body physics world on each screenshot call. When non-nil and returning a non-nil world, it overrides RigidPhysics. + RigidPhysicsFunc func() *physics.RigidWorld + + // DrawFrame optionally records the game's current frame into d for a target of width by height pixels. When nil, game_screenshot renders the active scene (from Scenes or Scene/SceneFunc) under Viewport if configured. + DrawFrame func(d *core.Drawing, width, height int) + + // CaptureFrame optionally returns an already-rendered game frame (for example from a GPU readback or offscreen canvas). Requested overlays are composited on top in the same camera and viewport coordinates. + CaptureFrame func(ctx context.Context) (*image.RGBA, error) + + // ScreenshotDir confines relative output paths written when game_screenshot is called with a path argument. When empty, writing to disk via path is refused. + ScreenshotDir string + + // ScreenshotBackground optionally fills the screenshot canvas before drawing the game frame when CaptureFrame is nil. Zero leaves the background transparent. + ScreenshotBackground core.Color } type compTypeKey any @@ -343,6 +369,7 @@ func (b *Bridge) Tools() []automation.Tool { out = append(out, b.replayTools()...) out = append(out, b.perfTools()...) out = append(out, b.assetTools()...) + out = append(out, b.screenshotTools()...) return out } diff --git a/packages/game/mcp/screenshot.go b/packages/game/mcp/screenshot.go new file mode 100644 index 00000000..8487f872 --- /dev/null +++ b/packages/game/mcp/screenshot.go @@ -0,0 +1,2182 @@ +package mcp + +import ( + "bytes" + "cmp" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "image" + "image/png" + "math" + "os" + "path" + "path/filepath" + "slices" + "strings" + + "github.com/nsgo-dev/game/packages/game/physics" + "github.com/nsgo-dev/game/packages/game/scene" + "github.com/nsgo-dev/game/packages/game/screen" + "github.com/nsgo-dev/game/packages/game/sprite" + "github.com/nsgo-dev/game/packages/game/tilemap" + "github.com/nsgo-dev/nsgo/automation" + "github.com/nsgo-dev/nsgo/core" +) + +// ToolScreenshot captures the game view as a PNG image, optionally with aligned sprite bounds, physics collision shapes, reference grid, camera frame and label overlays drawn on top. +const ToolScreenshot = "game_screenshot" + +const ( + maxScreenshotDim = 8192 + maxScreenshotPixels = 4096 * 4096 + defaultGridStep = 32 +) + +// OverlayStyle defines the colors drawn by game_screenshot diagnostic overlays. +type OverlayStyle struct { + BoundsColor core.Color + BoxColor core.Color + CircleColor core.Color + TriggerColor core.Color + SolidTileColor core.Color + OneWayTileColor core.Color + GridColor core.Color + CameraColor core.Color + LabelTextColor core.Color + LabelBgColor core.Color +} + +// DefaultOverlayStyle returns the default high-contrast colors for game_screenshot overlays. Collision shape colors match physics.DefaultDebugStyle. +func DefaultOverlayStyle() OverlayStyle { + pdef := physics.DefaultDebugStyle() + boxColor := pdef.BoxColor + if boxColor == 0 { + boxColor = core.RGB(0x22c55e) + } + circleColor := pdef.CircleColor + if circleColor == 0 { + circleColor = core.RGB(0x38bdf8) + } + solidTileColor := pdef.SolidTileColor + if solidTileColor == 0 { + solidTileColor = core.RGB(0xf59e0b) + } + oneWayTileColor := pdef.OneWayTileColor + if oneWayTileColor == 0 { + oneWayTileColor = core.RGB(0xc084fc) + } + return OverlayStyle{ + BoundsColor: core.RGB(0x00e5ff), + BoxColor: boxColor, + CircleColor: circleColor, + TriggerColor: core.RGB(0xf472b6), + SolidTileColor: solidTileColor, + OneWayTileColor: oneWayTileColor, + GridColor: core.RGBA(0xffffff, 0x40), + CameraColor: core.RGB(0xfacc15), + LabelTextColor: core.RGB(0xffffff), + LabelBgColor: core.RGBA(0x000000, 0xc0), + } +} + +// ScreenshotOverlays configures diagnostic overlays drawn on top of a game_screenshot capture. +type ScreenshotOverlays struct { + // Bounds draws crisp bounding rectangles aligned with every visible sprite in the scene. + Bounds bool `json:"bounds,omitempty"` + // CollisionShapes draws 2D physics collision shapes (boxes, circles, triggers, rigid bodies and collision tiles). + CollisionShapes bool `json:"collision_shapes,omitempty"` + // Physics is an alias for CollisionShapes; setting either enables collision-shape overlays. + Physics bool `json:"physics,omitempty"` + // Grid draws a reference grid in world space (or view space when no camera is active). + Grid bool `json:"grid,omitempty"` + // GridStep sets the spacing of the reference grid in world points when Grid is true (default 32). + GridStep float32 `json:"grid_step,omitempty"` + // Camera draws the active camera's visible frame and center crosshair. + Camera bool `json:"camera,omitempty"` + // Labels draws compact text labels next to drawn sprite bounds and physics bodies. + Labels bool `json:"labels,omitempty"` +} + +// OverlaysDrawn summarizes which overlays were rendered on a screenshot and how many primitives each drew. +type OverlaysDrawn struct { + Bounds bool `json:"bounds,omitempty"` + CollisionShapes bool `json:"collision_shapes,omitempty"` + Grid bool `json:"grid,omitempty"` + Camera bool `json:"camera,omitempty"` + Labels bool `json:"labels,omitempty"` + // SpriteBounds counts the sprites outlined: those in scene layers' Item.Batch. Sprites a Drawable item or a tilemap draws get no outline. + SpriteBounds int `json:"sprite_bounds,omitempty"` + PhysicsBoxes int `json:"physics_boxes,omitempty"` + PhysicsCircles int `json:"physics_circles,omitempty"` + PhysicsTriggers int `json:"physics_triggers,omitempty"` + PhysicsTiles int `json:"physics_tiles,omitempty"` +} + +// ScreenshotResult is the JSON result of game_screenshot. +type ScreenshotResult struct { + Width int `json:"width"` + Height int `json:"height"` + Format string `json:"format"` + Scene string `json:"scene,omitempty"` + Path string `json:"path,omitempty"` + Bytes int `json:"bytes"` + PNGBase64 string `json:"png_base64,omitempty"` + OverlaysDrawn OverlaysDrawn `json:"overlays_drawn"` + // SkippedOps counts, by draw operation kind (such as "DrawFillText" or "DrawEllipse"), what the software rasterizer did not draw when the frame was rendered rather than captured. A non-empty map means the image is partial. + SkippedOps map[string]int `json:"skipped_ops,omitempty"` + // SkippedImages counts image and atlas draws the software rasterizer left out because their source is not in memory (a URI, an "asset:" file or an Offscreen canvas) or could not be decoded. Use CaptureFrame to see them. + SkippedImages int `json:"skipped_images,omitempty"` +} + +// SetPhysics replaces the static 2D physics world configured on b. If Config.PhysicsFunc is set and returns a non-nil world, PhysicsFunc continues to take precedence. +func (b *Bridge) SetPhysics(w *physics.World) { + if b == nil { + return + } + b.cfg.Physics = w +} + +// SetRigidPhysics replaces the static 2D rigid-body physics world configured on b. If Config.RigidPhysicsFunc is set and returns a non-nil world, RigidPhysicsFunc continues to take precedence. +func (b *Bridge) SetRigidPhysics(w *physics.RigidWorld) { + if b == nil { + return + } + b.cfg.RigidPhysics = w +} + +func (b *Bridge) activePhysics() *physics.World { + if b == nil { + return nil + } + if b.cfg.PhysicsFunc != nil { + if w := b.cfg.PhysicsFunc(); w != nil { + return w + } + } + return b.cfg.Physics +} + +func (b *Bridge) activeRigidPhysics() *physics.RigidWorld { + if b == nil { + return nil + } + if b.cfg.RigidPhysicsFunc != nil { + if w := b.cfg.RigidPhysicsFunc(); w != nil { + return w + } + } + return b.cfg.RigidPhysics +} + +var schemaScreenshot = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "scene": { + "type": "string", + "description": "Optional scene name from game_scenes_list to render on its own with the software rasterizer (CaptureFrame and DrawFrame are not used); omit to capture the current game view." + }, + "width": { + "type": "integer", + "minimum": 1, + "maximum": 8192, + "description": "Output width in pixels (must be paired with height; omit to infer from CaptureFrame, Viewport or Camera)." + }, + "height": { + "type": "integer", + "minimum": 1, + "maximum": 8192, + "description": "Output height in pixels (must be paired with width; omit to infer from CaptureFrame, Viewport or Camera)." + }, + "format": { + "type": "string", + "enum": ["png"], + "description": "Image encoding format (default \"png\")." + }, + "path": { + "type": "string", + "description": "Relative .png file path inside Config.ScreenshotDir to write the PNG to instead of returning png_base64. Prefer it: png_base64 reaches an agent as text, not as an image." + }, + "bounds": { + "type": "boolean", + "description": "Draw sprite bounding rectangles aligned with visible sprites in the scene." + }, + "collision_shapes": { + "type": "boolean", + "description": "Draw 2D physics collision shapes (boxes, circles, triggers, rigid bodies and collision tiles) aligned with the scene camera and viewport." + }, + "physics": { + "type": "boolean", + "description": "Alias for collision_shapes." + }, + "grid": { + "type": "boolean", + "description": "Draw a world-space reference grid." + }, + "grid_step": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Spacing of the reference grid in world points (default 32)." + }, + "camera": { + "type": "boolean", + "description": "Draw the active camera's visible frame and center crosshair." + }, + "labels": { + "type": "boolean", + "description": "Draw compact text labels next to drawn sprite bounds and physics bodies." + }, + "overlays": { + "type": "object", + "additionalProperties": false, + "description": "Structured overlay flags merged with top-level overlay booleans.", + "properties": { + "bounds": { + "type": "boolean", + "description": "Draw sprite bounding rectangles aligned with visible sprites." + }, + "collision_shapes": { + "type": "boolean", + "description": "Draw 2D physics collision shapes." + }, + "physics": { + "type": "boolean", + "description": "Alias for collision_shapes." + }, + "grid": { + "type": "boolean", + "description": "Draw a world-space reference grid." + }, + "grid_step": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Spacing of the reference grid in world points (default 32)." + }, + "camera": { + "type": "boolean", + "description": "Draw the active camera's visible frame and center crosshair." + }, + "labels": { + "type": "boolean", + "description": "Draw compact text labels next to drawn overlays." + } + } + } + } +}`) + +func (b *Bridge) screenshotTools() []automation.Tool { + return []automation.Tool{ + { + Name: ToolScreenshot, + Description: "Capture the game view as a PNG image (returned as base64 or written inside ScreenshotDir), optionally with sprite bounds, physics collision shapes, grid, camera frame and labels aligned with sprites.", + InputSchema: schemaScreenshot, + Handler: b.handleScreenshot, + }, + } +} + +type screenshotArgs struct { + Scene string `json:"scene"` + Width int `json:"width"` + Height int `json:"height"` + Format string `json:"format"` + Path string `json:"path"` + Bounds bool `json:"bounds"` + CollisionShapes bool `json:"collision_shapes"` + Physics bool `json:"physics"` + Grid bool `json:"grid"` + GridStep float32 `json:"grid_step"` + Camera bool `json:"camera"` + Labels bool `json:"labels"` + Overlays *ScreenshotOverlays `json:"overlays"` +} + +func (b *Bridge) handleScreenshot(ctx context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[screenshotArgs](raw) + if err != nil { + return nil, err + } + + format := args.Format + if format == "" { + format = "png" + } + if format != "png" { + return nil, fmt.Errorf("mcp: unsupported screenshot format %q (supported: \"png\")", format) + } + + if args.Width < 0 || args.Height < 0 { + return nil, fmt.Errorf("mcp: screenshot dimensions must be positive (got %dx%d)", args.Width, args.Height) + } + if (args.Width == 0) != (args.Height == 0) { + return nil, fmt.Errorf("mcp: width and height must both be provided when overriding dimensions (got %dx%d)", args.Width, args.Height) + } + if err := checkScreenshotDims(args.Width, args.Height); err != nil { + return nil, err + } + + gridStep := float32(defaultGridStep) + gridStepSet := false + for _, gs := range []struct { + name string + v float32 + }{{"grid_step", args.GridStep}, {"overlays.grid_step", overlayGridStep(args.Overlays)}} { + if gs.v == 0 { + continue + } + f := float64(gs.v) + if math.IsNaN(f) || math.IsInf(f, 0) || f <= 0 { + return nil, fmt.Errorf("mcp: %s must be a positive finite number (got %v)", gs.name, gs.v) + } + if gridStepSet && gridStep != gs.v { + return nil, fmt.Errorf("mcp: grid_step %v and overlays.grid_step %v disagree", gridStep, gs.v) + } + gridStep, gridStepSet = gs.v, true + } + + var cleanRelPath string + if args.Path != "" { + if strings.TrimSpace(b.cfg.ScreenshotDir) == "" { + return nil, errors.New("mcp: screenshot path requested but Config.ScreenshotDir is not configured") + } + cleanRelPath, err = sanitizeScreenshotPath(args.Path) + if err != nil { + return nil, err + } + } + + wantBounds := args.Bounds || (args.Overlays != nil && args.Overlays.Bounds) + wantCollision := args.CollisionShapes || args.Physics || (args.Overlays != nil && (args.Overlays.CollisionShapes || args.Overlays.Physics)) + wantGrid := args.Grid || (args.Overlays != nil && args.Overlays.Grid) + wantCamera := args.Camera || (args.Overlays != nil && args.Overlays.Camera) + wantLabels := args.Labels || (args.Overlays != nil && args.Overlays.Labels) + + sceneName, drawnScenes, err := b.resolveScreenshotScenes(args.Scene) + if err != nil { + return nil, err + } + activeCam := screenshotCamera(drawnScenes) + + vp, hasVP := b.activeViewport() + var ( + img *image.RGBA + width = args.Width + height = args.Height + frame screenshotFrame + + skippedOps map[string]int + skippedImages int + ) + + if b.cfg.CaptureFrame != nil && args.Scene == "" { + captured, err := b.cfg.CaptureFrame(ctx) + if err != nil { + return nil, fmt.Errorf("mcp: capture frame: %w", err) + } + if captured == nil || captured.Bounds().Empty() { + return nil, errors.New("mcp: CaptureFrame returned an empty image") + } + imgW, imgH := captured.Bounds().Dx(), captured.Bounds().Dy() + if width > 0 && (width != imgW || height != imgH) { + return nil, fmt.Errorf("mcp: CaptureFrame returned %dx%d image, does not match requested %dx%d", imgW, imgH, width, height) + } + if err := checkScreenshotDims(imgW, imgH); err != nil { + return nil, fmt.Errorf("mcp: captured image: %w", err) + } + width, height = imgW, imgH + img = cloneRGBA(captured) + // The captured frame covers the view at the display's pixel ratio, so it may be in device pixels: lay the viewport out in the view's points, as the game does, and scale that layout to the image. A frame whose aspect ratio is not the view's is not of that view, and its pixels are taken as points. + view := b.activeViewSize(vp, hasVP) + if view.Width <= 0 || view.Height <= 0 || !sameAspect(view, imgW, imgH) { + view = core.Size{Width: core.Points(imgW), Height: core.Points(imgH)} + } + frame = newScreenshotFrame(view, width, height, vp, hasVP) + } else { + hasScene := len(drawnScenes) > 0 || (b.cfg.Scenes != nil && b.cfg.Scenes.Depth() > 0 && args.Scene == "") + hasPhysics := b.activePhysics() != nil || b.activeRigidPhysics() != nil + if b.cfg.DrawFrame == nil && !hasScene && !hasPhysics { + return nil, errors.New("mcp: no screenshot source configured (set CaptureFrame, DrawFrame, Scene/Scenes, or Physics)") + } + + var view core.Size + if width == 0 && height == 0 { + view, err = b.inferScreenshotView(vp, hasVP, activeCam) + if err != nil { + return nil, err + } + width, height = int(math.Round(float64(view.Width))), int(math.Round(float64(view.Height))) + if err := checkScreenshotDims(width, height); err != nil { + return nil, err + } + } + view = core.Size{Width: core.Points(width), Height: core.Points(height)} + frame = newScreenshotFrame(view, width, height, vp, hasVP) + + var d core.Drawing + switch { + case args.Scene != "": + drawScenesInto(&d, frame, drawnScenes) + case b.cfg.DrawFrame != nil: + b.cfg.DrawFrame(&d, width, height) + case b.cfg.Scenes != nil && b.cfg.Scenes.Depth() > 0: + b.drawManagerInto(&d, frame) + default: + drawScenesInto(&d, frame, drawnScenes) + } + var skipped rasterSkipped + img, skipped = rasterizeOps(width, height, d.Ops, b.cfg.ScreenshotBackground) + skippedOps, skippedImages = skipped.ops, skipped.images + } + + drawn := OverlaysDrawn{ + Bounds: wantBounds, + CollisionShapes: wantCollision, + Grid: wantGrid, + Camera: wantCamera, + Labels: wantLabels, + } + + if wantBounds || wantCollision || wantGrid || wantCamera || wantLabels { + b.compositeOverlays(img, frame, drawnScenes, activeCam, overlayRequest{ + bounds: wantBounds, + collisionShapes: wantCollision, + grid: wantGrid, + gridStep: gridStep, + camera: wantCamera, + labels: wantLabels, + }, &drawn) + } + + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + return nil, fmt.Errorf("mcp: encode screenshot png: %w", err) + } + pngBytes := buf.Bytes() + + res := ScreenshotResult{ + Width: width, + Height: height, + Format: format, + Scene: sceneName, + Bytes: len(pngBytes), + OverlaysDrawn: drawn, + SkippedOps: skippedOps, + SkippedImages: skippedImages, + } + + if cleanRelPath != "" { + if err := writeConfinedFile(b.cfg.ScreenshotDir, cleanRelPath, pngBytes); err != nil { + return nil, err + } + res.Path = cleanRelPath + } else { + res.PNGBase64 = base64.StdEncoding.EncodeToString(pngBytes) + } + return res, nil +} + +func overlayGridStep(o *ScreenshotOverlays) float32 { + if o == nil { + return 0 + } + return o.GridStep +} + +func (b *Bridge) resolveScreenshotScenes(requested string) (string, []*scene.Scene, error) { + _, resolved := b.collectScenes() + if requested != "" { + var target *resolvedScene + for i := len(resolved) - 1; i >= 0; i-- { + if resolved[i].info.Active && resolved[i].info.Name == requested { + target = &resolved[i] + break + } + } + if target == nil { + for i := range resolved { + if resolved[i].info.Name == requested { + target = &resolved[i] + break + } + } + } + if target == nil { + avail := make([]string, len(resolved)) + for i, r := range resolved { + avail[i] = r.info.Name + } + if len(avail) == 0 { + return "", nil, fmt.Errorf("mcp: scene %q not found (no scenes configured)", requested) + } + return "", nil, fmt.Errorf("mcp: scene %q not found (available: %s)", requested, strings.Join(avail, ", ")) + } + if target.scene == nil { + return "", nil, fmt.Errorf("mcp: scene %q has no scene.Scene to render (its controller draws through a custom Controller.Draw); omit scene to capture the current view", target.info.Name) + } + return target.info.Name, []*scene.Scene{target.scene}, nil + } + + if b.cfg.Scenes != nil && b.cfg.Scenes.Depth() > 0 { + var active []resolvedScene + for _, r := range resolved { + if r.info.Active { + active = append(active, r) + } + } + if len(active) == 0 { + return "", nil, nil + } + start := len(active) - 1 + for start > 0 && active[start].info.Transparent { + start-- + } + var out []*scene.Scene + for i := start; i < len(active); i++ { + if active[i].scene != nil { + out = append(out, active[i].scene) + } + } + return active[len(active)-1].info.Name, out, nil + } + + if sc := b.standaloneScene(); sc != nil { + return b.nameForStandaloneScene(sc), []*scene.Scene{sc}, nil + } + return "", nil, nil +} + +func screenshotCamera(scenes []*scene.Scene) *tilemap.Camera { + for i := len(scenes) - 1; i >= 0; i-- { + if scenes[i] != nil && scenes[i].Camera != nil { + return scenes[i].Camera + } + } + return nil +} + +func checkScreenshotDims(w, h int) error { + if w > maxScreenshotDim || h > maxScreenshotDim || int64(w)*int64(h) > maxScreenshotPixels { + return fmt.Errorf("mcp: screenshot dimensions %dx%d exceed maximum (%dx%d, %d pixels)", w, h, maxScreenshotDim, maxScreenshotDim, maxScreenshotPixels) + } + return nil +} + +// sameAspect reports whether an image of w by h pixels has view's aspect ratio, to within the one pixel rounding a device pixel ratio can introduce. +func sameAspect(view core.Size, w, h int) bool { + sx := float64(w) / float64(view.Width) + sy := float64(h) / float64(view.Height) + return math.Abs(sx-sy)*float64(view.Width) <= 1 && math.Abs(sx-sy)*float64(view.Height) <= 1 +} + +// screenshotFrame relates a screenshot's pixels to the game's view: view is the window size in points the game lays its viewport out in, and sx, sy are the image's pixels per view point. +type screenshotFrame struct { + view core.Size + sx, sy float64 + vp screen.Viewport + hasVP bool +} + +func newScreenshotFrame(view core.Size, width, height int, vp screen.Viewport, hasVP bool) screenshotFrame { + return screenshotFrame{ + view: view, + sx: float64(width) / float64(view.Width), + sy: float64(height) / float64(view.Height), + vp: vp, + hasVP: hasVP, + } +} + +// inferScreenshotView returns the view size in points a screenshot covers when the caller gives no width and height: the size game_input_pointer maps through (ViewSizeFunc, the attached window, then the viewport's virtual size), else the scene camera's size. +func (b *Bridge) inferScreenshotView(vp screen.Viewport, hasVP bool, cam *tilemap.Camera) (core.Size, error) { + view := b.activeViewSize(vp, hasVP) + if view.Width <= 0 || view.Height <= 0 { + if cam != nil { + view = core.Size{Width: core.Points(cam.Width), Height: core.Points(cam.Height)} + } + } + w, h := float64(view.Width), float64(view.Height) + if math.IsNaN(w) || math.IsNaN(h) || math.IsInf(w, 0) || math.IsInf(h, 0) { + return core.Size{}, fmt.Errorf("mcp: cannot determine screenshot dimensions: view size %vx%v is not finite", w, h) + } + if math.Round(w) < 1 || math.Round(h) < 1 { + return core.Size{}, errors.New("mcp: cannot determine screenshot dimensions (pass width and height, or configure Viewport/ViewportFunc, ViewSizeFunc, a scene Camera with Width/Height, or CaptureFrame)") + } + if w > maxScreenshotDim || h > maxScreenshotDim || w*h > maxScreenshotPixels { + return core.Size{}, fmt.Errorf("mcp: inferred screenshot dimensions %vx%v exceed maximum (%dx%d, %d pixels); pass width and height", w, h, maxScreenshotDim, maxScreenshotDim, maxScreenshotPixels) + } + return view, nil +} + +func (b *Bridge) drawManagerInto(d *core.Drawing, frame screenshotFrame) { + draw := func(dst *core.Drawing, size core.Size) { + cur := b.cfg.Scenes.Current() + if cur != nil && cur.Draw == nil && cur.Scene == nil { + if sc := b.standaloneScene(); sc != nil { + sc.Draw(dst) + return + } + } + b.cfg.Scenes.Draw(dst, size, 0) + } + if frame.hasVP { + frame.vp.Draw(d, frame.view, draw) + return + } + draw(d, frame.view) +} + +func drawScenesInto(d *core.Drawing, frame screenshotFrame, scenes []*scene.Scene) { + if len(scenes) == 0 { + return + } + draw := func(dst *core.Drawing, _ core.Size) { + for _, sc := range scenes { + if sc != nil { + sc.Draw(dst) + } + } + } + if frame.hasVP { + frame.vp.Draw(d, frame.view, draw) + return + } + draw(d, frame.view) +} + +func sanitizeScreenshotPath(p string) (string, error) { + if p == "" { + return "", errors.New("mcp: empty screenshot path") + } + if strings.ContainsRune(p, 0) { + return "", fmt.Errorf("mcp: invalid screenshot path %q: contains NUL byte", p) + } + if strings.ContainsAny(p, "\\:") { + return "", fmt.Errorf("mcp: invalid screenshot path %q: must be a relative slash-separated path", p) + } + if !strings.EqualFold(path.Ext(p), ".png") { + return "", fmt.Errorf("mcp: invalid screenshot path %q: must end in .png", p) + } + if strings.HasPrefix(p, "/") || filepath.IsAbs(p) { + return "", fmt.Errorf("mcp: invalid screenshot path %q: absolute paths are not allowed", p) + } + for _, seg := range strings.Split(p, "/") { + if seg == ".." { + return "", fmt.Errorf("mcp: invalid screenshot path %q: parent traversal is not allowed", p) + } + } + cleaned := path.Clean(p) + if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, "/") { + return "", fmt.Errorf("mcp: invalid screenshot path %q: path escapes ScreenshotDir", p) + } + return cleaned, nil +} + +func writeConfinedFile(dir, relSlash string, data []byte) error { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("mcp: create ScreenshotDir: %w", err) + } + root, err := os.OpenRoot(dir) + if err != nil { + return fmt.Errorf("mcp: open ScreenshotDir: %w", err) + } + defer root.Close() + + relOS := filepath.FromSlash(relSlash) + if parent := path.Dir(relSlash); parent != "." && parent != "" { + var cur string + for _, seg := range strings.Split(parent, "/") { + if cur == "" { + cur = seg + } else { + cur = filepath.Join(cur, seg) + } + if err := root.Mkdir(cur, 0o755); err != nil && !errors.Is(err, os.ErrExist) { + return fmt.Errorf("mcp: create screenshot directory %q: %w", cur, err) + } + } + } + f, err := root.OpenFile(relOS, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) + if err != nil { + return fmt.Errorf("mcp: write screenshot %q: %w", relSlash, err) + } + if _, err := f.Write(data); err != nil { + _ = f.Close() + return fmt.Errorf("mcp: write screenshot %q: %w", relSlash, err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("mcp: close screenshot %q: %w", relSlash, err) + } + return nil +} + +func cloneRGBA(src *image.RGBA) *image.RGBA { + sb := src.Bounds() + w, h := sb.Dx(), sb.Dy() + dst := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := range h { + sOff := src.PixOffset(sb.Min.X, sb.Min.Y+y) + dOff := dst.PixOffset(0, y) + copy(dst.Pix[dOff:dOff+w*4], src.Pix[sOff:sOff+w*4]) + } + return dst +} + +// --- Overlay compositing --- + +type overlayRequest struct { + bounds bool + collisionShapes bool + grid bool + gridStep float32 + camera bool + labels bool +} + +type overlayLabel struct { + x, y int + text string +} + +// viewportTransform maps the game's virtual canvas points to the screenshot's pixels and returns the pixel rectangle the canvas covers. +func viewportTransform(frame screenshotFrame, width, height int) (affine2D, image.Rectangle) { + full := image.Rect(0, 0, width, height) + pixels := affine2D{a: frame.sx, d: frame.sy} + if !frame.hasVP { + return pixels, full + } + pl := frame.vp.Layout(frame.view) + if pl.ScaleX <= 0 || pl.ScaleY <= 0 { + return identityAffine2D(), image.Rectangle{} + } + m := pixels.mul(affine2D{ + a: float64(pl.ScaleX), + d: float64(pl.ScaleY), + e: float64(pl.Rect.Origin.X), + f: float64(pl.Rect.Origin.Y), + }) + clip := full + if len(pl.Bars) > 0 { + r := image.Rect( + int(math.Ceil(float64(pl.Rect.Origin.X)*frame.sx-0.5)), + int(math.Ceil(float64(pl.Rect.Origin.Y)*frame.sy-0.5)), + int(math.Ceil(float64(pl.Rect.Origin.X+pl.Rect.Size.Width)*frame.sx-0.5)), + int(math.Ceil(float64(pl.Rect.Origin.Y+pl.Rect.Size.Height)*frame.sy-0.5)), + ) + clip = full.Intersect(r) + } + return m, clip +} + +func cameraAffine2D(cam *tilemap.Camera) affine2D { + if cam == nil { + return identityAffine2D() + } + var d core.Drawing + cam.Apply(&d) + m := identityAffine2D() + for _, op := range d.Ops { + m = applyTransformOp(m, op) + } + return m +} + +func (b *Bridge) compositeOverlays(img *image.RGBA, frame screenshotFrame, scenes []*scene.Scene, activeCam *tilemap.Camera, req overlayRequest, drawn *OverlaysDrawn) { + w, h := img.Bounds().Dx(), img.Bounds().Dy() + vpM, vpClip := viewportTransform(frame, w, h) + if vpClip.Empty() { + return + } + style := DefaultOverlayStyle() + worldM := vpM.mul(cameraAffine2D(activeCam)) + + var labels []overlayLabel + + if req.grid { + drawGridOverlay(img, vpClip, worldM, float64(req.gridStep), style.GridColor) + } + + if req.camera && activeCam != nil { + drawCameraOverlay(img, vpClip, worldM, activeCam, style.CameraColor) + } + + if req.bounds { + drawSceneBoundsOverlays(img, vpClip, vpM, scenes, style.BoundsColor, req.labels, &labels, drawn) + } + + if req.collisionShapes { + b.drawPhysicsOverlays(img, vpClip, worldM, activeCam, style, req.labels, &labels, drawn) + } + + if req.labels && len(labels) > 0 { + for _, lbl := range labels { + drawTinyLabel(img, vpClip, lbl.x, lbl.y, lbl.text, style.LabelTextColor, style.LabelBgColor) + } + } +} + +func drawGridOverlay(dst *image.RGBA, clip image.Rectangle, worldM affine2D, step float64, col core.Color) { + if step <= 0 { + step = defaultGridStep + } + inv, ok := worldM.invert() + if !ok { + return + } + // Map the four clip corners back to world space to find the visible world range. + x0, y0 := inv.apply(float64(clip.Min.X), float64(clip.Min.Y)) + x1, y1 := inv.apply(float64(clip.Max.X), float64(clip.Min.Y)) + x2, y2 := inv.apply(float64(clip.Max.X), float64(clip.Max.Y)) + x3, y3 := inv.apply(float64(clip.Min.X), float64(clip.Max.Y)) + + minX := min(min(x0, x1), min(x2, x3)) + maxX := max(max(x0, x1), max(x2, x3)) + minY := min(min(y0, y1), min(y2, y3)) + maxY := max(max(y0, y1), max(y2, y3)) + + // Double spacing if zoomed far out so grid drawing stays bounded. + for (maxX-minX)/step > 256 || (maxY-minY)/step > 256 { + step *= 2 + } + + sr, sg, sb, sa := premulFromColor(col, 1) + if sa <= 0 { + return + } + + startX := math.Floor(minX/step) * step + for gx := startX; gx <= maxX; gx += step { + ax, ay := worldM.apply(gx, minY) + bx, by := worldM.apply(gx, maxY) + drawLineBresenham(dst, clip, int(math.Floor(ax)), int(math.Floor(ay)), int(math.Floor(bx)), int(math.Floor(by)), sr, sg, sb, sa) + } + startY := math.Floor(minY/step) * step + for gy := startY; gy <= maxY; gy += step { + ax, ay := worldM.apply(minX, gy) + bx, by := worldM.apply(maxX, gy) + drawLineBresenham(dst, clip, int(math.Floor(ax)), int(math.Floor(ay)), int(math.Floor(bx)), int(math.Floor(by)), sr, sg, sb, sa) + } +} + +func drawCameraOverlay(dst *image.RGBA, clip image.Rectangle, worldM affine2D, cam *tilemap.Camera, col core.Color) { + vb := cam.VisibleBounds() + drawCrispRectOutline(dst, clip, worldM, float64(vb.Origin.X), float64(vb.Origin.Y), float64(vb.Size.Width), float64(vb.Size.Height), col) + shake := cam.ShakeOffset() + cx, cy := worldM.apply(float64(cam.X)+float64(shake.X), float64(cam.Y)+float64(shake.Y)) + px, py := int(math.Floor(cx)), int(math.Floor(cy)) + sr, sg, sb, sa := premulFromColor(col, 1) + drawLineBresenham(dst, clip, px-4, py, px+4, py, sr, sg, sb, sa) + drawLineBresenham(dst, clip, px, py-4, px, py+4, sr, sg, sb, sa) +} + +func drawSceneBoundsOverlays(dst *image.RGBA, clip image.Rectangle, vpM affine2D, scenes []*scene.Scene, col core.Color, wantLabels bool, labels *[]overlayLabel, drawn *OverlaysDrawn) { + for _, sc := range scenes { + if sc == nil || len(sc.Layers) == 0 { + continue + } + layers := make([]*scene.Layer, 0, len(sc.Layers)) + for _, l := range sc.Layers { + if l != nil && l.Visible { + layers = append(layers, l) + } + } + slices.SortStableFunc(layers, func(a, b *scene.Layer) int { + return cmp.Compare(a.Order, b.Order) + }) + + for _, l := range layers { + drawLayerSpriteBounds(dst, clip, vpM, sc.Camera, l, col, wantLabels, labels, drawn) + } + } +} + +func drawLayerSpriteBounds(dst *image.RGBA, clip image.Rectangle, vpM affine2D, cam *tilemap.Camera, l *scene.Layer, col core.Color, wantLabels bool, labels *[]overlayLabel, drawn *OverlaysDrawn) { + if len(l.Items) == 0 { + return + } + drawItemsWith := func(layerM affine2D) { + for _, it := range l.Items { + if it.Batch == nil || it.Batch.Atlas == nil { + continue + } + for _, sp := range it.Batch.Sprites { + if !spriteVisible(sp) { + continue + } + r := sp.Bounds() + if r.W <= 0 || r.H <= 0 { + continue + } + x0, y0, ok := drawCrispRectOutline(dst, clip, layerM, float64(r.X), float64(r.Y), float64(r.W), float64(r.H), col) + drawn.SpriteBounds++ + if wantLabels && ok { + text := sp.Frame.Name + if text == "" { + text = l.Name + } + if text == "" { + text = "SPR" + } + *labels = append(*labels, overlayLabel{x: x0, y: y0, text: text}) + } + } + } + } + + if l.Space == scene.SpaceWorld && cam != nil { + px, py := l.Parallax() + pcam := cam.Parallax(px, py) + pcam.X -= l.OffsetX + pcam.Y -= l.OffsetY + baseM := vpM.mul(cameraAffine2D(&pcam)) + minCol, maxCol, minRow, maxRow, rx, ry := layerRepeatRanges(l, pcam.VisibleBounds()) + if !rx && !ry { + drawItemsWith(baseM) + return + } + for row := minRow; row <= maxRow; row++ { + var ty float64 + if ry { + ty = float64(row) * float64(l.RepeatHeight) + } + for colIdx := minCol; colIdx <= maxCol; colIdx++ { + var tx float64 + if rx { + tx = float64(colIdx) * float64(l.RepeatWidth) + } + drawItemsWith(baseM.mul(affine2D{a: 1, d: 1, e: tx, f: ty})) + } + } + return + } + + layerM := vpM + if l.OffsetX != 0 || l.OffsetY != 0 { + layerM = layerM.mul(affine2D{a: 1, d: 1, e: float64(l.OffsetX), f: float64(l.OffsetY)}) + } + drawItemsWith(layerM) +} + +func spriteVisible(sp *sprite.Sprite) bool { + if sp == nil { + return false + } + f := sp.Frame + if f.W <= 0 || f.H <= 0 || sp.Alpha <= 0 || sp.ScaleX == 0 || sp.ScaleY == 0 { + return false + } + if sp.Tint != 0 && sp.Tint != core.RGB(0xffffff) && sp.Tint&0xff == 0 { + return false + } + for _, v := range [...]float32{sp.X, sp.Y, sp.OriginX, sp.OriginY, sp.Rotation, sp.ScaleX, sp.ScaleY, sp.Alpha} { + if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) { + return false + } + } + return true +} + +func layerRepeatRanges(l *scene.Layer, vb core.Bounds) (minCol, maxCol, minRow, maxRow int, repeatX, repeatY bool) { + if l.RepeatX && l.RepeatWidth > 0 && vb.Size.Width > 0 { + w := float64(l.RepeatWidth) + minX := float64(vb.Origin.X) + maxX := minX + float64(vb.Size.Width) + minCol = int(math.Floor(minX / w)) + maxCol = int(math.Ceil(maxX/w)) - 1 + if maxCol < minCol { + maxCol = minCol + } + repeatX = true + } + if l.RepeatY && l.RepeatHeight > 0 && vb.Size.Height > 0 { + h := float64(l.RepeatHeight) + minY := float64(vb.Origin.Y) + maxY := minY + float64(vb.Size.Height) + minRow = int(math.Floor(minY / h)) + maxRow = int(math.Ceil(maxY/h)) - 1 + if maxRow < minRow { + maxRow = minRow + } + repeatY = true + } + return minCol, maxCol, minRow, maxRow, repeatX, repeatY +} + +func (b *Bridge) drawPhysicsOverlays(dst *image.RGBA, clip image.Rectangle, worldM affine2D, cam *tilemap.Camera, style OverlayStyle, wantLabels bool, labels *[]overlayLabel, drawn *OverlaysDrawn) { + if pw := b.activePhysics(); pw != nil { + if pw.Tiles != nil { + vis := visibleWorldBounds(clip, worldM, cam) + drawPhysicsTilesOverlay(dst, clip, worldM, pw.Tiles, vis, style, drawn) + } + for _, body := range pw.Bodies { + if body == nil || body.Shape.Empty() { + continue + } + x0, y0, ok := drawPhysicsShapeOverlay(dst, clip, worldM, body.Shape, style.BoxColor, style.CircleColor, drawn, false) + if wantLabels && ok && body.Tag != "" { + *labels = append(*labels, overlayLabel{x: x0, y: y0, text: body.Tag}) + } + } + for _, tr := range pw.Triggers { + if tr == nil || tr.Shape.Empty() { + continue + } + x0, y0, ok := drawPhysicsShapeOverlay(dst, clip, worldM, tr.Shape, style.TriggerColor, style.TriggerColor, drawn, true) + if wantLabels && ok && tr.Tag != "" { + *labels = append(*labels, overlayLabel{x: x0, y: y0, text: tr.Tag}) + } + } + } + + if rw := b.activeRigidPhysics(); rw != nil { + for _, rb := range rw.Bodies { + if rb == nil || rb.Shape.Empty() { + continue + } + bodyM := worldM + if rb.Angle != 0 { + bodyM = worldM.mul(rotateAroundAffine2D(float64(rb.X), float64(rb.Y), float64(rb.Angle))) + } + x0, y0, ok := drawPhysicsShapeOverlay(dst, clip, bodyM, rb.Shape, style.BoxColor, style.CircleColor, drawn, false) + if wantLabels && ok && rb.Tag != "" { + *labels = append(*labels, overlayLabel{x: x0, y: y0, text: rb.Tag}) + } + } + } +} + +func visibleWorldBounds(clip image.Rectangle, worldM affine2D, cam *tilemap.Camera) core.Bounds { + if cam != nil { + return cam.VisibleBounds() + } + inv, ok := worldM.invert() + if !ok { + return core.Bounds{} + } + x0, y0 := inv.apply(float64(clip.Min.X), float64(clip.Min.Y)) + x1, y1 := inv.apply(float64(clip.Max.X), float64(clip.Min.Y)) + x2, y2 := inv.apply(float64(clip.Max.X), float64(clip.Max.Y)) + x3, y3 := inv.apply(float64(clip.Min.X), float64(clip.Max.Y)) + minX := min(min(x0, x1), min(x2, x3)) + maxX := max(max(x0, x1), max(x2, x3)) + minY := min(min(y0, y1), min(y2, y3)) + maxY := max(max(y0, y1), max(y2, y3)) + return core.Bounds{ + Origin: core.Point{X: core.Points(minX), Y: core.Points(minY)}, + Size: core.Size{Width: core.Points(maxX - minX), Height: core.Points(maxY - minY)}, + } +} + +func drawPhysicsTilesOverlay(dst *image.RGBA, clip image.Rectangle, worldM affine2D, grid physics.TileGrid, visible core.Bounds, style OverlayStyle, drawn *OverlaysDrawn) { + if grid == nil || visible.Size.Width <= 0 || visible.Size.Height <= 0 { + return + } + tileW, tileH := grid.TileSize() + cols, rows := grid.GridSize() + if tileW <= 0 || tileH <= 0 || cols <= 0 || rows <= 0 { + return + } + tw, th := float64(tileW), float64(tileH) + visMinX := float64(visible.Origin.X) + visMinY := float64(visible.Origin.Y) + visMaxX := visMinX + float64(visible.Size.Width) + visMaxY := visMinY + float64(visible.Size.Height) + + minCol := max(0, int(math.Floor(visMinX/tw))) + maxCol := min(cols-1, int(math.Ceil(visMaxX/tw))-1) + minRow := max(0, int(math.Floor(visMinY/th))) + maxRow := min(rows-1, int(math.Ceil(visMaxY/th))-1) + if minCol > maxCol || minRow > maxRow { + return + } + + owR, owG, owB, owA := premulFromColor(style.OneWayTileColor, 1) + tick := th * 0.25 + + for row := minRow; row <= maxRow; row++ { + y := float64(row) * th + for col := minCol; col <= maxCol; col++ { + flags := grid.TileFlagsAt(col, row) + if flags&physics.TileSolid != 0 { + drawCrispRectOutline(dst, clip, worldM, float64(col)*tw, y, tw, th, style.SolidTileColor) + drawn.PhysicsTiles++ + } else if flags&physics.TileOneWay != 0 { + drawOneWayTileOverlay(dst, clip, worldM, float64(col)*tw, y, tw, tick, owR, owG, owB, owA) + drawn.PhysicsTiles++ + } + } + } +} + +func drawPhysicsShapeOverlay(dst *image.RGBA, clip image.Rectangle, m affine2D, s physics.Shape, boxColor, circleColor core.Color, drawn *OverlaysDrawn, isTrigger bool) (int, int, bool) { + switch s.Kind { + case physics.ShapeBox: + b := s.Box + if b.Empty() { + return 0, 0, false + } + x0, y0, ok := drawCrispRectOutline(dst, clip, m, float64(b.X), float64(b.Y), float64(b.W), float64(b.H), boxColor) + if isTrigger { + drawn.PhysicsTriggers++ + } else { + drawn.PhysicsBoxes++ + } + return x0, y0, ok + case physics.ShapeCircle: + c := s.Circle + if c.Empty() { + return 0, 0, false + } + x0, y0, ok := drawCrispCircleOutline(dst, clip, m, float64(c.X), float64(c.Y), float64(c.R), circleColor) + if isTrigger { + drawn.PhysicsTriggers++ + } else { + drawn.PhysicsCircles++ + } + return x0, y0, ok + default: + return 0, 0, false + } +} + +func drawOneWayTileOverlay(dst *image.RGBA, clip image.Rectangle, m affine2D, x, y, tw, tick, sr, sg, sb, sa float64) { + if math.Abs(m.b) < 1e-6 && math.Abs(m.c) < 1e-6 { + sx0, sy0 := m.apply(x, y) + sx1, sy1 := m.apply(x+tw, y+tick) + minX, maxX := min(sx0, sx1), max(sx0, sx1) + minY, maxY := min(sy0, sy1), max(sy0, sy1) + px0 := int(math.Ceil(minX - 0.5)) + px1 := max(px0, int(math.Ceil(maxX-0.5))-1) + py0 := int(math.Ceil(minY - 0.5)) + py1 := max(py0, int(math.Ceil(maxY-0.5))-1) + drawLineBresenham(dst, clip, px0, py1, px0, py0, sr, sg, sb, sa) + drawLineBresenham(dst, clip, px0, py0, px1, py0, sr, sg, sb, sa) + drawLineBresenham(dst, clip, px1, py0, px1, py1, sr, sg, sb, sa) + return + } + drawWorldSegment(dst, clip, m, x, y+tick, x, y, sr, sg, sb, sa) + drawWorldSegment(dst, clip, m, x, y, x+tw, y, sr, sg, sb, sa) + drawWorldSegment(dst, clip, m, x+tw, y, x+tw, y+tick, sr, sg, sb, sa) +} + +func drawWorldSegment(dst *image.RGBA, clip image.Rectangle, m affine2D, x0, y0, x1, y1, sr, sg, sb, sa float64) { + sx0, sy0 := m.apply(x0, y0) + sx1, sy1 := m.apply(x1, y1) + drawLineBresenham(dst, clip, int(math.Floor(sx0)), int(math.Floor(sy0)), int(math.Floor(sx1)), int(math.Floor(sy1)), sr, sg, sb, sa) +} + +// drawCrispRectOutline draws a pixel-aligned 1-pixel border matching the exact pixel coverage of a filled rectangle [x, x+w) x [y, y+h) transformed by m, clipped to clip. It returns the top-left screen pixel coordinate and whether any part of the rectangle lies within clip. +func drawCrispRectOutline(dst *image.RGBA, clip image.Rectangle, m affine2D, x, y, w, h float64, col core.Color) (int, int, bool) { + x, y, w, h = normalizeRect2D(x, y, w, h) + if w <= 0 || h <= 0 { + return 0, 0, false + } + sr, sg, sb, sa := premulFromColor(col, 1) + if sa <= 0 { + return 0, 0, false + } + + // Axis-aligned fast path (covers all unrotated cameras/viewports/sprites/boxes). + if math.Abs(m.b) < 1e-6 && math.Abs(m.c) < 1e-6 { + sx0, sy0 := m.apply(x, y) + sx1, sy1 := m.apply(x+w, y+h) + minX, maxX := min(sx0, sx1), max(sx0, sx1) + minY, maxY := min(sy0, sy1), max(sy0, sy1) + + // Exact inclusive pixel bounds matching pixel-center (px+0.5, py+0.5) coverage of [minX, maxX) x [minY, maxY). + px0 := int(math.Ceil(minX - 0.5)) + px1 := int(math.Ceil(maxX-0.5)) - 1 + py0 := int(math.Ceil(minY - 0.5)) + py1 := int(math.Ceil(maxY-0.5)) - 1 + if px1 < px0 { + px1 = px0 + } + if py1 < py0 { + py1 = py0 + } + if px1 < clip.Min.X || px0 >= clip.Max.X || py1 < clip.Min.Y || py0 >= clip.Max.Y { + return px0, py0, false + } + + // Top and bottom horizontal edges. + hx0, hx1 := max(px0, clip.Min.X), min(px1, clip.Max.X-1) + if py0 >= clip.Min.Y && py0 < clip.Max.Y { + for px := hx0; px <= hx1; px++ { + blendOver2D(dst, px, py0, sr, sg, sb, sa) + } + } + if py1 != py0 && py1 >= clip.Min.Y && py1 < clip.Max.Y { + for px := hx0; px <= hx1; px++ { + blendOver2D(dst, px, py1, sr, sg, sb, sa) + } + } + // Left and right vertical edges (skip corners already blended on top/bottom). + vy0, vy1 := max(py0+1, clip.Min.Y), min(py1-1, clip.Max.Y-1) + if px0 >= clip.Min.X && px0 < clip.Max.X { + for py := vy0; py <= vy1; py++ { + blendOver2D(dst, px0, py, sr, sg, sb, sa) + } + } + if px1 != px0 && px1 >= clip.Min.X && px1 < clip.Max.X { + for py := vy0; py <= vy1; py++ { + blendOver2D(dst, px1, py, sr, sg, sb, sa) + } + } + return px0, py0, true + } + + // Rotated / sheared path: transform all four corners and draw four crisp 1px edges. + c0x, c0y := m.apply(x, y) + c1x, c1y := m.apply(x+w, y) + c2x, c2y := m.apply(x+w, y+h) + c3x, c3y := m.apply(x, y+h) + + p0x, p0y := int(math.Floor(c0x)), int(math.Floor(c0y)) + p1x, p1y := int(math.Floor(c1x)), int(math.Floor(c1y)) + p2x, p2y := int(math.Floor(c2x)), int(math.Floor(c2y)) + p3x, p3y := int(math.Floor(c3x)), int(math.Floor(c3y)) + + minPX := min(min(p0x, p1x), min(p2x, p3x)) + maxPX := max(max(p0x, p1x), max(p2x, p3x)) + minPY := min(min(p0y, p1y), min(p2y, p3y)) + maxPY := max(max(p0y, p1y), max(p2y, p3y)) + if maxPX < clip.Min.X || minPX >= clip.Max.X || maxPY < clip.Min.Y || minPY >= clip.Max.Y { + return minPX, minPY, false + } + + drawLineBresenham(dst, clip, p0x, p0y, p1x, p1y, sr, sg, sb, sa) + drawLineBresenham(dst, clip, p1x, p1y, p2x, p2y, sr, sg, sb, sa) + drawLineBresenham(dst, clip, p2x, p2y, p3x, p3y, sr, sg, sb, sa) + drawLineBresenham(dst, clip, p3x, p3y, p0x, p0y, sr, sg, sb, sa) + return minPX, minPY, true +} + +// drawCrispCircleOutline draws a closed 1-pixel circle/ellipse outline aligned to [cx-r, cx+r) x [cy-r, cy+r) under transform m, plus the +X orientation radius tick matching physics.DrawShape. +func drawCrispCircleOutline(dst *image.RGBA, clip image.Rectangle, m affine2D, cx, cy, r float64, col core.Color) (int, int, bool) { + if r <= 0 { + return 0, 0, false + } + sr, sg, sb, sa := premulFromColor(col, 1) + if sa <= 0 { + return 0, 0, false + } + + scx, scy := m.apply(cx, cy) + ux, uy := m.a*r, m.b*r + vx, vy := m.c*r, m.d*r + rx := math.Hypot(ux, uy) + ry := math.Hypot(vx, vy) + maxR := max(rx, ry) + if maxR <= 0 { + return 0, 0, false + } + + // Inset semi-axes by 0.5px so the 1px border stays strictly inside the circle's bounding pixels. + if rx > 0.5 { + scale := (rx - 0.5) / rx + ux *= scale + uy *= scale + } + if ry > 0.5 { + scale := (ry - 0.5) / ry + vx *= scale + vy *= scale + } + + minPX := int(math.Floor(scx - maxR)) + maxPX := int(math.Ceil(scx + maxR)) + minPY := int(math.Floor(scy - maxR)) + maxPY := int(math.Ceil(scy + maxR)) + if maxPX < clip.Min.X || minPX >= clip.Max.X || maxPY < clip.Min.Y || minPY >= clip.Max.Y { + return minPX, minPY, false + } + + steps := max(32, int(math.Ceil(2*math.Pi*maxR*2))) + prevX := int(math.Floor(scx + ux)) + prevY := int(math.Floor(scy + uy)) + for i := 1; i <= steps; i++ { + ang := 2 * math.Pi * float64(i) / float64(steps) + sn, cs := math.Sincos(ang) + nx := int(math.Floor(scx + ux*cs + vx*sn)) + ny := int(math.Floor(scy + uy*cs + vy*sn)) + if nx != prevX || ny != prevY { + drawLineBresenham(dst, clip, prevX, prevY, nx, ny, sr, sg, sb, sa) + prevX, prevY = nx, ny + } + } + + // Draw +X orientation tick from center to +X edge (matching physics.DrawShape). + drawLineBresenham(dst, clip, int(math.Floor(scx)), int(math.Floor(scy)), int(math.Floor(scx+ux)), int(math.Floor(scy+uy)), sr, sg, sb, sa) + return minPX, minPY, true +} + +func drawLineBresenham(dst *image.RGBA, clip image.Rectangle, x0, y0, x1, y1 int, sr, sg, sb, sa float64) { + dx := x1 - x0 + if dx < 0 { + dx = -dx + } + dy := y1 - y0 + if dy < 0 { + dy = -dy + } + sx := -1 + if x0 < x1 { + sx = 1 + } + sy := -1 + if y0 < y1 { + sy = 1 + } + err := dx - dy + for { + if x0 >= clip.Min.X && x0 < clip.Max.X && y0 >= clip.Min.Y && y0 < clip.Max.Y { + blendOver2D(dst, x0, y0, sr, sg, sb, sa) + } + if x0 == x1 && y0 == y1 { + break + } + e2 := 2 * err + if e2 > -dy { + err -= dy + x0 += sx + } + if e2 < dx { + err += dx + y0 += sy + } + } +} + +// --- Compact 3x5 bitmap font for diagnostic overlay labels --- + +var tinyGlyphs = map[rune][5]uint8{ + '0': {0b111, 0b101, 0b101, 0b101, 0b111}, + '1': {0b010, 0b110, 0b010, 0b010, 0b111}, + '2': {0b111, 0b001, 0b111, 0b100, 0b111}, + '3': {0b111, 0b001, 0b111, 0b001, 0b111}, + '4': {0b101, 0b101, 0b111, 0b001, 0b001}, + '5': {0b111, 0b100, 0b111, 0b001, 0b111}, + '6': {0b111, 0b100, 0b111, 0b101, 0b111}, + '7': {0b111, 0b001, 0b001, 0b010, 0b010}, + '8': {0b111, 0b101, 0b111, 0b101, 0b111}, + '9': {0b111, 0b101, 0b111, 0b001, 0b111}, + 'A': {0b010, 0b101, 0b111, 0b101, 0b101}, + 'B': {0b110, 0b101, 0b110, 0b101, 0b110}, + 'C': {0b011, 0b100, 0b100, 0b100, 0b011}, + 'D': {0b110, 0b101, 0b101, 0b101, 0b110}, + 'E': {0b111, 0b100, 0b110, 0b100, 0b111}, + 'F': {0b111, 0b100, 0b110, 0b100, 0b100}, + 'G': {0b011, 0b100, 0b101, 0b101, 0b011}, + 'H': {0b101, 0b101, 0b111, 0b101, 0b101}, + 'I': {0b111, 0b010, 0b010, 0b010, 0b111}, + 'J': {0b001, 0b001, 0b001, 0b101, 0b010}, + 'K': {0b101, 0b101, 0b110, 0b101, 0b101}, + 'L': {0b100, 0b100, 0b100, 0b100, 0b111}, + 'M': {0b101, 0b111, 0b101, 0b101, 0b101}, + 'N': {0b110, 0b101, 0b101, 0b101, 0b101}, + 'O': {0b010, 0b101, 0b101, 0b101, 0b010}, + 'P': {0b110, 0b101, 0b110, 0b100, 0b100}, + 'Q': {0b010, 0b101, 0b101, 0b011, 0b001}, + 'R': {0b110, 0b101, 0b110, 0b101, 0b101}, + 'S': {0b011, 0b100, 0b010, 0b001, 0b110}, + 'T': {0b111, 0b010, 0b010, 0b010, 0b010}, + 'U': {0b101, 0b101, 0b101, 0b101, 0b111}, + 'V': {0b101, 0b101, 0b101, 0b101, 0b010}, + 'W': {0b101, 0b101, 0b101, 0b111, 0b101}, + 'X': {0b101, 0b101, 0b010, 0b101, 0b101}, + 'Y': {0b101, 0b101, 0b010, 0b010, 0b010}, + 'Z': {0b111, 0b001, 0b010, 0b100, 0b111}, + '-': {0b000, 0b000, 0b111, 0b000, 0b000}, + '_': {0b000, 0b000, 0b000, 0b000, 0b111}, + ':': {0b000, 0b010, 0b000, 0b010, 0b000}, + '.': {0b000, 0b000, 0b000, 0b000, 0b010}, + '/': {0b001, 0b001, 0b010, 0b100, 0b100}, + ' ': {0b000, 0b000, 0b000, 0b000, 0b000}, +} + +func drawTinyLabel(dst *image.RGBA, clip image.Rectangle, x, y int, text string, fg, bg core.Color) { + text = strings.ToUpper(strings.TrimSpace(text)) + if text == "" { + return + } + if len(text) > 16 { + text = text[:16] + } + runes := []rune(text) + pillW := len(runes)*4 + 1 + pillH := 7 + + // Place label immediately above (x, y) when room exists, otherwise inside top-left. + ox := x + oy := y - pillH - 1 + if oy < clip.Min.Y { + oy = y + 1 + } + if ox < clip.Min.X { + ox = clip.Min.X + } + if ox+pillW > clip.Max.X { + ox = max(clip.Min.X, clip.Max.X-pillW) + } + if oy+pillH > clip.Max.Y { + oy = max(clip.Min.Y, clip.Max.Y-pillH) + } + + br, bgC, bb, ba := premulFromColor(bg, 1) + if ba > 0 { + for py := max(oy, clip.Min.Y); py < min(oy+pillH, clip.Max.Y); py++ { + for px := max(ox, clip.Min.X); px < min(ox+pillW, clip.Max.X); px++ { + blendOver2D(dst, px, py, br, bgC, bb, ba) + } + } + } + + fr, fgC, fb, fa := premulFromColor(fg, 1) + if fa <= 0 { + return + } + for i, ch := range runes { + g, ok := tinyGlyphs[ch] + if !ok { + g = tinyGlyphs[' '] + } + gx := ox + 1 + i*4 + gy := oy + 1 + for row := range 5 { + bits := g[row] + for col := range 3 { + if bits&(1<<(2-col)) != 0 { + px, py := gx+col, gy+row + if px >= clip.Min.X && px < clip.Max.X && py >= clip.Min.Y && py < clip.Max.Y { + blendOver2D(dst, px, py, fr, fgC, fb, fa) + } + } + } + } + } +} + +// --- Self-contained deterministic software rasterizer for core.DrawOp --- + +type affine2D struct { + a, b, c, d, e, f float64 +} + +func identityAffine2D() affine2D { + return affine2D{a: 1, d: 1} +} + +func rotateAroundAffine2D(cx, cy, angle float64) affine2D { + sin, cos := math.Sincos(angle) + t1 := affine2D{a: 1, d: 1, e: cx, f: cy} + rot := affine2D{a: cos, b: sin, c: -sin, d: cos} + t2 := affine2D{a: 1, d: 1, e: -cx, f: -cy} + return t1.mul(rot).mul(t2) +} + +func (m affine2D) mul(n affine2D) affine2D { + return affine2D{ + a: m.a*n.a + m.c*n.b, + b: m.b*n.a + m.d*n.b, + c: m.a*n.c + m.c*n.d, + d: m.b*n.c + m.d*n.d, + e: m.a*n.e + m.c*n.f + m.e, + f: m.b*n.e + m.d*n.f + m.f, + } +} + +func (m affine2D) apply(x, y float64) (float64, float64) { + return m.a*x + m.c*y + m.e, m.b*x + m.d*y + m.f +} + +func (m affine2D) invert() (affine2D, bool) { + det := m.a*m.d - m.b*m.c + if math.Abs(det) < 1e-12 { + return affine2D{}, false + } + invDet := 1 / det + return affine2D{ + a: m.d * invDet, + b: -m.b * invDet, + c: -m.c * invDet, + d: m.a * invDet, + e: (m.c*m.f - m.d*m.e) * invDet, + f: (m.b*m.e - m.a*m.f) * invDet, + }, true +} + +func applyTransformOp(m affine2D, op core.DrawOp) affine2D { + switch op.Kind { + case core.DrawTranslate: + return m.mul(affine2D{a: 1, d: 1, e: float64(op.X), f: float64(op.Y)}) + case core.DrawScale: + return m.mul(affine2D{a: float64(op.X), d: float64(op.Y)}) + case core.DrawRotate: + sin, cos := math.Sincos(float64(op.A)) + return m.mul(affine2D{a: cos, b: sin, c: -sin, d: cos}) + case core.DrawTransform: + return m.mul(affine2D{ + a: float64(op.X1), b: float64(op.Y1), + c: float64(op.X2), d: float64(op.Y2), + e: float64(op.X), f: float64(op.Y), + }) + case core.DrawSetTransform: + return affine2D{ + a: float64(op.X1), b: float64(op.Y1), + c: float64(op.X2), d: float64(op.Y2), + e: float64(op.X), f: float64(op.Y), + } + default: + return m + } +} + +type pathRect2D struct { + x, y, w, h float64 + m affine2D +} + +type pathSeg2D struct { + x0, y0, x1, y1 float64 +} + +type rasterState struct { + m affine2D + alpha float64 + fillColor core.Color + strokeColor core.Color + lineWidth float64 + clip image.Rectangle +} + +// rasterSkipped counts what rasterizeOps could not draw, so a result can say the image is partial. +type rasterSkipped struct { + ops map[string]int + images int +} + +func (r *rasterSkipped) op(k core.DrawKind) { + if r.ops == nil { + r.ops = make(map[string]int) + } + r.ops[k.String()]++ +} + +// rasterImage is an image source decoded for drawing, with its pixels per point on each axis. +type rasterImage struct { + img image.Image + ppx, ppy float64 +} + +func rasterizeOps(width, height int, ops []core.DrawOp, bg core.Color) (*image.RGBA, rasterSkipped) { + var skipped rasterSkipped + if width <= 0 || height <= 0 { + return image.NewRGBA(image.Rectangle{}), skipped + } + dst := image.NewRGBA(image.Rect(0, 0, width, height)) + if bg != 0 && bg != core.Transparent { + r, g, b, a := premulFromColor(bg, 1) + if a > 0 { + rb, gb, bb, ab := toByte2D(r), toByte2D(g), toByte2D(b), toByte2D(a) + for y := range height { + row := dst.Pix[y*dst.Stride:] + for x := range width { + off := x * 4 + row[off] = rb + row[off+1] = gb + row[off+2] = bb + row[off+3] = ab + } + } + } + } + + fullClip := image.Rect(0, 0, width, height) + cur := rasterState{ + m: identityAffine2D(), + alpha: 1, + fillColor: core.RGB(0x000000), + strokeColor: core.RGB(0x000000), + lineWidth: 1, + clip: fullClip, + } + var stack []rasterState + var rects []pathRect2D + var segs []pathSeg2D + var hasPen bool + var penX, penY, subX, subY float64 + decoded := make(map[string]image.Image) + + // resolveImage returns the pixels of an in-memory source (Pixels or Data). URI, asset: and Offscreen sources are not loaded here; they are counted in skipped.images. + resolveImage := func(src *core.ImageSource) (rasterImage, bool) { + if src == nil { + return rasterImage{}, false + } + var img image.Image + switch { + case src.Pixels != nil: + img = src.Pixels + case len(src.Data) > 0: + // Looking up with string(src.Data) in the index expression does not copy the bytes. + if cached, ok := decoded[string(src.Data)]; ok { + img = cached + } else { + dec, _, err := image.Decode(bytes.NewReader(src.Data)) + if err != nil { + return rasterImage{}, false + } + decoded[string(src.Data)] = dec + img = dec + } + default: + return rasterImage{}, false + } + b := img.Bounds() + if b.Empty() { + return rasterImage{}, false + } + ri := rasterImage{img: img, ppx: 1, ppy: 1} + // Without Size an in-memory image measures its pixels in points; with Size, source rectangles are in the image's points. + if src.Size.Width > 0 && src.Size.Height > 0 { + ri.ppx = float64(b.Dx()) / float64(src.Size.Width) + ri.ppy = float64(b.Dy()) / float64(src.Size.Height) + } + return ri, true + } + + for _, op := range ops { + switch op.Kind { + case core.DrawSave: + stack = append(stack, cur) + case core.DrawRestore: + if n := len(stack); n > 0 { + cur = stack[n-1] + stack = stack[:n-1] + } + case core.DrawTranslate, core.DrawScale, core.DrawRotate, core.DrawTransform, core.DrawSetTransform: + cur.m = applyTransformOp(cur.m, op) + case core.DrawAlpha: + cur.alpha = clamp01Float(float64(op.A)) + case core.DrawFillColor: + cur.fillColor = op.Color + case core.DrawStrokeColor: + cur.strokeColor = op.Color + case core.DrawLineWidth: + if op.W > 0 { + cur.lineWidth = float64(op.W) + } + case core.DrawBeginPath: + rects = rects[:0] + segs = segs[:0] + hasPen = false + case core.DrawRect: + rects = append(rects, pathRect2D{ + x: float64(op.X), y: float64(op.Y), + w: float64(op.W), h: float64(op.H), + m: cur.m, + }) + case core.DrawMoveTo: + penX, penY = cur.m.apply(float64(op.X), float64(op.Y)) + subX, subY = penX, penY + hasPen = true + case core.DrawLineTo: + nx, ny := cur.m.apply(float64(op.X), float64(op.Y)) + if hasPen { + segs = append(segs, pathSeg2D{x0: penX, y0: penY, x1: nx, y1: ny}) + } else { + subX, subY = nx, ny + hasPen = true + } + penX, penY = nx, ny + case core.DrawQuadTo, core.DrawCubicTo: + // An affine transform maps a Bezier curve to the Bezier curve of the mapped control points, so flatten in pixels. + c1x, c1y := cur.m.apply(float64(op.X1), float64(op.Y1)) + c2x, c2y := c1x, c1y + if op.Kind == core.DrawCubicTo { + c2x, c2y = cur.m.apply(float64(op.X2), float64(op.Y2)) + } + ex, ey := cur.m.apply(float64(op.X), float64(op.Y)) + if !hasPen { + penX, penY = c1x, c1y + subX, subY = c1x, c1y + hasPen = true + } + x0, y0 := penX, penY + length := math.Hypot(c1x-x0, c1y-y0) + math.Hypot(c2x-c1x, c2y-c1y) + math.Hypot(ex-c2x, ey-c2y) + steps := min(256, max(8, int(math.Ceil(length/2)))) + for i := 1; i <= steps; i++ { + t := float64(i) / float64(steps) + u := 1 - t + var px, py float64 + if op.Kind == core.DrawQuadTo { + px = u*u*x0 + 2*u*t*c1x + t*t*ex + py = u*u*y0 + 2*u*t*c1y + t*t*ey + } else { + px = u*u*u*x0 + 3*u*u*t*c1x + 3*u*t*t*c2x + t*t*t*ex + py = u*u*u*y0 + 3*u*u*t*c1y + 3*u*t*t*c2y + t*t*t*ey + } + segs = append(segs, pathSeg2D{x0: penX, y0: penY, x1: px, y1: py}) + penX, penY = px, py + } + case core.DrawRoundRect, core.DrawEllipse, core.DrawFillText, core.DrawStrokeText, core.DrawFillGradient, core.DrawStrokeGradient, core.DrawVertices: + skipped.op(op.Kind) + case core.DrawComposite: + if op.Composite != core.CompositeSourceOver { + skipped.op(op.Kind) + } + case core.DrawLineDash: + if op.Dash != nil && len(*op.Dash) > 0 { + skipped.op(op.Kind) + } + case core.DrawShadow: + if op.Color != core.Transparent && op.Color&0xff != 0 { + skipped.op(op.Kind) + } + case core.DrawClosePath: + if hasPen && (penX != subX || penY != subY) { + segs = append(segs, pathSeg2D{x0: penX, y0: penY, x1: subX, y1: subY}) + penX, penY = subX, subY + } + case core.DrawArc: + r := float64(op.R) + if r <= 0 { + continue + } + a0, a1 := float64(op.A0), float64(op.A1) + sweep := a1 - a0 + if op.CCW { + if sweep > 0 { + sweep -= 2 * math.Pi * math.Ceil(sweep/(2*math.Pi)) + } + } else { + if sweep < 0 { + sweep += 2 * math.Pi * math.Ceil(-sweep/(2*math.Pi)) + } + } + if math.Abs(sweep) > 2*math.Pi { + if op.CCW { + sweep = -2 * math.Pi + } else { + sweep = 2 * math.Pi + } + } + scale := max(math.Hypot(cur.m.a, cur.m.b), math.Hypot(cur.m.c, cur.m.d)) + steps := max(16, int(math.Ceil(math.Abs(sweep)*r*scale))) + cx, cy := float64(op.X), float64(op.Y) + for i := 0; i <= steps; i++ { + ang := a0 + sweep*float64(i)/float64(steps) + sn, cs := math.Sincos(ang) + px, py := cur.m.apply(cx+r*cs, cy+r*sn) + if i == 0 { + if hasPen { + segs = append(segs, pathSeg2D{x0: penX, y0: penY, x1: px, y1: py}) + } else { + subX, subY = px, py + hasPen = true + } + } else { + segs = append(segs, pathSeg2D{x0: penX, y0: penY, x1: px, y1: py}) + } + penX, penY = px, py + } + case core.DrawClip: + if clipR, ok := pathBoundsRect(rects, segs, fullClip); ok { + cur.clip = cur.clip.Intersect(clipR) + } + case core.DrawFill: + sr, sg, sb, sa := premulFromColor(cur.fillColor, cur.alpha) + if sa <= 0 || cur.clip.Empty() { + continue + } + for _, r := range rects { + fillTransformedRect2D(dst, cur.clip, r.m, r.x, r.y, r.w, r.h, sr, sg, sb, sa) + } + if len(segs) >= 3 { + fillPolygon2D(dst, cur.clip, segs, sr, sg, sb, sa) + } + case core.DrawStroke: + sr, sg, sb, sa := premulFromColor(cur.strokeColor, cur.alpha) + if sa <= 0 || cur.lineWidth <= 0 || cur.clip.Empty() { + continue + } + for _, r := range rects { + strokeTransformedRect2D(dst, cur.clip, r.m, r.x, r.y, r.w, r.h, cur.lineWidth, sr, sg, sb, sa) + } + if len(segs) > 0 { + scale := math.Sqrt(math.Hypot(cur.m.a, cur.m.b) * math.Hypot(cur.m.c, cur.m.d)) + lw := max(1, cur.lineWidth*scale) + for _, seg := range segs { + strokeSegment2D(dst, cur.clip, seg.x0, seg.y0, seg.x1, seg.y1, lw, sr, sg, sb, sa) + } + } + case core.DrawClear: + if cur.clip.Empty() { + continue + } + clearTransformedRect2D(dst, cur.clip, cur.m, float64(op.X), float64(op.Y), float64(op.W), float64(op.H)) + case core.DrawImage: + if cur.alpha <= 0 || cur.clip.Empty() { + continue + } + ri, ok := resolveImage(op.Image) + if !ok { + skipped.images++ + continue + } + b := ri.img.Bounds() + // The source rectangle is in the image's points; the destination defaults to the source's size in points. + sx, sy, sw, sh := float64(op.X1), float64(op.Y1), float64(op.X2), float64(op.Y2) + if sw == 0 && sh == 0 { + sx, sy = 0, 0 + sw, sh = float64(b.Dx())/ri.ppx, float64(b.Dy())/ri.ppy + } + dx, dy, dw, dh := float64(op.X), float64(op.Y), float64(op.W), float64(op.H) + if dw == 0 && dh == 0 { + dw, dh = sw, sh + } + drawTransformedImage2D(dst, cur.clip, cur.m, ri.img, sx*ri.ppx, sy*ri.ppy, sw*ri.ppx, sh*ri.ppy, dx, dy, dw, dh, cur.alpha, op.Tinted, op.Color) + case core.DrawAtlas: + if cur.alpha <= 0 || op.Atlas == nil || cur.clip.Empty() { + continue + } + ri, ok := resolveImage(op.Image) + if !ok { + skipped.images++ + continue + } + for _, s := range *op.Atlas { + alpha := cur.alpha * float64(s.Alpha) + if alpha <= 0 { + continue + } + t := s.Transform + m := cur.m.mul(affine2D{ + a: float64(t.SCos), b: float64(t.SSin), + c: -float64(t.SSin), d: float64(t.SCos), + e: float64(t.TX), f: float64(t.TY), + }) + sw, sh := float64(s.Rect.Size.Width), float64(s.Rect.Size.Height) + drawTransformedImage2D(dst, cur.clip, m, ri.img, float64(s.Rect.Origin.X)*ri.ppx, float64(s.Rect.Origin.Y)*ri.ppy, sw*ri.ppx, sh*ri.ppy, 0, 0, sw, sh, alpha, false, 0) + } + } + } + + return dst, skipped +} + +func pathBoundsRect(rects []pathRect2D, segs []pathSeg2D, full image.Rectangle) (image.Rectangle, bool) { + has := false + minX, minY := math.Inf(1), math.Inf(1) + maxX, maxY := math.Inf(-1), math.Inf(-1) + addPt := func(x, y float64) { + has = true + minX = min(minX, x) + minY = min(minY, y) + maxX = max(maxX, x) + maxY = max(maxY, y) + } + for _, r := range rects { + x0, y0 := r.m.apply(r.x, r.y) + x1, y1 := r.m.apply(r.x+r.w, r.y) + x2, y2 := r.m.apply(r.x+r.w, r.y+r.h) + x3, y3 := r.m.apply(r.x, r.y+r.h) + addPt(x0, y0) + addPt(x1, y1) + addPt(x2, y2) + addPt(x3, y3) + } + for _, s := range segs { + addPt(s.x0, s.y0) + addPt(s.x1, s.y1) + } + if !has { + return image.Rectangle{}, false + } + r := image.Rect( + int(math.Ceil(minX-0.5)), + int(math.Ceil(minY-0.5)), + int(math.Ceil(maxX-0.5)), + int(math.Ceil(maxY-0.5)), + ) + return r.Intersect(full), true +} + +func transformedBounds2D(m affine2D, x, y, w, h float64, clip image.Rectangle) (minX, minY, maxX, maxY int, ok bool) { + x0, y0 := m.apply(x, y) + x1, y1 := m.apply(x+w, y) + x2, y2 := m.apply(x, y+h) + x3, y3 := m.apply(x+w, y+h) + + loX := min(min(x0, x1), min(x2, x3)) + hiX := max(max(x0, x1), max(x2, x3)) + loY := min(min(y0, y1), min(y2, y3)) + hiY := max(max(y0, y1), max(y2, y3)) + + minX = max(clip.Min.X, int(math.Floor(loX))) + minY = max(clip.Min.Y, int(math.Floor(loY))) + maxX = min(clip.Max.X, int(math.Ceil(hiX))) + maxY = min(clip.Max.Y, int(math.Ceil(hiY))) + return minX, minY, maxX, maxY, minX < maxX && minY < maxY +} + +func normalizeRect2D(x, y, w, h float64) (float64, float64, float64, float64) { + if w < 0 { + x += w + w = -w + } + if h < 0 { + y += h + h = -h + } + return x, y, w, h +} + +func fillTransformedRect2D(dst *image.RGBA, clip image.Rectangle, m affine2D, x, y, w, h, sr, sg, sb, sa float64) { + x, y, w, h = normalizeRect2D(x, y, w, h) + if w <= 0 || h <= 0 { + return + } + inv, ok := m.invert() + if !ok { + return + } + minX, minY, maxX, maxY, visible := transformedBounds2D(m, x, y, w, h, clip) + if !visible { + return + } + for py := minY; py < maxY; py++ { + cy := float64(py) + 0.5 + for px := minX; px < maxX; px++ { + lx, ly := inv.apply(float64(px)+0.5, cy) + if lx >= x && lx < x+w && ly >= y && ly < y+h { + blendOver2D(dst, px, py, sr, sg, sb, sa) + } + } + } +} + +func strokeTransformedRect2D(dst *image.RGBA, clip image.Rectangle, m affine2D, x, y, w, h, lineWidth, sr, sg, sb, sa float64) { + x, y, w, h = normalizeRect2D(x, y, w, h) + if (w <= 0 && h <= 0) || lineWidth <= 0 { + return + } + inv, ok := m.invert() + if !ok { + return + } + half := lineWidth / 2 + ox, oy, ow, oh := x-half, y-half, w+lineWidth, h+lineWidth + ix0, iy0, ix1, iy1 := x+half, y+half, x+w-half, y+h-half + hasHole := ix0 < ix1 && iy0 < iy1 + + minX, minY, maxX, maxY, visible := transformedBounds2D(m, ox, oy, ow, oh, clip) + if !visible { + return + } + for py := minY; py < maxY; py++ { + cy := float64(py) + 0.5 + for px := minX; px < maxX; px++ { + lx, ly := inv.apply(float64(px)+0.5, cy) + if lx < ox || lx >= ox+ow || ly < oy || ly >= oy+oh { + continue + } + if hasHole && lx > ix0 && lx < ix1 && ly > iy0 && ly < iy1 { + continue + } + blendOver2D(dst, px, py, sr, sg, sb, sa) + } + } +} + +func clearTransformedRect2D(dst *image.RGBA, clip image.Rectangle, m affine2D, x, y, w, h float64) { + x, y, w, h = normalizeRect2D(x, y, w, h) + if w <= 0 || h <= 0 { + return + } + inv, ok := m.invert() + if !ok { + return + } + minX, minY, maxX, maxY, visible := transformedBounds2D(m, x, y, w, h, clip) + if !visible { + return + } + for py := minY; py < maxY; py++ { + cy := float64(py) + 0.5 + for px := minX; px < maxX; px++ { + lx, ly := inv.apply(float64(px)+0.5, cy) + if lx >= x && lx < x+w && ly >= y && ly < y+h { + off := dst.PixOffset(px, py) + dst.Pix[off] = 0 + dst.Pix[off+1] = 0 + dst.Pix[off+2] = 0 + dst.Pix[off+3] = 0 + } + } + } +} + +func fillPolygon2D(dst *image.RGBA, clip image.Rectangle, segs []pathSeg2D, sr, sg, sb, sa float64) { + minY, maxY := math.Inf(1), math.Inf(-1) + for _, s := range segs { + minY = min(minY, min(s.y0, s.y1)) + maxY = max(maxY, max(s.y0, s.y1)) + } + y0 := max(clip.Min.Y, int(math.Floor(minY))) + y1 := min(clip.Max.Y, int(math.Ceil(maxY))) + var xs []float64 + for py := y0; py < y1; py++ { + cy := float64(py) + 0.5 + xs = xs[:0] + for _, s := range segs { + if (s.y0 <= cy && s.y1 > cy) || (s.y1 <= cy && s.y0 > cy) { + t := (cy - s.y0) / (s.y1 - s.y0) + xs = append(xs, s.x0+t*(s.x1-s.x0)) + } + } + if len(xs) < 2 { + continue + } + slices.Sort(xs) + for i := 0; i+1 < len(xs); i += 2 { + px0 := max(clip.Min.X, int(math.Ceil(xs[i]-0.5))) + px1 := min(clip.Max.X, int(math.Ceil(xs[i+1]-0.5))) + for px := px0; px < px1; px++ { + blendOver2D(dst, px, py, sr, sg, sb, sa) + } + } + } +} + +func strokeSegment2D(dst *image.RGBA, clip image.Rectangle, x0, y0, x1, y1, lw, sr, sg, sb, sa float64) { + if lw <= 1.25 { + drawLineBresenham(dst, clip, int(math.Floor(x0)), int(math.Floor(y0)), int(math.Floor(x1)), int(math.Floor(y1)), sr, sg, sb, sa) + return + } + half := lw / 2 + minX := max(clip.Min.X, int(math.Floor(min(x0, x1)-half))) + maxX := min(clip.Max.X, int(math.Ceil(max(x0, x1)+half))) + minY := max(clip.Min.Y, int(math.Floor(min(y0, y1)-half))) + maxY := min(clip.Max.Y, int(math.Ceil(max(y0, y1)+half))) + dx, dy := x1-x0, y1-y0 + lenSq := dx*dx + dy*dy + halfSq := half * half + for py := minY; py < maxY; py++ { + cy := float64(py) + 0.5 + for px := minX; px < maxX; px++ { + cx := float64(px) + 0.5 + var t float64 + if lenSq > 0 { + t = clamp01Float(((cx-x0)*dx + (cy-y0)*dy) / lenSq) + } + qx, qy := x0+t*dx, y0+t*dy + ddx, ddy := cx-qx, cy-qy + if ddx*ddx+ddy*ddy <= halfSq { + blendOver2D(dst, px, py, sr, sg, sb, sa) + } + } + } +} + +func drawTransformedImage2D(dst *image.RGBA, clip image.Rectangle, m affine2D, src image.Image, sx, sy, sw, sh, dx, dy, dw, dh, alpha float64, tinted bool, tint core.Color) { + if sw == 0 || sh == 0 || dw == 0 || dh == 0 { + return + } + inv, ok := m.invert() + if !ok { + return + } + nx, ny, nw, nh := normalizeRect2D(dx, dy, dw, dh) + minX, minY, maxX, maxY, visible := transformedBounds2D(m, nx, ny, nw, nh, clip) + if !visible { + return + } + + var tr, tg, tb, ta float64 = 1, 1, 1, 1 + if tinted && tint != 0 && tint != core.RGB(0xffffff) { + tr = float64(tint>>24&0xff) / 255 + tg = float64(tint>>16&0xff) / 255 + tb = float64(tint>>8&0xff) / 255 + ta = float64(tint&0xff) / 255 + if ta <= 0 { + return + } + } + + sb := src.Bounds() + for py := minY; py < maxY; py++ { + cy := float64(py) + 0.5 + for px := minX; px < maxX; px++ { + lx, ly := inv.apply(float64(px)+0.5, cy) + if lx < nx || lx >= nx+nw || ly < ny || ly >= ny+nh { + continue + } + u := (lx - dx) / dw + v := (ly - dy) / dh + ix := sb.Min.X + int(math.Floor(sx+u*sw)) + iy := sb.Min.Y + int(math.Floor(sy+v*sh)) + ix = min(max(ix, sb.Min.X), sb.Max.X-1) + iy = min(max(iy, sb.Min.Y), sb.Max.Y-1) + + r16, g16, b16, a16 := src.At(ix, iy).RGBA() + if a16 == 0 { + continue + } + effA := alpha * ta + sr := (float64(r16) / 65535) * tr * effA + sg := (float64(g16) / 65535) * tg * effA + sbVal := (float64(b16) / 65535) * tb * effA + sa := (float64(a16) / 65535) * effA + blendOver2D(dst, px, py, sr, sg, sbVal, sa) + } + } +} + +func premulFromColor(c core.Color, globalAlpha float64) (r, g, b, a float64) { + if c == core.Transparent { + return 0, 0, 0, 0 + } + a = (float64(c&0xff) / 255) * globalAlpha + r = (float64(c>>24&0xff) / 255) * a + g = (float64(c>>16&0xff) / 255) * a + b = (float64(c>>8&0xff) / 255) * a + return r, g, b, a +} + +func blendOver2D(dst *image.RGBA, x, y int, sr, sg, sb, sa float64) { + off := dst.PixOffset(x, y) + if sa >= 1 { + dst.Pix[off] = toByte2D(sr) + dst.Pix[off+1] = toByte2D(sg) + dst.Pix[off+2] = toByte2D(sb) + dst.Pix[off+3] = 255 + return + } + invA := 1 - sa + dr := float64(dst.Pix[off]) / 255 + dg := float64(dst.Pix[off+1]) / 255 + db := float64(dst.Pix[off+2]) / 255 + da := float64(dst.Pix[off+3]) / 255 + + dst.Pix[off] = toByte2D(sr + dr*invA) + dst.Pix[off+1] = toByte2D(sg + dg*invA) + dst.Pix[off+2] = toByte2D(sb + db*invA) + dst.Pix[off+3] = toByte2D(sa + da*invA) +} + +func clamp01Float(v float64) float64 { + if v < 0 { + return 0 + } + if v > 1 { + return 1 + } + return v +} + +func toByte2D(v float64) uint8 { + return uint8(math.Round(clamp01Float(v) * 255)) +} diff --git a/packages/game/mcp/screenshot_test.go b/packages/game/mcp/screenshot_test.go new file mode 100644 index 00000000..0b204738 --- /dev/null +++ b/packages/game/mcp/screenshot_test.go @@ -0,0 +1,848 @@ +package mcp_test + +import ( + "bytes" + "context" + "encoding/base64" + "image" + "image/color" + "image/png" + "math" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/physics" + "github.com/nsgo-dev/game/packages/game/scene" + "github.com/nsgo-dev/game/packages/game/screen" + "github.com/nsgo-dev/game/packages/game/sprite" + "github.com/nsgo-dev/game/packages/game/tilemap" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func solidSpriteImage(w, h int, c color.RGBA) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := range h { + for x := range w { + img.SetRGBA(x, y, c) + } + } + return img +} + +func coreColorToRGBA(c core.Color) color.RGBA { + if c == core.Transparent { + return color.RGBA{} + } + return color.RGBA{ + R: uint8(c >> 24 & 0xff), + G: uint8(c >> 16 & 0xff), + B: uint8(c >> 8 & 0xff), + A: uint8(c & 0xff), + } +} + +func decodeBase64PNG(t *testing.T, b64 string) *image.RGBA { + t.Helper() + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + t.Fatalf("base64 decode: %v", err) + } + return decodePNGBytes(t, raw) +} + +func decodePNGBytes(t *testing.T, raw []byte) *image.RGBA { + t.Helper() + img, err := png.Decode(bytes.NewReader(raw)) + if err != nil { + t.Fatalf("png decode: %v", err) + } + b := img.Bounds() + rgba := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) + for y := range b.Dy() { + for x := range b.Dx() { + rgba.Set(x, y, img.At(b.Min.X+x, b.Min.Y+y)) + } + } + return rgba +} + +func assertPixel(t *testing.T, img *image.RGBA, x, y int, want color.RGBA, label string) { + t.Helper() + got := img.RGBAAt(x, y) + if got != want { + t.Errorf("%s pixel (%d,%d) = %+v, want %+v", label, x, y, got, want) + } +} + +func TestScreenshotBaseAndAlignedOverlays(t *testing.T) { + bgColor := core.RGB(0x101820) + bgRGBA := coreColorToRGBA(bgColor) + heroRGBA := color.RGBA{R: 220, G: 40, B: 50, A: 255} + ballRGBA := color.RGBA{R: 40, G: 90, B: 230, A: 255} + hiddenRGBA := color.RGBA{R: 250, G: 250, B: 10, A: 255} + + heroAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(16, 16, heroRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "hero": {Name: "hero", X: 0, Y: 0, W: 16, H: 16, Width: 16, Height: 16}, + }, + } + ballAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(20, 20, ballRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "ball": {Name: "ball", X: 0, Y: 0, W: 20, H: 20, Width: 20, Height: 20}, + }, + } + hiddenAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(8, 8, hiddenRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "secret": {Name: "secret", X: 0, Y: 0, W: 8, H: 8, Width: 8, Height: 8}, + }, + } + + hero := sprite.NewSprite(heroAtlas.Frames["hero"]) + hero.X, hero.Y = 10, 20 // occupies pixels x=[10..25], y=[20..35] + + ball := sprite.NewSprite(ballAtlas.Frames["ball"]) + ball.X, ball.Y = 60, 30 // occupies pixels x=[60..79], y=[30..49] + + secret := sprite.NewSprite(hiddenAtlas.Frames["secret"]) + secret.X, secret.Y = 110, 4 + + sc := scene.NewScene(nil) + actors := scene.NewLayer("actors", scene.SpaceWorld, 0) + actors.AddBatch(&sprite.Batch{Atlas: heroAtlas, Sprites: []*sprite.Sprite{&hero}}) + actors.AddBatch(&sprite.Batch{Atlas: ballAtlas, Sprites: []*sprite.Sprite{&ball}}) + sc.AddLayer(actors) + + hiddenLayer := scene.NewLayer("hidden", scene.SpaceWorld, 10) + hiddenLayer.Visible = false + hiddenLayer.AddBatch(&sprite.Batch{Atlas: hiddenAtlas, Sprites: []*sprite.Sprite{&secret}}) + sc.AddLayer(hiddenLayer) + + // Physics world with inset hero box, ball circle, trigger, and tile grid. + grid := physics.NewGrid(8, 4, 16, 16) + grid.Set(0, 3, physics.TileSolid) // pixels x=[0..15], y=[48..63] + grid.Set(1, 3, physics.TileOneWay) // top edge at y=48, x=[16..31] + pw := &physics.World{Tiles: grid} + pw.Add( + &physics.Body{ + Tag: "hero_box", + Shape: physics.BoxShape(physics.Box{X: 12, Y: 22, W: 12, H: 12}), // pixels x=[12..23], y=[22..33] + }, + &physics.Body{ + Tag: "ball_col", + Shape: physics.CircleShape(physics.Circle{X: 70, Y: 40, R: 10}), // bounds x=[60..79], y=[30..49] + }, + ) + pw.AddTrigger(&physics.Trigger{ + Tag: "goal", + Shape: physics.BoxShape(physics.Box{X: 90, Y: 10, W: 12, H: 10}), // pixels x=[90..101], y=[10..19] + }) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + Scene: sc, + Physics: pw, + ScreenshotBackground: bgColor, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // 1. Base screenshot without overlays. + baseRes := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "width": 128, + "height": 64, + }) + if baseRes.Width != 128 || baseRes.Height != 64 || baseRes.Format != "png" || baseRes.Bytes <= 0 || baseRes.PNGBase64 == "" { + t.Fatalf("unexpected base screenshot metadata: %+v", baseRes) + } + if baseRes.OverlaysDrawn.Bounds || baseRes.OverlaysDrawn.CollisionShapes { + t.Fatalf("expected no overlays drawn, got %+v", baseRes.OverlaysDrawn) + } + baseImg := decodeBase64PNG(t, baseRes.PNGBase64) + if baseImg.Bounds() != image.Rect(0, 0, 128, 64) { + t.Fatalf("decoded bounds = %v, want 128x64", baseImg.Bounds()) + } + assertPixel(t, baseImg, 10, 20, heroRGBA, "base hero top-left") + assertPixel(t, baseImg, 25, 35, heroRGBA, "base hero bottom-right") + assertPixel(t, baseImg, 18, 28, heroRGBA, "base hero interior") + assertPixel(t, baseImg, 9, 20, bgRGBA, "base outside hero left") + assertPixel(t, baseImg, 26, 20, bgRGBA, "base outside hero right") + assertPixel(t, baseImg, 60, 30, ballRGBA, "base ball top-left") + assertPixel(t, baseImg, 79, 49, ballRGBA, "base ball bottom-right") + assertPixel(t, baseImg, 112, 6, bgRGBA, "hidden layer sprite must not draw") + + // 2. Screenshot with sprite bounds + collision shapes enabled. + ovRes := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "width": 128, + "height": 64, + "bounds": true, + "collision_shapes": true, + }) + if !ovRes.OverlaysDrawn.Bounds || !ovRes.OverlaysDrawn.CollisionShapes { + t.Fatalf("expected bounds and collision_shapes overlays, got %+v", ovRes.OverlaysDrawn) + } + if ovRes.OverlaysDrawn.SpriteBounds != 2 || ovRes.OverlaysDrawn.PhysicsBoxes != 1 || ovRes.OverlaysDrawn.PhysicsCircles != 1 || ovRes.OverlaysDrawn.PhysicsTriggers != 1 || ovRes.OverlaysDrawn.PhysicsTiles != 2 { + t.Fatalf("unexpected overlay counts: %+v", ovRes.OverlaysDrawn) + } + + style := mcp.DefaultOverlayStyle() + boundsCol := coreColorToRGBA(style.BoundsColor) + boxCol := coreColorToRGBA(style.BoxColor) + circleCol := coreColorToRGBA(style.CircleColor) + triggerCol := coreColorToRGBA(style.TriggerColor) + solidTileCol := coreColorToRGBA(style.SolidTileColor) + oneWayCol := coreColorToRGBA(style.OneWayTileColor) + + ovImg := decodeBase64PNG(t, ovRes.PNGBase64) + + // Hero sprite bounds border aligned exactly with x=[10..25], y=[20..35]. + for _, pt := range [][2]int{{10, 20}, {25, 20}, {10, 35}, {25, 35}, {17, 20}, {17, 35}, {10, 28}, {25, 28}} { + assertPixel(t, ovImg, pt[0], pt[1], boundsCol, "hero bounds border") + } + // Immediately outside hero bounds remains untouched background. + for _, pt := range [][2]int{{9, 20}, {26, 20}, {10, 19}, {10, 36}} { + assertPixel(t, ovImg, pt[0], pt[1], bgRGBA, "outside hero bounds") + } + // Band between hero sprite bounds and inset physics box remains hero red. + assertPixel(t, ovImg, 11, 21, heroRGBA, "hero sprite band inside bounds") + assertPixel(t, ovImg, 24, 34, heroRGBA, "hero sprite band bottom-right") + + // Hero physics box border aligned exactly with x=[12..23], y=[22..33]. + for _, pt := range [][2]int{{12, 22}, {23, 22}, {12, 33}, {23, 33}, {17, 22}, {12, 28}} { + assertPixel(t, ovImg, pt[0], pt[1], boxCol, "hero physics box border") + } + // Interior of hero physics box remains hero red. + assertPixel(t, ovImg, 18, 28, heroRGBA, "hero physics box interior") + + // Ball sprite bounds corners aligned at x=[60..79], y=[30..49]. + for _, pt := range [][2]int{{60, 30}, {79, 30}, {60, 49}, {79, 49}} { + assertPixel(t, ovImg, pt[0], pt[1], boundsCol, "ball bounds corner") + } + // Ball circle collider cardinal points and +X orientation tick aligned with ball bounds. + for _, pt := range [][2]int{{79, 40}, {60, 40}, {70, 30}, {70, 49}, {74, 40}} { + assertPixel(t, ovImg, pt[0], pt[1], circleCol, "ball circle collider") + } + // Uncovered interior of ball stays blue. + assertPixel(t, ovImg, 65, 35, ballRGBA, "ball interior") + + // Trigger box at x=[90..101], y=[10..19]. + for _, pt := range [][2]int{{90, 10}, {101, 10}, {90, 19}, {101, 19}} { + assertPixel(t, ovImg, pt[0], pt[1], triggerCol, "trigger border") + } + assertPixel(t, ovImg, 95, 15, bgRGBA, "trigger interior") + + // Solid tile at x=[0..15], y=[48..63] and one-way tile top edge at y=48, x=[16..31]. + assertPixel(t, ovImg, 0, 48, solidTileCol, "solid tile top-left") + assertPixel(t, ovImg, 15, 63, solidTileCol, "solid tile bottom-right") + assertPixel(t, ovImg, 7, 55, bgRGBA, "solid tile interior") + assertPixel(t, ovImg, 16, 48, oneWayCol, "one-way tile top-left") + assertPixel(t, ovImg, 24, 48, oneWayCol, "one-way tile top-mid") + assertPixel(t, ovImg, 31, 48, oneWayCol, "one-way tile top-right") + assertPixel(t, ovImg, 32, 48, bgRGBA, "outside one-way tile right") +} + +func TestScreenshotCameraPanZoomAndViewportAlignment(t *testing.T) { + bgColor := core.RGB(0x182028) + bgRGBA := coreColorToRGBA(bgColor) + barColor := core.RGB(0x111111) + barRGBA := coreColorToRGBA(barColor) + actorRGBA := color.RGBA{R: 200, G: 70, B: 40, A: 255} + hudRGBA := color.RGBA{R: 180, G: 40, B: 200, A: 255} + + actorAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(16, 12, actorRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "player": {Name: "player", X: 0, Y: 0, W: 16, H: 12, Width: 16, Height: 12}, + }, + } + hudAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(8, 8, hudRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "heart": {Name: "heart", X: 0, Y: 0, W: 8, H: 8, Width: 8, Height: 8}, + }, + } + + // Virtual canvas 160x90 rendered into 320x240 via ModeFit: + // Scale = 2, letterbox bars top y=[0..29] and bottom y=[210..239], virtual rect origin = (0, 30). + vp := &screen.Viewport{ + Width: 160, + Height: 90, + Mode: screen.ModeFit, + BarColor: barColor, + } + + // Camera centered at world (50, 40) with Zoom=2 on virtual 160x90: + // WorldToView(wx, wy) = (80 + (wx - 50)*2, 45 + (wy - 40)*2) + // ViewToScreen(vx, vy) = (vx*2, 30 + vy*2) + cam := &tilemap.Camera{X: 50, Y: 40, Zoom: 2, Width: 160, Height: 90} + sc := scene.NewScene(cam) + + // World sprite at (42, 34) size 16x12: + // Virtual: [64, 96) x [33, 57) -> Screen: [128, 192) x [96, 144) -> pixels x=[128..191], y=[96..143]. + sp := sprite.NewSprite(actorAtlas.Frames["player"]) + sp.X, sp.Y = 42, 34 + worldLayer := scene.NewLayer("world", scene.SpaceWorld, 0) + worldLayer.AddBatch(&sprite.Batch{Atlas: actorAtlas, Sprites: []*sprite.Sprite{&sp}}) + sc.AddLayer(worldLayer) + + // HUD sprite in screen space at (4, 4) size 8x8: + // Unaffected by camera; under viewport -> Screen: [8, 24) x [38, 54) -> pixels x=[8..23], y=[38..53]. + hudSp := sprite.NewSprite(hudAtlas.Frames["heart"]) + hudSp.X, hudSp.Y = 4, 4 + hudLayer := scene.NewLayer("hud", scene.SpaceScreen, 10) + hudLayer.AddBatch(&sprite.Batch{Atlas: hudAtlas, Sprites: []*sprite.Sprite{&hudSp}}) + sc.AddLayer(hudLayer) + + // Inset physics box at (44, 36) size 12x8: + // Virtual: [68, 92) x [37, 53) -> Screen: [136, 184) x [104, 136) -> pixels x=[136..183], y=[104..135]. + pw := &physics.World{} + pw.Add(&physics.Body{ + Tag: "player", + Shape: physics.BoxShape(physics.Box{X: 44, Y: 36, W: 12, H: 8}), + }) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + Scene: sc, + Physics: pw, + Viewport: vp, + ScreenshotBackground: bgColor, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + res := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "width": 320, + "height": 240, + "overlays": map[string]any{ + "bounds": true, + "physics": true, + }, + }) + if res.Width != 320 || res.Height != 240 { + t.Fatalf("size = %dx%d, want 320x240", res.Width, res.Height) + } + if res.OverlaysDrawn.SpriteBounds != 2 || res.OverlaysDrawn.PhysicsBoxes != 1 { + t.Fatalf("overlays_drawn = %+v", res.OverlaysDrawn) + } + + style := mcp.DefaultOverlayStyle() + boundsCol := coreColorToRGBA(style.BoundsColor) + boxCol := coreColorToRGBA(style.BoxColor) + img := decodeBase64PNG(t, res.PNGBase64) + + // Letterbox bars remain intact. + assertPixel(t, img, 10, 10, barRGBA, "top letterbox bar") + assertPixel(t, img, 300, 225, barRGBA, "bottom letterbox bar") + + // World sprite + bounds outline aligned at exact zoomed/panned/letterboxed screen coords. + for _, pt := range [][2]int{{128, 96}, {191, 96}, {128, 143}, {191, 143}} { + assertPixel(t, img, pt[0], pt[1], boundsCol, "transformed world sprite bounds") + } + assertPixel(t, img, 127, 96, bgRGBA, "outside transformed sprite left") + assertPixel(t, img, 192, 96, bgRGBA, "outside transformed sprite right") + assertPixel(t, img, 130, 98, actorRGBA, "transformed sprite pixel inside bounds") + + // Physics box aligned inside transformed world sprite at x=[136..183], y=[104..135]. + for _, pt := range [][2]int{{136, 104}, {183, 104}, {136, 135}, {183, 135}} { + assertPixel(t, img, pt[0], pt[1], boxCol, "transformed physics box") + } + assertPixel(t, img, 160, 120, actorRGBA, "transformed physics box interior") + + // SpaceScreen HUD sprite + bounds aligned at x=[8..23], y=[38..53]. + for _, pt := range [][2]int{{8, 38}, {23, 38}, {8, 53}, {23, 53}} { + assertPixel(t, img, pt[0], pt[1], boundsCol, "screen-space HUD sprite bounds") + } + assertPixel(t, img, 15, 45, hudRGBA, "screen-space HUD sprite interior") + + // Also verify grid, camera and labels overlays execute cleanly and draw within the viewport clip. + fullRes := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "width": 320, + "height": 240, + "overlays": map[string]any{ + "bounds": true, + "physics": true, + "grid": true, + "grid_step": 16, + "camera": true, + "labels": true, + }, + }) + if !fullRes.OverlaysDrawn.Grid || !fullRes.OverlaysDrawn.Camera || !fullRes.OverlaysDrawn.Labels { + t.Fatalf("expected grid/camera/labels flags set: %+v", fullRes.OverlaysDrawn) + } + fullImg := decodeBase64PNG(t, fullRes.PNGBase64) + // Letterbox bar must still be completely untouched (clipped by viewport). + assertPixel(t, fullImg, 160, 5, barRGBA, "top letterbox bar clipped against grid/camera/labels") + // Camera crosshair at center of virtual rect (160, 120). + assertPixel(t, fullImg, 160, 120, coreColorToRGBA(style.CameraColor), "camera center crosshair") +} + +func TestScreenshotParallaxScaledOriginAndSceneManager(t *testing.T) { + bgColor := core.RGB(0x0c1018) + cloudRGBA := color.RGBA{R: 190, G: 210, B: 240, A: 255} + scaledRGBA := color.RGBA{R: 230, G: 140, B: 40, A: 255} + titleRGBA := color.RGBA{R: 90, G: 200, B: 110, A: 255} + + cloudAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(10, 10, cloudRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "cloud": {Name: "cloud", X: 0, Y: 0, W: 10, H: 10, Width: 10, Height: 10}, + }, + } + scaledAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(8, 8, scaledRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "crate": {Name: "crate", X: 0, Y: 0, W: 8, H: 8, Width: 8, Height: 8, PivotX: 4, PivotY: 4}, + }, + } + titleAtlas := &sprite.Atlas{ + Image: core.ImageSource{Pixels: solidSpriteImage(12, 6, titleRGBA), Version: 1}, + Frames: map[string]sprite.Frame{ + "logo": {Name: "logo", X: 0, Y: 0, W: 12, H: 6, Width: 12, Height: 6}, + }, + } + + // Camera at (40, 20) in a 100x80 view: center=(50, 40). + cam := &tilemap.Camera{X: 40, Y: 20, Zoom: 1, Width: 100, Height: 80} + gameScene := scene.NewScene(cam) + + // Parallax layer (0.5, 0.5) with Offset (6, 4): + // pcam.X = 40*0.5 - 6 = 14, pcam.Y = 20*0.5 - 4 = 6. + // Screen offset = (50 - 14, 40 - 6) = (36, 34). + // Cloud at (0, 0) size 10x10 -> screen [36..45] x [34..43]. + parallaxLayer := scene.NewParallaxLayer("clouds", -5, 0.5, 0.5) + parallaxLayer.OffsetX, parallaxLayer.OffsetY = 6, 4 + cloud := sprite.NewSprite(cloudAtlas.Frames["cloud"]) + cloud.X, cloud.Y = 0, 0 + parallaxLayer.AddBatch(&sprite.Batch{Atlas: cloudAtlas, Sprites: []*sprite.Sprite{&cloud}}) + gameScene.AddLayer(parallaxLayer) + + // World layer with centered-origin 2x-scaled sprite at (40, 20): + // Bounds in world = [40 - 8, 40 + 8) x [20 - 8, 20 + 8) = [32, 48) x [12, 28). + // Under cam (40, 20) -> screen [42..57] x [32..47]. + worldLayer := scene.NewLayer("actors", scene.SpaceWorld, 0) + crate := sprite.NewSprite(scaledAtlas.Frames["crate"]) + crate.X, crate.Y = 40, 20 + crate.ScaleX, crate.ScaleY = 2, 2 + worldLayer.AddBatch(&sprite.Batch{Atlas: scaledAtlas, Sprites: []*sprite.Sprite{&crate}}) + gameScene.AddLayer(worldLayer) + + // Transparent pause overlay scene on top of gameScene. + pauseScene := scene.NewScene(nil) + pauseLayer := scene.NewLayer("pause_hud", scene.SpaceScreen, 0) + pauseScene.AddLayer(pauseLayer) + + // Inactive named scene "title". + titleScene := scene.NewScene(nil) + titleLayer := scene.NewLayer("title_ui", scene.SpaceScreen, 0) + logo := sprite.NewSprite(titleAtlas.Frames["logo"]) + logo.X, logo.Y = 10, 10 // screen [10..21] x [10..15] + titleLayer.AddBatch(&sprite.Batch{Atlas: titleAtlas, Sprites: []*sprite.Sprite{&logo}}) + titleScene.AddLayer(titleLayer) + + gameCtrl := &scene.Controller{Scene: gameScene} + pauseCtrl := &scene.Controller{Scene: pauseScene, Transparent: true} + names := map[*scene.Controller]string{gameCtrl: "gameplay", pauseCtrl: "pause"} + + pw := &physics.World{} + pw.Add(&physics.Body{Shape: physics.BoxShape(physics.Box{X: 34, Y: 14, W: 12, H: 12})}) // screen [44..55] x [34..45] + + var ( + cx *core.Scope + mgr *scene.Manager + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + mgr = scene.NewManager(cx) + mgr.Switch(gameCtrl, nil) + mgr.Push(pauseCtrl) + if _, err := mcp.Attach(cx, mcp.Config{ + Scenes: mgr, + SceneName: func(c *scene.Controller) string { return names[c] }, + NamedScenes: map[string]*scene.Scene{"title": titleScene}, + PhysicsFunc: func() *physics.World { return pw }, + ViewSizeFunc: func() core.Size { return core.Size{Width: 100, Height: 80} }, + ScreenshotBackground: bgColor, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Capturing active transparent stack draws underlying gameplay scene + parallax + scaled sprite + physics box. + res := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "bounds": true, + "collision_shapes": true, + }) + if res.Width != 100 || res.Height != 80 || res.Scene != "pause" { + t.Fatalf("transparent stack result = %+v", res) + } + if res.OverlaysDrawn.SpriteBounds != 2 || res.OverlaysDrawn.PhysicsBoxes != 1 { + t.Fatalf("overlays_drawn = %+v", res.OverlaysDrawn) + } + style := mcp.DefaultOverlayStyle() + boundsCol := coreColorToRGBA(style.BoundsColor) + boxCol := coreColorToRGBA(style.BoxColor) + img := decodeBase64PNG(t, res.PNGBase64) + + // Parallax cloud bounds at [36..45] x [34..43]. + assertPixel(t, img, 36, 34, boundsCol, "parallax cloud top-left") + assertPixel(t, img, 36, 43, boundsCol, "parallax cloud bottom-left") + assertPixel(t, img, 39, 39, cloudRGBA, "parallax cloud interior") + + // Centered-origin 2x-scaled crate bounds at [42..57] x [32..47], with inset physics box at [44..55] x [34..45]. + for _, pt := range [][2]int{{42, 32}, {57, 32}, {42, 47}, {57, 47}} { + assertPixel(t, img, pt[0], pt[1], boundsCol, "scaled crate bounds") + } + for _, pt := range [][2]int{{44, 34}, {55, 34}, {44, 45}, {55, 45}} { + assertPixel(t, img, pt[0], pt[1], boxCol, "crate physics box") + } + assertPixel(t, img, 50, 40, scaledRGBA, "crate interior") + + // Capturing an inactive named scene directly via "scene": "title". + titleRes := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "scene": "title", + "width": 40, + "height": 30, + "bounds": true, + }) + if titleRes.Scene != "title" || titleRes.OverlaysDrawn.SpriteBounds != 1 { + t.Fatalf("named scene capture = %+v", titleRes) + } + titleImg := decodeBase64PNG(t, titleRes.PNGBase64) + assertPixel(t, titleImg, 10, 10, boundsCol, "title logo top-left bounds") + assertPixel(t, titleImg, 21, 15, boundsCol, "title logo bottom-right bounds") + assertPixel(t, titleImg, 15, 12, titleRGBA, "title logo interior") +} + +func TestScreenshotCaptureFrameDrawFrameAndDiskOutput(t *testing.T) { + // 1. CaptureFrame: overlays composite onto cloned frame without mutating caller's image. + srcImg := solidSpriteImage(80, 60, color.RGBA{R: 30, G: 40, B: 50, A: 255}) + pw := &physics.World{} + pw.Add(&physics.Body{Shape: physics.BoxShape(physics.Box{X: 10, Y: 10, W: 20, H: 15})}) + + shotsDir := t.TempDir() + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + Physics: pw, + CaptureFrame: func(context.Context) (*image.RGBA, error) { + return srcImg, nil + }, + ScreenshotDir: shotsDir, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Dimensions are inferred automatically from CaptureFrame; path writes PNG inside ScreenshotDir. + diskRes := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "collision_shapes": true, + "path": "nested/frame1.png", + }) + if diskRes.Width != 80 || diskRes.Height != 60 || diskRes.Path != "nested/frame1.png" || diskRes.PNGBase64 != "" { + t.Fatalf("disk screenshot result = %+v", diskRes) + } + onDisk, err := os.ReadFile(filepath.Join(shotsDir, "nested", "frame1.png")) + if err != nil { + t.Fatalf("read written screenshot: %v", err) + } + if len(onDisk) != diskRes.Bytes { + t.Fatalf("file bytes = %d, reported = %d", len(onDisk), diskRes.Bytes) + } + diskImg := decodePNGBytes(t, onDisk) + boxCol := coreColorToRGBA(mcp.DefaultOverlayStyle().BoxColor) + assertPixel(t, diskImg, 10, 10, boxCol, "CaptureFrame overlay box top-left") + assertPixel(t, diskImg, 29, 24, boxCol, "CaptureFrame overlay box bottom-right") + // Source image returned by CaptureFrame must NOT be mutated. + assertPixel(t, srcImg, 10, 10, color.RGBA{R: 30, G: 40, B: 50, A: 255}, "CaptureFrame source image unmodified") + + // 2. DrawFrame + RigidPhysics (rotated box and circle). + rw := &physics.RigidWorld{} + rb := physics.NewRigidBox(32, 24, 16, 10, 1) + rb.Angle = math.Pi / 4 + rc := physics.NewRigidCircle(60, 24, 8, 1) + rw.AddBody(rb, rc) + + var cx2 *core.Scope + app2 := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx2 = scope + if _, err := mcp.Attach(cx2, mcp.Config{ + RigidPhysics: rw, + DrawFrame: func(d *core.Drawing, w, h int) { + d.SetFillColor(core.RGB(0x202020)).FillRect(0, 0, float32(w), float32(h)) + }, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + rigidRes := callTool[mcp.ScreenshotResult](t, app2, cx2, mcp.ToolScreenshot, map[string]any{ + "width": 96, + "height": 48, + "collision_shapes": true, + }) + if rigidRes.OverlaysDrawn.PhysicsBoxes != 1 || rigidRes.OverlaysDrawn.PhysicsCircles != 1 { + t.Fatalf("rigid overlays = %+v", rigidRes.OverlaysDrawn) + } + rigidImg := decodeBase64PNG(t, rigidRes.PNGBase64) + circleCol := coreColorToRGBA(mcp.DefaultOverlayStyle().CircleColor) + assertPixel(t, rigidImg, 67, 24, circleCol, "rigid circle +X edge") + assertPixel(t, rigidImg, 52, 24, circleCol, "rigid circle -X edge") +} + +func TestScreenshotValidationAndGracefulNilHandling(t *testing.T) { + sc := scene.NewScene(&tilemap.Camera{X: 32, Y: 24, Width: 64, Height: 48}) + shotsDir := t.TempDir() + + var ( + cx *core.Scope + win core.Size + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + win = scope.Env().Window() + if _, err := mcp.Attach(cx, mcp.Config{ + Scene: sc, + ScreenshotDir: shotsDir, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + if win.Width <= 0 || win.Height <= 0 { + t.Fatalf("test window size = %v", win) + } + + // Graceful nil Physics: collision_shapes: true succeeds with 0 shapes drawn, dimensions inferred from the window as game_input_pointer maps them. + graceful := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{ + "bounds": true, + "collision_shapes": true, + }) + if graceful.Width != int(math.Round(float64(win.Width))) || graceful.Height != int(math.Round(float64(win.Height))) || graceful.OverlaysDrawn.PhysicsBoxes != 0 || graceful.OverlaysDrawn.SpriteBounds != 0 { + t.Fatalf("graceful nil physics/empty scene = %+v", graceful) + } + + // Unknown top-level and nested fields refused. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, `{"bogus":true}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("unknown top-level field = %v, want unknown field error", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, `{"overlays":{"bogus":true}}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("unknown nested field = %v, want unknown field error", err) + } + + // Unsupported format refused. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"format": "jpeg"}); err == nil || !strings.Contains(err.Error(), "unsupported screenshot format") { + t.Fatalf("bad format = %v", err) + } + + // Invalid dimensions refused. + for _, bad := range []map[string]any{ + {"width": -10, "height": 10}, + {"width": 10, "height": -10}, + {"width": 64}, + {"height": 48}, + {"width": 9000, "height": 9000}, + {"width": 8192, "height": 2049}, + } { + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, bad); err == nil { + t.Errorf("expected error for bad dimensions %v", bad) + } + } + + // Negative grid_step refused. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{ + "overlays": map[string]any{"grid": true, "grid_step": -8}, + }); err == nil { + t.Fatal("expected error for negative grid_step") + } + + // Unknown scene name refused. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"scene": "does_not_exist"}); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("unknown scene = %v", err) + } + + // Path traversal and unsafe paths refused. + for _, badPath := range []string{"../escape.png", "a/../../escape.png", "/tmp/abs.png", ".", "..", `sub\win.png`, "C:shot.png", "notes.txt", "shot"} { + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"path": badPath}); err == nil { + t.Errorf("expected error for unsafe path %q", badPath) + } + } + + // Unconfigured bridge (no ScreenshotDir, no Scene/Physics/DrawFrame/CaptureFrame). + var cxEmpty *core.Scope + appEmpty := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cxEmpty = scope + if _, err := mcp.Attach(cxEmpty, mcp.Config{}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + if _, err := callToolRaw(t, appEmpty, cxEmpty, mcp.ToolScreenshot, map[string]any{"width": 32, "height": 32, "path": "a.png"}); err == nil || !strings.Contains(err.Error(), "ScreenshotDir") { + t.Fatalf("path without ScreenshotDir = %v", err) + } + if _, err := callToolRaw(t, appEmpty, cxEmpty, mcp.ToolScreenshot, nil); err == nil || !strings.Contains(err.Error(), "no screenshot source") { + t.Fatalf("no source, no dimensions = %v", err) + } + if _, err := callToolRaw(t, appEmpty, cxEmpty, mcp.ToolScreenshot, map[string]any{"width": 32, "height": 32}); err == nil || !strings.Contains(err.Error(), "no screenshot source") { + t.Fatalf("no source = %v", err) + } +} + +func TestScreenshotCaptureFrameHiDPIViewportAlignment(t *testing.T) { + // A 160x90 integer-scaled viewport in a 400x225-point view at a 2x pixel ratio: the game scales by 2 points (4 pixels) with the canvas at (40, 22.5) points. Laying the viewport out on the 800x450 image instead would pick scale 5. + vp := &screen.Viewport{Width: 160, Height: 90, IntegerScale: true} + pw := &physics.World{} + pw.Add(&physics.Body{Shape: physics.BoxShape(physics.Box{X: 10, Y: 10, W: 20, H: 15})}) + bg := color.RGBA{R: 30, G: 40, B: 50, A: 255} + captured := solidSpriteImage(800, 450, bg) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + Physics: pw, + ViewportFunc: func() screen.Viewport { return *vp }, + ViewSizeFunc: func() core.Size { return core.Size{Width: 400, Height: 225} }, + CaptureFrame: func(context.Context) (*image.RGBA, error) { return captured, nil }, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + res := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, map[string]any{"collision_shapes": true}) + if res.Width != 800 || res.Height != 450 || res.OverlaysDrawn.PhysicsBoxes != 1 { + t.Fatalf("hidpi capture = %+v", res) + } + img := decodeBase64PNG(t, res.PNGBase64) + boxCol := coreColorToRGBA(mcp.DefaultOverlayStyle().BoxColor) + // Box [10, 30) x [10, 25) virtual -> [60, 100) x [42.5, 72.5) points -> [120, 200) x [85, 145) pixels. + assertPixel(t, img, 120, 85, boxCol, "hidpi box top-left") + assertPixel(t, img, 199, 144, boxCol, "hidpi box bottom-right") + assertPixel(t, img, 119, 85, bg, "hidpi left of box") + assertPixel(t, img, 120, 84, bg, "hidpi above box") +} + +func TestScreenshotPartialRasterAndLimits(t *testing.T) { + // A 4x4-pixel image measuring 2x2 points: left half red, right half blue. + red := color.RGBA{R: 255, A: 255} + blue := color.RGBA{B: 255, A: 255} + half := image.NewRGBA(image.Rect(0, 0, 4, 4)) + for y := range 4 { + for x := range 4 { + if x < 2 { + half.SetRGBA(x, y, red) + } else { + half.SetRGBA(x, y, blue) + } + } + } + sized := &core.ImageSource{Pixels: half, Size: core.Size{Width: 2, Height: 2}} + uri := &core.ImageSource{URI: "asset:sprites/hero.png"} + + sc := scene.NewScene(nil) + custom := &scene.Controller{Draw: func(*core.Drawing, float64) {}} + gameplay := &scene.Controller{Scene: sc} + names := map[*scene.Controller]string{custom: "custom", gameplay: "gameplay"} + + outside := t.TempDir() + shotsDir := t.TempDir() + if err := os.Symlink(outside, filepath.Join(shotsDir, "out")); err != nil { + t.Skipf("symlinks unavailable: %v", err) + } + + var ( + cx *core.Scope + viewSize = core.Size{Width: 8, Height: 8} + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + mgr := scene.NewManager(cx) + mgr.Switch(gameplay, nil) + mgr.Push(custom) + if _, err := mcp.Attach(cx, mcp.Config{ + Scenes: mgr, + SceneName: func(c *scene.Controller) string { return names[c] }, + ViewSizeFunc: func() core.Size { return viewSize }, + ScreenshotDir: shotsDir, + DrawFrame: func(d *core.Drawing, w, h int) { + d.Ops = append(d.Ops, + core.DrawOp{Kind: core.DrawImage, Image: sized}, + core.DrawOp{Kind: core.DrawImage, Image: uri, X: 4, Y: 4}, + core.DrawOp{Kind: core.DrawFillText, Text: "HP"}, + core.DrawOp{Kind: core.DrawEllipse, X: 4, Y: 4, R: 2, RY: 2}, + ) + }, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Image Size: the source is read in its points, so the 2-point image covers 2 pixels and its right half shows at x=1. + res := callTool[mcp.ScreenshotResult](t, app, cx, mcp.ToolScreenshot, nil) + if res.Width != 8 || res.Height != 8 { + t.Fatalf("partial raster dims = %+v", res) + } + img := decodeBase64PNG(t, res.PNGBase64) + assertPixel(t, img, 0, 0, red, "sized image left point") + assertPixel(t, img, 1, 0, blue, "sized image right point") + assertPixel(t, img, 2, 0, color.RGBA{}, "sized image ends at 2 points") + // What the rasterizer left out is reported. + if res.SkippedImages != 1 || res.SkippedOps["DrawFillText"] != 1 || res.SkippedOps["DrawEllipse"] != 1 || len(res.SkippedOps) != 2 { + t.Fatalf("skipped = %d images, ops %v", res.SkippedImages, res.SkippedOps) + } + + // A named scene without a scene.Scene is refused rather than rendered blank. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"scene": "custom"}); err == nil || !strings.Contains(err.Error(), "custom Controller.Draw") { + t.Fatalf("scene without Scene = %v", err) + } + + // Inferred dimensions are bounded like explicit ones, and non-finite sizes are refused. + for _, size := range []core.Size{ + {Width: 10000, Height: 100}, + {Width: 8192, Height: 2049}, + {Width: core.Points(math.Inf(1)), Height: 100}, + } { + viewSize = size + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, nil); err == nil || !strings.Contains(err.Error(), "screenshot dimensions") { + t.Errorf("inferred size %v = %v, want a dimensions error", size, err) + } + } + viewSize = core.Size{Width: 8, Height: 8} + + // A symbolic link inside ScreenshotDir cannot lead the write outside it. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"path": "out/escape.png"}); err == nil { + t.Fatal("write through a symlink leaving ScreenshotDir succeeded") + } + if _, err := os.Stat(filepath.Join(outside, "escape.png")); !os.IsNotExist(err) { + t.Fatalf("file written outside ScreenshotDir: %v", err) + } + + // grid_step at the top level matches the nested form, and conflicting values are refused. + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"grid": true, "grid_step": 4}); err != nil { + t.Fatalf("top-level grid_step = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolScreenshot, map[string]any{"grid": true, "grid_step": 4, "overlays": map[string]any{"grid_step": 8}}); err == nil || !strings.Contains(err.Error(), "disagree") { + t.Fatalf("conflicting grid_step = %v", err) + } +}