diff --git a/external_plugins/sprite-animation-pack/.zcode-plugin/plugin.json b/external_plugins/sprite-animation-pack/.zcode-plugin/plugin.json new file mode 100644 index 00000000..18920f5a --- /dev/null +++ b/external_plugins/sprite-animation-pack/.zcode-plugin/plugin.json @@ -0,0 +1,60 @@ +{ + "name": "sprite-animation-pack", + "version": "0.1.0", + "description": "Turn a character's animation frames — a folder of PNGs or a whole sprite sheet — into a game-ready animation pack: actions grouped automatically, every frame lined up on the feet (or kept in place), frame timing and loops, a uniform-cell atlas PNG, Aseprite/Phaser JSON, a Godot 4 SpriteFrames .tres and Unity slicing notes. Preview each action with onion skin and nudge frames pixel by pixel. Runs locally; no API keys.", + "description_i18n": { + "en": "Turn a character's animation frames — a folder of PNGs or a whole sprite sheet — into a game-ready animation pack: actions grouped automatically, every frame lined up on the feet (or kept in place), frame timing and loops, a uniform-cell atlas PNG, Aseprite/Phaser JSON, a Godot 4 SpriteFrames .tres and Unity slicing notes. Preview each action with onion skin and nudge frames pixel by pixel. Runs locally; no API keys.", + "zh-CN": "把角色的动作帧(一文件夹 PNG 或一整张精灵图)整理成游戏可直接用的动作包:自动按动作分组,所有帧按脚底对齐(或保持原位),设置帧时长和循环,导出等格图集 PNG、Aseprite/Phaser JSON、Godot 4 SpriteFrames .tres 和 Unity 切片说明。面板里逐个动作播放预览,带洋葱皮,可逐像素微调。在本地运行,无需 API 密钥。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "sprite", + "sprite sheet", + "animation", + "atlas", + "pixel art", + "godot", + "phaser", + "unity", + "aseprite", + "game", + "精灵图", + "动作", + "图集", + "游戏" + ], + "skills": "skills", + "mcpServers": { + "sprite-animation-pack": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "游戏角色动作包", + "en-US": "Sprite Animation Pack" + }, + "icon": "gamepad-2", + "server": "sprite-animation-pack", + "resourceUri": "ui://sprite-animation-pack/panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/sprite-animation-pack/LICENSE b/external_plugins/sprite-animation-pack/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/sprite-animation-pack/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/sprite-animation-pack/README.md b/external_plugins/sprite-animation-pack/README.md new file mode 100644 index 00000000..41232bf4 --- /dev/null +++ b/external_plugins/sprite-animation-pack/README.md @@ -0,0 +1,66 @@ +# Sprite Animation Pack + +Turn a character's animation frames into a pack your game engine can load: one atlas, every action's frames lined up on the same anchor, frame timing, loops, and import files for Phaser, Godot and Unity. + +## Features + +- **Input**: + - A folder of PNG frames. Actions are grouped by sub-folder (`run/1.png`) or by file name without the frame number (`hero_run_01.png` → `run`), and frames are sorted naturally. + - Or a whole sprite sheet sliced by a grid (cell size or cols/rows), with one action per row or per column. Empty cells are skipped. + - A solid background (magenta, green, or the corner colour) can be keyed out. +- **Alignment**: every frame is placed in a uniform cell so that its anchor sits at the same point. + - **feet**: horizontal centre of mass, resting on the lowest pixel. This is the default for trimmed frames. + - **keep**: the original position, chosen automatically when frames share a padded canvas, which preserves jumps. + - **center** is also available. + - Each frame can be nudged by 1 px. +- **Panel**: + - Action list with name, fps, loop and alignment. + - Live preview with zoom, ground line and onion skin, plus play/pause/step. + - Frame strip with duration per frame, nudge, reorder and delete. + - Settings and the atlas preview. +- **Export** to `sprites//`: + - `.png`: atlas with uniform cells and one row per action, with an integer nearest-neighbour scale (1–8×) for pixel art. + - `.json`: Aseprite format with frame durations and tags. Phaser 3 loads it with `load.aseprite` + `anims.createFromAseprite`; plain atlas loaders read it too. + - `.tres`: Godot 4 `SpriteFrames`, with per-action speed, loop and relative frame durations. It references the atlas next to it. + - `.unity.md`: Sprite Editor grid slicing settings, the pivot, and every frame's rectangle. + - `.phaser.js`: a ready-to-paste snippet. + - `.sprites.json`: the project, to reopen and change. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Slice hero.png into 32×32 cells — rows are idle, run and jump — and export a pack for Godot and Phaser" +- "Line up the frames in art/knight/ on the feet, make attack play once at 15 fps" +- "Export the runner at 4× for pixel-art scaling" + +## Tools + +| Tool | Purpose | +|---|---| +| `sprite_open` | Open a frames folder/list, a sprite sheet (+ grid) or a project; group, align and open the panel | +| `sprite_save` | Save names, order, timing, loops, alignment, nudges and settings | +| `sprite_export` | Write the atlas, Aseprite/Phaser JSON, Godot .tres, Unity notes and the project | + +## Scope (v0.1) + +- PNG frames only (with transparency, or a solid background to key out). +- Uniform cells; no tight packing or rotation. +- Generating new frames ("fill in the missing attack frames") is not included. Generate them with an image tool first, then add them to the folder. +- Unity gets slicing instructions rather than a `.meta` file, because Unity assigns its own GUIDs. + +## Privacy, network and files + +- **Everything runs locally.** No network, no uploads, no API keys or accounts. +- Reads only the images you pick. Writes only to `sprites//` in the workspace. No hooks. + +## Build and test (developers) + +- Source: `ui-plugins/sprite-animation-pack/`. +- Build: `pnpm install --frozen-lockfile && pnpm build`, then add `dist/local-marketplace` as a local source. +- Tests: `pnpm --filter @penova/plugin-sprite-animation-pack test` and `test:e2e`. +- `E2E_SPRITES` can point to real art. We used the CC0 "Runner character" by Blue Yeti Studios from OpenGameArt, both as the sheet and as trimmed frames. + +## Third-party components and licenses + +MIT licensed (author: Penova). Bundled: pngjs (MIT), jpeg-js (BSD-3-Clause), MCP SDK and ext-apps (MIT), zod (MIT); the full list is in `dist/THIRD_PARTY_NOTICES.txt`. diff --git a/external_plugins/sprite-animation-pack/README_CN.md b/external_plugins/sprite-animation-pack/README_CN.md new file mode 100644 index 00000000..c4b81de3 --- /dev/null +++ b/external_plugins/sprite-animation-pack/README_CN.md @@ -0,0 +1,66 @@ +# 游戏角色动作包 + +把角色的动作帧整理成游戏引擎能直接加载的动作包:一张图集,每个动作的帧都对齐到同一个锚点,带帧时长、循环设置,以及 Phaser、Godot、Unity 的导入文件。 + +## 功能 + +- **输入**: + - 一文件夹 PNG 帧:按子文件夹(`run/1.png`)或去掉帧号后的文件名(`hero_run_01.png` → `run`)分成动作,帧按自然顺序排列。 + - 或一整张精灵图:按网格切开(格子尺寸或行列数),每行或每列一个动作,空格子自动跳过。 + - 纯色底(品红、绿幕或左上角颜色)可以去掉。 +- **对齐**:所有帧放进统一大小的格子,锚点落在同一位置。 + - **脚底**:取不透明像素的水平重心,贴着最低点。裁切过的帧默认用这种方式。 + - **保持原位**:帧共用一块留有透明边的画布时自动选用,跳跃的高度会保留。 + - 也可以选**中心**对齐。 + - 每帧都能逐像素微调。 +- **面板**: + - 动作列表:名字、fps、循环、对齐方式。 + - 实时预览:可放大,带地面线和洋葱皮,可播放 / 暂停 / 逐帧。 + - 帧条:可改每帧时长、微调位置、调整顺序、删除。 + - 参数设置和图集预览。 +- **导出**(到 `sprites/<名字>/`): + - `名字.png`:等格图集,每个动作一行;像素画可按整数倍(1–8×)最近邻放大,不会糊。 + - `名字.json`:Aseprite 格式,带每帧时长和动作标签。Phaser 3 用 `load.aseprite` + `anims.createFromAseprite` 加载,普通 atlas 加载方式也能读。 + - `名字.tres`:Godot 4 的 `SpriteFrames`,每个动作有速度、循环和各帧相对时长,引用同一文件夹里的图集。 + - `名字.unity.md`:Unity Sprite Editor 按网格切片的参数、Pivot,以及每帧的矩形。 + - `名字.phaser.js`:可以直接粘贴的代码片段。 + - `名字.sprites.json`:工程文件,可以重新打开修改。 + +## 使用 + +在 ZCode Desktop 中对 Agent 说: + +- “把 hero.png 按 32×32 切开,三行分别是 idle、run、jump,导出 Godot 和 Phaser 用的动作包” +- “把 art/knight/ 里的帧按脚底对齐,attack 只播一次、15 帧每秒” +- “把 runner 放大 4 倍导出,像素风不要糊” + +## 工具 + +| 工具 | 作用 | +|---|---| +| `sprite_open` | 打开帧文件夹 / 文件列表、精灵图(加网格)或工程;分组、对齐并打开面板 | +| `sprite_save` | 保存名字、顺序、时长、循环、对齐方式、微调和参数 | +| `sprite_export` | 导出图集、Aseprite/Phaser JSON、Godot .tres、Unity 说明和工程 | + +## 范围(v0.1) + +- 只支持 PNG 帧(透明底,或可以去掉的纯色底)。 +- 等格排列,不做紧密打包或旋转。 +- 不包含“补全动作”(生成新帧):先用生图工具生成新帧,再放进文件夹。 +- Unity 提供切片说明而不是 `.meta` 文件,因为 GUID 由 Unity 自己分配。 + +## 隐私、网络与文件 + +- **全部在本地运行**:不联网、不上传,不需要 API 密钥或账号。 +- 只读取你选的图片,只写入工作区的 `sprites/<名字>/`。没有 hooks。 + +## 构建与测试(开发者) + +- 源码位于 `ui-plugins/sprite-animation-pack/`。 +- 构建:`pnpm install --frozen-lockfile && pnpm build`,然后把 `dist/local-marketplace` 添加为本地来源。 +- 测试:`pnpm --filter @penova/plugin-sprite-animation-pack test` 和 `test:e2e`。 +- `E2E_SPRITES` 可以指向真实素材。我们用的是 OpenGameArt 上 Blue Yeti Studios 的 CC0 素材“Runner character”,精灵图和裁切后的单帧两种形式都测了。 + +## 第三方组件与许可 + +MIT 许可(作者:Penova)。打包的组件:pngjs(MIT)、jpeg-js(BSD-3-Clause)、MCP SDK 和 ext-apps(MIT)、zod(MIT);完整清单见 `dist/THIRD_PARTY_NOTICES.txt`。 diff --git a/external_plugins/sprite-animation-pack/skills/sprite-animation-pack/SKILL.md b/external_plugins/sprite-animation-pack/skills/sprite-animation-pack/SKILL.md new file mode 100644 index 00000000..9724342a --- /dev/null +++ b/external_plugins/sprite-animation-pack/skills/sprite-animation-pack/SKILL.md @@ -0,0 +1,20 @@ +--- +name: sprite-animation-pack +description: 把角色动作帧(PNG 文件夹或整张精灵图)整理成游戏动作包:按动作分组、脚底对齐、帧时长与循环,导出图集 PNG、Aseprite/Phaser JSON、Godot .tres、Unity 切片说明。用户提到“精灵图 / 动作帧 / 序列帧 / 图集 / Godot SpriteFrames / Phaser 动画”时使用。 +--- + +# 游戏角色动作包 + +1. 打开素材: + - 帧文件夹:`sprite_open(frames: "art/hero", fps?)`。 + - 整张图:`sprite_open(sheet: "hero.png", grid: {width, height} 或 {cols, rows}, by: "row"|"column", actions: ["idle","run",…])`。 + - 不知道格子尺寸时先问用户,或者根据报错里给出的图片尺寸推断(常见 16/24/32/48/64)。 +2. 读返回的摘要:每个动作的帧数和对齐方式(auto → feet 或 keep)。跳跃、攻击这类带位移的动作如果是裁切过的单帧,建议用户在面板里检查,必要时改为 keep 或微调。 +3. 按用户要求改工程,然后 `sprite_save(project)`: + - 动作名:小写英文最适合引擎。 + - `frames[].duration`(毫秒)、`loop`、`anchor`、`scale`(像素画用 2–4×)。 + - 拆分或合并动作:直接编辑 `actions[].frames`。 +4. `sprite_export(project)`,告诉用户输出文件夹里各文件的用途: + - Phaser:`load.aseprite` + `createFromAseprite`。 + - Godot:把 `.tres` 和 PNG 放进同一文件夹,在 AnimatedSprite2D 上用这个 `.tres`。 + - Unity:照 `.unity.md` 的说明切片。 diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..8c44e52c 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,58 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "sprite-animation-pack", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/sprite-animation-pack", + "displayName": "Sprite Animation Pack", + "displayName_i18n": { + "en": "Sprite Animation Pack", + "zh-CN": "游戏角色动作包" + }, + "description": "Turn a character's animation frames — a folder of PNGs or a whole sprite sheet — into a game-ready animation pack: actions grouped automatically, every frame lined up on the feet (or kept in place), frame timing and loops, a uniform-cell atlas PNG, Aseprite/Phaser JSON, a Godot 4 SpriteFrames .tres and Unity slicing notes. Preview each action with onion skin and nudge frames pixel by pixel. Runs locally; no API keys.", + "description_i18n": { + "en": "Turn a character's animation frames — a folder of PNGs or a whole sprite sheet — into a game-ready animation pack: actions grouped automatically, every frame lined up on the feet (or kept in place), frame timing and loops, a uniform-cell atlas PNG, Aseprite/Phaser JSON, a Godot 4 SpriteFrames .tres and Unity slicing notes. Preview each action with onion skin and nudge frames pixel by pixel. Runs locally; no API keys.", + "zh-CN": "把角色的动作帧(一文件夹 PNG 或一整张精灵图)整理成游戏可直接用的动作包:自动按动作分组,所有帧按脚底对齐(或保持原位),设置帧时长和循环,导出等格图集 PNG、Aseprite/Phaser JSON、Godot 4 SpriteFrames .tres 和 Unity 切片说明。面板里逐个动作播放预览,带洋葱皮,可逐像素微调。在本地运行,无需 API 密钥。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "sprite", + "sprite sheet", + "animation", + "atlas", + "pixel art", + "godot", + "phaser", + "unity", + "aseprite", + "game", + "精灵图", + "动作", + "图集", + "游戏" + ], + "examplePrompts": [ + "Slice hero.png into 32×32 cells — rows are idle, run and jump — and export a pack for Godot and Phaser", + "Line up the frames in art/knight/ on the feet, make attack play once at 15 fps", + "Export the runner at 4× for pixel-art scaling" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "把 hero.png 按 32×32 切开,三行分别是 idle、run、jump,导出 Godot 和 Phaser 用的动作包", + "把 art/knight/ 里的帧按脚底对齐,attack 只播一次、15 帧每秒", + "把 runner 放大 4 倍导出,像素风不要糊" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..abd830c6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -226,6 +226,46 @@ importers: ui-plugins/soundcraft: {} + ui-plugins/sprite-animation-pack: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + jpeg-js: + specifier: 0.4.4 + version: 0.4.4 + pngjs: + specifier: 7.0.0 + version: 7.0.0 + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + '@types/pngjs': + specifier: 6.0.5 + version: 6.0.5 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + ui-plugins/typst-workbench: dependencies: '@modelcontextprotocol/sdk': @@ -1884,6 +1924,9 @@ packages: '@types/pako@2.0.4': resolution: {integrity: sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==} + '@types/pngjs@6.0.5': + resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==} + '@types/raf@3.4.3': resolution: {integrity: sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==} @@ -2475,10 +2518,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2753,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -2735,6 +2771,9 @@ packages: react: optional: true + jpeg-js@0.4.4: + resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} + js-base64@3.9.4: resolution: {integrity: sha512-PtOMXpEGuP0RRiRXsjzHzl44dMHxSu2CPvAhinupR1tBa88me+1DPqsobl7eupn5UukjLkln1ZnAOAOXOrYG0Q==} @@ -3068,10 +3107,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3101,6 +3136,10 @@ packages: png-chunks-extract@1.0.0: resolution: {integrity: sha512-ZiVwF5EJ0DNZyzAqld8BP1qyJBaGOFaq9zl579qfbkcmOwWLLO4I9L8i2O4j3HkI6/35i0nKG2n+dZplxiT89Q==} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + points-on-curve@0.2.0: resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} @@ -3383,18 +3422,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3773,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4285,11 +4316,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5118,6 +5149,10 @@ snapshots: '@types/pako@2.0.4': {} + '@types/pngjs@6.0.5': + dependencies: + '@types/node': 25.5.0 + '@types/raf@3.4.3': optional: true @@ -5809,13 +5844,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5902,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6077,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6060,6 +6087,8 @@ snapshots: '@types/react': 19.2.14 react: 19.2.7 + jpeg-js@0.4.4: {} + js-base64@3.9.4: {} json-schema-traverse@1.0.0: {} @@ -6406,8 +6435,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6433,6 +6460,8 @@ snapshots: dependencies: crc-32: 0.3.0 + pngjs@7.0.0: {} + points-on-curve@0.2.0: {} points-on-curve@1.0.1: {} @@ -6745,7 +6774,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6808,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) diff --git a/ui-plugins/sprite-animation-pack/package.json b/ui-plugins/sprite-animation-pack/package.json new file mode 100644 index 00000000..6ed73a1f --- /dev/null +++ b/ui-plugins/sprite-animation-pack/package.json @@ -0,0 +1,35 @@ +{ + "name": "@penova/plugin-sprite-animation-pack", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "Sprite Animation Pack" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "jpeg-js": "0.4.4", + "pngjs": "7.0.0", + "zod": "^4.6.5" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "@types/pngjs": "6.0.5", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4" + } +} diff --git a/ui-plugins/sprite-animation-pack/scripts/build.mjs b/ui-plugins/sprite-animation-pack/scripts/build.mjs new file mode 100644 index 00000000..02ff90d4 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/scripts/build.mjs @@ -0,0 +1,74 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +await writeNotices([ui.metafile, server.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/sprite-animation-pack/scripts/e2e.mts b/ui-plugins/sprite-animation-pack/scripts/e2e.mts new file mode 100644 index 00000000..f45ac456 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/scripts/e2e.mts @@ -0,0 +1,79 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板。需要 Chrome。 +// E2E_SPRITES 指向含 runner-sheet.png 与 runner-frames/ 的文件夹(OpenGameArt CC0 角色,见 SOURCES.txt);否则生成简单的小人。 +import assert from "node:assert/strict"; +import { cp, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createRaster, decodeImage, encodePng } from "../src/kit/raster.ts"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "sprite-animation-pack-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "sprites-e2e-")); +const art = join(workspace, "art"); +if (process.env.E2E_SPRITES) await cp(process.env.E2E_SPRITES, art, { recursive: true }); +else { + await mkdir(join(art, "runner-frames"), { recursive: true }); + const sheet = createRaster(256, 96); + const counts = { idle: 5, run: 8, jump: 4 }; + let row = 0; + for (const [name, n] of Object.entries(counts)) { + for (let i = 0; i < n; i++) { + const w = 10 + (i % 3) * 2, h = 24 - (i % 2); + const img = createRaster(w, h, [60 + i * 20, 90, 200, 255]); + await writeFile(join(art, `runner-frames/runner_${name}_${String(i + 1).padStart(2, "0")}.png`), encodePng(img)); + for (let y = 0; y < h; y++) sheet.data.set(img.data.subarray(y * w * 4, (y + 1) * w * 4), ((row * 32 + 32 - h + y) * 256 + i * 32 + 4) * 4); + } + row++; + } + await writeFile(join(art, "runner-sheet.png"), encodePng(sheet)); +} + +const harness = await startHarness({ workspace }); +const step = (text: string) => process.stdout.write(`• ${text}\n`); +try { + const { outer, frame } = await harness.open("?locale=zh-CN", { width: 1300, height: 900 }); + step("agent opens the trimmed frames"); + const opened = await harness.agent(outer, "sprite_open", { frames: "art/runner-frames", name: "runner", fps: 12 }); + assert.match(opened.content[0].text, /idle 5f 12fps loop anchor=feet \(auto\); jump 4f .*; run 8f /); + await frame.locator(".act").nth(2).waitFor(); + await frame.locator(".strip .fr canvas").first().waitFor(); + step("user inspects run, nudges a frame, sets jump to play once and exports at 4×"); + await frame.locator(".act").nth(2).click({ position: { x: 4, y: 4 } }); + await frame.locator(".strip .fr").nth(3).click(); + await frame.locator(".strip .fr").nth(3).locator("button[title='右移 1px']").click(); + await frame.locator("label", { hasText: "洋葱皮" }).locator("input").check(); + await frame.locator(".act").nth(1).locator("input[type=checkbox]").uncheck(); + await frame.locator(".settings select").first().selectOption("4"); + await frame.waitForTimeout(800); + await outer.screenshot({ path: join(shots, "01-run-onion.png") }); + await frame.locator(".act").nth(2).click({ position: { x: 4, y: 4 } }); + const play = frame.locator("button", { hasText: "▶ 播放" }); + if (await play.count()) await play.click(); + await frame.locator("button", { hasText: "导出动作包" }).click(); + await frame.locator(".card", { hasText: "已导出" }).waitFor(); + const dir = join(workspace, "sprites/runner"); + const json = JSON.parse(await readFile(join(dir, "runner.json"), "utf8")); + assert.deepEqual(json.meta.frameTags.map((t: any) => [t.name, t.from, t.to, t.repeat ?? "∞"]), [["idle", 0, 4, "∞"], ["jump", 5, 8, "1"], ["run", 9, 16, "∞"]]); + const project = JSON.parse(await readFile(join(dir, "runner.sprites.json"), "utf8")); + assert.equal(project.actions[2].frames[3].dx, 1); + const atlas = decodeImage(await readFile(join(dir, "runner.png"))); + assert.equal(atlas.width, json.meta.size.w); + assert.match(await readFile(join(dir, "runner.tres"), "utf8"), /"name": &"jump",\n"speed": 12\.048/); + await frame.waitForTimeout(600); + await outer.screenshot({ path: join(shots, "02-exported.png") }); + step("agent opens the original sheet with a grid"); + const sheet = await harness.agent(outer, "sprite_open", { sheet: "art/runner-sheet.png", grid: { width: 32, height: 32 }, actions: ["idle", "run", "jump"], name: "runner-sheet" }); + assert.match(sheet.content[0].text, /idle 5f .* anchor=keep \(auto\); run 8f .*; jump 4f /); + await frame.locator(".act input[type=text]").nth(2).and(frame.locator("[value='jump']")).waitFor().catch(() => undefined); + await frame.locator(".act").nth(2).click({ position: { x: 4, y: 4 } }); + await frame.waitForTimeout(800); + await outer.screenshot({ path: join(shots, "03-sheet-jump.png") }); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} catch (error) { + console.error("page errors:", harness.errors, harness.stderr.join("")); + throw error; +} finally { + await harness.close(); +} diff --git a/ui-plugins/sprite-animation-pack/scripts/harness.mjs b/ui-plugins/sprite-animation-pack/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/scripts/harness.mjs @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/sprite-animation-pack/scripts/licenses.mjs b/ui-plugins/sprite-animation-pack/scripts/licenses.mjs new file mode 100644 index 00000000..162c2a73 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} diff --git a/ui-plugins/sprite-animation-pack/src/export.ts b/ui-plugins/sprite-animation-pack/src/export.ts new file mode 100644 index 00000000..42d06ea4 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/export.ts @@ -0,0 +1,78 @@ +import type { Layout, Project } from "./sprites.ts"; + +const r = (l: Layout, p: Project, f: Layout["frames"][number]) => ({ x: f.x * p.scale, y: f.y * p.scale, w: l.cellW * p.scale, h: l.cellH * p.scale }); + +/** Aseprite 导出格式(JSON Hash + frameTags):Phaser 3 用 load.aseprite / createFromAseprite,也能当普通 atlas 用。 */ +export function asepriteJson(p: Project, l: Layout, image: string) { + const frames: Record = {}; + for (const f of l.frames) { + const rect = r(l, p, f); + frames[f.name] = { frame: rect, rotated: false, trimmed: false, spriteSourceSize: { x: 0, y: 0, w: rect.w, h: rect.h }, sourceSize: { w: rect.w, h: rect.h }, duration: f.duration }; + } + let i = 0; + const frameTags = p.actions.map((a) => { + const from = i; + i += a.frames.length; + return { name: a.name, from, to: i - 1, direction: "forward", ...(a.loop ? {} : { repeat: "1" }) }; + }); + return JSON.stringify({ frames, meta: { app: "https://github.com/ppppp2005-p (ZCode Sprite Animation Pack)", version: "0.1.0", image, format: "RGBA8888", size: { w: l.width * p.scale, h: l.height * p.scale }, scale: "1", frameTags, pivot: { x: l.pivot[0] / l.cellW, y: l.pivot[1] / l.cellH } } }, null, 1) + "\n"; +} + +/** Godot 4 SpriteFrames 资源;图集按相对路径引用(与 .tres 放在同一文件夹)。 */ +export function godotTres(p: Project, l: Layout, image: string) { + const subs: string[] = []; + const anims: string[] = []; + let n = 0; + for (const a of p.actions) { + const list = l.frames.filter((f) => f.action === a.name); + const base = mode(list.map((f) => f.duration)); + const frames = list.map((f) => { + n++; + const rect = r(l, p, f); + subs.push(`[sub_resource type="AtlasTexture" id="AtlasTexture_${n}"]\natlas = ExtResource("1_atlas")\nregion = Rect2(${rect.x}, ${rect.y}, ${rect.w}, ${rect.h})\n`); + return `{\n"duration": ${fmt(f.duration / base)},\n"texture": SubResource("AtlasTexture_${n}")\n}`; + }); + anims.push(`{\n"frames": [${frames.join(", ")}],\n"loop": ${a.loop},\n"name": &"${a.name}",\n"speed": ${fmt(1000 / base)}\n}`); + } + return `[gd_resource type="SpriteFrames" load_steps=${n + 2} format=3]\n\n[ext_resource type="Texture2D" path="${image}" id="1_atlas"]\n\n${subs.join("\n")}\n[resource]\nanimations = [${anims.join(", ")}]\n`; +} + +/** Unity:Sprite Editor 按网格切片的参数 + 每帧矩形(Unity 的 y 轴从下往上)。 */ +export function unityNotes(p: Project, l: Layout, image: string) { + const W = l.cellW * p.scale, H = l.cellH * p.scale, height = l.height * p.scale; + const px = (l.pivot[0] / l.cellW).toFixed(4), py = (1 - l.pivot[1] / l.cellH).toFixed(4); + const lines = [ + `# ${p.name} — Unity import`, + "", + `1. Copy \`${image}\` into \`Assets/\`. In the Inspector: Texture Type **Sprite (2D and UI)**, Sprite Mode **Multiple**, Filter Mode **Point (no filter)** for pixel art, Compression **None**.`, + `2. Sprite Editor → Slice → Type **Grid By Cell Size**, Pixel Size **${W} × ${H}**, Offset 0, Padding 0, Pivot **Custom (${px}, ${py})** — the character's feet / anchor. Slice, then Apply.`, + `3. Name the slices from this table (or keep Unity's numbering, they come in the same order). Drag each action's sprites into the Scene to create an Animation Clip, then set the sample rate below.`, + "", + "| Action | Frames | Sprites (x, y from bottom-left, w, h) | Frame durations (ms) | Loop |", + "|---|---|---|---|---|", + ]; + for (const a of p.actions) { + const list = l.frames.filter((f) => f.action === a.name); + const rects = list.map((f) => `${f.name} (${f.x * p.scale}, ${height - (f.y + l.cellH) * p.scale}, ${W}, ${H})`).join("
"); + lines.push(`| ${a.name} | ${list.length} | ${rects} | ${list.map((f) => f.duration).join(", ")} (≈${fmt(1000 / mode(list.map((f) => f.duration)))} fps) | ${a.loop ? "yes" : "no"} |`); + } + return lines.join("\n") + "\n"; +} + +export function phaserSnippet(p: Project, l: Layout, json: string, image: string) { + return `// Phaser 3 — load the atlas and create every animation from its tags. +// preload(): +this.load.aseprite("${p.name}", "${image}", "${json}"); +// create(): +this.anims.createFromAseprite("${p.name}"); +const sprite = this.add.sprite(400, 300, "${p.name}").setOrigin(${(l.pivot[0] / l.cellW).toFixed(3)}, ${(l.pivot[1] / l.cellH).toFixed(3)}); +sprite.play({ key: "${p.actions[0]?.name}", repeat: -1 }); +`; +} + +function mode(values: number[]) { + const c = new Map(); + for (const v of values) c.set(v, (c.get(v) ?? 0) + 1); + return [...c.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]?.[0] ?? 100; +} +const fmt = (n: number) => String(Math.round(n * 1000) / 1000).replace(/^(\d+)$/, "$1.0"); diff --git a/ui-plugins/sprite-animation-pack/src/kit/console.ts b/ui-plugins/sprite-animation-pack/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/kit/console.ts @@ -0,0 +1,5 @@ +// stdout 只留给 MCP 协议;依赖库的日志改写到 stderr。 +console.log = (...args: unknown[]) => process.stderr.write(`${args.map(String).join(" ")}\n`); +console.info = console.log; +console.warn = console.log; +console.debug = console.log; diff --git a/ui-plugins/sprite-animation-pack/src/kit/raster.ts b/ui-plugins/sprite-animation-pack/src/kit/raster.ts new file mode 100644 index 00000000..e711ec7a --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/kit/raster.ts @@ -0,0 +1,240 @@ +import jpeg from "jpeg-js"; +import { PNG } from "pngjs"; +import { KitError } from "./workspace.ts"; + +/** RGBA 8 位图像。 */ +export interface Raster { + width: number; + height: number; + data: Uint8ClampedArray | Uint8Array; +} + +export function createRaster(width: number, height: number, fill?: [number, number, number, number]): Raster { + const data = new Uint8ClampedArray(width * height * 4); + if (fill && (fill[0] || fill[1] || fill[2] || fill[3])) for (let i = 0; i < data.length; i += 4) data.set(fill, i); + return { width, height, data }; +} + +/** JPEG 的 EXIF 方向(1–8),没有则为 1。 */ +export function jpegOrientation(bytes: Uint8Array): number { + if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return 1; + let offset = 2; + while (offset + 4 < bytes.length) { + if (bytes[offset] !== 0xff) return 1; + const marker = bytes[offset + 1]; + const length = (bytes[offset + 2] << 8) | bytes[offset + 3]; + if (marker === 0xe1 && bytes[offset + 4] === 0x45 && bytes[offset + 5] === 0x78 && bytes[offset + 6] === 0x69 && bytes[offset + 7] === 0x66) { + const tiff = offset + 10; + const little = bytes[tiff] === 0x49; + const u16 = (at: number) => (little ? bytes[at] | (bytes[at + 1] << 8) : (bytes[at] << 8) | bytes[at + 1]); + const u32 = (at: number) => (little ? (bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16)) + bytes[at + 3] * 16777216 : bytes[at] * 16777216 + ((bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3])); + const ifd = tiff + u32(tiff + 4); + const count = u16(ifd); + for (let i = 0; i < count; i++) { + const entry = ifd + 2 + i * 12; + if (entry + 12 > bytes.length) break; + if (u16(entry) === 0x0112) return u16(entry + 8) || 1; + } + return 1; + } + if (marker === 0xda) return 1; + offset += 2 + length; + } + return 1; +} + +function orient(image: Raster, orientation: number): Raster { + if (orientation <= 1 || orientation > 8) return image; + const { width: w, height: h, data } = image; + const swap = orientation >= 5; + const out = createRaster(swap ? h : w, swap ? w : h); + for (let y = 0; y < h; y++) + for (let x = 0; x < w; x++) { + let nx = x; + let ny = y; + switch (orientation) { + case 2: nx = w - 1 - x; break; + case 3: nx = w - 1 - x; ny = h - 1 - y; break; + case 4: ny = h - 1 - y; break; + case 5: nx = y; ny = x; break; + case 6: nx = h - 1 - y; ny = x; break; + case 7: nx = h - 1 - y; ny = w - 1 - x; break; + case 8: nx = y; ny = w - 1 - x; break; + } + const s = (y * w + x) * 4; + const d = (ny * out.width + nx) * 4; + out.data[d] = data[s]; + out.data[d + 1] = data[s + 1]; + out.data[d + 2] = data[s + 2]; + out.data[d + 3] = data[s + 3]; + } + return out; +} + +export function decodeImage(bytes: Uint8Array, name = "image"): Raster { + try { + if (bytes[0] === 0x89 && bytes[1] === 0x50) { + const png = PNG.sync.read(Buffer.from(bytes)); + return { width: png.width, height: png.height, data: new Uint8ClampedArray(png.data.buffer, png.data.byteOffset, png.data.length) }; + } + if (bytes[0] === 0xff && bytes[1] === 0xd8) { + const image = jpeg.decode(bytes, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 1024, maxResolutionInMP: 200 }); + return orient({ width: image.width, height: image.height, data: new Uint8ClampedArray(image.data.buffer) }, jpegOrientation(bytes)); + } + } catch (error) { + throw new KitError("bad_image", `Cannot decode ${name}: ${error instanceof Error ? error.message : error}`); + } + throw new KitError("unsupported_image", `${name}: only PNG and JPEG are supported (convert WebP/HEIC first).`); +} + +export function encodePng(image: Raster): Buffer { + const png = new PNG({ width: image.width, height: image.height }); + png.data = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.length); + return PNG.sync.write(png, { colorType: 6 }); +} + +/** 不带透明通道的 PNG(应用商店截图等不接受 alpha)。 */ +export function encodePngOpaque(image: Raster, background: [number, number, number] = [255, 255, 255]): Buffer { + const png = new PNG({ width: image.width, height: image.height }); + png.data = Buffer.from(image.data.buffer, image.data.byteOffset, image.data.length); + return PNG.sync.write(png, { colorType: 2, inputHasAlpha: true, bgColor: { red: background[0], green: background[1], blue: background[2] } }); +} + +/** JPEG 不支持透明:先与背景色合成。 */ +export function encodeJpeg(image: Raster, quality = 90, background: [number, number, number] = [255, 255, 255]): Buffer { + const data = Buffer.alloc(image.width * image.height * 4); + for (let i = 0; i < data.length; i += 4) { + const a = image.data[i + 3] / 255; + data[i] = Math.round(image.data[i] * a + background[0] * (1 - a)); + data[i + 1] = Math.round(image.data[i + 1] * a + background[1] * (1 - a)); + data[i + 2] = Math.round(image.data[i + 2] * a + background[2] * (1 - a)); + data[i + 3] = 255; + } + return jpeg.encode({ width: image.width, height: image.height, data }, quality).data; +} + +/** 缩放:缩小用区域平均(预乘 alpha,避免透明边发黑),放大用双线性。 */ +export function resize(image: Raster, width: number, height: number): Raster { + width = Math.max(1, Math.round(width)); + height = Math.max(1, Math.round(height)); + if (width === image.width && height === image.height) return image; + const out = createRaster(width, height); + const sx = image.width / width; + const sy = image.height / height; + const src = image.data; + if (sx >= 1 && sy >= 1) { + for (let y = 0; y < height; y++) { + const y0 = y * sy; + const y1 = Math.min(image.height, (y + 1) * sy); + for (let x = 0; x < width; x++) { + const x0 = x * sx; + const x1 = Math.min(image.width, (x + 1) * sx); + let r = 0, g = 0, b = 0, a = 0, total = 0; + for (let yy = Math.floor(y0); yy < Math.ceil(y1); yy++) { + const wy = Math.min(yy + 1, y1) - Math.max(yy, y0); + for (let xx = Math.floor(x0); xx < Math.ceil(x1); xx++) { + const wgt = wy * (Math.min(xx + 1, x1) - Math.max(xx, x0)); + const i = (yy * image.width + xx) * 4; + const alpha = src[i + 3] * wgt; + r += src[i] * alpha; + g += src[i + 1] * alpha; + b += src[i + 2] * alpha; + a += alpha; + total += wgt; + } + } + const o = (y * width + x) * 4; + if (a > 0) { + out.data[o] = r / a; + out.data[o + 1] = g / a; + out.data[o + 2] = b / a; + } + out.data[o + 3] = a / total; + } + } + return out; + } + for (let y = 0; y < height; y++) { + const fy = Math.min(image.height - 1, Math.max(0, (y + 0.5) * sy - 0.5)); + const y0 = Math.floor(fy); + const y1 = Math.min(image.height - 1, y0 + 1); + const ty = fy - y0; + for (let x = 0; x < width; x++) { + const fx = Math.min(image.width - 1, Math.max(0, (x + 0.5) * sx - 0.5)); + const x0 = Math.floor(fx); + const x1 = Math.min(image.width - 1, x0 + 1); + const tx = fx - x0; + const o = (y * width + x) * 4; + const i00 = (y0 * image.width + x0) * 4, i10 = (y0 * image.width + x1) * 4, i01 = (y1 * image.width + x0) * 4, i11 = (y1 * image.width + x1) * 4; + const w00 = (1 - tx) * (1 - ty) * src[i00 + 3], w10 = tx * (1 - ty) * src[i10 + 3], w01 = (1 - tx) * ty * src[i01 + 3], w11 = tx * ty * src[i11 + 3]; + const a = w00 + w10 + w01 + w11; + if (a > 0) for (let c = 0; c < 3; c++) out.data[o + c] = (src[i00 + c] * w00 + src[i10 + c] * w10 + src[i01 + c] * w01 + src[i11 + c] * w11) / a; + out.data[o + 3] = a; + } + } + return out; +} + +/** 等比缩小到最长边不超过 max。 */ +export function fitWithin(image: Raster, max: number): Raster { + const scale = Math.min(1, max / Math.max(image.width, image.height)); + return scale < 1 ? resize(image, image.width * scale, image.height * scale) : image; +} + +/** 单通道盒式模糊(3 次近似高斯)。 */ +export function blurChannel(values: Float32Array, width: number, height: number, radius: number, passes = 3): Float32Array { + const r = Math.max(0, Math.round(radius)); + if (!r) return values; + let src = values; + let tmp = new Float32Array(values.length); + for (let pass = 0; pass < passes; pass++) { + for (let y = 0; y < height; y++) { + let sum = 0; + const row = y * width; + for (let x = -r; x <= r; x++) sum += src[row + Math.min(width - 1, Math.max(0, x))]; + for (let x = 0; x < width; x++) { + tmp[row + x] = sum / (2 * r + 1); + sum += src[row + Math.min(width - 1, x + r + 1)] - src[row + Math.max(0, x - r)]; + } + } + const out = new Float32Array(values.length); + for (let x = 0; x < width; x++) { + let sum = 0; + for (let y = -r; y <= r; y++) sum += tmp[Math.min(height - 1, Math.max(0, y)) * width + x]; + for (let y = 0; y < height; y++) { + out[y * width + x] = sum / (2 * r + 1); + sum += tmp[Math.min(height - 1, y + r + 1) * width + x] - tmp[Math.max(0, y - r) * width + x]; + } + } + src = out; + } + tmp = new Float32Array(0); + return src; +} + +export function parseColor(color: string | undefined, fallback: [number, number, number] = [255, 255, 255]): [number, number, number] { + const match = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((color ?? "").trim()); + if (!match) return fallback; + const hex = match[1].length === 3 ? [...match[1]].map((c) => c + c).join("") : match[1]; + return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)]; +} + +/** 把 src 按 alpha 叠到 dst 的 (dx, dy) 位置。 */ +export function drawOver(dst: Raster, src: Raster, dx: number, dy: number, opacity = 1) { + for (let y = 0; y < src.height; y++) { + const ty = y + dy; + if (ty < 0 || ty >= dst.height) continue; + for (let x = 0; x < src.width; x++) { + const tx = x + dx; + if (tx < 0 || tx >= dst.width) continue; + const s = (y * src.width + x) * 4; + const a = (src.data[s + 3] / 255) * opacity; + if (a <= 0) continue; + const d = (ty * dst.width + tx) * 4; + const da = dst.data[d + 3] / 255; + const oa = a + da * (1 - a); + for (let c = 0; c < 3; c++) dst.data[d + c] = (src.data[s + c] * a + dst.data[d + c] * da * (1 - a)) / oa; + dst.data[d + 3] = oa * 255; + } + } +} diff --git a/ui-plugins/sprite-animation-pack/src/kit/server-kit.ts b/ui-plugins/sprite-animation-pack/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/kit/server-kit.ts @@ -0,0 +1,84 @@ +import { readFile } from "node:fs/promises"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { z } from "zod"; +import { KitError } from "./workspace.ts"; + +export const HTML_MIME = "text/html;profile=mcp-app"; +type Visibility = ("model" | "app")[]; +type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface ToolOutput { + text: string; + structured?: Record; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 code 返回给 Agent 与页面。 */ +export function createKitServer(options: KitServerOptions) { + const log = options.log ?? (() => undefined); + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { logging: {} } }); + const panelMeta = { ui: { prefersBorder: false }, ...options.panelMeta }; + server.registerResource("panel", options.panelUri, { mimeType: HTML_MIME, _meta: panelMeta }, async () => ({ + contents: [{ uri: options.panelUri, mimeType: HTML_MIME, _meta: panelMeta, text: await options.panelHtml() }], + })); + + const tool = ( + name: string, + config: { + description: string; + input: Record; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise, + ) => { + server.registerTool( + name, + { + description: config.description, + inputSchema: config.input, + annotations: { readOnlyHint: !!config.readOnly, ...(config.readOnly ? {} : { destructiveHint: false }), openWorldHint: false }, + _meta: { + ui: { resourceUri: options.panelUri, surface: options.surface, visibility: config.visibility ?? ["model", "app"] }, + ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}), + ...(config.openPanel ? { "openai/ui": { preferredModelDisplayMode: "fullscreen" } } : {}), + }, + }, + async (input: unknown) => { + try { + const output = await run(input); + const content: Content[] = [{ type: "text", text: output.text }]; + for (const image of output.images ?? []) content.push({ type: "image", ...image }); + return { content, ...(output.structured ? { structuredContent: output.structured } : {}) }; + } catch (error) { + const code = error instanceof KitError ? error.code : "internal_error"; + const message = error instanceof Error ? error.message : String(error); + if (!(error instanceof KitError)) log(`${name} failed: ${error instanceof Error ? error.stack : message}`); + return { + isError: true, + content: [{ type: "text" as const, text: `[${code}] ${message}` }], + structuredContent: { error: { code, message } }, + }; + } + }, + ); + }; + return { server, tool }; +} + +export async function readPanel(path: string) { + return readFile(path, "utf8"); +} diff --git a/ui-plugins/sprite-animation-pack/src/kit/workspace.ts b/ui-plugins/sprite-animation-pack/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/kit/workspace.ts @@ -0,0 +1,151 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +export class KitError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "KitError"; + } +} + +const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".cache", "__pycache__"]); + +/** 只允许读写当前工作区内的文件;所有路径都相对工作区根目录。 */ +export class Workspace { + readonly root: string; + constructor(root: string) { + this.root = resolve(root); + } + + resolve(path: string): string { + if (typeof path !== "string" || !path.trim()) throw new KitError("bad_path", "Path is empty."); + const absolute = resolve(this.root, path); + const rel = relative(this.root, absolute); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) + throw new KitError("outside_workspace", `Path is outside the workspace: ${path}`); + this.assertRealInside(absolute, path); + return absolute; + } + + private realRoot?: string; + + /** + * 符号链接不能把读写带出工作区:从目标往上找到第一个已存在的路径,取它的真实路径, + * 必须仍在工作区根目录的真实路径之下。还不存在的写入目标按其已存在的上级目录判断; + * 指向不存在位置的悬空链接一律拒绝(否则 writeFile 会顺着它在外部建文件)。 + */ + private assertRealInside(absolute: string, path: string) { + let realRoot: string; + try { + realRoot = this.realRoot ??= realpathSync(this.root); + } catch { + return; // 根目录本身不存在时,没有可逃出的链接 + } + const outside = (real: string) => { + const rel = relative(realRoot, real); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + }; + let probe = absolute; + for (;;) { + let real: string | undefined; + try { + real = realpathSync(probe); + } catch { + let link = false; + try { + link = lstatSync(probe).isSymbolicLink(); + } catch {} + if (link) { + const target = resolve(dirname(probe), readlinkSync(probe)); + throw new KitError("outside_workspace", outside(target) ? `Path leaves the workspace through a link: ${path}` : `Path goes through a broken link: ${path}`); + } + } + if (real !== undefined) { + if (outside(real)) throw new KitError("outside_workspace", `Path leaves the workspace through a link: ${path}`); + return; + } + const parent = dirname(probe); + if (parent === probe) return; + probe = parent; + } + } + + rel(absolute: string): string { + return relative(this.root, absolute).split(sep).join("/") || "."; + } + + async exists(path: string): Promise { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise { + const absolute = this.resolve(path); + let info; + try { + info = await stat(absolute); + } catch { + throw new KitError("not_found", `File not found: ${path}`); + } + if (!info.isFile()) throw new KitError("not_a_file", `Not a file: ${path}`); + if (info.size > maxBytes) throw new KitError("too_large", `File is larger than ${Math.round(maxBytes / 1048576)} MB: ${path}`); + return readFile(absolute); + } + + async readText(path: string): Promise { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise { + const absolute = this.resolve(path); + await mkdir(dirname(absolute), { recursive: true }); + await writeFile(absolute, data); + return this.rel(absolute); + } + + /** 列出文件(默认递归、跳过依赖与构建目录),按路径排序。 */ + async list({ dir = ".", exts, recursive = true, limit = 2000 }: { dir?: string; exts?: string[]; recursive?: boolean; limit?: number } = {}) { + const wanted = exts?.map((ext) => ext.toLowerCase()); + const out: { path: string; size: number }[] = []; + const walk = async (absolute: string, depth: number) => { + if (out.length >= limit || depth > 8) return; + let entries; + try { + entries = await readdir(absolute, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })); + for (const entry of entries) { + if (out.length >= limit) return; + if (entry.name.startsWith(".") && entry.name !== ".") continue; + const child = join(absolute, entry.name); + if (entry.isDirectory()) { + if (recursive && !SKIP.has(entry.name)) await walk(child, depth + 1); + } else if (entry.isFile() && (!wanted || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} diff --git a/ui-plugins/sprite-animation-pack/src/main.ts b/ui-plugins/sprite-animation-pack/src/main.ts new file mode 100644 index 00000000..f666e751 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[sprite-animation-pack] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/sprite-animation-pack/src/server.ts b/ui-plugins/sprite-animation-pack/src/server.ts new file mode 100644 index 00000000..9d641b89 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/server.ts @@ -0,0 +1,187 @@ +import { readFile, stat } from "node:fs/promises"; +import { extname, join } from "node:path"; +import { z } from "zod"; +import { asepriteJson, godotTres, phaserSnippet, unityNotes } from "./export.ts"; +import { decodeImage, encodePng, type Raster } from "./kit/raster.ts"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { compose, crop, groupFiles, keyBackground, layout, normalizeProject, sliceSheet, upscale, type Frame, type Project } from "./sprites.ts"; + +export const NAME = "sprite-animation-pack"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const IMAGE_EXTS = [".png"]; + +export interface ServerOptions { + workspaceRoot: string; + assetRoot: string; + log?: (line: string) => void; +} + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const { server, tool } = createKitServer({ + name: NAME, + version: VERSION, + panelUri: PANEL_URI, + surface: "editor", + panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), + log: options.log, + }); + + const images = new Map(); + async function image(path: string) { + if (!IMAGE_EXTS.includes(extname(path).toLowerCase())) throw new KitError("bad_image", `${path}: frames must be PNG (with transparency).`); + const st = await stat(ws.resolve(path)).catch(() => { + throw new KitError("not_found", `File not found: ${path}`); + }); + const hit = images.get(path); + if (hit && hit.mtime === st.mtimeMs) return hit.img; + if (st.size > 64 * 1024 * 1024) throw new KitError("too_large", `${path} is too large.`); + const img = decodeImage(await ws.read(path, 64 * 1024 * 1024), path); + if (img.width * img.height > 64e6) throw new KitError("too_large", `${path} is too large.`); + images.set(path, { mtime: st.mtimeMs, img }); + return img; + } + async function prepare(raw: unknown) { + const { project, warnings } = normalizeProject(raw); + for (const a of project.actions) for (const f of a.frames) await image(f.source); + const load = (f: Frame) => keyBackground(f.region ? crop(images.get(f.source)!.img, f.region) : images.get(f.source)!.img, project.background); + const l = layout(project, load); + for (const n of l.empty) warnings.push(`Frame ${n} is empty (fully transparent).`); + if (l.width * project.scale > 8192 || l.height * project.scale > 8192) warnings.push(`The atlas is ${l.width * project.scale}×${l.height * project.scale}; some engines and GPUs limit textures to 4096 or 8192 px.`); + return { project, warnings, l }; + } + const projectPath = (p: Project) => `${p.output}/${p.name}/${p.name}.sprites.json`; + function summary(p: Project, l: ReturnType) { + return [ + `${p.name}: ${p.actions.length} action(s) — ${p.actions.map((a) => `${a.name} ${a.frames.length}f ${Math.round(1000 / a.frames[0].duration)}fps ${a.loop ? "loop" : "once"} anchor=${l.modes[a.name]}${a.anchor === "auto" ? " (auto)" : ""}`).join("; ")}.`, + `Cell ${l.cellW}×${l.cellH} px, pivot (${l.pivot[0]}, ${l.pivot[1]}); atlas ${l.width * p.scale}×${l.height * p.scale} px at scale ${p.scale}×.`, + ].join("\n"); + } + const result = (kind: string, p: Project, l: ReturnType, warnings: string[], extra: Record = {}) => ({ + kind, + project: p, + warnings, + cell: [l.cellW, l.cellH], + pivot: l.pivot, + modes: l.modes, + ...extra, + }); + + const projectSchema = z + .record(z.string(), z.unknown()) + .describe('{name, actions: [{name, loop, anchor "auto"|"feet"|"center"|"keep", frames: [{source, region?: {x,y,w,h}, duration (ms), dx, dy}]}], scale (1–8, nearest neighbour), padding, background "auto"|"none"|"#rrggbb", output}'); + + tool( + "sprite_open", + { + description: + "Open Sprite Animation Pack with a character's animation frames: a folder (or list) of PNG frames — grouped into actions by sub-folder or by file name without its frame number (run_01.png, run_02.png…) — or a whole sprite sheet sliced by a grid, one action per row (or column). Lines up every frame on a common anchor (feet), and opens the panel to preview and fix each action. Or pass an existing .sprites.json project.", + input: { + frames: z.union([z.string(), z.array(z.string())]).optional().describe("Folder of PNG frames, or a list of PNG files."), + sheet: z.string().optional().describe("A sprite sheet PNG."), + grid: z.object({ cols: z.number().int().positive().optional(), rows: z.number().int().positive().optional(), width: z.number().int().positive().optional(), height: z.number().int().positive().optional() }).optional().describe("Sheet cell size (px) or cols/rows."), + by: z.enum(["row", "column"]).optional().describe("Sheet: one action per row (default) or per column."), + actions: z.array(z.string()).optional().describe("Sheet: action names in order (e.g. [\"idle\",\"run\",\"jump\"])."), + name: z.string().optional(), + fps: z.number().positive().optional().describe("Default 10."), + project: z.string().optional(), + }, + openPanel: true, + timeoutMs: 120_000, + }, + async ({ frames, sheet, grid, by = "row", actions: names, name, fps = 10, project: path }) => { + let raw: any; + const notes: string[] = []; + if (path) { + try { + raw = JSON.parse(await ws.readText(path)); + } catch { + throw new KitError("bad_project", `Cannot read project ${path}.`); + } + } else if (sheet) { + const s = sliceSheet(await image(sheet), sheet, grid ?? {}, by, names ?? [], "auto", fps); + if (!s.actions.length) throw new KitError("empty_sheet", `${sheet}: every cell is empty with that grid.`); + notes.push(`Sliced ${sheet} into ${s.cols}×${s.rows} cells of ${s.cell[0]}×${s.cell[1]} px; ${by === "row" ? "rows" : "columns"} → actions.`); + if (names && names.length !== s.actions.length) notes.push(`! ${names.length} action names given for ${s.actions.length} non-empty ${by}s.`); + raw = { name: name ?? sheet.split("/").pop()!.replace(/\.[^.]+$/, ""), actions: s.actions }; + } else if (frames) { + let files: string[]; + if (Array.isArray(frames)) files = frames; + else files = (await ws.list({ dir: frames, exts: IMAGE_EXTS, limit: 2000 })).map((f) => f.path); + if (!files.length) throw new KitError("no_frames", `No PNG frames found in ${String(frames)}.`); + const grouped = groupFiles(files, fps); + raw = { name: name ?? (Array.isArray(frames) ? grouped[0].name : frames.split("/").filter(Boolean).pop()), actions: grouped }; + } else throw new KitError("no_input", "Pass `frames` (folder or files), `sheet` (+ grid), or `project`."); + const { project, warnings, l } = await prepare(raw); + await ws.write(projectPath(project), JSON.stringify(project, null, 1) + "\n"); + return { + text: [...notes, summary(project, l), ...warnings.map((w) => `! ${w}`), `Saved ${projectPath(project)}. Rename actions, set fps/loop with sprite_save, then sprite_export. "keep" = frames already share a canvas (good for jumps); "feet" = align feet on one baseline.`].join("\n"), + structured: result("project", project, l, warnings), + }; + }, + ); + + tool( + "sprite_save", + { description: "Validate and save the project: rename/reorder actions, frame order and durations, loop, anchor mode, per-frame nudges (dx, dy), scale, padding, background keying.", input: { project: projectSchema } }, + async ({ project: raw }) => { + const { project, warnings, l } = await prepare(raw); + await ws.write(projectPath(project), JSON.stringify(project, null, 1) + "\n"); + return { text: [summary(project, l), ...warnings.map((w) => `! ${w}`), `Saved ${projectPath(project)}.`].join("\n"), structured: result("project", project, l, warnings) }; + }, + ); + + tool( + "sprite_export", + { + description: + "Export the animation pack to //: atlas PNG (uniform cells, one row per action), Aseprite-format JSON with frame tags (Phaser 3: load.aseprite + createFromAseprite), Godot 4 SpriteFrames .tres, Unity slicing notes, a Phaser snippet and the project file.", + input: { project: projectSchema }, + }, + async ({ project: raw }) => { + const { project: p, warnings, l } = await prepare(raw); + const dir = `${p.output}/${p.name}`; + const png = `${p.name}.png`; + const atlas = upscale(compose(l), p.scale); + const files = [ + await ws.write(`${dir}/${png}`, encodePng(atlas)), + await ws.write(`${dir}/${p.name}.json`, asepriteJson(p, l, png)), + await ws.write(`${dir}/${p.name}.tres`, godotTres(p, l, png)), + await ws.write(`${dir}/${p.name}.unity.md`, unityNotes(p, l, png)), + await ws.write(`${dir}/${p.name}.phaser.js`, phaserSnippet(p, l, `${p.name}.json`, png)), + await ws.write(projectPath(p), JSON.stringify(p, null, 1) + "\n"), + ]; + return { + text: [`Exported ${files.join(", ")}.`, summary(p, l), ...warnings.map((w) => `! ${w}`)].join("\n"), + structured: result("exported", p, l, warnings, { files }), + }; + }, + ); + + tool( + "atlas_preview", + { description: "Atlas (scale 1) and frame rectangles for the panel.", input: { project: projectSchema }, visibility: ["app"], readOnly: true }, + async ({ project: raw }) => { + const { project, warnings, l } = await prepare(raw); + return { + text: `${l.width}×${l.height}`, + structured: { ...result("preview", project, l, warnings), data: encodePng(compose(l)).toString("base64"), frames: l.frames.map((f) => ({ action: f.action, index: f.index, name: f.name, x: f.x, y: f.y, duration: f.duration })) }, + }; + }, + ); + + tool( + "workspace_files", + { description: "PNG files, folders with PNGs and projects for the panel.", input: {}, visibility: ["app"], readOnly: true }, + async () => { + const all = (await ws.list({ exts: [".png", ".json"], limit: 4000 })).map((f) => f.path); + const pngs = all.filter((f) => f.endsWith(".png")); + const folders = [...new Set(pngs.map((f) => f.split("/").slice(0, -1).join("/")).filter(Boolean))]; + return { text: `${pngs.length}`, structured: { pngs, folders, projects: all.filter((f) => f.endsWith(".sprites.json")) } }; + }, + ); + + return server; +} diff --git a/ui-plugins/sprite-animation-pack/src/sprites.ts b/ui-plugins/sprite-animation-pack/src/sprites.ts new file mode 100644 index 00000000..3d9a8a4c --- /dev/null +++ b/ui-plugins/sprite-animation-pack/src/sprites.ts @@ -0,0 +1,247 @@ +import { type Raster, createRaster } from "./kit/raster.ts"; +import { KitError } from "./kit/workspace.ts"; + +export type AnchorMode = "auto" | "feet" | "center" | "keep"; +export interface Region { x: number; y: number; w: number; h: number } +export interface Frame { source: string; region?: Region; duration: number; dx: number; dy: number } +export interface Action { name: string; frames: Frame[]; loop: boolean; anchor: AnchorMode } +export interface Project { + version: 1; + name: string; + actions: Action[]; + scale: number; + padding: number; + background: string; // "none" | "auto" | "#rrggbb":把纯色底变透明 + output: string; +} + +const slug = (s: string) => s.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "_").replace(/^_+|_+$/g, "") || "action"; + +export function normalizeProject(raw: any): { project: Project; warnings: string[] } { + const warnings: string[] = []; + const actions: Action[] = []; + const seen = new Set(); + for (const a of Array.isArray(raw?.actions) ? raw.actions : []) { + let name = slug(String(a?.name ?? "")); + for (let k = 2; seen.has(name); k++) name = `${slug(String(a?.name ?? ""))}_${k}`; + const fps = Number(a?.fps); + const frames: Frame[] = (Array.isArray(a?.frames) ? a.frames : []).map((f: any) => { + if (typeof f?.source !== "string" || !f.source) throw new KitError("bad_frame", `Action ${name}: every frame needs a source image.`); + const r = f.region; + const region = r && [r.x, r.y, r.w, r.h].every((v) => Number.isInteger(v) && v >= 0) && r.w > 0 && r.h > 0 ? { x: r.x, y: r.y, w: r.w, h: r.h } : undefined; + const duration = Math.round(Number(f?.duration) || (fps > 0 ? 1000 / fps : 100)); + return { source: f.source, ...(region ? { region } : {}), duration: Math.max(10, Math.min(10_000, duration)), dx: Math.round(Number(f?.dx) || 0), dy: Math.round(Number(f?.dy) || 0) }; + }); + if (!frames.length) { + warnings.push(`Action "${name}" has no frames — dropped.`); + continue; + } + seen.add(name); + actions.push({ name, frames, loop: a?.loop !== false, anchor: ["auto", "feet", "center", "keep"].includes(a?.anchor) ? a.anchor : "auto" }); + } + if (!actions.length) throw new KitError("no_actions", "No actions with frames."); + const bg = String(raw?.background ?? "auto"); + return { + project: { + version: 1, + name: slug(String(raw?.name ?? "")) || "character", + actions, + scale: Math.max(1, Math.min(8, Math.round(Number(raw?.scale) || 1))), + padding: Math.max(0, Math.min(16, Math.round(Number(raw?.padding ?? 1)))), + background: bg === "none" || /^#[0-9a-f]{6}$/i.test(bg) ? bg.toLowerCase() : "auto", + output: String(raw?.output ?? "").replace(/^\/+|\/+$/g, "") || "sprites", + }, + warnings, + }; +} + +export function crop(src: Raster, r: Region): Raster { + const out = createRaster(r.w, r.h); + for (let y = 0; y < r.h; y++) { + const sy = r.y + y; + if (sy >= src.height) break; + const from = (sy * src.width + r.x) * 4; + const w = Math.max(0, Math.min(r.w, src.width - r.x)); + out.data.set(src.data.subarray(from, from + w * 4), y * r.w * 4); + } + return out; +} + +/** 纯色底变透明:auto = 左上角像素不透明时用它的颜色。 */ +export function keyBackground(img: Raster, mode: string): Raster { + if (mode === "none") return img; + let color: number[] | undefined; + if (mode === "auto") { + if (img.data[3] < 250) return img; + color = [img.data[0], img.data[1], img.data[2]]; + } else color = [1, 3, 5].map((i) => parseInt(mode.slice(i, i + 2), 16)); + const out = { width: img.width, height: img.height, data: new Uint8ClampedArray(img.data) }; + for (let i = 0; i < out.data.length; i += 4) { + if (Math.abs(out.data[i] - color[0]) + Math.abs(out.data[i + 1] - color[1]) + Math.abs(out.data[i + 2] - color[2]) <= 24) out.data[i + 3] = 0; + } + return out; +} + +export interface Box { x0: number; y0: number; x1: number; y1: number } // x1/y1 不含 +export function opaqueBox(img: Raster, threshold = 8): Box | undefined { + let x0 = img.width, y0 = img.height, x1 = -1, y1 = -1; + for (let y = 0; y < img.height; y++) + for (let x = 0; x < img.width; x++) + if (img.data[(y * img.width + x) * 4 + 3] > threshold) { + if (x < x0) x0 = x; + if (x > x1) x1 = x; + if (y < y0) y0 = y; + if (y > y1) y1 = y; + } + return x1 < 0 ? undefined : { x0, y0, x1: x1 + 1, y1: y1 + 1 }; +} + +/** 锚点:feet = 不透明像素的水平重心、贴着最低点;center = 包围盒中心;keep = 原画布底边中点(保持原位置,跳跃等动作用)。 */ +export function anchorOf(img: Raster, box: Box, mode: Exclude): [number, number] { + if (mode === "keep") return [Math.floor(img.width / 2), img.height]; + if (mode === "center") return [Math.round((box.x0 + box.x1) / 2), Math.round((box.y0 + box.y1) / 2)]; + // 水平方向用全部不透明像素的重心(躯干占主导,跑步时比脚的位置稳定),垂直方向贴着最低点 + let sum = 0, n = 0; + for (let y = box.y0; y < box.y1; y++) + for (let x = box.x0; x < box.x1; x++) + if (img.data[(y * img.width + x) * 4 + 3] > 8) { + sum += x; + n++; + } + return [n ? Math.round(sum / n + 0.5) : Math.round((box.x0 + box.x1) / 2), box.y1]; +} + +export interface Placed { action: string; index: number; name: string; img: Raster; box: Box; anchor: [number, number]; duration: number; x: number; y: number } +export interface Layout { + cellW: number; + cellH: number; + pivot: [number, number]; // 像素(未缩放),在单元格内 + width: number; + height: number; + frames: Placed[]; + modes: Record>; + empty: string[]; +} + +/** 统一单元格:所有帧按锚点对齐到同一个点,单元格大小取所有帧的最大外扩;每个动作从新的一行开始。 */ +export function layout(p: Project, load: (f: Frame) => Raster, maxWidth = 4096): Layout { + const items: Omit[] = []; + const modes: Layout["modes"] = {}; + const empty: string[] = []; + for (const a of p.actions) { + const imgs = a.frames.map((f) => load(f)); + // 同尺寸画布、且画布四周留有透明边(不是裁切过的)→ 原画已经对齐好,保持原位置 + const sameSize = imgs.every((i) => i.width === imgs[0].width && i.height === imgs[0].height); + const padded = imgs.some((i) => { + const b = opaqueBox(i); + return !!b && (b.x0 > 0 || b.y0 > 0 || b.x1 < i.width || b.y1 < i.height); + }); + const mode = a.anchor === "auto" ? (sameSize && padded && imgs.length > 1 ? "keep" : "feet") : a.anchor; + modes[a.name] = mode; + imgs.forEach((img, i) => { + const f = a.frames[i]; + const name = `${a.name}_${String(i + 1).padStart(2, "0")}`; + const box = opaqueBox(img) ?? { x0: 0, y0: 0, x1: 1, y1: 1 }; + if (!opaqueBox(img)) empty.push(name); + const [ax, ay] = anchorOf(img, box, mode); + items.push({ action: a.name, index: i, name, img, box, anchor: [ax - f.dx, ay - f.dy], duration: f.duration }); + }); + } + let left = 0, right = 0, up = 0, down = 0; + for (const it of items) { + left = Math.max(left, it.anchor[0] - it.box.x0); + right = Math.max(right, it.box.x1 - it.anchor[0]); + up = Math.max(up, it.anchor[1] - it.box.y0); + down = Math.max(down, it.box.y1 - it.anchor[1]); + } + // 左右对称,方便翻转朝向 + const half = Math.max(left, right); + const cellW = 2 * half + 2 * p.padding; + const cellH = up + down + 2 * p.padding; + const cols = Math.max(1, Math.min(Math.max(...p.actions.map((a) => a.frames.length)), Math.floor(maxWidth / (cellW * p.scale)))); + const frames: Placed[] = []; + let row = 0; + for (const a of p.actions) { + const list = items.filter((it) => it.action === a.name); + list.forEach((it, i) => frames.push({ ...it, x: (i % cols) * cellW, y: (row + Math.floor(i / cols)) * cellH })); + row += Math.ceil(list.length / cols); + } + return { cellW, cellH, pivot: [p.padding + half, p.padding + up], width: cols * cellW, height: row * cellH, frames, modes, empty }; +} + +/** 合成图集(未缩放)。 */ +export function compose(l: Layout): Raster { + const out = createRaster(l.width, l.height); + for (const f of l.frames) { + const ox = f.x + l.pivot[0] - f.anchor[0]; + const oy = f.y + l.pivot[1] - f.anchor[1]; + for (let y = f.box.y0; y < f.box.y1; y++) + for (let x = f.box.x0; x < f.box.x1; x++) { + const s = (y * f.img.width + x) * 4; + if (!f.img.data[s + 3]) continue; + const tx = ox + x, ty = oy + y; + if (tx < f.x || ty < f.y || tx >= f.x + l.cellW || ty >= f.y + l.cellH) continue; + out.data.set(f.img.data.subarray(s, s + 4), (ty * l.width + tx) * 4); + } + } + return out; +} + +/** 整数倍最近邻放大(像素画不糊)。 */ +export function upscale(img: Raster, k: number): Raster { + if (k === 1) return img; + const out = createRaster(img.width * k, img.height * k); + for (let y = 0; y < out.height; y++) + for (let x = 0; x < out.width; x++) { + const s = (Math.floor(y / k) * img.width + Math.floor(x / k)) * 4; + out.data.set(img.data.subarray(s, s + 4), (y * out.width + x) * 4); + } + return out; +} + +/** 按网格切整张精灵图:by = row 时每行一个动作,column 时每列一个动作;全透明的格子跳过。 */ +export function sliceSheet(sheet: Raster, source: string, grid: { cols?: number; rows?: number; width?: number; height?: number }, by: "row" | "column", names: string[], background: string, fps: number) { + let cw = grid.width ?? (grid.cols ? Math.floor(sheet.width / grid.cols) : undefined); + let ch = grid.height ?? (grid.rows ? Math.floor(sheet.height / grid.rows) : undefined); + if (!cw && !ch && sheet.width > sheet.height && sheet.width % sheet.height === 0) cw = ch = sheet.height; // 单行等宽条 + if (!cw && ch) cw = ch; + if (!ch && cw) ch = cw; + if (!cw || !ch) throw new KitError("need_grid", `${source} is ${sheet.width}×${sheet.height}. Pass grid: {width, height} (cell size in px) or {cols, rows}.`); + const cols = Math.floor(sheet.width / cw); + const rows = Math.floor(sheet.height / ch); + const keyed = keyBackground(sheet, background); + const lines = by === "row" ? rows : cols; + const per = by === "row" ? cols : rows; + const actions: Action[] = []; + for (let l = 0; l < lines; l++) { + const frames: Frame[] = []; + for (let k = 0; k < per; k++) { + const [c, r] = by === "row" ? [k, l] : [l, k]; + const region = { x: c * cw, y: r * ch, w: cw, h: ch }; + if (opaqueBox(crop(keyed, region))) frames.push({ source, region, duration: Math.round(1000 / fps), dx: 0, dy: 0 }); + } + if (frames.length) actions.push({ name: names[actions.length] ?? `${by}${l + 1}`, frames, loop: true, anchor: "auto" }); + } + return { actions, cell: [cw, ch] as [number, number], cols, rows }; +} + +/** 从文件名分组:子文件夹名,或去掉末尾编号后的名字(再去掉所有组共同的前缀)。 */ +export function groupFiles(files: string[], fps: number): Action[] { + const coll = new Intl.Collator(undefined, { numeric: true }); + const groups = new Map(); + const sub = new Set(files.map((f) => f.split("/").slice(0, -1).join("/"))); + for (const f of [...files].sort(coll.compare)) { + const parts = f.split("/"); + const stem = parts[parts.length - 1].replace(/\.[^.]+$/, ""); + const key = sub.size > 1 ? parts[parts.length - 2] ?? "default" : stem.replace(/[\s_.-]*\d+$/, "") || "default"; + groups.set(key, [...(groups.get(key) ?? []), f]); + } + let keys = [...groups.keys()]; + if (keys.length > 1) { + let prefix = keys[0]; + for (const k of keys) while (!k.startsWith(prefix)) prefix = prefix.slice(0, -1); + const cut = prefix.match(/^.*[\s_.-]/)?.[0] ?? ""; + if (cut && keys.every((k) => k.length > cut.length)) keys = keys.map((k) => k.slice(cut.length)); + } + return [...groups.values()].map((list, i) => ({ name: keys[i], frames: list.map((source) => ({ source, duration: Math.round(1000 / fps), dx: 0, dy: 0 })), loop: true, anchor: "auto" })); +} diff --git a/ui-plugins/sprite-animation-pack/test/tools.test.ts b/ui-plugins/sprite-animation-pack/test/tools.test.ts new file mode 100644 index 00000000..e7f0bbc8 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/test/tools.test.ts @@ -0,0 +1,129 @@ +import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { beforeAll, describe, expect, it } from "vitest"; +import { createRaster, decodeImage, encodePng, type Raster } from "../src/kit/raster.ts"; +import { groupFiles, normalizeProject, opaqueBox } from "../src/sprites.ts"; +import { createServer } from "../src/server.ts"; + +let workspace: string; +let client: Client; +const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; +const fill = (img: Raster, x: number, y: number, w: number, h: number, c: [number, number, number, number]) => { + for (let j = y; j < y + h; j++) for (let i = x; i < x + w; i++) img.data.set(c, (j * img.width + i) * 4); +}; +/** 小人:头 + 身体 + 两只脚,脚的位置随帧变化;trimmed = 裁到内容。 */ +function dude(frame: number, lift = 0) { + const img = createRaster(20, 30); + fill(img, 7, 2 - lift + 4, 6, 6, [240, 200, 160, 255]); + fill(img, 6, 12 - lift, 8, 10, [30, 90, 200, 255]); + fill(img, 6 + (frame % 2), 22 - lift, 2, 6, [40, 40, 40, 255]); + fill(img, 12 - (frame % 2), 22 - lift, 2, 6, [40, 40, 40, 255]); + return img; +} +function trim(img: Raster) { + const b = opaqueBox(img)!; + const out = createRaster(b.x1 - b.x0, b.y1 - b.y0); + for (let y = b.y0; y < b.y1; y++) out.data.set(img.data.subarray((y * img.width + b.x0) * 4, (y * img.width + b.x1) * 4), (y - b.y0) * out.width * 4); + return out; +} + +beforeAll(async () => { + workspace = await mkdtemp(join(tmpdir(), "sprites-")); + await mkdir(join(workspace, "hero")); + for (let i = 0; i < 4; i++) await writeFile(join(workspace, `hero/hero_run_${i + 1}.png`), encodePng(trim(dude(i)))); + for (let i = 0; i < 2; i++) await writeFile(join(workspace, `hero/hero_idle_${i + 1}.png`), encodePng(trim(dude(0, i)))); + // 品红底的精灵图:3 列 × 2 行,第二行只有 2 帧(跳跃,保持原位) + const sheet = createRaster(60, 60, [255, 0, 255, 255]); + const put = (img: Raster, cx: number, cy: number) => { for (let y = 0; y < 30; y++) for (let x = 0; x < 20; x++) { const s = (y * 20 + x) * 4; if (img.data[s + 3]) sheet.data.set(img.data.subarray(s, s + 4), ((cy + y) * 60 + cx + x) * 4); } }; + for (let i = 0; i < 3; i++) put(dude(i), i * 20, 0); + put(dude(0, 0), 0, 30); + put(dude(0, 4), 20, 30); + await writeFile(join(workspace, "sheet.png"), encodePng(sheet)); + const server = createServer({ workspaceRoot: workspace, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + client = new Client({ name: "t", version: "1" }); + await client.connect(b); +}); + +describe("grouping and normalising", () => { + it("groups frames by name or sub-folder", () => { + const g = groupFiles(["a/hero_run_10.png", "a/hero_run_2.png", "a/hero_idle-1.png", "a/hero_run_1.png"], 12); + expect(g.map((x) => [x.name, x.frames.map((f) => f.source.split("/")[1])])).toEqual([["idle", ["hero_idle-1.png"]], ["run", ["hero_run_1.png", "hero_run_2.png", "hero_run_10.png"]]]); + expect(g[0].frames[0].duration).toBe(83); + expect(groupFiles(["x/walk/1.png", "x/walk/2.png", "x/jump/1.png"], 10).map((a) => a.name)).toEqual(["jump", "walk"]); + }); + it("normalises names, durations and settings", () => { + const { project, warnings } = normalizeProject({ name: "My Hero!", actions: [{ name: "Run Fast", fps: 8, frames: [{ source: "a.png" }] }, { name: "run fast", frames: [{ source: "b.png", duration: 5 }] }, { name: "x", frames: [] }], scale: 20 }); + expect(project.name).toBe("my_hero"); + expect(project.actions.map((a) => [a.name, a.frames[0].duration])).toEqual([["run_fast", 125], ["run_fast_2", 10]]); + expect(project.scale).toBe(8); + expect(warnings[0]).toMatch(/"x" has no frames/); + }); +}); + +describe("tools", () => { + it("aligns trimmed frames on the feet and exports every format", async () => { + const r = await call("sprite_open", { frames: "hero", fps: 12 }); + expect(r.isError).toBeFalsy(); + expect(r.content[0].text).toMatch(/idle 2f 12fps loop anchor=feet \(auto\); run 4f 12fps loop anchor=feet/); + const p = r.structuredContent.project; + p.actions[0].loop = false; + const x = await call("sprite_export", { project: { ...p, scale: 2 } }); + expect(x.structuredContent.files).toEqual(["sprites/hero/hero.png", "sprites/hero/hero.json", "sprites/hero/hero.tres", "sprites/hero/hero.unity.md", "sprites/hero/hero.phaser.js", "sprites/hero/hero.sprites.json"]); + const [cw, ch] = x.structuredContent.cell; + const atlas = decodeImage(await readFile(join(workspace, "sprites/hero/hero.png"))); + expect([atlas.width, atlas.height]).toEqual([4 * cw * 2, 2 * ch * 2]); + // 每帧最低的不透明像素都在同一条地面线上 + const [px, py] = x.structuredContent.pivot; + for (let i = 0; i < 4; i++) { + const cell = createRaster(cw * 2, ch * 2); + for (let y = 0; y < ch * 2; y++) cell.data.set(atlas.data.subarray(((ch * 2 + y) * atlas.width + i * cw * 2) * 4, ((ch * 2 + y) * atlas.width + (i + 1) * cw * 2) * 4), y * cw * 2 * 4); + expect(opaqueBox(cell)!.y1).toBe(py * 2); + } + expect(px * 2).toBe(cw); + const json = JSON.parse(await readFile(join(workspace, "sprites/hero/hero.json"), "utf8")); + expect(json.meta.frameTags).toEqual([{ name: "idle", from: 0, to: 1, direction: "forward", repeat: "1" }, { name: "run", from: 2, to: 5, direction: "forward" }]); + expect(json.frames.run_02.frame).toEqual({ x: cw * 2, y: ch * 2, w: cw * 2, h: ch * 2 }); + expect(json.frames.run_02.duration).toBe(83); + const tres = await readFile(join(workspace, "sprites/hero/hero.tres"), "utf8"); + expect(tres).toMatch(/^\[gd_resource type="SpriteFrames" load_steps=8 format=3\]/); + expect(tres).toContain('[ext_resource type="Texture2D" path="hero.png" id="1_atlas"]'); + expect(tres).toContain(`region = Rect2(${cw * 2}, ${ch * 2}, ${cw * 2}, ${ch * 2})`); + expect(tres).toMatch(/"loop": false,\n"name": &"idle",\n"speed": 12\.048/); + const unity = await readFile(join(workspace, "sprites/hero/hero.unity.md"), "utf8"); + expect(unity).toContain(`Pixel Size **${cw * 2} × ${ch * 2}**`); + expect(unity).toContain(`run_01 (0, 0, ${cw * 2}, ${ch * 2})`); + expect(await readFile(join(workspace, "sprites/hero/hero.phaser.js"), "utf8")).toContain('this.anims.createFromAseprite("hero");'); + }); + it("slices a sheet, keys out the background and keeps pre-aligned jumps", async () => { + const r = await call("sprite_open", { sheet: "sheet.png", grid: { width: 20, height: 30 }, actions: ["walk", "jump"] }); + expect(r.content[0].text).toMatch(/Sliced sheet\.png into 3×2 cells of 20×30 px[\s\S]*walk 3f .* anchor=keep \(auto\); jump 2f .* anchor=keep/); + const prev = await call("atlas_preview", { project: r.structuredContent.project }); + const img = decodeImage(Buffer.from(prev.structuredContent.data, "base64")); + expect(img.data[3]).toBe(0); // 品红底已去掉 + const [cw, ch] = prev.structuredContent.cell; + const jumpFrames = prev.structuredContent.frames.filter((f: any) => f.action === "jump"); + const box = (f: any) => { const c = createRaster(cw, ch); for (let y = 0; y < ch; y++) c.data.set(img.data.subarray(((f.y + y) * img.width + f.x) * 4, ((f.y + y) * img.width + f.x + cw) * 4), y * cw * 4); return opaqueBox(c)!; }; + expect(box(jumpFrames[0]).y1 - box(jumpFrames[1]).y1).toBe(4); // 跳起 4px 保留 + const feet = await call("atlas_preview", { project: { ...r.structuredContent.project, actions: r.structuredContent.project.actions.map((a: any) => ({ ...a, anchor: "feet" })) } }); + const img2 = decodeImage(Buffer.from(feet.structuredContent.data, "base64")); + const box2 = (f: any) => { const [w, hh] = feet.structuredContent.cell; const c = createRaster(w, hh); for (let y = 0; y < hh; y++) c.data.set(img2.data.subarray(((f.y + y) * img2.width + f.x) * 4, ((f.y + y) * img2.width + f.x + w) * 4), y * w * 4); return opaqueBox(c)!; }; + const jf = feet.structuredContent.frames.filter((f: any) => f.action === "jump"); + expect(box2(jf[0]).y1).toBe(box2(jf[1]).y1); + }); + it("applies nudges and explains errors", async () => { + const r = await call("sprite_open", { frames: "hero" }); + const p = r.structuredContent.project; + const before = (await call("atlas_preview", { project: p })).structuredContent; + p.actions[1].frames[0].dy = -3; + const after = (await call("atlas_preview", { project: p })).structuredContent; + expect(after.cell[1]).toBe(before.cell[1] + 3); + expect((await call("sprite_open", { sheet: "sheet.png" })).content[0].text).toMatch(/sheet\.png is 60×60\. Pass grid/); + expect((await call("sprite_open", { frames: "nope" })).isError).toBe(true); + expect((await call("sprite_save", { project: { actions: [{ name: "a", frames: [{ source: "x.jpg" }] }] } })).content[0].text).toMatch(/must be PNG/); + }); +}); diff --git a/ui-plugins/sprite-animation-pack/test/workspace-links.test.ts b/ui-plugins/sprite-animation-pack/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); diff --git a/ui-plugins/sprite-animation-pack/tsconfig.json b/ui-plugins/sprite-animation-pack/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/sprite-animation-pack/ui/env.d.ts b/ui-plugins/sprite-animation-pack/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/sprite-animation-pack/ui/kit.css b/ui-plugins/sprite-animation-pack/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/sprite-animation-pack/ui/kit.css @@ -0,0 +1,34 @@ +:root { --bg:#fff; --fg:#1d1f23; --muted:#6b7280; --line:#e5e7eb; --panel:#f7f7f8; --accent:#2563eb; --warn:#b45309; --warnbg:#fef3c7; --bad:#b91c1c; --badbg:#fee2e2; --okbg:#dcfce7; --ok:#15803d; } +[data-theme="dark"] { --bg:#18191b; --fg:#e8e8ea; --muted:#9ca3af; --line:#2e3035; --panel:#222327; --accent:#60a5fa; --warn:#fbbf24; --warnbg:#3b2f10; --bad:#f87171; --badbg:#3b1717; --okbg:#12301d; --ok:#4ade80; } +* { box-sizing: border-box; } +html, body { margin:0; background:var(--bg); color:var(--fg); font:13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; } +#root { padding: 12px; } +h1 { font-size: 15px; margin: 0 0 8px; } +h2 { font-size: 13px; margin: 14px 0 6px; color: var(--muted); font-weight: 600; text-transform: none; } +button { font: inherit; border:1px solid var(--line); background:var(--panel); color:var(--fg); border-radius:6px; padding:5px 10px; cursor:pointer; } +button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +button:disabled { opacity:.5; cursor:default; } +input, select, textarea { font: inherit; color: var(--fg); background: var(--bg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; } +input[type="color"] { padding: 0; width: 32px; height: 26px; } +input[type="range"] { padding: 0; } +label { display:flex; gap:6px; align-items:center; } +.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin: 6px 0; } +.muted { color: var(--muted); } +.card { border:1px solid var(--line); border-radius:8px; padding:10px; background:var(--panel); margin: 8px 0; } +.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:8px; } +.thumb { border:1px solid var(--line); border-radius:6px; overflow:hidden; background: var(--bg); cursor:pointer; position:relative; } +.thumb img { width:100%; display:block; aspect-ratio:1; object-fit:contain; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; } +.thumb .cap { padding:4px 6px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +.thumb.selected { outline: 2px solid var(--accent); } +.badge { display:inline-block; font-size:11px; padding:1px 6px; border-radius:10px; background:var(--warnbg); color:var(--warn); } +.badge.bad { background: var(--badbg); color: var(--bad); } +.badge.ok { background: var(--okbg); color: var(--ok); } +table.data { border-collapse: collapse; width: 100%; } +table.data td, table.data th { border:1px solid var(--line); padding:3px 6px; text-align:left; vertical-align:top; } +table.data th { background: var(--panel); } +.toast { position: fixed; right: 12px; bottom: 12px; padding: 8px 12px; border-radius: 6px; background: var(--okbg); color: var(--ok); z-index: 10; max-width: 80%; } +.toast.error { background: var(--badbg); color: var(--bad); } +.empty { padding: 24px; text-align:center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; } +.busy { opacity:.6; pointer-events:none; } +.split { display:grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 10px; } +@media (max-width: 640px) { .split { grid-template-columns: 1fr; } } diff --git a/ui-plugins/sprite-animation-pack/ui/kit.ts b/ui-plugins/sprite-animation-pack/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call>(name: string, args: Record = {}, timeout = 300_000): Promise { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h( + tag: K, + props: Record = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/sprite-animation-pack/ui/main.ts b/ui-plugins/sprite-animation-pack/ui/main.ts new file mode 100644 index 00000000..7a7807d0 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/ui/main.ts @@ -0,0 +1,199 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +interface Frame { source: string; region?: { x: number; y: number; w: number; h: number }; duration: number; dx: number; dy: number } +interface Action { name: string; frames: Frame[]; loop: boolean; anchor: "auto" | "feet" | "center" | "keep" } +interface Project { version: 1; name: string; actions: Action[]; scale: number; padding: number; background: string; output: string } +interface Rect { action: string; index: number; name: string; x: number; y: number; duration: number } + +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const state: { + p?: Project; sel: number; frame?: number; playing: boolean; onion: boolean; zoom: number; warnings: string[]; modes: Record; + atlas?: HTMLImageElement; rects: Rect[]; cell: [number, number]; pivot: [number, number]; files?: { pngs: string[]; folders: string[]; projects: string[] }; dirty: boolean; exported?: string[]; exportedPng?: string; +} = { sel: 0, playing: true, onion: false, zoom: 6, warnings: [], modes: {}, rects: [], cell: [1, 1], pivot: [0, 0], dirty: false }; +const root = document.getElementById("root")!; + +async function busy(work: () => Promise, label = ""): Promise { + root.classList.add("busy"); + const st = document.getElementById("status"); + if (st) st.textContent = label; + try { return await work(); } catch (error) { toast(error instanceof Error ? error.message : String(error), "error"); return undefined; } finally { root.classList.remove("busy"); if (st) st.textContent = ""; } +} + +function load(v: Record) { + state.p = v.project as Project; + state.warnings = (v.warnings as string[]) ?? []; + state.modes = (v.modes as Record) ?? {}; + if (state.sel >= state.p.actions.length) state.sel = 0; + state.dirty = false; + render(); + void refresh(); +} +onToolResult((v) => { + if (!v) return; + if (v.kind === "project") { state.exported = undefined; load(v); } + if (v.kind === "exported") { load(v); showExported(v.files as string[]); } +}); + +let token = 0; +async function refresh() { + if (!state.p) return; + const my = ++token; + const r = await call<{ data: string; frames: Rect[]; cell: [number, number]; pivot: [number, number]; modes: Record; warnings: string[] }>("atlas_preview", { project: state.p }).catch((e) => { toast(String(e?.message ?? e), "error"); return undefined; }); + if (!r || my !== token) return; + const img = new Image(); + img.src = `data:image/png;base64,${r.data}`; + await img.decode().catch(() => undefined); + if (my !== token) return; + Object.assign(state, { atlas: img, rects: r.frames, cell: r.cell, pivot: r.pivot, modes: r.modes, warnings: r.warnings }); + render(); +} +let refreshTimer: ReturnType | undefined; +function changed(rerender = true) { + state.dirty = true; + if (rerender) render(); + clearTimeout(refreshTimer); + refreshTimer = setTimeout(() => void refresh(), 120); +} + +function showExported(files: string[]) { + state.exported = files; + render(); +} + +const actionRects = () => state.rects.filter((r) => r.action === state.p!.actions[state.sel]?.name); +function drawFrame(ctx: CanvasRenderingContext2D, r: Rect, zoom: number, alpha = 1) { + if (!state.atlas) return; + ctx.globalAlpha = alpha; + ctx.imageSmoothingEnabled = false; + ctx.drawImage(state.atlas, r.x, r.y, state.cell[0], state.cell[1], 0, 0, state.cell[0] * zoom, state.cell[1] * zoom); + ctx.globalAlpha = 1; +} + +let playIndex = 0; +let last = 0; +let acc = 0; +function tick(now: number) { + const canvas = document.getElementById("stage") as HTMLCanvasElement | null; + const rects = state.p ? actionRects() : []; + if (canvas && rects.length && state.atlas) { + const z = state.zoom; + const dt = last ? now - last : 0; + last = now; + if (state.playing) { + acc += dt; + while (acc >= (rects[playIndex % rects.length]?.duration ?? 100)) { + acc -= rects[playIndex % rects.length].duration; + playIndex++; + if (!state.p!.actions[state.sel].loop && playIndex >= rects.length) { playIndex = rects.length - 1; acc = 0; break; } + } + } + const i = state.playing ? playIndex % rects.length : Math.min(state.frame ?? 0, rects.length - 1); + const ctx = canvas.getContext("2d")!; + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (state.onion && rects.length > 1) drawFrame(ctx, rects[(i - 1 + rects.length) % rects.length], z, 0.3); + drawFrame(ctx, rects[i], z); + ctx.strokeStyle = "rgba(239,68,68,.7)"; + ctx.beginPath(); + ctx.moveTo(0, state.pivot[1] * z + 0.5); + ctx.lineTo(canvas.width, state.pivot[1] * z + 0.5); + ctx.moveTo(state.pivot[0] * z + 0.5, state.pivot[1] * z - 8); + ctx.lineTo(state.pivot[0] * z + 0.5, state.pivot[1] * z + 8); + ctx.stroke(); + const label = document.getElementById("flabel"); + if (label) label.textContent = `${i + 1} / ${rects.length}`; + } else last = now; + requestAnimationFrame(tick); +} +requestAnimationFrame(tick); + +function thumbs() { + const a = state.p!.actions[state.sel]; + const rects = actionRects(); + return a.frames.map((f, i) => { + const r = rects[i]; + const c = h("canvas", { width: state.cell[0] * 2, height: state.cell[1] * 2 }) as HTMLCanvasElement; + if (r) drawFrame(c.getContext("2d")!, r, 2); + const nudge = (dx: number, dy: number) => { f.dx += dx; f.dy += dy; changed(false); }; + return h("div", { class: `fr${!state.playing && state.frame === i ? " sel" : ""}`, onclick: () => { state.playing = false; state.frame = i; render(); } }, + c, + h("div", {}, `${i + 1}`, f.dx || f.dy ? h("span", { class: "muted" }, ` (${f.dx},${f.dy})`) : null), + h("input", { type: "number", min: 10, step: 10, value: f.duration, title: T("时长(毫秒)", "Duration (ms)"), onclick: (e: Event) => e.stopPropagation(), onchange: (e: Event) => { f.duration = Number((e.target as HTMLInputElement).value) || 100; changed(); } }), + h("div", { class: "nudge" }, + h("button", { title: T("左移 1px", "1 px left"), onclick: (e: Event) => { e.stopPropagation(); nudge(-1, 0); } }, "←"), + h("button", { title: T("上移 1px", "1 px up"), onclick: (e: Event) => { e.stopPropagation(); nudge(0, -1); } }, "↑"), + h("button", { title: T("下移 1px", "1 px down"), onclick: (e: Event) => { e.stopPropagation(); nudge(0, 1); } }, "↓"), + h("button", { title: T("右移 1px", "1 px right"), onclick: (e: Event) => { e.stopPropagation(); nudge(1, 0); } }, "→")), + h("div", { class: "nudge" }, + h("button", { title: T("前移", "Move earlier"), disabled: i === 0, onclick: (e: Event) => { e.stopPropagation(); a.frames.splice(i - 1, 0, ...a.frames.splice(i, 1)); state.frame = i - 1; changed(); } }, "◀"), + h("button", { title: T("删除这帧", "Delete frame"), disabled: a.frames.length < 2, onclick: (e: Event) => { e.stopPropagation(); a.frames.splice(i, 1); state.frame = Math.max(0, i - 1); changed(); } }, "✕"), + h("button", { title: T("后移", "Move later"), disabled: i === a.frames.length - 1, onclick: (e: Event) => { e.stopPropagation(); a.frames.splice(i + 1, 0, ...a.frames.splice(i, 1)); state.frame = i + 1; changed(); } }, "▶"))); + }); +} + +function render() { + applyTheme(); + const p = state.p; + const toolbar = h("div", { class: "toolbar" }, + h("b", {}, T("游戏角色动作包", "Sprite Animation Pack")), + h("select", { onchange: (e: Event) => { const v = (e.target as HTMLSelectElement).value; if (!v) return; const [kind, path] = [v.slice(0, 2), v.slice(2)]; void busy(async () => load(await call("sprite_open", kind === "p:" ? { project: path } : kind === "s:" ? { sheet: path } : { frames: path })), T("读取中…", "Loading…")); } }, + h("option", { value: "" }, T("打开动作帧文件夹 / 精灵图 / 工程…", "Open frames folder / sheet / project…")), + ...(state.files?.projects ?? []).map((f) => h("option", { value: `p:${f}` }, `📁 ${f}`)), + ...(state.files?.folders ?? []).map((f) => h("option", { value: `f:${f}` }, `🗂 ${f}/`)), + ...(state.files?.pngs ?? []).map((f) => h("option", { value: `s:${f}` }, `🖼 ${f}`))), + h("span", { id: "status", class: "muted" }), + h("span", { class: "spacer" }), + p ? h("button", { id: "save", disabled: !state.dirty, onclick: () => void busy(async () => { load(await call("sprite_save", { project: p })); toast(T("已保存", "Saved")); }, T("保存中…", "Saving…")) }, T("保存", "Save")) : null, + p ? h("button", { class: "primary", onclick: () => void busy(async () => { const r = await call>("sprite_export", { project: p }); load(r); showExported(r.files as string[]); toast(T("已导出", "Exported")); }, T("导出中…", "Exporting…")) }, T("导出动作包", "Export pack")) : null, + ); + if (!p) { + put(root, toolbar, h("div", { class: "empty" }, T("选一个装着动作帧的文件夹(run_01.png、run_02.png… 或按动作分子文件夹),或者一整张精灵图;也可以对 Agent 说“把 hero.png 按 32×32 切开,三行分别是 idle、run、jump,导出 Godot 和 Phaser 用的动作包”。", "Pick a folder of frames (run_01.png, run_02.png… or one sub-folder per action) or a whole sprite sheet; or ask the agent to slice hero.png into 32×32 cells (rows idle, run, jump) and export a pack for Godot and Phaser."))); + return; + } + const a = p.actions[state.sel]; + const acts = h("div", { class: "acts" }, + ...p.actions.map((x, i) => h("div", { class: `act${i === state.sel ? " sel" : ""}`, onclick: () => { if (state.sel !== i) { state.sel = i; state.frame = 0; playIndex = 0; render(); } } }, + h("div", { class: "r" }, h("input", { type: "text", value: x.name, onchange: (e: Event) => { x.name = (e.target as HTMLInputElement).value; changed(); } }), h("span", { class: "muted" }, `${x.frames.length}f`), + h("button", { title: T("删除动作", "Delete action"), disabled: p.actions.length < 2, onclick: (e: Event) => { e.stopPropagation(); p.actions.splice(i, 1); state.sel = 0; changed(); } }, "✕")), + h("div", { class: "r" }, "fps", h("input", { class: "num", type: "number", min: 1, max: 60, value: Math.round(1000 / x.frames[0].duration), title: T("把这个动作所有帧设成同一速度", "Set all frames of this action to this speed"), onchange: (e: Event) => { const fps = Number((e.target as HTMLInputElement).value) || 10; for (const f of x.frames) f.duration = Math.round(1000 / fps); changed(); } }), + h("label", {}, h("input", { type: "checkbox", checked: x.loop, onchange: (e: Event) => { x.loop = (e.target as HTMLInputElement).checked; changed(); } }), T("循环", "Loop"))), + h("div", { class: "r" }, T("对齐", "Align"), h("select", { onclick: (e: Event) => e.stopPropagation(), onchange: (e: Event) => { x.anchor = (e.target as HTMLSelectElement).value as Action["anchor"]; changed(); } }, + ...([["auto", T(`自动(${state.modes[x.name] === "keep" ? "保持原位" : "脚底"})`, `Auto (${state.modes[x.name] ?? "…"})`)], ["feet", T("脚底对齐", "Feet")], ["center", T("中心对齐", "Center")], ["keep", T("保持原位", "Keep position")]] as const).map(([v, l]) => h("option", { value: v, selected: x.anchor === v }, l))))))); + const [cw, ch] = state.cell; + const stage = h("div", { class: "stage" }, + h("canvas", { id: "stage", width: cw * state.zoom, height: ch * state.zoom }), + h("div", { class: "controls" }, + h("button", { onclick: () => { state.playing = !state.playing; state.frame = playIndex % Math.max(1, a.frames.length); render(); } }, state.playing ? T("❚❚ 暂停", "❚❚ Pause") : T("▶ 播放", "▶ Play")), + h("button", { onclick: () => { state.playing = false; state.frame = ((state.frame ?? 0) - 1 + a.frames.length) % a.frames.length; render(); } }, "⏮"), + h("button", { onclick: () => { state.playing = false; state.frame = ((state.frame ?? 0) + 1) % a.frames.length; render(); } }, "⏭"), + h("span", { id: "flabel", class: "muted" }), + h("label", {}, h("input", { type: "checkbox", checked: state.onion, onchange: (e: Event) => { state.onion = (e.target as HTMLInputElement).checked; } }), T("洋葱皮", "Onion skin")), + h("label", {}, T("放大", "Zoom"), h("input", { type: "range", min: 1, max: 12, value: state.zoom, oninput: (e: Event) => { state.zoom = Number((e.target as HTMLInputElement).value); const c = document.getElementById("stage") as HTMLCanvasElement; c.width = cw * state.zoom; c.height = ch * state.zoom; } })), + h("span", { class: "muted small" }, T(`单元格 ${cw}×${ch},红线 = 锚点 / 地面`, `Cell ${cw}×${ch}; red = anchor / ground`))), + h("div", { class: "strip" }, ...thumbs())); + const settings = h("div", { class: "settings" }, + h("label", {}, h("span", {}, T("名称", "Name")), h("input", { type: "text", value: p.name, onchange: (e: Event) => { p.name = (e.target as HTMLInputElement).value; changed(); } })), + h("label", {}, h("span", {}, T("放大倍数", "Scale")), h("select", { onchange: (e: Event) => { p.scale = Number((e.target as HTMLSelectElement).value); changed(); } }, ...[1, 2, 3, 4, 6, 8].map((k) => h("option", { value: k, selected: p.scale === k }, `${k}×`)))), + h("label", {}, h("span", {}, T("留边", "Padding")), h("input", { type: "number", min: 0, max: 16, value: p.padding, style: { width: "60px" }, onchange: (e: Event) => { p.padding = Number((e.target as HTMLInputElement).value) || 0; changed(); } }), "px"), + h("label", {}, h("span", {}, T("去底色", "Background")), h("select", { onchange: (e: Event) => { p.background = (e.target as HTMLSelectElement).value; changed(); } }, + ...([["auto", T("自动(左上角是纯色时去掉)", "Auto (key out a solid corner colour)")], ["none", T("不处理", "Keep")], ["#ff00ff", T("品红 #ff00ff", "Magenta #ff00ff")], ["#00ff00", T("绿幕 #00ff00", "Green #00ff00")]] as const).map(([v, l]) => h("option", { value: v, selected: p.background === v }, l)))), + h("label", {}, h("span", {}, T("输出", "Output")), h("input", { type: "text", value: p.output, onchange: (e: Event) => { p.output = (e.target as HTMLInputElement).value; changed(); } })), + h("div", { class: "small muted" }, T("导出:图集 PNG、Aseprite/Phaser JSON、Godot .tres、Unity 切片说明。", "Exports: atlas PNG, Aseprite/Phaser JSON, Godot .tres, Unity slicing notes.")), + state.atlas ? h("div", { class: "atlas" }, h("div", { class: "small muted" }, T(`图集 ${state.atlas.width * p.scale}×${state.atlas.height * p.scale}`, `Atlas ${state.atlas.width * p.scale}×${state.atlas.height * p.scale}`)), h("img", { src: state.atlas.src })) : null); + put(root, toolbar, + state.warnings.length ? h("div", { class: "card small" }, ...state.warnings.map((w) => h("div", {}, `⚠ ${w}`))) : null, + state.exported ? h("div", { class: "card small" }, h("b", {}, T("已导出:", "Exported: ")), state.exported.join(" · ")) : null, + h("div", { class: "layout" }, acts, stage, settings)); +} + +onHostContext(() => render()); +render(); +void initHost("sprite-animation-pack", "0.1.0").then(async () => { + state.files = await call<{ pngs: string[]; folders: string[]; projects: string[] }>("workspace_files").catch(() => undefined); + render(); +}); diff --git a/ui-plugins/sprite-animation-pack/ui/panel.css b/ui-plugins/sprite-animation-pack/ui/panel.css new file mode 100644 index 00000000..8095b9dd --- /dev/null +++ b/ui-plugins/sprite-animation-pack/ui/panel.css @@ -0,0 +1,26 @@ +.toolbar { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding-bottom:8px; border-bottom:1px solid var(--line); margin-bottom:8px; } +.spacer { flex:1; } +.layout { display:grid; grid-template-columns: 230px minmax(0,1fr) 220px; gap: 12px; align-items:start; } +@media (max-width: 900px) { .layout { grid-template-columns: 1fr; } } +.acts { display:flex; flex-direction:column; gap:6px; } +.act { border:1px solid var(--line); border-radius:8px; padding:6px; background: var(--panel); cursor:pointer; font-size:12px; } +.act.sel { border-color:#3b82f6; box-shadow: 0 0 0 1px #3b82f6; } +.act .r { display:flex; gap:4px; align-items:center; margin-top:3px; } +.act input[type=text] { flex:1; min-width:0; font-weight:600; } +.act input.num { width:52px; } +.act select { font-size: 11px; } +.stage { display:flex; flex-direction:column; align-items:center; gap:6px; } +.stage canvas { image-rendering: pixelated; border:1px solid var(--line); border-radius:8px; background-color:#fff; background-image: linear-gradient(45deg,#e5e7eb 25%,transparent 25%),linear-gradient(-45deg,#e5e7eb 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#e5e7eb 75%),linear-gradient(-45deg,transparent 75%,#e5e7eb 75%); background-size:16px 16px; background-position:0 0,0 8px,8px -8px,-8px 0; } +.controls { display:flex; gap:6px; align-items:center; flex-wrap:wrap; font-size:12px; } +.strip { display:flex; gap:6px; overflow-x:auto; padding:6px 2px; width:100%; } +.fr { flex:none; border:1px solid var(--line); border-radius:6px; padding:3px; font-size:10px; text-align:center; background: var(--panel); cursor:pointer; } +.fr.sel { border-color:#f59e0b; box-shadow: 0 0 0 1px #f59e0b; } +.fr canvas { image-rendering: pixelated; display:block; margin:0 auto 2px; background:#f8fafc; } +.fr input { width:46px; font-size:10px; } +.fr .nudge button { padding:0 3px; font-size:10px; } +.settings { display:flex; flex-direction:column; gap:6px; font-size:12px; } +.settings label { display:flex; gap:6px; align-items:center; } +.settings label > span { width:64px; color: var(--muted); } +.settings input[type=text], .settings select { flex:1; min-width:0; } +.atlas img { max-width:100%; image-rendering: pixelated; border:1px solid var(--line); background:#f1f5f9; } +.small { font-size: 11px; } diff --git a/ui-plugins/sprite-animation-pack/vitest.config.ts b/ui-plugins/sprite-animation-pack/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/sprite-animation-pack/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } });