Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add drawn angry and sad mouths, keep half-lidded eyes for angry

shinshin86b9b59256d579
diff --git a/.changeset/expression-drawn-eyes.md b/.changeset/expression-drawn-eyes.md
index 05a0426..53ada43 100644
--- a/.changeset/expression-drawn-eyes.md
+++ b/.changeset/expression-drawn-eyes.md
@@ -2,4 +2,4 @@
"mesh-avatar": minor
---
-Switch to drawn expression eyes (`eyes_angry`, `eyes_sad`, `eyes_surprise` sprites) while the angry, sad or surprised expression or emotion tag is active. Blinking still closes them, and avatars without these sprites look the same as before.
+Switch to drawn expression eyes (`eyes_sad`, `eyes_surprise` sprites) and closed mouths (`mouth_angry`, `mouth_sad`) while the matching expression or emotion tag is active. Blinking still closes the eyes, speaking still shows the open mouth drawings, and avatars without these sprites look the same as before.
diff --git a/README.ja.md b/README.ja.md
index a8911a5..795707b 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -68,7 +68,7 @@ npm run dev
描き分け画像がない間は、目と口をメッシュの変形だけで動かしています。閉じた目や母音ごとの口の絵を用意すると、まばたきと口の動きがかなり自然になります。「描き分け画像」の欄で「目」「口」の片方または両方にチェックを入れ、表示された文章をコピーして、このリポジトリのフォルダで開いた Codex に貼り付けてください。Codex が組み込みの画像生成で絵を作って取り込み、エディタが自動で読み込み直します。Claude Code は画像を生成できないため、Claude Code 向けの文章では、マスクと依頼文を用意して画像生成に渡すファイルを案内するところまでを頼みます。
-「表情の目」は任意です。怒った目・悲しい目・驚いた目を描き分けると、その表情や感情タグのときに描いた目へ切り替わります。まばたきはそのまま動きます。描いていないアバターの見た目は今までと変わりません。
+「表情の目と口」は任意です。悲しい目・驚いた目と、怒った口・悲しい口(閉じた口)を描き分けると、その表情や感情タグのときに描いた絵へ切り替わります。まばたきや話すときの口はそのまま動きます。描いていないアバターの見た目は今までと変わりません。
![口の描き分けの依頼](docs/images/ja/05-variants.png)
diff --git a/README.md b/README.md
index 275e03e..28cd297 100644
--- a/README.md
+++ b/README.md
@@ -94,9 +94,9 @@ repository folder. Codex draws them with its built-in image generation and impor
editor reloads them automatically. (Claude Code cannot generate images; its message prepares
the masks and prompts for you to hand to an image generator.)
-**Expression eyes** is optional: it adds drawn angry, sad and surprised eyes. The avatar
-switches to them for those expressions and emotion tags and still blinks; avatars without
-them look the same as before.
+**Expressions** is optional: it adds drawn sad and surprised eyes and closed angry and sad
+mouths. The avatar switches to them for those expressions and emotion tags and still blinks
+and speaks; avatars without them look the same as before.
![Requesting drawn mouths](docs/images/en/05-variants.png)
diff --git a/docs/agent-guide.md b/docs/agent-guide.md
index c4fa477..19eccc6 100644
--- a/docs/agent-guide.md
+++ b/docs/agent-guide.md
@@ -162,13 +162,14 @@ uv run tools/variant-requests.py projects/<name>
```
This writes `projects/<name>/variant-requests/` with, for each variant (closed / half /
-smiling eyes; mouths あ, half あ, い, お; angry / sad / surprised expression eyes): an edit
-mask, the prompt, and a README.
+smiling eyes; mouths あ, half あ, い, お; sad / surprised expression eyes; angry / sad closed
+mouths): an edit mask, the prompt, and a README.
-The expression eyes (`eyes_angry`, `eyes_sad`, `eyes_surprise`) are optional; create them
-only when the person asks for them. They use the eye mask, which leaves the eyebrows out: the
-rig already moves the brows for each expression, and a drawn brow would show twice. The
-half-lidded expression uses `eyes_half`, so it needs no separate drawing.
+The expression eyes (`eyes_sad`, `eyes_surprise`) and closed mouths (`mouth_angry`,
+`mouth_sad`) are optional; create them only when the person asks for them. The eyes use the
+eye mask, which leaves the eyebrows out: the rig already moves the brows for each expression,
+and a drawn brow would show twice. The mouths use the mouth mask and stay closed. The angry
+and half-lidded expressions use `eyes_half`, so they need no separate eye drawing.
Ask the person before generating: image generation sends `source.png` and a mask to the
generator. If they decline, stop here; the avatar still works without variants.
@@ -182,7 +183,9 @@ generator. If they decline, stop here; the avatar still works without variants.
In each mask, transparent pixels may change and opaque pixels must stay identical. Many
generators recompress the whole image, fill in the transparent background or shift it by a
pixel. `build-sprites` then imports the masked area only: it corrects a shift of up to 3 px,
-resizes a result with the source's aspect ratio, and logs `importing the mask area only`. It
+resizes a result with the source's aspect ratio, removes a uniform colour tint measured just
+inside the mask edge (on flat skin it would show as a patch), and logs `importing the mask
+area only`. It
still rejects, with the reason, a result whose whole image is shifted further, whose picture
outside the mask was redrawn, whose drawing spills over the mask edge, or whose aspect ratio
differs. Generate a rejected variant again, asking for identical size and untouched pixels
@@ -193,7 +196,7 @@ Then:
uv run tools/build-sprites.py projects/<name>
```
It cuts accepted variants into `built/sprites/`. Render the poses again (Step 5); the
-`angry`, `sad` and `surprise` frames show the expression eyes.
+`angry`, `sad` and `surprise` frames show the expression eyes and mouths.
## Step 7 — Hand over
diff --git a/docs/format.md b/docs/format.md
index 9be2b42..6b3d9a4 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -123,21 +123,24 @@ individually; readers must not require a complete set.
| `eyes_closed_0`, `eyes_closed_1` | Closed eyes with relaxed lids. |
| `eyes_half_0`, `eyes_half_1` | Half-open eyes. |
| `eyes_smile_0`, `eyes_smile_1` | Closed eyes in a smile. |
-| `eyes_angry_0`, `eyes_angry_1` | Open eyes for the angry expression. |
| `eyes_sad_0`, `eyes_sad_1` | Open eyes for the sad expression. |
| `eyes_surprise_0`, `eyes_surprise_1` | Wide-open eyes for the surprised expression. |
| `mouth_a` | Open mouth for “a”. |
| `mouth_a_half` | Partly open “a”; also reused for “e”. |
| `mouth_i` | Wide mouth for “i”. |
| `mouth_o` | Rounded mouth for “o”; also reused, with reduced width, for “u”. |
+| `mouth_angry` | Closed mouth for the angry expression (corners turned down). |
+| `mouth_sad` | Closed mouth for the sad expression (corners drooping). |
The eye suffix is the index in `rig.eyes`, not a separate left/right convention.
The expression eyes replace the open and half-open eye while the live expression
-(`setExpression`: `angry`, `sad`, `surprise`) or the emotion tag (`setEmotion`: `angry`,
-`sad`, `surprised`) is active; a blink still switches to `eyes_closed`. They cover the
-same area as the other eye drawings and do not include the eyebrows, which the rig moves.
-Without them, those expressions use the other drawings as before.
-The original base drawing provides the closed mouth.
+(`setExpression`: `sad`, `surprise`) or the emotion tag (`setEmotion`: `sad`, `surprised`)
+is active; a blink still switches to `eyes_closed`. They cover the same area as the other
+eye drawings and do not include the eyebrows, which the rig moves. The angry expression
+keeps `eyes_half`. The expression mouths replace the closed mouth while the angry or sad
+expression or emotion tag is active; while speaking, the open mouth drawings are shown over
+them. Without these drawings, those expressions look as before.
+Otherwise the original base drawing provides the closed mouth.
## Archive rules and compatibility
diff --git a/e2e/workflow.spec.ts b/e2e/workflow.spec.ts
index 243c697..f44bc1a 100644
--- a/e2e/workflow.spec.ts
+++ b/e2e/workflow.spec.ts
@@ -133,9 +133,9 @@ test('eye and mouth checkboxes immediately adapt the prompt and lip fallback ope
const prompt = panel.getByRole('textbox', { name: 'Copy message', exact: true });
await panel.getByRole('checkbox', { name: 'Eyes', exact: true }).check(); await expect(prompt).toContainText('eye drawn variants');
await panel.getByRole('checkbox', { name: 'Mouth', exact: true }).check(); await expect(prompt).toContainText('eye and mouth drawn variants');
- await panel.getByRole('checkbox', { name: 'Expression eyes', exact: true }).check();
- await expect(prompt).toContainText('eye, expression eye (angry, sad, surprised) and mouth drawn variants');
- await panel.getByRole('checkbox', { name: 'Expression eyes', exact: true }).uncheck();
+ await panel.getByRole('checkbox', { name: 'Expressions', exact: true }).check();
+ await expect(prompt).toContainText('eye, expression (sad and surprised eyes, angry and sad closed mouths) and mouth drawn variants');
+ await panel.getByRole('checkbox', { name: 'Expressions', exact: true }).uncheck();
await panel.getByRole('checkbox', { name: 'Eyes', exact: true }).uncheck(); await expect(prompt).toContainText('mouth drawn variants');
await panel.getByRole('checkbox', { name: 'Mouth', exact: true }).uncheck(); await expect(prompt).toHaveCount(0);
await panel.locator(':scope > summary').click();
diff --git a/packages/runtime/src/engine/sprites.js b/packages/runtime/src/engine/sprites.js
index 4feb4f6..fa781d5 100644
--- a/packages/runtime/src/engine/sprites.js
+++ b/packages/runtime/src/engine/sprites.js
@@ -27,6 +27,9 @@ export function createSpriteModule(engine, rig) {
// below this the drawn closed mouth of the original image is shown (a barely open mouth
// drawing looked like a stuck, oddly shaped mouth)
const MOUTH_OPEN_MIN = 0.16;
+ // Closed mouths drawn for an expression (mouth_angry / mouth_sad) replace the closed mouth of
+ // the original image while it lasts; speaking still switches to the open mouth drawings.
+ const MOUTH_MOODS = ['angry', 'sad'];
// Vowel regions on the form axis, with a little hysteresis so the drawing does not flicker
// when the form hovers on a boundary.
@@ -44,8 +47,10 @@ export function createSpriteModule(engine, rig) {
// and the drawn closed / smiling eye.
const EYE_OPEN_MIN = 0.75, EYE_CLOSED_MAX = 0.3, EYE_FADE_SEC = 0.06;
- // Open eyes drawn for an expression (eyes_angry / eyes_sad / eyes_surprise) replace the open
- // and half-open eye while it lasts; a blink still switches to the closed drawing.
+ // Open eyes drawn for an expression (eyes_sad / eyes_surprise) replace the open and half-open
+ // eye while it lasts; a blink still switches to the closed drawing. The angry face keeps the
+ // half-closed eye (a drawn glare read as a different character) and only swaps the mouth.
+ const EYE_MOODS_DRAWN = ['sad', 'surprise'];
function eyeSprite(open, smile, mood = null) {
if (mood && open >= EYE_CLOSED_MAX) return mood;
if (open >= EYE_OPEN_MIN) return null;
@@ -81,9 +86,11 @@ export function createSpriteModule(engine, rig) {
*/
function createSprites(R, sheet, imgs, buildGrid, alphaOf) {
const items = {};
- // draw order matters for the cross-fades: half-closed and expression eyes under closed / smiling (the fade-in frame is drawn on top)
+ // draw order matters for the cross-fades: half-closed and expression eyes under closed / smiling,
+ // expression closed mouths under open ones (the fade-in frame is drawn on top)
const shut = n => n.startsWith('eyes_closed') || n.startsWith('eyes_smile');
- const order = n => (shut(n) ? 1 : n.startsWith('eyes_') ? 0 : 2);
+ const moodMouth = n => MOUTH_MOODS.some(m => n === `mouth_${m}`);
+ const order = n => (shut(n) ? 1 : n.startsWith('eyes_') ? 0 : moodMouth(n) ? 2 : 3);
const entries = Object.entries(sheet.layers).sort((x, y) => order(x[0]) - order(y[0]));
for (const [name, rect] of entries) {
const mesh = buildGrid(rect, rig.mesh.spriteCell, alphaOf(imgs[name]), imgs[name].width);
@@ -121,7 +128,8 @@ export function createSpriteModule(engine, rig) {
/**
* Show / hide and deform the sprites for this frame.
* Returns which eyes are covered by a sprite, so the layered eye parts can be hidden.
- * `mood` (angry / sad / surprise) picks drawn expression eyes when the avatar has them.
+ * `mood` (angry / sad / surprise) picks drawn expression eyes (sad, surprise) and closed
+ * mouths (angry, sad) when the avatar has them.
*/
update(P, phys, dt = 1 / 60, mood = null) {
for (const it of Object.values(items)) it.layer.visible = false;
@@ -134,7 +142,7 @@ export function createSpriteModule(engine, rig) {
// EYE_FADE_SEC (a time-based cross-fade, so no double image is ever held)
eyes.forEach(([open, smile], i) => {
const st = eyeState[i];
- const drawn = mood && items[`eyes_${mood}_${i}`] ? `eyes_${mood}` : null;
+ const drawn = EYE_MOODS_DRAWN.includes(mood) && items[`eyes_${mood}_${i}`] ? `eyes_${mood}` : null;
const want = eyeSprite(open, smile, drawn) ?? 'open';
if (want !== st.cur) { st.prev = st.cur; st.cur = want; st.t = 0; }
// A redraw without elapsed time (a paused preview moving a slider) shows the target
@@ -163,6 +171,13 @@ export function createSpriteModule(engine, rig) {
lastShape = shape;
const def = shape && MOUTH_SHAPES[shape];
const mt = def && items[def.sprite];
+ // the expression's closed mouth stays solid under an open mouth drawing until it has faded in
+ const closed = MOUTH_MOODS.includes(mood) && items[`mouth_${mood}`];
+ if (closed && (!mt || P.mouthOpen < MOUTH_OPEN_MIN + 0.04)) {
+ closed.layer.visible = true;
+ closed.layer.alpha = 1;
+ place(closed, P, phys, 1);
+ }
if (mt) {
mt.layer.visible = true;
// fade in right above the threshold so the closed line hands over softly
@@ -178,10 +193,11 @@ export function createSpriteModule(engine, rig) {
return { createSprites, mouthShape, eyeSprite };
}
-// Expressions (live overlay names and motion expression keys) that have drawn open eyes.
+// Expressions (live overlay names and motion expression keys) that have drawn variants: open
+// eyes for sad and surprise, a closed mouth for angry and sad.
const EYE_MOODS = { angry: 'angry', angryTalk: 'angry', sad: 'sad', sadTalk: 'sad', surprise: 'surprise', surprisedTalk: 'surprise' };
-/** The drawn-eye mood for the live expression, else for the motion expression (if it is applied). */
+/** The drawn-eye / mouth mood for the live expression, else for the motion expression (if it is applied). */
export function eyeMood(overlay, expression) {
if (overlay && overlay !== 'neutral') return EYE_MOODS[overlay] ?? null;
return (expression && EYE_MOODS[expression]) ?? null;
diff --git a/src/editor/VariantsPanel.tsx b/src/editor/VariantsPanel.tsx
index c9cc1eb..deafab9 100644
--- a/src/editor/VariantsPanel.tsx
+++ b/src/editor/VariantsPanel.tsx
@@ -1,12 +1,15 @@
import { useEffect, useRef, useState } from 'react';
import { useI18n } from './i18n';
-import { variantGroups, variantNames, projectVariantRequests, openSampleAvatar, ProjectJobError, type LocalProject, type ProjectJob, type VariantGroup, type JobResult, type VariantRequest } from './project';
+import { variantGroups, variantNames, projectVariantRequests, openSampleAvatar, ProjectJobError, type LocalProject, type ProjectJob, type VariantGroup, type VariantName, type JobResult, type VariantRequest } from './project';
import { AskAgent } from './AskAgent';
import { JobFeedback } from './JobFeedback';
import { CopyButton } from './CopyButton';
import { Icon } from './Icon';
-const labels = ['eyesClosed', 'eyesHalf', 'eyesSmile', 'eyesAngry', 'eyesSad', 'eyesSurprise', 'mouthA', 'mouthAHalf', 'mouthI', 'mouthO'] as const;
+const labels = {
+ eyes_closed: 'eyesClosed', eyes_half: 'eyesHalf', eyes_smile: 'eyesSmile', eyes_sad: 'eyesSad', eyes_surprise: 'eyesSurprise',
+ mouth_a: 'mouthA', mouth_a_half: 'mouthAHalf', mouth_i: 'mouthI', mouth_o: 'mouthO', mouth_angry: 'mouthAngry', mouth_sad: 'mouthSad',
+} as const satisfies Record<VariantName, string>;
const groupOf = (name: string) => (Object.keys(variantGroups) as VariantGroup[]).find(group => (variantGroups[group] as readonly string[]).includes(name));
export function VariantsPanel({ project, projectPath, assets, rootPath, busy, stale, onRun, mouthRequest, onMouthPresence }: {
project: LocalProject | null; projectPath?: string; assets?: Record<string, string>; rootPath?: string; busy: boolean; stale: boolean;
@@ -39,7 +42,7 @@ export function VariantsPanel({ project, projectPath, assets, rootPath, busy, st
}).then(data => {
if (revision !== current.current) return;
const ready = data?.layers ? variantNames.filter(name => name.startsWith('eyes_') ? `${name}_0` in data.layers && `${name}_1` in data.layers : name in data.layers) : [];
- setPresent(ready); onMouthPresence(ready.some(name => name.startsWith('mouth_')));
+ setPresent(ready); onMouthPresence(ready.some(name => (variantGroups.mouth as readonly string[]).includes(name)));
}).catch(() => { if (revision === current.current) onMouthPresence(false); });
if (project) void projectVariantRequests(project).then(value => { if (revision === current.current) setRequests(value); });
}, [project?.name, assets, onMouthPresence]);
@@ -70,8 +73,8 @@ export function VariantsPanel({ project, projectPath, assets, rootPath, busy, st
{writable ? <button disabled={busy || stale} onClick={() => { void run('variant-requests'); }}>{busy ? t.operationBusy : t.createRequests}</button> : <p className="workflow-note">{t.variantsUnavailable}</p>}
{stale && <p className="workflow-note">{t.variantsNeedRebuild}</p>}
{requests.length > 0 && <div className="variant-requests">{requests.filter(request => !target.length || target.includes(groupOf(request.name)!)).map(request => <details key={request.name}>
- <summary>{t[labels[variantNames.indexOf(request.name)]]} · <code>{request.name}.png</code></summary>
- <img src={request.maskUrl} alt={`${t.requestFiles}: ${t[labels[variantNames.indexOf(request.name)]]}`} />
+ <summary>{t[labels[request.name]]} · <code>{request.name}.png</code></summary>
+ <img src={request.maskUrl} alt={`${t.requestFiles}: ${t[labels[request.name]]}`} />
<p><code>{project?.relativePath}/source.png</code><br /><code>{project?.relativePath}/variant-requests/{request.name}/mask.png</code></p>
<div className="workflow-buttons"><CopyButton value={request.prompt} label={t.copyVariantPrompt} /><CopyButton value={`${project?.relativePath}/source.png\n${project?.relativePath}/variant-requests/${request.name}/mask.png\n${project?.relativePath}/variant-requests/${request.name}/prompt.md`} label={t.copyFilePaths} /></div>
<pre>{request.prompt}</pre><p>{t.variantOutput}: <code>{project?.relativePath}/variants/{request.name}.png</code></p>
diff --git a/src/editor/i18n-zh.ts b/src/editor/i18n-zh.ts
index 2e57acd..a50c53a 100644
--- a/src/editor/i18n-zh.ts
+++ b/src/editor/i18n-zh.ts
@@ -47,7 +47,7 @@ export const uiZh = {
export const workflowZh: typeof workflowEn = {
agentInstruction: '在本项目文件夹中打开 AGENT,然后粘贴下面的请求。',
variantsReloaded: '已加载表情差分。', mouthFallback: '尚无嘴型差分图片,正在使用网格变形。', drawMouth: '→ 制作嘴型差分',
- eyesKinds: '闭眼、半闭眼、笑眼', expressionKinds: '生气、悲伤、惊讶(可选)', mouthKinds: 'あ(a)、半张嘴あ(a)、い(i)、お(o)', variantCount: 'COUNT / TOTAL 张',
+ eyesKinds: '闭眼、半闭眼、笑眼', expressionKinds: '悲伤、惊讶的眼睛,生气、悲伤的嘴(可选)', mouthKinds: 'あ(a)、半张嘴あ(a)、い(i)、お(o)', variantCount: 'COUNT / TOTAL 张',
askAgent: '请编程助手制作',
copyPrompt: '复制请求', copyDone: '已复制', rootUnavailable: '请在包含本应用和 docs/agent-guide.md 的文件夹中打开编程助手。启动本地开发服务后,可在此复制完整路径。',
newIllustration: '从新插画创建角色',
@@ -57,7 +57,7 @@ export const workflowZh: typeof workflowEn = {
agentClaudePrompt: '请按照 docs/agent-guide.md 的步骤 6,为 PROJECT 的 TARGET差分准备制作请求。运行 variant-requests 生成蒙版和提示词。Claude Code 不能生成图片:请明确告诉我,需要将哪些 source.png、蒙版和提示词交给 Codex 或其他生图工具,以及应以哪些完整尺寸的 PNG 文件名保存到 variants/,然后停止。暂时不要生成或发送图片,也不要运行 build-sprites。所有文件都保存在本仓库内。',
agentCopySample: '请先将只读项目 SOURCE 复制到 PROJECT;如果目标已存在,请使用一个未占用的新名称。保留原项目。',
agentUnknownPath: '浏览器无法读取该文件夹的完整路径。请从本地开发服务的项目列表中打开它,以生成包含准确路径的请求。',
- agentEyes: '眼睛', agentExpression: '表情眼睛(生气、悲伤、惊讶)', agentMouth: '嘴型',
+ agentEyes: '眼睛', agentExpression: '表情(悲伤、惊讶的眼睛,以及生气、悲伤的闭嘴)', agentMouth: '嘴型',
rebuild: '保存并重建图层', rebuilding: '正在保存并重建图层…', staleLocal: '轮廓已修改,重建图层后即可更新预览。',
staleSample: '示例项目是只读的。请复制为自己的项目后继续编辑。', copyContinue: '复制并继续编辑',
staleListed: '此项目已在本地项目列表中。', reopenListed: '从列表中重新打开',
@@ -76,12 +76,12 @@ export const workflowZh: typeof workflowEn = {
jobFailed: '本地工具未能完成操作,之前的图层已保留。', dependenciesHelp: '请安装 uv 和 Python 3.10 或更高版本后重试。安装说明见 docs/agent-guide.md。',
unsafeFilesHelp: '项目中包含指向其他位置的文件。请改用此项目内的普通文件后重试。', showLog: '查看日志', operationBusy: '正在本地处理…', reloadFailed: '无法重新加载项目,当前视图仍保留。',
variantsTitle: '表情差分', variantMissing: '暂无', variantsHelp: '为闭眼、说话以及生气、悲伤、惊讶的表情绘制不同的图片,可让动作更自然。',
- eyesClosed: '闭眼', eyesHalf: '半闭眼', eyesSmile: '笑眼', eyesAngry: '生气的眼睛', eyesSad: '悲伤的眼睛', eyesSurprise: '惊讶的眼睛', mouthA: '嘴型「あ」', mouthAHalf: '半张嘴「あ」', mouthI: '嘴型「い」', mouthO: '嘴型「お」',
- targetEyes: '眼睛', targetExpression: '表情眼睛', targetMouth: '嘴型',
+ eyesClosed: '闭眼', eyesHalf: '半闭眼', eyesSmile: '笑眼', eyesSad: '悲伤的眼睛', eyesSurprise: '惊讶的眼睛', mouthA: '嘴型「あ」', mouthAHalf: '半张嘴「あ」', mouthI: '嘴型「い」', mouthO: '嘴型「お」', mouthAngry: '生气的嘴', mouthSad: '悲伤的嘴',
+ targetEyes: '眼睛', targetExpression: '表情的眼睛和嘴', targetMouth: '嘴型',
createRequests: '导出蒙版和提示词', requestsReady: '已在本地生成蒙版和提示词。', requestFiles: '蒙版和提示词', copyVariantPrompt: '复制生图提示词', copyFilePaths: '复制文件路径',
manualVariants: '自己准备差分图片', manualHelp: '将 source.png、蒙版和提示词交给图片编辑工具。按下方文件名保存与原图尺寸相同的 PNG,再拖入此处。仅可修改蒙版的透明区域,不透明区域必须与原图完全一致。',
variantOutput: '将返回的图片保存为', dropVariants: '将生成的 PNG 图片拖入此处', chooseVariants: '选择差分图片', variantFiles: '生成的差分图片',
- variantFilenameHelp: '使用 eyes_closed.png、eyes_half.png、eyes_smile.png、eyes_angry.png、eyes_sad.png、eyes_surprise.png、mouth_a.png、mouth_a_half.png、mouth_i.png 或 mouth_o.png。图片会保存在本地。',
+ variantFilenameHelp: '使用 eyes_closed.png、eyes_half.png、eyes_smile.png、eyes_sad.png、eyes_surprise.png、mouth_a.png、mouth_a_half.png、mouth_i.png、mouth_o.png、mouth_angry.png 或 mouth_sad.png。图片会保存在本地。',
importAccepted: '导入成功,预览已更新。', importMaskOnly: '蒙版外的像素与原图不同(重新压缩或轻微偏移),因此只导入了蒙版内的区域。', importRejected: '导入未通过,之前的差分和图层已保留。', importOutside: '编辑蒙版以外的像素被修改了。', importSize: '请使用与 source.png 尺寸相同的 PNG 图片。', importMask: '该差分的编辑蒙版不符合要求。',
importInvalid: '请使用列出的 PNG 文件名,每个名称最多一张;单张不超过 24 MB,总计不超过 26 MB。', metricsTitle: '蒙版外像素对比', outsideMax: '最大差异', outsideMean: '平均差异', outsidePixels: '超出容差的像素数',
variantsUnavailable: '若要在此制作请求或导入图片,请从本地开发服务的列表中打开一个可编辑项目。其他文件夹可让编程助手按照 docs/agent-guide.md 的步骤 6 处理。',
diff --git a/src/editor/project.ts b/src/editor/project.ts
index d147a72..6bcf33e 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -103,7 +103,7 @@ export async function revealRepository() {
}
export const variantGroups = {
eyes: ['eyes_closed', 'eyes_half', 'eyes_smile'],
- expression: ['eyes_angry', 'eyes_sad', 'eyes_surprise'],
+ expression: ['eyes_sad', 'eyes_surprise', 'mouth_angry', 'mouth_sad'],
mouth: ['mouth_a', 'mouth_a_half', 'mouth_i', 'mouth_o'],
} as const;
export type VariantGroup = keyof typeof variantGroups;
diff --git a/src/editor/workflow-i18n.ts b/src/editor/workflow-i18n.ts
index c3ccc18..6041ad6 100644
--- a/src/editor/workflow-i18n.ts
+++ b/src/editor/workflow-i18n.ts
@@ -1,7 +1,7 @@
export const workflowEn = {
agentInstruction: 'Open AGENT in this repository folder and paste the following message.',
variantsReloaded: 'Drawn variants loaded.', mouthFallback: 'No drawn mouth images; using mesh deformation.', drawMouth: '→ Draw mouth variants',
- eyesKinds: 'Closed, half-closed, smiling', expressionKinds: 'Angry, sad, surprised (optional)', mouthKinds: 'あ, half-open あ, い, お', variantCount: 'COUNT of TOTAL images',
+ eyesKinds: 'Closed, half-closed, smiling', expressionKinds: 'Sad, surprised eyes; angry, sad mouths (optional)', mouthKinds: 'あ, half-open あ, い, お', variantCount: 'COUNT of TOTAL images',
askAgent: 'Ask your agent',
copyPrompt: 'Copy message', copyDone: 'Copied', rootUnavailable: 'Open the folder containing this app and docs/agent-guide.md. Start the development server to copy its full path here.',
newIllustration: 'Create from a new illustration',
@@ -11,7 +11,7 @@ export const workflowEn = {
agentClaudePrompt: 'Prepare TARGET drawn variant requests for PROJECT following docs/agent-guide.md Step 6. Run variant-requests to prepare the masks and prompts. Claude Code cannot generate images: tell me exactly which source.png, masks and prompts to give to Codex or another image generator and which full-size PNG filenames to save in variants/, then stop. Do not generate or send images, or run build-sprites yet. Keep all files inside this repository.',
agentCopySample: 'First copy the read-only project at SOURCE into PROJECT; if the destination exists, use an unused name. Keep the original project unchanged. ',
agentUnknownPath: 'The browser cannot read this folder’s full path. Open it from the development server’s project list to prepare an exact request.',
- agentEyes: 'eye', agentExpression: 'expression eye (angry, sad, surprised)', agentMouth: 'mouth',
+ agentEyes: 'eye', agentExpression: 'expression (sad and surprised eyes, angry and sad closed mouths)', agentMouth: 'mouth',
rebuild: 'Save and rebuild layers', rebuilding: 'Saving and rebuilding layers…', staleLocal: 'Outlines changed. Rebuild layers to update the preview.',
staleSample: 'The sample is read-only. To continue editing, copy it into a project.', copyContinue: 'Copy and continue editing',
staleListed: 'This project is available in the project list.', reopenListed: 'Reopen from the list',
@@ -30,12 +30,12 @@ export const workflowEn = {
jobFailed: 'The local tool could not finish. Previous layers were kept.', dependenciesHelp: 'Install uv and Python 3.10 or later, then try again. With Homebrew: brew install uv python. Setup: docs/agent-guide.md.',
unsafeFilesHelp: 'The project contains redirected files. Use regular files inside this project and try again.', showLog: 'Show log', operationBusy: 'Working locally…', reloadFailed: 'Could not reload the project. The current view is still open.',
variantsTitle: 'Drawn variants', variantMissing: 'Missing', variantsHelp: 'Drawn expressions make closed eyes, speaking and angry, sad or surprised faces look more natural.',
- eyesClosed: 'Closed eyes', eyesHalf: 'Half-closed eyes', eyesSmile: 'Smiling eyes', eyesAngry: 'Angry eyes', eyesSad: 'Sad eyes', eyesSurprise: 'Surprised eyes', mouthA: 'Mouth あ', mouthAHalf: 'Half-open あ', mouthI: 'Mouth い', mouthO: 'Mouth お',
- targetEyes: 'Eyes', targetExpression: 'Expression eyes', targetMouth: 'Mouth',
+ eyesClosed: 'Closed eyes', eyesHalf: 'Half-closed eyes', eyesSmile: 'Smiling eyes', eyesSad: 'Sad eyes', eyesSurprise: 'Surprised eyes', mouthA: 'Mouth あ', mouthAHalf: 'Half-open あ', mouthI: 'Mouth い', mouthO: 'Mouth お', mouthAngry: 'Angry mouth', mouthSad: 'Sad mouth',
+ targetEyes: 'Eyes', targetExpression: 'Expressions', targetMouth: 'Mouth',
createRequests: 'Export masks and prompts', requestsReady: 'Local masks and prompts are ready.', requestFiles: 'Masks and prompts', copyVariantPrompt: 'Copy image prompt', copyFilePaths: 'Copy file paths',
manualVariants: 'If you prepare images yourself', manualHelp: 'Give your image editor source.png, the mask and its prompt. Save a full-size PNG with the filename below, then drop it here. Transparent mask pixels may change; opaque pixels must stay identical.',
variantOutput: 'Save the returned drawing as', dropVariants: 'Drop returned PNG images here', chooseVariants: 'Choose returned images', variantFiles: 'Returned variant images',
- variantFilenameHelp: 'Use eyes_closed.png, eyes_half.png, eyes_smile.png, eyes_angry.png, eyes_sad.png, eyes_surprise.png, mouth_a.png, mouth_a_half.png, mouth_i.png or mouth_o.png. The app keeps the images local.',
+ variantFilenameHelp: 'Use eyes_closed.png, eyes_half.png, eyes_smile.png, eyes_sad.png, eyes_surprise.png, mouth_a.png, mouth_a_half.png, mouth_i.png, mouth_o.png, mouth_angry.png or mouth_sad.png. The app keeps the images local.',
importAccepted: 'Accepted; preview updated.', importMaskOnly: 'The image differed outside the mask (re-encoded or slightly shifted), so only the masked area was used.', importRejected: 'Rejected; previous drawings and layers were kept.', importOutside: 'Pixels outside the edit mask changed.', importSize: 'The returned image must be a PNG with the same dimensions as source.png.', importMask: 'The edit mask is not valid for this drawing.',
importInvalid: 'Use the listed PNG filenames (one of each), up to 24 MB per file and 26 MB total.', metricsTitle: 'Measured comparison outside the mask', outsideMax: 'Maximum difference', outsideMean: 'Mean difference', outsidePixels: 'Pixels over tolerance',
variantsUnavailable: 'To create requests or import images here, open a writable project from the local development server. An agent can use docs/agent-guide.md Step 6 for other folders.',
@@ -44,7 +44,7 @@ export const workflowEn = {
export const workflowJa: typeof workflowEn = {
agentInstruction: 'このリポジトリのフォルダで AGENT を開いて、次の文章を貼ってください。',
variantsReloaded: '描き分け画像を読み込みました', mouthFallback: '描き分け画像がないため、メッシュの変形で代用しています', drawMouth: '→ 口を描き分ける',
- eyesKinds: '閉じた目・半目・笑った目', expressionKinds: '怒り・悲しみ・驚き(任意)', mouthKinds: 'あ・半分のあ・い・お', variantCount: 'TOTAL枚中COUNT枚',
+ eyesKinds: '閉じた目・半目・笑った目', expressionKinds: '悲しみ・驚きの目、怒り・悲しみの口(任意)', mouthKinds: 'あ・半分のあ・い・お', variantCount: 'TOTAL枚中COUNT枚',
askAgent: 'エージェントに依頼',
copyPrompt: '依頼文をコピー', copyDone: 'コピーしました', rootUnavailable: 'このアプリと docs/agent-guide.md があるフォルダで開いてください。開発サーバーを起動すると、ここでフルパスをコピーできます。',
newIllustration: '新しいイラストから作る',
@@ -54,7 +54,7 @@ export const workflowJa: typeof workflowEn = {
agentClaudePrompt: 'PROJECT の TARGETの描き分けについて、docs/agent-guide.md の Step 6 に沿って variant-requests でマスクと依頼文を用意してください。Claude Code は画像を生成できません。source.png と各マスク・依頼文のどのファイルを Codex などの画像生成に渡すか、結果を variants/ のどの PNG 名で保存するかを具体的に案内して、そこで止まってください。画像の生成・送信や build-sprites の実行はまだ行わないでください。ファイルはすべてこのリポジトリ内に保存してください。',
agentCopySample: '最初に読み取り専用の SOURCE を PROJECT にコピーしてください。作成先が存在する場合は未使用の名前を選び、元のプロジェクトは変更しないでください。',
agentUnknownPath: 'ブラウザで選んだフォルダの実際の場所は取得できません。正しい場所を含む依頼文を作るには、開発サーバーのプロジェクト一覧から開いてください。',
- agentEyes: '目', agentExpression: '表情の目(怒り・悲しみ・驚き)', agentMouth: '口',
+ agentEyes: '目', agentExpression: '表情(悲しみ・驚きの目と、怒り・悲しみの閉じた口)', agentMouth: '口',
rebuild: '保存してレイヤーを作り直す', rebuilding: '保存してレイヤーを作り直しています…', staleLocal: '輪郭が変更されました。レイヤーを作り直すとプレビューに反映されます。',
staleSample: 'サンプルは読み取り専用です。編集を続けるには、コピーしてプロジェクトにしてください。', copyContinue: 'コピーして編集を続ける',
staleListed: 'このプロジェクトは一覧から開けます', reopenListed: '一覧から開き直す',
@@ -73,12 +73,12 @@ export const workflowJa: typeof workflowEn = {
jobFailed: '作業を完了できませんでした。以前のレイヤーは残しています。', dependenciesHelp: 'uv と Python 3.10 以降を用意してから、もう一度お試しください。Homebrew の場合: brew install uv python。準備手順: docs/agent-guide.md。',
unsafeFilesHelp: 'プロジェクトに別の場所へ転送するファイルがあります。このプロジェクト内の通常のファイルにしてからお試しください。', showLog: 'ログを表示', operationBusy: 'この端末で処理中…', reloadFailed: 'プロジェクトを読み込み直せませんでした。現在の画面は残っています。',
variantsTitle: '描き分け画像', variantMissing: 'なし', variantsHelp: '目を閉じたとき・話すとき・怒りや悲しみや驚きの表情の絵を描き分けると、動きが自然になります。',
- eyesClosed: '閉じた目', eyesHalf: '半分閉じた目', eyesSmile: '笑った目', eyesAngry: '怒った目', eyesSad: '悲しい目', eyesSurprise: '驚いた目', mouthA: '口「あ」', mouthAHalf: '半分開いた「あ」', mouthI: '口「い」', mouthO: '口「お」',
- targetEyes: '目', targetExpression: '表情の目', targetMouth: '口',
+ eyesClosed: '閉じた目', eyesHalf: '半分閉じた目', eyesSmile: '笑った目', eyesSad: '悲しい目', eyesSurprise: '驚いた目', mouthA: '口「あ」', mouthAHalf: '半分開いた「あ」', mouthI: '口「い」', mouthO: '口「お」', mouthAngry: '怒った口', mouthSad: '悲しい口',
+ targetEyes: '目', targetExpression: '表情の目と口', targetMouth: '口',
createRequests: 'マスクと依頼文を書き出す', requestsReady: 'マスクと依頼文をこの端末に作りました。', requestFiles: 'マスクと依頼文', copyVariantPrompt: '画像の依頼文をコピー', copyFilePaths: 'ファイルの場所をコピー',
manualVariants: '自分で画像を用意する場合', manualHelp: '元画像 source.png・マスク・依頼文を画像編集ツールに渡してください。同じ大きさの PNG を下記の名前で保存し、この欄にドロップします。マスクの透明部分だけ変更でき、不透明部分は元画像と同じにします。',
variantOutput: '戻ってきた画像の保存先', dropVariants: '戻ってきた PNG 画像をここにドロップ', chooseVariants: '戻ってきた画像を選ぶ', variantFiles: '戻ってきた描き分け画像',
- variantFilenameHelp: 'eyes_closed.png・eyes_half.png・eyes_smile.png・eyes_angry.png・eyes_sad.png・eyes_surprise.png・mouth_a.png・mouth_a_half.png・mouth_i.png・mouth_o.png の名前を使います。画像はこの端末内に保存します。',
+ variantFilenameHelp: 'eyes_closed.png・eyes_half.png・eyes_smile.png・eyes_sad.png・eyes_surprise.png・mouth_a.png・mouth_a_half.png・mouth_i.png・mouth_o.png・mouth_angry.png・mouth_sad.png の名前を使います。画像はこの端末内に保存します。',
importAccepted: '合格しました。プレビューに反映しました。', importMaskOnly: 'マスクの外側が元画像と違っていた(再圧縮や小さなずれ)ため、マスクの中だけを取り込みました。', importRejected: '不合格でした。以前の画像とレイヤーは残しています。', importOutside: 'マスクの外側の画素が変更されています。', importSize: '元画像 source.png と同じ大きさの PNG にしてください。', importMask: 'この描き分けに使うマスクの形が正しくありません。',
importInvalid: '指定された PNG 名を使ってください(同じ名前は1枚まで)。1枚24 MB・合計26 MBまで取り込めます。', metricsTitle: 'マスクの外側の比較結果', outsideMax: '差の最大値', outsideMean: '差の平均値', outsidePixels: '許容差を超えた画素数',
variantsUnavailable: 'ここで依頼ファイルを作ったり画像を取り込んだりするには、開発サーバーの一覧から編集できるプロジェクトを開いてください。ほかのフォルダは、エージェントに docs/agent-guide.md の Step 6 を依頼できます。',
diff --git a/src/server/project-jobs.ts b/src/server/project-jobs.ts
index 5011841..aa4435c 100644
--- a/src/server/project-jobs.ts
+++ b/src/server/project-jobs.ts
@@ -3,7 +3,7 @@ import { execFile } from 'node:child_process';
import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
import { join, resolve, relative, dirname } from 'node:path';
-export const VARIANTS = ['eyes_closed', 'eyes_half', 'eyes_smile', 'eyes_angry', 'eyes_sad', 'eyes_surprise', 'mouth_a', 'mouth_a_half', 'mouth_i', 'mouth_o'] as const;
+export const VARIANTS = ['eyes_closed', 'eyes_half', 'eyes_smile', 'eyes_sad', 'eyes_surprise', 'mouth_a', 'mouth_a_half', 'mouth_i', 'mouth_o', 'mouth_angry', 'mouth_sad'] as const;
export type Tool = 'build-layers' | 'variant-requests' | 'build-sprites';
export class JobError extends Error {
constructor(public code: 'dependencies' | 'toolFailed' | 'unsafeFiles', public log: string) { super(code); }
diff --git a/tests/expression-eyes.test.ts b/tests/expression-eyes.test.ts
index d16599a..97ee182 100644
--- a/tests/expression-eyes.test.ts
+++ b/tests/expression-eyes.test.ts
@@ -18,8 +18,8 @@ function sprites(names: string[]) {
const grid = (rect: number[]) => ({ rest: [rect[0], rect[1]], pos: [0, 0] });
type Create = (...args: unknown[]) => { update(P: Record<string, number>, phys: unknown, dt: number, mood?: string | null): { eyes: boolean[] } };
const update = (createSpriteModule(engine, rig).createSprites as unknown as Create)(renderer, sheet, images, grid, () => new Uint8Array(1));
- return (open: number, mood: string | null = null, dt = 1) => {
- const result = update.update({ ...defaults, eyeROpen: open, eyeLOpen: open, eyeSmile: 0, eyeSmileL: 0 }, physics, dt, mood);
+ return (open: number, mood: string | null = null, dt = 1, mouthOpen = 0) => {
+ const result = update.update({ ...defaults, eyeROpen: open, eyeLOpen: open, eyeSmile: 0, eyeSmileL: 0, mouthOpen }, physics, dt, mood);
return { covered: result.eyes, shown: [...layers].filter(([, layer]) => layer.visible && layer.alpha > 0).map(([name]) => name).sort() };
};
}
@@ -38,7 +38,9 @@ test('expression names map to drawn-eye moods, and the live expression wins over
test('drawn expression eyes replace open and half eyes, and blinks still close them', () => {
const frame = sprites(eyes('closed', 'half', 'smile', 'angry', 'sad', 'surprise'));
- expect(frame(0.72, 'angry')).toEqual({ covered: [true, true], shown: eyes('angry') });
+ expect(frame(0.72, 'sad')).toEqual({ covered: [true, true], shown: eyes('sad') });
+ // the angry face keeps the half-closed eye, even if angry eyes were drawn
+ expect(frame(0.72, 'angry').shown).toEqual(eyes('half'));
expect(frame(1.22, 'surprise')).toEqual({ covered: [true, true], shown: eyes('surprise') });
expect(frame(0.1, 'surprise')).toEqual({ covered: [true, true], shown: eyes('closed') });
expect(frame(0.78, 'sad').shown).toEqual(eyes('sad'));
@@ -47,13 +49,13 @@ test('drawn expression eyes replace open and half eyes, and blinks still close t
});
test('the blink fade keeps one drawing solid underneath, so no eye turns see-through', () => {
- const frame = sprites(eyes('closed', 'half', 'angry'));
- frame(0.72, 'angry');
+ const frame = sprites(eyes('closed', 'half', 'sad'));
+ frame(0.78, 'sad');
// Mid-fade both drawings are shown and the layered eye stays hidden underneath.
- expect(frame(0.1, 'angry', 0.02)).toEqual({ covered: [false, false], shown: eyes('angry', 'closed').sort() });
- frame(0.1, 'angry', 1);
- expect(frame(0.72, 'angry', 0.02).shown).toEqual(eyes('angry', 'closed').sort());
- expect(frame(0.72, 'angry', 1).shown).toEqual(eyes('angry'));
+ expect(frame(0.1, 'sad', 0.02)).toEqual({ covered: [false, false], shown: eyes('closed', 'sad').sort() });
+ frame(0.1, 'sad', 1);
+ expect(frame(0.78, 'sad', 0.02).shown).toEqual(eyes('closed', 'sad').sort());
+ expect(frame(0.78, 'sad', 1).shown).toEqual(eyes('sad'));
});
test('avatars without drawn expression eyes keep the previous drawings', () => {
@@ -62,3 +64,20 @@ test('avatars without drawn expression eyes keep the previous drawings', () => {
expect(frame(1.22, 'surprise')).toEqual({ covered: [false, false], shown: [] });
expect(frame(0.1, 'sad').shown).toEqual(eyes('closed'));
});
+
+test('drawn expression mouths replace the closed mouth until an open mouth drawing has faded in', () => {
+ const frame = sprites(['mouth_a', 'mouth_a_half', 'mouth_angry', 'mouth_sad']);
+ expect(frame(1, 'angry').shown).toEqual(['mouth_angry']);
+ expect(frame(1, 'sad').shown).toEqual(['mouth_sad']);
+ expect(frame(1, 'surprise').shown).toEqual([]);
+ // fading in, the open mouth is drawn over the solid closed one; then it is shown alone
+ expect(frame(1, 'angry', 1, 0.18).shown).toEqual(['mouth_a_half', 'mouth_angry']);
+ expect(frame(1, 'angry', 1, 0.5).shown).toEqual(['mouth_a_half']);
+ expect(frame(1, null).shown).toEqual([]);
+});
+
+test('without open mouth drawings the expression mouth stays while speaking', () => {
+ const frame = sprites(['mouth_sad']);
+ expect(frame(1, 'sad', 1, 0.5).shown).toEqual(['mouth_sad']);
+ expect(frame(1, 'angry', 1, 0).shown).toEqual([]);
+});
diff --git a/tools/agent_common.py b/tools/agent_common.py
index f075190..2fc75ac 100644
--- a/tools/agent_common.py
+++ b/tools/agent_common.py
@@ -110,9 +110,13 @@ def grid_image(image, region=None, step=50):
EYE_VARIANTS = ("eyes_closed", "eyes_half", "eyes_smile")
# Open eyes drawn for an expression; the brows stay outside the mask (the runtime moves them).
-EXPRESSION_EYE_VARIANTS = ("eyes_angry", "eyes_sad", "eyes_surprise")
+# The angry face keeps the half-closed eyes and only gets a drawn mouth.
+EXPRESSION_EYE_VARIANTS = ("eyes_sad", "eyes_surprise")
ALL_EYE_VARIANTS = (*EYE_VARIANTS, *EXPRESSION_EYE_VARIANTS)
MOUTH_VARIANTS = ("mouth_a", "mouth_a_half", "mouth_i", "mouth_o")
+# Closed mouths drawn for an expression, shown while the avatar is not speaking.
+EXPRESSION_MOUTH_VARIANTS = ("mouth_angry", "mouth_sad")
+ALL_MOUTH_VARIANTS = (*MOUTH_VARIANTS, *EXPRESSION_MOUTH_VARIANTS)
def edit_masks(rig, size):
diff --git a/tools/build-sprites.py b/tools/build-sprites.py
index 94c1787..5e1e123 100644
--- a/tools/build-sprites.py
+++ b/tools/build-sprites.py
@@ -15,7 +15,7 @@ import cv2
import numpy as np
from agent_common import (
ALL_EYE_VARIANTS,
- MOUTH_VARIANTS,
+ ALL_MOUTH_VARIANTS,
edit_masks,
inside_repo,
project_image,
@@ -76,6 +76,10 @@ RING = 12
MAX_RING_MEAN = 20
MAX_RING_SHARE = 0.12
RING_LEVEL = 48
+# Generators also tint the whole picture slightly; on flat skin even a few levels show as a
+# patch. The tint is measured just inside the mask edge, where the skin should be unchanged.
+TINT_BAND = 10
+MAX_TINT = 24
def grey(image):
@@ -143,7 +147,20 @@ def mask_only(name, variant, source, region):
# Generators flatten transparency; the masked face keeps the source alpha.
variant = variant.copy()
variant[..., 3] = source[..., 3]
- print(f"{name}: importing the mask area only (corrected shift {sx:+d}, {sy:+d} px)")
+ inside = cv2.distanceTransform(region.astype(np.uint8), cv2.DIST_L2, 5)
+ band = opaque & (inside > 0) & (inside <= TINT_BAND)
+ tint = np.zeros(3)
+ if np.any(band):
+ tint = np.median(variant[band][:, :3].astype(np.float32) - source[band][:, :3], axis=0)
+ if np.abs(tint).max() <= MAX_TINT:
+ inner = region > 0
+ variant[inner, :3] = np.clip(variant[inner, :3] - tint, 0, 255).astype(np.uint8)
+ else:
+ tint = np.zeros(3)
+ print(
+ f"{name}: importing the mask area only (corrected shift {sx:+d}, {sy:+d} px, "
+ f"tint {tint[0]:+.0f}, {tint[1]:+.0f}, {tint[2]:+.0f})"
+ )
return variant
@@ -173,7 +190,7 @@ def build(project, output=None, tolerance=8):
if rig["image"] != {"width": source_image.width, "height": source_image.height}:
raise ValueError("rig.image must match source.png")
images, meta = {}, {}
- for name in (*ALL_EYE_VARIANTS, *MOUTH_VARIANTS):
+ for name in (*ALL_EYE_VARIANTS, *ALL_MOUTH_VARIANTS):
path = project / "variants" / f"{name}.png"
if not path.exists():
print(f"Skipping missing variant: {name}")
diff --git a/tools/test_agent_tools.py b/tools/test_agent_tools.py
index 44c35e5..8c40700 100644
--- a/tools/test_agent_tools.py
+++ b/tools/test_agent_tools.py
@@ -126,10 +126,14 @@ class AgentToolsTest(unittest.TestCase):
result = self.cli("variant-requests", self.project)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
- len(list((self.project / "variant-requests").glob("*/mask.png"))), 10
+ len(list((self.project / "variant-requests").glob("*/mask.png"))), 11
)
self.assertEqual(
- (self.project / "variant-requests/eyes_angry/mask.png").read_bytes(),
+ (self.project / "variant-requests/mouth_angry/mask.png").read_bytes(),
+ (self.project / "variant-requests/mouth_a/mask.png").read_bytes(),
+ )
+ self.assertEqual(
+ (self.project / "variant-requests/eyes_sad/mask.png").read_bytes(),
(self.project / "variant-requests/eyes_closed/mask.png").read_bytes(),
)
self.assertIn(
@@ -179,7 +183,7 @@ class AgentToolsTest(unittest.TestCase):
Image.fromarray(source).save(self.project / "source.png")
variants = self.project / "variants"
variants.mkdir()
- path = variants / "eyes_angry.png"
+ path = variants / "eyes_sad.png"
def save(image):
Image.fromarray(image).save(path)
@@ -192,10 +196,23 @@ class AgentToolsTest(unittest.TestCase):
save(np.clip(noisy, 0, 255).astype(np.uint8))
sprites.build(self.project)
layers = json.loads((self.project / "built/sprites/sprites.json").read_text())["layers"]
- self.assertEqual(sorted(layers), ["eyes_angry_0", "eyes_angry_1"])
- with Image.open(self.project / "built/sprites/eyes_angry_0.png") as image:
- x, y = layers["eyes_angry_0"][:2]
+ self.assertEqual(sorted(layers), ["eyes_sad_0", "eyes_sad_1"])
+ with Image.open(self.project / "built/sprites/eyes_sad_0.png") as image:
+ x, y = layers["eyes_sad_0"][:2]
self.assertLess(image.getpixel((20 - x, 30 - y))[0], 40)
+ # A uniform tint is measured at the mask edge and removed, so the skin matches.
+ tinted = drawn.astype(int)
+ tinted[..., :3] -= 8
+ tinted[..., 3] = 255
+ save(np.clip(tinted, 0, 255).astype(np.uint8))
+ sprites.build(self.project)
+ x, y, w, h = json.loads((self.project / "built/sprites/sprites.json").read_text())["layers"]["eyes_sad_0"]
+ with Image.open(self.project / "built/sprites/eyes_sad_0.png") as image:
+ sprite = np.array(image.convert("RGBA")).astype(int)
+ solid = sprite[..., 3] == 255
+ solid[25 - y : 36 - y, 15 - x : 26 - x] = False
+ self.assertTrue(solid.any())
+ self.assertLess(np.abs(sprite[..., :3] - source[y : y + h, x : x + w, :3])[solid].mean(), 1)
# A one-pixel shift is corrected; a uniformly scaled image is resized.
save(np.roll(drawn, 1, axis=1))
sprites.build(self.project)
diff --git a/tools/variant-requests.py b/tools/variant-requests.py
index f27b4a0..96f32d7 100644
--- a/tools/variant-requests.py
+++ b/tools/variant-requests.py
@@ -10,7 +10,7 @@ from pathlib import Path
from agent_common import (
ALL_EYE_VARIANTS,
- MOUTH_VARIANTS,
+ ALL_MOUTH_VARIANTS,
edit_masks,
inside_repo,
project_image,
@@ -23,9 +23,10 @@ CHANGES = {
"eyes_closed": "Close both eyes naturally, using one clean upper lash line per eye. Remove all visible iris and eye white. Keep the eyebrows unchanged.",
"eyes_half": "Draw both eyes half closed, with the upper lids halfway down. Keep the iris visible only below the upper lid and preserve the original gaze.",
"eyes_smile": "Draw both eyes closed in a gentle smiling upward arc, with clean lashes and no visible iris or eye white. Keep the eyebrows unchanged.",
- "eyes_angry": "Redraw both eyes as angry open eyes: the upper lids lowered into a narrowed glare that slants down toward the nose, with the upper part of each iris hidden under the lid and the gaze straight ahead. Keep each eye in place and the eyebrows unchanged; they are moved separately.",
"eyes_sad": "Redraw both eyes as sad open eyes: the upper lids drooping at the outer corners and raised toward the nose, softer and slightly moist, with the gaze a little downward. Do not draw tears on the cheeks. Keep each eye in place and the eyebrows unchanged; they are moved separately.",
"eyes_surprise": "Redraw both eyes as surprised wide-open eyes: the upper lids raised to show eye white above the iris, slightly smaller irises with clear highlights, and the gaze straight ahead. Keep each eye in place and the eyebrows unchanged; they are moved separately.",
+ "mouth_angry": "Redraw the closed mouth as angry: a tight, closed mouth with the corners turned down into a firm frown (an upside-down V), slightly shorter than the original. Keep it closed with no teeth, and keep its center in place.",
+ "mouth_sad": "Redraw the closed mouth as sad: a small closed mouth with the corners drooping downward in a gentle, soft curve, slightly wavering. Keep it closed with no teeth, and keep its center in place.",
"mouth_a": "Open the mouth in the Japanese vowel あ (a): a natural vertically open mouth, with a subtle tongue and upper teeth.",
"mouth_a_half": "Draw the Japanese vowel あ (a) at half openness: a smaller, gently open mouth.",
"mouth_i": "Draw the Japanese vowel い (i): a wide, narrow open smile with subtle upper teeth.",
@@ -41,7 +42,7 @@ def generate(project):
eyes, mouth = edit_masks(rig, image.size)
output = project / "variant-requests"
output.mkdir(exist_ok=True)
- names = (*ALL_EYE_VARIANTS, *MOUTH_VARIANTS)
+ names = (*ALL_EYE_VARIANTS, *ALL_MOUTH_VARIANTS)
for name in names:
folder = output / name
save_image(
@@ -65,8 +66,8 @@ def generate(project):
"# Drawn variant requests\n\n"
f"Required output size: **{image.width} x {image.height}** pixels, RGBA PNG.\n\n"
"For each variant below, supply `../source.png`, the variant's `mask.png`, and its "
- "`prompt.md` to an image editor you trust. The expression eyes (`eyes_angry`, `eyes_sad`, "
- "`eyes_surprise`) are optional; generate only the ones you want. Transparent mask pixels may change; opaque "
+ "`prompt.md` to an image editor you trust. The expression eyes (`eyes_sad`, `eyes_surprise`) "
+ "and closed mouths (`mouth_angry`, `mouth_sad`) are optional; generate only the ones you want. Transparent mask pixels may change; opaque "
"mask pixels must stay identical. Generating these files is a separate action: this "
"command uploads nothing. If the image must stay local, use a local editor.\n\n"
+ "\n".join(