diff --git a/AGENTS.md b/AGENTS.md index f91ff90..d920c57 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,10 +10,12 @@ packages/editor-recipe @lumorphia/editor-recipe 編集レシピ (zod)。ブラ packages/editor-engine @lumorphia/editor-engine 状態、描画、推論 (Worker)、下書き、CLI editor-models packages/editor-react @lumorphia/editor-react UI。 apps/web 単独アプリ (E2E の土台を兼ねる) -docs/adr/ 設計判断 +e2e/ E2E (prismtone から移した。apps/web を土台にして回す: #3) +docs/design/ 設計 (edit-recipe.md: レシピ、editor.md: 画面・描画・推論・テスト) +docs/adr/ 設計判断 (README.md に一覧と prismtone の番号との対応) ``` -パッケージの中身は lumorphia/prismtone から履歴ごと移す (#2)。 +パッケージの中身は lumorphia/prismtone から履歴ごと移した。コミットメッセージの `lumorphia/prismtone#N` は prismtone の Issue / PR。 ## 依存の方向 (ESLint が強制する。tooling/eslint-boundaries.test.ts が確かめる) diff --git a/README.md b/README.md index b17e515..e976efd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ | `@lumorphia/editor-engine` | 状態、描画 (PixiJS / WebGL)、推論 (Worker)、下書き | | `@lumorphia/editor-react` | UI (``) | -今はリポジトリの土台を作った段階。中身は prismtone から移す (#2)。開発の約束は [AGENTS.md](AGENTS.md)。 +中身は prismtone から履歴ごと移した (`git log --follow` で最初の現像までたどれる)。設計は [docs/design/](docs/design/)、判断は [docs/adr/](docs/adr/README.md)、開発の約束は [AGENTS.md](AGENTS.md)。 ## 開発 @@ -18,7 +18,9 @@ Node 24.21 以上と pnpm 12.8 以上。 ```sh pnpm install -pnpm test +pnpm test # 単体テスト (ビルド不要) +pnpm build # 各パッケージを dist に +node packages/editor-engine/dist/bin/editor-models.js fetch --out models # 認識のモデルと WASM ``` ## ライセンス diff --git a/docs/adr/0002-client-side-editing-and-export.md b/docs/adr/0002-client-side-editing-and-export.md new file mode 100644 index 0000000..5485535 --- /dev/null +++ b/docs/adr/0002-client-side-editing-and-export.md @@ -0,0 +1,52 @@ +# ADR-0002: 画像編集は PixiJS (WebGL) でブラウザ内に閉じ、最終書き出しもブラウザで行う + +> lumorphia/prismtone の ADR-0005 (https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0005-client-side-editing-and-export.md) を移植したもの (2026-10-06)。本文は当時のまま。パスは prismtone の中にあったころのもので、今は `packages/editor-*` にある。リンク、Issue 番号、本文中の ADR の番号は prismtone のもの (このリポジトリの番号との対応は docs/adr/README.md)。 + +| 項目 | 内容 | +| -------- | ---------- | +| Status | Accepted | +| Date | 2026-09-13 | +| Deciders | t1nyb0x | + +## Context + +要件は「編集操作は即時にプレビューへ反映」「非破壊編集」「ログイン不要で編集・端末保存」。同時に「原本を恒久保存しない」方針が決まっている。編集をどこで実行し、最終画像をどこで生成するかは、ストレージ費用・サーバー負荷・再編集体験に直結する。 + +## Decision + +- 編集のプレビューと最終書き出しの両方をブラウザで行う。サーバーはレシピからの再現像を行わない +- レンダリングは PixiJS v8 (WebGL2、環境が許せば WebGPU) を使い、全補正を 1 つのカスタム `Filter` (GLSL) で 1 パス適用する +- 書き出しは `RenderTexture` を原寸 (長辺上限 4096px) で描画し `canvas.toBlob` で WebP (非対応時 JPEG) を生成する +- 原本とレシピは IndexedDB に一時保持し、同一端末での再編集に使う + +## Consequences + +### 良い点 + +- 編集だけの利用者はサーバー資源を一切消費しない。「投稿が集まらない」リスク対策として編集を無料・無登録にする方針と噛み合う +- 原本がサーバーに存在しないため、保存費用と権利上の懸念が最小になる +- プレビューと書き出しが同一コードパスなので「プレビューと結果が違う」問題が起きない + +### 悪い点・受け入れるリスク + +- 端末性能に依存する。30MB の PNG (例: 5120x2880) のデコードと WebGL テクスチャ化はスマートフォンでは失敗しうる。長辺 4096px への事前縮小と、失敗時のメッセージで対処する +- ブラウザ間で `toBlob` の WebP 品質・色管理に差がある。sRGB 前提で統一し、色空間の厳密さは追わない +- 別端末からの再編集はできない ([03. 画像パイプライン §9](https://github.com/lumorphia/prismtone/blob/develop/docs/design/03-image-pipeline.md)) +- 書き出し画像が利用者側で生成されるため、サーバーは受け取った画像を信用しない (worker で再検証・再エンコードする) + +### 追従して必要になること + +- シェーダのパラメータ定義とレシピスキーマを対応させる ([04. 編集レシピ](https://github.com/lumorphia/prismtone/blob/develop/docs/design/04-edit-recipe.md)) +- WebGL 非対応環境の検出とフォールバック表示 (編集不可、投稿導線のみ案内) + +## Alternatives + +- **サーバーでレシピから現像 (原本をアップロードし Sharp / libvips で適用)**: 原本保存が必須になり、方針と衝突する。サーバー負荷も高い +- **Canvas 2D + WebAssembly (例: wasm-vips)**: 高精度だがプレビューのリアルタイム性に劣る。WebGL で十分 +- **WebGPU 専用**: 対応ブラウザがまだ限られる。PixiJS が抽象化してくれるため、将来自然に移行できる + +## References + +- [03. 画像パイプライン](https://github.com/lumorphia/prismtone/blob/develop/docs/design/03-image-pipeline.md) +- [08. フロントエンド](https://github.com/lumorphia/prismtone/blob/develop/docs/design/08-frontend.md) +- [ADR-0006](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0006-storage-r2-direct-upload-no-originals.md) diff --git a/docs/adr/0003-versioned-edit-recipe.md b/docs/adr/0003-versioned-edit-recipe.md new file mode 100644 index 0000000..56ce4ef --- /dev/null +++ b/docs/adr/0003-versioned-edit-recipe.md @@ -0,0 +1,49 @@ +# ADR-0003: 編集レシピはバージョン付き JSON として保存する + +> lumorphia/prismtone の ADR-0009 (https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0009-versioned-edit-recipe.md) を移植したもの (2026-10-06)。本文は当時のまま。パスは prismtone の中にあったころのもので、今は `packages/editor-*` にある。リンク、Issue 番号、本文中の ADR の番号は prismtone のもの (このリポジトリの番号との対応は docs/adr/README.md)。 + +| 項目 | 内容 | +| -------- | ---------- | +| Status | Accepted | +| Date | 2026-09-13 | +| Deciders | t1nyb0x | + +## Context + +編集は非破壊で、調整値を「編集レシピ」として保持する。レシピはブラウザの編集状態、IndexedDB の一時保存、DB の `edit_recipes`、将来のレシピ共有 (Phase 2) と複数の場所で使われる。補正項目は将来増える (部分補正、粒状感など) が、投稿済みレシピの見え方を変えてはならない。 + +## Decision + +- レシピは `{ version, presetId, adjust, geometry }` の JSON とし、スキーマは `packages/shared/recipe/` に zod で定義してブラウザとサーバーで共有する +- `version` は必須。読み込み時は必ず `migrateRecipe()` を通し、最新版に変換する。未知の version は拒否する +- 変更は **追加のみ**。既存項目の意味・値域を変えない。廃止する場合は deprecated として残し、読み込み時に無視する +- プリセットは `adjust` への部分適用として定義し、適用結果を展開して保存する。`presetId` は表示用であり、プリセット定義の変更が既存レシピに影響しない +- DB は `edit_recipes.recipe` を jsonb で持ち、`version` を別列に持つ (移行対象の検索用)。サーバーはレシピの内容を解釈せず、検証と保存のみ行う + +## Consequences + +### 良い点 + +- スキーマが 1 か所にあり、ブラウザ・API・DB で不整合が起きない +- 新機能追加時に旧レシピの互換性を機械的に担保できる (`migrate` の単体テスト) +- プリセットの調整を自由に行える + +### 悪い点・受け入れるリスク + +- 廃止項目を残すためスキーマが肥大化しうる。年 1 回程度、利用のない項目を version 更新で整理する +- jsonb のため DB 側で値の制約をかけられない。zod 検証をサーバーで必ず通す + +### 追従して必要になること + +- [04. 編集レシピ](https://github.com/lumorphia/prismtone/blob/develop/docs/design/04-edit-recipe.md) に v1 の完全な定義を置く +- シェーダの uniform とレシピ項目の対応表を保守する + +## Alternatives + +- **各補正値を DB の列にする**: 型は強くなるが、項目追加のたびにマイグレーションが必要。レシピが主に「表示・共有用のデータ」であることを考えると過剰 +- **バージョンなし JSON**: 項目追加時に旧データの解釈が曖昧になる + +## References + +- [04. 編集レシピ](https://github.com/lumorphia/prismtone/blob/develop/docs/design/04-edit-recipe.md) +- [ADR-0005](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0005-client-side-editing-and-export.md) diff --git a/docs/adr/0004-two-stage-render-local-adjustments.md b/docs/adr/0004-two-stage-render-local-adjustments.md new file mode 100644 index 0000000..b838de7 --- /dev/null +++ b/docs/adr/0004-two-stage-render-local-adjustments.md @@ -0,0 +1,50 @@ +# ADR-0004: 現像を「合成の段」と「表示の段」に分け、部分補正はフィルタを重ねて掛ける + +> lumorphia/prismtone の ADR-0021 (https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0021-two-stage-render-local-adjustments.md) を移植したもの (2026-10-06)。本文は当時のまま。パスは prismtone の中にあったころのもので、今は `packages/editor-*` にある。リンク、Issue 番号、本文中の ADR の番号は prismtone のもの (このリポジトリの番号との対応は docs/adr/README.md)。 + +| 項目 | 内容 | +| -------- | ---------- | +| Status | Accepted | +| Date | 2026-09-20 | +| Deciders | t1nyb0x | + +## Context + +[ADR-0005](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0005-client-side-editing-and-export.md) と [08 §3.3](https://github.com/lumorphia/prismtone/blob/develop/docs/design/08-frontend.md) は「Sprite 1 枚に `AdjustFilter` 1 つ、補正は 1 パス」としていた。[#109](https://github.com/lumorphia/prismtone/issues/109) の部分補正 (マスク付きの補正、最大 8 個) は、マスクの座標を画像に対して固定したまま、プレビューと原寸書き出しで同じ結果にする必要がある。 + +表示用の Sprite に直接フィルタを重ねる案を pixi.js 8.20.1 のソースで確かめたところ、フィルタ領域は「回転後の外接矩形をビューポートでクリップした矩形」になる (`FilterSystem.mjs` の `push`)。そのままではマスクの座標が表示倍率とスクロールに依存し、近傍を見る処理 (シャープ・平滑化) のテクセル幅もプレビューと書き出しで変わる。 + +## Decision + +- 描画を 2 段にする。**合成の段** (`render/develop-stage.ts`) は無変換の Sprite に `[AdjustFilter, LocalAdjustFilter × N]` を掛け、`filterArea` で領域を画像矩形に固定して、画像座標のままの `RenderTexture` に描く。**表示の段** (`render/editor-renderer.ts`) はそのテクスチャの Sprite に幾何 (回転・反転) を掛け、トリミングは書き出し時の `frame` で切る (従来どおり) +- 領域 = 画像矩形なので、頂点シェーダの `aPosition` がそのまま画像の正規化座標 (`vImageUv`) になる。マスクはこの座標で評価する。幾何は合成のあとに掛かるので、回転・反転・トリミングでマスクはずれない +- 部分補正 1 件 = フィルタ 1 パス。中間テクスチャは pixi が入力と temp の 2 枚を使い回すので、件数はテクスチャ枚数に効かず、パス数と fragment の負荷にだけ効く +- 合成の段は**レシピが変わったフレームだけ**描く (`dirty`)。ズーム・リサイズ・比較は表示の段だけ +- プレビューの合成は長辺 2048 まで縮小、書き出しは原寸 (4096 と `MAX_TEXTURE_SIZE` の小さい方) で描き直してから切り出す。書き出し後は `TexturePool.clear(true)` で原寸のフィルタ用テクスチャを捨てる (プールは GC されない) +- 全フィルタ `padding: 0`、`antialias: "off"`、`resolution: 1`。近傍サンプルは `uInputClamp` で自前クランプする (プールのテクスチャは 2 のべき乗で余白がある) +- 色補正の GLSL は `render/adjust-glsl.ts` に 1 つ置き、全体と部分の両方のフィルタが埋め込む。CPU 参照 (`adjust-math.ts`、`mask-math.ts`) と同じ式 + +## Consequences + +### 良い点 + +- マスクの座標が画像に固定され、プレビュー (縮小) と書き出し (原寸) で同じ場所に同じ量が掛かる。E2E で GPU と CPU 参照を ±3/255 で照合できる (回転 + トリミング後も同じ画素) +- スライダーのドラッグ以外 (ズーム・比較) で合成を描き直さない +- 幾何・比較・書き出しの既存コードはほぼそのまま + +### 悪い点・受け入れるリスク + +- GPU メモリが増える。見積: プレビュー ≈ 116 MB (従来比 +68 MB)、書き出し時ピーク ≈ 310 MB (4096×3072)。実測は PR3 の spike に残す +- 部分補正 8 個で 9 パス。プレビューは ≤ 2048 なので許容範囲と見込むが、平滑化 (5×5) を足したあとで計測する。上限 8 の根拠もそこで確かめる +- 比較の左 (元画像) は原寸、右 (現像後) はプレビュー解像度なので、拡大時に鮮鋭度が僅かに違う。気になれば元画像もプレビュー寸法に揃える +- `Sprite.width/height` を非整数にすると領域が 1px ずれて uv が歪む。寸法は整数で持つ + +## Alternatives + +- **表示用 Sprite にフィルタを直付けし、逆変換 uniform でマスク座標を戻す**: 可能だが、ビューポートのクリップで見えない部分が評価されない、テクセル幅が表示倍率に依存する、チェーンの中間パスで `uOutputFrame.xy` が 0 に固定される、と前提が多い。採らない +- **マスクを Pixi の `mask` (Graphics / Sprite) で掛ける**: 比較機能が `sprite.mask` を使っていて衝突する。ぼかしも表現できない + +## References + +- [08 §3.3](https://github.com/lumorphia/prismtone/blob/develop/docs/design/08-frontend.md)、[04 §1.1](https://github.com/lumorphia/prismtone/blob/develop/docs/design/04-edit-recipe.md) +- `node_modules/pixi.js/lib/filters/FilterSystem.mjs` (領域・uniform の根拠。8.20.1) diff --git a/docs/adr/0005-in-browser-inference-and-recipe-v3.md b/docs/adr/0005-in-browser-inference-and-recipe-v3.md new file mode 100644 index 0000000..6b699b2 --- /dev/null +++ b/docs/adr/0005-in-browser-inference-and-recipe-v3.md @@ -0,0 +1,47 @@ +# ADR-0005: 部分補正の自動選択はブラウザ内の推論で行い、マスクは Recipe v3 の多角形・ビットマップで持つ + +> lumorphia/prismtone の ADR-0025 (https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0025-in-browser-inference-and-recipe-v3.md) を移植したもの (2026-10-06)。本文は当時のまま。パスは prismtone の中にあったころのもので、今は `packages/editor-*` にある。リンク、Issue 番号、本文中の ADR の番号は prismtone のもの (このリポジトリの番号との対応は docs/adr/README.md)。 + +| 項目 | 内容 | +| -------- | ---------- | +| Status | Accepted | +| Date | 2026-09-21 | +| Deciders | t1nyb0x | + +## Context + +lumorphia/prismtone#109 の部分補正は円形とブラシのマスクを手で置く。「瞳」「美肌」「装備強調」を押したら顔・瞳・装備が選ばれた状態になってほしい (lumorphia/prismtone#162、lumorphia/prismtone#175)。spike ([2026-09-21](https://github.com/lumorphia/prismtone/blob/develop/docs/spikes/2026-09-21-auto-select.md)) で、MediaPipe Face Landmarker (顔・瞳) と SlimSAM (装備・人物) がブラウザの WASM で FF14 のスクショに対して使える精度と速さだと分かった。 + +決めることは 3 つ: (1) 推論をどこで動かすか、(2) モデルをどう配るか、(3) 認識結果のマスクをレシピにどう持つか。 + +## Decision + +### 推論はブラウザの中だけ + +- 画像も推論もブラウザの中で行い、編集のために画像を外部 API にもサーバーにも送らない (プライバシーポリシー §1 に明記)。サーバーは推論しない (VPS 1 台で GPU も無い) +- ライブラリは動的 import、推論は Web Worker で動かし、現像の初期表示と UI スレッドに載せない +- CSP は `script-src 'self' 'wasm-unsafe-eval'` のまま。`unsafe-eval` は許さない。spike で MediaPipe と onnxruntime-web がこの CSP で動くことを確認した +- WebGPU は「使えれば速い」の位置。WASM で成立しているので、実機で計測してから足す +- **追記 (2026-09-21、lumorphia/prismtone#182)**: `/edit` の文書と `/assets/` `/models/` の応答に COEP `credentialless` を付けて cross-origin isolated にし、ORT をマルチスレッドで動かす (準備 10 秒 → 3.4 秒)。`require-corp` でなく `credentialless` なので、CORP の無い他オリジンの画像 (XIVAPI、R2) も匿名で読める。他の文書には付けない +- 認識に失敗しても手動のマスクで全部できる。自動選択は「初期値を置く」だけで、置いたあとは今の道具 (ハンドル、ブラシ) で直す。失敗の文言は理由を断定しない (「自動選択できませんでした。手動で範囲を指定できます」) + +### モデルは自前ホスト + +- モデルと WASM は git に入れず、`apps/app/scripts/fetch-models.ts` が sha256 を固定してダウンロードし `apps/app/models/-v/` に置き (`dev` / `build` の前。CI と Docker build も `pnpm build` 経由で同じ)、Fastify の static が `/models/` で配る。CDN や Hugging Face から直接は読まない +- ディレクトリに版を付けるので、静的アセットの `immutable` キャッシュのまま差し替えられる +- 大きさ (gzip 後): 顔 6.3 MB、SAM 13 MB + ORT 4.8 MB。初回だけ進捗を出して読み込む + +### マスクは Recipe v3 の多角形とビットマップ + +- 顔の輪郭は `polygon` (外周 + 穴)、SAM の切り抜きは `bitmap` (長辺 256、RLE) で持つ。ブラシ点列に崩すとレシピが肥大化し (64 本 × 512 点)、描画も重い +- どちらも `strokes` を持ち、自動で置いたマスクの上にブラシで足す / 消す (道具は 1 つ) +- ラスタライズは全部 CPU 側 (`brush-raster.ts`、長辺 1024) で、GPU はテクスチャを読むだけ。`invert` もラスタ側。CPU の参照実装と GPU の出力を E2E で照合する原則 (docs/design/08 §7) を保つ +- 人物補正 (lumorphia/prismtone#175) の「顔・瞳 ×2・人物・背景」は `groupId` で束ねる。上限は 8 → 12 +- モデルやライブラリの版が変わっても、レシピには結果のマスクだけが入っているので既存の投稿の見え方は変わらない (推論は編集時の 1 回きり) + +## Consequences + +- 現像のバンドルに推論ライブラリは載らない (動的 import)。押したときに 6〜18 MB を読むので、初回の待ちは避けられない +- 横顔、褐色肌 + 角 (アウラ)、顔の高さ 80 px 以下、逆さ・90 度回転は取れない (spike の結果)。手動に落ちる +- 依存が増える: `@mediapipe/tasks-vision` (Apache-2.0)、`@huggingface/transformers` (Apache-2.0)、onnxruntime-web (MIT)。`pnpm licenses:check` の対象 +- 規約 §3 (生成 AI による加工) は変えない。選択であって描き足しではない。目を大きくする、顔の再生成などの変形・生成は対象外 (lumorphia/prismtone#175) diff --git a/docs/adr/README.md b/docs/adr/README.md new file mode 100644 index 0000000..bab020c --- /dev/null +++ b/docs/adr/README.md @@ -0,0 +1,20 @@ +# ADR の一覧 + +| 番号 | 決めたこと | 元 | +| -------------------------------------------------- | ---------------------------------------------- | ------------------ | +| [0001](0001-record-architecture-decisions.md) | ADR を使う | | +| [0002](0002-client-side-editing-and-export.md) | 編集と書き出しはブラウザで行う | prismtone ADR-0005 | +| [0003](0003-versioned-edit-recipe.md) | 編集レシピは版付きの JSON、変更は足すだけ | prismtone ADR-0009 | +| [0004](0004-two-stage-render-local-adjustments.md) | 合成の段と表示の段、部分補正はフィルタを重ねる | prismtone ADR-0021 | +| [0005](0005-in-browser-inference-and-recipe-v3.md) | 認識はブラウザの中で、モデルは自前で配る | prismtone ADR-0025 | + +0002〜0005 は lumorphia/prismtone から移植したもので、本文中の ADR の番号は prismtone のもの。対応は次のとおり。 + +| prismtone | このリポジトリ | +| --------- | -------------- | +| ADR-0005 | ADR-0002 | +| ADR-0009 | ADR-0003 | +| ADR-0021 | ADR-0004 | +| ADR-0025 | ADR-0005 | + +切り出しの経緯は prismtone の [ADR-0035](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0035-extract-editor-to-lumorphia-editor.md)。 diff --git a/docs/design/edit-recipe.md b/docs/design/edit-recipe.md new file mode 100644 index 0000000..2d7983f --- /dev/null +++ b/docs/design/edit-recipe.md @@ -0,0 +1,254 @@ +# 04. 編集レシピ + +> lumorphia/prismtone の docs/design/04-edit-recipe.md (https://github.com/lumorphia/prismtone/blob/develop/docs/design/04-edit-recipe.md) を移植したもの (2026-10-06)。リンク、Issue 番号、ADR の番号は prismtone のもの。今後はこちらを正とする。 + +関連 ADR: [ADR-0009](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0009-versioned-edit-recipe.md), [ADR-0005](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0005-client-side-editing-and-export.md) + +編集レシピは「原本に対する調整値の集合」であり、非破壊編集の唯一の状態。調整の範囲は色調整 (範囲を選んだ部分補正を含む)、シャープ・輪郭を残す軽い平滑化、幾何 (回転・トリミング) に限る。人物切り抜き、背景差し替え、生成 AI による加工は著作物利用許諾条件の「過度な加工・改変」に当たる恐れがあるため、将来も追加しない ([spike](https://github.com/lumorphia/prismtone/blob/develop/docs/spikes/2026-09-13-terms-and-licensing.md))。ブラウザの編集画面、IndexedDB の一時保持、投稿詳細での表示、プリセット定義のすべてが同じスキーマを使う。定義は `packages/editor-recipe/` (`@lumorphia/editor-recipe`、ADR-0035) に zod で置き、ブラウザとサーバーで共有する。 + +## 1. スキーマ v1 + +```ts +type EditRecipeV1 = { + version: 1; + presetId: string | null; // 適用したプリセット。値は下記に展開済み + adjust: { + exposure: number; // -5.0 .. +5.0 (EV) + contrast: number; // -100 .. +100 + highlights: number; // -100 .. +100 + shadows: number; // -100 .. +100 + temperature: number; // -100 .. +100 (負: 寒色, 正: 暖色) + tint: number; // -100 .. +100 (負: 緑, 正: マゼンタ) + vibrance: number; // -100 .. +100 (自然な彩度) + saturation: number; // -100 .. +100 + }; + geometry: { + rotation: 0 | 90 | 180 | 270; // 直角回転 + straighten: number; // -45 .. +45 (度, 微調整) + flipH: boolean; + crop: { + // 回転・水平補正後の座標系、0..1 の正規化座標 + x: number; + y: number; + w: number; + h: number; + } | null; + aspect: string | null; // "free" | "1:1" | "4:3" | "16:9" | "3:2" | "9:16" | ... + }; +}; +``` + +既定値: `adjust` は全て 0、`geometry` は `rotation: 0, straighten: 0, flipH: false, crop: null, aspect: null`。 + +### 1.1 v2: 部分補正 (lumorphia/prismtone#109) + +v1 に `localAdjustments` を足したもの。v1 の項目は触らない。 + +```ts +type EditRecipeV2 = Omit & { + version: 2; + localAdjustments: LocalAdjustmentV2[]; // 最大 8 +}; + +type LocalAdjustmentV2 = { + id: string; // 編集画面内の識別子 (max 32) + name: string | null; // 利用者が付ける名前 (max 32) + presetId: "eyes" | "skin" | "gear" | null; // 瞳強調 / 美肌 / 装備強調。表示用 + mask: EllipseMaskV2 | BrushMaskV2; + adjust: { + // 全体の補正から vibrance を外し、sharpen / smooth を足す + exposure; + contrast; + highlights; + shadows; + temperature; + tint; + saturation; + sharpen: number; // 0 .. 100 (アンシャープ 3x3) + smooth: number; // 0 .. 60 (輪郭を残す平滑化。美肌。過度なぼかしを避ける上限) + }; + amount: number; // 効果量 0 .. 100 + visible: boolean; +}; + +type EllipseMaskV2 = { + kind: "ellipse"; + cx: number; + cy: number; // 中心 0..1 + rx: number; + ry: number; // 半径。rx は画像の幅、ry は高さに対する比 (0 < r <= 1) + rotation: number; // -180 .. 180 (度) + feather: number; // 半径に対するぼかし幅の比 0..1 + invert: boolean; +}; + +type BrushMaskV2 = { + kind: "brush"; + strokes: { + // 最大 64 + mode: "add" | "erase"; + size: number; // ブラシ径。画像の長辺に対する比 0.005 .. 0.5 + hardness: number; // 0..1 + points: { x: number; y: number }[]; // 0..1、1 ストローク最大 512 点 (描画中に間引く) + }[]; + feather: number; + invert: boolean; +}; +``` + +- **マスクの座標系は幾何を掛ける前の画像** (4096px に収めたあとのビットマップ) の正規化座標。回転・水平補正・反転・トリミングは部分補正を合成したあとに掛かるので、幾何を変えてもマスクの位置はずれない。`GeometryV1.crop` が「回転後の座標系」なのと違う点に注意 +- 上限 (8 個、64 ストローク、512 点) はレシピの肥大化 (jsonb) と描画パス数を抑えるため。根拠の計測は PR3 の spike に残す +- 部分補正のプリセットは `packages/editor-recipe/src/local-presets.ts`。適用は選択中の部分補正の `adjust` と `amount` を上書きし、マスクには触れない + +### 1.2 値域と正規化 + +- zod で値域を検証し、範囲外は clamp ではなく拒否する (不正なレシピを保存しない) +- 数値は小数第 2 位で丸めて保存する。プレビュー中は丸めない +- `presetId` は表示用。レシピの適用結果は `adjust` の値で完全に決まり、プリセット定義が後から変わっても投稿済みレシピの見え方は変わらない + +### 1.3 v3: 自動選択のマスクと人物補正のまとまり (lumorphia/prismtone#175 / lumorphia/prismtone#176 / lumorphia/prismtone#177) + +v2 に多角形とビットマップのマスク、部分補正の `groupId` を足したもの。v2 の項目は触らない。上限は 12 件 (人物補正が 1 人で 5 件使う)。 + +```ts +type EditRecipeV3 = Omit & { + version: 3; + localAdjustments: LocalAdjustmentV3[]; // 最大 12 +}; + +type LocalAdjustmentV3 = Omit & { + mask: EllipseMaskV2 | BrushMaskV2 | PolygonMaskV3 | BitmapMaskV3; + groupId: string | null; // 人物補正 (lumorphia/prismtone#175) など、まとめて扱う部分補正の組 (max 32) +}; + +type PolygonMaskV3 = { + // 顔の輪郭 (lumorphia/prismtone#176) + kind: "polygon"; + rings: { x: number; y: number }[][]; // 先頭が外周、以降は穴 (偶奇で塗る)。最大 8 本、1 本 3..256 点 + strokes: BrushStrokeV2[]; // 自動で置いたあとブラシで足す / 消す (最大 64) + feather: number; // 0..1。長辺の 5% までのぼかし + invert: boolean; +}; + +type BitmapMaskV3 = { + // SAM の切り抜き (lumorphia/prismtone#177) + kind: "bitmap"; + width: number; + height: number; // 1..256 + rle: string; // width × height の 0/1 を rle.ts (LEB128 + base64url) で圧縮。max 64 KB + strokes: BrushStrokeV2[]; + feather: number; + invert: boolean; +}; +``` + +- 顔の輪郭 (36 点) や SAM の切り抜きをブラシ点列 (最大 512 点 × 64 本) に崩さず持つため。多角形は穴で目・口を抜けるので、美肌がまつ毛や唇を潰さない +- どのマスクも **ラスタライズは CPU 側** (`packages/editor-engine/src/brush-raster.ts` の `rasterizeMask`、長辺 1024) で、GPU は同じテクスチャの読み取りだけ (`uMaskMode = 1`)。`invert` もラスタ側で済ませる (シェーダは楕円だけ反転する)。CPU の参照実装 (`maskValue`) と GPU の出力を E2E で照合する +- ビットマップは長辺 256。GPU が線形補間で拡大するので境界は滑らか。`feather` は縦横 2 回の箱ぼかし + +### 1.4 v4: 人物補正の空間効果 (lumorphia/prismtone#184) + +v3 の部分補正に次の4項目を追加する。既存項目とマスクの意味は変えず、v1〜v3を読むときは全項目を中立値 `0` で補う。 + +```ts +type EditRecipeV4 = Omit & { + version: 4; + localAdjustments: LocalAdjustmentV4[]; +}; + +type LocalAdjustmentV4 = Omit & { + adjust: LocalAdjustmentV3["adjust"] & { + blur: number; // 0..32、元画像 px の半径 + bloom: number; // 0..100、高輝度成分をぼかして加算 + vignette: number; // 0..100、画像中心から周辺を減光 + clarity: number; // -100..100、近傍平均との差による局所コントラスト + }; +}; +``` + +- `blur` はプレビュー解像度ではなく元画像のpxで半径を決めるため、プレビューと書き出しで広がりが変わらない +- `blur` / `bloom` / `clarity` は共有の3×3近傍を使う。半径は `max(blur, bloomなら8px, clarityなら4px)`。同じ部分補正に複数を入れても近傍読み取りを1回に抑える +- `bloom` は0.65を超える高輝度成分を加算する。`vignette` は画像全体の中心を基準にするが、ほかの部分補正と同じくマスクと効果量で合成する +- GLSLとCPU参照実装を `e2e/editor.spec.ts` で4項目ごとに照合し、4K + 12件は `e2e/perf-local-adjust.spec.ts` で計測する + +## 2. プリセット + +プリセットは `Partial` として `packages/editor-recipe/src/presets.ts` に定義する。適用は「現在の adjust にプリセット値を上書き」であり、幾何情報 (crop 等) には触れない。 + +初期プリセット案 (10 種、値は実装時に実画像で調整): + +| id | 名称 | 狙い | +| --------------- | ---------- | ------------------------------------------------ | +| `night-city` | 夜景 | 露光を少し下げ、シャドウを持ち上げ、寒色寄りに | +| `warm-sunset` | 夕暮れ | 暖色、ハイライト抑制、彩度控えめ | +| `cool-morning` | 朝霧 | 寒色、コントラスト低め、シャドウ持ち上げ | +| `pastel` | パステル | コントラスト低、自然な彩度 +、ハイライト持ち上げ | +| `vivid` | ビビッド | 自然な彩度 +、コントラスト + | +| `film` | フィルム風 | シャドウ持ち上げ、ハイライト抑制、彩度 - | +| `mono` | モノクロ | 彩度 -100、コントラスト + | +| `soft-portrait` | ソフト | コントラスト -、ハイライト -、自然な彩度 + | +| `dungeon` | ダンジョン | 露光 +、シャドウ +、寒色 | +| `gold-hour` | ゴールド | 暖色 +、露光 +、ハイライト - | + +### 2.1 部分補正のプリセット (lumorphia/prismtone#109) + +`packages/editor-recipe/src/local-presets.ts`。選択中の部分補正の `adjust` と `amount` を上書きし、マスクには触れない。手でスライダーを動かしたら `presetId` は外す (全体と同じ)。 + +| id | 名称 | 狙い | 値 (初期案) | +| ------ | -------- | -------------------------------------- | -------------------------------------------------------------------------- | +| `eyes` | 瞳強調 | 円形マスクを左右の目に置く | 露光 +0.3、彩度 +15、コントラスト +10、シャープ 30 | +| `skin` | 美肌 | 顔にマスクを置き、輪郭を残して滑らかに | 平滑化 40、露光 +0.15、色温度 +5 | +| `gear` | 装備強調 | 見せたい装備をブラシで塗る | 露光 +0.15、シャドウ +45、コントラスト +15、シャープ 30、彩度 +8、質感 +25 | + +シャープは 3×3 のアンシャープ、平滑化は 5×5 の輝度差で重み付けした平均 (輪郭を残す)。近傍の間隔は元画像の px で決めるので、プレビュー (縮小) と書き出し (原寸) で同じ広がりになる。ブラシの `feather` は硬さを下げる方向に効く。 + +### 2.2 人物補正のプリセット (lumorphia/prismtone#175) + +`packages/editor-recipe/src/portrait-presets.ts`。1 人ぶんの「背景・人物・顔・瞳」の 4 役に対する部分補正の値 (`Partial`) と役ごとの効果量。ナチュラル / 明るく / ドラマチック / やわらか / 瞳くっきり の 5 つ。背景にはぼかしと周辺減光、人物には質感、顔と瞳には発光をプリセットごとの強さで組み込む。 + +- 適用は部分補正 5 件 (背景 → 人物 → 顔 → 瞳 ×2、後の方が上に掛かる) を `groupId` で束ねて 1 手で足す。役はレシピに持たず、マスクの形から決める (`portraitRole`: 反転したビットマップ = 背景、ビットマップ = 人物、多角形 = 顔、楕円 = 瞳) +- グループの効果量 (0..100) は役ごとの効果量 × effect / 100 で各部分補正の `amount` に写す (`scalePortraitAmount`)。読み戻しは `portraitAmount` +- プリセットの切り替えは `applyPortraitPreset` でグループの `adjust` と `amount` を差し替える (マスクは触らない)。個別の値は部分補正タブでそのまま直せる +- 上限 12 件のうち 1 人で 5 件。2 人までは置ける。入り切らなければ置かずに伝える + +## 3. undo / redo + +編集画面の状態は `{ past: EditRecipeV1[], present: EditRecipeV1, future: EditRecipeV1[] }`。レシピは不変オブジェクトとして扱い、変更のたびに新しいオブジェクトを `present` に置く。 + +- スライダーのドラッグ中は `present` だけを更新し、ドラッグ終了 (`pointerup`) で `past` に積む (履歴が 1 ピクセルごとに増えるのを防ぐ) +- 「全リセット」は既定値を `present` にする 1 手として履歴に積む +- 履歴上限 100 + +## 4. シェーダとの対応 + +PixiJS の `Filter` に adjust を uniform として渡す。全体の補正が 1 パス、部分補正は 1 件 1 パスで、無変換の画像に順に掛けてから幾何を掛ける ([ADR-0021](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0021-two-stage-render-local-adjustments.md))。色の順序は Lightroom 系に倣う。部分補正は同じ式 (vibrance 無し) の結果を `mix(元, 補正後, マスク × 効果量)` で混ぜる。 + +``` +入力 (sRGB) + -> linear 化 + -> exposure : rgb *= 2^exposure + -> temperature/tint : 白色点の簡易シフト (rgb 各チャンネルへのゲイン) + -> highlights/shadows : 輝度に基づく重み付きの持ち上げ・抑制 + -> contrast : 中間灰 (0.18) を軸にした S カーブ + -> vibrance : 彩度が低い画素ほど強く彩度を上げる + -> saturation : HSL の S を線形スケール + -> sRGB 化 +``` + +幾何 (回転・水平補正・反転・トリミング) はシェーダではなく `Sprite` の transform と `RenderTexture` の切り出しで行う。 + +## 5. バージョニング + +- `version` を必須にし、読み込み時に `migrateRecipe(input: unknown): EditRecipe` を通す。未知の version は拒否。各版は strict に検証し、版に無い項目が混ざっていれば拒む +- v1 → v2 は `migrateV1toV2` (`localAdjustments: []` で埋める)、v2 → v3 は `migrateV2toV3` (`groupId: null`)、v3 → v4 は `migrateV3toV4` (4効果を中立値 `0`)。読む側は **必ず** `migrateRecipe` を通す: `@lumorphia/editor-recipe` の `upgradeStoredRecipe` (読めないものは null) を、端末の下書き (`@lumorphia/editor-engine` の `createDraftStore`)、pending と投稿下書き (`features/post-form/work-in-progress.ts`) から呼ぶ、投稿詳細 (`routes/post-detail.tsx`) +- API の入出力は `editRecipeInputSchema` (v1 | v2 | v3 | v4 の union)。旧版の投稿は保存したままの版で返り、旧版のクライアントからの投稿も受ける。`edit_recipes.version` にはその版が入る +- **後方非互換な変更 (既存項目の意味や値域の変更) は行わない**。必要なら新しい項目を追加し、旧項目は deprecated として残す +- サーバーは保存時に `version` と zod 検証のみ行い、レシピの意味を解釈しない + +## 6. 保存先 + +| 場所 | 形式 | 目的 | +| ----------------------------- | ------------------ | -------------------------------------------- | +| ブラウザ IndexedDB | 原本 Blob + レシピ | 端末内での再編集 (最大 5 件, LRU) | +| `edit_recipes.recipe` (jsonb) | レシピのみ | 投稿詳細での表示、将来のレシピ共有 (Phase 2) | +| URL クエリ (将来) | base64url 圧縮 | レシピ共有リンク | diff --git a/docs/design/editor.md b/docs/design/editor.md new file mode 100644 index 0000000..486f523 --- /dev/null +++ b/docs/design/editor.md @@ -0,0 +1,121 @@ +# 現像エディタ (画面・描画・推論・テスト) + +> lumorphia/prismtone の docs/design/08-frontend.md (https://github.com/lumorphia/prismtone/blob/develop/docs/design/08-frontend.md) の §3 (編集画面) と §7 (テスト) を移植したもの (2026-10-06)。投稿画面への受け渡し (§4) と、prismtone だけのテスト (loader、OGP) は prismtone に残る。リンク、Issue 番号、ADR の番号は prismtone のもの。今後はこちらを正とする。 + +## 3. 編集画面 (`/edit`) + +### 3.1 構成 + +``` ++------------------------------------------------------------+ +| ヘッダ: ファイルを開く | 比較 (スライダー: 左が元画像、右が現像後。ドラッグと矢印キーで境界を動かす。トリミング中は無効) | ← 戻る / 進む → (ツールチップに「露光量 +0.30 を取り消す (Ctrl+Z)」のように操作名を出し、横に「最後の操作: …」を表示) | 書き出し | 投稿へ | ++---------------------------------------+--------------------+ +| | プリセット (10) | +| PixiJS キャンバス | ------------------ | +| (フィット表示、ピンチ/ホイールでズーム) | 基本補正 スライダ x8 | +| | ------------------ | +| | 部分補正: 一覧 (≤8)、| +| | 円形を追加、瞳強調/ | +| | 美肌/装備強調、効果量| +| | ------------------ | +| | 幾何: 回転/反転/ | +| | 水平/アスペクト/ | +| | トリミング | +| | ------------------ | +| | 全リセット | ++---------------------------------------+--------------------+ +``` + +スマートフォンでは右パネルを下部のタブ (プリセット / 補正 / 幾何) に切り替える。 + +現像は prismtone を知らない ([ADR-0035](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0035-extract-editor-to-lumorphia-editor.md))。`packages/editor-engine` (`@lumorphia/editor-engine`: 状態、描画、推論、下書き。React に依存しない) と `packages/editor-react` (`@lumorphia/editor-react`: UI) にあり、ESLint (`editorEngineHasNoHost` / `editorReactHasNoHost`) が prismtone への依存を禁じる。ホストが `EditorHost` (`packages/editor-react/src/host.ts`) で次を渡し、`` で組み込む。UI のクラスは `app.css` の `@source` で Tailwind に走査させる (無いと `touch-none` などが抜ける。`e2e/editor-styles.spec.ts`)。prismtone の組み立ては `features/editor-host/prismtone-host.ts` と `routes/edit.tsx`。 + +- 表示言語 (`locale`)。文言はエディタの中の `useEditorI18n()` (`t(ja, en)`、語彙の英訳は `@lumorphia/editor-recipe/labels` の `translateLabel`) +- 下書きの置き場所 (`drafts`) と開く下書き (`initialDraftId`、prismtone は `?draft=`) +- 送り先 (`destinations`)。prismtone は「投稿へ」1 件 (§3.4) +- 計測 (`telemetry`)。prismtone は ADR-0034 の `open` / `save` / `to_post` に読み替える (送れたときだけ数える) +- モデルの置き場所 (`inference.modelBaseUrl`、既定は `/models/`)、保存ファイル名の接尾辞 (`-prismtone`)、E2E のフック (`__prismtoneEditor`) + +### 3.2 画像の読み込み + +1. `` またはドラッグ&ドロップ +2. 30MB 超は拒否。マジックバイトで形式を確認 (拡張子は信用しない) +3. `createImageBitmap(file, { imageOrientation: "from-image" })` でデコード。EXIF 方向をここで解決 +4. 長辺 4096px 超は OffscreenCanvas で縮小 (WebGL テクスチャ上限とメモリのため) +5. `Texture` を作成し、原本 Blob と共に IndexedDB (`drafts` ストア, LRU 5 件) に保存 + +### 3.3 レンダリング + +2 段構成 ([ADR-0021](https://github.com/lumorphia/prismtone/blob/develop/docs/adr/0021-two-stage-render-local-adjustments.md)、lumorphia/prismtone#109)。 + +- **合成の段** (`render/develop-stage.ts`): 無変換の `Sprite` (原本) に `[AdjustFilter, LocalAdjustFilter × 部分補正の数]` を付け、`filterArea` で領域を画像矩形に固定して、画像座標のままの `RenderTexture` に描く。レシピが変わったフレームだけ (`dirty`)。プレビューは長辺 2048 まで縮小 +- **表示の段** (`render/editor-renderer.ts`): そのテクスチャの `Sprite` に幾何 (rotation / scale(-1,1)) を `Container` の transform で掛ける。トリミングは `mask` ではなく書き出し時の `frame` で切り出す。プレビュー中はクロップ枠と円形マスクの枠をオーバーレイ (DOM) で描く +- スライダー変更は uniform 更新と `dirty` だけ。再描画は Pixi の ticker で 1 フレームに 1 回 +- ズームと移動は表示の段だけ (`render/viewport.ts`、純関数)。操作は `ui/use-canvas-gestures.ts` (ジェスチャの計算は `ui/gesture.ts`): ホイールでカーソルを軸にズーム (トラックパッドのピンチも同じ)、ドラッグで移動 (ブラシ・ハンドル・トリミング枠の上では起きない。中ボタンと Space + ドラッグはどこでも移動)、2 本指はピンチでズームしそのまま動かして移動。ブラシで描いている途中に 2 本目が触れたらピンチに切り替え、描きかけは捨てる (`pointercancel`)。ホストは `touch-action: none`。フィットの 0.5〜8 倍、小さい画像は等倍まで縮小可、ツールバーの −/+/倍率 (押すと等倍)/フィット。オーバーレイは `viewRect` から位置を出すので追従する。canvas は絶対配置にし、`section` に `min-w-0` を付けて、窓を狭めたときに右パネルが押し出されないようにする +- 「比較」は表示の段で、元画像の `Sprite` を下に置き、現像後を境界より右だけ `mask` で見せる +- ブラシマスクは `brush-raster.ts` (純関数) でストロークを長辺 1024 のラスタに描き、`render/mask-texture.ts` が canvas 経由でテクスチャにする。確定 (commit) ではゼロから描き直し、描画中は `previewStroke` で線分ごとに足す。`BrushOverlay` はポインタの点列を画像座標にして間引き (長辺の 0.5% 未満は捨てる、最大 512 点)、離したときに 1 ストローク = 1 手で積む +- 部分補正のマスクは幾何を掛ける前の画像の正規化座標。頂点シェーダの `aPosition` がそのまま画像座標になる (領域 = 画像矩形) ので、回転・反転・トリミングでずれない。画面との往復は `mask-math.ts` (`imageUvToCanvas` / `canvasToImageUv`)。選択中の範囲は `uShowMask` で赤く重ねる (ブラシで塗っている・円形をドラッグしている間だけ。常時は「範囲を表示」で。常時だと補正の効きが赤に埋もれて見えない) +- 色補正の GLSL は `render/adjust-glsl.ts` に 1 つ。全体と部分の両方が埋め込み、`adjust-math.ts` / `mask-math.ts` の CPU 参照と同じ式 + +### 3.4 書き出し + +1. 合成の段を原寸 (4096 と `MAX_TEXTURE_SIZE` の小さい方) で描き直し、`renderer.extract.canvas(container, { frame: cropRect, resolution })` で切り出す。終わったらプレビュー寸法に戻し `TexturePool.clear(true)` +2. `toBlob("image/webp", 0.92)`。非対応なら `image/jpeg`, 0.92 +3. 「端末に保存」は ``。送り先のボタン (prismtone は「投稿へ」) は書き出した Blob、レシピ、原本を送り先の `send` に渡す。prismtone の「投稿へ」は Blob とレシピを IndexedDB の `pending` に置いて `/edit/post` へ遷移する +4. 書き出し中は進捗を表示 (大きな画像で 1 秒以上かかる) + +### 3.5 状態 + +```ts +type EditorState = { + source: { bitmap: ImageBitmap; blob: Blob; name: string } | null; + history: { past: EditRecipeV1[]; present: EditRecipeV1; future: EditRecipeV1[] }; + ui: { + comparing: boolean; + tool: "presets" | "adjust" | "local" | "geometry"; + local: { selectedId: string | null; showMask: boolean }; + }; +}; +``` + +部分補正 (`local/*` アクション) も同じ履歴に積む。追加・削除・表示切替・プリセットは 1 手、スライダーとマスクのドラッグは preview / commit の同じ規則。`ui.local.selectedId` は undo で消えることがあるので、reducer が履歴の操作後に引き直す。 + +`history` の操作は `packages/editor-engine/src/history.ts` に純粋関数として置き、単体テストする。 + +### 3.6 自動選択 (ブラウザ内の認識、lumorphia/prismtone#176 / ADR-0025) + +「瞳強調」「美肌」を押すと顔を認識してマスクを自動で置く。置いたあとは今の道具 (ハンドル、ブラシ) で直す。 + +- **推論は Web Worker** (`packages/editor-engine/src/inference/face.worker.ts`)。MediaPipe Face Landmarker (WASM、CPU)。classic worker にする (MediaPipe の WASM ローダーが `importScripts` を使うので module worker では動かない)。ライブラリは押したときに動的 import (`inference/face.ts`) し、現像の初期表示に載せない +- **検出はピラミッド**: 画像全体 → 2 倍の 3×3 の重なる切り抜き。同じ顔 (IoU 0.3) は先に見つかった方を残し、切り抜きの縁にかかる顔は捨てる。しきい値 0.3。根拠は [spike](https://github.com/lumorphia/prismtone/blob/develop/docs/spikes/2026-09-21-auto-select.md) +- **結果からマスクへ** (`inference/face-masks.ts`、純関数): 瞳は虹彩の中心と半径 (×1.3) の円形 ×2、美肌は顔の輪郭 (36 点) を外周、両目と唇を穴にした `polygon`。目を閉じている (`eyeBlink` ≥ 0.5) 目には置かない。複数の顔は一番大きい顔 (人物の選択は lumorphia/prismtone#175) +- **計画** (`inference/auto-select.ts`、純関数): 何を足すか (`local/add-auto` で 1 手) と一言 (`ui/notice`)。失敗の文言は理由を断定しない: 「自動選択できませんでした。手動で範囲を指定できます」 +- **モデルの配布**: `pnpm models` (`@lumorphia/editor-engine` の CLI `editor-models fetch --out models`、一覧は `packages/editor-engine/bin/assets.ts`) が sha256 固定で `apps/app/models/face-landmarker-v1/` に置き (git には入れない、`dev` / `build` の前に走る)、Fastify の static (`server/plugins/models.ts`) が `/models/` で配る。Vite の `public/` には置かない (dev の Vite が `import()` に `?import` を足して WASM ローダーを読めなくする)。モデル本体は Worker が fetch して進捗を出し、`modelAssetBuffer` で渡す +- **CSP**: `script-src 'self' 'wasm-unsafe-eval'` と `worker-src 'self'` のまま。`csp.spec.ts` が顔の画像で瞳が置かれることを見る +- 画像も推論結果も外に送らない。`editor.spec.ts` が自分のオリジン以外へのリクエストが無いことを見る + +### 3.7 タップで切る (SlimSAM、lumorphia/prismtone#177 / ADR-0025) + +「装備強調」を何も選ばずに押すと、画像の埋め込みを済ませてからタップ待ちになり、タップした装備を切り抜いて `bitmap` マスクで置く。「キャラクター」「背景」はプリセット無しで人物全体 (背景はその反転) を置く。 + +- **推論は module worker** (`inference/segment.worker.ts`)。transformers.js の `SamModel` + `Xenova/slimsam-77-uniform` (q8) を onnxruntime-web (WASM) で。`env.allowRemoteModels = false`、`localModelPath = "/models/"`、ORT の WASM は `/models/ort-v1/`。HF Hub には行かない +- **埋め込みは画像 1 枚につき 1 回** (`prepareSegmenter`、同じ bitmap なら使い回す)。タップごとに `segmentAt` で 3 段のマスクを bitmap (長辺 256、RLE) にして返す +- **3 段の粒度** (`SAM_LEVELS`): 0 = キャラクター全体、1 = その装備 1 点、2 = 部品。装備強調の既定は 1 (IoU スコアで選ぶと全体に寄る)。パネルの「切り抜きの範囲」で差し替えられる (下地だけ替え、反転と塗り足したストロークは保つ) +- **時間** (この機、headless): 押してからタップ待ちまで 3.4〜3.9 秒 (WASM 初期化 + モデル + 埋め込み)、タップ 0.3 秒。`/edit` の文書と `/assets/` `/models/` の応答に `Cross-Origin-Embedder-Policy: credentialless` を付け (COOP は helmet の `same-origin`)、cross-origin isolated にして SharedArrayBuffer を使えるようにした (lumorphia/prismtone#182。付ける前はシングルスレッドで約 10 秒)。専用 worker のスクリプトの応答にも COEP が要るので、文書だけでなくアセットにも付けている。`credentialless` なので CORP の無い他オリジンの画像 (`/edit/post` に client-side で進んだあとの XIVAPI のアイコン、R2 の画像) も匿名で読める。`/edit` 以外の文書には付けない。WebGPU は未計測 (実機で測ってから) +- **タップ待ち** (`ui.local.tap`): `TapOverlay` がキャンバス全体でクリックを 1 回受け、画像の正規化座標にする。Esc と「やめる」で抜ける + +### 3.8 人物補正 (lumorphia/prismtone#175) + +「人物補正」タブ: 人物を認識する → (複数なら) 番号で選ぶ → プリセット → 効果量。中身は部分補正 5 件 (背景・人物・顔・瞳 ×2、`groupId` で束ねる) で、部分補正タブで個別に直せる。 + +- 検出は 3.6 の顔検出、人物のマスクは 3.7 の SAM (顔の外接矩形の中心をタップ、index 0 = 全体) の組み合わせ。`inference/portrait.ts` の `buildPortraitItems` が 5 件を組む (閉じている目は置かない) +- 状態は `ui.portrait` (検出した顔、選んだ人物、グループ、プリセット)。グループがレシピに残っているかは `activePortraitGroup` で見る (undo で消え redo で戻るので、ui の id は消さない)。プリセットの切り替えは 1 手、効果量はドラッグの規則 (preview / commit) +- 複数の顔は `FaceBoxesOverlay` が番号付きの枠を重ね、枠かパネルの番号で選ぶ +- 失敗 (顔が無い、切り抜けない) は「自動選択できませんでした。手動で範囲を指定できます」+ 部分補正タブへの導線。上限 12 件に 5 件が入り切らないときも置かずに伝える +- 性能: 部分補正はパスに比例する。12 件で 8 件の 1.5 倍 (SwiftShader の計測は [spike](https://github.com/lumorphia/prismtone/blob/develop/docs/spikes/2026-09-20-local-adjust-perf.md))。人物補正 2 人 (10 件) が実用の上限 + +## 7. テスト + +- `history.ts`, レシピ zod (`packages/shared`), プリセット適用: Vitest +- シェーダ: `adjust-math.ts` に CPU 参照実装を置き、GLSL はそれを写す。Playwright (headless Chromium + SwiftShader) で 4 色のテスト画像を書き出し、全プリセットについて GPU 出力と CPU 参照が ±3/255 に収まることを検証する。露光 +1 EV で線形輝度 2 倍、彩度 -100 で R=G=B も確認 +- 画面: Playwright で「画像を開く → プリセット適用 → undo/redo/リセット → 端末に保存 (download イベント)」と、不正ファイルの拒否メッセージを E2E。E2E 用に `window.__PRISMTONE_E2E__` が立っているときだけ `window.__prismtoneEditor.exportPixels()` を露出する (名前はホストの `testHook` で渡す) diff --git a/e2e/README.md b/e2e/README.md new file mode 100644 index 0000000..c271b58 --- /dev/null +++ b/e2e/README.md @@ -0,0 +1,5 @@ +# E2E + +prismtone から移した現像の E2E (`editor.spec.ts`: GPU と CPU の照合、マスク、推論。`perf-local-adjust.spec.ts`: 性能の計測)。 + +今はまだ動かない。prismtone の土台 (`./test.ts` の CSP の見張り、`./helpers.ts`、`./api.ts` の `devLogin`、投稿画面への遷移) を前提にしているため。単独アプリ (`apps/web`) を E2E の土台にして、このリポジトリで回せるようにする (#3)。それまでは lint だけかかり、型検査 (tsconfig.json の include に無い) と実行はしない。 diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts new file mode 100644 index 0000000..97c97e8 --- /dev/null +++ b/e2e/editor.spec.ts @@ -0,0 +1,1013 @@ +import { type Page } from "@playwright/test"; +import { expect, test } from "./test.ts"; +import { + DEFAULT_BRUSH_MASK, + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + applyPreset, + findPreset, + type EditRecipe, +} from "@lumorphia/editor-recipe"; +import { applyAdjust, applyRecipeAt } from "@lumorphia/editor-engine/reference"; +import { devLogin } from "./api.ts"; +import { continueToPostForm } from "./helpers.ts"; + +// 4 色のブロックからなるテスト画像 (200x100)。左から赤・緑・青・灰 +const BLOCKS: [number, number, number][] = [ + [200, 40, 60], + [40, 180, 80], + [50, 90, 220], + [128, 128, 128], +]; + +async function makePng(page: Page): Promise { + const dataUrl = await page.evaluate((blocks) => { + const c = document.createElement("canvas"); + c.width = 200; + c.height = 100; + const ctx = c.getContext("2d")!; + blocks.forEach(([r, g, b], i) => { + ctx.fillStyle = `rgb(${r},${g},${b})`; + ctx.fillRect(i * 50, 0, 50, 100); + }); + return c.toDataURL("image/png"); + }, BLOCKS); + return Buffer.from(dataUrl.split(",")[1]!, "base64"); +} + +async function openEditorWithImage(page: Page) { + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + await expect(page.getByRole("button", { name: "画像を開く" })).toBeVisible(); + const png = await makePng(page); + await page + .getByTestId("file-input") + .setInputFiles({ name: "test.png", mimeType: "image/png", buffer: png }); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.waitForFunction(() => + Boolean((window as Window & { __prismtoneEditor?: unknown }).__prismtoneEditor), + ); +} + +type Pixels = { width: number; height: number; type: string; pixels: number[][] }; + +async function exportPixels( + page: Page, + recipe: EditRecipe, + points: { x: number; y: number }[], +): Promise { + return page.evaluate( + ({ recipe, points }) => + ( + window as Window & { + __prismtoneEditor?: { + exportPixels: (r: EditRecipe, p: { x: number; y: number }[]) => Promise; + }; + } + ).__prismtoneEditor!.exportPixels(recipe, points), + { recipe, points }, + ); +} + +const CENTERS = BLOCKS.map((_, i) => ({ x: i * 50 + 25, y: 50 })); + +function expectClose(actual: number[], expected: number[], tolerance: number) { + actual.forEach((v, i) => + expect( + Math.abs(v - expected[i]!), + `channel ${i}: ${actual} vs ${expected}`, + ).toBeLessThanOrEqual(tolerance), + ); +} + +// 各テストは /edit を開き直し、状態を共有しないので、ファイルの中でも並べて走らせる (#277) +test.describe.configure({ mode: "parallel" }); + +test.describe("editor", () => { + test("default recipe exports the source pixels unchanged", async ({ page }) => { + await openEditorWithImage(page); + const out = await exportPixels(page, DEFAULT_RECIPE, CENTERS); + expect(out.width).toBe(200); + expect(out.height).toBe(100); + out.pixels.forEach((px, i) => expectClose(px, BLOCKS[i]!, 2)); + }); + + test("GPU output matches the CPU reference for every preset", async ({ page }) => { + await openEditorWithImage(page); + const { PRESETS } = await import("@lumorphia/editor-recipe"); + for (const preset of PRESETS) { + const recipe = applyPreset(DEFAULT_RECIPE, preset); + const out = await exportPixels(page, recipe, CENTERS); + out.pixels.forEach((px, i) => { + const src = BLOCKS[i]!.map((v) => v / 255) as [number, number, number]; + const expected = applyAdjust(src, recipe.adjust).map((v) => Math.round(v * 255)); + expectClose(px, expected, 3); + }); + } + }); + + test("saturation -100 yields neutral gray, exposure +1 doubles linear light", async ({ + page, + }) => { + await openEditorWithImage(page); + const mono = applyPreset(DEFAULT_RECIPE, findPreset("mono")!); + const gray = await exportPixels( + page, + { ...mono, adjust: { ...mono.adjust, contrast: 0 } }, + CENTERS, + ); + for (const [r, g, b] of gray.pixels) { + expect(Math.abs(r! - g!)).toBeLessThanOrEqual(2); + expect(Math.abs(g! - b!)).toBeLessThanOrEqual(2); + } + const bright = await exportPixels( + page, + { ...DEFAULT_RECIPE, adjust: { ...DEFAULT_RECIPE.adjust, exposure: 1 } }, + [CENTERS[3]!], + ); + // 128/255 -> linear 0.2158 -> x2 = 0.4317 -> sRGB 0.6906 -> 176 + expectClose(bright.pixels[0]!, [176, 176, 176], 3); + }); + + test("geometry: rotation and crop change the output size", async ({ page }) => { + await openEditorWithImage(page); + const rotated: EditRecipe = { + ...DEFAULT_RECIPE, + geometry: { ...DEFAULT_RECIPE.geometry, rotation: 90 }, + }; + const r = await exportPixels(page, rotated, [{ x: 50, y: 25 }]); + expect(r.width).toBe(100); + expect(r.height).toBe(200); + // 右回転後: 元の左端 (赤) は上端に来る + expectClose(r.pixels[0]!, BLOCKS[0]!, 2); + + const cropped: EditRecipe = { + ...DEFAULT_RECIPE, + geometry: { ...DEFAULT_RECIPE.geometry, crop: { x: 0.5, y: 0, w: 0.5, h: 1 } }, + }; + const c = await exportPixels(page, cropped, [ + { x: 25, y: 50 }, + { x: 75, y: 50 }, + ]); + expect(c.width).toBe(100); + expectClose(c.pixels[0]!, BLOCKS[2]!, 2); + expectClose(c.pixels[1]!, BLOCKS[3]!, 2); + }); + + test("a local adjustment applies inside its ellipse mask only, and follows rotation and crop (#109)", async ({ + page, + }) => { + await openEditorWithImage(page); + const size = { width: 200, height: 100 }; + // 赤ブロックの中心に半径 20px の円。ぼかし無し + const eye = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "eye", + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.125, cy: 0.5, rx: 0.1, ry: 0.2, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 1, saturation: -50 }, + amount: 100, + }; + const recipe: EditRecipe = { + ...DEFAULT_RECIPE, + adjust: { ...DEFAULT_RECIPE.adjust, contrast: 20 }, + localAdjustments: [eye], + }; + const cpu = (rgb: [number, number, number], uv: { x: number; y: number }) => + applyRecipeAt(rgb.map((v) => v / 255) as [number, number, number], uv, recipe, size).map( + (v) => Math.round(v * 255), + ); + + const out = await exportPixels(page, recipe, [ + { x: 25, y: 50 }, // マスクの中心 + { x: 75, y: 50 }, // 緑 (マスク外) + { x: 25, y: 5 }, // 赤だがマスクの外 (縦半径 20px) + ]); + expectClose(out.pixels[0]!, cpu(BLOCKS[0]!, { x: 0.125, y: 0.5 }), 3); + expectClose(out.pixels[1]!, cpu(BLOCKS[1]!, { x: 0.375, y: 0.5 }), 3); + expectClose(out.pixels[2]!, cpu(BLOCKS[0]!, { x: 0.125, y: 0.05 }), 3); + // マスク内は外と違う (補正が効いている) + expect(out.pixels[0]).not.toEqual(out.pixels[2]); + + // 90 度回転 + 左半分をトリミングしても、同じ画素が同じ値になる。 + // 回転後 (100x200) で赤ブロックは上端 0..50、マスクの中心は (50, 25)。crop は上半分 + const rotated: EditRecipe = { + ...recipe, + geometry: { ...recipe.geometry, rotation: 90, crop: { x: 0, y: 0, w: 1, h: 0.5 } }, + }; + const r = await exportPixels(page, rotated, [ + { x: 50, y: 25 }, + { x: 95, y: 25 }, + ]); + expect(r.width).toBe(100); + expect(r.height).toBe(100); + expectClose(r.pixels[0]!, out.pixels[0]!, 3); + expectClose(r.pixels[1]!, out.pixels[2]!, 3); + + // 非表示なら掛からない + const hidden: EditRecipe = { ...recipe, localAdjustments: [{ ...eye, visible: false }] }; + const h = await exportPixels(page, hidden, [{ x: 25, y: 50 }]); + expectClose( + h.pixels[0]!, + cpu(BLOCKS[0]!, { x: 0.375, y: 0.5 }).map((_, i) => + Math.round( + applyAdjust(BLOCKS[0]!.map((v) => v / 255) as [number, number, number], recipe.adjust)[ + i + ]! * 255, + ), + ), + 3, + ); + }); + + test("a brush mask applies along its strokes, erase takes it back, and smoothing leaves flat areas alone (#109)", async ({ + page, + }) => { + await openEditorWithImage(page); + const size = { width: 200, height: 100 }; + const stroke = (x: number, mode: "add" | "erase" = "add") => ({ + mode, + size: 0.15, // 直径 30px、半径 15px + hardness: 1, + points: [{ x, y: 0.5 }], + }); + // 緑と青のブロックの中心を塗り、青の方を消す。露光 +1 と美肌 (平滑化) を掛ける + const gear = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "gear", + mask: { + ...DEFAULT_BRUSH_MASK, + strokes: [stroke(0.375), stroke(0.625), stroke(0.625, "erase")], + }, + adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 1, smooth: 60, sharpen: 40 }, + amount: 100, + }; + const recipe: EditRecipe = { ...DEFAULT_RECIPE, localAdjustments: [gear] }; + const cpu = (rgb: [number, number, number], uv: { x: number; y: number }) => + applyRecipeAt(rgb.map((v) => v / 255) as [number, number, number], uv, recipe, size).map( + (v) => Math.round(v * 255), + ); + const out = await exportPixels(page, recipe, [ + { x: 75, y: 50 }, // 緑の中心 (塗った) + { x: 125, y: 50 }, // 青の中心 (塗って消した) + { x: 25, y: 50 }, // 赤 (塗っていない) + ]); + // 平坦部なので平滑化・シャープは値を変えず、露光だけが効く + expectClose(out.pixels[0]!, cpu(BLOCKS[1]!, { x: 0.375, y: 0.5 }), 3); + expectClose(out.pixels[1]!, BLOCKS[2]!, 2); + expectClose(out.pixels[2]!, BLOCKS[0]!, 2); + expect(out.pixels[0]).not.toEqual(BLOCKS[1]); + }); + + const sourceAt = ({ x }: { x: number; y: number }) => + BLOCKS[Math.min(BLOCKS.length - 1, Math.floor(x * BLOCKS.length))]!.map( + (value) => value / 255, + ) as [number, number, number]; + const spatialRecipe = (adjust: Partial): EditRecipe => ({ + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "spatial", + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, ...adjust }, + }, + ], + }); + const spatialCpu = (recipe: EditRecipe, point: { x: number; y: number }) => + applyRecipeAt(sourceAt, { x: point.x / 200, y: point.y / 100 }, recipe, { + width: 200, + height: 100, + }).map((value) => Math.round(value * 255)); + + test("background blur matches the CPU reference at a colour boundary (#184)", async ({ + page, + }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ blur: 10 }); + const point = { x: 95, y: 50 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("bloom adds blurred highlights like the CPU reference (#184)", async ({ page }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ bloom: 100 }); + const point = { x: 55, y: 50 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("vignette darkens the corner like the CPU reference (#184)", async ({ page }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ vignette: 100 }); + const point = { x: 5, y: 5 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("clarity raises local contrast like the CPU reference (#184)", async ({ page }) => { + await openEditorWithImage(page); + const recipe = spatialRecipe({ clarity: 100 }); + const point = { x: 95, y: 50 }; + const out = await exportPixels(page, recipe, [point]); + expectClose(out.pixels[0]!, spatialCpu(recipe, point), 4); + }); + + test("the brush tool paints and erases on the canvas, one history step per stroke (#109)", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + // 手動の流れ: ブラシを足してから装備強調のプリセット (何も選んでいないときの「装備強調」はタップで切る、#177) + await page.getByTestId("local-add-brush").click(); + await page.getByRole("button", { name: "装備強調", exact: true }).click(); + await expect(page.getByTestId("local-list")).toContainText("装備強調 (ブラシ)"); + await expect(page.getByTestId("brush-settings")).toBeVisible(); + await expect(page.getByTestId("brush-overlay")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("美肌")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("背景ぼかし")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("発光")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("周辺減光")).toBeVisible(); + await expect(page.getByTestId("local-sliders").getByLabel("質感")).toBeVisible(); + + const host = await page.getByTestId("canvas-host").boundingBox(); + if (!host) throw new Error("no canvas"); + const y = host.y + host.height / 2; + const x0 = host.x + host.width * 0.3; + await page.mouse.move(x0, y); + await page.mouse.down(); + await page.mouse.move(x0 + 60, y, { steps: 6 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("ブラシ"); + + // 塗っている間だけ範囲が赤く重なり、離すと消えて補正 (露光 +2) だけが見える + const view = await page.evaluate(() => + ( + window as Window & { + __prismtoneEditor?: { + viewRect: () => { x: number; y: number; width: number; height: number }; + }; + } + ).__prismtoneEditor!.viewRect(), + ); + const uv = { + x: (x0 + 30 - host.x - view.x) / view.width, + y: (y - host.y - view.y) / view.height, + }; + const readAt = () => + page.evaluate( + (p) => + ( + window as Window & { + __prismtoneEditor?: { previewPixels: (q: { x: number; y: number }[]) => number[][] }; + } + ).__prismtoneEditor!.previewPixels([p])[0]!, + uv, + ); + const exposure = page.getByTestId("local-sliders").getByLabel("露光量"); + await exposure.focus(); + for (let i = 0; i < 4; i++) await page.keyboard.press("Shift+ArrowRight"); + // 装備強調の +0.15 に +2.00 が乗る + await expect(page.getByTestId("history-last")).toContainText("露光量 +2.15"); + const released = await readAt(); + expect(released[1]).toBeGreaterThan(BLOCKS[1]![1]! + 20); // 緑ブロックの上、露光で明るい + expect(released[1]).toBeGreaterThan(released[0]!); // 赤く染まっていない (緑が主のまま) + await page.mouse.move(x0 + 30, y); + await page.mouse.down(); + const pressed = await readAt(); + expect(pressed[0]).toBeGreaterThan(released[0]! + 40); // 押している間は赤が乗る + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("ブラシ"); + + await page.getByRole("button", { name: "消す", exact: true }).click(); + await page.mouse.move(x0, y); + await page.mouse.down(); + await page.mouse.move(x0 + 20, y, { steps: 3 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("消しゴム"); + await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("history-last")).toContainText("ブラシ"); + }); + + test("the local panel adds an ellipse, drags it, undoes, hides, and survives a redo of the export (#109)", async ({ + page, + }) => { + // 「投稿へ」から戻ってくる導線を使うのでログインしておく (MiAuth の共有の利用者は使わない。並列で走るため) + await devLogin(page, "editor_tester"); + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + // 手動の流れ: 円形を足してから瞳強調のプリセットを当てる (何も選んでいないときの「瞳強調」は顔の自動選択、#176) + await page.getByTestId("local-add-ellipse").click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await page.getByRole("button", { name: "瞳強調", exact: true }).click(); + await expect(page.getByTestId("local-list")).toContainText("瞳強調 (円形)"); + await expect(page.getByTestId("history-last")).toContainText("部分補正: 瞳強調"); + await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); + await expect(page.getByTestId("local-sliders")).toBeVisible(); + + // 中心ハンドルを右へ 40px ドラッグすると 1 手の履歴になり、ハンドルもついてくる + const move = page.getByTestId("ellipse-handle-move"); + const before = await move.boundingBox(); + if (!before) throw new Error("no handle"); + const cx = before.x + before.width / 2; + const cy = before.y + before.height / 2; + await page.mouse.move(cx, cy); + await page.mouse.down(); + await page.mouse.move(cx + 20, cy, { steps: 4 }); + await page.mouse.move(cx + 40, cy, { steps: 4 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("マスクを動かす"); + const after = await move.boundingBox(); + expect(Math.abs(after!.x - before.x - 40)).toBeLessThan(2); + await page.getByTestId("history-undo").click(); + const back = await move.boundingBox(); + expect(Math.abs(back!.x - before.x)).toBeLessThan(2); + await page.getByTestId("history-redo").click(); + + // スライダーは選択中の範囲に効く (露光量)。値の表示で確かめる + const exposure = page.getByTestId("local-sliders").getByLabel("露光量"); + await exposure.focus(); + await page.keyboard.press("ArrowRight"); + await expect(page.getByTestId("history-last")).toContainText("部分補正: 露光量 +0.35"); + // 手で変えたのでプリセットの強調は外れる + await expect(page.getByRole("button", { name: "瞳強調", exact: true })).toHaveAttribute( + "aria-pressed", + "false", + ); + + // 「枠を表示」を外すと輪郭とハンドルが消え、戻すと出る + await page.getByLabel("枠を表示").uncheck(); + await expect(page.getByTestId("ellipse-overlay")).toHaveCount(0); + await page.getByLabel("枠を表示").check(); + await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); + + // 隠すとオーバーレイは残るが (選択中)、非表示の印になる + await page.getByRole("button", { name: "表示中" }).click(); + await expect(page.getByTestId("local-list")).toContainText("非表示"); + + // 投稿へ → 現像をやり直す で戻っても部分補正が残っている (下書きの復元、v2 のレシピ) + await continueToPostForm(page); + await page.getByTestId("pending-image-redo-0").click(); + await page.waitForURL(/\/edit(\?|$)/); + await page.getByRole("tab", { name: "部分補正" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await expect(page.getByTestId("local-list")).toContainText("非表示"); + + // 全リセットで消える + await page.getByRole("button", { name: "全リセット" }).click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await expect(page.getByTestId("ellipse-overlay")).toHaveCount(0); + }); + + test("zoom: buttons, wheel around the cursor, drag pan, two-finger pinch, and fit; overlays follow", async ({ + page, + }) => { + await openEditorWithImage(page); + const viewRect = () => + page.evaluate(() => + ( + window as Window & { + __prismtoneEditor?: { + viewRect: () => { x: number; y: number; scale: number; width: number }; + }; + } + ).__prismtoneEditor!.viewRect(), + ); + const fit = await viewRect(); + await expect(page.getByTestId("zoom-percent")).toHaveText(`${Math.round(fit.scale * 100)}%`); + + await page.getByRole("button", { name: "拡大" }).click(); + const zoomed = await viewRect(); + expect(zoomed.scale / fit.scale).toBeCloseTo(1.25, 2); + await expect(page.getByTestId("zoom-percent")).toHaveText(`${Math.round(zoomed.scale * 100)}%`); + + // 円形マスクのハンドルは表示に追従する (中心のハンドルは画像の中心 = view の中央) + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByTestId("local-add-ellipse").click(); + const handle = page.getByTestId("ellipse-handle-move"); + const h1 = await handle.boundingBox(); + // ホイールで画像の左上寄りを軸に拡大 → 中心ハンドルは右下へ動く + const host = (await page.getByTestId("canvas-host").boundingBox())!; + await page.mouse.move(host.x + 10, host.y + 10); + await page.mouse.wheel(0, -100); + await expect.poll(async () => (await viewRect()).scale).toBeGreaterThan(zoomed.scale); + const h2 = await handle.boundingBox(); + expect(h2!.x).toBeGreaterThan(h1!.x); + expect(h2!.y).toBeGreaterThan(h1!.y); + + // ツールの無い場所をドラッグすると移動 (ハンドルの外、画像の上) + const before = await viewRect(); + await page.mouse.move(host.x + 40, host.y + 40); + await page.mouse.down(); + await page.mouse.move(host.x + 100, host.y + 70, { steps: 4 }); + await page.mouse.up(); + const dragged = await viewRect(); + expect(dragged.x - before.x).toBeCloseTo(60, 0); + expect(dragged.y - before.y).toBeCloseTo(30, 0); + expect(dragged.scale).toBe(before.scale); + + // 2 本指のピンチ (タッチのポインタイベントをホストに送る) で拡大 + await page.evaluate(() => { + const host = document.querySelector('[data-testid="canvas-host"]') as HTMLElement; + const r = host.getBoundingClientRect(); + const ev = (type: string, id: number, x: number, y: number) => + host.dispatchEvent( + new PointerEvent(type, { + pointerId: id, + pointerType: "touch", + isPrimary: id === 1, + clientX: r.left + x, + clientY: r.top + y, + bubbles: true, + cancelable: true, + }), + ); + ev("pointerdown", 1, 200, 200); + ev("pointerdown", 2, 300, 200); + ev("pointermove", 1, 150, 200); + ev("pointermove", 2, 350, 200); + ev("pointerup", 1, 150, 200); + ev("pointerup", 2, 350, 200); + }); + const pinched = await viewRect(); + expect(pinched.scale / dragged.scale).toBeCloseTo(2, 1); + + // 拡大して移動したあとに足した円形は、今見えている範囲の中央に来る (画像の中央ではない) + await page.getByTestId("local-add-ellipse").click(); + const hostBox = (await page.getByTestId("canvas-host").boundingBox())!; + const added = (await page.getByTestId("ellipse-handle-move").boundingBox())!; + const v = await viewRect(); + const visibleCx = + Math.max(0, v.x) + (Math.min(hostBox.width, v.x + v.width) - Math.max(0, v.x)) / 2; + expect(added.x + added.width / 2 - hostBox.x).toBeCloseTo(visibleCx, 0); + + await page.getByRole("button", { name: "フィット" }).click(); + await expect.poll(async () => (await viewRect()).scale).toBeCloseTo(fit.scale, 5); + // 等倍 + await page.getByTestId("zoom-percent").click(); + await expect(page.getByTestId("zoom-percent")).toHaveText("100%"); + }); + + test("a second finger during a brush stroke turns it into a pinch and discards the stroke", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByTestId("local-add-brush").click(); + const scaleBefore = await page.evaluate( + () => + ( + window as Window & { __prismtoneEditor?: { viewRect: () => { scale: number } } } + ).__prismtoneEditor!.viewRect().scale, + ); + await page.evaluate(() => { + const host = document.querySelector('[data-testid="canvas-host"]') as HTMLElement; + const overlay = host.querySelector('[data-testid="brush-overlay"]') as HTMLElement; + const r = host.getBoundingClientRect(); + const ev = (el: HTMLElement, type: string, id: number, x: number, y: number) => + el.dispatchEvent( + new PointerEvent(type, { + pointerId: id, + pointerType: "touch", + isPrimary: id === 1, + button: 0, + clientX: r.left + x, + clientY: r.top + y, + bubbles: true, + cancelable: true, + }), + ); + ev(overlay, "pointerdown", 1, 200, 200); + ev(overlay, "pointermove", 1, 220, 200); + ev(overlay, "pointerdown", 2, 300, 200); + ev(overlay, "pointermove", 1, 180, 200); + ev(overlay, "pointermove", 2, 340, 200); + ev(overlay, "pointerup", 1, 180, 200); + ev(overlay, "pointerup", 2, 340, 200); + }); + const scaleAfter = await page.evaluate( + () => + ( + window as Window & { __prismtoneEditor?: { viewRect: () => { scale: number } } } + ).__prismtoneEditor!.viewRect().scale, + ); + expect(scaleAfter).toBeGreaterThan(scaleBefore); + // ストロークは履歴に積まれていない + await expect(page.getByTestId("history-last")).not.toContainText("ブラシ"); + }); + + test("shrinking the window keeps the side panel and refits the image", async ({ page }) => { + await page.setViewportSize({ width: 1800, height: 900 }); + await openEditorWithImage(page); + await page.setViewportSize({ width: 1100, height: 800 }); + await expect + .poll(async () => { + const aside = await page.locator("aside").boundingBox(); + return aside ? aside.x + aside.width : 0; + }) + .toBeLessThanOrEqual(1100); + const host = await page.getByTestId("canvas-host").boundingBox(); + const view = await page.evaluate(() => + ( + window as Window & { __prismtoneEditor?: { viewRect: () => { width: number } } } + ).__prismtoneEditor!.viewRect(), + ); + expect(view.width).toBeLessThanOrEqual(host!.width); + expect(view.width).toBeGreaterThan(host!.width * 0.9); + }); + + test("a large image is developed over its whole preview, and a local adjustment lands where it was placed", async ({ + page, + }) => { + // 3000x2000 はプレビューで 2048 に縮む。縮小した合成の段でも画像全体が描かれ、右下の部分補正も効く + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + const png = await page.evaluate(() => { + const c = document.createElement("canvas"); + c.width = 3000; + c.height = 2000; + const g = c.getContext("2d")!; + g.fillStyle = "rgb(128,128,128)"; + g.fillRect(0, 0, 3000, 2000); + return c.toDataURL("image/png"); + }); + await page.getByTestId("file-input").setInputFiles({ + name: "big.png", + mimeType: "image/png", + buffer: Buffer.from(png.split(",")[1]!, "base64"), + }); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.waitForFunction(() => + Boolean((window as Window & { __prismtoneEditor?: unknown }).__prismtoneEditor), + ); + // 右下 (0.9, 0.9) に露光 +2 の円形マスク + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByTestId("local-add-ellipse").click(); + const move = page.getByTestId("ellipse-handle-move"); + const view = await page.evaluate(() => + ( + window as Window & { + __prismtoneEditor?: { + viewRect: () => { x: number; y: number; width: number; height: number }; + }; + } + ).__prismtoneEditor!.viewRect(), + ); + const host = (await page.getByTestId("canvas-host").boundingBox())!; + const from = (await move.boundingBox())!; + await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2); + await page.mouse.down(); + await page.mouse.move(host.x + view.x + 0.9 * view.width, host.y + view.y + 0.9 * view.height, { + steps: 5, + }); + await page.mouse.up(); + const exposure = page.getByTestId("local-sliders").getByLabel("露光量"); + await exposure.focus(); + for (let i = 0; i < 4; i++) await page.keyboard.press("Shift+ArrowRight"); + await expect(page.getByTestId("history-last")).toContainText("露光量 +2.00"); + + const px = await page.evaluate(() => + ( + window as Window & { + __prismtoneEditor?: { previewPixels: (p: { x: number; y: number }[]) => number[][] }; + } + ).__prismtoneEditor!.previewPixels([ + { x: 0.9, y: 0.9 }, + { x: 0.1, y: 0.1 }, + { x: 0.98, y: 0.5 }, + ]), + ); + // マスクの中心は明るく、離れた左上はそのまま、右端 (マスクの外) も (透明 = 黒ではなく) 灰色で描かれている + expect(px[0]![0]).toBeGreaterThan(200); + expectClose(px[1]!, [128, 128, 128], 2); + expectClose(px[2]!, [128, 128, 128], 2); + + // 書き出し (原寸 3000x2000) も四隅まで描かれ、マスクの中心は明るい + const recipe = await page.evaluate(() => + ( + window as Window & { __prismtoneEditor?: { currentRecipe: () => EditRecipe } } + ).__prismtoneEditor!.currentRecipe(), + ); + const out = await exportPixels(page, recipe, [ + { x: 10, y: 10 }, + { x: 2990, y: 1990 }, + { x: 2700, y: 1800 }, + { x: 2940, y: 1000 }, + ]); + expect(out.width).toBe(3000); + expect(out.height).toBe(2000); + expectClose(out.pixels[0]!, [128, 128, 128], 2); + expectClose(out.pixels[1]!, [128, 128, 128], 2); + expect(out.pixels[2]![0]).toBeGreaterThan(200); + expectClose(out.pixels[3]!, [128, 128, 128], 2); + }); + + test("preset, undo, redo and reset drive the UI", async ({ page }) => { + await openEditorWithImage(page); + await page.getByRole("button", { name: "モノクロ", exact: true }).click(); + await expect(page.getByRole("button", { name: "モノクロ", exact: true })).toHaveAttribute( + "aria-pressed", + "true", + ); + await expect(page.getByTestId("history-undo")).toBeEnabled(); + await expect(page.getByTestId("history-undo")).toHaveAttribute( + "title", + "プリセット: モノクロ を取り消す (Ctrl+Z)", + ); + await expect(page.getByTestId("history-last")).toContainText("プリセット: モノクロ"); + await page.getByTestId("history-undo").click(); + await expect(page.getByRole("button", { name: "モノクロ", exact: true })).toHaveAttribute( + "aria-pressed", + "false", + ); + await page.getByTestId("history-redo").click(); + await expect(page.getByRole("button", { name: "モノクロ", exact: true })).toHaveAttribute( + "aria-pressed", + "true", + ); + await page.getByRole("button", { name: "全リセット" }).click(); + await expect(page.getByRole("button", { name: "モノクロ", exact: true })).toHaveAttribute( + "aria-pressed", + "false", + ); + }); + + test("compare slider toggles, moves by drag and keyboard, and turns off while cropping", async ({ + page, + }) => { + await openEditorWithImage(page); + await page.getByRole("button", { name: "モノクロ", exact: true }).click(); + const toggle = page.getByTestId("compare-toggle"); + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-pressed", "true"); + const slider = page.getByTestId("compare-slider"); + await expect(slider).toBeVisible(); + + // ドラッグで境界が動く + const box = (await slider.boundingBox())!; + await page.mouse.move(box.x + box.width * 0.5, box.y + box.height * 0.5); + await page.mouse.down(); + await page.mouse.move(box.x + box.width * 0.8, box.y + box.height * 0.5, { steps: 5 }); + await page.mouse.up(); + const range = page.getByTestId("compare-range"); + expect(Number(await range.inputValue())).toBeGreaterThan(700); + + // キーボードでも動く + await range.focus(); + await page.keyboard.press("ArrowLeft"); + expect(Number(await range.inputValue())).toBeLessThan(800); + + // 切り抜きを始めると比較は切れ、ボタンも押せない + await page.getByRole("tab", { name: "幾何" }).click(); + await page.getByRole("button", { name: "トリミング", exact: true }).click(); + await expect(slider).toHaveCount(0); + await expect(toggle).toBeDisabled(); + }); + + test("save downloads an image file", async ({ page }) => { + await openEditorWithImage(page); + const download = page.waitForEvent("download"); + await page.getByTestId("save").click(); + const d = await download; + expect(d.suggestedFilename()).toMatch(/^test-prismtone\.(webp|jpg)$/); + }); + + test("rejects non-image files with a message", async ({ page }) => { + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles({ name: "x.png", mimeType: "image/png", buffer: Buffer.from("not a png") }); + await expect(page.getByRole("alert")).toContainText("PNG または JPEG"); + }); + + test("瞳強調の選択中でも美肌を自動選択で追加でき、範囲をブラシで直せる (#176, #210)", async ({ + page, + }) => { + // 顔の認識のモデル (WASM) の読み込みを最大 60 秒待つので、テスト全体の持ち時間 (既定 60 秒) を延ばす。 + // 遅い CI では読み込みだけで 20 秒近くかかる (#348 の CI で 60 秒を使い切った) + test.setTimeout(180_000); + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + // 画像を外に送らないこと: このテストの間、自分のオリジン以外へのリクエストが無い + const foreign: string[] = []; + page.on("request", (req) => { + if (!/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/)/.test(req.url())) foreign.push(req.url()); + }); + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.getByRole("tab", { name: "部分補正" }).click(); + + // 瞳: 初回はモデルを読み込む (数 MB) ので待つ。両目に円形が 2 つ、1 手の履歴 + await page.getByRole("button", { name: "瞳強調", exact: true }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(2, { + timeout: 60_000, + }); + await expect(page.getByTestId("local-list")).toContainText("瞳強調 (円形)"); + await expect(page.getByTestId("history-last")).toContainText("瞳強調 (自動)"); + await expect(page.getByTestId("ellipse-overlay")).toBeVisible(); + // 円形は顔の上半分にある (画像は 960×540、顔は中央やや上) + const handle = await page.getByTestId("ellipse-handle-move").boundingBox(); + const host = await page.getByTestId("canvas-host").boundingBox(); + expect(handle && host && handle.y < host.y + host.height * 0.6).toBe(true); + + // 瞳が選択中でも、美肌を別の自動選択として追加できる。顔の輪郭が選択され、ブラシで直せる + await page.getByTestId("local-auto-skin").click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(3); + await expect(page.getByTestId("local-list")).toContainText("美肌 (多角形)"); + await expect(page.getByTestId("history-last")).toContainText("美肌 (自動)"); + await expect(page.getByTestId("brush-settings")).toBeVisible(); + await page.getByTestId("brush-settings").getByRole("button", { name: "消す" }).click(); + const box = (await page.getByTestId("canvas-host").boundingBox())!; + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + box.width / 2 + 30, box.y + box.height / 2, { steps: 4 }); + await page.mouse.up(); + await expect(page.getByTestId("history-last")).toContainText("消しゴム"); + + expect(foreign).toEqual([]); + }); + + test("when no face is found the panel says so and manual masks still work (#176)", async ({ + page, + }) => { + // 顔の認識のモデル (WASM) の読み込みを最大 60 秒待つので、テスト全体の持ち時間 (既定 60 秒) を延ばす。 + // 遅い CI では読み込みだけで 20 秒近くかかる (#348 の CI で 60 秒を使い切った) + test.setTimeout(180_000); + await openEditorWithImage(page); + await page.getByRole("tab", { name: "部分補正" }).click(); + await page.getByRole("button", { name: "美肌", exact: true }).click(); + await expect(page.getByTestId("local-notice")).toContainText("自動選択できませんでした", { + timeout: 60_000, + }); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByTestId("local-add-brush").click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(1); + await expect(page.getByTestId("local-notice")).toHaveCount(0); + }); + + test("装備強調 cuts out the tapped gear with SAM, switches granularity, and キャラクター / 背景 select the person (#177)", async ({ + page, + }) => { + test.setTimeout(180_000); + const foreign: string[] = []; + page.on("request", (req) => { + if (!/^https?:\/\/(127\.0\.0\.1|localhost)(:|\/)/.test(req.url())) foreign.push(req.url()); + }); + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.getByRole("tab", { name: "部分補正" }).click(); + // /edit は COOP + COEP credentialless で cross-origin isolated (#182)。SharedArrayBuffer が使えて ORT がマルチスレッドになる + expect(await page.evaluate(() => crossOriginIsolated)).toBe(true); + + // 装備強調: モデルの読み込みと埋め込み (マルチスレッドの WASM で 3〜4 秒) のあとタップ待ちになる + await page.getByRole("button", { name: "装備強調", exact: true }).click(); + await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 120_000 }); + const host = (await page.getByTestId("canvas-host").boundingBox())!; + // 胸のあたり (赤いコート) をタップ + await page.mouse.click(host.x + host.width * 0.5, host.y + host.height * 0.85); + await expect(page.getByTestId("local-list")).toContainText("装備強調 (切り抜き)", { + timeout: 60_000, + }); + await expect(page.getByTestId("history-last")).toContainText("装備強調 (自動)"); + await expect(page.getByTestId("tap-overlay")).toHaveCount(0); + // 3 段の粒度。既定は「装備」、全体に切り替えると 1 手 + const levels = page.getByTestId("segment-levels"); + await expect(levels.getByRole("button", { name: "装備" })).toHaveAttribute( + "aria-pressed", + "true", + ); + await levels.getByRole("button", { name: "全体" }).click(); + await expect(page.getByTestId("history-last")).toContainText("切り抜き: 全体"); + await expect(levels.getByRole("button", { name: "全体" })).toHaveAttribute( + "aria-pressed", + "true", + ); + // 切り抜きの上にブラシで塗れる + await expect(page.getByTestId("brush-settings")).toBeVisible(); + + // キャラクター / 背景: プリセット無しの範囲。同じ画像なので埋め込みは使い回し (すぐタップ待ちになる) + await page.getByTestId("history-undo").click(); + await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByTestId("local-auto-background").click(); + await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 10_000 }); + await page.mouse.click(host.x + host.width * 0.5, host.y + host.height * 0.5); + await expect(page.getByTestId("local-list")).toContainText("背景", { timeout: 60_000 }); + await expect(page.getByTestId("history-last")).toContainText("背景を選択"); + + // やめる: タップ待ちを Esc で抜ける + await page.getByRole("button", { name: "背景 を削除" }).click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByTestId("local-auto-person").click(); + await expect(page.getByTestId("tap-overlay")).toBeVisible({ timeout: 10_000 }); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("tap-overlay")).toHaveCount(0); + + expect(foreign).toEqual([]); + }); + + test("人物補正 detects the person, applies a preset as five grouped adjustments, scales them, and survives a reload (#175)", async ({ + page, + }) => { + test.setTimeout(180_000); + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + await page + .getByTestId("file-input") + .setInputFiles(new URL("./fixtures/face.jpg", import.meta.url).pathname); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled(); + await page.getByRole("tab", { name: "人物補正" }).click(); + await page.getByTestId("portrait-detect").click(); + await expect(page.getByTestId("portrait-presets")).toBeVisible({ timeout: 60_000 }); + // 1 人なので人物の選択は出ない + await expect(page.getByTestId("portrait-faces")).toHaveCount(0); + + // プリセットを選ぶと 5 件 (背景・人物・顔・瞳 ×2) が 1 手で置かれる + await page.getByRole("button", { name: "ナチュラル" }).click(); + await expect(page.getByTestId("portrait-amount")).toBeVisible({ timeout: 120_000 }); + await expect(page.getByTestId("history-last")).toContainText("人物補正: ナチュラル"); + await expect( + page.getByTestId("portrait-presets").getByRole("button", { name: "ナチュラル" }), + ).toHaveAttribute("aria-pressed", "true"); + + // プリセットの切り替えは 1 手、効果量はドラッグの規則 (キーボードで 1 手) + await page + .getByTestId("portrait-presets") + .getByRole("button", { name: "ドラマチック" }) + .click(); + await expect(page.getByTestId("history-last")).toContainText("人物補正: ドラマチック"); + const amount = page.getByTestId("portrait-amount").getByLabel("効果量"); + await amount.focus(); + await page.keyboard.press("ArrowLeft"); + await expect(page.getByTestId("history-last")).toContainText("人物補正の効果量 99"); + + // 部分補正タブに 5 件、名前は役 + await page.getByRole("tab", { name: "部分補正" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(5); + await expect(page.getByTestId("local-list")).toContainText("背景"); + await expect(page.getByTestId("local-list")).toContainText("瞳 (左)"); + + // undo で 3 手戻すとグループごと消え、人物補正タブは「プリセットを選ぶ」に戻る。redo で戻る + for (let i = 0; i < 3; i++) await page.getByTestId("history-undo").click(); + await expect(page.getByTestId("local-list")).toHaveCount(0); + await page.getByRole("tab", { name: "人物補正" }).click(); + await expect(page.getByTestId("portrait-amount")).toHaveCount(0); + for (let i = 0; i < 3; i++) await page.getByTestId("history-redo").click(); + await expect(page.getByTestId("portrait-amount")).toBeVisible(); + + // 下書きを開き直しても 5 件が残り (v3 のレシピが IndexedDB を往復する)、書き出せる + const draftId = await page.evaluate( + () => + new Promise((resolve, reject) => { + const open = indexedDB.open("prismtone-editor"); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const req = open.result.transaction("kv").objectStore("kv").getAllKeys(); + req.onsuccess = () => { + const key = (req.result as string[]).find((k) => k.startsWith("draft:")); + if (!key) reject(new Error("no draft")); + else resolve(key.slice("draft:".length)); + }; + }; + }), + ); + await page.goto(`/edit?draft=${draftId}`); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled({ timeout: 30_000 }); + await page.getByRole("tab", { name: "部分補正" }).click(); + await expect(page.getByTestId("local-list").getByRole("listitem")).toHaveCount(5); + const download = page.waitForEvent("download"); + await page.getByTestId("save").click(); + expect((await download).suggestedFilename()).toMatch(/\.(webp|jpe?g|png)$/); + }); + + test("人物補正 says so when no face is found and points to the manual tools (#175)", async ({ + page, + }) => { + // 顔の認識のモデル (WASM) の読み込みを最大 60 秒待つので、テスト全体の持ち時間 (既定 60 秒) を延ばす。 + // 遅い CI では読み込みだけで 20 秒近くかかる (#348 の CI で 60 秒を使い切った) + test.setTimeout(180_000); + await openEditorWithImage(page); + await page.getByRole("tab", { name: "人物補正" }).click(); + await page.getByTestId("portrait-detect").click(); + await expect(page.getByTestId("portrait-notice")).toContainText("自動選択できませんでした", { + timeout: 60_000, + }); + await page.getByRole("button", { name: "部分補正で手で置く" }).click(); + await expect(page.getByTestId("local-add-brush")).toBeVisible(); + }); +}); diff --git a/e2e/fixtures/face.jpg b/e2e/fixtures/face.jpg new file mode 100644 index 0000000..e5a1aef Binary files /dev/null and b/e2e/fixtures/face.jpg differ diff --git a/e2e/perf-local-adjust.spec.ts b/e2e/perf-local-adjust.spec.ts new file mode 100644 index 0000000..acdd074 --- /dev/null +++ b/e2e/perf-local-adjust.spec.ts @@ -0,0 +1,114 @@ +import { type Page } from "@playwright/test"; +import { expect, test } from "./test.ts"; +import { + DEFAULT_BRUSH_MASK, + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + type EditRecipe, + type LocalAdjustment, +} from "@lumorphia/editor-recipe"; + +/** + * 部分補正の性能計測 (#109、docs/spikes/2026-09-20-local-adjust-perf.md)。 + * 通常の E2E では走らせない。PERF=1 pnpm exec playwright test e2e/perf-local-adjust.spec.ts --headed + * headless (SwiftShader、CPU 描画) は上限の目安。実機の GPU では --headed で取る + */ +test.skip(!process.env.PERF, "PERF=1 のときだけ"); + +async function makeNoisePng(page: Page, width: number, height: number): Promise { + const dataUrl = await page.evaluate( + ({ width, height }) => { + const c = document.createElement("canvas"); + c.width = width; + c.height = height; + const ctx = c.getContext("2d")!; + const img = ctx.createImageData(width, height); + let seed = 1; + for (let i = 0; i < img.data.length; i += 4) { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + img.data[i] = seed & 255; + img.data[i + 1] = (seed >> 8) & 255; + img.data[i + 2] = (seed >> 16) & 255; + img.data[i + 3] = 255; + } + ctx.putImageData(img, 0, 0); + return c.toDataURL("image/png"); + }, + { width, height }, + ); + return Buffer.from(dataUrl.split(",")[1]!, "base64"); +} + +const local = (i: number): LocalAdjustment => ({ + ...DEFAULT_LOCAL_ADJUSTMENT, + id: `l${i}`, + mask: + i % 2 === 0 + ? { ...DEFAULT_ELLIPSE_MASK, cx: 0.2 + i * 0.08, cy: 0.5, rx: 0.1, ry: 0.15 } + : { + ...DEFAULT_BRUSH_MASK, + strokes: [ + { + mode: "add", + size: 0.1, + hardness: 0.8, + points: Array.from({ length: 64 }, (_, k) => ({ + x: 0.1 + k * 0.012, + y: 0.3 + i * 0.05, + })), + }, + ], + }, + adjust: { + ...DEFAULT_LOCAL_ADJUST, + exposure: 0.3, + sharpen: 30, + smooth: i % 2 === 0 ? 0 : 40, + blur: i % 4 === 0 ? 8 : 0, + bloom: i % 4 === 1 ? 30 : 0, + vignette: i % 4 === 2 ? 20 : 0, + clarity: i % 4 === 3 ? 30 : 0, + }, +}); + +test("measure develop / export time and texture memory for 0 / 4 / 8 / 12 local adjustments", async ({ + page, +}) => { + test.setTimeout(600_000); + await page.addInitScript(() => { + (window as Window & { __PRISMTONE_E2E__?: boolean }).__PRISMTONE_E2E__ = true; + }); + await page.goto("/edit"); + const png = await makeNoisePng(page, 4096, 2304); + await page + .getByTestId("file-input") + .setInputFiles({ name: "4k.png", mimeType: "image/png", buffer: png }); + await page.waitForFunction(() => + Boolean((window as Window & { __prismtoneEditor?: unknown }).__prismtoneEditor), + ); + await expect(page.getByRole("button", { name: "端末に保存" })).toBeEnabled({ timeout: 60_000 }); + const gpu = await page.evaluate(() => { + const gl = document.createElement("canvas").getContext("webgl2"); + const dbg = gl?.getExtension("WEBGL_debug_renderer_info"); + return dbg && gl ? String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)) : "unknown"; + }); + console.log(`renderer: ${gpu}`); + for (const n of [0, 4, 8, 12]) { + const recipe: EditRecipe = { + ...DEFAULT_RECIPE, + localAdjustments: Array.from({ length: n }, (_, i) => local(i)), + }; + const r = await page.evaluate( + (recipe) => + ( + window as Window & { + __prismtoneEditor?: { benchmark: (r: EditRecipe, frames?: number) => Promise }; + } + ).__prismtoneEditor!.benchmark(recipe, 20), + recipe, + ); + console.log(`locals=${n} ${JSON.stringify(r)}`); + } +}); diff --git a/packages/editor-engine/bin/assets.test.ts b/packages/editor-engine/bin/assets.test.ts new file mode 100644 index 0000000..64dc185 --- /dev/null +++ b/packages/editor-engine/bin/assets.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; +import { modelPaths } from "../src/inference/model-paths.ts"; +import { MODEL_ASSETS, parseArgs } from "./assets.ts"; + +describe("MODEL_ASSETS", () => { + const targets = MODEL_ASSETS.map((a) => a.to); + // Worker が読むパス (model-paths.ts) からベースの "/" を外したもの + const paths = modelPaths("/"); + const dir = (p: string) => p.replace(/^\//, "").replace(/\/$/, ""); + + it("fills the face landmarker model and its WASM loaders", () => { + expect(targets).toContain(`${dir(paths.face)}/face_landmarker.task`); + expect(targets).toContain(`${dir(paths.face)}/wasm/vision_wasm_internal.js`); + expect(targets).toContain(`${dir(paths.face)}/wasm/vision_wasm_internal.wasm`); + }); + + it("fills the SlimSAM model under its model id", () => { + expect(targets).toContain(`${paths.samModelId}/config.json`); + expect(targets).toContain(`${paths.samModelId}/onnx/vision_encoder_quantized.onnx`); + }); + + it("fills the onnxruntime WASM", () => { + expect(targets).toContain(`${dir(paths.ortWasm)}/ort-wasm-simd-threaded.jsep.wasm`); + }); + + it("pins every download with a sha256", () => { + for (const a of MODEL_ASSETS) { + if (a.kind === "download") expect(a.sha256, a.to).toMatch(/^[0-9a-f]{64}$/); + } + }); +}); + +describe("parseArgs", () => { + it("reads the output directory of fetch", () => { + expect(parseArgs(["fetch", "--out", "models"])).toEqual({ command: "fetch", out: "models" }); + }); + + it("rejects a missing output directory", () => { + expect(() => parseArgs(["fetch"])).toThrow("--out"); + }); + + it("rejects an unknown command", () => { + expect(() => parseArgs(["pull", "--out", "models"])).toThrow("usage"); + }); +}); diff --git a/packages/editor-engine/bin/assets.ts b/packages/editor-engine/bin/assets.ts new file mode 100644 index 0000000..db37e57 --- /dev/null +++ b/packages/editor-engine/bin/assets.ts @@ -0,0 +1,94 @@ +/** + * ブラウザ内の認識 (ADR-0025) に使うモデルと WASM。ホストが同じオリジンで配る (既定は /models/)。 + * to は配る場所からの相対パスで、Worker が読むパス (src/inference/model-paths.ts) と合わせる。 + * + * - ダウンロードするものは URL と sha256 を固定する。ハッシュが合わなければ捨てて失敗する + * - 依存のパッケージからコピーするもの (WASM) は、その版を上げたら -v の n も上げる + * (静的アセットは immutable でキャッシュされるので、同じパスで中身を変えない) + */ +export type DownloadAsset = { kind: "download"; to: string; url: string; sha256: string }; +export type CopyAsset = { + kind: "copy"; + to: string; + /** editor-engine の依存のパッケージ名と、その中のパス */ + from: { pkg: string; path: string }; + prepend?: string; + append?: string; +}; +export type ModelAsset = DownloadAsset | CopyAsset; + +export const MODEL_ASSETS: readonly ModelAsset[] = [ + // MediaPipe Face Landmarker (瞳・顔、#176)。Apache-2.0 + { + kind: "download", + to: "face-landmarker-v1/face_landmarker.task", + url: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task", + sha256: "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff", + }, + ...[ + "vision_wasm_internal.js", + "vision_wasm_internal.wasm", + "vision_wasm_nosimd_internal.js", + "vision_wasm_nosimd_internal.wasm", + ].map((f): CopyAsset => ({ + kind: "copy", + to: `face-landmarker-v1/wasm/${f}`, + from: { pkg: "@mediapipe/tasks-vision", path: `wasm/${f}` }, + // ローダー (.js) は classic script (sloppy mode) 前提。module worker からは MediaPipe が import() で + // 読む (importScripts が使えない) ので、ES module (strict mode) でも動くように 2 か所を補う: + // - `var ModuleFactory` は module スコープに閉じるので、末尾で self に出す + // - if ブロック内の `function custom_dbg` は strict では外に見えないので、先頭で self に置く + // classic worker (importScripts) で読んでも害はない + ...(f.endsWith(".js") + ? { + prepend: + 'if (typeof self.custom_dbg === "undefined") self.custom_dbg = (...a) => console.warn(...a);\n', + append: "\n;self.ModuleFactory = ModuleFactory;\n", + } + : {}), + })), + // SlimSAM (装備・人物の切り抜き、#177)。Xenova/slimsam-77-uniform の q8。Apache-2.0 + ...( + [ + ["config.json", "6339884f168658d3ca6473b486973913fb33e84e625e06ae2dd7b4a808187419"], + [ + "preprocessor_config.json", + "225545a743c654e3c495ec6f545a0eaba57c8ba3fbbd8483b3cb1c0fc58db517", + ], + [ + "onnx/vision_encoder_quantized.onnx", + "cce23c7b2e5d4f330932738fb67ba518e04b0d99ccdd1cccd22a7da4e01f2971", + ], + [ + "onnx/prompt_encoder_mask_decoder_quantized.onnx", + "cb90b279f549d2cab7fd6e20c38522438c65d84bdcca3d2a764cff7d857fdce2", + ], + ] as const + ).map(([f, sha256]): DownloadAsset => ({ + kind: "download", + to: `slimsam-77-q8-v1/${f}`, + url: `https://huggingface.co/Xenova/slimsam-77-uniform/resolve/main/${f}`, + sha256, + })), + // onnxruntime-web の WASM (transformers.js が同梱する jsep 版)。MIT + ...["ort-wasm-simd-threaded.jsep.mjs", "ort-wasm-simd-threaded.jsep.wasm"].map( + (f): CopyAsset => ({ + kind: "copy", + to: `ort-v1/${f}`, + from: { pkg: "@huggingface/transformers", path: `dist/${f}` }, + }), + ), +]; + +export type Args = { command: "fetch"; out: string }; + +const USAGE = "usage: editor-models fetch --out "; + +export function parseArgs(argv: readonly string[]): Args { + const [command, ...rest] = argv; + if (command !== "fetch") throw new Error(USAGE); + const i = rest.indexOf("--out"); + const out = i >= 0 ? rest[i + 1] : undefined; + if (!out) throw new Error(`--out が要る。${USAGE}`); + return { command, out }; +} diff --git a/packages/editor-engine/bin/editor-models.ts b/packages/editor-engine/bin/editor-models.ts new file mode 100644 index 0000000..fd87b4a --- /dev/null +++ b/packages/editor-engine/bin/editor-models.ts @@ -0,0 +1,90 @@ +#!/usr/bin/env node +/** + * editor-models fetch --out + * 認識のモデルと WASM (assets.ts) を に揃える。ホストは を同じオリジンで配る (既定の URL は /models/)。 + * 既にあってハッシュが合えば何もしない (2 回目以降は一瞬で終わる)。 には .gitignore を置く + */ +import { createHash } from "node:crypto"; +import { access, mkdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { MODEL_ASSETS, parseArgs, type CopyAsset, type DownloadAsset } from "./assets.ts"; + +async function sha256(file: string): Promise { + try { + return createHash("sha256") + .update(await readFile(file)) + .digest("hex"); + } catch { + return null; + } +} + +/** 依存のパッケージのディレクトリ。exports に package.json が無いものもあるので、入口から上へたどる */ +async function packageDir(pkg: string): Promise { + let dir = path.dirname(fileURLToPath(import.meta.resolve(pkg))); + for (;;) { + try { + const json = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8")) as { + name?: string; + }; + if (json.name === pkg) return dir; + } catch { + // package.json の無い階層 + } + const parent = path.dirname(dir); + if (parent === dir) throw new Error(`models: ${pkg} が見つからない (pnpm install を先に)`); + dir = parent; + } +} + +async function download(out: string, asset: DownloadAsset): Promise { + const target = path.join(out, asset.to); + if ((await sha256(target)) === asset.sha256) return; + console.log(`models: downloading ${asset.to}`); + const res = await fetch(asset.url); + if (!res.ok) throw new Error(`models: ${asset.url} -> ${res.status}`); + const body = Buffer.from(await res.arrayBuffer()); + const got = createHash("sha256").update(body).digest("hex"); + if (got !== asset.sha256) { + throw new Error( + `models: sha256 mismatch for ${asset.to}: expected ${asset.sha256}, got ${got}`, + ); + } + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, body); +} + +async function copy(out: string, asset: CopyAsset): Promise { + const target = path.join(out, asset.to); + const from = path.join(await packageDir(asset.from.pkg), asset.from.path); + let body: Buffer; + try { + body = await readFile(from); + } catch { + throw new Error(`models: missing ${from} (pnpm install を先に)`); + } + if (asset.prepend) body = Buffer.concat([Buffer.from(asset.prepend), body]); + if (asset.append) body = Buffer.concat([body, Buffer.from(asset.append)]); + const want = createHash("sha256").update(body).digest("hex"); + if ((await sha256(target)) === want) return; + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, body); +} + +const { out: outArg } = parseArgs(process.argv.slice(2)); +const out = path.resolve(outArg); +await mkdir(out, { recursive: true }); +for (const asset of MODEL_ASSETS) { + if (asset.kind === "download") await download(out, asset); + else await copy(out, asset); +} +// git に入れないことを、ディレクトリ自身にも書いておく +try { + await access(path.join(out, ".gitignore")); +} catch { + await writeFile(path.join(out, ".gitignore"), "*\n"); +} +console.log( + `models: ${MODEL_ASSETS.length} files ready in ${path.relative(process.cwd(), out) || "."}`, +); diff --git a/packages/editor-engine/package.json b/packages/editor-engine/package.json new file mode 100644 index 0000000..a0fc108 --- /dev/null +++ b/packages/editor-engine/package.json @@ -0,0 +1,53 @@ +{ + "name": "@lumorphia/editor-engine", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./render": { + "source": "./src/render/editor-renderer.ts", + "types": "./dist/render/editor-renderer.d.ts", + "default": "./dist/render/editor-renderer.js" + }, + "./inference/face": { + "source": "./src/inference/face.ts", + "types": "./dist/inference/face.d.ts", + "default": "./dist/inference/face.js" + }, + "./inference/segment": { + "source": "./src/inference/segment.ts", + "types": "./dist/inference/segment.d.ts", + "default": "./dist/inference/segment.js" + }, + "./reference": { + "source": "./src/adjust-math.ts", + "types": "./dist/adjust-math.d.ts", + "default": "./dist/adjust-math.js" + } + }, + "scripts": { + "build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/finish-dist.ts && tsc -p tsconfig.bin.json", + "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.node.json", + "test": "vitest run" + }, + "dependencies": { + "@huggingface/transformers": "^3.8.1", + "@lumorphia/editor-recipe": "workspace:*", + "@mediapipe/tasks-vision": "^1.0.1", + "idb-keyval": "^6.3.0", + "pixi.js": "^8.22.0" + }, + "bin": { + "editor-models": "./dist/bin/editor-models.js" + }, + "files": [ + "dist", + "src", + "!src/**/*.test.ts" + ] +} diff --git a/packages/editor-engine/scripts/finish-dist.ts b/packages/editor-engine/scripts/finish-dist.ts new file mode 100644 index 0000000..f13d5c3 --- /dev/null +++ b/packages/editor-engine/scripts/finish-dist.ts @@ -0,0 +1,17 @@ +/** tsc のあとに dist を仕上げる。Worker を起こすファイルの URL を .js にする (worker-urls.ts) */ +import { readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { rewriteWorkerUrls } from "./worker-urls.ts"; + +const dist = path.resolve(import.meta.dirname, "../dist"); +/** Worker を起こすファイル。ここで 1 つも書き換わらなければ、ソースの書き方が変わったので止める */ +const SPAWNERS = ["inference/face.js", "inference/segment.js"]; + +for (const file of SPAWNERS) { + const target = path.join(dist, file); + const { code, count } = rewriteWorkerUrls(await readFile(target, "utf8")); + if (count !== 1) + throw new Error(`finish-dist: ${file} で Worker の URL が ${count} 件 (1 件のはず)`); + await writeFile(target, code); +} +console.log(`finish-dist: ${SPAWNERS.length} files`); diff --git a/packages/editor-engine/scripts/worker-urls.test.ts b/packages/editor-engine/scripts/worker-urls.test.ts new file mode 100644 index 0000000..cd19971 --- /dev/null +++ b/packages/editor-engine/scripts/worker-urls.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { rewriteWorkerUrls } from "./worker-urls.ts"; + +describe("rewriteWorkerUrls", () => { + it("points a module worker at the built .js file", () => { + const src = 'new Worker(new URL("./face.worker.ts", import.meta.url), { type: "module" });'; + expect(rewriteWorkerUrls(src)).toEqual({ + code: 'new Worker(new URL("./face.worker.js", import.meta.url), { type: "module" });', + count: 1, + }); + }); + + it("leaves other URLs alone", () => { + const src = 'new URL("./face.task", import.meta.url); import("./x.ts");'; + expect(rewriteWorkerUrls(src)).toEqual({ code: src, count: 0 }); + }); +}); diff --git a/packages/editor-engine/scripts/worker-urls.ts b/packages/editor-engine/scripts/worker-urls.ts new file mode 100644 index 0000000..eda6b7d --- /dev/null +++ b/packages/editor-engine/scripts/worker-urls.ts @@ -0,0 +1,14 @@ +/** + * tsc は import の .ts を .js に書き換えるが、new URL("./x.worker.ts", import.meta.url) の文字列は書き換えない。 + * dist では Worker を .js で指す。ホスト (prismtone などの Vite) がこの new Worker(new URL(...)) を見て Worker を束ねる + */ +const WORKER_URL = /new URL\("(\.\/[\w.-]+\.worker)\.ts", import\.meta\.url\)/g; + +export function rewriteWorkerUrls(code: string): { code: string; count: number } { + let count = 0; + const out = code.replace(WORKER_URL, (_match, base: string) => { + count += 1; + return `new URL("${base}.js", import.meta.url)`; + }); + return { code: out, count }; +} diff --git a/packages/editor-engine/src/adjust-math.test.ts b/packages/editor-engine/src/adjust-math.test.ts new file mode 100644 index 0000000..09f03d7 --- /dev/null +++ b/packages/editor-engine/src/adjust-math.test.ts @@ -0,0 +1,228 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_ADJUST, + DEFAULT_BRUSH_MASK, + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, +} from "@lumorphia/editor-recipe"; +import { + applyAdjust, + applyLocalAdjust, + applyRecipeAt, + linearToSrgb, + srgbToLinear, + type RGB, +} from "./adjust-math.ts"; + +const near = (a: number, b: number, eps = 1e-3) => Math.abs(a - b) < eps; + +describe("applyAdjust", () => { + it("is identity with default adjust", () => { + for (const px of [ + [0.2, 0.5, 0.8], + [0, 0, 0], + [1, 1, 1], + [0.5, 0.5, 0.5], + ] as RGB[]) { + const out = applyAdjust(px, DEFAULT_ADJUST); + out.forEach((v, i) => expect(near(v, px[i]!)).toBe(true)); + } + }); + + it("exposure +1 EV doubles linear light on mid tones", () => { + const px: RGB = [0.3, 0.3, 0.3]; + const out = applyAdjust(px, { ...DEFAULT_ADJUST, exposure: 1 }); + expect(near(srgbToLinear(out[0]), srgbToLinear(px[0]) * 2, 1e-3)).toBe(true); + }); + + it("saturation -100 produces neutral gray", () => { + const out = applyAdjust([0.9, 0.2, 0.4], { ...DEFAULT_ADJUST, saturation: -100 }); + expect(near(out[0], out[1])).toBe(true); + expect(near(out[1], out[2])).toBe(true); + }); + + it("warm temperature raises red and lowers blue", () => { + const px: RGB = [0.5, 0.5, 0.5]; + const out = applyAdjust(px, { ...DEFAULT_ADJUST, temperature: 100 }); + expect(out[0]).toBeGreaterThan(px[0]); + expect(out[2]).toBeLessThan(px[2]); + expect(near(out[1], px[1])).toBe(true); + }); + + it("positive contrast pushes values away from mid gray", () => { + const dark = applyAdjust([0.3, 0.3, 0.3], { ...DEFAULT_ADJUST, contrast: 100 }); + const light = applyAdjust([0.7, 0.7, 0.7], { ...DEFAULT_ADJUST, contrast: 100 }); + expect(dark[0]).toBeLessThan(0.3); + expect(light[0]).toBeGreaterThan(0.7); + }); + + it("shadows lift dark pixels more than bright ones", () => { + const dark = applyAdjust([0.1, 0.1, 0.1], { ...DEFAULT_ADJUST, shadows: 100 }); + const bright = applyAdjust([0.9, 0.9, 0.9], { ...DEFAULT_ADJUST, shadows: 100 }); + expect(dark[0] - 0.1).toBeGreaterThan(bright[0] - 0.9); + }); + + it("vibrance affects low-saturation pixels more than saturated ones", () => { + const pale: RGB = [0.55, 0.5, 0.5]; + const vivid: RGB = [1, 0, 0]; + const paleOut = applyAdjust(pale, { ...DEFAULT_ADJUST, vibrance: 100 }); + const vividOut = applyAdjust(vivid, { ...DEFAULT_ADJUST, vibrance: 100 }); + expect(paleOut[0] - paleOut[1]).toBeGreaterThan(pale[0] - pale[1]); + expect(near(vividOut[0], 1)).toBe(true); + }); + + it("always returns values within 0..1", () => { + const out = applyAdjust([1, 1, 1], { + ...DEFAULT_ADJUST, + exposure: 5, + contrast: 100, + saturation: 100, + }); + out.forEach((v) => { + expect(v).toBeGreaterThanOrEqual(0); + expect(v).toBeLessThanOrEqual(1); + }); + }); +}); + +describe("srgb conversions", () => { + it("round-trips", () => { + for (const v of [0, 0.01, 0.2, 0.5, 0.9, 1]) { + expect(near(linearToSrgb(srgbToLinear(v)), v, 1e-6)).toBe(true); + } + }); +}); + +describe("applyRecipeAt (部分補正の CPU 参照、#109)", () => { + const eye = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "eye", + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.25, cy: 0.5, rx: 0.1, ry: 0.2, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, exposure: 1 }, + }; + const size = { width: 200, height: 100 }; + const px: RGB = [0.3, 0.3, 0.3]; + + it("applies the local adjustment fully inside the mask and not at all outside", () => { + const recipe = { ...DEFAULT_RECIPE, localAdjustments: [eye] }; + const inside = applyRecipeAt(px, { x: 0.25, y: 0.5 }, recipe, size); + const outside = applyRecipeAt(px, { x: 0.75, y: 0.5 }, recipe, size); + expect(inside).toEqual(applyLocalAdjust(px, eye.adjust)); + expect(outside).toEqual(px); + }); + + it("blends by amount and skips hidden adjustments", () => { + const half = { ...DEFAULT_RECIPE, localAdjustments: [{ ...eye, amount: 50 }] }; + const out = applyRecipeAt(px, { x: 0.25, y: 0.5 }, half, size); + const full = applyLocalAdjust(px, eye.adjust); + expect(near(out[0], (px[0] + full[0]) / 2)).toBe(true); + const hidden = { ...DEFAULT_RECIPE, localAdjustments: [{ ...eye, visible: false }] }; + expect(applyRecipeAt(px, { x: 0.25, y: 0.5 }, hidden, size)).toEqual(px); + }); + + it("applies the global adjust first, then local adjustments in order", () => { + const recipe = { + ...DEFAULT_RECIPE, + adjust: { ...DEFAULT_ADJUST, saturation: -100 }, + localAdjustments: [eye], + }; + const out = applyRecipeAt([0.9, 0.2, 0.4], { x: 0.25, y: 0.5 }, recipe, size); + const expected = applyLocalAdjust(applyAdjust([0.9, 0.2, 0.4], recipe.adjust), eye.adjust); + expect(out).toEqual(expected); + }); + + it("applyLocalAdjust matches applyAdjust with the same values and no vibrance", () => { + const local = { ...DEFAULT_LOCAL_ADJUST, exposure: 0.5, contrast: 20, temperature: -30 }; + expect(applyLocalAdjust(px, local)).toEqual( + applyAdjust(px, { ...DEFAULT_ADJUST, exposure: 0.5, contrast: 20, temperature: -30 }), + ); + }); + + it("evaluates a brush mask through the stroke geometry", () => { + const brush = { + ...eye, + id: "gear", + mask: { + ...DEFAULT_BRUSH_MASK, + strokes: [{ mode: "add" as const, size: 0.2, hardness: 1, points: [{ x: 0.75, y: 0.5 }] }], + }, + }; + const recipe = { ...DEFAULT_RECIPE, localAdjustments: [brush] }; + expect(applyRecipeAt(px, { x: 0.75, y: 0.5 }, recipe, size)).toEqual( + applyLocalAdjust(px, eye.adjust), + ); + expect(applyRecipeAt(px, { x: 0.25, y: 0.5 }, recipe, size)).toEqual(px); + }); + + it("blurs with a radius measured in source pixels", () => { + const recipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, blur: 10 }, + }, + ], + }; + const source = ({ x }: { x: number; y: number }): RGB => (x < 0.5 ? [1, 1, 1] : [0, 0, 0]); + const out = applyRecipeAt(source, { x: 0.5, y: 0.5 }, recipe, size); + expect(out[0]).toBeGreaterThan(0); + expect(out[0]).toBeLessThan(1); + }); + + it("adds bloom from bright neighbouring pixels", () => { + const recipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, bloom: 100 }, + }, + ], + }; + const source = ({ x }: { x: number; y: number }): RGB => + x < 0.5 ? [1, 1, 1] : [0.1, 0.1, 0.1]; + const out = applyRecipeAt(source, { x: 0.51, y: 0.5 }, recipe, size); + expect(out[0]).toBeGreaterThan(0.1); + }); + + it("darkens image corners with vignette while preserving the centre", () => { + const recipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, vignette: 100 }, + }, + ], + }; + const centre = applyRecipeAt([0.7, 0.7, 0.7], { x: 0.5, y: 0.5 }, recipe, size); + const corner = applyRecipeAt([0.7, 0.7, 0.7], { x: 0, y: 0 }, recipe, size); + expect(centre[0]).toBeCloseTo(0.7); + expect(corner[0]).toBeLessThan(centre[0]); + }); + + it("increases or decreases local contrast with clarity", () => { + const source = ({ x }: { x: number; y: number }): RGB => + x < 0.5 ? [0.8, 0.8, 0.8] : [0.4, 0.4, 0.4]; + const withClarity = (clarity: number) => ({ + ...DEFAULT_RECIPE, + localAdjustments: [ + { + ...eye, + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 1, ry: 1, feather: 0 }, + adjust: { ...DEFAULT_LOCAL_ADJUST, clarity }, + }, + ], + }); + const sharp = applyRecipeAt(source, { x: 0.49, y: 0.5 }, withClarity(100), size); + const soft = applyRecipeAt(source, { x: 0.49, y: 0.5 }, withClarity(-100), size); + expect(sharp[0]).toBeGreaterThan(0.8); + expect(soft[0]).toBeLessThan(0.8); + }); +}); diff --git a/packages/editor-engine/src/adjust-math.ts b/packages/editor-engine/src/adjust-math.ts new file mode 100644 index 0000000..d4b9d4b --- /dev/null +++ b/packages/editor-engine/src/adjust-math.ts @@ -0,0 +1,196 @@ +import type { AdjustV1, EditRecipe, LocalAdjust } from "@lumorphia/editor-recipe"; +import type { Point } from "./mask-math.ts"; +import { maskValue } from "./brush-raster.ts"; +import type { Size } from "./render/geometry.ts"; + +/** + * 補正パイプラインの CPU 参照実装。 + * GLSL (render/adjust-filter.ts) はこの関数と同じ式を実装する。 + * 単体テストと、Playwright での GPU 出力との照合に使う (docs/design/04 §4)。 + */ + +export type RGB = readonly [number, number, number]; +export type ImageSampler = (uv: Point) => RGB; + +const BLOOM_RADIUS_PX = 8; +const CLARITY_RADIUS_PX = 4; +const BLOOM_THRESHOLD = 0.65; + +export function srgbToLinear(c: number): number { + return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); +} + +export function linearToSrgb(c: number): number { + return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055; +} + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); +const smoothstep = (e0: number, e1: number, x: number) => { + const t = clamp01((x - e0) / (e1 - e0)); + return t * t * (3 - 2 * t); +}; +const mix = (a: number, b: number, t: number) => a + (b - a) * t; + +/** レシピの値域 (-100..100 / EV) をシェーダ用の正規化値に変換する。 */ +export function normalizeAdjust(a: AdjustV1) { + return { + exposure: a.exposure, + contrast: a.contrast / 100, + highlights: a.highlights / 100, + shadows: a.shadows / 100, + temperature: a.temperature / 100, + tint: a.tint / 100, + vibrance: a.vibrance / 100, + saturation: a.saturation / 100, + }; +} + +export type NormalizedAdjust = ReturnType; + +export function applyAdjust(input: RGB, adjust: AdjustV1): RGB { + const u = normalizeAdjust(adjust); + + // --- linear 空間 --- + let r = srgbToLinear(input[0]); + let g = srgbToLinear(input[1]); + let b = srgbToLinear(input[2]); + + const gain = Math.pow(2, u.exposure); + r *= gain; + g *= gain; + b *= gain; + + r *= 1 + 0.25 * u.temperature; + b *= 1 - 0.25 * u.temperature; + g *= 1 - 0.25 * u.tint; + + const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; + const wh = smoothstep(0.3, 1.0, luma); + const ws = 1 - smoothstep(0.0, 0.5, luma); + const hs = (1 + u.highlights * 0.5 * wh) * (1 + u.shadows * 0.5 * ws); + r *= hs; + g *= hs; + b *= hs; + + // --- sRGB 空間 --- + r = linearToSrgb(clamp01(r)); + g = linearToSrgb(clamp01(g)); + b = linearToSrgb(clamp01(b)); + + const cf = 1 + u.contrast * 0.8; + r = (r - 0.5) * cf + 0.5; + g = (g - 0.5) * cf + 0.5; + b = (b - 0.5) * cf + 0.5; + + const y = 0.299 * r + 0.587 * g + 0.114 * b; + const sat = Math.max(r, g, b) - Math.min(r, g, b); + const vf = 1 + u.vibrance * (1 - clamp01(sat)); + r = mix(y, r, vf); + g = mix(y, g, vf); + b = mix(y, b, vf); + + const sf = 1 + u.saturation; + r = mix(y, r, sf); + g = mix(y, g, sf); + b = mix(y, b, sf); + + return [clamp01(r), clamp01(g), clamp01(b)]; +} + +/** + * 部分補正の色調整。全体の補正と同じ式で vibrance だけ無い (#109)。 + * sharpen / smooth は既存テストとの互換のため点ごとの参照には含めない。#184 の空間効果は + * context があるとき 3x3 の近傍を参照し、GLSL と同じ式で計算する。 + */ +export function applyLocalAdjust( + input: RGB, + adjust: LocalAdjust, + context?: { uv: Point; sampleOffset: (dx: number, dy: number) => RGB }, +): RGB { + const { sharpen: _sharpen, smooth: _smooth, blur, bloom, vignette, clarity, ...rest } = adjust; + let spatial: RGB = input; + const radius = Math.max( + blur, + bloom > 0 ? BLOOM_RADIUS_PX : 0, + clarity !== 0 ? CLARITY_RADIUS_PX : 0, + ); + let average: RGB = input; + let glow: RGB = [0, 0, 0]; + if (context && radius > 0) { + const sum = [0, 0, 0]; + const bright = [0, 0, 0]; + for (const y of [-1, 0, 1]) { + for (const x of [-1, 0, 1]) { + const sampled = context.sampleOffset(x * radius, y * radius); + for (let channel = 0; channel < 3; channel += 1) { + const value = sampled[channel]!; + sum[channel] = sum[channel]! + value; + bright[channel] = + bright[channel]! + Math.max(0, value - BLOOM_THRESHOLD) / (1 - BLOOM_THRESHOLD); + } + } + } + average = [sum[0]! / 9, sum[1]! / 9, sum[2]! / 9]; + glow = [bright[0]! / 9, bright[1]! / 9, bright[2]! / 9]; + } + if (blur > 0 && context) spatial = average; + if (clarity !== 0 && context) { + const strength = clarity / 100; + spatial = spatial.map((value, channel) => + clamp01(value + (input[channel]! - average[channel]!) * strength), + ) as unknown as RGB; + } + if (bloom > 0 && context) { + const strength = (bloom / 100) * 0.5; + spatial = spatial.map((value, channel) => + clamp01(value + glow[channel]! * strength), + ) as unknown as RGB; + } + let adjusted = applyAdjust(spatial, { ...rest, vibrance: 0 }); + if (vignette > 0 && context) { + const px = (context.uv.x - 0.5) * 2; + const py = (context.uv.y - 0.5) * 2; + const distance = (px * px + py * py) / 2; + const shade = 1 - (vignette / 100) * 0.65 * smoothstep(0.2, 1, distance); + adjusted = adjusted.map((value) => clamp01(value * shade)) as unknown as RGB; + } + return adjusted; +} + +/** + * レシピ全体を 1 画素に適用する参照実装: 全体の補正 → 部分補正を順に。 + * uv は幾何を掛ける前の画像の正規化座標 + */ +export function applyRecipeAt( + input: RGB | ImageSampler, + uv: Point, + recipe: EditRecipe, + size: Size, +): RGB { + const source: ImageSampler = typeof input === "function" ? input : () => input; + let stage: ImageSampler = (point) => applyAdjust(source(point), recipe.adjust); + for (const local of recipe.localAdjustments) { + if (!local.visible) continue; + const previous = stage; + stage = (point) => { + const rgb = previous(point); + const mask = maskValue(point, local.mask, size); + const m = mask * (local.amount / 100); + if (m <= 0) return rgb; + const adjusted = applyLocalAdjust(rgb, local.adjust, { + uv: point, + sampleOffset: (dx, dy) => + previous({ + x: clamp01(point.x + dx / size.width), + y: clamp01(point.y + dy / size.height), + }), + }); + return [ + mix(rgb[0], adjusted[0], m), + mix(rgb[1], adjusted[1], m), + mix(rgb[2], adjusted[2], m), + ]; + }; + } + return stage(uv); +} diff --git a/packages/editor-engine/src/brush-raster.test.ts b/packages/editor-engine/src/brush-raster.test.ts new file mode 100644 index 0000000..31d3c90 --- /dev/null +++ b/packages/editor-engine/src/brush-raster.test.ts @@ -0,0 +1,266 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_BRUSH_MASK, + encodeRle, + type BitmapMaskV3, + type BrushStrokeV2, + type PolygonMaskV3, +} from "@lumorphia/editor-recipe"; +import { + bitmapMaskValue, + brushMaskValue, + createMaskRaster, + polygonMaskValue, + rasterSize, + rasterizeBrushMask, + rasterizeMask, + simplifyPoints, + stampStroke, +} from "./brush-raster.ts"; + +const source = { width: 200, height: 100 }; +const dot = (x: number, y: number, extra: Partial = {}): BrushStrokeV2 => ({ + mode: "add", + size: 0.2, // 長辺 200 の 20% = 直径 40px、半径 20px + hardness: 1, + points: [{ x, y }], + ...extra, +}); +const at = (r: ReturnType, x: number, y: number) => + r.data[y * r.width + x]!; + +describe("rasterSize", () => { + it("keeps the aspect ratio and caps the long edge", () => { + expect(rasterSize({ width: 4096, height: 2048 }, 1024)).toEqual({ width: 1024, height: 512 }); + expect(rasterSize(source, 1024)).toEqual({ width: 200, height: 100 }); + }); +}); + +describe("stampStroke / rasterizeBrushMask", () => { + it("a hard dot fills its radius and nothing outside", () => { + const r = rasterizeBrushMask({ ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)] }, source); + expect(at(r, 100, 50)).toBe(255); + expect(at(r, 115, 50)).toBe(255); + expect(at(r, 125, 50)).toBe(0); + expect(at(r, 100, 25)).toBe(0); + }); + + it("a soft dot falls off towards the edge", () => { + const r = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5, { hardness: 0 })] }, + source, + ); + // 画素の中心は円の中心から 0.7px ずれるので、硬さ 0 では 255 に僅かに届かない + expect(at(r, 100, 50)).toBeGreaterThanOrEqual(250); + const mid = at(r, 110, 50); + expect(mid).toBeGreaterThan(0); + expect(mid).toBeLessThan(255); + expect(at(r, 121, 50)).toBe(0); + }); + + it("a stroke between two points has no gap", () => { + const stroke = dot(0.25, 0.5, { + points: [ + { x: 0.25, y: 0.5 }, + { x: 0.75, y: 0.5 }, + ], + }); + const r = rasterizeBrushMask({ ...DEFAULT_BRUSH_MASK, strokes: [stroke] }, source); + for (let x = 50; x <= 150; x += 5) expect(at(r, x, 50)).toBe(255); + }); + + it("erase removes what a previous stroke added, in order", () => { + const strokes = [dot(0.5, 0.5), dot(0.5, 0.5, { mode: "erase", size: 0.1 })]; + const r = rasterizeBrushMask({ ...DEFAULT_BRUSH_MASK, strokes }, source); + expect(at(r, 100, 50)).toBe(0); + expect(at(r, 115, 50)).toBe(255); + // 順序が逆なら消すものが無い + const reversed = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [...strokes].reverse() }, + source, + ); + expect(at(reversed, 100, 50)).toBe(255); + }); + + it("invert flips the raster and feather softens the edge", () => { + const inv = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)], invert: true }, + source, + ); + expect(at(inv, 100, 50)).toBe(0); + expect(at(inv, 10, 10)).toBe(255); + const soft = rasterizeBrushMask( + { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)], feather: 1 }, + source, + ); + expect(at(soft, 115, 50)).toBeLessThan(255); + }); + + it("stampStroke draws into an existing raster (incremental preview)", () => { + const r = createMaskRaster(source); + stampStroke(r, dot(0.25, 0.5), 0); + stampStroke(r, dot(0.75, 0.5), 0); + expect(at(r, 50, 50)).toBe(255); + expect(at(r, 150, 50)).toBe(255); + expect(at(r, 100, 50)).toBe(0); + }); +}); + +describe("brushMaskValue (CPU 参照)", () => { + it("agrees with the raster inside, outside and after an erase", () => { + const mask = { + ...DEFAULT_BRUSH_MASK, + strokes: [dot(0.5, 0.5), dot(0.5, 0.5, { mode: "erase", size: 0.1 })], + }; + expect(brushMaskValue({ x: 0.5, y: 0.5 }, mask, source)).toBe(0); + expect(brushMaskValue({ x: 0.575, y: 0.5 }, mask, source)).toBe(1); + expect(brushMaskValue({ x: 0.9, y: 0.5 }, mask, source)).toBe(0); + expect(brushMaskValue({ x: 0.9, y: 0.5 }, { ...mask, invert: true }, source)).toBe(1); + }); + + it("measures distance to the segment, not only to the points", () => { + const stroke = dot(0.25, 0.5, { + points: [ + { x: 0.25, y: 0.5 }, + { x: 0.75, y: 0.5 }, + ], + }); + const mask = { ...DEFAULT_BRUSH_MASK, strokes: [stroke] }; + expect(brushMaskValue({ x: 0.5, y: 0.5 }, mask, source)).toBe(1); + expect(brushMaskValue({ x: 0.5, y: 0.5 + 0.25 }, mask, source)).toBe(0); + }); +}); + +describe("simplifyPoints", () => { + it("drops points closer than the minimum distance but keeps the first and last", () => { + const pts = [ + { x: 0.1, y: 0.1 }, + { x: 0.101, y: 0.1 }, + { x: 0.2, y: 0.1 }, + { x: 0.2005, y: 0.1 }, + ]; + expect(simplifyPoints(pts, 0.005)).toEqual([ + { x: 0.1, y: 0.1 }, + { x: 0.2, y: 0.1 }, + { x: 0.2005, y: 0.1 }, + ]); + }); + + it("caps the number of points", () => { + const pts = Array.from({ length: 2000 }, (_, i) => ({ x: i / 2000, y: 0.5 })); + expect(simplifyPoints(pts, 0, 512)).toHaveLength(512); + }); +}); + +describe("rasterizePolygon (v3 多角形マスク)", () => { + // 幅 200 × 高さ 100 の画像に、左半分を覆う長方形 (x 0..0.5) を置く + const rect = [ + { x: 0, y: 0 }, + { x: 0.5, y: 0 }, + { x: 0.5, y: 1 }, + { x: 0, y: 1 }, + ]; + const polygon = (rings: { x: number; y: number }[][], extra = {}): PolygonMaskV3 => ({ + kind: "polygon", + rings, + strokes: [], + feather: 0, + invert: false, + ...extra, + }); + + it("fills the inside of the outer ring and leaves the outside empty", () => { + const r = rasterizeMask(polygon([rect]), source); + expect(at(r, 50, 50)).toBe(255); + expect(at(r, 150, 50)).toBe(0); + }); + + it("subtracts holes (偶奇塗り) so a face polygon can cut out the eyes", () => { + const hole = [ + { x: 0.1, y: 0.4 }, + { x: 0.3, y: 0.4 }, + { x: 0.3, y: 0.6 }, + { x: 0.1, y: 0.6 }, + ]; + const r = rasterizeMask(polygon([rect, hole]), source); + expect(at(r, 40, 50)).toBe(0); + expect(at(r, 40, 20)).toBe(255); + expect(at(r, 80, 50)).toBe(255); + }); + + it("applies brush strokes on top of the polygon (erase then add)", () => { + const erase: BrushStrokeV2 = { ...dot(0.25, 0.5), mode: "erase" }; + const add = dot(0.75, 0.5); + const r = rasterizeMask(polygon([rect], { strokes: [erase, add] }), source); + expect(at(r, 50, 50)).toBe(0); + expect(at(r, 150, 50)).toBe(255); + }); + + it("feathers the edge and invert flips the result", () => { + const soft = rasterizeMask(polygon([rect], { feather: 0.5 }), source); + const edge = at(soft, 99, 50); + expect(edge).toBeGreaterThan(0); + expect(edge).toBeLessThan(255); + const inv = rasterizeMask(polygon([rect], { invert: true }), source); + expect(at(inv, 50, 50)).toBe(0); + expect(at(inv, 150, 50)).toBe(255); + }); + + it("polygonMaskValue agrees with the raster inside and outside", () => { + const m = polygon([rect]); + expect(polygonMaskValue({ x: 0.25, y: 0.5 }, m)).toBe(1); + expect(polygonMaskValue({ x: 0.75, y: 0.5 }, m)).toBe(0); + }); +}); + +describe("rasterizeBitmap (v3 ビットマップマスク)", () => { + // 4×2 のビットマップ: 上の行は右半分、下の行は左半分が 1 + const bits = Uint8Array.from([0, 0, 1, 1, 1, 1, 0, 0]); + const bitmap = (extra = {}): BitmapMaskV3 => ({ + kind: "bitmap", + width: 4, + height: 2, + rle: encodeRle(bits), + strokes: [], + feather: 0, + invert: false, + ...extra, + }); + + it("scales the bitmap up to the raster with nearest neighbour", () => { + const r = rasterizeMask(bitmap(), source); + expect(at(r, 150, 25)).toBe(255); + expect(at(r, 50, 25)).toBe(0); + expect(at(r, 50, 75)).toBe(255); + expect(at(r, 150, 75)).toBe(0); + }); + + it("feather blurs the boundary between cells", () => { + const r = rasterizeMask(bitmap({ feather: 0.3 }), source); + const edge = at(r, 100, 25); + expect(edge).toBeGreaterThan(0); + expect(edge).toBeLessThan(255); + expect(at(r, 190, 10)).toBe(255); + }); + + it("brush strokes edit the bitmap and invert flips it", () => { + const r = rasterizeMask(bitmap({ strokes: [dot(0.25, 0.25)] }), source); + expect(at(r, 50, 25)).toBe(255); + const inv = rasterizeMask(bitmap({ invert: true }), source); + expect(at(inv, 150, 25)).toBe(0); + expect(at(inv, 50, 25)).toBe(255); + }); + + it("bitmapMaskValue samples the cell under the point", () => { + const m = bitmap(); + expect(bitmapMaskValue({ x: 0.75, y: 0.25 }, m)).toBe(1); + expect(bitmapMaskValue({ x: 0.25, y: 0.25 }, m)).toBe(0); + }); +}); + +describe("rasterizeMask (brush は今までどおり)", () => { + it("delegates a brush mask to rasterizeBrushMask", () => { + const mask = { ...DEFAULT_BRUSH_MASK, strokes: [dot(0.5, 0.5)] }; + expect(rasterizeMask(mask, source)).toEqual(rasterizeBrushMask(mask, source)); + }); +}); diff --git a/packages/editor-engine/src/brush-raster.ts b/packages/editor-engine/src/brush-raster.ts new file mode 100644 index 0000000..f05bb18 --- /dev/null +++ b/packages/editor-engine/src/brush-raster.ts @@ -0,0 +1,310 @@ +import { + MAX_BRUSH_POINTS, + decodeRle, + type BitmapMaskV3, + type BrushMaskV2, + type BrushStrokeV2, + type Mask, + type PolygonMaskV3, + type StrokedMask, +} from "@lumorphia/editor-recipe"; +import { ellipseMaskValue, type Point } from "./mask-math.ts"; +import type { Size } from "./render/geometry.ts"; + +/** + * ブラシマスクのラスタライズ (#109)。DOM に依存しない純関数で、単体テストと GPU 出力の照合に使う。 + * ストロークは幾何を掛ける前の画像の正規化座標。半径は画像の長辺に対する比 (size / 2)。 + * 描画は「点の周りに円のスタンプを、線分に沿って半径の 1/4 間隔で押す」。add は max、erase は min。 + */ + +export type MaskRaster = { width: number; height: number; data: Uint8ClampedArray }; + +/** マスクテクスチャの長辺。画像より粗くても、GPU で線形補間されるので境界は滑らか */ +export const MASK_RASTER_MAX_EDGE = 1024; + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); +const smoothstep = (e0: number, e1: number, x: number) => { + const t = clamp01((x - e0) / (e1 - e0)); + return t * t * (3 - 2 * t); +}; + +/** 画像の縦横比を保って長辺を maxEdge に収めた整数の寸法 */ +export function rasterSize(source: Size, maxEdge = MASK_RASTER_MAX_EDGE): Size { + const edge = Math.max(source.width, source.height); + const s = edge > maxEdge ? maxEdge / edge : 1; + return { + width: Math.max(1, Math.round(source.width * s)), + height: Math.max(1, Math.round(source.height * s)), + }; +} + +export function createMaskRaster(source: Size, maxEdge = MASK_RASTER_MAX_EDGE): MaskRaster { + const { width, height } = rasterSize(source, maxEdge); + return { width, height, data: new Uint8ClampedArray(width * height) }; +} + +/** + * スタンプ 1 つの値 (0..1)。中心から hardness × 半径までは 1、そこから縁でなだらかに 0。 + * feather (0..1) は硬さを下げる方向に効く (輪郭をぼかすため) + */ +function falloff(distance: number, radius: number, hardness: number, feather: number): number { + if (distance >= radius) return 0; + const core = clamp01(hardness * (1 - feather)); + if (core >= 1) return 1; + return 1 - smoothstep(core * radius, radius, distance); +} + +/** 線分 ab 上で p に最も近い点までの距離 */ +function distanceToSegment(p: Point, a: Point, b: Point): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len2 = dx * dx + dy * dy; + const t = len2 === 0 ? 0 : clamp01(((p.x - a.x) * dx + (p.y - a.y) * dy) / len2); + return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy)); +} + +/** ストローク 1 本をラスタに描く (その場で書き換える)。プレビューでは 1 本ずつ足す */ +export function stampStroke(raster: MaskRaster, stroke: BrushStrokeV2, feather: number): void { + const { width, height, data } = raster; + const edge = Math.max(width, height); + const radius = (stroke.size * edge) / 2; + const toPx = (p: Point) => ({ x: p.x * width, y: p.y * height }); + const points = stroke.points.map(toPx); + const paint = (c: Point) => { + const x0 = Math.max(0, Math.floor(c.x - radius)); + const x1 = Math.min(width - 1, Math.ceil(c.x + radius)); + const y0 = Math.max(0, Math.floor(c.y - radius)); + const y1 = Math.min(height - 1, Math.ceil(c.y + radius)); + for (let y = y0; y <= y1; y++) { + for (let x = x0; x <= x1; x++) { + const d = Math.hypot(x + 0.5 - c.x, y + 0.5 - c.y); + const v = Math.round(falloff(d, radius, stroke.hardness, feather) * 255); + if (v === 0) continue; + const i = y * width + x; + data[i] = stroke.mode === "add" ? Math.max(data[i]!, v) : Math.min(data[i]!, 255 - v); + } + } + }; + const spacing = Math.max(0.5, radius / 4); + let prev = points[0]!; + paint(prev); + for (const next of points.slice(1)) { + const len = Math.hypot(next.x - prev.x, next.y - prev.y); + const n = Math.ceil(len / spacing); + for (let k = 1; k <= n; k++) { + const t = k / n; + paint({ x: prev.x + (next.x - prev.x) * t, y: prev.y + (next.y - prev.y) * t }); + } + prev = next; + } +} + +function invertRaster(raster: MaskRaster): void { + for (let i = 0; i < raster.data.length; i++) raster.data[i] = 255 - raster.data[i]!; +} + +/** マスク全体をゼロから描く (undo・下書き復元・書き出し) */ +export function rasterizeBrushMask( + mask: BrushMaskV2, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + const raster = createMaskRaster(source, maxEdge); + for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); + if (mask.invert) invertRaster(raster); + return raster; +} + +/** + * 多角形 (v3) の下地を走査線で塗る。輪は外周 + 穴で、偶奇 (交差回数が奇数なら内側) で塗るので + * 顔の輪郭から目・口を抜ける。点は正規化座標 + */ +function fillPolygon(raster: MaskRaster, rings: PolygonMaskV3["rings"]): void { + const { width, height, data } = raster; + const edges: { x0: number; y0: number; x1: number; y1: number }[] = []; + for (const ring of rings) { + for (let i = 0; i < ring.length; i++) { + const a = ring[i]!; + const b = ring[(i + 1) % ring.length]!; + edges.push({ x0: a.x * width, y0: a.y * height, x1: b.x * width, y1: b.y * height }); + } + } + const xs: number[] = []; + for (let y = 0; y < height; y++) { + const cy = y + 0.5; + xs.length = 0; + for (const e of edges) { + // 半開区間で数えて、頂点を 2 回数えない + if (e.y0 <= cy === e.y1 <= cy) continue; + xs.push(e.x0 + ((cy - e.y0) * (e.x1 - e.x0)) / (e.y1 - e.y0)); + } + xs.sort((a, b) => a - b); + for (let k = 0; k + 1 < xs.length; k += 2) { + const from = Math.max(0, Math.round(xs[k]!)); + const to = Math.min(width, Math.round(xs[k + 1]!)); + if (to > from) data.fill(255, y * width + from, y * width + to); + } + } +} + +/** 箱ぼかしを縦横に 2 回 (三角形のカーネル相当)。radius は px */ +function blurRaster(raster: MaskRaster, radius: number): void { + const r = Math.round(radius); + if (r < 1) return; + const { width, height } = raster; + const pass = (src: Uint8ClampedArray, horizontal: boolean): Uint8ClampedArray => { + const out = new Uint8ClampedArray(src.length); + const len = horizontal ? width : height; + const lines = horizontal ? height : width; + const idx = (line: number, i: number) => (horizontal ? line * width + i : i * width + line); + for (let line = 0; line < lines; line++) { + let sum = 0; + for (let i = -r; i <= r; i++) sum += src[idx(line, Math.min(len - 1, Math.max(0, i)))]!; + for (let i = 0; i < len; i++) { + out[idx(line, i)] = sum / (2 * r + 1); + sum += src[idx(line, Math.min(len - 1, i + r + 1))]! - src[idx(line, Math.max(0, i - r))]!; + } + } + return out; + }; + for (let k = 0; k < 2; k++) { + raster.data = pass(raster.data, true); + raster.data = pass(raster.data, false); + } +} + +/** feather (0..1) を px に。長辺の 5% まで */ +const featherPx = (feather: number, raster: MaskRaster) => + feather * 0.05 * Math.max(raster.width, raster.height); + +export function rasterizePolygonMask( + mask: PolygonMaskV3, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + const raster = createMaskRaster(source, maxEdge); + fillPolygon(raster, mask.rings); + blurRaster(raster, featherPx(mask.feather, raster)); + for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); + if (mask.invert) invertRaster(raster); + return raster; +} + +/** ビットマップ (v3) を最近傍でラスタの寸法に広げる */ +export function rasterizeBitmapMask( + mask: BitmapMaskV3, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + const raster = createMaskRaster(source, maxEdge); + const bits = decodeRle(mask.rle, mask.width * mask.height); + const { width, height, data } = raster; + for (let y = 0; y < height; y++) { + const by = Math.min(mask.height - 1, Math.floor(((y + 0.5) / height) * mask.height)); + for (let x = 0; x < width; x++) { + const bx = Math.min(mask.width - 1, Math.floor(((x + 0.5) / width) * mask.width)); + data[y * width + x] = bits[by * mask.width + bx] ? 255 : 0; + } + } + blurRaster(raster, featherPx(mask.feather, raster)); + for (const stroke of mask.strokes) stampStroke(raster, stroke, mask.feather); + if (mask.invert) invertRaster(raster); + return raster; +} + +/** strokes を持つマスク (brush / polygon / bitmap) をゼロから描く */ +export function rasterizeMask( + mask: StrokedMask, + source: Size, + maxEdge = MASK_RASTER_MAX_EDGE, +): MaskRaster { + switch (mask.kind) { + case "brush": + return rasterizeBrushMask(mask, source, maxEdge); + case "polygon": + return rasterizePolygonMask(mask, source, maxEdge); + case "bitmap": + return rasterizeBitmapMask(mask, source, maxEdge); + } +} + +/** 1 点での多角形マスクの値 (0/1、feather と strokes は見ない)。偶奇の参照実装 */ +export function polygonMaskValue(uv: Point, mask: PolygonMaskV3): number { + let inside = false; + for (const ring of mask.rings) { + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const a = ring[i]!; + const b = ring[j]!; + if (a.y > uv.y !== b.y > uv.y && uv.x < a.x + ((uv.y - a.y) * (b.x - a.x)) / (b.y - a.y)) + inside = !inside; + } + } + const v = inside ? 1 : 0; + return mask.invert ? 1 - v : v; +} + +/** 1 点でのマスクの値 (参照実装)。種類で振り分ける */ +export function maskValue(uv: Point, mask: Mask, source: Size): number { + switch (mask.kind) { + case "ellipse": + return ellipseMaskValue(uv, mask, source); + case "brush": + return brushMaskValue(uv, mask, source); + case "polygon": + return polygonMaskValue(uv, mask); + case "bitmap": + return bitmapMaskValue(uv, mask); + } +} + +/** 1 点でのビットマップマスクの値 (0/1、feather と strokes は見ない) */ +export function bitmapMaskValue(uv: Point, mask: BitmapMaskV3): number { + const bits = decodeRle(mask.rle, mask.width * mask.height); + const bx = Math.min(mask.width - 1, Math.floor(uv.x * mask.width)); + const by = Math.min(mask.height - 1, Math.floor(uv.y * mask.height)); + const v = bits[by * mask.width + bx] ? 1 : 0; + return mask.invert ? 1 - v : v; +} + +/** + * 1 点でのブラシマスクの値 (0..1)。ラスタを介さず線分までの距離で評価する参照実装。 + * ストロークを順に適用する (add は max、erase は min) のはラスタと同じ + */ +export function brushMaskValue(uv: Point, mask: BrushMaskV2, source: Size): number { + const edge = Math.max(source.width, source.height); + const p = { x: uv.x * source.width, y: uv.y * source.height }; + let value = 0; + for (const stroke of mask.strokes) { + const radius = (stroke.size * edge) / 2; + const pts = stroke.points.map((q) => ({ x: q.x * source.width, y: q.y * source.height })); + let d = Infinity; + for (let i = 0; i < pts.length; i++) { + d = Math.min(d, distanceToSegment(p, pts[i]!, pts[Math.min(i + 1, pts.length - 1)]!)); + } + const v = falloff(d, radius, stroke.hardness, mask.feather); + value = stroke.mode === "add" ? Math.max(value, v) : Math.min(value, 1 - v); + } + return mask.invert ? 1 - value : value; +} + +/** + * ポインタの点列を間引く: 直前に残した点から minDistance 未満の移動は捨てる。最初と最後は残す。 + * 上限を超えたら等間隔に間引く (レシピの肥大化を抑える、docs/design/04 §1.1) + */ +export function simplifyPoints( + points: readonly Point[], + minDistance: number, + limit = MAX_BRUSH_POINTS, +): Point[] { + if (points.length === 0) return []; + const kept: Point[] = [points[0]!]; + for (let i = 1; i < points.length - 1; i++) { + const last = kept[kept.length - 1]!; + if (Math.hypot(points[i]!.x - last.x, points[i]!.y - last.y) >= minDistance) + kept.push(points[i]!); + } + if (points.length > 1) kept.push(points[points.length - 1]!); + if (kept.length <= limit) return kept; + const step = (kept.length - 1) / (limit - 1); + return Array.from({ length: limit }, (_, i) => kept[Math.round(i * step)]!); +} diff --git a/packages/editor-engine/src/drafts.test.ts b/packages/editor-engine/src/drafts.test.ts new file mode 100644 index 0000000..6d0404a --- /dev/null +++ b/packages/editor-engine/src/drafts.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE } from "@lumorphia/editor-recipe"; +import { + createDraftStore, + DRAFT_LIMIT, + selectStaleDrafts, + type Draft, + type DraftKeyValue, +} from "./drafts.ts"; + +const draft = (id: string, updatedAt: number): Draft => ({ + id, + name: id, + blob: new Blob([id]), + recipe: DEFAULT_RECIPE, + updatedAt, +}); + +/** IndexedDB の代わり。キーと値をそのまま持つ */ +function memoryKeyValue(initial: Record = {}): DraftKeyValue & { + entries: () => Record; +} { + let data: Record = { ...initial }; + return { + get: async (key: string) => data[key] as T | undefined, + set: async (key, value) => { + data = { ...data, [key]: value }; + }, + del: async (key) => { + const { [key]: _removed, ...rest } = data; + data = rest; + }, + keys: async () => Object.keys(data), + entries: () => data, + }; +} + +describe("selectStaleDrafts", () => { + const seven = Array.from({ length: DRAFT_LIMIT + 2 }, (_, i) => draft(String(i), i)); + + it("removes the oldest beyond the limit", () => { + expect(selectStaleDrafts(seven, []).map((d) => d.id)).toEqual(["0", "1"]); + expect(selectStaleDrafts(seven.slice(0, DRAFT_LIMIT), [])).toEqual([]); + }); + + it("never removes protected drafts, even if they are the oldest", () => { + expect(selectStaleDrafts(seven, ["0", "1"]).map((d) => d.id)).toEqual(["2", "3"]); + // 保護で候補が足りないときは残る分を消すだけ + expect(selectStaleDrafts(seven, ["0", "1", "2", "3", "4", "5"]).map((d) => d.id)).toEqual([ + "6", + ]); + }); +}); + +describe("createDraftStore", () => { + it("stores a draft under the draft: key so existing drafts stay readable", async () => { + const kv = memoryKeyValue(); + await createDraftStore(kv).save(draft("a", 1)); + expect(Object.keys(kv.entries())).toEqual(["draft:a"]); + }); + + it("loads a draft saved before the split with its recipe upgraded", async () => { + const { version: _v, localAdjustments: _l, ...v1 } = DEFAULT_RECIPE; + const kv = memoryKeyValue({ + "draft:old": { ...draft("old", 1), recipe: { ...v1, version: 1 } }, + }); + expect((await createDraftStore(kv).load("old"))?.recipe).toEqual(DEFAULT_RECIPE); + }); + + it("treats a draft with an unreadable recipe as missing", async () => { + const kv = memoryKeyValue({ "draft:bad": { ...draft("bad", 1), recipe: { version: 99 } } }); + expect(await createDraftStore(kv).load("bad")).toBeUndefined(); + }); + + it("drops the oldest drafts once the limit is exceeded", async () => { + const kv = memoryKeyValue(); + const store = createDraftStore(kv); + for (let i = 0; i < DRAFT_LIMIT + 1; i += 1) await store.save(draft(String(i), i)); + expect((await store.list()).map((d) => d.id)).toEqual(["5", "4", "3", "2", "1"]); + }); + + it("keeps drafts the host protects when trimming", async () => { + const kv = memoryKeyValue(); + const store = createDraftStore(kv, { protectedIds: async () => ["0"] }); + for (let i = 0; i < DRAFT_LIMIT + 1; i += 1) await store.save(draft(String(i), i)); + expect((await store.list()).map((d) => d.id)).toEqual(["5", "4", "3", "2", "0"]); + }); + + it("ignores keys that other features keep in the same store", async () => { + const kv = memoryKeyValue({ pending: [], "post-form": {}, "postDraft:x": {} }); + expect(await createDraftStore(kv).list()).toEqual([]); + }); + + it("removes a draft by id", async () => { + const kv = memoryKeyValue(); + const store = createDraftStore(kv); + await store.save(draft("a", 1)); + await store.remove("a"); + expect(await store.load("a")).toBeUndefined(); + }); +}); diff --git a/packages/editor-engine/src/drafts.ts b/packages/editor-engine/src/drafts.ts new file mode 100644 index 0000000..28ebdeb --- /dev/null +++ b/packages/editor-engine/src/drafts.ts @@ -0,0 +1,107 @@ +import { createStore, del, get, keys, set } from "idb-keyval"; +import { upgradeStoredRecipe, type EditRecipe } from "@lumorphia/editor-recipe"; + +/** + * 端末内の下書き (docs/design/04 §6, 03 §9)。原本 Blob とレシピを IndexedDB に置く。 + * 最大 5 件、古いものから消す。別端末には同期しない。 + * どの DB に置くか、どの下書きを消さずに残すかはホスト (prismtone なら投稿導線) が決める + */ +export type Draft = { + id: string; + name: string; + blob: Blob; + recipe: EditRecipe; + updatedAt: number; +}; + +export const DRAFT_LIMIT = 5; +const DRAFT_PREFIX = "draft:"; + +/** 下書きを置くキーバリュー。IndexedDB (idb-keyval) か、テストではメモリ */ +export type DraftKeyValue = { + get(key: string): Promise; + set(key: string, value: unknown): Promise; + del(key: string): Promise; + keys(): Promise; +}; + +export type DraftStore = { + save(draft: Draft): Promise; + load(id: string): Promise; + /** 新しい順 */ + list(): Promise; + remove(id: string): Promise; +}; + +export type DraftStoreOptions = { + /** 上限を超えても消さない下書き。投稿画像として残っているもの (#64) など */ + protectedIds?: () => Promise; +}; + +function upgradeDraft(draft: Draft | undefined): Draft | undefined { + if (!draft) return undefined; + const recipe = upgradeStoredRecipe(draft.recipe); + return recipe ? { ...draft, recipe } : undefined; +} + +/** + * 上限を超えた分だけ古い順に消す候補。保護された下書きは消さない。 + * 保護した分で上限を超えることはある (prismtone では両方の上限が 5 なので最大 5 件残る)。 + */ +export function selectStaleDrafts( + drafts: readonly Draft[], + protectedIds: readonly string[], +): Draft[] { + const keep = new Set(protectedIds); + const excess = drafts.length - DRAFT_LIMIT; + if (excess <= 0) return []; + return [...drafts] + .filter((d) => !keep.has(d.id)) + .sort((a, b) => a.updatedAt - b.updatedAt) + .slice(0, excess); +} + +export function createDraftStore(kv: DraftKeyValue, options: DraftStoreOptions = {}): DraftStore { + const draftKeys = async () => + (await kv.keys()).filter( + (k): k is string => typeof k === "string" && k.startsWith(DRAFT_PREFIX), + ); + + return { + async save(draft) { + await kv.set(`${DRAFT_PREFIX}${draft.id}`, draft); + const all = await draftKeys(); + if (all.length <= DRAFT_LIMIT) return; + const drafts = await Promise.all(all.map((k) => kv.get(k))); + const protectedIds = (await options.protectedIds?.()) ?? []; + for (const d of selectStaleDrafts( + drafts.filter((d): d is Draft => Boolean(d)), + protectedIds, + )) + await kv.del(`${DRAFT_PREFIX}${d.id}`); + }, + async load(id) { + return upgradeDraft(await kv.get(`${DRAFT_PREFIX}${id}`)); + }, + async list() { + const drafts = await Promise.all( + (await draftKeys()).map((k) => kv.get(k).then(upgradeDraft)), + ); + return drafts.filter((d): d is Draft => Boolean(d)).sort((a, b) => b.updatedAt - a.updatedAt); + }, + async remove(id) { + await kv.del(`${DRAFT_PREFIX}${id}`); + }, + }; +} + +/** idb-keyval の 1 ストアをキーバリューとして使う */ +export function idbKeyValue(dbName: string, storeName: string): DraftKeyValue { + const store = () => createStore(dbName, storeName); + return { + get: (key) => get(key, store()), + set: (key, value) => set(key, value, store()), + del: (key) => del(key, store()), + keys: () => keys(store()), + }; +} diff --git a/packages/editor-engine/src/history.test.ts b/packages/editor-engine/src/history.test.ts new file mode 100644 index 0000000..975a01d --- /dev/null +++ b/packages/editor-engine/src/history.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE, type EditRecipe } from "@lumorphia/editor-recipe"; +import { + canRedo, + canUndo, + commit, + createHistory, + HISTORY_LIMIT, + preview, + redo, + redoLabel, + undo, + undoLabel, +} from "./history.ts"; + +const withExposure = (r: EditRecipe, exposure: number): EditRecipe => ({ + ...r, + adjust: { ...r.adjust, exposure }, +}); + +describe("history", () => { + it("starts with nothing to undo or redo", () => { + const h = createHistory(DEFAULT_RECIPE); + expect(canUndo(h)).toBe(false); + expect(canRedo(h)).toBe(false); + expect(undo(h)).toBe(h); + expect(redo(h)).toBe(h); + }); + + it("preview does not create history entries", () => { + const h = preview(createHistory(DEFAULT_RECIPE), withExposure(DEFAULT_RECIPE, 1)); + expect(h.present.adjust.exposure).toBe(1); + expect(canUndo(h)).toBe(false); + }); + + it("commit then undo then redo round-trips", () => { + const a = DEFAULT_RECIPE; + const b = withExposure(a, 1); + const c = withExposure(a, 2); + let h = commit(commit(createHistory(a), b), c); + expect(h.present).toBe(c); + h = undo(h); + expect(h.present).toBe(b); + expect(canRedo(h)).toBe(true); + h = undo(h); + expect(h.present).toBe(a); + h = redo(h); + expect(h.present).toBe(b); + }); + + it("commit after undo discards the redo stack", () => { + const a = DEFAULT_RECIPE; + let h = commit(createHistory(a), withExposure(a, 1)); + h = undo(h); + h = commit(h, withExposure(a, -1)); + expect(canRedo(h)).toBe(false); + expect(h.present.adjust.exposure).toBe(-1); + }); + + it("commit with the same object is a no-op", () => { + const h = createHistory(DEFAULT_RECIPE); + expect(commit(h, DEFAULT_RECIPE)).toBe(h); + }); + + it("caps history length", () => { + let h = createHistory(DEFAULT_RECIPE); + for (let i = 1; i <= HISTORY_LIMIT + 10; i++) + h = commit(h, withExposure(DEFAULT_RECIPE, i / 100)); + expect(h.past.length).toBe(HISTORY_LIMIT); + }); + + it("never mutates previous states", () => { + const h0 = createHistory(DEFAULT_RECIPE); + const h1 = commit(h0, withExposure(DEFAULT_RECIPE, 1)); + expect(h0.past).toEqual([]); + expect(h0.present).toBe(DEFAULT_RECIPE); + expect(h1.past).not.toBe(h0.past); + }); +}); + +describe("history labels", () => { + it("commit の操作名が undo / redo で行き来する", () => { + let h = createHistory(DEFAULT_RECIPE); + h = commit(h, withExposure(DEFAULT_RECIPE, 1), "露光量 +1.00"); + h = commit(h, withExposure(DEFAULT_RECIPE, 2), "露光量 +2.00"); + expect(undoLabel(h)).toBe("露光量 +2.00"); + expect(redoLabel(h)).toBeNull(); + h = undo(h); + expect(undoLabel(h)).toBe("露光量 +1.00"); + expect(redoLabel(h)).toBe("露光量 +2.00"); + h = redo(h); + expect(undoLabel(h)).toBe("露光量 +2.00"); + // 新しい commit で future の名前も消える + h = undo(h); + h = commit(h, withExposure(DEFAULT_RECIPE, 3), "露光量 +3.00"); + expect(redoLabel(h)).toBeNull(); + expect(h.pastLabels).toEqual(["露光量 +1.00", "露光量 +3.00"]); + }); +}); diff --git a/packages/editor-engine/src/history.ts b/packages/editor-engine/src/history.ts new file mode 100644 index 0000000..50006bf --- /dev/null +++ b/packages/editor-engine/src/history.ts @@ -0,0 +1,67 @@ +import type { EditRecipe } from "@lumorphia/editor-recipe"; + +/** + * undo / redo の履歴。レシピは不変オブジェクトとして扱い、常に新しい History を返す + * (docs/design/04 §3)。 + */ +export type History = { + readonly past: readonly EditRecipe[]; + readonly present: EditRecipe; + readonly future: readonly EditRecipe[]; + /** past[i] から次の状態へ進めた操作の名前 (past と同じ長さ)。取り消しの説明に使う */ + readonly pastLabels: readonly string[]; + /** future[i] へ進める操作の名前 (future と同じ長さ)。やり直しの説明に使う */ + readonly futureLabels: readonly string[]; +}; + +export const HISTORY_LIMIT = 100; + +export function createHistory(present: EditRecipe): History { + return { past: [], present, future: [], pastLabels: [], futureLabels: [] }; +} + +/** 履歴に積まずに present だけ置き換える (スライダーのドラッグ中)。 */ +export function preview(h: History, next: EditRecipe): History { + return { ...h, present: next }; +} + +/** present を履歴に積んで next を現在にする (ドラッグ終了、プリセット適用、リセット)。 */ +export function commit(h: History, next: EditRecipe, label = "変更"): History { + if (next === h.present) return h; + const past = [...h.past, h.present].slice(-HISTORY_LIMIT); + const pastLabels = [...h.pastLabels, label].slice(-HISTORY_LIMIT); + return { past, present: next, future: [], pastLabels, futureLabels: [] }; +} + +export function undo(h: History): History { + const prev = h.past.at(-1); + if (!prev) return h; + const label = h.pastLabels.at(-1) ?? "変更"; + return { + past: h.past.slice(0, -1), + present: prev, + future: [h.present, ...h.future], + pastLabels: h.pastLabels.slice(0, -1), + futureLabels: [label, ...h.futureLabels], + }; +} + +export function redo(h: History): History { + const [next, ...rest] = h.future; + if (!next) return h; + const [label = "変更", ...restLabels] = h.futureLabels; + return { + past: [...h.past, h.present], + present: next, + future: rest, + pastLabels: [...h.pastLabels, label], + futureLabels: restLabels, + }; +} + +export const canUndo = (h: History) => h.past.length > 0; +export const canRedo = (h: History) => h.future.length > 0; +/** 「戻る」で取り消される操作の名前 */ +export const undoLabel = (h: History) => h.pastLabels.at(-1) ?? null; +/** 「進む」でやり直される操作の名前 */ +export const redoLabel = (h: History) => h.futureLabels[0] ?? null; diff --git a/packages/editor-engine/src/image-format.test.ts b/packages/editor-engine/src/image-format.test.ts new file mode 100644 index 0000000..93b230c --- /dev/null +++ b/packages/editor-engine/src/image-format.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { + fitWithin, + MAX_UPLOAD_BYTES, + sniffImageFormat, + validateImageFile, +} from "./image-format.ts"; + +const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0]); +const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 0]); +const webp = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50]); + +describe("sniffImageFormat", () => { + it("detects png and jpeg by magic bytes", () => { + expect(sniffImageFormat(png)).toBe("png"); + expect(sniffImageFormat(jpeg)).toBe("jpeg"); + }); + it("rejects other formats and short input", () => { + expect(sniffImageFormat(webp)).toBeNull(); + expect(sniffImageFormat(new Uint8Array([0xff]))).toBeNull(); + }); +}); + +describe("validateImageFile", () => { + it("rejects oversized files first", () => { + expect(validateImageFile(MAX_UPLOAD_BYTES + 1, png)).toBe("too_large"); + }); + it("rejects unsupported formats", () => { + expect(validateImageFile(100, webp)).toBe("unsupported_format"); + }); + it("accepts a png under the limit", () => { + expect(validateImageFile(MAX_UPLOAD_BYTES, png)).toBeNull(); + }); +}); + +describe("fitWithin", () => { + it("keeps images under the limit unchanged", () => { + expect(fitWithin(1920, 1080, 4096)).toEqual({ width: 1920, height: 1080 }); + }); + it("scales the long edge down to the limit", () => { + expect(fitWithin(5120, 2880, 4096)).toEqual({ width: 4096, height: 2304 }); + expect(fitWithin(2880, 5120, 4096)).toEqual({ width: 2304, height: 4096 }); + }); +}); diff --git a/packages/editor-engine/src/image-format.ts b/packages/editor-engine/src/image-format.ts new file mode 100644 index 0000000..fb04d46 --- /dev/null +++ b/packages/editor-engine/src/image-format.ts @@ -0,0 +1,33 @@ +/** 拡張子ではなく先頭バイトで画像形式を判定する (docs/design/09 §2)。 */ +export type ImageFormat = "png" | "jpeg"; + +export const MAX_UPLOAD_BYTES = 30 * 1024 * 1024; +export const MAX_EDIT_EDGE = 4096; + +const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + +export function sniffImageFormat(head: Uint8Array): ImageFormat | null { + if (head.length >= 8 && PNG.every((b, i) => head[i] === b)) return "png"; + if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return "jpeg"; + return null; +} + +export type ValidationError = "too_large" | "unsupported_format"; + +export function validateImageFile(size: number, head: Uint8Array): ValidationError | null { + if (size > MAX_UPLOAD_BYTES) return "too_large"; + if (!sniffImageFormat(head)) return "unsupported_format"; + return null; +} + +/** 長辺が max を超える場合の縮小後サイズ。超えなければそのまま。 */ +export function fitWithin( + width: number, + height: number, + max: number, +): { width: number; height: number } { + const edge = Math.max(width, height); + if (edge <= max) return { width, height }; + const s = max / edge; + return { width: Math.round(width * s), height: Math.round(height * s) }; +} diff --git a/packages/editor-engine/src/index.ts b/packages/editor-engine/src/index.ts new file mode 100644 index 0000000..63a6f90 --- /dev/null +++ b/packages/editor-engine/src/index.ts @@ -0,0 +1,16 @@ +// 現像のエンジン (ADR-0035)。React に依存しない。 +// 描画 (PixiJS、./render) と推論 (Worker、./inference/face, ./inference/segment) は重いので、使うときに動的 import する +export * from "./state.ts"; +export * from "./history.ts"; +export * from "./mask-math.ts"; +export * from "./brush-raster.ts"; +export * from "./image-format.ts"; +export * from "./load-image.ts"; +export * from "./drafts.ts"; +export * from "./render/geometry.ts"; +export * from "./render/viewport.ts"; +export * from "./inference/auto-select.ts"; +export * from "./inference/face-masks.ts"; +export * from "./inference/portrait.ts"; +export * from "./inference/segment-masks.ts"; +export * from "./inference/model-paths.ts"; diff --git a/packages/editor-engine/src/inference/auto-select.test.ts b/packages/editor-engine/src/inference/auto-select.test.ts new file mode 100644 index 0000000..07fe5a7 --- /dev/null +++ b/packages/editor-engine/src/inference/auto-select.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; +import { encodeRle, type BitmapMaskV3 } from "@lumorphia/editor-recipe"; +import { AUTO_SELECT_FAILED, planFaceSelection, planSegmentSelection } from "./auto-select.ts"; +import type { FaceResult } from "./face-masks.ts"; + +const square = (cx: number, cy: number, r: number) => [ + { x: cx - r, y: cy - r }, + { x: cx + r, y: cy - r }, + { x: cx + r, y: cy + r }, + { x: cx - r, y: cy + r }, +]; +const face = (overrides: Partial = {}): FaceResult => ({ + bbox: [0.3, 0.2, 0.7, 0.8], + oval: square(0.5, 0.5, 0.25), + leftEye: square(0.4, 0.4, 0.03), + rightEye: square(0.6, 0.4, 0.03), + mouth: square(0.5, 0.65, 0.05), + leftIris: { cx: 0.4, cy: 0.4, rx: 0.01, ry: 0.02 }, + rightIris: { cx: 0.6, cy: 0.4, rx: 0.01, ry: 0.02 }, + blink: { left: 0.05, right: 0.1 }, + ...overrides, +}); + +describe("planFaceSelection", () => { + it("瞳: puts two ellipses on the main face's irises in one step", () => { + const plan = planFaceSelection("eyes", [face()]); + expect(plan.items).toHaveLength(2); + expect(plan.items.every((i) => i.presetId === "eyes" && i.mask.kind === "ellipse")).toBe(true); + expect(plan.label).toBe("瞳強調 (自動)"); + expect(plan.notice).toBeNull(); + }); + + it("美肌: puts one polygon with holes on the main face", () => { + const plan = planFaceSelection("skin", [face()]); + expect(plan.items).toHaveLength(1); + expect(plan.items[0]!.presetId).toBe("skin"); + expect(plan.items[0]!.mask.kind).toBe("polygon"); + expect(plan.label).toBe("美肌 (自動)"); + }); + + it("says so without guessing why when no face was found", () => { + const plan = planFaceSelection("eyes", []); + expect(plan.items).toHaveLength(0); + expect(plan.notice).toBe(AUTO_SELECT_FAILED); + }); + + it("瞳: tells when the eyes are closed and places only the open one", () => { + const one = planFaceSelection("eyes", [face({ blink: { left: 0.9, right: 0.1 } })]); + expect(one.items).toHaveLength(1); + expect(one.notice).toMatch(/閉じている/); + const none = planFaceSelection("eyes", [face({ blink: { left: 0.9, right: 0.8 } })]); + expect(none.items).toHaveLength(0); + expect(none.notice).toMatch(/閉じている/); + }); + + it("uses the largest face when there are several", () => { + const small = face({ + bbox: [0.1, 0.1, 0.2, 0.25], + leftIris: { cx: 0.12, cy: 0.15, rx: 0.003, ry: 0.005 }, + }); + const plan = planFaceSelection("eyes", [small, face()]); + expect(plan.items[0]!.mask).toMatchObject({ cx: 0.4 }); + }); +}); + +describe("planSegmentSelection", () => { + const bitmap = (tag: number): BitmapMaskV3 => ({ + kind: "bitmap", + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([tag, 1])), + strokes: [], + feather: 0.1, + invert: false, + }); + const masks = [bitmap(0), bitmap(1), bitmap(0)]; + + it("装備強調: uses the middle granularity (index 1) with the gear preset", () => { + const plan = planSegmentSelection("gear", masks); + expect(plan.items).toHaveLength(1); + expect(plan.items[0]!.presetId).toBe("gear"); + expect(plan.items[0]!.mask).toBe(masks[1]); + expect(plan.label).toBe("装備強調 (自動)"); + }); + + it("キャラクター: uses the whole-character mask (index 0) without a preset", () => { + const plan = planSegmentSelection("person", masks); + expect(plan.items[0]!.presetId).toBeNull(); + expect(plan.items[0]!.name).toBe("キャラクター"); + expect(plan.items[0]!.mask).toBe(masks[0]); + }); + + it("背景: inverts the whole-character mask", () => { + const plan = planSegmentSelection("background", masks); + expect(plan.items[0]!.name).toBe("背景"); + expect(plan.items[0]!.mask).toMatchObject({ kind: "bitmap", invert: true }); + }); + + it("says so when the segmenter returned nothing", () => { + expect(planSegmentSelection("gear", []).notice).toBe(AUTO_SELECT_FAILED); + }); +}); diff --git a/packages/editor-engine/src/inference/auto-select.ts b/packages/editor-engine/src/inference/auto-select.ts new file mode 100644 index 0000000..3fd2ee9 --- /dev/null +++ b/packages/editor-engine/src/inference/auto-select.ts @@ -0,0 +1,73 @@ +import type { BitmapMaskV3, LocalPresetId } from "@lumorphia/editor-recipe"; +import type { AutoLocalItem } from "../state.ts"; +import { facePolygon, irisEllipses, pickMainFace, type FaceResult } from "./face-masks.ts"; +import { GEAR_LEVEL, PERSON_LEVEL } from "./segment-masks.ts"; + +/** + * 自動選択 (#176) の計画: 検出結果から「何を足すか」と「利用者に伝える一言」を決める純関数。 + * 文言は理由を断定しない (#175): 横顔・種族・小ささのどれで外れたかは分からない + */ + +export const AUTO_SELECT_FAILED = "自動選択できませんでした。手動で範囲を指定できます"; +export const EYES_CLOSED = "目を閉じているようです。手動で範囲を指定できます"; +export const ONE_EYE_CLOSED = "片方の目は閉じているようなので、開いている方だけに置きました"; + +export type FaceSelectionKind = Extract; + +export type SelectionPlan = { + readonly items: readonly AutoLocalItem[]; + readonly label: string; + readonly notice: string | null; +}; + +export function planFaceSelection( + kind: FaceSelectionKind, + faces: readonly FaceResult[], +): SelectionPlan { + const face = pickMainFace(faces); + if (!face) return { items: [], label: "", notice: AUTO_SELECT_FAILED }; + if (kind === "skin") { + return { + items: [{ presetId: "skin", mask: facePolygon(face) }], + label: "美肌 (自動)", + notice: null, + }; + } + const ellipses = irisEllipses(face); + if (ellipses.length === 0) return { items: [], label: "", notice: EYES_CLOSED }; + return { + items: ellipses.map((mask) => ({ presetId: "eyes", mask })), + label: "瞳強調 (自動)", + notice: ellipses.length === 1 ? ONE_EYE_CLOSED : null, + }; +} + +/** タップで切る対象 (#177)。gear は装備強調、person / background はプリセット無しの範囲 */ +export type SegmentSelectionKind = "gear" | "person" | "background"; + +export const SEGMENT_KIND_LABELS: Record = { + gear: "装備強調 (自動)", + person: "キャラクター", + background: "背景", +}; + +/** SAM の 3 段のマスクから何を足すか。gear は index 1 (装備 1 点)、person / background は index 0 (全体) */ +export function planSegmentSelection( + kind: SegmentSelectionKind, + masks: readonly BitmapMaskV3[], +): SelectionPlan { + const level = kind === "gear" ? GEAR_LEVEL : PERSON_LEVEL; + const mask = masks[level]; + if (!mask) return { items: [], label: "", notice: AUTO_SELECT_FAILED }; + if (kind === "gear") { + return { items: [{ presetId: "gear", mask }], label: SEGMENT_KIND_LABELS.gear, notice: null }; + } + const name = SEGMENT_KIND_LABELS[kind]; + return { + items: [ + { presetId: null, name, mask: kind === "background" ? { ...mask, invert: true } : mask }, + ], + label: `${name}を選択`, + notice: null, + }; +} diff --git a/packages/editor-engine/src/inference/face-masks.test.ts b/packages/editor-engine/src/inference/face-masks.test.ts new file mode 100644 index 0000000..ad1678a --- /dev/null +++ b/packages/editor-engine/src/inference/face-masks.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from "vitest"; +import type { EllipseMaskV2 } from "@lumorphia/editor-recipe"; +import { facePolygon, irisEllipses, pickMainFace, type FaceResult } from "./face-masks.ts"; + +const square = (cx: number, cy: number, r: number) => [ + { x: cx - r, y: cy - r }, + { x: cx + r, y: cy - r }, + { x: cx + r, y: cy + r }, + { x: cx - r, y: cy + r }, +]; + +const face = (overrides: Partial = {}): FaceResult => ({ + bbox: [0.3, 0.2, 0.7, 0.8], + oval: square(0.5, 0.5, 0.25), + leftEye: square(0.4, 0.4, 0.03), + rightEye: square(0.6, 0.4, 0.03), + mouth: square(0.5, 0.65, 0.05), + leftIris: { cx: 0.4, cy: 0.4, rx: 0.01, ry: 0.02 }, + rightIris: { cx: 0.6, cy: 0.4, rx: 0.01, ry: 0.02 }, + blink: { left: 0.05, right: 0.1 }, + ...overrides, +}); + +describe("pickMainFace", () => { + it("picks the tallest face (一番大きい顔)", () => { + const small = face({ bbox: [0.1, 0.1, 0.2, 0.25] }); + const big = face(); + expect(pickMainFace([small, big])).toBe(big); + expect(pickMainFace([])).toBeNull(); + }); +}); + +describe("irisEllipses", () => { + it("places an ellipse on each iris, 1.3 times the iris radius, with a soft edge", () => { + const [l, r] = irisEllipses(face()) as [EllipseMaskV2, EllipseMaskV2]; + expect(l).toMatchObject({ kind: "ellipse", cx: 0.4, cy: 0.4, rotation: 0, invert: false }); + expect(l.rx).toBeCloseTo(0.013); + expect(l.ry).toBeCloseTo(0.026); + expect(l.feather).toBe(0.5); + expect(r.cx).toBe(0.6); + }); + + it("skips an eye that is closed (eyeBlink 0.5 以上)", () => { + const closedLeft = face({ blink: { left: 0.8, right: 0.1 } }); + expect(irisEllipses(closedLeft)).toHaveLength(1); + expect(irisEllipses(closedLeft)[0]!.cx).toBe(0.6); + expect(irisEllipses(face({ blink: { left: 0.9, right: 0.7 } }))).toHaveLength(0); + // blendshape が無ければ開いているとみなす + expect(irisEllipses(face({ blink: { left: null, right: null } }))).toHaveLength(2); + }); +}); + +describe("facePolygon", () => { + it("uses the face oval as the outer ring and cuts holes for the eyes and mouth", () => { + const m = facePolygon(face()); + expect(m.kind).toBe("polygon"); + expect(m.rings).toHaveLength(4); + expect(m.rings[0]).toEqual(square(0.5, 0.5, 0.25)); + expect(m.rings[3]).toEqual(square(0.5, 0.65, 0.05)); + expect(m.strokes).toEqual([]); + expect(m.invert).toBe(false); + expect(m.feather).toBeGreaterThan(0); + }); + + it("leaves out a hole that has too few points", () => { + const m = facePolygon(face({ mouth: [] })); + expect(m.rings).toHaveLength(3); + }); +}); diff --git a/packages/editor-engine/src/inference/face-masks.ts b/packages/editor-engine/src/inference/face-masks.ts new file mode 100644 index 0000000..4338686 --- /dev/null +++ b/packages/editor-engine/src/inference/face-masks.ts @@ -0,0 +1,80 @@ +import type { EllipseMaskV2, PolygonMaskV3 } from "@lumorphia/editor-recipe"; + +/** + * 顔検出 (face.worker.ts) の結果から部分補正のマスクを組む純関数 (#176、ADR-0025)。 + * 座標は幾何を掛ける前の画像の正規化座標 (レシピのマスクと同じ)。 + */ + +export type NormalizedPoint = { x: number; y: number }; + +export type Iris = { + cx: number; + cy: number; + /** 半径。rx は画像の幅、ry は高さに対する比 (楕円マスクと同じ) */ + rx: number; + ry: number; +}; + +export type FaceResult = { + /** 顔の輪郭の外接矩形 [x0, y0, x1, y1] */ + bbox: [number, number, number, number]; + /** 顔の輪郭 (36 点)。多角形の外周になる */ + oval: NormalizedPoint[]; + leftEye: NormalizedPoint[]; + rightEye: NormalizedPoint[]; + /** 唇の外側 */ + mouth: NormalizedPoint[]; + leftIris: Iris; + rightIris: Iris; + /** blendshape の eyeBlinkLeft / eyeBlinkRight (0..1)。無ければ null */ + blink: { left: number | null; right: number | null }; +}; + +/** これ以上なら目を閉じているとみなして瞳は置かない */ +export const BLINK_CLOSED = 0.5; +/** 虹彩に対する円形マスクの半径の比。虹彩より少し広く取って縁を柔らかくする */ +const IRIS_SCALE = 1.3; +const IRIS_FEATHER = 0.5; +/** 顔の多角形のぼかし (0..1、長辺の 5% まで)。輪郭で補正が段にならない程度 */ +const FACE_FEATHER = 0.2; + +/** 一番大きい顔 (高さで比べる)。無ければ null */ +export function pickMainFace(faces: readonly FaceResult[]): FaceResult | null { + let best: FaceResult | null = null; + for (const f of faces) { + if (!best || f.bbox[3] - f.bbox[1] > best.bbox[3] - best.bbox[1]) best = f; + } + return best; +} + +const irisEllipse = (iris: Iris): EllipseMaskV2 => ({ + kind: "ellipse", + cx: iris.cx, + cy: iris.cy, + rx: iris.rx * IRIS_SCALE, + ry: iris.ry * IRIS_SCALE, + rotation: 0, + feather: IRIS_FEATHER, + invert: false, +}); + +/** 開いている目の虹彩に円形マスクを置く (左、右の順)。閉じている目は飛ばす */ +export function irisEllipses(face: FaceResult): EllipseMaskV2[] { + const open = (blink: number | null) => blink === null || blink < BLINK_CLOSED; + return [ + ...(open(face.blink.left) ? [irisEllipse(face.leftIris)] : []), + ...(open(face.blink.right) ? [irisEllipse(face.rightIris)] : []), + ]; +} + +/** 顔の輪郭を外周、目と口を穴にした多角形 (美肌用)。点が足りない穴は入れない */ +export function facePolygon(face: FaceResult): PolygonMaskV3 { + const holes = [face.leftEye, face.rightEye, face.mouth].filter((ring) => ring.length >= 3); + return { + kind: "polygon", + rings: [face.oval, ...holes], + strokes: [], + feather: FACE_FEATHER, + invert: false, + }; +} diff --git a/packages/editor-engine/src/inference/face.ts b/packages/editor-engine/src/inference/face.ts new file mode 100644 index 0000000..13b8d6e --- /dev/null +++ b/packages/editor-engine/src/inference/face.ts @@ -0,0 +1,74 @@ +import type { FaceResult } from "./face-masks.ts"; +import type { FaceRequest, FaceResponse } from "./face.worker.ts"; + +/** + * 顔検出の呼び出し側 (#176)。Worker を 1 つ起こして使い回す。画像は ImageBitmap を複製して渡す + * (Worker 側で閉じる)。進捗は初回のモデル取得の分だけ届く。 + */ + +export class InferenceError extends Error { + override readonly name = "InferenceError"; +} + +export type Progress = { loaded: number; total: number }; + +let worker: Worker | null = null; +let seq = 0; + +function getWorker(): Worker { + if (!worker) { + // module worker (dev の Vite は classic worker に import 文を残すので動かない)。MediaPipe は + // module worker では WASM ローダーを import() で読み、そのままだと "ModuleFactory not set" になる。 + // fetch-models.ts がローダーの末尾に self.ModuleFactory = ModuleFactory を足して通している + worker = new Worker(new URL("./face.worker.ts", import.meta.url), { type: "module" }); + } + return worker; +} + +/** Worker を捨てる (テストや、エラー後に作り直すとき) */ +export function resetFaceWorker(): void { + worker?.terminate(); + worker = null; +} + +export async function detectFaces( + bitmap: ImageBitmap, + options: { modelBaseUrl: string; onProgress?: (p: Progress) => void; signal?: AbortSignal }, +): Promise { + const w = getWorker(); + const id = ++seq; + // Worker に渡す複製 (元は現像で使い続ける) + const copy = await createImageBitmap(bitmap); + return new Promise((resolve, reject) => { + const onMessage = (e: MessageEvent) => { + const m = e.data; + if (m.id !== id) return; + if (m.type === "progress") { + options.onProgress?.({ loaded: m.loaded, total: m.total }); + return; + } + cleanup(); + if (m.type === "result") resolve(m.faces); + else reject(new InferenceError(m.message)); + }; + const onError = (e: ErrorEvent) => { + cleanup(); + resetFaceWorker(); + reject(new InferenceError(e.message || "worker error")); + }; + const onAbort = () => { + cleanup(); + reject(new InferenceError("aborted")); + }; + const cleanup = () => { + w.removeEventListener("message", onMessage); + w.removeEventListener("error", onError); + options.signal?.removeEventListener("abort", onAbort); + }; + w.addEventListener("message", onMessage); + w.addEventListener("error", onError); + options.signal?.addEventListener("abort", onAbort); + const req: FaceRequest = { id, bitmap: copy, modelBaseUrl: options.modelBaseUrl }; + w.postMessage(req, [copy]); + }); +} diff --git a/packages/editor-engine/src/inference/face.worker.ts b/packages/editor-engine/src/inference/face.worker.ts new file mode 100644 index 0000000..f535e68 --- /dev/null +++ b/packages/editor-engine/src/inference/face.worker.ts @@ -0,0 +1,241 @@ +/// +/** + * 顔検出の Web Worker (#176、ADR-0025)。MediaPipe Face Landmarker (WASM、CPU) を動かし、 + * 顔ごとの輪郭・目・唇・虹彩と blendshape (まばたき) を正規化座標で返す。 + * + * spike (docs/spikes/2026-09-21-auto-select.md) の detectFace を移したもの: + * - 画像全体 → 2 倍の 3×3 の重なる切り抜き の順に検出する (ピラミッド)。BlazeFace 短距離は顔が画面の + * 大部分を占める前提で、スクショの中くらいの顔をそのままでは拾えない + * - 同じ顔 (IoU 0.3 以上) は先に見つかった方 (広い文脈) を残す。切り抜きの縁にかかる顔は捨てる + * - 3 倍の段は誤検出だけ増えたので入れない + * + * 画像も推論もここ (ブラウザ) で完結し、外には送らない。モデルと WASM はホストが同じオリジンで配る (既定は /models/、model-paths.ts)。 + */ +import { FaceLandmarker, FilesetResolver } from "@mediapipe/tasks-vision"; +import type { FaceResult, NormalizedPoint } from "./face-masks.ts"; +import { modelPaths } from "./model-paths.ts"; + +/** 進捗の表示に使う総量の目安 (モデル 3.7 MB + WASM 11 MB)。WASM の取得は MediaPipe の中なので数えられない */ +export const FACE_MODEL_BYTES = 3_758_596 + 11_153_617; + +export type FaceRequest = { + id: number; + bitmap: ImageBitmap; + /** モデルと WASM の置き場所 (model-paths.ts)。最初の 1 回の読み込みで使う */ + modelBaseUrl: string; + /** 検出のしきい値。spike の結果は 0.3 */ + confidence?: number; +}; +export type FaceResponse = + | { id: number; type: "progress"; loaded: number; total: number } + | { id: number; type: "result"; faces: FaceResult[]; ms: number } + | { id: number; type: "error"; message: string }; + +const CONFIDENCE = 0.3; +const PYRAMID = [2]; +/** 同じ顔とみなす bbox の IoU */ +const SAME_FACE_IOU = 0.3; +/** 切り抜きの縁からこの割合 (画像全体に対して) 以内にかかる顔は不完全なので捨てる */ +const EDGE_MARGIN = 0.02; + +/** 接続リスト ({start,end}) を辿って 1 本の輪郭 (点の index 列) にする。複数の輪があれば一番長いもの (唇の外側) */ +type Connection = { start: number; end: number }; + +function chain(connections: readonly Connection[]): number[] { + const next = new Map(connections.map((c) => [c.start, c.end])); + const seen = new Set(); + let best: number[] = []; + for (const c of connections) { + if (seen.has(c.start)) continue; + const ring = [c.start]; + seen.add(c.start); + for (;;) { + const n = next.get(ring[ring.length - 1]!); + if (n === undefined || seen.has(n)) break; + ring.push(n); + seen.add(n); + } + if (ring.length > best.length) best = ring; + } + return best; +} + +const OVAL = chain(FaceLandmarker.FACE_LANDMARKS_FACE_OVAL); +const LEFT_EYE = chain(FaceLandmarker.FACE_LANDMARKS_LEFT_EYE); +const RIGHT_EYE = chain(FaceLandmarker.FACE_LANDMARKS_RIGHT_EYE); +const LIPS = chain(FaceLandmarker.FACE_LANDMARKS_LIPS); +// 虹彩は 468 (左の中心) + 469..472、473 (右の中心) + 474..477 +const IRIS = { left: [468, 469, 470, 471, 472], right: [473, 474, 475, 476, 477] } as const; + +type Landmark = { x: number; y: number }; + +let landmarker: FaceLandmarker | null = null; +let loading: Promise | null = null; + +async function fetchWithProgress( + url: string, + onProgress: (loaded: number) => void, +): Promise { + const res = await fetch(url); + if (!res.ok || !res.body) throw new Error(`model fetch failed: ${res.status}`); + const chunks: Uint8Array[] = []; + let loaded = 0; + const reader = res.body.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + loaded += value.byteLength; + onProgress(loaded); + } + const out = new Uint8Array(loaded); + let offset = 0; + for (const c of chunks) { + out.set(c, offset); + offset += c.byteLength; + } + return out; +} + +function load( + modelBaseUrl: string, + confidence: number, + onProgress: (loaded: number) => void, +): Promise { + if (landmarker) return Promise.resolve(landmarker); + if (loading) return loading; + // module worker では MediaPipe が WASM ローダーを self.import ?? import() で読む。dev の Vite は + // 素の import() に ?import を足して public のファイルを「URL を export するモジュール」に変えて + // しまうので、Vite の書き換えを避けた import を渡す (本番ビルドでは同じ動き) + (self as unknown as { import?: (url: string) => Promise }).import = (url) => + import(/* @vite-ignore */ url); + const base = modelPaths(modelBaseUrl).face; + loading = (async () => { + const model = await fetchWithProgress(`${base}/face_landmarker.task`, onProgress); + const vision = await FilesetResolver.forVisionTasks(`${base}/wasm`); + const lm = await FaceLandmarker.createFromOptions(vision, { + baseOptions: { modelAssetBuffer: model, delegate: "CPU" }, + runningMode: "IMAGE", + numFaces: 6, + minFaceDetectionConfidence: confidence, + minFacePresenceConfidence: confidence, + outputFaceBlendshapes: true, + }); + landmarker = lm; + loading = null; + return lm; + })(); + return loading; +} + +type Crop = { x: number; y: number; w: number; h: number; scale: number }; + +function* crops(w: number, h: number): Generator { + yield { x: 0, y: 0, w, h, scale: 1 }; + for (const s of PYRAMID) { + const cw = w / s; + const ch = h / s; + const n = 2 * s - 1; + for (let j = 0; j < n; j++) + for (let i = 0; i < n; i++) + yield { x: (i * cw) / 2, y: (j * ch) / 2, w: cw, h: ch, scale: s }; + } +} + +function iou(a: number[], b: number[]): number { + const ix = Math.max(0, Math.min(a[2]!, b[2]!) - Math.max(a[0]!, b[0]!)); + const iy = Math.max(0, Math.min(a[3]!, b[3]!) - Math.max(a[1]!, b[1]!)); + const inter = ix * iy; + const area = (r: number[]) => (r[2]! - r[0]!) * (r[3]! - r[1]!); + return inter / (area(a) + area(b) - inter); +} + +function bboxOf(lms: Landmark[]): [number, number, number, number] { + const xs = OVAL.map((k) => lms[k]!.x); + const ys = OVAL.map((k) => lms[k]!.y); + return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]; +} + +function detectAll(lm: FaceLandmarker, bitmap: ImageBitmap): FaceResult[] { + const w = bitmap.width; + const h = bitmap.height; + const canvas = new OffscreenCanvas(1, 1); + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("no 2d context"); + const found: { lms: Landmark[]; bbox: number[]; blink: FaceResult["blink"] }[] = []; + for (const c of crops(w, h)) { + let res; + if (c.scale === 1) { + res = lm.detect(bitmap); + } else { + canvas.width = Math.round(c.w); + canvas.height = Math.round(c.h); + ctx.drawImage(bitmap, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height); + res = lm.detect(canvas); + } + res.faceLandmarks.forEach((raw, i) => { + // 切り抜きの正規化座標を画像全体の座標に戻す + const lms: Landmark[] = raw.map((p) => ({ + x: (c.x + p.x * c.w) / w, + y: (c.y + p.y * c.h) / h, + })); + const b = bboxOf(lms); + if (c.scale > 1) { + const m = EDGE_MARGIN / c.scale; + if ( + b[0] < c.x / w + m || + b[1] < c.y / h + m || + b[2] > (c.x + c.w) / w - m || + b[3] > (c.y + c.h) / h - m + ) + return; + } + if (found.some((f) => iou(f.bbox, b) > SAME_FACE_IOU)) return; + const shapes = res.faceBlendshapes?.[i]?.categories ?? []; + const shape = (name: string) => shapes.find((s) => s.categoryName === name)?.score ?? null; + found.push({ + lms, + bbox: b, + blink: { left: shape("eyeBlinkLeft"), right: shape("eyeBlinkRight") }, + }); + }); + } + return found.map(({ lms, bbox, blink }) => { + const ring = (idx: readonly number[]): NormalizedPoint[] => + idx.map((k) => ({ x: lms[k]!.x, y: lms[k]!.y })); + const iris = (idx: readonly number[]) => { + const [c, ...rim] = idx.map((k) => lms[k]!); + // 半径は px で測ってから幅・高さの比に戻す (楕円マスクの rx / ry と同じ意味) + const rPx = + rim.reduce((a, p) => a + Math.hypot((p.x - c!.x) * w, (p.y - c!.y) * h), 0) / rim.length; + return { cx: c!.x, cy: c!.y, rx: rPx / w, ry: rPx / h }; + }; + return { + bbox: bbox as [number, number, number, number], + oval: ring(OVAL), + leftEye: ring(LEFT_EYE), + rightEye: ring(RIGHT_EYE), + mouth: ring(LIPS), + leftIris: iris(IRIS.left), + rightIris: iris(IRIS.right), + blink, + }; + }); +} + +self.onmessage = async (e: MessageEvent) => { + const { id, bitmap, modelBaseUrl, confidence = CONFIDENCE } = e.data; + const post = (m: FaceResponse) => self.postMessage(m); + try { + const lm = await load(modelBaseUrl, confidence, (loaded) => + post({ id, type: "progress", loaded, total: FACE_MODEL_BYTES }), + ); + const t0 = performance.now(); + const faces = detectAll(lm, bitmap); + post({ id, type: "result", faces, ms: performance.now() - t0 }); + } catch (err) { + post({ id, type: "error", message: err instanceof Error ? err.message : String(err) }); + } finally { + bitmap.close(); + } +}; diff --git a/packages/editor-engine/src/inference/model-paths.test.ts b/packages/editor-engine/src/inference/model-paths.test.ts new file mode 100644 index 0000000..9dbb84c --- /dev/null +++ b/packages/editor-engine/src/inference/model-paths.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_MODEL_BASE_URL, modelPaths } from "./model-paths.ts"; + +describe("modelPaths", () => { + it("serves models from /models/ by default", () => { + expect(DEFAULT_MODEL_BASE_URL).toBe("/models/"); + expect(modelPaths(DEFAULT_MODEL_BASE_URL)).toEqual({ + face: "/models/face-landmarker-v1", + samRoot: "/models/", + samModelId: "slimsam-77-q8-v1", + ortWasm: "/models/ort-v1/", + }); + }); + + it("accepts a base URL without a trailing slash", () => { + expect(modelPaths("https://cdn.example/m").face).toBe( + "https://cdn.example/m/face-landmarker-v1", + ); + }); +}); diff --git a/packages/editor-engine/src/inference/model-paths.ts b/packages/editor-engine/src/inference/model-paths.ts new file mode 100644 index 0000000..46ce62f --- /dev/null +++ b/packages/editor-engine/src/inference/model-paths.ts @@ -0,0 +1,25 @@ +/** + * 推論のモデルと WASM の置き場所 (ADR-0025)。ホストが同じオリジンで配る。 + * ディレクトリは版付き (`-v1`)。中身を変えたら版を上げる (apps/app/scripts/fetch-models.ts と合わせる) + */ +export const DEFAULT_MODEL_BASE_URL = "/models/"; + +export type ModelPaths = { + /** MediaPipe Face Landmarker の .task と wasm/ */ + face: string; + /** transformers.js の localModelPath。この下に samModelId のディレクトリがある */ + samRoot: string; + samModelId: string; + /** onnxruntime-web の WASM */ + ortWasm: string; +}; + +export function modelPaths(baseUrl: string): ModelPaths { + const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`; + return { + face: `${base}face-landmarker-v1`, + samRoot: base, + samModelId: "slimsam-77-q8-v1", + ortWasm: `${base}ort-v1/`, + }; +} diff --git a/packages/editor-engine/src/inference/portrait.test.ts b/packages/editor-engine/src/inference/portrait.test.ts new file mode 100644 index 0000000..29862e0 --- /dev/null +++ b/packages/editor-engine/src/inference/portrait.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { encodeRle, findPortraitPreset, type BitmapMaskV3 } from "@lumorphia/editor-recipe"; +import type { FaceResult } from "./face-masks.ts"; +import { buildPortraitItems, faceCenter } from "./portrait.ts"; + +const square = (cx: number, cy: number, r: number) => [ + { x: cx - r, y: cy - r }, + { x: cx + r, y: cy - r }, + { x: cx + r, y: cy + r }, + { x: cx - r, y: cy + r }, +]; +const face: FaceResult = { + bbox: [0.3, 0.2, 0.7, 0.8], + oval: square(0.5, 0.5, 0.25), + leftEye: square(0.4, 0.4, 0.03), + rightEye: square(0.6, 0.4, 0.03), + mouth: square(0.5, 0.65, 0.05), + leftIris: { cx: 0.4, cy: 0.4, rx: 0.01, ry: 0.02 }, + rightIris: { cx: 0.6, cy: 0.4, rx: 0.01, ry: 0.02 }, + blink: { left: 0.05, right: 0.1 }, +}; +const person: BitmapMaskV3 = { + kind: "bitmap", + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([1, 0])), + strokes: [], + feather: 0.1, + invert: false, +}; + +describe("buildPortraitItems", () => { + it("builds 背景 → 人物 → 顔 → 瞳 ×2 with the preset's values scaled by the effect", () => { + const natural = findPortraitPreset("natural")!; + const items = buildPortraitItems(face, person, natural, 50); + expect(items.map((i) => i.name)).toEqual(["背景", "人物", "顔", "瞳 (左)", "瞳 (右)"]); + expect(items[0]!.mask).toMatchObject({ kind: "bitmap", invert: true }); + expect(items[1]!.mask).toBe(person); + expect(items[2]!.mask.kind).toBe("polygon"); + expect(items[2]!.presetId).toBe("skin"); + expect(items[3]!.presetId).toBe("eyes"); + expect(items[0]!.amount).toBe(Math.round(natural.roles.background.amount / 2)); + expect(items[2]!.adjust?.smooth).toBe(natural.roles.face.adjust.smooth); + }); + + it("leaves out closed eyes", () => { + const closed = { ...face, blink: { left: 0.9, right: 0.1 } }; + const items = buildPortraitItems(closed, person, findPortraitPreset("eyes")!, 100); + expect(items.map((i) => i.name)).toEqual(["背景", "人物", "顔", "瞳 (右)"]); + }); +}); + +describe("faceCenter", () => { + it("is the centre of the face box (SAM のタップ位置)", () => { + expect(faceCenter(face)).toEqual({ x: 0.5, y: 0.5 }); + }); +}); diff --git a/packages/editor-engine/src/inference/portrait.ts b/packages/editor-engine/src/inference/portrait.ts new file mode 100644 index 0000000..9c2c38a --- /dev/null +++ b/packages/editor-engine/src/inference/portrait.ts @@ -0,0 +1,62 @@ +import { + DEFAULT_LOCAL_ADJUST, + type BitmapMaskV3, + type PortraitPreset, + type PortraitRole, +} from "@lumorphia/editor-recipe"; +import type { AutoLocalItem } from "../state.ts"; +import { facePolygon, irisEllipses, type FaceResult } from "./face-masks.ts"; +import type { NormalizedPoint } from "./face-masks.ts"; + +/** + * 人物補正 (#175) の部分補正の組み立て (純関数)。顔検出と人物の切り抜きから、 + * 背景 → 人物 → 顔 → 瞳 の順に部分補正を作る (後の方が上に掛かる)。 + */ + +export const PORTRAIT_FULL = + "部分補正の上限 (12 件) に届くので置けません。不要な部分補正を削除してください"; + +export const PORTRAIT_ROLE_NAMES: Record = { + background: "背景", + person: "人物", + face: "顔", + eyes: "瞳", +}; + +/** SAM に渡すタップ位置: 顔の外接矩形の中心 (人物全体のマスクは index 0) */ +export function faceCenter(face: FaceResult): NormalizedPoint { + return { x: (face.bbox[0] + face.bbox[2]) / 2, y: (face.bbox[1] + face.bbox[3]) / 2 }; +} + +export function buildPortraitItems( + face: FaceResult, + person: BitmapMaskV3, + preset: PortraitPreset, + effect: number, +): AutoLocalItem[] { + const role = (r: PortraitRole) => ({ + adjust: { ...DEFAULT_LOCAL_ADJUST, ...preset.roles[r].adjust }, + amount: Math.round((preset.roles[r].amount * effect) / 100), + }); + const eyes = irisEllipses(face); + const openEyes = [ + ...(face.blink.left === null || face.blink.left < 0.5 ? ["左"] : []), + ...(face.blink.right === null || face.blink.right < 0.5 ? ["右"] : []), + ]; + return [ + { + name: PORTRAIT_ROLE_NAMES.background, + presetId: null, + mask: { ...person, invert: true }, + ...role("background"), + }, + { name: PORTRAIT_ROLE_NAMES.person, presetId: null, mask: person, ...role("person") }, + { name: PORTRAIT_ROLE_NAMES.face, presetId: "skin", mask: facePolygon(face), ...role("face") }, + ...eyes.map((mask, i) => ({ + name: `${PORTRAIT_ROLE_NAMES.eyes} (${openEyes[i]})`, + presetId: "eyes" as const, + mask, + ...role("eyes"), + })), + ]; +} diff --git a/packages/editor-engine/src/inference/segment-masks.test.ts b/packages/editor-engine/src/inference/segment-masks.test.ts new file mode 100644 index 0000000..635a227 --- /dev/null +++ b/packages/editor-engine/src/inference/segment-masks.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import { BITMAP_MAX_EDGE, decodeRle } from "@lumorphia/editor-recipe"; +import { SAM_LEVELS, toBitmapMask } from "./segment-masks.ts"; + +describe("toBitmapMask", () => { + it("shrinks a full-size mask to the bitmap edge limit keeping the aspect ratio", () => { + // 1024×512 の右半分が 1 + const w = 1024; + const h = 512; + const src = new Uint8Array(w * h); + for (let y = 0; y < h; y++) src.fill(1, y * w + w / 2, y * w + w); + const m = toBitmapMask(src, w, h); + expect(m.kind).toBe("bitmap"); + expect(m.width).toBe(BITMAP_MAX_EDGE); + expect(m.height).toBe(BITMAP_MAX_EDGE / 2); + const bits = decodeRle(m.rle, m.width * m.height); + expect(bits[10]).toBe(0); + expect(bits[m.width - 10]).toBe(1); + expect(m.strokes).toEqual([]); + expect(m.invert).toBe(false); + }); + + it("keeps a small mask as-is and can invert it (背景 = 人物の反転)", () => { + const src = Uint8Array.from([1, 0, 0, 1]); + const m = toBitmapMask(src, 2, 2, { invert: true }); + expect([m.width, m.height]).toEqual([2, 2]); + expect(decodeRle(m.rle, 4)).toEqual(Uint8Array.from([1, 0, 0, 1])); + expect(m.invert).toBe(true); + }); + + it("a cell is set when at least half of its source pixels are set", () => { + // 4×1 → 2×1: 左のセルは 1 が 1/2 (境界で 1)、右のセルは 0/2 + const m = toBitmapMask(Uint8Array.from([1, 0, 0, 0]), 4, 1, { maxEdge: 2 }); + expect(decodeRle(m.rle, 2)).toEqual(Uint8Array.from([1, 0])); + }); + + it("names the three SAM granularities in a fixed order (全体 → 装備 → 部品)", () => { + expect(SAM_LEVELS.map((l) => l.index)).toEqual([0, 1, 2]); + expect(SAM_LEVELS[1]!.label).toBe("装備"); + }); +}); diff --git a/packages/editor-engine/src/inference/segment-masks.ts b/packages/editor-engine/src/inference/segment-masks.ts new file mode 100644 index 0000000..96f5cad --- /dev/null +++ b/packages/editor-engine/src/inference/segment-masks.ts @@ -0,0 +1,54 @@ +import { BITMAP_MAX_EDGE, encodeRle, type BitmapMaskV3 } from "@lumorphia/editor-recipe"; + +/** + * SAM の切り抜き (segment.worker.ts) をレシピの bitmap マスクにする純関数 (#177、ADR-0025)。 + * 原寸の 0/1 を長辺 256 に縮め (セルの半分以上が 1 なら 1)、RLE で持つ。 + */ + +/** SAM が返す 3 段の粒度。spike で順番が安定していた: 0 = キャラクター全体、1 = その装備 1 点、2 = その一部 */ +export const SAM_LEVELS = [ + { index: 0, label: "全体", hint: "キャラクター全体 (髪・顔・装備)" }, + { index: 1, label: "装備", hint: "タップした装備 1 点" }, + { index: 2, label: "部品", hint: "装備の一部 (袖、襟、胸当てなど)" }, +] as const; +export type SamLevel = (typeof SAM_LEVELS)[number]["index"]; +/** 装備強調の既定。IoU で選ぶと全体に寄るので使わない */ +export const GEAR_LEVEL: SamLevel = 1; +export const PERSON_LEVEL: SamLevel = 0; + +/** bitmap マスクのぼかし。境界の階段を消す程度 */ +const BITMAP_FEATHER = 0.1; + +export function toBitmapMask( + mask: Uint8Array, + width: number, + height: number, + options: { invert?: boolean; maxEdge?: number; feather?: number } = {}, +): BitmapMaskV3 { + const maxEdge = options.maxEdge ?? BITMAP_MAX_EDGE; + const scale = Math.min(1, maxEdge / Math.max(width, height)); + const w = Math.max(1, Math.round(width * scale)); + const h = Math.max(1, Math.round(height * scale)); + const bits = new Uint8Array(w * h); + for (let y = 0; y < h; y++) { + const y0 = Math.floor((y * height) / h); + const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * height) / h)); + for (let x = 0; x < w; x++) { + const x0 = Math.floor((x * width) / w); + const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * width) / w)); + let on = 0; + for (let yy = y0; yy < y1; yy++) + for (let xx = x0; xx < x1; xx++) on += mask[yy * width + xx]!; + bits[y * w + x] = on * 2 >= (y1 - y0) * (x1 - x0) ? 1 : 0; + } + } + return { + kind: "bitmap", + width: w, + height: h, + rle: encodeRle(bits), + strokes: [], + feather: options.feather ?? BITMAP_FEATHER, + invert: options.invert ?? false, + }; +} diff --git a/packages/editor-engine/src/inference/segment.ts b/packages/editor-engine/src/inference/segment.ts new file mode 100644 index 0000000..fd04126 --- /dev/null +++ b/packages/editor-engine/src/inference/segment.ts @@ -0,0 +1,99 @@ +import type { BitmapMaskV3 } from "@lumorphia/editor-recipe"; +import { InferenceError, type Progress } from "./face.ts"; +import type { SegmentRequest, SegmentResponse } from "./segment.worker.ts"; + +/** + * 装備・人物の切り抜きの呼び出し側 (#177)。Worker を 1 つ起こして使い回す。 + * 画像ごとに prepareSegmenter (埋め込み、重い) を 1 回、タップごとに segmentAt (軽い)。 + */ + +let worker: Worker | null = null; +let seq = 0; +/** 埋め込み済みの画像の印。同じ画像なら埋め込みを使い回す */ +let embeddedFor: object | null = null; + +function getWorker(): Worker { + if (!worker) { + worker = new Worker(new URL("./segment.worker.ts", import.meta.url), { type: "module" }); + } + return worker; +} + +export function resetSegmentWorker(): void { + worker?.terminate(); + worker = null; + embeddedFor = null; +} + +type Body = SegmentRequest extends infer R + ? R extends { id: number } + ? Omit + : never + : never; + +function call( + req: Body, + done: T, + options: { onProgress?: ((p: Progress) => void) | undefined; transfer?: Transferable[] } = {}, +): Promise> { + const w = getWorker(); + const id = ++seq; + return new Promise((resolve, reject) => { + const onMessage = (e: MessageEvent) => { + const m = e.data; + if (m.id !== id) return; + if (m.type === "progress") { + options.onProgress?.({ loaded: m.loaded, total: m.total }); + return; + } + cleanup(); + if (m.type === done) resolve(m as Extract); + else if (m.type === "error") reject(new InferenceError(m.message)); + else reject(new InferenceError(`unexpected ${m.type}`)); + }; + const onError = (e: ErrorEvent) => { + cleanup(); + resetSegmentWorker(); + reject(new InferenceError(e.message || "worker error")); + }; + const cleanup = () => { + w.removeEventListener("message", onMessage); + w.removeEventListener("error", onError); + }; + w.addEventListener("message", onMessage); + w.addEventListener("error", onError); + w.postMessage({ id, ...req }, options.transfer ?? []); + }); +} + +/** 画像の埋め込み。同じ bitmap なら 2 回目以降は何もしない。戻り値は埋め込みに掛かった ms (使い回しは 0) */ +export async function prepareSegmenter( + bitmap: ImageBitmap, + options: { modelBaseUrl: string; onProgress?: (p: Progress) => void }, +): Promise { + if (embeddedFor === bitmap) return 0; + const copy = await createImageBitmap(bitmap); + const res = await call( + { type: "embed", bitmap: copy, modelBaseUrl: options.modelBaseUrl }, + "embedded", + { + onProgress: options.onProgress, + transfer: [copy], + }, + ); + embeddedFor = bitmap; + return res.ms; +} + +export type Segmentation = { + /** 3 段の粒度 (0 = 全体、1 = 装備、2 = 部品)。segment-masks.ts の SAM_LEVELS */ + masks: BitmapMaskV3[]; + scores: number[]; + ms: number; +}; + +/** タップ位置 (幾何を掛ける前の画像の正規化座標) の切り抜き。prepareSegmenter のあとで */ +export async function segmentAt(x: number, y: number): Promise { + const res = await call({ type: "segment", x, y }, "segmented"); + return { masks: res.masks, scores: res.scores, ms: res.ms }; +} diff --git a/packages/editor-engine/src/inference/segment.worker.ts b/packages/editor-engine/src/inference/segment.worker.ts new file mode 100644 index 0000000..9919331 --- /dev/null +++ b/packages/editor-engine/src/inference/segment.worker.ts @@ -0,0 +1,162 @@ +/// +/** + * 装備・人物の切り抜きの Web Worker (#177、ADR-0025)。SlimSAM (Xenova/slimsam-77-uniform、q8) を + * transformers.js + onnxruntime-web (WASM) で動かす。 + * + * - 画像 1 枚につき埋め込み (vision encoder) を 1 回 (重い、spike で 2 秒)。使い回す + * - タップごとにデコード (0.2 秒)。3 段の粒度のマスクを全部 bitmap にして返す (spike で 0 = 全体、1 = 装備、2 = 部品) + * - モデルと WASM はホストが同じオリジンで配る (既定は /models/、model-paths.ts)。HF Hub には行かない + * - COOP / COEP が無いので SharedArrayBuffer は無く、ORT はシングルスレッド + * + * spike (docs/spikes/2026-09-21-auto-select.md) の segmentAnything を移したもの。 + */ +import type * as TransformersNs from "@huggingface/transformers"; +import type { BitmapMaskV3 } from "@lumorphia/editor-recipe"; +import { toBitmapMask } from "./segment-masks.ts"; +import { modelPaths } from "./model-paths.ts"; + +export type SegmentRequest = + | { id: number; type: "embed"; bitmap: ImageBitmap; modelBaseUrl: string } + | { id: number; type: "segment"; x: number; y: number }; +export type SegmentResponse = + | { id: number; type: "progress"; loaded: number; total: number } + | { id: number; type: "embedded"; ms: number } + | { id: number; type: "segmented"; masks: BitmapMaskV3[]; scores: number[]; ms: number } + | { id: number; type: "error"; message: string }; + +type Transformers = typeof TransformersNs; +type SamInputs = { original_sizes: number[][]; reshaped_input_sizes: number[][] } & Record< + string, + unknown +>; +type TensorLike = { dims: number[]; data: ArrayLike }; +type SamProcessor = ((image: unknown) => Promise) & { + post_process_masks: ( + masks: unknown, + originalSizes: number[][], + reshapedSizes: number[][], + ) => Promise; +}; +type SamModel = { + get_image_embeddings: (inputs: SamInputs) => Promise>; + (inputs: Record): Promise<{ pred_masks: unknown; iou_scores: TensorLike }>; +}; + +let lib: Transformers | null = null; +let model: SamModel | null = null; +let processor: SamProcessor | null = null; +let embedded: { inputs: SamInputs; embeddings: Record } | null = null; + +async function load(modelBaseUrl: string, onProgress: (loaded: number, total: number) => void) { + if (lib && model && processor) return { lib, model, processor }; + const paths = modelPaths(modelBaseUrl); + const t = await import("@huggingface/transformers"); + // 自前ホストだけを見る。models/ の下は HF の repo と同じ配置 (config.json, onnx/*.onnx) + t.env.allowLocalModels = true; + t.env.allowRemoteModels = false; + t.env.localModelPath = paths.samRoot; + if (t.env.backends.onnx.wasm) t.env.backends.onnx.wasm.wasmPaths = paths.ortWasm; + const totals = new Map(); + const progress_callback = (p: { + status: string; + file?: string; + loaded?: number; + total?: number; + }) => { + if (p.status !== "progress" || !p.file || !p.total) return; + totals.set(p.file, { loaded: p.loaded ?? 0, total: p.total }); + let loaded = 0; + let total = 0; + for (const v of totals.values()) { + loaded += v.loaded; + total += v.total; + } + onProgress(loaded, total); + }; + const m = (await t.SamModel.from_pretrained(paths.samModelId, { + dtype: "q8", + device: "wasm", + progress_callback, + })) as unknown as SamModel; + const pr = (await t.AutoProcessor.from_pretrained(paths.samModelId, { + progress_callback, + })) as unknown as SamProcessor; + lib = t; + model = m; + processor = pr; + return { lib: t, model: m, processor: pr }; +} + +function rawImageOf(t: Transformers, bitmap: ImageBitmap) { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("no 2d context"); + ctx.drawImage(bitmap, 0, 0); + const data = ctx.getImageData(0, 0, bitmap.width, bitmap.height); + return new t.RawImage(data.data, bitmap.width, bitmap.height, 4); +} + +async function embed( + bitmap: ImageBitmap, + modelBaseUrl: string, + onProgress: (l: number, t: number) => void, +): Promise { + const { lib: t, model: m, processor: pr } = await load(modelBaseUrl, onProgress); + const raw = rawImageOf(t, bitmap); + const t0 = performance.now(); + const inputs = await pr(raw); + const embeddings = await m.get_image_embeddings(inputs); + embedded = { inputs, embeddings }; + return performance.now() - t0; +} + +async function segment(x: number, y: number) { + if (!embedded || !lib || !model || !processor) throw new Error("not embedded"); + const t0 = performance.now(); + const { inputs, embeddings } = embedded; + const reshaped = inputs.reshaped_input_sizes[0]!; // [h, w] + // タップ位置は正規化座標 → 埋め込みに使った縮小後の px + const input_points = new lib.Tensor( + "float32", + [x * reshaped[1]!, y * reshaped[0]!], + [1, 1, 1, 2], + ); + const input_labels = new lib.Tensor("int64", [1n], [1, 1, 1]); + const out = await model({ ...embeddings, input_points, input_labels }); + const masks = await processor.post_process_masks( + out.pred_masks, + inputs.original_sizes, + inputs.reshaped_input_sizes, + ); + const m = masks[0]!; // [1, 3, H, W] + const [, levels, h, w] = m.dims as [number, number, number, number]; + const result: BitmapMaskV3[] = []; + for (let k = 0; k < levels; k++) { + const bits = new Uint8Array(w * h); + for (let i = 0; i < w * h; i++) bits[i] = m.data[k * w * h + i] ? 1 : 0; + result.push(toBitmapMask(bits, w, h)); + } + return { masks: result, scores: Array.from(out.iou_scores.data), ms: performance.now() - t0 }; +} + +self.onmessage = async (e: MessageEvent) => { + const req = e.data; + const post = (m: SegmentResponse) => self.postMessage(m); + try { + if (req.type === "embed") { + try { + const ms = await embed(req.bitmap, req.modelBaseUrl, (loaded, total) => + post({ id: req.id, type: "progress", loaded, total }), + ); + post({ id: req.id, type: "embedded", ms }); + } finally { + req.bitmap.close(); + } + } else { + const r = await segment(req.x, req.y); + post({ id: req.id, type: "segmented", ...r }); + } + } catch (err) { + post({ id: req.id, type: "error", message: err instanceof Error ? err.message : String(err) }); + } +}; diff --git a/packages/editor-engine/src/load-image.ts b/packages/editor-engine/src/load-image.ts new file mode 100644 index 0000000..2971f4f --- /dev/null +++ b/packages/editor-engine/src/load-image.ts @@ -0,0 +1,57 @@ +import { + fitWithin, + MAX_EDIT_EDGE, + sniffImageFormat, + validateImageFile, + type ValidationError, +} from "./image-format.ts"; + +export type LoadedImage = { + bitmap: ImageBitmap; + blob: Blob; + name: string; + format: "png" | "jpeg"; + original: { width: number; height: number }; +}; + +export class ImageLoadError extends Error { + readonly reason: ValidationError | "decode_failed"; + constructor(reason: ValidationError | "decode_failed") { + super(reason); + this.name = "ImageLoadError"; + this.reason = reason; + } +} + +/** + * ファイルを検証してデコードし、長辺 4096px に収めた ImageBitmap を返す (docs/design/08 §3.2)。 + * EXIF の回転はここで解決する。 + */ +export async function loadImageFile(file: File): Promise { + const head = new Uint8Array(await file.slice(0, 16).arrayBuffer()); + const invalid = validateImageFile(file.size, head); + if (invalid) throw new ImageLoadError(invalid); + const format = sniffImageFormat(head); + if (!format) throw new ImageLoadError("unsupported_format"); + + let bitmap: ImageBitmap; + try { + bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); + } catch { + throw new ImageLoadError("decode_failed"); + } + + const original = { width: bitmap.width, height: bitmap.height }; + const fitted = fitWithin(bitmap.width, bitmap.height, MAX_EDIT_EDGE); + if (fitted.width !== bitmap.width || fitted.height !== bitmap.height) { + const canvas = new OffscreenCanvas(fitted.width, fitted.height); + const ctx = canvas.getContext("2d"); + if (!ctx) throw new ImageLoadError("decode_failed"); + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(bitmap, 0, 0, fitted.width, fitted.height); + bitmap.close(); + bitmap = await createImageBitmap(canvas); + } + + return { bitmap, blob: file, name: file.name, format, original }; +} diff --git a/packages/editor-engine/src/mask-math.test.ts b/packages/editor-engine/src/mask-math.test.ts new file mode 100644 index 0000000..a05dc52 --- /dev/null +++ b/packages/editor-engine/src/mask-math.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ELLIPSE_MASK, DEFAULT_GEOMETRY } from "@lumorphia/editor-recipe"; +import { canvasToImageUv, ellipseMaskValue, imageUvToCanvas } from "./mask-math.ts"; + +const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) < eps; +const size = { width: 200, height: 100 }; + +describe("ellipseMaskValue", () => { + const mask = { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 0.1, ry: 0.2, feather: 0.5 }; + + it("is 1 at the center and 0 outside the radius", () => { + expect(ellipseMaskValue({ x: 0.5, y: 0.5 }, mask, size)).toBe(1); + expect(ellipseMaskValue({ x: 0.5 + 0.11, y: 0.5 }, mask, size)).toBe(0); + expect(ellipseMaskValue({ x: 0.5, y: 0.5 + 0.21 }, mask, size)).toBe(0); + }); + + it("is 1 inside the un-feathered core and in between across the feather band", () => { + // feather 0.5 なら半径の 50% までが芯、そこから縁までなだらかに 0 へ + expect(ellipseMaskValue({ x: 0.5 + 0.04, y: 0.5 }, mask, size)).toBe(1); + const mid = ellipseMaskValue({ x: 0.5 + 0.075, y: 0.5 }, mask, size); + expect(mid).toBeGreaterThan(0); + expect(mid).toBeLessThan(1); + }); + + it("has a hard edge when feather is 0", () => { + const hard = { ...mask, feather: 0 }; + expect(ellipseMaskValue({ x: 0.5 + 0.099, y: 0.5 }, hard, size)).toBe(1); + expect(ellipseMaskValue({ x: 0.5 + 0.101, y: 0.5 }, hard, size)).toBe(0); + }); + + it("inverts", () => { + const inv = { ...mask, invert: true }; + expect(ellipseMaskValue({ x: 0.5, y: 0.5 }, inv, size)).toBe(0); + expect(ellipseMaskValue({ x: 0.9, y: 0.9 }, inv, size)).toBe(1); + }); + + it("rotates in pixel space so a 90 degree turn swaps the pixel radii", () => { + // rx 0.1 × 200px = 20px、ry 0.2 × 100px = 20px。回転しても円のまま + const circle = { ...mask, rotation: 90 }; + expect(ellipseMaskValue({ x: 0.5 + 0.095, y: 0.5 }, circle, size)).toBeGreaterThan(0); + // rx 0.1 × 200 = 20px、ry 0.05 × 100 = 5px の横長を 90 度回すと縦長 (x 方向は 5px = 0.025) + const tall = { ...mask, ry: 0.05, rotation: 90 }; + expect(ellipseMaskValue({ x: 0.5 + 0.03, y: 0.5 }, tall, size)).toBe(0); + expect(ellipseMaskValue({ x: 0.5, y: 0.5 + 0.15 }, tall, size)).toBeGreaterThan(0); + }); +}); + +describe("imageUvToCanvas / canvasToImageUv", () => { + it("is the identity offset by nothing when geometry is default", () => { + const p = imageUvToCanvas({ x: 0.25, y: 0.75 }, size, DEFAULT_GEOMETRY); + expect(p).toEqual({ x: 50, y: 75 }); + const uv = canvasToImageUv(p, size, DEFAULT_GEOMETRY); + expect(near(uv.x, 0.25) && near(uv.y, 0.75)).toBe(true); + }); + + it("maps the image's top-left corner to the canvas top-right after rotating 90 degrees", () => { + // 200x100 を 90 度回すとキャンバスは 100x200。左上 (0,0) は右上 (100,0) へ + const p = imageUvToCanvas({ x: 0, y: 0 }, size, { ...DEFAULT_GEOMETRY, rotation: 90 }); + expect(near(p.x, 100) && near(p.y, 0)).toBe(true); + }); + + it("mirrors x when flipped horizontally", () => { + const p = imageUvToCanvas({ x: 0.25, y: 0.5 }, size, { ...DEFAULT_GEOMETRY, flipH: true }); + expect(near(p.x, 150) && near(p.y, 50)).toBe(true); + }); + + it("round-trips through rotation, straighten and flip", () => { + const g = { ...DEFAULT_GEOMETRY, rotation: 270 as const, straighten: -7, flipH: true }; + for (const uv of [ + { x: 0.1, y: 0.2 }, + { x: 0.9, y: 0.9 }, + { x: 0.5, y: 0.5 }, + ]) { + const back = canvasToImageUv(imageUvToCanvas(uv, size, g), size, g); + expect(near(back.x, uv.x) && near(back.y, uv.y)).toBe(true); + } + }); +}); diff --git a/packages/editor-engine/src/mask-math.ts b/packages/editor-engine/src/mask-math.ts new file mode 100644 index 0000000..697af50 --- /dev/null +++ b/packages/editor-engine/src/mask-math.ts @@ -0,0 +1,67 @@ +import type { EllipseMaskV2, GeometryV1 } from "@lumorphia/editor-recipe"; +import { canvasSize, totalRotationDeg, type Size } from "./render/geometry.ts"; + +/** + * 部分補正のマスクと座標変換の CPU 参照実装 (#109)。 + * GLSL (render/local-adjust-filter.ts) はこの関数と同じ式を実装する。 + * マスクの座標は幾何を掛ける前の画像の正規化座標 (docs/design/04 §1.1)。 + */ + +export type Point = { x: number; y: number }; + +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); +const smoothstep = (e0: number, e1: number, x: number) => { + const t = clamp01((x - e0) / (e1 - e0)); + return t * t * (3 - 2 * t); +}; + +/** feather 0 でも smoothstep の edge0 == edge1 (未定義) にならないよう、僅かな幅を残す */ +export const MIN_FEATHER = 1e-4; + +/** + * 楕円マスクの値 (0..1)。回転は画素空間で掛ける (画像の縦横比に依存しない角度にするため)。 + * 中心からの距離を半径で割った d に対して、1 - feather までは 1、1 で 0。 + */ +export function ellipseMaskValue(uv: Point, mask: EllipseMaskV2, size: Size): number { + const px = (uv.x - mask.cx) * size.width; + const py = (uv.y - mask.cy) * size.height; + const rad = (-mask.rotation * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + const rx = (c * px - s * py) / (mask.rx * size.width); + const ry = (s * px + c * py) / (mask.ry * size.height); + const d = Math.hypot(rx, ry); + const feather = Math.max(mask.feather, MIN_FEATHER); + const v = 1 - smoothstep(1 - feather, 1, d); + return mask.invert ? 1 - v : v; +} + +/** + * 画像の正規化座標 → 幾何適用後のキャンバス座標 (px)。 + * PixiJS の Sprite (anchor 0.5、position = キャンバス中央、rotation、scale.x = flipH ? -1 : 1) と同じ順で掛ける。 + */ +export function imageUvToCanvas(uv: Point, source: Size, g: GeometryV1): Point { + const canvas = canvasSize(source, g); + const rad = (totalRotationDeg(g) * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + const lx = (uv.x - 0.5) * source.width * (g.flipH ? -1 : 1); + const ly = (uv.y - 0.5) * source.height; + return { + x: canvas.width / 2 + lx * c - ly * s, + y: canvas.height / 2 + lx * s + ly * c, + }; +} + +/** imageUvToCanvas の逆。範囲外 (画像の外) も返す。呼ぶ側で clamp する */ +export function canvasToImageUv(p: Point, source: Size, g: GeometryV1): Point { + const canvas = canvasSize(source, g); + const rad = (-totalRotationDeg(g) * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + const wx = p.x - canvas.width / 2; + const wy = p.y - canvas.height / 2; + const lx = (wx * c - wy * s) * (g.flipH ? -1 : 1); + const ly = wx * s + wy * c; + return { x: lx / source.width + 0.5, y: ly / source.height + 0.5 }; +} diff --git a/packages/editor-engine/src/render/adjust-filter.ts b/packages/editor-engine/src/render/adjust-filter.ts new file mode 100644 index 0000000..d3d8a59 --- /dev/null +++ b/packages/editor-engine/src/render/adjust-filter.ts @@ -0,0 +1,84 @@ +import { Filter, GlProgram } from "pixi.js"; +import type { AdjustV1 } from "@lumorphia/editor-recipe"; +import { normalizeAdjust } from "../adjust-math.ts"; +import { ADJUST_GLSL, FILTER_VERTEX } from "./adjust-glsl.ts"; + +// adjust-math.ts の CPU 実装と同じ式 (adjust-glsl.ts)。片方を変えたら必ずもう片方も変える。 + +const fragment = /* glsl */ ` +precision highp float; + +in vec2 vTextureCoord; +in vec2 vImageUv; +out vec4 finalColor; + +uniform sampler2D uTexture; + +uniform float uExposure; +uniform float uContrast; +uniform float uHighlights; +uniform float uShadows; +uniform float uTemperature; +uniform float uTint; +uniform float uVibrance; +uniform float uSaturation; + +${ADJUST_GLSL} + +void main(void) { + vec4 src = texture(uTexture, vTextureCoord); + // premultiplied alpha を戻す + vec3 rgb = src.a > 0.0 ? src.rgb / src.a : src.rgb; + rgb = adjustColor(rgb, uExposure, uContrast, uHighlights, uShadows, uTemperature, uTint, uVibrance, uSaturation); + finalColor = vec4(rgb * src.a, src.a); +} +`; + +export type AdjustUniforms = { + uExposure: { value: number; type: "f32" }; + uContrast: { value: number; type: "f32" }; + uHighlights: { value: number; type: "f32" }; + uShadows: { value: number; type: "f32" }; + uTemperature: { value: number; type: "f32" }; + uTint: { value: number; type: "f32" }; + uVibrance: { value: number; type: "f32" }; + uSaturation: { value: number; type: "f32" }; +}; + +export class AdjustFilter extends Filter { + constructor(adjust: AdjustV1) { + const n = normalizeAdjust(adjust); + super({ + glProgram: GlProgram.from({ vertex: FILTER_VERTEX, fragment, name: "prismtone-adjust" }), + resources: { + adjustUniforms: { + uExposure: { value: n.exposure, type: "f32" }, + uContrast: { value: n.contrast, type: "f32" }, + uHighlights: { value: n.highlights, type: "f32" }, + uShadows: { value: n.shadows, type: "f32" }, + uTemperature: { value: n.temperature, type: "f32" }, + uTint: { value: n.tint, type: "f32" }, + uVibrance: { value: n.vibrance, type: "f32" }, + uSaturation: { value: n.saturation, type: "f32" }, + } satisfies AdjustUniforms, + }, + // DevelopStage の前提: 領域 = 画像矩形、中間テクスチャの余白に触れない (docs/design/08 §3.3) + padding: 0, + antialias: "off", + resolution: 1, + }); + } + + setAdjust(adjust: AdjustV1): void { + const n = normalizeAdjust(adjust); + const u = this.resources.adjustUniforms.uniforms as Record; + u.uExposure = n.exposure; + u.uContrast = n.contrast; + u.uHighlights = n.highlights; + u.uShadows = n.shadows; + u.uTemperature = n.temperature; + u.uTint = n.tint; + u.uVibrance = n.vibrance; + u.uSaturation = n.saturation; + } +} diff --git a/packages/editor-engine/src/render/adjust-glsl.ts b/packages/editor-engine/src/render/adjust-glsl.ts new file mode 100644 index 0000000..ab7d943 --- /dev/null +++ b/packages/editor-engine/src/render/adjust-glsl.ts @@ -0,0 +1,83 @@ +// AdjustFilter と LocalAdjustFilter で共有する GLSL (#109)。 +// 色補正の式は adjust-math.ts の CPU 実装と同じ。片方を変えたら必ずもう片方も変える。 + +/** + * フィルタの頂点シェーダ。PixiJS v8 の既定 (defaultFilter.vert) と同じ位置計算に、 + * 画像の正規化座標 vImageUv を足したもの。 + * DevelopStage ではフィルタ領域 (uOutputFrame) が画像矩形そのものなので、aPosition (0..1) が + * そのまま画像の正規化座標になる。表示用の Sprite に直接フィルタを付けると領域が回転後の + * 外接矩形とビューポートに依存するので、この前提が崩れる (docs/design/08 §3.3) + */ +export const FILTER_VERTEX = /* glsl */ ` +in vec2 aPosition; +out vec2 vTextureCoord; +out vec2 vImageUv; + +uniform vec4 uInputSize; +uniform vec4 uOutputFrame; +uniform vec4 uOutputTexture; + +vec4 filterVertexPosition(void) { + vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy; + position.x = position.x * (2.0 / uOutputTexture.x) - 1.0; + position.y = position.y * (2.0 * uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z; + return vec4(position, 0.0, 1.0); +} + +vec2 filterTextureCoord(void) { + return aPosition * (uOutputFrame.zw * uInputSize.zw); +} + +void main(void) { + gl_Position = filterVertexPosition(); + vTextureCoord = filterTextureCoord(); + vImageUv = aPosition; +} +`; + +/** sRGB <-> linear と、8 項目の色補正 (docs/design/04 §4 の順) */ +export const ADJUST_GLSL = /* glsl */ ` +vec3 srgbToLinear(vec3 c) { + vec3 lo = c / 12.92; + vec3 hi = pow((c + 0.055) / 1.055, vec3(2.4)); + return mix(lo, hi, step(0.04045, c)); +} + +vec3 linearToSrgb(vec3 c) { + vec3 lo = c * 12.92; + vec3 hi = 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055; + return mix(lo, hi, step(0.0031308, c)); +} + +vec3 adjustColor( + vec3 rgb, + float exposure, float contrast, float highlights, float shadows, + float temperature, float tint, float vibrance, float saturation +) { + // --- linear --- + rgb = srgbToLinear(rgb); + rgb *= exp2(exposure); + rgb.r *= 1.0 + 0.25 * temperature; + rgb.b *= 1.0 - 0.25 * temperature; + rgb.g *= 1.0 - 0.25 * tint; + + float luma = dot(rgb, vec3(0.2126, 0.7152, 0.0722)); + float wh = smoothstep(0.3, 1.0, luma); + float ws = 1.0 - smoothstep(0.0, 0.5, luma); + rgb *= (1.0 + highlights * 0.5 * wh) * (1.0 + shadows * 0.5 * ws); + + // --- sRGB --- + rgb = linearToSrgb(clamp(rgb, 0.0, 1.0)); + + float cf = 1.0 + contrast * 0.8; + rgb = (rgb - 0.5) * cf + 0.5; + + float y = dot(rgb, vec3(0.299, 0.587, 0.114)); + float sat = max(rgb.r, max(rgb.g, rgb.b)) - min(rgb.r, min(rgb.g, rgb.b)); + float vf = 1.0 + vibrance * (1.0 - clamp(sat, 0.0, 1.0)); + rgb = mix(vec3(y), rgb, vf); + rgb = mix(vec3(y), rgb, 1.0 + saturation); + + return clamp(rgb, 0.0, 1.0); +} +`; diff --git a/packages/editor-engine/src/render/develop-stage.ts b/packages/editor-engine/src/render/develop-stage.ts new file mode 100644 index 0000000..281b0e0 --- /dev/null +++ b/packages/editor-engine/src/render/develop-stage.ts @@ -0,0 +1,152 @@ +import { Container, Rectangle, RenderTexture, Sprite, type Renderer, type Texture } from "pixi.js"; +import type { BrushStrokeV2, EditRecipe, LocalAdjustment } from "@lumorphia/editor-recipe"; +import { AdjustFilter } from "./adjust-filter.ts"; +import { LocalAdjustFilter } from "./local-adjust-filter.ts"; +import { MaskTexture } from "./mask-texture.ts"; +import type { Size } from "./geometry.ts"; + +/** + * 現像の段 (docs/design/08 §3.3、ADR-0021)。 + * 無変換の Sprite に [全体の補正, 部分補正...] のフィルタを掛け、画像座標のままの RenderTexture に描く。 + * 幾何 (回転・反転・トリミング) は表示の段 (EditorRenderer) がこのテクスチャに対して掛けるので、 + * マスクの座標は幾何の影響を受けない。 + * + * フィルタ領域を filterArea で画像矩形に固定するのが要。これで頂点シェーダの aPosition が + * そのまま画像の正規化座標になり、プレビュー (縮小) と書き出し (原寸) で同じマスクが同じ場所に掛かる。 + * レシピが変わったフレームだけ描き直す (dirty)。 + */ +export class DevelopStage { + readonly container = new Container(); + readonly texture: RenderTexture; + private readonly sprite: Sprite; + private readonly global: AdjustFilter; + private locals: LocalAdjustFilter[] = []; + /** テクスチャで持つマスク (ブラシ・多角形・ビットマップ、部分補正の id ごと)。マスクのオブジェクトが変わったら描き直す */ + private masks = new Map(); + private readonly source: Size; + private recipe: EditRecipe; + private previewMaskId: string | null = null; + dirty = true; + + constructor(source: Texture, size: Size, recipe: EditRecipe) { + this.recipe = recipe; + this.source = { width: source.width, height: source.height }; + this.sprite = new Sprite(source); + this.container.addChild(this.sprite); + this.texture = RenderTexture.create({ + width: size.width, + height: size.height, + resolution: 1, + antialias: false, + // 書き出しで原寸に resize する。dynamic でないと、表示側の Sprite が resize の update を購読せず + // (Sprite.mjs の texture setter)、四角形が古い寸法のまま描かれて周りが黒くなる + dynamic: true, + }); + this.global = new AdjustFilter(recipe.adjust); + this.setSize(size); + this.setRecipe(recipe); + } + + get size(): Size { + return { width: this.texture.width, height: this.texture.height }; + } + + /** 描く寸法 (整数)。プレビューは縮小、書き出しは原寸 */ + setSize(size: Size): void { + const width = Math.max(1, Math.round(size.width)); + const height = Math.max(1, Math.round(size.height)); + if (this.texture.width !== width || this.texture.height !== height) { + this.texture.resize(width, height); + } + this.sprite.width = width; + this.sprite.height = height; + // filterArea はローカル座標で、Pixi が worldTransform (上の width/height による縮小) を掛ける + // (FilterSystem._calculateFilterArea)。元寸で与えて、world で RenderTexture の寸法に一致させる。 + // 縮小した寸法を与えると、フィルタが画像の左上の一部しか描かない + const orig = this.sprite.texture.orig; + this.sprite.filterArea = new Rectangle(0, 0, orig.width, orig.height); + this.dirty = true; + } + + setRecipe(recipe: EditRecipe): void { + this.recipe = recipe; + this.global.setAdjust(recipe.adjust); + this.syncLocals(recipe.localAdjustments.filter((l) => l.visible)); + this.dirty = true; + } + + /** 選択中の部分補正の範囲を赤で重ねる (null で消す) */ + setMaskPreview(id: string | null): void { + if (this.previewMaskId === id) return; + this.previewMaskId = id; + this.syncLocals(this.recipe.localAdjustments.filter((l) => l.visible)); + this.dirty = true; + } + + /** 描きかけを捨て、レシピにあるストロークだけでマスクを描き直す */ + discardPreviewStroke(id: string): void { + const entry = this.masks.get(id); + if (!entry || entry.mask.kind === "ellipse") return; + entry.texture.set(entry.mask); + this.dirty = true; + } + + /** 描画中のストロークをマスクに足す (レシピに入れる前のプレビュー) */ + previewStroke(id: string, stroke: BrushStrokeV2): void { + const entry = this.masks.get(id); + if (!entry || entry.mask.kind === "ellipse") return; + entry.texture.addStroke(stroke, entry.mask.feather); + this.dirty = true; + } + + private syncLocals(locals: readonly LocalAdjustment[]): void { + while (this.locals.length > locals.length) this.locals.pop()?.destroy(); + while (this.locals.length < locals.length) { + this.locals.push(new LocalAdjustFilter(locals[this.locals.length]!, this.source)); + } + const alive = new Set(); + locals.forEach((l, i) => { + const filter = this.locals[i]!; + filter.setLocal(l, l.id === this.previewMaskId); + if (l.mask.kind !== "ellipse") { + alive.add(l.id); + let entry = this.masks.get(l.id); + if (!entry) { + entry = { mask: l.mask, texture: new MaskTexture(this.source) }; + entry.texture.set(l.mask); + this.masks.set(l.id, entry); + } else if (entry.mask !== l.mask) { + entry.mask = l.mask; + entry.texture.set(l.mask); + } + filter.setMaskTexture(entry.texture.texture.source); + } else { + filter.setMaskTexture(null); + } + }); + for (const [id, entry] of this.masks) { + if (!alive.has(id)) { + entry.texture.destroy(); + this.masks.delete(id); + } + } + this.sprite.filters = [this.global, ...this.locals]; + } + + render(renderer: Renderer): void { + renderer.render({ container: this.container, target: this.texture, clear: true }); + this.dirty = false; + } + + destroy(): void { + this.sprite.filters = []; + this.global.destroy(); + for (const f of this.locals) f.destroy(); + this.locals = []; + for (const entry of this.masks.values()) entry.texture.destroy(); + this.masks.clear(); + this.sprite.destroy(); + this.container.destroy(); + this.texture.destroy(true); + } +} diff --git a/packages/editor-engine/src/render/editor-renderer.ts b/packages/editor-engine/src/render/editor-renderer.ts new file mode 100644 index 0000000..20ba046 --- /dev/null +++ b/packages/editor-engine/src/render/editor-renderer.ts @@ -0,0 +1,497 @@ +// PixiJS は既定でシェーダーの uniform 同期に new Function (unsafe-eval) を使う。CSP で 'unsafe-eval' を +// 許さない代わりに、eval を使わない実装へ差し替える (RM-28)。pixi.js より先に読み込む必要がある +import "pixi.js/unsafe-eval"; +import { + Application, + Container, + Graphics, + Rectangle, + Sprite, + Texture, + TexturePool, + type WebGLRenderer, +} from "pixi.js"; +import type { BrushStrokeV2, EditRecipe, GeometryV1 } from "@lumorphia/editor-recipe"; +import { canvasToImageUv } from "../mask-math.ts"; +import { DevelopStage } from "./develop-stage.ts"; +import { canvasSize, cropRect, exportScale, totalRotationDeg, type Size } from "./geometry.ts"; +import { + clampPan, + DEFAULT_VIEWPORT, + panBy, + place, + zoomAt, + ZOOM_STEP, + type Viewport, +} from "./viewport.ts"; + +export type ExportFormat = "image/webp" | "image/jpeg" | "image/png"; + +export type ExportOptions = { + format?: ExportFormat; + quality?: number; + maxEdge?: number; +}; + +export type ViewRect = { x: number; y: number; width: number; height: number; scale: number }; + +export type Benchmark = { + developMs: number; + exportMs: number; + textureBytes: number; + previewSize: Size; +}; + +export const EXPORT_MAX_EDGE = 4096; +/** プレビュー用の現像テクスチャの長辺。書き出しは原寸で描き直す */ +export const PREVIEW_MAX_EDGE = 2048; + +/** 長辺を maxEdge に収めた寸法 (整数)。 */ +export function fitEdge(size: Size, maxEdge: number): Size { + const edge = Math.max(size.width, size.height); + if (edge <= maxEdge) return { width: Math.round(size.width), height: Math.round(size.height) }; + const s = maxEdge / edge; + return { + width: Math.max(1, Math.round(size.width * s)), + height: Math.max(1, Math.round(size.height * s)), + }; +} + +/** + * PixiJS による編集プレビューと書き出し (docs/design/08 §3.3-3.4, ADR-0021)。 + * - 現像の段 (DevelopStage): 無変換の Sprite に [全体の補正, 部分補正...] を掛けて画像座標の + * RenderTexture に描く。レシピが変わったフレームだけ + * - 表示の段 (ここ): そのテクスチャの Sprite に幾何 (回転・反転) を Container の transform で掛ける。 + * crop は書き出し時の frame + * - プレビューは幾何適用後のキャンバス全体を表示し、crop 枠は DOM 側で描く + * - プレビューの現像は長辺 2048 まで、書き出しは原寸 (4096 まで) で描き直す + */ +export class EditorRenderer { + private readonly app: Application; + private readonly host: HTMLElement; + + private constructor(app: Application, host: HTMLElement) { + this.app = app; + this.host = host; + } + + private readonly stage = new Container(); + private readonly image = new Container(); + private sprite: Sprite | null = null; + /** 比較用の元画像 (フィルタなし)。sprite の下に同じ変換で置き、比較中だけ見せる */ + private original: Sprite | null = null; + /** 比較中、現像後 (sprite) を境界より右だけに見せるマスク */ + private compareMask: Graphics | null = null; + private develop: DevelopStage | null = null; + /** 元画像のテクスチャ。現像の段と比較用の original が共有する */ + private sourceTexture: Texture | null = null; + private source: Size = { width: 1, height: 1 }; + private previewMaskId: string | null = null; + private geometry: GeometryV1 | null = null; + private comparing = false; + /** 比較の境界。0 = 全部現像後、1 = 全部元画像 (左が元画像、右が現像後) */ + private comparePosition = 0.5; + private resizeObserver: ResizeObserver | null = null; + /** 表示のズームと移動。レシピではなく画面の状態 (docs/design/08 §3.3) */ + private viewport: Viewport = DEFAULT_VIEWPORT; + /** 置き直すたびに呼ぶ。DOM のオーバーレイが viewRect を追うための唯一の通知 */ + onView: ((rect: ViewRect) => void) | null = null; + + static async create(host: HTMLElement): Promise { + const app = new Application(); + await app.init({ + resizeTo: host, + backgroundAlpha: 0, + antialias: true, + autoDensity: true, + resolution: Math.min(window.devicePixelRatio || 1, 2), + preference: "webgl", + }); + // resizeTo が canvas に px の幅・高さを書く。通常フローに置くとその幅が親の最小幅になり、 + // 窓を狭めても親が縮まない。絶対配置にしてレイアウトに影響させない + app.canvas.style.position = "absolute"; + app.canvas.style.inset = "0"; + host.appendChild(app.canvas); + const r = new EditorRenderer(app, host); + app.stage.addChild(r.stage); + r.stage.addChild(r.image); + // resizeTo は window の resize しか見ない。ツールバーの折り返しなどでホストだけ変わったときも + // canvas を合わせてから置き直す + r.resizeObserver = new ResizeObserver(() => { + app.resize(); + r.fit(); + }); + r.resizeObserver.observe(host); + // TickerPlugin の描画 (LOW) より先に走り、レシピが変わっていれば現像の段を描く + app.ticker.add(r.tick); + return r; + } + + private readonly tick = (): void => { + if (this.develop?.dirty) this.develop.render(this.app.renderer); + }; + + /** GPU が扱えるテクスチャの上限。書き出しの原寸をこれで抑える */ + get maxTextureSize(): number { + const gl = (this.app.renderer as WebGLRenderer).gl as WebGL2RenderingContext | undefined; + return gl ? (gl.getParameter(gl.MAX_TEXTURE_SIZE) as number) : EXPORT_MAX_EDGE; + } + + get canvasElement(): HTMLCanvasElement { + return this.app.canvas as HTMLCanvasElement; + } + + setImage(bitmap: ImageBitmap, recipe: EditRecipe): void { + this.clearImage(); + const texture = Texture.from(bitmap); + this.sourceTexture = texture; + const original = new Sprite(texture); + original.anchor.set(0.5); + original.visible = false; + this.original = original; + this.image.addChild(original); + this.source = { width: bitmap.width, height: bitmap.height }; + this.viewport = DEFAULT_VIEWPORT; + this.develop = new DevelopStage(texture, this.previewSize, recipe); + const sprite = new Sprite(this.develop.texture); + sprite.anchor.set(0.5); + this.sprite = sprite; + this.image.addChild(sprite); + this.setRecipe(recipe); + } + + private get previewSize(): Size { + return fitEdge(this.source, PREVIEW_MAX_EDGE); + } + + private clearImage(): void { + if (this.compareMask) { + this.compareMask.destroy(); + this.compareMask = null; + } + if (this.original) { + this.image.removeChild(this.original); + this.original.destroy(); + this.original = null; + } + if (this.sprite) { + this.image.removeChild(this.sprite); + this.sprite.destroy(); + this.sprite = null; + } + if (this.develop) { + this.develop.destroy(); + this.develop = null; + } + this.sourceTexture?.destroy(true); + this.sourceTexture = null; + } + + setRecipe(recipe: EditRecipe): void { + if (!this.sprite || !this.develop) return; + this.develop.setRecipe(recipe); + this.geometry = recipe.geometry; + this.placeSprites(recipe.geometry); + this.fit(); + this.applyCompare(); + } + + /** + * 計測用 (docs/spikes の部分補正の性能、#109): 合成の段を frames 回描いたときの 1 回あたりの ms と、 + * 書き出し 1 回の ms、GPU に載っているテクスチャの概算バイト数。開発と E2E のフックからだけ呼ぶ。 + * 描いたテクスチャから 1px 読み戻して GPU の完了まで待つので、実際のフレーム時間より重めに出る + * (gl.finish() は ANGLE で待たないことがある) + */ + async benchmark(recipe: EditRecipe, frames = 30): Promise { + if (!this.develop) throw new Error("no image loaded"); + this.setRecipe(recipe); + const t0 = performance.now(); + for (let i = 0; i < frames; i++) { + this.develop.dirty = true; + this.develop.render(this.app.renderer); + this.app.renderer.extract.pixels({ + target: this.develop.texture, + frame: new Rectangle(0, 0, 1, 1), + }); + } + const developMs = (performance.now() - t0) / frames; + const t1 = performance.now(); + await this.export(recipe, { format: "image/png" }); + const exportMs = performance.now() - t1; + const textureBytes = this.managedTextureBytes(); + return { developMs, exportMs, textureBytes, previewSize: this.develop.size }; + } + + /** GL に載っているテクスチャの概算 (RGBA8 として w × h × 4)。managedTextures は 8.15 で deprecated なので防御的に */ + private managedTextureBytes(): number { + const system = (this.app.renderer as WebGLRenderer).texture as unknown as { + _managedTextures?: { + items?: Record; + }; + }; + const items = Object.values(system._managedTextures?.items ?? {}); + return items.reduce((sum, t) => sum + (t ? t.pixelWidth * t.pixelHeight * 4 : 0), 0); + } + + /** ブラシで描いている途中のストロークを、レシピに入れる前にマスクへ足す */ + previewStroke(id: string, stroke: BrushStrokeV2): void { + this.develop?.previewStroke(id, stroke); + } + + /** 描きかけのストロークを捨てる (ピンチに切り替わったとき) */ + discardPreviewStroke(id: string): void { + this.develop?.discardPreviewStroke(id); + } + + /** 選択中の部分補正の範囲を赤で重ねる (null で消す) */ + setMaskPreview(id: string | null): void { + this.previewMaskId = id; + this.develop?.setMaskPreview(id); + } + + /** + * 幾何を Sprite の transform に写す。現像テクスチャは縮小されていることがあるので、 + * 表示上の大きさが元画像の px になるようスケールで戻す (キャンバス座標は常に元画像の px) + */ + private placeSprites(geometry: GeometryV1): void { + const size = canvasSize(this.source, geometry); + const rotation = (totalRotationDeg(geometry) * Math.PI) / 180; + const flip = geometry.flipH ? -1 : 1; + if (this.sprite && this.develop) { + const dev = this.develop.size; + this.sprite.rotation = rotation; + this.sprite.scale.set( + (flip * this.source.width) / dev.width, + this.source.height / dev.height, + ); + this.sprite.position.set(size.width / 2, size.height / 2); + } + if (this.original) { + this.original.rotation = rotation; + this.original.scale.set(flip, 1); + this.original.position.set(size.width / 2, size.height / 2); + } + } + + /** 比較のオン・オフと境界の位置。左が元画像、右が現像後 */ + setCompare(on: boolean, position: number = this.comparePosition): void { + this.comparing = on; + this.comparePosition = Math.min(1, Math.max(0, position)); + this.applyCompare(); + } + + private applyCompare(): void { + if (!this.sprite || !this.original) return; + if (!this.comparing) { + this.original.visible = false; + this.sprite.mask = null; + this.compareMask?.destroy(); + this.compareMask = null; + return; + } + const size = this.canvasSize; + const x = size.width * this.comparePosition; + if (!this.compareMask) { + this.compareMask = new Graphics(); + this.image.addChild(this.compareMask); + } + this.compareMask + .clear() + .rect(x, 0, Math.max(0, size.width - x), size.height) + .fill(0xffffff); + this.sprite.mask = this.compareMask; + this.original.visible = true; + } + + /** 幾何適用後のキャンバスサイズ (crop 前)。DOM の crop 枠の基準になる。 */ + get canvasSize(): Size { + return this.geometry ? canvasSize(this.source, this.geometry) : this.source; + } + + /** ホスト内でキャンバスが占める矩形 (CSS px)。DOM オーバーレイの配置に使う。 */ + get viewRect(): ViewRect { + const size = this.canvasSize; + const s = this.stage.scale.x; + return { + x: this.stage.x, + y: this.stage.y, + width: size.width * s, + height: size.height * s, + scale: s, + }; + } + + private get hostSize(): Size { + return { width: this.host.clientWidth, height: this.host.clientHeight }; + } + + /** 現在のズームと移動でステージを置く。ホストの寸法が変わったときは移動を抑え直す */ + fit(): void { + if (!this.sprite) return; + const host = this.hostSize; + if (host.width === 0 || host.height === 0) return; + this.viewport = clampPan(this.canvasSize, host, this.viewport); + const p = place(this.canvasSize, host, this.viewport); + this.stage.scale.set(p.scale); + this.stage.position.set(p.x, p.y); + this.onView?.(this.viewRect); + } + + /** + * テスト用: プレビュー (合成の段のテクスチャ) の画素を画像の正規化座標で読む。 + * 書き出し (原寸) ではなく縮小プレビューが正しく描けているかを見るため + */ + previewPixels(points: readonly { x: number; y: number }[]): number[][] { + if (!this.develop) throw new Error("no image loaded"); + if (this.develop.dirty) this.develop.render(this.app.renderer); + const { width, height } = this.develop.size; + const px = this.app.renderer.extract.pixels({ target: this.develop.texture }); + return points.map((p) => { + const x = Math.min(width - 1, Math.floor(p.x * width)); + const y = Math.min(height - 1, Math.floor(p.y * height)); + const i = (y * px.width + x) * 4; + return [px.pixels[i]!, px.pixels[i + 1]!, px.pixels[i + 2]!]; + }); + } + + /** + * 今見えている範囲の中央 (画像の正規化座標、0..1 に収める) と、見えている範囲の大きさ (画像 px)。 + * 円形マスクを「画像の中央」ではなく「今見ている場所」に置くため (docs/design/08 §3.3) + */ + get visibleCenter(): { uv: { x: number; y: number }; visible: Size } { + const host = this.hostSize; + const rect = this.viewRect; + // ホストと画像の重なりの中央 (キャンバス座標) + const x0 = Math.max(0, rect.x); + const y0 = Math.max(0, rect.y); + const x1 = Math.min(host.width, rect.x + rect.width); + const y1 = Math.min(host.height, rect.y + rect.height); + const cx = ((x0 + x1) / 2 - rect.x) / rect.scale; + const cy = ((y0 + y1) / 2 - rect.y) / rect.scale; + const uv = this.geometry + ? canvasToImageUv({ x: cx, y: cy }, this.source, this.geometry) + : { x: 0.5, y: 0.5 }; + return { + uv: { x: Math.min(1, Math.max(0, uv.x)), y: Math.min(1, Math.max(0, uv.y)) }, + visible: { width: (x1 - x0) / rect.scale, height: (y1 - y0) / rect.scale }, + }; + } + + /** 元画像の px に対する表示倍率 (1 = 等倍) */ + get displayScale(): number { + return this.stage.scale.x; + } + + get zoom(): number { + return this.viewport.zoom; + } + + /** 倍率を factor 倍する。anchor (ホスト内の CSS px) の下の点は動かない */ + zoomBy(factor: number, anchor?: { x: number; y: number }): void { + if (!this.sprite) return; + this.viewport = zoomAt( + this.canvasSize, + this.hostSize, + this.viewport, + this.viewport.zoom * factor, + anchor, + ); + this.fit(); + } + + /** フィット表示に対する倍率を直接指定する (1 = フィット)。anchor はホストの中央 */ + setZoom(zoom: number): void { + if (!this.sprite) return; + this.viewport = zoomAt(this.canvasSize, this.hostSize, this.viewport, zoom); + this.fit(); + } + + /** 元画像の等倍 (1 画像 px = 1 CSS px) にする */ + zoomToActual(): void { + if (!this.sprite) return; + const fit = place(this.canvasSize, this.hostSize, DEFAULT_VIEWPORT).scale; + this.setZoom(1 / fit); + } + + resetView(): void { + this.viewport = DEFAULT_VIEWPORT; + this.fit(); + } + + /** CSS px だけ表示を動かす */ + panBy(dx: number, dy: number): void { + if (!this.sprite) return; + this.viewport = panBy(this.canvasSize, this.hostSize, this.viewport, dx, dy); + this.fit(); + } + + /** ホイール 1 ノッチぶんの倍率 */ + static readonly ZOOM_STEP = ZOOM_STEP; + + async export(recipe: EditRecipe, opts: ExportOptions = {}): Promise { + if (!this.sprite || !this.develop) throw new Error("no image loaded"); + const wasComparing = this.comparing; + this.setCompare(false); + this.setMaskPreview(null); + this.setRecipe(recipe); + + const full = this.canvasSize; + const rect = cropRect(full, recipe.geometry); + const scale = exportScale(rect, opts.maxEdge ?? EXPORT_MAX_EDGE); + + // 現像の段を原寸で描き直し、表示用のスケールを外して原寸で切り出す + const develop = this.develop; + develop.setSize(fitEdge(this.source, Math.min(EXPORT_MAX_EDGE, this.maxTextureSize))); + develop.render(this.app.renderer); + this.placeSprites(recipe.geometry); + const saved = { x: this.stage.x, y: this.stage.y, s: this.stage.scale.x }; + this.stage.scale.set(1); + this.stage.position.set(0, 0); + try { + const canvas = this.app.renderer.extract.canvas({ + target: this.image, + frame: new Rectangle(rect.x, rect.y, rect.width, rect.height), + resolution: scale, + clearColor: "#000000", + }) as HTMLCanvasElement; + const format = opts.format ?? ((await supportsWebp()) ? "image/webp" : "image/jpeg"); + return await toBlob(canvas, format, opts.quality ?? 0.92); + } finally { + this.stage.scale.set(saved.s); + this.stage.position.set(saved.x, saved.y); + // プレビュー寸法に戻す。原寸のフィルタ用テクスチャはプールに残る (GC されない) ので捨てる + develop.setSize(this.previewSize); + develop.render(this.app.renderer); + this.placeSprites(recipe.geometry); + TexturePool.clear(true); + this.setCompare(wasComparing); + this.setMaskPreview(this.previewMaskId); + } + } + + destroy(): void { + this.resizeObserver?.disconnect(); + this.app.ticker.remove(this.tick); + this.clearImage(); + this.app.destroy(true, { children: true }); + } +} + +function toBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise { + return new Promise((resolve, reject) => { + canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("toBlob failed"))), type, quality); + }); +} + +let webpSupport: Promise | null = null; +export function supportsWebp(): Promise { + if (!webpSupport) { + webpSupport = new Promise((resolve) => { + const c = document.createElement("canvas"); + c.width = 1; + c.height = 1; + c.toBlob((b) => resolve(b?.type === "image/webp"), "image/webp"); + }); + } + return webpSupport; +} diff --git a/packages/editor-engine/src/render/geometry.test.ts b/packages/editor-engine/src/render/geometry.test.ts new file mode 100644 index 0000000..8a6175b --- /dev/null +++ b/packages/editor-engine/src/render/geometry.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_GEOMETRY } from "@lumorphia/editor-recipe"; +import { + aspectRatio, + canvasSize, + centeredCrop, + cropRect, + exportScale, + rotatedBounds, +} from "./geometry.ts"; + +describe("rotatedBounds", () => { + it("swaps width and height at 90 degrees", () => { + expect(rotatedBounds({ width: 1920, height: 1080 }, 90)).toEqual({ width: 1080, height: 1920 }); + }); + it("is unchanged at 0 and 180", () => { + expect(rotatedBounds({ width: 1920, height: 1080 }, 0)).toEqual({ width: 1920, height: 1080 }); + expect(rotatedBounds({ width: 1920, height: 1080 }, 180)).toEqual({ + width: 1920, + height: 1080, + }); + }); + it("grows for small straighten angles", () => { + const b = rotatedBounds({ width: 1000, height: 1000 }, 10); + expect(b.width).toBeGreaterThan(1000); + expect(b.height).toBeGreaterThan(1000); + }); +}); + +describe("canvasSize / cropRect", () => { + const src = { width: 1920, height: 1080 }; + it("uses the whole canvas without crop", () => { + expect(cropRect(canvasSize(src, DEFAULT_GEOMETRY), DEFAULT_GEOMETRY)).toEqual({ + x: 0, + y: 0, + width: 1920, + height: 1080, + }); + }); + it("converts normalized crop to pixels and clamps to the canvas", () => { + const g = { ...DEFAULT_GEOMETRY, crop: { x: 0.5, y: 0.5, w: 0.75, h: 0.75 } }; + expect(cropRect(src, g)).toEqual({ x: 960, y: 540, width: 960, height: 540 }); + }); + it("never yields a zero-sized rect", () => { + const g = { ...DEFAULT_GEOMETRY, crop: { x: 0, y: 0, w: 0, h: 0 } }; + const r = cropRect(src, g); + expect(r.width).toBeGreaterThanOrEqual(1); + expect(r.height).toBeGreaterThanOrEqual(1); + }); +}); + +describe("aspect helpers", () => { + it("parses ratios", () => { + expect(aspectRatio("16:9")).toBeCloseTo(16 / 9); + expect(aspectRatio("free")).toBeUndefined(); + expect(aspectRatio(null)).toBeUndefined(); + }); + it("centers a 1:1 crop inside a landscape canvas", () => { + const c = centeredCrop({ width: 1920, height: 1080 }, 1); + expect(c.h).toBe(1); + expect(c.w).toBeCloseTo(1080 / 1920); + expect(c.x).toBeCloseTo((1 - 1080 / 1920) / 2); + }); + it("centers a 9:16 crop inside a landscape canvas", () => { + const c = centeredCrop({ width: 1920, height: 1080 }, 9 / 16); + expect(c.h).toBe(1); + expect(c.w).toBeCloseTo(9 / 16 / (1920 / 1080)); + }); +}); + +describe("exportScale", () => { + it("does not upscale", () => expect(exportScale({ width: 100, height: 50 }, 4096)).toBe(1)); + it("scales the long edge to the max", () => + expect(exportScale({ width: 8192, height: 100 }, 4096)).toBe(0.5)); +}); diff --git a/packages/editor-engine/src/render/geometry.ts b/packages/editor-engine/src/render/geometry.ts new file mode 100644 index 0000000..e7d1fe1 --- /dev/null +++ b/packages/editor-engine/src/render/geometry.ts @@ -0,0 +1,72 @@ +import type { GeometryV1 } from "@lumorphia/editor-recipe"; + +/** + * 幾何変換の純粋な計算部分。PixiJS には依存しない (単体テスト対象)。 + * 座標系: 回転・水平補正・反転を適用した後の「キャンバス」上で crop を 0..1 の正規化座標として持つ。 + */ + +export type Size = { width: number; height: number }; +export type Rect = { x: number; y: number; width: number; height: number }; + +/** 直角回転と微調整回転を合わせた角度 (度)。 */ +export function totalRotationDeg(g: GeometryV1): number { + return g.rotation + g.straighten; +} + +/** 元画像を angle 度回転したときの外接矩形サイズ。 */ +export function rotatedBounds(src: Size, angleDeg: number): Size { + const rad = (angleDeg * Math.PI) / 180; + const c = Math.abs(Math.cos(rad)); + const s = Math.abs(Math.sin(rad)); + return { + width: Math.round(src.width * c + src.height * s), + height: Math.round(src.width * s + src.height * c), + }; +} + +/** 幾何適用後のキャンバスサイズ (crop 前)。 */ +export function canvasSize(src: Size, g: GeometryV1): Size { + return rotatedBounds(src, totalRotationDeg(g)); +} + +/** crop を実ピクセルの矩形にする。crop が無ければキャンバス全体。 */ +export function cropRect(canvas: Size, g: GeometryV1): Rect { + if (!g.crop) return { x: 0, y: 0, width: canvas.width, height: canvas.height }; + const x = Math.round(g.crop.x * canvas.width); + const y = Math.round(g.crop.y * canvas.height); + const width = Math.max(1, Math.round(g.crop.w * canvas.width)); + const height = Math.max(1, Math.round(g.crop.h * canvas.height)); + return { + x, + y, + width: Math.min(width, canvas.width - x), + height: Math.min(height, canvas.height - y), + }; +} + +/** アスペクト指定文字列 ("16:9" 等) を比率に変換する。free / null は undefined。 */ +export function aspectRatio(aspect: GeometryV1["aspect"]): number | undefined { + if (!aspect || aspect === "free") return undefined; + const [w, h] = aspect.split(":").map(Number); + if (!w || !h) return undefined; + return w / h; +} + +/** 指定比率でキャンバス中央に収まる最大の crop (正規化座標)。 */ +export function centeredCrop(canvas: Size, ratio: number): NonNullable { + const canvasRatio = canvas.width / canvas.height; + let w = 1; + let h = 1; + if (ratio > canvasRatio) { + h = canvasRatio / ratio; + } else { + w = ratio / canvasRatio; + } + return { x: (1 - w) / 2, y: (1 - h) / 2, w, h }; +} + +/** 出力サイズを長辺 maxEdge に収めるスケール。 */ +export function exportScale(rect: Size, maxEdge: number): number { + const edge = Math.max(rect.width, rect.height); + return edge > maxEdge ? maxEdge / edge : 1; +} diff --git a/packages/editor-engine/src/render/local-adjust-filter.ts b/packages/editor-engine/src/render/local-adjust-filter.ts new file mode 100644 index 0000000..b49fa8d --- /dev/null +++ b/packages/editor-engine/src/render/local-adjust-filter.ts @@ -0,0 +1,265 @@ +import { Filter, GlProgram, Texture, type TextureSource } from "pixi.js"; +import type { LocalAdjustment } from "@lumorphia/editor-recipe"; +import { MIN_FEATHER } from "../mask-math.ts"; +import type { Size } from "./geometry.ts"; +import { ADJUST_GLSL, FILTER_VERTEX } from "./adjust-glsl.ts"; + +// 部分補正 1 件 = フィルタ 1 パス (#109)。マスク (mask-math.ts / brush-raster.ts) と色補正 +// (adjust-math.ts) の CPU 実装と同じ式。片方を変えたら必ずもう片方も変える。 +// シャープ (3x3 アンシャープ) と美肌 (5x5 の輪郭を残す平滑化) は近傍を見るので CPU 参照は無く、 +// #184 のぼかし・bloom・周辺減光・clarity は adjust-math.ts と E2E で同じ式を照合する。 +// 近傍の間隔は元画像の px で決める (uSourceSize) ので、プレビュー (縮小) と書き出し (原寸) で +// 同じ広がりになる。 + +/** 近傍サンプルの間隔 (元画像の px)。5x5 で ±2 タップ = ±4px */ +export const KERNEL_STEP_PX = 2; + +const fragment = /* glsl */ ` +precision highp float; +#define KERNEL_STEP ${KERNEL_STEP_PX.toFixed(1)} + +in vec2 vTextureCoord; +in vec2 vImageUv; +out vec4 finalColor; + +uniform sampler2D uTexture; +uniform sampler2D uMask; // テクスチャのマスク (r。ブラシ・多角形・ビットマップ、invert 適用済み)。楕円のときは白 1px +uniform vec4 uInputSize; // .zw = 1 / 中間テクスチャの px +uniform vec4 uInputClamp; // 近傍サンプルの範囲 (中間テクスチャの余白に触れない) +uniform vec4 uOutputFrame; // .zw = 画像の px サイズ (領域 = 画像矩形) +uniform vec2 uSourceSize; // 元画像の px (近傍の間隔を原寸基準にする) +uniform float uMaskMode; // 0 = 楕円 (解析的)、1 = テクスチャ (brush-raster.ts が invert まで済ませている) +uniform float uSharpen; // 0..1 +uniform float uSmooth; // 0..0.6 +uniform float uBlur; // 0..32 (元画像 px) +uniform float uBloom; // 0..1 +uniform float uVignette; // 0..1 +uniform float uClarity; // -1..1 + +uniform float uExposure; +uniform float uContrast; +uniform float uHighlights; +uniform float uShadows; +uniform float uTemperature; +uniform float uTint; +uniform float uSaturation; +uniform float uAmount; // 効果量 0..1 +uniform vec2 uCenter; // 楕円の中心 (正規化) +uniform vec2 uRadii; // 半径 (幅・高さに対する比) +uniform float uRotation; // rad +uniform float uFeather; // 0..1 +uniform float uInvert; // 0 / 1 (楕円だけ。テクスチャは CPU 側で反転済み) +uniform float uShowMask; // 1 なら選択範囲を赤で重ねる (UI のマスク表示) + +${ADJUST_GLSL} + +vec3 tap(vec2 offsetPx) { + // 元画像の px → 中間テクスチャの座標: 画像 uv 1 = uOutputFrame.zw * uInputSize.zw + vec2 d = offsetPx / uSourceSize * (uOutputFrame.zw * uInputSize.zw); + vec4 c = texture(uTexture, clamp(vTextureCoord + d, uInputClamp.xy, uInputClamp.zw)); + return c.a > 0.0 ? c.rgb / c.a : c.rgb; +} + +// 3x3 の平均との差を足す +vec3 sharpen(vec3 rgb) { + vec3 sum = vec3(0.0); + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + sum += tap(vec2(float(x), float(y)) * KERNEL_STEP); + } + } + return rgb + (rgb - sum / 9.0) * uSharpen; +} + +// 5x5 の bilateral。輝度が近い画素だけ平均する (輪郭を残す) +vec3 smoothSkin(vec3 rgb) { + float y0 = dot(rgb, vec3(0.299, 0.587, 0.114)); + vec3 sum = vec3(0.0); + float wsum = 0.0; + for (int y = -2; y <= 2; y++) { + for (int x = -2; x <= 2; x++) { + vec3 c = tap(vec2(float(x), float(y)) * KERNEL_STEP); + float dy = dot(c, vec3(0.299, 0.587, 0.114)) - y0; + float ws = exp(-float(x * x + y * y) / 8.0); + float wr = exp(-(dy * dy) / 0.02); + float w = ws * wr; + sum += c * w; + wsum += w; + } + } + return sum / wsum; +} + +// 背景ぼかし・bloom・clarity で共有する 3x3 近傍。半径は元画像 px。 +// bloom は 0.65 より明るい成分だけを集める。 +void spatialNeighborhood(float radius, out vec3 average, out vec3 glow) { + vec3 sum = vec3(0.0); + vec3 bright = vec3(0.0); + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + vec3 c = tap(vec2(float(x), float(y)) * radius); + sum += c; + bright += max(c - vec3(0.65), vec3(0.0)) / 0.35; + } + } + average = sum / 9.0; + glow = bright / 9.0; +} + +float ellipseMask(void) { + vec2 p = (vImageUv - uCenter) * uOutputFrame.zw; + float c = cos(-uRotation); + float s = sin(-uRotation); + vec2 q = vec2(c * p.x - s * p.y, s * p.x + c * p.y) / (uRadii * uOutputFrame.zw); + float d = length(q); + float v = 1.0 - smoothstep(1.0 - uFeather, 1.0, d); + return mix(v, 1.0 - v, uInvert); +} + +void main(void) { + vec4 src = texture(uTexture, vTextureCoord); + float mask = uMaskMode > 0.5 ? texture(uMask, vImageUv).r : ellipseMask(); + float m = mask * uAmount; + vec3 rgb = src.a > 0.0 ? src.rgb / src.a : src.rgb; + if (m > 0.0) { + vec3 adjusted = rgb; + float radius = max(uBlur, max(uBloom > 0.0 ? 8.0 : 0.0, abs(uClarity) > 0.0 ? 4.0 : 0.0)); + if (radius > 0.0) { + vec3 average; + vec3 glow; + spatialNeighborhood(radius, average, glow); + if (uBlur > 0.0) adjusted = average; + if (abs(uClarity) > 0.0) adjusted = clamp(adjusted + (rgb - average) * uClarity, 0.0, 1.0); + if (uBloom > 0.0) adjusted = clamp(adjusted + glow * uBloom * 0.5, 0.0, 1.0); + } + if (uSmooth > 0.0) adjusted = mix(adjusted, smoothSkin(adjusted), uSmooth); + if (uSharpen > 0.0) adjusted = sharpen(adjusted); + adjusted = adjustColor(clamp(adjusted, 0.0, 1.0), uExposure, uContrast, uHighlights, uShadows, uTemperature, uTint, 0.0, uSaturation); + if (uVignette > 0.0) { + vec2 p = (vImageUv - vec2(0.5)) * 2.0; + float d = dot(p, p) / 2.0; + adjusted *= 1.0 - uVignette * 0.65 * smoothstep(0.2, 1.0, d); + } + rgb = mix(rgb, adjusted, m); + } + if (uShowMask > 0.5) { + rgb = mix(rgb, vec3(1.0, 0.15, 0.15), mask * 0.5); + } + finalColor = vec4(rgb * src.a, src.a); +} +`; + +type F32 = { value: number; type: "f32" }; +type Vec2 = { value: Float32Array; type: "vec2" }; + +type LocalUniforms = { + uExposure: F32; + uContrast: F32; + uHighlights: F32; + uShadows: F32; + uTemperature: F32; + uTint: F32; + uSaturation: F32; + uAmount: F32; + uSourceSize: Vec2; + uMaskMode: F32; + uSharpen: F32; + uSmooth: F32; + uBlur: F32; + uBloom: F32; + uVignette: F32; + uClarity: F32; + uCenter: Vec2; + uRadii: Vec2; + uRotation: F32; + uFeather: F32; + uInvert: F32; + uShowMask: F32; +}; + +const f32 = (value: number): F32 => ({ value, type: "f32" }); +const vec2 = (x: number, y: number): Vec2 => ({ + value: new Float32Array([x, y]), + type: "vec2", +}); + +export class LocalAdjustFilter extends Filter { + constructor(local: LocalAdjustment, source: Size) { + super({ + glProgram: GlProgram.from({ + vertex: FILTER_VERTEX, + fragment, + name: "prismtone-local-adjust", + }), + resources: { + localUniforms: { + uExposure: f32(0), + uContrast: f32(0), + uHighlights: f32(0), + uShadows: f32(0), + uTemperature: f32(0), + uTint: f32(0), + uSaturation: f32(0), + uAmount: f32(1), + uSourceSize: vec2(source.width, source.height), + uMaskMode: f32(0), + uSharpen: f32(0), + uSmooth: f32(0), + uBlur: f32(0), + uBloom: f32(0), + uVignette: f32(0), + uClarity: f32(0), + uCenter: vec2(0.5, 0.5), + uRadii: vec2(0.1, 0.1), + uRotation: f32(0), + uFeather: f32(0.5), + uInvert: f32(0), + uShowMask: f32(0), + } satisfies LocalUniforms, + uMask: Texture.WHITE.source, + }, + padding: 0, + antialias: "off", + resolution: 1, + }); + this.setLocal(local, false); + } + + /** テクスチャのマスク (ブラシ・多角形・ビットマップ)。null で楕円 (解析的) に戻す */ + setMaskTexture(source: TextureSource | null): void { + this.resources.uMask = source ?? Texture.WHITE.source; + } + + setLocal(local: LocalAdjustment, showMask: boolean): void { + const u = this.resources.localUniforms.uniforms as { + [K in keyof LocalUniforms]: LocalUniforms[K]["value"]; + }; + const a = local.adjust; + u.uExposure = a.exposure; + u.uContrast = a.contrast / 100; + u.uHighlights = a.highlights / 100; + u.uShadows = a.shadows / 100; + u.uTemperature = a.temperature / 100; + u.uTint = a.tint / 100; + u.uSaturation = a.saturation / 100; + u.uAmount = local.amount / 100; + u.uSharpen = a.sharpen / 100; + u.uSmooth = a.smooth / 100; + u.uBlur = a.blur; + u.uBloom = a.bloom / 100; + u.uVignette = a.vignette / 100; + u.uClarity = a.clarity / 100; + u.uShowMask = showMask ? 1 : 0; + u.uMaskMode = local.mask.kind === "ellipse" ? 0 : 1; + u.uInvert = local.mask.invert ? 1 : 0; + if (local.mask.kind === "ellipse") { + const m = local.mask; + u.uCenter[0] = m.cx; + u.uCenter[1] = m.cy; + u.uRadii[0] = m.rx; + u.uRadii[1] = m.ry; + u.uRotation = (m.rotation * Math.PI) / 180; + u.uFeather = Math.max(m.feather, MIN_FEATHER); + } + } +} diff --git a/packages/editor-engine/src/render/mask-texture.ts b/packages/editor-engine/src/render/mask-texture.ts new file mode 100644 index 0000000..aafef2a --- /dev/null +++ b/packages/editor-engine/src/render/mask-texture.ts @@ -0,0 +1,63 @@ +import { Texture, TextureStyle } from "pixi.js"; +import type { BrushStrokeV2, StrokedMask } from "@lumorphia/editor-recipe"; +import { createMaskRaster, rasterizeMask, stampStroke, type MaskRaster } from "../brush-raster.ts"; +import type { Size } from "./geometry.ts"; + +/** + * ブラシ・多角形・ビットマップのマスクのテクスチャ (#109、v3)。brush-raster.ts のラスタを canvas に写して PixiJS の Texture にする。 + * レシピの確定 (commit) ではゼロから描き直し、描画中は 1 ストロークだけ足して更新する。 + */ +export class MaskTexture { + readonly texture: Texture; + private readonly canvas: HTMLCanvasElement; + private readonly ctx: CanvasRenderingContext2D; + private raster: MaskRaster; + private source: Size; + + constructor(source: Size) { + this.source = source; + this.raster = createMaskRaster(source); + this.canvas = document.createElement("canvas"); + this.canvas.width = this.raster.width; + this.canvas.height = this.raster.height; + const ctx = this.canvas.getContext("2d", { willReadFrequently: true }); + if (!ctx) throw new Error("no 2d context"); + this.ctx = ctx; + this.texture = Texture.from(this.canvas); + this.texture.source.style = new TextureStyle({ + scaleMode: "linear", + addressMode: "clamp-to-edge", + }); + this.upload(); + } + + /** マスク全体を描き直す */ + set(mask: StrokedMask): void { + this.raster = rasterizeMask(mask, this.source); + this.upload(); + } + + /** 描画中のストロークを足す (レシピには入れない)。invert は set 側で扱うので、ここでは加算だけ */ + addStroke(stroke: BrushStrokeV2, feather: number): void { + stampStroke(this.raster, stroke, feather); + this.upload(); + } + + private upload(): void { + const { width, height, data } = this.raster; + const image = this.ctx.createImageData(width, height); + for (let i = 0; i < data.length; i++) { + const v = data[i]!; + image.data[i * 4] = v; + image.data[i * 4 + 1] = v; + image.data[i * 4 + 2] = v; + image.data[i * 4 + 3] = 255; + } + this.ctx.putImageData(image, 0, 0); + this.texture.source.update(); + } + + destroy(): void { + this.texture.destroy(true); + } +} diff --git a/packages/editor-engine/src/render/viewport.test.ts b/packages/editor-engine/src/render/viewport.test.ts new file mode 100644 index 0000000..58adbae --- /dev/null +++ b/packages/editor-engine/src/render/viewport.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { + clampPan, + DEFAULT_VIEWPORT, + fitScale, + MAX_ZOOM, + MIN_ZOOM, + panBy, + place, + zoomAt, +} from "./viewport.ts"; + +const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) < eps; +const canvas = { width: 1000, height: 2000 }; +const host = { width: 800, height: 600 }; + +describe("viewport", () => { + it("fit places the image centered with a 4% margin", () => { + const p = place(canvas, host, DEFAULT_VIEWPORT); + expect(near(p.scale, (600 / 2000) * 0.96)).toBe(true); + expect(near(p.x, (800 - 1000 * p.scale) / 2)).toBe(true); + expect(near(p.y, (600 - 2000 * p.scale) / 2)).toBe(true); + }); + + it("zoomAt keeps the image point under the anchor fixed", () => { + const anchor = { x: 500, y: 200 }; + const before = place(canvas, host, DEFAULT_VIEWPORT); + const ix = (anchor.x - before.x) / before.scale; + const iy = (anchor.y - before.y) / before.scale; + const vp = zoomAt(canvas, host, DEFAULT_VIEWPORT, 2, anchor); + const after = place(canvas, host, vp); + expect(near(after.x + ix * after.scale, anchor.x)).toBe(true); + expect(near(after.y + iy * after.scale, anchor.y)).toBe(true); + expect(near(after.scale, fitScale(canvas, host) * 2)).toBe(true); + }); + + it("clamps zoom to the allowed range", () => { + expect(zoomAt(canvas, host, DEFAULT_VIEWPORT, 100).zoom).toBe(MAX_ZOOM); + expect(zoomAt(canvas, host, DEFAULT_VIEWPORT, 0.01).zoom).toBe(MIN_ZOOM); + }); + + it("lets a small image shrink to actual size even below the usual minimum", () => { + const small = { width: 200, height: 100 }; + const fit = fitScale(small, host); // > 1 + const vp = zoomAt(small, host, DEFAULT_VIEWPORT, 1 / fit); + expect(near(place(small, host, vp).scale, 1)).toBe(true); + expect(zoomAt(small, host, DEFAULT_VIEWPORT, 0.001).zoom).toBeCloseTo(1 / fit, 6); + }); + + it("pan cannot push the image completely out of the host", () => { + const vp = panBy(canvas, host, { zoom: 2, pan: { x: 0, y: 0 } }, 100_000, -100_000); + const p = place(canvas, host, vp); + // 画像の左端はホストの中央より右に行かず、下端は中央より上に行かない + expect(p.x).toBeLessThanOrEqual(host.width / 2 + 1e-6); + expect(p.y + canvas.height * p.scale).toBeGreaterThanOrEqual(host.height / 2 - 1e-6); + }); + + it("clampPan leaves a viewport that already fits untouched", () => { + const vp = clampPan(canvas, host, DEFAULT_VIEWPORT); + expect(vp).toEqual(DEFAULT_VIEWPORT); + }); +}); diff --git a/packages/editor-engine/src/render/viewport.ts b/packages/editor-engine/src/render/viewport.ts new file mode 100644 index 0000000..258969b --- /dev/null +++ b/packages/editor-engine/src/render/viewport.ts @@ -0,0 +1,82 @@ +import type { Size } from "./geometry.ts"; + +/** + * 表示のズームと移動 (純粋な計算、PixiJS に依存しない)。 + * zoom はフィット表示に対する倍率 (1 = ホストに収まる)。pan はフィット時の中央からのずれ (CSS px)。 + * 画像がホストから完全に出ないよう pan を clamp する。 + */ +export type Viewport = { zoom: number; pan: { x: number; y: number } }; + +export const MIN_ZOOM = 0.5; +export const MAX_ZOOM = 8; +export const FIT_MARGIN = 0.96; +export const DEFAULT_VIEWPORT: Viewport = { zoom: 1, pan: { x: 0, y: 0 } }; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +/** ホストに収まる倍率 (画像 px → CSS px) */ +export function fitScale(canvas: Size, host: Size): number { + return Math.min(host.width / canvas.width, host.height / canvas.height) * FIT_MARGIN; +} + +/** 表示の倍率と、ステージの左上位置 (CSS px) */ +export function place( + canvas: Size, + host: Size, + vp: Viewport, +): { scale: number; x: number; y: number } { + const scale = fitScale(canvas, host) * vp.zoom; + return { + scale, + x: (host.width - canvas.width * scale) / 2 + vp.pan.x, + y: (host.height - canvas.height * scale) / 2 + vp.pan.y, + }; +} + +/** 画像の端がホストの中央を越えて外へ出ないよう pan を抑える */ +export function clampPan(canvas: Size, host: Size, vp: Viewport): Viewport { + const scale = fitScale(canvas, host) * vp.zoom; + const limitX = Math.max(0, (canvas.width * scale - host.width) / 2 + host.width / 2); + const limitY = Math.max(0, (canvas.height * scale - host.height) / 2 + host.height / 2); + return { + zoom: vp.zoom, + pan: { x: clamp(vp.pan.x, -limitX, limitX), y: clamp(vp.pan.y, -limitY, limitY) }, + }; +} + +/** + * anchor (ホスト内の CSS px) の下にある画像の点を動かさずに倍率を変える。 + * anchor を省くとホストの中央 + */ +export function zoomAt( + canvas: Size, + host: Size, + vp: Viewport, + nextZoom: number, + anchor: { x: number; y: number } = { x: host.width / 2, y: host.height / 2 }, +): Viewport { + // 小さい画像はフィットが等倍より大きい。等倍 (1 / fit) までは縮められるようにする + const zoom = clamp(nextZoom, Math.min(MIN_ZOOM, 1 / fitScale(canvas, host)), MAX_ZOOM); + const before = place(canvas, host, vp); + // anchor の画像座標 (px) + const ix = (anchor.x - before.x) / before.scale; + const iy = (anchor.y - before.y) / before.scale; + const scale = fitScale(canvas, host) * zoom; + // 同じ画像座標が anchor に来る左上位置 → 中央基準の pan に戻す + const x = anchor.x - ix * scale; + const y = anchor.y - iy * scale; + return clampPan(canvas, host, { + zoom, + pan: { + x: x - (host.width - canvas.width * scale) / 2, + y: y - (host.height - canvas.height * scale) / 2, + }, + }); +} + +export function panBy(canvas: Size, host: Size, vp: Viewport, dx: number, dy: number): Viewport { + return clampPan(canvas, host, { zoom: vp.zoom, pan: { x: vp.pan.x + dx, y: vp.pan.y + dy } }); +} + +/** ホイールの 1 ノッチで進む倍率の刻み */ +export const ZOOM_STEP = 1.25; diff --git a/packages/editor-engine/src/state.test.ts b/packages/editor-engine/src/state.test.ts new file mode 100644 index 0000000..676f8af --- /dev/null +++ b/packages/editor-engine/src/state.test.ts @@ -0,0 +1,441 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_ELLIPSE_MASK, + DEFAULT_RECIPE, + MAX_LOCAL_ADJUSTMENTS, + encodeRle, +} from "@lumorphia/editor-recipe"; +import { + activePortraitGroup, + editorReducer, + initialEditorState, + type EditorState, +} from "./state.ts"; + +const loaded: EditorState = editorReducer(initialEditorState, { + type: "image/loaded", + draftId: "d1", + image: { + bitmap: {} as ImageBitmap, + blob: new Blob(), + name: "a.png", + format: "png", + original: { width: 1, height: 1 }, + }, +}); + +describe("editorReducer", () => { + it("drag preview does not add history, commit adds exactly one entry with the pre-drag base", () => { + let s = loaded; + s = editorReducer(s, { type: "adjust/preview", key: "exposure", value: 0.5 }); + s = editorReducer(s, { type: "adjust/preview", key: "exposure", value: 1 }); + s = editorReducer(s, { type: "adjust/preview", key: "exposure", value: 1.5 }); + expect(s.history.past).toHaveLength(0); + expect(s.history.present.adjust.exposure).toBe(1.5); + s = editorReducer(s, { type: "adjust/commit", key: "exposure", value: 1.5 }); + expect(s.history.past).toHaveLength(1); + expect(s.history.past[0]).toBe(DEFAULT_RECIPE); + expect(s.dragBase).toBeNull(); + s = editorReducer(s, { type: "history/undo" }); + expect(s.history.present.adjust.exposure).toBe(0); + }); + + it("applying a preset records presetId and is undoable", () => { + let s = editorReducer(loaded, { type: "preset/apply", id: "mono" }); + expect(s.history.present.presetId).toBe("mono"); + expect(s.history.present.adjust.saturation).toBe(-100); + s = editorReducer(s, { type: "history/undo" }); + expect(s.history.present).toBe(DEFAULT_RECIPE); + }); + + it("manual adjust after a preset clears presetId", () => { + let s = editorReducer(loaded, { type: "preset/apply", id: "mono" }); + s = editorReducer(s, { type: "adjust/commit", key: "contrast", value: 10 }); + expect(s.history.present.presetId).toBeNull(); + expect(s.history.present.adjust.saturation).toBe(-100); + }); + + it("reset returns to defaults as one undoable step", () => { + let s = editorReducer(loaded, { type: "preset/apply", id: "vivid" }); + s = editorReducer(s, { type: "geometry/commit", patch: { rotation: 90 } }); + s = editorReducer(s, { type: "recipe/reset" }); + expect(s.history.present).toBe(DEFAULT_RECIPE); + s = editorReducer(s, { type: "history/undo" }); + expect(s.history.present.geometry.rotation).toBe(90); + }); + + it("ignores unknown preset ids", () => { + const s = editorReducer(loaded, { type: "preset/apply", id: "nope" }); + expect(s).toBe(loaded); + }); + + it("loading a new image resets history and clears errors", () => { + let s = editorReducer(loaded, { type: "ui/error", error: "x" }); + s = editorReducer(s, { type: "preset/apply", id: "film" }); + s = editorReducer(s, { type: "image/loaded", draftId: "d2", image: loaded.source! }); + expect(s.history.past).toHaveLength(0); + expect(s.ui.error).toBeNull(); + expect(s.draftId).toBe("d2"); + }); +}); + +describe("compare slider", () => { + it("境界は 0..1 に収め、切り抜きを始めると比較を切る", () => { + let s = editorReducer(initialEditorState, { type: "ui/compare", on: true }); + s = editorReducer(s, { type: "ui/compare-position", position: 1.7 }); + expect(s.ui.comparePosition).toBe(1); + s = editorReducer(s, { type: "ui/compare-position", position: -0.2 }); + expect(s.ui.comparePosition).toBe(0); + s = editorReducer(s, { type: "ui/cropping", on: true }); + expect(s.ui.comparing).toBe(false); + }); +}); + +describe("editorReducer: 部分補正 (#109)", () => { + const withOne = editorReducer(loaded, { type: "local/add", kind: "ellipse" }); + const id = withOne.history.present.localAdjustments[0]!.id; + + it("adds an ellipse adjustment as one history step and selects it", () => { + expect(withOne.history.past).toHaveLength(1); + expect(withOne.history.pastLabels[0]).toBe("部分補正を追加"); + expect(withOne.history.present.localAdjustments).toHaveLength(1); + expect(withOne.history.present.localAdjustments[0]!.mask.kind).toBe("ellipse"); + expect(withOne.ui.local.selectedId).toBe(id); + expect(withOne.ui.tool).toBe("local"); + }); + + it("places a new ellipse where asked (the centre of the current view)", () => { + const at = { cx: 0.2, cy: 0.7, rx: 0.05, ry: 0.06 }; + const s = editorReducer(loaded, { type: "local/add", kind: "ellipse", at }); + expect(s.history.present.localAdjustments[0]!.mask).toEqual({ ...DEFAULT_ELLIPSE_MASK, ...at }); + // ブラシには関係ない + const b = editorReducer(loaded, { type: "local/add", kind: "brush", at }); + expect(b.history.present.localAdjustments[0]!.mask.kind).toBe("brush"); + }); + + it("adds with a preset applied when asked", () => { + const s = editorReducer(loaded, { type: "local/add", kind: "ellipse", presetId: "eyes" }); + const local = s.history.present.localAdjustments[0]!; + expect(local.presetId).toBe("eyes"); + expect(local.adjust.sharpen).toBe(30); + expect(s.history.pastLabels[0]).toBe("部分補正を追加: 瞳強調"); + }); + + it("refuses an adjustment beyond the limit (v3 は 12)", () => { + let s = loaded; + for (let i = 0; i < MAX_LOCAL_ADJUSTMENTS + 1; i++) + s = editorReducer(s, { type: "local/add", kind: "ellipse" }); + expect(s.history.present.localAdjustments).toHaveLength(MAX_LOCAL_ADJUSTMENTS); + expect(s.history.past).toHaveLength(MAX_LOCAL_ADJUSTMENTS); + }); + + it("adds a brush stroke to a polygon mask (自動で置いたマスクをブラシで直す)", () => { + const polygon = { + kind: "polygon" as const, + rings: [ + [ + { x: 0.2, y: 0.2 }, + { x: 0.8, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0, + invert: false, + }; + let s = editorReducer(withOne, { type: "local/mask-commit", id: id, mask: polygon }); + const stroke = { mode: "erase" as const, size: 0.1, hardness: 1, points: [{ x: 0.5, y: 0.5 }] }; + s = editorReducer(s, { type: "local/stroke-commit", id: id, stroke }); + const mask = s.history.present.localAdjustments[0]!.mask; + expect(mask.kind).toBe("polygon"); + expect(mask.kind === "polygon" && mask.strokes).toEqual([stroke]); + }); + + it("adds several adjustments at once as one history step with a shared groupId (自動選択)", () => { + const s = editorReducer(loaded, { + type: "local/add-auto", + label: "瞳強調 (自動)", + groupId: "face1", + items: [ + { presetId: "eyes", mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.4 } }, + { presetId: "eyes", mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.6 } }, + ], + }); + const list = s.history.present.localAdjustments; + expect(list).toHaveLength(2); + expect(list.map((l) => l.groupId)).toEqual(["face1", "face1"]); + expect(list[0]!.presetId).toBe("eyes"); + expect(list[0]!.adjust.sharpen).toBe(30); + expect(s.history.past).toHaveLength(1); + expect(s.history.pastLabels[0]).toBe("瞳強調 (自動)"); + expect(s.ui.local.selectedId).toBe(list[0]!.id); + expect(s.ui.tool).toBe("local"); + }); + + it("adds nothing when the batch would exceed the limit", () => { + let s = loaded; + for (let i = 0; i < MAX_LOCAL_ADJUSTMENTS - 1; i++) + s = editorReducer(s, { type: "local/add", kind: "ellipse" }); + const before = s.history.present; + s = editorReducer(s, { + type: "local/add-auto", + label: "x", + items: [ + { presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, + { presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, + ], + }); + expect(s.history.present).toBe(before); + }); + + it("tracks inference status and notice in the ui state", () => { + let s = editorReducer(loaded, { + type: "ui/inference", + inference: { status: "loading", progress: { loaded: 1, total: 4 } }, + }); + expect(s.ui.local.inference.status).toBe("loading"); + expect(s.ui.local.inference.progress).toEqual({ loaded: 1, total: 4 }); + s = editorReducer(s, { type: "ui/inference", inference: { status: "idle", progress: null } }); + s = editorReducer(s, { type: "ui/notice", notice: "自動選択できませんでした" }); + expect(s.ui.local.inference.status).toBe("idle"); + expect(s.ui.local.notice).toBe("自動選択できませんでした"); + // 部分補正を足したら文言は消える + s = editorReducer(s, { type: "local/add", kind: "brush" }); + expect(s.ui.local.notice).toBeNull(); + }); + + it("keeps the segmentation candidates while their adjustment exists, and lets the mask be swapped with a label", () => { + const masks = [ + { ...DEFAULT_ELLIPSE_MASK, cx: 0.1 }, + { ...DEFAULT_ELLIPSE_MASK, cx: 0.2 }, + ]; + let s = editorReducer(withOne, { type: "ui/tap", tap: "gear" }); + expect(s.ui.local.tap).toBe("gear"); + s = editorReducer(s, { type: "ui/segment", segment: { localId: id, masks } }); + s = editorReducer(s, { type: "ui/tap", tap: null }); + s = editorReducer(s, { + type: "local/mask-commit", + id, + mask: masks[1]!, + label: "切り抜き: 全体", + }); + expect(s.history.pastLabels.at(-1)).toBe("切り抜き: 全体"); + expect(s.ui.local.segment?.localId).toBe(id); + s = editorReducer(s, { type: "local/remove", id }); + expect(s.ui.local.segment).toBeNull(); + }); + + it("gives each adjustment a distinct id", () => { + let s = withOne; + s = editorReducer(s, { type: "local/add", kind: "ellipse" }); + const ids = s.history.present.localAdjustments.map((l) => l.id); + expect(new Set(ids).size).toBe(2); + }); + + it("drag preview of a local slider adds no history, commit adds one with the pre-drag base", () => { + let s = withOne; + s = editorReducer(s, { type: "local/adjust-preview", id, key: "exposure", value: 0.5 }); + s = editorReducer(s, { type: "local/adjust-preview", id, key: "exposure", value: 1 }); + expect(s.history.past).toHaveLength(1); + expect(s.history.present.localAdjustments[0]!.adjust.exposure).toBe(1); + s = editorReducer(s, { type: "local/adjust-commit", id, key: "exposure", value: 1 }); + expect(s.history.past).toHaveLength(2); + expect(s.history.past[1]).toBe(withOne.history.present); + expect(s.history.pastLabels[1]).toBe("部分補正: 露光量 +1.00"); + }); + + it("clears presetId when a local slider is committed", () => { + let s = editorReducer(loaded, { type: "local/add", kind: "ellipse", presetId: "eyes" }); + const pid = s.history.present.localAdjustments[0]!.id; + s = editorReducer(s, { type: "local/adjust-commit", id: pid, key: "exposure", value: 0.1 }); + expect(s.history.present.localAdjustments[0]!.presetId).toBeNull(); + }); + + it("amount and mask drags follow the same preview / commit rule", () => { + let s = withOne; + s = editorReducer(s, { type: "local/amount-preview", id, value: 40 }); + s = editorReducer(s, { type: "local/amount-commit", id, value: 40 }); + expect(s.history.present.localAdjustments[0]!.amount).toBe(40); + const mask = { ...DEFAULT_ELLIPSE_MASK, cx: 0.2, cy: 0.3 }; + s = editorReducer(s, { type: "local/mask-preview", id, mask }); + expect(s.history.past).toHaveLength(2); + s = editorReducer(s, { type: "local/mask-commit", id, mask }); + expect(s.history.past).toHaveLength(3); + expect(s.history.pastLabels[2]).toBe("マスクを動かす"); + expect(s.history.present.localAdjustments[0]!.mask).toEqual(mask); + }); + + it("applies a local preset to the selected adjustment, keeping its mask", () => { + const mask = { ...DEFAULT_ELLIPSE_MASK, cx: 0.2 }; + let s = editorReducer(withOne, { type: "local/mask-commit", id, mask }); + s = editorReducer(s, { type: "local/preset", id, presetId: "gear" }); + const local = s.history.present.localAdjustments[0]!; + expect(local.presetId).toBe("gear"); + expect(local.adjust.shadows).toBe(45); + expect(local.mask).toEqual(mask); + expect(s.history.pastLabels.at(-1)).toBe("部分補正: 装備強調"); + }); + + it("toggles visibility and removes, moving the selection to a neighbour", () => { + let s = editorReducer(withOne, { type: "local/add", kind: "ellipse" }); + const second = s.history.present.localAdjustments[1]!.id; + s = editorReducer(s, { type: "local/toggle-visible", id }); + expect(s.history.present.localAdjustments[0]!.visible).toBe(false); + expect(s.history.pastLabels.at(-1)).toBe("部分補正を隠す"); + s = editorReducer(s, { type: "local/select", id: second }); + s = editorReducer(s, { type: "local/remove", id: second }); + expect(s.history.present.localAdjustments.map((l) => l.id)).toEqual([id]); + expect(s.ui.local.selectedId).toBe(id); + s = editorReducer(s, { type: "local/remove", id }); + expect(s.ui.local.selectedId).toBeNull(); + }); + + it("undo of an add drops the selection and reset clears everything", () => { + let s = editorReducer(withOne, { type: "history/undo" }); + expect(s.history.present.localAdjustments).toHaveLength(0); + expect(s.ui.local.selectedId).toBeNull(); + s = editorReducer(withOne, { type: "recipe/reset" }); + expect(s.history.present.localAdjustments).toEqual([]); + expect(s.ui.local.selectedId).toBeNull(); + }); + + it("ignores actions for an unknown id", () => { + const s = editorReducer(withOne, { + type: "local/adjust-commit", + id: "nope", + key: "exposure", + value: 1, + }); + expect(s).toBe(withOne); + }); + + it("the mask overlay is off by default, can be pinned on, and is on while drawing", () => { + expect(initialEditorState.ui.local.showMask).toBe(false); + const on = editorReducer(withOne, { type: "ui/show-mask", on: true }); + expect(on.ui.local.showMask).toBe(true); + expect(on.history).toBe(withOne.history); + expect(initialEditorState.ui.local.showHandles).toBe(true); + expect( + editorReducer(withOne, { type: "ui/show-handles", on: false }).ui.local.showHandles, + ).toBe(false); + const drawing = editorReducer(withOne, { type: "ui/drawing", on: true }); + expect(drawing.ui.local.drawing).toBe(true); + expect(editorReducer(drawing, { type: "ui/drawing", on: false }).ui.local.drawing).toBe(false); + }); + + it("adds a brush adjustment and appends strokes as one history step each", () => { + let s = editorReducer(loaded, { type: "local/add", kind: "brush", presetId: "gear" }); + const bid = s.history.present.localAdjustments[0]!.id; + expect(s.history.present.localAdjustments[0]!.mask.kind).toBe("brush"); + const stroke = { mode: "add" as const, size: 0.1, hardness: 0.8, points: [{ x: 0.5, y: 0.5 }] }; + s = editorReducer(s, { type: "local/stroke-commit", id: bid, stroke }); + s = editorReducer(s, { + type: "local/stroke-commit", + id: bid, + stroke: { ...stroke, mode: "erase" }, + }); + const mask = s.history.present.localAdjustments[0]!.mask; + expect(mask.kind === "brush" && mask.strokes).toHaveLength(2); + expect(s.history.pastLabels.slice(-2)).toEqual(["ブラシ", "消しゴム"]); + // ストロークはプリセットの表示を外さない (色の値は変えていない) + expect(s.history.present.localAdjustments[0]!.presetId).toBe("gear"); + }); + + it("ignores a stroke on an ellipse adjustment and beyond the stroke limit", () => { + const stroke = { mode: "add" as const, size: 0.1, hardness: 1, points: [{ x: 0.5, y: 0.5 }] }; + expect(editorReducer(withOne, { type: "local/stroke-commit", id, stroke })).toBe(withOne); + let s = editorReducer(loaded, { type: "local/add", kind: "brush" }); + const bid = s.history.present.localAdjustments[0]!.id; + for (let i = 0; i < 70; i++) + s = editorReducer(s, { type: "local/stroke-commit", id: bid, stroke }); + const mask = s.history.present.localAdjustments[0]!.mask; + expect(mask.kind === "brush" && mask.strokes).toHaveLength(64); + }); + + it("keeps the brush settings in ui state", () => { + const s = editorReducer(loaded, { + type: "ui/brush", + brush: { mode: "erase", size: 0.2, hardness: 0.3 }, + }); + expect(s.ui.local.brush).toEqual({ mode: "erase", size: 0.2, hardness: 0.3 }); + expect(initialEditorState.ui.local.brush.mode).toBe("add"); + }); +}); + +describe("editorReducer: 人物補正 (#175)", () => { + // 役はマスクの形で決まる (portraitRole): 反転したビットマップ = 背景、ビットマップ = 人物、多角形 = 顔 + const bitmap = (invert: boolean) => ({ + kind: "bitmap" as const, + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([1, 0])), + strokes: [], + feather: 0.1, + invert, + }); + const polygon = { + kind: "polygon" as const, + rings: [ + [ + { x: 0.3, y: 0.2 }, + { x: 0.7, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0.2, + invert: false, + }; + const items = [ + { name: "背景", presetId: null, mask: bitmap(true), amount: 60 }, + { name: "人物", presetId: null, mask: bitmap(false), amount: 60 }, + { name: "顔", presetId: "skin" as const, mask: polygon, amount: 80 }, + ]; + const applied = editorReducer(loaded, { type: "portrait/apply", items, presetId: "natural" }); + + it("applies a portrait as one history step, groups the adjustments, and remembers the group and preset", () => { + const list = applied.history.present.localAdjustments; + expect(list).toHaveLength(3); + expect(new Set(list.map((l) => l.groupId)).size).toBe(1); + expect(list[0]!.groupId).toBe(applied.ui.portrait.groupId); + expect(applied.ui.portrait.presetId).toBe("natural"); + expect(applied.history.pastLabels.at(-1)).toBe("人物補正: ナチュラル"); + expect(applied.ui.tool).toBe("portrait"); + }); + + it("switches the preset for the whole group in one step", () => { + const s = editorReducer(applied, { type: "portrait/preset", presetId: "dramatic" }); + expect(s.ui.portrait.presetId).toBe("dramatic"); + expect(s.history.pastLabels.at(-1)).toBe("人物補正: ドラマチック"); + const bg = s.history.present.localAdjustments[0]!; + expect(bg.adjust.exposure).toBe(-0.5); + }); + + it("amount preview / commit scale the group's amounts with the drag rule", () => { + let s = editorReducer(applied, { type: "portrait/amount-preview", value: 50 }); + expect(s.history.past).toHaveLength(applied.history.past.length); + expect(s.history.present.localAdjustments[0]!.amount).toBe(30); + s = editorReducer(s, { type: "portrait/amount-commit", value: 50 }); + expect(s.history.past).toHaveLength(applied.history.past.length + 1); + expect(s.history.pastLabels.at(-1)).toBe("人物補正の効果量 50"); + }); + + it("the group is inactive after undo and active again after redo", () => { + let s = editorReducer(applied, { type: "history/undo" }); + expect(activePortraitGroup(s)).toBeNull(); + expect(editorReducer(s, { type: "portrait/preset", presetId: "soft" })).toBe(s); + s = editorReducer(s, { type: "history/redo" }); + expect(activePortraitGroup(s)).toBe(applied.ui.portrait.groupId); + }); + + it("keeps detected faces and the chosen one in the ui state", () => { + let s = editorReducer(loaded, { type: "portrait/faces", faces: [] }); + expect(s.ui.portrait.faces).toEqual([]); + s = editorReducer(s, { type: "portrait/select-face", index: 1 }); + expect(s.ui.portrait.selectedFace).toBe(1); + // 画像を開き直したら忘れる + s = editorReducer(s, { type: "image/loaded", draftId: "d3", image: loaded.source! }); + expect(s.ui.portrait.faces).toBeNull(); + expect(s.ui.portrait.selectedFace).toBe(0); + }); +}); diff --git a/packages/editor-engine/src/state.ts b/packages/editor-engine/src/state.ts new file mode 100644 index 0000000..97d5a8b --- /dev/null +++ b/packages/editor-engine/src/state.ts @@ -0,0 +1,649 @@ +import { + DEFAULT_BRUSH_MASK, + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + MAX_BRUSH_STROKES, + MAX_LOCAL_ADJUSTMENTS, + applyLocalPreset, + applyPortraitPreset, + applyPreset, + findLocalPreset, + findPortraitPreset, + findPreset, + portraitAmount, + scalePortraitAmount, + type PortraitPresetId, + type AdjustV1, + type BrushStrokeV2, + type EditRecipe, + type GeometryV1, + type LocalAdjust, + type LocalAdjustment, + type LocalPresetId, + type Mask, +} from "@lumorphia/editor-recipe"; +import type { SegmentSelectionKind } from "./inference/auto-select.ts"; +import type { FaceResult } from "./inference/face-masks.ts"; +import { commit, createHistory, preview, redo, undo, type History } from "./history.ts"; +import { adjustLabel, geometryLabel, localAdjustLabel } from "@lumorphia/editor-recipe/labels"; +import type { LoadedImage } from "./load-image.ts"; + +export type Tool = "adjust" | "geometry" | "presets" | "local" | "portrait"; + +/** 円形マスクの初期配置 (今見えている範囲の中央に置くため) */ +export type EllipsePlacement = { cx: number; cy: number; rx: number; ry: number }; + +/** ブラウザ内の認識 (#176) の進み具合。loading はモデルの取得、running は検出中 */ +export type InferenceStatus = { + readonly status: "idle" | "loading" | "running"; + readonly progress: { loaded: number; total: number } | null; +}; + +/** 自動選択で一度に足す部分補正 */ +export type AutoLocalItem = { + readonly mask: Mask; + /** null ならプリセット無し (キャラクター / 背景の範囲だけ) */ + readonly presetId: LocalPresetId | null; + readonly name?: string | undefined; + /** 与えればプリセットの値の代わりに使う (人物補正の役ごとの値、#175) */ + readonly adjust?: LocalAdjust | undefined; + readonly amount?: number | undefined; +}; + +export type BrushSettings = { + readonly mode: BrushStrokeV2["mode"]; + /** 直径。画像の長辺に対する比 */ + readonly size: number; + readonly hardness: number; +}; + +export type EditorState = { + readonly source: LoadedImage | null; + readonly draftId: string | null; + readonly history: History; + /** スライダーのドラッグ開始時点のレシピ。commit 時にこれを履歴に積む。 */ + readonly dragBase: EditRecipe | null; + readonly ui: { + readonly tool: Tool; + readonly comparing: boolean; + /** 比較スライダーの境界 (0..1)。左が元画像、右が現像後 */ + readonly comparePosition: number; + readonly cropping: boolean; + readonly exporting: boolean; + readonly error: string | null; + /** 部分補正 (#109) の UI 状態。selectedId はレシピに無い id を指すことがある (undo 後) ので、使う側で引き直す */ + readonly local: { + readonly selectedId: string | null; + /** 「範囲を表示」を常時オンにするか。オフでも描いている間 (drawing) は見せる */ + readonly showMask: boolean; + /** ブラシで塗っている・円形をドラッグしている間 */ + readonly drawing: boolean; + /** 円形の輪郭とハンドルを出すか。仕上がりを見たいときにオフにする (オフの間は動かせない) */ + readonly showHandles: boolean; + /** ブラシの設定。ストロークごとにレシピへ写す */ + readonly brush: BrushSettings; + readonly inference: InferenceStatus; + /** 自動選択の結果の一言 (失敗、目を閉じている、など)。次の操作で消える */ + readonly notice: string | null; + /** タップで切る (#177) 待ち。null なら通常 */ + readonly tap: SegmentSelectionKind | null; + /** 直近のタップの 3 段の候補。粒度の切り替えに使う。その部分補正が消えたら捨てる */ + readonly segment: { readonly localId: string; readonly masks: readonly Mask[] } | null; + }; + /** 人物補正 (#175)。検出した顔と選んだ人物、今のグループとプリセット */ + readonly portrait: { + /** null は未検出。空配列は検出したが顔が無い */ + readonly faces: readonly FaceResult[] | null; + readonly selectedFace: number; + /** 直近に当てたグループ。レシピに残っているかは activePortraitGroup で見る (undo / redo で消えたり戻ったりする) */ + readonly groupId: string | null; + readonly presetId: PortraitPresetId | null; + }; + }; +}; + +export type EditorAction = + | { type: "image/loaded"; image: LoadedImage; draftId: string; recipe?: EditRecipe } + | { type: "image/failed"; error: string } + | { type: "adjust/preview"; key: keyof AdjustV1; value: number } + | { type: "adjust/commit"; key: keyof AdjustV1; value: number } + | { type: "geometry/commit"; patch: Partial } + | { type: "geometry/preview"; patch: Partial } + | { type: "preset/apply"; id: string } + | { type: "recipe/reset" } + | { + type: "local/add"; + kind: "ellipse" | "brush"; + presetId?: LocalPresetId | undefined; + /** 円形の初期位置 (画像の正規化座標)。省くと画像の中央 */ + at?: EllipsePlacement | undefined; + } + | { + /** 自動選択 (#176 / #177): 複数の部分補正を 1 手で足す。入り切らなければ何もしない */ + type: "local/add-auto"; + items: readonly AutoLocalItem[]; + label: string; + groupId?: string | undefined; + /** タップの 3 段の候補 (#177)。先頭の部分補正に紐づけて粒度を切り替えられるようにする */ + candidates?: readonly Mask[] | undefined; + } + | { type: "local/remove"; id: string } + | { type: "local/select"; id: string | null } + | { type: "local/toggle-visible"; id: string } + | { type: "local/adjust-preview"; id: string; key: keyof LocalAdjust; value: number } + | { type: "local/adjust-commit"; id: string; key: keyof LocalAdjust; value: number } + | { type: "local/amount-preview"; id: string; value: number } + | { type: "local/amount-commit"; id: string; value: number } + | { type: "local/mask-preview"; id: string; mask: Mask } + | { type: "local/mask-commit"; id: string; mask: Mask; label?: string | undefined } + | { type: "local/preset"; id: string; presetId: LocalPresetId } + | { type: "local/stroke-commit"; id: string; stroke: BrushStrokeV2 } + | { type: "ui/show-mask"; on: boolean } + | { type: "ui/drawing"; on: boolean } + | { type: "ui/show-handles"; on: boolean } + | { type: "ui/brush"; brush: BrushSettings } + | { type: "ui/inference"; inference: InferenceStatus } + | { type: "ui/notice"; notice: string | null } + | { type: "portrait/faces"; faces: readonly FaceResult[] } + | { type: "portrait/select-face"; index: number } + | { + /** 検出と切り抜きの結果を 1 手で足し、グループとして覚える */ + type: "portrait/apply"; + items: readonly AutoLocalItem[]; + presetId: PortraitPresetId; + } + | { type: "portrait/preset"; presetId: PortraitPresetId } + | { type: "portrait/amount-preview"; value: number } + | { type: "portrait/amount-commit"; value: number } + | { type: "ui/tap"; tap: SegmentSelectionKind | null } + | { type: "ui/segment"; segment: EditorState["ui"]["local"]["segment"] } + | { type: "history/undo" } + | { type: "history/redo" } + | { type: "ui/tool"; tool: Tool } + | { type: "ui/compare"; on: boolean } + | { type: "ui/compare-position"; position: number } + | { type: "ui/cropping"; on: boolean } + | { type: "ui/exporting"; on: boolean } + | { type: "ui/error"; error: string | null }; + +export const initialEditorState: EditorState = { + source: null, + draftId: null, + history: createHistory(DEFAULT_RECIPE), + dragBase: null, + ui: { + tool: "presets", + comparing: false, + comparePosition: 0.5, + cropping: false, + exporting: false, + error: null, + local: { + selectedId: null, + showMask: false, + drawing: false, + showHandles: true, + brush: { mode: "add", size: 0.08, hardness: 0.7 }, + inference: { status: "idle", progress: null }, + notice: null, + tap: null, + segment: null, + }, + portrait: { faces: null, selectedFace: 0, groupId: null, presetId: null }, + }, +}; + +const DEFAULT_PORTRAIT_UI = initialEditorState.ui.portrait; + +const withAdjust = (r: EditRecipe, key: keyof AdjustV1, value: number): EditRecipe => ({ + ...r, + presetId: null, + adjust: { ...r.adjust, [key]: value }, +}); + +const withGeometry = (r: EditRecipe, patch: Partial): EditRecipe => ({ + ...r, + geometry: { ...r.geometry, ...patch }, +}); + +/** 指定 id の部分補正だけ差し替えたレシピ。無ければ null */ +function withLocal( + r: EditRecipe, + id: string, + update: (local: LocalAdjustment) => LocalAdjustment, +): EditRecipe | null { + const index = r.localAdjustments.findIndex((l) => l.id === id); + if (index < 0) return null; + return { + ...r, + localAdjustments: r.localAdjustments.map((l, i) => (i === index ? update(l) : l)), + }; +} + +/** 手で値を変えたらプリセットの表示は外す (全体の補正と同じ原則) */ +const withLocalValue = + (key: keyof LocalAdjust, value: number) => + (l: LocalAdjustment): LocalAdjustment => ({ + ...l, + presetId: null, + adjust: { ...l.adjust, [key]: value }, + }); + +const withLocalAmount = + (value: number) => + (l: LocalAdjustment): LocalAdjustment => ({ ...l, amount: value }); + +const withLocalMask = + (mask: Mask) => + (l: LocalAdjustment): LocalAdjustment => ({ ...l, mask }); + +let localSeq = 0; +/** レシピ内で一意ならよい。時刻 + 連番で、下書きから戻したものとぶつからないようにする */ +function newLocalId(): string { + localSeq = (localSeq + 1) % 1000; + return `l${Date.now().toString(36)}${localSeq.toString(36)}`; +} +function newGroupId(): string { + return `p${Date.now().toString(36)}${(localSeq++ % 1000).toString(36)}`; +} + +/** 自動選択の部分補正を組み立てる (local/add-auto と portrait/apply で共通) */ +function buildAutoLocals( + items: readonly AutoLocalItem[], + groupId: string | null, +): LocalAdjustment[] { + return items.map((item) => { + const preset = item.presetId ? findLocalPreset(item.presetId) : undefined; + const base: LocalAdjustment = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: newLocalId(), + name: item.name ?? null, + groupId, + mask: item.mask, + }; + const withPreset = preset ? applyLocalPreset(base, preset) : base; + return { + ...withPreset, + ...(item.adjust ? { adjust: item.adjust } : {}), + ...(item.amount !== undefined ? { amount: item.amount } : {}), + }; + }); +} + +/** ドラッグ中の preview / 終了時の commit を部分補正に適用する共通処理 */ +function localPreview( + state: EditorState, + id: string, + update: (l: LocalAdjustment) => LocalAdjustment, +): EditorState { + const next = withLocal(state.history.present, id, update); + if (!next) return state; + return { + ...state, + dragBase: state.dragBase ?? state.history.present, + history: preview(state.history, next), + }; +} + +function localCommit( + state: EditorState, + id: string, + update: (l: LocalAdjustment) => LocalAdjustment, + label: string, +): EditorState { + const base = state.dragBase ?? state.history.present; + const next = withLocal(base, id, update); + if (!next) return state; + return { + ...state, + dragBase: null, + history: commit({ ...state.history, present: base }, next, label), + }; +} + +function selectLocal(state: EditorState, selectedId: string | null): EditorState { + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, selectedId } } }; +} + +function withNotice(state: EditorState, notice: string | null): EditorState { + if (state.ui.local.notice === notice) return state; + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, notice } } }; +} + +/** 選択中の id・切り抜きの候補・人物補正のグループがレシピから消えていたら外す (undo / 削除 / リセット後) */ +function reconcileSelection(state: EditorState): EditorState { + const { selectedId, segment } = state.ui.local; + const list = state.history.present.localAdjustments; + const has = (id: string) => list.some((l) => l.id === id); + let next = state; + if (selectedId && !has(selectedId)) next = selectLocal(next, null); + if (segment && !has(segment.localId)) { + next = { ...next, ui: { ...next.ui, local: { ...next.ui.local, segment: null } } }; + } + return next; +} + +/** 人物補正のグループが今のレシピにあるか。undo で消え、redo で戻るので、ui の groupId は消さずにここで見る */ +export function activePortraitGroup(state: EditorState): string | null { + const { groupId } = state.ui.portrait; + if (!groupId) return null; + return state.history.present.localAdjustments.some((l) => l.groupId === groupId) ? groupId : null; +} + +export function editorReducer(state: EditorState, action: EditorAction): EditorState { + const { history } = state; + switch (action.type) { + case "image/loaded": + return { + ...state, + source: action.image, + draftId: action.draftId, + history: createHistory(action.recipe ?? DEFAULT_RECIPE), + dragBase: null, + ui: { ...state.ui, error: null, cropping: false, portrait: DEFAULT_PORTRAIT_UI }, + }; + case "image/failed": + return { ...state, ui: { ...state.ui, error: action.error } }; + case "adjust/preview": + return { + ...state, + dragBase: state.dragBase ?? history.present, + history: preview(history, withAdjust(history.present, action.key, action.value)), + }; + case "adjust/commit": { + // ドラッグ中の preview は履歴に積まない。ドラッグ開始時点 (dragBase) を積む + const base = state.dragBase ?? history.present; + const next = withAdjust(base, action.key, action.value); + return { + ...state, + dragBase: null, + history: commit({ ...history, present: base }, next, adjustLabel(action.key, action.value)), + }; + } + case "geometry/preview": + return { + ...state, + dragBase: state.dragBase ?? history.present, + history: preview(history, withGeometry(history.present, action.patch)), + }; + case "geometry/commit": { + const base = state.dragBase ?? history.present; + const next = withGeometry(base, action.patch); + return { + ...state, + dragBase: null, + history: commit({ ...history, present: base }, next, geometryLabel(action.patch)), + }; + } + case "preset/apply": { + const preset = findPreset(action.id); + if (!preset) return state; + return { + ...state, + history: commit( + history, + applyPreset(history.present, preset), + `プリセット: ${preset.name}`, + ), + }; + } + case "recipe/reset": + return reconcileSelection({ + ...state, + history: commit(history, DEFAULT_RECIPE, "全リセット"), + }); + case "history/undo": + return reconcileSelection({ ...state, history: undo(history) }); + case "history/redo": + return reconcileSelection({ ...state, history: redo(history) }); + case "local/add": { + if (history.present.localAdjustments.length >= MAX_LOCAL_ADJUSTMENTS) return state; + const preset = action.presetId ? findLocalPreset(action.presetId) : undefined; + const base: LocalAdjustment = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: newLocalId(), + mask: + action.kind === "ellipse" + ? { ...DEFAULT_ELLIPSE_MASK, ...action.at } + : DEFAULT_BRUSH_MASK, + }; + const local = preset ? applyLocalPreset(base, preset) : base; + const next = { + ...history.present, + localAdjustments: [...history.present.localAdjustments, local], + }; + const label = preset ? `部分補正を追加: ${preset.name}` : "部分補正を追加"; + return { + ...selectLocal(state, local.id), + history: commit(history, next, label), + ui: { + ...state.ui, + tool: "local", + local: { ...state.ui.local, selectedId: local.id, notice: null }, + }, + }; + } + case "local/add-auto": { + const room = MAX_LOCAL_ADJUSTMENTS - history.present.localAdjustments.length; + if (action.items.length === 0 || action.items.length > room) return state; + const added = buildAutoLocals(action.items, action.groupId ?? null); + const next = { + ...history.present, + localAdjustments: [...history.present.localAdjustments, ...added], + }; + return { + ...state, + history: commit(history, next, action.label), + ui: { + ...state.ui, + tool: "local", + local: { + ...state.ui.local, + selectedId: added[0]!.id, + notice: null, + tap: null, + segment: action.candidates + ? { localId: added[0]!.id, masks: action.candidates } + : state.ui.local.segment, + }, + }, + }; + } + case "local/remove": { + const list = history.present.localAdjustments; + const index = list.findIndex((l) => l.id === action.id); + if (index < 0) return state; + const rest = list.filter((l) => l.id !== action.id); + const next = { ...history.present, localAdjustments: rest }; + const neighbour = rest[Math.min(index, rest.length - 1)]?.id ?? null; + return reconcileSelection( + selectLocal( + { ...state, history: commit(history, next, "部分補正を削除") }, + state.ui.local.selectedId === action.id ? neighbour : state.ui.local.selectedId, + ), + ); + } + case "local/select": + return selectLocal(state, action.id); + case "local/toggle-visible": { + const target = history.present.localAdjustments.find((l) => l.id === action.id); + if (!target) return state; + return localCommit( + state, + action.id, + (l) => ({ ...l, visible: !l.visible }), + target.visible ? "部分補正を隠す" : "部分補正を表示", + ); + } + case "local/adjust-preview": + return localPreview(state, action.id, withLocalValue(action.key, action.value)); + case "local/adjust-commit": + return localCommit( + state, + action.id, + withLocalValue(action.key, action.value), + localAdjustLabel(action.key, action.value), + ); + case "local/amount-preview": + return localPreview(state, action.id, withLocalAmount(action.value)); + case "local/amount-commit": + return localCommit(state, action.id, withLocalAmount(action.value), `効果量 ${action.value}`); + case "local/mask-preview": + return localPreview(state, action.id, withLocalMask(action.mask)); + case "local/mask-commit": + return localCommit( + state, + action.id, + withLocalMask(action.mask), + action.label ?? "マスクを動かす", + ); + case "local/preset": { + const preset = findLocalPreset(action.presetId); + if (!preset) return state; + return localCommit( + state, + action.id, + (l) => applyLocalPreset(l, preset), + `部分補正: ${preset.name}`, + ); + } + case "local/stroke-commit": { + // ブラシ・多角形・ビットマップ (strokes を持つマスク) にストロークを足す。自動で置いたマスクもブラシで直せる + const target = history.present.localAdjustments.find((l) => l.id === action.id); + if (!target || target.mask.kind === "ellipse") return state; + if (target.mask.strokes.length >= MAX_BRUSH_STROKES) return state; + const mask = target.mask; + return localCommit( + state, + action.id, + (l) => ({ ...l, mask: { ...mask, strokes: [...mask.strokes, action.stroke] } }), + action.stroke.mode === "add" ? "ブラシ" : "消しゴム", + ); + } + case "ui/brush": + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, brush: action.brush } } }; + case "ui/inference": + return { + ...state, + ui: { ...state.ui, local: { ...state.ui.local, inference: action.inference } }, + }; + case "ui/notice": + return withNotice(state, action.notice); + case "portrait/faces": + return { + ...state, + ui: { + ...state.ui, + portrait: { ...state.ui.portrait, faces: action.faces, selectedFace: 0 }, + }, + }; + case "portrait/select-face": + return { + ...state, + ui: { ...state.ui, portrait: { ...state.ui.portrait, selectedFace: action.index } }, + }; + case "portrait/apply": { + const room = MAX_LOCAL_ADJUSTMENTS - history.present.localAdjustments.length; + const preset = findPortraitPreset(action.presetId); + if (!preset || action.items.length === 0 || action.items.length > room) return state; + const groupId = newGroupId(); + const next = { + ...history.present, + localAdjustments: [ + ...history.present.localAdjustments, + ...buildAutoLocals(action.items, groupId), + ], + }; + return { + ...state, + history: commit(history, next, `人物補正: ${preset.name}`), + ui: { + ...state.ui, + tool: "portrait", + local: { ...state.ui.local, notice: null }, + portrait: { ...state.ui.portrait, groupId, presetId: action.presetId }, + }, + }; + } + case "portrait/preset": { + const groupId = activePortraitGroup(state); + const { presetId } = state.ui.portrait; + const preset = findPortraitPreset(action.presetId); + const current = presetId ? findPortraitPreset(presetId) : undefined; + if (!groupId || !preset || !current) return state; + const effect = portraitAmount(history.present, groupId, current); + return { + ...state, + history: commit( + history, + applyPortraitPreset(history.present, groupId, preset, effect), + `人物補正: ${preset.name}`, + ), + ui: { ...state.ui, portrait: { ...state.ui.portrait, presetId: action.presetId } }, + }; + } + case "portrait/amount-preview": { + const groupId = activePortraitGroup(state); + const { presetId } = state.ui.portrait; + const preset = presetId ? findPortraitPreset(presetId) : undefined; + if (!groupId || !preset) return state; + return { + ...state, + dragBase: state.dragBase ?? history.present, + history: preview( + history, + scalePortraitAmount(history.present, groupId, preset, action.value), + ), + }; + } + case "portrait/amount-commit": { + const groupId = activePortraitGroup(state); + const { presetId } = state.ui.portrait; + const preset = presetId ? findPortraitPreset(presetId) : undefined; + if (!groupId || !preset) return state; + const base = state.dragBase ?? history.present; + return { + ...state, + dragBase: null, + history: commit( + { ...history, present: base }, + scalePortraitAmount(base, groupId, preset, action.value), + `人物補正の効果量 ${action.value}`, + ), + }; + } + case "ui/tap": + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, tap: action.tap } } }; + case "ui/segment": + return { + ...state, + ui: { ...state.ui, local: { ...state.ui.local, segment: action.segment } }, + }; + case "ui/show-handles": + return { + ...state, + ui: { ...state.ui, local: { ...state.ui.local, showHandles: action.on } }, + }; + case "ui/drawing": + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, drawing: action.on } } }; + case "ui/show-mask": + return { ...state, ui: { ...state.ui, local: { ...state.ui.local, showMask: action.on } } }; + case "ui/tool": + return { ...state, ui: { ...state.ui, tool: action.tool } }; + case "ui/compare": + return { ...state, ui: { ...state.ui, comparing: action.on } }; + case "ui/compare-position": + return { + ...state, + ui: { ...state.ui, comparePosition: Math.min(1, Math.max(0, action.position)) }, + }; + case "ui/cropping": + // 切り抜き中は座標が合わないので比較を切る (docs: #40) + return { ...state, ui: { ...state.ui, cropping: action.on, comparing: false } }; + case "ui/exporting": + return { ...state, ui: { ...state.ui, exporting: action.on } }; + case "ui/error": + return { ...state, ui: { ...state.ui, error: action.error } }; + } +} diff --git a/packages/editor-engine/tsconfig.bin.json b/packages/editor-engine/tsconfig.bin.json new file mode 100644 index 0000000..dde81a4 --- /dev/null +++ b/packages/editor-engine/tsconfig.bin.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.node.json", + "compilerOptions": { + "noEmit": false, + "rootDir": "bin", + "outDir": "dist/bin" + }, + "include": ["bin/**/*"], + "exclude": ["bin/**/*.test.ts"] +} diff --git a/packages/editor-engine/tsconfig.build.json b/packages/editor-engine/tsconfig.build.json new file mode 100644 index 0000000..a18d5c9 --- /dev/null +++ b/packages/editor-engine/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist" + }, + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/editor-engine/tsconfig.json b/packages/editor-engine/tsconfig.json new file mode 100644 index 0000000..e19cea0 --- /dev/null +++ b/packages/editor-engine/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2024", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "types": [] + }, + "include": ["src/**/*"] +} diff --git a/packages/editor-engine/tsconfig.node.json b/packages/editor-engine/tsconfig.node.json new file mode 100644 index 0000000..4463775 --- /dev/null +++ b/packages/editor-engine/tsconfig.node.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2024"], + "types": ["node"] + }, + "include": ["bin/**/*", "scripts/**/*", "src/inference/model-paths.ts"] +} diff --git a/packages/editor-engine/vitest.config.ts b/packages/editor-engine/vitest.config.ts new file mode 100644 index 0000000..5b541ae --- /dev/null +++ b/packages/editor-engine/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vitest/config"; +import { readEditorSource } from "../../vitest.source.ts"; +export default defineConfig({ + ...readEditorSource, + test: { + name: "editor-engine", + include: ["src/**/*.test.ts", "scripts/**/*.test.ts", "bin/**/*.test.ts"], + }, +}); diff --git a/packages/editor-react/package.json b/packages/editor-react/package.json new file mode 100644 index 0000000..6cd90a4 --- /dev/null +++ b/packages/editor-react/package.json @@ -0,0 +1,34 @@ +{ + "name": "@lumorphia/editor-react", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "rm -rf dist && tsc -p tsconfig.build.json", + "typecheck": "tsc -p tsconfig.json", + "test": "vitest run" + }, + "dependencies": { + "@lumorphia/editor-engine": "workspace:*", + "@lumorphia/editor-recipe": "workspace:*" + }, + "peerDependencies": { + "react": "^19.3.0" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "react": "^19.3.0" + }, + "files": [ + "dist", + "src", + "!src/**/*.test.ts" + ] +} diff --git a/packages/editor-react/src/AdjustPanel.tsx b/packages/editor-react/src/AdjustPanel.tsx new file mode 100644 index 0000000..bb2789e --- /dev/null +++ b/packages/editor-react/src/AdjustPanel.tsx @@ -0,0 +1,52 @@ +import type { AdjustV1 } from "@lumorphia/editor-recipe"; +import { ADJUST_LABELS } from "@lumorphia/editor-recipe/labels"; +import { Slider } from "./Slider.tsx"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type Props = { + adjust: AdjustV1; + onPreview: (key: keyof AdjustV1, value: number) => void; + onCommit: (key: keyof AdjustV1, value: number) => void; +}; + +const ROWS: { + key: keyof AdjustV1; + label: string; + min: number; + max: number; + step: number; + ev?: boolean; +}[] = [ + { key: "exposure", label: ADJUST_LABELS.exposure, min: -5, max: 5, step: 0.05, ev: true }, + { key: "contrast", label: ADJUST_LABELS.contrast, min: -100, max: 100, step: 1 }, + { key: "highlights", label: ADJUST_LABELS.highlights, min: -100, max: 100, step: 1 }, + { key: "shadows", label: ADJUST_LABELS.shadows, min: -100, max: 100, step: 1 }, + { key: "temperature", label: ADJUST_LABELS.temperature, min: -100, max: 100, step: 1 }, + { key: "tint", label: ADJUST_LABELS.tint, min: -100, max: 100, step: 1 }, + { key: "vibrance", label: ADJUST_LABELS.vibrance, min: -100, max: 100, step: 1 }, + { key: "saturation", label: ADJUST_LABELS.saturation, min: -100, max: 100, step: 1 }, +]; + +export function AdjustPanel({ adjust, onPreview, onCommit }: Props) { + const { tx } = useEditorI18n(); + return ( +
+ {ROWS.map((r) => ( + `${v >= 0 ? "+" : ""}${v.toFixed(2)}` : (v) => `${v > 0 ? "+" : ""}${v}` + } + onPreview={(v) => onPreview(r.key, v)} + onCommit={(v) => onCommit(r.key, v)} + onReset={() => onCommit(r.key, 0)} + /> + ))} +
+ ); +} diff --git a/packages/editor-react/src/BrushOverlay.tsx b/packages/editor-react/src/BrushOverlay.tsx new file mode 100644 index 0000000..64dea40 --- /dev/null +++ b/packages/editor-react/src/BrushOverlay.tsx @@ -0,0 +1,129 @@ +import { useRef, useState } from "react"; +import type { BrushStrokeV2, GeometryV1 } from "@lumorphia/editor-recipe"; +import { simplifyPoints } from "@lumorphia/editor-engine"; +import { canvasToImageUv, type Point } from "@lumorphia/editor-engine"; +import type { Size } from "@lumorphia/editor-engine"; +import type { BrushSettings } from "@lumorphia/editor-engine"; + +type View = { x: number; y: number; width: number; height: number; scale: number }; + +type Props = { + view: View; + source: Size; + geometry: GeometryV1; + brush: BrushSettings; + /** 描画中: 直前の点から今の点までの線分をマスクに足す (レシピには入れない) */ + onPreview: (segment: BrushStrokeV2) => void; + /** 離したとき: 間引いたストロークをレシピに積む */ + onCommit: (stroke: BrushStrokeV2) => void; + /** 押している間 true。範囲の赤い重ねを出すために使う */ + onDrawing: (on: boolean) => void; + /** 描きかけを捨てる (ピンチに切り替わったとき)。プレビューで足した分を消すためにレシピを描き直す */ + onCancel: () => void; +}; + +/** ポインタの移動をこれ未満 (画像の長辺に対する比) なら捨てる。レシピの点数を抑える */ +const MIN_POINT_DISTANCE = 0.005; + +/** + * ブラシマスクの DOM オーバーレイ (#109)。キャンバス全体でポインタを受け、画像座標の点列にする。 + * 描画中は 1 線分ずつ renderer に足して即時に見せ、離したときに 1 ストロークとして履歴に積む。 + */ +export function BrushOverlay({ + view, + source, + geometry, + brush, + onPreview, + onCommit, + onDrawing, + onCancel, +}: Props) { + const points = useRef(null); + const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null); + + const toUv = (e: React.PointerEvent): Point => { + const host = (e.currentTarget as HTMLElement).getBoundingClientRect(); + const canvas = { + x: (e.clientX - host.left - view.x) / view.scale, + y: (e.clientY - host.top - view.y) / view.scale, + }; + const uv = canvasToImageUv(canvas, source, geometry); + return { x: Math.min(1, Math.max(0, uv.x)), y: Math.min(1, Math.max(0, uv.y)) }; + }; + const stroke = (pts: Point[]): BrushStrokeV2 => ({ + mode: brush.mode, + size: brush.size, + hardness: brush.hardness, + points: pts, + }); + + const onPointerDown = (e: React.PointerEvent) => { + if (e.button !== 0) return; + e.preventDefault(); + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + const p = toUv(e); + points.current = [p]; + onDrawing(true); + onPreview(stroke([p])); + }; + const onPointerMove = (e: React.PointerEvent) => { + const host = (e.currentTarget as HTMLElement).getBoundingClientRect(); + setCursor({ x: e.clientX - host.left, y: e.clientY - host.top }); + const pts = points.current; + if (!pts) return; + const p = toUv(e); + const last = pts[pts.length - 1]!; + if (Math.hypot(p.x - last.x, p.y - last.y) < MIN_POINT_DISTANCE) return; + pts.push(p); + onPreview(stroke([last, p])); + }; + const onPointerUp = (e: React.PointerEvent) => { + const pts = points.current; + points.current = null; + if (!pts) return; + onDrawing(false); + const p = toUv(e); + const all = simplifyPoints([...pts, p], MIN_POINT_DISTANCE); + onCommit(stroke(all)); + }; + /** 2 本目の指が触れた (ピンチに切り替わった) など。描きかけは捨てる */ + const onPointerCancel = () => { + if (!points.current) return; + points.current = null; + onDrawing(false); + onCancel(); + }; + + // ブラシの円 (画面 px)。直径 = size × 長辺 × 表示倍率 + const diameter = brush.size * Math.max(source.width, source.height) * view.scale; + + return ( +
setCursor(null)} + > + {cursor && ( + + ); +} diff --git a/packages/editor-react/src/CompareSlider.tsx b/packages/editor-react/src/CompareSlider.tsx new file mode 100644 index 0000000..c585670 --- /dev/null +++ b/packages/editor-react/src/CompareSlider.tsx @@ -0,0 +1,83 @@ +import { useRef } from "react"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type View = { x: number; y: number; width: number; height: number }; + +/** + * before / after の境界を左右にドラッグする。左が元画像、右が現像後。 + * ドラッグに加えて透明な range で矢印キーでも動かせる (ジェスチャーだけにしない)。 + */ +export function CompareSlider({ + view, + position, + onChange, +}: { + view: View; + position: number; + onChange: (position: number) => void; +}) { + const { t } = useEditorI18n(); + const dragging = useRef(false); + const toPosition = (clientX: number, el: HTMLElement) => { + const rect = el.getBoundingClientRect(); + return Math.min(1, Math.max(0, (clientX - rect.left) / rect.width)); + }; + const x = view.x + view.width * position; + return ( +
{ + dragging.current = true; + e.currentTarget.setPointerCapture(e.pointerId); + onChange(toPosition(e.clientX, e.currentTarget)); + }} + onPointerMove={(e) => { + if (dragging.current) onChange(toPosition(e.clientX, e.currentTarget)); + }} + onPointerUp={(e) => { + dragging.current = false; + e.currentTarget.releasePointerCapture(e.pointerId); + }} + onPointerCancel={() => { + dragging.current = false; + }} + > + + + + onChange(Number(e.currentTarget.value) / 1000)} + aria-label={t( + "比較の境界 (左が元画像、右が現像後)", + "Comparison boundary (original on left, edited on right)", + )} + className="absolute inset-x-0 bottom-0 h-6 w-full cursor-ew-resize opacity-0" + data-testid="compare-range" + /> +
+ ); +} diff --git a/packages/editor-react/src/CropOverlay.tsx b/packages/editor-react/src/CropOverlay.tsx new file mode 100644 index 0000000..fbaae7d --- /dev/null +++ b/packages/editor-react/src/CropOverlay.tsx @@ -0,0 +1,115 @@ +import { useRef } from "react"; +import type { GeometryV1 } from "@lumorphia/editor-recipe"; +import { dragCrop, type Crop, type Handle } from "./crop-drag.ts"; + +type Props = { + view: { x: number; y: number; width: number; height: number }; + crop: Crop; + aspect: GeometryV1["aspect"]; + canvasRatio: number; + onPreview: (crop: Crop) => void; + onCommit: (crop: Crop) => void; +}; + +const HANDLES: { h: Handle; cls: string; cursor: string }[] = [ + { h: "nw", cls: "-left-1.5 -top-1.5", cursor: "nwse-resize" }, + { h: "ne", cls: "-right-1.5 -top-1.5", cursor: "nesw-resize" }, + { h: "sw", cls: "-left-1.5 -bottom-1.5", cursor: "nesw-resize" }, + { h: "se", cls: "-right-1.5 -bottom-1.5", cursor: "nwse-resize" }, + { h: "n", cls: "left-1/2 -top-1.5 -translate-x-1/2", cursor: "ns-resize" }, + { h: "s", cls: "left-1/2 -bottom-1.5 -translate-x-1/2", cursor: "ns-resize" }, + { h: "w", cls: "-left-1.5 top-1/2 -translate-y-1/2", cursor: "ew-resize" }, + { h: "e", cls: "-right-1.5 top-1/2 -translate-y-1/2", cursor: "ew-resize" }, +]; + +function ratioOf(aspect: GeometryV1["aspect"], canvasRatio: number): number | undefined { + if (!aspect || aspect === "free") return undefined; + const [w, h] = aspect.split(":").map(Number); + if (!w || !h) return undefined; + return w / h / canvasRatio; +} + +/** DOM で描く crop 枠 (docs/design/08 §3.3)。ドラッグ中は onPreview、離したら onCommit。 */ +export function CropOverlay({ view, crop, aspect, canvasRatio, onPreview, onCommit }: Props) { + const drag = useRef<{ handle: Handle; start: Crop; sx: number; sy: number } | null>(null); + const ratio = ratioOf(aspect, canvasRatio); + + const onPointerDown = (handle: Handle) => (e: React.PointerEvent) => { + e.preventDefault(); + e.stopPropagation(); + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { handle, start: crop, sx: e.clientX, sy: e.clientY }; + }; + const onPointerMove = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return; + const next = dragCrop( + d.start, + d.handle, + (e.clientX - d.sx) / view.width, + (e.clientY - d.sy) / view.height, + ratio, + ); + onPreview(next); + }; + const onPointerUp = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return; + drag.current = null; + const next = dragCrop( + d.start, + d.handle, + (e.clientX - d.sx) / view.width, + (e.clientY - d.sy) / view.height, + ratio, + ); + onCommit(next); + }; + + const box = { + left: view.x + crop.x * view.width, + top: view.y + crop.y * view.height, + width: crop.w * view.width, + height: crop.h * view.height, + }; + + return ( +
+
+
+
+ {Array.from({ length: 9 }, (_, i) => ( +
+ ))} +
+ {HANDLES.map(({ h, cls, cursor }) => ( +
+ ))} +
+
+ ); +} diff --git a/packages/editor-react/src/EditorI18n.tsx b/packages/editor-react/src/EditorI18n.tsx new file mode 100644 index 0000000..9fb4787 --- /dev/null +++ b/packages/editor-react/src/EditorI18n.tsx @@ -0,0 +1,22 @@ +import { createContext, useContext, useMemo } from "react"; +import { editorTranslator, type EditorLocale, type EditorTranslator } from "./i18n.ts"; + +/** エディタの中だけの i18n。表示言語はホストが渡す (prismtone の I18nProvider には依存しない) */ +const EditorI18nContext = createContext(null); + +export function EditorI18nProvider({ + locale, + children, +}: { + locale: EditorLocale; + children: React.ReactNode; +}) { + const value = useMemo(() => editorTranslator(locale), [locale]); + return {children}; +} + +export function useEditorI18n(): EditorTranslator { + const value = useContext(EditorI18nContext); + if (!value) throw new Error("EditorI18nProvider is missing"); + return value; +} diff --git a/packages/editor-react/src/EditorPage.tsx b/packages/editor-react/src/EditorPage.tsx new file mode 100644 index 0000000..680c46e --- /dev/null +++ b/packages/editor-react/src/EditorPage.tsx @@ -0,0 +1,910 @@ +import { useCallback, useEffect, useReducer, useRef, useState } from "react"; +import { DEFAULT_ELLIPSE_MASK, type EditRecipe } from "@lumorphia/editor-recipe"; +import { activePortraitGroup, editorReducer, initialEditorState } from "@lumorphia/editor-engine"; +import { canRedo, canUndo, redoLabel, undoLabel } from "@lumorphia/editor-engine"; +import { ImageLoadError, loadImageFile, type LoadedImage } from "@lumorphia/editor-engine"; +import { downloadName, type EditorDestination, type EditorHost } from "./host.ts"; +import { DEFAULT_MODEL_BASE_URL } from "@lumorphia/editor-engine"; +import { aspectRatio, centeredCrop } from "@lumorphia/editor-engine"; +import type { EditorRenderer } from "@lumorphia/editor-engine/render"; +import { AdjustPanel } from "./AdjustPanel.tsx"; +import { PresetPanel } from "./PresetPanel.tsx"; +import { GeometryPanel } from "./GeometryPanel.tsx"; +import { ZOOM_STEP } from "@lumorphia/editor-engine"; +import { useCanvasGestures } from "./use-canvas-gestures.ts"; +import { CropOverlay } from "./CropOverlay.tsx"; +import { EllipseMaskOverlay } from "./EllipseMaskOverlay.tsx"; +import { BrushOverlay } from "./BrushOverlay.tsx"; +import { LocalPanel } from "./LocalPanel.tsx"; +import { + AUTO_SELECT_FAILED, + planFaceSelection, + planSegmentSelection, + type SegmentSelectionKind, +} from "@lumorphia/editor-engine"; +import type { FaceResult } from "@lumorphia/editor-engine"; +import { SAM_LEVELS } from "@lumorphia/editor-engine"; +import { TapOverlay } from "./TapOverlay.tsx"; +import type { Point } from "@lumorphia/editor-engine"; +import { PortraitPanel } from "./PortraitPanel.tsx"; +import { FaceBoxesOverlay } from "./FaceBoxesOverlay.tsx"; +import { PORTRAIT_FULL, buildPortraitItems, faceCenter } from "@lumorphia/editor-engine"; +import { + MAX_LOCAL_ADJUSTMENTS, + findPortraitPreset, + portraitAmount, + type PortraitPresetId, +} from "@lumorphia/editor-recipe"; +import { CompareSlider } from "./CompareSlider.tsx"; +import { EditorI18nProvider, useEditorI18n } from "./EditorI18n.tsx"; + +const ERROR_TEXT: Record = { + too_large: "30MB を超える画像は読み込めません。", + unsupported_format: "PNG または JPEG の画像を選んでください。", + decode_failed: "画像を読み込めませんでした。", + webgl: "このブラウザでは編集機能を使えません (WebGL が無効です)。", +}; + +const tabBtn = + "shrink-0 whitespace-nowrap px-2 py-1.5 text-sm border-b-2 border-transparent aria-selected:border-accent"; +const toolBtn = + "rounded border border-line-soft px-3 py-1.5 text-sm hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; + +/** Playwright からレシピ適用結果の画素を読むためのフック。ホストが有効にしたときだけ露出する。 */ +function installTestHook( + renderer: EditorRenderer, + getRecipe: () => EditRecipe, + hook: EditorHost["testHook"], +) { + if (!hook?.enabled()) return; + (window as unknown as Record)[hook.globalName] = { + async exportPixels(recipe: EditRecipe, points: { x: number; y: number }[]) { + const blob = await renderer.export(recipe, { format: "image/png" }); + const bitmap = await createImageBitmap(blob); + const c = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = c.getContext("2d"); + if (!ctx) throw new Error("no 2d context"); + ctx.drawImage(bitmap, 0, 0); + return { + width: bitmap.width, + height: bitmap.height, + type: blob.type, + pixels: points.map((p) => Array.from(ctx.getImageData(p.x, p.y, 1, 1).data).slice(0, 3)), + }; + }, + benchmark(recipe: EditRecipe, frames?: number) { + return renderer.benchmark(recipe, frames); + }, + viewRect() { + return renderer.viewRect; + }, + previewPixels(points: { x: number; y: number }[]) { + return renderer.previewPixels(points); + }, + currentRecipe() { + return getRecipe(); + }, + }; +} + +/** 現像エディタ。ホスト (下書きの置き場所、送り先、計測、表示言語) は外から渡す (ADR-0035) */ +export function Editor({ host }: { host: EditorHost }) { + return ( + + + + ); +} + +function EditorPage({ host }: { host: EditorHost }) { + const { t } = useEditorI18n(); + const modelBaseUrl = host.inference?.modelBaseUrl ?? DEFAULT_MODEL_BASE_URL; + const [state, dispatch] = useReducer(editorReducer, initialEditorState); + const hostRef = useRef(null); + const rendererRef = useRef(null); + const fileInput = useRef(null); + const [view, setView] = useState({ x: 0, y: 0, width: 1, height: 1, scale: 1 }); + // 編集画面の使われ方 (#344)。開いたことを 1 回だけ送る (StrictMode の 2 回目の effect では送らない) + const openReported = useRef(false); + useEffect(() => { + if (openReported.current) return; + openReported.current = true; + host.telemetry?.({ type: "open" }); + }, []); + const [ready, setReady] = useState(false); + + const recipe = state.history.present; + const recipeRef = useRef(recipe); + recipeRef.current = recipe; + + // PixiJS は SSR 不可なので動的 import (docs/design/08 §1) + useEffect(() => { + let disposed = false; + let renderer: EditorRenderer | null = null; + (async () => { + const container = hostRef.current; + if (!container) return; + try { + const { EditorRenderer } = await import("@lumorphia/editor-engine/render"); + renderer = await EditorRenderer.create(container); + if (disposed) { + renderer.destroy(); + return; + } + rendererRef.current = renderer; + // 置き直し (fit / zoom / resize) はすべてここを通る。オーバーレイの位置の唯一の出どころ + renderer.onView = setView; + setReady(true); + installTestHook(renderer, () => recipeRef.current, host.testHook); + } catch (e) { + // 原因を飲み込まない (CSP や WebGL の不調を切り分けられるように) + console.error("editor renderer failed", e); + dispatch({ type: "ui/error", error: ERROR_TEXT.webgl ?? "WebGL error" }); + } + })(); + return () => { + disposed = true; + rendererRef.current = null; + renderer?.destroy(); + }; + }, []); + + // レシピ変更をレンダラへ反映 (view は renderer.onView で追従する) + useEffect(() => { + const r = rendererRef.current; + if (!r || !state.source) return; + r.setRecipe(recipe); + }, [recipe, state.source]); + + useEffect(() => { + rendererRef.current?.setCompare(state.ui.comparing, state.ui.comparePosition); + }, [state.ui.comparing, state.ui.comparePosition]); + + // 部分補正 (#109): 部分補正タブで選択中の範囲を赤で重ねる + const selectedLocal = + recipe.localAdjustments.find((l) => l.id === state.ui.local.selectedId) ?? null; + // 赤い重ねは、描いている間 (ブラシ・円形のドラッグ中) か「範囲を表示」をオンにしたときだけ。 + // 常時だと補正の効きが赤に埋もれて見えない + const maskPreviewId = + state.ui.tool === "local" && + (state.ui.local.showMask || state.ui.local.drawing) && + !state.ui.comparing + ? (selectedLocal?.id ?? null) + : null; + useEffect(() => { + rendererRef.current?.setMaskPreview(maskPreviewId); + }, [maskPreviewId, state.source]); + + // ズームと移動 (docs/design/08 §3.3): ホイールでズーム、ドラッグで移動、2 本指でピンチ + const gestureTarget = useCallback( + () => (state.source ? rendererRef.current : null), + [state.source], + ); + useCanvasGestures(hostRef, gestureTarget, Boolean(state.source)); + + /** + * 新しい円形を今見えている範囲の中央に置く。半径は見えている範囲の短辺の 1/4 (拡大中は小さく)、 + * 既定 (画像の 12%) を上限にする + */ + const ellipseAtView = () => { + const r = rendererRef.current; + if (!r || !state.source) return undefined; + const { uv, visible } = r.visibleCenter; + const short = Math.min(visible.width, visible.height) / 4; + return { + cx: uv.x, + cy: uv.y, + rx: Math.min(DEFAULT_ELLIPSE_MASK.rx, short / state.source.bitmap.width), + ry: Math.min(DEFAULT_ELLIPSE_MASK.ry, short / state.source.bitmap.height), + }; + }; + + // 自動選択 (#176): 顔の検出結果は画像 (draftId) ごとに 1 回だけ取り、瞳・美肌で使い回す。 + // 検出のライブラリ (WASM) は押したときに動的 import する (現像の初期表示に載せない) + const facesRef = useRef<{ draftId: string; faces: FaceResult[] } | null>(null); + /** 顔の検出 (画像ごとに 1 回)。失敗は null (文言は呼ぶ側で出す) */ + const detectFacesOnce = async ( + source: LoadedImage, + draftId: string, + ): Promise => { + if (facesRef.current?.draftId === draftId) return facesRef.current.faces; + dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); + try { + const { detectFaces } = await import("@lumorphia/editor-engine/inference/face"); + const faces = await detectFaces(source.bitmap, { + modelBaseUrl, + onProgress: (progress) => + dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), + }); + facesRef.current = { draftId, faces }; + return faces; + } catch (e) { + console.error("face detection failed", e); + return null; + } finally { + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + }; + /** 画像の埋め込み (SAM、画像ごとに 1 回)。失敗は false */ + const prepareSegmenterOnce = async (source: LoadedImage): Promise => { + dispatch({ type: "ui/inference", inference: { status: "loading", progress: null } }); + try { + const { prepareSegmenter } = await import("@lumorphia/editor-engine/inference/segment"); + await prepareSegmenter(source.bitmap, { + modelBaseUrl, + onProgress: (progress) => + dispatch({ type: "ui/inference", inference: { status: "loading", progress } }), + }); + return true; + } catch (e) { + console.error("segmenter failed", e); + return false; + } finally { + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + }; + + // 人物補正 (#175): 検出 → 人物を選ぶ → プリセットで 5 件 (背景・人物・顔・瞳 ×2) を 1 手で置く + const portraitDetect = async () => { + const source = state.source; + const draftId = state.draftId; + if (!source || !draftId || state.ui.local.inference.status !== "idle") return; + const faces = await detectFacesOnce(source, draftId); + if (!faces) { + dispatch({ type: "portrait/faces", faces: [] }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "portrait/faces", faces }); + if (faces.length === 0) dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + }; + const portraitApply = async (presetId: PortraitPresetId) => { + const source = state.source; + const faces = state.ui.portrait.faces; + const face = faces?.[state.ui.portrait.selectedFace]; + if (!source || !face || state.ui.local.inference.status !== "idle") return; + if (activePortraitGroup(state)) { + dispatch({ type: "portrait/preset", presetId }); + return; + } + const preset = findPortraitPreset(presetId); + if (!preset) return; + // 1 人で最大 5 件 (背景・人物・顔・瞳 ×2) 使う。入り切らなければ先に伝える + if (MAX_LOCAL_ADJUSTMENTS - recipe.localAdjustments.length < 5) { + dispatch({ type: "ui/notice", notice: PORTRAIT_FULL }); + return; + } + if (!(await prepareSegmenterOnce(source))) { + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "ui/inference", inference: { status: "running", progress: null } }); + try { + const { segmentAt } = await import("@lumorphia/editor-engine/inference/segment"); + const center = faceCenter(face); + const { masks } = await segmentAt(center.x, center.y); + const person = masks[0]; + if (!person || person.kind !== "bitmap") throw new Error("no person mask"); + dispatch({ + type: "portrait/apply", + items: buildPortraitItems(face, person, preset, 100), + presetId, + }); + } catch (e) { + console.error("portrait failed", e); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + } finally { + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + } + }; + const portraitGroupId = activePortraitGroup(state); + const portraitEffect = (() => { + const { presetId } = state.ui.portrait; + const preset = presetId ? findPortraitPreset(presetId) : undefined; + return portraitGroupId && preset ? portraitAmount(recipe, portraitGroupId, preset) : 100; + })(); + + const autoSelect = async (kind: "eyes" | "skin" | SegmentSelectionKind) => { + const source = state.source; + const draftId = state.draftId; + if (!source || !draftId || state.ui.local.inference.status !== "idle") return; + if (kind === "gear" || kind === "person" || kind === "background") { + // タップで切る (#177): 画像の埋め込み (初回は数秒) を済ませてからタップを待つ + if (!(await prepareSegmenterOnce(source))) { + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + dispatch({ type: "ui/tap", tap: kind }); + return; + } + const faces = await detectFacesOnce(source, draftId); + if (!faces) { + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + return; + } + const plan = planFaceSelection(kind, faces); + if (plan.items.length > 0) { + dispatch({ type: "local/add-auto", items: plan.items, label: plan.label }); + } + if (plan.notice) dispatch({ type: "ui/notice", notice: plan.notice }); + }; + + const onTap = async (uv: Point) => { + const kind = state.ui.local.tap; + if (!kind) return; + dispatch({ type: "ui/inference", inference: { status: "running", progress: null } }); + try { + const { segmentAt } = await import("@lumorphia/editor-engine/inference/segment"); + const { masks } = await segmentAt(uv.x, uv.y); + const plan = planSegmentSelection(kind, masks); + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + if (plan.items.length > 0) { + dispatch({ + type: "local/add-auto", + items: plan.items, + label: plan.label, + candidates: masks, + }); + } else { + dispatch({ type: "ui/tap", tap: null }); + } + if (plan.notice) dispatch({ type: "ui/notice", notice: plan.notice }); + } catch (e) { + console.error("segmentation failed", e); + dispatch({ type: "ui/inference", inference: { status: "idle", progress: null } }); + dispatch({ type: "ui/tap", tap: null }); + dispatch({ type: "ui/notice", notice: AUTO_SELECT_FAILED }); + } + }; + const onSegmentLevel = (localId: string, index: number) => { + const candidate = state.ui.local.segment?.masks[index]; + const target = recipe.localAdjustments.find((l) => l.id === localId); + if (!candidate || !target || target.mask.kind !== "bitmap") return; + // 反転 (背景) と塗り足したストロークは保ったまま、下地だけ差し替える + const mask = { + ...candidate, + ...(candidate.kind === "bitmap" + ? { invert: target.mask.invert, strokes: target.mask.strokes } + : {}), + }; + dispatch({ + type: "local/mask-commit", + id: localId, + mask, + label: `切り抜き: ${SAM_LEVELS[index]?.label ?? index}`, + }); + }; + + const zoomBy = (factor: number) => rendererRef.current?.zoomBy(factor); + const zoomFit = () => rendererRef.current?.resetView(); + const zoomActual = () => rendererRef.current?.zoomToActual(); + // 表示倍率 (元画像の px に対して)。デバイスの px ではなく CSS px + const zoomPercent = Math.round(view.scale * 100); + + // 下書きを自動保存 (レシピ確定ごと) + useEffect(() => { + if (!state.source || !state.draftId) return; + const { source, draftId } = state; + void host.drafts.save({ + id: draftId, + name: source.name, + blob: source.blob, + recipe, + updatedAt: Date.now(), + }); + }, [state.source, state.draftId, recipe, state]); + + const openFile = useCallback(async (file: File, draft?: { id: string; recipe: EditRecipe }) => { + try { + const image = await loadImageFile(file); + const draftId = draft?.id ?? crypto.randomUUID(); + const r = rendererRef.current; + dispatch({ + type: "image/loaded", + image, + draftId, + ...(draft ? { recipe: draft.recipe } : {}), + }); + r?.setImage(image.bitmap, draft?.recipe ?? initialEditorState.history.present); + } catch (e) { + const reason = e instanceof ImageLoadError ? e.reason : "decode_failed"; + dispatch({ type: "image/failed", error: ERROR_TEXT[reason] ?? reason }); + } + }, []); + + // 開いたときの下書き (prismtone は /edit?draft=、投稿設定の「現像をやり直す」#64)。 + // 下書きの原本とレシピを開き直し、同じ draftId で書き出す + const requestedDraft = host.initialDraftId ?? null; + useEffect(() => { + if (!requestedDraft) return; + let cancelled = false; + void host.drafts.load(requestedDraft).then((draft) => { + if (cancelled) return; + // 1 回きり。リロードで再適用されないよう、ホストが外す + host.onInitialDraftConsumed?.(); + if (!draft) { + dispatch({ + type: "ui/error", + error: "元の画像が端末に残っていないため、もう一度画像を選んでください。", + }); + return; + } + void openFile(new File([draft.blob], draft.name, { type: draft.blob.type }), { + id: draft.id, + recipe: draft.recipe, + }); + }); + return () => { + cancelled = true; + }; + // openFile は安定、host は毎回変わりうるので依存から外す (react-hooks の lint は入れていない) + }, [requestedDraft]); + + // 画像が後から来た場合 (レンダラ初期化前に読み込んだ) の反映 + useEffect(() => { + const r = rendererRef.current; + if (ready && r && state.source) r.setImage(state.source.bitmap, recipe); + // recipe は setRecipe 側の effect で追従するため依存に含めない + }, [ready, state.source]); + + const exportBlob = useCallback(async (r: EditRecipe) => { + const renderer = rendererRef.current; + if (!renderer) throw new Error("renderer not ready"); + dispatch({ type: "ui/exporting", on: true }); + try { + return await renderer.export(r); + } finally { + dispatch({ type: "ui/exporting", on: false }); + } + }, []); + + const onSave = async () => { + if (!state.source) return; + try { + const blob = await exportBlob(recipe); + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = downloadName(state.source.name, blob.type, host.download?.fileSuffix ?? ""); + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 10_000); + host.telemetry?.({ type: "save" }); + } catch { + dispatch({ type: "ui/error", error: t("書き出しに失敗しました。", "Export failed.") }); + } + }; + + const onSend = async (destination: EditorDestination) => { + if (!state.source || !state.draftId) return; + try { + const blob = await exportBlob(recipe); + await destination.send({ + blob, + recipe, + original: state.source.blob, + sourceName: state.source.name, + draftId: state.draftId, + }); + // 送れたときだけ数える (上限で断られたら数えない)。送り先が画面を移しても届くよう、計測は keepalive で送る + host.telemetry?.({ type: "send", destinationId: destination.id }); + } catch (error) { + dispatch({ + type: "ui/error", + error: + error instanceof Error ? error.message : t("書き出しに失敗しました。", "Export failed."), + }); + } + }; + + const onAspect = (aspect: EditRecipe["geometry"]["aspect"]) => { + const r = rendererRef.current; + const ratio = aspectRatio(aspect); + const crop = ratio && r ? centeredCrop(r.canvasSize, ratio) : recipe.geometry.crop; + dispatch({ + type: "geometry/commit", + patch: { aspect, crop: aspect === "free" ? recipe.geometry.crop : crop }, + }); + if (aspect !== "free") dispatch({ type: "ui/cropping", on: true }); + }; + + const startCropping = (on: boolean) => { + if (on && !recipe.geometry.crop) { + dispatch({ type: "geometry/commit", patch: { crop: { x: 0.1, y: 0.1, w: 0.8, h: 0.8 } } }); + } + dispatch({ type: "ui/cropping", on }); + }; + + // キーボード: Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (!(e.ctrlKey || e.metaKey)) return; + if (e.key === "z" && !e.shiftKey) { + e.preventDefault(); + dispatch({ type: "history/undo" }); + } else if ((e.key === "z" && e.shiftKey) || e.key === "y") { + e.preventDefault(); + dispatch({ type: "history/redo" }); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); + + const hasImage = Boolean(state.source); + // 書き出しはレンダラが要る。画像の読み込みより WebGL の初期化が遅れることがある (CI の headless で顕著) ので、 + // 準備できるまで押せない + const canExport = hasImage && ready && !state.ui.exporting; + const lastOp = undoLabel(state.history); + const nextOp = redoLabel(state.history); + const undoTitle = lastOp + ? t(`${lastOp} を取り消す (Ctrl+Z)`, `Undo ${lastOp} (Ctrl+Z)`) + : t("取り消す操作はありません", "Nothing to undo"); + const redoTitle = nextOp + ? t(`${nextOp} をやり直す (Ctrl+Shift+Z)`, `Redo ${nextOp} (Ctrl+Shift+Z)`) + : t("やり直す操作はありません", "Nothing to redo"); + const canvasRatio = rendererRef.current + ? rendererRef.current.canvasSize.width / rendererRef.current.canvasSize.height + : 1; + + return ( +
+ {/* min-w-0: canvas の明示幅で flex の子が縮めなくなり、窓を狭めたとき右パネルが押し出されるのを防ぐ */} +
+
+ { + const f = e.currentTarget.files?.[0]; + if (f) void openFile(f); + e.currentTarget.value = ""; + }} + /> + + + + + {lastOp && ( + + {t("最後の操作", "Last action")}: {lastOp} + + )} + + + + + + + + + + {host.destinations.map((destination) => ( + + ))} +
+ {state.ui.error && ( +

+ {state.ui.error} +

+ )} +
e.preventDefault()} + onDrop={(e) => { + e.preventDefault(); + const f = e.dataTransfer.files[0]; + if (f) void openFile(f); + }} + > + {!hasImage && ( +

+ {t( + "PNG / JPEG をドロップするか「画像を開く」を押してください", + "Drop a PNG or JPEG here, or select Open image", + )} +

+ )} + {hasImage && state.ui.comparing && !state.ui.cropping && ( + dispatch({ type: "ui/compare-position", position })} + /> + )} + {hasImage && + state.source && + state.ui.tool === "local" && + selectedLocal?.mask.kind === "ellipse" && + state.ui.local.showHandles && + !state.ui.comparing && + !state.ui.cropping && ( + + dispatch({ type: "local/mask-preview", id: selectedLocal.id, mask }) + } + onCommit={(mask) => + dispatch({ type: "local/mask-commit", id: selectedLocal.id, mask }) + } + onDrawing={(on) => dispatch({ type: "ui/drawing", on })} + /> + )} + {hasImage && + state.source && + state.ui.tool === "local" && + selectedLocal && + selectedLocal.mask.kind !== "ellipse" && + !state.ui.comparing && + !state.ui.cropping && ( + + rendererRef.current?.previewStroke(selectedLocal.id, segment) + } + onCommit={(stroke) => + dispatch({ type: "local/stroke-commit", id: selectedLocal.id, stroke }) + } + onDrawing={(on) => dispatch({ type: "ui/drawing", on })} + onCancel={() => rendererRef.current?.discardPreviewStroke(selectedLocal.id)} + /> + )} + {hasImage && + state.source && + state.ui.tool === "local" && + state.ui.local.tap && + !state.ui.cropping && ( + void onTap(uv)} + onCancel={() => dispatch({ type: "ui/tap", tap: null })} + /> + )} + {hasImage && + state.source && + state.ui.tool === "portrait" && + (state.ui.portrait.faces?.length ?? 0) > 1 && + !state.ui.comparing && + !state.ui.cropping && ( + dispatch({ type: "portrait/select-face", index })} + /> + )} + {hasImage && state.ui.cropping && recipe.geometry.crop && ( + dispatch({ type: "geometry/preview", patch: { crop } })} + onCommit={(crop) => dispatch({ type: "geometry/commit", patch: { crop } })} + /> + )} +
+
+ + +
+ ); +} diff --git a/packages/editor-react/src/EllipseMaskOverlay.tsx b/packages/editor-react/src/EllipseMaskOverlay.tsx new file mode 100644 index 0000000..9585df8 --- /dev/null +++ b/packages/editor-react/src/EllipseMaskOverlay.tsx @@ -0,0 +1,158 @@ +import { useRef } from "react"; +import type { EllipseMaskV2, GeometryV1 } from "@lumorphia/editor-recipe"; +import { canvasToImageUv, imageUvToCanvas, type Point } from "@lumorphia/editor-engine"; +import { totalRotationDeg, type Size } from "@lumorphia/editor-engine"; +import { + dragEllipse, + ellipseHandles, + ROTATE_HANDLE_OFFSET_PX, + type EllipseHandle, +} from "./ellipse-drag.ts"; + +type View = { x: number; y: number; width: number; height: number; scale: number }; + +type Props = { + view: View; + source: Size; + geometry: GeometryV1; + mask: EllipseMaskV2; + onPreview: (mask: EllipseMaskV2) => void; + onCommit: (mask: EllipseMaskV2) => void; + /** ドラッグしている間 true。範囲の赤い重ねを出すために使う */ + onDrawing: (on: boolean) => void; +}; + +/** + * 円形マスクの DOM オーバーレイ (#109)。CropOverlay と同じ作りで、ドラッグ中は onPreview、離したら onCommit。 + * マスクは幾何を掛ける前の画像座標で持つので、画面 (view) との往復は mask-math の変換を通す。 + * 楕円の輪郭は SVG に「画像 px → 画面 px」の行列を掛けて描く (回転・反転にそのまま追従する)。 + */ +export function EllipseMaskOverlay({ + view, + source, + geometry, + mask, + onPreview, + onCommit, + onDrawing, +}: Props) { + const drag = useRef<{ handle: EllipseHandle; start: EllipseMaskV2; from: Point } | null>(null); + + const viewToUv = (clientX: number, clientY: number, host: DOMRect): Point => { + const canvas = { + x: (clientX - host.left - view.x) / view.scale, + y: (clientY - host.top - view.y) / view.scale, + }; + return canvasToImageUv(canvas, source, geometry); + }; + const uvToView = (uv: Point) => { + const c = imageUvToCanvas(uv, source, geometry); + return { x: view.x + c.x * view.scale, y: view.y + c.y * view.scale }; + }; + const hostRect = (e: React.PointerEvent) => + (e.currentTarget as HTMLElement).closest("[data-testid=canvas-host]")!.getBoundingClientRect(); + + const onPointerDown = (handle: EllipseHandle) => (e: React.PointerEvent) => { + e.preventDefault(); + e.stopPropagation(); + (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); + drag.current = { handle, start: mask, from: viewToUv(e.clientX, e.clientY, hostRect(e)) }; + onDrawing(true); + }; + const next = (e: React.PointerEvent) => { + const d = drag.current; + if (!d) return null; + return dragEllipse( + d.start, + d.handle, + d.from, + viewToUv(e.clientX, e.clientY, hostRect(e)), + source, + ); + }; + const onPointerMove = (e: React.PointerEvent) => { + const m = next(e); + if (m) onPreview(m); + }; + const onPointerUp = (e: React.PointerEvent) => { + const m = next(e); + drag.current = null; + onDrawing(false); + if (m) onCommit(m); + }; + + // 画像 px → 画面 px: translate(view) scale(s) translate(center) rotate(θ) scale(flip, 1) translate(-W/2, -H/2) + const center = imageUvToCanvas({ x: 0.5, y: 0.5 }, source, geometry); + const matrix = [ + `translate(${view.x} ${view.y})`, + `scale(${view.scale})`, + `translate(${center.x} ${center.y})`, + `rotate(${totalRotationDeg(geometry)})`, + `scale(${geometry.flipH ? -1 : 1} 1)`, + `translate(${-source.width / 2} ${-source.height / 2})`, + ].join(" "); + const handles = ellipseHandles(mask, source, ROTATE_HANDLE_OFFSET_PX / view.scale); + const cx = mask.cx * source.width; + const cy = mask.cy * source.height; + const handleDot = (name: Exclude, cursor: string, label: string) => { + const p = uvToView(handles[name]); + return ( +
+ ); +} diff --git a/packages/editor-react/src/FaceBoxesOverlay.tsx b/packages/editor-react/src/FaceBoxesOverlay.tsx new file mode 100644 index 0000000..6fa058c --- /dev/null +++ b/packages/editor-react/src/FaceBoxesOverlay.tsx @@ -0,0 +1,60 @@ +import type { GeometryV1 } from "@lumorphia/editor-recipe"; +import type { FaceResult } from "@lumorphia/editor-engine"; +import { imageUvToCanvas } from "@lumorphia/editor-engine"; +import type { Size } from "@lumorphia/editor-engine"; + +type View = { x: number; y: number; width: number; height: number; scale: number }; + +type Props = { + view: View; + source: Size; + geometry: GeometryV1; + faces: readonly FaceResult[]; + selected: number; + onSelect: (index: number) => void; +}; + +/** 人物補正 (#175) で複数の顔があるとき、番号付きの枠を重ねて選ばせる。幾何 (回転・反転) を追う */ +export function FaceBoxesOverlay({ view, source, geometry, faces, selected, onSelect }: Props) { + const toScreen = (x: number, y: number) => { + const c = imageUvToCanvas({ x, y }, source, geometry); + return { x: view.x + c.x * view.scale, y: view.y + c.y * view.scale }; + }; + return ( +
+ {faces.map((f, i) => { + const [x0, y0, x1, y1] = f.bbox; + // 回転しても囲えるように 4 隅を写してから外接矩形を取る + const corners = [toScreen(x0, y0), toScreen(x1, y0), toScreen(x1, y1), toScreen(x0, y1)]; + const left = Math.min(...corners.map((c) => c.x)); + const top = Math.min(...corners.map((c) => c.y)); + const right = Math.max(...corners.map((c) => c.x)); + const bottom = Math.max(...corners.map((c) => c.y)); + const active = i === selected; + return ( + + ); + })} +
+ ); +} diff --git a/packages/editor-react/src/GeometryPanel.tsx b/packages/editor-react/src/GeometryPanel.tsx new file mode 100644 index 0000000..6c30cc9 --- /dev/null +++ b/packages/editor-react/src/GeometryPanel.tsx @@ -0,0 +1,107 @@ +import { ASPECT_PRESETS, type GeometryV1 } from "@lumorphia/editor-recipe"; +import { Slider } from "./Slider.tsx"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type Props = { + geometry: GeometryV1; + cropping: boolean; + onPreview: (patch: Partial) => void; + onCommit: (patch: Partial) => void; + onCropping: (on: boolean) => void; + onAspect: (aspect: GeometryV1["aspect"]) => void; +}; + +const ASPECT_LABEL: Record<(typeof ASPECT_PRESETS)[number], string> = { + free: "自由", + "1:1": "1:1", + "4:3": "4:3", + "3:2": "3:2", + "16:9": "16:9", + "9:16": "9:16", + "3:4": "3:4", + "2:3": "2:3", +}; + +const btn = + "rounded border border-line-soft px-3 py-1.5 text-sm hover:bg-surface-hover aria-pressed:bg-accent aria-pressed:text-accent-ink"; + +export function GeometryPanel({ + geometry, + cropping, + onPreview, + onCommit, + onCropping, + onAspect, +}: Props) { + const { t } = useEditorI18n(); + const rotate = (delta: 90 | -90) => { + const next = (((geometry.rotation + delta) % 360) + 360) % 360; + onCommit({ rotation: next as GeometryV1["rotation"], crop: null }); + }; + return ( +
+
+ + + +
+ `${v.toFixed(1)}°`} + onPreview={(v) => onPreview({ straighten: v })} + onCommit={(v) => onCommit({ straighten: v })} + onReset={() => onCommit({ straighten: 0 })} + /> +
+

{t("アスペクト比", "Aspect ratio")}

+
+ {ASPECT_PRESETS.map((a) => ( + + ))} +
+
+
+ + {geometry.crop && ( + + )} +
+
+ ); +} diff --git a/packages/editor-react/src/LocalPanel.tsx b/packages/editor-react/src/LocalPanel.tsx new file mode 100644 index 0000000..5f4c64d --- /dev/null +++ b/packages/editor-react/src/LocalPanel.tsx @@ -0,0 +1,396 @@ +import { + LOCAL_PRESETS, + MAX_LOCAL_ADJUSTMENTS, + MAX_LOCAL_BLUR, + MAX_LOCAL_SMOOTH, + type LocalAdjust, + type LocalAdjustment, + type LocalPresetId, +} from "@lumorphia/editor-recipe"; +import { LOCAL_ADJUST_LABELS } from "@lumorphia/editor-recipe/labels"; +import type { BrushSettings, EditorState, InferenceStatus } from "@lumorphia/editor-engine"; +import type { SegmentSelectionKind } from "@lumorphia/editor-engine"; +import { SAM_LEVELS } from "@lumorphia/editor-engine"; +import { Slider } from "./Slider.tsx"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type Props = { + list: readonly LocalAdjustment[]; + selectedId: string | null; + showMask: boolean; + showHandles: boolean; + brush: BrushSettings; + inference: InferenceStatus; + notice: string | null; + /** タップ待ち (#177) と、直近のタップの 3 段の候補 */ + tap: SegmentSelectionKind | null; + segment: EditorState["ui"]["local"]["segment"]; + onAdd: (kind: "ellipse" | "brush", presetId?: LocalPresetId) => void; + /** 瞳・美肌は顔を検出して置く (#176)、装備・キャラクター・背景はタップで切る (#177)。無ければ手動の追加に落ちる */ + onAuto?: ((kind: "eyes" | "skin" | SegmentSelectionKind) => void) | undefined; + onCancelTap?: (() => void) | undefined; + /** 切り抜きの粒度を切り替える (segment の候補の index) */ + onSegmentLevel?: ((localId: string, index: number) => void) | undefined; + onBrush: (brush: BrushSettings) => void; + onSelect: (id: string | null) => void; + onRemove: (id: string) => void; + onToggleVisible: (id: string) => void; + onPreset: (id: string, presetId: LocalPresetId) => void; + onAmountPreview: (id: string, value: number) => void; + onAmountCommit: (id: string, value: number) => void; + onAdjustPreview: (id: string, key: keyof LocalAdjust, value: number) => void; + onAdjustCommit: (id: string, key: keyof LocalAdjust, value: number) => void; + onShowMask: (on: boolean) => void; + onShowHandles: (on: boolean) => void; +}; + +const ROWS: { key: keyof LocalAdjust; min: number; max: number; step: number; ev?: boolean }[] = [ + { key: "exposure", min: -5, max: 5, step: 0.05, ev: true }, + { key: "contrast", min: -100, max: 100, step: 1 }, + { key: "highlights", min: -100, max: 100, step: 1 }, + { key: "shadows", min: -100, max: 100, step: 1 }, + { key: "temperature", min: -100, max: 100, step: 1 }, + { key: "tint", min: -100, max: 100, step: 1 }, + { key: "saturation", min: -100, max: 100, step: 1 }, + { key: "sharpen", min: 0, max: 100, step: 1 }, + { key: "smooth", min: 0, max: MAX_LOCAL_SMOOTH, step: 1 }, + { key: "blur", min: 0, max: MAX_LOCAL_BLUR, step: 1 }, + { key: "bloom", min: 0, max: 100, step: 1 }, + { key: "vignette", min: 0, max: 100, step: 1 }, + { key: "clarity", min: -100, max: 100, step: 1 }, +]; + +const btn = + "rounded border border-line-soft px-2 py-1 text-xs hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; + +const MASK_KIND_LABELS: Record = { + ellipse: "円形", + brush: "ブラシ", + polygon: "多角形", + bitmap: "切り抜き", +}; + +/** 粒度の切り替えで下地だけ差し替えるので、反転やストロークが違っても同じ候補なら同じとみなす */ +function isSameBitmap(a: LocalAdjustment["mask"], b: LocalAdjustment["mask"] | undefined): boolean { + return a.kind === "bitmap" && b?.kind === "bitmap" && a.rle === b.rle; +} + +function localName(l: LocalAdjustment, index: number): string { + if (l.name) return l.name; + const preset = LOCAL_PRESETS.find((p) => p.id === l.presetId); + const kind = MASK_KIND_LABELS[l.mask.kind]; + return preset ? `${preset.name} (${kind})` : `部分補正 ${index + 1} (${kind})`; +} + +/** 部分補正のパネル (#109): 一覧、追加 (円形 / ブラシ)、ブラシの設定、プリセット、効果量とスライダー */ +export function LocalPanel(p: Props) { + const { t, tx } = useEditorI18n(); + const selected = p.list.find((l) => l.id === p.selectedId) ?? null; + const full = p.list.length >= MAX_LOCAL_ADJUSTMENTS; + const busy = p.inference.status !== "idle"; + return ( +
+
+ + + + {p.list.length} / {MAX_LOCAL_ADJUSTMENTS} + + + + +
+ {p.list.length === 0 ? ( +

+ {t( + "範囲を選んで、そこだけに補正を掛けます。「円形を追加」で始めるか、プリセットを選んでください。", + "Select an area to adjust only that part. Add an ellipse or choose a preset to begin.", + )} +

+ ) : ( +
    + {p.list.map((l, i) => ( +
  • + + + +
  • + ))} +
+ )} + {selected && selected.mask.kind !== "ellipse" && ( +
+
+ + {t("キャンバスをなぞって範囲を塗る", "Paint an area on the canvas")} + + + {( + [ + ["add", "塗る"], + ["erase", "消す"], + ] as const + ).map(([mode, label]) => ( + + ))} +
+ `${v}%`} + onPreview={(v) => p.onBrush({ ...p.brush, size: v / 100 })} + onCommit={(v) => p.onBrush({ ...p.brush, size: v / 100 })} + /> + `${v}%`} + onPreview={(v) => p.onBrush({ ...p.brush, hardness: v / 100 })} + onCommit={(v) => p.onBrush({ ...p.brush, hardness: v / 100 })} + /> +
+ )} +
+

+ {selected + ? t("選択中の範囲に適用", "Apply to selected area") + : p.onAuto + ? t( + "瞳・美肌は顔を認識して置き、装備は画像をタップして切り抜きます", + "Eyes and skin use face detection; tap the image to select gear.", + ) + : t( + "新しいマスクを追加して適用 (瞳・美肌は円形、装備はブラシ)", + "Add a new mask (ellipse for eyes or skin, brush for gear)", + )} +

+
+ {LOCAL_PRESETS.map((preset) => ( + + ))} +
+ {p.onAuto && selected && ( +
+ + {t("自動選択で追加:", "Add with auto selection:")} + + {LOCAL_PRESETS.map((preset) => ( + + ))} +
+ )} + {p.onAuto && ( +
+ + {t("タップで範囲だけ選ぶ:", "Select an area by tapping:")} + + + +
+ )} + {p.tap && ( +

+ {t( + `画像の中の${p.tap === "gear" ? "装備" : "キャラクター"}をタップしてください`, + `Tap the ${p.tap === "gear" ? "gear" : "character"} in the image`, + )} + +

+ )} + {selected && p.segment?.localId === selected.id && p.onSegmentLevel && ( +
+ + {t("切り抜きの範囲:", "Selection scope:")} + + {SAM_LEVELS.map((level) => ( + + ))} +
+ )} + {busy && ( +

+ {p.inference.status === "loading" && p.inference.progress + ? t( + `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + `Loading detection data (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + ) + : p.inference.status === "loading" + ? t("認識の準備をしています…", "Preparing detection…") + : t("画像を読み取っています…", "Analyzing image…")} +

+ )} + {p.notice && !busy && ( +

+ {tx(p.notice)} +

+ )} +
+ {selected && ( +
+ p.onAmountPreview(selected.id, v)} + onCommit={(v) => p.onAmountCommit(selected.id, v)} + onReset={() => p.onAmountCommit(selected.id, 100)} + /> + {ROWS.map((r) => ( + `${v >= 0 ? "+" : ""}${v.toFixed(2)}` + : r.key === "blur" + ? (v) => `${v}px` + : (v) => `${v > 0 ? "+" : ""}${v}` + } + onPreview={(v) => p.onAdjustPreview(selected.id, r.key, v)} + onCommit={(v) => p.onAdjustCommit(selected.id, r.key, v)} + onReset={() => p.onAdjustCommit(selected.id, r.key, 0)} + /> + ))} +
+ )} +
+ ); +} diff --git a/packages/editor-react/src/PortraitPanel.tsx b/packages/editor-react/src/PortraitPanel.tsx new file mode 100644 index 0000000..06da812 --- /dev/null +++ b/packages/editor-react/src/PortraitPanel.tsx @@ -0,0 +1,165 @@ +import { PORTRAIT_PRESETS, type PortraitPresetId } from "@lumorphia/editor-recipe"; +import type { FaceResult } from "@lumorphia/editor-engine"; +import type { InferenceStatus } from "@lumorphia/editor-engine"; +import { Slider } from "./Slider.tsx"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type Props = { + faces: readonly FaceResult[] | null; + selectedFace: number; + groupId: string | null; + presetId: PortraitPresetId | null; + /** グループの効果量 0..100 */ + amount: number; + inference: InferenceStatus; + notice: string | null; + onDetect: () => void; + onSelectFace: (index: number) => void; + onApply: (presetId: PortraitPresetId) => void; + onAmountPreview: (value: number) => void; + onAmountCommit: (value: number) => void; + /** 部分補正タブへ (自動で置いた 5 件を個別に直す) */ + onGoLocal: () => void; +}; + +const btn = + "rounded border border-line-soft px-2 py-1 text-xs hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"; + +/** + * 人物補正 (#175): 人物を検出 → (複数なら) 選ぶ → プリセット → 効果量。 + * 中身は部分補正 5 件 (背景・人物・顔・瞳 ×2) で、部分補正タブで個別に直せる + */ +export function PortraitPanel(p: Props) { + const { t, tx } = useEditorI18n(); + const busy = p.inference.status !== "idle"; + const faces = p.faces ?? []; + return ( +
+

+ {t( + "人物を認識して、顔・瞳・人物・背景をまとめて整えます。認識も補正もこの端末の中だけで行います。", + "Detect a person and adjust their face, eyes, body, and background together. Detection and editing stay on this device.", + )} +

+ {p.faces === null ? ( + + ) : faces.length === 0 ? ( +

+ {p.notice + ? tx(p.notice) + : t( + "自動選択できませんでした。手動で範囲を指定できます", + "Automatic selection failed. You can select an area manually.", + )} + +

+ ) : ( + <> + {faces.length > 1 && ( +
+ {t("補正する人物:", "Person:")} + {faces.map((_, i) => ( + + ))} + + {t( + "(画像の番号をタップしても選べます)", + "(You can also tap a number on the image)", + )} + +
+ )} +
+

+ {p.groupId + ? t("プリセットを切り替える", "Switch preset") + : t("プリセットを選ぶと補正を置きます", "Choose a preset to apply adjustments")} +

+
+ {PORTRAIT_PRESETS.map((preset) => ( + + ))} +
+
+ {p.groupId && ( +
+ p.onAmountCommit(100)} + /> +

+ {t( + "顔・瞳・人物・背景のマスクは", + "Edit the face, eyes, person, and background masks under", + )}{" "} + + {t( + "で個別に直せます (ブラシで足す / 消す、値の調整)。", + " (paint, erase, or adjust individual values).", + )} +

+
+ )} + + )} + {busy && ( +

+ {p.inference.status === "loading" && p.inference.progress + ? t( + `認識用のデータを読み込んでいます (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + `Loading detection data (${Math.round((p.inference.progress.loaded / p.inference.progress.total) * 100)}%)`, + ) + : p.inference.status === "loading" + ? t("認識の準備をしています…", "Preparing detection…") + : t("人物を認識しています…", "Detecting people…")} +

+ )} + {p.notice && !busy && faces.length > 0 && ( +

+ {tx(p.notice)} +

+ )} +
+ ); +} diff --git a/packages/editor-react/src/PresetPanel.tsx b/packages/editor-react/src/PresetPanel.tsx new file mode 100644 index 0000000..b6d7473 --- /dev/null +++ b/packages/editor-react/src/PresetPanel.tsx @@ -0,0 +1,34 @@ +import { PRESETS } from "@lumorphia/editor-recipe"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type Props = { + activeId: string | null; + onApply: (id: string) => void; +}; + +export function PresetPanel({ activeId, onApply }: Props) { + const { tx } = useEditorI18n(); + return ( +
+ {PRESETS.map((p) => { + const active = p.id === activeId; + return ( + + ); + })} +
+ ); +} diff --git a/packages/editor-react/src/Slider.tsx b/packages/editor-react/src/Slider.tsx new file mode 100644 index 0000000..c0a0c50 --- /dev/null +++ b/packages/editor-react/src/Slider.tsx @@ -0,0 +1,91 @@ +import { useId } from "react"; + +type Props = { + label: string; + value: number; + min: number; + max: number; + step: number; + format?: (v: number) => string; + onPreview: (v: number) => void; + onCommit: (v: number) => void; + onReset?: () => void; +}; + +/** + * 補正用スライダー。ドラッグ中は onPreview、離したら onCommit (docs/design/04 §3)。 + * キーボード操作は矢印で step、Shift+矢印で 10 step (docs/design/08 §6)。 + */ +export function Slider({ + label, + value, + min, + max, + step, + format, + onPreview, + onCommit, + onReset, +}: Props) { + const id = useId(); + const text = format ? format(value) : String(value); + return ( +
+ + onPreview(Number(e.currentTarget.value))} + onPointerUp={(e) => onCommit(Number(e.currentTarget.value))} + onKeyDown={(e) => { + if ( + ![ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "PageUp", + "PageDown", + ].includes(e.key) + ) + return; + if (e.shiftKey && (e.key === "ArrowLeft" || e.key === "ArrowRight")) { + e.preventDefault(); + const dir = e.key === "ArrowRight" ? 1 : -1; + const next = Math.min(max, Math.max(min, value + dir * step * 10)); + onCommit(next); + } + }} + onKeyUp={(e) => { + if ( + [ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "PageUp", + "PageDown", + ].includes(e.key) + ) { + onCommit(Number(e.currentTarget.value)); + } + }} + /> + + {text} + +
+ ); +} diff --git a/packages/editor-react/src/TapOverlay.tsx b/packages/editor-react/src/TapOverlay.tsx new file mode 100644 index 0000000..c49dac7 --- /dev/null +++ b/packages/editor-react/src/TapOverlay.tsx @@ -0,0 +1,59 @@ +import { useEffect } from "react"; +import type { GeometryV1 } from "@lumorphia/editor-recipe"; +import { canvasToImageUv, type Point } from "@lumorphia/editor-engine"; +import type { Size } from "@lumorphia/editor-engine"; +import { useEditorI18n } from "./EditorI18n.tsx"; + +type View = { x: number; y: number; width: number; height: number; scale: number }; + +type Props = { + view: View; + source: Size; + geometry: GeometryV1; + /** 何を切るかの一言 (「切りたい装備をタップ」など) */ + hint: string; + /** タップ位置 (幾何を掛ける前の画像の正規化座標) */ + onTap: (uv: Point) => void; + /** Esc か「やめる」 */ + onCancel: () => void; +}; + +/** + * タップで切る (#177) の DOM オーバーレイ。キャンバス全体でクリックを 1 回受けて画像座標にする。 + * 画像の外をタップしたら無視する + */ +export function TapOverlay({ view, source, geometry, hint, onTap, onCancel }: Props) { + const { t } = useEditorI18n(); + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onCancel(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onCancel]); + return ( +
{ + if (e.button !== 0) return; + e.preventDefault(); + const host = e.currentTarget.getBoundingClientRect(); + const canvas = { + x: (e.clientX - host.left - view.x) / view.scale, + y: (e.clientY - host.top - view.y) / view.scale, + }; + const uv = canvasToImageUv(canvas, source, geometry); + if (uv.x < 0 || uv.x > 1 || uv.y < 0 || uv.y > 1) return; + onTap(uv); + }} + > +

+ {hint} {t("(Esc でやめる)", "(press Esc to cancel)")} +

+
+ ); +} diff --git a/packages/editor-react/src/crop-drag.test.ts b/packages/editor-react/src/crop-drag.test.ts new file mode 100644 index 0000000..0a9c35e --- /dev/null +++ b/packages/editor-react/src/crop-drag.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { dragCrop } from "./crop-drag.ts"; + +const full = { x: 0, y: 0, w: 1, h: 1 }; +const mid = { x: 0.25, y: 0.25, w: 0.5, h: 0.5 }; + +describe("dragCrop", () => { + it("moves within bounds", () => { + expect(dragCrop(mid, "move", 0.1, -0.1)).toEqual({ x: 0.35, y: 0.15, w: 0.5, h: 0.5 }); + expect(dragCrop(mid, "move", 1, 1)).toEqual({ x: 0.5, y: 0.5, w: 0.5, h: 0.5 }); + }); + + it("resizes from the east edge without moving the west edge", () => { + const r = dragCrop(mid, "e", 0.1, 0); + expect(r.x).toBe(0.25); + expect(r.w).toBeCloseTo(0.6); + }); + + it("keeps a minimum size", () => { + const r = dragCrop(mid, "e", -1, 0); + expect(r.w).toBeCloseTo(0.05); + }); + + it("locks ratio when resizing a corner", () => { + const r = dragCrop(full, "se", -0.5, 0, 1); + expect(r.w).toBeCloseTo(r.h); + expect(r.x).toBe(0); + expect(r.y).toBe(0); + }); + + it("locked ratio never exceeds the canvas", () => { + const r = dragCrop({ x: 0.5, y: 0.5, w: 0.4, h: 0.4 }, "se", 0.5, 0.5, 1); + expect(r.x + r.w).toBeLessThanOrEqual(1 + 1e-9); + expect(r.y + r.h).toBeLessThanOrEqual(1 + 1e-9); + }); +}); diff --git a/packages/editor-react/src/crop-drag.ts b/packages/editor-react/src/crop-drag.ts new file mode 100644 index 0000000..1a5c594 --- /dev/null +++ b/packages/editor-react/src/crop-drag.ts @@ -0,0 +1,73 @@ +import type { GeometryV1 } from "@lumorphia/editor-recipe"; + +export type Crop = NonNullable; +export type Handle = "move" | "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw"; + +const MIN = 0.05; +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +/** + * crop 枠のドラッグ計算 (正規化座標、純粋関数)。 + * ratio は「キャンバス座標系での w/h 比」= (目的の比率) / (キャンバスの比率)。 + */ +export function dragCrop( + start: Crop, + handle: Handle, + dx: number, + dy: number, + ratio?: number, +): Crop { + if (handle === "move") { + return { + ...start, + x: clamp(start.x + dx, 0, 1 - start.w), + y: clamp(start.y + dy, 0, 1 - start.h), + }; + } + + let x0 = start.x; + let y0 = start.y; + let x1 = start.x + start.w; + let y1 = start.y + start.h; + + if (handle.includes("w")) x0 = clamp(x0 + dx, 0, x1 - MIN); + if (handle.includes("e")) x1 = clamp(x1 + dx, x0 + MIN, 1); + if (handle.includes("n")) y0 = clamp(y0 + dy, 0, y1 - MIN); + if (handle.includes("s")) y1 = clamp(y1 + dy, y0 + MIN, 1); + + if (ratio) { + // 幅を優先し、高さを比率から決める。固定辺 (アンカー) は動かした辺の反対側 + let w = x1 - x0; + let h = w / ratio; + const horizontalOnly = handle === "e" || handle === "w"; + const verticalOnly = handle === "n" || handle === "s"; + if (verticalOnly) { + h = y1 - y0; + w = h * ratio; + } + // はみ出すなら縮める + const anchorX = handle.includes("w") ? x1 : x0; + const anchorY = handle.includes("n") ? y1 : y0; + const maxW = handle.includes("w") ? anchorX : 1 - anchorX; + const maxH = handle.includes("n") ? anchorY : 1 - anchorY; + if (w > maxW) { + w = maxW; + h = w / ratio; + } + if (h > maxH) { + h = maxH; + w = h * ratio; + } + if (horizontalOnly || !verticalOnly) { + x0 = handle.includes("w") ? anchorX - w : anchorX; + y0 = handle.includes("n") ? anchorY - h : anchorY; + } else { + y0 = handle.includes("n") ? anchorY - h : anchorY; + x0 = handle.includes("w") ? anchorX - w : anchorX; + } + x1 = x0 + w; + y1 = y0 + h; + } + + return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} diff --git a/packages/editor-react/src/ellipse-drag.test.ts b/packages/editor-react/src/ellipse-drag.test.ts new file mode 100644 index 0000000..af19242 --- /dev/null +++ b/packages/editor-react/src/ellipse-drag.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ELLIPSE_MASK } from "@lumorphia/editor-recipe"; +import { dragEllipse, ellipseHandles } from "./ellipse-drag.ts"; + +const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) < eps; +const size = { width: 200, height: 100 }; +const mask = { ...DEFAULT_ELLIPSE_MASK, cx: 0.5, cy: 0.5, rx: 0.1, ry: 0.2, rotation: 0 }; + +describe("dragEllipse", () => { + it("move shifts the center by the pointer delta and clamps to the image", () => { + const out = dragEllipse(mask, "move", { x: 0.5, y: 0.5 }, { x: 0.6, y: 0.45 }, size); + expect(near(out.cx, 0.6) && near(out.cy, 0.45)).toBe(true); + const far = dragEllipse(mask, "move", { x: 0.5, y: 0.5 }, { x: 2, y: -1 }, size); + expect(far.cx).toBe(1); + expect(far.cy).toBe(0); + }); + + it("rx handle sets the horizontal radius from the pointer distance", () => { + const out = dragEllipse(mask, "rx", { x: 0.6, y: 0.5 }, { x: 0.75, y: 0.5 }, size); + expect(near(out.rx, 0.25)).toBe(true); + expect(out.ry).toBe(mask.ry); + }); + + it("ry handle sets the vertical radius, and radii never go below the minimum", () => { + const out = dragEllipse(mask, "ry", { x: 0.5, y: 0.3 }, { x: 0.5, y: 0.4 }, size); + expect(near(out.ry, 0.1)).toBe(true); + const tiny = dragEllipse(mask, "ry", { x: 0.5, y: 0.3 }, { x: 0.5, y: 0.5 }, size); + expect(tiny.ry).toBeGreaterThan(0); + }); + + it("radius handles measure along the rotated axes", () => { + // 90 度回した楕円の rx 軸は画面の縦方向。縦に 30px 離れた点で rx = 30 / 200 + const rotated = { ...mask, rotation: 90 }; + const out = dragEllipse(rotated, "rx", { x: 0.5, y: 0.3 }, { x: 0.5, y: 0.2 }, size); + expect(near(out.rx, 0.15)).toBe(true); + }); + + it("rotate handle sets the angle from the pointer around the center", () => { + // 回転ハンドルは楕円の上 (-ry 方向)。真右へ持っていけば 90 度 + const out = dragEllipse(mask, "rotate", { x: 0.5, y: 0.3 }, { x: 0.7, y: 0.5 }, size); + expect(near(out.rotation, 90, 1e-6)).toBe(true); + const left = dragEllipse(mask, "rotate", { x: 0.5, y: 0.3 }, { x: 0.3, y: 0.5 }, size); + expect(near(left.rotation, -90, 1e-6)).toBe(true); + }); +}); + +describe("ellipseHandles", () => { + it("places rx / ry / rotate handles on the rotated axes in image uv", () => { + const h = ellipseHandles(mask, size); + expect(near(h.rx.x, 0.6) && near(h.rx.y, 0.5)).toBe(true); + expect(near(h.ry.x, 0.5) && near(h.ry.y, 0.3)).toBe(true); + expect(h.rotate.y).toBeLessThan(h.ry.y); + const r = ellipseHandles({ ...mask, rotation: 90 }, size); + // rx 軸 (20px) が縦になる: 20px / 100 = 0.2 下 + expect(near(r.rx.x, 0.5) && near(r.rx.y, 0.7)).toBe(true); + }); +}); diff --git a/packages/editor-react/src/ellipse-drag.ts b/packages/editor-react/src/ellipse-drag.ts new file mode 100644 index 0000000..6a2f305 --- /dev/null +++ b/packages/editor-react/src/ellipse-drag.ts @@ -0,0 +1,86 @@ +import type { EllipseMaskV2 } from "@lumorphia/editor-recipe"; +import type { Point } from "@lumorphia/editor-engine"; +import type { Size } from "@lumorphia/editor-engine"; + +export type EllipseHandle = "move" | "rx" | "ry" | "rotate"; + +/** 半径の下限 (幅・高さに対する比)。スキーマの gt(0) を満たしつつ、掴めなくならない程度 */ +export const MIN_RADIUS = 0.005; +/** 回転ハンドルを楕円の上端からどれだけ離すか (px) */ +export const ROTATE_HANDLE_OFFSET_PX = 32; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); + +/** 中心からの相対位置 (px) を、楕円の軸に合わせて回した座標にする */ +function toAxes(mask: EllipseMaskV2, uv: Point, size: Size): Point { + const px = (uv.x - mask.cx) * size.width; + const py = (uv.y - mask.cy) * size.height; + const rad = (-mask.rotation * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + return { x: c * px - s * py, y: s * px + c * py }; +} + +/** 楕円の軸上の点 (px、中心相対) を画像の正規化座標にする */ +function fromAxes(mask: EllipseMaskV2, p: Point, size: Size): Point { + const rad = (mask.rotation * Math.PI) / 180; + const c = Math.cos(rad); + const s = Math.sin(rad); + return { + x: mask.cx + (c * p.x - s * p.y) / size.width, + y: mask.cy + (s * p.x + c * p.y) / size.height, + }; +} + +/** + * 楕円マスクのドラッグ (純粋関数、#109)。座標は幾何を掛ける前の画像の正規化座標。 + * from / to はドラッグの開始点と現在点。 + */ +export function dragEllipse( + start: EllipseMaskV2, + handle: EllipseHandle, + from: Point, + to: Point, + size: Size, +): EllipseMaskV2 { + switch (handle) { + case "move": + return { + ...start, + cx: clamp(start.cx + (to.x - from.x), 0, 1), + cy: clamp(start.cy + (to.y - from.y), 0, 1), + }; + case "rx": { + const p = toAxes(start, to, size); + return { ...start, rx: Math.max(MIN_RADIUS, Math.abs(p.x) / size.width) }; + } + case "ry": { + const p = toAxes(start, to, size); + return { ...start, ry: Math.max(MIN_RADIUS, Math.abs(p.y) / size.height) }; + } + case "rotate": { + // ハンドルは -ry 方向 (上) にある。その方向が真上になる角度が 0 + const px = (to.x - start.cx) * size.width; + const py = (to.y - start.cy) * size.height; + let deg = (Math.atan2(py, px) * 180) / Math.PI + 90; + if (deg > 180) deg -= 360; + if (deg < -180) deg += 360; + return { ...start, rotation: deg }; + } + } +} + +/** ハンドルの位置 (画像の正規化座標)。rotateOffsetPx は画像 px (画面上で一定にしたければ表示倍率で割って渡す) */ +export function ellipseHandles( + mask: EllipseMaskV2, + size: Size, + rotateOffsetPx = ROTATE_HANDLE_OFFSET_PX, +): Record, Point> { + const rxPx = mask.rx * size.width; + const ryPx = mask.ry * size.height; + return { + rx: fromAxes(mask, { x: rxPx, y: 0 }, size), + ry: fromAxes(mask, { x: 0, y: -ryPx }, size), + rotate: fromAxes(mask, { x: 0, y: -ryPx - rotateOffsetPx }, size), + }; +} diff --git a/packages/editor-react/src/gesture.test.ts b/packages/editor-react/src/gesture.test.ts new file mode 100644 index 0000000..a37a0d7 --- /dev/null +++ b/packages/editor-react/src/gesture.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { dragPan, pinch, wheelZoomFactor } from "./gesture.ts"; + +const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) < eps; + +describe("pinch", () => { + it("spreading two fingers doubles the factor around their midpoint", () => { + const p = pinch({ x: 100, y: 100 }, { x: 200, y: 100 }, { x: 50, y: 100 }, { x: 250, y: 100 }); + expect(near(p.factor, 2)).toBe(true); + expect(p.anchor).toEqual({ x: 150, y: 100 }); + expect(p.pan).toEqual({ x: 0, y: 0 }); + }); + + it("moving both fingers together pans by the midpoint delta without zooming", () => { + const p = pinch({ x: 100, y: 100 }, { x: 200, y: 100 }, { x: 130, y: 140 }, { x: 230, y: 140 }); + expect(near(p.factor, 1)).toBe(true); + expect(p.pan).toEqual({ x: 30, y: 40 }); + }); + + it("does not blow up when the fingers overlap", () => { + const p = pinch({ x: 100, y: 100 }, { x: 100, y: 100 }, { x: 100, y: 100 }, { x: 150, y: 100 }); + expect(p.factor).toBe(1); + }); +}); + +describe("wheelZoomFactor", () => { + it("zooms in when scrolling away and out when scrolling towards, symmetrically", () => { + const zoomIn = wheelZoomFactor(-100, 0); + const zoomOut = wheelZoomFactor(100, 0); + expect(zoomIn).toBeGreaterThan(1); + expect(near(zoomIn * zoomOut, 1)).toBe(true); + }); + + it("treats line-mode deltas like a few pixels of scrolling", () => { + expect(near(wheelZoomFactor(-3, 1), wheelZoomFactor(-48, 0))).toBe(true); + }); +}); + +describe("dragPan", () => { + it("is the pointer delta", () => { + expect(dragPan({ x: 10, y: 20 }, { x: 15, y: 10 })).toEqual({ x: 5, y: -10 }); + }); +}); diff --git a/packages/editor-react/src/gesture.ts b/packages/editor-react/src/gesture.ts new file mode 100644 index 0000000..6f60cd4 --- /dev/null +++ b/packages/editor-react/src/gesture.ts @@ -0,0 +1,46 @@ +/** + * キャンバスのズーム・移動のジェスチャ (純粋な計算、#109 のあとの操作性の見直し)。 + * ポインタの位置 (ホスト内の CSS px) から、倍率と移動量を出す。DOM には触れない。 + */ + +export type Pt = { x: number; y: number }; + +export type Pinch = { + /** 倍率 (前の 2 点間の距離に対する今の距離) */ + factor: number; + /** 拡大の軸 (今の 2 点の中点) */ + anchor: Pt; + /** 中点の移動 (移動量) */ + pan: Pt; +}; + +const mid = (a: Pt, b: Pt): Pt => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); +const dist = (a: Pt, b: Pt) => Math.hypot(a.x - b.x, a.y - b.y); + +/** + * 2 本指: 前の位置 (a0, b0) から今の位置 (a1, b1) への変化。 + * 指が重なって距離 0 のときは倍率 1 とする + */ +export function pinch(a0: Pt, b0: Pt, a1: Pt, b1: Pt): Pinch { + const d0 = dist(a0, b0); + const d1 = dist(a1, b1); + const m0 = mid(a0, b0); + const m1 = mid(a1, b1); + return { + factor: d0 > 0 && d1 > 0 ? d1 / d0 : 1, + anchor: m1, + pan: { x: m1.x - m0.x, y: m1.y - m0.y }, + }; +} + +/** ホイール 1 回の倍率。deltaY が正 (手前に回す) で縮小。ピクセル単位の delta も行単位も同じ式で扱う */ +export function wheelZoomFactor(deltaY: number, deltaMode: number): number { + // deltaMode 1 = 行、2 = ページ。ピクセルに寄せる + const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 400 : deltaY; + return Math.exp(-px * 0.0025); +} + +/** 1 本指 / ドラッグの移動量 */ +export function dragPan(from: Pt, to: Pt): Pt { + return { x: to.x - from.x, y: to.y - from.y }; +} diff --git a/packages/editor-react/src/host.test.ts b/packages/editor-react/src/host.test.ts new file mode 100644 index 0000000..1b607cb --- /dev/null +++ b/packages/editor-react/src/host.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { downloadName } from "./host.ts"; + +describe("downloadName", () => { + it("replaces the extension and adds the host's suffix", () => { + expect(downloadName("shot.png", "image/webp", "-prismtone")).toBe("shot-prismtone.webp"); + }); + + it("uses jpg when the browser could not encode WebP", () => { + expect(downloadName("shot.png", "image/jpeg", "-prismtone")).toBe("shot-prismtone.jpg"); + }); + + it("adds nothing when the host gives no suffix", () => { + expect(downloadName("shot.v2.jpeg", "image/webp", "")).toBe("shot.v2.webp"); + }); +}); diff --git a/packages/editor-react/src/host.ts b/packages/editor-react/src/host.ts new file mode 100644 index 0000000..0c4bef7 --- /dev/null +++ b/packages/editor-react/src/host.ts @@ -0,0 +1,60 @@ +import type { EditRecipe } from "@lumorphia/editor-recipe"; +import type { DraftStore } from "@lumorphia/editor-engine"; +import type { EditorLocale } from "./i18n.ts"; + +/** + * エディタを組み込むホスト (prismtone、単独アプリ、ほかのアプリ) が渡すもの (ADR-0035)。 + * エディタはホストのルーティング・保存先・計測を知らない。ここに無いものに依存しない + */ +export type EditorHost = { + locale: EditorLocale; + /** 端末の下書き (原本とレシピ)。自動保存と「現像し直し」に使う */ + drafts: DraftStore; + /** 開いたときに読み込む下書き (prismtone は /edit?draft=) */ + initialDraftId?: string | null; + /** initialDraftId を読み終えた (リロードで読み直さないよう、ホストが URL などから外す) */ + onInitialDraftConsumed?: () => void; + /** 書き出した画像の送り先。並べた順にボタンを出す。0 件なら「端末に保存」だけ */ + destinations: readonly EditorDestination[]; + /** 使われ方の計測。誰が使ったかは渡さない */ + telemetry?: (event: EditorTelemetryEvent) => void; + inference?: { + /** モデルと WASM の置き場所。既定は /models/ (同じオリジン) */ + modelBaseUrl?: string; + }; + download?: { + /** 端末に保存するファイル名の接尾辞 (prismtone は "-prismtone") */ + fileSuffix?: string; + }; + /** E2E から描画結果を読むフック。enabled のときだけ window[globalName] に置く */ + testHook?: { globalName: string; enabled: () => boolean }; +}; + +export type EditorDestination = { + id: string; + label: { ja: string; en: string }; + /** 強調して出す (主な送り先) */ + primary?: boolean; + /** 投げたらその message を画面に出す */ + send(payload: EditorSendPayload): Promise; +}; + +export type EditorSendPayload = { + /** 書き出した画像 (WebP、なければ JPEG) */ + blob: Blob; + recipe: EditRecipe; + /** 原本。送り先で現像し直すとき (送客) に使う */ + original: Blob; + sourceName: string; + draftId: string; +}; + +export type EditorTelemetryEvent = + { type: "open" } | { type: "save" } | { type: "send"; destinationId: string }; + +/** 端末に保存するときのファイル名。拡張子は書き出した形式に合わせる */ +export function downloadName(sourceName: string, blobType: string, suffix: string): string { + const ext = blobType === "image/webp" ? "webp" : "jpg"; + const base = sourceName.replace(/\.[^.]+$/, ""); + return `${base}${suffix}.${ext}`; +} diff --git a/packages/editor-react/src/i18n.test.ts b/packages/editor-react/src/i18n.test.ts new file mode 100644 index 0000000..92102dd --- /dev/null +++ b/packages/editor-react/src/i18n.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { editorTranslator } from "./i18n.ts"; + +describe("editorTranslator", () => { + it("picks the Japanese text for ja", () => { + expect(editorTranslator("ja").t("保存", "Save")).toBe("保存"); + }); + + it("picks the English text for en", () => { + expect(editorTranslator("en").t("保存", "Save")).toBe("Save"); + }); + + it("translates editor vocabulary with tx", () => { + expect(editorTranslator("en").tx("露光量")).toBe("Exposure"); + }); +}); diff --git a/packages/editor-react/src/i18n.ts b/packages/editor-react/src/i18n.ts new file mode 100644 index 0000000..f6d5810 --- /dev/null +++ b/packages/editor-react/src/i18n.ts @@ -0,0 +1,19 @@ +import { translateLabel } from "@lumorphia/editor-recipe/labels"; + +export type EditorLocale = "ja" | "en"; + +export type EditorTranslator = { + locale: EditorLocale; + /** 画面の文言。日本語と英語を並べて書き、表示言語のほうを返す */ + t: (ja: string, en: string) => string; + /** 現像の語彙 (項目名・プリセット名) を表示言語にする */ + tx: (value: string) => string; +}; + +export function editorTranslator(locale: EditorLocale): EditorTranslator { + return { + locale, + t: (ja, en) => (locale === "en" ? en : ja), + tx: (value) => translateLabel(locale, value), + }; +} diff --git a/packages/editor-react/src/index.ts b/packages/editor-react/src/index.ts new file mode 100644 index 0000000..901bf66 --- /dev/null +++ b/packages/editor-react/src/index.ts @@ -0,0 +1,10 @@ +// 現像の UI (ADR-0035)。ホストは で組み込む。react-router に依存しない +export { Editor } from "./EditorPage.tsx"; +export { + downloadName, + type EditorDestination, + type EditorHost, + type EditorSendPayload, + type EditorTelemetryEvent, +} from "./host.ts"; +export type { EditorLocale } from "./i18n.ts"; diff --git a/packages/editor-react/src/use-canvas-gestures.ts b/packages/editor-react/src/use-canvas-gestures.ts new file mode 100644 index 0000000..337c78c --- /dev/null +++ b/packages/editor-react/src/use-canvas-gestures.ts @@ -0,0 +1,158 @@ +import { useEffect, type RefObject } from "react"; +import { dragPan, pinch, wheelZoomFactor, type Pt } from "./gesture.ts"; + +export type GestureTarget = { + zoomBy: (factor: number, anchor?: Pt) => void; + panBy: (dx: number, dy: number) => void; +}; + +/** + * キャンバスのズームと移動 (docs/design/08 §3.3)。 + * - ホイール: カーソルを軸にズーム (Ctrl 付き = トラックパッドのピンチも同じ) + * - ドラッグ: 移動。ツール (ブラシ・円形のハンドル・トリミング枠) の上では起きない。 + * 中ボタンと Space + ドラッグはツールの上でも移動 + * - 2 本指: ピンチでズーム、そのまま動かして移動。ブラシで描いている途中でも 2 本目が触れたらこちらに切り替え、 + * 描きかけのストロークは捨てる (pointercancel を送る) + * ネイティブの capture でツールより先に見るので、React の onPointer* より前に判断できる + */ +export function useCanvasGestures( + hostRef: RefObject, + getTarget: () => GestureTarget | null, + enabled: boolean, +): void { + useEffect(() => { + const host = hostRef.current; + if (!host || !enabled) return; + + const pointers = new Map(); + let mode: "none" | "pan" | "pinch" = "none"; + let last: Pt | null = null; + let spaceDown = false; + let cancelling = false; + + const pos = (e: PointerEvent): Pt => { + const r = host.getBoundingClientRect(); + return { x: e.clientX - r.left, y: e.clientY - r.top }; + }; + /** ツール (オーバーレイの要素) の上か。ホスト自身と canvas は素の場所 */ + const onTool = (target: EventTarget | null) => + target !== host && !(target instanceof HTMLCanvasElement); + + const onDown = (e: PointerEvent) => { + const t = getTarget(); + if (!t) return; + pointers.set(e.pointerId, { pos: pos(e), target: e.target }); + if (pointers.size === 2) { + // 1 本目がツールに掴まれていたら、描きかけを捨てさせる。自分で送る cancel は onUp で数えない + mode = "pinch"; + cancelling = true; + for (const [id, p] of pointers) { + if (id !== e.pointerId && p.target && onTool(p.target)) { + p.target.dispatchEvent( + new PointerEvent("pointercancel", { pointerId: id, bubbles: true, cancelable: true }), + ); + } + } + cancelling = false; + e.stopPropagation(); + e.preventDefault(); + return; + } + if (pointers.size > 2) { + e.stopPropagation(); + return; + } + const panByDrag = e.button === 1 || spaceDown || (e.button === 0 && !onTool(e.target)); + if (panByDrag) { + mode = "pan"; + last = pos(e); + host.setPointerCapture(e.pointerId); + e.stopPropagation(); + e.preventDefault(); + } + }; + const onMove = (e: PointerEvent) => { + const t = getTarget(); + const entry = pointers.get(e.pointerId); + if (!t || !entry) return; + const now = pos(e); + if (mode === "pinch" && pointers.size === 2) { + const [a, b] = [...pointers.values()]; + const before = entry.pos; + const other = a === entry ? b!.pos : a!.pos; + // 動いた指が 1 本目なら (a, b) = (動いた, 止まった)、2 本目ならその逆で渡す + const p = a === entry ? pinch(before, other, now, other) : pinch(other, before, other, now); + if (p.factor !== 1) t.zoomBy(p.factor, p.anchor); + if (p.pan.x !== 0 || p.pan.y !== 0) t.panBy(p.pan.x, p.pan.y); + entry.pos = now; + e.stopPropagation(); + e.preventDefault(); + return; + } + if (mode === "pan" && last) { + const d = dragPan(last, now); + t.panBy(d.x, d.y); + last = now; + e.stopPropagation(); + e.preventDefault(); + return; + } + entry.pos = now; + }; + const onUp = (e: PointerEvent) => { + if (cancelling || !pointers.has(e.pointerId)) return; + pointers.delete(e.pointerId); + if (mode === "pinch") { + // 片方を離しても、残った指で描き始めないよう次に全部離れるまで何もしない + if (pointers.size === 0) mode = "none"; + e.stopPropagation(); + return; + } + if (mode === "pan") { + mode = "none"; + last = null; + if (host.hasPointerCapture(e.pointerId)) host.releasePointerCapture(e.pointerId); + e.stopPropagation(); + } + }; + const onWheel = (e: WheelEvent) => { + const t = getTarget(); + if (!t) return; + e.preventDefault(); + t.zoomBy(wheelZoomFactor(e.deltaY, e.deltaMode), pos(e as unknown as PointerEvent)); + }; + const isTyping = (el: EventTarget | null) => + el instanceof HTMLElement && (el.tagName === "INPUT" || el.tagName === "TEXTAREA"); + const onKeyDown = (e: KeyboardEvent) => { + if (e.code === "Space" && !isTyping(e.target) && !e.repeat) { + spaceDown = true; + host.style.cursor = "grab"; + e.preventDefault(); + } + }; + const onKeyUp = (e: KeyboardEvent) => { + if (e.code === "Space") { + spaceDown = false; + host.style.cursor = ""; + } + }; + + host.addEventListener("pointerdown", onDown, { capture: true }); + host.addEventListener("pointermove", onMove, { capture: true }); + host.addEventListener("pointerup", onUp, { capture: true }); + host.addEventListener("pointercancel", onUp, { capture: true }); + host.addEventListener("wheel", onWheel, { passive: false }); + window.addEventListener("keydown", onKeyDown); + window.addEventListener("keyup", onKeyUp); + return () => { + host.removeEventListener("pointerdown", onDown, { capture: true }); + host.removeEventListener("pointermove", onMove, { capture: true }); + host.removeEventListener("pointerup", onUp, { capture: true }); + host.removeEventListener("pointercancel", onUp, { capture: true }); + host.removeEventListener("wheel", onWheel); + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("keyup", onKeyUp); + host.style.cursor = ""; + }; + }, [hostRef, getTarget, enabled]); +} diff --git a/packages/editor-react/tsconfig.build.json b/packages/editor-react/tsconfig.build.json new file mode 100644 index 0000000..a18d5c9 --- /dev/null +++ b/packages/editor-react/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist" + }, + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/editor-react/tsconfig.json b/packages/editor-react/tsconfig.json new file mode 100644 index 0000000..7c96790 --- /dev/null +++ b/packages/editor-react/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2024", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "types": ["react"] + }, + "include": ["src/**/*"] +} diff --git a/packages/editor-react/vitest.config.ts b/packages/editor-react/vitest.config.ts new file mode 100644 index 0000000..8ee7563 --- /dev/null +++ b/packages/editor-react/vitest.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from "vitest/config"; +import { readEditorSource } from "../../vitest.source.ts"; +export default defineConfig({ + ...readEditorSource, + test: { name: "editor-react", include: ["src/**/*.test.ts"] }, +}); diff --git a/packages/editor-recipe/package.json b/packages/editor-recipe/package.json new file mode 100644 index 0000000..b19707a --- /dev/null +++ b/packages/editor-recipe/package.json @@ -0,0 +1,31 @@ +{ + "name": "@lumorphia/editor-recipe", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "source": "./src/index.ts", + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./labels": { + "source": "./src/labels.ts", + "types": "./dist/labels.d.ts", + "default": "./dist/labels.js" + } + }, + "scripts": { + "build": "rm -rf dist && tsc -p tsconfig.build.json", + "typecheck": "tsc -p tsconfig.json", + "test": "vitest run" + }, + "files": [ + "dist", + "src", + "!src/**/*.test.ts" + ], + "dependencies": { + "zod": "^4.6.5" + } +} diff --git a/packages/editor-recipe/src/index.ts b/packages/editor-recipe/src/index.ts new file mode 100644 index 0000000..0c0ab3c --- /dev/null +++ b/packages/editor-recipe/src/index.ts @@ -0,0 +1,7 @@ +export * from "./schema.ts"; +export * from "./migrate.ts"; +export * from "./presets.ts"; +export * from "./local-presets.ts"; +export * from "./rle.ts"; +export * from "./portrait-presets.ts"; +export * from "./upgrade.ts"; diff --git a/packages/editor-recipe/src/labels.test.ts b/packages/editor-recipe/src/labels.test.ts new file mode 100644 index 0000000..68915ca --- /dev/null +++ b/packages/editor-recipe/src/labels.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ELLIPSE_MASK, DEFAULT_LOCAL_ADJUSTMENT } from "./index.ts"; +import { + adjustLabel, + geometryLabel, + localAdjustLabel, + localAdjustmentsSummary, + translateLabel, +} from "./labels.ts"; + +describe("operation labels", () => { + it("補正は項目名と符号付きの値", () => { + expect(adjustLabel("exposure", 0.3)).toBe("露光量 +0.30"); + expect(adjustLabel("contrast", -20)).toBe("コントラスト -20"); + expect(adjustLabel("saturation", 0)).toBe("彩度 0"); + }); + it("幾何は変えた項目から決める", () => { + expect(geometryLabel({ rotation: 90 })).toBe("回転 90°"); + expect(geometryLabel({ straighten: -2.5 })).toBe("水平 -2.5°"); + expect(geometryLabel({ flipH: true })).toBe("左右反転"); + expect(geometryLabel({ aspect: "3:4" })).toBe("縦横比 3:4"); + expect(geometryLabel({ crop: null })).toBe("トリミングを解除"); + expect(geometryLabel({})).toBe("幾何の変更"); + }); +}); + +describe("localAdjustLabel (#109)", () => { + it("prefixes the item with 部分補正 and formats exposure to two decimals", () => { + expect(localAdjustLabel("exposure", 0.35)).toBe("部分補正: 露光量 +0.35"); + expect(localAdjustLabel("shadows", -20)).toBe("部分補正: シャドウ -20"); + expect(localAdjustLabel("blur", 8)).toBe("部分補正: 背景ぼかし 8px"); + expect(localAdjustLabel("clarity", -25)).toBe("部分補正: 質感 -25"); + }); +}); + +describe("localAdjustmentsSummary (#109)", () => { + const local = (presetId: "eyes" | "skin" | "gear" | null) => ({ + ...DEFAULT_LOCAL_ADJUSTMENT, + id: presetId ?? "free", + mask: DEFAULT_ELLIPSE_MASK, + presetId, + }); + + it("returns null when there are no local adjustments", () => { + expect(localAdjustmentsSummary([])).toBeNull(); + }); + + it("counts by preset in preset order and puts free-form ones last", () => { + expect( + localAdjustmentsSummary([local(null), local("skin"), local("eyes"), local("eyes")]), + ).toBe("4 件 (瞳強調 ×2、美肌、その他 1)"); + }); + + it("omits the breakdown when everything is free-form", () => { + expect(localAdjustmentsSummary([local(null)])).toBe("1 件"); + }); +}); + +describe("translateLabel", () => { + it("translates editor vocabulary into English", () => { + expect(translateLabel("en", "露光量")).toBe("Exposure"); + expect(translateLabel("en", "瞳強調")).toBe("Enhance eyes"); + expect(translateLabel("en", "背景ぼかし")).toBe("Background blur"); + expect(translateLabel("en", "質感")).toBe("Clarity"); + }); + + it("keeps text it does not know as it is", () => { + expect(translateLabel("en", "利用者が入力したタイトル")).toBe("利用者が入力したタイトル"); + }); + + it("keeps Japanese as it is", () => { + expect(translateLabel("ja", "露光量")).toBe("露光量"); + }); +}); diff --git a/packages/editor-recipe/src/labels.ts b/packages/editor-recipe/src/labels.ts new file mode 100644 index 0000000..ecb5eaa --- /dev/null +++ b/packages/editor-recipe/src/labels.ts @@ -0,0 +1,122 @@ +import { + LOCAL_PRESETS, + type AdjustV1, + type GeometryV1, + type LocalAdjust, + type LocalAdjustment, +} from "./index.ts"; + +/** 補正項目の表示名。AdjustPanel と履歴の操作名で共有する */ +export const ADJUST_LABELS: Readonly> = { + exposure: "露光量", + contrast: "コントラスト", + highlights: "ハイライト", + shadows: "シャドウ", + temperature: "色温度", + tint: "色かぶり", + vibrance: "自然な彩度", + saturation: "彩度", +}; + +/** 部分補正の項目名 (#109, #184) */ +export const LOCAL_ADJUST_LABELS: Readonly> = { + exposure: "露光量", + contrast: "コントラスト", + highlights: "ハイライト", + shadows: "シャドウ", + temperature: "色温度", + tint: "色かぶり", + saturation: "彩度", + sharpen: "シャープ", + smooth: "美肌", + blur: "背景ぼかし", + bloom: "発光", + vignette: "周辺減光", + clarity: "質感", +}; + +const signed = (n: number, digits = 0) => `${n > 0 ? "+" : ""}${n.toFixed(digits)}`; + +/** 履歴に残す操作名: 「露光量 +0.30」「コントラスト -20」 */ +export function adjustLabel(key: keyof AdjustV1, value: number): string { + return `${ADJUST_LABELS[key]} ${key === "exposure" ? signed(value, 2) : signed(value)}`; +} + +/** 部分補正の操作名: 「部分補正: 露光量 +0.30」 */ +export function localAdjustLabel(key: keyof LocalAdjust, value: number): string { + if (key === "blur") return `部分補正: ${LOCAL_ADJUST_LABELS[key]} ${value}px`; + const v = key === "exposure" ? signed(value, 2) : signed(value); + return `部分補正: ${LOCAL_ADJUST_LABELS[key]} ${v}`; +} + +/** 幾何の操作名: 変えた項目から決める。複数なら先頭だけ */ +export function geometryLabel(patch: Partial): string { + if (patch.rotation !== undefined) return `回転 ${patch.rotation}°`; + if (patch.straighten !== undefined) return `水平 ${signed(patch.straighten, 1)}°`; + if (patch.flipH !== undefined) return patch.flipH ? "左右反転" : "反転を戻す"; + if (patch.aspect !== undefined) return patch.aspect ? `縦横比 ${patch.aspect}` : "縦横比を解除"; + if (patch.crop !== undefined) return patch.crop ? "トリミング" : "トリミングを解除"; + return "幾何の変更"; +} + +/** + * 投稿詳細の「編集レシピ」に出す部分補正の要約: 「4 件 (瞳強調 ×2、美肌、その他 1)」。 + * プリセットの並び順で数え、プリセット無しは「その他」。無ければ null + */ +export function localAdjustmentsSummary(list: readonly LocalAdjustment[]): string | null { + if (list.length === 0) return null; + const parts = LOCAL_PRESETS.flatMap((preset) => { + const n = list.filter((l) => l.presetId === preset.id).length; + return n === 0 ? [] : [n === 1 ? preset.name : `${preset.name} ×${n}`]; + }); + const free = list.filter((l) => l.presetId === null).length; + if (free > 0 && parts.length > 0) parts.push(`その他 ${free}`); + const head = `${list.length} 件`; + return parts.length === 0 ? head : `${head} (${parts.join("、")})`; +} + +/** 現像の語彙 (項目名・プリセット名・マスクの種類) の英訳。ここに無いもの (利用者の入力など) はそのまま */ +const LABELS_EN: Readonly> = { + 露光量: "Exposure", + コントラスト: "Contrast", + ハイライト: "Highlights", + シャドウ: "Shadows", + 色温度: "Temperature", + 色かぶり: "Tint", + 自然な彩度: "Vibrance", + 彩度: "Saturation", + シャープ: "Sharpen", + 美肌: "Smooth skin", + 背景ぼかし: "Background blur", + 発光: "Bloom", + 周辺減光: "Vignette", + 質感: "Clarity", + 夜景: "Night", + 夕暮れ: "Sunset", + 朝霧: "Cool morning", + パステル: "Pastel", + ビビッド: "Vivid", + フィルム: "Film", + モノクロ: "Monochrome", + ソフト: "Soft", + ダンジョン: "Dungeon", + ゴールド: "Gold", + 瞳強調: "Enhance eyes", + 装備強調: "Enhance gear", + ナチュラル: "Natural", + 明るく: "Bright", + ドラマチック: "Dramatic", + やわらか: "Soft", + 瞳くっきり: "Bright eyes", + 円形: "Ellipse", + ブラシ: "Brush", + 多角形: "Polygon", + 切り抜き: "Selection", + 全体: "Whole character", + 装備: "Gear", + 部品: "Detail", +}; + +export function translateLabel(locale: "ja" | "en", value: string): string { + return locale === "en" ? (LABELS_EN[value] ?? value) : value; +} diff --git a/packages/editor-recipe/src/local-presets.ts b/packages/editor-recipe/src/local-presets.ts new file mode 100644 index 0000000..9c50093 --- /dev/null +++ b/packages/editor-recipe/src/local-presets.ts @@ -0,0 +1,67 @@ +import { + DEFAULT_LOCAL_ADJUST, + type LocalAdjust, + type LocalAdjustment, + type LocalPresetId, +} from "./schema.ts"; + +export type LocalPreset = { + id: LocalPresetId; + name: string; + /** 何に使うかの一言 (UI のツールチップ) */ + hint: string; + adjust: Partial; + amount: number; +}; + +// 部分補正のプリセット (#109)。数値は実画像で調整する。docs/design/04-edit-recipe.md §2.1 +export const LOCAL_PRESETS: readonly LocalPreset[] = Object.freeze([ + { + id: "eyes", + name: "瞳強調", + hint: "円形マスクを左右の目に置く。露光・彩度・コントラスト・シャープを弱く上げる", + adjust: { exposure: 0.3, saturation: 15, contrast: 10, sharpen: 30 }, + amount: 100, + }, + { + id: "skin", + name: "美肌", + hint: "顔にマスクを置く。輪郭を残して滑らかにし、露光と色温度を弱く補正する", + adjust: { smooth: 40, exposure: 0.15, temperature: 5 }, + amount: 100, + }, + { + id: "gear", + name: "装備強調", + hint: "見せたい装備をブラシで塗る。暗部を持ち上げ、質感と色を整える", + adjust: { + exposure: 0.15, + shadows: 45, + contrast: 15, + sharpen: 30, + saturation: 8, + clarity: 25, + }, + amount: 100, + }, +]); + +export function findLocalPreset(id: string): LocalPreset | undefined { + return LOCAL_PRESETS.find((p) => p.id === id); +} + +/** + * 部分補正にプリセットを適用した新しい部分補正を返す。元は変更しない。 + * adjust と amount を上書きし、マスクには触れない。 + */ +export function applyLocalPreset>( + local: T, + preset: LocalPreset, +): T { + return { + ...local, + presetId: preset.id, + adjust: { ...DEFAULT_LOCAL_ADJUST, ...preset.adjust }, + amount: preset.amount, + }; +} diff --git a/packages/editor-recipe/src/migrate.ts b/packages/editor-recipe/src/migrate.ts new file mode 100644 index 0000000..0e5abb1 --- /dev/null +++ b/packages/editor-recipe/src/migrate.ts @@ -0,0 +1,117 @@ +import { z } from "zod"; +import { + editRecipeSchemaV1, + editRecipeSchemaV2, + editRecipeSchemaV3, + editRecipeSchemaV4, + localAdjustSchemaV4, + localAdjustmentSchemaV2, + localAdjustmentSchemaV3, + localAdjustmentSchemaV4, + MAX_LOCAL_ADJUSTMENTS, + MAX_LOCAL_ADJUSTMENTS_V2, + type EditRecipe, + type EditRecipeV1, + type EditRecipeV2, + type EditRecipeV3, + type EditRecipeV4, +} from "./schema.ts"; + +export class RecipeMigrationError extends Error { + override readonly name = "RecipeMigrationError"; +} + +const versioned = z.object({ version: z.number().int() }); + +// strict は object にしか付かないので、部分補正とマスクの中まで strict にした版を組み立てる。 +// v2 に groupId が混ざっていれば拒む (version の書き間違いを通さない) +const strictV2 = editRecipeSchemaV2.strict().extend({ + localAdjustments: localAdjustmentSchemaV2 + .strict() + .extend({ adjust: localAdjustmentSchemaV2.shape.adjust.strict() }) + .array() + .max(MAX_LOCAL_ADJUSTMENTS_V2), +}); +const strictV3 = editRecipeSchemaV3.strict().extend({ + localAdjustments: localAdjustmentSchemaV3 + .strict() + .extend({ adjust: localAdjustmentSchemaV3.shape.adjust.strict() }) + .array() + .max(MAX_LOCAL_ADJUSTMENTS), +}); +const strictV4 = editRecipeSchemaV4.strict().extend({ + localAdjustments: localAdjustmentSchemaV4 + .strict() + .extend({ adjust: localAdjustSchemaV4.strict() }) + .array() + .max(MAX_LOCAL_ADJUSTMENTS), +}); + +/** v1 -> v2: 部分補正を空で足す (#109) */ +export function migrateV1toV2(v1: EditRecipeV1): EditRecipeV2 { + return { ...v1, version: 2, localAdjustments: [] }; +} + +/** v2 -> v3: 部分補正に groupId: null を足す (#175)。マスクはそのまま (v2 の 2 種は v3 でも有効) */ +export function migrateV2toV3(v2: EditRecipeV2): EditRecipeV3 { + return { + ...v2, + version: 3, + localAdjustments: v2.localAdjustments.map((l) => ({ ...l, groupId: null })), + }; +} + +/** v3 -> v4: 人物補正の追加効果を中立値で足す (#184) */ +export function migrateV3toV4(v3: EditRecipeV3): EditRecipeV4 { + return { + ...v3, + version: 4, + localAdjustments: v3.localAdjustments.map((local) => ({ + ...local, + adjust: { + ...local.adjust, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, + }, + })), + }; +} + +function parseOrThrow(schema: z.ZodType, input: unknown, label: string): T { + const parsed = schema.safeParse(input); + if (!parsed.success) { + throw new RecipeMigrationError( + `invalid ${label} recipe: ${parsed.error.issues[0]?.message ?? "unknown"}`, + ); + } + return parsed.data; +} + +/** + * 任意の入力を現行バージョンのレシピに変換する。 + * 未知の version、検証に失敗する入力は RecipeMigrationError を投げる。 + * 旧 version は順に変換する (v1 -> v2 -> ...)。新しい version を足すときはここに case を足す。 + * 各版は strict に検証し、版に無い項目が混ざっていれば拒む (version の書き間違いを通さない)。 + */ +export function migrateRecipe(input: unknown): EditRecipe { + const head = versioned.safeParse(input); + if (!head.success) { + throw new RecipeMigrationError("recipe has no valid version"); + } + switch (head.data.version) { + case 1: + return migrateV3toV4( + migrateV2toV3(migrateV1toV2(parseOrThrow(editRecipeSchemaV1.strict(), input, "v1"))), + ); + case 2: + return migrateV3toV4(migrateV2toV3(parseOrThrow(strictV2, input, "v2"))); + case 3: + return migrateV3toV4(parseOrThrow(strictV3, input, "v3")); + case 4: + return parseOrThrow(strictV4, input, "v4"); + default: + throw new RecipeMigrationError(`unsupported recipe version: ${head.data.version}`); + } +} diff --git a/packages/editor-recipe/src/portrait-presets.test.ts b/packages/editor-recipe/src/portrait-presets.test.ts new file mode 100644 index 0000000..117003a --- /dev/null +++ b/packages/editor-recipe/src/portrait-presets.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + editRecipeSchema, + localAdjustSchemaV4, + type EditRecipe, + type LocalAdjustment, +} from "./schema.ts"; +import { encodeRle } from "./rle.ts"; +import { + PORTRAIT_PRESETS, + PORTRAIT_ROLES, + applyPortraitPreset, + findPortraitPreset, + portraitAmount, + portraitRole, + scalePortraitAmount, +} from "./portrait-presets.ts"; + +const bitmap = (invert: boolean) => ({ + kind: "bitmap" as const, + width: 2, + height: 1, + rle: encodeRle(Uint8Array.from([1, 0])), + strokes: [], + feather: 0.1, + invert, +}); +const polygon = { + kind: "polygon" as const, + rings: [ + [ + { x: 0.3, y: 0.2 }, + { x: 0.7, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0.2, + invert: false, +}; +const local = ( + id: string, + mask: LocalAdjustment["mask"], + extra: Partial = {}, +): LocalAdjustment => ({ + ...DEFAULT_LOCAL_ADJUSTMENT, + id, + mask, + groupId: "p1", + ...extra, +}); +const group: EditRecipe = { + ...DEFAULT_RECIPE, + localAdjustments: [ + local("bg", bitmap(true)), + local("person", bitmap(false)), + local("face", polygon, { presetId: "skin" }), + local("eyeL", DEFAULT_ELLIPSE_MASK, { presetId: "eyes" }), + local("other", DEFAULT_ELLIPSE_MASK, { groupId: null }), + ], +}; + +describe("PORTRAIT_PRESETS", () => { + it("has the five presets and every role's adjust is a valid local adjust", () => { + expect(PORTRAIT_PRESETS.map((p) => p.id)).toEqual([ + "natural", + "bright", + "dramatic", + "soft", + "eyes", + ]); + for (const preset of PORTRAIT_PRESETS) { + for (const role of PORTRAIT_ROLES) { + const r = preset.roles[role]; + expect( + localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, ...r.adjust }).success, + ).toBe(true); + expect(r.amount).toBeGreaterThanOrEqual(0); + expect(r.amount).toBeLessThanOrEqual(100); + } + } + expect(findPortraitPreset("nope")).toBeUndefined(); + }); + + it("uses at least one v4 effect in every portrait preset", () => { + const keys = ["blur", "bloom", "vignette", "clarity"] as const; + for (const preset of PORTRAIT_PRESETS) { + expect( + PORTRAIT_ROLES.some((role) => + keys.some((key) => preset.roles[role].adjust[key] !== undefined), + ), + ).toBe(true); + } + }); +}); + +describe("portraitRole", () => { + it("derives the role from the mask: inverted bitmap = 背景, bitmap = 人物, polygon = 顔, ellipse = 瞳", () => { + expect(group.localAdjustments.slice(0, 4).map(portraitRole)).toEqual([ + "background", + "person", + "face", + "eyes", + ]); + }); +}); + +describe("applyPortraitPreset", () => { + it("rewrites adjust and amount of the group's adjustments by role, leaving others alone", () => { + const dramatic = findPortraitPreset("dramatic")!; + const out = applyPortraitPreset(group, "p1", dramatic, 100); + const bg = out.localAdjustments[0]!; + expect(bg.adjust).toEqual({ ...DEFAULT_LOCAL_ADJUST, ...dramatic.roles.background.adjust }); + expect(bg.amount).toBe(dramatic.roles.background.amount); + expect(out.localAdjustments[4]).toBe(group.localAdjustments[4]); + expect(editRecipeSchema.safeParse(out).success).toBe(true); + expect(group.localAdjustments[0]!.amount).toBe(100); + }); + + it("keeps presetId on the face and eyes for the panel's labels", () => { + const out = applyPortraitPreset(group, "p1", findPortraitPreset("natural")!, 100); + expect(out.localAdjustments[2]!.presetId).toBe("skin"); + expect(out.localAdjustments[3]!.presetId).toBe("eyes"); + }); +}); + +describe("scalePortraitAmount / portraitAmount", () => { + it("scales each role's amount by the group's effect and reads it back", () => { + const natural = findPortraitPreset("natural")!; + const half = scalePortraitAmount(group, "p1", natural, 50); + expect(half.localAdjustments[0]!.amount).toBe(Math.round(natural.roles.background.amount / 2)); + expect(portraitAmount(half, "p1", natural)).toBe(50); + expect(portraitAmount(scalePortraitAmount(group, "p1", natural, 0), "p1", natural)).toBe(0); + }); +}); diff --git a/packages/editor-recipe/src/portrait-presets.ts b/packages/editor-recipe/src/portrait-presets.ts new file mode 100644 index 0000000..4692fb3 --- /dev/null +++ b/packages/editor-recipe/src/portrait-presets.ts @@ -0,0 +1,180 @@ +import { + DEFAULT_LOCAL_ADJUST, + type EditRecipe, + type LocalAdjust, + type LocalAdjustment, +} from "./schema.ts"; + +/** + * 人物補正 (#175) のプリセット。1 人ぶんの「背景・人物・顔・瞳」の 4 役に対する部分補正の値と効果量。 + * 部分補正は groupId で束ね、役はマスクの形から決める (portraitRole)。レシピには結果の値だけが + * 入るので、プリセットの定義が後から変わっても投稿済みの見え方は変わらない (04 §1.2 と同じ原則)。 + * 合成順は 背景 → 人物 → 顔 → 瞳 (後の方が上に掛かる)。 + */ + +export const PORTRAIT_ROLES = ["background", "person", "face", "eyes"] as const; +export type PortraitRole = (typeof PORTRAIT_ROLES)[number]; + +export const PORTRAIT_PRESET_IDS = ["natural", "bright", "dramatic", "soft", "eyes"] as const; +export type PortraitPresetId = (typeof PORTRAIT_PRESET_IDS)[number]; + +export type PortraitRoleSetting = { adjust: Partial; amount: number }; + +export type PortraitPreset = { + id: PortraitPresetId; + name: string; + hint: string; + roles: Record; +}; + +const eyesLight: PortraitRoleSetting = { + adjust: { exposure: 0.3, saturation: 15, contrast: 10, sharpen: 30 }, + amount: 70, +}; + +// 数値は実画像で調整する。空間効果は背景・人物・顔の役に分け、1 パスに重い効果を重ねすぎない。 +export const PORTRAIT_PRESETS: readonly PortraitPreset[] = Object.freeze([ + { + id: "natural", + name: "ナチュラル", + hint: "顔を少し明るく、美肌と瞳強調を弱く。背景はわずかに落とす", + roles: { + background: { + adjust: { exposure: -0.15, saturation: -10, contrast: -5, blur: 3, vignette: 10 }, + amount: 60, + }, + person: { adjust: { shadows: 15, contrast: 5, sharpen: 10, clarity: 10 }, amount: 60 }, + face: { adjust: { exposure: 0.15, temperature: 5, smooth: 25, bloom: 8 }, amount: 80 }, + eyes: eyesLight, + }, + }, + { + id: "bright", + name: "明るく", + hint: "顔と人物の露光・シャドウを持ち上げる", + roles: { + background: { adjust: { exposure: -0.05, blur: 2, vignette: 5 }, amount: 40 }, + person: { adjust: { exposure: 0.2, shadows: 30, clarity: 5 }, amount: 80 }, + face: { adjust: { exposure: 0.35, shadows: 20, smooth: 20, bloom: 12 }, amount: 90 }, + eyes: eyesLight, + }, + }, + { + id: "dramatic", + name: "ドラマチック", + hint: "人物のコントラストを上げ、背景を暗く沈める", + roles: { + background: { + adjust: { exposure: -0.5, saturation: -25, contrast: -10, blur: 4, vignette: 30 }, + amount: 90, + }, + person: { adjust: { contrast: 20, shadows: -10, sharpen: 20, clarity: 35 }, amount: 90 }, + face: { adjust: { contrast: 10, smooth: 15 }, amount: 80 }, + eyes: { adjust: { contrast: 20, sharpen: 40, saturation: 10, bloom: 5 }, amount: 80 }, + }, + }, + { + id: "soft", + name: "やわらか", + hint: "美肌を強めに、コントラストを抑えてやわらかく", + roles: { + background: { + adjust: { contrast: -20, saturation: -10, blur: 6, vignette: 15 }, + amount: 70, + }, + person: { adjust: { contrast: -10, highlights: -10 }, amount: 60 }, + face: { + adjust: { smooth: 45, exposure: 0.1, temperature: 8, bloom: 20, clarity: -20 }, + amount: 90, + }, + eyes: { adjust: { exposure: 0.2, sharpen: 10 }, amount: 50 }, + }, + }, + { + id: "eyes", + name: "瞳くっきり", + hint: "両目の露光・彩度・シャープを中心に。他は控えめ", + roles: { + background: { adjust: { exposure: -0.1, blur: 2, vignette: 10 }, amount: 40 }, + person: { adjust: { sharpen: 10, clarity: 15 }, amount: 40 }, + face: { adjust: { smooth: 10 }, amount: 40 }, + eyes: { + adjust: { exposure: 0.4, saturation: 25, contrast: 20, sharpen: 50, bloom: 8, clarity: 20 }, + amount: 100, + }, + }, + }, +]); + +export function findPortraitPreset(id: string): PortraitPreset | undefined { + return PORTRAIT_PRESETS.find((p) => p.id === id); +} + +/** 部分補正の役をマスクの形から決める。反転したビットマップ = 背景、ビットマップ = 人物、多角形 = 顔、楕円 = 瞳 */ +export function portraitRole(local: LocalAdjustment): PortraitRole { + switch (local.mask.kind) { + case "bitmap": + return local.mask.invert ? "background" : "person"; + case "polygon": + return "face"; + case "ellipse": + return "eyes"; + case "brush": + return "person"; + } +} + +const roleAmount = (preset: PortraitPreset, role: PortraitRole, effect: number) => + Math.round((preset.roles[role].amount * effect) / 100); + +/** グループの部分補正にプリセットを当てた新しいレシピ。effect は効果量 0..100。元は変更しない */ +export function applyPortraitPreset( + recipe: EditRecipe, + groupId: string, + preset: PortraitPreset, + effect: number, +): EditRecipe { + return { + ...recipe, + localAdjustments: recipe.localAdjustments.map((l) => { + if (l.groupId !== groupId) return l; + const role = portraitRole(l); + return { + ...l, + adjust: { ...DEFAULT_LOCAL_ADJUST, ...preset.roles[role].adjust }, + amount: roleAmount(preset, role, effect), + }; + }), + }; +} + +/** グループの効果量だけを変えた新しいレシピ (役ごとのプリセットの効果量 × effect / 100) */ +export function scalePortraitAmount( + recipe: EditRecipe, + groupId: string, + preset: PortraitPreset, + effect: number, +): EditRecipe { + return { + ...recipe, + localAdjustments: recipe.localAdjustments.map((l) => + l.groupId === groupId ? { ...l, amount: roleAmount(preset, portraitRole(l), effect) } : l, + ), + }; +} + +/** グループの効果量 (0..100) を読み戻す。役の中で効果量の基準が最大のものから逆算する */ +export function portraitAmount( + recipe: EditRecipe, + groupId: string, + preset: PortraitPreset, +): number { + let best: { base: number; amount: number } | null = null; + for (const l of recipe.localAdjustments) { + if (l.groupId !== groupId) continue; + const base = preset.roles[portraitRole(l)].amount; + if (base > 0 && (!best || base > best.base)) best = { base, amount: l.amount }; + } + if (!best) return 100; + return Math.min(100, Math.round((best.amount / best.base) * 100)); +} diff --git a/packages/editor-recipe/src/presets.ts b/packages/editor-recipe/src/presets.ts new file mode 100644 index 0000000..faf510d --- /dev/null +++ b/packages/editor-recipe/src/presets.ts @@ -0,0 +1,49 @@ +import { DEFAULT_ADJUST, type AdjustV1, type EditRecipe } from "./schema.ts"; + +export type Preset = { + id: string; + name: string; + adjust: Partial; +}; + +// 初期プリセット。数値は実装時 (M1) に実画像で調整する。docs/design/04-edit-recipe.md §2 +export const PRESETS: readonly Preset[] = Object.freeze([ + { + id: "night-city", + name: "夜景", + adjust: { exposure: -0.3, shadows: 25, temperature: -20, contrast: 10 }, + }, + { + id: "warm-sunset", + name: "夕暮れ", + adjust: { temperature: 30, highlights: -20, saturation: -10 }, + }, + { id: "cool-morning", name: "朝霧", adjust: { temperature: -25, contrast: -15, shadows: 20 } }, + { id: "pastel", name: "パステル", adjust: { contrast: -20, vibrance: 15, highlights: 15 } }, + { id: "vivid", name: "ビビッド", adjust: { vibrance: 30, contrast: 15 } }, + { id: "film", name: "フィルム", adjust: { shadows: 20, highlights: -15, saturation: -15 } }, + { id: "mono", name: "モノクロ", adjust: { saturation: -100, contrast: 15 } }, + { id: "soft-portrait", name: "ソフト", adjust: { contrast: -10, highlights: -10, vibrance: 10 } }, + { id: "dungeon", name: "ダンジョン", adjust: { exposure: 0.4, shadows: 30, temperature: -15 } }, + { + id: "gold-hour", + name: "ゴールド", + adjust: { temperature: 35, exposure: 0.2, highlights: -15 }, + }, +]); + +export function findPreset(id: string): Preset | undefined { + return PRESETS.find((p) => p.id === id); +} + +/** + * プリセットを適用した新しいレシピを返す。元のレシピは変更しない。 + * 適用は adjust への上書きであり、幾何情報には触れない。 + */ +export function applyPreset(recipe: EditRecipe, preset: Preset): EditRecipe { + return { + ...recipe, + presetId: preset.id, + adjust: { ...DEFAULT_ADJUST, ...preset.adjust }, + }; +} diff --git a/packages/editor-recipe/src/recipe.test.ts b/packages/editor-recipe/src/recipe.test.ts new file mode 100644 index 0000000..727df24 --- /dev/null +++ b/packages/editor-recipe/src/recipe.test.ts @@ -0,0 +1,441 @@ +import { describe, expect, it } from "vitest"; +import { + BITMAP_MAX_EDGE, + DEFAULT_ELLIPSE_MASK, + DEFAULT_LOCAL_ADJUST, + DEFAULT_LOCAL_ADJUST_V2, + DEFAULT_LOCAL_ADJUSTMENT, + DEFAULT_RECIPE, + CURRENT_RECIPE_VERSION, + MAX_LOCAL_ADJUSTMENTS, + MAX_POLYGON_POINTS, + editRecipeInputSchema, + editRecipeSchema, + editRecipeSchemaV2, + editRecipeSchemaV3, + localAdjustSchemaV4, + localAdjustmentSchema, +} from "./schema.ts"; +import { encodeRle } from "./rle.ts"; +import { migrateRecipe, RecipeMigrationError } from "./migrate.ts"; +import { applyPreset, findPreset, PRESETS } from "./presets.ts"; +import { applyLocalPreset, LOCAL_PRESETS } from "./local-presets.ts"; + +describe("editRecipeSchema v1", () => { + it("rejects a version 1 recipe as the current schema", () => { + expect(editRecipeSchema.safeParse({ ...DEFAULT_RECIPE, version: 1 }).success).toBe(false); + }); + + it("rejects out-of-range values instead of clamping", () => { + const bad = { ...DEFAULT_RECIPE, adjust: { ...DEFAULT_RECIPE.adjust, exposure: 6 } }; + expect(editRecipeSchema.safeParse(bad).success).toBe(false); + }); + + it("rejects non-right-angle rotation", () => { + const bad = { ...DEFAULT_RECIPE, geometry: { ...DEFAULT_RECIPE.geometry, rotation: 45 } }; + expect(editRecipeSchema.safeParse(bad).success).toBe(false); + }); +}); + +describe("migrateRecipe", () => { + it("throws on unknown version", () => { + expect(() => migrateRecipe({ ...DEFAULT_RECIPE, version: 99 })).toThrow(RecipeMigrationError); + }); + + it("throws on input without version", () => { + expect(() => migrateRecipe({})).toThrow(RecipeMigrationError); + expect(() => migrateRecipe(null)).toThrow(RecipeMigrationError); + }); +}); + +describe("editRecipeSchema v4 (#184 人物補正の追加効果)", () => { + const v3 = { + version: 3, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: [ + { + id: "background", + name: null, + presetId: null, + groupId: "portrait", + mask: DEFAULT_ELLIPSE_MASK, + adjust: { + exposure: 0, + contrast: 0, + highlights: 0, + shadows: 0, + temperature: 0, + tint: 0, + saturation: 0, + sharpen: 0, + smooth: 0, + }, + amount: 100, + visible: true, + }, + ], + } as const; + + it("uses version 4 for new recipes and accepts the four additional local effects", () => { + expect(CURRENT_RECIPE_VERSION).toBe(4); + expect(DEFAULT_RECIPE.version).toBe(4); + expect( + localAdjustSchemaV4.safeParse({ + ...DEFAULT_LOCAL_ADJUST, + blur: 12, + bloom: 30, + vignette: 20, + clarity: -25, + }).success, + ).toBe(true); + }); + + it("migrates v3 by adding neutral values without changing existing adjustments", () => { + const out = migrateRecipe(v3); + expect(out.version).toBe(4); + expect(out.localAdjustments[0]!.adjust).toEqual({ + ...v3.localAdjustments[0]!.adjust, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, + }); + }); + + it("rejects v4 effects on a recipe labelled as v3", () => { + const leaked = { + ...v3, + localAdjustments: [ + { + ...v3.localAdjustments[0], + adjust: { ...v3.localAdjustments[0]!.adjust, blur: 10 }, + }, + ], + }; + expect(() => migrateRecipe(leaked)).toThrow(RecipeMigrationError); + }); + + it("rejects additional effects outside their ranges", () => { + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, blur: 33 }).success).toBe( + false, + ); + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, bloom: 101 }).success).toBe( + false, + ); + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, vignette: 101 }).success).toBe( + false, + ); + expect(localAdjustSchemaV4.safeParse({ ...DEFAULT_LOCAL_ADJUST, clarity: -101 }).success).toBe( + false, + ); + }); +}); + +describe("presets", () => { + it("has 10 presets with unique ids", () => { + expect(PRESETS).toHaveLength(10); + expect(new Set(PRESETS.map((p) => p.id)).size).toBe(10); + }); + + it("every preset produces a valid recipe", () => { + for (const preset of PRESETS) { + expect(editRecipeSchema.safeParse(applyPreset(DEFAULT_RECIPE, preset)).success).toBe(true); + } + }); + + it("applyPreset does not mutate the input and keeps geometry", () => { + const before = structuredClone(DEFAULT_RECIPE); + const cropped = { + ...DEFAULT_RECIPE, + geometry: { ...DEFAULT_RECIPE.geometry, rotation: 90 as const }, + }; + const mono = findPreset("mono"); + if (!mono) throw new Error("mono preset missing"); + const out = applyPreset(cropped, mono); + expect(out.adjust.saturation).toBe(-100); + expect(out.geometry.rotation).toBe(90); + expect(out.presetId).toBe("mono"); + expect(DEFAULT_RECIPE).toEqual(before); + }); +}); + +describe("editRecipeSchema v2 (#109 部分補正)", () => { + const ellipse = { + id: "eye-l", + name: null, + presetId: "eyes", + mask: { + kind: "ellipse", + cx: 0.4, + cy: 0.3, + rx: 0.05, + ry: 0.04, + rotation: 0, + feather: 0.3, + invert: false, + }, + adjust: { ...DEFAULT_LOCAL_ADJUST_V2, exposure: 0.3, sharpen: 30 }, + amount: 100, + visible: true, + } as const; + const stroke = { mode: "add", size: 0.05, hardness: 0.8, points: [{ x: 0.5, y: 0.5 }] } as const; + const brush = { + ...ellipse, + id: "gear", + presetId: null, + mask: { kind: "brush", strokes: [stroke], feather: 0, invert: false }, + } as const; + const v2 = (local: unknown[]) => ({ + version: 2, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: local, + }); + + it("accepts an ellipse and a brush local adjustment", () => { + expect(editRecipeSchemaV2.safeParse(v2([ellipse, brush])).success).toBe(true); + }); + + it("rejects a 9th local adjustment in v2 (v2 の上限は 8 のまま)", () => { + const nine = Array.from({ length: 9 }, (_, i) => ({ ...ellipse, id: `m${i}` })); + expect(editRecipeSchemaV2.safeParse(v2(nine)).success).toBe(false); + expect(editRecipeSchemaV2.safeParse(v2(nine.slice(0, 8))).success).toBe(true); + }); + + it("rejects smooth above 60 (美肌の上限)", () => { + const bad = { ...ellipse, adjust: { ...ellipse.adjust, smooth: 61 } }; + expect(editRecipeSchemaV2.safeParse(v2([bad])).success).toBe(false); + }); + + it("rejects a brush stroke with more than 512 points", () => { + const points = Array.from({ length: 513 }, () => ({ x: 0.5, y: 0.5 })); + const bad = { ...brush, mask: { ...brush.mask, strokes: [{ ...stroke, points }] } }; + expect(editRecipeSchemaV2.safeParse(v2([bad])).success).toBe(false); + }); + + it("rejects an ellipse with zero radius", () => { + const bad = { ...ellipse, mask: { ...ellipse.mask, rx: 0 } }; + expect(editRecipeSchemaV2.safeParse(v2([bad])).success).toBe(false); + }); + + it("rejects an unknown local preset id", () => { + expect(editRecipeSchemaV2.safeParse(v2([{ ...ellipse, presetId: "nose" }])).success).toBe( + false, + ); + }); + + it("rejects v3 masks (polygon) in a v2 recipe", () => { + const poly = { ...ellipse, mask: polygonMask }; + expect(editRecipeSchemaV2.safeParse(v2([poly])).success).toBe(false); + }); +}); + +const polygonMask = { + kind: "polygon", + rings: [ + [ + { x: 0.3, y: 0.2 }, + { x: 0.7, y: 0.2 }, + { x: 0.5, y: 0.8 }, + ], + ], + strokes: [], + feather: 0.1, + invert: false, +} as const; + +describe("editRecipeSchema v3 (#176 自動選択のマスク)", () => { + const base = { + id: "face", + name: null, + presetId: "skin", + groupId: null, + adjust: DEFAULT_LOCAL_ADJUST_V2, + amount: 100, + visible: true, + } as const; + const bitmapMask = { + kind: "bitmap", + width: 4, + height: 2, + rle: encodeRle(Uint8Array.from([0, 1, 1, 0, 0, 1, 1, 0])), + strokes: [], + feather: 0, + invert: false, + } as const; + const v3 = (local: unknown[]) => ({ + version: 3, + presetId: DEFAULT_RECIPE.presetId, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: local, + }); + + it("the current recipe keeps v3 masks and starts with no local adjustments", () => { + expect(DEFAULT_RECIPE.version).toBe(4); + expect(DEFAULT_RECIPE.localAdjustments).toEqual([]); + expect(editRecipeSchema.parse(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + }); + + it("accepts polygon and bitmap masks alongside ellipse and brush", () => { + const list = [ + { ...base, mask: polygonMask }, + { ...base, id: "gear", presetId: "gear", mask: bitmapMask }, + { ...base, id: "eye", presetId: "eyes", mask: DEFAULT_ELLIPSE_MASK }, + ]; + expect(editRecipeSchemaV3.safeParse(v3(list)).success).toBe(true); + }); + + it("allows up to 12 local adjustments (人物補正 1 人で 5 件使う)", () => { + expect(MAX_LOCAL_ADJUSTMENTS).toBe(12); + const many = (n: number) => + Array.from({ length: n }, (_, i) => ({ ...base, id: `m${i}`, mask: DEFAULT_ELLIPSE_MASK })); + expect(editRecipeSchemaV3.safeParse(v3(many(12))).success).toBe(true); + expect(editRecipeSchemaV3.safeParse(v3(many(13))).success).toBe(false); + }); + + it("rejects a polygon ring with fewer than 3 points or more than the limit", () => { + const two = { ...polygonMask, rings: [polygonMask.rings[0].slice(0, 2)] }; + expect(editRecipeSchemaV3.safeParse(v3([{ ...base, mask: two }])).success).toBe(false); + const ring = Array.from({ length: MAX_POLYGON_POINTS + 1 }, (_, i) => ({ + x: (i % 100) / 100, + y: 0.5, + })); + expect( + editRecipeSchemaV3.safeParse(v3([{ ...base, mask: { ...polygonMask, rings: [ring] } }])) + .success, + ).toBe(false); + }); + + it("rejects a bitmap larger than the edge limit or with a mismatched rle", () => { + const big = { + ...bitmapMask, + width: BITMAP_MAX_EDGE + 1, + height: 1, + rle: encodeRle(new Uint8Array(BITMAP_MAX_EDGE + 1)), + }; + expect(editRecipeSchemaV3.safeParse(v3([{ ...base, mask: big }])).success).toBe(false); + const short = { ...bitmapMask, rle: encodeRle(Uint8Array.from([1, 1, 1])) }; + expect(editRecipeSchemaV3.safeParse(v3([{ ...base, mask: short }])).success).toBe(false); + }); + + it("carries a groupId so a portrait's adjustments can be handled together", () => { + const grouped = { ...base, groupId: "p1", mask: polygonMask }; + expect(editRecipeSchemaV3.safeParse(v3([grouped])).success).toBe(true); + expect( + editRecipeSchemaV3.safeParse(v3([{ ...grouped, groupId: "x".repeat(33) }])).success, + ).toBe(false); + }); +}); + +describe("migrateRecipe v2 -> v3", () => { + const v2 = { + version: 2, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + localAdjustments: [ + { + id: "a", + name: null, + presetId: "eyes", + mask: DEFAULT_ELLIPSE_MASK, + adjust: DEFAULT_LOCAL_ADJUST_V2, + amount: 80, + visible: true, + }, + ], + }; + + it("adds groupId and neutral v4 effects to each local adjustment", () => { + const out = migrateRecipe(v2); + expect(out.version).toBe(4); + expect(out.localAdjustments[0]).toEqual({ + ...v2.localAdjustments[0], + groupId: null, + adjust: { + ...v2.localAdjustments[0]!.adjust, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, + }, + }); + }); + + it("migrates v1 all the way to v4", () => { + const v1 = { + version: 1, + presetId: null, + adjust: DEFAULT_RECIPE.adjust, + geometry: DEFAULT_RECIPE.geometry, + }; + expect(migrateRecipe(v1)).toEqual({ ...v1, version: 4, localAdjustments: [] }); + }); + + it("rejects a v2 recipe that already carries groupId", () => { + const leaked = { ...v2, localAdjustments: [{ ...v2.localAdjustments[0], groupId: null }] }; + expect(() => migrateRecipe(leaked)).toThrow(RecipeMigrationError); + }); + + it("accepts v1 through v4 through editRecipeInputSchema (API の入出力)", () => { + expect(editRecipeInputSchema.safeParse(v2).success).toBe(true); + expect(editRecipeInputSchema.safeParse(DEFAULT_RECIPE).success).toBe(true); + expect(editRecipeInputSchema.safeParse({ ...DEFAULT_RECIPE, version: 5 }).success).toBe(false); + }); +}); + +describe("migrateRecipe v1 -> v2", () => { + const v1 = { + version: 1, + presetId: "mono", + adjust: { ...DEFAULT_RECIPE.adjust, saturation: -100 }, + geometry: { ...DEFAULT_RECIPE.geometry, rotation: 90 }, + }; + + it("fills localAdjustments with an empty array (v2 の形) on the way to the current version", () => { + expect(migrateRecipe(v1)).toEqual({ ...v1, version: 4, localAdjustments: [] }); + }); + + it("passes a valid current recipe through unchanged", () => { + expect(migrateRecipe(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + }); + + it("rejects a v1 recipe that already carries v2 fields", () => { + expect(() => migrateRecipe({ ...v1, localAdjustments: [] })).toThrow(RecipeMigrationError); + }); + + it("accepts v1 through editRecipeInputSchema but not a v1 body labelled v3", () => { + expect(editRecipeInputSchema.safeParse(v1).success).toBe(true); + expect(editRecipeInputSchema.safeParse({ ...v1, version: 3 }).success).toBe(false); + }); +}); + +describe("local presets", () => { + it("has eyes / skin / gear and each produces a valid adjustment", () => { + expect(LOCAL_PRESETS.map((p) => p.id)).toEqual(["eyes", "skin", "gear"]); + for (const preset of LOCAL_PRESETS) { + const local = applyLocalPreset( + { ...DEFAULT_LOCAL_ADJUSTMENT, id: "x", mask: DEFAULT_ELLIPSE_MASK }, + preset, + ); + expect(localAdjustmentSchema.safeParse(local).success).toBe(true); + expect(local.presetId).toBe(preset.id); + } + }); + + it("applyLocalPreset keeps the mask and does not mutate the input", () => { + const input = { + ...DEFAULT_LOCAL_ADJUSTMENT, + id: "x", + mask: { ...DEFAULT_ELLIPSE_MASK, cx: 0.2 }, + }; + const before = structuredClone(input); + const out = applyLocalPreset(input, LOCAL_PRESETS[0]!); + expect(out.mask).toEqual(input.mask); + expect(input).toEqual(before); + }); +}); diff --git a/packages/editor-recipe/src/rle.test.ts b/packages/editor-recipe/src/rle.test.ts new file mode 100644 index 0000000..66ab7e3 --- /dev/null +++ b/packages/editor-recipe/src/rle.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { decodeRle, encodeRle } from "./rle.ts"; + +describe("rle (bitmap マスクの圧縮)", () => { + it("0/1 の列を往復できる", () => { + const src = Uint8Array.from([0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1]); + const text = encodeRle(src); + expect(decodeRle(text, src.length)).toEqual(src); + }); + + it("全部 0 と全部 1 も往復できる", () => { + for (const v of [0, 1]) { + const src = new Uint8Array(1000).fill(v); + expect(decodeRle(encodeRle(src), 1000)).toEqual(src); + } + }); + + it("長い連 (65535 超) も往復できる", () => { + const src = new Uint8Array(70000).fill(1); + src[0] = 0; + expect(decodeRle(encodeRle(src), src.length)).toEqual(src); + }); + + it("URL に載せられる文字だけを使う (base64url)", () => { + const src = Uint8Array.from({ length: 512 }, (_, i) => (i % 7 < 3 ? 1 : 0)); + expect(encodeRle(src)).toMatch(/^[A-Za-z0-9_-]*$/); + }); + + it("長さが合わない入力は捨てる", () => { + const text = encodeRle(Uint8Array.from([1, 1, 0])); + expect(() => decodeRle(text, 4)).toThrow(); + expect(() => decodeRle("!!", 3)).toThrow(); + }); +}); diff --git a/packages/editor-recipe/src/rle.ts b/packages/editor-recipe/src/rle.ts new file mode 100644 index 0000000..ae4c923 --- /dev/null +++ b/packages/editor-recipe/src/rle.ts @@ -0,0 +1,105 @@ +/** + * bitmap マスク (Recipe v3、#176 / #177) の 0/1 列をランレングスで圧縮する。 + * 連の長さを 0 から始めて交互に (0 の連、1 の連、0 の連 ...) LEB128 の可変長整数で並べ、 + * base64url にする。ブラウザでも Node でも動くように、Buffer や atob は使わない。 + * 256×256 (65,536 px) のマスクは、輪郭の複雑さにもよるが数百〜数 KB になる。 + */ + +const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; +const LOOKUP = new Map(Array.from(ALPHABET, (c, i) => [c, i])); + +function toBase64Url(bytes: readonly number[]): string { + let out = ""; + for (let i = 0; i < bytes.length; i += 3) { + const b0 = bytes[i]!; + const b1 = bytes[i + 1]; + const b2 = bytes[i + 2]; + out += ALPHABET[b0 >> 2]!; + out += ALPHABET[((b0 & 3) << 4) | ((b1 ?? 0) >> 4)]!; + if (b1 === undefined) break; + out += ALPHABET[((b1 & 15) << 2) | ((b2 ?? 0) >> 6)]!; + if (b2 === undefined) break; + out += ALPHABET[b2 & 63]!; + } + return out; +} + +function fromBase64Url(text: string): number[] { + const out: number[] = []; + let acc = 0; + let bits = 0; + for (const c of text) { + const v = LOOKUP.get(c); + if (v === undefined) throw new Error("rle: invalid character"); + acc = (acc << 6) | v; + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push((acc >> bits) & 255); + } + } + return out; +} + +/** 0/1 (0 以外は 1 とみなす) の列を圧縮する */ +export function encodeRle(mask: Uint8Array | Uint8ClampedArray): string { + const bytes: number[] = []; + const pushVarint = (n: number) => { + let v = n; + while (v >= 128) { + bytes.push((v & 127) | 128); + v = Math.floor(v / 128); + } + bytes.push(v); + }; + let current = 0; + let run = 0; + for (let i = 0; i < mask.length; i++) { + const bit = mask[i] ? 1 : 0; + if (bit === current) { + run++; + } else { + pushVarint(run); + current = bit; + run = 1; + } + } + pushVarint(run); + return toBase64Url(bytes); +} + +/** 圧縮した列を length 個の 0/1 に戻す。長さが合わなければ捨てる (壊れたレシピを通さない) */ +export function decodeRle(text: string, length: number): Uint8Array { + const bytes = fromBase64Url(text); + const out = new Uint8Array(length); + let pos = 0; + let current = 0; + let i = 0; + while (i < bytes.length) { + let run = 0; + let shift = 1; + for (;;) { + const b = bytes[i++]; + if (b === undefined) throw new Error("rle: truncated"); + run += (b & 127) * shift; + if (b < 128) break; + shift *= 128; + } + if (pos + run > length) throw new Error("rle: length mismatch"); + if (current) out.fill(1, pos, pos + run); + pos += run; + current ^= 1; + } + if (pos !== length) throw new Error("rle: length mismatch"); + return out; +} + +/** 復号できて長さが合うか (スキーマの検証用) */ +export function isValidRle(text: string, length: number): boolean { + try { + decodeRle(text, length); + return true; + } catch { + return false; + } +} diff --git a/packages/editor-recipe/src/schema.ts b/packages/editor-recipe/src/schema.ts new file mode 100644 index 0000000..29c55d2 --- /dev/null +++ b/packages/editor-recipe/src/schema.ts @@ -0,0 +1,334 @@ +import { z } from "zod"; +import { isValidRle } from "./rle.ts"; + +// zod 4 は JIT の可否を Function("") で探る。CSP (script-src に unsafe-eval が無い) の下では握られて動作は +// 落ちないが、ブラウザから違反が報告され続ける (RM-30)。このスキーマはブラウザでも動くので JIT を使わない。 +// 同じ zod のインスタンスを使う server 側の検証も jitless になるが、この規模では差が出ない +z.config({ jitless: true }); + +// 編集レシピ。定義は docs/design/04-edit-recipe.md を正とする。 +// 変更は追加のみ。既存項目の意味・値域は変えない (ADR-0009)。 +// v1: 全体の補正と幾何。v2: 部分補正 (マスク付きの補正、#109) を追加。 +// v3: 自動選択 (#176 / #177) のための多角形・ビットマップのマスクと、人物補正 (#175) の groupId を追加。 + +const pct = z.number().min(-100).max(100); + +/** v2 の部分補正の上限 (レシピの肥大化と描画負荷を抑える、#109)。v3 は MAX_LOCAL_ADJUSTMENTS */ +export const MAX_LOCAL_ADJUSTMENTS_V2 = 8; +export const MAX_BRUSH_STROKES = 64; +export const MAX_BRUSH_POINTS = 512; +export const MAX_LOCAL_SMOOTH = 60; +/** 背景ぼかしの半径 (元画像 px)。固定 3x3 カーネルの間隔として使う */ +export const MAX_LOCAL_BLUR = 32; + +export const adjustSchemaV1 = z.object({ + exposure: z.number().min(-5).max(5), + contrast: pct, + highlights: pct, + shadows: pct, + temperature: pct, + tint: pct, + vibrance: pct, + saturation: pct, +}); + +export const cropSchemaV1 = z.object({ + x: z.number().min(0).max(1), + y: z.number().min(0).max(1), + w: z.number().min(0).max(1), + h: z.number().min(0).max(1), +}); + +export const ASPECT_PRESETS = ["free", "1:1", "4:3", "3:2", "16:9", "9:16", "3:4", "2:3"] as const; + +export const geometrySchemaV1 = z.object({ + rotation: z.union([z.literal(0), z.literal(90), z.literal(180), z.literal(270)]), + straighten: z.number().min(-45).max(45), + flipH: z.boolean(), + crop: cropSchemaV1.nullable(), + aspect: z.enum(ASPECT_PRESETS).nullable(), +}); + +export const editRecipeSchemaV1 = z.object({ + version: z.literal(1), + presetId: z.string().max(64).nullable(), + adjust: adjustSchemaV1, + geometry: geometrySchemaV1, +}); + +export type AdjustV1 = z.infer; +export type GeometryV1 = z.infer; +export type EditRecipeV1 = z.infer; + +// ---- v2: 部分補正 (#109) ---- +// マスクの座標は幾何 (回転・反転・トリミング) を掛ける前の画像の正規化座標 (0..1)。 +// 幾何は合成後に掛かるので、回転・トリミングしてもマスクの位置はずれない。 + +const unit = z.number().min(0).max(1); + +/** 部分補正で使える項目。全体の補正から vibrance を外し、シャープと美肌 (平滑化) を足す */ +export const localAdjustSchemaV2 = z.object({ + exposure: z.number().min(-5).max(5), + contrast: pct, + highlights: pct, + shadows: pct, + temperature: pct, + tint: pct, + saturation: pct, + /** アンシャープマスク (3x3)。0..100 */ + sharpen: z.number().min(0).max(100), + /** 輪郭を残す平滑化 (美肌)。過度なぼかしを避けるため上限 60 */ + smooth: z.number().min(0).max(MAX_LOCAL_SMOOTH), +}); + +export const ellipseMaskSchemaV2 = z.object({ + kind: z.literal("ellipse"), + cx: unit, + cy: unit, + /** 半径。rx は画像の幅、ry は高さに対する比 */ + rx: z.number().gt(0).max(1), + ry: z.number().gt(0).max(1), + /** 度 */ + rotation: z.number().min(-180).max(180), + /** 半径に対するぼかし幅の比 */ + feather: unit, + invert: z.boolean(), +}); + +export const brushStrokeSchemaV2 = z.object({ + mode: z.enum(["add", "erase"]), + /** ブラシ径。画像の長辺に対する比 */ + size: z.number().min(0.005).max(0.5), + hardness: unit, + points: z + .array(z.object({ x: unit, y: unit })) + .min(1) + .max(MAX_BRUSH_POINTS), +}); + +export const brushMaskSchemaV2 = z.object({ + kind: z.literal("brush"), + strokes: z.array(brushStrokeSchemaV2).max(MAX_BRUSH_STROKES), + feather: unit, + invert: z.boolean(), +}); + +export const maskSchemaV2 = z.discriminatedUnion("kind", [ellipseMaskSchemaV2, brushMaskSchemaV2]); + +export const LOCAL_PRESET_IDS = ["eyes", "skin", "gear"] as const; + +export const localAdjustmentSchemaV2 = z.object({ + id: z.string().min(1).max(32), + name: z.string().max(32).nullable(), + /** 表示用。結果は adjust と amount で決まる (v1 の presetId と同じ原則) */ + presetId: z.enum(LOCAL_PRESET_IDS).nullable(), + mask: maskSchemaV2, + adjust: localAdjustSchemaV2, + /** 効果量 0..100 */ + amount: z.number().min(0).max(100), + visible: z.boolean(), +}); + +export const editRecipeSchemaV2 = editRecipeSchemaV1.extend({ + version: z.literal(2), + localAdjustments: z.array(localAdjustmentSchemaV2).max(MAX_LOCAL_ADJUSTMENTS_V2), +}); + +export type LocalAdjustV2 = z.infer; +export type EllipseMaskV2 = z.infer; +export type BrushStrokeV2 = z.infer; +export type BrushMaskV2 = z.infer; +export type MaskV2 = z.infer; +export type LocalPresetId = (typeof LOCAL_PRESET_IDS)[number]; +export type LocalAdjustmentV2 = z.infer; +export type EditRecipeV2 = z.infer; + +// ---- v3: 自動選択のマスクと人物補正のまとまり (#175 / #176 / #177) ---- +// 顔の輪郭 (多角形) と SAM の切り抜き (ビットマップ) をブラシ点列に崩さず持つ。どちらも strokes を持ち、 +// 自動で置いたマスクの上にブラシで足す / 消す (brush と同じ道具で直せる)。 +// 座標系は v2 と同じ (幾何を掛ける前の画像の正規化座標)。 + +/** 部分補正の上限。人物補正 (#175) が 1 人で 5 件 (顔・瞳 ×2・人物・背景) 使う */ +export const MAX_LOCAL_ADJUSTMENTS = 12; +/** 多角形の輪 (外周 1 + 穴) の上限と、1 輪の点数の上限 */ +export const MAX_POLYGON_RINGS = 8; +export const MAX_POLYGON_POINTS = 256; +/** ビットマップマスクの 1 辺の上限 (px)。GPU では線形補間で拡大するので境界は滑らか */ +export const BITMAP_MAX_EDGE = 256; + +const ring = z + .array(z.object({ x: unit, y: unit })) + .min(3) + .max(MAX_POLYGON_POINTS); + +export const polygonMaskSchemaV3 = z.object({ + kind: z.literal("polygon"), + /** 先頭が外周、以降は穴 (偶奇で塗る)。顔なら外周 = 顔の輪郭、穴 = 目・口 */ + rings: z.array(ring).min(1).max(MAX_POLYGON_RINGS), + strokes: z.array(brushStrokeSchemaV2).max(MAX_BRUSH_STROKES), + feather: unit, + invert: z.boolean(), +}); + +export const bitmapMaskSchemaV3 = z + .object({ + kind: z.literal("bitmap"), + width: z.number().int().min(1).max(BITMAP_MAX_EDGE), + height: z.number().int().min(1).max(BITMAP_MAX_EDGE), + /** width × height の 0/1 を rle.ts で圧縮したもの (行優先) */ + rle: z.string().max(64 * 1024), + strokes: z.array(brushStrokeSchemaV2).max(MAX_BRUSH_STROKES), + feather: unit, + invert: z.boolean(), + }) + .refine((m) => isValidRle(m.rle, m.width * m.height), { message: "rle does not match size" }); + +export const maskSchemaV3 = z.discriminatedUnion("kind", [ + ellipseMaskSchemaV2, + brushMaskSchemaV2, + polygonMaskSchemaV3, + bitmapMaskSchemaV3, +]); + +export const localAdjustmentSchemaV3 = localAdjustmentSchemaV2.extend({ + mask: maskSchemaV3, + /** 人物補正 (#175) など、まとめて扱う部分補正の組。無ければ null */ + groupId: z.string().min(1).max(32).nullable(), +}); + +export const editRecipeSchemaV3 = editRecipeSchemaV1.extend({ + version: z.literal(3), + localAdjustments: z.array(localAdjustmentSchemaV3).max(MAX_LOCAL_ADJUSTMENTS), +}); + +export type PolygonMaskV3 = z.infer; +export type BitmapMaskV3 = z.infer; +export type MaskV3 = z.infer; +export type LocalAdjustmentV3 = z.infer; +export type EditRecipeV3 = z.infer; +/** strokes を持つマスク (ブラシで直せるもの) */ +export type StrokedMask = Exclude; + +// ---- v4: 人物補正の追加効果 (#184) ---- +// v3 までの部分補正の意味を変えず、空間効果を中立値 0 で追加する。 + +export const localAdjustSchemaV4 = localAdjustSchemaV2.extend({ + /** 背景ぼかしの半径 (元画像 px)。0..32 */ + blur: z.number().min(0).max(MAX_LOCAL_BLUR), + /** 高輝度成分をぼかして加算する発光。0..100 */ + bloom: z.number().min(0).max(100), + /** 画像中心から周辺を減光する強さ。0..100 */ + vignette: z.number().min(0).max(100), + /** 近傍平均との差による局所コントラスト。-100..100 */ + clarity: pct, +}); + +export const localAdjustmentSchemaV4 = localAdjustmentSchemaV3.extend({ + adjust: localAdjustSchemaV4, +}); + +export const editRecipeSchemaV4 = editRecipeSchemaV1.extend({ + version: z.literal(4), + localAdjustments: z.array(localAdjustmentSchemaV4).max(MAX_LOCAL_ADJUSTMENTS), +}); + +export type LocalAdjustV4 = z.infer; +export type LocalAdjustmentV4 = z.infer; +export type EditRecipeV4 = z.infer; + +/** 現行のレシピ型。version を上げたらここを差し替える。 */ +export type EditRecipe = EditRecipeV4; +export type LocalAdjust = LocalAdjustV4; +export type LocalAdjustment = LocalAdjustmentV4; +export type Mask = MaskV3; +export const editRecipeSchema = editRecipeSchemaV4; +export const CURRENT_RECIPE_VERSION = 4 as const; +export const localAdjustmentSchema = localAdjustmentSchemaV4; + +/** + * API の入出力で受けるレシピ。旧版の投稿はそのまま返り、投稿時も旧版のクライアントを受ける。 + * 読む側は migrateRecipe で現行に揃える。 + */ +export const editRecipeInputSchema = z.union([ + editRecipeSchemaV1, + editRecipeSchemaV2, + editRecipeSchemaV3, + editRecipeSchemaV4, +]); +export type EditRecipeInput = z.infer; + +export const DEFAULT_ADJUST: AdjustV1 = Object.freeze({ + exposure: 0, + contrast: 0, + highlights: 0, + shadows: 0, + temperature: 0, + tint: 0, + vibrance: 0, + saturation: 0, +}); + +export const DEFAULT_GEOMETRY: GeometryV1 = Object.freeze({ + rotation: 0, + straighten: 0, + flipH: false, + crop: null, + aspect: null, +}); + +export const DEFAULT_LOCAL_ADJUST_V2: LocalAdjustV2 = Object.freeze({ + exposure: 0, + contrast: 0, + highlights: 0, + shadows: 0, + temperature: 0, + tint: 0, + saturation: 0, + sharpen: 0, + smooth: 0, +}); + +export const DEFAULT_LOCAL_ADJUST: LocalAdjustV4 = Object.freeze({ + ...DEFAULT_LOCAL_ADJUST_V2, + blur: 0, + bloom: 0, + vignette: 0, + clarity: 0, +}); + +/** 画像の中央、短辺の 1/8 程度の円 */ +export const DEFAULT_ELLIPSE_MASK: EllipseMaskV2 = Object.freeze({ + kind: "ellipse", + cx: 0.5, + cy: 0.5, + rx: 0.12, + ry: 0.12, + rotation: 0, + feather: 0.5, + invert: false, +}); + +export const DEFAULT_BRUSH_MASK: BrushMaskV2 = Object.freeze({ + kind: "brush", + strokes: [], + feather: 0, + invert: false, +}); + +/** id と mask を除いた部分補正の既定値。呼ぶ側が id と mask を与える */ +export const DEFAULT_LOCAL_ADJUSTMENT: Omit = Object.freeze({ + name: null, + presetId: null, + groupId: null, + adjust: DEFAULT_LOCAL_ADJUST, + amount: 100, + visible: true, +}); + +export const DEFAULT_RECIPE: EditRecipe = Object.freeze({ + version: 4, + presetId: null, + adjust: DEFAULT_ADJUST, + geometry: DEFAULT_GEOMETRY, + localAdjustments: [], +}); diff --git a/packages/editor-recipe/src/upgrade.test.ts b/packages/editor-recipe/src/upgrade.test.ts new file mode 100644 index 0000000..93aa110 --- /dev/null +++ b/packages/editor-recipe/src/upgrade.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_RECIPE } from "./schema.ts"; +import { upgradeStoredRecipe } from "./upgrade.ts"; + +describe("upgradeStoredRecipe (#109 レシピの版上げ)", () => { + it("brings a version 1 recipe saved before local adjustments up to the current version", () => { + const { version: _v, localAdjustments: _l, ...v1 } = DEFAULT_RECIPE; + expect(upgradeStoredRecipe({ ...v1, version: 1 })).toEqual(DEFAULT_RECIPE); + }); + + it("returns null for a recipe it cannot read instead of throwing", () => { + expect(upgradeStoredRecipe({ version: 99 })).toBeNull(); + expect(upgradeStoredRecipe(undefined)).toBeNull(); + }); + + it("keeps a current recipe as it is", () => { + expect(upgradeStoredRecipe(DEFAULT_RECIPE)).toEqual(DEFAULT_RECIPE); + }); +}); diff --git a/packages/editor-recipe/src/upgrade.ts b/packages/editor-recipe/src/upgrade.ts new file mode 100644 index 0000000..28d452e --- /dev/null +++ b/packages/editor-recipe/src/upgrade.ts @@ -0,0 +1,15 @@ +import { migrateRecipe } from "./migrate.ts"; +import type { EditRecipe } from "./schema.ts"; + +/** + * 端末に残っているレシピを現行の版に上げる (docs/design/04 §5)。 + * 部分補正 (#109) より前に保存した下書きは version 1 なので、読むたびにここで揃える。 + * 読めないものは null (壊れた下書きは無かったことにする) + */ +export function upgradeStoredRecipe(input: unknown): EditRecipe | null { + try { + return migrateRecipe(input); + } catch { + return null; + } +} diff --git a/packages/editor-recipe/tsconfig.build.json b/packages/editor-recipe/tsconfig.build.json new file mode 100644 index 0000000..a18d5c9 --- /dev/null +++ b/packages/editor-recipe/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "rootDir": "src", + "outDir": "dist" + }, + "exclude": ["src/**/*.test.ts"] +} diff --git a/packages/editor-recipe/tsconfig.json b/packages/editor-recipe/tsconfig.json new file mode 100644 index 0000000..b43ca44 --- /dev/null +++ b/packages/editor-recipe/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "lib": ["ES2024", "DOM"], + "types": [] + }, + "include": ["src/**/*"] +} diff --git a/packages/editor-recipe/vitest.config.ts b/packages/editor-recipe/vitest.config.ts new file mode 100644 index 0000000..a3fd42f --- /dev/null +++ b/packages/editor-recipe/vitest.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from "vitest/config"; +import { readEditorSource } from "../../vitest.source.ts"; +export default defineConfig({ + ...readEditorSource, + test: { name: "editor-recipe", include: ["src/**/*.test.ts"] }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c2456ba..f8bca9e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -162,6 +162,9 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + '@huggingface/transformers>sharp': ^0.35.5 + importers: .: @@ -194,6 +197,46 @@ importers: specifier: ^5.0.3 version: 5.0.3(@types/node@24.19.1)(@vitest/coverage-v8@5.0.3)(vite@8.3.2(@types/node@24.19.1)(yaml@2.9.1)) + packages/editor-engine: + dependencies: + '@huggingface/transformers': + specifier: ^3.8.1 + version: 3.8.1(@types/node@24.19.1) + '@lumorphia/editor-recipe': + specifier: workspace:* + version: link:../editor-recipe + '@mediapipe/tasks-vision': + specifier: ^1.0.1 + version: 1.0.1 + idb-keyval: + specifier: ^6.3.0 + version: 6.3.0 + pixi.js: + specifier: ^8.22.0 + version: 8.22.0 + + packages/editor-react: + dependencies: + '@lumorphia/editor-engine': + specifier: workspace:* + version: link:../editor-engine + '@lumorphia/editor-recipe': + specifier: workspace:* + version: link:../editor-recipe + devDependencies: + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + react: + specifier: ^19.3.0 + version: 19.3.0 + + packages/editor-recipe: + dependencies: + zod: + specifier: ^4.6.5 + version: 4.6.5 + packages: '@babel/helper-string-parser@7.29.7': @@ -223,6 +266,9 @@ packages: '@cacheable/utils@2.5.0': resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + '@eslint-community/eslint-utils@4.10.1': resolution: {integrity: sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -253,6 +299,13 @@ packages: resolution: {integrity: sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==} engines: {node: ^20.19.0 || ^22.13.0 || >=24} + '@huggingface/jinja@0.5.10': + resolution: {integrity: sha512-SgS1D1bglQ94ceD4ZCL6eayUDy9uV1xuyk61OjgSxU5GJh7upqZCKII0JoTYMc6wWsg3JUgaPRX0ElQzXPk3Cw==} + engines: {node: '>=18'} + + '@huggingface/transformers@3.8.1': + resolution: {integrity: sha512-tsTk4zVjImqdqjS8/AOZg2yNLd1z9S5v+7oUPpXaasDRwEDhB+xnglK1k5cad26lL5/ZIaeREgWWy0bs9y9pPA==} + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -273,6 +326,172 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [darwin] + + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} + engines: {node: '>=20.9.0'} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} + engines: {node: '>=20.9.0'} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} + engines: {node: '>=20.9.0'} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} + engines: {node: ^20.9.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [win32] + + '@isaacs/fs-minipass@4.0.1': + resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} + engines: {node: '>=18.0.0'} + '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -292,9 +511,42 @@ packages: '@keyv/serialize@1.1.1': resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==} + '@mediapipe/tasks-vision@1.0.1': + resolution: {integrity: sha512-rvRE2FmAZ6ZxKSw7wq+e+jQDpN3t1B/tD2mJz9SmAzb1msoDkd4dMoE4wAh8Z30Um0PQwLiHr9QtomhmXk3aUQ==} + '@oxc-project/types@0.152.0': resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==} + '@pixi/colord@2.9.6': + resolution: {integrity: sha512-nezytU2pw587fQstUu1AsJZDVEynjskwOL+kibwcdxsMBFqPsFFNA7xl0ii/gXuDi6M0xj3mfRJj8pBSc2jCfA==} + + '@protobufjs/aspromise@1.1.2': + resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} + + '@protobufjs/base64@1.1.2': + resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==} + + '@protobufjs/codegen@2.0.5': + resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==} + + '@protobufjs/eventemitter@1.1.1': + resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==} + + '@protobufjs/fetch@1.1.1': + resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==} + + '@protobufjs/float@1.0.2': + resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==} + + '@protobufjs/path@1.1.2': + resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==} + + '@protobufjs/pool@1.1.0': + resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==} + + '@protobufjs/utf8@1.1.2': + resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==} + '@rolldown/binding-android-arm-eabi@1.2.12': resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -400,6 +652,9 @@ packages: '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + '@types/earcut@3.0.0': + resolution: {integrity: sha512-k/9fOUGO39yd2sCjrbAJvGDEQvRwRnQIZlBz43roGwUZo5SHAmyVvSFyaVVZkicRVCaDXPKlbxrUcBuJoSWunQ==} + '@types/esrecurse@4.3.1': resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==} @@ -412,6 +667,9 @@ packages: '@types/node@24.19.1': resolution: {integrity: sha512-aS3/DG0oM05K0RIXXP+hKjinGG5IgSSVGzswZxW3O0sS3pH4/fycXundUC9XsszgKCk4gHXylTEK6hyFxVxnoQ==} + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + '@typescript-eslint/eslint-plugin@8.71.0': resolution: {integrity: sha512-pqcS9c1HxZTHt7End4nXqd0s5lJrrFzrgCkKFJrsbUnaL6M3+6oBFZaslg6Gjsl3argl2DDRFROnXARaZ2e4Nw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -502,6 +760,13 @@ packages: '@vitest/spy@5.0.3': resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==} + '@webgpu/types@0.1.74': + resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==} + + '@xmldom/xmldom@0.8.15': + resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==} + engines: {node: '>=10.0.0'} + acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -526,6 +791,10 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} + boolean@3.2.0: + resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -537,10 +806,17 @@ packages: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} + chownr@3.0.0: + resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} + engines: {node: '>=18'} + cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -553,13 +829,38 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + define-data-property@1.1.4: + resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} + engines: {node: '>= 0.4'} + + define-properties@1.2.1: + resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} + engines: {node: '>= 0.4'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + detect-node@2.1.0: + resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} + + earcut@3.2.4: + resolution: {integrity: sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + es6-error@4.1.1: + resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==} + escape-string-regexp@4.0.0: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} @@ -609,6 +910,9 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} + eventemitter3@5.0.4: + resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} + expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} @@ -641,6 +945,9 @@ packages: flat-cache@6.1.23: resolution: {integrity: sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} + flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} @@ -649,10 +956,31 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + gifuct-js@2.1.2: + resolution: {integrity: sha512-rI2asw77u0mGgwhV3qA+OEgYqaDn5UNqgs+Bx0FGwSpuqfYn+Ir6RQY5ENNQ8SbIiG/m5gVa7CD5RriO4f4Lsg==} + glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} + global-agent@3.0.0: + resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==} + engines: {node: '>=10.0'} + + globalthis@1.0.4: + resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} + engines: {node: '>= 0.4'} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + guid-typescript@1.0.9: + resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} + + has-property-descriptors@1.0.2: + resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} + hashery@1.5.1: resolution: {integrity: sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==} engines: {node: '>=20'} @@ -668,6 +996,9 @@ packages: engines: {node: '>=18'} hasBin: true + idb-keyval@6.3.0: + resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==} + ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -691,6 +1022,12 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + ismobilejs@1.1.1: + resolution: {integrity: sha512-VaFW53yt8QO61k2WJui0dHf4SlL8lxBofUuUmwBo0ljPk0Drz2TiuDW4jo3wDcv41qy/SxrJ+VAzJ/qYqsmzRw==} + + js-binary-schema-parser@2.0.3: + resolution: {integrity: sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg==} + js-tokens@10.0.0: resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} @@ -700,6 +1037,9 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json-stringify-safe@5.0.1: + resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==} + keyv@5.6.0: resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==} @@ -790,16 +1130,31 @@ packages: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + magic-string@1.4.2: resolution: {integrity: sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g==} magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} + matcher@3.0.0: + resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} + engines: {node: '>=10'} + minimatch@10.2.6: resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} engines: {node: 18 || 20 || >=22} + minipass@7.1.3: + resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} + engines: {node: '>=16 || 14 >=14.17'} + + minizlib@3.1.0: + resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} + engines: {node: '>= 18'} + ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -811,10 +1166,27 @@ packages: natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + object-keys@1.1.1: + resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} + engines: {node: '>= 0.4'} + obug@2.2.1: resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} engines: {node: '>=12.20.0'} + onnxruntime-common@1.21.0: + resolution: {integrity: sha512-Q632iLLrtCAVOTO65dh2+mNbQir/QNTVBG3h/QdZBpns7mZ0RYbLRBgGABPbpU9351AgYy7SJf1WaeVwMrBFPQ==} + + onnxruntime-common@1.22.0-dev.20250409-89f8206ba4: + resolution: {integrity: sha512-vDJMkfCfb0b1A836rgHj+ORuZf4B4+cc2bASQtpeoJLueuFc5DuYwjIZUBrSvx/fO5IrLjLz+oTrB3pcGlhovQ==} + + onnxruntime-node@1.21.0: + resolution: {integrity: sha512-NeaCX6WW2L8cRCSqy3bInlo5ojjQqu2fD3D+9W5qb5irwxhEyWKXeH2vZ8W9r6VxaMPUan+4/7NDwZMtouZxEw==} + os: [win32, darwin, linux] + + onnxruntime-web@1.22.0-dev.20250409-89f8206ba4: + resolution: {integrity: sha512-0uS76OPgH0hWCPrFKlL8kYVV7ckM7t/36HfbgoFw6Nd0CZVVbQC4PkrR8mBX8LtNUFZO25IQBqV2Hx2ho3FlbQ==} + optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -827,6 +1199,9 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} + parse-svg-path@0.2.0: + resolution: {integrity: sha512-Tf7FFIrguPKQwzD4pWnYkR2VOv3raoHeKED80Bm+BYHI3KxC8KsgsGC5+fSMzAGDA6UEk4bHvmi+RsjmL3khpg==} + path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -842,6 +1217,12 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pixi.js@8.22.0: + resolution: {integrity: sha512-QbTANHMZ751MIjLiLSUSM8a7LNMWwMIf0KbRCqlW+SPS9hNLfSVS+cl1O2SEp9g1K/wyLzj/OJHv+1TUfiPr/w==} + + platform@1.3.6: + resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} + postcss@8.5.28: resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} engines: {node: ^10 || ^12 || >=14} @@ -855,6 +1236,10 @@ packages: engines: {node: '>=14'} hasBin: true + protobufjs@7.6.6: + resolution: {integrity: sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==} + engines: {node: '>=12.0.0'} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -863,16 +1248,40 @@ packages: resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==} engines: {node: '>=20'} + react@19.3.0: + resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==} + engines: {node: '>=0.10.0'} + + roarr@2.15.4: + resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==} + engines: {node: '>=8.0'} + rolldown@1.2.12: resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + semver-compare@1.0.0: + resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==} + semver@7.8.5: resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} engines: {node: '>=10'} hasBin: true + serialize-error@7.0.1: + resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==} + engines: {node: '>=10'} + + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@types/node': '*' + peerDependenciesMeta: + '@types/node': + optional: true + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -885,6 +1294,9 @@ packages: resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} + sprintf-js@1.1.3: + resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} + std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} @@ -892,6 +1304,14 @@ packages: resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==} engines: {node: '>=0.6.19'} + tar@7.5.22: + resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} + engines: {node: '>=18'} + + tiny-lru@11.4.7: + resolution: {integrity: sha512-w/Te7uMUVeH0CR8vZIjr+XiN41V+30lkDdK+NRIDCUYKKuL9VcmaUEmaPISuwGhLlrTGh5yu18lENtR9axSxYw==} + engines: {node: '>=12'} + tinybench@6.2.0: resolution: {integrity: sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==} engines: {node: '>=20.0.0'} @@ -914,10 +1334,17 @@ packages: peerDependencies: typescript: '>=4.8.4' + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + type-check@0.4.0: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} + type-fest@0.13.1: + resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==} + engines: {node: '>=10'} + typescript-eslint@8.71.0: resolution: {integrity: sha512-fBdHYiqQ14RW6mOMXD14Svn82ZsCYAoQSzGRzyEjR59S5A2Krh/l7fGTOQ7iCr8gGy/mHVXtEF7s5fgjEdV0Pw==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -1034,6 +1461,10 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} + yallist@5.0.0: + resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} + engines: {node: '>=18'} + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} @@ -1043,6 +1474,9 @@ packages: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} + zod@4.6.5: + resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==} + snapshots: '@babel/helper-string-parser@7.29.7': {} @@ -1072,6 +1506,11 @@ snapshots: hashery: 1.5.1 keyv: 5.6.0 + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.8.1 + optional: true + '@eslint-community/eslint-utils@4.10.1(eslint@10.12.0)': dependencies: eslint: 10.12.0 @@ -1102,6 +1541,17 @@ snapshots: '@eslint/core': 1.2.1 levn: 0.4.1 + '@huggingface/jinja@0.5.10': {} + + '@huggingface/transformers@3.8.1(@types/node@24.19.1)': + dependencies: + '@huggingface/jinja': 0.5.10 + onnxruntime-node: 1.21.0 + onnxruntime-web: 1.22.0-dev.20250409-89f8206ba4 + sharp: 0.35.5(@types/node@24.19.1) + transitivePeerDependencies: + - '@types/node' + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -1118,6 +1568,116 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.3.4 + optional: true + + '@img/sharp-darwin-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.3.4 + optional: true + + '@img/sharp-freebsd-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-darwin-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + optional: true + + '@img/sharp-linux-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.4 + optional: true + + '@img/sharp-linux-arm@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.4 + optional: true + + '@img/sharp-linux-ppc64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.4 + optional: true + + '@img/sharp-linux-riscv64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.4 + optional: true + + '@img/sharp-linux-s390x@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.4 + optional: true + + '@img/sharp-linux-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + optional: true + + '@img/sharp-wasm32@0.35.5': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.5': + dependencies: + '@img/sharp-wasm32': 0.35.5 + optional: true + + '@img/sharp-win32-arm64@0.35.5': + optional: true + + '@img/sharp-win32-ia32@0.35.5': + optional: true + + '@img/sharp-win32-x64@0.35.5': + optional: true + + '@isaacs/fs-minipass@4.0.1': + dependencies: + minipass: 7.1.3 + '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} @@ -1135,8 +1695,32 @@ snapshots: '@keyv/serialize@1.1.1': {} + '@mediapipe/tasks-vision@1.0.1': {} + '@oxc-project/types@0.152.0': {} + '@pixi/colord@2.9.6': {} + + '@protobufjs/aspromise@1.1.2': {} + + '@protobufjs/base64@1.1.2': {} + + '@protobufjs/codegen@2.0.5': {} + + '@protobufjs/eventemitter@1.1.1': {} + + '@protobufjs/fetch@1.1.1': + dependencies: + '@protobufjs/aspromise': 1.1.2 + + '@protobufjs/float@1.0.2': {} + + '@protobufjs/path@1.1.2': {} + + '@protobufjs/pool@1.1.0': {} + + '@protobufjs/utf8@1.1.2': {} + '@rolldown/binding-android-arm-eabi@1.2.12': optional: true @@ -1191,6 +1775,8 @@ snapshots: '@types/deep-eql@4.0.2': {} + '@types/earcut@3.0.0': {} + '@types/esrecurse@4.3.1': {} '@types/estree@1.0.9': {} @@ -1201,6 +1787,10 @@ snapshots: dependencies: undici-types: 7.24.6 + '@types/react@19.3.0': + dependencies: + csstype: 3.2.3 + '@typescript-eslint/eslint-plugin@8.71.0(@typescript-eslint/parser@8.71.0(eslint@10.12.0)(typescript@6.0.3))(eslint@10.12.0)(typescript@6.0.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -1321,6 +1911,10 @@ snapshots: '@vitest/spy@5.0.3': {} + '@webgpu/types@0.1.74': {} + + '@xmldom/xmldom@0.8.15': {} + acorn-jsx@5.3.2(acorn@8.18.0): dependencies: acorn: 8.18.0 @@ -1344,6 +1938,8 @@ snapshots: balanced-match@4.0.4: {} + boolean@3.2.0: {} + brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -1358,22 +1954,48 @@ snapshots: chai@6.3.0: {} + chownr@3.0.0: {} + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 shebang-command: 2.0.0 which: 2.0.2 + csstype@3.2.3: {} + debug@4.4.3: dependencies: ms: 2.1.3 deep-is@0.1.4: {} + define-data-property@1.1.4: + dependencies: + es-define-property: 1.0.1 + es-errors: 1.3.0 + gopd: 1.2.0 + + define-properties@1.2.1: + dependencies: + define-data-property: 1.1.4 + has-property-descriptors: 1.0.2 + object-keys: 1.1.1 + detect-libc@2.1.2: {} + detect-node@2.1.0: {} + + earcut@3.2.4: {} + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + es-module-lexer@2.3.2: {} + es6-error@4.1.1: {} + escape-string-regexp@4.0.0: {} eslint-scope@9.1.2: @@ -1444,6 +2066,8 @@ snapshots: esutils@2.0.3: {} + eventemitter3@5.0.4: {} + expect-type@1.4.0: {} fast-deep-equal@3.1.3: {} @@ -1471,15 +2095,43 @@ snapshots: flatted: 3.4.4 hookified: 1.15.1 + flatbuffers@25.9.23: {} + flatted@3.4.4: {} fsevents@2.3.3: optional: true + gifuct-js@2.1.2: + dependencies: + js-binary-schema-parser: 2.0.3 + glob-parent@6.0.2: dependencies: is-glob: 4.0.3 + global-agent@3.0.0: + dependencies: + boolean: 3.2.0 + es6-error: 4.1.1 + matcher: 3.0.0 + roarr: 2.15.4 + semver: 7.8.5 + serialize-error: 7.0.1 + + globalthis@1.0.4: + dependencies: + define-properties: 1.2.1 + gopd: 1.2.0 + + gopd@1.2.0: {} + + guid-typescript@1.0.9: {} + + has-property-descriptors@1.0.2: + dependencies: + es-define-property: 1.0.1 + hashery@1.5.1: dependencies: hookified: 1.15.1 @@ -1490,6 +2142,8 @@ snapshots: husky@9.1.7: {} + idb-keyval@6.3.0: {} + ignore@5.3.2: {} ignore@7.0.12: {} @@ -1504,12 +2158,18 @@ snapshots: isexe@2.0.0: {} + ismobilejs@1.1.1: {} + + js-binary-schema-parser@2.0.3: {} + js-tokens@10.0.0: {} json-schema-traverse@0.4.1: {} json-stable-stringify-without-jsonify@1.0.1: {} + json-stringify-safe@5.0.1: {} + keyv@5.6.0: dependencies: '@keyv/serialize': 1.1.1 @@ -1580,6 +2240,8 @@ snapshots: dependencies: p-locate: 5.0.0 + long@5.3.2: {} + magic-string@1.4.2: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 @@ -1590,18 +2252,49 @@ snapshots: '@babel/types': 7.29.8 source-map-js: 1.2.2 + matcher@3.0.0: + dependencies: + escape-string-regexp: 4.0.0 + minimatch@10.2.6: dependencies: brace-expansion: 5.0.12 + minipass@7.1.3: {} + + minizlib@3.1.0: + dependencies: + minipass: 7.1.3 + ms@2.1.3: {} nanoid@3.3.19: {} natural-compare@1.4.0: {} + object-keys@1.1.1: {} + obug@2.2.1: {} + onnxruntime-common@1.21.0: {} + + onnxruntime-common@1.22.0-dev.20250409-89f8206ba4: {} + + onnxruntime-node@1.21.0: + dependencies: + global-agent: 3.0.0 + onnxruntime-common: 1.21.0 + tar: 7.5.22 + + onnxruntime-web@1.22.0-dev.20250409-89f8206ba4: + dependencies: + flatbuffers: 25.9.23 + guid-typescript: 1.0.9 + long: 5.3.2 + onnxruntime-common: 1.22.0-dev.20250409-89f8206ba4 + platform: 1.3.6 + protobufjs: 7.6.6 + optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -1619,6 +2312,8 @@ snapshots: dependencies: p-limit: 3.1.0 + parse-svg-path@0.2.0: {} + path-exists@4.0.0: {} path-key@3.1.1: {} @@ -1627,6 +2322,21 @@ snapshots: picomatch@4.0.7: {} + pixi.js@8.22.0: + dependencies: + '@pixi/colord': 2.9.6 + '@types/earcut': 3.0.0 + '@webgpu/types': 0.1.74 + '@xmldom/xmldom': 0.8.15 + earcut: 3.2.4 + eventemitter3: 5.0.4 + gifuct-js: 2.1.2 + ismobilejs: 1.1.1 + parse-svg-path: 0.2.0 + tiny-lru: 11.4.7 + + platform@1.3.6: {} + postcss@8.5.28: dependencies: nanoid: 3.3.19 @@ -1637,12 +2347,37 @@ snapshots: prettier@3.9.9: {} + protobufjs@7.6.6: + dependencies: + '@protobufjs/aspromise': 1.1.2 + '@protobufjs/base64': 1.1.2 + '@protobufjs/codegen': 2.0.5 + '@protobufjs/eventemitter': 1.1.1 + '@protobufjs/fetch': 1.1.1 + '@protobufjs/float': 1.0.2 + '@protobufjs/path': 1.1.2 + '@protobufjs/pool': 1.1.0 + '@protobufjs/utf8': 1.1.2 + '@types/node': 24.19.1 + long: 5.3.2 + punycode@2.3.1: {} qified@0.10.1: dependencies: hookified: 2.2.0 + react@19.3.0: {} + + roarr@2.15.4: + dependencies: + boolean: 3.2.0 + detect-node: 2.1.0 + globalthis: 1.0.4 + json-stringify-safe: 5.0.1 + semver-compare: 1.0.0 + sprintf-js: 1.1.3 + rolldown@1.2.12: dependencies: '@oxc-project/types': 0.152.0 @@ -1664,8 +2399,47 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.12 '@rolldown/binding-win32-x64-msvc': 1.2.12 + semver-compare@1.0.0: {} + semver@7.8.5: {} + serialize-error@7.0.1: + dependencies: + type-fest: 0.13.1 + + sharp@0.35.5(@types/node@24.19.1): + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.5 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.35.5 + '@img/sharp-darwin-x64': 0.35.5 + '@img/sharp-freebsd-wasm32': 0.35.5 + '@img/sharp-libvips-darwin-arm64': 1.3.4 + '@img/sharp-libvips-darwin-x64': 1.3.4 + '@img/sharp-libvips-linux-arm': 1.3.4 + '@img/sharp-libvips-linux-arm64': 1.3.4 + '@img/sharp-libvips-linux-ppc64': 1.3.4 + '@img/sharp-libvips-linux-riscv64': 1.3.4 + '@img/sharp-libvips-linux-s390x': 1.3.4 + '@img/sharp-libvips-linux-x64': 1.3.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 + '@img/sharp-linux-arm': 0.35.5 + '@img/sharp-linux-arm64': 0.35.5 + '@img/sharp-linux-ppc64': 0.35.5 + '@img/sharp-linux-riscv64': 0.35.5 + '@img/sharp-linux-s390x': 0.35.5 + '@img/sharp-linux-x64': 0.35.5 + '@img/sharp-linuxmusl-arm64': 0.35.5 + '@img/sharp-linuxmusl-x64': 0.35.5 + '@img/sharp-webcontainers-wasm32': 0.35.5 + '@img/sharp-win32-arm64': 0.35.5 + '@img/sharp-win32-ia32': 0.35.5 + '@img/sharp-win32-x64': 0.35.5 + '@types/node': 24.19.1 + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 @@ -1674,10 +2448,22 @@ snapshots: source-map-js@1.2.2: {} + sprintf-js@1.1.3: {} + std-env@4.3.0: {} string-argv@0.3.2: {} + tar@7.5.22: + dependencies: + '@isaacs/fs-minipass': 4.0.1 + chownr: 3.0.0 + minipass: 7.1.3 + minizlib: 3.1.0 + yallist: 5.0.0 + + tiny-lru@11.4.7: {} + tinybench@6.2.0: {} tinyexec@1.3.1: {} @@ -1693,10 +2479,15 @@ snapshots: dependencies: typescript: 6.0.3 + tslib@2.8.1: + optional: true + type-check@0.4.0: dependencies: prelude-ls: 1.2.1 + type-fest@0.13.1: {} + typescript-eslint@8.71.0(eslint@10.12.0)(typescript@6.0.3): dependencies: '@typescript-eslint/eslint-plugin': 8.71.0(@typescript-eslint/parser@8.71.0(eslint@10.12.0)(typescript@6.0.3))(eslint@10.12.0)(typescript@6.0.3) @@ -1758,7 +2549,11 @@ snapshots: word-wrap@1.2.5: {} + yallist@5.0.0: {} + yaml@2.9.1: optional: true yocto-queue@0.1.0: {} + + zod@4.6.5: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index b541d60..9da969e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -5,7 +5,18 @@ packages: # 公開から 1 日経っていない版は入れない (pnpm 12 の既定の minimumReleaseAge。lumorphia/prismtone の ADR-0033 と同じ)。 # ここで緩めない。手元で確かめるだけなら pnpm_config_minimum_release_age=0 を付ける +# 依存の版の固定。脆弱性やバンドルの都合で、間接依存の版を上書きする (lumorphia/prismtone と同じ) +overrides: + "@huggingface/transformers>sharp": ^0.35.5 + # 依存のビルドスクリプト (install / postinstall) を走らせるかを 1 つずつ決める。載っていないものは install が失敗する allowBuilds: # ネイティブのバイナリを置く。vite / vitest で使う esbuild: true + # transformers.js (切り抜き) の Node 向けの依存。ブラウザでは使わない + # CUDA のバイナリ (330 MB) を取りに行くだけ。CPU 用はパッケージに入っているので要らない + onnxruntime-node: false + # 同梱の CLI の版を確かめるだけ + protobufjs: false + # 画像のネイティブのバイナリ。transformers.js の Node 向けで、現像 (ブラウザ) では使わない + sharp: false diff --git a/vitest.config.ts b/vitest.config.ts index 3fd0821..39a9df3 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -15,8 +15,23 @@ export default defineConfig({ include: ["packages/*/src/**"], exclude: [ "**/*.test.ts", - // ブラウザ専用 (React、PixiJS、GLSL、Worker、IndexedDB)。Playwright の E2E で検証する + // パッケージの入口 (export を並べるだけ) + "packages/*/src/index.ts", + // ブラウザ専用 (React、PixiJS、GLSL、Worker、ポインタ操作)。Playwright の E2E で検証する。 + // GPU の出力は E2E が CPU の参照 (adjust-math.ts) と照合する "packages/*/src/**/*.tsx", + "packages/editor-engine/src/render/editor-renderer.ts", + "packages/editor-engine/src/render/adjust-filter.ts", + "packages/editor-engine/src/render/adjust-glsl.ts", + "packages/editor-engine/src/render/local-adjust-filter.ts", + "packages/editor-engine/src/render/develop-stage.ts", + "packages/editor-engine/src/render/mask-texture.ts", + "packages/editor-engine/src/load-image.ts", + "packages/editor-engine/src/inference/face.ts", + "packages/editor-engine/src/inference/face.worker.ts", + "packages/editor-engine/src/inference/segment.ts", + "packages/editor-engine/src/inference/segment.worker.ts", + "packages/editor-react/src/use-canvas-gestures.ts", ], thresholds: { lines: 80, functions: 80, branches: 70, statements: 80 }, },