From 89c5b523d3b373da2fc482ec959b0ae01b8874f9 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 20:16:50 +0900 Subject: [PATCH 1/4] feat(editor): add Spec viewport overlays and toggle legend (#1006) --- ...26-editor-spec-viewport-overlays-legend.md | 46 + .../public/schemas/editor-settings.v1.json | 7 + changelog.d/editor-viewport-overlays-1006.md | 9 + docs/en/editor.md | 21 +- docs/en/formats.md | 7 + docs/zh/editor.md | 21 +- docs/zh/formats.md | 7 + packages/game/editor/editormcp/tools.go | 4 +- packages/game/editor/gizmo2d.go | 33 +- packages/game/editor/locales/en.yaml | 7 + packages/game/editor/locales/zh.yaml | 7 + packages/game/editor/overlays.go | 7 +- packages/game/editor/problems.go | 7 +- packages/game/editor/problems_fix.go | 101 +- packages/game/editor/settings.go | 39 + packages/game/editor/snap.go | 5 +- packages/game/editor/spec_feedback_ui.go | 771 +++++----- packages/game/editor/state.go | 15 +- .../testdata/golden/viewport_overlays_1x.png | Bin 0 -> 12580 bytes .../testdata/golden/viewport_overlays_2x.png | Bin 0 -> 34209 bytes packages/game/editor/viewport.go | 267 ++-- packages/game/editor/viewport3d.go | 47 +- packages/game/editor/viewport_overlay.go | 1265 +++++++++++++++++ packages/game/editor/viewport_overlay_test.go | 825 +++++++++++ packages/game/gametest/golden.go | 74 +- packages/game/gametest/golden_shapes.go | 267 ++++ .../game/tooling/assetcheck/assetcheck.go | 28 +- .../tooling/assetcheck/assetcheck_test.go | 31 + .../tooling/assetcheck/connections_test.go | 10 +- packages/game/tooling/assetcheck/scene.go | 246 +++- 30 files changed, 3473 insertions(+), 701 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-26-editor-spec-viewport-overlays-legend.md create mode 100644 changelog.d/editor-viewport-overlays-1006.md create mode 100644 packages/game/editor/testdata/golden/viewport_overlays_1x.png create mode 100644 packages/game/editor/testdata/golden/viewport_overlays_2x.png create mode 100644 packages/game/editor/viewport_overlay.go create mode 100644 packages/game/editor/viewport_overlay_test.go create mode 100644 packages/game/gametest/golden_shapes.go diff --git a/.agents/notes/implemented/feature/2026-11-26-editor-spec-viewport-overlays-legend.md b/.agents/notes/implemented/feature/2026-11-26-editor-spec-viewport-overlays-legend.md new file mode 100644 index 000000000..fdcf4c893 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-26-editor-spec-viewport-overlays-legend.md @@ -0,0 +1,46 @@ +# Agent Note: Spec viewport overlays, toggle legend, and object-level problem attribution + +Status: implemented + +## Problem + +Viewport overlays in the 2D and 3D scene editors previously used ad-hoc colors and line styles (such as a hardcoded `0x38BDF8` selection polygon, separate 3D selection/wireframe colors, and inline drawing code for agent tasks and problems), with no single Spec-compliant drawing helper for the seven semantic overlay kinds in `docs/design/editor/Spec.dc.html`, no shared top-left toggle legend persisted per person, no reduced-motion handling for change fades and agent pulses, and no object ID on `assetcheck.Problem` when scene diagnostics reported only a file and line (#1006). + +## Decision + +Centralize every Spec semantic viewport overlay behind `DrawObjectOverlay`, expose a shared top-left toggle legend persisted in per-user `EditorSettings`, attach `Object` directly to `assetcheck.Problem`, and migrate non-semantic viewport guides (camera frame, camera bounds, tile grid, snap grid) to neutral `SpecPalette` hairline/dotted tokens. + +### Single Spec overlay helper and live API (`packages/game/editor/viewport_overlay.go`) +- `DrawObjectOverlay(d, SpecPalette, ObjectOverlay)` renders all seven `OverlayKind` values exclusively from `SpecPalette` tokens at the Spec's exact widths and non-color second cues: + - `OverlayKindSelection`: `Accent`, 1.5 px solid, four 8×8 corner handles, and accent name tag (person's selection only). + - `OverlayKindAgent`: `Agent`, 1.5 px solid, no handles, 1.6 s pulse between 100% and 45% (`OverlayAgentPulseAlpha`), dark pill with 4-point sparkle glyph or numbered task badge (`Holding` variant uses 45% dashed outline + clock glyph). + - `OverlayKindAdded`: `Added`, 1.5 px dashed (`5, 3`), dark pill with `"+ "`. + - `OverlayKindChanged`: `Changed`, 1.5 px dashed (`5, 3`), dark pill with `"field old → new"`. + - `OverlayKindRemoved`: `Removed`, 1.5 px solid around a 25% grey ghost (`TextFaint` at 25%), dark pill with struck-through name + `"removed"`. + - `OverlayKindProblem`: `Problem`, 2 px solid on the live object, filled `Problem.Fg`/`Problem.OnFill` pill with alert triangle glyph and message (never resembling a removed ghost). + - `OverlayKindFocusedChange`: renders its base `ChangeKind` color and dash at 2.5 px with a full-opacity outlined pill, never `Accent`. +- When `PairedWithSelection` is set on `OverlayKindAgent`, the agent outline expands an extra `OverlaySelectionAgentGap` (3 px) outside Selection's outline so Selection keeps its corner handles unobstructed and the agent pill stacks above. +- Change overlays fade in over 240 ms (`OverlayFadeAlpha`); when `ReduceMotion` is active (`Scope.Env().ReduceMotion()` or `Editor.SetReduceMotion(true)`), fades resolve immediately to 100%, agent outlines stay solid at 100%, and `viewport.go` skips scheduling the 33 ms `overlayAnimRev` timer. +- `SceneOverlayEntry` and `Editor.SetSceneOverlays` / `AddSceneOverlay` / `RemoveSceneOverlay` / `ClearSceneOverlays` provide the live scene API for agent edits, reviews, and plans in both 2D (`drawSceneOverlays2D`) and 3D (`drawSceneOverlays3D`). + +### Shared top-left toggle legend and per-user persistence (`spec_feedback_ui.go`, `settings.go`, `apps/website/public/schemas/editor-settings.v1.json`) +- `viewportOverlayLegendView` mounts in the top-left corner of the shared viewport container (`viewport.go`) for both 2D and 3D edit modes, rendering six `core.RoleSwitch` rows (`legend-selection`, `legend-agent`, `legend-added`, `legend-changed`, `legend-removed`, `legend-problem`) with drawn line-style + second-cue swatches. +- `EditorSettings.OverlayLegend` (`*[]string`, `yaml:"overlayLegend,omitempty"`) follows the same pointer-to-slice persistence pattern as `ViewportOverlays` in [2026-11-26-editor-viewport-overlays.md](./2026-11-26-editor-viewport-overlays.md): `nil` omits the key and enables all six kinds by default, while `&[]string{}` serializes `overlayLegend: []` so turning all six rows off survives restart without mutating project or scene files. Unknown or duplicate values are refused by `ParseEditorSettings`. +- `OverlayKindProblem` stays synchronized with `Editor.ProblemOverlayVisible()` (see [2026-11-26-editor-live-problems-agent-fix.md](./2026-11-26-editor-live-problems-agent-fix.md)), and `SpecOverlayLegendView` (see [2026-11-26-editor-spec-light-theme.md](./2026-11-26-editor-spec-light-theme.md)) draws every card through `DrawObjectOverlay`. + +### Object-level problem attribution and neutral guides (`tooling/assetcheck/assetcheck.go`, `scene.go`, `viewport.go`, `viewport3d.go`, `overlays.go`, `snap.go`) +- `assetcheck.Problem` adds `Object string` (and `editormcp.Problem` exposes `object`), populated by `sceneChecker.withObject` during scene/component/asset traversal and by `yamlFieldErrorObject` for `sceneformat.FieldError` paths (including `layers[*].objects[*]`, `overrides.`, and `connections[*]` live endpoints). `Editor.attributeProblemObject` checks `p.Object` first before falling back to message regex and line spans. +- Camera frame, camera bounds, camera tether, tile grid, snap grid, and 3D grid/wireframe use neutral `SpecPalette` `TextMuted`/`TextFaint` 1 px hairlines and `2, 4` dotted strokes so no guide shares a color or dash style with the semantic legend. +- `gametest.RenderOps` (`gametest/golden.go`, `golden_shapes.go`) adds `DrawRoundRect`, `DrawArc`, `DrawEllipse`, `DrawLineDash`, scaled dash/line widths, and deterministic 5×7 bitmap text rendering so 1x and 2x golden-image tests verify every Spec overlay primitive headlessly. + +## Alternatives considered + +1. **Keeping separate 2D and 3D overlay drawing code paths**: 3D already drew wireframe bounding boxes and dots directly in `viewport3d.go`. Rejected because Selection, Agent, Problem, and diff overlays would drift in stroke width, pill layout, reduced-motion behavior, and legend toggles across 2D and 3D. Projecting 3D object corners to canvas bounds and calling `DrawObjectOverlay` keeps both viewports identical. +2. **Storing legend toggles inside `ViewportOverlays` (`SHOW IN VIEWPORT` popover)**: Combining semantic overlay kinds with scene-inspection overlays (`collision_shapes`, `connections`, `navigation`) would avoid a new `EditorSettings` field, but `Spec.dc.html` and `Main.dc.html` place the six semantic kinds in a dedicated top-left legend with explicit line-style swatches separate from the bottom-center inspection bar. Separate `overlayLegend` persistence keeps both independent and backward compatible. +3. **Inferring Problem object IDs solely in `editor` by re-parsing YAML**: Avoiding a field on `assetcheck.Problem` would keep `assetcheck` untouched, but `assetcheck` already walks every scene object, override, and `FieldError` path during validation; emitting `Problem.Object` at the source eliminates fragile regex heuristics and makes object attribution available to `editormcp`'s `game_check` too. + +## Consequences + +- **Benefits**: One Spec-compliant overlay renderer across 2D and 3D viewports, greyscale-distinguishable semantic cues, instant reduced-motion compliance, persistent per-user legend switches outside project files, exact object-level Problem overlays, and 1x/2x golden-image + native macOS screenshot coverage. +- **Costs**: `gametest.RenderOps` now maintains software rasterizers for rounded rects, arcs, dashed strokes, and 5×7 bitmap glyphs for golden comparisons (so changes to overlay geometry or styling require intentional `-update-golden` updates to `viewport_overlays_1x.png` and `viewport_overlays_2x.png`). +- **Verification**: `packages/game/editor/viewport_overlay_test.go` verifies 1x and 2x golden images, pairwise greyscale distinguishability, Selection+Agent 3 px offset, 240 ms fade / 1.6 s pulse / reduced-motion static rendering, 2D+3D legend toggles and restart persistence (including `[]` and invalid YAML refusal), live Problems panel integration in 2D and 3D, neutral camera/grid tokens, and native macOS Dark/Light `nsgotest` screenshots; `packages/game/tooling/assetcheck/assetcheck_test.go` and `connections_test.go` verify `Problem.Object`. diff --git a/apps/website/public/schemas/editor-settings.v1.json b/apps/website/public/schemas/editor-settings.v1.json index f81011d64..9f3b2d382 100644 --- a/apps/website/public/schemas/editor-settings.v1.json +++ b/apps/website/public/schemas/editor-settings.v1.json @@ -76,6 +76,13 @@ "type": "string" } }, + "overlayLegend": { + "description": "OverlayLegend lists the enabled Spec viewport overlay legend kinds (\"selection\", \"agent\", \"added\", \"changed\", \"removed\", \"problem\") in canonical sorted order. When omitted, all six legend kinds are enabled by default; an empty list hides all six kinds.", + "type": "array", + "items": { + "type": "string" + } + }, "shortcuts": { "description": "Shortcuts overrides default command shortcuts keyed by command ID (for example \"view.frame\": \"g\"). An empty string explicitly unbinds a command.", "type": "object", diff --git a/changelog.d/editor-viewport-overlays-1006.md b/changelog.d/editor-viewport-overlays-1006.md new file mode 100644 index 000000000..60847fcd2 --- /dev/null +++ b/changelog.d/editor-viewport-overlays-1006.md @@ -0,0 +1,9 @@ +### Added + +- `game/editor`: unified Spec viewport overlay renderer (`DrawObjectOverlay`) and live overlay API (`SceneOverlayEntry`, `SetSceneOverlays`) supporting all seven Spec overlay kinds (Selection, Agent working, Added, Changed, Removed, Problem, Focused change in Review) with non-color second cues, Selection+Agent 3 px outer pairing, 240 ms change fade-in, 1.6 s Agent pulse, and reduced-motion static rendering (#1006). +- `game/editor`: shared top-left viewport overlay legend (`viewport-overlay-legend`) across 2D and 3D viewports with six `role="switch"` toggles persisted per user under `overlayLegend` in `EditorSettings` (`editor-settings.v1.json`) (#1006). +- `game/tooling/assetcheck`: populate `Problem.Object` on scene object, component, override, and connection diagnostics (and expose `object` in `editormcp`'s `game_check`) so live Problem overlays attach directly to objects in the open scene (#1006). + +### Changed + +- `game/editor`: switch 2D and 3D selection outlines to the Spec style (1.5 px solid accent, four corner handles, name tag) and move camera frame, camera bounds, tile grid, and snap grid to neutral `SpecPalette` hairline/dotted tokens distinct from all legend kinds (#1006). diff --git a/docs/en/editor.md b/docs/en/editor.md index 5aa0ea426..c928e5e02 100644 --- a/docs/en/editor.md +++ b/docs/en/editor.md @@ -1140,7 +1140,7 @@ The Particle Emitter Editor (`ParticleEditorPanelView`), opened from the toolbar The editor UI is localized in English (`en`) and Simplified Chinese (`zh`) through embedded versioned `l10n` YAML string tables (`editor/locales/en.yaml`, `editor/locales/zh.yaml`), and per-user preferences are stored outside any project as deterministic versioned YAML: -- **Per-user settings file (`EditorSettings`, `SettingsVersion = 1`, #921, #1005, #1028)**: stored at `DefaultSettingsPath()` (under `os.UserConfigDir()` as `nsgo-game/editor.yaml`, outside every game project) and loaded/saved with `ParseEditorSettings`, `EncodeEditorSettings`, `LoadEditorSettings`, `SaveEditorSettings`, `Editor.LoadSettings`, `Editor.LoadUserSettings`, and `Editor.SaveSettings`. It stores `version`, `language`, `appearance`, optional `autoSave` (defaults to `true` when omitted), optional `interfaceSize` (`compact`, `default`, or `large`), optional `snap` (per-person defaults for `grid`, `gridSize`, `pixel`, `rotation`, `rotationStepDeg`, `scale`, `scaleStep`, and `showGrid`, used when a project does not override snap in `.game/editor.yaml`), optional `showAgentChanges` (defaults to `true` when omitted), optional `navigation3D` (`default`, `blender`, or `maya`), optional `viewportOverlays` (canonical sorted list of enabled 2D viewport overlay IDs; omitted for defaults, `[]` for all off), optional `shortcuts`, optional `seenTips`, and optional `agent` preferences (task routing, MCP tool toggles, external MCP servers, weekly request limit, outbound privacy switches, and local usage counters; secrets such as API keys are never stored in `editor.yaml`). Unknown keys, YAML anchors/aliases/merge keys, trailing documents, negative/non-finite snap steps, and invalid enum values are refused with `*loaderr.Error`. Output is deterministic 2-space YAML prefixed with `SettingsSchemaComment` so a load-save round trip changes nothing byte-for-byte. Its published JSON Schema is `https://game.nsgo.dev/schemas/editor-settings.v1.json` (`SettingsSchemaURL`). +- **Per-user settings file (`EditorSettings`, `SettingsVersion = 1`, #921, #1005, #1006, #1028)**: stored at `DefaultSettingsPath()` (under `os.UserConfigDir()` as `nsgo-game/editor.yaml`, outside every game project) and loaded/saved with `ParseEditorSettings`, `EncodeEditorSettings`, `LoadEditorSettings`, `SaveEditorSettings`, `Editor.LoadSettings`, `Editor.LoadUserSettings`, and `Editor.SaveSettings`. It stores `version`, `language`, `appearance`, optional `autoSave` (defaults to `true` when omitted), optional `interfaceSize` (`compact`, `default`, or `large`), optional `snap` (per-person defaults for `grid`, `gridSize`, `pixel`, `rotation`, `rotationStepDeg`, `scale`, `scaleStep`, and `showGrid`, used when a project does not override snap in `.game/editor.yaml`), optional `showAgentChanges` (defaults to `true` when omitted), optional `navigation3D` (`default`, `blender`, or `maya`), optional `viewportOverlays` (canonical sorted list of enabled 2D viewport overlay IDs; omitted for defaults, `[]` for all off), optional `overlayLegend` (canonical sorted list of enabled Spec viewport overlay legend kinds: `selection`, `agent`, `added`, `changed`, `removed`, `problem`; omitted enables all six, `[]` hides all six), optional `shortcuts`, optional `seenTips`, and optional `agent` preferences (task routing, MCP tool toggles, external MCP servers, weekly request limit, outbound privacy switches, and local usage counters; secrets such as API keys are never stored in `editor.yaml`). Unknown keys, YAML anchors/aliases/merge keys, trailing documents, negative/non-finite snap steps, and invalid enum values are refused with `*loaderr.Error`. Output is deterministic 2-space YAML prefixed with `SettingsSchemaComment` so a load-save round trip changes nothing byte-for-byte. Its published JSON Schema is `https://game.nsgo.dev/schemas/editor-settings.v1.json` (`SettingsSchemaURL`). ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/editor-settings.v1.json version: 1 @@ -1575,3 +1575,22 @@ When an agent request does not simply succeed, `AgentPanelView` renders dedicate - **Stopped (`AgentStoppedState`)**: stopping a running turn records `DONE` and `NOT DONE` step sections, **Resume** (`ResumeAgentTurn`, which starts strictly at the first not-done step and skips steps already done), and **Review N changes**; completed changes stay unkept until explicitly reviewed and kept. - **Mismatch (`AgentMismatchReport`)**: the editor automatically checks every turn summary against the actual diff (`CheckAgentSummaryAgainstDiff`) and displays a `WHAT · SUMMARY · REVIEW` table when they disagree, including the auto-derived reason when known (for example, an object added at step 3 and removed at step 5), **Ask why** (`AskAgentWhyMismatch`), and **Open review** (`OpenAgentTurnReview`). **Keep** always applies the actual review diff, never the prose summary. - **Offline (`AgentStatusOffline`, `SetAgentOffline`)**: displays `"You're offline"` and queues submitted requests with timestamps (`AgentQueuedRequests`, `QueueAgentRequest`, `RemoveQueuedAgentRequest`) while Select, Move, the Inspector, game check, and Play keep working. Returning online never runs queued requests on its own; each queued request waits for an explicit **Send** (`SendQueuedAgentRequest`). + +## Spec viewport overlays and toggle legend (#1006) + +Every semantic overlay drawn over the 2D and 3D viewports passes through one shared helper (`DrawObjectOverlay`) using exclusively `SpecPalette` tokens (`docs/design/editor/Spec.dc.html`, "Overlay legend"), with a non-color second cue (corner handles, pill glyph/prefix, ghost fill, strikethrough, or filled alert badge) so every kind remains distinguishable in greyscale: + +| Kind (`OverlayKind`) | Token & line style | Second cue | +| --- | --- | --- | +| **Selection** (`selection`) | `Accent`, 1.5 px solid | Four 8×8 corner handles and an accent name tag (person's selection only) | +| **Agent working** (`agent`) | `Agent`, 1.5 px solid, no handles | Pulsing 1.6 s between 100% and 45%, dark pill with 4-point agent glyph (or numbered task badge) saying what the agent is doing | +| **Added** (`added`) | `Added`, 1.5 px dashed | Dark pill labelled `"+ "` | +| **Changed** (`changed`) | `Changed`, 1.5 px dashed | Dark pill showing field, old, and new value (for example `"z 10 → 12"`) | +| **Removed** (`removed`) | `Removed`, 1.5 px solid | 25% grey ghost fill and dark pill with struck-through object name + `"removed"` | +| **Problem** (`problem`) | `Problem`, 2 px solid on the live object | Filled pill (`Problem.Fg` / `Problem.OnFill`) with alert triangle icon and message; never resembles a removed ghost | +| **Focused change in Review** (`focused`) | Base change kind's own color and dash at 2.5 px (never `Accent`) | Bright outlined pill matching the change kind | + +- **Pairing, motion, and reduced motion**: When **Selection** and **Agent working** sit on the same object (`PairedWithSelection`), Selection keeps its four corner handles and the Agent outline sits 3 px further out (`OverlaySelectionAgentGap`) with its pill stacked above. Added, Changed, and Removed overlays fade in over 240 ms (`OverlayChangeFadeDuration` / `OverlayFadeAlpha`), and active Agent working outlines pulse on a 1.6 s cycle (`OverlayAgentPulsePeriod` / `OverlayAgentPulseAlpha`). With reduced motion enabled (`core.Environment.ReduceMotion` or `Editor.SetReduceMotion(true)`), change overlays appear immediately at 100% and Agent outlines stay solid at 100% with no animation timer running. +- **Top-left toggle legend (`viewport-overlay-legend`)**: Every edit-mode viewport (both 2D and 3D) mounts the same top-left legend card (`viewportOverlayLegendView`) with six accessible `role="switch"` rows (**Selection**, **Agent working**, **Added**, **Changed**, **Removed**, **Problem**), each showing its drawn line style and second cue. Toggling any row (`Editor.ToggleOverlayKind`, `Editor.SetOverlayKindVisible`, `Editor.SetOverlayLegendKinds`) hides or shows that kind across all viewports immediately and persists `overlayLegend` in the per-user `EditorSettings` YAML file (`Editor.SettingsPath`, outside the project, never modifying project or scene files). +- **Live scene overlay API and Problems object attribution**: Live agent edits, reviews, and plans attach overlays to objects (or removed ghost bounds) via `Editor.SetSceneOverlays`, `AddSceneOverlay`, `RemoveSceneOverlay`, and `ClearSceneOverlays` (`SceneOverlayEntry`). `assetcheck.Problem` now carries `Object` (also returned by `editormcp`'s `game_check`) for scene object, component, override, and connection diagnostics so Problems naming a live object in the open scene automatically draw the Spec **Problem** overlay on that object in both 2D and 3D viewports. +- **Neutral viewport guides**: The camera frame, camera bounds, camera tether, tile grid, and snap grid use neutral `SpecPalette` tokens (`TextMuted` / `TextFaint` 1 px hairline and `2, 4` dotted lines) that no semantic legend kind uses. diff --git a/docs/en/formats.md b/docs/en/formats.md index c5da0f6dd..8335e350f 100644 --- a/docs/en/formats.md +++ b/docs/en/formats.md @@ -88,6 +88,13 @@ viewportOverlays: - connections - navigation - triggers +overlayLegend: + - added + - agent + - changed + - problem + - removed + - selection shortcuts: view.frame: g seenTips: diff --git a/docs/zh/editor.md b/docs/zh/editor.md index 4ab006f29..0982c6006 100644 --- a/docs/zh/editor.md +++ b/docs/zh/editor.md @@ -1140,7 +1140,7 @@ func main() { 编辑器界面通过内嵌的带版本号 `l10n` YAML 字符串表(`editor/locales/en.yaml`、`editor/locales/zh.yaml`)同时提供英文(`en`)与简体中文(`zh`)界面,并将每名用户的编辑器偏好设置作为确定性的带版本号 YAML 保存在项目之外: -- **用户级设置文件(`EditorSettings`、`SettingsVersion = 1`、#921、#1005、#1028)**:默认保存在 `DefaultSettingsPath()`(`os.UserConfigDir()` 下的 `nsgo-game/editor.yaml`,位于所有游戏项目之外),通过 `ParseEditorSettings`、`EncodeEditorSettings`、`LoadEditorSettings`、`SaveEditorSettings`、`Editor.LoadSettings`、`Editor.LoadUserSettings` 和 `Editor.SaveSettings` 读写。文件保存 `version`、`language`、`appearance`、可选的 `autoSave`(省略时默认为 `true`)、可选的 `interfaceSize`(`compact`、`default` 或 `large`)、可选的 `snap`(用户级默认吸附设置:`grid`、`gridSize`、`pixel`、`rotation`、`rotationStepDeg`、`scale`、`scaleStep` 与 `showGrid`,当项目未在 `.game/editor.yaml` 单独覆盖吸附设置时自动生效)、可选的 `showAgentChanges`(省略时默认为 `true`)、可选的 `navigation3D`(`default`、`blender` 或 `maya`)、可选的 `viewportOverlays`(按字典序排列的已启用 2D 视口叠加层 ID 列表;省略时使用默认组合,`[]` 表示全部关闭)、可选的 `shortcuts`、可选的 `seenTips` 以及可选的 `agent` 偏好(任务路由、MCP 工具开关、外部 MCP 服务器、每周请求限额、出站隐私开关与本地用量统计;API 密钥等机密绝不写入 `editor.yaml`)。未知字段、YAML 锚点/别名/合并键、多余文档、负数/非有限吸附步长和非法枚举值都会被拒绝并返回 `*loaderr.Error`。输出为带 `SettingsSchemaComment` 头的确定性 2 空格 YAML,加载后重新保存字节完全不变。已发布的 JSON Schema 为 `https://game.nsgo.dev/schemas/editor-settings.v1.json`(`SettingsSchemaURL`)。 +- **用户级设置文件(`EditorSettings`、`SettingsVersion = 1`、#921、#1005、#1006、#1028)**:默认保存在 `DefaultSettingsPath()`(`os.UserConfigDir()` 下的 `nsgo-game/editor.yaml`,位于所有游戏项目之外),通过 `ParseEditorSettings`、`EncodeEditorSettings`、`LoadEditorSettings`、`SaveEditorSettings`、`Editor.LoadSettings`、`Editor.LoadUserSettings` 和 `Editor.SaveSettings` 读写。文件保存 `version`、`language`、`appearance`、可选的 `autoSave`(省略时默认为 `true`)、可选的 `interfaceSize`(`compact`、`default` 或 `large`)、可选的 `snap`(用户级默认吸附设置:`grid`、`gridSize`、`pixel`、`rotation`、`rotationStepDeg`、`scale`、`scaleStep` 与 `showGrid`,当项目未在 `.game/editor.yaml` 单独覆盖吸附设置时自动生效)、可选的 `showAgentChanges`(省略时默认为 `true`)、可选的 `navigation3D`(`default`、`blender` 或 `maya`)、可选的 `viewportOverlays`(按字典序排列的已启用 2D 视口叠加层 ID 列表;省略时使用默认组合,`[]` 表示全部关闭)、可选的 `overlayLegend`(按字典序排列的已启用 Spec 视口叠加图例类型:`selection`、`agent`、`added`、`changed`、`removed`、`problem`;省略时全部开启,`[]` 表示全部隐藏)、可选的 `shortcuts`、可选的 `seenTips` 以及可选的 `agent` 偏好(任务路由、MCP 工具开关、外部 MCP 服务器、每周请求限额、出站隐私开关与本地用量统计;API 密钥等机密绝不写入 `editor.yaml`)。未知字段、YAML 锚点/别名/合并键、多余文档、负数/非有限吸附步长和非法枚举值都会被拒绝并返回 `*loaderr.Error`。输出为带 `SettingsSchemaComment` 头的确定性 2 空格 YAML,加载后重新保存字节完全不变。已发布的 JSON Schema 为 `https://game.nsgo.dev/schemas/editor-settings.v1.json`(`SettingsSchemaURL`)。 ```yaml # yaml-language-server: $schema=https://game.nsgo.dev/schemas/editor-settings.v1.json version: 1 @@ -1575,3 +1575,22 @@ func main() { - **已停止(`AgentStoppedState`)**:停止运行中的请求后,卡片分区列出 `DONE` 与 `NOT DONE` 步骤,提供 **Resume**(`ResumeAgentTurn`,从首个未完成步骤开始继续,跳过已完成步骤不重复执行)与 **Review N changes**;已生成的改动在审查采纳前保持未保留状态。 - **摘要与差异不一致(`AgentMismatchReport`)**:编辑器会自动将每条智能体摘要与实际 diff 比对(`CheckAgentSummaryAgainstDiff`),当两者不一致时展示 `WHAT · SUMMARY · REVIEW` 对比表与已知原因(例如某对象在第 3 步被添加、第 5 步被移除),并提供 **Ask why**(`AskAgentWhyMismatch`)与 **Open review**(`OpenAgentTurnReview`)。点击 **Keep** 始终仅采纳实际审查差异,绝不采纳摘要中的虚构数量。 - **离线队列(`AgentStatusOffline`、`SetAgentOffline`)**:展示 `"You're offline"`,并在保持选择、移动、检视器、游戏检查与 Play 全部可用的同时,将提交的请求连同时间戳加入队列(`AgentQueuedRequests`、`QueueAgentRequest`、`RemoveQueuedAgentRequest`)。恢复联网后队列中的请求不会自动执行,而是逐条等待用户手动点击 **Send**(`SendQueuedAgentRequest`)发送。 + +## 规范视口叠加层与可切换图例(#1006) + +2D 与 3D 视口中的所有语义叠加层都通过统一绘制辅助函数 `DrawObjectOverlay` 绘制,完全使用 `SpecPalette` 令牌(对应 `docs/design/editor/Spec.dc.html` 中的 “Overlay legend”),且每一种类型都配备非颜色的第二视觉线索(角点手柄、胶囊图标/前缀、灰色幽灵填充、删除线或实心警告徽章),在灰度下依然彼此可辨: + +| 类型(`OverlayKind`) | 令牌与线型 | 第二视觉线索 | +| --- | --- | --- | +| **选中**(`selection`) | `Accent`,1.5 px 实线 | 四个 8×8 角点手柄与强调色名称标签(仅表示用户的选中) | +| **智能体处理中**(`agent`) | `Agent`,1.5 px 实线,无手柄 | 1.6 秒周期在 100% 与 45% 之间脉冲,深色胶囊配四角星智能体图标(或编号任务徽章)说明正在执行的操作 | +| **已添加**(`added`) | `Added`,1.5 px 虚线 | 带 `"+ <名称>"` 文本的深色胶囊 | +| **已修改**(`changed`) | `Changed`,1.5 px 虚线 | 显示字段名及旧值与新值的深色胶囊(如 `"z 10 → 12"`) | +| **已移除**(`removed`) | `Removed`,1.5 px 实线 | 25% 透明度灰色幽灵块与带删除线对象名 + `"removed"` 的深色胶囊 | +| **问题**(`problem`) | `Problem`,活体对象上的 2 px 实线 | 实心填充胶囊(`Problem.Fg` / `Problem.OnFill`),带三角警告图标与错误信息,绝不会与已移除幽灵混淆 | +| **审查中聚焦的改动**(`focused`) | 沿用对应改动类型自身颜色与虚/实线,线宽 2.5 px(绝不使用 `Accent`) | 与该改动同色描边的醒目胶囊 | + +- **同对象叠加、动效与减弱动态效果**:当**选中**与**智能体处理中**同时落在同一对象上(`PairedWithSelection`)时,选中框保留四个角点手柄,智能体外框向外偏移 3 px(`OverlaySelectionAgentGap`),其胶囊自动上移堆叠。已添加、已修改、已移除叠加层在 240 ms 内淡入(`OverlayChangeFadeDuration` / `OverlayFadeAlpha`),智能体处理中外框以 1.6 s 周期脉冲(`OverlayAgentPulsePeriod` / `OverlayAgentPulseAlpha`)。开启减弱动态效果(`core.Environment.ReduceMotion` 或 `Editor.SetReduceMotion(true)`)后,变更叠加层立即以 100% 出现,智能体外框保持 100% 实线且不再启动动画定时器。 +- **左上角可切换图例(`viewport-overlay-legend`)**:所有编辑态视口(2D 与 3D)在左上角挂载同一张图例卡片(`viewportOverlayLegendView`),提供 6 行无障碍 `role="switch"` 开关(**选中**、**智能体处理中**、**已添加**、**已修改**、**已移除**、**问题**),每行都绘出对应线型与第二线索。切换任一行(`Editor.ToggleOverlayKind`、`Editor.SetOverlayKindVisible`、`Editor.SetOverlayLegendKinds`)会立即在所有视口隐藏或显示该类叠加层,并将 `overlayLegend` 持久化到项目之外的用户级 `EditorSettings` YAML 文件(`Editor.SettingsPath`,绝不修改项目或场景文件)。 +- **实时场景叠加层接口与问题对象关联**:实时智能体编辑、审查与计划通过 `Editor.SetSceneOverlays`、`AddSceneOverlay`、`RemoveSceneOverlay` 和 `ClearSceneOverlays`(`SceneOverlayEntry`)将叠加层附加到场景对象或已移除幽灵边界上。`assetcheck.Problem` 现包含 `Object` 字段(同时通过 `editormcp` 的 `game_check` 返回),覆盖场景对象、组件、覆写与连接诊断,使问题面板中指向当前打开场景对象的诊断会自动在 2D 与 3D 视口中绘制 Spec **问题**叠加层。 +- **中性视口参考线**:相机取景框、相机边界、相机连线、瓦片网格与对齐网格统一迁移到中性 `SpecPalette` 令牌(`TextMuted` / `TextFaint` 1 px 细线与 `2, 4` 点线),与所有语义图例线型完全区分。 diff --git a/docs/zh/formats.md b/docs/zh/formats.md index 1dfb26c64..55fd24fd0 100644 --- a/docs/zh/formats.md +++ b/docs/zh/formats.md @@ -88,6 +88,13 @@ viewportOverlays: - connections - navigation - triggers +overlayLegend: + - added + - agent + - changed + - problem + - removed + - selection shortcuts: view.frame: g seenTips: diff --git a/packages/game/editor/editormcp/tools.go b/packages/game/editor/editormcp/tools.go index 6d7f9489d..bcb8d2c48 100644 --- a/packages/game/editor/editormcp/tools.go +++ b/packages/game/editor/editormcp/tools.go @@ -755,6 +755,8 @@ type Problem struct { Line int `json:"line,omitempty"` // Column is the 1-based column on Line where the scene format knows it, or 0 when unknown. Column int `json:"column,omitempty"` + // Object is the ID of the scene object the problem names or belongs to when known. + Object string `json:"object,omitempty"` // Message says what is wrong. Message string `json:"message"` } @@ -814,7 +816,7 @@ func gameCheck(ctx context.Context, c *Call) (*Result, error) { found := ed.Problems() res := Check{Problems: make([]Problem, 0, len(found))} for _, p := range found { - res.Problems = append(res.Problems, Problem{File: p.File, Line: p.Line, Column: p.Column, Message: p.Message}) + res.Problems = append(res.Problems, Problem{File: p.File, Line: p.Line, Column: p.Column, Object: p.Object, Message: p.Message}) } if file != "" && unsaved(scene, file, reg) { res.Unsaved = name diff --git a/packages/game/editor/gizmo2d.go b/packages/game/editor/gizmo2d.go index 9915d7e11..7018c45ef 100644 --- a/packages/game/editor/gizmo2d.go +++ b/packages/game/editor/gizmo2d.go @@ -8,6 +8,7 @@ import ( "github.com/nsgo-dev/game/packages/game/math2d" "github.com/nsgo-dev/game/packages/game/sceneformat" "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/ui" ) // GizmoHandle2D names a part of the 2D transform gizmo drawn on the selected object, or the object itself, that a drag in the 2D viewport takes. @@ -1332,37 +1333,43 @@ func (c *transform2DCmd) Undo() { } } -// Gizmo colors: the axes as most editors color them, X red and Y green. +// Gizmo colors derived from Spec palette tokens. var ( - gizmoColorX = core.RGBA(0xEF4444, 1) - gizmoColorY = core.RGBA(0x22C55E, 1) - gizmoColorRing = core.RGBA(0x38BDF8, 0.8) - gizmoColorCenter = core.RGBA(0xF8FAFC, 1) - gizmoColorActive = core.RGBA(0xFBBF24, 1) + gizmoColorX = specRemoved + gizmoColorY = specAdded + gizmoColorRing = ui.Alpha(specAccent, 0.8) + gizmoColorCenter = specTextStrong + gizmoColorActive = specWarning ) // drawGizmo2D draws the selected object's transform gizmo: the rotation ring, the X and Y arrows, the move square and, on an outline large enough, the scale handles. The handle a drag holds is drawn highlighted. func (e *Editor) drawGizmo2D(d *core.Drawing) { - if !e.Gizmo2DShown() || !e.OverlayLegendKindEnabled(OverlayLegendSelection) { + if !e.Gizmo2DShown() || !e.OverlayKindVisible(OverlayKindSelection) { return } g, _ := e.gizmo2D() + spec := e.SpecPalette(nil) + colX := spec.Problem().Fg + colY := spec.Added.Fg + colRing := ui.Alpha(spec.Accent.Edge, 0.8) + colCenter := specHandleFill(spec) + colActive := spec.Warning.Fg active := e.drag2D.handle pick := func(h GizmoHandle2D, c core.Color) core.Color { if h == active { - return gizmoColorActive + return colActive } return c } d.Save() d.SetLineWidth(1.5) - d.SetStrokeColor(pick(Handle2DRotate, gizmoColorRing)) + d.SetStrokeColor(pick(Handle2DRotate, colRing)) d.BeginPath().Arc(g.origin.X, g.origin.Y, g.ring, 0, 2*math.Pi, false).Stroke() for _, a := range [2]struct { h GizmoHandle2D dir math2d.Vec2 c core.Color - }{{Handle2DMoveX, g.axisX, gizmoColorX}, {Handle2DMoveY, g.axisY, gizmoColorY}} { + }{{Handle2DMoveX, g.axisX, colX}, {Handle2DMoveY, g.axisY, colY}} { c := pick(a.h, a.c) from := g.origin.Add(a.dir.Scale(gizmoArrowStart)) tip := g.origin.Add(a.dir.Scale(gizmoArrowLen)) @@ -1374,15 +1381,15 @@ func (e *Editor) drawGizmo2D(d *core.Drawing) { d.SetFillColor(c) d.BeginPath().MoveTo(tip.X, tip.Y).LineTo(l.X, l.Y).LineTo(r.X, r.Y).ClosePath().Fill() } - d.SetFillColor(pick(Handle2DMove, gizmoColorCenter)) + d.SetFillColor(pick(Handle2DMove, colCenter)) d.FillRect(g.origin.X-gizmoCenterHalf, g.origin.Y-gizmoCenterHalf, 2*gizmoCenterHalf, 2*gizmoCenterHalf) d.SetLineWidth(1.5) for h := Handle2DScaleN; h <= Handle2DScaleNW; h++ { if g.scaleShown(h) { c := g.scaleHandlePos(h) - d.SetFillColor(pick(h, gizmoColorCenter)) + d.SetFillColor(pick(h, colCenter)) d.FillRect(c.X-gizmoScaleHalf, c.Y-gizmoScaleHalf, 2*gizmoScaleHalf, 2*gizmoScaleHalf) - d.SetStrokeColor(core.RGBA(0x38BDF8, 1)) + d.SetStrokeColor(spec.Accent.Edge) d.StrokeRect(c.X-gizmoScaleHalf, c.Y-gizmoScaleHalf, 2*gizmoScaleHalf, 2*gizmoScaleHalf) } } diff --git a/packages/game/editor/locales/en.yaml b/packages/game/editor/locales/en.yaml index f8672df92..2b3036706 100644 --- a/packages/game/editor/locales/en.yaml +++ b/packages/game/editor/locales/en.yaml @@ -763,6 +763,13 @@ strings: overlays.fit: Fit overlays.fitLabel: Fit all visible objects in the 2D viewport overlays.labels: Labels + overlays.legend.added: Added + overlays.legend.agent: Agent working + overlays.legend.changed: Changed + overlays.legend.problem: Problem + overlays.legend.removed: Removed + overlays.legend.selection: Selection + overlays.legendTitle: OVERLAYS overlays.navigation: Navigation overlays.patrolPaths: Patrol paths overlays.popoverTitle: SHOW IN VIEWPORT diff --git a/packages/game/editor/locales/zh.yaml b/packages/game/editor/locales/zh.yaml index 129a2105a..5646fc362 100644 --- a/packages/game/editor/locales/zh.yaml +++ b/packages/game/editor/locales/zh.yaml @@ -763,6 +763,13 @@ strings: overlays.fit: 适应画面 overlays.fitLabel: 在 2D 视口中适应显示全部可见对象 overlays.labels: 标签 + overlays.legend.added: 已添加 + overlays.legend.agent: 智能体处理中 + overlays.legend.changed: 已修改 + overlays.legend.problem: 问题 + overlays.legend.removed: 已移除 + overlays.legend.selection: 选中 + overlays.legendTitle: 叠加层 overlays.navigation: 导航区域 overlays.patrolPaths: 巡逻路径 overlays.popoverTitle: 在视口中显示 diff --git a/packages/game/editor/overlays.go b/packages/game/editor/overlays.go index 6e2a0d6e0..b4e82f65e 100644 --- a/packages/game/editor/overlays.go +++ b/packages/game/editor/overlays.go @@ -490,6 +490,10 @@ func (e *Editor) syncOverlaysFromSettings() { if e == nil { return } + legendSet := e.effectiveOverlayLegendSet() + e.problems.mu.Lock() + e.problems.problemOverlayHidden = !legendSet[OverlayKindProblem] + e.problems.mu.Unlock() if e.settings.ViewportOverlays == nil { e.ShowNavMesh2D = true return @@ -1138,7 +1142,8 @@ func drawCameraBoundsOverlay(e *Editor, d *core.Drawing, _ *sceneformat.BuiltSce font := core.Font{Family: core.FontMonospace, Size: 10.5} b := e.Doc.Camera.Bounds pts := worldRectCanvasCorners(e, b.X, b.Y, b.Width, b.Height) - d.SetStrokeColor(col).SetLineWidth(1.25).SetLineDash(3, 3) + // Camera bounds use a fine 1 px dotted line in Spec TextFaint, distinct from all legend kinds. + d.SetStrokeColor(col).SetLineWidth(1).SetLineDash(2, 4) strokePolygon(d, pts) d.SetLineDash() caption := fmt.Sprintf("bounds %g × %g", b.Width, b.Height) diff --git a/packages/game/editor/problems.go b/packages/game/editor/problems.go index 47c00ec27..b36556f37 100644 --- a/packages/game/editor/problems.go +++ b/packages/game/editor/problems.go @@ -1160,7 +1160,7 @@ func runProjectCheckWithOverrides(dir string, reg *sceneformat.ComponentRegistry } slices.SortFunc(problems, func(a, b assetcheck.Problem) int { - return cmp.Or(cmp.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line), cmp.Compare(a.Column, b.Column), cmp.Compare(a.Message, b.Message)) + return cmp.Or(cmp.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line), cmp.Compare(a.Column, b.Column), cmp.Compare(a.Object, b.Object), cmp.Compare(a.Message, b.Message)) }) problems = slices.Compact(problems) return problems, nil @@ -1400,6 +1400,11 @@ func (e *Editor) attributeProblemObject(p assetcheck.Problem, loadSpans func() [ return false } + // 0. Direct object ID reported by assetcheck.Problem.Object. + if p.Object != "" && hasObj(p.Object) { + return p.Object + } + // 1. Explicit connection error: attach to the live endpoint (for example, // when a lever's connection targets missing "door_3", attach to "lever"). if m := connProblemRE.FindStringSubmatch(p.Message); len(m) == 6 { diff --git a/packages/game/editor/problems_fix.go b/packages/game/editor/problems_fix.go index 70226534f..315b7426e 100644 --- a/packages/game/editor/problems_fix.go +++ b/packages/game/editor/problems_fix.go @@ -4,14 +4,12 @@ import ( "errors" "fmt" "maps" - "math" "path" "path/filepath" "regexp" "slices" "strings" - "github.com/nsgo-dev/game/packages/game/math2d" "github.com/nsgo-dev/game/packages/game/sceneformat" "github.com/nsgo-dev/game/packages/game/tooling/assetcheck" "github.com/nsgo-dev/nsgo/core" @@ -161,30 +159,21 @@ func (e *Editor) SetProblemAgentPanelOpen(open bool) { } // ProblemOverlayVisible reports whether the Spec Problem overlay is drawn on -// live objects in the 2D viewport (true by default). +// live objects in the viewport (true by default, synchronized with the Problem legend toggle). func (e *Editor) ProblemOverlayVisible() bool { if e == nil { return false } - e.problems.mu.Lock() - defer e.problems.mu.Unlock() - return !e.problems.problemOverlayHidden + return e.OverlayKindVisible(OverlayKindProblem) } -// SetProblemOverlayVisible toggles the Spec Problem overlay in the 2D viewport. +// SetProblemOverlayVisible toggles the Spec Problem overlay in the viewport +// (synchronized with the Problem legend toggle and persisted when SettingsPath is set). func (e *Editor) SetProblemOverlayVisible(visible bool) { if e == nil { return } - e.problems.mu.Lock() - hidden := !visible - if e.problems.problemOverlayHidden == hidden { - e.problems.mu.Unlock() - return - } - e.problems.problemOverlayHidden = hidden - e.problems.mu.Unlock() - e.notify() + _ = e.SetOverlayKindVisible(OverlayKindProblem, visible) } // ActiveProblem returns the problem currently focused in the Agent problem panel. @@ -1166,6 +1155,9 @@ func extractProblemObjectIDFromDoc(doc *sceneformat.SceneDoc, p assetcheck.Probl return "" } hasObj := func(id string) bool { return locateObject(doc, id).obj != nil } + if p.Object != "" && hasObj(p.Object) { + return p.Object + } if m := connProblemRE.FindStringSubmatch(p.Message); len(m) == 6 { if hasObj(m[2]) { return m[2] @@ -1215,9 +1207,9 @@ func shortProblemLabel(p assetcheck.Problem) string { // drawProblemOverlays2D draws the Spec Problem overlay (2 px solid Problem.Edge // outline on the live object plus a filled Problem.Fg pill with the alert // triangle icon and message in Problem.OnFill) for every live visible object in -// the open scene that has a non-ignored problem. +// the open scene that has a non-ignored problem, through DrawObjectOverlay. func (e *Editor) drawProblemOverlays2D(d *core.Drawing, scene *sceneformat.BuiltScene) { - if e == nil || d == nil || scene == nil || e.playing || e.HistoryPreviewActive() || !e.ProblemOverlayVisible() || !e.OverlayLegendKindEnabled(OverlayLegendProblem) { + if e == nil || d == nil || scene == nil || e.playing || e.HistoryPreviewActive() || !e.OverlayKindVisible(OverlayKindProblem) { return } objProbs := e.openSceneObjectProblems() @@ -1225,83 +1217,38 @@ func (e *Editor) drawProblemOverlays2D(d *core.Drawing, scene *sceneformat.Built return } spec := e.SpecPalette(nil) - probRole := spec.Problem() - font := core.Font{Family: core.FontMonospace, Size: 10.5} + canvas := core.Size{Width: core.Points(e.canvasW), Height: core.Points(e.canvasH)} d.Save() for _, layer := range scene.Layers { if !layer.Visible { continue } - layerM := e.layerAffineFor(layer.Space, layer.ParallaxX, layer.ParallaxY) var walk func(objs []*sceneformat.BuiltObject, hidden bool) walk = func(objs []*sceneformat.BuiltObject, hidden bool) { for _, bo := range objs { h := hidden || e.hidden[bo.ID] if !h && bo != nil && bo.Doc != nil { if probs := objProbs[bo.ID]; len(probs) > 0 { - m := layerM.Mul(bo.World) - rx, ry, rw, rh := objectOutline(bo) - corners := [4]math2d.Vec2{ - m.TransformPoint(math2d.Vec2{X: rx, Y: ry}), - m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry}), - m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry + rh}), - m.TransformPoint(math2d.Vec2{X: rx, Y: ry + rh}), - } - minX, minY := corners[0].X, corners[0].Y - maxX, maxY := corners[0].X, corners[0].Y - for _, pt := range corners[1:] { - minX = float32(math.Min(float64(minX), float64(pt.X))) - minY = float32(math.Min(float64(minY), float64(pt.Y))) - maxX = float32(math.Max(float64(maxX), float64(pt.X))) - maxY = float32(math.Max(float64(maxY), float64(pt.Y))) + bounds, _, ok := e.builtObjectCanvasBounds(scene, bo) + if !ok { + continue } - // 2 px solid Spec Problem outline with 3 px offset around the live object. - const pad float32 = 3 - d.SetStrokeColor(probRole.Edge).SetLineWidth(2).SetLineDash() - d.BeginPath().Rect(minX-pad, minY-pad, (maxX-minX)+2*pad, (maxY-minY)+2*pad).Stroke() - - // Filled Spec Problem pill above the object with alert triangle icon + message. label := shortProblemLabel(probs[0]) if len(probs) > 1 { label = fmt.Sprintf("%s (+%d)", label, len(probs)-1) } - const iconW float32 = 14 - const pillH float32 = 20 - pillW := float32(len([]rune(label)))*6.5 + iconW + 16 - cx := (minX + maxX) * 0.5 - px := cx - pillW*0.5 - if e.canvasW > 0 { - if px+pillW > e.canvasW-6 { - px = e.canvasW - pillW - 6 - } - if px < 6 { - px = 6 - } - } - py := minY - pad - pillH - 6 - if py < 6 { - py = maxY + pad + 6 + stackOff := float32(0) + if e.IsSelected(bo.ID) && e.OverlayKindVisible(OverlayKindSelection) { + stackOff = 24 } - if e.canvasH > 0 { - if py+pillH > e.canvasH-6 { - py = e.canvasH - pillH - 6 - } - if py < 6 { - py = 6 - } - } - d.SetFillColor(probRole.Fg) - d.BeginPath().Rect(px, py, pillW, pillH).Fill() - - // Alert triangle icon in Problem.OnFill (never color alone). - ix, iy := px+6, py+4 - d.SetStrokeColor(probRole.OnFill).SetLineWidth(1.5).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) - d.BeginPath().MoveTo(ix+6, iy+1).LineTo(ix+11, iy+10.5).LineTo(ix+1, iy+10.5).ClosePath().Stroke() - d.BeginPath().MoveTo(ix+6, iy+4.5).LineTo(ix+6, iy+7.2).Stroke() - d.SetFillColor(probRole.OnFill).BeginPath().Arc(ix+6, iy+9, 0.75, 0, float32(2*math.Pi), false).Fill() - - d.SetFillColor(probRole.OnFill).FillText(label, px+iconW+8, py+13.5, font) + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindProblem, + Label: label, + Bounds: bounds, + CanvasSize: canvas, + PillStackOffset: stackOff, + }) } } walk(bo.Children, h) diff --git a/packages/game/editor/settings.go b/packages/game/editor/settings.go index caad839fd..6f6e73871 100644 --- a/packages/game/editor/settings.go +++ b/packages/game/editor/settings.go @@ -177,6 +177,10 @@ type EditorSettings struct { // HiddenOverlayKinds lists Spec overlay legend kinds toggled off by the user // ("selection", "agent", "added", "changed", "removed", "problem") in canonical sorted order. HiddenOverlayKinds []string `yaml:"hiddenOverlayKinds,omitempty"` + // OverlayLegend lists the enabled Spec viewport overlay legend kinds + // ("selection", "agent", "added", "changed", "removed", "problem") in canonical sorted order. + // When omitted, all six legend kinds are enabled by default; an empty list hides all six kinds. + OverlayLegend *[]string `yaml:"overlayLegend,omitempty"` // Shortcuts overrides default command shortcuts keyed by command ID (for example "view.frame": "g"). An empty string explicitly unbinds a command. Shortcuts map[string]string `yaml:"shortcuts,omitempty"` // SeenTips lists the onboarding tip IDs already seen or skipped by this user in canonical sorted order. @@ -397,6 +401,18 @@ func ValidateEditorSettings(s *EditorSettings) error { seen[raw] = struct{}{} } } + if s.OverlayLegend != nil { + seen := make(map[string]struct{}, len(*s.OverlayLegend)) + for i, id := range *s.OverlayLegend { + if !OverlayKind(id).IsLegendKind() { + return loaderr.Errorf(fmt.Sprintf("overlayLegend[%d]", i), "use legend kinds selection, agent, added, changed, removed, or problem", "editor: invalid overlay legend kind %q", id) + } + if _, dup := seen[id]; dup { + return loaderr.Errorf(fmt.Sprintf("overlayLegend[%d]", i), "remove duplicate overlay legend kinds", "editor: duplicate overlay legend kind %q", id) + } + seen[id] = struct{}{} + } + } for _, cmdID := range slices.Sorted(maps.Keys(s.Shortcuts)) { raw := s.Shortcuts[cmdID] if err := validateCommandID(cmdID); err != nil { @@ -495,6 +511,14 @@ func EncodeEditorSettings(s *EditorSettings) ([]byte, error) { slices.Sort(hidden) out.HiddenOverlayKinds = hidden } + if s.OverlayLegend != nil { + sorted := slices.Clone(*s.OverlayLegend) + if sorted == nil { + sorted = []string{} + } + slices.Sort(sorted) + out.OverlayLegend = &sorted + } var buf bytes.Buffer buf.WriteString(SettingsSchemaComment + "\n") enc := yaml.NewEncoder(&buf) @@ -586,6 +610,13 @@ func (e *Editor) Settings() EditorSettings { } else { s.HiddenOverlayKinds = nil } + if s.OverlayLegend != nil { + cp := slices.Clone(*s.OverlayLegend) + if cp == nil { + cp = []string{} + } + s.OverlayLegend = &cp + } if len(s.Shortcuts) > 0 { s.Shortcuts = maps.Clone(s.Shortcuts) } else { @@ -862,6 +893,14 @@ func (e *Editor) ApplySettings(s EditorSettings) error { } else { s.HiddenOverlayKinds = nil } + if s.OverlayLegend != nil { + cp := slices.Clone(*s.OverlayLegend) + if cp == nil { + cp = []string{} + } + slices.Sort(cp) + s.OverlayLegend = &cp + } if len(s.Shortcuts) > 0 { normalized := make(map[string]string, len(s.Shortcuts)) for cmdID, raw := range s.Shortcuts { diff --git a/packages/game/editor/snap.go b/packages/game/editor/snap.go index cb536f705..3152df6b5 100644 --- a/packages/game/editor/snap.go +++ b/packages/game/editor/snap.go @@ -579,9 +579,10 @@ func (e *Editor) drawSnapGridOverlay(d *core.Drawing) { startRow := int(startRowF) endRow := int(endRowF) + spec := e.SpecPalette(nil) d.Save() applyAffine(d, m) - d.SetStrokeColor(core.RGBA(0x94A3B8, 0.22)).SetLineWidth(lw).BeginPath() + d.SetStrokeColor(ui.Alpha(spec.TextFaint, 0.20)).SetLineWidth(lw).BeginPath() for c := startCol; c <= endCol; c++ { if c == 0 { continue @@ -606,7 +607,7 @@ func (e *Editor) drawSnapGridOverlay(d *core.Drawing) { // Emphasize the origin axes (x=0, y=0) when visible. if startCol <= 0 && endCol >= 0 || startRow <= 0 && endRow >= 0 { - d.SetStrokeColor(core.RGBA(0x94A3B8, 0.42)).SetLineWidth(lw).BeginPath() + d.SetStrokeColor(ui.Alpha(spec.TextFaint, 0.42)).SetLineWidth(lw).BeginPath() if startCol <= 0 && endCol >= 0 { d.MoveTo(0, minY).LineTo(0, maxY) } diff --git a/packages/game/editor/spec_feedback_ui.go b/packages/game/editor/spec_feedback_ui.go index 1a1cc1a9e..c08c255fd 100644 --- a/packages/game/editor/spec_feedback_ui.go +++ b/packages/game/editor/spec_feedback_ui.go @@ -34,17 +34,17 @@ var ( } ) -// OverlayLegendOpen reports whether the compact viewport overlay legend is visible. +// OverlayLegendOpen reports whether the compact viewport overlay legend is visible (true by default in edit mode). func (e *Editor) OverlayLegendOpen() bool { - return e != nil && e.overlayLegendOpen + return e != nil && !e.overlayLegendHidden } // SetOverlayLegendOpen shows or hides the compact viewport overlay legend in the viewport top-left corner. func (e *Editor) SetOverlayLegendOpen(open bool) { - if e == nil || e.overlayLegendOpen == open { + if e == nil || e.overlayLegendHidden == !open { return } - e.overlayLegendOpen = open + e.overlayLegendHidden = !open e.notify() } @@ -767,133 +767,314 @@ func specToastIcon(p SpecPalette, kind ToastKind) core.Node { } } -// viewportOverlayLegendView renders the compact interactive Spec overlay legend in the top-left of the -// viewport when Editor.OverlayLegendOpen is true or live agent overlays are active (matching Spec.dc.html's -// line-style legend). Each row toggles its overlay kind on or off and persists the choice per user in -// EditorSettings.HiddenOverlayKinds. +// viewportOverlayLegendView renders the Spec overlay legend in the top-left corner of every +// edit-mode viewport (both 2D and 3D) as six accessible role="switch" toggles — one per kind +// (Selection, Agent working, Added, Changed, Removed, Problem) with its exact Spec line style +// and second cue. Turning a row off hides that kind and saves the choice per person in EditorSettings. func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { + type legendStateKey struct { + visible bool + dark bool + viewMode ViewMode + lang string + mask uint8 + } + keyMemo := core.NewMemo(cx, func() legendStateKey { + _ = rev.Get() + if ed == nil || ed.Playing() || ed.HistoryPreviewActive() || !ed.OverlayLegendOpen() { + return legendStateKey{} + } + var mask uint8 + for i, k := range OverlayLegendKinds() { + if ed.OverlayKindVisible(k) { + mask |= 1 << uint(i) + } + } + return legendStateKey{ + visible: true, + dark: cx.Dark(), + viewMode: ed.ViewMode, + lang: ed.ResolvedLanguage(), + mask: mask, + } + }) + return core.Show{ When: func() bool { - _ = rev.Get() - return !ed.Playing() && !ed.HistoryPreviewActive() && (ed.OverlayLegendOpen() || ed.HasAgentLiveOverlays()) + return keyMemo.Get().visible }, Then: func(cx *core.Scope) core.Node { - row := func(testID string, kind OverlayLegendKind, labelKey string, colFn func(SpecPalette) core.Color, dashed bool) core.Node { - k := kind - isOn := func() bool { - _ = rev.Get() - return ed.OverlayLegendKindEnabled(k) + return core.Dynamic(func(cx *core.Scope) core.Node { + k := keyMemo.Get() + if !k.visible { + return core.View{} } - return core.View{ - TestID: testID, - Role: core.RoleSwitch, - LabelFunc: func() string { _ = rev.Get(); return ed.T(labelKey) }, - Checked: isOn, - Focusable: func() bool { return true }, - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 8, - Height: core.Pt(28), - Padding: core.Symmetric(0, 6), - CornerRadius: 6, - }, - StyleFunc: func() core.Style { - return core.Style{FocusVisible: ed.SpecPalette(cx).FocusRing(2)} - }, - OnPress: func(core.PressEvent) { - ed.report(ed.ToggleOverlayLegendKind(k)) - }, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pt(18), Height: core.Pt(10), FlexShrink: 0}, - Draw: func(d *core.Drawing, _ core.Size) { - _ = rev.Get() - p := ed.SpecPalette(cx) - c := colFn(p) - if !ed.OverlayLegendKindEnabled(k) { - c = ui.Alpha(p.TextFaint, 0.45) - } - d.SetStrokeColor(c).SetLineWidth(1.8) - if dashed { - d.SetLineDash(4, 2.5) + p := SpecPaletteFor(k.dark) + leftPt := core.Pt(10) + topPt := core.Pt(10) + compact3D := k.viewMode == ViewMode3D + if compact3D { + // Sit cleanly beneath view3d-bar + view3d-help in the 3D viewport's top-left corner + // using a compact 2×3 layout so the middle-left orbit/pan zone stays unobstructed. + leftPt = core.Pt(16) + topPt = core.Pt(92) + } + + legendLabel := func(kind OverlayKind) string { + switch kind { + case OverlayKindSelection: + return ed.T("overlays.legend.selection") + case OverlayKindAgent: + return ed.T("overlays.legend.agent") + case OverlayKindAdded: + return ed.T("overlays.legend.added") + case OverlayKindChanged: + return ed.T("overlays.legend.changed") + case OverlayKindRemoved: + return ed.T("overlays.legend.removed") + case OverlayKindProblem: + return ed.T("overlays.legend.problem") + default: + return string(kind) + } + } + + legendRole := func(kind OverlayKind) SpecRole { + switch kind { + case OverlayKindSelection: + return p.Accent + case OverlayKindAgent: + return p.Agent + case OverlayKindAdded: + return p.Added + case OverlayKindChanged: + return p.Changed + case OverlayKindRemoved: + return p.Removed + case OverlayKindProblem: + return p.Problem() + default: + return p.Accent + } + } + + legendRow := func(kind OverlayKind) core.Node { + on := ed.OverlayKindVisible(kind) + role := legendRole(kind) + label := legendLabel(kind) + swatchAlpha := float32(1) + textColor := p.TextSecondary + if !on { + swatchAlpha = 0.35 + textColor = p.TextFaint + } + trackBg := p.LineRaised + knobLeft := core.Pt(2) + if on { + trackBg = role.Fg + knobLeft = core.Pt(12) + } + knobBg := specHandleFill(p) + if on && p.Dark { + knobBg = role.OnFill + } + + swatch := core.Canvas{ + Style: core.Style{Width: core.Pt(26), Height: core.Pt(12), FlexShrink: 0}, + Draw: func(d *core.Drawing, _ core.Size) { + d.Save() + edge := ui.Alpha(role.Edge, swatchAlpha) + fg := ui.Alpha(role.Fg, swatchAlpha) + switch kind { + case OverlayKindSelection: + // 1.5 px solid accent line + two corner handle squares. + d.SetStrokeColor(edge).SetLineWidth(1.5) + d.BeginPath().MoveTo(4, 6).LineTo(22, 6).Stroke() + hf := ui.Alpha(specHandleFill(p), swatchAlpha) + for _, hx := range [2]float32{1.5, 19.5} { + d.SetFillColor(hf).BeginPath().RoundRect(hx, 3.5, 5, 5, 1).Fill() + d.SetStrokeColor(edge).SetLineWidth(1.2).BeginPath().RoundRect(hx, 3.5, 5, 5, 1).Stroke() } - d.BeginPath().MoveTo(1, 5).LineTo(17, 5).Stroke() - }, + case OverlayKindAgent: + // 1.5 px solid agent violet line + 4-point agent sparkle glyph. + d.SetStrokeColor(edge).SetLineWidth(1.5) + d.BeginPath().MoveTo(1.5, 6).LineTo(14.5, 6).Stroke() + drawAgentSparkleGlyph(d, 21, 6, 4.2, fg) + case OverlayKindAdded: + // 1.5 px dashed added green line + "+" cue. + d.SetStrokeColor(edge).SetLineWidth(1.5).SetLineDash(3.5, 2) + d.BeginPath().MoveTo(1.5, 6).LineTo(15.5, 6).Stroke() + d.SetLineDash() + d.SetStrokeColor(fg).SetLineWidth(1.5).SetLineCap(core.CapRound) + d.BeginPath().MoveTo(18.5, 6).LineTo(24.5, 6).MoveTo(21.5, 3).LineTo(21.5, 9).Stroke() + case OverlayKindChanged: + // 1.5 px dashed changed amber line + "→" cue. + d.SetStrokeColor(edge).SetLineWidth(1.5).SetLineDash(3.5, 2) + d.BeginPath().MoveTo(1.5, 6).LineTo(14.5, 6).Stroke() + d.SetLineDash() + d.SetStrokeColor(fg).SetLineWidth(1.5).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) + d.BeginPath().MoveTo(17.5, 6).LineTo(24.5, 6).MoveTo(22, 3.5).LineTo(24.5, 6).LineTo(22, 8.5).Stroke() + case OverlayKindRemoved: + // 1.5 px solid removed red frame around a 25% grey ghost + strikethrough cue. + d.SetFillColor(ui.Alpha(p.TextFaint, 0.28*swatchAlpha)).BeginPath().RoundRect(2.5, 2.5, 11, 7, 1.5).Fill() + d.SetStrokeColor(edge).SetLineWidth(1.5).BeginPath().RoundRect(1.5, 1.5, 13, 9, 2).Stroke() + d.SetStrokeColor(fg).SetLineWidth(1.4).SetLineCap(core.CapRound) + d.BeginPath().MoveTo(17, 6).LineTo(24.5, 6).Stroke() + case OverlayKindProblem: + // 2 px solid problem red line + filled alert triangle badge. + d.SetStrokeColor(edge).SetLineWidth(2) + d.BeginPath().MoveTo(1.5, 6).LineTo(12.5, 6).Stroke() + d.SetFillColor(fg).BeginPath().RoundRect(15, 0.5, 11, 11, 5.5).Fill() + onFill := ui.Alpha(role.OnFill, swatchAlpha) + d.SetStrokeColor(onFill).SetLineWidth(1.2).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) + d.BeginPath().MoveTo(20.5, 2.5).LineTo(23.8, 8.8).LineTo(17.2, 8.8).ClosePath().Stroke() + d.BeginPath().MoveTo(20.5, 5).LineTo(20.5, 6.7).Stroke() + } + d.Restore() }, - core.Text{ - ContentFunc: func() string { - _ = rev.Get() - return ed.T(labelKey) - }, - Style: core.Style{ - FontSize: 11.5, - FontWeight: 500, + } + + switchTrack := core.View{ + PointerEvents: core.PointerEventsNone, + Style: core.Style{ + Position: core.Relative, + Width: core.Pt(22), + Height: core.Pt(12), + CornerRadius: 6, + Background: trackBg, + FlexShrink: 0, + }, + Children: []core.Node{ + core.View{ + Style: core.Style{ + Position: core.Absolute, + Left: knobLeft, + Top: core.Pt(2), + Width: core.Pt(8), + Height: core.Pt(8), + CornerRadius: 4, + Background: knobBg, + }, }, - StyleFunc: func() core.Style { - p := ed.SpecPalette(cx) - if !isOn() { - return core.Style{ - Color: p.TextFaint, - TextDecoration: core.TextDecorationLineThrough, - } - } - return core.Style{Color: p.TextSecondary} + }, + } + + kindCopy := kind + rowStyle := core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 6, + Height: core.Pt(20), + Padding: core.Symmetric(0, 4), + CornerRadius: 5, + FocusVisible: p.FocusRing(2), + } + if compact3D { + rowStyle.MinWidth = core.Pt(138) + } + return core.View{ + TestID: "legend-" + string(kind), + Role: core.RoleSwitch, + Label: label, + Checked: func() bool { _ = rev.Get(); return ed.OverlayKindVisible(kindCopy) }, + Focusable: func() bool { return true }, + OnPress: func(core.PressEvent) { + ed.report(ed.ToggleOverlayKind(kindCopy)) + }, + Style: rowStyle, + Children: []core.Node{ + swatch, + core.Text{ + Content: label, + MaxLines: 1, + Style: core.Style{ + FlexGrow: 1, + FontSize: 11, + FontWeight: 500, + Color: textColor, + }, }, + switchTrack, }, - }, + } } - } - return core.View{ - TestID: "viewport-overlay-legend", - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(12), - Top: core.Pt(12), - Padding: core.Symmetric(8, 10), - Gap: 0, - CornerRadius: 10, - BorderWidth: 1, - }, - StyleFunc: func() core.Style { - p := ed.SpecPalette(cx) - return core.Style{ - Background: p.Raised, - BorderColor: p.LineRaised, + if compact3D { + kinds := OverlayLegendKinds() + leftCol := make([]core.Node, 0, 3) + rightCol := make([]core.Node, 0, 3) + for i, kind := range kinds { + if i < 3 { + leftCol = append(leftCol, legendRow(kind)) + } else { + rightCol = append(rightCol, legendRow(kind)) + } } - }, - Children: []core.Node{ - core.Text{ - ContentFunc: func() string { - _ = rev.Get() - return ed.T("agent.legendTitle") - }, + return core.View{ + TestID: "viewport-overlay-legend", + Role: core.RoleGroup, + Label: ed.T("overlays.legendTitle"), Style: core.Style{ - FontSize: 10.5, - FontWeight: 600, - LetterSpacing: 0.6, - Padding: core.Edges{Left: 6, Right: 6, Bottom: 4}, + Position: core.Absolute, + Left: leftPt, + Top: topPt, + Direction: core.Row, + Gap: 6, + Padding: core.Symmetric(4, 5), + CornerRadius: 8, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, }, - StyleFunc: func() core.Style { - return core.Style{Color: ed.SpecPalette(cx).TextFaint} + Children: []core.Node{ + core.View{Style: core.Style{Gap: 2}, Children: leftCol}, + core.View{Style: core.Style{Gap: 2}, Children: rightCol}, }, + } + } + + children := make([]core.Node, 0, 7) + children = append(children, core.Text{ + TestID: "viewport-overlay-legend-title", + Content: ed.T("overlays.legendTitle"), + Style: core.Style{ + FontSize: 9.5, + FontWeight: 600, + LetterSpacing: 0.6, + Color: p.TextFaint, + Padding: core.Edges{Left: 4, Right: 4, Top: 1, Bottom: 1}, }, - row("legend-selection", OverlayLegendSelection, "agent.legendSelection", func(p SpecPalette) core.Color { return p.Accent.Edge }, false), - row("legend-agent", OverlayLegendAgent, "agent.legendAgent", func(p SpecPalette) core.Color { return p.Agent.Edge }, false), - row("legend-added", OverlayLegendAdded, "agent.legendAdded", func(p SpecPalette) core.Color { return p.Added.Edge }, true), - row("legend-changed", OverlayLegendChanged, "agent.legendChanged", func(p SpecPalette) core.Color { return p.Changed.Edge }, true), - row("legend-removed", OverlayLegendRemoved, "agent.legendRemoved", func(p SpecPalette) core.Color { return p.Removed.Edge }, false), - row("legend-problem", OverlayLegendProblem, "agent.legendProblem", func(p SpecPalette) core.Color { return p.Problem().Edge }, false), - }, - } + }) + for _, kind := range OverlayLegendKinds() { + children = append(children, legendRow(kind)) + } + + return core.View{ + TestID: "viewport-overlay-legend", + Role: core.RoleGroup, + Label: ed.T("overlays.legendTitle"), + Style: core.Style{ + Position: core.Absolute, + Left: leftPt, + Top: topPt, + MinWidth: core.Pt(150), + Padding: core.Symmetric(4, 4), + Gap: 1, + CornerRadius: 8, + Background: p.Raised, + BorderWidth: 1, + BorderColor: p.LineRaised, + }, + Children: children, + } + }) }, } } -// SpecOverlayLegendView renders the complete 6-card Spec.dc.html Overlay Legend board -// (Selection, Agent working, Added, Changed, Removed, Problem) on the active theme's viewport surround, -// using exclusively SpecPalette tokens so every outline (>= 3:1) and pill label (>= 4.5:1) can be -// inspected side by side in Dark and Light appearances. +// SpecOverlayLegendView renders the complete Spec.dc.html Overlay Legend board +// (Selection, Agent working, Added, Changed, Removed, Problem, and Focused change in Review) +// on the active theme's viewport surround, drawing every card through DrawObjectOverlay using +// exclusively SpecPalette tokens so Dark and Light appearances can be inspected side by side. func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Node { return core.Dynamic(func(cx *core.Scope) core.Node { _ = rev.Get() @@ -903,7 +1084,21 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) modeLabel = "Dark theme" } - card := func(testID, title, desc string, preview core.Node) core.Node { + drawVPBackdrop := func(d *core.Drawing, sz core.Size) { + w, h := float32(sz.Width), float32(sz.Height) + d.SetFillColor(p.Viewport).FillRect(0, 0, w, h) + d.SetFillColor(p.ViewportDot) + for y := float32(8); y < h; y += 16 { + for x := float32(8); x < w; x += 16 { + d.FillRect(x, y, 1.2, 1.2) + } + } + floorY := h - 34 + d.SetFillColor(p.Inset).FillRect(0, floorY, w, 34) + d.SetFillColor(p.LineRaised).FillRect(0, floorY, w, 3) + } + + card := func(testID, title, desc string, drawPreview func(d *core.Drawing, sz core.Size)) core.Node { return core.View{ TestID: testID, Style: core.Style{ @@ -922,7 +1117,15 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) BorderColor: p.Line, Overflow: core.Hidden, }, - Children: []core.Node{preview}, + Children: []core.Node{ + core.Canvas{ + Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, + Draw: func(d *core.Drawing, sz core.Size) { + drawVPBackdrop(d, sz) + drawPreview(d, sz) + }, + }, + }, }, core.Text{ Content: title, @@ -943,116 +1146,16 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) } } - drawVPBackdrop := func(d *core.Drawing, sz core.Size) { - w, h := float32(sz.Width), float32(sz.Height) - d.SetFillColor(p.Viewport).FillRect(0, 0, w, h) - d.SetFillColor(p.ViewportDot) - for y := float32(8); y < h; y += 16 { - for x := float32(8); x < w; x += 16 { - d.FillRect(x, y, 1.2, 1.2) - } - } - // Floor strip using Spec Inset / LineRaised tokens. - floorY := h - 34 - d.SetFillColor(p.Inset).FillRect(0, floorY, w, 34) - d.SetFillColor(p.LineRaised).FillRect(0, floorY, w, 3) - } - - pillNode := func(testID, label string, fg, bg, border core.Color, strikePrefix string) core.Node { - kids := []core.Node{} - if strikePrefix != "" { - kids = append(kids, core.Text{ - Content: strikePrefix, - Style: core.Style{ - FontFamily: core.FontMonospace, - FontSize: 11, - FontWeight: 500, - Color: fg, - TextDecoration: core.TextDecorationLineThrough, - }, - }) - } - kids = append(kids, core.Text{ - Content: label, - Style: core.Style{ - FontFamily: core.FontMonospace, - FontSize: 11, - FontWeight: 600, - Color: fg, - }, - }) - st := core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 6, - Height: core.Pt(22), - Padding: core.Symmetric(0, 8), - CornerRadius: 11, - Background: bg, - JustifyContent: core.JustifyCenter, - } - if border != core.Transparent { - st.BorderWidth = 1 - st.BorderColor = border - } - return core.View{TestID: testID, Style: st, Children: kids} - } - selectionCard := card( "spec-legend-selection", "Selection", "accent · 1.5 px solid · four handles and a name tag.", - core.View{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100), Position: core.Relative}, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, - Draw: func(d *core.Drawing, sz core.Size) { - drawVPBackdrop(d, sz) - cx := float32(sz.Width) / 2 - fy := float32(sz.Height) - 34 - d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() - d.SetStrokeColor(p.Accent.Edge).SetLineWidth(1.5).BeginPath().RoundRect(cx-18, fy-40, 36, 46, 6).Stroke() - for _, pt := range [4][2]float32{{cx - 18, fy - 40}, {cx + 18, fy - 40}, {cx - 18, fy + 6}, {cx + 18, fy + 6}} { - d.SetFillColor(p.Raised).FillRect(pt[0]-4, pt[1]-4, 8, 8) - d.SetStrokeColor(p.Accent.Edge).SetLineWidth(1.5).StrokeRect(pt[0]-4, pt[1]-4, 8, 8) - } - }, - }, - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(56), - Direction: core.Row, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - core.View{ - TestID: "spec-legend-selection-tag", - Style: core.Style{ - Height: core.Pt(20), - Padding: core.Symmetric(0, 8), - CornerRadius: 5, - Background: p.Accent.Fg, - AlignItems: core.AlignCenter, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - core.Text{ - Content: "Knight", - Style: core.Style{ - FontSize: 11, - FontWeight: 600, - Color: p.Accent.OnFill, - }, - }, - }, - }, - }, - }, - }, + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 12), Y: core.Points(fy - 34)}, Size: core.Size{Width: 24, Height: 34}} + d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindSelection, Label: "Knight", Bounds: bounds, CanvasSize: sz}) }, ) @@ -1060,62 +1163,12 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) "spec-legend-agent", "Agent working", "agent · 1.5 px solid · pulsing violet · agent pill.", - core.View{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100), Position: core.Relative}, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, - Draw: func(d *core.Drawing, sz core.Size) { - drawVPBackdrop(d, sz) - cx := float32(sz.Width) / 2 - fy := float32(sz.Height) - 34 - d.SetFillColor(ui.Alpha(p.Agent.Fg, 0.28)).BeginPath().RoundRect(cx-15, fy-22, 30, 22, 8).Fill() - d.SetStrokeColor(p.Agent.Edge).SetLineWidth(1.5).BeginPath().RoundRect(cx-19, fy-26, 38, 30, 10).Stroke() - }, - }, - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(68), - Direction: core.Row, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - core.View{ - TestID: "spec-legend-agent-pill", - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 6, - Height: core.Pt(22), - Padding: core.Symmetric(0, 8), - CornerRadius: 11, - Background: p.PillBg, - BorderWidth: 1, - BorderColor: p.Agent.Edge, - }, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pt(10), Height: core.Pt(10)}, - Draw: func(d *core.Drawing, _ core.Size) { - d.SetFillColor(p.Agent.Fg).BeginPath().MoveTo(5, 0.5).LineTo(6.6, 3.4).LineTo(9.5, 5).LineTo(6.6, 6.6).LineTo(5, 9.5).LineTo(3.4, 6.6).LineTo(0.5, 5).LineTo(3.4, 3.4).ClosePath().Fill() - }, - }, - core.Text{ - Content: "placing slime_02", - Style: core.Style{ - FontSize: 11, - FontWeight: 500, - Color: p.TextSecondary, - }, - }, - }, - }, - }, - }, - }, + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 15), Y: core.Points(fy - 22)}, Size: core.Size{Width: 30, Height: 22}} + d.SetFillColor(ui.Alpha(p.Agent.Fg, 0.28)).BeginPath().RoundRect(cx-15, fy-22, 30, 22, 8).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindAgent, Label: "placing slime_02", Bounds: bounds, CanvasSize: sz}) }, ) @@ -1123,33 +1176,12 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) "spec-legend-added", "Added", "added · 1.5 px dashed · “+ name” pill.", - core.View{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100), Position: core.Relative}, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, - Draw: func(d *core.Drawing, sz core.Size) { - drawVPBackdrop(d, sz) - cx := float32(sz.Width) / 2 - fy := float32(sz.Height) - 34 - d.SetFillColor(ui.Alpha(p.Added.Fg, 0.28)).BeginPath().RoundRect(cx-15, fy-22, 30, 22, 8).Fill() - d.SetStrokeColor(p.Added.Edge).SetLineWidth(1.5).SetLineDash(5, 3).BeginPath().RoundRect(cx-19, fy-26, 38, 30, 10).Stroke() - }, - }, - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(68), - Direction: core.Row, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - pillNode("spec-legend-added-pill", "+ slime_03", p.Added.Fg, p.Added.Fill, p.Added.Edge, ""), - }, - }, - }, + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 15), Y: core.Points(fy - 22)}, Size: core.Size{Width: 30, Height: 22}} + d.SetFillColor(ui.Alpha(p.Added.Fg, 0.28)).BeginPath().RoundRect(cx-15, fy-22, 30, 22, 8).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindAdded, Label: "slime_03", Bounds: bounds, CanvasSize: sz}) }, ) @@ -1157,101 +1189,68 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) "spec-legend-changed", "Changed", "changed · 1.5 px dashed · field old → new pill.", - core.View{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100), Position: core.Relative}, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, - Draw: func(d *core.Drawing, sz core.Size) { - drawVPBackdrop(d, sz) - cx := float32(sz.Width) / 2 - fy := float32(sz.Height) - 34 - d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() - d.SetStrokeColor(p.Changed.Edge).SetLineWidth(1.5).SetLineDash(5, 3).BeginPath().RoundRect(cx-17, fy-39, 34, 44, 6).Stroke() - }, - }, - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(56), - Direction: core.Row, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - pillNode("spec-legend-changed-pill", "z 10 → 12", p.Changed.Fg, p.Changed.Fill, p.Changed.Edge, ""), - }, - }, - }, + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 12), Y: core.Points(fy - 34)}, Size: core.Size{Width: 24, Height: 34}} + d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindChanged, Label: "z 10 → 12", Bounds: bounds, CanvasSize: sz}) }, ) removedCard := card( "spec-legend-removed", "Removed", - "removed · 1.5 px solid around ghost · struck-through name.", - core.View{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100), Position: core.Relative}, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, - Draw: func(d *core.Drawing, sz core.Size) { - drawVPBackdrop(d, sz) - cx := float32(sz.Width) / 2 - fy := float32(sz.Height) - 34 - d.SetFillColor(ui.Alpha(p.TextFaint, 0.30)).BeginPath().Ellipse(cx, fy-16, 8, 8).Fill() - d.SetStrokeColor(p.Removed.Edge).SetLineWidth(1.5).BeginPath().RoundRect(cx-13, fy-29, 26, 26, 6).Stroke() - }, - }, - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(64), - Direction: core.Row, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - pillNode("spec-legend-removed-pill", "removed", p.Removed.Fg, p.Removed.Fill, p.Removed.Edge, "coin_04"), - }, - }, - }, + "removed · 1.5 px solid around 25% grey ghost · struck-through name.", + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 10), Y: core.Points(fy - 24)}, Size: core.Size{Width: 20, Height: 20}} + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindRemoved, Label: "coin_04", Bounds: bounds, CanvasSize: sz}) }, ) problemCard := card( "spec-legend-problem", "Problem", - "problem · 2 px solid on live object · filled pill.", - core.View{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100), Position: core.Relative}, - Children: []core.Node{ - core.Canvas{ - Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}, - Draw: func(d *core.Drawing, sz core.Size) { - drawVPBackdrop(d, sz) - cx := float32(sz.Width) / 2 - fy := float32(sz.Height) - 34 - d.SetFillColor(p.TextMuted).BeginPath().RoundRect(cx-14, fy-38, 28, 38, 4).Fill() - d.SetStrokeColor(p.Problem().Edge).SetLineWidth(2).BeginPath().RoundRect(cx-18, fy-42, 36, 46, 6).Stroke() - }, - }, - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: core.Pt(0), - Right: core.Pt(0), - Top: core.Pt(52), - Direction: core.Row, - JustifyContent: core.JustifyCenter, - }, - Children: []core.Node{ - pillNode("spec-legend-problem-pill", "door: lever_02 missing", p.Problem().OnFill, p.Problem().Fg, core.Transparent, ""), - }, - }, - }, + "problem · 2 px solid on live object · filled alert pill.", + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 14), Y: core.Points(fy - 38)}, Size: core.Size{Width: 28, Height: 38}} + d.SetFillColor(p.TextMuted).BeginPath().RoundRect(cx-14, fy-38, 28, 38, 4).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindProblem, Label: "door: lever_02 missing", Bounds: bounds, CanvasSize: sz}) + }, + ) + + focusedCard := card( + "spec-legend-focused", + "Focused change in Review", + "own color & dash · 2.5 px · outlined pill · never accent.", + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + leftBounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 56), Y: core.Points(fy - 22)}, Size: core.Size{Width: 30, Height: 22}} + d.SetFillColor(ui.Alpha(p.Added.Fg, 0.28)).BeginPath().RoundRect(cx-56, fy-22, 30, 22, 8).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindAdded, Bounds: leftBounds, CanvasSize: sz}) + + rightBounds := core.Bounds{Origin: core.Point{X: core.Points(cx + 12), Y: core.Points(fy - 22)}, Size: core.Size{Width: 30, Height: 22}} + d.SetFillColor(ui.Alpha(p.Added.Fg, 0.45)).BeginPath().RoundRect(cx+12, fy-22, 30, 22, 8).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindFocusedChange, ChangeKind: OverlayKindAdded, Label: "slime_02", Bounds: rightBounds, CanvasSize: sz}) + }, + ) + + pairedCard := card( + "spec-legend-paired", + "Selection + Agent", + "selection keeps handles · agent outline sits 3 px further out.", + func(d *core.Drawing, sz core.Size) { + cx := float32(sz.Width) / 2 + fy := float32(sz.Height) - 34 + bounds := core.Bounds{Origin: core.Point{X: core.Points(cx - 12), Y: core.Points(fy - 34)}, Size: core.Size{Width: 24, Height: 34}} + d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindSelection, Label: "Knight", Bounds: bounds, CanvasSize: sz}) + DrawObjectOverlay(d, p, ObjectOverlay{Kind: OverlayKindAgent, Label: "tuning jump", Bounds: bounds, CanvasSize: sz, PairedWithSelection: true, PillStackOffset: 24}) }, ) @@ -1321,14 +1320,14 @@ func SpecOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) Direction: core.Row, Gap: 16, }, - Children: []core.Node{selectionCard, agentCard, addedCard}, + Children: []core.Node{selectionCard, agentCard, addedCard, changedCard}, }, core.View{ Style: core.Style{ Direction: core.Row, Gap: 16, }, - Children: []core.Node{changedCard, removedCard, problemCard}, + Children: []core.Node{removedCard, problemCard, focusedCard, pairedCard}, }, }, } diff --git a/packages/game/editor/state.go b/packages/game/editor/state.go index 75a227a15..9868f99a4 100644 --- a/packages/game/editor/state.go +++ b/packages/game/editor/state.go @@ -886,8 +886,16 @@ type Editor struct { toastSeq uint64 toastNextInst uint64 toastRT *toastRuntime - // overlayLegendOpen controls whether the compact Spec overlay legend is shown in the viewport corner. - overlayLegendOpen bool + // overlayLegendHidden hides the compact Spec overlay legend in the viewport top-left corner when true (shown by default in edit mode). + overlayLegendHidden bool + // sceneOverlays holds active live Spec viewport overlays (Agent working, Added, Changed, Removed, Focused change). + sceneOverlays []SceneOverlayEntry + // overlayEpoch is the reference start time used for pulsing task overlays. + overlayEpoch time.Time + // overlayNowFn optionally overrides time.Now for deterministic overlay animation tests. + overlayNowFn func() time.Time + // reduceMotionOverride optionally overrides Scope.Env().ReduceMotion() for tests and headless editors. + reduceMotionOverride *bool // agentLive tracks the pending agent turn, structural diff overlays, active touched objects, and header pill state. agentLive agentLiveState // agentMutating is > 0 while an agent-originated MCP tool executes through RunAsAgent. @@ -1035,7 +1043,8 @@ func New(doc *sceneformat.SceneDoc, resolver sceneformat.AssetResolver) (*Editor open: false, lastStatus: "Ready", }, - settings: DefaultEditorSettings(), + settings: DefaultEditorSettings(), + overlayEpoch: time.Now(), perms: permissionsState{ file: DefaultPermissions(), initialized: true, diff --git a/packages/game/editor/testdata/golden/viewport_overlays_1x.png b/packages/game/editor/testdata/golden/viewport_overlays_1x.png new file mode 100644 index 0000000000000000000000000000000000000000..681d46cb05ea86c6f07050fb494507069dd7f1fe GIT binary patch literal 12580 zcmdUV2Ut@}yRHfd(gdYRkz%1qQBXPvQWI&?q=eo=6%ruS2-2jA^e!cW1c-DKno>oY z1OkX6(hUd!=`}aH_jbGgd(VH*eeQG5bMDMMYi8EW`exQQ-#2Tm_g#=zO5_pCTjiYUWR3gGD(D>_Rlr|fF{{vVEtfOg80VG z$9>FG$KcmBsp%}2CdGBUQ|z=7dh0;kEBAgiMF4;?hW0qV#Rlwq(4(It{16zMmd5nr zZJC;Sqv0RJl1>g`ZA+kzq~Mzkw7k(|KN8X-0LSV5)}DivK|lbDDFcGJ2C^kk9efTp z7oS3pfASwE-z$@?Qm=HyPfZbS=;ybdxB@7!rWV{B#93IMZqTLP|O?febK=ciZ&XC2u zR(ZS$2i5)?^FhsG z*-};me^d_FRtCm2jxWMXdPVp!L^0x8Q-mj6TD@auV?fC*OS=YqtN-~2$?STU;d(>a zD3gDQV+&_dPj#?bvReH3%elqL(Et7wsZ^+f+)fR4g0cH#5R=JiWRf$BO1Q1h^gXa& z*q3S)PqgxTY=eFupFo6S1P>ENki`NMovISSqC%lRlzT4#!p|w$p){6}oHMv{ZM9FP zRpQgzYl;KX%D>yzKg-J}vD!=}wg%1nCS!gc_FGHITe%#j&HMJji|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V z%Y7mWv2vnnT@V!1?M%2m`9;U+EA?3Na)GA+l^aseMQ2B?-516^_ybe7bvHLtFfras z%fp2%I0~4~q5u7(X$4csjct{Qd~iY1YAf;MTv*Wr`^Bg2(M#s$>31}?mUm0>vx9Yj z^F9u!TW*Ub*f!&d3X>gGgu71ps7|n&CF`ScrdLnPrLf3M z^Cz^gr6wE36I~mn>r+?p;`814HY+MZ9|er@A686HqQ0RV8|ctXz)Cj6N!&@Y;{ehb zc5>tFzjUMF%hmPqc6=4g`{0mz5Vyhk5BebYWN}T5=?M#k*F)=oZecEz);E|MiQbU> zC*<+(8HfLfjQ~j$yY9nd7{dc31^9*H0Y%tS$)8!9u^CnIU;g@c4r~VgZwJZ+6}#fU zzU%e6l$(?DmRE%lH!%S~=z|T}QymLP{sZY2U_YhIpsw7fws!1v(?y)2Kt%t+#niW5 zR%_1N+z3JUO{@j}U*quu#Qy=UfO!Ii1aBVS^fYbQ-;^vYVJs?P{2M60Z#K({Vm)7a zJ2CV#jsCA+;jbVRZp%uL!h!E_&(wd}|FZwtfmTJZD`Y1Y*&nba?|lZJAO$To9o0$| H>#+X;1hLdd literal 0 HcmV?d00001 diff --git a/packages/game/editor/testdata/golden/viewport_overlays_2x.png b/packages/game/editor/testdata/golden/viewport_overlays_2x.png new file mode 100644 index 0000000000000000000000000000000000000000..e6ec238d3f3438ef3a94dd349d8506810e843d8d GIT binary patch literal 34209 zcmeFZ1zc2H-!_a1qLiR0Fmxj!l0$ccA|Wv#q97nWF!U(h-7p|hN(>?;LySr(&5SVA zfP%!3A}#d|c+S!L96jg$e((D}&+~rYy|4Y-EB4x}_KN?CYlU6cRv{s#AtoRoAW>6Q z)FmJ|9Z5iNJdx-)-lm)+YMp@KA%U8roSsMK!r)aB0)cbQuZp-Iaw}{pbWxo{W^!1* z+$@e^Rg1^pd8QCTlpIi%5XT6}3joKG{>SiNnFk0?6iJv4E`40D9^fM`&UQl1@~-?b2zY#F&&aEhyG!9C})IQ-V14=|8jS{ zuR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4k_VJasenC!a&N zFpSY{Ppb}{I~@JtAxB;Nt+H-nxiLLB}*cK#CYw2Z$UK&hj? z_gDVsb``GjNZaO~gp#n1k8>TncJggunhWGaGOWPMHaq-nh#gW8o=OK_iCY!>X#~E@ zQ`8<$kpIzoLN3Aht9{%LlAI*G5K-%rXCm4C$gf)^QY^oyVi1jJ`78hMdpBwS$Jp=w z4cBuOYI8VGtB7@ zSuH6h>RI!DnyH)DkQAH-+{;qu5W z)%x_Y1_7vZMe7Z!_$^&~ITh2}Vg~)>D<`BjU5^ha|xns750Bdh+O6X literal 0 HcmV?d00001 diff --git a/packages/game/editor/viewport.go b/packages/game/editor/viewport.go index 185e96e74..110cf60eb 100644 --- a/packages/game/editor/viewport.go +++ b/packages/game/editor/viewport.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "slices" + "time" "github.com/nsgo-dev/game/packages/game/math2d" "github.com/nsgo-dev/game/packages/game/particles" @@ -516,6 +517,7 @@ func (e *Editor) DrawViewport(d *core.Drawing, size core.Size) { e.drawSelectionOverlay(d, scene) e.drawAgentTaskOverlays(d, scene) e.drawAgentLiveOverlays(d, scene) + e.drawSceneOverlays2D(d, scene) e.drawComponentShapes2D(d, scene) e.drawViewportOverlays(d, scene) e.drawProblemOverlays2D(d, scene) @@ -603,41 +605,43 @@ func (e *Editor) drawCameraFrameOverlay(d *core.Drawing) { highlight := e.ShowingSceneSettings() spec := e.SpecPalette(nil) d.Save() + // Camera frame, camera bounds, and camera handle use neutral Spec tokens in a 1 px hairline/dotted + // style distinct from all semantic overlay legend kinds (never Accent, Agent, Added, Changed, Removed, Problem). if highlight { - d.SetStrokeColor(spec.Accent.Edge).SetLineWidth(1.5) + d.SetStrokeColor(ui.Alpha(spec.TextMuted, 0.9)).SetLineWidth(1) } else { - d.SetStrokeColor(ui.Alpha(spec.TextMuted, 0.7)).SetLineWidth(1) + d.SetStrokeColor(ui.Alpha(spec.TextFaint, 0.65)).SetLineWidth(1) } strokePolygon(d, corners(0, 0, vw, vh, e.ScreenToCanvas)) if e.Doc != nil && e.Doc.Camera != nil && e.Doc.Camera.Bounds != nil && e.drawOverlayOverride == nil { b := e.Doc.Camera.Bounds if highlight { - d.SetStrokeColor(ui.Alpha(spec.Changed.Edge, 0.95)).SetLineWidth(1.5).SetLineDash(6, 4) + d.SetStrokeColor(ui.Alpha(spec.TextMuted, 0.85)).SetLineWidth(1).SetLineDash(2, 4) strokePolygon(d, corners(b.X, b.Y, b.Width, b.Height, e.WorldToCanvas)) if e.Tool == ToolSelect || e.Tool == ToolMove { - drawWorldRectHandles(e, d, b.X, b.Y, b.Width, b.Height, e.cameraBoundsDrag.handle, spec.Raised, spec.Changed.Edge, spec.Changed.Fg) + drawWorldRectHandles(e, d, b.X, b.Y, b.Width, b.Height, e.cameraBoundsDrag.handle, spec.Raised, spec.TextMuted, spec.TextPrimary) } } } if hx, hy, ok := e.CameraHandleCanvasPos(); ok { // If bounds clamp the visible frame away from the camera's configured position, - // draw a dashed tether from the handle to the clamped frame center. + // draw a fine dotted tether from the handle to the clamped frame center. fcx, fcy := e.ScreenToCanvas(vw/2, vh/2) if math.Hypot(float64(hx-fcx), float64(hy-fcy)) > 1 { - d.SetStrokeColor(ui.Alpha(spec.Accent.Edge, 0.6)).SetLineWidth(1).SetLineDash(4, 3) + d.SetStrokeColor(ui.Alpha(spec.TextFaint, 0.7)).SetLineWidth(1).SetLineDash(2, 4) d.BeginPath().MoveTo(hx, hy).LineTo(fcx, fcy).Stroke() } - // Reset dash for the solid crosshair and circular handle. + // Reset dash for the solid neutral crosshair and circular handle. d.SetLineDash() const arm float32 = 10 - d.SetStrokeColor(spec.Accent.Edge).SetLineWidth(1.5) + d.SetStrokeColor(spec.TextMuted).SetLineWidth(1) d.BeginPath().MoveTo(hx-arm, hy).LineTo(hx+arm, hy).MoveTo(hx, hy-arm).LineTo(hx, hy+arm).Stroke() r := float32(5) fill := spec.Raised - stroke := spec.Accent.Edge + stroke := spec.TextMuted if e.cameraDrag.active { r = 6 - fill = spec.Accent.Edge + fill = spec.TextPrimary stroke = spec.Raised } d.SetFillColor(fill).SetStrokeColor(stroke).SetLineWidth(1.5) @@ -656,10 +660,11 @@ func (e *Editor) drawTileGridOverlay(d *core.Drawing) { } space, px, py := e.layerSpaceAndParallax(layerName) m := e.layerAffineFor(space, px, py) + spec := e.SpecPalette(nil) d.Save() applyAffine(d, m) - // The grid is a hairline at any zoom. - d.SetStrokeColor(core.RGBA(0xFFFFFF, 0.2)).SetLineWidth(1 / strokeScale(m)) + // The tile grid is a neutral hairline using Spec tokens, distinct from every legend kind. + d.SetStrokeColor(ui.Alpha(spec.TextFaint, 0.22)).SetLineWidth(1 / strokeScale(m)) ox, oy := tm.OffsetX, tm.OffsetY totalW := float32(tm.Width) * float32(tm.TileWidth) totalH := float32(tm.Height) * float32(tm.TileHeight) @@ -804,7 +809,7 @@ func drawBuiltLayer(d *core.Drawing, layer *sceneformat.BuiltLayer) { } func (e *Editor) drawSelectionOverlay(d *core.Drawing, scene *sceneformat.BuiltScene) { - if !e.OverlayLegendKindEnabled(OverlayLegendSelection) { + if !e.OverlayKindVisible(OverlayKindSelection) { return } ids := e.SelectedIDs() @@ -812,31 +817,16 @@ func (e *Editor) drawSelectionOverlay(d *core.Drawing, scene *sceneformat.BuiltS return } spec := e.SpecPalette(nil) + canvas := core.Size{Width: core.Points(e.canvasW), Height: core.Points(e.canvasH)} d.Save() drawn := 0 var minX, maxX, minY, maxY float32 for _, id := range ids { bo := scene.Object(id) - if bo == nil || bo.Doc == nil || viewFlagged(e.hidden, bo) { + bounds, corners, ok := e.builtObjectCanvasBounds(scene, bo) + if !ok { continue } - space := sceneformat.SpaceWorld - var px, py float32 = 1, 1 - if layer := scene.Layer(bo.Layer); layer != nil { - if !layer.Visible { - continue - } - space = layer.Space - px, py = layer.ParallaxX, layer.ParallaxY - } - m := e.layerAffineFor(space, px, py).Mul(bo.World) - rx, ry, rw, rh := objectOutline(bo) - corners := []math2d.Vec2{ - m.TransformPoint(math2d.Vec2{X: rx, Y: ry}), - m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry}), - m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry + rh}), - m.TransformPoint(math2d.Vec2{X: rx, Y: ry + rh}), - } for _, c := range corners { if drawn == 0 { minX, maxX, minY, maxY = c.X, c.X, c.Y, c.Y @@ -845,8 +835,13 @@ func (e *Editor) drawSelectionOverlay(d *core.Drawing, scene *sceneformat.BuiltS minY, maxY = min(minY, c.Y), max(maxY, c.Y) } } - d.SetStrokeColor(spec.Accent.Edge).SetLineWidth(1.5) - strokePolygon(d, corners) + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindSelection, + Label: e.objectDisplayName(bo, id), + Bounds: bounds, + Corners: corners, + CanvasSize: canvas, + }) drawn++ } if drawn > 1 { @@ -856,11 +851,11 @@ func (e *Editor) drawSelectionOverlay(d *core.Drawing, scene *sceneformat.BuiltS d.Restore() } -// drawAgentTaskOverlays draws numbered violet overlays (editing solid, holding at 45% opacity -// with clock glyph and "waiting on " pill) for active background agent tasks on the open scene, -// following docs/design/editor/Tasks.dc.html and Spec.dc.html. +// drawAgentTaskOverlays draws numbered violet overlays (editing solid pulsing 1.6 s between 100% and 45%, +// holding at 45% dashed with clock glyph and "waiting on " pill) for active background agent tasks +// on the open scene through DrawObjectOverlay, respecting the Agent working legend toggle and ReduceMotion. func (e *Editor) drawAgentTaskOverlays(d *core.Drawing, scene *sceneformat.BuiltScene) { - if !e.ShowAgentChanges() || !e.OverlayLegendKindEnabled(OverlayLegendAgent) || e.HistoryPreviewActive() { + if !e.ShowAgentChanges() || !e.OverlayKindVisible(OverlayKindAgent) || e.HistoryPreviewActive() { return } ovs := e.SceneTaskOverlays() @@ -868,60 +863,36 @@ func (e *Editor) drawAgentTaskOverlays(d *core.Drawing, scene *sceneformat.Built return } spec := e.SpecPalette(nil) - d.Save() - fontNum := core.Font{Size: 10, Weight: 600} - fontLbl := core.Font{Size: 11, Weight: 500} + now := e.overlayNow() + rm := e.ReduceMotion() + canvas := core.Size{Width: core.Points(e.canvasW), Height: core.Points(e.canvasH)} type objBox struct { - ov ObjectTaskOverlay - minX, minY float32 - maxX, maxY float32 - pad float32 + ov ObjectTaskOverlay + bounds core.Bounds + paired bool } var boxes []objBox for _, ov := range ovs { bo := scene.Object(ov.ObjectID) - if bo == nil || bo.Doc == nil || viewFlagged(e.hidden, bo) { + bounds, _, ok := e.builtObjectCanvasBounds(scene, bo) + if !ok { continue } - space := sceneformat.SpaceWorld - var px, py float32 = 1, 1 - if layer := scene.Layer(bo.Layer); layer != nil { - if !layer.Visible { - continue - } - space = layer.Space - px, py = layer.ParallaxX, layer.ParallaxY - } - m := e.layerAffineFor(space, px, py).Mul(bo.World) - rx, ry, rw, rh := objectOutline(bo) - corners := []math2d.Vec2{ - m.TransformPoint(math2d.Vec2{X: rx, Y: ry}), - m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry}), - m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry + rh}), - m.TransformPoint(math2d.Vec2{X: rx, Y: ry + rh}), - } - minX, maxX := corners[0].X, corners[0].X - minY, maxY := corners[0].Y, corners[0].Y - for _, c := range corners[1:] { - minX, maxX = min(minX, c.X), max(maxX, c.X) - minY, maxY = min(minY, c.Y), max(maxY, c.Y) - } - pad := float32(3) - if e.IsSelected(ov.ObjectID) { - pad = 6 - } - outlineColor := spec.Agent.Edge - if ov.Holding { - outlineColor = ui.Alpha(spec.Agent.Edge, 0.45) - d.SetLineDash(4, 3) - } else { - d.SetLineDash() - } - d.SetStrokeColor(outlineColor).SetLineWidth(1.5) - d.BeginPath().RoundRect(minX-pad, minY-pad, (maxX-minX)+pad*2, (maxY-minY)+pad*2, 4).Stroke() - d.SetLineDash() - boxes = append(boxes, objBox{ov: ov, minX: minX, minY: minY, maxX: maxX, maxY: maxY, pad: pad}) + paired := e.IsSelected(ov.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + // Draw the pulsing/holding outline on every target object (pill drawn once per task group below). + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindAgent, + TaskNumber: ov.TaskNumber, + Holding: ov.Holding, + Bounds: bounds, + CanvasSize: canvas, + PairedWithSelection: paired, + Elapsed: now.Sub(e.overlayEpoch), + HasElapsed: true, + ReduceMotion: rm, + }) + boxes = append(boxes, objBox{ov: ov, bounds: bounds, paired: paired}) } // Pick one anchor box per (taskID, holding) group — preferring the highest object so holding @@ -938,86 +909,58 @@ func (e *Editor) drawAgentTaskOverlays(d *core.Drawing, scene *sceneformat.Built if !exists { groupOrder = append(groupOrder, k) anchorByGroup[k] = b - } else if b.minY < prev.minY { + } else if b.bounds.Origin.Y < prev.bounds.Origin.Y { anchorByGroup[k] = b } } - type rectF struct{ x, y, w, h float32 } - overlapsAny := func(r rectF, placed []rectF) bool { + overlapsAny := func(r core.Bounds, placed []core.Bounds) bool { for _, o := range placed { - if r.x < o.x+o.w+6 && r.x+r.w+6 > o.x && r.y < o.y+o.h+4 && r.y+r.h+4 > o.y { + if r.Origin.X < o.Origin.X+o.Size.Width+6 && + r.Origin.X+r.Size.Width+6 > o.Origin.X && + r.Origin.Y < o.Origin.Y+o.Size.Height+4 && + r.Origin.Y+r.Size.Height+4 > o.Origin.Y { return true } } return false } - var placed []rectF + var placed []core.Bounds for _, k := range groupOrder { b := anchorByGroup[k] - ov := b.ov - label := ov.Label - numStr := fmt.Sprintf("%d", ov.TaskNumber) - clockW := float32(0) - if ov.Holding { - clockW = 16 - } - textW := float32(len([]rune(label))) * 6.2 - pillW := 4 + 16 + 6 + clockW + textW + 8 - const pillH float32 = 22 - cx := (b.minX + b.maxX) * 0.5 - pillX := cx - pillW*0.5 - pillY := b.minY - b.pad - pillH - 8 - if pillY < 8 { - pillY = b.maxY + b.pad + 8 + stackOff := float32(0) + if b.paired { + stackOff = 24 } for range 8 { - if !overlapsAny(rectF{pillX, pillY, pillW, pillH}, placed) { + estY := float32(b.bounds.Origin.Y) - OverlayBaseOffset - 22 - 8 - stackOff + est := core.Bounds{ + Origin: core.Point{X: b.bounds.Origin.X, Y: core.Points(estY)}, + Size: core.Size{Width: core.Points(max(float32(len([]rune(b.ov.Label)))*6.2+40, 80)), Height: 22}, + } + if !overlapsAny(est, placed) { break } - pillY -= pillH + 6 - } - placed = append(placed, rectF{pillX, pillY, pillW, pillH}) - - pillBorder := spec.Agent.Edge - if ov.Holding { - pillBorder = spec.LineRaised - } - d.SetFillColor(ui.Alpha(spec.PillBg, 0.94)) - d.BeginPath().RoundRect(pillX, pillY, pillW, pillH, 11).Fill() - d.SetStrokeColor(pillBorder).SetLineWidth(1) - d.BeginPath().RoundRect(pillX, pillY, pillW, pillH, 11).Stroke() - - // Number circle badge. - badgeCX := pillX + 12 - badgeCY := pillY + pillH*0.5 - if ov.Holding { - d.SetStrokeColor(spec.Agent.Edge).SetLineWidth(1.5) - d.BeginPath().Ellipse(badgeCX, badgeCY, 7.5, 7.5).Stroke() - d.SetFillColor(spec.TextSecondary).FillText(numStr, badgeCX-3, badgeCY+3.5, fontNum) - } else { - d.SetFillColor(spec.Agent.Fg).BeginPath().Ellipse(badgeCX, badgeCY, 8, 8).Fill() - d.SetFillColor(spec.Agent.OnFill).FillText(numStr, badgeCX-3, badgeCY+3.5, fontNum) + stackOff += 28 + } + pill := DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindAgent, + Label: b.ov.Label, + TaskNumber: b.ov.TaskNumber, + Holding: b.ov.Holding, + Bounds: b.bounds, + CanvasSize: canvas, + PairedWithSelection: b.paired, + PillStackOffset: stackOff, + Elapsed: now.Sub(e.overlayEpoch), + HasElapsed: true, + ReduceMotion: rm, + }) + if pill.Size.Width > 0 && pill.Size.Height > 0 { + placed = append(placed, pill) } - - curX := pillX + 26 - if ov.Holding { - // Clock glyph beside task number (never hue-only). - ccx := curX + 5 - ccy := pillY + pillH*0.5 - d.SetStrokeColor(spec.TextMuted).SetLineWidth(1.4).SetLineCap(core.CapRound) - d.BeginPath().Ellipse(ccx, ccy, 5, 5).Stroke() - d.BeginPath().MoveTo(ccx, ccy-2.5).LineTo(ccx, ccy).LineTo(ccx+2.2, ccy+1.4).Stroke() - curX += clockW - } - txtColor := spec.TextSecondary - if ov.Holding { - txtColor = spec.TextMuted - } - d.SetFillColor(txtColor).FillText(label, curX, pillY+14.5, fontLbl) } - d.Restore() } // wheelZoomPoints is how far a wheel moves the content, in points, to double or halve the 2D view's zoom: a notch of 40 points zooms by about 15%. @@ -1344,6 +1287,41 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod agentPulseRev.Set(ed.AgentPulseRevision()) }) cx.Cleanup(unsubAgentPulse) + + // Animate active Agent working pulses (1.6 s) and change overlay fade-ins (240 ms). + // Disabled completely when ReduceMotion is enabled so nothing fades or pulses. + overlayAnimRev := core.NewSignal(cx, uint64(0)) + animateOverlays := core.NewMemo(cx, func() bool { + _ = rev.Get() + if cx.Env().ReduceMotion() || ed.ReduceMotion() { + return false + } + return ed.hasAnimatedOverlays() + }) + cx.Effect(func() { + if !animateOverlays.Get() { + return + } + stopped := false + var stop func() bool + var tick func() + tick = func() { + if stopped { + return + } + overlayAnimRev.Set(overlayAnimRev.Get() + 1) + if !cx.Env().ReduceMotion() && ed.hasAnimatedOverlays() { + stop = cx.AfterFunc(33*time.Millisecond, tick) + } + } + stop = cx.AfterFunc(33*time.Millisecond, tick) + cx.Cleanup(func() { + stopped = true + if stop != nil { + stop() + } + }) + }) var g viewportGestures var g3 viewport3DGestures // frame is the view the 3D viewport's flight locks the pointer to. @@ -1517,6 +1495,7 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod _ = rev.Get() _ = tileAnimRev.Get() _ = agentPulseRev.Get() + _ = overlayAnimRev.Get() ed.DrawViewport(d, size) }, } diff --git a/packages/game/editor/viewport3d.go b/packages/game/editor/viewport3d.go index 8809fb63d..d0e58f5be 100644 --- a/packages/game/editor/viewport3d.go +++ b/packages/game/editor/viewport3d.go @@ -2257,6 +2257,10 @@ func (e *Editor) DrawViewport3D(d *core.Drawing, size core.Size) { e.drawWireframe3D(d, s3, w, h) } + // 5b. Spec viewport overlays (Agent working, Added, Changed, Removed, Focused change, Problem) + // sharing DrawObjectOverlay and the top-left legend toggles with the 2D viewport. + e.drawSceneOverlays3D(d, w, h) + proj := e.Projection3D(w, h) // 6. Active 3D transform gizmo, light/camera handles, and component gizmo handles on the selected object (hidden while painting a GridMap or 3D Terrain brush). @@ -2298,7 +2302,8 @@ func (e *Editor) drawWireframe3D(d *core.Drawing, s *scene3DState, w, h float32) if s.built == nil { return } - d.Save().SetStrokeColor(core.RGBA(0xE2E8F0, 0.55)).SetLineWidth(1).BeginPath() + spec := e.SpecPalette(nil) + d.Save().SetStrokeColor(ui.Alpha(spec.TextSecondary, 0.55)).SetLineWidth(1).BeginPath() drawn := 0 var world [][3]float32 for _, dr := range s.built.Drawables { @@ -2347,7 +2352,8 @@ func (e *Editor) drawGrid3D(d *core.Drawing, w, h float32) { extent := step * float32(half) vc := e.activeView3DCam(w, h) - d.Save().SetStrokeColor(core.RGBA(0x94A3B8, 0.22)).SetLineWidth(1).BeginPath() + spec := e.SpecPalette(nil) + d.Save().SetStrokeColor(ui.Alpha(spec.TextFaint, 0.24)).SetLineWidth(1).BeginPath() hasSegments := false for i := -half; i <= half; i++ { coord := float32(i) * step @@ -2380,13 +2386,14 @@ func (e *Editor) drawOriginAxes3D(d *core.Drawing, w, h float32) { origin := [3]float32{0, 0, 0} vc := e.activeView3DCam(w, h) + spec := e.SpecPalette(nil) axes := []struct { end [3]float32 color core.Color }{ - {[3]float32{axisLen, 0, 0}, core.RGBA(0xEF4444, 0.9)}, - {[3]float32{0, axisLen, 0}, core.RGBA(0x22C55E, 0.9)}, - {[3]float32{0, 0, axisLen}, core.RGBA(0x3B82F6, 0.9)}, + {[3]float32{axisLen, 0, 0}, ui.Alpha(spec.Problem().Fg, 0.9)}, + {[3]float32{0, axisLen, 0}, ui.Alpha(spec.Added.Fg, 0.9)}, + {[3]float32{0, 0, axisLen}, ui.Alpha(spec.Accent.Fg, 0.9)}, } for _, ax := range axes { x0, y0, x1, y1, vis := vc.projectSegment(origin, ax.end, w, h) @@ -2480,21 +2487,25 @@ func (e *Editor) drawSceneObjects3D(d *core.Drawing, w, h float32, overlay bool) return cmp.Compare(b.depth, a.depth) }) + spec := e.SpecPalette(nil) + selVisible := e.OverlayKindVisible(OverlayKindSelection) + canvas := core.Size{Width: core.Points(w), Height: core.Points(h)} + for _, item := range items { occluded := e.vp3d.occludedObjects[item.obj.ID] lod, hasLOD := e.vp3d.lodByObject[item.obj.ID] if item.wireframe { corners := e.objectCorners3DUnder(item.obj, item.parent) - color := core.RGBA(0xCBD5E1, 0.8) + color := ui.Alpha(spec.TextMuted, 0.75) lineWidth := float32(1.25) if occluded { - color = core.RGBA(0x94A3B8, 0.35) + color = ui.Alpha(spec.TextFaint, 0.35) } else if e.ShowLODOverlay && hasLOD { color = lodColor3D(lod) } - if item.selected { - color = core.RGBA(0x38BDF8, 1) - lineWidth = 2.0 + if item.selected && selVisible { + color = spec.Accent.Edge + lineWidth = overlaySelectionWidth } d.Save().SetStrokeColor(color).SetLineWidth(lineWidth) @@ -2521,10 +2532,18 @@ func (e *Editor) drawSceneObjects3D(d *core.Drawing, w, h float32, overlay bool) e.drawObjectLODBadge3D(d, item.obj, lod, w, h) } - if item.selected { - pos := vec32(item.parent.point([3]float64{float64(item.obj.X), float64(item.obj.Y), float64(item.obj.PosZ)})) - if cx, cy, _, vis := vc.project(pos, w, h); vis { - d.Save().SetFillColor(core.RGBA(0x38BDF8, 1)).BeginPath().Arc(cx, cy, 3, 0, float32(2*math.Pi), false).Fill().Restore() + if item.selected && selVisible { + if bounds, vis := e.projectObject3DBounds(item.obj, item.parent, vc, w, h); vis { + name := item.obj.Name + if name == "" { + name = item.obj.ID + } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindSelection, + Label: name, + Bounds: bounds, + CanvasSize: canvas, + }) } } } diff --git a/packages/game/editor/viewport_overlay.go b/packages/game/editor/viewport_overlay.go new file mode 100644 index 000000000..928f4a97d --- /dev/null +++ b/packages/game/editor/viewport_overlay.go @@ -0,0 +1,1265 @@ +package editor + +import ( + "fmt" + "math" + "slices" + "strings" + "time" + + "github.com/nsgo-dev/game/packages/game/math2d" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/ui" +) + +// OverlayKind identifies one of the seven Spec viewport overlay styles defined in +// docs/design/editor/Spec.dc.html ("Overlay legend"). +type OverlayKind string + +const ( + // OverlayKindSelection is the person's selection: accent, 1.5 px solid, four corner handles, name tag. + OverlayKindSelection OverlayKind = "selection" + // OverlayKindAgent is the agent working overlay: agent violet, 1.5 px solid, no handles, + // pulsing 1.6 s between 100% and 45%, pill with agent glyph saying what it is doing. + OverlayKindAgent OverlayKind = "agent" + // OverlayKindAdded marks a newly added object: added green, 1.5 px dashed, "+ name" pill. + OverlayKindAdded OverlayKind = "added" + // OverlayKindChanged marks an edited object: changed amber, 1.5 px dashed, "field old → new" pill. + OverlayKindChanged OverlayKind = "changed" + // OverlayKindRemoved marks a removed object: removed red, 1.5 px solid around a 25% grey ghost, + // pill with struck-through name. + OverlayKindRemoved OverlayKind = "removed" + // OverlayKindProblem marks a live object with a problem: problem red, 2 px solid on the live object, + // filled pill with alert triangle icon and message (never like a removed ghost). + OverlayKindProblem OverlayKind = "problem" + // OverlayKindFocusedChange highlights the focused change in a Review: its own color and dash at 2.5 px + // with an outlined pill, never accent. + OverlayKindFocusedChange OverlayKind = "focused" +) + +// Spec viewport overlay timing and geometry constants (docs/design/editor/Spec.dc.html). +const ( + // OverlayChangeFadeDuration is the fade-in duration for Added, Changed, and Removed overlays. + OverlayChangeFadeDuration = 240 * time.Millisecond + // OverlayAgentPulsePeriod is the full pulse cycle duration for the Agent working outline. + OverlayAgentPulsePeriod = 1600 * time.Millisecond + // OverlayAgentPulseMinAlpha is the minimum opacity reached during an Agent working pulse (45%). + OverlayAgentPulseMinAlpha float32 = 0.45 + + // OverlayBaseOffset is the default gap in points between an object's bounds and its overlay outline. + OverlayBaseOffset float32 = 3 + // OverlaySelectionAgentGap is how much further out the Agent working outline sits when + // paired with the person's Selection on the same object. + OverlaySelectionAgentGap float32 = 3 + + // Spec overlay outline stroke widths in points. + overlaySelectionWidth float32 = 1.5 + overlayAgentWidth float32 = 1.5 + overlayChangeWidth float32 = 1.5 + overlayRemovedWidth float32 = 1.5 + overlayProblemWidth float32 = 2.0 + overlayFocusedWidth float32 = 2.5 + + overlayHandleSize float32 = 8 +) + +// OverlayLegendKinds returns the six toggleable Spec overlay legend kinds in display order: +// Selection, Agent working, Added, Changed, Removed, Problem. +func OverlayLegendKinds() []OverlayKind { + return []OverlayKind{ + OverlayKindSelection, + OverlayKindAgent, + OverlayKindAdded, + OverlayKindChanged, + OverlayKindRemoved, + OverlayKindProblem, + } +} + +// DefaultOverlayLegendKinds returns the canonical sorted IDs of all six legend kinds enabled by default. +func DefaultOverlayLegendKinds() []string { + return []string{ + string(OverlayKindAdded), + string(OverlayKindAgent), + string(OverlayKindChanged), + string(OverlayKindProblem), + string(OverlayKindRemoved), + string(OverlayKindSelection), + } +} + +// IsLegendKind reports whether k is one of the six toggleable rows in the viewport overlay legend. +func (k OverlayKind) IsLegendKind() bool { + switch k { + case OverlayKindSelection, OverlayKindAgent, OverlayKindAdded, OverlayKindChanged, OverlayKindRemoved, OverlayKindProblem: + return true + default: + return false + } +} + +// Valid reports whether k is any of the seven Spec overlay kinds. +func (k OverlayKind) Valid() bool { + return k.IsLegendKind() || k == OverlayKindFocusedChange +} + +// IsChangeKind reports whether k is a diff/review change kind (Added, Changed, or Removed). +func (k OverlayKind) IsChangeKind() bool { + return k == OverlayKindAdded || k == OverlayKindChanged || k == OverlayKindRemoved +} + +// OverlayFadeAlpha returns the opacity in [0, 1] for a change overlay (Added, Changed, Removed) +// elapsed after it appeared. With reduceMotion enabled, it returns 1 immediately without fading. +func OverlayFadeAlpha(elapsed time.Duration, reduceMotion bool) float32 { + if reduceMotion { + return 1 + } + if elapsed <= 0 { + return 0 + } + if elapsed >= OverlayChangeFadeDuration { + return 1 + } + return float32(elapsed) / float32(OverlayChangeFadeDuration) +} + +// OverlayAgentPulseAlpha returns the outline opacity in [0.45, 1.0] for an active Agent working +// overlay pulsing on a 1.6 s period. With reduceMotion enabled, it stays solid at 1.0. +func OverlayAgentPulseAlpha(elapsed time.Duration, reduceMotion bool) float32 { + if reduceMotion { + return 1 + } + period := OverlayAgentPulsePeriod.Seconds() + phase := math.Mod(elapsed.Seconds(), period) / period + if phase < 0 { + phase += 1 + } + wave := 0.5 * (1 + math.Cos(2*math.Pi*phase)) + return OverlayAgentPulseMinAlpha + (1-OverlayAgentPulseMinAlpha)*float32(wave) +} + +// ObjectOverlay describes one Spec viewport overlay drawn over an object's canvas bounds. +type ObjectOverlay struct { + // Kind selects which of the seven Spec overlay styles to draw. + Kind OverlayKind + // ChangeKind, when Kind is OverlayKindFocusedChange, chooses the underlying change kind + // (OverlayKindAdded, OverlayKindChanged, or OverlayKindRemoved; defaults to OverlayKindAdded). + // Focused changes always keep their own semantic color and dash at 2.5 px — never Accent. + ChangeKind OverlayKind + // Label is the primary text shown in the overlay's tag or pill: + // - Selection: object name (for example "Knight") + // - Agent: what the agent is doing (for example "placing slime_02") + // - Added: object name (prefixed with "+ " automatically if absent) + // - Changed: field old → new value (for example "z 10 → 12") + // - Removed: removed object name (drawn struck-through beside SecondaryLabel) + // - Problem: alert message (for example "door: lever_02 is missing") + Label string + // SecondaryLabel optionally overrides the trailing text on Removed pills (defaults to "removed"). + SecondaryLabel string + // TaskNumber, when > 0 on OverlayKindAgent, draws the numbered task badge inside the agent pill. + TaskNumber int + // Holding, when true on OverlayKindAgent, renders the holding (45% dashed + clock glyph) variant. + Holding bool + // Bounds is the object's axis-aligned bounding box in canvas points. + Bounds core.Bounds + // Corners optionally supplies the exact transformed 4-corner quad in canvas points for + // rotated 2D selection outlines. When empty, Bounds is used. + Corners []math2d.Vec2 + // CanvasSize optionally clamps pill placement inside the viewport canvas. + CanvasSize core.Size + // PairedWithSelection, when true on OverlayKindAgent, places the agent outline 3 px further + // out than Selection's outline so Selection keeps its handles inside. + PairedWithSelection bool + // PillStackOffset shifts the pill upward in points to clear another pill on the same object. + PillStackOffset float32 + // Elapsed is the time since this overlay appeared (change fade-in) or started (agent pulse). + // When HasElapsed is false, the overlay renders at full opacity (1.0). + Elapsed time.Duration + HasElapsed bool + // ReduceMotion disables fade-in (instant 100%) and agent outline pulsing (solid 100%). + ReduceMotion bool +} + +// specHandleFill returns the crisp handle fill color from SpecPalette tokens only +// (#FFFFFF in both dark and light modes, matching Spec.dc.html). +func specHandleFill(p SpecPalette) core.Color { + if p.Dark { + return p.TextPrimary + } + return p.Raised +} + +// DrawObjectOverlay is the single Spec viewport overlay drawing helper in editor. +// It draws any of the seven Spec overlay kinds (Selection, Agent working, Added, Changed, +// Removed, Problem, Focused change in Review) using exclusively SpecPalette tokens at the +// Spec's exact line widths, dash patterns, offsets, handles, ghosts, and pills, and returns +// the canvas rectangle occupied by the drawn tag/pill (if any). +func DrawObjectOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay) core.Bounds { + if d == nil || !ov.Kind.Valid() { + return core.Bounds{} + } + bx := float32(ov.Bounds.Origin.X) + by := float32(ov.Bounds.Origin.Y) + bw := float32(ov.Bounds.Size.Width) + bh := float32(ov.Bounds.Size.Height) + if bw < 0 { + bx += bw + bw = -bw + } + if bh < 0 { + by += bh + bh = -bh + } + + d.Save() + defer d.Restore() + + switch ov.Kind { + case OverlayKindSelection: + return drawSelectionSpecOverlay(d, p, ov, bx, by, bw, bh) + case OverlayKindAgent: + return drawAgentSpecOverlay(d, p, ov, bx, by, bw, bh) + case OverlayKindAdded, OverlayKindChanged, OverlayKindRemoved: + return drawChangeSpecOverlay(d, p, ov, ov.Kind, false, bx, by, bw, bh) + case OverlayKindFocusedChange: + base := ov.ChangeKind + if !base.IsChangeKind() { + base = OverlayKindAdded + } + return drawChangeSpecOverlay(d, p, ov, base, true, bx, by, bw, bh) + case OverlayKindProblem: + return drawProblemSpecOverlay(d, p, ov, bx, by, bw, bh) + default: + return core.Bounds{} + } +} + +func clampOverlayPillPos(cx, minY, maxY, pad, pillW, pillH, stackOffset float32, canvas core.Size) (float32, float32) { + px := cx - pillW*0.5 + py := minY - pad - pillH - 8 - stackOffset + if py < 6 { + py = maxY + pad + 8 + stackOffset + } + if canvas.Width > 0 { + cw := float32(canvas.Width) + if px+pillW > cw-6 { + px = cw - pillW - 6 + } + if px < 6 { + px = 6 + } + } + if canvas.Height > 0 { + ch := float32(canvas.Height) + if py+pillH > ch-6 { + py = ch - pillH - 6 + } + if py < 6 { + py = 6 + } + } + return px, py +} + +// expandQuadOutward expands a 4-corner quad outward from its centroid along its edge normals by pad points. +func expandQuadOutward(corners []math2d.Vec2, pad float32) []math2d.Vec2 { + if len(corners) != 4 || pad == 0 { + return corners + } + // Compute signed area to orient outward normals consistently regardless of flip. + area := float32(0) + for i := range 4 { + a, b := corners[i], corners[(i+1)%4] + area += a.X*b.Y - b.X*a.Y + } + sign := float32(1) + if area < 0 { + sign = -1 + } + // Edge outward unit normals. + var normals [4]math2d.Vec2 + for i := range 4 { + a, b := corners[i], corners[(i+1)%4] + dx, dy := b.X-a.X, b.Y-a.Y + l := float32(math.Hypot(float64(dx), float64(dy))) + if l < 1e-4 { + continue + } + // For clockwise screen coords (area > 0), outward normal of (dx, dy) is (dy, -dx). + normals[i] = math2d.Vec2{X: sign * dy / l, Y: -sign * dx / l} + } + out := make([]math2d.Vec2, 4) + for i := range 4 { + nPrev := normals[(i+3)%4] + nCurr := normals[i] + out[i] = math2d.Vec2{ + X: corners[i].X + (nPrev.X+nCurr.X)*pad, + Y: corners[i].Y + (nPrev.Y+nCurr.Y)*pad, + } + } + return out +} + +func drawSelectionSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bx, by, bw, bh float32) core.Bounds { + pad := OverlayBaseOffset + handleHalf := overlayHandleSize * 0.5 + handleFill := specHandleFill(p) + + var handlePts [4]math2d.Vec2 + var minX, minY, maxX, maxY float32 + if len(ov.Corners) == 4 { + expanded := expandQuadOutward(ov.Corners, pad) + d.SetStrokeColor(p.Accent.Edge).SetLineWidth(overlaySelectionWidth).SetLineDash() + strokePolygon(d, expanded) + minX, maxX = expanded[0].X, expanded[0].X + minY, maxY = expanded[0].Y, expanded[0].Y + for i, c := range expanded { + handlePts[i] = c + minX, maxX = min(minX, c.X), max(maxX, c.X) + minY, maxY = min(minY, c.Y), max(maxY, c.Y) + } + } else { + ox, oy := bx-pad, by-pad + ow, oh := bw+2*pad, bh+2*pad + d.SetStrokeColor(p.Accent.Edge).SetLineWidth(overlaySelectionWidth).SetLineDash() + d.BeginPath().RoundRect(ox, oy, ow, oh, 6).Stroke() + handlePts = [4]math2d.Vec2{ + {X: ox, Y: oy}, + {X: ox + ow, Y: oy}, + {X: ox + ow, Y: oy + oh}, + {X: ox, Y: oy + oh}, + } + minX, minY, maxX, maxY = ox, oy, ox+ow, oy+oh + } + + // Four corner handles (8x8 rounded squares, 1.5 px accent border). + for _, pt := range handlePts { + d.SetFillColor(handleFill) + d.BeginPath().RoundRect(pt.X-handleHalf, pt.Y-handleHalf, overlayHandleSize, overlayHandleSize, 2).Fill() + d.SetStrokeColor(p.Accent.Edge).SetLineWidth(overlaySelectionWidth).SetLineDash() + d.BeginPath().RoundRect(pt.X-handleHalf, pt.Y-handleHalf, overlayHandleSize, overlayHandleSize, 2).Stroke() + } + + if ov.Label == "" { + return core.Bounds{} + } + font := core.Font{Size: 10.5, Weight: 600} + const tagH float32 = 18 + tagW := float32(len([]rune(ov.Label)))*6.3 + 12 + tx, ty := clampOverlayPillPos((minX+maxX)*0.5, minY, maxY, handleHalf, tagW, tagH, ov.PillStackOffset, ov.CanvasSize) + + d.SetFillColor(p.Accent.Fg) + d.BeginPath().RoundRect(tx, ty, tagW, tagH, 5).Fill() + d.SetFillColor(p.Accent.OnFill).FillText(ov.Label, tx+6, ty+12.5, font) + return core.Bounds{ + Origin: core.Point{X: core.Points(tx), Y: core.Points(ty)}, + Size: core.Size{Width: core.Points(tagW), Height: core.Points(tagH)}, + } +} + +func drawAgentSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bx, by, bw, bh float32) core.Bounds { + pad := OverlayBaseOffset + if ov.PairedWithSelection { + pad += OverlaySelectionAgentGap + } + alpha := float32(1) + if ov.Holding { + alpha = OverlayAgentPulseMinAlpha + } else if ov.HasElapsed { + alpha = OverlayAgentPulseAlpha(ov.Elapsed, ov.ReduceMotion) + } + + ox, oy := bx-pad, by-pad + ow, oh := bw+2*pad, bh+2*pad + d.SetStrokeColor(ui.Alpha(p.Agent.Edge, alpha)).SetLineWidth(overlayAgentWidth) + if ov.Holding { + d.SetLineDash(4, 3) + } else { + d.SetLineDash() + } + d.BeginPath().RoundRect(ox, oy, ow, oh, 6).Stroke() + d.SetLineDash() + + if ov.Label == "" { + return core.Bounds{} + } + + const pillH float32 = 22 + fontLbl := core.Font{Size: 11, Weight: 500} + textW := float32(len([]rune(ov.Label))) * 6.2 + var pillW float32 + if ov.TaskNumber > 0 { + clockW := float32(0) + if ov.Holding { + clockW = 16 + } + pillW = 4 + 16 + 6 + clockW + textW + 8 + } else { + // 8 left pad + 12 sparkle glyph + 6 gap + text + 8 right pad. + pillW = 8 + 12 + 6 + textW + 8 + } + + px, py := clampOverlayPillPos(bx+bw*0.5, by, by+bh, pad, pillW, pillH, ov.PillStackOffset, ov.CanvasSize) + + pillBorder := ui.Alpha(p.Agent.Edge, 0.65) + if ov.TaskNumber > 0 { + pillBorder = p.Agent.Edge + } + if ov.Holding { + pillBorder = p.LineRaised + } + d.SetFillColor(ui.Alpha(p.PillBg, 0.92)) + d.BeginPath().RoundRect(px, py, pillW, pillH, 11).Fill() + d.SetStrokeColor(pillBorder).SetLineWidth(1) + d.BeginPath().RoundRect(px, py, pillW, pillH, 11).Stroke() + + if ov.TaskNumber > 0 { + fontNum := core.Font{Size: 10, Weight: 600} + numStr := fmt.Sprintf("%d", ov.TaskNumber) + badgeCX := px + 12 + badgeCY := py + pillH*0.5 + if ov.Holding { + d.SetStrokeColor(p.Agent.Edge).SetLineWidth(1.5) + d.BeginPath().Ellipse(badgeCX, badgeCY, 7.5, 7.5).Stroke() + d.SetFillColor(p.TextSecondary).FillText(numStr, badgeCX-3, badgeCY+3.5, fontNum) + } else { + d.SetFillColor(p.Agent.Fg).BeginPath().Ellipse(badgeCX, badgeCY, 8, 8).Fill() + d.SetFillColor(p.Agent.OnFill).FillText(numStr, badgeCX-3, badgeCY+3.5, fontNum) + } + curX := px + 26 + if ov.Holding { + ccx := curX + 5 + ccy := py + pillH*0.5 + d.SetStrokeColor(p.TextMuted).SetLineWidth(1.4).SetLineCap(core.CapRound) + d.BeginPath().Ellipse(ccx, ccy, 5, 5).Stroke() + d.BeginPath().MoveTo(ccx, ccy-2.5).LineTo(ccx, ccy).LineTo(ccx+2.2, ccy+1.4).Stroke() + curX += 16 + } + txtColor := p.TextSecondary + if ov.Holding { + txtColor = p.TextMuted + } + d.SetFillColor(txtColor).FillText(ov.Label, curX, py+14.5, fontLbl) + } else { + // Agent 4-point sparkle glyph in Spec Agent.Fg (never white on violet). + drawAgentSparkleGlyph(d, px+14, py+pillH*0.5, 5, p.Agent.Fg) + d.SetFillColor(p.TextSecondary).FillText(ov.Label, px+26, py+14.5, fontLbl) + } + + return core.Bounds{ + Origin: core.Point{X: core.Points(px), Y: core.Points(py)}, + Size: core.Size{Width: core.Points(pillW), Height: core.Points(pillH)}, + } +} + +// drawAgentSparkleGlyph draws the 4-point star agent glyph centered at (cx, cy) with outer radius r. +func drawAgentSparkleGlyph(d *core.Drawing, cx, cy, r float32, col core.Color) { + inner := r * 0.34 + d.SetFillColor(col) + d.BeginPath(). + MoveTo(cx, cy-r). + LineTo(cx+inner, cy-inner). + LineTo(cx+r, cy). + LineTo(cx+inner, cy+inner). + LineTo(cx, cy+r). + LineTo(cx-inner, cy+inner). + LineTo(cx-r, cy). + LineTo(cx-inner, cy-inner). + ClosePath(). + Fill() +} + +func drawChangeSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, base OverlayKind, focused bool, bx, by, bw, bh float32) core.Bounds { + alpha := float32(1) + if ov.HasElapsed { + alpha = OverlayFadeAlpha(ov.Elapsed, ov.ReduceMotion) + } + if alpha <= 0 { + return core.Bounds{} + } + + var role SpecRole + var dashed bool + switch base { + case OverlayKindChanged: + role = p.Changed + dashed = true + case OverlayKindRemoved: + role = p.Removed + dashed = false + default: // OverlayKindAdded + role = p.Added + dashed = true + } + + pad := OverlayBaseOffset + ox, oy := bx-pad, by-pad + ow, oh := bw+2*pad, bh+2*pad + + // Removed draws a 25% grey ghost inside the solid removed outline so it never resembles Problem. + if base == OverlayKindRemoved { + d.SetFillColor(ui.Alpha(p.TextFaint, 0.25*alpha)) + d.BeginPath().RoundRect(bx, by, bw, bh, 4).Fill() + } + + lw := overlayChangeWidth + if base == OverlayKindRemoved { + lw = overlayRemovedWidth + } + if focused { + lw = overlayFocusedWidth + } + + d.SetStrokeColor(ui.Alpha(role.Edge, alpha)).SetLineWidth(lw) + if dashed { + d.SetLineDash(5, 3) + } else { + d.SetLineDash() + } + d.BeginPath().RoundRect(ox, oy, ow, oh, 6).Stroke() + d.SetLineDash() + + label := ov.Label + if label == "" { + return core.Bounds{} + } + if base == OverlayKindAdded && !strings.HasPrefix(label, "+") { + label = "+ " + label + } + + const pillH float32 = 22 + fontMono := core.Font{Family: core.FontMonospace, Size: 11, Weight: 500} + fontBody := core.Font{Size: 11, Weight: 500} + var pillW float32 + secondary := ov.SecondaryLabel + if base == OverlayKindRemoved { + if secondary == "" { + secondary = "removed" + } + nameW := float32(len([]rune(label))) * 6.4 + secW := float32(len([]rune(secondary))) * 6.0 + pillW = 8 + nameW + 6 + secW + 8 + } else { + pillW = 8 + float32(len([]rune(label)))*6.4 + 8 + } + + px, py := clampOverlayPillPos(bx+bw*0.5, by, by+bh, pad, pillW, pillH, ov.PillStackOffset, ov.CanvasSize) + + pillFill := ui.Alpha(p.PillBg, 0.92*alpha) + borderColor := ui.Alpha(role.Edge, 0.45*alpha) + borderWidth := float32(1) + if focused { + pillFill = ui.Alpha(p.PillBg, 0.96*alpha) + borderColor = ui.Alpha(role.Edge, alpha) + borderWidth = 1.5 + } + d.SetFillColor(pillFill) + d.BeginPath().RoundRect(px, py, pillW, pillH, 11).Fill() + d.SetStrokeColor(borderColor).SetLineWidth(borderWidth) + d.BeginPath().RoundRect(px, py, pillW, pillH, 11).Stroke() + + fg := ui.Alpha(role.Fg, alpha) + if base == OverlayKindRemoved { + nameX := px + 8 + nameW := float32(len([]rune(label))) * 6.4 + d.SetFillColor(fg).FillText(label, nameX, py+14.5, fontMono) + // Explicit strikethrough line across the removed object's name (never color alone). + strikeY := py + pillH*0.5 + d.SetStrokeColor(fg).SetLineWidth(1.2) + d.BeginPath().MoveTo(nameX-1, strikeY).LineTo(nameX+nameW, strikeY).Stroke() + d.SetFillColor(fg).FillText(secondary, nameX+nameW+6, py+14.5, fontBody) + } else { + d.SetFillColor(fg).FillText(label, px+8, py+14.5, fontMono) + } + + return core.Bounds{ + Origin: core.Point{X: core.Points(px), Y: core.Points(py)}, + Size: core.Size{Width: core.Points(pillW), Height: core.Points(pillH)}, + } +} + +func drawProblemSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bx, by, bw, bh float32) core.Bounds { + role := p.Problem() + pad := OverlayBaseOffset + ox, oy := bx-pad, by-pad + ow, oh := bw+2*pad, bh+2*pad + + // 2 px solid Problem outline directly around the live object (never a ghost). + d.SetStrokeColor(role.Edge).SetLineWidth(overlayProblemWidth).SetLineDash() + d.BeginPath().RoundRect(ox, oy, ow, oh, 6).Stroke() + + if ov.Label == "" { + return core.Bounds{} + } + + const pillH float32 = 22 + const iconW float32 = 12 + font := core.Font{Size: 11, Weight: 600} + pillW := 8 + iconW + 6 + float32(len([]rune(ov.Label)))*6.3 + 8 + px, py := clampOverlayPillPos(bx+bw*0.5, by, by+bh, pad, pillW, pillH, ov.PillStackOffset, ov.CanvasSize) + + // Solid filled Problem pill with alert triangle icon + message in Problem.OnFill. + d.SetFillColor(role.Fg) + d.BeginPath().RoundRect(px, py, pillW, pillH, 11).Fill() + + ix, iy := px+8, py+5 + drawProblemAlertGlyph(d, ix, iy, role.OnFill) + d.SetFillColor(role.OnFill).FillText(ov.Label, px+8+iconW+6, py+14.5, font) + + return core.Bounds{ + Origin: core.Point{X: core.Points(px), Y: core.Points(py)}, + Size: core.Size{Width: core.Points(pillW), Height: core.Points(pillH)}, + } +} + +// drawProblemAlertGlyph draws the 12x12 alert triangle icon at top-left (ix, iy). +func drawProblemAlertGlyph(d *core.Drawing, ix, iy float32, col core.Color) { + d.SetStrokeColor(col).SetLineWidth(1.5).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) + d.BeginPath().MoveTo(ix+6, iy+1).LineTo(ix+11, iy+10.5).LineTo(ix+1, iy+10.5).ClosePath().Stroke() + d.BeginPath().MoveTo(ix+6, iy+4.5).LineTo(ix+6, iy+7.2).Stroke() + d.SetFillColor(col).BeginPath().Arc(ix+6, iy+9.1, 0.8, 0, float32(2*math.Pi), false).Fill() +} + +// --- Live Scene Overlay State & Legend Visibility on Editor --- + +// SceneOverlayEntry attaches a live Spec overlay (Agent working, Added, Changed, Removed, +// or Focused change in Review) to an object in the open scene (or world ghost bounds for Removed). +type SceneOverlayEntry struct { + // ID optionally identifies this entry for targeted updates or removal. + ID string + // ObjectID names the scene object this overlay attaches to. + ObjectID string + // Kind selects which Spec overlay style to draw (Agent, Added, Changed, Removed, or FocusedChange). + Kind OverlayKind + // ChangeKind selects the base change kind when Kind is OverlayKindFocusedChange. + ChangeKind OverlayKind + // Label is the pill text (action text for Agent, object name for Added/Removed, "field old → new" for Changed). + Label string + // SecondaryLabel optionally overrides "removed" on Removed pills. + SecondaryLabel string + // GhostBounds optionally supplies 2D world bounds for a Removed object that is no longer in the scene. + GhostBounds *core.Bounds + // GhostPos3D and GhostSize3D optionally supply 3D world center & extents for a Removed object in 3D view. + GhostPos3D *[3]float32 + GhostSize3D *[3]float32 + // StartedAt records when the overlay appeared; automatically stamped with the editor clock when zero. + StartedAt time.Time +} + +func (e *Editor) overlayNow() time.Time { + if e != nil && e.overlayNowFn != nil { + return e.overlayNowFn() + } + return time.Now() +} + +// SetOverlayClock sets a custom clock function for overlay fade-in and pulse animation timing +// (used in deterministic tests; pass nil to restore time.Now). +func (e *Editor) SetOverlayClock(fn func() time.Time) { + if e == nil { + return + } + e.overlayNowFn = fn + e.notify() +} + +// ReduceMotion reports whether reduced motion is active for viewport overlays and animations: +// it honors an explicit SetReduceMotion override when set, otherwise follows the attached +// UI scope's Environment.ReduceMotion(). +func (e *Editor) ReduceMotion() bool { + if e == nil { + return false + } + if e.reduceMotionOverride != nil { + return *e.reduceMotionOverride + } + if e.scope != nil { + return e.scope.Env().ReduceMotion() + } + return false +} + +// SetReduceMotion forces reduced motion on or off on the editor (overriding the platform environment). +func (e *Editor) SetReduceMotion(on bool) { + if e == nil { + return + } + v := on + e.reduceMotionOverride = &v + e.notify() +} + +// ClearReduceMotion clears any explicit SetReduceMotion override so ReduceMotion follows the platform environment. +func (e *Editor) ClearReduceMotion() { + if e == nil || e.reduceMotionOverride == nil { + return + } + e.reduceMotionOverride = nil + e.notify() +} + +// SetSceneOverlays replaces the active live scene overlays (agent working, added, changed, removed, +// focused review change) drawn over the open scene in both 2D and 3D viewports. +func (e *Editor) SetSceneOverlays(entries []SceneOverlayEntry) { + if e == nil { + return + } + now := e.overlayNow() + if len(entries) == 0 { + if len(e.sceneOverlays) == 0 { + return + } + e.sceneOverlays = nil + e.notify() + return + } + cp := make([]SceneOverlayEntry, len(entries)) + for i, ent := range entries { + if ent.StartedAt.IsZero() { + ent.StartedAt = now + } + if ent.GhostBounds != nil { + r := *ent.GhostBounds + ent.GhostBounds = &r + } + if ent.GhostPos3D != nil { + v := *ent.GhostPos3D + ent.GhostPos3D = &v + } + if ent.GhostSize3D != nil { + v := *ent.GhostSize3D + ent.GhostSize3D = &v + } + cp[i] = ent + } + e.sceneOverlays = cp + e.notify() +} + +// AddSceneOverlay appends (or replaces by matching non-empty ID) one live scene overlay entry. +func (e *Editor) AddSceneOverlay(entry SceneOverlayEntry) { + if e == nil { + return + } + if entry.StartedAt.IsZero() { + entry.StartedAt = e.overlayNow() + } + if entry.GhostBounds != nil { + r := *entry.GhostBounds + entry.GhostBounds = &r + } + if entry.GhostPos3D != nil { + v := *entry.GhostPos3D + entry.GhostPos3D = &v + } + if entry.GhostSize3D != nil { + v := *entry.GhostSize3D + entry.GhostSize3D = &v + } + if entry.ID != "" { + for i := range e.sceneOverlays { + if e.sceneOverlays[i].ID == entry.ID { + e.sceneOverlays[i] = entry + e.notify() + return + } + } + } + e.sceneOverlays = append(e.sceneOverlays, entry) + e.notify() +} + +// RemoveSceneOverlay removes all live scene overlay entries matching id. +func (e *Editor) RemoveSceneOverlay(id string) { + if e == nil || id == "" || len(e.sceneOverlays) == 0 { + return + } + kept := e.sceneOverlays[:0] + removed := false + for _, ent := range e.sceneOverlays { + if ent.ID == id { + removed = true + continue + } + kept = append(kept, ent) + } + if !removed { + return + } + if len(kept) == 0 { + e.sceneOverlays = nil + } else { + e.sceneOverlays = kept + } + e.notify() +} + +// ClearSceneOverlays removes all live scene overlay entries. +func (e *Editor) ClearSceneOverlays() { + e.SetSceneOverlays(nil) +} + +// SceneOverlays returns a copy of the active live scene overlay entries. +func (e *Editor) SceneOverlays() []SceneOverlayEntry { + if e == nil || len(e.sceneOverlays) == 0 { + return nil + } + out := make([]SceneOverlayEntry, len(e.sceneOverlays)) + copy(out, e.sceneOverlays) + return out +} + +// hasAnimatedOverlays reports whether any currently visible scene or task overlay needs +// active animation ticks (pulsing agent outline or fading change overlay < 240 ms). +func (e *Editor) hasAnimatedOverlays() bool { + if e == nil || e.playing || e.ReduceMotion() { + return false + } + if e.OverlayKindVisible(OverlayKindAgent) { + for _, ov := range e.SceneTaskOverlays() { + if !ov.Holding { + return true + } + } + } + now := e.overlayNow() + for _, ent := range e.sceneOverlays { + switch ent.Kind { + case OverlayKindAgent: + if e.OverlayKindVisible(OverlayKindAgent) { + return true + } + case OverlayKindAdded, OverlayKindChanged, OverlayKindRemoved: + if e.OverlayKindVisible(ent.Kind) && now.Sub(ent.StartedAt) < OverlayChangeFadeDuration { + return true + } + case OverlayKindFocusedChange: + base := ent.ChangeKind + if !base.IsChangeKind() { + base = OverlayKindAdded + } + if e.OverlayKindVisible(base) && now.Sub(ent.StartedAt) < OverlayChangeFadeDuration { + return true + } + } + } + return false +} + +// --- Legend Toggle Persistence (EditorSettings.OverlayLegend) --- + +func (e *Editor) effectiveOverlayLegendSet() map[OverlayKind]bool { + set := make(map[OverlayKind]bool, 6) + if e != nil && e.settings.OverlayLegend != nil { + for _, id := range *e.settings.OverlayLegend { + k := OverlayKind(id) + if k.IsLegendKind() { + set[k] = true + } + } + return set + } + for _, k := range OverlayLegendKinds() { + set[k] = true + } + return set +} + +// OverlayKindVisible reports whether overlay kind is currently enabled in the top-left viewport legend. +// For OverlayKindFocusedChange, it reports whether any change kind is enabled (callers with a specific +// ChangeKind should pass that ChangeKind). +func (e *Editor) OverlayKindVisible(kind OverlayKind) bool { + if e == nil { + return false + } + if kind == OverlayKindFocusedChange { + set := e.effectiveOverlayLegendSet() + return set[OverlayKindAdded] || set[OverlayKindChanged] || set[OverlayKindRemoved] + } + if !kind.IsLegendKind() { + return false + } + return e.effectiveOverlayLegendSet()[kind] +} + +// ActiveOverlayLegendKinds returns the enabled legend kinds in Spec display order. +func (e *Editor) ActiveOverlayLegendKinds() []OverlayKind { + if e == nil { + return nil + } + set := e.effectiveOverlayLegendSet() + var out []OverlayKind + for _, k := range OverlayLegendKinds() { + if set[k] { + out = append(out, k) + } + } + return out +} + +// SetOverlayKindVisible shows or hides one legend kind across all viewports (2D and 3D) and +// persists the choice per person in Editor.SettingsPath when configured (never touching project files). +func (e *Editor) SetOverlayKindVisible(kind OverlayKind, visible bool) error { + if e == nil { + return nil + } + if !kind.IsLegendKind() { + return fmt.Errorf("editor: unknown overlay legend kind %q", kind) + } + if e.OverlayKindVisible(kind) == visible { + return nil + } + set := e.effectiveOverlayLegendSet() + if visible { + set[kind] = true + } else { + delete(set, kind) + } + return e.commitOverlayLegendSet(set) +} + +// ToggleOverlayKind flips one legend kind between visible and hidden and persists to SettingsPath when set. +func (e *Editor) ToggleOverlayKind(kind OverlayKind) error { + if e == nil { + return nil + } + return e.SetOverlayKindVisible(kind, !e.OverlayKindVisible(kind)) +} + +// SetOverlayLegendKinds replaces the enabled legend kinds and persists to SettingsPath when set. +func (e *Editor) SetOverlayLegendKinds(kinds []OverlayKind) error { + if e == nil { + return nil + } + set := make(map[OverlayKind]bool, len(kinds)) + for _, k := range kinds { + if !k.IsLegendKind() { + return fmt.Errorf("editor: unknown overlay legend kind %q", k) + } + set[k] = true + } + return e.commitOverlayLegendSet(set) +} + +func (e *Editor) commitOverlayLegendSet(set map[OverlayKind]bool) error { + list := make([]string, 0, len(set)) + for k, on := range set { + if on && k.IsLegendKind() { + list = append(list, string(k)) + } + } + slices.Sort(list) + cur := e.Settings() + cur.OverlayLegend = &list + e.settings = cur + + // Keep legacy problemOverlayHidden in sync with the Problem legend toggle. + e.problems.mu.Lock() + e.problems.problemOverlayHidden = !set[OverlayKindProblem] + e.problems.mu.Unlock() + + if e.SettingsPath != "" { + if err := SaveEditorSettings(e.SettingsPath, &cur); err != nil { + e.notify() + return err + } + } + e.notify() + return nil +} + +// --- Viewport Rendering Passes (2D & 3D) --- + +func (e *Editor) builtObjectCanvasBounds(scene *sceneformat.BuiltScene, bo *sceneformat.BuiltObject) (core.Bounds, []math2d.Vec2, bool) { + if e == nil || scene == nil || bo == nil || bo.Doc == nil || viewFlagged(e.hidden, bo) { + return core.Bounds{}, nil, false + } + space := sceneformat.SpaceWorld + var px, py float32 = 1, 1 + if layer := scene.Layer(bo.Layer); layer != nil { + if !layer.Visible { + return core.Bounds{}, nil, false + } + space = layer.Space + px, py = layer.ParallaxX, layer.ParallaxY + } + m := e.layerAffineFor(space, px, py).Mul(bo.World) + rx, ry, rw, rh := objectOutline(bo) + corners := []math2d.Vec2{ + m.TransformPoint(math2d.Vec2{X: rx, Y: ry}), + m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry}), + m.TransformPoint(math2d.Vec2{X: rx + rw, Y: ry + rh}), + m.TransformPoint(math2d.Vec2{X: rx, Y: ry + rh}), + } + minX, maxX := corners[0].X, corners[0].X + minY, maxY := corners[0].Y, corners[0].Y + for _, c := range corners[1:] { + minX, maxX = min(minX, c.X), max(maxX, c.X) + minY, maxY = min(minY, c.Y), max(maxY, c.Y) + } + 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)}, + }, corners, true +} + +func (e *Editor) objectDisplayName(bo *sceneformat.BuiltObject, fallbackID string) string { + if bo != nil && bo.Doc != nil && bo.Doc.Name != "" { + return bo.Doc.Name + } + if bo != nil && bo.ID != "" { + return bo.ID + } + return fallbackID +} + +// drawSceneOverlays2D draws all live SceneOverlayEntry items (Agent working, Added, Changed, +// Removed, Focused change) in the 2D viewport through DrawObjectOverlay, honoring legend toggles. +func (e *Editor) drawSceneOverlays2D(d *core.Drawing, scene *sceneformat.BuiltScene) { + if e == nil || d == nil || scene == nil || e.playing || len(e.sceneOverlays) == 0 { + return + } + spec := e.SpecPalette(nil) + now := e.overlayNow() + rm := e.ReduceMotion() + canvas := core.Size{Width: core.Points(e.canvasW), Height: core.Points(e.canvasH)} + + for _, ent := range e.sceneOverlays { + checkKind := ent.Kind + if ent.Kind == OverlayKindFocusedChange { + base := ent.ChangeKind + if !base.IsChangeKind() { + base = OverlayKindAdded + } + checkKind = base + } + if !e.OverlayKindVisible(checkKind) { + continue + } + + var bounds core.Bounds + var ok bool + if bo := scene.Object(ent.ObjectID); bo != nil { + bounds, _, ok = e.builtObjectCanvasBounds(scene, bo) + } else if ent.GhostBounds != nil && (ent.Kind == OverlayKindRemoved || (ent.Kind == OverlayKindFocusedChange && ent.ChangeKind == OverlayKindRemoved)) { + r := *ent.GhostBounds + pts := worldRectCanvasCorners(e, float32(r.Origin.X), float32(r.Origin.Y), float32(r.Size.Width), float32(r.Size.Height)) + minX, maxX := pts[0].X, pts[0].X + minY, maxY := pts[0].Y, pts[0].Y + for _, c := range pts[1:] { + minX, maxX = min(minX, c.X), max(maxX, c.X) + minY, maxY = min(minY, c.Y), max(maxY, c.Y) + } + bounds = 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)}, + } + ok = true + } + if !ok { + continue + } + + pairedSel := ent.Kind == OverlayKindAgent && e.IsSelected(ent.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + stackOff := float32(0) + if pairedSel { + stackOff = 24 + } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: ent.Kind, + ChangeKind: ent.ChangeKind, + Label: ent.Label, + SecondaryLabel: ent.SecondaryLabel, + Bounds: bounds, + CanvasSize: canvas, + PairedWithSelection: pairedSel, + PillStackOffset: stackOff, + Elapsed: now.Sub(ent.StartedAt), + HasElapsed: true, + ReduceMotion: rm, + }) + } +} + +// projectObject3DBounds projects a 3D object's 8 corners onto canvas-space 2D bounds. +func (e *Editor) projectObject3DBounds(o *sceneformat.ObjectDoc, parent aff3, vc view3DCam, w, h float32) (core.Bounds, bool) { + if o == nil { + return core.Bounds{}, false + } + corners := e.objectCorners3DUnder(o, parent) + var minX, minY, maxX, maxY float32 + anyVis := false + for _, c := range corners { + sx, sy, _, vis := vc.project(c, w, h) + if !vis || !isFiniteFloat32(sx) || !isFiniteFloat32(sy) { + continue + } + if !anyVis { + minX, maxX = sx, sx + minY, maxY = sy, sy + anyVis = true + } else { + minX, maxX = min(minX, sx), max(maxX, sx) + minY, maxY = min(minY, sy), max(maxY, sy) + } + } + if !anyVis { + return core.Bounds{}, false + } + return core.Bounds{ + Origin: core.Point{X: core.Points(minX), Y: core.Points(minY)}, + Size: core.Size{Width: core.Points(max(maxX-minX, 12)), Height: core.Points(max(maxY-minY, 12))}, + }, true +} + +// drawSceneOverlays3D draws Spec Agent working, Added, Changed, Removed, Focused change, and Problem +// overlays on projected 3D object bounds in the 3D viewport through DrawObjectOverlay, sharing the +// exact same legend toggles as the 2D viewport. +func (e *Editor) drawSceneOverlays3D(d *core.Drawing, w, h float32) { + if e == nil || d == nil || e.playing { + return + } + spec := e.SpecPalette(nil) + now := e.overlayNow() + rm := e.ReduceMotion() + vc := e.activeView3DCam(w, h) + canvas := core.Size{Width: core.Points(w), Height: core.Points(h)} + + // Map visible 3D objects by ID for fast lookup. + type objRef3D struct { + obj *sceneformat.ObjectDoc + parent aff3 + } + byID := make(map[string]objRef3D) + if doc := e.resolvedDoc(); doc != nil { + for li := range doc.Layers { + layer := &doc.Layers[li] + if !layer.IsVisible() || layer.EffectiveSpace() == sceneformat.SpaceScreen { + continue + } + var walk func(objs []sceneformat.ObjectDoc, parent aff3) + walk = func(objs []sceneformat.ObjectDoc, parent aff3) { + for oi := range objs { + o := &objs[oi] + if e.hidden[o.ID] { + continue + } + posed := e.posed3D(o) + byID[o.ID] = objRef3D{obj: posed, parent: parent} + walk(o.Children, parent.mul(local3(posed))) + } + } + walk(layer.Objects, ident3) + } + } + + // 1. Live agent task overlays in 3D. + if e.OverlayKindVisible(OverlayKindAgent) { + for _, ov := range e.SceneTaskOverlays() { + ref, ok := byID[ov.ObjectID] + if !ok { + continue + } + bounds, vis := e.projectObject3DBounds(ref.obj, ref.parent, vc, w, h) + if !vis { + continue + } + pairedSel := e.IsSelected(ov.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + stackOff := float32(0) + if pairedSel { + stackOff = 24 + } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindAgent, + Label: ov.Label, + TaskNumber: ov.TaskNumber, + Holding: ov.Holding, + Bounds: bounds, + CanvasSize: canvas, + PairedWithSelection: pairedSel, + PillStackOffset: stackOff, + Elapsed: now.Sub(e.overlayEpoch), + HasElapsed: true, + ReduceMotion: rm, + }) + } + } + + // 2. Live scene overlay entries (Agent working, Added, Changed, Removed, Focused change). + for _, ent := range e.sceneOverlays { + checkKind := ent.Kind + if ent.Kind == OverlayKindFocusedChange { + base := ent.ChangeKind + if !base.IsChangeKind() { + base = OverlayKindAdded + } + checkKind = base + } + if !e.OverlayKindVisible(checkKind) { + continue + } + var bounds core.Bounds + var vis bool + if ref, ok := byID[ent.ObjectID]; ok { + bounds, vis = e.projectObject3DBounds(ref.obj, ref.parent, vc, w, h) + } else if ent.GhostPos3D != nil && (ent.Kind == OverlayKindRemoved || (ent.Kind == OverlayKindFocusedChange && ent.ChangeKind == OverlayKindRemoved)) { + pos := *ent.GhostPos3D + ext := [3]float32{16, 16, 16} + if ent.GhostSize3D != nil { + ext = *ent.GhostSize3D + } + ghost := &sceneformat.ObjectDoc{X: pos[0], Y: pos[1], PosZ: pos[2], Depth: ext[2]} + bounds, vis = e.projectObject3DBounds(ghost, ident3, vc, w, h) + } + if !vis { + continue + } + pairedSel := ent.Kind == OverlayKindAgent && e.IsSelected(ent.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + stackOff := float32(0) + if pairedSel { + stackOff = 24 + } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: ent.Kind, + ChangeKind: ent.ChangeKind, + Label: ent.Label, + SecondaryLabel: ent.SecondaryLabel, + Bounds: bounds, + CanvasSize: canvas, + PairedWithSelection: pairedSel, + PillStackOffset: stackOff, + Elapsed: now.Sub(ent.StartedAt), + HasElapsed: true, + ReduceMotion: rm, + }) + } + + // 3. Live Problem overlays in 3D. + if e.OverlayKindVisible(OverlayKindProblem) { + objProbs := e.openSceneObjectProblems() + for objID, probs := range objProbs { + if len(probs) == 0 { + continue + } + ref, ok := byID[objID] + if !ok { + continue + } + bounds, vis := e.projectObject3DBounds(ref.obj, ref.parent, vc, w, h) + if !vis { + continue + } + label := shortProblemLabel(probs[0]) + if len(probs) > 1 { + label = fmt.Sprintf("%s (+%d)", label, len(probs)-1) + } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindProblem, + Label: label, + Bounds: bounds, + CanvasSize: canvas, + }) + } + } +} diff --git a/packages/game/editor/viewport_overlay_test.go b/packages/game/editor/viewport_overlay_test.go new file mode 100644 index 000000000..97a972aa9 --- /dev/null +++ b/packages/game/editor/viewport_overlay_test.go @@ -0,0 +1,825 @@ +package editor_test + +import ( + "bytes" + "image" + "image/color" + "math" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/editor" + "github.com/nsgo-dev/game/packages/game/gametest" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" + "github.com/nsgo-dev/nsgo/ui" +) + +const ( + overlayBoardCols = 4 + overlayBoardRows = 2 + overlayCellW = 196 + overlayCellH = 148 + overlayBoardPad = 12 + overlayBoardGap = 10 + overlayBoardWidth = overlayBoardPad*2 + overlayBoardCols*overlayCellW + (overlayBoardCols-1)*overlayBoardGap + overlayBoardH = overlayBoardPad*2 + overlayBoardRows*overlayCellH + (overlayBoardRows-1)*overlayBoardGap +) + +type overlayBoardSlot struct { + name string + x, y float32 + draw func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) +} + +func specOverlayBoardSlots() []overlayBoardSlot { + return []overlayBoardSlot{ + { + name: "selection", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 12), Y: core.Points(fy - 34)}, Size: core.Size{Width: 24, Height: 34}} + d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindSelection, + Label: "Knight", + Bounds: obj, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "agent", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 15), Y: core.Points(fy - 22)}, Size: core.Size{Width: 30, Height: 22}} + d.SetFillColor(ui.Alpha(p.Agent.Fg, 0.30)).BeginPath().RoundRect(cx-15, fy-22, 30, 22, 6).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindAgent, + Label: "placing slime_02", + Bounds: obj, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "added", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 15), Y: core.Points(fy - 22)}, Size: core.Size{Width: 30, Height: 22}} + d.SetFillColor(ui.Alpha(p.Added.Fg, 0.30)).BeginPath().RoundRect(cx-15, fy-22, 30, 22, 6).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindAdded, + Label: "slime_03", + Bounds: obj, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "changed", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 12), Y: core.Points(fy - 34)}, Size: core.Size{Width: 24, Height: 34}} + d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindChanged, + Label: "z 10 → 12", + Bounds: obj, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "removed", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 10), Y: core.Points(fy - 22)}, Size: core.Size{Width: 20, Height: 20}} + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindRemoved, + Label: "coin_04", + Bounds: obj, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "problem", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 14), Y: core.Points(fy - 38)}, Size: core.Size{Width: 28, Height: 38}} + d.SetFillColor(p.TextMuted).BeginPath().RoundRect(cx-14, fy-38, 28, 38, 4).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindProblem, + Label: "door: lever_02 missing", + Bounds: obj, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "focused", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + // Unfocused peer on left + focused 2.5 px change with outlined pill on right (never accent). + left := core.Bounds{Origin: core.Point{X: core.Points(cx - 56), Y: core.Points(fy - 22)}, Size: core.Size{Width: 28, Height: 20}} + d.SetFillColor(ui.Alpha(p.Added.Fg, 0.28)).BeginPath().RoundRect(cx-56, fy-22, 28, 20, 6).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindAdded, + Bounds: left, + CanvasSize: cell.Size, + }) + right := core.Bounds{Origin: core.Point{X: core.Points(cx + 12), Y: core.Points(fy - 22)}, Size: core.Size{Width: 28, Height: 20}} + d.SetFillColor(ui.Alpha(p.Added.Fg, 0.48)).BeginPath().RoundRect(cx+12, fy-22, 28, 20, 6).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindFocusedChange, + ChangeKind: editor.OverlayKindAdded, + Label: "slime_02", + Bounds: right, + CanvasSize: cell.Size, + }) + }, + }, + { + name: "selection_and_agent", + draw: func(d *core.Drawing, p editor.SpecPalette, cell core.Bounds) { + cx := float32(cell.Origin.X + cell.Size.Width/2) + fy := float32(cell.Origin.Y+cell.Size.Height) - 24 + obj := core.Bounds{Origin: core.Point{X: core.Points(cx - 12), Y: core.Points(fy - 34)}, Size: core.Size{Width: 24, Height: 34}} + d.SetFillColor(p.Changed.Fg).BeginPath().RoundRect(cx-12, fy-34, 24, 34, 4).Fill() + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindSelection, + Label: "Knight", + Bounds: obj, + CanvasSize: cell.Size, + }) + editor.DrawObjectOverlay(d, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindAgent, + Label: "tuning jump", + Bounds: obj, + CanvasSize: cell.Size, + PairedWithSelection: true, + PillStackOffset: 24, + }) + }, + }, + } +} + +func renderOverlayBoard(scale int) (*image.RGBA, []image.Rectangle, []string) { + p := editor.DarkSpecPalette() + slots := specOverlayBoardSlots() + var d core.Drawing + if scale > 1 { + d.Scale(float32(scale), float32(scale)) + } + d.SetFillColor(p.Bg).FillRect(0, 0, overlayBoardWidth, overlayBoardH) + + cellRects := make([]image.Rectangle, len(slots)) + names := make([]string, len(slots)) + for i, slot := range slots { + col := i % overlayBoardCols + row := i / overlayBoardCols + x := float32(overlayBoardPad + col*(overlayCellW+overlayBoardGap)) + y := float32(overlayBoardPad + row*(overlayCellH+overlayBoardGap)) + cellRects[i] = image.Rect(int(x)*scale, int(y)*scale, int(x+overlayCellW)*scale, int(y+overlayCellH)*scale) + names[i] = slot.name + + d.Save() + d.Translate(x, y) + // Viewport cell backdrop matching Spec.dc.html. + d.SetFillColor(p.Viewport).BeginPath().RoundRect(0, 0, overlayCellW, overlayCellH, 10).Fill() + d.SetStrokeColor(p.Line).SetLineWidth(1).BeginPath().RoundRect(0, 0, overlayCellW, overlayCellH, 10).Stroke() + d.SetFillColor(p.ViewportDot) + for dy := float32(10); dy < overlayCellH-24; dy += 16 { + for dx := float32(10); dx < overlayCellW-6; dx += 16 { + d.FillRect(dx, dy, 1.2, 1.2) + } + } + d.SetFillColor(p.Inset).FillRect(1, overlayCellH-24, overlayCellW-2, 23) + d.SetFillColor(p.LineRaised).FillRect(1, overlayCellH-24, overlayCellW-2, 2) + + slot.draw(&d, p, core.Bounds{Size: core.Size{Width: overlayCellW, Height: overlayCellH}}) + d.Restore() + } + + img := gametest.RenderOps(overlayBoardWidth*scale, overlayBoardH*scale, d.Ops) + return img, cellRects, names +} + +// #1006 Acceptance 1: Golden-image test draws each overlay kind at 1x and 2x and matches the Spec's legend. +func TestViewportOverlayGolden1xAnd2x(t *testing.T) { + img1x, _, _ := renderOverlayBoard(1) + gametest.AssertGolden(t, "viewport_overlays_1x", img1x) + + img2x, _, _ := renderOverlayBoard(2) + gametest.AssertGolden(t, "viewport_overlays_2x", img2x) +} + +func toGreyscale(src *image.RGBA) *image.RGBA { + b := src.Bounds() + out := image.NewRGBA(b) + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + c := src.RGBAAt(x, y) + // WCAG Rec. 709 luminance. + lum := uint8(math.Round(0.2126*float64(c.R) + 0.7152*float64(c.G) + 0.0722*float64(c.B))) + out.SetRGBA(x, y, color.RGBA{R: lum, G: lum, B: lum, A: c.A}) + } + } + return out +} + +// #1006 Acceptance 2: The same render in greyscale still tells every kind apart by line, handles, pill or ghost. +func TestViewportOverlayGreyscaleDistinguishable(t *testing.T) { + p := editor.DarkSpecPalette() + // Draw every kind onto identical 180x140 cells with the SAME neutral object block + // (except Removed which draws its own 25% grey ghost) so hue CANNOT account for differences. + const w, h = 180, 140 + obj := core.Bounds{ + Origin: core.Point{X: 76, Y: 72}, + Size: core.Size{Width: 28, Height: 34}, + } + + kinds := []struct { + name string + drawSolid bool + ov editor.ObjectOverlay + }{ + {"selection", true, editor.ObjectOverlay{Kind: editor.OverlayKindSelection, Label: "Knight", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + {"agent", true, editor.ObjectOverlay{Kind: editor.OverlayKindAgent, Label: "placing slime_02", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + {"added", true, editor.ObjectOverlay{Kind: editor.OverlayKindAdded, Label: "slime_03", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + {"changed", true, editor.ObjectOverlay{Kind: editor.OverlayKindChanged, Label: "z 10 → 12", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + {"removed", false, editor.ObjectOverlay{Kind: editor.OverlayKindRemoved, Label: "coin_04", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + {"problem", true, editor.ObjectOverlay{Kind: editor.OverlayKindProblem, Label: "door: lever_02 missing", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + {"focused", true, editor.ObjectOverlay{Kind: editor.OverlayKindFocusedChange, ChangeKind: editor.OverlayKindAdded, Label: "slime_03", Bounds: obj, CanvasSize: core.Size{Width: w, Height: h}}}, + } + + renders := make([]*image.RGBA, len(kinds)) + for i, k := range kinds { + var d core.Drawing + d.SetFillColor(p.Viewport).FillRect(0, 0, w, h) + if k.drawSolid { + // Identical neutral live object body across every non-Removed kind. + d.SetFillColor(p.TextMuted).FillRect(float32(obj.Origin.X), float32(obj.Origin.Y), float32(obj.Size.Width), float32(obj.Size.Height)) + } + editor.DrawObjectOverlay(&d, p, k.ov) + renders[i] = toGreyscale(gametest.RenderOps(w, h, d.Ops)) + } + + // Verify every pair of kinds has a substantial structural greyscale difference (not identical or hue-only). + for i := 0; i < len(kinds); i++ { + for j := i + 1; j < len(kinds); j++ { + diffPixels := 0 + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + a := renders[i].RGBAAt(x, y).R + b := renders[j].RGBAAt(x, y).R + if int(a)-int(b) > 12 || int(b)-int(a) > 12 { + diffPixels++ + } + } + } + if diffPixels < 120 { + t.Errorf("greyscale renders of %q and %q differ by only %d pixels (want >= 120 structural cue pixels)", kinds[i].name, kinds[j].name, diffPixels) + } + } + } + + // Verify Focused change NEVER uses Accent color. + var focusedDraw core.Drawing + editor.DrawObjectOverlay(&focusedDraw, p, editor.ObjectOverlay{ + Kind: editor.OverlayKindFocusedChange, + ChangeKind: editor.OverlayKindAdded, + Label: "slime_02", + Bounds: obj, + }) + for _, op := range focusedDraw.Ops { + if (op.Kind == core.DrawStrokeColor || op.Kind == core.DrawFillColor) && op.Color == p.Accent.Edge { + t.Fatal("Focused change overlay used Accent color; Spec forbids Accent on Focused change") + } + } + // Verify Focused change uses 2.5 px width. + has25 := false + for _, op := range focusedDraw.Ops { + if op.Kind == core.DrawLineWidth && op.W == 2.5 { + has25 = true + break + } + } + if !has25 { + t.Fatal("Focused change overlay did not use 2.5 px stroke width") + } +} + +// #1006 Scope: Selection + Agent on one object keeps selection handles and places agent outline 3 px further out. +func TestViewportOverlaySelectionAndAgentPairedOffset(t *testing.T) { + p := editor.DarkSpecPalette() + obj := core.Bounds{Origin: core.Point{X: 100, Y: 100}, Size: core.Size{Width: 40, Height: 40}} + + var selDraw, agentAloneDraw, agentPairedDraw core.Drawing + editor.DrawObjectOverlay(&selDraw, p, editor.ObjectOverlay{Kind: editor.OverlayKindSelection, Label: "Knight", Bounds: obj}) + editor.DrawObjectOverlay(&agentAloneDraw, p, editor.ObjectOverlay{Kind: editor.OverlayKindAgent, Label: "editing", Bounds: obj}) + editor.DrawObjectOverlay(&agentPairedDraw, p, editor.ObjectOverlay{Kind: editor.OverlayKindAgent, Label: "editing", Bounds: obj, PairedWithSelection: true}) + + findOutline := func(ops []core.DrawOp) (core.DrawOp, bool) { + for _, op := range ops { + if op.Kind == core.DrawRoundRect && op.W >= 40 && op.H >= 40 { + return op, true + } + } + return core.DrawOp{}, false + } + + selRR, ok1 := findOutline(selDraw.Ops) + aloneRR, ok2 := findOutline(agentAloneDraw.Ops) + pairedRR, ok3 := findOutline(agentPairedDraw.Ops) + if !ok1 || !ok2 || !ok3 { + t.Fatalf("missing outline RoundRect ops: sel=%v alone=%v paired=%v", ok1, ok2, ok3) + } + if selRR.X != 97 || selRR.W != 46 { + t.Fatalf("selection outline = (x=%v, w=%v), want (97, 46)", selRR.X, selRR.W) + } + if aloneRR.X != 97 || aloneRR.W != 46 { + t.Fatalf("unpaired agent outline = (x=%v, w=%v), want (97, 46)", aloneRR.X, aloneRR.W) + } + if pairedRR.X != selRR.X-3 || pairedRR.W != selRR.W+6 { + t.Fatalf("paired agent outline = (x=%v, w=%v), want 3 px further out than selection (x=%v, w=%v)", + pairedRR.X, pairedRR.W, selRR.X-3, selRR.W+6) + } + + // Selection has 4 corner handles (8x8 rounded rects); Agent has 0 handles. + countHandles := func(ops []core.DrawOp) int { + n := 0 + for _, op := range ops { + if op.Kind == core.DrawRoundRect && op.W == 8 && op.H == 8 { + n++ + } + } + return n + } + if got := countHandles(selDraw.Ops); got != 8 { // 4 fill + 4 stroke RoundRects + t.Fatalf("selection handle RoundRect count = %d, want 8 (4 filled + 4 stroked corner handles)", got) + } + if got := countHandles(agentPairedDraw.Ops); got != 0 { + t.Fatalf("agent outline unexpectedly drew %d handle RoundRects, want 0", got) + } +} + +// #1006 Acceptance 4: Change overlays fade in over 240 ms and Agent pulses 1.6 s between 100% and 45%; +// with reduced motion on, nothing fades or pulses. +func TestViewportOverlayMotionAndReduceMotion(t *testing.T) { + // 1. Change fade-in math (240 ms). + if got := editor.OverlayFadeAlpha(0, false); got != 0 { + t.Fatalf("OverlayFadeAlpha(0, false) = %v, want 0", got) + } + if got := editor.OverlayFadeAlpha(120*time.Millisecond, false); math.Abs(float64(got-0.5)) > 0.01 { + t.Fatalf("OverlayFadeAlpha(120ms, false) = %v, want ~0.5", got) + } + if got := editor.OverlayFadeAlpha(240*time.Millisecond, false); got != 1 { + t.Fatalf("OverlayFadeAlpha(240ms, false) = %v, want 1", got) + } + if got := editor.OverlayFadeAlpha(0, true); got != 1 { + t.Fatalf("OverlayFadeAlpha(0, reduceMotion=true) = %v, want 1", got) + } + + // 2. Agent pulse math (1.6 s between 100% and 45%). + if got := editor.OverlayAgentPulseAlpha(0, false); math.Abs(float64(got-1.0)) > 0.01 { + t.Fatalf("OverlayAgentPulseAlpha(0, false) = %v, want 1.0", got) + } + if got := editor.OverlayAgentPulseAlpha(800*time.Millisecond, false); math.Abs(float64(got-0.45)) > 0.01 { + t.Fatalf("OverlayAgentPulseAlpha(800ms, false) = %v, want 0.45", got) + } + if got := editor.OverlayAgentPulseAlpha(1600*time.Millisecond, false); math.Abs(float64(got-1.0)) > 0.01 { + t.Fatalf("OverlayAgentPulseAlpha(1600ms, false) = %v, want 1.0", got) + } + for _, dt := range []time.Duration{0, 400 * time.Millisecond, 800 * time.Millisecond, 1200 * time.Millisecond} { + if got := editor.OverlayAgentPulseAlpha(dt, true); got != 1 { + t.Fatalf("OverlayAgentPulseAlpha(%v, reduceMotion=true) = %v, want solid 1.0", dt, got) + } + } + + // 3. Live Editor DrawViewport with deterministic clock and ReduceMotion toggle. + ed := newOverlaysTestEditor(t) + _ = ed.SetAppearance(editor.AppearanceDark) + baseTime := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC) + now := baseTime + ed.SetOverlayClock(func() time.Time { return now }) + + ed.SetSceneOverlays([]editor.SceneOverlayEntry{ + {ID: "a1", ObjectID: "slime_01", Kind: editor.OverlayKindAgent, Label: "placing slime_01", StartedAt: baseTime}, + {ID: "c1", ObjectID: "knight", Kind: editor.OverlayKindAdded, Label: "knight", StartedAt: baseTime}, + }) + + spec := editor.DarkSpecPalette() + findStrokeColor := func(ops []core.DrawOp, rgb core.Color) (uint8, bool) { + wantRGB := uint32(rgb) >> 8 + for _, op := range ops { + if op.Kind == core.DrawStrokeColor && (uint32(op.Color)>>8) == wantRGB { + return uint8(op.Color & 0xFF), true + } + } + return 0, false + } + + // With ReduceMotion OFF at t=0: Added overlay starts at alpha 0 (no stroke emitted yet). + ed.SetReduceMotion(false) + var d0 core.Drawing + ed.DrawViewport(&d0, core.Size{Width: 640, Height: 360}) + if _, ok := findStrokeColor(d0.Ops, spec.Added.Edge); ok { + t.Fatal("expected Added overlay at t=0 without ReduceMotion to start at 0 alpha") + } + + // At t=800ms without ReduceMotion: Agent outline pulses down to 45% (~115/255), Added is at 100%. + now = baseTime.Add(800 * time.Millisecond) + var d800 core.Drawing + ed.DrawViewport(&d800, core.Size{Width: 640, Height: 360}) + agentA, okA := findStrokeColor(d800.Ops, spec.Agent.Edge) + if !okA || agentA > 130 || agentA < 100 { + t.Fatalf("Agent stroke alpha at t=800ms = %d (found=%v), want ~115 (45%%)", agentA, okA) + } + addedA, okAdd := findStrokeColor(d800.Ops, spec.Added.Edge) + if !okAdd || addedA != 255 { + t.Fatalf("Added stroke alpha at t=800ms = %d (found=%v), want 255", addedA, okAdd) + } + + // With ReduceMotion ON via core.Environment: at t=0 Added appears immediately at 100%, + // and at t=800ms Agent stays solid at 100%! + ed.ClearReduceMotion() + now = baseTime + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 720), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + ReduceMotion: true, + })) + app.Settle() + + if !ed.ReduceMotion() { + t.Fatal("ed.ReduceMotion() = false under Environment{ReduceMotion: true}, want true") + } + var rm0 core.Drawing + ed.DrawViewport(&rm0, core.Size{Width: 640, Height: 360}) + if a, ok := findStrokeColor(rm0.Ops, spec.Added.Edge); !ok || a != 255 { + t.Fatalf("with ReduceMotion at t=0, Added alpha = %d (found=%v), want instant 255", a, ok) + } + now = baseTime.Add(800 * time.Millisecond) + var rm800 core.Drawing + ed.DrawViewport(&rm800, core.Size{Width: 640, Height: 360}) + if a, ok := findStrokeColor(rm800.Ops, spec.Agent.Edge); !ok || a != 255 { + t.Fatalf("with ReduceMotion at t=800ms, Agent alpha = %d (found=%v), want solid 255", a, ok) + } +} + +// #1006 Acceptance 3: Top-left legend renders six role="switch" toggles in both 2D and 3D viewports, +// turning a row off hides that kind, and the choice persists in EditorSettings YAML across restarts. +func TestViewportOverlayLegendTogglesAndRestartPersistence(t *testing.T) { + ed, projDir := openTestProject(t) + _ = ed.SetAppearance(editor.AppearanceDark) + settingsPath := filepath.Join(t.TempDir(), "user-config", "editor.yaml") + if err := ed.LoadSettings(settingsPath); err != nil { + t.Fatalf("LoadSettings: %v", err) + } + + // Seed every overlay kind onto an existing object in the open scene (never mutating the scene file). + var objID string + if ed.Doc != nil { + for _, layer := range ed.Doc.Layers { + if len(layer.Objects) > 0 { + objID = layer.Objects[0].ID + break + } + } + } + if objID == "" { + var err error + objID, err = ed.PlaceObject(ed.ActiveLayer, sceneformat.ObjectDoc{ID: "knight", Name: "Knight", X: 160, Y: 180}) + if err != nil { + t.Fatal(err) + } + if ed.ScenePath != "" { + if err := ed.SaveFile(ed.ScenePath); err != nil { + t.Fatal(err) + } + } + } + + gamePath := filepath.Join(projDir, "game.yaml") + scenePath := filepath.Join(projDir, "scenes", "room.scene.yaml") + if ed.ScenePath != "" { + if filepath.IsAbs(ed.ScenePath) { + scenePath = ed.ScenePath + } else { + scenePath = filepath.Join(projDir, ed.ScenePath) + } + } + gameBefore, err := os.ReadFile(gamePath) + if err != nil { + t.Fatalf("read game.yaml before: %v", err) + } + sceneBefore, err := os.ReadFile(scenePath) + if err != nil { + t.Fatalf("read %s before: %v", scenePath, err) + } + ed.SelectObject(objID) + ed.SetReduceMotion(true) + ed.SetSceneOverlays([]editor.SceneOverlayEntry{ + {ID: "ag", ObjectID: objID, Kind: editor.OverlayKindAgent, Label: "tuning knight"}, + {ID: "ad", ObjectID: objID, Kind: editor.OverlayKindAdded, Label: "new_slime"}, + {ID: "ch", ObjectID: objID, Kind: editor.OverlayKindChanged, Label: "z 10 → 12"}, + {ID: "rm", ObjectID: "gone_coin", Kind: editor.OverlayKindRemoved, Label: "coin_04", GhostBounds: &core.Bounds{Origin: core.Point{X: 260, Y: 180}, Size: core.Size{Width: 20, Height: 20}}}, + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + ReduceMotion: true, + })) + app.Settle() + + // 1. Verify top-left legend is shown in 2D with all 6 role="switch" rows checked. + if !app.Exists("id:viewport-overlay-legend") { + t.Fatal("expected top-left viewport-overlay-legend in 2D viewport") + } + for _, k := range editor.OverlayLegendKinds() { + row := app.Find("id:legend-" + string(k)) + if row.Props.Role != core.RoleSwitch { + t.Errorf("legend-%s Role = %v, want RoleSwitch", k, row.Props.Role) + } + if !row.Props.Checked { + t.Errorf("legend-%s Checked = false, want true by default", k) + } + } + + // Verify 2D viewport initially draws Selection, Agent, Added, Changed, and Removed labels. + vp := app.Find("id:editor-viewport") + for _, wantText := range []string{"tuning knight", "+ new_slime", "z 10 → 12", "coin_04"} { + if !hasOverlayFillText(vp.Ops, wantText) { + t.Fatalf("2D viewport missing overlay text %q before toggling legend off", wantText) + } + } + + // 2. Toggle Selection, Added, and Removed OFF via the top-left legend switches. + app.Press("id:legend-selection") + app.Settle() + app.Press("id:legend-added") + app.Settle() + app.Press("id:legend-removed") + app.Settle() + + if app.Find("id:legend-selection").Props.Checked { + t.Fatal("legend-selection still checked after pressing switch") + } + if app.Find("id:legend-added").Props.Checked { + t.Fatal("legend-added still checked after pressing switch") + } + if app.Find("id:legend-removed").Props.Checked { + t.Fatal("legend-removed still checked after pressing switch") + } + + vpAfter := app.Find("id:editor-viewport") + if hasOverlayFillText(vpAfter.Ops, "+ new_slime") { + t.Fatal("Added overlay still drew after turning legend-added off") + } + if hasOverlayFillText(vpAfter.Ops, "coin_04") { + t.Fatal("Removed overlay still drew after turning legend-removed off") + } + if !hasOverlayFillText(vpAfter.Ops, "tuning knight") || !hasOverlayFillText(vpAfter.Ops, "z 10 → 12") { + t.Fatal("turning off other legend kinds hid Agent or Changed overlays unexpectedly") + } + + // 3. Switch to 3D viewport: the SAME legend is shown and honors the SAME toggle choices! + app.Post(func() { ed.SetViewMode(editor.ViewMode3D) }) + app.Settle() + if !app.Exists("id:viewport-overlay-legend") { + t.Fatal("expected the same viewport-overlay-legend in 3D viewport") + } + if app.Find("id:legend-added").Props.Checked { + t.Fatal("3D viewport legend-added did not reflect persisted off state") + } + vp3D := app.Find("id:editor-viewport") + if hasOverlayFillText(vp3D.Ops, "+ new_slime") { + t.Fatal("3D viewport drew Added overlay while legend-added was off") + } + if !hasOverlayFillText(vp3D.Ops, "tuning knight") || !hasOverlayFillText(vp3D.Ops, "z 10 → 12") { + t.Fatal("3D viewport missing active Agent/Changed overlays through shared helper") + } + + // 4. Verify project files were untouched and EditorSettings YAML persists choices across restart. + gameAfter, err := os.ReadFile(gamePath) + if err != nil { + t.Fatalf("read game.yaml after: %v", err) + } + sceneAfter, err := os.ReadFile(scenePath) + if err != nil { + t.Fatalf("read %s after: %v", scenePath, err) + } + if !bytes.Equal(gameBefore, gameAfter) || !bytes.Equal(sceneBefore, sceneAfter) { + t.Fatal("toggling overlay legend modified project or scene files") + } + + raw, err := os.ReadFile(settingsPath) + if err != nil { + t.Fatalf("read persisted settings: %v", err) + } + if !strings.Contains(string(raw), "overlayLegend:") { + t.Fatalf("persisted settings missing overlayLegend:\n%s", raw) + } + + restarted, err := editor.New(nil, nil) + if err != nil { + t.Fatalf("editor.New (restarted): %v", err) + } + if err := restarted.LoadSettings(settingsPath); err != nil { + t.Fatalf("restarted.LoadSettings: %v", err) + } + wantActive := []editor.OverlayKind{ + editor.OverlayKindAgent, + editor.OverlayKindChanged, + editor.OverlayKindProblem, + } + if got := restarted.ActiveOverlayLegendKinds(); !slices.Equal(got, wantActive) { + t.Fatalf("restarted ActiveOverlayLegendKinds = %v, want %v", got, wantActive) + } + + // Turning all 6 off writes explicit overlayLegend: [] and survives restart without reverting to defaults. + if err := restarted.SetOverlayLegendKinds(nil); err != nil { + t.Fatalf("SetOverlayLegendKinds(nil): %v", err) + } + emptyRaw, err := os.ReadFile(settingsPath) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(emptyRaw), "overlayLegend: []") { + t.Fatalf("expected explicit overlayLegend: [] in settings YAML, got:\n%s", emptyRaw) + } + restartedEmpty, err := editor.New(nil, nil) + if err != nil { + t.Fatal(err) + } + if err := restartedEmpty.LoadSettings(settingsPath); err != nil { + t.Fatal(err) + } + if got := restartedEmpty.ActiveOverlayLegendKinds(); len(got) != 0 { + t.Fatalf("restartedEmpty ActiveOverlayLegendKinds = %v, want empty", got) + } + + // Invalid and duplicate overlayLegend values are refused by ParseEditorSettings. + for name, bad := range map[string]string{ + "unknown": "version: 1\nlanguage: system\nappearance: system\noverlayLegend:\n - bogus\n", + "duplicate": "version: 1\nlanguage: system\nappearance: system\noverlayLegend:\n - selection\n - selection\n", + } { + if _, err := editor.ParseEditorSettings([]byte(bad)); err == nil { + t.Errorf("ParseEditorSettings(%s) succeeded, want error", name) + } + } +} + +// #1006 Scope: Problems panel problems naming an object in the open scene draw the Problem overlay +// (2 px solid + filled alert pill) in both 2D and 3D viewports, and assetcheck.Problem.Object is populated. +func TestViewportOverlayProblemsPanelIntegration2DAnd3D(t *testing.T) { + ed, dir := setupLiveProblemFixture(t) + if err := ed.OpenProject(dir); err != nil { + t.Fatal(err) + } + ed.WaitForProblems() + + // Rename door_3 -> gate so boss_room's connection ("lever" pulled -> "door_3" open) breaks. + if err := ed.OpenScene("scenes/doors.scene.yaml"); err != nil { + t.Fatal(err) + } + if err := ed.SetObjectID("door_3", "gate"); err != nil { + t.Fatal(err) + } + ed.WaitForProblems() + + probs := ed.Problems() + if len(probs) != 1 { + t.Fatalf("expected 1 live problem, got %+v", probs) + } + if probs[0].Object != "lever" { + t.Fatalf("live problem Object = %q, want %q", probs[0].Object, "lever") + } + + if err := ed.OpenScene("scenes/boss_room.scene.yaml"); err != nil { + t.Fatal(err) + } + ed.SetCanvasSize(640, 360) + + // 2D viewport draws the Problem overlay on live object "lever". + var d2 core.Drawing + ed.DrawViewport(&d2, core.Size{Width: 640, Height: 360}) + if !hasFillTextContaining(d2.Ops, `target "door_3" not found`) { + t.Fatal("2D viewport missing Problem overlay pill on live object lever") + } + + // 3D viewport also draws the Problem overlay on live object "lever". + ed.SetViewMode(editor.ViewMode3D) + ed.FrameSelection() + var d3 core.Drawing + ed.DrawViewport(&d3, core.Size{Width: 640, Height: 360}) + if !hasFillTextContaining(d3.Ops, `target "door_3" not found`) { + t.Fatal("3D viewport missing Problem overlay pill on live object lever") + } + + // Turning Problem off in the legend hides it in both 3D and 2D! + if err := ed.SetOverlayKindVisible(editor.OverlayKindProblem, false); err != nil { + t.Fatal(err) + } + var d3Off core.Drawing + ed.DrawViewport(&d3Off, core.Size{Width: 640, Height: 360}) + if hasFillTextContaining(d3Off.Ops, `target "door_3" not found`) { + t.Fatal("3D viewport still drew Problem overlay after turning Problem legend toggle off") + } + ed.SetViewMode(editor.ViewMode2D) + var d2Off core.Drawing + ed.DrawViewport(&d2Off, core.Size{Width: 640, Height: 360}) + if hasFillTextContaining(d2Off.Ops, `target "door_3" not found`) { + t.Fatal("2D viewport still drew Problem overlay after turning Problem legend toggle off") + } +} + +// #1006 Scope: Camera frame, camera bounds, and tile grid use Spec neutral tokens in a style +// distinct from all semantic legend kinds (never Accent, Agent, Added, Changed, Removed, Problem). +func TestCameraFrameBoundsAndTileGridUseNeutralSpecTokens(t *testing.T) { + ed := newOverlaysTestEditor(t) + _ = ed.SetAppearance(editor.AppearanceDark) + ed.ClearSelection() // ShowingSceneSettings() == true -> highlights camera frame & bounds + ed.ShowGrid = true + + spec := editor.DarkSpecPalette() + forbiddenLegendRGBs := map[uint32]string{ + uint32(spec.Accent.Edge) >> 8: "accent", + uint32(spec.Agent.Edge) >> 8: "agent", + uint32(spec.Added.Edge) >> 8: "added", + uint32(spec.Changed.Edge) >> 8: "changed", + uint32(spec.Removed.Edge) >> 8: "removed", + 0x38BDF8: "legacy sky blue", + } + + // Draw with only camera_bounds overlay enabled (no selection, no semantic overlays). + var d core.Drawing + if err := ed.DrawViewportWithOverlays(&d, core.Size{Width: 640, Height: 360}, []string{editor.OverlayCameraBounds}); err != nil { + t.Fatal(err) + } + for _, op := range d.Ops { + if op.Kind == core.DrawStrokeColor { + rgb := uint32(op.Color) >> 8 + if name, bad := forbiddenLegendRGBs[rgb]; bad { + t.Errorf("camera frame/bounds/snap grid used %s color #%06X; must use neutral Spec tokens distinct from legend kinds", name, rgb) + } + } + } +} + +// #1006 Acceptance 5: Real nsgotest screenshot on macOS showing live overlays and the top-left +// toggle legend in both Dark and Light Spec themes. +func TestViewportOverlaysSpecMacOSScreenshot(t *testing.T) { + ed := newOverlaysTestEditor(t) + ed.SelectObject("knight") + ed.SetReduceMotion(true) + ed.SetSceneOverlays([]editor.SceneOverlayEntry{ + {ID: "ag", ObjectID: "knight", Kind: editor.OverlayKindAgent, Label: "tuning jump"}, + {ID: "ad", ObjectID: "slime_02", Kind: editor.OverlayKindAdded, Label: "slime_02"}, + {ID: "ch", ObjectID: "slime_01", Kind: editor.OverlayKindChanged, Label: "z 10 → 12"}, + {ID: "rm", ObjectID: "coin_04", Kind: editor.OverlayKindRemoved, Label: "coin_04", GhostBounds: &core.Bounds{Origin: core.Point{X: 330, Y: 256}, Size: core.Size{Width: 16, Height: 16}}}, + {ID: "fc", ObjectID: "door_01", Kind: editor.OverlayKindFocusedChange, ChangeKind: editor.OverlayKindAdded, Label: "door_01"}, + }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1440, 900), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + ReduceMotion: true, + })) + app.Settle() + app.Screenshot("viewport-overlays-spec-dark") + + app.SetEnvironment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: false, + ReduceMotion: true, + }) + app.Settle() + app.Screenshot("viewport-overlays-spec-light") +} diff --git a/packages/game/gametest/golden.go b/packages/game/gametest/golden.go index e3456f59f..a57f671cd 100644 --- a/packages/game/gametest/golden.go +++ b/packages/game/gametest/golden.go @@ -68,6 +68,7 @@ func RenderOps(width, height int, ops []core.DrawOp, opts ...RenderOptions) *ima fillColor core.Color strokeColor core.Color lineWidth float64 + dash []float64 } type pathRect struct { x, y, w, h float64 @@ -115,7 +116,11 @@ func RenderOps(width, height int, ops []core.DrawOp, opts ...RenderOptions) *ima for _, op := range ops { switch op.Kind { case core.DrawSave: - stack = append(stack, cur) + saved := cur + if len(cur.dash) > 0 { + saved.dash = slices.Clone(cur.dash) + } + stack = append(stack, saved) case core.DrawRestore: if n := len(stack); n > 0 { cur = stack[n-1] @@ -150,6 +155,22 @@ func RenderOps(width, height int, ops []core.DrawOp, opts ...RenderOptions) *ima if op.W > 0 { cur.lineWidth = float64(op.W) } + case core.DrawLineDash: + cur.dash = nil + if op.Dash != nil && len(*op.Dash) > 0 { + d := make([]float64, 0, len(*op.Dash)) + for _, v := range *op.Dash { + if v > 0 { + d = append(d, float64(v)) + } + } + if len(d) > 0 { + if len(d)%2 == 1 { + d = append(d, d...) + } + cur.dash = d + } + } case core.DrawBeginPath: rects = rects[:0] subs = subs[:0] @@ -160,6 +181,22 @@ func RenderOps(width, height int, ops []core.DrawOp, opts ...RenderOptions) *ima w: float64(op.W), h: float64(op.H), m: cur.m, }) + case core.DrawRoundRect: + if sub, ok := buildRoundRectSub(cur.m, float64(op.X), float64(op.Y), float64(op.W), float64(op.H), float64(op.R)); ok { + subs = append(subs, sub) + } + case core.DrawArc: + if pts := buildArcPoints(cur.m, float64(op.X), float64(op.Y), float64(op.R), float64(op.R), float64(op.A0), float64(op.A1), op.CCW); len(pts) > 0 { + curSub = append(curSub, pts...) + } + case core.DrawEllipse: + rx, ry := float64(op.R), float64(op.RY) + if ry == 0 { + ry = rx + } + if pts := buildArcPoints(cur.m, float64(op.X), float64(op.Y), rx, ry, 0, 2*math.Pi, false); len(pts) > 0 { + subs = append(subs, pathSub{pts: pts, closed: true}) + } case core.DrawMoveTo: if len(curSub) > 0 { subs = append(subs, pathSub{pts: curSub}) @@ -194,16 +231,47 @@ func RenderOps(width, height int, ops []core.DrawOp, opts ...RenderOptions) *ima if sa <= 0 || cur.lineWidth <= 0 { continue } + scale := cur.m.scale() + lw := cur.lineWidth * scale + scaledDash := scaleDashPattern(cur.dash, scale) for _, r := range rects { - strokeTransformedRect(dst, r.m, r.x, r.y, r.w, r.h, cur.lineWidth, sr, sg, sb, sa) + if len(scaledDash) > 0 { + x, y, w, h := normalizeRect(r.x, r.y, r.w, r.h) + p0x, p0y := r.m.apply(x, y) + p1x, p1y := r.m.apply(x+w, y) + p2x, p2y := r.m.apply(x+w, y+h) + p3x, p3y := r.m.apply(x, y+h) + rSub := []pathSub{{ + pts: []pathPt{{p0x, p0y}, {p1x, p1y}, {p2x, p2y}, {p3x, p3y}}, + closed: true, + }} + strokePolygonsDashed(dst, rSub, lw, scaledDash, sr, sg, sb, sa) + } else { + strokeTransformedRect(dst, r.m, r.x, r.y, r.w, r.h, cur.lineWidth, sr, sg, sb, sa) + } } if len(subs) > 0 || len(curSub) >= 2 { all := subs if len(curSub) >= 2 { all = append(slices.Clone(subs), pathSub{pts: curSub}) } - strokePolygons(dst, all, cur.lineWidth, sr, sg, sb, sa) + if len(scaledDash) > 0 { + strokePolygonsDashed(dst, all, lw, scaledDash, sr, sg, sb, sa) + } else { + strokePolygons(dst, all, lw, sr, sg, sb, sa) + } } + case core.DrawFillText: + if op.Text == "" { + continue + } + sr, sg, sb, sa := premulFromColor(cur.fillColor, cur.alpha) + if sa <= 0 { + continue + } + px, py := cur.m.apply(float64(op.X), float64(op.Y)) + scale := max(1, int(math.Round(cur.m.scale()))) + drawBitmapText(dst, int(math.Round(px)), int(math.Round(py))-7*scale, op.Text, sr, sg, sb, sa, scale) case core.DrawClear: clearTransformedRect(dst, cur.m, float64(op.X), float64(op.Y), float64(op.W), float64(op.H)) case core.DrawImage: diff --git a/packages/game/gametest/golden_shapes.go b/packages/game/gametest/golden_shapes.go new file mode 100644 index 000000000..a05a364cb --- /dev/null +++ b/packages/game/gametest/golden_shapes.go @@ -0,0 +1,267 @@ +package gametest + +import ( + "image" + "math" +) + +func (m affine) scale() float64 { + s := math.Sqrt(math.Hypot(m.a, m.b) * math.Hypot(m.c, m.d)) + if math.IsNaN(s) || math.IsInf(s, 0) || s <= 0 { + return 1 + } + return s +} + +func scaleDashPattern(dash []float64, scale float64) []float64 { + if len(dash) == 0 { + return nil + } + out := make([]float64, len(dash)) + for i, v := range dash { + out[i] = v * scale + } + return out +} + +func buildRoundRectSub(m affine, x, y, w, h, r float64) (pathSub, bool) { + x, y, w, h = normalizeRect(x, y, w, h) + if w <= 0 || h <= 0 { + return pathSub{}, false + } + r = min(max(r, 0), min(w/2, h/2)) + if r <= 0 { + p0x, p0y := m.apply(x, y) + p1x, p1y := m.apply(x+w, y) + p2x, p2y := m.apply(x+w, y+h) + p3x, p3y := m.apply(x, y+h) + return pathSub{pts: []pathPt{{p0x, p0y}, {p1x, p1y}, {p2x, p2y}, {p3x, p3y}}, closed: true}, true + } + const cornerSteps = 6 + pts := make([]pathPt, 0, 4*(cornerSteps+1)) + addCorner := func(cx, cy, a0, a1 float64) { + for i := 0; i <= cornerSteps; i++ { + a := a0 + (a1-a0)*float64(i)/float64(cornerSteps) + px, py := m.apply(cx+r*math.Cos(a), cy+r*math.Sin(a)) + pts = append(pts, pathPt{x: px, y: py}) + } + } + addCorner(x+w-r, y+r, -math.Pi/2, 0) + addCorner(x+w-r, y+h-r, 0, math.Pi/2) + addCorner(x+r, y+h-r, math.Pi/2, math.Pi) + addCorner(x+r, y+r, math.Pi, 1.5*math.Pi) + return pathSub{pts: pts, closed: true}, true +} + +func buildArcPoints(m affine, cx, cy, rx, ry, a0, a1 float64, ccw bool) []pathPt { + if rx <= 0 || ry <= 0 { + return nil + } + sweep := a1 - a0 + if 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 ccw { + sweep = -2 * math.Pi + } else { + sweep = 2 * math.Pi + } + } + steps := max(12, min(64, int(math.Ceil(math.Abs(sweep)*max(rx, ry)*m.scale()/2)))) + pts := make([]pathPt, 0, steps+1) + for i := 0; i <= steps; i++ { + a := a0 + sweep*float64(i)/float64(steps) + px, py := m.apply(cx+rx*math.Cos(a), cy+ry*math.Sin(a)) + pts = append(pts, pathPt{x: px, y: py}) + } + return pts +} + +func strokePolygonsDashed(dst *image.RGBA, subs []pathSub, lineWidth float64, dash []float64, sr, sg, sb, sa float64) { + if len(dash) == 0 || lineWidth <= 0 { + strokePolygons(dst, subs, lineWidth, sr, sg, sb, sa) + return + } + var dashedSubs []pathSub + for _, sub := range subs { + n := len(sub.pts) + if n < 2 { + continue + } + segCount := n - 1 + if sub.closed { + segCount = n + } + dashIdx := 0 + rem := dash[0] + drawing := true + var active []pathPt + + flush := func() { + if len(active) >= 2 { + dashedSubs = append(dashedSubs, pathSub{pts: active}) + } + active = nil + } + + for i := range segCount { + p0 := sub.pts[i] + p1 := sub.pts[(i+1)%n] + dx, dy := p1.x-p0.x, p1.y-p0.y + segLen := math.Hypot(dx, dy) + if segLen <= 1e-9 { + continue + } + pos := 0.0 + for pos < segLen-1e-9 { + step := min(rem, segLen-pos) + t0 := pos / segLen + t1 := (pos + step) / segLen + a := pathPt{x: p0.x + dx*t0, y: p0.y + dy*t0} + b := pathPt{x: p0.x + dx*t1, y: p0.y + dy*t1} + if drawing { + if len(active) == 0 { + active = append(active, a) + } + active = append(active, b) + } + pos += step + rem -= step + if rem <= 1e-9 { + if drawing { + flush() + } + dashIdx = (dashIdx + 1) % len(dash) + rem = dash[dashIdx] + drawing = !drawing + } + } + } + flush() + } + strokePolygons(dst, dashedSubs, lineWidth, sr, sg, sb, sa) +} + +var bitmapGlyph5x7 = map[rune][7]uint8{ + ' ': {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, + '!': {0x04, 0x04, 0x04, 0x04, 0x04, 0x00, 0x04}, + '"': {0x0A, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00}, + '+': {0x00, 0x04, 0x04, 0x1F, 0x04, 0x04, 0x00}, + '-': {0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00}, + '.': {0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C}, + '/': {0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10}, + '0': {0x0E, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0E}, + '1': {0x04, 0x0C, 0x04, 0x04, 0x04, 0x04, 0x0E}, + '2': {0x0E, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1F}, + '3': {0x1F, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0E}, + '4': {0x02, 0x06, 0x0A, 0x12, 0x1F, 0x02, 0x02}, + '5': {0x1F, 0x10, 0x1E, 0x01, 0x01, 0x11, 0x0E}, + '6': {0x06, 0x08, 0x10, 0x1E, 0x11, 0x11, 0x0E}, + '7': {0x1F, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08}, + '8': {0x0E, 0x11, 0x11, 0x0E, 0x11, 0x11, 0x0E}, + '9': {0x0E, 0x11, 0x11, 0x0F, 0x01, 0x02, 0x0C}, + ':': {0x00, 0x04, 0x04, 0x00, 0x04, 0x04, 0x00}, + '(': {0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02}, + ')': {0x08, 0x04, 0x02, 0x02, 0x02, 0x04, 0x08}, + '_': {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F}, + 'A': {0x0E, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11}, + 'B': {0x1E, 0x11, 0x11, 0x1E, 0x11, 0x11, 0x1E}, + 'C': {0x0E, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0E}, + 'D': {0x1E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1E}, + 'E': {0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x1F}, + 'F': {0x1F, 0x10, 0x10, 0x1E, 0x10, 0x10, 0x10}, + 'G': {0x0E, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0F}, + 'H': {0x11, 0x11, 0x11, 0x1F, 0x11, 0x11, 0x11}, + 'I': {0x0E, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E}, + 'J': {0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0C}, + 'K': {0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11}, + 'L': {0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1F}, + 'M': {0x11, 0x1B, 0x15, 0x15, 0x11, 0x11, 0x11}, + 'N': {0x11, 0x19, 0x15, 0x13, 0x11, 0x11, 0x11}, + 'O': {0x0E, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E}, + 'P': {0x1E, 0x11, 0x11, 0x1E, 0x10, 0x10, 0x10}, + 'Q': {0x0E, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0D}, + 'R': {0x1E, 0x11, 0x11, 0x1E, 0x14, 0x12, 0x11}, + 'S': {0x0F, 0x10, 0x10, 0x0E, 0x01, 0x01, 0x1E}, + 'T': {0x1F, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04}, + 'U': {0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0E}, + 'V': {0x11, 0x11, 0x11, 0x11, 0x11, 0x0A, 0x04}, + 'W': {0x11, 0x11, 0x11, 0x15, 0x15, 0x1B, 0x11}, + 'X': {0x11, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x11}, + 'Y': {0x11, 0x11, 0x0A, 0x04, 0x04, 0x04, 0x04}, + 'Z': {0x1F, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1F}, + 'a': {0x00, 0x00, 0x0E, 0x01, 0x0F, 0x11, 0x0F}, + 'b': {0x10, 0x10, 0x1E, 0x11, 0x11, 0x11, 0x1E}, + 'c': {0x00, 0x00, 0x0E, 0x10, 0x10, 0x11, 0x0E}, + 'd': {0x01, 0x01, 0x0F, 0x11, 0x11, 0x11, 0x0F}, + 'e': {0x00, 0x00, 0x0E, 0x11, 0x1F, 0x10, 0x0E}, + 'f': {0x06, 0x08, 0x1E, 0x08, 0x08, 0x08, 0x08}, + 'g': {0x00, 0x00, 0x0F, 0x11, 0x0F, 0x01, 0x0E}, + 'h': {0x10, 0x10, 0x1E, 0x11, 0x11, 0x11, 0x11}, + 'i': {0x04, 0x00, 0x0C, 0x04, 0x04, 0x04, 0x0E}, + 'j': {0x02, 0x00, 0x06, 0x02, 0x02, 0x12, 0x0C}, + 'k': {0x10, 0x10, 0x12, 0x14, 0x18, 0x14, 0x12}, + 'l': {0x0C, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0E}, + 'm': {0x00, 0x00, 0x1A, 0x15, 0x15, 0x15, 0x15}, + 'n': {0x00, 0x00, 0x1E, 0x11, 0x11, 0x11, 0x11}, + 'o': {0x00, 0x00, 0x0E, 0x11, 0x11, 0x11, 0x0E}, + 'p': {0x00, 0x00, 0x1E, 0x11, 0x1E, 0x10, 0x10}, + 'q': {0x00, 0x00, 0x0F, 0x11, 0x0F, 0x01, 0x01}, + 'r': {0x00, 0x00, 0x16, 0x19, 0x10, 0x10, 0x10}, + 's': {0x00, 0x00, 0x0F, 0x10, 0x0E, 0x01, 0x1E}, + 't': {0x08, 0x08, 0x1E, 0x08, 0x08, 0x09, 0x06}, + 'u': {0x00, 0x00, 0x11, 0x11, 0x11, 0x13, 0x0D}, + 'v': {0x00, 0x00, 0x11, 0x11, 0x11, 0x0A, 0x04}, + 'w': {0x00, 0x00, 0x11, 0x11, 0x15, 0x15, 0x0A}, + 'x': {0x00, 0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11}, + 'y': {0x00, 0x00, 0x11, 0x11, 0x0F, 0x01, 0x0E}, + 'z': {0x00, 0x00, 0x1F, 0x02, 0x04, 0x08, 0x1F}, + '→': {0x00, 0x04, 0x02, 0x1F, 0x02, 0x04, 0x00}, + '×': {0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x00}, + '·': {0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00}, +} + +func drawBitmapText(dst *image.RGBA, x, y int, text string, sr, sg, sb, sa float64, scale int) { + b := dst.Bounds() + w, h := b.Dx(), b.Dy() + cx := x + for _, ch := range text { + glyph, ok := bitmapGlyph5x7[ch] + if !ok { + if ch >= 'a' && ch <= 'z' { + glyph = bitmapGlyph5x7[ch-'a'+'A'] + } else { + glyph = bitmapGlyph5x7[' '] + } + } + for row := range 7 { + bits := glyph[row] + for col := range 5 { + if bits&(1<<(4-col)) == 0 { + continue + } + for dy := range scale { + py := y + row*scale + dy + if py < 0 || py >= h { + continue + } + for dx := range scale { + px := cx + col*scale + dx + if px < 0 || px >= w { + continue + } + blendOver(dst, px, py, sr, sg, sb, sa) + } + } + } + } + cx += 6 * scale + } +} diff --git a/packages/game/tooling/assetcheck/assetcheck.go b/packages/game/tooling/assetcheck/assetcheck.go index 28b8a6151..4ed29c879 100644 --- a/packages/game/tooling/assetcheck/assetcheck.go +++ b/packages/game/tooling/assetcheck/assetcheck.go @@ -49,6 +49,8 @@ type Problem struct { Line int // Column is the 1-based column on Line where the scene or YAML format knows it, or 0 when unknown. Column int + // Object is the ID of the scene object the problem names or belongs to when known, or "" for file-wide or non-scene problems. + Object string // Message says what is wrong. Message string } @@ -278,6 +280,19 @@ type checker struct { l10nByRoot map[string]*l10nIndex // localeTables holds the parsed l10n YAML string tables discovered in each project root. localeTables map[string]*projectLocales + // curObjectFile and curObject tag scene-object problems recorded against curObjectFile with Object. + curObjectFile string + curObject string +} + +// withObject scopes problems recorded against file inside fn to objectID. +func (c *checker) withObject(file, objectID string, fn func()) { + prevFile, prevObj := c.curObjectFile, c.curObject + c.curObjectFile, c.curObject = file, objectID + defer func() { + c.curObjectFile, c.curObject = prevFile, prevObj + }() + fn() } // problem records a problem in file at line (0 for none). @@ -287,18 +302,27 @@ func (c *checker) problem(file string, line int, format string, args ...any) { // problemAt records a problem in file at 1-based line and column (0 for unknown). func (c *checker) problemAt(file string, line, col int, format string, args ...any) { + obj := "" + if file == c.curObjectFile { + obj = c.curObject + } + c.problemOnObject(file, line, col, obj, format, args...) +} + +// problemOnObject records a problem in file at 1-based line and column attributed to objectID (or "" for none). +func (c *checker) problemOnObject(file string, line, col int, objectID, format string, args ...any) { c.broken[file] = true if line <= 0 { col = 0 } - c.report.Problems = append(c.report.Problems, Problem{File: file, Line: line, Column: col, Message: fmt.Sprintf(format, args...)}) + c.report.Problems = append(c.report.Problems, Problem{File: file, Line: line, Column: col, Object: objectID, Message: fmt.Sprintf(format, args...)}) } // finish sorts the problems, drops repeats and returns the report. func (c *checker) finish() *Report { r := &c.report slices.SortFunc(r.Problems, func(a, b Problem) int { - return cmp.Or(cmp.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line), cmp.Compare(a.Column, b.Column), cmp.Compare(a.Message, b.Message)) + return cmp.Or(cmp.Compare(a.File, b.File), cmp.Compare(a.Line, b.Line), cmp.Compare(a.Column, b.Column), cmp.Compare(a.Object, b.Object), cmp.Compare(a.Message, b.Message)) }) r.Problems = slices.Compact(r.Problems) return r diff --git a/packages/game/tooling/assetcheck/assetcheck_test.go b/packages/game/tooling/assetcheck/assetcheck_test.go index e92ac8968..e79fe3886 100644 --- a/packages/game/tooling/assetcheck/assetcheck_test.go +++ b/packages/game/tooling/assetcheck/assetcheck_test.go @@ -306,6 +306,37 @@ func TestProblemString(t *testing.T) { } } +func TestProblemNamesSceneObject(t *testing.T) { + // Missing sprite frame on a scene object attaches Object ID. + fsys := project(t) + fsys["scenes/room.scene.yaml"].Data = []byte(strings.Replace(roomScene, "frame: hero", "frame: ghost_frame", 1)) + r := mustCheck(t, fsys) + if len(r.Problems) != 1 || r.Problems[0].Object != "hero" { + t.Fatalf("missing sprite frame problem = %+v, want Object=%q", r.Problems, "hero") + } + + // Missing material on a scene object attaches Object ID (not on external non-scene files). + fsys = project(t) + fsys["scenes/room.scene.yaml"].Data = []byte(strings.Replace(roomScene, "material: materials/stone.material.yaml", "material: materials/missing.material.yaml", 1)) + r = mustCheck(t, fsys) + if len(r.Problems) != 1 || r.Problems[0].Object != "hero" { + t.Fatalf("missing material problem = %+v, want Object=%q", r.Problems, "hero") + } + + // Broken texture inside the external material file has empty Object (file-scoped, not a scene object). + fsys = project(t) + delete(fsys, "art/stone.png") + r = mustCheck(t, fsys) + if len(r.Problems) == 0 { + t.Fatal("expected problem for missing art/stone.png") + } + for _, p := range r.Problems { + if p.File != "scenes/room.scene.yaml" && p.Object != "" { + t.Fatalf("non-scene problem %+v unexpectedly set Object=%q", p, p.Object) + } + } +} + func TestProblemsAreSortedAndCounted(t *testing.T) { fsys := project(t) delete(fsys, "art/sky.png") diff --git a/packages/game/tooling/assetcheck/connections_test.go b/packages/game/tooling/assetcheck/connections_test.go index 6178b6d3b..a4048555e 100644 --- a/packages/game/tooling/assetcheck/connections_test.go +++ b/packages/game/tooling/assetcheck/connections_test.go @@ -117,8 +117,8 @@ func TestCheckReportsConnectionsToMissingObjects(t *testing.T) { t.Fatal(err) } want := []assetcheck.Problem{ - {File: "scenes/derived.scene.yaml", Line: lineOf(t, badDerived, "from: crank"), Column: 11, Message: `sceneformat: connection 0 ("crank" pressed -> "door" open): the scene has no object "crank", counting those of the scenes it instances and inherits`}, - {File: "scenes/level.scene.yaml", Line: lineOf(t, badLevel, "to: west/ghost"), Column: 9, Message: `sceneformat: connection 0 ("lever" pressed -> "west/ghost" open): the scene has no object "west/ghost", counting those of the scenes it instances and inherits`}, + {File: "scenes/derived.scene.yaml", Line: lineOf(t, badDerived, "from: crank"), Column: 11, Object: "door", Message: `sceneformat: connection 0 ("crank" pressed -> "door" open): the scene has no object "crank", counting those of the scenes it instances and inherits`}, + {File: "scenes/level.scene.yaml", Line: lineOf(t, badLevel, "to: west/ghost"), Column: 9, Object: "lever", Message: `sceneformat: connection 0 ("lever" pressed -> "west/ghost" open): the scene has no object "west/ghost", counting those of the scenes it instances and inherits`}, } if got := r.Problems; len(got) != len(want) || got[0] != want[0] || got[1] != want[1] { t.Fatalf("problems:\n%s\nwant:\n%v\n%v", problems(r), want[0], want[1]) @@ -292,8 +292,8 @@ func TestCheckWithComponentsReportsOverriddenComponents(t *testing.T) { t.Fatal(err) } want := []assetcheck.Problem{ - {File: "scenes/derived.scene.yaml", Line: lineOf(t, derived, "nope: 3"), Column: 15, Message: `sceneformat: object "door" component "door" field "nope": unknown field (the type has no fields)`}, - {File: "scenes/level.scene.yaml", Line: lineOf(t, level, "door: {nope: 3}"), Column: 28, Message: `sceneformat: object "west/door" component "door" field "nope": unknown field (the type has no fields)`}, + {File: "scenes/derived.scene.yaml", Line: lineOf(t, derived, "nope: 3"), Column: 15, Object: "door", Message: `sceneformat: object "door" component "door" field "nope": unknown field (the type has no fields)`}, + {File: "scenes/level.scene.yaml", Line: lineOf(t, level, "door: {nope: 3}"), Column: 28, Object: "west/door", Message: `sceneformat: object "west/door" component "door" field "nope": unknown field (the type has no fields)`}, } if got := r.Problems; len(got) != len(want) || got[0] != want[0] || got[1] != want[1] { t.Fatalf("problems:\n%s\nwant:\n%v\n%v", problems(r), want[0], want[1]) @@ -309,7 +309,7 @@ func TestCheckWithComponentsReportsConnectionsRepeatingBroughtOnes(t *testing.T) if err != nil { t.Fatal(err) } - want := assetcheck.Problem{File: "scenes/level.scene.yaml", Line: lineOf(t, level, "handler: open"), Column: 14, Message: `sceneformat: connection 0 ("west/button" pressed -> "west/door" open): connects the same event and handler as a connection that a scene it instances or inherits brings`} + want := assetcheck.Problem{File: "scenes/level.scene.yaml", Line: lineOf(t, level, "handler: open"), Column: 14, Object: "west/door", Message: `sceneformat: connection 0 ("west/button" pressed -> "west/door" open): connects the same event and handler as a connection that a scene it instances or inherits brings`} if len(r.Problems) != 1 || r.Problems[0] != want { t.Fatalf("problems:\n%s\nwant:\n%v", problems(r), want) } diff --git a/packages/game/tooling/assetcheck/scene.go b/packages/game/tooling/assetcheck/scene.go index 6da0ac0ff..5512577a3 100644 --- a/packages/game/tooling/assetcheck/scene.go +++ b/packages/game/tooling/assetcheck/scene.go @@ -74,18 +74,45 @@ func (s *sceneCheck) located(err error) { if ce, ok := errors.AsType[*sceneformat.ComponentError](err); ok { e := *ce e.File, e.Line, e.Column = "", 0, 0 - s.problemAt(s.path, min(ce.Line, s.lines), ce.Column, "%v", &e) + s.problemOnObject(s.path, min(ce.Line, s.lines), ce.Column, ce.Object, "%v", &e) return } if ce, ok := errors.AsType[*sceneformat.ConnectionError](err); ok { e := *ce e.File, e.Line, e.Column = "", 0, 0 - s.problemAt(s.path, min(ce.Line, s.lines), ce.Column, "%v", &e) + obj := connectionErrorObject(ce) + s.problemOnObject(s.path, min(ce.Line, s.lines), ce.Column, obj, "%v", &e) return } s.problem(s.path, 0, "%v", err) } +func connectionErrorObject(ce *sceneformat.ConnectionError) string { + if ce == nil { + return "" + } + switch ce.Field { + case "to", "handler": + if ce.To != "" { + return ce.To + } + return ce.From + case "from", "event": + if ce.From != "" { + return ce.From + } + return ce.To + default: + if ce.Arg != "" && ce.To != "" { + return ce.To + } + if ce.From != "" { + return ce.From + } + return ce.To + } +} + // sceneRefs checks doc, a scene that instances or inherits other scenes: that it resolves, that its own connections name objects of the resolved scene and, given component types reg, that the components its overrides change keep their types and that every connection of the resolved scene, its own and those the scenes it instances and inherits bring, names events, handlers and arguments its objects declare. A fault a scene brings unchanged from a file it instances or inherits is reported on that file, which is checked on its own; one this scene's overrides cause is reported at the override, so each fault is reported once. func (s *sceneCheck) sceneRefs(doc *sceneformat.SceneDoc, reg *sceneformat.ComponentRegistry) { projectFS := s.fsys @@ -118,26 +145,32 @@ func (s *sceneCheck) sceneRefs(doc *sceneformat.SceneDoc, reg *sceneformat.Compo } overrides := s.overrides(doc) for _, ov := range overrides { - if o := byID[ov.id]; o != nil && o.Model != "" && (ov.model != nil || ov.modelNode != nil || ov.modelMesh != nil) { - s.overrideModel(o, ov) - } - if o := byID[ov.id]; o != nil && o.GridMap != "" && ov.gridMap != nil { - s.gridMap(o.GridMap, s.line(append(slices.Clip(ov.steps), "gridMap")...)) - } - if ov.reflectionProbe != nil && ov.reflectionProbe.Cubemap != "" { - s.reflectionProbeCubemap(ov.reflectionProbe.Cubemap, append(slices.Clip(ov.steps), "reflectionProbe", "cubemap")...) - } - if ov.lightProbeGrid != nil && ov.lightProbeGrid.Data != "" { - s.lightProbeGridData(ov.lightProbeGrid.Data, append(slices.Clip(ov.steps), "lightProbeGrid", "data")...) - } + s.withObject(s.path, ov.id, func() { + if o := byID[ov.id]; o != nil && o.Model != "" && (ov.model != nil || ov.modelNode != nil || ov.modelMesh != nil) { + s.overrideModel(o, ov) + } + if o := byID[ov.id]; o != nil && o.GridMap != "" && ov.gridMap != nil { + s.gridMap(o.GridMap, s.line(append(slices.Clip(ov.steps), "gridMap")...)) + } + if ov.reflectionProbe != nil && ov.reflectionProbe.Cubemap != "" { + s.reflectionProbeCubemap(ov.reflectionProbe.Cubemap, append(slices.Clip(ov.steps), "reflectionProbe", "cubemap")...) + } + if ov.lightProbeGrid != nil && ov.lightProbeGrid.Data != "" { + s.lightProbeGridData(ov.lightProbeGrid.Data, append(slices.Clip(ov.steps), "lightProbeGrid", "data")...) + } + }) } missing := false for i, c := range conns { - for _, end := range []struct{ field, id string }{{"from", c.From}, {"to", c.To}} { + for _, end := range []struct{ field, id, other string }{{"from", c.From, c.To}, {"to", c.To, c.From}} { if byID[end.id] == nil { missing = true line, col := s.pos("connections", strconv.Itoa(i), end.field) - s.problemAt(s.path, line, col, "sceneformat: connection %d (%q %s -> %q %s): the scene has no object %q, counting those of the scenes it instances and inherits", i, c.From, c.Event, c.To, c.Handler, end.id) + liveObj := "" + if byID[end.other] != nil { + liveObj = end.other + } + s.problemOnObject(s.path, line, col, liveObj, "sceneformat: connection %d (%q %s -> %q %s): the scene has no object %q, counting those of the scenes it instances and inherits", i, c.From, c.Event, c.To, c.Handler, end.id) } } } @@ -157,13 +190,13 @@ func (s *sceneCheck) sceneRefs(doc *sceneformat.SceneDoc, reg *sceneformat.Compo ce, ok := errors.AsType[*sceneformat.ComponentError](err) if !ok { line, col := s.pos(append(slices.Clip(ov.steps), "components", name)...) - s.problemAt(s.path, line, col, "sceneformat: object %q component %q: %v", ov.id, name, err) + s.problemOnObject(s.path, line, col, ov.id, "sceneformat: object %q component %q: %v", ov.id, name, err) continue } e := *ce e.File, e.Line, e.Column, e.Object = "", 0, 0, ov.id line, col := s.pos(append(slices.Clip(ov.steps), "components", name, ce.Field)...) - s.problemAt(s.path, line, col, "%v", &e) + s.problemOnObject(s.path, line, col, ov.id, "%v", &e) } } s.resolvedConnections(resolved, len(resolved.Connections), conns, overrides, reg) @@ -207,7 +240,7 @@ func (s *sceneCheck) resolvedConnections(resolved *sceneformat.SceneDoc, merged steps = append(steps, e.Arg) } line, col := s.pos(steps...) - s.problemAt(s.path, line, col, "%v", &e) + s.problemOnObject(s.path, line, col, connectionErrorObject(&e), "%v", &e) } else { at := e.To if e.Field == "from" || e.Field == "event" { @@ -219,7 +252,7 @@ func (s *sceneCheck) resolvedConnections(resolved *sceneformat.SceneDoc, merged arg = fmt.Sprintf(" argument %q", e.Arg) } line, col := s.pos(overrides[i].steps...) - s.problemAt(s.path, line, col, "sceneformat: the override of object %q breaks connection (%q %s -> %q %s)%s, which a scene it instances or inherits brings: %s", at, e.From, e.Event, e.To, e.Handler, arg, e.Msg) + s.problemOnObject(s.path, line, col, at, "sceneformat: the override of object %q breaks connection (%q %s -> %q %s)%s, which a scene it instances or inherits brings: %s", at, e.From, e.Event, e.To, e.Handler, arg, e.Msg) } } resolved.Connections = slices.Delete(resolved.Connections, ce.Index, ce.Index+1) @@ -287,7 +320,7 @@ func (s *sceneCheck) unresolved(own *sceneformat.SceneDoc, files *sceneFiles, er if len(o.Overrides) > 0 && strings.Contains(ierr.Error(), " overrides ") { field = "overrides" } - s.problem(s.path, s.line(append(slices.Clip(steps), field)...), "%v", ierr) + s.problemOnObject(s.path, s.line(append(slices.Clip(steps), field)...), 0, o.ID, "%v", ierr) }) if found { return @@ -337,31 +370,33 @@ func (s *sceneCheck) objects(objs []sceneformat.ObjectDoc, steps ...string) { for j := range objs { o := &objs[j] op := append(slices.Clip(steps), strconv.Itoa(j)) - if o.Sprite != nil { - s.sprite(o.Sprite, append(slices.Clip(op), "sprite")...) - } - if o.Material != "" { - s.material(o.Material, append(slices.Clip(op), "material")...) - } - if o.Particles != nil { - s.particlesRef(o.Particles, append(slices.Clip(op), "particles")...) - } - if o.Model != "" { - at := func(key string) int { return s.line(append(slices.Clip(op), key)...) } - s.model(o.Model, o.ModelNode, o.ModelMesh, at("model"), at("modelNode"), at("modelMesh"), true) - } - if o.GridMap != "" { - s.gridMap(o.GridMap, s.line(append(slices.Clip(op), "gridMap")...)) - } - if o.ReflectionProbe != nil && o.ReflectionProbe.Cubemap != "" { - s.reflectionProbeCubemap(o.ReflectionProbe.Cubemap, append(slices.Clip(op), "reflectionProbe", "cubemap")...) - } - if o.LightProbeGrid != nil && o.LightProbeGrid.Data != "" { - s.lightProbeGridData(o.LightProbeGrid.Data, append(slices.Clip(op), "lightProbeGrid", "data")...) - } - if o.Components != nil { - s.animator(o, op...) - } + s.withObject(s.path, o.ID, func() { + if o.Sprite != nil { + s.sprite(o.Sprite, append(slices.Clip(op), "sprite")...) + } + if o.Material != "" { + s.material(o.Material, append(slices.Clip(op), "material")...) + } + if o.Particles != nil { + s.particlesRef(o.Particles, append(slices.Clip(op), "particles")...) + } + if o.Model != "" { + at := func(key string) int { return s.line(append(slices.Clip(op), key)...) } + s.model(o.Model, o.ModelNode, o.ModelMesh, at("model"), at("modelNode"), at("modelMesh"), true) + } + if o.GridMap != "" { + s.gridMap(o.GridMap, s.line(append(slices.Clip(op), "gridMap")...)) + } + if o.ReflectionProbe != nil && o.ReflectionProbe.Cubemap != "" { + s.reflectionProbeCubemap(o.ReflectionProbe.Cubemap, append(slices.Clip(op), "reflectionProbe", "cubemap")...) + } + if o.LightProbeGrid != nil && o.LightProbeGrid.Data != "" { + s.lightProbeGridData(o.LightProbeGrid.Data, append(slices.Clip(op), "lightProbeGrid", "data")...) + } + if o.Components != nil { + s.animator(o, op...) + } + }) s.objects(o.Children, append(slices.Clip(op), "children")...) } } @@ -755,11 +790,13 @@ func (c *checker) yamlError(p string, data []byte, err error) { if fe, ok := errors.AsType[*sceneformat.FieldError](err); ok { var root yaml.Node line, col := 0, 0 + obj := "" if yaml.Unmarshal(data, &root) == nil { line, col = yamlPos(&root, fe.Path) line = min(line, yamlLineCount(data)) + obj = yamlFieldErrorObject(&root, fe.Path) } - c.problemAt(p, line, col, "%v", fe) + c.problemOnObject(p, line, col, obj, "%v", fe) return } if te, ok := errors.AsType[*yaml.TypeError](err); ok { @@ -848,3 +885,118 @@ func yamlPos(root *yaml.Node, steps []string) (int, int) { } return line, col } + +// yamlFieldErrorObject resolves the scene object ID associated with a sceneformat.FieldError +// path (under layers[*].objects[*]..., overrides...., or connections[*].from/to) when present in root. +func yamlFieldErrorObject(root *yaml.Node, steps []string) string { + if root == nil || len(steps) < 2 { + return "" + } + doc := root + if doc.Kind == yaml.DocumentNode && len(doc.Content) > 0 { + doc = doc.Content[0] + } + if doc.Kind != yaml.MappingNode { + return "" + } + lookup := func(n *yaml.Node, key string) *yaml.Node { + if n == nil || n.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(n.Content); i += 2 { + if n.Content[i].Value == key { + return n.Content[i+1] + } + } + return nil + } + // Collect existing object IDs in the scene so connection errors attach to a live endpoint. + liveIDs := make(map[string]bool) + var collectIDs func(seq *yaml.Node) + collectIDs = func(seq *yaml.Node) { + if seq == nil || seq.Kind != yaml.SequenceNode { + return + } + for _, item := range seq.Content { + if idNode := lookup(item, "id"); idNode != nil && idNode.Value != "" { + liveIDs[idNode.Value] = true + } + collectIDs(lookup(item, "children")) + } + } + if layers := lookup(doc, "layers"); layers != nil && layers.Kind == yaml.SequenceNode { + for _, layer := range layers.Content { + collectIDs(lookup(layer, "objects")) + } + } + + switch steps[0] { + case "layers": + // Walk down layers[i].objects[j](.children[k])* and remember the innermost object ID. + cur := doc + lastID := "" + for i := 0; i < len(steps); i++ { + step := steps[i] + switch cur.Kind { + case yaml.MappingNode: + next := lookup(cur, step) + if next == nil { + return lastID + } + cur = next + case yaml.SequenceNode: + idx, err := strconv.Atoi(step) + if err != nil || idx < 0 || idx >= len(cur.Content) { + return lastID + } + cur = cur.Content[idx] + if i >= 3 && (steps[i-1] == "objects" || steps[i-1] == "children") { + if idNode := lookup(cur, "id"); idNode != nil && idNode.Value != "" { + lastID = idNode.Value + } + } + default: + return lastID + } + } + return lastID + case "overrides": + return steps[1] + case "connections": + conns := lookup(doc, "connections") + idx, err := strconv.Atoi(steps[1]) + if conns == nil || conns.Kind != yaml.SequenceNode || err != nil || idx < 0 || idx >= len(conns.Content) { + return "" + } + conn := conns.Content[idx] + fromID := "" + toID := "" + if n := lookup(conn, "from"); n != nil { + fromID = n.Value + } + if n := lookup(conn, "to"); n != nil { + toID = n.Value + } + field := "" + if len(steps) >= 3 { + field = steps[2] + } + // Attach to the live object endpoint. + if field == "from" { + if liveIDs[toID] { + return toID + } + if liveIDs[fromID] { + return fromID + } + } else { + if liveIDs[fromID] { + return fromID + } + if liveIDs[toID] { + return toID + } + } + } + return "" +} From 67fc81902e2fbc08bb0b05f01013107c96b039d1 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 20:25:12 +0900 Subject: [PATCH 2/4] fix(editor): render viewport overlay legend as compact 1x6 strip in 2D and 3D --- packages/game/editor/spec_feedback_ui.go | 184 +++++++---------------- 1 file changed, 54 insertions(+), 130 deletions(-) diff --git a/packages/game/editor/spec_feedback_ui.go b/packages/game/editor/spec_feedback_ui.go index c08c255fd..9658d90d2 100644 --- a/packages/game/editor/spec_feedback_ui.go +++ b/packages/game/editor/spec_feedback_ui.go @@ -811,13 +811,13 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint } p := SpecPaletteFor(k.dark) leftPt := core.Pt(10) - topPt := core.Pt(10) - compact3D := k.viewMode == ViewMode3D - if compact3D { - // Sit cleanly beneath view3d-bar + view3d-help in the 3D viewport's top-left corner - // using a compact 2×3 layout so the middle-left orbit/pan zone stays unobstructed. + topPt := core.Pt(8) + if k.viewMode == ViewMode3D { + // Sit as a compact 1×6 strip at y ∈ [120, 148] beneath view3d-bar + view3d-help + // and the top-right orientation widget, clear of top-view ortho pick targets (y≈110), + // upper-left 3D plugin tool drags (y=100), and middle-left orbit/pan drags (y=170). leftPt = core.Pt(16) - topPt = core.Pt(92) + topPt = core.Pt(120) } legendLabel := func(kind OverlayKind) string { @@ -864,23 +864,17 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint label := legendLabel(kind) swatchAlpha := float32(1) textColor := p.TextSecondary + chipBg := ui.Alpha(role.Fill, 0.7) + chipBorder := ui.Alpha(role.Edge, 0.45) if !on { - swatchAlpha = 0.35 + swatchAlpha = 0.32 textColor = p.TextFaint - } - trackBg := p.LineRaised - knobLeft := core.Pt(2) - if on { - trackBg = role.Fg - knobLeft = core.Pt(12) - } - knobBg := specHandleFill(p) - if on && p.Dark { - knobBg = role.OnFill + chipBg = core.Transparent + chipBorder = core.Transparent } swatch := core.Canvas{ - Style: core.Style{Width: core.Pt(26), Height: core.Pt(12), FlexShrink: 0}, + Style: core.Style{Width: core.Pt(18), Height: core.Pt(12), FlexShrink: 0}, Draw: func(d *core.Drawing, _ core.Size) { d.Save() edge := ui.Alpha(role.Edge, swatchAlpha) @@ -889,89 +883,52 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint case OverlayKindSelection: // 1.5 px solid accent line + two corner handle squares. d.SetStrokeColor(edge).SetLineWidth(1.5) - d.BeginPath().MoveTo(4, 6).LineTo(22, 6).Stroke() + d.BeginPath().MoveTo(3, 6).LineTo(15, 6).Stroke() hf := ui.Alpha(specHandleFill(p), swatchAlpha) - for _, hx := range [2]float32{1.5, 19.5} { - d.SetFillColor(hf).BeginPath().RoundRect(hx, 3.5, 5, 5, 1).Fill() - d.SetStrokeColor(edge).SetLineWidth(1.2).BeginPath().RoundRect(hx, 3.5, 5, 5, 1).Stroke() + for _, hx := range [2]float32{1, 13} { + d.SetFillColor(hf).BeginPath().RoundRect(hx, 4, 4, 4, 1).Fill() + d.SetStrokeColor(edge).SetLineWidth(1.1).BeginPath().RoundRect(hx, 4, 4, 4, 1).Stroke() } case OverlayKindAgent: // 1.5 px solid agent violet line + 4-point agent sparkle glyph. d.SetStrokeColor(edge).SetLineWidth(1.5) - d.BeginPath().MoveTo(1.5, 6).LineTo(14.5, 6).Stroke() - drawAgentSparkleGlyph(d, 21, 6, 4.2, fg) + d.BeginPath().MoveTo(1, 6).LineTo(9.5, 6).Stroke() + drawAgentSparkleGlyph(d, 14, 6, 3.6, fg) case OverlayKindAdded: // 1.5 px dashed added green line + "+" cue. - d.SetStrokeColor(edge).SetLineWidth(1.5).SetLineDash(3.5, 2) - d.BeginPath().MoveTo(1.5, 6).LineTo(15.5, 6).Stroke() + d.SetStrokeColor(edge).SetLineWidth(1.5).SetLineDash(3, 2) + d.BeginPath().MoveTo(1, 6).LineTo(10, 6).Stroke() d.SetLineDash() - d.SetStrokeColor(fg).SetLineWidth(1.5).SetLineCap(core.CapRound) - d.BeginPath().MoveTo(18.5, 6).LineTo(24.5, 6).MoveTo(21.5, 3).LineTo(21.5, 9).Stroke() + d.SetStrokeColor(fg).SetLineWidth(1.4).SetLineCap(core.CapRound) + d.BeginPath().MoveTo(12, 6).LineTo(17, 6).MoveTo(14.5, 3.5).LineTo(14.5, 8.5).Stroke() case OverlayKindChanged: // 1.5 px dashed changed amber line + "→" cue. - d.SetStrokeColor(edge).SetLineWidth(1.5).SetLineDash(3.5, 2) - d.BeginPath().MoveTo(1.5, 6).LineTo(14.5, 6).Stroke() + d.SetStrokeColor(edge).SetLineWidth(1.5).SetLineDash(3, 2) + d.BeginPath().MoveTo(1, 6).LineTo(9.5, 6).Stroke() d.SetLineDash() - d.SetStrokeColor(fg).SetLineWidth(1.5).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) - d.BeginPath().MoveTo(17.5, 6).LineTo(24.5, 6).MoveTo(22, 3.5).LineTo(24.5, 6).LineTo(22, 8.5).Stroke() + d.SetStrokeColor(fg).SetLineWidth(1.4).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) + d.BeginPath().MoveTo(11.5, 6).LineTo(17, 6).MoveTo(15, 4).LineTo(17, 6).LineTo(15, 8).Stroke() case OverlayKindRemoved: // 1.5 px solid removed red frame around a 25% grey ghost + strikethrough cue. - d.SetFillColor(ui.Alpha(p.TextFaint, 0.28*swatchAlpha)).BeginPath().RoundRect(2.5, 2.5, 11, 7, 1.5).Fill() - d.SetStrokeColor(edge).SetLineWidth(1.5).BeginPath().RoundRect(1.5, 1.5, 13, 9, 2).Stroke() - d.SetStrokeColor(fg).SetLineWidth(1.4).SetLineCap(core.CapRound) - d.BeginPath().MoveTo(17, 6).LineTo(24.5, 6).Stroke() + d.SetFillColor(ui.Alpha(p.TextFaint, 0.28*swatchAlpha)).BeginPath().RoundRect(2, 2.5, 8, 7, 1.5).Fill() + d.SetStrokeColor(edge).SetLineWidth(1.5).BeginPath().RoundRect(1, 1.5, 10, 9, 2).Stroke() + d.SetStrokeColor(fg).SetLineWidth(1.3).SetLineCap(core.CapRound) + d.BeginPath().MoveTo(12.5, 6).LineTo(17.5, 6).Stroke() case OverlayKindProblem: // 2 px solid problem red line + filled alert triangle badge. d.SetStrokeColor(edge).SetLineWidth(2) - d.BeginPath().MoveTo(1.5, 6).LineTo(12.5, 6).Stroke() - d.SetFillColor(fg).BeginPath().RoundRect(15, 0.5, 11, 11, 5.5).Fill() + d.BeginPath().MoveTo(1, 6).LineTo(7, 6).Stroke() + d.SetFillColor(fg).BeginPath().RoundRect(8.5, 1, 9.5, 9.5, 4.75).Fill() onFill := ui.Alpha(role.OnFill, swatchAlpha) - d.SetStrokeColor(onFill).SetLineWidth(1.2).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) - d.BeginPath().MoveTo(20.5, 2.5).LineTo(23.8, 8.8).LineTo(17.2, 8.8).ClosePath().Stroke() - d.BeginPath().MoveTo(20.5, 5).LineTo(20.5, 6.7).Stroke() + d.SetStrokeColor(onFill).SetLineWidth(1.1).SetLineCap(core.CapRound).SetLineJoin(core.JoinRound) + d.BeginPath().MoveTo(13.25, 2.8).LineTo(16, 8.2).LineTo(10.5, 8.2).ClosePath().Stroke() + d.BeginPath().MoveTo(13.25, 4.8).LineTo(13.25, 6.4).Stroke() } d.Restore() }, } - switchTrack := core.View{ - PointerEvents: core.PointerEventsNone, - Style: core.Style{ - Position: core.Relative, - Width: core.Pt(22), - Height: core.Pt(12), - CornerRadius: 6, - Background: trackBg, - FlexShrink: 0, - }, - Children: []core.Node{ - core.View{ - Style: core.Style{ - Position: core.Absolute, - Left: knobLeft, - Top: core.Pt(2), - Width: core.Pt(8), - Height: core.Pt(8), - CornerRadius: 4, - Background: knobBg, - }, - }, - }, - } - kindCopy := kind - rowStyle := core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 6, - Height: core.Pt(20), - Padding: core.Symmetric(0, 4), - CornerRadius: 5, - FocusVisible: p.FocusRing(2), - } - if compact3D { - rowStyle.MinWidth = core.Pt(138) - } return core.View{ TestID: "legend-" + string(kind), Role: core.RoleSwitch, @@ -981,69 +938,35 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint OnPress: func(core.PressEvent) { ed.report(ed.ToggleOverlayKind(kindCopy)) }, - Style: rowStyle, + Style: core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 3, + Height: core.Pt(20), + Padding: core.Symmetric(0, 4), + CornerRadius: 5, + Background: chipBg, + BorderWidth: 1, + BorderColor: chipBorder, + FlexShrink: 0, + FocusVisible: p.FocusRing(2), + }, Children: []core.Node{ swatch, core.Text{ Content: label, MaxLines: 1, Style: core.Style{ - FlexGrow: 1, - FontSize: 11, + FontSize: 10, FontWeight: 500, Color: textColor, }, }, - switchTrack, - }, - } - } - if compact3D { - kinds := OverlayLegendKinds() - leftCol := make([]core.Node, 0, 3) - rightCol := make([]core.Node, 0, 3) - for i, kind := range kinds { - if i < 3 { - leftCol = append(leftCol, legendRow(kind)) - } else { - rightCol = append(rightCol, legendRow(kind)) - } - } - return core.View{ - TestID: "viewport-overlay-legend", - Role: core.RoleGroup, - Label: ed.T("overlays.legendTitle"), - Style: core.Style{ - Position: core.Absolute, - Left: leftPt, - Top: topPt, - Direction: core.Row, - Gap: 6, - Padding: core.Symmetric(4, 5), - CornerRadius: 8, - Background: p.Raised, - BorderWidth: 1, - BorderColor: p.LineRaised, - }, - Children: []core.Node{ - core.View{Style: core.Style{Gap: 2}, Children: leftCol}, - core.View{Style: core.Style{Gap: 2}, Children: rightCol}, }, } } - children := make([]core.Node, 0, 7) - children = append(children, core.Text{ - TestID: "viewport-overlay-legend-title", - Content: ed.T("overlays.legendTitle"), - Style: core.Style{ - FontSize: 9.5, - FontWeight: 600, - LetterSpacing: 0.6, - Color: p.TextFaint, - Padding: core.Edges{Left: 4, Right: 4, Top: 1, Bottom: 1}, - }, - }) + children := make([]core.Node, 0, 6) for _, kind := range OverlayLegendKinds() { children = append(children, legendRow(kind)) } @@ -1056,9 +979,10 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint Position: core.Absolute, Left: leftPt, Top: topPt, - MinWidth: core.Pt(150), - Padding: core.Symmetric(4, 4), - Gap: 1, + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 2, + Padding: core.Symmetric(3, 4), CornerRadius: 8, Background: p.Raised, BorderWidth: 1, From 0d38d4a15a89d79e33a8a8f4dfe5dc2794cd4148 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Thu, 26 Nov 2026 21:31:57 +0900 Subject: [PATCH 3/4] fix(editor,assetcheck): harden Spec viewport overlays, legend focus, 3D/History guards, and connection attribution --- packages/game/editor/agent.go | 1 + packages/game/editor/agent_live.go | 28 +- packages/game/editor/spec_feedback_ui.go | 84 ++--- packages/game/editor/tabs.go | 3 + packages/game/editor/viewport.go | 98 +++--- packages/game/editor/viewport3d.go | 2 +- packages/game/editor/viewport_overlay.go | 295 +++++++++++------- packages/game/editor/viewport_overlay_test.go | 209 +++++++++++++ .../tooling/assetcheck/connections_test.go | 56 ++++ packages/game/tooling/assetcheck/scene.go | 16 +- 10 files changed, 574 insertions(+), 218 deletions(-) diff --git a/packages/game/editor/agent.go b/packages/game/editor/agent.go index 3bcbd6634..d0e0ab7c8 100644 --- a/packages/game/editor/agent.go +++ b/packages/game/editor/agent.go @@ -607,6 +607,7 @@ func (e *Editor) resetAgentForProject() { e.CloseAskInPlace() e.resetTurnReviewForProject() e.resetTaskNotificationsForProject() + e.sceneOverlays = nil e.agent.activeRunID++ e.agent.activeTurnID = "" e.agent.clients = nil diff --git a/packages/game/editor/agent_live.go b/packages/game/editor/agent_live.go index 4c235dadd..a0b83e038 100644 --- a/packages/game/editor/agent_live.go +++ b/packages/game/editor/agent_live.go @@ -773,12 +773,12 @@ func (e *Editor) HasAgentLiveOverlays() bool { } // OverlayLegendKindEnabled reports whether the Spec overlay legend row kind is currently toggled on. -// All kinds default to enabled unless persisted in EditorSettings.HiddenOverlayKinds. +// All kinds default to enabled unless persisted in EditorSettings.OverlayLegend / HiddenOverlayKinds. func (e *Editor) OverlayLegendKindEnabled(kind OverlayLegendKind) bool { if e == nil || !kind.Valid() { return true } - return !slices.Contains(e.settings.HiddenOverlayKinds, string(kind)) + return e.OverlayKindVisible(OverlayKind(kind)) } // SetOverlayLegendKind turns the Spec overlay legend row kind on or off and persists the choice @@ -790,29 +790,7 @@ func (e *Editor) SetOverlayLegendKind(kind OverlayLegendKind, on bool) error { if !kind.Valid() { return fmt.Errorf("editor: unknown overlay legend kind %q", kind) } - if e.OverlayLegendKindEnabled(kind) == on { - return nil - } - cur := e.Settings() - k := string(kind) - if on { - cur.HiddenOverlayKinds = slices.DeleteFunc(cur.HiddenOverlayKinds, func(s string) bool { return s == k }) - if len(cur.HiddenOverlayKinds) == 0 { - cur.HiddenOverlayKinds = nil - } - } else if !slices.Contains(cur.HiddenOverlayKinds, k) { - cur.HiddenOverlayKinds = append(cur.HiddenOverlayKinds, k) - slices.Sort(cur.HiddenOverlayKinds) - } - e.settings = cur - if e.SettingsPath != "" { - if err := SaveEditorSettings(e.SettingsPath, &cur); err != nil { - e.notify() - return err - } - } - e.notify() - return nil + return e.SetOverlayKindVisible(OverlayKind(kind), on) } // ToggleOverlayLegendKind flips the Spec overlay legend row kind between shown and hidden diff --git a/packages/game/editor/spec_feedback_ui.go b/packages/game/editor/spec_feedback_ui.go index 9658d90d2..55b81414f 100644 --- a/packages/game/editor/spec_feedback_ui.go +++ b/packages/game/editor/spec_feedback_ui.go @@ -777,25 +777,17 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint dark bool viewMode ViewMode lang string - mask uint8 } keyMemo := core.NewMemo(cx, func() legendStateKey { _ = rev.Get() if ed == nil || ed.Playing() || ed.HistoryPreviewActive() || !ed.OverlayLegendOpen() { return legendStateKey{} } - var mask uint8 - for i, k := range OverlayLegendKinds() { - if ed.OverlayKindVisible(k) { - mask |= 1 << uint(i) - } - } return legendStateKey{ visible: true, - dark: cx.Dark(), + dark: ed.SpecPalette(cx).Dark, viewMode: ed.ViewMode, lang: ed.ResolvedLanguage(), - mask: mask, } }) @@ -859,27 +851,22 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint } legendRow := func(kind OverlayKind) core.Node { - on := ed.OverlayKindVisible(kind) - role := legendRole(kind) - label := legendLabel(kind) - swatchAlpha := float32(1) - textColor := p.TextSecondary - chipBg := ui.Alpha(role.Fill, 0.7) - chipBorder := ui.Alpha(role.Edge, 0.45) - if !on { - swatchAlpha = 0.32 - textColor = p.TextFaint - chipBg = core.Transparent - chipBorder = core.Transparent - } + kindCopy := kind + role := legendRole(kindCopy) + label := legendLabel(kindCopy) swatch := core.Canvas{ Style: core.Style{Width: core.Pt(18), Height: core.Pt(12), FlexShrink: 0}, Draw: func(d *core.Drawing, _ core.Size) { + _ = rev.Get() + swatchAlpha := float32(1) + if !ed.OverlayKindVisible(kindCopy) { + swatchAlpha = 0.32 + } d.Save() edge := ui.Alpha(role.Edge, swatchAlpha) fg := ui.Alpha(role.Fg, swatchAlpha) - switch kind { + switch kindCopy { case OverlayKindSelection: // 1.5 px solid accent line + two corner handle squares. d.SetStrokeColor(edge).SetLineWidth(1.5) @@ -928,9 +915,8 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint }, } - kindCopy := kind return core.View{ - TestID: "legend-" + string(kind), + TestID: "legend-" + string(kindCopy), Role: core.RoleSwitch, Label: label, Checked: func() bool { _ = rev.Get(); return ed.OverlayKindVisible(kindCopy) }, @@ -938,28 +924,44 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint OnPress: func(core.PressEvent) { ed.report(ed.ToggleOverlayKind(kindCopy)) }, - Style: core.Style{ - Direction: core.Row, - AlignItems: core.AlignCenter, - Gap: 3, - Height: core.Pt(20), - Padding: core.Symmetric(0, 4), - CornerRadius: 5, - Background: chipBg, - BorderWidth: 1, - BorderColor: chipBorder, - FlexShrink: 0, - FocusVisible: p.FocusRing(2), + StyleFunc: func() core.Style { + _ = rev.Get() + chipBg := ui.Alpha(role.Fill, 0.7) + chipBorder := ui.Alpha(role.Edge, 0.45) + if !ed.OverlayKindVisible(kindCopy) { + chipBg = core.Transparent + chipBorder = core.Transparent + } + return core.Style{ + Direction: core.Row, + AlignItems: core.AlignCenter, + Gap: 3, + Height: core.Pt(20), + Padding: core.Symmetric(0, 4), + CornerRadius: 5, + Background: chipBg, + BorderWidth: 1, + BorderColor: chipBorder, + FlexShrink: 0, + FocusVisible: p.FocusRing(2), + } }, Children: []core.Node{ swatch, core.Text{ Content: label, MaxLines: 1, - Style: core.Style{ - FontSize: 10, - FontWeight: 500, - Color: textColor, + StyleFunc: func() core.Style { + _ = rev.Get() + textColor := p.TextSecondary + if !ed.OverlayKindVisible(kindCopy) { + textColor = p.TextFaint + } + return core.Style{ + FontSize: 10, + FontWeight: 500, + Color: textColor, + } }, }, }, diff --git a/packages/game/editor/tabs.go b/packages/game/editor/tabs.go index c661cc925..0df463a59 100644 --- a/packages/game/editor/tabs.go +++ b/packages/game/editor/tabs.go @@ -58,6 +58,7 @@ type sceneTab struct { tileSel TileRect hasTileSel bool tileReview *tileReviewState + sceneOverlays []SceneOverlayEntry agentTurn *agentLiveTurnState agentWorkingIDs []string agentWorkingActivity string @@ -165,6 +166,7 @@ func (e *Editor) syncActiveTab() { t.tileSel = e.tileSel t.hasTileSel = e.hasTileSel t.tileReview = e.tileReview + t.sceneOverlays = e.sceneOverlays t.agentTurn = e.agentLive.turn t.agentWorkingIDs = slices.Clone(e.agentLive.workingIDs) t.agentWorkingActivity = e.agentLive.workingActivity @@ -210,6 +212,7 @@ func (e *Editor) loadActiveTab() { e.hasTileSel = t.hasTileSel hadWorking := len(e.agentLive.workingIDs) > 0 e.tileReview = t.tileReview + e.sceneOverlays = t.sceneOverlays e.agentLive.turn = t.agentTurn e.agentLive.workingIDs = slices.Clone(t.agentWorkingIDs) if len(e.agentLive.workingIDs) > 0 { diff --git a/packages/game/editor/viewport.go b/packages/game/editor/viewport.go index 110cf60eb..337a743ac 100644 --- a/packages/game/editor/viewport.go +++ b/packages/game/editor/viewport.go @@ -880,18 +880,6 @@ func (e *Editor) drawAgentTaskOverlays(d *core.Drawing, scene *sceneformat.Built continue } paired := e.IsSelected(ov.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) - // Draw the pulsing/holding outline on every target object (pill drawn once per task group below). - DrawObjectOverlay(d, spec, ObjectOverlay{ - Kind: OverlayKindAgent, - TaskNumber: ov.TaskNumber, - Holding: ov.Holding, - Bounds: bounds, - CanvasSize: canvas, - PairedWithSelection: paired, - Elapsed: now.Sub(e.overlayEpoch), - HasElapsed: true, - ReduceMotion: rm, - }) boxes = append(boxes, objBox{ov: ov, bounds: bounds, paired: paired}) } @@ -902,16 +890,39 @@ func (e *Editor) drawAgentTaskOverlays(d *core.Drawing, scene *sceneformat.Built holding bool } var groupOrder []pillGroupKey - anchorByGroup := make(map[pillGroupKey]objBox) - for _, b := range boxes { + anchorIdxByGroup := make(map[pillGroupKey]int) + for i, b := range boxes { k := pillGroupKey{taskID: b.ov.TaskID, holding: b.ov.Holding} - prev, exists := anchorByGroup[k] + prevIdx, exists := anchorIdxByGroup[k] if !exists { groupOrder = append(groupOrder, k) - anchorByGroup[k] = b - } else if b.bounds.Origin.Y < prev.bounds.Origin.Y { - anchorByGroup[k] = b + anchorIdxByGroup[k] = i + } else if b.bounds.Origin.Y < boxes[prevIdx].bounds.Origin.Y { + anchorIdxByGroup[k] = i + } + } + isAnchor := make([]bool, len(boxes)) + for _, idx := range anchorIdxByGroup { + isAnchor[idx] = true + } + + // Draw outline-only on non-anchor target objects (anchors draw outline + pill once below so + // semi-transparent pulsing/holding outlines are never double-stroked). + for i, b := range boxes { + if isAnchor[i] { + continue } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: OverlayKindAgent, + TaskNumber: b.ov.TaskNumber, + Holding: b.ov.Holding, + Bounds: b.bounds, + CanvasSize: canvas, + PairedWithSelection: b.paired, + Elapsed: now.Sub(e.overlayEpoch), + HasElapsed: true, + ReduceMotion: rm, + }) } overlapsAny := func(r core.Bounds, placed []core.Bounds) bool { @@ -928,7 +939,7 @@ func (e *Editor) drawAgentTaskOverlays(d *core.Drawing, scene *sceneformat.Built var placed []core.Bounds for _, k := range groupOrder { - b := anchorByGroup[k] + b := boxes[anchorIdxByGroup[k]] stackOff := float32(0) if b.paired { stackOff = 24 @@ -1290,38 +1301,49 @@ func ViewportView(cx *core.Scope, ed *Editor, rev *core.Signal[uint64]) core.Nod // Animate active Agent working pulses (1.6 s) and change overlay fade-ins (240 ms). // Disabled completely when ReduceMotion is enabled so nothing fades or pulses. + // Uses an explicit running flag so a subsequent change fade re-arms the timer cleanly + // after an earlier 240 ms fade has completed. overlayAnimRev := core.NewSignal(cx, uint64(0)) - animateOverlays := core.NewMemo(cx, func() bool { - _ = rev.Get() - if cx.Env().ReduceMotion() || ed.ReduceMotion() { - return false - } - return ed.hasAnimatedOverlays() - }) - cx.Effect(func() { - if !animateOverlays.Get() { - return - } - stopped := false + { var stop func() bool + running := false + disposed := false + stopTimer := func() { + if stop != nil { + stop() + stop = nil + } + running = false + } var tick func() tick = func() { - if stopped { + if disposed { return } overlayAnimRev.Set(overlayAnimRev.Get() + 1) if !cx.Env().ReduceMotion() && ed.hasAnimatedOverlays() { stop = cx.AfterFunc(33*time.Millisecond, tick) + } else { + stop = nil + running = false } } - stop = cx.AfterFunc(33*time.Millisecond, tick) - cx.Cleanup(func() { - stopped = true - if stop != nil { - stop() + cx.Effect(func() { + _ = rev.Get() + if cx.Env().ReduceMotion() || !ed.hasAnimatedOverlays() { + stopTimer() + return + } + if !running { + running = true + stop = cx.AfterFunc(33*time.Millisecond, tick) } }) - }) + cx.Cleanup(func() { + disposed = true + stopTimer() + }) + } var g viewportGestures var g3 viewport3DGestures // frame is the view the 3D viewport's flight locks the pointer to. diff --git a/packages/game/editor/viewport3d.go b/packages/game/editor/viewport3d.go index d0e58f5be..209a2d1ea 100644 --- a/packages/game/editor/viewport3d.go +++ b/packages/game/editor/viewport3d.go @@ -2488,7 +2488,7 @@ func (e *Editor) drawSceneObjects3D(d *core.Drawing, w, h float32, overlay bool) }) spec := e.SpecPalette(nil) - selVisible := e.OverlayKindVisible(OverlayKindSelection) + selVisible := !e.playing && !e.HistoryPreviewActive() && e.OverlayKindVisible(OverlayKindSelection) canvas := core.Size{Width: core.Points(w), Height: core.Points(h)} for _, item := range items { diff --git a/packages/game/editor/viewport_overlay.go b/packages/game/editor/viewport_overlay.go index 928f4a97d..322359acf 100644 --- a/packages/game/editor/viewport_overlay.go +++ b/packages/game/editor/viewport_overlay.go @@ -2,6 +2,7 @@ package editor import ( "fmt" + "maps" "math" "slices" "strings" @@ -190,6 +191,29 @@ func specHandleFill(p SpecPalette) core.Color { return p.Raised } +// isWideOverlayRune reports whether r is a fullwidth/CJK rune that occupies roughly twice the +// horizontal advance of an ASCII glyph in overlay pills. +func isWideOverlayRune(r rune) bool { + return (r >= 0x2E80 && r <= 0x9FFF) || + (r >= 0xAC00 && r <= 0xD7AF) || + (r >= 0xF900 && r <= 0xFAFF) || + (r >= 0xFF00 && r <= 0xFFEF) +} + +// overlayTextWidth estimates the drawn width of s in canvas points, matching asciiAdvance per rune +// for ASCII/Latin/arrow strings while expanding CJK/fullwidth characters so localized pills never clip. +func overlayTextWidth(s string, asciiAdvance float32) float32 { + var units float32 + for _, r := range s { + if isWideOverlayRune(r) { + units += 1.85 + } else { + units += 1 + } + } + return units * asciiAdvance +} + // DrawObjectOverlay is the single Spec viewport overlay drawing helper in editor. // It draws any of the seven Spec overlay kinds (Selection, Agent working, Added, Changed, // Removed, Problem, Focused change in Review) using exclusively SpecPalette tokens at the @@ -346,7 +370,7 @@ func drawSelectionSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, } font := core.Font{Size: 10.5, Weight: 600} const tagH float32 = 18 - tagW := float32(len([]rune(ov.Label)))*6.3 + 12 + tagW := overlayTextWidth(ov.Label, 6.3) + 12 tx, ty := clampOverlayPillPos((minX+maxX)*0.5, minY, maxY, handleHalf, tagW, tagH, ov.PillStackOffset, ov.CanvasSize) d.SetFillColor(p.Accent.Fg) @@ -387,7 +411,7 @@ func drawAgentSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bx, const pillH float32 = 22 fontLbl := core.Font{Size: 11, Weight: 500} - textW := float32(len([]rune(ov.Label))) * 6.2 + textW := overlayTextWidth(ov.Label, 6.2) var pillW float32 if ov.TaskNumber > 0 { clockW := float32(0) @@ -417,15 +441,16 @@ func drawAgentSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bx, if ov.TaskNumber > 0 { fontNum := core.Font{Size: 10, Weight: 600} numStr := fmt.Sprintf("%d", ov.TaskNumber) + numHalfW := float32(len(numStr)) * 3 badgeCX := px + 12 badgeCY := py + pillH*0.5 if ov.Holding { d.SetStrokeColor(p.Agent.Edge).SetLineWidth(1.5) d.BeginPath().Ellipse(badgeCX, badgeCY, 7.5, 7.5).Stroke() - d.SetFillColor(p.TextSecondary).FillText(numStr, badgeCX-3, badgeCY+3.5, fontNum) + d.SetFillColor(p.TextSecondary).FillText(numStr, badgeCX-numHalfW, badgeCY+3.5, fontNum) } else { d.SetFillColor(p.Agent.Fg).BeginPath().Ellipse(badgeCX, badgeCY, 8, 8).Fill() - d.SetFillColor(p.Agent.OnFill).FillText(numStr, badgeCX-3, badgeCY+3.5, fontNum) + d.SetFillColor(p.Agent.OnFill).FillText(numStr, badgeCX-numHalfW, badgeCY+3.5, fontNum) } curX := px + 26 if ov.Holding { @@ -533,15 +558,15 @@ func drawChangeSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bas fontBody := core.Font{Size: 11, Weight: 500} var pillW float32 secondary := ov.SecondaryLabel + nameW := overlayTextWidth(label, 6.4) if base == OverlayKindRemoved { if secondary == "" { secondary = "removed" } - nameW := float32(len([]rune(label))) * 6.4 - secW := float32(len([]rune(secondary))) * 6.0 + secW := overlayTextWidth(secondary, 6.0) pillW = 8 + nameW + 6 + secW + 8 } else { - pillW = 8 + float32(len([]rune(label)))*6.4 + 8 + pillW = 8 + nameW + 8 } px, py := clampOverlayPillPos(bx+bw*0.5, by, by+bh, pad, pillW, pillH, ov.PillStackOffset, ov.CanvasSize) @@ -562,7 +587,6 @@ func drawChangeSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bas fg := ui.Alpha(role.Fg, alpha) if base == OverlayKindRemoved { nameX := px + 8 - nameW := float32(len([]rune(label))) * 6.4 d.SetFillColor(fg).FillText(label, nameX, py+14.5, fontMono) // Explicit strikethrough line across the removed object's name (never color alone). strikeY := py + pillH*0.5 @@ -596,7 +620,7 @@ func drawProblemSpecOverlay(d *core.Drawing, p SpecPalette, ov ObjectOverlay, bx const pillH float32 = 22 const iconW float32 = 12 font := core.Font{Size: 11, Weight: 600} - pillW := 8 + iconW + 6 + float32(len([]rune(ov.Label)))*6.3 + 8 + pillW := 8 + iconW + 6 + overlayTextWidth(ov.Label, 6.3) + 8 px, py := clampOverlayPillPos(bx+bw*0.5, by, by+bh, pad, pillW, pillH, ov.PillStackOffset, ov.CanvasSize) // Solid filled Problem pill with alert triangle icon + message in Problem.OnFill. @@ -699,6 +723,22 @@ func (e *Editor) ClearReduceMotion() { e.notify() } +func cloneSceneOverlayEntry(ent SceneOverlayEntry) SceneOverlayEntry { + if ent.GhostBounds != nil { + r := *ent.GhostBounds + ent.GhostBounds = &r + } + if ent.GhostPos3D != nil { + v := *ent.GhostPos3D + ent.GhostPos3D = &v + } + if ent.GhostSize3D != nil { + v := *ent.GhostSize3D + ent.GhostSize3D = &v + } + return ent +} + // SetSceneOverlays replaces the active live scene overlays (agent working, added, changed, removed, // focused review change) drawn over the open scene in both 2D and 3D viewports. func (e *Editor) SetSceneOverlays(entries []SceneOverlayEntry) { @@ -719,19 +759,7 @@ func (e *Editor) SetSceneOverlays(entries []SceneOverlayEntry) { if ent.StartedAt.IsZero() { ent.StartedAt = now } - if ent.GhostBounds != nil { - r := *ent.GhostBounds - ent.GhostBounds = &r - } - if ent.GhostPos3D != nil { - v := *ent.GhostPos3D - ent.GhostPos3D = &v - } - if ent.GhostSize3D != nil { - v := *ent.GhostSize3D - ent.GhostSize3D = &v - } - cp[i] = ent + cp[i] = cloneSceneOverlayEntry(ent) } e.sceneOverlays = cp e.notify() @@ -745,18 +773,7 @@ func (e *Editor) AddSceneOverlay(entry SceneOverlayEntry) { if entry.StartedAt.IsZero() { entry.StartedAt = e.overlayNow() } - if entry.GhostBounds != nil { - r := *entry.GhostBounds - entry.GhostBounds = &r - } - if entry.GhostPos3D != nil { - v := *entry.GhostPos3D - entry.GhostPos3D = &v - } - if entry.GhostSize3D != nil { - v := *entry.GhostSize3D - entry.GhostSize3D = &v - } + entry = cloneSceneOverlayEntry(entry) if entry.ID != "" { for i := range e.sceneOverlays { if e.sceneOverlays[i].ID == entry.ID { @@ -800,20 +817,22 @@ func (e *Editor) ClearSceneOverlays() { e.SetSceneOverlays(nil) } -// SceneOverlays returns a copy of the active live scene overlay entries. +// SceneOverlays returns a deep copy of the active live scene overlay entries. func (e *Editor) SceneOverlays() []SceneOverlayEntry { if e == nil || len(e.sceneOverlays) == 0 { return nil } out := make([]SceneOverlayEntry, len(e.sceneOverlays)) - copy(out, e.sceneOverlays) + for i, ent := range e.sceneOverlays { + out[i] = cloneSceneOverlayEntry(ent) + } return out } // hasAnimatedOverlays reports whether any currently visible scene or task overlay needs // active animation ticks (pulsing agent outline or fading change overlay < 240 ms). func (e *Editor) hasAnimatedOverlays() bool { - if e == nil || e.playing || e.ReduceMotion() { + if e == nil || e.playing || e.HistoryPreviewActive() || e.ReduceMotion() || !e.ShowAgentChanges() { return false } if e.OverlayKindVisible(OverlayKindAgent) { @@ -851,13 +870,30 @@ func (e *Editor) hasAnimatedOverlays() bool { func (e *Editor) effectiveOverlayLegendSet() map[OverlayKind]bool { set := make(map[OverlayKind]bool, 6) - if e != nil && e.settings.OverlayLegend != nil { - for _, id := range *e.settings.OverlayLegend { + if e != nil { + e.settingsMu.RLock() + legend := e.settings.OverlayLegend + hidden := e.settings.HiddenOverlayKinds + if legend != nil { + for _, id := range *legend { + k := OverlayKind(id) + if k.IsLegendKind() { + set[k] = true + } + } + e.settingsMu.RUnlock() + return set + } + for _, k := range OverlayLegendKinds() { + set[k] = true + } + for _, id := range hidden { k := OverlayKind(id) if k.IsLegendKind() { - set[k] = true + delete(set, k) } } + e.settingsMu.RUnlock() return set } for _, k := range OverlayLegendKinds() { @@ -944,26 +980,34 @@ func (e *Editor) SetOverlayLegendKinds(kinds []OverlayKind) error { func (e *Editor) commitOverlayLegendSet(set map[OverlayKind]bool) error { list := make([]string, 0, len(set)) - for k, on := range set { - if on && k.IsLegendKind() { + var hidden []string + for _, k := range OverlayLegendKinds() { + if set[k] { list = append(list, string(k)) + } else { + hidden = append(hidden, string(k)) } } slices.Sort(list) - cur := e.Settings() - cur.OverlayLegend = &list - e.settings = cur + slices.Sort(hidden) + e.settingsMu.Lock() + e.normalizeSettingsLocked() + e.settings.OverlayLegend = &list + if len(hidden) > 0 { + e.settings.HiddenOverlayKinds = hidden + } else { + e.settings.HiddenOverlayKinds = nil + } + e.settingsMu.Unlock() // Keep legacy problemOverlayHidden in sync with the Problem legend toggle. e.problems.mu.Lock() e.problems.problemOverlayHidden = !set[OverlayKindProblem] e.problems.mu.Unlock() - if e.SettingsPath != "" { - if err := SaveEditorSettings(e.SettingsPath, &cur); err != nil { - e.notify() - return err - } + if err := e.persistEditorSettings(); err != nil { + e.notify() + return err } e.notify() return nil @@ -1015,9 +1059,10 @@ func (e *Editor) objectDisplayName(bo *sceneformat.BuiltObject, fallbackID strin } // drawSceneOverlays2D draws all live SceneOverlayEntry items (Agent working, Added, Changed, -// Removed, Focused change) in the 2D viewport through DrawObjectOverlay, honoring legend toggles. +// Removed, Focused change) in the 2D viewport through DrawObjectOverlay, honoring legend toggles +// and Editor.ShowAgentChanges(). func (e *Editor) drawSceneOverlays2D(d *core.Drawing, scene *sceneformat.BuiltScene) { - if e == nil || d == nil || scene == nil || e.playing || len(e.sceneOverlays) == 0 { + if e == nil || d == nil || scene == nil || e.playing || !e.ShowAgentChanges() || len(e.sceneOverlays) == 0 { return } spec := e.SpecPalette(nil) @@ -1061,9 +1106,10 @@ func (e *Editor) drawSceneOverlays2D(d *core.Drawing, scene *sceneformat.BuiltSc continue } - pairedSel := ent.Kind == OverlayKindAgent && e.IsSelected(ent.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + selOnObj := e.IsSelected(ent.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + pairedSel := ent.Kind == OverlayKindAgent && selOnObj stackOff := float32(0) - if pairedSel { + if selOnObj && ent.Kind != OverlayKindSelection { stackOff = 24 } DrawObjectOverlay(d, spec, ObjectOverlay{ @@ -1082,12 +1128,8 @@ func (e *Editor) drawSceneOverlays2D(d *core.Drawing, scene *sceneformat.BuiltSc } } -// projectObject3DBounds projects a 3D object's 8 corners onto canvas-space 2D bounds. -func (e *Editor) projectObject3DBounds(o *sceneformat.ObjectDoc, parent aff3, vc view3DCam, w, h float32) (core.Bounds, bool) { - if o == nil { - return core.Bounds{}, false - } - corners := e.objectCorners3DUnder(o, parent) +// projectCorners3DBounds projects 8 world-space 3D corners onto canvas-space 2D bounds. +func projectCorners3DBounds(corners [8][3]float32, vc view3DCam, w, h float32) (core.Bounds, bool) { var minX, minY, maxX, maxY float32 anyVis := false for _, c := range corners { @@ -1113,11 +1155,33 @@ func (e *Editor) projectObject3DBounds(o *sceneformat.ObjectDoc, parent aff3, vc }, true } +// projectBox3DBounds projects an axis-aligned 3D box centered at pos with extents ext onto canvas bounds. +func projectBox3DBounds(pos, ext [3]float32, vc view3DCam, w, h float32) (core.Bounds, bool) { + hx, hy, hz := ext[0]*0.5, ext[1]*0.5, ext[2]*0.5 + var corners [8][3]float32 + for i, s := range boxSigns3D { + corners[i] = [3]float32{ + pos[0] + float32(s[0])*hx, + pos[1] + float32(s[1])*hy, + pos[2] + float32(s[2])*hz, + } + } + return projectCorners3DBounds(corners, vc, w, h) +} + +// projectObject3DBounds projects a 3D object's 8 corners onto canvas-space 2D bounds. +func (e *Editor) projectObject3DBounds(o *sceneformat.ObjectDoc, parent aff3, vc view3DCam, w, h float32) (core.Bounds, bool) { + if o == nil { + return core.Bounds{}, false + } + return projectCorners3DBounds(e.objectCorners3DUnder(o, parent), vc, w, h) +} + // drawSceneOverlays3D draws Spec Agent working, Added, Changed, Removed, Focused change, and Problem // overlays on projected 3D object bounds in the 3D viewport through DrawObjectOverlay, sharing the // exact same legend toggles as the 2D viewport. func (e *Editor) drawSceneOverlays3D(d *core.Drawing, w, h float32) { - if e == nil || d == nil || e.playing { + if e == nil || d == nil || e.playing || e.HistoryPreviewActive() { return } spec := e.SpecPalette(nil) @@ -1155,7 +1219,8 @@ func (e *Editor) drawSceneOverlays3D(d *core.Drawing, w, h float32) { } // 1. Live agent task overlays in 3D. - if e.OverlayKindVisible(OverlayKindAgent) { + showAgentChanges := e.ShowAgentChanges() + if showAgentChanges && e.OverlayKindVisible(OverlayKindAgent) { for _, ov := range e.SceneTaskOverlays() { ref, ok := byID[ov.ObjectID] if !ok { @@ -1187,58 +1252,61 @@ func (e *Editor) drawSceneOverlays3D(d *core.Drawing, w, h float32) { } // 2. Live scene overlay entries (Agent working, Added, Changed, Removed, Focused change). - for _, ent := range e.sceneOverlays { - checkKind := ent.Kind - if ent.Kind == OverlayKindFocusedChange { - base := ent.ChangeKind - if !base.IsChangeKind() { - base = OverlayKindAdded + if showAgentChanges { + for _, ent := range e.sceneOverlays { + checkKind := ent.Kind + if ent.Kind == OverlayKindFocusedChange { + base := ent.ChangeKind + if !base.IsChangeKind() { + base = OverlayKindAdded + } + checkKind = base } - checkKind = base - } - if !e.OverlayKindVisible(checkKind) { - continue - } - var bounds core.Bounds - var vis bool - if ref, ok := byID[ent.ObjectID]; ok { - bounds, vis = e.projectObject3DBounds(ref.obj, ref.parent, vc, w, h) - } else if ent.GhostPos3D != nil && (ent.Kind == OverlayKindRemoved || (ent.Kind == OverlayKindFocusedChange && ent.ChangeKind == OverlayKindRemoved)) { - pos := *ent.GhostPos3D - ext := [3]float32{16, 16, 16} - if ent.GhostSize3D != nil { - ext = *ent.GhostSize3D + if !e.OverlayKindVisible(checkKind) { + continue } - ghost := &sceneformat.ObjectDoc{X: pos[0], Y: pos[1], PosZ: pos[2], Depth: ext[2]} - bounds, vis = e.projectObject3DBounds(ghost, ident3, vc, w, h) - } - if !vis { - continue - } - pairedSel := ent.Kind == OverlayKindAgent && e.IsSelected(ent.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) - stackOff := float32(0) - if pairedSel { - stackOff = 24 + var bounds core.Bounds + var vis bool + if ref, ok := byID[ent.ObjectID]; ok { + bounds, vis = e.projectObject3DBounds(ref.obj, ref.parent, vc, w, h) + } else if ent.GhostPos3D != nil && (ent.Kind == OverlayKindRemoved || (ent.Kind == OverlayKindFocusedChange && ent.ChangeKind == OverlayKindRemoved)) { + pos := *ent.GhostPos3D + ext := [3]float32{16, 16, 16} + if ent.GhostSize3D != nil { + ext = *ent.GhostSize3D + } + bounds, vis = projectBox3DBounds(pos, ext, vc, w, h) + } + if !vis { + continue + } + selOnObj := e.IsSelected(ent.ObjectID) && e.OverlayKindVisible(OverlayKindSelection) + pairedSel := ent.Kind == OverlayKindAgent && selOnObj + stackOff := float32(0) + if selOnObj && ent.Kind != OverlayKindSelection { + stackOff = 24 + } + DrawObjectOverlay(d, spec, ObjectOverlay{ + Kind: ent.Kind, + ChangeKind: ent.ChangeKind, + Label: ent.Label, + SecondaryLabel: ent.SecondaryLabel, + Bounds: bounds, + CanvasSize: canvas, + PairedWithSelection: pairedSel, + PillStackOffset: stackOff, + Elapsed: now.Sub(ent.StartedAt), + HasElapsed: true, + ReduceMotion: rm, + }) } - DrawObjectOverlay(d, spec, ObjectOverlay{ - Kind: ent.Kind, - ChangeKind: ent.ChangeKind, - Label: ent.Label, - SecondaryLabel: ent.SecondaryLabel, - Bounds: bounds, - CanvasSize: canvas, - PairedWithSelection: pairedSel, - PillStackOffset: stackOff, - Elapsed: now.Sub(ent.StartedAt), - HasElapsed: true, - ReduceMotion: rm, - }) } - // 3. Live Problem overlays in 3D. + // 3. Live Problem overlays in 3D (sorted deterministically by object ID). if e.OverlayKindVisible(OverlayKindProblem) { objProbs := e.openSceneObjectProblems() - for objID, probs := range objProbs { + for _, objID := range slices.Sorted(maps.Keys(objProbs)) { + probs := objProbs[objID] if len(probs) == 0 { continue } @@ -1254,11 +1322,16 @@ func (e *Editor) drawSceneOverlays3D(d *core.Drawing, w, h float32) { if len(probs) > 1 { label = fmt.Sprintf("%s (+%d)", label, len(probs)-1) } + stackOff := float32(0) + if e.IsSelected(objID) && e.OverlayKindVisible(OverlayKindSelection) { + stackOff = 24 + } DrawObjectOverlay(d, spec, ObjectOverlay{ - Kind: OverlayKindProblem, - Label: label, - Bounds: bounds, - CanvasSize: canvas, + Kind: OverlayKindProblem, + Label: label, + Bounds: bounds, + CanvasSize: canvas, + PillStackOffset: stackOff, }) } } diff --git a/packages/game/editor/viewport_overlay_test.go b/packages/game/editor/viewport_overlay_test.go index 97a972aa9..3c5af80d6 100644 --- a/packages/game/editor/viewport_overlay_test.go +++ b/packages/game/editor/viewport_overlay_test.go @@ -823,3 +823,212 @@ func TestViewportOverlaysSpecMacOSScreenshot(t *testing.T) { app.Settle() app.Screenshot("viewport-overlays-spec-light") } + +// Regression test: Play mode and History preview hide overlays and legend in both 2D and 3D and restore +// them cleanly; SceneOverlays are scoped per scene tab, deep-copied, and cleared on OpenDemo; +// toggling a legend switch does not remount or steal keyboard focus. +func TestViewportOverlayLifecyclePlayHistoryAndFocus(t *testing.T) { + ed, _ := openTestProject(t) + ed.SetReduceMotion(true) + + var objID string + for _, layer := range ed.Doc.Layers { + if len(layer.Objects) > 0 { + objID = layer.Objects[0].ID + break + } + } + if objID == "" { + var err error + objID, err = ed.PlaceObject(ed.ActiveLayer, sceneformat.ObjectDoc{ID: "knight", Name: "Knight", X: 160, Y: 180}) + if err != nil { + t.Fatal(err) + } + } + ed.SelectObject(objID) + + ghost := core.Bounds{Origin: core.Point{X: 200, Y: 160}, Size: core.Size{Width: 20, Height: 20}} + ghostPos3D := [3]float32{0, 0, 0} + ghostSize3D := [3]float32{32, 48, 24} + ed.SetSceneOverlays([]editor.SceneOverlayEntry{ + {ID: "ad", ObjectID: objID, Kind: editor.OverlayKindAdded, Label: "new_slime"}, + {ID: "rm", ObjectID: "gone", Kind: editor.OverlayKindRemoved, Label: "coin_04", GhostBounds: &ghost, GhostPos3D: &ghostPos3D, GhostSize3D: &ghostSize3D}, + }) + + // 1. SceneOverlays() returns a deep copy that does not alias internal pointers. + snap := ed.SceneOverlays() + if len(snap) != 2 || snap[1].GhostBounds == nil || snap[1].GhostSize3D == nil { + t.Fatalf("SceneOverlays() = %+v, want 2 entries with ghost pointers", snap) + } + snap[1].GhostBounds.Origin.X = 9999 + snap[1].GhostSize3D[0] = 9999 + snap2 := ed.SceneOverlays() + if snap2[1].GhostBounds.Origin.X == 9999 || snap2[1].GhostSize3D[0] == 9999 { + t.Fatal("mutating SceneOverlays() result mutated internal editor state") + } + + // 2. Play mode hides overlays and legend in both 2D and 3D, and Stop() restores them. + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 720), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + ReduceMotion: true, + })) + app.Settle() + + if !app.Exists("id:viewport-overlay-legend") { + t.Fatal("expected legend visible before Play") + } + // Focus legend-added and toggle it via Space: switch toggles cleanly and keeps keyboard focus (no remount). + app.Focus("id:legend-added") + app.Settle() + if !app.Find("id:legend-added").Focused { + t.Fatal("legend-added did not gain keyboard focus") + } + app.Key("space") + app.Settle() + if app.Find("id:legend-added").Props.Checked { + t.Fatal("Space key did not toggle focused legend-added switch off") + } + if !app.Find("id:legend-added").Focused { + t.Fatal("toggling legend-added via Space remounted the switch and lost keyboard focus") + } + // Toggle it back ON via Space so overlays are active for Play & History checks. + app.Key("space") + app.Settle() + if !app.Find("id:legend-added").Props.Checked || !app.Find("id:legend-added").Focused { + t.Fatal("second Space key press did not restore legend-added while keeping focus") + } + + app.Post(func() { _ = ed.Play() }) + app.Settle() + if app.Exists("id:viewport-overlay-legend") { + t.Fatal("legend stayed visible during Play mode") + } + var play2D core.Drawing + ed.DrawViewport(&play2D, core.Size{Width: 640, Height: 360}) + if hasOverlayFillText(play2D.Ops, "+ new_slime") { + t.Fatal("2D overlays drew during Play mode") + } + ed.SetViewMode(editor.ViewMode3D) + var play3D core.Drawing + ed.DrawViewport(&play3D, core.Size{Width: 640, Height: 360}) + if hasOverlayFillText(play3D.Ops, "+ new_slime") || hasOverlayFillText(play3D.Ops, objID) { + t.Fatal("3D overlays drew during Play mode") + } + + app.Post(func() { + _ = ed.Stop() + ed.SetViewMode(editor.ViewMode2D) + }) + app.Settle() + if !app.Exists("id:viewport-overlay-legend") { + t.Fatal("legend did not restore after Stop()") + } + + // 3. History preview hides overlays & legend in both 2D and 3D and restores them on exit. + if _, err := ed.PlaceObject(ed.ActiveLayer, sceneformat.ObjectDoc{ID: "hist_prop", Name: "HistProp", X: 80, Y: 80}); err != nil { + t.Fatal(err) + } + ed.SetHistoryPanelOpen(true) + entries := ed.HistoryEntries() + if len(entries) == 0 { + t.Fatal("expected at least one history entry") + } + app.Post(func() { _ = ed.PreviewHistoryEntry(entries[0].ID) }) + app.Settle() + if !ed.HistoryPreviewActive() { + t.Fatal("expected HistoryPreviewActive()") + } + if app.Exists("id:viewport-overlay-legend") { + t.Fatal("legend stayed visible during History preview") + } + var hist2D core.Drawing + ed.DrawViewport(&hist2D, core.Size{Width: 640, Height: 360}) + if hasOverlayFillText(hist2D.Ops, "+ new_slime") { + t.Fatal("2D overlays drew during History preview") + } + ed.SetViewMode(editor.ViewMode3D) + var hist3D core.Drawing + ed.DrawViewport(&hist3D, core.Size{Width: 640, Height: 360}) + if hasOverlayFillText(hist3D.Ops, "+ new_slime") || hasOverlayFillText(hist3D.Ops, "coin_04") { + t.Fatal("3D overlays drew during History preview") + } + app.Post(func() { + ed.ExitHistoryPreview() + ed.SetViewMode(editor.ViewMode2D) + }) + app.Settle() + if !app.Exists("id:viewport-overlay-legend") { + t.Fatal("legend did not restore after ExitHistoryPreview()") + } + + // 4. Tab/scene lifecycle: new scene starts with clean SceneOverlays; switching back preserves tab 0; + // OpenDemo clears all scene overlays. + if _, err := ed.NewScene("scenes/second.scene.yaml"); err != nil { + t.Fatal(err) + } + if got := ed.SceneOverlays(); len(got) != 0 { + t.Fatalf("new scene tab inherited stale SceneOverlays: %+v", got) + } + if err := ed.SelectTab(0); err != nil { + t.Fatal(err) + } + if got := ed.SceneOverlays(); len(got) != 2 { + t.Fatalf("switching back to tab 0 lost SceneOverlays: got %d, want 2", len(got)) + } + if err := ed.OpenDemo(); err != nil { + t.Fatal(err) + } + if got := ed.SceneOverlays(); len(got) != 0 { + t.Fatalf("OpenDemo() left stale SceneOverlays: %+v", got) + } +} + +// Regression test: adding a second change overlay after a first 240 ms fade completes re-arms the +// viewport fade animation timer so the new overlay smoothly animates to full opacity. +func TestViewportOverlaySequentialFadeRearmsTimer(t *testing.T) { + ed := newOverlaysTestEditor(t) + _ = ed.SetAppearance(editor.AppearanceDark) + ed.ClearReduceMotion() + now := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC) + ed.SetOverlayClock(func() time.Time { return now }) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return editor.EditorView(cx, ed) + }, nsgotest.Size(1280, 720), nsgotest.Environment(core.Environment{ + OS: core.OSMacOS, + Idiom: core.IdiomDesktop, + Dark: true, + ReduceMotion: false, + })) + app.Settle() + + // 1. First Added overlay starts fading and finishes after 240 ms. + app.Post(func() { + ed.AddSceneOverlay(editor.SceneOverlayEntry{ID: "first", ObjectID: "knight", Kind: editor.OverlayKindAdded, Label: "knight", StartedAt: now}) + }) + app.Settle() + now = now.Add(300 * time.Millisecond) + app.Advance(40 * time.Millisecond) + app.Settle() + + // 2. Second Added overlay starts at t=300ms (initially alpha 0); timer must re-arm and redraw it at 100%. + secondStart := now + app.Post(func() { + ed.AddSceneOverlay(editor.SceneOverlayEntry{ID: "second", ObjectID: "slime_01", Kind: editor.OverlayKindAdded, Label: "slime_01", StartedAt: secondStart}) + }) + app.Settle() + if hasOverlayFillText(app.Find("id:editor-viewport").Ops, "+ slime_01") { + t.Fatal("expected second Added overlay to start invisible at t=0") + } + + now = secondStart.Add(300 * time.Millisecond) + app.Advance(50 * time.Millisecond) + app.Settle() + if !hasOverlayFillText(app.Find("id:editor-viewport").Ops, "+ slime_01") { + t.Fatal("sequential Added overlay stayed invisible: fade animation timer did not re-arm") + } +} diff --git a/packages/game/tooling/assetcheck/connections_test.go b/packages/game/tooling/assetcheck/connections_test.go index a4048555e..5a1b7e08d 100644 --- a/packages/game/tooling/assetcheck/connections_test.go +++ b/packages/game/tooling/assetcheck/connections_test.go @@ -350,3 +350,59 @@ layers: t.Fatalf("%d problems, want 3:\n%s", len(r.Problems), got) } } + +func TestStandaloneConnectionErrorAttributesLiveEndpoint(t *testing.T) { + fsys := fstest.MapFS{ + "scenes/solo.scene.yaml": &fstest.MapFile{Data: []byte(`version: 2 +layers: + - name: actors + objects: + - id: lever + components: + button: {} + - id: door + components: + door: {} +connections: + - from: lever + event: pressed + to: missing_door + handler: open + - from: missing_lever + event: pressed + to: door + handler: open +`)}, + } + r, err := assetcheck.CheckWith(fsys, assetcheck.Options{Components: connectionsRegistry(t)}) + if err != nil { + t.Fatal(err) + } + if len(r.Problems) != 1 { + t.Fatalf("expected 1 standalone connection problem (first validation error), got %+v", r.Problems) + } + if r.Problems[0].Object != "lever" { + t.Fatalf("standalone missing-to connection Object = %q, want live endpoint %q", r.Problems[0].Object, "lever") + } + + fsys["scenes/solo.scene.yaml"] = &fstest.MapFile{Data: []byte(`version: 2 +layers: + - name: actors + objects: + - id: door + components: + door: {} +connections: + - from: missing_lever + event: pressed + to: door + handler: open +`)} + r, err = assetcheck.CheckWith(fsys, assetcheck.Options{Components: connectionsRegistry(t)}) + if err != nil { + t.Fatal(err) + } + if len(r.Problems) != 1 || r.Problems[0].Object != "door" { + t.Fatalf("standalone missing-from connection = %+v, want Object=%q", r.Problems, "door") + } +} diff --git a/packages/game/tooling/assetcheck/scene.go b/packages/game/tooling/assetcheck/scene.go index 5512577a3..f0be35d56 100644 --- a/packages/game/tooling/assetcheck/scene.go +++ b/packages/game/tooling/assetcheck/scene.go @@ -92,16 +92,28 @@ func connectionErrorObject(ce *sceneformat.ConnectionError) string { return "" } switch ce.Field { - case "to", "handler": + case "handler", "args": if ce.To != "" { return ce.To } return ce.From - case "from", "event": + case "event": if ce.From != "" { return ce.From } return ce.To + case "to": + // "to" errors report a missing target object; attach the Problem to the live source endpoint. + if ce.From != "" { + return ce.From + } + return ce.To + case "from": + // "from" errors report a missing source object; attach the Problem to the live target endpoint. + if ce.To != "" { + return ce.To + } + return ce.From default: if ce.Arg != "" && ce.To != "" { return ce.To From 76d7b85824de6c9406af3b6fba63dfb18477f551 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Fri, 27 Nov 2026 03:18:29 +0900 Subject: [PATCH 4/4] fix(editor): hide viewport overlay legend while 2D Sketch toolbar is active --- packages/game/editor/spec_feedback_ui.go | 3 +++ packages/game/editor/viewport_overlay_test.go | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/packages/game/editor/spec_feedback_ui.go b/packages/game/editor/spec_feedback_ui.go index 55b81414f..0a6ae3faf 100644 --- a/packages/game/editor/spec_feedback_ui.go +++ b/packages/game/editor/spec_feedback_ui.go @@ -783,6 +783,9 @@ func viewportOverlayLegendView(cx *core.Scope, ed *Editor, rev *core.Signal[uint if ed == nil || ed.Playing() || ed.HistoryPreviewActive() || !ed.OverlayLegendOpen() { return legendStateKey{} } + if ed.ViewMode == ViewMode2D && ed.SketchActive() && !ed.sketchBlockedByScreen() { + return legendStateKey{} + } return legendStateKey{ visible: true, dark: ed.SpecPalette(cx).Dark, diff --git a/packages/game/editor/viewport_overlay_test.go b/packages/game/editor/viewport_overlay_test.go index 3c5af80d6..b047a53e7 100644 --- a/packages/game/editor/viewport_overlay_test.go +++ b/packages/game/editor/viewport_overlay_test.go @@ -965,6 +965,22 @@ func TestViewportOverlayLifecyclePlayHistoryAndFocus(t *testing.T) { t.Fatal("legend did not restore after ExitHistoryPreview()") } + // 3b. Active 2D Sketch mode hides the top-left legend so it never collides with the floating Sketch toolbar, + // and finishing Sketch mode restores the legend immediately. + app.Post(func() { ed.SetSketchActive(true) }) + app.Settle() + if !app.Exists("id:viewport-sketch-toolbar") { + t.Fatal("expected viewport-sketch-toolbar while Sketch mode is active") + } + if app.Exists("id:viewport-overlay-legend") { + t.Fatal("viewport-overlay-legend overlapped active viewport-sketch-toolbar") + } + app.Post(func() { ed.FinishSketch() }) + app.Settle() + if !app.Exists("id:viewport-overlay-legend") { + t.Fatal("viewport-overlay-legend did not restore after FinishSketch()") + } + // 4. Tab/scene lifecycle: new scene starts with clean SceneOverlays; switching back preserves tab 0; // OpenDemo clears all scene overlays. if _, err := ed.NewScene("scenes/second.scene.yaml"); err != nil {