Skip to content

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

Port motion, expressions, lip sync and the Avatar API to the native core

shinshin86020b28a1f0aa
diff --git a/native/Cargo.toml b/native/Cargo.toml
index e4db84c..ae40e51 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -12,6 +12,6 @@ publish = false
mesh-avatar-core = { path = "crates/mesh-avatar-core" }
anyhow = "1"
serde = { version = "1", features = ["derive"] }
-serde_json = "1"
+serde_json = { version = "1", features = ["float_roundtrip"] }
png = "0.17"
zip = { version = "2", default-features = false }
diff --git a/native/conformance/avatar.mjs b/native/conformance/avatar.mjs
new file mode 100644
index 0000000..69ae133
--- /dev/null
+++ b/native/conformance/avatar.mjs
@@ -0,0 +1,85 @@
+import { writeFile } from 'node:fs/promises';
+import { registerHooks } from 'node:module';
+import { seededRandom } from '../../tools/motion-scenarios.mjs';
+import { capture } from './capture-renderer.mjs';
+
+const actions = [
+ [0, 'setAutoIdle', true], [0, 'setAutoMotion', true], [60, 'play', 'nod'], [120, 'setSpeaking', true],
+ [180, 'setEmotion', 'happy'], [240, 'setExpression', 'sad'],
+ [300, 'speakKana', 'こんにちは。きゃっほー!', { loop: true }],
+ [360, 'setParameters', { angleX: -12, eyeLOpen: 0.5, mouthOpen: 0.8, mouthForm: -1 }, 0.6],
+ [420, 'setLipSync', { granularity: 0.2, openness: 0.8, closeSpeed: 0.1 }],
+ [480, 'holdMouth', 'o'], [540, 'stopLipSync'], [600, 'setExpression', 'neutral'],
+ [660, 'setAutoIdle', false], [720, 'setParameters', {}], [780, 'setSpeaking', false],
+ [840, 'play', 'doze'], [900, 'setSwayGain', 0.8], [960, 'setEmotion', 'relaxed', { playMotion: false }],
+ [1020, 'setExpression', 'wink'], [1080, 'setSpeaking', true], [1140, 'setExpression', 'neutral'],
+];
+
+export async function dumpAvatar({ rig, metadata, sprites, images, destination }) {
+ const runtime = new URL('../../packages/runtime/src/engine/createMeshAvatar.js', import.meta.url).href;
+ const replacement = new URL('./capture-renderer.mjs', import.meta.url).href;
+ const hooks = registerHooks({ load(url, context, next) {
+ const result = next(url, context);
+ if (url === runtime) return { ...result, source: String(result.source).replace(
+ "import { createRenderer } from './renderer.js';", `import { createRenderer } from ${JSON.stringify(replacement)};`) };
+ return result;
+ } });
+ const { createMeshAvatarImpl } = await import(runtime);
+ hooks.deregister();
+ const original = { random: Math.random, fetch: globalThis.fetch, Image: globalThis.Image,
+ document: globalThis.document, cancelAnimationFrame: globalThis.cancelAnimationFrame };
+ try {
+ globalThis.Image = class {
+ set src(name) {
+ const image = images[name];
+ if (!image) { queueMicrotask(() => this.onerror(new Error(`Missing image: ${name}`))); return; }
+ this.width = image.width; this.height = image.height; this.data = image.data;
+ queueMicrotask(() => this.onload());
+ }
+ };
+ globalThis.document = { createElement() {
+ let image;
+ return { getContext() { return { drawImage(value) { image = value; }, getImageData() { return { data: image.data }; } }; } };
+ } };
+ globalThis.cancelAnimationFrame = () => {};
+ const variants = [];
+ for (const [name, hasSprites, preserveMouthForm] of [['drawn', true, false], ['painted', false, true]]) {
+ Math.random = seededRandom(173);
+ globalThis.fetch = async name => {
+ const value = name === 'layers.json' ? metadata : name === 'sprites/sprites.json' && hasSprites ? sprites : undefined;
+ return { ok: value !== undefined, status: value === undefined ? 404 : 200, json: async () => value };
+ };
+ // Use a distinct JSON asset URL so the real runtime's shared cache cannot carry a sprite
+ // sheet into the variant without one. PNGs remain shared and are decoded once.
+ const assets = Object.fromEntries(Object.keys(images).map(name => [name, name]));
+ assets['layers.json'] = 'layers.json'; assets['sprites/sprites.json'] = hasSprites ? 'sprites/sprites.json' : 'absent-sprites.json';
+ const avatar = await createMeshAvatarImpl({}, { rig, assets, manual: true, preserveMouthForm });
+ const events = []; avatar.onMotion(id => events.push(id));
+ const samples = [], frames = 1200;
+ for (let frame = 0; frame < frames; frame++) {
+ for (const [at, method, ...args] of actions) if (frame === at) avatar[method](...args);
+ const voice = 0.5 + Math.sin(frame * 0.73) * 0.45; avatar.setVoiceLevel(voice);
+ const dt = frame === 600 ? 0 : frame === 900 ? 0.08 : 1 / 60, step = Math.min(0.05, dt);
+ avatar.advance(step, step === 0 ? 60 : 1 / step);
+ if (frame % 60 <= 4 || frame === frames - 1) {
+ const snapshot = capture.renderer.snapshot();
+ // Static UV/index data is already covered by grids.json; keep it only once per
+ // layer in this sequence to avoid writing it on every sampled frame.
+ for (const layer of snapshot.layers) { delete layer.uvs; delete layer.indices; }
+ samples.push({ frame, dt, voice, parameters: avatar.getParameters(), ...snapshot,
+ expression: avatar.getExpression(), lipSync: avatar.getLipSyncState(), events: events.splice(0) });
+ }
+ }
+ const file = `avatar-${name}.json`;
+ await writeFile(new URL(file, destination), JSON.stringify({ version: 1, hasSprites, preserveMouthForm, actions, samples }) + '\n');
+ variants.push(file); avatar.destroy();
+ }
+ await writeFile(new URL('avatar.json', destination), JSON.stringify({ version: 1, seed: 173, seconds: 20, files: variants }) + '\n');
+ console.log(`Wrote ${variants.length} full Avatar tick sequences from the JS runtime`);
+ } finally {
+ Math.random = original.random;
+ for (const key of ['fetch', 'Image', 'document', 'cancelAnimationFrame']) {
+ if (original[key] === undefined) delete globalThis[key]; else globalThis[key] = original[key];
+ }
+ }
+}
diff --git a/native/conformance/capture-renderer.mjs b/native/conformance/capture-renderer.mjs
new file mode 100644
index 0000000..f0ca295
--- /dev/null
+++ b/native/conformance/capture-renderer.mjs
@@ -0,0 +1,31 @@
+// Capture the real avatar tick path without a browser or GPU.
+import { createRenderer as realRenderer } from '../../packages/runtime/src/engine/renderer.js';
+export const capture = { renderer: null };
+const f32 = values => Array.from(new Float32Array(values));
+
+export function createRenderer(engine, rig) {
+ const { buildGrid } = realRenderer(engine, rig);
+ class Renderer {
+ constructor() { this.layers = []; capture.renderer = this; }
+ addLayer(name, image, mesh, options = {}) {
+ const layer = { name, image, mesh, visible: true, ...options };
+ this.layers.push(layer); return layer;
+ }
+ draw(state) { this.state = state; }
+ destroy() {}
+ snapshot() {
+ const state = this.state, mouth = rig.mouth;
+ return { layers: this.layers.filter(layer => layer.visible && !layer.overlay).map(layer => ({
+ name: layer.name, texture: `${layer.name.startsWith('eyes_') || layer.name.startsWith('mouth_') ? 'sprites/' : ''}${layer.name}.png`,
+ rect: layer.mesh.rect, positions: Array.from(layer.mesh.pos), uvs: Array.from(layer.mesh.uv), indices: Array.from(layer.mesh.tris),
+ alpha: layer.alpha ?? 1, face: !!layer.face, eye_ball: layer.eyeBall ?? null,
+ })), uniforms: {
+ angles: f32([state.angleX, state.angleY, state.angleZ]),
+ eye_box: rig.eyes.map(e => f32([e.x0, e.x1, 0, 0])), eye_top: rig.eyes.map(e => f32(e.top)), eye_bot: rig.eyes.map(e => f32(e.bot)),
+ eyes: f32(state.eyes), mouth: f32([mouth.cx, mouth.cy, mouth.angle, mouth.halfLen]),
+ mouth_state: f32([state.mouthOpen, state.mouthForm, mouth.bow, 0]), cheeks: f32(rig.cheeks.flat()), cheek: Math.fround(state.cheek),
+ } };
+ }
+ }
+ return { Renderer, buildGrid };
+}
diff --git a/native/conformance/dump.mjs b/native/conformance/dump.mjs
index e10a470..7dffe6e 100644
--- a/native/conformance/dump.mjs
+++ b/native/conformance/dump.mjs
@@ -1,10 +1,11 @@
-// Run with Node.js 22.17+ from any directory: node native/conformance/dump.mjs
+// Run with Node.js 22.17+: node --experimental-strip-types native/conformance/dump.mjs
import { existsSync } from 'node:fs';
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { registerHooks } from 'node:module';
import { fileURLToPath } from 'node:url';
import { PNG } from 'pngjs';
import { dumpDeformation } from './deformation.mjs';
+import { dumpMotion } from './motion.mjs';
// Match the runtime's bundler-style extensionless lighting imports in plain Node.
const hooks = registerHooks({ resolve(specifier, context, next) {
@@ -19,7 +20,6 @@ const hooks = registerHooks({ resolve(specifier, context, next) {
const { createRig } = await import('../../packages/runtime/src/engine/rig.js');
const { createRenderer } = await import('../../packages/runtime/src/engine/renderer.js');
const { parseRig } = await import('../../packages/runtime/src/rig/validate.ts');
-hooks.deregister();
const sample = new URL('../../samples/miko-qipao/', import.meta.url);
const json = async path => JSON.parse(await readFile(new URL(path, sample), 'utf8'));
@@ -64,3 +64,7 @@ await writeFile(new URL('grids.json', destination), JSON.stringify({ version: 1,
console.log(`Wrote ${grids.length} layer/sprite grids and ${cases.length} edge cases to ${fileURLToPath(new URL('grids.json', destination))}`);
images['hairmask.png'] = PNG.sync.read(await readFile(new URL('built/hairmask.png', sample)));
await dumpDeformation({ rig, engine, grids, images, sprites, buildGrid, destination });
+await dumpMotion({ rig, engine, destination });
+const { dumpAvatar } = await import('./avatar.mjs');
+await dumpAvatar({ rig, metadata, sprites, images, destination });
+hooks.deregister();
diff --git a/native/conformance/motion.mjs b/native/conformance/motion.mjs
new file mode 100644
index 0000000..1717903
--- /dev/null
+++ b/native/conformance/motion.mjs
@@ -0,0 +1,72 @@
+import { writeFile } from 'node:fs/promises';
+import { SCENARIOS, createScenario, seededRandom } from '../../tools/motion-scenarios.mjs';
+import { Motion } from '../../packages/runtime/src/engine/motion.js';
+import { ExpressionOverlay } from '../../packages/runtime/src/engine/expression-overlay.js';
+import { kanaToMoras, sampleMoras, skippedKanaCharacters } from '../../packages/runtime/src/engine/kana.js';
+
+export const speechText = 'こんにちは。きょうも、いっしょにあいうえおをれんしゅうしましょう。';
+export const actions = [
+ [0, 'setAutoIdle', false], [0, 'setAutoMotion', false], [5, 'setSpeaking', true], [30, 'setEmotion', 'happy'],
+ [60, 'setEmotion', 'sad', { playMotion: false }], [70, 'setExpression', 'wink'],
+ [90, 'setSpeaking', false], [120, 'speakKana', speechText, { loop: true, speed: 8 }],
+ [150, 'setLipSync', { granularity: 0.1, openness: 0.8, closeSpeed: 0.2 }],
+ [180, 'holdMouth', 'n'], [190, 'holdMouth', 'i'], [200, 'stopLipSync'], [210, 'setExpression', 'sad'],
+ [230, 'setExpression', 'neutral'], [240, 'speakKana', 'あ'], [265, 'setLipSync', { closeSpeed: 0.5 }],
+ [280, 'setSpeaking', true], [320, 'setSpeaking', false], [340, 'setExpression', 'unknown'],
+];
+
+export async function dumpMotion({ rig, engine, destination }) {
+ const original = Math.random;
+ try {
+ const scenarios = [];
+ for (const name of [...SCENARIOS, 'automatic']) {
+ Math.random = seededRandom(173);
+ const current = createScenario(name === 'automatic' ? 'idle' : name, rig, engine, 20), samples = [];
+ if (name === 'automatic') { current.motion.autoMotion = true; current.motion.autoIdle = false; }
+ for (let frame = 0; frame < current.frames; frame++) {
+ const { parameters, offsets } = current.step(frame);
+ if (frame % 60 === 0 || frame === current.frames - 1) samples.push({ frame, parameters: { ...parameters },
+ offsets: structuredClone(offsets), chains: current.physics.chains.map(ch => ({ phi: ch.phi, points: ch.pts })) });
+ }
+ scenarios.push({ name, schedule: current.schedule, samples });
+ }
+ Math.random = seededRandom(173);
+ const motion = new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy]);
+ const expression = new ExpressionOverlay(), updates = [];
+ for (let frame = 0; frame < 360; frame++) {
+ for (const [at, method, ...args] of actions) if (at === frame) {
+ if (method === 'setExpression') expression.set(...args);
+ else if (method === 'setAutoIdle') motion.autoIdle = args[0];
+ else if (method === 'setAutoMotion') motion.autoMotion = args[0];
+ else motion[method](...args);
+ }
+ const voice = 0.5 + Math.sin(frame * 0.73) * 0.45;
+ motion.setVoiceLevel(voice);
+ const dt = frame === 100 ? 0 : 1 / 60;
+ const parameters = { ...motion.update(dt) }, output = expression.apply(parameters, dt);
+ updates.push({ frame, voice, dt, parameters, output, expression: { name: expression.name, active: expression.active }, lipSync: motion.getLipSyncState() });
+ }
+ const kana = ['コンニチハ、きゃっほー!abc😀', 'あいうえおん', 'まみむめも ぱぴぷぺぽ'].flatMap(text => [0, 0.1, 0.5, 0.8, 1].map(granularity => {
+ const moras = kanaToMoras(text), samples = [];
+ for (let t = 0; t < 4; t += 0.037) samples.push({ t, target: sampleMoras(moras, t, granularity) });
+ return { text, granularity, moras, skipped: skippedKanaCharacters(text), samples };
+ }));
+ const rng = seededRandom(173);
+ const modes = [];
+ for (const mode of ['manual', 'mouse']) {
+ Math.random = seededRandom(173);
+ const motion = new Motion([600, 500]); motion.mode = mode; motion.setExpression('shy');
+ const samples = [];
+ for (let frame = 0; frame < 120; frame++) {
+ if (frame === 30) motion.playMotion('tilt');
+ motion.manual.angleX = 12; motion.manual.eyeLOpen = 0.4; motion.manual.breath = 0.6;
+ motion.pointer = [600 + Math.sin(frame / 20) * 350, 500 + Math.cos(frame / 25) * 200];
+ samples.push({ pointer: motion.pointer, parameters: { ...motion.update(1 / 60) } });
+ }
+ modes.push({ mode, samples });
+ }
+ await writeFile(new URL('motion.json', destination), JSON.stringify({ version: 1, seed: 173, seconds: 20, stride: 60,
+ random: Array.from({ length: 100 }, () => rng()), scenarios, actions, updates, kana, modes }) + '\n');
+ console.log(`Wrote ${scenarios.length} seeded motion scenarios, speech/expression sequences and kana samples`);
+ } finally { Math.random = original; }
+}
diff --git a/native/conformance/sync-motion-data.mjs b/native/conformance/sync-motion-data.mjs
new file mode 100644
index 0000000..dfb4f50
--- /dev/null
+++ b/native/conformance/sync-motion-data.mjs
@@ -0,0 +1,9 @@
+// Authored keyframes and expression targets shared with the JS runtime.
+import { writeFile } from 'node:fs/promises';
+import { MOTIONS, IDLE_MOTIONS, ADDITIVE } from '../../packages/runtime/src/engine/motions.js';
+import { EXPRESSIONS } from '../../packages/runtime/src/engine/motion.js';
+const motions = Object.entries({ ...MOTIONS, ...IDLE_MOTIONS }).map(([id, motion]) => ({
+ id, ...motion, idle: motion.idle ?? false, tracks: Object.entries(motion.tracks),
+}));
+await writeFile(new URL('../crates/mesh-avatar-core/src/engine/motions.json', import.meta.url),
+ JSON.stringify({ motions, additive: [...ADDITIVE], expressions: EXPRESSIONS }, null, 2) + '\n');
diff --git a/native/crates/mesh-avatar-core/src/avatar.rs b/native/crates/mesh-avatar-core/src/avatar.rs
new file mode 100644
index 0000000..b8b6dc8
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/avatar.rs
@@ -0,0 +1,570 @@
+use crate::{
+ engine::{
+ expression::ExpressionOverlay,
+ grid::{build_grid, Grid},
+ kana::Vowel,
+ lip_sync::LipSyncSettings,
+ motion::{LipSyncState, Mode, Motion, SpeakOptions},
+ motions::{motions, MotionDefinition},
+ physics::Physics,
+ random::{RandomSource, SeededRandom},
+ rig::{
+ eye_part_alpha, eye_part_y, BaseWeights, EyePart, HandWeights, Parameters, RigEngine,
+ },
+ sprites::{eye_mood, Sprites},
+ },
+ format::{AvatarPackage, Rect, Texture},
+};
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+use std::{collections::BTreeMap, path::Path};
+
+#[derive(Default)]
+pub struct AvatarOptions {
+ pub preserve_mouth_form: bool,
+ pub lip_sync: Option<LipSyncSettings>,
+}
+#[derive(Debug, Clone, Serialize)]
+pub struct DrawLayer {
+ pub name: String,
+ pub texture: String,
+ pub rect: [f64; 4],
+ pub positions: Vec<f32>,
+ pub uvs: Vec<f32>,
+ pub indices: Vec<u32>,
+ pub alpha: f64,
+ pub face: bool,
+ pub eye_ball: Option<usize>,
+}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FaceUniforms {
+ pub angles: [f32; 3],
+ pub eye_box: [[f32; 4]; 2],
+ pub eye_top: [[f32; 24]; 2],
+ pub eye_bot: [[f32; 24]; 2],
+ pub eyes: [f32; 8],
+ pub mouth: [f32; 4],
+ pub mouth_state: [f32; 4],
+ pub cheeks: [f32; 4],
+ pub cheek: f32,
+}
+#[derive(Debug, Clone, Serialize)]
+pub struct Frame {
+ pub layers: Vec<DrawLayer>,
+ pub uniforms: FaceUniforms,
+ pub motion_events: Vec<Option<String>>,
+}
+
+struct BaseLayer {
+ name: String,
+ mesh: Grid,
+ weights: Vec<BaseWeights>,
+}
+struct EyeLayer {
+ base: BaseLayer,
+ eye: usize,
+ part: EyePart,
+ alpha: f64,
+}
+struct HandLayer {
+ mesh: Grid,
+ weights: Vec<HandWeights>,
+}
+
+fn mesh(package: &AvatarPackage, name: &str, rect: Rect, cell: u32, fine: bool) -> Result<Grid> {
+ let image = &package.textures[&format!("{name}.png")];
+ build_grid(
+ rect.map(f64::from),
+ cell as f64,
+ &image.alpha(),
+ image.width as usize,
+ fine.then_some(&package.rig.mesh.fine),
+ )
+}
+fn weighted(engine: &RigEngine<'_>, name: &str, mesh: Grid, hair: Option<&Texture>) -> BaseLayer {
+ let weights = mesh
+ .rest
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|&[x, y]| {
+ let h = hair.map_or(0.0, |image| {
+ let ix = (x.round().max(0.0) as u32).min(image.width - 1);
+ let iy = (y.round().max(0.0) as u32).min(image.height - 1);
+ image.rgba[((iy * image.width + ix) * 4) as usize] as f64 / 255.0
+ });
+ engine.base_weights(x as f64, y as f64, h)
+ })
+ .collect();
+ BaseLayer {
+ name: name.into(),
+ mesh,
+ weights,
+ }
+}
+fn draw_layer(
+ name: &str,
+ texture: String,
+ mesh: &Grid,
+ alpha: f64,
+ face: bool,
+ eye_ball: Option<usize>,
+) -> DrawLayer {
+ DrawLayer {
+ name: name.into(),
+ texture,
+ rect: mesh.rect,
+ positions: mesh.pos.clone(),
+ uvs: mesh.uv.clone(),
+ indices: mesh.tris.clone(),
+ alpha,
+ face,
+ eye_ball,
+ }
+}
+
+pub struct Avatar {
+ package: AvatarPackage,
+ motion: Motion,
+ physics: Physics,
+ expression: ExpressionOverlay,
+ options: AvatarOptions,
+ overrides: BTreeMap<String, f64>,
+ parameter_weight: f64,
+ last_parameters: Parameters,
+ base: BaseLayer,
+ eyes: Vec<EyeLayer>,
+ sprites: Option<Sprites>,
+ tassels: Vec<(String, Grid)>,
+ hand: Option<HandLayer>,
+}
+
+impl Avatar {
+ /// Load with deterministic seed zero. Use with_rng to inject another sequence.
+ pub fn open(path: impl AsRef<Path>) -> Result<Self> {
+ Self::from_package(AvatarPackage::open(path)?)
+ }
+ pub fn from_package(package: AvatarPackage) -> Result<Self> {
+ Self::with_rng(
+ package,
+ AvatarOptions::default(),
+ Box::new(SeededRandom::new(0)),
+ )
+ }
+ pub fn with_rng(
+ package: AvatarPackage,
+ options: AvatarOptions,
+ rng: Box<dyn RandomSource>,
+ ) -> Result<Self> {
+ let r = &package.rig;
+ let engine = RigEngine::new(r);
+ let mut motion = Motion::with_rng(
+ r.view
+ .gaze_center
+ .unwrap_or([r.head.ellipse.cx, r.head.ellipse.cy]),
+ rng,
+ );
+ if let Some(settings) = &package.manifest.lip_sync {
+ motion.set_lip_sync(&LipSyncSettings::parse(settings)?)?;
+ }
+ if let Some(settings) = &options.lip_sync {
+ motion.set_lip_sync(settings)?;
+ }
+ let base_rect = package.layers.layers.get("base").copied().unwrap_or([
+ 0,
+ 0,
+ r.image.width,
+ r.image.height,
+ ]);
+ let base = weighted(
+ &engine,
+ "base",
+ mesh(&package, "base", base_rect, r.mesh.base_cell, true)?,
+ Some(&package.textures["hairmask.png"]),
+ );
+ let mut eyes = vec![];
+ for eye in 0..2 {
+ for (name, part) in [
+ ("ball", EyePart::Ball),
+ ("low", EyePart::Low),
+ ("crease", EyePart::Crease),
+ ("lash", EyePart::Lash),
+ ] {
+ let name = format!("eye{eye}_{name}");
+ let cell = if matches!(part, EyePart::Ball) {
+ r.mesh.eye_ball_cell
+ } else {
+ r.mesh.eye_cell
+ };
+ eyes.push(EyeLayer {
+ base: weighted(
+ &engine,
+ &name,
+ mesh(&package, &name, package.layers.layers[&name], cell, false)?,
+ None,
+ ),
+ eye,
+ part,
+ alpha: 1.0,
+ });
+ }
+ }
+ let sprites = package
+ .sprites
+ .as_ref()
+ .map(|sheet| Sprites::new(&engine, sheet, &package.textures))
+ .transpose()?;
+ let tassels = r
+ .accessories
+ .iter()
+ .map(|t| {
+ Ok((
+ t.name.clone(),
+ mesh(
+ &package,
+ &t.name,
+ package.layers.layers[&t.name],
+ r.mesh.tassel_cell,
+ false,
+ )?,
+ ))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let hand = if r.hand.is_some() {
+ let mesh = mesh(
+ &package,
+ "hand",
+ package.layers.layers["hand"],
+ r.mesh.hand_cell,
+ false,
+ )?;
+ let weights = mesh
+ .rest
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|&[x, y]| engine.hand_weights(x as f64, y as f64))
+ .collect();
+ Some(HandLayer { mesh, weights })
+ } else {
+ None
+ };
+ let physics = Physics::new(r);
+ Ok(Self {
+ package,
+ motion,
+ physics,
+ expression: ExpressionOverlay::default(),
+ options,
+ overrides: BTreeMap::new(),
+ parameter_weight: 1.0,
+ last_parameters: Parameters::default(),
+ base,
+ eyes,
+ sprites,
+ tassels,
+ hand,
+ })
+ }
+ pub fn motions(&self) -> &'static [MotionDefinition] {
+ motions()
+ }
+ pub fn package(&self) -> &AvatarPackage {
+ &self.package
+ }
+ pub fn textures(&self) -> &BTreeMap<String, Texture> {
+ &self.package.textures
+ }
+ pub fn parameters(&self) -> &Parameters {
+ &self.last_parameters
+ }
+ pub fn set_parameters(&mut self, values: BTreeMap<String, f64>) {
+ self.set_parameters_weighted(values, 1.0);
+ }
+ pub fn set_parameters_weighted(&mut self, values: BTreeMap<String, f64>, weight: f64) {
+ self.overrides = values;
+ self.parameter_weight = if weight.is_nan() {
+ 0.0
+ } else {
+ weight.clamp(0.0, 1.0)
+ };
+ }
+ pub fn set_voice_level(&mut self, value: f64) {
+ self.motion.set_voice_level(value);
+ }
+ pub fn set_speaking(&mut self, on: bool) {
+ self.motion.set_speaking(on);
+ }
+ pub fn set_emotion(&mut self, tag: &str) {
+ self.motion.set_emotion(tag, true);
+ }
+ pub fn set_emotion_with_motion(&mut self, tag: &str, play_motion: bool) {
+ self.motion.set_emotion(tag, play_motion);
+ }
+ pub fn set_expression(&mut self, name: &str) {
+ self.expression.set(name);
+ }
+ pub fn expression(&self) -> (&str, bool) {
+ (&self.expression.name, self.expression.active())
+ }
+ pub fn play(&mut self, id: &str) {
+ self.motion.play_motion(id);
+ }
+ pub fn speak_kana(&mut self, text: &str, options: SpeakOptions) {
+ self.motion.speak_kana(text, options);
+ }
+ pub fn hold_mouth(&mut self, vowel: Vowel) {
+ self.motion.hold_mouth(Some(vowel));
+ }
+ pub fn stop_lip_sync(&mut self) {
+ self.motion.stop_lip_sync();
+ }
+ pub fn lip_sync_state(&self) -> LipSyncState {
+ self.motion.lip_sync_state()
+ }
+ pub fn set_lip_sync(&mut self, settings: &LipSyncSettings) -> Result<()> {
+ self.motion.set_lip_sync(settings)
+ }
+ pub fn set_auto_idle(&mut self, on: bool) {
+ self.motion.auto_idle = on;
+ }
+ pub fn set_auto_motion(&mut self, on: bool) {
+ self.motion.auto_motion = on;
+ }
+ pub fn set_sway_gain(&mut self, gain: f64) {
+ self.physics.gain = if gain.is_nan() { 0.0 } else { gain.max(0.0) };
+ }
+ pub fn set_talk_gain(&mut self, gain: f64) {
+ self.motion.talk_gain = if gain.is_nan() { 0.0 } else { gain.max(0.0) };
+ }
+
+ fn update_parameters(&mut self, dt: f64) -> Parameters {
+ let mut p = self.motion.update(dt);
+ for (key, &value) in &self.overrides {
+ let original = p.get(key).unwrap_or(0.0);
+ p.set(
+ key,
+ if self.parameter_weight == 1.0 {
+ value
+ } else {
+ original + (value - original) * self.parameter_weight
+ },
+ );
+ }
+ if self.motion.lip_open.is_some() {
+ p.mouth_open = self.motion.parameters.mouth_open;
+ if !self.options.preserve_mouth_form || !self.overrides.contains_key("mouthForm") {
+ p.mouth_form = self.motion.parameters.mouth_form;
+ }
+ }
+ let out = self.expression.apply(&p, dt);
+ self.last_parameters = out.clone();
+ out
+ }
+ pub fn advance_parameters(&mut self, dt: f64) -> &Parameters {
+ self.update_parameters(if dt.is_finite() { dt.max(0.0) } else { 0.0 });
+ &self.last_parameters
+ }
+
+ /// Advance by caller-provided seconds, capped at 0.05 like the JS animation loop.
+ pub fn tick(&mut self, dt: f64) -> Frame {
+ let dt = if dt.is_nan() {
+ 0.0
+ } else {
+ dt.clamp(0.0, 0.05)
+ };
+ let p = self.update_parameters(dt);
+ let engine = RigEngine::new(&self.package.rig);
+ let phys = self.physics.step(&engine, &p, dt);
+ for (k, (rest, pos)) in self
+ .base
+ .mesh
+ .rest
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .zip(self.base.mesh.pos.as_chunks_mut::<2>().0)
+ .enumerate()
+ {
+ let q = engine.deform_base(
+ rest[0] as f64,
+ rest[1] as f64,
+ &self.base.weights[k],
+ &p,
+ phys,
+ );
+ *pos = q.map(|v| v as f32);
+ }
+ let has_sprites = self.sprites.is_some();
+ for eye in &mut self.eyes {
+ let open = if has_sprites {
+ 1.0
+ } else if eye.eye == 0 {
+ p.eye_r_open
+ } else {
+ p.eye_l_open
+ };
+ let smile = if eye.eye == 0 {
+ p.eye_smile
+ } else {
+ p.eye_smile_l.unwrap_or(p.eye_smile)
+ };
+ eye.alpha = eye_part_alpha(eye.part, open, smile);
+ for (k, (rest, pos)) in eye
+ .base
+ .mesh
+ .rest
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .zip(eye.base.mesh.pos.as_chunks_mut::<2>().0)
+ .enumerate()
+ {
+ let x = rest[0] as f64;
+ let y = eye_part_y(
+ &engine.rig.eyes[eye.eye],
+ eye.part,
+ x,
+ rest[1] as f64,
+ open,
+ smile,
+ );
+ *pos = engine
+ .deform_base(x, y, &eye.base.weights[k], &p, phys)
+ .map(|v| v as f32);
+ }
+ }
+ if let Some(sprites) = &mut self.sprites {
+ let mood = eye_mood(
+ Some(&self.expression.name),
+ if self.motion.mode == Mode::Manual {
+ None
+ } else {
+ Some(&self.motion.expr)
+ },
+ );
+ let covered = sprites.update(&engine, &p, phys, dt, mood);
+ for eye in &mut self.eyes {
+ if covered.eyes[eye.eye] {
+ eye.alpha = 0.0;
+ }
+ }
+ }
+ if let Some(hand) = &mut self.hand {
+ let frame = engine.hand_frame(&p);
+ for (k, (rest, pos)) in hand
+ .mesh
+ .rest
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .zip(hand.mesh.pos.as_chunks_mut::<2>().0)
+ .enumerate()
+ {
+ *pos = engine
+ .deform_hand(rest[0] as f64, rest[1] as f64, &hand.weights[k], &p, &frame)
+ .map(|v| v as f32);
+ }
+ }
+ for (chain, (_, mesh)) in self.physics.chains.iter().zip(&mut self.tassels) {
+ chain
+ .deform_grid(mesh)
+ .expect("physics initialized tassel joints");
+ }
+ let mut layers = vec![draw_layer(
+ "base",
+ "base.png".into(),
+ &self.base.mesh,
+ 1.0,
+ true,
+ None,
+ )];
+ for eye in &self.eyes {
+ layers.push(draw_layer(
+ &eye.base.name,
+ format!("{}.png", eye.base.name),
+ &eye.base.mesh,
+ eye.alpha,
+ false,
+ matches!(eye.part, EyePart::Ball).then_some(eye.eye),
+ ));
+ }
+ if let Some(sprites) = &self.sprites {
+ for sprite in &sprites.items {
+ if sprite.visible {
+ layers.push(draw_layer(
+ &sprite.name,
+ format!("sprites/{}.png", sprite.name),
+ &sprite.mesh,
+ sprite.alpha,
+ false,
+ None,
+ ));
+ }
+ }
+ }
+ for (name, mesh) in &self.tassels {
+ layers.push(draw_layer(
+ name,
+ format!("{name}.png"),
+ mesh,
+ 1.0,
+ false,
+ None,
+ ));
+ }
+ if let Some(hand) = &self.hand {
+ layers.push(draw_layer(
+ "hand",
+ "hand.png".into(),
+ &hand.mesh,
+ 1.0,
+ false,
+ None,
+ ));
+ }
+ let r = &self.package.rig;
+ let mouth = &r.mouth;
+ let uniforms = FaceUniforms {
+ angles: [p.angle_x as f32, p.angle_y as f32, p.angle_z as f32],
+ eye_box: r
+ .eyes
+ .each_ref()
+ .map(|e| [e.x0 as f32, e.x1 as f32, 0.0, 0.0]),
+ 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 },
+ 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 },
+ p.eye_smile_l.unwrap_or(p.eye_smile),
+ p.gaze_x * 7.0 * 0.85,
+ -p.gaze_y * 7.0 * 0.6,
+ ]
+ .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 },
+ p.mouth_form,
+ mouth.bow,
+ 0.0,
+ ]
+ .map(|v| v as f32),
+ cheeks: [
+ r.cheeks[0][0],
+ r.cheeks[0][1],
+ r.cheeks[1][0],
+ r.cheeks[1][1],
+ ]
+ .map(|v| v as f32),
+ cheek: p.blush as f32,
+ };
+ Frame {
+ layers,
+ uniforms,
+ motion_events: std::mem::take(&mut self.motion.motion_events),
+ }
+ }
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/expression.rs b/native/crates/mesh-avatar-core/src/engine/expression.rs
new file mode 100644
index 0000000..8a75ffa
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/expression.rs
@@ -0,0 +1,82 @@
+use super::{motion::expression_target, rig::Parameters};
+use std::collections::BTreeMap;
+
+pub const OVERLAY_EXPRESSIONS: &[(&str, &str)] = &[
+ ("neutral", "normal"),
+ ("smile", "smile"),
+ ("shy", "shy"),
+ ("surprise", "surprise"),
+ ("halfLidded", "jito"),
+ ("angry", "angryTalk"),
+ ("sad", "sadTalk"),
+ ("wink", "wink"),
+];
+pub fn overlay_target(name: &str) -> BTreeMap<String, f64> {
+ let expr = OVERLAY_EXPRESSIONS
+ .iter()
+ .find(|(n, _)| *n == name)
+ .map_or("normal", |(_, e)| *e);
+ let mut target = expression_target(expr);
+ target.remove("mouthForm");
+ target.insert("pitch".into(), if name == "sad" { -6.0 } else { 0.0 });
+ if name == "sad" {
+ target.insert("gy".into(), -0.45);
+ }
+ target
+}
+pub fn apply_overlay(p: &Parameters, m: &BTreeMap<String, f64>) -> Parameters {
+ let mut out = p.clone();
+ out.eye_r_open = p.eye_r_open * m["eyeOpen"];
+ out.eye_l_open = p.eye_l_open * m["eyeOpenL"];
+ out.eye_smile = p.eye_smile.max(m["eyeSmile"]);
+ out.eye_smile_l = Some(p.eye_smile_l.unwrap_or(p.eye_smile).max(m["eyeSmileL"]));
+ out.blush = p.blush.max(m["blush"]);
+ out.brow_y = (p.brow_y + m["browY"]).clamp(-1.0, 1.0);
+ out.brow_angle = (p.brow_angle + m["browAngle"]).clamp(-1.0, 1.0);
+ out.mouth_open = p.mouth_open.max(m["mouthOpen"]);
+ out.gaze_x = (p.gaze_x + m["gx"]).clamp(-1.0, 1.0);
+ out.gaze_y = (p.gaze_y + m["gy"]).clamp(-1.0, 1.0);
+ out.angle_y = (p.angle_y + m["pitch"]).clamp(-30.0, 30.0);
+ out
+}
+pub struct ExpressionOverlay {
+ pub name: String,
+ mix: BTreeMap<String, f64>,
+}
+impl Default for ExpressionOverlay {
+ fn default() -> Self {
+ Self {
+ name: "neutral".into(),
+ mix: overlay_target("neutral"),
+ }
+ }
+}
+impl ExpressionOverlay {
+ pub fn set(&mut self, name: &str) {
+ self.name = if OVERLAY_EXPRESSIONS.iter().any(|(n, _)| *n == name) {
+ name
+ } else {
+ "neutral"
+ }
+ .into();
+ }
+ pub fn active(&self) -> bool {
+ self.name != "neutral"
+ || overlay_target("neutral")
+ .iter()
+ .any(|(key, value)| (self.mix[key] - value).abs() > 1e-3)
+ }
+ pub fn apply(&mut self, p: &Parameters, dt: f64) -> Parameters {
+ if !self.active() {
+ self.mix = overlay_target("neutral");
+ return p.clone();
+ }
+ let target = overlay_target(&self.name);
+ let k = 1.0 - (-dt.max(0.0) * 12.0).exp();
+ for (key, value) in target {
+ let mix = self.mix.get_mut(&key).unwrap();
+ *mix += (value - *mix) * k;
+ }
+ apply_overlay(p, &self.mix)
+ }
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/kana.rs b/native/crates/mesh-avatar-core/src/engine/kana.rs
new file mode 100644
index 0000000..4a538d7
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/kana.rs
@@ -0,0 +1,214 @@
+//! Kana-to-mora timing without audio or external text processing.
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Vowel {
+ A,
+ I,
+ U,
+ E,
+ O,
+ N,
+}
+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+pub struct MouthTarget {
+ pub open: f64,
+ pub form: Option<f64>,
+ pub vowel: Vowel,
+}
+impl Vowel {
+ pub fn parse(name: &str) -> Option<Self> {
+ match name {
+ "a" => Some(Self::A),
+ "i" => Some(Self::I),
+ "u" => Some(Self::U),
+ "e" => Some(Self::E),
+ "o" => Some(Self::O),
+ "n" => Some(Self::N),
+ _ => None,
+ }
+ }
+ pub fn target(self) -> MouthTarget {
+ let (open, form) = match self {
+ Self::A => (0.9, Some(0.0)),
+ Self::I => (0.5, Some(-0.85)),
+ Self::U => (0.4, Some(0.9)),
+ Self::E => (0.62, Some(-0.4)),
+ Self::O => (0.75, Some(0.6)),
+ Self::N => (0.0, None),
+ };
+ MouthTarget {
+ open,
+ form,
+ vowel: self,
+ }
+ }
+}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Onset {
+ Lips,
+ Consonant,
+}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Mora {
+ pub vowel: Vowel,
+ pub dur: f64,
+ pub onset: Option<Onset>,
+}
+fn hiragana(c: char) -> char {
+ if ('ァ'..='ヶ').contains(&c) {
+ char::from_u32(c as u32 - 0x60).unwrap()
+ } else {
+ c
+ }
+}
+fn vowel_of(c: char) -> Option<Vowel> {
+ [
+ (Vowel::A, "あかさたなはまやらわがざだばぱぁ"),
+ (Vowel::I, "いきしちにひみりぎじぢびぴぃ"),
+ (Vowel::U, "うくすつぬふむゆるぐずづぶぷぅゔ"),
+ (Vowel::E, "えけせてねへめれげぜでべぺぇ"),
+ (Vowel::O, "おこそとのほもよろをごぞどぼぽぉ"),
+ ]
+ .into_iter()
+ .find(|(_, row)| row.contains(c))
+ .map(|(v, _)| v)
+}
+fn small_y(c: char) -> Option<Vowel> {
+ match c {
+ 'ゃ' => Some(Vowel::A),
+ 'ゅ' => Some(Vowel::U),
+ 'ょ' => Some(Vowel::O),
+ _ => None,
+ }
+}
+fn pause(c: char) -> bool {
+ "、。,.,.!?!?  …".contains(c)
+}
+pub fn skipped_kana_characters(text: &str) -> Vec<char> {
+ let mut out = vec![];
+ for c in text.chars().map(hiragana) {
+ if vowel_of(c).is_none()
+ && small_y(c).is_none()
+ && !matches!(c, 'ー' | 'っ' | 'ん')
+ && !pause(c)
+ && !out.contains(&c)
+ {
+ out.push(c);
+ }
+ }
+ out
+}
+pub fn kana_to_moras(text: &str, mora: f64) -> Vec<Mora> {
+ let mut out: Vec<Mora> = vec![];
+ for c in text.chars().map(hiragana) {
+ if let Some(last) = out.last_mut() {
+ if let Some(v) = small_y(c) {
+ last.vowel = v;
+ continue;
+ }
+ if c == 'ー' {
+ last.dur += mora;
+ continue;
+ }
+ }
+ if matches!(c, 'っ' | 'ん') || pause(c) {
+ out.push(Mora {
+ vowel: Vowel::N,
+ dur: mora
+ * if c == 'っ' {
+ 0.8
+ } else if c == 'ん' {
+ 1.0
+ } else {
+ 2.2
+ },
+ onset: None,
+ });
+ continue;
+ }
+ if let Some(vowel) = vowel_of(c) {
+ let onset = if "まみむめもばびぶべぼぱぴぷぺぽ".contains(c) {
+ Some(Onset::Lips)
+ } else if "あいうえおぁぃぅぇぉ".contains(c) {
+ None
+ } else {
+ Some(Onset::Consonant)
+ };
+ out.push(Mora {
+ vowel,
+ dur: mora,
+ onset,
+ });
+ }
+ }
+ out
+}
+pub fn sample_moras(moras: &[Mora], t: f64, granularity: f64) -> Option<MouthTarget> {
+ let grouped = granularity != 0.5;
+ let group_seconds = if granularity < 0.5 {
+ (0.5 - granularity) * 0.72
+ } else {
+ 0.0
+ };
+ let mut start = 0.0;
+ let mut group_duration = 0.0;
+ let mut group_vowel = None;
+ for m in moras {
+ let mut vowel = m.vowel;
+ if grouped {
+ if m.vowel == Vowel::N {
+ if let Some(group) = group_vowel.filter(|_| group_seconds != 0.0 && m.dur <= 0.2) {
+ vowel = group;
+ } else {
+ group_duration = 0.0;
+ group_vowel = None;
+ }
+ } else {
+ if group_vowel.is_none() || group_duration >= group_seconds {
+ group_vowel = Some(m.vowel);
+ group_duration = 0.0;
+ }
+ group_duration += m.dur;
+ if group_seconds != 0.0 {
+ vowel = group_vowel.unwrap();
+ }
+ }
+ }
+ if t < start + m.dur {
+ let mut target = vowel.target();
+ let original = match m.onset {
+ Some(Onset::Lips) => 0.05,
+ Some(Onset::Consonant) => 0.45,
+ None => 1.0,
+ };
+ let k = if grouped {
+ let onset = if granularity < 0.5 {
+ 1.0 - (1.0 - original) * granularity * 2.0
+ } else {
+ original * (2.0 - granularity * 2.0)
+ };
+ let attack = (m.dur * 0.35).min(0.05);
+ let x = (t - start) / attack;
+ if x < 1.0 {
+ onset + (1.0 - onset) * x
+ } else {
+ 1.0
+ }
+ } else {
+ let x = (t - start) / m.dur;
+ if x < 0.35 {
+ original + (1.0 - original) * (x / 0.35)
+ } else {
+ 1.0
+ }
+ };
+ target.open *= k;
+ return Some(target);
+ }
+ start += m.dur;
+ }
+ None
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/lip_sync.rs b/native/crates/mesh-avatar-core/src/engine/lip_sync.rs
new file mode 100644
index 0000000..6a1aa24
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/lip_sync.rs
@@ -0,0 +1,112 @@
+use anyhow::{ensure, Result};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LipSyncSettings {
+ pub granularity: Option<f64>,
+ pub openness: Option<f64>,
+ pub close_speed: Option<f64>,
+ pub preset: Option<String>,
+}
+impl LipSyncSettings {
+ pub fn parse(value: &serde_json::Value) -> Result<Self> {
+ ensure!(value.is_object(), "lipSync: expected an object");
+ for key in ["granularity", "openness", "closeSpeed"] {
+ if let Some(v) = value.get(key) {
+ ensure!(
+ v.as_f64()
+ .is_some_and(|n| n.is_finite() && (0.0..=1.0).contains(&n)),
+ "lipSync.{key}: expected 0–1"
+ );
+ }
+ }
+ if let Some(v) = value.get("preset") {
+ ensure!(
+ v.as_str().is_some_and(|s| matches!(
+ s,
+ "calm" | "default" | "lively" | "subtle" | "big" | "custom"
+ )),
+ "lipSync.preset: invalid preset"
+ );
+ }
+ Ok(serde_json::from_value(value.clone())?)
+ }
+ pub fn resolve(&self, base: ResolvedLipSync) -> Result<ResolvedLipSync> {
+ for v in [self.granularity, self.openness, self.close_speed]
+ .into_iter()
+ .flatten()
+ {
+ ensure!(
+ v.is_finite() && (0.0..=1.0).contains(&v),
+ "lipSync: expected 0–1"
+ );
+ }
+ if let Some(p) = &self.preset {
+ ensure!(
+ matches!(
+ p.as_str(),
+ "calm" | "default" | "lively" | "subtle" | "big" | "custom"
+ ),
+ "lipSync.preset: invalid preset"
+ );
+ }
+ Ok(ResolvedLipSync {
+ granularity: self.granularity.unwrap_or(base.granularity),
+ openness: self.openness.unwrap_or(base.openness),
+ close_speed: self.close_speed.unwrap_or(base.close_speed),
+ })
+ }
+}
+#[derive(Debug, Clone, Copy, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ResolvedLipSync {
+ pub granularity: f64,
+ pub openness: f64,
+ pub close_speed: f64,
+}
+impl Default for ResolvedLipSync {
+ fn default() -> Self {
+ Self {
+ granularity: 0.5,
+ openness: 0.5,
+ close_speed: 0.5,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct LipMotionOptions {
+ pub arm: f64,
+ pub trigger: f64,
+ pub relax: f64,
+ pub range: f64,
+ pub rise_power: f64,
+ pub openness: f64,
+ pub audio_release: f64,
+ pub kana_release: f64,
+}
+fn centered(value: f64, low: f64, center: f64, high: f64) -> f64 {
+ if value == 0.5 {
+ center
+ } else if value < 0.5 {
+ low + (center - low) * value * 2.0
+ } else {
+ center + (high - center) * (value - 0.5) * 2.0
+ }
+}
+impl ResolvedLipSync {
+ pub fn motion_options(self) -> LipMotionOptions {
+ let g = self.granularity;
+ LipMotionOptions {
+ arm: centered(g, 0.2, 0.6, 0.9),
+ trigger: centered(g, 0.65, 0.8, 0.95),
+ relax: centered(g, 1.5, 5.0, 12.0),
+ range: centered(g, 0.7, 0.3, 0.05),
+ rise_power: centered(g, 0.05, 0.3, 0.8),
+ openness: centered(self.openness, 0.55, 1.0, 1.25),
+ audio_release: centered(self.close_speed, 6.0, 32.0, 45.0),
+ kana_release: centered(self.close_speed, 6.0, 22.0, 45.0),
+ }
+ }
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/mod.rs b/native/crates/mesh-avatar-core/src/engine/mod.rs
index 8e28625..5e84a79 100644
--- a/native/crates/mesh-avatar-core/src/engine/mod.rs
+++ b/native/crates/mesh-avatar-core/src/engine/mod.rs
@@ -1,4 +1,10 @@
+pub mod expression;
pub mod grid;
+pub mod kana;
+pub mod lip_sync;
+pub mod motion;
+pub mod motions;
pub mod physics;
+pub mod random;
pub mod rig;
pub mod sprites;
diff --git a/native/crates/mesh-avatar-core/src/engine/motion.rs b/native/crates/mesh-avatar-core/src/engine/motion.rs
new file mode 100644
index 0000000..7fb8e8e
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/motion.rs
@@ -0,0 +1,724 @@
+//! Idle, gaze, blinking, reactions, speech and spring-smoothed parameters.
+use super::{
+ kana::{kana_to_moras, sample_moras, Mora, Vowel},
+ lip_sync::{LipMotionOptions, LipSyncSettings, ResolvedLipSync},
+ motions::{data, find_motion, motions, sample_track},
+ random::{RandomSource, SeededRandom},
+ rig::{sstep, Parameters, PARAMS},
+};
+use crate::rig::Point;
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Mode {
+ Auto,
+ Mouse,
+ Manual,
+}
+struct Blink {
+ t: f64,
+ start: f64,
+ double: bool,
+}
+struct Gaze {
+ x: f64,
+ y: f64,
+ next: f64,
+}
+struct Tap {
+ next: f64,
+ until: f64,
+}
+pub struct Playback {
+ pub id: String,
+ pub t: f64,
+}
+struct Kana {
+ moras: Vec<Mora>,
+ t: f64,
+ looping: bool,
+ duration: f64,
+}
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(default)]
+pub struct SpeakOptions {
+ pub speed: Option<f64>,
+ #[serde(rename = "loop")]
+ pub looping: bool,
+}
+#[derive(Debug, Serialize)]
+pub struct LipSyncState {
+ pub active: bool,
+ pub open: f64,
+ pub form: f64,
+}
+
+pub struct Motion {
+ pub mode: Mode,
+ pub parameters: Parameters,
+ pub manual: Parameters,
+ pub expr: String,
+ pub t: f64,
+ pub pointer: Option<Point>,
+ pub face_center: Point,
+ pub lip_open: Option<f64>,
+ pub lip_form: f64,
+ pub speaking: bool,
+ pub voice: f64,
+ pub talk_gain: f64,
+ pub play: Option<Playback>,
+ pub auto_motion: bool,
+ pub auto_idle: bool,
+ pub lip_sync: ResolvedLipSync,
+ pub motion_events: Vec<Option<String>>,
+ cur: Parameters,
+ vel: Parameters,
+ expr_mix: BTreeMap<String, f64>,
+ blink: Blink,
+ gaze: Gaze,
+ tap: Tap,
+ mouth: f64,
+ vowel: Vowel,
+ vowel_form: f64,
+ lip_motion: LipMotionOptions,
+ syllable_armed: bool,
+ voice_peak: f64,
+ voice_trough: f64,
+ kana: Option<Kana>,
+ lip_hold: Option<Vowel>,
+ emotion_until: f64,
+ next_auto: f64,
+ next_idle: f64,
+ last_auto: Option<String>,
+ breath_phase: f64,
+ breath_period: f64,
+ talk_nod: f64,
+ rng: Box<dyn RandomSource>,
+}
+
+fn noise(t: f64, seed: f64) -> f64 {
+ let i = t.floor();
+ let f = t - i;
+ let h = |n: f64| {
+ let x = ((n + seed * 57.3) * 127.1).sin() * 43758.5453;
+ x - x.floor()
+ };
+ let u = f * f * (3.0 - 2.0 * f);
+ (h(i) * (1.0 - u) + h(i + 1.0) * u) * 2.0 - 1.0
+}
+fn fbm(t: f64, s: f64) -> f64 {
+ noise(t, s) * 0.7 + noise(t * 2.3, s + 9.0) * 0.3
+}
+fn face_track(id: &str) -> bool {
+ matches!(
+ id,
+ "eyeOpen"
+ | "eyeOpenL"
+ | "eyeSmileL"
+ | "eyeSmile"
+ | "mouthOpen"
+ | "mouthForm"
+ | "blush"
+ | "browY"
+ | "browAngle"
+ )
+}
+
+pub(crate) fn expression_target(expr: &str) -> BTreeMap<String, f64> {
+ let e = &data()
+ .expressions
+ .get(expr)
+ .unwrap_or(&data().expressions["normal"])
+ .p;
+ let get = |key: &str, default: f64| {
+ e.get(key)
+ .and_then(serde_json::Value::as_f64)
+ .unwrap_or(default)
+ };
+ let eye = get("eyeOpen", 1.0);
+ let smile = get("eyeSmile", 0.0);
+ let glance = e.get("glance").and_then(serde_json::Value::as_array);
+ BTreeMap::from([
+ ("eyeOpen".into(), eye),
+ ("eyeOpenL".into(), get("eyeOpenL", eye)),
+ ("eyeSmile".into(), smile),
+ ("eyeSmileL".into(), get("eyeSmileL", smile)),
+ ("mouthOpen".into(), get("mouthOpen", 0.0)),
+ ("mouthForm".into(), get("mouthForm", 0.0)),
+ ("blush".into(), get("blush", 0.0)),
+ ("browY".into(), get("browY", 0.0)),
+ ("browAngle".into(), get("browAngle", 0.0)),
+ (
+ "gx".into(),
+ glance
+ .and_then(|v| v.first())
+ .and_then(serde_json::Value::as_f64)
+ .unwrap_or(0.0),
+ ),
+ (
+ "gy".into(),
+ glance
+ .and_then(|v| v.get(1))
+ .and_then(serde_json::Value::as_f64)
+ .unwrap_or(0.0),
+ ),
+ ])
+}
+
+impl Motion {
+ /// Default to seed zero; all randomness can be supplied by the caller.
+ pub fn new(gaze_center: Point) -> Self {
+ Self::with_rng(gaze_center, Box::new(SeededRandom::new(0)))
+ }
+ pub fn with_rng(face_center: Point, rng: Box<dyn RandomSource>) -> Self {
+ let p = Parameters::default();
+ let mut vel = p.clone();
+ for param in PARAMS {
+ vel.set(param.id, 0.0);
+ }
+ let lip_sync = ResolvedLipSync::default();
+ Self {
+ mode: Mode::Auto,
+ parameters: p.clone(),
+ manual: p.clone(),
+ cur: p,
+ vel,
+ expr: "normal".into(),
+ expr_mix: BTreeMap::new(),
+ t: 0.0,
+ blink: Blink {
+ t: 0.0,
+ start: 1.5,
+ double: false,
+ },
+ gaze: Gaze {
+ x: 0.0,
+ y: 0.0,
+ next: 0.0,
+ },
+ tap: Tap {
+ next: 4.0,
+ until: -1.0,
+ },
+ pointer: None,
+ face_center,
+ lip_open: None,
+ lip_form: 0.0,
+ speaking: false,
+ voice: 0.0,
+ mouth: 0.0,
+ vowel: Vowel::A,
+ vowel_form: 0.0,
+ lip_sync,
+ lip_motion: lip_sync.motion_options(),
+ syllable_armed: true,
+ voice_peak: 0.0,
+ voice_trough: 0.0,
+ kana: None,
+ lip_hold: None,
+ emotion_until: 0.0,
+ talk_gain: 1.0,
+ play: None,
+ auto_motion: true,
+ next_auto: 14.0,
+ auto_idle: true,
+ next_idle: 3.0,
+ last_auto: None,
+ motion_events: vec![],
+ breath_phase: 0.0,
+ breath_period: 3.8,
+ talk_nod: 0.0,
+ rng,
+ }
+ }
+ pub fn set_expression(&mut self, name: &str) {
+ self.expr = if data().expressions.contains_key(name) {
+ name
+ } else {
+ "normal"
+ }
+ .into();
+ }
+ pub fn set_voice_level(&mut self, v: f64) {
+ self.voice = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) };
+ }
+ pub fn set_lip_sync(&mut self, settings: &LipSyncSettings) -> Result<()> {
+ self.lip_sync = settings.resolve(self.lip_sync)?;
+ self.lip_motion = self.lip_sync.motion_options();
+ Ok(())
+ }
+ pub fn set_speaking(&mut self, on: bool) {
+ if on == self.speaking {
+ return;
+ }
+ self.speaking = on;
+ if !on {
+ self.emotion_until = self.t + 1.2;
+ self.voice = 0.0;
+ }
+ }
+ pub fn set_emotion(&mut self, tag: &str, play_motion: bool) {
+ let (expr, motion) = match tag {
+ "happy" => ("happyTalk", Some("nod")),
+ "sad" => ("sadTalk", Some("sigh")),
+ "angry" => ("angryTalk", Some("no")),
+ "surprised" => ("surprisedTalk", Some("surprise")),
+ "relaxed" => ("relaxedTalk", Some("sway")),
+ _ => ("normal", None),
+ };
+ self.expr = expr.into();
+ self.emotion_until = f64::INFINITY;
+ if play_motion {
+ if let Some(id) = motion {
+ self.play_motion(id);
+ }
+ }
+ }
+ pub fn speak_kana(&mut self, text: &str, options: SpeakOptions) {
+ self.lip_hold = None;
+ let mora = options.speed.map_or(0.14, |speed| {
+ 1.0 / (if speed == 0.0 || speed.is_nan() {
+ 7.0
+ } else {
+ speed
+ })
+ .clamp(4.0, 12.0)
+ });
+ let moras = kana_to_moras(text, mora);
+ let duration = moras.iter().map(|m| m.dur).sum();
+ self.kana = if moras.is_empty() {
+ None
+ } else {
+ Some(Kana {
+ moras,
+ t: 0.0,
+ looping: options.looping,
+ duration,
+ })
+ };
+ }
+ pub fn hold_mouth(&mut self, vowel: Option<Vowel>) {
+ self.kana = None;
+ self.lip_hold = vowel;
+ }
+ pub fn stop_lip_sync(&mut self) {
+ self.kana = None;
+ self.lip_hold = None;
+ self.lip_open = None;
+ self.mouth = 0.0;
+ }
+ pub fn lip_sync_state(&self) -> LipSyncState {
+ LipSyncState {
+ active: self.kana.is_some() || self.lip_hold.is_some(),
+ open: self.parameters.mouth_open,
+ form: self.parameters.mouth_form,
+ }
+ }
+ pub fn play_motion(&mut self, id: &str) {
+ if find_motion(id).is_none() {
+ return;
+ }
+ self.last_auto = Some(id.into());
+ self.play = Some(Playback {
+ id: id.into(),
+ t: 0.0,
+ });
+ self.motion_events.push(Some(id.into()));
+ }
+ fn play_random(&mut self, idle: bool) {
+ let pool: Vec<_> = motions()
+ .iter()
+ .filter(|m| {
+ m.idle == idle
+ && (idle || m.id != "surprise")
+ && Some(m.id.as_str()) != self.last_auto.as_deref()
+ })
+ .collect();
+ let index = (self.rng.next_f64() * pool.len() as f64).floor() as usize;
+ if let Some(m) = pool.get(index) {
+ self.play_motion(&m.id);
+ }
+ }
+ fn speech_mouth(&mut self, dt: f64) -> Option<Point> {
+ if self.kana.is_some() || self.lip_hold.is_some() {
+ let m = if let Some(v) = self.lip_hold {
+ Some(v.target())
+ } else {
+ let kana = self.kana.as_mut().unwrap();
+ kana.t += dt;
+ if kana.looping {
+ kana.t %= kana.duration;
+ }
+ sample_moras(&kana.moras, kana.t, self.lip_sync.granularity)
+ };
+ let Some(m) = m else {
+ self.kana = None;
+ return if self.mouth > 0.01 {
+ self.mouth *= if self.lip_sync.close_speed == 0.5 {
+ 0.6
+ } else {
+ (-dt * self.lip_motion.kana_release).exp()
+ };
+ Some([self.mouth, self.vowel_form])
+ } else {
+ None
+ };
+ };
+ let target = if self.lip_motion.openness == 1.0 {
+ m.open
+ } else {
+ (m.open * self.lip_motion.openness).min(1.0)
+ };
+ let k = 1.0
+ - (-dt
+ * if target > self.mouth {
+ 30.0
+ } else {
+ self.lip_motion.kana_release
+ })
+ .exp();
+ self.mouth += (target - self.mouth) * k;
+ if let Some(form) = m.form {
+ self.vowel_form = form;
+ }
+ return Some([self.mouth, self.vowel_form]);
+ }
+ let v = if self.speaking { self.voice } else { 0.0 };
+ let relax = 1.0 - (-dt * self.lip_motion.relax).exp();
+ self.voice_peak = if v > self.voice_peak {
+ v
+ } else {
+ self.voice_peak + (v - self.voice_peak) * relax
+ };
+ self.voice_trough = if v < self.voice_trough {
+ v
+ } else {
+ self.voice_trough + (v - self.voice_trough) * relax
+ };
+ let peak = self.voice_peak.max(0.05);
+ if v < peak * self.lip_motion.arm {
+ self.syllable_armed = true;
+ } else if self.syllable_armed && v > peak * self.lip_motion.trigger && v > 0.1 {
+ self.syllable_armed = false;
+ let r = self.rng.next_f64();
+ self.vowel = if r < 0.4 {
+ Vowel::A
+ } else if r < 0.58 {
+ Vowel::O
+ } else if r < 0.74 {
+ Vowel::E
+ } else if r < 0.88 {
+ Vowel::I
+ } else {
+ Vowel::U
+ };
+ }
+ let range = self.voice_peak - self.voice_trough;
+ let rise = if range < peak * self.lip_motion.range {
+ 1.0
+ } else {
+ ((v - self.voice_trough) / range).max(0.0)
+ };
+ let shape = self.vowel.target();
+ let level = (v.powf(0.7) * 1.15).min(1.0) * rise.powf(self.lip_motion.rise_power);
+ let base_target = if self.speaking {
+ level.min(0.95) * (0.45 + 0.55 * shape.open / 0.9)
+ } else {
+ 0.0
+ };
+ let target = if self.lip_motion.openness == 1.0 {
+ base_target
+ } else {
+ (base_target * self.lip_motion.openness).min(1.0)
+ };
+ let k = 1.0
+ - (-dt
+ * if target > self.mouth {
+ 40.0
+ } else {
+ self.lip_motion.audio_release
+ })
+ .exp();
+ self.mouth += (target - self.mouth) * k;
+ if self.speaking {
+ self.vowel_form = shape.form.unwrap();
+ }
+ if self.speaking || self.mouth > 0.01 {
+ Some([self.mouth, self.vowel_form])
+ } else {
+ None
+ }
+ }
+ fn breath_value(&mut self, dt: f64) -> f64 {
+ self.breath_phase += dt / self.breath_period;
+ if self.breath_phase >= 1.0 {
+ self.breath_phase -= 1.0;
+ self.breath_period = 3.2 + self.rng.next_f64() * 1.4;
+ }
+ let x = self.breath_phase;
+ if x < 0.4 {
+ sstep(0.0, 0.4, x)
+ } else if x < 0.88 {
+ 1.0 - sstep(0.4, 0.88, x)
+ } else {
+ 0.0
+ }
+ }
+ fn blink_value(&mut self, dt: f64) -> f64 {
+ let b = &mut self.blink;
+ b.t += dt;
+ if b.t < b.start {
+ return 1.0;
+ }
+ let x = (b.t - b.start) / 0.17;
+ if x >= 1.0 {
+ if b.double {
+ b.double = false;
+ b.start = b.t + 0.07;
+ } else {
+ b.start = b.t + 1.8 + self.rng.next_f64() * 4.2;
+ b.double = self.rng.next_f64() < 0.18;
+ }
+ return 1.0;
+ }
+ if x < 0.45 {
+ 1.0 - x / 0.45
+ } else {
+ (x - 0.45) / 0.55
+ }
+ }
+ pub fn update(&mut self, dt: f64) -> Parameters {
+ self.t += dt;
+ let t = self.t;
+ let mut target = Parameters::default();
+ match self.mode {
+ Mode::Manual => target = self.manual.clone(),
+ Mode::Auto => {
+ target.angle_x = fbm(t * 0.18, 1.0) * 10.0 + self.gaze.x * 11.0;
+ target.angle_y = fbm(t * 0.15, 2.0) * 6.0 - 1.0 + self.gaze.y * 7.0;
+ target.angle_z = fbm(t * 0.12, 3.0) * 10.0;
+ target.body_angle_x = fbm(t * 0.1, 4.0) * 5.0;
+ target.body_angle_z = fbm(t * 0.09, 5.0) * 4.0;
+ target.arm_angle = fbm(t * 0.14, 6.0) * 5.0;
+ target.hand_angle = fbm(t * 0.21, 7.0) * 5.0;
+ if t > self.gaze.next {
+ let r = self.rng.next_f64();
+ self.gaze.x = if r < 0.45 {
+ 0.0
+ } else {
+ (self.rng.next_f64() * 2.0 - 1.0) * 0.8
+ };
+ self.gaze.y = if r < 0.45 {
+ 0.0
+ } else {
+ (self.rng.next_f64() * 2.0 - 1.0) * 0.5
+ };
+ self.gaze.next = t + 0.8 + self.rng.next_f64() * 2.5;
+ }
+ target.gaze_x = self.gaze.x + target.angle_x / 60.0;
+ target.gaze_y = self.gaze.y + target.angle_y / 60.0;
+ if t > self.tap.next {
+ self.tap.until = t + 1.1;
+ self.tap.next = t + 5.0 + self.rng.next_f64() * 6.0;
+ }
+ if self.speaking {
+ self.next_idle = self.next_idle.max(t + 2.5);
+ self.next_auto = self.next_auto.max(t + 6.0);
+ let g = self.talk_gain;
+ self.talk_nod += (self.voice * 7.0 * g - self.talk_nod) * (dt * 6.0).min(1.0);
+ target.angle_y -= self.talk_nod;
+ target.angle_x += fbm(t * 0.6, 11.0) * 5.0 * g;
+ target.angle_z += fbm(t * 0.5, 12.0) * 4.0 * g;
+ }
+ if !self.speaking && t > self.emotion_until {
+ self.expr = "normal".into();
+ self.emotion_until = f64::INFINITY;
+ }
+ if !self.speaking {
+ if self.play.is_none() && self.auto_motion && t > self.next_auto {
+ self.play_random(false);
+ self.next_auto = t + 15.0 + self.rng.next_f64() * 10.0;
+ self.next_idle = self.next_idle.max(t + 5.0);
+ } else if self.play.is_none() && self.auto_idle && t > self.next_idle {
+ self.play_random(true);
+ self.next_idle = t + 5.0 + self.rng.next_f64() * 5.0;
+ }
+ }
+ }
+ Mode::Mouse => {
+ if let Some(pointer) = self.pointer {
+ let dx = (pointer[0] - self.face_center[0]) / 500.0;
+ let dy = (pointer[1] - self.face_center[1]) / 500.0;
+ target.angle_x = (dx * 30.0).clamp(-30.0, 30.0);
+ target.angle_y = (-dy * 30.0).clamp(-30.0, 30.0);
+ target.angle_z = (-dx * dy * 25.0).clamp(-12.0, 12.0);
+ target.body_angle_x = (dx * 10.0).clamp(-10.0, 10.0) * 0.6;
+ target.gaze_x = (dx * 1.4).clamp(-1.0, 1.0);
+ target.gaze_y = (-dy * 1.4).clamp(-1.0, 1.0);
+ target.hand_angle = (dx * 4.0).clamp(-5.0, 5.0);
+ }
+ }
+ }
+ if self.mode != Mode::Manual {
+ target.breath = self.breath_value(dt);
+ if t < self.tap.until {
+ target.finger_tap = ((self.tap.until - t) * std::f64::consts::PI * 3.6)
+ .sin()
+ .max(0.0)
+ .powi(2);
+ }
+ }
+ let mut tracks = None;
+ let mut mw = 0.0;
+ let mut idle = false;
+ if let Some(play) = &mut self.play {
+ let def = find_motion(&play.id).unwrap();
+ play.t += dt;
+ if play.t >= def.dur {
+ self.play = None;
+ self.motion_events.push(None);
+ } else {
+ idle = def.idle;
+ let m: BTreeMap<_, _> = def
+ .tracks
+ .iter()
+ .map(|(id, keys)| (id.clone(), sample_track(keys, play.t)))
+ .collect();
+ mw = sstep(0.0, 0.15, play.t) * (1.0 - sstep(def.dur - 0.25, def.dur, play.t));
+ for (id, &v) in &m {
+ let current = target.get(id).unwrap_or(0.0);
+ if data().additive.contains(id) {
+ target.set(id, current + v);
+ } else if id == "breath" {
+ target.set(id, current + (v - current) * mw);
+ } else if !face_track(id) {
+ target.set(id, current.max(v.max(0.0)));
+ }
+ }
+ tracks = Some(m);
+ }
+ }
+ if self.mode != Mode::Manual {
+ target.angle_y += target.breath * 1.6;
+ }
+ let expr_target = expression_target(&self.expr);
+ let k = 1.0 - (-dt * 9.0).exp();
+ for (key, value) in expr_target {
+ let mix = self.expr_mix.entry(key).or_insert(value);
+ *mix += (value - *mix) * k;
+ }
+ let mut out = Parameters::default();
+ for param in PARAMS {
+ let id = param.id;
+ let value = target.get(id).unwrap();
+ if self.mode == Mode::Manual && tracks.is_none() {
+ out.set(id, value);
+ self.cur.set(id, value);
+ self.vel.set(id, 0.0);
+ continue;
+ }
+ let (mut stiff, mut zeta) = match id {
+ "gazeX" | "gazeY" => (260.0_f64, 0.9),
+ "angleX" | "angleY" => (55.0, 0.72),
+ "angleZ" => (45.0, 0.75),
+ "bodyAngleX" => (14.0, 0.9),
+ "bodyAngleZ" => (12.0, 0.9),
+ "armAngle" => (20.0, 0.85),
+ "handAngle" => (30.0, 0.8),
+ _ => (120.0, 0.95),
+ };
+ if tracks.is_some() && (id.starts_with("angle") || id.starts_with("body")) {
+ if idle {
+ stiff *= 1.8;
+ zeta = 0.8;
+ } else if id.starts_with("angle") {
+ stiff *= 4.5;
+ zeta = 0.75;
+ }
+ }
+ let damp = 2.0 * stiff.sqrt() * zeta;
+ let mut velocity = self.vel.get(id).unwrap();
+ let mut current = self.cur.get(id).unwrap();
+ velocity += (stiff * (value - current) - damp * velocity) * dt;
+ current += velocity * dt;
+ self.vel.set(id, velocity);
+ self.cur.set(id, current);
+ out.set(id, current);
+ }
+ let mut blink = 1.0;
+ if self.mode != Mode::Manual {
+ blink = self.blink_value(dt);
+ let x = &self.expr_mix;
+ out.eye_r_open = x["eyeOpen"] * blink;
+ out.eye_l_open = x["eyeOpenL"] * blink;
+ out.eye_smile = x["eyeSmile"];
+ out.eye_smile_l = Some(x["eyeSmileL"]);
+ out.mouth_open = x["mouthOpen"];
+ out.mouth_form = x["mouthForm"];
+ out.blush = x["blush"];
+ out.brow_y = x["browY"]
+ + if out.angle_y > 0.0 {
+ out.angle_y / 60.0
+ } else {
+ 0.0
+ }
+ - (1.0 - blink) * 0.18;
+ out.brow_angle = x["browAngle"];
+ out.gaze_x = (out.gaze_x + x["gx"]).clamp(-1.0, 1.0);
+ out.gaze_y = (out.gaze_y + x["gy"]).clamp(-1.0, 1.0);
+ } else {
+ out.eye_smile_l = Some(out.eye_smile);
+ }
+ if let Some(m) = tracks {
+ let mut mix = |key: &str, v: f64| {
+ let current = out.get(key).unwrap();
+ out.set(key, current + (v - current) * mw);
+ };
+ if let Some(&v) = m.get("eyeOpen") {
+ mix("eyeROpen", v.clamp(0.0, 1.3) * blink);
+ if !m.contains_key("eyeOpenL") {
+ mix("eyeLOpen", v.clamp(0.0, 1.3) * blink);
+ }
+ }
+ if let Some(&v) = m.get("eyeOpenL") {
+ mix("eyeLOpen", v.clamp(0.0, 1.3) * blink);
+ }
+ if let Some(&v) = m.get("eyeSmile") {
+ mix("eyeSmile", v);
+ if !m.contains_key("eyeSmileL") {
+ mix("eyeSmileL", v);
+ }
+ }
+ if let Some(&v) = m.get("eyeSmileL") {
+ mix("eyeSmileL", v);
+ }
+ for id in ["mouthOpen", "mouthForm", "blush", "browY", "browAngle"] {
+ if let Some(&v) = m.get(id) {
+ mix(
+ id,
+ if matches!(id, "mouthOpen" | "blush") {
+ v.max(0.0)
+ } else {
+ v
+ },
+ );
+ }
+ }
+ }
+ if let Some(sm) = self.speech_mouth(dt) {
+ self.lip_open = Some(sm[0]);
+ self.lip_form = sm[1];
+ } else if self.lip_open.is_some() && !self.speaking && self.kana.is_none() {
+ self.lip_open = None;
+ }
+ if let Some(open) = self.lip_open {
+ out.mouth_open = (out.mouth_open * 0.3).max(open);
+ out.mouth_form = self.lip_form.clamp(-1.0, 1.0);
+ }
+ self.parameters = out.clone();
+ out
+ }
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/motions.json b/native/crates/mesh-avatar-core/src/engine/motions.json
new file mode 100644
index 0000000..1620129
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/motions.json
@@ -0,0 +1,5371 @@
+{
+ "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 4.8,
+ 2
+ ],
+ [
+ 6.4,
+ 0
+ ]
+ ]
+ ],
+ [
+ "eyeOpen",
+ [
+ [
+ 0,
+ 1
+ ],
+ [
+ 1.4,
+ 0.8
+ ],
+ [
+ 3,
+ 0.8
+ ],
+ [
+ 3.35,
+ 0.56
+ ],
+ [
+ 3.8,
+ 0.8
+ ],
+ [
+ 4.8,
+ 0.8
+ ],
+ [
+ 5.6,
+ 1.04
+ ],
+ [
+ 6.4,
+ 1
+ ]
+ ]
+ ],
+ [
+ "browY",
+ [
+ [
+ 0,
+ 0
+ ],
+ [
+ 1.6,
+ 0.15
+ ],
+ [
+ 4.8,
+ 0.15
+ ],
+ [
+ 5.6,
+ 0.35
+ ],
+ [
+ 6.6,
+ 0
+ ]
+ ]
+ ],
+ [
+ "breath",
+ [
+ [
+ 0,
+ 0
+ ],
+ [
+ 1.6,
+ 0.9
+ ],
+ [
+ 3.4,
+ 0
+ ],
+ [
+ 5,
+ 0.9
+ ],
+ [
+ 6.2,
+ 0.1
+ ],
+ [
+ 7.4,
+ 0
+ ]
+ ]
+ ]
+ ]
+ }
+ ],
+ "additive": [
+ "angleX",
+ "angleY",
+ "angleZ",
+ "bodyAngleX",
+ "bodyAngleZ",
+ "armAngle",
+ "handAngle",
+ "gazeX",
+ "gazeY"
+ ],
+ "expressions": {
+ "normal": {
+ "label": "Neutral",
+ "p": {}
+ },
+ "smile": {
+ "label": "Smile",
+ "p": {
+ "eyeOpen": 0,
+ "eyeSmile": 1,
+ "blush": 0.35,
+ "browY": 0.2
+ }
+ },
+ "shy": {
+ "label": "Blush",
+ "p": {
+ "eyeOpen": 0.78,
+ "eyeSmile": 0.5,
+ "blush": 1,
+ "browAngle": -0.5,
+ "browY": -0.1,
+ "glance": [
+ 0.7,
+ 0.35
+ ]
+ }
+ },
+ "jito": {
+ "label": "Half-lidded",
+ "p": {
+ "eyeOpen": 0.5,
+ "browY": -0.5,
+ "browAngle": 0.6
+ }
+ },
+ "surprise": {
+ "label": "Surprise",
+ "p": {
+ "eyeOpen": 1.22,
+ "browY": 1,
+ "mouthOpen": 0.6,
+ "mouthForm": 0.6
+ }
+ },
+ "wink": {
+ "label": "Wink",
+ "p": {
+ "eyeOpenL": 0,
+ "eyeSmileL": 1,
+ "blush": 0.3
+ }
+ },
+ "happyTalk": {
+ "label": "happy",
+ "p": {
+ "eyeOpen": 0.8,
+ "eyeSmile": 0.45,
+ "blush": 0.35,
+ "browY": 0.25,
+ "mouthForm": -0.5
+ }
+ },
+ "sadTalk": {
+ "label": "sad",
+ "p": {
+ "eyeOpen": 0.78,
+ "browAngle": -0.8,
+ "browY": -0.2,
+ "mouthForm": 0.3,
+ "glance": [
+ 0,
+ -0.35
+ ]
+ }
+ },
+ "angryTalk": {
+ "label": "angry",
+ "p": {
+ "eyeOpen": 0.72,
+ "browAngle": 0.85,
+ "browY": -0.55,
+ "mouthForm": 0.2
+ }
+ },
+ "surprisedTalk": {
+ "label": "surprised",
+ "p": {
+ "eyeOpen": 1.18,
+ "browY": 0.9,
+ "mouthForm": 0.9
+ }
+ },
+ "relaxedTalk": {
+ "label": "relaxed",
+ "p": {
+ "eyeOpen": 0.82,
+ "eyeSmile": 0.35,
+ "blush": 0.15,
+ "browY": 0.1
+ }
+ }
+ }
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/motions.rs b/native/crates/mesh-avatar-core/src/engine/motions.rs
new file mode 100644
index 0000000..e65bc1f
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/motions.rs
@@ -0,0 +1,71 @@
+//! Authored keyframes and cubic Hermite sampling.
+use serde::{Deserialize, Serialize};
+use std::{collections::BTreeMap, sync::OnceLock};
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct MotionDefinition {
+ pub id: String,
+ pub label: String,
+ pub dur: f64,
+ pub idle: bool,
+ pub tracks: Vec<(String, Vec<[f64; 2]>)>,
+}
+#[derive(Debug, Clone, Deserialize)]
+pub struct Expression {
+ pub label: String,
+ pub p: BTreeMap<String, serde_json::Value>,
+}
+#[derive(Deserialize)]
+pub struct MotionData {
+ pub motions: Vec<MotionDefinition>,
+ pub additive: Vec<String>,
+ pub expressions: BTreeMap<String, Expression>,
+}
+
+pub fn data() -> &'static MotionData {
+ static DATA: OnceLock<MotionData> = OnceLock::new();
+ DATA.get_or_init(|| {
+ serde_json::from_str(include_str!("motions.json")).expect("valid built-in motion data")
+ })
+}
+pub fn motions() -> &'static [MotionDefinition] {
+ &data().motions
+}
+pub fn find_motion(id: &str) -> Option<&'static MotionDefinition> {
+ motions().iter().find(|m| m.id == id)
+}
+pub fn sample_track(keys: &[[f64; 2]], t: f64) -> f64 {
+ if keys.is_empty() {
+ return 0.0;
+ }
+ if t <= keys[0][0] {
+ return keys[0][1];
+ }
+ let n = keys.len() - 1;
+ if t >= keys[n][0] {
+ return keys[n][1];
+ }
+ let mut i = 0;
+ while t > keys[i + 1][0] {
+ i += 1;
+ }
+ let [t0, v0] = keys[i];
+ let [t1, v1] = keys[i + 1];
+ let tan = |j: usize| {
+ if j == 0 || j >= n {
+ 0.0
+ } else {
+ (keys[j + 1][1] - keys[j - 1][1]) / (keys[j + 1][0] - keys[j - 1][0])
+ }
+ };
+ let h = t1 - t0;
+ let u = (t - t0) / h;
+ let m0 = tan(i) * h;
+ let m1 = tan(i + 1) * h;
+ let u2 = u * u;
+ let u3 = u2 * u;
+ (2.0 * u3 - 3.0 * u2 + 1.0) * v0
+ + (u3 - 2.0 * u2 + u) * m0
+ + (-2.0 * u3 + 3.0 * u2) * v1
+ + (u3 - u2) * m1
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/random.rs b/native/crates/mesh-avatar-core/src/engine/random.rs
new file mode 100644
index 0000000..22d87ba
--- /dev/null
+++ b/native/crates/mesh-avatar-core/src/engine/random.rs
@@ -0,0 +1,28 @@
+//! Caller-injected randomness; core never reads a wall clock.
+pub trait RandomSource {
+ fn next_f64(&mut self) -> f64;
+}
+impl<F: FnMut() -> f64> RandomSource for F {
+ fn next_f64(&mut self) -> f64 {
+ self()
+ }
+}
+
+/// The seededRandom algorithm used by the JavaScript motion scenarios.
+pub struct SeededRandom {
+ state: u32,
+}
+impl SeededRandom {
+ pub fn new(seed: u32) -> Self {
+ Self { state: seed }
+ }
+}
+impl RandomSource for SeededRandom {
+ fn next_f64(&mut self) -> f64 {
+ self.state = self.state.wrapping_add(0x6d2b79f5);
+ let state = self.state;
+ let mut t = (state ^ (state >> 15)).wrapping_mul(1 | state);
+ t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(61 | t));
+ f64::from(t ^ (t >> 14)) / 4294967296.0
+ }
+}
diff --git a/native/crates/mesh-avatar-core/src/engine/rig.rs b/native/crates/mesh-avatar-core/src/engine/rig.rs
index f16b1ec..80afc73 100644
--- a/native/crates/mesh-avatar-core/src/engine/rig.rs
+++ b/native/crates/mesh-avatar-core/src/engine/rig.rs
@@ -25,6 +25,15 @@ macro_rules! parameters {
impl Default for Parameters {
fn default() -> Self { Self { $($field: $default,)* eye_smile_l: None } }
}
+ impl Parameters {
+ pub fn get(&self, id: &str) -> Option<f64> {
+ match id { $($id => Some(self.$field),)* "eyeSmileL" => self.eye_smile_l, _ => None }
+ }
+ pub fn set(&mut self, id: &str, value: f64) -> bool {
+ match id { $($id => self.$field = value,)* "eyeSmileL" => self.eye_smile_l = Some(value), _ => return false }
+ true
+ }
+ }
pub const PARAMS: &[ParameterDefinition] = &[
$(ParameterDefinition { id: $id, label: $label, min: $min, max: $max, default: $default, group: $group },)*
];
diff --git a/native/crates/mesh-avatar-core/src/format.rs b/native/crates/mesh-avatar-core/src/format.rs
index 76c0b32..d651043 100644
--- a/native/crates/mesh-avatar-core/src/format.rs
+++ b/native/crates/mesh-avatar-core/src/format.rs
@@ -36,8 +36,12 @@ pub struct Studio {
impl Manifest {
fn parse(bytes: &[u8]) -> Result<Self> {
- let m: Self =
+ let raw: Value =
serde_json::from_slice(bytes).context("avatar.json: invalid manifest JSON")?;
+ if let Some(settings) = raw.get("lipSync") {
+ crate::engine::lip_sync::LipSyncSettings::parse(settings)?;
+ }
+ let m: Self = serde_json::from_value(raw).context("avatar.json: invalid manifest JSON")?;
ensure!(
m.format == "mesh-avatar" && m.version == 1,
"avatar.json: unsupported format or version"
@@ -127,9 +131,15 @@ impl<'de> Deserialize<'de> for SpriteMetadata {
self,
mut map: M,
) -> std::result::Result<Self::Value, M::Error> {
- let mut entries = Vec::new();
- while let Some(entry) = map.next_entry()? {
- entries.push(entry);
+ let mut entries: Vec<(String, Rect)> = Vec::new();
+ while let Some((name, rect)) = map.next_entry::<String, Rect>()? {
+ if let Some((_, value)) =
+ entries.iter_mut().find(|(key, _)| *key == name)
+ {
+ *value = rect;
+ } else {
+ entries.push((name, rect));
+ }
}
Ok(OrderedLayers(entries))
}
@@ -567,6 +577,12 @@ impl AvatarPackage {
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn duplicate_sprite_keys_keep_first_position_and_last_rectangle() {
+ let metadata: SpriteMetadata = serde_json::from_str(r#"{"build":"test","layers":{"eyes_half_0":[0,0,1,1],"eyes_closed_0":[1,1,2,2],"eyes_half_0":[2,2,3,3]}}"#).unwrap();
+ assert_eq!(metadata.layer_order, ["eyes_half_0", "eyes_closed_0"]);
+ assert_eq!(metadata.layers["eyes_half_0"], [2, 2, 3, 3]);
+ }
use std::{
io::Write,
sync::{
@@ -758,6 +774,10 @@ mod tests {
fn rejects_bad_rigs_metadata_and_images() {
type Mutation = (&'static str, fn(&mut Value));
let mutations: &[Mutation] = &[
+ ("avatar.json", |v| v["lipSync"] = Value::Null),
+ ("avatar.json", |v| {
+ v["lipSync"] = serde_json::json!({"granularity":2})
+ }),
("rig.json", |v| v["version"] = 2.into()),
("rig.json", |v| v["head"]["rx"] = 0.into()),
("rig.json", |v| v["mesh"]["baseCell"] = 0.into()),
diff --git a/native/crates/mesh-avatar-core/src/lib.rs b/native/crates/mesh-avatar-core/src/lib.rs
index 6ba75e5..689f2bc 100644
--- a/native/crates/mesh-avatar-core/src/lib.rs
+++ b/native/crates/mesh-avatar-core/src/lib.rs
@@ -1,5 +1,7 @@
//! Data loading and CPU geometry for mesh avatars.
+mod avatar;
pub mod engine;
pub mod format;
pub mod rig;
+pub use avatar::{Avatar, AvatarOptions, DrawLayer, FaceUniforms, Frame};
diff --git a/native/crates/mesh-avatar-core/tests/avatar.rs b/native/crates/mesh-avatar-core/tests/avatar.rs
new file mode 100644
index 0000000..4e65a26
--- /dev/null
+++ b/native/crates/mesh-avatar-core/tests/avatar.rs
@@ -0,0 +1,272 @@
+use mesh_avatar_core::{
+ engine::{
+ grid::Grid, kana::Vowel, lip_sync::LipSyncSettings, random::SeededRandom, rig::Parameters,
+ },
+ format::AvatarPackage,
+ Avatar, AvatarOptions, FaceUniforms,
+};
+use serde::{de::DeserializeOwned, Deserialize};
+use serde_json::{json, Value};
+use std::{collections::BTreeMap, fs, path::Path};
+
+fn read<T: DeserializeOwned>(name: &str) -> Option<T> {
+ let path = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../target/conformance")
+ .join(name);
+ match fs::read(path) {
+ Ok(bytes) => Some(serde_json::from_slice(&bytes).unwrap()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ eprintln!("{name} absent; skipping. Run node native/conformance/dump.mjs first.");
+ None
+ }
+ Err(e) => panic!("{e}"),
+ }
+}
+fn package() -> AvatarPackage {
+ AvatarPackage::open(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../samples/miko-qipao"))
+ .unwrap()
+}
+fn compare(a: f64, b: f64, tolerance: f64, max: &mut f64) {
+ let delta = (a - b).abs();
+ assert!(a.is_finite() && b.is_finite());
+ *max = max.max(delta);
+ assert!(delta <= tolerance, "{a} vs {b}, delta {delta}");
+}
+fn compare_json(a: &Value, b: &Value, max: &mut f64) {
+ match (a, b) {
+ (Value::Number(a), Value::Number(b)) => {
+ compare(a.as_f64().unwrap(), b.as_f64().unwrap(), 1e-6, max)
+ }
+ (Value::Array(a), Value::Array(b)) => {
+ assert_eq!(a.len(), b.len());
+ for (a, b) in a.iter().zip(b) {
+ compare_json(a, b, max);
+ }
+ }
+ (Value::Object(a), Value::Object(b)) => {
+ assert_eq!(a.len(), b.len());
+ for (k, b) in b {
+ compare_json(&a[k], b, max);
+ }
+ }
+ _ => assert_eq!(a, b),
+ }
+}
+#[derive(Deserialize)]
+struct Index {
+ version: u32,
+ files: Vec<String>,
+}
+#[derive(Deserialize)]
+struct Sequence {
+ version: u32,
+ #[serde(rename = "hasSprites")]
+ has_sprites: bool,
+ #[serde(rename = "preserveMouthForm")]
+ preserve_mouth_form: bool,
+ actions: Vec<Value>,
+ samples: Vec<Sample>,
+}
+#[derive(Deserialize)]
+struct Sample {
+ frame: usize,
+ dt: f64,
+ voice: f64,
+ parameters: Parameters,
+ layers: Vec<Layer>,
+ uniforms: FaceUniforms,
+ expression: Value,
+ #[serde(rename = "lipSync")]
+ lip_sync: Value,
+ events: Vec<Option<String>>,
+}
+#[derive(Deserialize)]
+struct Layer {
+ name: String,
+ texture: String,
+ rect: [f64; 4],
+ positions: Vec<f32>,
+ alpha: f64,
+ face: bool,
+ eye_ball: Option<usize>,
+}
+#[derive(Deserialize)]
+struct Grids {
+ grids: Vec<NamedGrid>,
+}
+#[derive(Deserialize)]
+struct NamedGrid {
+ name: String,
+ mesh: Grid,
+}
+
+fn action(avatar: &mut Avatar, event: &Value) {
+ let arg = &event[2];
+ match event[1].as_str().unwrap() {
+ "setAutoIdle" => avatar.set_auto_idle(arg.as_bool().unwrap()),
+ "setAutoMotion" => avatar.set_auto_motion(arg.as_bool().unwrap()),
+ "play" => avatar.play(arg.as_str().unwrap()),
+ "setSpeaking" => avatar.set_speaking(arg.as_bool().unwrap()),
+ "setEmotion" => avatar.set_emotion_with_motion(
+ arg.as_str().unwrap(),
+ event
+ .get(3)
+ .and_then(|v| v.get("playMotion"))
+ .and_then(Value::as_bool)
+ .unwrap_or(true),
+ ),
+ "setExpression" => avatar.set_expression(arg.as_str().unwrap()),
+ "speakKana" => avatar.speak_kana(
+ arg.as_str().unwrap(),
+ event
+ .get(3)
+ .map(|v| serde_json::from_value(v.clone()).unwrap())
+ .unwrap_or_default(),
+ ),
+ "setParameters" => avatar.set_parameters_weighted(
+ serde_json::from_value(arg.clone()).unwrap(),
+ event.get(3).and_then(Value::as_f64).unwrap_or(1.0),
+ ),
+ "setLipSync" => avatar
+ .set_lip_sync(&LipSyncSettings::parse(arg).unwrap())
+ .unwrap(),
+ "holdMouth" => avatar.hold_mouth(Vowel::parse(arg.as_str().unwrap()).unwrap()),
+ "stopLipSync" => avatar.stop_lip_sync(),
+ "setSwayGain" => avatar.set_sway_gain(arg.as_f64().unwrap()),
+ _ => panic!("unknown action"),
+ }
+}
+#[test]
+fn full_avatar_tick_draw_list_and_uniforms_match_real_javascript_tick_path() {
+ let Some(index) = read::<Index>("avatar.json") else {
+ return;
+ };
+ assert_eq!(index.version, 1);
+ let grids = read::<Grids>("grids.json").unwrap();
+ let mut max_positions = 0.0;
+ let mut max_uniforms = 0.0;
+ let mut count = 0;
+ for file in index.files {
+ let expected = read::<Sequence>(&file).unwrap();
+ assert_eq!(expected.version, 1);
+ let mut package = package();
+ if !expected.has_sprites {
+ package.sprites = None;
+ }
+ let mut avatar = Avatar::with_rng(
+ package,
+ AvatarOptions {
+ preserve_mouth_form: expected.preserve_mouth_form,
+ ..Default::default()
+ },
+ Box::new(SeededRandom::new(173)),
+ )
+ .unwrap();
+ let mut sample = 0;
+ let mut events = vec![];
+ for frame in 0..1200 {
+ for event in &expected.actions {
+ if event[0] == frame {
+ action(&mut avatar, event);
+ }
+ }
+ let dt = if frame == 600 {
+ 0.0
+ } else if frame == 900 {
+ 0.08
+ } else {
+ 1.0 / 60.0
+ };
+ let voice = 0.5 + (frame as f64 * 0.73).sin() * 0.45;
+ avatar.set_voice_level(voice);
+ let output = avatar.tick(dt);
+ events.extend(output.motion_events);
+ if frame % 60 > 4 && frame != 1199 {
+ continue;
+ }
+ let expected = &expected.samples[sample];
+ sample += 1;
+ count += 1;
+ assert_eq!(expected.frame, frame);
+ assert_eq!(expected.dt, dt);
+ compare(voice, expected.voice, 1e-12, &mut max_uniforms);
+ compare_json(
+ &serde_json::to_value(avatar.parameters()).unwrap(),
+ &serde_json::to_value(&expected.parameters).unwrap(),
+ &mut max_uniforms,
+ );
+ assert_eq!(output.layers.len(), expected.layers.len());
+ for (actual, expected) in output.layers.iter().zip(&expected.layers) {
+ assert_eq!(actual.name, expected.name, "draw order at frame {frame}");
+ assert_eq!(actual.texture, expected.texture);
+ assert_eq!(actual.rect, expected.rect);
+ assert_eq!(actual.face, expected.face);
+ assert_eq!(actual.eye_ball, expected.eye_ball);
+ compare(actual.alpha, expected.alpha, 1e-6, &mut max_uniforms);
+ assert_eq!(actual.positions.len(), expected.positions.len());
+ for (&a, &b) in actual.positions.iter().zip(&expected.positions) {
+ compare(a as f64, b as f64, 1e-3, &mut max_positions);
+ }
+ let grid = &grids
+ .grids
+ .iter()
+ .find(|g| g.name == actual.name)
+ .unwrap()
+ .mesh;
+ assert_eq!(actual.uvs, grid.uv);
+ assert_eq!(actual.indices, grid.tris);
+ }
+ compare_json(
+ &serde_json::to_value(output.uniforms).unwrap(),
+ &serde_json::to_value(&expected.uniforms).unwrap(),
+ &mut max_uniforms,
+ );
+ let (name, active) = avatar.expression();
+ assert_eq!(json!({"name":name,"active":active}), expected.expression);
+ compare_json(
+ &serde_json::to_value(avatar.lip_sync_state()).unwrap(),
+ &expected.lip_sync,
+ &mut max_uniforms,
+ );
+ assert_eq!(events, expected.events);
+ events.clear();
+ }
+ assert_eq!(sample, expected.samples.len());
+ }
+ eprintln!("Full Avatar: {count} captured frames, max position delta {max_positions} px, max parameter/uniform delta {max_uniforms}");
+}
+
+#[test]
+fn public_api_validates_settings_and_exposes_owned_texture_and_frame_data() {
+ let mut avatar = Avatar::from_package(package()).unwrap();
+ assert!(!avatar.motions().is_empty());
+ assert!(avatar.textures().contains_key("base.png"));
+ avatar.set_auto_idle(false);
+ avatar.set_auto_motion(false);
+ avatar.set_talk_gain(0.5);
+ avatar.set_parameters(BTreeMap::from([("angleX".into(), 12.0)]));
+ avatar.tick(0.0);
+ assert_eq!(avatar.parameters().angle_x, 12.0);
+ avatar.set_emotion("neutral");
+ avatar.play("missing-motion");
+ avatar.hold_mouth(Vowel::A);
+ avatar.tick(1.0 / 60.0);
+ assert!(avatar.lip_sync_state().active);
+ avatar.stop_lip_sync();
+ assert!(!avatar.lip_sync_state().active);
+ for value in [
+ json!(null),
+ json!({"openness":null}),
+ json!({"granularity":-1}),
+ json!({"closeSpeed":2}),
+ json!({"preset":"unknown"}),
+ ] {
+ assert!(LipSyncSettings::parse(&value).is_err());
+ }
+ assert!(avatar
+ .set_lip_sync(&LipSyncSettings {
+ openness: Some(f64::NAN),
+ ..Default::default()
+ })
+ .is_err());
+}
diff --git a/native/crates/mesh-avatar-core/tests/motion.rs b/native/crates/mesh-avatar-core/tests/motion.rs
new file mode 100644
index 0000000..f3ba329
--- /dev/null
+++ b/native/crates/mesh-avatar-core/tests/motion.rs
@@ -0,0 +1,272 @@
+use mesh_avatar_core::{
+ engine::{
+ expression::ExpressionOverlay,
+ kana::{kana_to_moras, sample_moras, skipped_kana_characters, Vowel},
+ lip_sync::LipSyncSettings,
+ motion::{Motion, SpeakOptions},
+ physics::Physics,
+ random::{RandomSource, SeededRandom},
+ rig::RigEngine,
+ },
+ rig::Rig,
+};
+use serde_json::{json, Value};
+use std::{fs, path::Path};
+
+fn fixture() -> Option<Value> {
+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/conformance/motion.json");
+ match fs::read(path) {
+ Ok(bytes) => Some(serde_json::from_slice(&bytes).unwrap()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ eprintln!(
+ "Motion goldens absent; skipping. Run node native/conformance/dump.mjs first."
+ );
+ None
+ }
+ Err(e) => panic!("{e}"),
+ }
+}
+fn rig() -> Rig {
+ Rig::parse(include_bytes!("../../../../samples/miko-qipao/rig.json")).unwrap()
+}
+fn compare(a: &Value, b: &Value, tolerance: f64, max: &mut f64) {
+ match (a, b) {
+ (Value::Number(a), Value::Number(b)) => {
+ let d = (a.as_f64().unwrap() - b.as_f64().unwrap()).abs();
+ *max = max.max(d);
+ assert!(d <= tolerance, "{a} vs {b}, delta {d}");
+ }
+ (Value::Array(a), Value::Array(b)) => {
+ assert_eq!(a.len(), b.len());
+ for (a, b) in a.iter().zip(b) {
+ compare(a, b, tolerance, max);
+ }
+ }
+ (Value::Object(a), Value::Object(b)) => {
+ assert_eq!(a.len(), b.len(), "keys: {a:?} vs {b:?}");
+ for (k, b) in b {
+ assert!(a.contains_key(k), "missing {k}");
+ compare(&a[k], b, tolerance, max);
+ }
+ }
+ _ => assert_eq!(a, b),
+ }
+}
+#[test]
+fn seeded_motion_and_physics_scenarios_match_javascript() {
+ let Some(f) = fixture() else {
+ return;
+ };
+ let rig = rig();
+ let engine = RigEngine::new(&rig);
+ let mut max = 0.0;
+ let mut rng = SeededRandom::new(173);
+ for expected in f["random"].as_array().unwrap() {
+ assert_eq!(rng.next_f64(), expected.as_f64().unwrap());
+ }
+ for scenario in f["scenarios"].as_array().unwrap() {
+ let mut motion = Motion::with_rng(
+ rig.view
+ .gaze_center
+ .unwrap_or([rig.head.ellipse.cx, rig.head.ellipse.cy]),
+ Box::new(SeededRandom::new(173)),
+ );
+ let mut physics = Physics::new(&rig);
+ motion.auto_motion = scenario["name"] == "automatic";
+ motion.auto_idle = scenario["name"] == "idle";
+ if scenario["name"] == "speech" {
+ motion.speak_kana(
+ "こんにちは。きょうも、いっしょにあいうえおをれんしゅうしましょう。",
+ SpeakOptions {
+ looping: true,
+ ..Default::default()
+ },
+ );
+ }
+ let mut sample = 0;
+ for frame in 0..1200 {
+ for event in scenario["schedule"].as_array().unwrap() {
+ if event["frame"] == frame {
+ if let Some(id) = event["id"].as_str() {
+ motion.play_motion(id);
+ } else {
+ motion.set_emotion(event["tag"].as_str().unwrap(), true);
+ }
+ }
+ }
+ let p = motion.update(1.0 / 60.0);
+ let out = physics.step(&engine, &p, 1.0 / 60.0);
+ if frame % 60 == 0 || frame == 1199 {
+ let expected = &scenario["samples"][sample];
+ sample += 1;
+ assert_eq!(expected["frame"], frame);
+ compare(
+ &serde_json::to_value(p).unwrap(),
+ &expected["parameters"],
+ 1e-6,
+ &mut max,
+ );
+ compare(
+ &serde_json::to_value(out).unwrap(),
+ &expected["offsets"],
+ 1e-3,
+ &mut max,
+ );
+ let chains: Vec<_> = physics
+ .chains
+ .iter()
+ .map(|ch| json!({"phi":ch.phi,"points":ch.points.unwrap()}))
+ .collect();
+ compare(&json!(chains), &expected["chains"], 1e-3, &mut max);
+ }
+ }
+ assert_eq!(sample, 21);
+ }
+ eprintln!("Seeded motion/physics: max delta {max}");
+}
+
+fn action(motion: &mut Motion, overlay: &mut ExpressionOverlay, event: &Value) {
+ let arg = &event[2];
+ match event[1].as_str().unwrap() {
+ "setAutoIdle" => motion.auto_idle = arg.as_bool().unwrap(),
+ "setAutoMotion" => motion.auto_motion = arg.as_bool().unwrap(),
+ "setSpeaking" => motion.set_speaking(arg.as_bool().unwrap()),
+ "setEmotion" => motion.set_emotion(
+ arg.as_str().unwrap(),
+ event
+ .get(3)
+ .and_then(|v| v.get("playMotion"))
+ .and_then(Value::as_bool)
+ .unwrap_or(true),
+ ),
+ "setExpression" => overlay.set(arg.as_str().unwrap()),
+ "speakKana" => motion.speak_kana(
+ arg.as_str().unwrap(),
+ event
+ .get(3)
+ .map(|v| serde_json::from_value(v.clone()).unwrap())
+ .unwrap_or_default(),
+ ),
+ "setLipSync" => motion
+ .set_lip_sync(&LipSyncSettings::parse(arg).unwrap())
+ .unwrap(),
+ "holdMouth" => motion.hold_mouth(Vowel::parse(arg.as_str().unwrap())),
+ "stopLipSync" => motion.stop_lip_sync(),
+ _ => panic!("unknown action"),
+ }
+}
+#[test]
+fn speech_settings_and_expression_sequences_match_javascript() {
+ let Some(f) = fixture() else {
+ return;
+ };
+ let rig = rig();
+ let mut motion = Motion::with_rng(
+ rig.view
+ .gaze_center
+ .unwrap_or([rig.head.ellipse.cx, rig.head.ellipse.cy]),
+ Box::new(SeededRandom::new(173)),
+ );
+ let mut overlay = ExpressionOverlay::default();
+ let mut max = 0.0;
+ for update in f["updates"].as_array().unwrap() {
+ for event in f["actions"].as_array().unwrap() {
+ if event[0] == update["frame"] {
+ action(&mut motion, &mut overlay, event);
+ }
+ }
+ motion.set_voice_level(update["voice"].as_f64().unwrap());
+ let dt = update["dt"].as_f64().unwrap();
+ let p = motion.update(dt);
+ let output = overlay.apply(&p, dt);
+ compare(
+ &serde_json::to_value(p).unwrap(),
+ &update["parameters"],
+ 1e-6,
+ &mut max,
+ );
+ compare(
+ &serde_json::to_value(output).unwrap(),
+ &update["output"],
+ 1e-6,
+ &mut max,
+ );
+ compare(
+ &json!({"name":overlay.name,"active":overlay.active()}),
+ &update["expression"],
+ 0.0,
+ &mut max,
+ );
+ compare(
+ &serde_json::to_value(motion.lip_sync_state()).unwrap(),
+ &update["lipSync"],
+ 1e-6,
+ &mut max,
+ );
+ }
+ eprintln!("Speech/expression: max delta {max}");
+}
+#[test]
+fn kana_timing_and_grouping_match_javascript() {
+ let Some(f) = fixture() else {
+ return;
+ };
+ let mut max = 0.0;
+ for case in f["kana"].as_array().unwrap() {
+ let text = case["text"].as_str().unwrap();
+ let moras = kana_to_moras(text, 0.14);
+ compare(
+ &serde_json::to_value(&moras).unwrap(),
+ &case["moras"],
+ 1e-12,
+ &mut max,
+ );
+ let skipped: Vec<_> = skipped_kana_characters(text)
+ .into_iter()
+ .map(|c| c.to_string())
+ .collect();
+ assert_eq!(json!(skipped), case["skipped"]);
+ for sample in case["samples"].as_array().unwrap() {
+ let target = sample_moras(
+ &moras,
+ sample["t"].as_f64().unwrap(),
+ case["granularity"].as_f64().unwrap(),
+ );
+ compare(
+ &serde_json::to_value(target).unwrap(),
+ &sample["target"],
+ 1e-12,
+ &mut max,
+ );
+ }
+ }
+}
+
+#[test]
+fn manual_and_pointer_modes_with_keyframes_match_javascript() {
+ let Some(f) = fixture() else {
+ return;
+ };
+ let mut max = 0.0;
+ for mode in f["modes"].as_array().unwrap() {
+ let mut motion = Motion::with_rng([600.0, 500.0], Box::new(SeededRandom::new(173)));
+ motion.mode = serde_json::from_value(mode["mode"].clone()).unwrap();
+ motion.set_expression("shy");
+ motion.manual.angle_x = 12.0;
+ motion.manual.eye_l_open = 0.4;
+ motion.manual.breath = 0.6;
+ for (frame, sample) in mode["samples"].as_array().unwrap().iter().enumerate() {
+ if frame == 30 {
+ motion.play_motion("tilt");
+ }
+ motion.pointer = Some(serde_json::from_value(sample["pointer"].clone()).unwrap());
+ compare(
+ &serde_json::to_value(motion.update(1.0 / 60.0)).unwrap(),
+ &sample["parameters"],
+ 1e-6,
+ &mut max,
+ );
+ }
+ }
+ eprintln!("Manual/pointer modes: max delta {max}");
+}