Skip to content

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

Fall back for missing drawn variants instead of hiding eyes and mouth

shinshin869e3001baed28
diff --git a/.changeset/partial-sprite-fallback.md b/.changeset/partial-sprite-fallback.md
new file mode 100644
index 0000000..649f542
--- /dev/null
+++ b/.changeset/partial-sprite-fallback.md
@@ -0,0 +1,8 @@
+---
+"mesh-avatar": patch
+---
+
+Avatars with only some drawn eye or mouth variants no longer lose their eyes or mouth. A
+missing half-closed eye now uses the layered eye, a missing smiling eye uses the closed one,
+and a mouth shape without a drawing uses the shader mouth. Avatars with all variants, or none,
+render exactly as before.
diff --git a/native/crates/mesh-avatar-core/src/avatar.rs b/native/crates/mesh-avatar-core/src/avatar.rs
index b8b6dc8..ab4b811 100644
--- a/native/crates/mesh-avatar-core/src/avatar.rs
+++ b/native/crates/mesh-avatar-core/src/avatar.rs
@@ -395,9 +395,10 @@ impl Avatar {
);
*pos = q.map(|v| v as f32);
}
- let has_sprites = self.sprites.is_some();
+ let eyes_drawn = self.sprites.as_ref().map_or([false; 2], |s| s.eyes_drawn);
+ let mut mouth_drawn = false;
for eye in &mut self.eyes {
- let open = if has_sprites {
+ let open = if eyes_drawn[eye.eye] {
1.0
} else if eye.eye == 0 {
p.eye_r_open
@@ -444,6 +445,7 @@ impl Avatar {
},
);
let covered = sprites.update(&engine, &p, phys, dt, mood);
+ mouth_drawn = covered.mouth_drawn;
for eye in &mut self.eyes {
if covered.eyes[eye.eye] {
eye.alpha = 0.0;
@@ -534,11 +536,11 @@ impl Avatar {
eye_top: r.eyes.each_ref().map(|e| e.top.map(|v| v as f32)),
eye_bot: r.eyes.each_ref().map(|e| e.bot.map(|v| v as f32)),
eyes: [
- if has_sprites { 1.0 } else { p.eye_r_open },
+ if eyes_drawn[0] { 1.0 } else { p.eye_r_open },
p.eye_smile,
p.gaze_x * 7.0,
-p.gaze_y * 7.0 * 0.6,
- if has_sprites { 1.0 } else { p.eye_l_open },
+ if eyes_drawn[1] { 1.0 } else { p.eye_l_open },
p.eye_smile_l.unwrap_or(p.eye_smile),
p.gaze_x * 7.0 * 0.85,
-p.gaze_y * 7.0 * 0.6,
@@ -546,7 +548,7 @@ impl Avatar {
.map(|v| v as f32),
mouth: [mouth.cx, mouth.cy, mouth.angle, mouth.half_len].map(|v| v as f32),
mouth_state: [
- if has_sprites { 0.0 } else { p.mouth_open },
+ if mouth_drawn { 0.0 } else { p.mouth_open },
p.mouth_form,
mouth.bow,
0.0,
diff --git a/native/crates/mesh-avatar-core/src/engine/sprites.rs b/native/crates/mesh-avatar-core/src/engine/sprites.rs
index a0e65e3..ca036c1 100644
--- a/native/crates/mesh-avatar-core/src/engine/sprites.rs
+++ b/native/crates/mesh-avatar-core/src/engine/sprites.rs
@@ -140,10 +140,17 @@ struct EyeState {
pub struct SpriteCoverage {
pub eyes: [bool; 2],
pub mouth: Option<MouthShape>,
+ /// Whether a drawing shows the mouth, so the shader mouth is left out.
+ #[serde(rename = "mouthDrawn")]
+ pub mouth_drawn: bool,
}
pub struct Sprites {
pub items: Vec<SpriteItem>,
+ /// Whether each eye has the closed and half-closed drawings, so the layered eye stays open.
+ /// A partial set leaves what is missing to the layered eye and the shader mouth.
+ pub eyes_drawn: [bool; 2],
+ mouths_drawn: bool,
last_shape: Option<MouthShape>,
eye_state: [EyeState; 2],
}
@@ -245,8 +252,24 @@ impl Sprites {
alpha: 1.0,
});
}
+ let has = |name: &str| items.iter().any(|it: &SpriteItem| it.name == name);
+ let eyes_drawn = std::array::from_fn(|i| {
+ has(&format!("eyes_closed_{i}")) && has(&format!("eyes_half_{i}"))
+ });
+ let mouths_drawn = [
+ MouthShape::A,
+ MouthShape::AHalf,
+ MouthShape::I,
+ MouthShape::E,
+ MouthShape::O,
+ MouthShape::U,
+ ]
+ .into_iter()
+ .any(|shape| has(shape.definition().0));
Ok(Self {
items,
+ eyes_drawn,
+ mouths_drawn,
last_shape: None,
eye_state: std::array::from_fn(|_| EyeState {
cur: "open".into(),
@@ -302,7 +325,14 @@ impl Sprites {
.any(|it| it.name == format!("eyes_{m}_{i}"))
})
.map(|m| format!("eyes_{m}"));
- let want = eye_sprite(open, smile, drawn.as_deref()).unwrap_or("open");
+ let has = |name: &str| self.items.iter().any(|it| it.name == format!("{name}_{i}"));
+ let mut want = eye_sprite(open, smile, drawn.as_deref()).unwrap_or("open");
+ if want == "eyes_smile" && !has(want) {
+ want = "eyes_closed";
+ }
+ if want != "open" && !has(want) {
+ want = "open";
+ }
let st = &mut self.eye_state[i];
if want != st.cur {
st.prev = st.cur.clone();
@@ -359,6 +389,7 @@ impl Sprites {
SpriteCoverage {
eyes: covered,
mouth: shape,
+ mouth_drawn: self.mouths_drawn && (def.is_none() || mouth.is_some()),
}
}
}
diff --git a/packages/runtime/src/engine/createMeshAvatar.js b/packages/runtime/src/engine/createMeshAvatar.js
index 72dbb29..cce4bb4 100644
--- a/packages/runtime/src/engine/createMeshAvatar.js
+++ b/packages/runtime/src/engine/createMeshAvatar.js
@@ -171,9 +171,9 @@ export async function createMeshAvatarImpl(canvas, options) {
}
// with drawn eye sprites the layered eye is only ever shown exactly as drawn: moving the
// cut-out lash leaves seams at its edges
- const eyeOpenFor = v => (sprites ? 1 : v);
+ const eyeOpenFor = (v, eye) => (sprites?.eyesDrawn[eye] ? 1 : v);
for (const ep of eyeParts) {
- const open = eyeOpenFor(ep.eye === 0 ? P.eyeROpen : P.eyeLOpen);
+ const open = eyeOpenFor(ep.eye === 0 ? P.eyeROpen : P.eyeLOpen, ep.eye);
const smile = ep.eye === 0 ? P.eyeSmile : (P.eyeSmileL ?? P.eyeSmile);
ep.layer.alpha = eyePartAlpha(ep.part, open, smile);
const r = ep.mesh.rest, o = ep.mesh.pos;
@@ -197,11 +197,11 @@ export async function createMeshAvatarImpl(canvas, options) {
R.draw({
angleX: P.angleX, angleY: P.angleY, angleZ: P.angleZ,
eyes: [
- eyeOpenFor(P.eyeROpen), P.eyeSmile, P.gazeX * ball, -P.gazeY * ball * 0.6,
- eyeOpenFor(P.eyeLOpen), P.eyeSmileL ?? P.eyeSmile, P.gazeX * ball * 0.85, -P.gazeY * ball * 0.6,
+ eyeOpenFor(P.eyeROpen, 0), P.eyeSmile, P.gazeX * ball, -P.gazeY * ball * 0.6,
+ eyeOpenFor(P.eyeLOpen, 1), P.eyeSmileL ?? P.eyeSmile, P.gazeX * ball * 0.85, -P.gazeY * ball * 0.6,
],
// with sprites the drawn mouths replace the shader-painted one
- mouthOpen: sprites ? 0 : P.mouthOpen, mouthForm: P.mouthForm, cheek: P.blush,
+ mouthOpen: cover?.mouthDrawn ? 0 : P.mouthOpen, mouthForm: P.mouthForm, cheek: P.blush,
showMesh: false, originalAlpha: 0, joints: [],
});
}
diff --git a/packages/runtime/src/engine/sprites.js b/packages/runtime/src/engine/sprites.js
index fa781d5..bb9f0ee 100644
--- a/packages/runtime/src/engine/sprites.js
+++ b/packages/runtime/src/engine/sprites.js
@@ -104,6 +104,15 @@ export function createSpriteModule(engine, rig) {
layer.visible = false;
items[name] = { mesh, W, inner, layer };
}
+ // A partial set (a variant that failed or was never drawn) leaves what is missing to the
+ // layered eye and the shader mouth instead of hiding them under a drawing that is not there.
+ // Only an eye with both the closed and the half-closed drawing is held open for the sprites.
+ const eyesDrawn = [0, 1].map(i => Boolean(items[`eyes_closed_${i}`] && items[`eyes_half_${i}`]));
+ const mouthsDrawn = Object.values(MOUTH_SHAPES).some(def => items[def.sprite]);
+ const frameFor = (want, i) => {
+ if (want === 'eyes_smile' && !items[`eyes_smile_${i}`]) want = 'eyes_closed';
+ return want === 'open' || items[`${want}_${i}`] ? want : 'open';
+ };
const tmp = [0, 0];
let lastShape = null;
const eyeState = [0, 1].map(() => ({ cur: 'open', prev: 'open', t: 1 }));
@@ -127,7 +136,8 @@ export function createSpriteModule(engine, rig) {
return {
/**
* 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.
+ * Returns which eyes are covered by a sprite, so the layered eye parts can be hidden, and
+ * whether a drawing shows the mouth, so the shader mouth can be left out.
* `mood` (angry / sad / surprise) picks drawn expression eyes (sad, surprise) and closed
* mouths (angry, sad) when the avatar has them.
*/
@@ -143,7 +153,7 @@ export function createSpriteModule(engine, rig) {
eyes.forEach(([open, smile], i) => {
const st = eyeState[i];
const drawn = EYE_MOODS_DRAWN.includes(mood) && items[`eyes_${mood}_${i}`] ? `eyes_${mood}` : null;
- const want = eyeSprite(open, smile, drawn) ?? 'open';
+ const want = frameFor(eyeSprite(open, smile, drawn) ?? 'open', i);
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
// frame at once; otherwise the fade would stay at its first frame.
@@ -186,8 +196,11 @@ export function createSpriteModule(engine, rig) {
const squash = Math.min(1.1, Math.max(0.5, P.mouthOpen / def.ref));
place(mt, P, phys, squash, def.width);
}
- return { eyes: covered, mouth: shape };
+ // the shader mouth stays off while a drawing could show the mouth: closed, or a drawn shape
+ return { eyes: covered, mouth: shape, mouthDrawn: mouthsDrawn && (!def || Boolean(mt)) };
},
+ /** Whether each eye has the closed and half-closed drawings, so the layered eye stays open. */
+ eyesDrawn,
};
}
return { createSprites, mouthShape, eyeSprite };
diff --git a/tests/expression-eyes.test.ts b/tests/expression-eyes.test.ts
index 97ee182..3fc8d55 100644
--- a/tests/expression-eyes.test.ts
+++ b/tests/expression-eyes.test.ts
@@ -16,12 +16,15 @@ function sprites(names: string[]) {
const sheet = { build: 'test', layers: Object.fromEntries(names.map(name => [name, [500, 400, 10, 10]])) };
const images = Object.fromEntries(names.map(name => [name, { width: 10 }]));
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[] } };
+ type Create = (...args: unknown[]) => { eyesDrawn: boolean[]; update(P: Record<string, number>, phys: unknown, dt: number, mood?: string | null): { eyes: boolean[]; mouthDrawn: 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, mouthOpen = 0) => {
- const result = update.update({ ...defaults, eyeROpen: open, eyeLOpen: open, eyeSmile: 0, eyeSmileL: 0, mouthOpen }, physics, dt, mood);
+ let mouthDrawn = false;
+ const frame = (open: number, mood: string | null = null, dt = 1, mouthOpen = 0, smile = 0, mouthForm = 0) => {
+ const result = update.update({ ...defaults, eyeROpen: open, eyeLOpen: open, eyeSmile: smile, eyeSmileL: smile, mouthOpen, mouthForm }, physics, dt, mood);
+ mouthDrawn = result.mouthDrawn;
return { covered: result.eyes, shown: [...layers].filter(([, layer]) => layer.visible && layer.alpha > 0).map(([name]) => name).sort() };
};
+ return Object.assign(frame, { eyesDrawn: update.eyesDrawn, mouthDrawn: () => mouthDrawn });
}
const eyes = (...kinds: string[]) => kinds.flatMap(kind => [`eyes_${kind}_0`, `eyes_${kind}_1`]);
@@ -81,3 +84,34 @@ test('without open mouth drawings the expression mouth stays while speaking', ()
expect(frame(1, 'sad', 1, 0.5).shown).toEqual(['mouth_sad']);
expect(frame(1, 'angry', 1, 0).shown).toEqual([]);
});
+
+test('a partial set leaves missing eye drawings to the layered eye instead of hiding it', () => {
+ const frame = sprites(eyes('closed'));
+ // without the half-closed drawing the layered eye keeps animating its own openness
+ expect(frame.eyesDrawn).toEqual([false, false]);
+ expect(frame(0.5)).toEqual({ covered: [false, false], shown: [] });
+ expect(frame(0.1)).toEqual({ covered: [true, true], shown: eyes('closed') });
+ // a smiling blink without the smiling drawing uses the closed one
+ expect(frame(0.1, null, 1, 0, 1)).toEqual({ covered: [true, true], shown: eyes('closed') });
+ expect(frame(0.5, 'angry')).toEqual({ covered: [false, false], shown: [] });
+ expect(sprites(eyes('closed', 'half')).eyesDrawn).toEqual([true, true]);
+});
+
+test('the shader mouth is turned off only while a drawing shows the mouth', () => {
+ const eyesOnly = sprites(eyes('closed', 'half'));
+ eyesOnly(1, null, 1, 0.8);
+ expect(eyesOnly.mouthDrawn()).toBe(false);
+ const some = sprites(['mouth_a']);
+ some(1, null, 1, 0);
+ expect(some.mouthDrawn()).toBe(true);
+ expect(some(1, null, 1, 0.8).shown).toEqual(['mouth_a']);
+ expect(some.mouthDrawn()).toBe(true);
+ // the い shape has no drawing here, so the shader mouth shows it
+ expect(some(1, null, 1, 0.5, 0, -1).shown).toEqual([]);
+ expect(some.mouthDrawn()).toBe(false);
+ const full = sprites(['mouth_a', 'mouth_a_half', 'mouth_i', 'mouth_o']);
+ for (const [open, form] of [[0, 0], [0.3, 0], [0.8, 0], [0.5, -1], [0.6, 1]]) {
+ full(1, null, 1, open, 0, form);
+ expect(full.mouthDrawn()).toBe(true);
+ }
+});