diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-assets-and-hot-reload.md b/.agents/notes/implemented/feature/2026-11-24-mcp-assets-and-hot-reload.md new file mode 100644 index 00000000..3ab762db --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-assets-and-hot-reload.md @@ -0,0 +1,42 @@ +# Agent Note: MCP assets inspection and hot reload + +Status: implemented + +## Problem + +Agents debugging or iterating on a running NSGo game over `nsgo mcp` (see [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md)) could inspect scenes, layers, and entities, but had no way to see which asset groups were loaded, how much memory they held, or to reload edited assets such as sprite atlases, shaders, materials, and YAML resources on demand without restarting the game. + +## Decision + +Extend `packages/game/mcp` with a dedicated `assets.go` tool group (`game_assets_list`, `game_asset_reload`, `game_assets_reload_group`) and minimal additive `Config` hookup in `mcp.go`, backed by read-only stats and synchronous in-place reload helpers in `packages/game/assets`, `packages/game/tooling/hotreload`, and `packages/game/resource`. + +## Architecture and tool contract + +- **Minimal `mcp.go` surface for parallel work**: All asset tool constants, schemas, result structs, handlers, and `RegisterAsset` / `RegisterAtlas` helpers live in `packages/game/mcp/assets.go`. `mcp.go` only adds optional `Config` fields (`Assets`, `AssetsFunc`, `Resources`, `Shaders`, `Materials`, `ReloadAsset`), one unexported `customAssets` registry pointer on `Bridge`, and `b.assetTools()` in `Bridge.Tools()`. +- **Deterministic group listing and memory accounting**: `packages/game/assets/stats.go` adds side-effect-free `Manager.GroupNames`, `Manager.LookupGroup`, `Manager.GroupStats`, and `Group.Stats` using untracked signal reads so MCP calls never subscribe to reactive signals or lazily create phantom groups. `Group` tracks raw file byte sizes alongside loaded resources (`rawBytes`) and combines them with pixel buffers (`ImageSource.Pixels`), inline byte payloads (`ImageSource.Data`), declared image/atlas dimensions, and decoded PCM duration estimates for sounds. `game_assets_list` merges `assets.Manager` groups, loaded `resource.Library` paths, `ShaderReloader` shaders, `MaterialReloader` materials, and custom registered assets, sorted deterministically by `(name, source)` and per-group `key`. +- **Off-goroutine fetch, engine-goroutine apply**: `automation.Call` executes tool handlers synchronously on the engine goroutine, and a handler cannot wait for work posted back to it. `Manager.ReloadAsset` and `Manager.ReloadGroup` therefore read updated bytes through each group's configured reader (`g.readAssetFunc()`), parse atlases and run custom loaders on a separate goroutine, as `Group.Load` does, wait for it (or for the call's context, after which unapplied custom values are released), and then update loaded assets in place on the engine goroutine (`*cur = *next` for `*sprite.Atlas`) before incrementing `Manager.Revision()` once. Existing `*sprite.Atlas` pointers held by running game code see updated frames immediately and reactive canvases redraw on `Revision()`. Sounds, images without a file and files at a density the screen does not show are reported as skipped: a sound decodes asynchronously on the platform, so its result could not be reported in the same call, and replacing an unshown density would drop the source's other scales, as `Manager.Reload` already avoids. +- **Structured reload diagnostics vs protocol errors**: Argument validation errors (unknown JSON fields via `DisallowUnknownFields()`, missing `key`/`group`, invalid `state`, conflicting `key` + `all`), unconfigured/disposed managers, and unknown asset/group lookups return Go errors to `automation.Call`. Parse, read, schema, or shader compilation errors on a matched asset preserve the previously working asset and return a structured JSON `AssetReloadResult` / `AssetsReloadGroupResult` with `reloaded: false` and the diagnostic message in `error`, keeping the live game running. +- **Unified reload across hot-reload subsystems**: Small additive `ReloadFile` / `ReloadShaderFile` / `ReloadMaterialFile` and path getters in `packages/game/resource` and `packages/game/tooling/hotreload` (building on [Shader and material hot reload](2026-11-24-shader-material-hot-reload.md)) allow `game_asset_reload` and `game_assets_reload_group` to reload atlases, images, bytes, custom assets, shaders, materials, and YAML resources uniformly from their configured file systems. + +## Alternatives considered + +### Re-using `Group.Release()` followed by `Group.Load()` for MCP reloads + +Releasing and asynchronously reloading a group would require no new per-spec reload code in `packages/game/assets`. It was rejected for two reasons: (1) `Group.Release()` + `Group.Load()` allocates new `*sprite.Atlas` pointers, so game systems holding an existing `*sprite.Atlas` pointer would never see the update; and (2) `Group.Load()` completes asynchronously via `core.Scope.Post`, which cannot be waited on synchronously inside an `automation.Call` handler on the engine goroutine without deadlocking. + +### Returning reload parse/compile failures as raw tool call errors + +Returning parse or shader compile errors as top-level Go errors from `game_asset_reload` would match argument errors. It was rejected because reloading an asset (or a whole group via `game_assets_reload_group` / `all: true`) can partially succeed and benefits from returning timing (`duration_ms`), preserved `bytes`, `group`, per-item status (`items`), and structured `error` details alongside `reloaded: false` so agents can diagnose broken edits cleanly. + +### Routing all reloads exclusively through `hotreload.Watcher` + +Delegating MCP reloads solely to `hotreload.Watcher` would avoid adding `ReloadAsset` / `ReloadShaderFile` / `ReloadMaterialFile`. It was rejected because `hotreload.Watcher` is a polling loop compiled out under `-tags release` and games using `assets.WithFS` or `nsgotest` often run without an active filesystem polling watcher; direct on-demand reload works deterministically in both `nsgo dev -automation` and `nsgo test`. + +## Consequences + +- **Benefits**: Coding agents can inspect loaded asset groups, states, asset keys, and memory usage and trigger deterministic in-place reloads of atlases, images, bytes, custom assets, shaders, materials, and YAML resources over `nsgo mcp`, immediately updating the running game while keeping broken edits non-fatal. +- **Costs**: `packages/game/assets` maintains `rawBytes` per loaded asset for memory accounting and an on-demand reload path alongside `Manager.Reload(uri, data)`. Memory figures for URI-only images and decoded sounds without inline pixel/byte buffers are estimates derived from declared dimensions, frame extents, or audio duration. + +## Verification + +Verified with `gofmt`, `go run ./cmd/gameschema -check`, `go tool nsgo check -target macos,windows,linux,android,web`, `go tool nsgo test ./mcp`, `go tool nsgo test ./assets`, `go tool nsgo test ./resource`, `go tool nsgo test ./tooling/hotreload`, `go tool nsgo test -run TestStabilityTable .`, `go run ./tools/changelog check`, and `bun run verify-notes`. diff --git a/changelog.d/mcp-assets-hotreload.md b/changelog.d/mcp-assets-hotreload.md new file mode 100644 index 00000000..cfb4ac27 --- /dev/null +++ b/changelog.d/mcp-assets-hotreload.md @@ -0,0 +1,5 @@ +### Added + +- `game/mcp`: added `game_assets_list`, `game_asset_reload`, and `game_assets_reload_group` tools plus `RegisterAsset`, `RegisterAtlas`, and `Config` asset/hot-reload hooks to inspect loaded asset groups/memory and hot-reload atlases, images, bytes, custom assets, shaders, materials, and YAML resources in place; sounds, images without a file and unshown densities are reported as skipped (#469). +- `game/assets`: added read-only `Manager.Disposed`, `Manager.GroupNames`, `Manager.LookupGroup`, `Manager.GroupStats`, `Group.Stats`, and on-demand in-place `Manager.ReloadAsset` and `Manager.ReloadGroup` helpers that read and parse off the engine goroutine, plus `EstimateAtlasBytes` (#469). +- `game/tooling/hotreload`, `game/resource`: added `ShaderReloader.ShaderPath`, `ShaderReloader.ReloadShaderFile`, `MaterialReloader.MaterialPath`, `MaterialReloader.ReloadMaterialFile`, and `Library.ReloadFile` helpers for on-demand hot reload (#469). diff --git a/docs/en/mcp.md b/docs/en/mcp.md index b7984291..581b9f40 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -1,6 +1,6 @@ # mcp -`game/mcp` exposes a running game's scenes, layers, entities, components, fixed-step loop controls, game-coordinate input injection, tunables and debug console to coding agents over MCP through NSGo's `github.com/nsgo-dev/nsgo/automation` package. +`game/mcp` exposes a running game's scenes, layers, entities, components, fixed-step loop controls, game-coordinate input injection, tunables, debug console, loaded asset groups and hot reload controls to coding agents over MCP through NSGo's `github.com/nsgo-dev/nsgo/automation` package. NSGo's built-in `nsgo mcp` server sees native views only; a game draws into one `Canvas` or GPU view. Attaching an `mcp.Bridge` to a `core.Scope` registers game-specific tools on the engine's reactive graph so `nsgo mcp` serves them alongside the built-in tools whenever the app runs under `go tool nsgo dev -automation` or `go tool nsgo test`. In ordinary and release builds, `automation.Register` is a no-op and adds no runtime protocol. @@ -30,6 +30,11 @@ bridge, err := mcp.Attach(cx, mcp.Config{ Console: g.console, Overlay: g.debugOverlay, RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) }, + Assets: g.assets, + Resources: g.resources, + Shaders: g.shaderReloader, + Materials: g.materialReloader, + ReloadAsset: g.reloadCustomAsset, }) if err != nil { return err @@ -122,6 +127,9 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r | `game_perf_readout` | `include_history` (optional, default `false`), `history_limit` (optional), `include_zones` (optional, default `false`), `zones_limit` (optional) | Live performance readout matching the debug overlay: `fps`, rolling average and latest `frame_ms`/`update_ms`/`draw_ms`, min/max/p50/p95/p99 frame times, draw stats (`draw_calls`, `sprites`, `batches`, `triangles`, `vertices`), per-frame heap allocations (`allocs_per_frame`, `alloc_bytes_per_frame`, `last_frame_allocs`, `last_frame_alloc_bytes`), `heap_bytes`, `gc_count`, GC pause/hitch metrics, optional `render3d` and `asset_memory` breakdowns, and optional chronological `history` and profiler `zones`. | | `game_perf_zones` | `limit` (optional) | Named timing zones from `debug.Profiler` sorted by recent frame cost (`name`, `last_ms`, `avg_ms`, `max_ms`, `calls`), plus `recording`, `recorded_frames` and `total`. | | `game_perf_reset` | `{}` | Resets accumulated `debug.Overlay` frame timings and pushed draw stats, `debug.Profiler` zone timings, and `debug.GCMonitor` history. A profiler trace recording started with `StartRecording` keeps running and keeps its events. | +| `game_assets_list` | `group` (optional), `state` (`loaded`/`loading`/`unloaded`/`failed`), `kind` (optional) | Deterministically sorted asset groups (`assets.Manager` groups, `resource.Library`, `hotreload.ShaderReloader`, `hotreload.MaterialReloader`, and custom registered assets) with load states, asset keys/kinds/URIs, frame counts, per-group estimated bytes, and `total_bytes`. | +| `game_asset_reload` | `key` (name, URI or relative path), `group` (optional), `all` (boolean, optional) | Reloads a matching asset in place (or all loaded assets when `all: true`), returning `{reloaded, key, group, kind, bytes, duration_ms, revision, items, error}`; each item carries `skipped` when it was left unchanged without an error. Parse and compile errors are returned in the structured result while keeping the previously loaded working asset intact. `all: true` needs an asset manager, reloader or registered asset; `Config.ReloadAsset` only reloads a single key. | +| `game_assets_reload_group` | `group` (required) | Reloads every loaded asset in the named group in place, reporting per-item results, `count` reloaded, `failed`, `skipped`, memory bytes, duration, and any item errors without crashing the running game. | All tools reject unknown argument fields. @@ -200,6 +208,16 @@ Pass your [`debug.Overlay`](debug.md) via `Config.Overlay` to expose the exact s - `Config.RenderStatsFunc` attaches detailed 3D culling, batching, state-switch and GPU memory metrics from [`render3d.RenderStats`](render3d.md) under `render3d`, and populates top-level `draw_calls`, `batches`, `triangles` and `vertices` automatically when no 2D draw-stats provider is set. `mcp.PerfRender3DStats` has the same fields as `render3d.RenderStats`, so `mcp.PerfRender3DStats(stats)` converts one; `game/mcp` does not import `game/render3d`, so a 2D game that attaches the bridge does not link the 3D renderer. - `game_perf_readout` always includes a `sources` object indicating which telemetry providers are active (`overlay`, `profiler`, `gc`, `memory`, `draw_stats`, `render3d`). +## Assets and hot reload + +Wire `Config.Assets` (or `Config.AssetsFunc` / `bridge.SetAssets`), `Config.Resources`, `Config.Shaders`, `Config.Materials`, and/or `Config.ReloadAsset` to let agents inspect memory usage and trigger live reloads without restarting the game: + +- **In-place atlas updates**: Reloading an atlas in `assets.Manager` (by asset name such as `"hero"`, full URI `"asset:sprites/hero.json"`, relative path `"sprites/hero.json"`, or image path `"sprites/hero.png"`) updates the existing `*sprite.Atlas` pointer in place and increments `assets.Manager.Revision()`, so sprites holding the atlas pointer and canvases reading `Revision()` update immediately. +- **Standalone assets and atlases**: Games that hold a `*sprite.Atlas` or custom resource outside `assets.Manager` can register it with `bridge.RegisterAtlas(...)` or `bridge.RegisterAsset(mcp.CustomAsset{...})`. +- **Safe failure handling**: Syntax, schema, or shader compilation errors leave the previous working atlas, shader, material, or resource active and return `reloaded: false` with the diagnostic message in `error`. +- **Skipped assets**: Sounds are not replaced in place, images with no file behind them (such as generated textures) have nothing to reload, and a file at a density the screen does not show (the 1x file on a 2x screen) would change nothing on screen. These items carry `skipped` with the reason (`assets.SkippedSound`, `assets.SkippedNoFile`, `assets.SkippedDensity`) and count neither as reloaded nor as failed. A group reload also skips an image whose file the group's reader cannot find; reloading that image by key reports the read error. +- **Off the engine goroutine**: `Manager.ReloadAsset` and `Manager.ReloadGroup` read files, parse atlases and run custom loaders on another goroutine, as `Group.Load` does, and apply the results on the engine goroutine once they finish. The tool call waits for them, so a custom reader or loader must not wait on the engine goroutine; when the call's context ends first, nothing is replaced and the tool returns the context's error. + ## Stable entity references Every live entity receives a generational reference formatted as `"entity::"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`: diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 2194abc0..7f2143af 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -1,6 +1,6 @@ # mcp -`game/mcp` 通过 NSGo 的 `github.com/nsgo-dev/nsgo/automation` 包,把运行中游戏的场景、图层、实体、组件、固定步长主循环控制、游戏坐标输入注入、可调参数与调试控制台暴露给 MCP 智能体。 +`game/mcp` 通过 NSGo 的 `github.com/nsgo-dev/nsgo/automation` 包,把运行中游戏的场景、图层、实体、组件、固定步长主循环控制、游戏坐标输入注入、可调参数、调试控制台、已加载资源组以及热重载能力暴露给 MCP 智能体。 NSGo 内置的 `nsgo mcp` 服务器只能看到原生视图,而游戏通常绘制在单个 `Canvas` 或 GPU 视图中。把 `mcp.Bridge` 挂载到 `core.Scope` 上后,它会通过 `automation.Register` 在引擎响应式图上注册游戏专用工具;当应用在 `go tool nsgo dev -automation` 或 `go tool nsgo test` 下运行时,`nsgo mcp` 会自动将这些工具与内置工具一并提供。在普通构建与发布构建中,`automation.Register` 为空操作,不会引入运行时协议开销。 @@ -30,6 +30,11 @@ bridge, err := mcp.Attach(cx, mcp.Config{ Console: g.console, Overlay: g.debugOverlay, RenderStatsFunc: func() mcp.PerfRender3DStats { return mcp.PerfRender3DStats(g.lastRenderStats) }, + Assets: g.assets, + Resources: g.resources, + Shaders: g.shaderReloader, + Materials: g.materialReloader, + ReloadAsset: g.reloadCustomAsset, }) if err != nil { return err @@ -122,6 +127,9 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_perf_readout` | `include_history`(可选,默认 `false`)、`history_limit`(可选)、`include_zones`(可选,默认 `false`)、`zones_limit`(可选) | 与调试浮层数值一致的实时性能读数:`fps`、滑动平均与最近一帧的 `frame_ms`/`update_ms`/`draw_ms`、最小/最大及 p50/p95/p99 帧时间、绘制统计(`draw_calls`、`sprites`、`batches`、`triangles`、`vertices`)、每帧堆分配(`allocs_per_frame`、`alloc_bytes_per_frame`、`last_frame_allocs`、`last_frame_alloc_bytes`)、`heap_bytes`、`gc_count`、GC 停顿与卡顿统计、可选的 `render3d` 与 `asset_memory` 明细,以及可选的时间序 `history` 与分析器 `zones`。 | | `game_perf_zones` | `limit`(可选) | 按最近帧耗时降序排列的 `debug.Profiler` 命名计时区间列表(`name`、`last_ms`、`avg_ms`、`max_ms`、`calls`),以及 `recording`、`recorded_frames` 和 `total`。 | | `game_perf_reset` | `{}` | 重置累积的 `debug.Overlay` 帧耗时与推送绘制统计、`debug.Profiler` 区间耗时以及 `debug.GCMonitor` 历史记录。通过 `StartRecording` 开始的分析器追踪录制会继续进行,已录制的事件也会保留。 | +| `game_assets_list` | `group`(可选)、`state`(`loaded`/`loading`/`unloaded`/`failed`)、`kind`(可选) | 按确定顺序排列的资源组列表(涵盖 `assets.Manager`、`resource.Library`、`hotreload.ShaderReloader`、`hotreload.MaterialReloader` 与自定义注册资源),包含加载状态、资源键/类型/URI、图集帧数、各组估算内存字节数及 `total_bytes`。 | +| `game_asset_reload` | `key`(资源名、URI 或相对路径)、`group`(可选)、`all`(布尔值,可选) | 就地重载匹配的单个资源(或在 `all: true` 时重载全部已加载资源),返回 `{reloaded, key, group, kind, bytes, duration_ms, revision, items, error}`;未报错但保持不变的条目会带有 `skipped`。解析或编译错误会以结构化结果返回,同时保留原先正常的资源不变。`all: true` 需要配置资源管理器、重载器或已注册资源;`Config.ReloadAsset` 只用于重载单个 key。 | +| `game_assets_reload_group` | `group`(必填) | 就地重载指定资源组内的所有已加载资源,返回逐项结果、重载数 `count`、失败数 `failed`、跳过数 `skipped`、内存字节数、耗时及错误详情,不会导致运行中的游戏崩溃。 | 所有工具都会拒绝未知的参数字段。 @@ -200,6 +208,16 @@ bridge, err := mcp.Attach(cx, mcp.Config{ - `Config.RenderStatsFunc` 会在 `render3d` 字段下附加来自 [`render3d.RenderStats`](render3d.md) 的 3D 裁剪、合批、状态切换与 GPU 内存明细;在未配置 2D 绘制统计来源时,还会自动填充顶层的 `draw_calls`、`batches`、`triangles` 与 `vertices`。`mcp.PerfRender3DStats` 与 `render3d.RenderStats` 字段相同,可直接用 `mcp.PerfRender3DStats(stats)` 转换;`game/mcp` 不导入 `game/render3d`,因此挂接桥接器的 2D 游戏不会链接 3D 渲染器。 - `game_perf_readout` 始终返回 `sources` 对象,标明哪些遥测来源已启用(`overlay`、`profiler`、`gc`、`memory`、`draw_stats`、`render3d`)。 +## 资源检查与热重载 + +配置 `Config.Assets`(或 `Config.AssetsFunc` / `bridge.SetAssets`)、`Config.Resources`、`Config.Shaders`、`Config.Materials` 和/或 `Config.ReloadAsset`,即可让智能体检查资源内存占用并在不重启游戏的情况下触发热重载: + +- **图集就地更新**:在 `assets.Manager` 中按资源名(如 `"hero"`)、完整 URI(`"asset:sprites/hero.json"`)、相对路径(`"sprites/hero.json"`)或图片路径(`"sprites/hero.png"`)重载图集时,会直接就地更新原有的 `*sprite.Atlas` 指针并递增 `assets.Manager.Revision()`,使持有该指针的精灵与读取 `Revision()` 的画布立即刷新。 +- **独立资源与图集**:若游戏在 `assets.Manager` 之外维护了独立的 `*sprite.Atlas` 或自定义资源,可通过 `bridge.RegisterAtlas(...)` 或 `bridge.RegisterAsset(mcp.CustomAsset{...})` 注册。 +- **安全的错误处理**:遇到语法、Schema 或着色器编译错误时,原有可用的图集、着色器、材质或资源会保持激活状态,工具返回 `reloaded: false` 并在 `error` 字段中附带详细诊断信息。 +- **跳过的资源**:音效不会就地替换;没有对应文件的图片(如程序生成的纹理)无从重载;屏幕不显示的密度对应的文件(如 2x 屏幕上的 1x 文件)即使替换也不会改变画面。这些条目会在 `skipped` 中给出原因(`assets.SkippedSound`、`assets.SkippedNoFile`、`assets.SkippedDensity`),既不计入重载成功,也不计入失败。按组重载时,组的读取器找不到文件的图片同样会被跳过;按 key 单独重载该图片则会返回读取错误。 +- **不在引擎 goroutine 上读取**:`Manager.ReloadAsset` 与 `Manager.ReloadGroup` 与 `Group.Load` 一样,在其他 goroutine 上读取文件、解析图集并运行自定义加载器,完成后再在引擎 goroutine 上应用结果。工具调用会等待这些工作完成,因此自定义读取器或加载器不能等待引擎 goroutine;若调用的 context 先结束,则不会替换任何资源,工具返回该 context 的错误。 + ## 稳定的实体引用 每个存活实体都会获得一个格式为 `"entity::"`(例如 `"entity:0:1"`)的代数引用,由 `FormatEntityRef` 格式化并由 `ParseEntityRef` 解析: diff --git a/packages/game/assets/group.go b/packages/game/assets/group.go index 3e90d82d..384e2acf 100644 --- a/packages/game/assets/group.go +++ b/packages/game/assets/group.go @@ -64,11 +64,12 @@ type Group struct { loadCancel context.CancelFunc waiters []func(error) - atlases map[string]*sprite.Atlas - sounds map[string]*audio.Sound - images map[string]core.ImageSource - bytes map[string][]byte - custom map[string]customEntry + atlases map[string]*sprite.Atlas + sounds map[string]*audio.Sound + images map[string]core.ImageSource + bytes map[string][]byte + custom map[string]customEntry + rawBytes map[string]int64 progressSig *core.Signal[float64] loadedSig *core.Signal[int] @@ -334,6 +335,7 @@ func (g *Group) Load(onDone func(error)) { g.images = map[string]core.ImageSource{} g.bytes = map[string][]byte{} g.custom = map[string]customEntry{} + g.rawBytes = map[string]int64{} g.m.cx.Batch(func() { g.loadedSig.Set(0) @@ -391,10 +393,11 @@ func (g *Group) startSpec(gen uint64, loadCtx context.Context, readFn func(conte func (g *Group) startAtlas(gen uint64, loadCtx context.Context, readFn func(context.Context, string) ([]byte, error), spec assetSpec) { prefetch := needsPrefetch(spec.img) var ( - parsed *sprite.Atlas - parsedOK bool - imgOK = !prefetch - failed bool + parsed *sprite.Atlas + parsedLen int64 + parsedOK bool + imgOK = !prefetch + failed bool ) finish := func(err error) { if failed || !g.isActive(gen) { @@ -407,6 +410,7 @@ func (g *Group) startAtlas(gen uint64, loadCtx context.Context, readFn func(cont } if parsedOK && imgOK { g.atlases[spec.name] = parsed + g.rawBytes[spec.name] = parsedLen g.completeItem(gen) } } @@ -439,8 +443,10 @@ func (g *Group) startAtlas(gen uint64, loadCtx context.Context, readFn func(cont }) return } + dataLen := int64(len(data)) g.m.postWithCleanup(nil, func() { parsed = atlas + parsedLen = dataLen parsedOK = true finish(nil) }) @@ -547,6 +553,7 @@ func (g *Group) startCustom(gen uint64, loadCtx context.Context, readFn func(con v := val release = func() { spec.release(v) } } + dataLen := int64(len(data)) g.m.postWithCleanup(release, func() { if !g.isActive(gen) { if release != nil { @@ -555,6 +562,7 @@ func (g *Group) startCustom(gen uint64, loadCtx context.Context, readFn func(con return } g.custom[spec.name] = customEntry{value: val, release: spec.release} + g.rawBytes[spec.name] = dataLen g.completeItem(gen) }) }() @@ -689,4 +697,5 @@ func (g *Group) releaseLoadedValues() { g.images = nil g.bytes = nil g.custom = nil + g.rawBytes = nil } diff --git a/packages/game/assets/reload.go b/packages/game/assets/reload.go index bcbf1bc8..6b17885b 100644 --- a/packages/game/assets/reload.go +++ b/packages/game/assets/reload.go @@ -1,6 +1,7 @@ package assets import ( + "context" "errors" "fmt" "io/fs" @@ -8,6 +9,7 @@ import ( "strings" "github.com/nsgo-dev/game/packages/game/internal/devimage" + "github.com/nsgo-dev/game/packages/game/loaderr" "github.com/nsgo-dev/game/packages/game/sprite" "github.com/nsgo-dev/nsgo/core" ) @@ -50,6 +52,10 @@ func (m *Manager) Reload(uri string, data []byte) ([]string, error) { continue } *cur = *next + if g.rawBytes == nil { + g.rawBytes = map[string]int64{} + } + g.rawBytes[spec.name] = int64(len(data)) } else if img, ok := devimage.Reloaded(spec.img, uri, data, ratio, same); ok { cur.Image = img } else { @@ -64,6 +70,10 @@ func (m *Manager) Reload(uri string, data []byte) ([]string, error) { continue } g.images[spec.name] = img + if g.rawBytes == nil { + g.rawBytes = map[string]int64{} + } + g.rawBytes[spec.name] = int64(len(data)) case kindBytes: if _, ok := g.bytes[spec.name]; !ok || normalizeURI(spec.uri) != want || g.readsFromPack(spec.uri) { continue @@ -94,7 +104,7 @@ func (g *Group) readsFromPack(uri string) bool { return err == nil } -// Revision returns how many Reload calls have replaced an asset. Reading it inside a core.Canvas Draw callback or a core.Effect subscribes to later reloads. +// Revision counts the Reload, ReloadAsset and ReloadGroup calls that replaced at least one asset; each such call adds one. Reading it inside a core.Canvas Draw callback or a core.Effect subscribes to later reloads. func (m *Manager) Revision() int { return m.revision.Get() } @@ -107,3 +117,442 @@ func normalizeURI(uri string) string { } return "asset:" + strings.TrimPrefix(path.Clean("/"+rel), "/") } + +// ReloadedAsset describes one loaded asset that ReloadAsset or ReloadGroup matched. Err holds a read or parse failure, after which the previous asset stays in place. Skipped says why an asset was left unchanged without an error. +type ReloadedAsset struct { + Group string + Name string + Kind string + URI string + Bytes int64 + Frames int + Skipped string + Err error +} + +// Reasons ReloadAsset and ReloadGroup give in ReloadedAsset.Skipped. +const ( + // SkippedSound marks a sound: sounds decode asynchronously on the platform, so they are not replaced in place. + SkippedSound = "sounds are not reloaded in place" + // SkippedNoFile marks an image with no file behind it, such as one registered with in-memory pixels, or, in ReloadGroup, one whose URI the group's reader cannot find. + SkippedNoFile = "no file to reload from" + // SkippedDensity marks an image file at a density the screen does not show, so replacing it would change nothing on screen. + SkippedDensity = "file is at a density the screen does not show" +) + +// ReloadAsset reloads the loaded assets that match key by asset name, URI or relative path, reading fresh bytes through each group's reader (the group's FS, Manager.ReadAsset, the Manager's FS or the local assets/ directory). When groupName is non-empty, only that group is searched. It returns an empty slice and a nil error when no loaded asset matches key, and an error when groupName names no group. +// +// The reads, atlas parses and custom loaders run off the engine goroutine, as they do in Group.Load, while ReloadAsset waits for them, so a reader or loader must not wait on the engine goroutine. When ctx is done first, ReloadAsset returns ctx's error and changes nothing. The results are applied on the engine goroutine: an atlas is updated in place (*cur = *next), so the *sprite.Atlas pointers the game holds stay valid, and a failed read or parse leaves the previous asset in place and is reported both in the item's Err and in the joined error. Sounds, images with no file behind them and files at a density the screen does not show are reported in Skipped and left unchanged. Revision goes up by one when at least one asset was replaced. +// +// Call ReloadAsset on the engine goroutine. +func (m *Manager) ReloadAsset(ctx context.Context, groupName, key string) ([]ReloadedAsset, error) { + if m == nil || m.isDisposed() { + return nil, errors.New("assets: manager is disposed") + } + if ctx == nil { + ctx = m.ctx + } + var groups []*Group + if groupName != "" { + g, ok := m.groups[groupName] + if !ok { + return nil, fmt.Errorf("assets: group %q not found", groupName) + } + groups = []*Group{g} + } else { + groups = make([]*Group, 0, len(m.groupOrder)) + for _, name := range m.groupOrder { + if g, ok := m.groups[name]; ok { + groups = append(groups, g) + } + } + } + + ratio := core.Untracked(m.cx, func() float32 { return m.cx.Env().PixelRatio() }) + var jobs []*reloadJob + for _, g := range groups { + for _, spec := range g.specs { + matchMode, matchedURI := matchSpec(spec, key, ratio) + if matchMode == specMatchNone || !g.isSpecLoaded(spec) { + continue + } + jobs = append(jobs, g.planReload(spec, matchMode, matchedURI, ratio, false)) + } + } + return m.runReloads(ctx, jobs) +} + +// ReloadGroup reloads every loaded asset in the named group in place, as ReloadAsset does for one key. Images whose file the group's reader cannot find are reported as skipped rather than failed, so a group that mixes files with generated textures reloads cleanly. +// +// Call ReloadGroup on the engine goroutine. +func (m *Manager) ReloadGroup(ctx context.Context, groupName string) ([]ReloadedAsset, error) { + if m == nil || m.isDisposed() { + return nil, errors.New("assets: manager is disposed") + } + g, ok := m.groups[groupName] + if !ok { + return nil, fmt.Errorf("assets: group %q not found", groupName) + } + if g.state == stateLoading { + return nil, fmt.Errorf("assets: group %q is currently loading", groupName) + } + if g.state != stateLoaded { + return nil, fmt.Errorf("assets: group %q is not loaded (state: %s)", groupName, groupStateName(g.state)) + } + if ctx == nil { + ctx = m.ctx + } + + ratio := core.Untracked(m.cx, func() float32 { return m.cx.Env().PixelRatio() }) + jobs := make([]*reloadJob, 0, len(g.specs)) + for _, spec := range g.specs { + if !g.isSpecLoaded(spec) { + continue + } + jobs = append(jobs, g.planReload(spec, specMatchName, "", ratio, true)) + } + return m.runReloads(ctx, jobs) +} + +type specMatchKind uint8 + +const ( + specMatchNone specMatchKind = iota + specMatchName + specMatchURI + specMatchImageURI +) + +func matchSpec(spec assetSpec, key string, ratio float32) (specMatchKind, string) { + if key == "" { + return specMatchNone, "" + } + if spec.name == key { + return specMatchName, "" + } + if spec.uri != "" && matchURI(spec.uri, key) { + return specMatchURI, spec.uri + } + if spec.img.URI != "" { + shown := devimage.Shown(spec.img, ratio) + if matchURI(shown, key) { + return specMatchImageURI, shown + } + if shown != spec.img.URI && matchURI(spec.img.URI, key) { + return specMatchImageURI, spec.img.URI + } + } + if spec.sound.URI != "" && matchURI(spec.sound.URI, key) { + return specMatchURI, spec.sound.URI + } + return specMatchNone, "" +} + +func matchURI(specURI, key string) bool { + normSpec := normalizeURI(specURI) + if normalizeURI(key) == normSpec { + return true + } + if !strings.HasPrefix(key, "asset:") && !strings.HasPrefix(key, "file://") { + if normalizeURI("asset:"+strings.TrimPrefix(key, "/")) == normSpec { + return true + } + } + return false +} + +func (g *Group) isSpecLoaded(spec assetSpec) bool { + switch spec.kind { + case kindAtlas: + a, ok := g.atlases[spec.name] + return ok && a != nil + case kindSound: + s, ok := g.sounds[spec.name] + return ok && s != nil + case kindImage: + _, ok := g.images[spec.name] + return ok + case kindBytes: + _, ok := g.bytes[spec.name] + return ok + case kindCustom: + _, ok := g.custom[spec.name] + return ok + default: + return false + } +} + +// reloadJob is one asset ReloadAsset or ReloadGroup reloads. planReload fills the plan on the engine goroutine, fetch fills the fetched fields off it, and apply swaps the result in on the engine goroutine. +type reloadJob struct { + g *Group + gen uint64 + spec assetSpec + res ReloadedAsset + bulk bool + ratio float32 + + readFn func(context.Context, string) ([]byte, error) + dataURI string + imgURI string + imgOnly bool + curImage core.ImageSource + + data []byte + img core.ImageSource + imgOK bool + atlas *sprite.Atlas + custom any + readErr error + err error +} + +func (g *Group) planReload(spec assetSpec, mode specMatchKind, matchedURI string, ratio float32, bulk bool) *reloadJob { + j := &reloadJob{ + g: g, + gen: g.gen, + spec: spec, + bulk: bulk, + ratio: ratio, + readFn: g.readAssetFunc(), + res: ReloadedAsset{ + Group: g.name, + Name: spec.name, + Kind: assetKindName(spec.kind), + URI: specURI(spec), + }, + } + switch spec.kind { + case kindSound: + j.res.Skipped = SkippedSound + case kindAtlas: + j.curImage = g.atlases[spec.name].Image + if mode == specMatchImageURI { + j.imgOnly = true + j.planImage(matchedURI) + return j + } + j.dataURI = spec.uri + if mode == specMatchName && spec.img.URI != "" { + j.imgURI = devimage.Shown(spec.img, ratio) + } + case kindImage: + j.planImage(matchedURI) + case kindBytes, kindCustom: + j.dataURI = spec.uri + } + return j +} + +func (j *reloadJob) planImage(matchedURI string) { + if j.spec.img.URI == "" { + j.res.Skipped = SkippedNoFile + return + } + shown := devimage.Shown(j.spec.img, j.ratio) + target := matchedURI + if target == "" { + target = shown + } + j.res.URI = target + if normalizeURI(target) != normalizeURI(shown) { + j.res.Skipped = SkippedDensity + return + } + j.imgURI = target +} + +// fetch reads and parses the job's files. It runs off the engine goroutine and touches only the job. +func (j *reloadJob) fetch(ctx context.Context) { + if j.res.Skipped != "" { + return + } + same := func(a, b string) bool { return normalizeURI(a) == normalizeURI(b) } + name := j.spec.name + if j.imgURI != "" { + data, err := j.readFn(ctx, j.imgURI) + switch { + case err == nil && len(data) > 0: + j.img, j.imgOK = devimage.Reloaded(j.spec.img, j.imgURI, data, j.ratio, same) + case j.imgOnly || j.spec.kind == kindImage: + if err == nil { + err = errors.New("file is empty") + } + j.readErr = err + j.err = fmt.Errorf("assets: %s %q: read %q: %w", assetKindName(j.spec.kind), name, j.imgURI, err) + return + } + } + if j.dataURI == "" { + return + } + data, err := j.readFn(ctx, j.dataURI) + if err != nil { + j.readErr = err + j.err = fmt.Errorf("assets: %s %q: read %q: %w", assetKindName(j.spec.kind), name, j.dataURI, err) + return + } + j.data = data + switch j.spec.kind { + case kindAtlas: + img := j.curImage + if j.imgOK { + img = j.img + } + atlas, err := sprite.LoadAtlas(img, data) + if err != nil { + j.err = fmt.Errorf("assets: atlas %q: %w", name, loaderr.WithFile(err, j.dataURI)) + return + } + j.atlas = atlas + case kindCustom: + var val any = data + if j.spec.loader != nil { + val, err = j.spec.loader(ctx, data) + if err != nil { + j.err = fmt.Errorf("assets: custom %q: %w", name, err) + return + } + } + j.custom = val + } +} + +// releaseUnused releases a custom value the job loaded but did not apply. +func (j *reloadJob) releaseUnused(m *Manager) { + if j.custom == nil || j.spec.release == nil { + return + } + v, release := j.custom, j.spec.release + j.custom = nil + done := func() { release(v) } + m.postWithCleanup(done, done) +} + +// runReloads fetches every job off the engine goroutine, waits for the fetches or for ctx, and applies the results on the engine goroutine. +func (m *Manager) runReloads(ctx context.Context, jobs []*reloadJob) ([]ReloadedAsset, error) { + done := make(chan struct{}) + go func() { + defer close(done) + for _, j := range jobs { + if ctx.Err() != nil { + return + } + j.fetch(ctx) + } + }() + select { + case <-done: + case <-ctx.Done(): + go func() { + <-done + for _, j := range jobs { + j.releaseUnused(m) + } + }() + return nil, ctx.Err() + } + if err := ctx.Err(); err != nil { + for _, j := range jobs { + j.releaseUnused(m) + } + return nil, err + } + + results := make([]ReloadedAsset, 0, len(jobs)) + var ( + errs []error + replaced bool + ) + for _, j := range jobs { + if j.apply(m) { + replaced = true + } + if j.res.Err != nil { + errs = append(errs, j.res.Err) + } + results = append(results, j.res) + } + if replaced { + m.revision.Set(m.revision.GetUntracked() + 1) + } + return results, errors.Join(errs...) +} + +// apply swaps the fetched result in on the engine goroutine and reports whether it replaced the asset. +func (j *reloadJob) apply(m *Manager) bool { + g, spec := j.g, j.spec + defer func() { j.res.Bytes, j.res.Frames = g.reloadedSize(spec) }() + if j.res.Skipped != "" { + return false + } + if m.isDisposed() || g.gen != j.gen || g.state != stateLoaded || !g.isSpecLoaded(spec) { + j.releaseUnused(m) + j.res.Err = fmt.Errorf("assets: %s %q: group %q changed during the reload", j.res.Kind, spec.name, g.name) + return false + } + if j.err != nil { + if j.bulk && spec.kind == kindImage && errors.Is(j.readErr, fs.ErrNotExist) { + j.res.Skipped = SkippedNoFile + return false + } + j.res.Err = j.err + return false + } + if g.rawBytes == nil { + g.rawBytes = map[string]int64{} + } + switch spec.kind { + case kindAtlas: + cur := g.atlases[spec.name] + if j.imgOnly { + if !j.imgOK { + j.res.Skipped = SkippedDensity + return false + } + cur.Image = j.img + return true + } + *cur = *j.atlas + g.rawBytes[spec.name] = int64(len(j.data)) + case kindImage: + if !j.imgOK { + j.res.Skipped = SkippedDensity + return false + } + g.images[spec.name] = j.img + g.rawBytes[spec.name] = int64(len(j.img.Data)) + case kindBytes: + g.bytes[spec.name] = j.data + case kindCustom: + old := g.custom[spec.name] + if old.release != nil && old.value != nil { + old.release(old.value) + } + g.custom[spec.name] = customEntry{value: j.custom, release: spec.release} + g.rawBytes[spec.name] = int64(len(j.data)) + j.custom = nil + default: + return false + } + return true +} + +// reloadedSize reports the estimated bytes and atlas frame count of a loaded asset. +func (g *Group) reloadedSize(spec assetSpec) (int64, int) { + switch spec.kind { + case kindAtlas: + if a := g.atlases[spec.name]; a != nil { + return EstimateAtlasBytes(a, g.rawBytes[spec.name]), len(a.Frames) + } + case kindImage: + return estimateImageBytes(g.images[spec.name]), 0 + case kindBytes: + return int64(len(g.bytes[spec.name])), 0 + case kindCustom: + return estimateCustomBytes(g.custom[spec.name].value, g.rawBytes[spec.name]), 0 + case kindSound: + return g.assetStats(spec).Bytes, 0 + } + return 0, 0 +} diff --git a/packages/game/assets/reloadasset_test.go b/packages/game/assets/reloadasset_test.go new file mode 100644 index 00000000..19cfcb92 --- /dev/null +++ b/packages/game/assets/reloadasset_test.go @@ -0,0 +1,153 @@ +package assets_test + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + "testing/fstest" + "time" + + "github.com/nsgo-dev/game/packages/game/assets" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func TestReloadAssetSkipsDensitiesTheScreenDoesNotShowAndImagesWithoutFiles(t *testing.T) { + const ( + heroImage = "asset:images/hero.png" + heroImage2x = "asset:images/hero@2x.png" + ) + fsys := fstest.MapFS{ + "images/hero.png": {Data: []byte("1x on disk")}, + "images/hero@2x.png": {Data: []byte("2x on disk")}, + } + var mgr *assets.Manager + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + mgr = assets.NewManager(cx, assets.WithFS(fsys)) + mgr.Group("ui"). + AddImage("hero", core.ImageSource{URI: heroImage, Scales: core.ScalesOf(1, 2), Data: []byte("embedded")}). + AddImage("generated", core.ImageSource{Data: []byte("generated")}) + mgr.LoadGroup("ui", func(err error) { + if err != nil { + t.Errorf("LoadGroup: %v", err) + } + }) + return core.Canvas{Style: core.Style{Width: core.Pt(8), Height: core.Pt(8)}} + }, nsgotest.Environment(core.Environment{PixelRatio: 2})) + app.WaitUntil(time.Second, func() bool { return mgr.Group("ui").Done() }) + + reload := func(key string) ([]assets.ReloadedAsset, error, core.ImageSource, int) { + t.Helper() + var ( + got []assets.ReloadedAsset + err error + img core.ImageSource + rev int + ) + app.Post(func() { + got, err = mgr.ReloadAsset(context.Background(), "", key) + img, _ = mgr.Image("hero") + rev = mgr.Revision() + }) + app.Settle() + return got, err, img, rev + } + + // A 2x screen does not show the 1x file: reloading it leaves the multi-scale source alone. + got, err, img, rev := reload("images/hero.png") + if err != nil || len(got) != 1 || got[0].Skipped != assets.SkippedDensity || got[0].Err != nil { + t.Fatalf("reload 1x = (%+v, %v), want skipped for density", got, err) + } + if string(img.Data) != "embedded" || img.Scales != core.ScalesOf(1, 2) || rev != 0 { + t.Fatalf("reloading the 1x file changed the image: %+v (revision %d)", img, rev) + } + + got, err, img, rev = reload("images/hero@2x.png") + if err != nil || len(got) != 1 || got[0].Skipped != "" || got[0].Err != nil { + t.Fatalf("reload 2x = (%+v, %v)", got, err) + } + if string(img.Data) != "2x on disk" || img.URI != heroImage2x || img.Density() != 2 || rev != 1 { + t.Fatalf("reloading the 2x file = %+v (density %v, revision %d)", img, img.Density(), rev) + } + + // A group reload skips the generated image instead of failing the group. + var groupRes []assets.ReloadedAsset + app.Post(func() { groupRes, err = mgr.ReloadGroup(context.Background(), "ui") }) + app.Settle() + if err != nil || len(groupRes) != 2 { + t.Fatalf("ReloadGroup(ui) = (%+v, %v)", groupRes, err) + } + if groupRes[1].Name != "generated" || groupRes[1].Skipped != assets.SkippedNoFile || groupRes[1].Err != nil { + t.Fatalf("generated image = %+v, want skipped with no file", groupRes[1]) + } +} + +func TestReloadAssetRunsCustomLoadersOffTheEngineGoroutine(t *testing.T) { + fsys := fstest.MapFS{"data/table.txt": {Data: []byte("v1")}} + var ( + mu sync.Mutex + calls int + released []string + ) + gate := make(chan struct{}) + load := func(_ context.Context, data []byte) (any, error) { + mu.Lock() + calls++ + first := calls == 1 + mu.Unlock() + if !first { + // A loader that ignores ctx: ReloadAsset must give up on ctx without waiting for it on the engine goroutine. + <-gate + } + return string(data), nil + } + release := func(v any) { + mu.Lock() + released = append(released, v.(string)) + mu.Unlock() + } + + var mgr *assets.Manager + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + mgr = assets.NewManager(cx, assets.WithFS(fsys)) + mgr.Group("data").AddCustomLoader("table", "asset:data/table.txt", load, release) + mgr.LoadGroup("data", func(err error) { + if err != nil { + t.Errorf("LoadGroup: %v", err) + } + }) + return core.View{} + }) + app.WaitUntil(time.Second, func() bool { return mgr.Group("data").Done() }) + + fsys["data/table.txt"] = &fstest.MapFile{Data: []byte("v2")} + var ( + err error + cur any + ) + app.Post(func() { + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + _, err = mgr.ReloadAsset(ctx, "", "table") + cur, _ = mgr.Get("table") + }) + app.Settle() + if !errors.Is(err, context.DeadlineExceeded) || cur != "v1" { + t.Fatalf("ReloadAsset with a stuck loader = %v, table %v; want deadline exceeded and v1 kept", err, cur) + } + + // Once the loader finishes, the value nobody applied is released. + close(gate) + app.WaitUntil(time.Second, func() bool { + mu.Lock() + defer mu.Unlock() + return slices.Equal(released, []string{"v2"}) + }) + app.Post(func() { cur, _ = mgr.Get("table") }) + app.Settle() + if cur != "v1" { + t.Fatalf("table after abandoned reload = %v, want v1", cur) + } +} diff --git a/packages/game/assets/stats.go b/packages/game/assets/stats.go new file mode 100644 index 00000000..435f90ea --- /dev/null +++ b/packages/game/assets/stats.go @@ -0,0 +1,266 @@ +package assets + +import ( + "math" + "slices" + + "github.com/nsgo-dev/game/packages/game/sprite" + "github.com/nsgo-dev/nsgo/core" +) + +// Group lifecycle state names reported by GroupStats.State. +const ( + StateUnloaded = "unloaded" + StateLoading = "loading" + StateLoaded = "loaded" + StateFailed = "failed" +) + +// AssetStats describes one registered asset inside a Group and its estimated in-memory size. +type AssetStats struct { + Name string + Kind string // "atlas", "sound", "image", "bytes", "custom" + URI string + ImageURI string // atlas image URI when Kind == "atlas" + Loaded bool + Bytes int64 + Frames int // atlas frame count when loaded and Kind == "atlas" +} + +// GroupStats describes a Group's current load state, assets and estimated memory footprint. +type GroupStats struct { + Name string + State string // StateUnloaded, StateLoading, StateLoaded, or StateFailed + Loaded int + Total int + Bytes int64 + Error string + Assets []AssetStats +} + +// Disposed reports whether the manager's owning scope has been disposed. +func (m *Manager) Disposed() bool { + if m == nil { + return true + } + return m.isDisposed() +} + +// GroupNames returns the names of all registered groups in registration order. +func (m *Manager) GroupNames() []string { + if m == nil || len(m.groupOrder) == 0 { + return nil + } + return slices.Clone(m.groupOrder) +} + +// LookupGroup returns the existing group named name without creating one when absent. +func (m *Manager) LookupGroup(name string) (*Group, bool) { + if m == nil { + return nil, false + } + g, ok := m.groups[name] + return g, ok +} + +// GroupStats returns a read-only stats snapshot for every registered group in registration order. Reading GroupStats does not subscribe the caller to reactive signals. +func (m *Manager) GroupStats() []GroupStats { + if m == nil || len(m.groupOrder) == 0 { + return nil + } + out := make([]GroupStats, 0, len(m.groupOrder)) + for _, name := range m.groupOrder { + if g, ok := m.groups[name]; ok { + out = append(out, g.Stats()) + } + } + return out +} + +// Stats returns a read-only snapshot of g's load state, registered assets, and estimated memory usage in bytes. Calling Stats does not subscribe the caller to reactive signals. +func (g *Group) Stats() GroupStats { + if g == nil { + return GroupStats{State: StateUnloaded} + } + st := GroupStats{ + Name: g.name, + State: groupStateName(g.state), + Loaded: g.loaded, + Total: len(g.specs), + Assets: make([]AssetStats, 0, len(g.specs)), + } + if g.state == stateFailed && g.errSig != nil { + if err := g.errSig.GetUntracked(); err != nil { + st.Error = err.Error() + } + } + for _, spec := range g.specs { + as := g.assetStats(spec) + st.Bytes += as.Bytes + st.Assets = append(st.Assets, as) + } + return st +} + +func (g *Group) assetStats(spec assetSpec) AssetStats { + as := AssetStats{ + Name: spec.name, + Kind: assetKindName(spec.kind), + URI: specURI(spec), + } + if spec.kind == kindAtlas { + as.ImageURI = spec.img.URI + } + switch spec.kind { + case kindAtlas: + if a, ok := g.atlases[spec.name]; ok && a != nil { + as.Loaded = true + as.Frames = len(a.Frames) + as.Bytes = EstimateAtlasBytes(a, g.rawBytes[spec.name]) + } + case kindSound: + if s, ok := g.sounds[spec.name]; ok && s != nil { + as.Loaded = true + bytes := int64(len(spec.sound.Data)) + if d := s.Duration(); d > 0 { + // Decoded 44.1 kHz 16-bit stereo PCM estimate. + if pcm := int64(math.Round(d.Seconds() * 44100 * 4)); pcm > bytes { + bytes = pcm + } + } + as.Bytes = bytes + } + case kindImage: + if img, ok := g.images[spec.name]; ok { + as.Loaded = true + as.Bytes = estimateImageBytes(img) + if as.Bytes == 0 { + as.Bytes = g.rawBytes[spec.name] + } + } + case kindBytes: + if b, ok := g.bytes[spec.name]; ok { + as.Loaded = true + as.Bytes = int64(len(b)) + } + case kindCustom: + if c, ok := g.custom[spec.name]; ok { + as.Loaded = true + as.Bytes = estimateCustomBytes(c.value, g.rawBytes[spec.name]) + } + } + return as +} + +func groupStateName(s groupState) string { + switch s { + case stateLoading: + return StateLoading + case stateLoaded: + return StateLoaded + case stateFailed: + return StateFailed + default: + return StateUnloaded + } +} + +func assetKindName(k assetKind) string { + switch k { + case kindAtlas: + return "atlas" + case kindSound: + return "sound" + case kindImage: + return "image" + case kindBytes: + return "bytes" + case kindCustom: + return "custom" + default: + return "unknown" + } +} + +func specURI(spec assetSpec) string { + switch spec.kind { + case kindImage: + return spec.img.URI + case kindSound: + return spec.sound.URI + default: + return spec.uri + } +} + +type memorySizer interface { + MemoryBytes() int64 +} + +func estimateCustomBytes(v any, rawBytes int64) int64 { + if sizer, ok := v.(memorySizer); ok { + if n := sizer.MemoryBytes(); n >= 0 { + return n + } + } + switch x := v.(type) { + case []byte: + return int64(len(x)) + case string: + return int64(len(x)) + } + return rawBytes +} + +// EstimateAtlasBytes estimates the memory an atlas holds: rawJSONBytes (or a per-frame estimate when it is 0) plus the image bytes, which come from the image's pixels, data or size, or from the packed frame extents at 4 bytes per pixel when the image has only a URI. game/mcp uses it for atlases registered outside a Manager. +func EstimateAtlasBytes(a *sprite.Atlas, rawJSONBytes int64) int64 { + if a == nil { + return 0 + } + total := rawJSONBytes + if total == 0 { + total = int64(len(a.Frames)*128 + len(a.Animations)*64 + len(a.Slices)*64) + } + imgBytes := estimateImageBytes(a.Image) + if imgBytes == 0 && len(a.Frames) > 0 { + // When Image has only a URI without inline Data/Pixels/Size, derive a conservative RGBA pixel estimate from the packed frame extents. + var maxX, maxY float32 + for _, f := range a.Frames { + if right := f.X + f.W; right > maxX { + maxX = right + } + if bottom := f.Y + f.H; bottom > maxY { + maxY = bottom + } + } + if maxX > 0 && maxY > 0 { + d := float64(a.Image.Density()) + if d <= 0 { + d = 1 + } + w := int64(math.Ceil(float64(maxX) * d)) + h := int64(math.Ceil(float64(maxY) * d)) + imgBytes = w * h * 4 + } + } + return total + imgBytes +} + +func estimateImageBytes(img core.ImageSource) int64 { + if img.Pixels != nil { + return int64(len(img.Pixels.Pix)) + } + if len(img.Data) > 0 { + return int64(len(img.Data)) + } + if img.Size.Width > 0 && img.Size.Height > 0 { + d := float64(img.Density()) + if d <= 0 { + d = 1 + } + w := int64(math.Ceil(float64(img.Size.Width) * d)) + h := int64(math.Ceil(float64(img.Size.Height) * d)) + return w * h * 4 + } + return 0 +} diff --git a/packages/game/assets/stats_test.go b/packages/game/assets/stats_test.go new file mode 100644 index 00000000..f4fef728 --- /dev/null +++ b/packages/game/assets/stats_test.go @@ -0,0 +1,117 @@ +package assets_test + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/assets" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func TestGroupStatsAndReloadAsset(t *testing.T) { + dir := t.TempDir() + mustWrite := func(rel, content string) { + t.Helper() + full := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + mustWrite("sprites/hero.json", heroAtlasJSON) + mustWrite("fonts/pixel.fnt", "BMFont-v1") + + var mgr *assets.Manager + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + mgr = assets.NewManager(cx, assets.WithFS(os.DirFS(dir))) + mgr.Group("level1"). + AddAtlas("hero", heroJSONURI, core.Src(heroPNGURI)). + AddBytes("font", fontURI) + mgr.Group("level2"). + AddBytes("font2", fontURI) + mgr.LoadGroup("level1", func(err error) { + if err != nil { + t.Errorf("LoadGroup: %v", err) + } + }) + return core.View{} + }, envWithMedia()...) + app.WaitUntil(time.Second, func() bool { return mgr.Group("level1").Done() }) + + var ( + names []string + stats []assets.GroupStats + found bool + ) + app.Post(func() { + names = mgr.GroupNames() + stats = mgr.GroupStats() + _, found = mgr.LookupGroup("does_not_exist") + }) + app.Settle() + + if found { + t.Fatal("LookupGroup should not find or create missing group") + } + if !slices.Equal(names, []string{"level1", "level2"}) { + t.Fatalf("GroupNames = %v, want [level1 level2]", names) + } + if len(stats) != 2 { + t.Fatalf("len(GroupStats) = %d, want 2", len(stats)) + } + if stats[0].Name != "level1" || stats[0].State != assets.StateLoaded || stats[0].Loaded != 2 || stats[0].Bytes <= 0 { + t.Fatalf("stats[0] = %+v", stats[0]) + } + if stats[1].Name != "level2" || stats[1].State != assets.StateUnloaded || stats[1].Bytes != 0 { + t.Fatalf("stats[1] = %+v", stats[1]) + } + + // Update hero.json on disk and reload by name. + held := mustAtlas(t, app, mgr) + mustWrite("sprites/hero.json", heroAtlasJSONWithJump) + var ( + reloaded []assets.ReloadedAsset + err error + ) + app.Post(func() { + reloaded, err = mgr.ReloadAsset(context.Background(), "", "hero") + }) + app.Settle() + if err != nil || len(reloaded) != 1 || reloaded[0].Name != "hero" || reloaded[0].Frames != 3 { + t.Fatalf("ReloadAsset(hero) = (%+v, %v)", reloaded, err) + } + if _, ok := held.Frames["jump.png"]; !ok { + t.Fatalf("held atlas missing jump.png after ReloadAsset: %+v", held.Frames) + } + + // Update font and reload entire group. + mustWrite("fonts/pixel.fnt", "BMFont-v2-longer") + app.Post(func() { + reloaded, err = mgr.ReloadGroup(context.Background(), "level1") + }) + app.Settle() + if err != nil || len(reloaded) != 2 { + t.Fatalf("ReloadGroup(level1) = (%+v, %v)", reloaded, err) + } + var gotFont []byte + app.Post(func() { gotFont, _ = mgr.Bytes("font") }) + app.Settle() + if string(gotFont) != "BMFont-v2-longer" { + t.Fatalf("font after ReloadGroup = %q", gotFont) + } + + // ReloadGroup on unloaded group returns error. + app.Post(func() { _, err = mgr.ReloadGroup(context.Background(), "level2") }) + app.Settle() + if err == nil || !strings.Contains(err.Error(), "not loaded") { + t.Fatalf("ReloadGroup(level2) = %v, want not loaded", err) + } +} diff --git a/packages/game/mcp/assets.go b/packages/game/mcp/assets.go new file mode 100644 index 00000000..d821c5cd --- /dev/null +++ b/packages/game/mcp/assets.go @@ -0,0 +1,1169 @@ +package mcp + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "path" + "slices" + "strings" + "time" + + "github.com/nsgo-dev/game/packages/game/assets" + "github.com/nsgo-dev/game/packages/game/loaderr" + "github.com/nsgo-dev/game/packages/game/sprite" + "github.com/nsgo-dev/nsgo/automation" +) + +// Asset and hot-reload tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation. +const ( + // ToolAssetsList lists asset groups, asset keys/types, load states, and estimated memory usage in bytes. + ToolAssetsList = "game_assets_list" + // ToolAssetReload reloads a single named asset, URI, or path (or all loaded assets) in place. + ToolAssetReload = "game_asset_reload" + // ToolAssetsReloadGroup reloads every loaded asset in a named asset group in place. + ToolAssetsReloadGroup = "game_assets_reload_group" +) + +var ( + // ErrEmptyAssetKey reports registering a custom asset with an empty key. + ErrEmptyAssetKey = errors.New("mcp: empty asset key") + // ErrDuplicateAsset reports registering a custom asset key that is already registered on the Bridge. + ErrDuplicateAsset = errors.New("mcp: duplicate asset registration") +) + +// CustomAsset registers a game-managed asset outside assets.Manager (such as a standalone sprite.Atlas, scene file, or data table) so game_assets_list reports its memory and game_asset_reload / game_assets_reload_group can reload it on demand. +type CustomAsset struct { + // Key is the unique asset identifier (required). + Key string + // Group is the asset group name reported by game_assets_list (defaults to "custom" when empty). + Group string + // Kind describes the asset type (e.g. "atlas", "image", "scene", "shader", "material", "sound", "bytes", "custom"). + Kind string + // URI is an optional source path or URI shown in game_assets_list and matched by game_asset_reload. + URI string + // Bytes returns the asset's current estimated memory footprint in bytes (optional). + Bytes func() int64 + // Frames returns the current frame count for atlas-like assets (optional). + Frames func() int + // Reload reloads the asset in place (optional). + Reload func(ctx context.Context) error +} + +type assetRegistry struct { + entries map[string]CustomAsset + order []string +} + +// AssetEntry describes one asset within an asset group returned by game_assets_list. +type AssetEntry struct { + Key string `json:"key"` + Kind string `json:"kind"` + URI string `json:"uri,omitempty"` + ImageURI string `json:"image_uri,omitempty"` + Loaded bool `json:"loaded"` + Bytes int64 `json:"bytes"` + Frames int `json:"frames,omitempty"` +} + +// AssetGroupSummary describes one asset group and its estimated memory usage returned by game_assets_list. +type AssetGroupSummary struct { + Name string `json:"name"` + Source string `json:"source"` + State string `json:"state"` + Loaded int `json:"loaded"` + Total int `json:"total"` + Bytes int64 `json:"bytes"` + Error string `json:"error,omitempty"` + Assets []AssetEntry `json:"assets"` +} + +// AssetsListResult is the JSON result of game_assets_list. +type AssetsListResult struct { + Revision int `json:"revision,omitempty"` + GroupCount int `json:"group_count"` + AssetCount int `json:"asset_count"` + TotalBytes int64 `json:"total_bytes"` + Groups []AssetGroupSummary `json:"groups"` +} + +// ReloadedItem describes one asset touched during a reload operation. +type ReloadedItem struct { + Key string `json:"key"` + Group string `json:"group,omitempty"` + Kind string `json:"kind,omitempty"` + URI string `json:"uri,omitempty"` + Bytes int64 `json:"bytes"` + Frames int `json:"frames,omitempty"` + // Skipped says why the asset was left unchanged without an error, such as a sound or an image with no file behind it. + Skipped string `json:"skipped,omitempty"` + Error string `json:"error,omitempty"` +} + +func reloadedItem(r assets.ReloadedAsset) ReloadedItem { + item := ReloadedItem{ + Key: r.Name, + Group: r.Group, + Kind: r.Kind, + URI: r.URI, + Bytes: r.Bytes, + Frames: r.Frames, + Skipped: r.Skipped, + } + if r.Err != nil { + item.Error = r.Err.Error() + } + return item +} + +// anyReloaded reports whether at least one item was reloaded rather than skipped or failed. +func anyReloaded(items []ReloadedItem) bool { + for _, it := range items { + if it.Error == "" && it.Skipped == "" { + return true + } + } + return false +} + +// AssetReloadResult is the JSON result of game_asset_reload. +type AssetReloadResult struct { + Reloaded bool `json:"reloaded"` + Key string `json:"key,omitempty"` + Group string `json:"group,omitempty"` + Kind string `json:"kind,omitempty"` + Bytes int64 `json:"bytes"` + DurationMS float64 `json:"duration_ms"` + Revision int `json:"revision,omitempty"` + Items []ReloadedItem `json:"items,omitempty"` + Error string `json:"error,omitempty"` +} + +// AssetsReloadGroupResult is the JSON result of game_assets_reload_group. +type AssetsReloadGroupResult struct { + Group string `json:"group"` + Reloaded bool `json:"reloaded"` + Count int `json:"count"` + Failed int `json:"failed,omitempty"` + Skipped int `json:"skipped,omitempty"` + Bytes int64 `json:"bytes"` + DurationMS float64 `json:"duration_ms"` + Revision int `json:"revision,omitempty"` + Items []ReloadedItem `json:"items"` + Error string `json:"error,omitempty"` +} + +var ( + schemaAssetsList = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "group": { + "type": "string", + "description": "Filter to a specific asset group name." + }, + "state": { + "type": "string", + "enum": ["loaded", "loading", "unloaded", "failed"], + "description": "Filter asset groups by lifecycle state." + }, + "kind": { + "type": "string", + "description": "Filter listed assets by kind (for example \"atlas\", \"image\", \"sound\", \"bytes\", \"custom\", \"shader\", \"material\")." + } + } + }`) + + schemaAssetReload = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "key": { + "type": "string", + "description": "Asset name, URI (such as \"asset:sprites/hero.json\"), or relative path to reload. Required unless \"all\" is true." + }, + "group": { + "type": "string", + "description": "Optional asset group name to scope the reload." + }, + "all": { + "type": "boolean", + "description": "Reload every loaded asset across all configured groups and reloaders (default false)." + } + } + }`) + + schemaAssetsReloadGroup = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["group"], + "properties": { + "group": { + "type": "string", + "description": "Name of the asset group to reload (from game_assets_list)." + } + } + }`) +) + +// SetAssets replaces the static Assets manager configured on b. If Config.AssetsFunc is set and returns a non-nil manager, AssetsFunc continues to take precedence. +func (b *Bridge) SetAssets(m *assets.Manager) { + if b == nil { + return + } + b.cfg.Assets = m +} + +// RegisterAsset registers a custom game-managed asset on b for game_assets_list and game_asset_reload. +func (b *Bridge) RegisterAsset(asset CustomAsset) error { + if b == nil { + return ErrNilBridge + } + if strings.TrimSpace(asset.Key) == "" { + return ErrEmptyAssetKey + } + if asset.Group == "" { + asset.Group = "custom" + } + if asset.Kind == "" { + asset.Kind = "custom" + } + if b.customAssets == nil { + b.customAssets = &assetRegistry{entries: make(map[string]CustomAsset)} + } + if _, dup := b.customAssets.entries[asset.Key]; dup { + return fmt.Errorf("mcp: asset %q: %w", asset.Key, ErrDuplicateAsset) + } + b.customAssets.entries[asset.Key] = asset + b.customAssets.order = append(b.customAssets.order, asset.Key) + slices.Sort(b.customAssets.order) + return nil +} + +// RegisterAtlas registers a standalone live *sprite.Atlas (not owned by an assets.Manager) on b so game_assets_list reports its frame count and estimated memory, and game_asset_reload re-parses jsonPath via readFile and updates *atlas in place without replacing the pointer. +func (b *Bridge) RegisterAtlas(key, group, jsonPath string, atlas *sprite.Atlas, readFile func(ctx context.Context, path string) ([]byte, error)) error { + if b == nil { + return ErrNilBridge + } + if atlas == nil { + return errors.New("mcp: nil atlas") + } + if group == "" { + group = "custom" + } + var lastJSONBytes int64 + return b.RegisterAsset(CustomAsset{ + Key: key, + Group: group, + Kind: "atlas", + URI: jsonPath, + Bytes: func() int64 { + return assets.EstimateAtlasBytes(atlas, lastJSONBytes) + }, + Frames: func() int { + return len(atlas.Frames) + }, + Reload: func(ctx context.Context) error { + if readFile == nil { + return fmt.Errorf("mcp: atlas %q has no file reader configured", key) + } + data, err := readFile(ctx, jsonPath) + if err != nil { + return fmt.Errorf("mcp: atlas %q: read %q: %w", key, jsonPath, err) + } + next, err := sprite.LoadAtlas(atlas.Image, data) + if err != nil { + return fmt.Errorf("mcp: atlas %q: %w", key, loaderr.WithFile(err, jsonPath)) + } + *atlas = *next + lastJSONBytes = int64(len(data)) + return nil + }, + }) +} + +func (b *Bridge) assetTools() []automation.Tool { + return []automation.Tool{ + { + Name: ToolAssetsList, + Description: "List loaded asset groups, their load states, asset keys/types, and estimated memory usage in bytes.", + InputSchema: schemaAssetsList, + Handler: b.handleAssetsList, + }, + { + Name: ToolAssetReload, + Description: "Reload a named asset, URI, or relative path (atlas, image, bytes, custom asset, shader, material, or resource) in place, or reload all loaded assets when all=true. Surfaces parse/compile errors cleanly without crashing.", + InputSchema: schemaAssetReload, + Handler: b.handleAssetReload, + }, + { + Name: ToolAssetsReloadGroup, + Description: "Reload every loaded asset in a named asset group in place, reporting per-asset results and any parse or load errors.", + InputSchema: schemaAssetsReloadGroup, + Handler: b.handleAssetsReloadGroup, + }, + } +} + +func (b *Bridge) activeAssets() *assets.Manager { + if b == nil { + return nil + } + if b.cfg.AssetsFunc != nil { + if m := b.cfg.AssetsFunc(); m != nil { + return m + } + } + return b.cfg.Assets +} + +func (b *Bridge) hasAnyAssetSource() bool { + return b.activeAssets() != nil || + b.cfg.Resources != nil || + b.cfg.Shaders != nil || + b.cfg.Materials != nil || + (b.customAssets != nil && len(b.customAssets.entries) > 0) +} + +func (b *Bridge) hasAnyReloadSource() bool { + return b.hasAnyAssetSource() || b.cfg.ReloadAsset != nil +} + +type assetsListArgs struct { + Group string `json:"group"` + State string `json:"state"` + Kind string `json:"kind"` +} + +func (b *Bridge) handleAssetsList(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[assetsListArgs](raw) + if err != nil { + return nil, err + } + if args.State != "" { + switch args.State { + case assets.StateLoaded, assets.StateLoading, assets.StateUnloaded, assets.StateFailed: + default: + return nil, fmt.Errorf("mcp: invalid asset state %q (want loaded, loading, unloaded, or failed)", args.State) + } + } + if !b.hasAnyAssetSource() { + return nil, errors.New("mcp: no asset manager configured") + } + + mgr := b.activeAssets() + if mgr != nil && mgr.Disposed() { + return nil, errors.New("mcp: asset manager is disposed") + } + + var groups []AssetGroupSummary + if mgr != nil { + for _, gs := range mgr.GroupStats() { + summary := AssetGroupSummary{ + Name: gs.Name, + Source: "manager", + State: gs.State, + Loaded: gs.Loaded, + Total: gs.Total, + Bytes: gs.Bytes, + Error: gs.Error, + Assets: make([]AssetEntry, 0, len(gs.Assets)), + } + for _, a := range gs.Assets { + summary.Assets = append(summary.Assets, AssetEntry{ + Key: a.Name, + Kind: a.Kind, + URI: a.URI, + ImageURI: a.ImageURI, + Loaded: a.Loaded, + Bytes: a.Bytes, + Frames: a.Frames, + }) + } + slices.SortFunc(summary.Assets, func(a, b AssetEntry) int { + return cmp.Compare(a.Key, b.Key) + }) + groups = append(groups, summary) + } + } + + if b.cfg.Resources != nil { + if paths := b.cfg.Resources.Paths(); len(paths) > 0 { + summary := AssetGroupSummary{ + Name: "resources", + Source: "resources", + State: assets.StateLoaded, + Loaded: len(paths), + Total: len(paths), + Assets: make([]AssetEntry, 0, len(paths)), + } + for _, p := range paths { + kind := "resource" + if r, err := b.cfg.Resources.Load(p); err == nil && r != nil { + kind = string(r.Kind()) + } + summary.Assets = append(summary.Assets, AssetEntry{ + Key: p, + Kind: kind, + URI: p, + Loaded: true, + }) + } + groups = append(groups, summary) + } + } + + if b.cfg.Shaders != nil { + if names := b.cfg.Shaders.ShaderNames(); len(names) > 0 { + summary := AssetGroupSummary{ + Name: "shaders", + Source: "shaders", + State: assets.StateLoaded, + Loaded: len(names), + Total: len(names), + Assets: make([]AssetEntry, 0, len(names)), + } + for _, name := range names { + p, _ := b.cfg.Shaders.ShaderPath(name) + summary.Assets = append(summary.Assets, AssetEntry{ + Key: name, + Kind: "shader", + URI: p, + Loaded: true, + }) + } + groups = append(groups, summary) + } + } + + if b.cfg.Materials != nil { + if names := b.cfg.Materials.MaterialNames(); len(names) > 0 { + summary := AssetGroupSummary{ + Name: "materials", + Source: "materials", + State: assets.StateLoaded, + Loaded: len(names), + Total: len(names), + Assets: make([]AssetEntry, 0, len(names)), + } + for _, name := range names { + p, _ := b.cfg.Materials.MaterialPath(name) + summary.Assets = append(summary.Assets, AssetEntry{ + Key: name, + Kind: "material", + URI: p, + Loaded: true, + }) + } + groups = append(groups, summary) + } + } + + if b.customAssets != nil && len(b.customAssets.entries) > 0 { + byGroup := make(map[string]*AssetGroupSummary) + var groupNames []string + for _, key := range b.customAssets.order { + ca := b.customAssets.entries[key] + gs, ok := byGroup[ca.Group] + if !ok { + gs = &AssetGroupSummary{ + Name: ca.Group, + Source: "custom", + State: assets.StateLoaded, + Assets: []AssetEntry{}, + } + byGroup[ca.Group] = gs + groupNames = append(groupNames, ca.Group) + } + var sz int64 + if ca.Bytes != nil { + sz = max(0, ca.Bytes()) + } + var frames int + if ca.Frames != nil { + frames = max(0, ca.Frames()) + } + gs.Loaded++ + gs.Total++ + gs.Bytes += sz + gs.Assets = append(gs.Assets, AssetEntry{ + Key: ca.Key, + Kind: ca.Kind, + URI: ca.URI, + Loaded: true, + Bytes: sz, + Frames: frames, + }) + } + slices.Sort(groupNames) + for _, name := range groupNames { + groups = append(groups, *byGroup[name]) + } + } + + // Deterministic ordering by group name, then source. + slices.SortFunc(groups, func(a, b AssetGroupSummary) int { + if c := cmp.Compare(a.Name, b.Name); c != 0 { + return c + } + return cmp.Compare(a.Source, b.Source) + }) + + filtered := make([]AssetGroupSummary, 0, len(groups)) + var ( + totalAssets int + totalBytes int64 + ) + for _, g := range groups { + if args.Group != "" && g.Name != args.Group { + continue + } + if args.State != "" && g.State != args.State { + continue + } + if args.Kind != "" { + matched := make([]AssetEntry, 0, len(g.Assets)) + var bytes int64 + var loaded int + for _, a := range g.Assets { + if a.Kind != args.Kind { + continue + } + matched = append(matched, a) + bytes += a.Bytes + if a.Loaded { + loaded++ + } + } + if len(matched) == 0 { + continue + } + g.Assets = matched + g.Bytes = bytes + g.Loaded = loaded + g.Total = len(matched) + } + totalAssets += len(g.Assets) + totalBytes += g.Bytes + filtered = append(filtered, g) + } + + res := AssetsListResult{ + GroupCount: len(filtered), + AssetCount: totalAssets, + TotalBytes: totalBytes, + Groups: filtered, + } + if mgr != nil { + res.Revision = mgr.Revision() + } + return res, nil +} + +type assetReloadArgs struct { + Key string `json:"key"` + Group string `json:"group"` + All bool `json:"all"` +} + +func (b *Bridge) handleAssetReload(ctx context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[assetReloadArgs](raw) + if err != nil { + return nil, err + } + key := strings.TrimSpace(args.Key) + if args.All && key != "" { + return nil, errors.New("mcp: key and all cannot both be set") + } + if !args.All && key == "" { + return nil, errors.New("mcp: key is required (or set all: true)") + } + if !b.hasAnyReloadSource() { + return nil, errors.New("mcp: no asset manager or reloader configured") + } + + mgr := b.activeAssets() + if mgr != nil && mgr.Disposed() { + return nil, errors.New("mcp: asset manager is disposed") + } + + start := time.Now() + if args.All { + if !b.hasAnyAssetSource() { + return nil, errors.New("mcp: all: true needs an asset manager, reloader or registered asset; Config.ReloadAsset reloads a single key only") + } + return b.reloadAllAssets(ctx, mgr, args.Group, start) + } + + if args.Group != "" && !b.groupExists(mgr, args.Group) { + return nil, fmt.Errorf("mcp: asset group %q not found", args.Group) + } + + var ( + items []ReloadedItem + errs []error + ) + + // 1. assets.Manager + if mgr != nil && (args.Group == "" || hasManagerGroup(mgr, args.Group)) { + reloaded, err := mgr.ReloadAsset(ctx, args.Group, key) + if err != nil && len(reloaded) == 0 { + return nil, err + } + for _, r := range reloaded { + items = append(items, reloadedItem(r)) + if r.Err != nil { + errs = append(errs, r.Err) + } + } + } + + // 2. Registered custom assets + if b.customAssets != nil { + for _, caKey := range b.customAssets.order { + ca := b.customAssets.entries[caKey] + if args.Group != "" && ca.Group != args.Group { + continue + } + if !matchCustomAsset(ca, key) { + continue + } + item, err := reloadCustomAsset(ctx, ca) + items = append(items, item) + if err != nil { + errs = append(errs, err) + } + } + } + + // 3. hotreload.MaterialReloader + if b.cfg.Materials != nil && (args.Group == "" || args.Group == "materials") { + if p, sz, tracked, err := b.cfg.Materials.ReloadMaterialFile(key); tracked { + item := ReloadedItem{ + Key: key, + Group: "materials", + Kind: "material", + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + // 4. hotreload.ShaderReloader + if b.cfg.Shaders != nil && (args.Group == "" || args.Group == "shaders") { + if p, sz, tracked, err := b.cfg.Shaders.ReloadShaderFile(key); tracked { + item := ReloadedItem{ + Key: key, + Group: "shaders", + Kind: "shader", + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + // 5. resource.Library + if b.cfg.Resources != nil && (args.Group == "" || args.Group == "resources") { + resKey := normalizeRelKey(key) + if sz, loaded, err := b.cfg.Resources.ReloadFile(resKey); loaded { + kind := "resource" + if r, loadErr := b.cfg.Resources.Load(resKey); loadErr == nil && r != nil { + kind = string(r.Kind()) + } + item := ReloadedItem{ + Key: resKey, + Group: "resources", + Kind: kind, + URI: resKey, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + // 6. Custom ReloadAsset fallback hook + if len(items) == 0 { + if b.cfg.ReloadAsset != nil { + err := b.cfg.ReloadAsset(ctx, key) + res := AssetReloadResult{ + Reloaded: err == nil, + Key: key, + Group: args.Group, + DurationMS: elapsedMS(start), + } + if mgr != nil { + res.Revision = mgr.Revision() + } + if err != nil { + res.Error = err.Error() + } + return res, nil + } + if args.Group != "" { + return nil, fmt.Errorf("mcp: asset %q not found in group %q", key, args.Group) + } + return nil, fmt.Errorf("mcp: asset %q not found", key) + } + + res := AssetReloadResult{ + Reloaded: len(errs) == 0 && anyReloaded(items), + Key: key, + Group: args.Group, + DurationMS: elapsedMS(start), + Items: items, + } + var totalBytes int64 + for _, it := range items { + totalBytes += it.Bytes + } + res.Bytes = totalBytes + if len(items) == 1 { + res.Key = items[0].Key + res.Group = items[0].Group + res.Kind = items[0].Kind + } else if res.Group == "" { + firstGroup := items[0].Group + sameGroup := true + for _, it := range items[1:] { + if it.Group != firstGroup { + sameGroup = false + break + } + } + if sameGroup { + res.Group = firstGroup + } + } + if mgr != nil { + res.Revision = mgr.Revision() + } + if len(errs) > 0 { + res.Error = errors.Join(errs...).Error() + } + return res, nil +} + +func (b *Bridge) reloadAllAssets(ctx context.Context, mgr *assets.Manager, groupFilter string, start time.Time) (any, error) { + if groupFilter != "" && !b.groupExists(mgr, groupFilter) { + return nil, fmt.Errorf("mcp: asset group %q not found", groupFilter) + } + var ( + items []ReloadedItem + errs []error + ) + + if mgr != nil { + groupNames := mgr.GroupNames() + slices.Sort(groupNames) + for _, gName := range groupNames { + if groupFilter != "" && gName != groupFilter { + continue + } + g, ok := mgr.LookupGroup(gName) + if !ok || g.Stats().State != assets.StateLoaded { + continue + } + reloaded, _ := mgr.ReloadGroup(ctx, gName) + for _, r := range reloaded { + items = append(items, reloadedItem(r)) + if r.Err != nil { + errs = append(errs, r.Err) + } + } + } + } + + if b.customAssets != nil { + for _, caKey := range b.customAssets.order { + ca := b.customAssets.entries[caKey] + if groupFilter != "" && ca.Group != groupFilter { + continue + } + if ca.Reload == nil { + continue + } + item, err := reloadCustomAsset(ctx, ca) + items = append(items, item) + if err != nil { + errs = append(errs, err) + } + } + } + + if b.cfg.Shaders != nil && (groupFilter == "" || groupFilter == "shaders") { + seen := make(map[string]bool) + for _, name := range b.cfg.Shaders.ShaderNames() { + p, ok := b.cfg.Shaders.ShaderPath(name) + if !ok || seen[p] { + continue + } + seen[p] = true + p, sz, tracked, err := b.cfg.Shaders.ReloadShaderFile(name) + if !tracked { + continue + } + item := ReloadedItem{ + Key: name, + Group: "shaders", + Kind: "shader", + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + if b.cfg.Materials != nil && (groupFilter == "" || groupFilter == "materials") { + seen := make(map[string]bool) + for _, name := range b.cfg.Materials.MaterialNames() { + p, ok := b.cfg.Materials.MaterialPath(name) + if !ok || seen[p] { + continue + } + seen[p] = true + p, sz, tracked, err := b.cfg.Materials.ReloadMaterialFile(name) + if !tracked { + continue + } + item := ReloadedItem{ + Key: name, + Group: "materials", + Kind: "material", + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + if b.cfg.Resources != nil && (groupFilter == "" || groupFilter == "resources") { + for _, p := range b.cfg.Resources.Paths() { + sz, loaded, err := b.cfg.Resources.ReloadFile(p) + if !loaded { + continue + } + kind := "resource" + if r, loadErr := b.cfg.Resources.Load(p); loadErr == nil && r != nil { + kind = string(r.Kind()) + } + item := ReloadedItem{ + Key: p, + Group: "resources", + Kind: kind, + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + var totalBytes int64 + for _, it := range items { + totalBytes += it.Bytes + } + res := AssetReloadResult{ + Reloaded: len(errs) == 0 && anyReloaded(items), + Group: groupFilter, + Bytes: totalBytes, + DurationMS: elapsedMS(start), + Items: items, + } + if mgr != nil { + res.Revision = mgr.Revision() + } + if len(errs) > 0 { + res.Error = errors.Join(errs...).Error() + } + return res, nil +} + +type assetsReloadGroupArgs struct { + Group string `json:"group"` +} + +func (b *Bridge) handleAssetsReloadGroup(ctx context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[assetsReloadGroupArgs](raw) + if err != nil { + return nil, err + } + groupName := strings.TrimSpace(args.Group) + if groupName == "" { + return nil, errors.New("mcp: group is required") + } + if !b.hasAnyAssetSource() { + return nil, errors.New("mcp: no asset manager configured") + } + + mgr := b.activeAssets() + if mgr != nil && mgr.Disposed() { + return nil, errors.New("mcp: asset manager is disposed") + } + + start := time.Now() + var ( + items []ReloadedItem + errs []error + matched bool + ) + + if hasManagerGroup(mgr, groupName) { + matched = true + reloaded, err := mgr.ReloadGroup(ctx, groupName) + if err != nil && len(reloaded) == 0 { + return nil, fmt.Errorf("mcp: %w", err) + } + for _, r := range reloaded { + items = append(items, reloadedItem(r)) + if r.Err != nil { + errs = append(errs, r.Err) + } + } + } + + if b.customAssets != nil { + for _, caKey := range b.customAssets.order { + ca := b.customAssets.entries[caKey] + if ca.Group != groupName { + continue + } + matched = true + item, err := reloadCustomAsset(ctx, ca) + items = append(items, item) + if err != nil { + errs = append(errs, err) + } + } + } + + if groupName == "shaders" && b.cfg.Shaders != nil && len(b.cfg.Shaders.ShaderNames()) > 0 { + matched = true + seen := make(map[string]bool) + for _, name := range b.cfg.Shaders.ShaderNames() { + p, ok := b.cfg.Shaders.ShaderPath(name) + if !ok || seen[p] { + continue + } + seen[p] = true + p, sz, tracked, err := b.cfg.Shaders.ReloadShaderFile(name) + if !tracked { + continue + } + item := ReloadedItem{ + Key: name, + Group: "shaders", + Kind: "shader", + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + if groupName == "materials" && b.cfg.Materials != nil && len(b.cfg.Materials.MaterialNames()) > 0 { + matched = true + seen := make(map[string]bool) + for _, name := range b.cfg.Materials.MaterialNames() { + p, ok := b.cfg.Materials.MaterialPath(name) + if !ok || seen[p] { + continue + } + seen[p] = true + p, sz, tracked, err := b.cfg.Materials.ReloadMaterialFile(name) + if !tracked { + continue + } + item := ReloadedItem{ + Key: name, + Group: "materials", + Kind: "material", + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + if groupName == "resources" && b.cfg.Resources != nil && len(b.cfg.Resources.Paths()) > 0 { + matched = true + for _, p := range b.cfg.Resources.Paths() { + sz, loaded, err := b.cfg.Resources.ReloadFile(p) + if !loaded { + continue + } + kind := "resource" + if r, loadErr := b.cfg.Resources.Load(p); loadErr == nil && r != nil { + kind = string(r.Kind()) + } + item := ReloadedItem{ + Key: p, + Group: "resources", + Kind: kind, + URI: p, + Bytes: sz, + } + if err != nil { + item.Error = err.Error() + errs = append(errs, err) + } + items = append(items, item) + } + } + + if !matched { + return nil, fmt.Errorf("mcp: asset group %q not found", groupName) + } + + if items == nil { + items = []ReloadedItem{} + } + var ( + totalBytes int64 + succeeded int + failed int + skipped int + ) + for _, it := range items { + totalBytes += it.Bytes + switch { + case it.Error != "": + failed++ + case it.Skipped != "": + skipped++ + default: + succeeded++ + } + } + + res := AssetsReloadGroupResult{ + Group: groupName, + Reloaded: failed == 0, + Count: succeeded, + Failed: failed, + Skipped: skipped, + Bytes: totalBytes, + DurationMS: elapsedMS(start), + Items: items, + } + if mgr != nil { + res.Revision = mgr.Revision() + } + if len(errs) > 0 { + res.Error = errors.Join(errs...).Error() + } + return res, nil +} + +func hasManagerGroup(mgr *assets.Manager, name string) bool { + if mgr == nil { + return false + } + _, ok := mgr.LookupGroup(name) + return ok +} + +func (b *Bridge) groupExists(mgr *assets.Manager, name string) bool { + if hasManagerGroup(mgr, name) { + return true + } + if name == "shaders" && b.cfg.Shaders != nil && len(b.cfg.Shaders.ShaderNames()) > 0 { + return true + } + if name == "materials" && b.cfg.Materials != nil && len(b.cfg.Materials.MaterialNames()) > 0 { + return true + } + if name == "resources" && b.cfg.Resources != nil && len(b.cfg.Resources.Paths()) > 0 { + return true + } + if b.customAssets != nil { + for _, ca := range b.customAssets.entries { + if ca.Group == name { + return true + } + } + } + return false +} + +func matchCustomAsset(ca CustomAsset, key string) bool { + if ca.Key == key { + return true + } + if ca.URI == "" { + return false + } + if ca.URI == key { + return true + } + return normalizeRelKey(ca.URI) == normalizeRelKey(key) +} + +func reloadCustomAsset(ctx context.Context, ca CustomAsset) (ReloadedItem, error) { + item := ReloadedItem{ + Key: ca.Key, + Group: ca.Group, + Kind: ca.Kind, + URI: ca.URI, + } + var err error + if ca.Reload == nil { + err = fmt.Errorf("mcp: asset %q does not support reload", ca.Key) + } else { + err = ca.Reload(ctx) + } + if ca.Bytes != nil { + item.Bytes = max(0, ca.Bytes()) + } + if ca.Frames != nil { + item.Frames = max(0, ca.Frames()) + } + if err != nil { + item.Error = err.Error() + } + return item, err +} + +func normalizeRelKey(k string) string { + k = strings.TrimPrefix(k, "asset:") + k = strings.ReplaceAll(k, "\\", "/") + return strings.TrimPrefix(path.Clean("/"+k), "/") +} + +func elapsedMS(start time.Time) float64 { + return float64(time.Since(start).Microseconds()) / 1000.0 +} diff --git a/packages/game/mcp/assets_test.go b/packages/game/mcp/assets_test.go new file mode 100644 index 00000000..a6717ede --- /dev/null +++ b/packages/game/mcp/assets_test.go @@ -0,0 +1,602 @@ +package mcp_test + +import ( + "context" + "errors" + "image" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/assets" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/resource" + "github.com/nsgo-dev/game/packages/game/sprite" + "github.com/nsgo-dev/game/packages/game/tooling/hotreload" + "github.com/nsgo-dev/nsgo/audio" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const ( + atlasV1 = `{ + "frames": { + "idle.png": {"frame": {"x": 0, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}}, + "run.png": {"frame": {"x": 16, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}} + }, + "meta": {"scale": "1"} +}` + atlasV2 = `{ + "frames": { + "idle.png": {"frame": {"x": 0, "y": 0, "w": 24, "h": 32}, "sourceSize": {"w": 24, "h": 32}}, + "run.png": {"frame": {"x": 24, "y": 0, "w": 24, "h": 32}, "sourceSize": {"w": 24, "h": 32}}, + "jump.png": {"frame": {"x": 48, "y": 0, "w": 24, "h": 32}, "sourceSize": {"w": 24, "h": 32}} + }, + "meta": {"scale": "1"} +}` + atlasBroken = `{"frames": [` + + validWGSLV1 = ` +@vertex fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4f { + return vec4f(0.0, 0.0, 0.0, 1.0); +} +@fragment fn fs_main() -> @location(0) vec4f { + return vec4f(1.0, 0.0, 0.0, 1.0); +} +` + validWGSLV2 = ` +@vertex fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4f { + return vec4f(0.0, 0.0, 0.0, 1.0); +} +@fragment fn fs_main() -> @location(0) vec4f { + return vec4f(0.0, 1.0, 0.0, 1.0); +} +` + brokenWGSL = `@vertex fn vs_main( -> broken` + + validMaterialV1 = `version: 1 +name: hero_mat +shader: shaders/hero.wgsl +blend: opaque +scalars: + roughness: 0.4 +` + validMaterialV2 = `version: 1 +name: hero_mat +shader: shaders/hero.wgsl +blend: alpha +scalars: + roughness: 0.85 +` + brokenMaterial = `version: 99 +unknownField: true +` + validResourceV1 = `type: curve +version: 1 +keys: + - time: 0 + value: 0 + - time: 1 + value: 1 +` + validResourceV2 = `type: curve +version: 1 +keys: + - time: 0 + value: 0 + - time: 1 + value: 2.5 +` +) + +func writeDiskFile(t *testing.T, root, rel, content string) string { + t.Helper() + full := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return full +} + +// TestAssetsListAndAtlasHotReload verifies listing asset groups/memory and reloading an on-disk sprite atlas through MCP updates the live running game in place. +func TestAssetsListAndAtlasHotReload(t *testing.T) { + dir := t.TempDir() + writeDiskFile(t, dir, "sprites/hero.json", atlasV1) + writeDiskFile(t, dir, "sprites/hero.png", "png-bytes-v1") + writeDiskFile(t, dir, "data/config.txt", "difficulty=normal") + writeDiskFile(t, dir, "data/table.txt", "level-1-data") + + var ( + cx *core.Scope + mgr *assets.Manager + liveAtlas *sprite.Atlas + draws int + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + mgr = assets.NewManager(cx, assets.WithFS(os.DirFS(dir))) + + // Add groups out of alphabetical order to verify deterministic sorting. + mgr.Group("level1"). + AddAtlas("hero", "asset:sprites/hero.json", core.ImageSource{ + URI: "asset:sprites/hero.png", + Size: core.Size{Width: 32, Height: 16}, + }). + AddImage("bg", core.ImageSource{ + URI: "asset:images/bg.png", + Pixels: image.NewRGBA(image.Rect(0, 0, 16, 16)), + }). + AddSound("jump", audio.Source{URI: "asset:sounds/jump.wav"}). + AddBytes("config", "asset:data/config.txt"). + AddCustom("table", "asset:data/table.txt", func(b []byte) (any, error) { + return strings.ToUpper(string(b)), nil + }, nil) + + mgr.Group("boss"). + AddBytes("boss_script", "asset:data/table.txt") + + mgr.LoadGroup("level1", func(err error) { + if err != nil { + t.Errorf("LoadGroup(level1): %v", err) + } + }) + + if _, err := mcp.Attach(cx, mcp.Config{Assets: mgr}); err != nil { + t.Fatal(err) + } + return core.Canvas{ + Style: core.Style{Width: core.Pt(64), Height: core.Pt(64)}, + Draw: func(*core.Drawing, core.Size) { + _ = mgr.Revision() + draws++ + }, + } + }, + nsgotest.Environment(core.Environment{Audio: true}), + func(a *nsgotest.App) { + a.AudioDurations = map[string]time.Duration{ + "asset:sounds/jump.wav": 200 * time.Millisecond, + } + a.ImageSizes = map[string]core.Size{ + "asset:sprites/hero.png": {Width: 32, Height: 16}, + } + }, + ) + app.WaitUntil(time.Second, func() bool { return mgr.Group("level1").Done() }) + + // Grab the live *sprite.Atlas pointer held by the running game. + app.Post(func() { + var ok bool + liveAtlas, ok = mgr.Atlas("hero") + if !ok || liveAtlas == nil { + t.Fatal("hero atlas not loaded") + } + }) + app.Settle() + + if f := liveAtlas.Frames["idle.png"]; f.W != 16 || f.H != 16 { + t.Fatalf("initial idle frame = %+v, want 16x16", f) + } + + // 1. List asset groups: sorted deterministically ("boss", "level1") with accurate states & memory. + listRes := callTool[mcp.AssetsListResult](t, app, cx, mcp.ToolAssetsList, nil) + if listRes.GroupCount != 2 || len(listRes.Groups) != 2 { + t.Fatalf("groups = %+v, want 2", listRes) + } + if listRes.Groups[0].Name != "boss" || listRes.Groups[0].State != assets.StateUnloaded || listRes.Groups[0].Bytes != 0 { + t.Fatalf("groups[0] = %+v, want unloaded boss group with 0 bytes", listRes.Groups[0]) + } + lvl := listRes.Groups[1] + if lvl.Name != "level1" || lvl.State != assets.StateLoaded || lvl.Loaded != 5 || lvl.Total != 5 { + t.Fatalf("groups[1] = %+v, want loaded level1 (5/5)", lvl) + } + if lvl.Bytes <= 0 || listRes.TotalBytes != lvl.Bytes { + t.Fatalf("memory bytes = group:%d total:%d, want >0 and equal", lvl.Bytes, listRes.TotalBytes) + } + // Verify assets within level1 are sorted by key and have accurate kinds & bytes. + wantKeys := []string{"bg", "config", "hero", "jump", "table"} + for i, wantKey := range wantKeys { + if lvl.Assets[i].Key != wantKey || !lvl.Assets[i].Loaded || lvl.Assets[i].Bytes <= 0 { + t.Fatalf("level1.Assets[%d] = %+v, want loaded key=%q bytes>0", i, lvl.Assets[i], wantKey) + } + } + // bg has a 16x16 RGBA pixel buffer => exactly 1024 bytes. + if lvl.Assets[0].Bytes != 16*16*4 { + t.Fatalf("bg bytes = %d, want %d", lvl.Assets[0].Bytes, 16*16*4) + } + // config is raw bytes "difficulty=normal" => 17 bytes. + if lvl.Assets[1].Bytes != int64(len("difficulty=normal")) { + t.Fatalf("config bytes = %d, want %d", lvl.Assets[1].Bytes, len("difficulty=normal")) + } + // hero atlas has 2 frames initially. + if lvl.Assets[2].Kind != "atlas" || lvl.Assets[2].Frames != 2 { + t.Fatalf("hero entry = %+v, want kind=atlas frames=2", lvl.Assets[2]) + } + + // Filter by state and kind. + loadedOnly := callTool[mcp.AssetsListResult](t, app, cx, mcp.ToolAssetsList, map[string]any{ + "state": "loaded", + "kind": "atlas", + }) + if loadedOnly.GroupCount != 1 || loadedOnly.AssetCount != 1 || loadedOnly.Groups[0].Assets[0].Key != "hero" { + t.Fatalf("filtered list = %+v", loadedOnly) + } + + // 2. Edit sprites/hero.json on disk and reload through MCP -> live *sprite.Atlas updates in place! + writeDiskFile(t, dir, "sprites/hero.json", atlasV2) + drawsBefore := draws + + reloadRes := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{ + "key": "hero", + }) + if !reloadRes.Reloaded || reloadRes.Error != "" || reloadRes.Key != "hero" || reloadRes.Group != "level1" || reloadRes.Kind != "atlas" { + t.Fatalf("reload hero = %+v", reloadRes) + } + if reloadRes.Bytes <= 0 || reloadRes.DurationMS < 0 || reloadRes.Revision != 1 { + t.Fatalf("reload hero metrics = %+v", reloadRes) + } + // The exact live *sprite.Atlas pointer held by the game now has the new 24x32 frames + jump.png! + if len(liveAtlas.Frames) != 3 { + t.Fatalf("liveAtlas frame count = %d, want 3", len(liveAtlas.Frames)) + } + if f := liveAtlas.Frames["idle.png"]; f.W != 24 || f.H != 32 { + t.Fatalf("liveAtlas idle frame = %+v, want 24x32", f) + } + if f, ok := liveAtlas.Frames["jump.png"]; !ok || f.X != 48 || f.W != 24 || f.H != 32 { + t.Fatalf("liveAtlas jump frame = (%+v, %v), want x=48 24x32", f, ok) + } + // Canvas reading mgr.Revision() redrew automatically! + if draws <= drawsBefore { + t.Fatalf("expected canvas to redraw after MCP atlas reload (before=%d after=%d)", drawsBefore, draws) + } + + // 3. Reload atlas image specifically by relative path and verify image bytes updated on liveAtlas. + writeDiskFile(t, dir, "sprites/hero.png", "png-bytes-v2-updated") + imgReload := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{ + "key": "sprites/hero.png", + }) + if !imgReload.Reloaded || imgReload.Error != "" { + t.Fatalf("reload hero.png = %+v", imgReload) + } + if string(liveAtlas.Image.Data) != "png-bytes-v2-updated" { + t.Fatalf("liveAtlas.Image.Data = %q, want %q", liveAtlas.Image.Data, "png-bytes-v2-updated") + } + + // 4. Write broken JSON to disk and reload through MCP: returns structured error, keeps liveAtlas intact! + writeDiskFile(t, dir, "sprites/hero.json", atlasBroken) + brokenRes := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{ + "key": "asset:sprites/hero.json", + }) + if brokenRes.Reloaded || brokenRes.Error == "" || !strings.Contains(brokenRes.Error, "hero") { + t.Fatalf("broken reload = %+v, want reloaded=false with error", brokenRes) + } + // Live atlas kept its previous working 3 frames! + if len(liveAtlas.Frames) != 3 || liveAtlas.Frames["idle.png"].W != 24 { + t.Fatalf("broken reload corrupted liveAtlas: %+v", liveAtlas.Frames) + } + + // 5. Fix JSON on disk and update data/config.txt & data/table.txt, then call game_assets_reload_group! + writeDiskFile(t, dir, "sprites/hero.json", atlasV1) + writeDiskFile(t, dir, "data/config.txt", "difficulty=hardcore") + writeDiskFile(t, dir, "data/table.txt", "level-1-remastered") + + groupRes := callTool[mcp.AssetsReloadGroupResult](t, app, cx, mcp.ToolAssetsReloadGroup, map[string]any{ + "group": "level1", + }) + // "bg" names asset:images/bg.png, which is not in dir, and "jump" is a sound, so both are skipped rather than failed while hero, config and table reload. + if groupRes.Group != "level1" || groupRes.Count != 3 || groupRes.Failed != 0 || groupRes.Skipped != 2 || !groupRes.Reloaded { + t.Fatalf("group reload (with missing bg file) = %+v", groupRes) + } + skipped := map[string]string{} + for _, it := range groupRes.Items { + if it.Skipped != "" { + skipped[it.Key] = it.Skipped + } + } + if skipped["bg"] != assets.SkippedNoFile || skipped["jump"] != assets.SkippedSound { + t.Fatalf("group reload skipped = %v", skipped) + } + + // Reloading the missing image by key reports the read error, and reloading the sound by key reports it as skipped, not reloaded. + bgRes := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "bg"}) + if bgRes.Reloaded || bgRes.Error == "" { + t.Fatalf("reload missing bg = %+v, want an error", bgRes) + } + jumpRes := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "jump"}) + if jumpRes.Reloaded || jumpRes.Error != "" || len(jumpRes.Items) != 1 || jumpRes.Items[0].Skipped != assets.SkippedSound { + t.Fatalf("reload jump = %+v, want skipped without error", jumpRes) + } + if len(liveAtlas.Frames) != 2 || liveAtlas.Frames["idle.png"].W != 16 { + t.Fatalf("liveAtlas after group reload = %+v, want V1 (2 frames, 16x16)", liveAtlas.Frames) + } + var ( + gotConfig []byte + gotTable any + ) + app.Post(func() { + gotConfig, _ = mgr.Bytes("config") + gotTable, _ = mgr.Get("table") + }) + app.Settle() + if string(gotConfig) != "difficulty=hardcore" { + t.Fatalf("config after group reload = %q", gotConfig) + } + if gotTable != "LEVEL-1-REMASTERED" { + t.Fatalf("custom table after group reload = %v, want LEVEL-1-REMASTERED", gotTable) + } + + // Provide images/bg.png on disk and verify the group reload now replaces bg too. + writeDiskFile(t, dir, "images/bg.png", "bg-png-v2") + cleanGroupRes := callTool[mcp.AssetsReloadGroupResult](t, app, cx, mcp.ToolAssetsReloadGroup, map[string]any{ + "group": "level1", + }) + if !cleanGroupRes.Reloaded || cleanGroupRes.Failed != 0 || cleanGroupRes.Count != 4 || cleanGroupRes.Skipped != 1 || cleanGroupRes.Error != "" { + t.Fatalf("clean group reload = %+v", cleanGroupRes) + } +} + +// TestShadersMaterialsResourcesAndCustomAtlasReload verifies MCP listing and reloading across hotreload.ShaderReloader, hotreload.MaterialReloader, resource.Library, standalone RegisterAtlas, and Config.ReloadAsset fallback hook. +func TestShadersMaterialsResourcesAndCustomAtlasReload(t *testing.T) { + dir := t.TempDir() + writeDiskFile(t, dir, "shaders/hero.wgsl", validWGSLV1) + writeDiskFile(t, dir, "materials/hero.material.yaml", validMaterialV1) + writeDiskFile(t, dir, "resources/ease.yaml", validResourceV1) + writeDiskFile(t, dir, "atlases/ui.json", atlasV1) + + fsys := os.DirFS(dir) + resLib := resource.NewLibrary(fsys) + loadedCurve, err := resource.LoadAs[*resource.Curve](resLib, "resources/ease.yaml") + if err != nil { + t.Fatal(err) + } + + standaloneAtlas, err := sprite.LoadAtlas(core.Src("asset:atlases/ui.png"), []byte(atlasV1)) + if err != nil { + t.Fatal(err) + } + + var ( + cx *core.Scope + shaders *hotreload.ShaderReloader + mats *hotreload.MaterialReloader + hookKeys []string + hookErr error + ) + + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + shaders = hotreload.NewShaderReloader(cx, nil, hotreload.WithShaderDir(dir)) + if _, err := shaders.RegisterShader("hero_shader", "shaders/hero.wgsl"); err != nil { + t.Fatal(err) + } + mats = hotreload.NewMaterialReloader(cx, shaders, hotreload.WithMaterialDir(dir)) + if _, _, err := mats.Register("hero_mat", "materials/hero.material.yaml", nil); err != nil { + t.Fatal(err) + } + + b := mcp.New(mcp.Config{ + Resources: resLib, + Shaders: shaders, + Materials: mats, + ReloadAsset: func(_ context.Context, key string) error { + hookKeys = append(hookKeys, key) + return hookErr + }, + }) + if err := b.RegisterAtlas("ui_atlas", "ui", "atlases/ui.json", standaloneAtlas, func(_ context.Context, p string) ([]byte, error) { + return os.ReadFile(filepath.Join(dir, filepath.FromSlash(p))) + }); err != nil { + t.Fatal(err) + } + if err := b.Attach(cx); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // 1. game_assets_list surfaces materials, resources, shaders, and custom ui groups in sorted order. + listed := callTool[mcp.AssetsListResult](t, app, cx, mcp.ToolAssetsList, nil) + if listed.GroupCount != 4 { + t.Fatalf("groups = %+v, want 4 (materials, resources, shaders, ui)", listed) + } + wantGroups := []string{"materials", "resources", "shaders", "ui"} + for i, want := range wantGroups { + if listed.Groups[i].Name != want { + t.Fatalf("groups[%d].Name = %q, want %q", i, listed.Groups[i].Name, want) + } + } + + // 2. Reload standalone atlas after updating disk file -> updates standaloneAtlas in place. + writeDiskFile(t, dir, "atlases/ui.json", atlasV2) + uiReload := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "ui_atlas"}) + if !uiReload.Reloaded || uiReload.Error != "" || len(standaloneAtlas.Frames) != 3 || standaloneAtlas.Frames["idle.png"].W != 24 { + t.Fatalf("standalone atlas reload = %+v, frames=%+v", uiReload, standaloneAtlas.Frames) + } + + // 3. Reload valid shader edit, then broken shader edit (must report structured error & keep previous shader alive). + writeDiskFile(t, dir, "shaders/hero.wgsl", validWGSLV2) + shReload := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "hero_shader"}) + if !shReload.Reloaded || shReload.Kind != "shader" || shaders.Revision() != 1 { + t.Fatalf("shader reload = %+v, rev=%d", shReload, shaders.Revision()) + } + writeDiskFile(t, dir, "shaders/hero.wgsl", brokenWGSL) + shBroken := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "shaders/hero.wgsl"}) + if shBroken.Reloaded || shBroken.Error == "" { + t.Fatalf("broken shader reload = %+v, want reloaded=false + error", shBroken) + } + if shaders.Shader("hero_shader") == nil { + t.Fatal("previous working shader was lost after compile error") + } + // Restore valid shader for subsequent reloads. + writeDiskFile(t, dir, "shaders/hero.wgsl", validWGSLV2) + + // 4. Reload valid material edit, then broken material YAML (keeps previous material active). + writeDiskFile(t, dir, "materials/hero.material.yaml", validMaterialV2) + matReload := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "hero_mat"}) + if !matReload.Reloaded || matReload.Kind != "material" { + t.Fatalf("material reload = %+v", matReload) + } + if def := mats.Material("hero_mat"); def == nil || def.Blend != "alpha" || def.Scalars["roughness"] != 0.85 { + t.Fatalf("reloaded material def = %+v", def) + } + writeDiskFile(t, dir, "materials/hero.material.yaml", brokenMaterial) + matBroken := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "hero_mat"}) + if matBroken.Reloaded || matBroken.Error == "" { + t.Fatalf("broken material reload = %+v", matBroken) + } + if def := mats.Material("hero_mat"); def == nil || def.Blend != "alpha" { + t.Fatalf("broken material overwrote working material: %+v", def) + } + writeDiskFile(t, dir, "materials/hero.material.yaml", validMaterialV2) + + // 5. Reload YAML resource in place via resource.Library. + writeDiskFile(t, dir, "resources/ease.yaml", validResourceV2) + resReload := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "resources/ease.yaml"}) + if !resReload.Reloaded || resReload.Group != "resources" { + t.Fatalf("resource reload = %+v", resReload) + } + if loadedCurve.Keys[1].Value != 2.5 { + t.Fatalf("live curve not updated in place: %+v", loadedCurve.Keys) + } + + // 6. Reload all=true reloads everything across all groups cleanly. + allRes := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"all": true}) + if !allRes.Reloaded || len(allRes.Items) != 4 || allRes.Error != "" { + t.Fatalf("reload all = %+v", allRes) + } + + // 7. Fallback ReloadAsset hook handles unknown keys (success and structured error). + hookRes := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "scenes/level1.scene.yaml"}) + if !hookRes.Reloaded || len(hookKeys) != 1 || hookKeys[0] != "scenes/level1.scene.yaml" { + t.Fatalf("fallback hook reload = %+v, keys=%v", hookRes, hookKeys) + } + hookErr = errors.New("scene parse failed at line 4") + hookFail := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "scenes/broken.scene.yaml"}) + if hookFail.Reloaded || !strings.Contains(hookFail.Error, "line 4") { + t.Fatalf("fallback hook failure = %+v", hookFail) + } +} + +func TestAssetsToolsValidationAndErrorCases(t *testing.T) { + var ( + cx *core.Scope + b *mcp.Bridge + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + var err error + b, err = mcp.Attach(cx, mcp.Config{}) + if err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Unconfigured asset manager / reloader returns clear errors. + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsList, nil); err == nil || !strings.Contains(err.Error(), "no asset manager") { + t.Fatalf("assets list unconfigured = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "hero"}); err == nil || !strings.Contains(err.Error(), "no asset manager") { + t.Fatalf("asset reload unconfigured = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsReloadGroup, map[string]any{"group": "level1"}); err == nil || !strings.Contains(err.Error(), "no asset manager") { + t.Fatalf("reload group unconfigured = %v", err) + } + + // Unknown JSON fields rejected on all three tools. + for _, tool := range []string{mcp.ToolAssetsList, mcp.ToolAssetReload, mcp.ToolAssetsReloadGroup} { + if _, err := callToolRaw(t, app, cx, tool, `{"bogus":true}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("%s unknown field = %v, want unknown field error", tool, err) + } + } + + // Missing required args / invalid combinations. + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsList, map[string]any{"state": "invalid"}); err == nil || !strings.Contains(err.Error(), "invalid asset state") { + t.Fatalf("invalid state = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, `{}`); err == nil || !strings.Contains(err.Error(), "key is required") { + t.Fatalf("missing key = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "hero", "all": true}); err == nil || !strings.Contains(err.Error(), "cannot both be set") { + t.Fatalf("key+all = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsReloadGroup, `{}`); err == nil || !strings.Contains(err.Error(), "group is required") { + t.Fatalf("missing group = %v", err) + } + + // Attach a live assets.Manager with an unloaded group, test not-found & not-loaded errors. + var mgr *assets.Manager + var childScope *core.Scope + app.Post(func() { + childScope = cx.Child() + mgr = assets.NewManager(childScope) + mgr.Group("unloaded_lvl").AddBytes("doc", "asset:doc.txt") + b.SetAssets(mgr) + }) + app.Settle() + + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "missing"}); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("missing asset = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "doc", "group": "no_such_group"}); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("missing group = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsReloadGroup, map[string]any{"group": "unloaded_lvl"}); err == nil || !strings.Contains(err.Error(), "not loaded") { + t.Fatalf("reloading unloaded group = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsReloadGroup, map[string]any{"group": "missing"}); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("reloading unknown group = %v", err) + } + + // Disposed manager returns clear error. + app.Post(func() { childScope.Dispose() }) + app.Settle() + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetsList, nil); err == nil || !strings.Contains(err.Error(), "disposed") { + t.Fatalf("disposed manager list = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "doc"}); err == nil || !strings.Contains(err.Error(), "disposed") { + t.Fatalf("disposed manager reload = %v", err) + } + + // Custom asset registration validation. + if err := (*mcp.Bridge)(nil).RegisterAsset(mcp.CustomAsset{Key: "a"}); !errors.Is(err, mcp.ErrNilBridge) { + t.Fatalf("nil bridge RegisterAsset = %v", err) + } + if err := b.RegisterAsset(mcp.CustomAsset{}); !errors.Is(err, mcp.ErrEmptyAssetKey) { + t.Fatalf("empty key RegisterAsset = %v", err) + } + if err := b.RegisterAsset(mcp.CustomAsset{Key: "dup"}); err != nil { + t.Fatal(err) + } + if err := b.RegisterAsset(mcp.CustomAsset{Key: "dup"}); !errors.Is(err, mcp.ErrDuplicateAsset) { + t.Fatalf("duplicate RegisterAsset = %v", err) + } + if err := b.RegisterAtlas("a", "g", "p.json", nil, nil); err == nil { + t.Fatal("expected error for nil atlas in RegisterAtlas") + } +} + +func TestAssetReloadAllNeedsMoreThanTheReloadAssetHook(t *testing.T) { + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + ReloadAsset: func(context.Context, string) error { return nil }, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + if _, err := callToolRaw(t, app, cx, mcp.ToolAssetReload, map[string]any{"all": true}); err == nil || !strings.Contains(err.Error(), "single key") { + t.Fatalf("reload all with only the ReloadAsset hook = %v, want an error", err) + } + res := callTool[mcp.AssetReloadResult](t, app, cx, mcp.ToolAssetReload, map[string]any{"key": "scenes/level1.scene.yaml"}) + if !res.Reloaded || res.Error != "" { + t.Fatalf("reload one key through the hook = %+v", res) + } +} diff --git a/packages/game/mcp/doc.go b/packages/game/mcp/doc.go index 51d150a0..11913bdf 100644 --- a/packages/game/mcp/doc.go +++ b/packages/game/mcp/doc.go @@ -36,6 +36,9 @@ // - game_perf_readout: read live frame timing (FPS, frame/update/draw costs and percentiles), draw statistics, allocations per frame, heap/GC counters, asset memory, and optional frame history or profiler zones matching the debug overlay. // - game_perf_zones: list named profiler timing zones sorted by recent per-frame cost. // - game_perf_reset: reset accumulated debug overlay frame timings, pushed draw statistics, profiler zones and GC monitor history. +// - game_assets_list: list loaded asset groups, asset keys/types, load states, and estimated memory usage in bytes. +// - game_asset_reload: reload a named asset, URI, or path (or all loaded assets) in place and report structured reload diagnostics. +// - game_assets_reload_group: reload every loaded asset in a named asset group in place. // // Components registered on an [entities.World] with [entities.RegisterCodec] are readable and editable automatically. Transient or non-saved components can also be exposed with [RegisterComponent], [RegisterComponentFunc], [RegisterMutableComponent] or [RegisterComponentEditor], and built-in [entities.Transform2D], [entities.WorldTransform2D] and [sceneformat.ObjectRef] components are surfaced automatically when present and not already registered under another name. Prefabs can be registered via [Config.Prefabs], [Bridge.RegisterPrefab], [Bridge.RegisterEntityPrefab] or [Bridge.RegisterScenePrefab]. // diff --git a/packages/game/mcp/example_test.go b/packages/game/mcp/example_test.go index 2adcf0c3..3b05b518 100644 --- a/packages/game/mcp/example_test.go +++ b/packages/game/mcp/example_test.go @@ -69,4 +69,7 @@ func ExampleNew() { // game_perf_readout // game_perf_zones // game_perf_reset + // game_assets_list + // game_asset_reload + // game_assets_reload_group } diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index e8862000..9421ce1a 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -2,6 +2,7 @@ package mcp import ( "bytes" + "context" "encoding" "encoding/json" "errors" @@ -14,12 +15,15 @@ import ( "strings" "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/assets" "github.com/nsgo-dev/game/packages/game/debug" "github.com/nsgo-dev/game/packages/game/entities" "github.com/nsgo-dev/game/packages/game/input" "github.com/nsgo-dev/game/packages/game/random" + "github.com/nsgo-dev/game/packages/game/resource" "github.com/nsgo-dev/game/packages/game/scene" "github.com/nsgo-dev/game/packages/game/screen" + "github.com/nsgo-dev/game/packages/game/tooling/hotreload" "github.com/nsgo-dev/nsgo/automation" "github.com/nsgo-dev/nsgo/core" ) @@ -144,6 +148,24 @@ type Config struct { // RenderStatsFunc supplies 3D per-frame render statistics (culling, batching, state switches, geometry and GPU memory). A game using game/render3d returns mcp.PerfRender3DStats(stats) for its latest render3d.RenderStats. RenderStatsFunc func() PerfRender3DStats + + // Assets is the game's asset manager for listing loaded asset groups/memory and reloading assets or groups. + Assets *assets.Manager + + // AssetsFunc dynamically resolves the active asset manager on each tool call. When non-nil and returning a non-nil manager, it overrides Assets. + AssetsFunc func() *assets.Manager + + // Resources is an optional resource.Library whose loaded YAML resources are listed and can be reloaded by path. + Resources *resource.Library + + // Shaders is an optional hotreload.ShaderReloader whose tracked shaders are listed and can be reloaded by name or path. + Shaders *hotreload.ShaderReloader + + // Materials is an optional hotreload.MaterialReloader whose tracked materials are listed and can be reloaded by name or path. + Materials *hotreload.MaterialReloader + + // ReloadAsset is an optional custom reload callback invoked by game_asset_reload when no configured asset manager, reloader or custom asset owns key. + ReloadAsset func(ctx context.Context, key string) error } type compTypeKey any @@ -177,6 +199,8 @@ type Bridge struct { prefabs map[string]prefabEntry prefabOrder []string + + customAssets *assetRegistry } // New constructs a Bridge for cfg without registering its tools yet. @@ -318,6 +342,7 @@ func (b *Bridge) Tools() []automation.Tool { out = append(out, b.editTools()...) out = append(out, b.replayTools()...) out = append(out, b.perfTools()...) + out = append(out, b.assetTools()...) return out } diff --git a/packages/game/resource/library.go b/packages/game/resource/library.go index 7450046e..3c4f8a7b 100644 --- a/packages/game/resource/library.go +++ b/packages/game/resource/library.go @@ -136,6 +136,29 @@ func (l *Library) Paths() []string { return out } +// ReloadFile re-reads path from the library's file system and reloads it in place via Reload. It reports the file's byte size, whether path was loaded in the library, and any read or parse error. An unloaded path returns (0, false, nil). On error, the previously loaded resource stays unchanged. +func (l *Library) ReloadFile(path string) (int64, bool, error) { + if l == nil { + return 0, false, nil + } + l.mu.Lock() + _, ok := l.items[path] + fsys := l.fsys + l.mu.Unlock() + if !ok { + return 0, false, nil + } + if fsys == nil { + return 0, true, fmt.Errorf("resource: library has no file system to reload %q from", path) + } + data, err := fs.ReadFile(fsys, path) + if err != nil { + return 0, true, fmt.Errorf("resource: reload %s: %w", path, err) + } + loaded, err := l.Reload(path, data) + return int64(len(data)), loaded, err +} + // Revision counts the successful reloads, so code that derives values from resources, such as a gameui.Theme built with Theme.Apply, can tell when to derive them again. func (l *Library) Revision() uint64 { if l == nil { diff --git a/packages/game/tooling/hotreload/material.go b/packages/game/tooling/hotreload/material.go index 3324d47d..71f25936 100644 --- a/packages/game/tooling/hotreload/material.go +++ b/packages/game/tooling/hotreload/material.go @@ -801,6 +801,54 @@ func (r *MaterialReloader) MaterialNames() []string { return names } +// MaterialPath returns the slash-separated relative file path registered for material name. +func (r *MaterialReloader) MaterialPath(name string) (string, bool) { + if r == nil { + return "", false + } + r.mu.Lock() + defer r.mu.Unlock() + e, ok := r.materials[name] + if !ok { + return "", false + } + return e.path, true +} + +// ReloadMaterialFile resolves nameOrPath (a registered material name or relative path), reads fresh YAML bytes from the reloader's configured file system, and calls ReloadMaterial. It reports the resolved path, file byte length, whether the material is tracked, and any error. +func (r *MaterialReloader) ReloadMaterialFile(nameOrPath string) (string, int64, bool, error) { + if r == nil || nameOrPath == "" { + return "", 0, false, nil + } + r.mu.Lock() + if r.closed { + r.mu.Unlock() + return "", 0, false, nil + } + clean := "" + tracked := false + if e, ok := r.materials[nameOrPath]; ok { + clean = e.path + tracked = true + } else { + cand := normalizeRelPath(nameOrPath) + if len(r.byPath[cand]) > 0 { + clean = cand + tracked = true + } + } + r.mu.Unlock() + if !tracked { + return "", 0, false, nil + } + data, err := r.readFile(clean) + if err != nil { + return clean, 0, true, err + } + reloaded, err := r.ReloadMaterial(clean, data) + return clean, int64(len(data)), reloaded, err +} + // LastError returns the most recent unresolved ReloadError for name and whether one is active. func (r *MaterialReloader) LastError(name string) (ReloadError, bool) { if r == nil { diff --git a/packages/game/tooling/hotreload/shader.go b/packages/game/tooling/hotreload/shader.go index d91edd3e..a09fdec9 100644 --- a/packages/game/tooling/hotreload/shader.go +++ b/packages/game/tooling/hotreload/shader.go @@ -620,6 +620,46 @@ func (r *ShaderReloader) ShaderNames() []string { return names } +// ShaderPath returns the slash-separated relative file path registered for shader name. +func (r *ShaderReloader) ShaderPath(name string) (string, bool) { + if r == nil { + return "", false + } + r.mu.Lock() + defer r.mu.Unlock() + p, ok := r.namedShader[name] + return p, ok +} + +// ReloadShaderFile resolves nameOrPath (a registered shader name or relative path), reads fresh source bytes from the reloader's configured file system, and calls ReloadShader. It reports the resolved path, source byte length, whether the shader is tracked, and any error. +func (r *ShaderReloader) ReloadShaderFile(nameOrPath string) (string, int64, bool, error) { + if r == nil || nameOrPath == "" { + return "", 0, false, nil + } + r.mu.Lock() + if r.closed { + r.mu.Unlock() + return "", 0, false, nil + } + clean := "" + if p, ok := r.namedShader[nameOrPath]; ok { + clean = p + } else { + clean = normalizeRelPath(nameOrPath) + } + tracked, _, _, _ := r.snapshotDependentsLocked(clean) + r.mu.Unlock() + if !tracked { + return "", 0, false, nil + } + data, err := r.readFile(clean) + if err != nil { + return clean, 0, true, err + } + reloaded, err := r.ReloadShader(clean, data) + return clean, int64(len(data)), reloaded, err +} + // PipelineNames returns the sorted list of registered pipeline names. func (r *ShaderReloader) PipelineNames() []string { if r == nil {