Skip to content

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

Add a C ABI for the native avatar runtime

shinshin86f9e70641d7c0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 42a7ce3..c1826d0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -107,3 +107,15 @@ jobs:
- name: Run tests
run: cargo test
+
+ - name: Install pinned C header generator
+ run: cargo install cbindgen --version 0.29.4 --locked --root target/header-tools
+
+ - name: Check generated C header
+ run: bash conformance/ffi-header.sh --check
+
+ - name: Build C ABI libraries
+ run: cargo build --release -p mesh-avatar-ffi
+
+ - name: Build and run C example
+ run: make -C examples/c run
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 9d90aff..3df73ec 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -1062,6 +1062,15 @@ dependencies = [
"winit",
]
+[[package]]
+name = "mesh-avatar-ffi"
+version = "0.1.0"
+dependencies = [
+ "mesh-avatar-core",
+ "serde_json",
+ "zip",
+]
+
[[package]]
name = "mesh-avatar-wgpu"
version = "0.1.0"
diff --git a/native/Cargo.toml b/native/Cargo.toml
index b2af69f..6d4c38c 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["crates/mesh-avatar-core", "crates/mesh-avatar-wgpu", "apps/mesh-avatar-desktop"]
+members = ["crates/mesh-avatar-core", "crates/mesh-avatar-wgpu", "crates/mesh-avatar-ffi", "apps/mesh-avatar-desktop"]
resolver = "2"
[workspace.package]
diff --git a/native/README.ja.md b/native/README.ja.md
index 34c0062..8b22837 100644
--- a/native/README.ja.md
+++ b/native/README.ja.md
@@ -114,6 +114,37 @@ cargo run --release --manifest-path native/Cargo.toml -p mesh-avatar-wgpu \
指定しなかったポーズのパラメータは既定値になります。`--seconds` を指定すると、書き出す前に毎秒 60 ステップでアバターの時間を進めます。
`--help` で、表示余白、fit、表情、マルチサンプリングのオプションを確認できます。
+## C ABIを使う
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
+make -C native/examples/c run
+```
+
+CPU版ライブラリの `libmesh_avatar_ffi.a` と共有ライブラリ(macOSでは `libmesh_avatar_ffi.dylib`)が `native/target/release/` に生成されます。
+ホスト側では [`mesh_avatar.h`](include/mesh_avatar.h) をインクルードします。Cのサンプルは、アバターにポーズを設定して時間を進め、頂点・uniform・テクスチャと不正な入力への応答を確認します。ウィンドウやマイクは起動しません。
+
+ビルド済みフォルダやアーカイブは `mesh_avatar_open_path`、メモリ上のアーカイブは `mesh_avatar_open_bytes` で開きます。
+入力は呼び出し中に読み取り・コピーするため、開いた後はアーカイブのバッファを解放できます。ハンドルには `uint64_t` の識別子を使い、0は無効です。
+別のスレッドへ渡して使えます。同じハンドルへのAPI呼び出しは内部で直列化します。使い終わったら `mesh_avatar_destroy` を呼んでください。
+
+フレームとレイヤーには、ライブラリが所有する読み取り専用ポインターが入っています。有効期間は、そのハンドルの次のtickか破棄までです。設定だけを変更してもキャッシュしたフレームは変わりません。
+テクスチャ名とストレートアルファのRGBA8画像は、ハンドルの破棄まで有効です。これらのポインターは解放しないでください。
+tick後も必要なデータはコピーし、別スレッドからのtick・破棄とデータの読み取りが重ならないよう同期してください。
+各関数の `MaStatus` を確認し、失敗時は `mesh_avatar_last_error` を読みます。エラー文字列は同じスレッドで次のAPIを呼ぶまで有効です。
+Rustのpanicを検知したハンドルは、破棄して開き直します。ポインターと要素数、所有権の条件は生成ヘッダーにも記載しています。
+
+通常のライブラリビルドにヘッダー生成ツールは不要です。ヘッダーを更新するときは、バージョンを固定した開発用ツールをGit管理外のビルド先へ入れます。
+
+```sh
+cargo install cbindgen --version 0.29.4 --locked --root native/target/header-tools
+bash native/conformance/ffi-header.sh
+bash native/conformance/ffi-header.sh --check
+```
+
+CIも同じバージョンでヘッダーの差分を確認し、ライブラリとCサンプルをビルド・実行します。
+C ABIは実験的な段階です。GPU描画用の関数はまだないため、フレームデータをホスト側のレンダラーで描画してください。
+
## チェックと見た目の比較
Node.js 22.17 以降とリポジトリの npm 依存関係は、JavaScript 版との比較にだけ必要です。
diff --git a/native/README.md b/native/README.md
index 2df4bcb..8418d7a 100644
--- a/native/README.md
+++ b/native/README.md
@@ -147,6 +147,47 @@ Unspecified pose parameters use their defaults. `--seconds` advances the avatar
at 60 simulation steps per second before rendering. `--help` lists options for
viewport padding, fit, expressions and multisampling.
+## Use the C ABI
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
+make -C native/examples/c run
+```
+
+The CPU-only library produces `libmesh_avatar_ffi.a` and a platform shared library
+(`libmesh_avatar_ffi.dylib` on macOS) in `native/target/release/`. Include
+[`mesh_avatar.h`](include/mesh_avatar.h) in your host. The C example opens the
+sample, applies a pose, ticks it, reads geometry/uniforms/textures and checks
+invalid-input behavior. It does not create a window or capture audio.
+
+Open a built folder/archive with `mesh_avatar_open_path`, or an in-memory archive
+with `mesh_avatar_open_bytes`. Inputs are copied or consumed during the call;
+the archive buffer can be released after opening. Handles are opaque `uint64_t`
+tokens, with zero invalid. They can move between threads; calls on the same
+handle are serialized internally. Always call `mesh_avatar_destroy` when finished.
+
+Frame and layer descriptors contain borrowed, read-only pointers. They remain
+valid until the next tick or destroy on that handle; setters leave the cached
+frame intact. Texture names and straight RGBA8 pixels remain valid until destroy.
+Do not free these pointers. Copy data if it must outlive a tick, and synchronize
+borrowed reads against tick/destroy on other threads. Check every `MaStatus`;
+`mesh_avatar_last_error` returns a thread-local message until the next API call
+on that thread. A contained Rust panic requires destroying and reopening that
+handle. The generated header documents pointer/count and ownership requirements.
+
+Normal library builds do not need a header generator. To regenerate the checked-in
+header, install the pinned development tool into the ignored build directory:
+
+```sh
+cargo install cbindgen --version 0.29.4 --locked --root native/target/header-tools
+bash native/conformance/ffi-header.sh
+bash native/conformance/ffi-header.sh --check
+```
+
+CI installs that version, verifies the header has no drift, builds both library
+types, and builds/runs the C example. The C ABI is experimental and has no GPU
+rendering entry point yet; use the frame data with a host renderer.
+
## Checks and visual comparison
Node.js 22.17 or newer and the repository's npm dependencies are needed only for
diff --git a/native/README.zh.md b/native/README.zh.md
index 92c89ec..1ca112e 100644
--- a/native/README.zh.md
+++ b/native/README.zh.md
@@ -114,6 +114,36 @@ cargo run --release --manifest-path native/Cargo.toml -p mesh-avatar-wgpu \
未指定的姿势参数使用默认值。`--seconds` 会在渲染前以每秒 60 步推进虚拟形象的时间。
`--help` 会列出视图边距、fit、表情和多重采样等选项。
+## 使用C ABI
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi
+make -C native/examples/c run
+```
+
+CPU库会在 `native/target/release/` 中生成 `libmesh_avatar_ffi.a` 和平台共享库(macOS上为 `libmesh_avatar_ffi.dylib`)。
+宿主程序需包含 [`mesh_avatar.h`](include/mesh_avatar.h)。C示例会加载示例虚拟形象、设置姿势、推进动画,读取几何数据、uniform和纹理,并检查无效输入的返回值,不会创建窗口或启用麦克风。
+
+使用 `mesh_avatar_open_path` 打开已构建的文件夹或归档,使用 `mesh_avatar_open_bytes` 打开内存中的归档。
+输入在调用期间读取或复制,打开成功后即可释放归档缓冲区。句柄是不透明的 `uint64_t` 标识符,0无效。
+句柄可在线程间传递;同一句柄的API调用在内部串行执行。使用完毕后调用 `mesh_avatar_destroy`。
+
+帧和图层描述符包含由库持有的只读指针,有效期到该句柄的下一次tick或销毁为止;仅修改设置不会改变缓存帧。
+纹理名称和未预乘Alpha的RGBA8像素在销毁句柄前保持有效。不要释放这些指针;如需跨tick保留数据,请自行复制。
+读取借用数据时,必须与其他线程上的tick或销毁操作同步,避免并发访问。
+检查每个 `MaStatus`,失败时读取 `mesh_avatar_last_error`;错误字符串在同一线程下一次API调用前有效。
+遇到被捕获的Rust panic时,应销毁并重新打开该句柄。生成的头文件也记录了指针、长度和所有权要求。
+
+普通库构建不需要头文件生成器。更新头文件时,将固定版本的开发工具安装到Git忽略的构建目录:
+
+```sh
+cargo install cbindgen --version 0.29.4 --locked --root native/target/header-tools
+bash native/conformance/ffi-header.sh
+bash native/conformance/ffi-header.sh --check
+```
+
+CI使用相同版本检查头文件差异,并构建库、编译和运行C示例。C ABI仍为实验性功能,尚无GPU渲染入口;请用宿主渲染器绘制帧数据。
+
## 检查与画面对比
只有在与 JavaScript 运行时对比时,才需要 Node.js 22.17 或更高版本以及仓库的 npm 依赖:
diff --git a/native/conformance/ffi-header.sh b/native/conformance/ffi-header.sh
new file mode 100644
index 0000000..ad51fb5
--- /dev/null
+++ b/native/conformance/ffi-header.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+generator="${CBINDGEN:-target/header-tools/bin/cbindgen}"
+if [[ "$("$generator" --version)" != "cbindgen 0.29.4" ]]; then
+ echo "Expected cbindgen 0.29.4. Install with the command in the native guide." >&2
+ exit 1
+fi
+mkdir -p target/generated include
+"$generator" --quiet --only-target-dependencies --config crates/mesh-avatar-ffi/cbindgen.toml --crate mesh-avatar-ffi --output target/generated/mesh_avatar.h
+case "${1:-}" in
+ --check) diff -u include/mesh_avatar.h target/generated/mesh_avatar.h ;;
+ "") cp target/generated/mesh_avatar.h include/mesh_avatar.h ;;
+ *) echo "Usage: bash conformance/ffi-header.sh [--check]" >&2; exit 2 ;;
+esac
diff --git a/native/crates/mesh-avatar-core/src/engine/random.rs b/native/crates/mesh-avatar-core/src/engine/random.rs
index 22d87ba..c938c91 100644
--- a/native/crates/mesh-avatar-core/src/engine/random.rs
+++ b/native/crates/mesh-avatar-core/src/engine/random.rs
@@ -1,8 +1,9 @@
//! Caller-injected randomness; core never reads a wall clock.
-pub trait RandomSource {
+/// Random sources travel with an avatar between host threads; captures must be Send.
+pub trait RandomSource: Send {
fn next_f64(&mut self) -> f64;
}
-impl<F: FnMut() -> f64> RandomSource for F {
+impl<F: FnMut() -> f64 + Send> RandomSource for F {
fn next_f64(&mut self) -> f64 {
self()
}
diff --git a/native/crates/mesh-avatar-ffi/Cargo.toml b/native/crates/mesh-avatar-ffi/Cargo.toml
new file mode 100644
index 0000000..822d79e
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "mesh-avatar-ffi"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+publish.workspace = true
+
+[lib]
+crate-type = ["cdylib", "staticlib", "rlib"]
+
+[dependencies]
+mesh-avatar-core.workspace = true
+
+[dev-dependencies]
+zip.workspace = true
+serde_json.workspace = true
diff --git a/native/crates/mesh-avatar-ffi/cbindgen.toml b/native/crates/mesh-avatar-ffi/cbindgen.toml
new file mode 100644
index 0000000..129d835
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/cbindgen.toml
@@ -0,0 +1,43 @@
+language = "C"
+include_guard = "MESH_AVATAR_H"
+autogen_warning = "/* Generated by cbindgen 0.29.4. Do not edit; run conformance/ffi-header.sh. */"
+usize_is_size_t = true
+documentation = true
+style = "type"
+cpp_compat = true
+header = """
+/* Experimental CPU-only Mesh Avatar C ABI.
+ *
+ * Handles are opaque uint64 tokens, not pointers. Zero/unknown/destroyed tokens
+ * are rejected, and IDs are never reused. Handles may be used from any thread;
+ * API calls on the same handle are serialized internally.
+ *
+ * All returned pointers are borrowed, read-only library storage: NEVER free or
+ * modify them. Frame/layer pointers (including names, arrays and descriptors)
+ * expire on the next tick or destroy of that handle. Texture name/RGBA pointers
+ * expire only at destroy. Copying a descriptor does not copy the pointed-to data.
+ * Callers MUST synchronize borrowed reads against tick/destroy on other threads.
+ *
+ * Input strings are readable UTF-8 NUL-terminated C strings. Nonempty input
+ * buffers must be readable/aligned for their specified lengths. Output pointers
+ * must be writable/aligned and must not alias inputs or borrowed library data.
+ * NULL pointers, invalid handle tokens and indices are checked; the caller is
+ * still responsible for non-NULL memory validity. Inputs are consumed/copied
+ * during the call and are never retained.
+ *
+ * Return values are MA_* status codes. A failed call sets a thread-local error;
+ * mesh_avatar_last_error returns it until the next API call on that thread.
+ * Default Cargo profiles use unwinding: Rust panics become MA_PANIC. A handle
+ * whose state panicked must be destroyed and reopened; other handles remain usable.
+ * No caller-visible allocation needs a separate free function.
+ * Destroy every handle before unloading the library. All borrowed pointers,
+ * including version/error strings, become invalid when the library is unloaded.
+ */
+"""
+
+[parse]
+parse_deps = false
+
+[export]
+item_types = ["constants", "enums", "structs", "typedefs", "functions"]
+exclude = ["Entries", "Entry", "CachedFrame", "Error", "Result"]
diff --git a/native/crates/mesh-avatar-ffi/src/boundary.rs b/native/crates/mesh-avatar-ffi/src/boundary.rs
new file mode 100644
index 0000000..4de2fca
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/boundary.rs
@@ -0,0 +1,109 @@
+use crate::types::*;
+use std::{
+ cell::RefCell,
+ ffi::{c_char, CStr, CString},
+ mem::{align_of, size_of},
+ panic::{catch_unwind, AssertUnwindSafe},
+};
+
+pub(crate) struct Error {
+ pub code: MaStatus,
+ pub message: String,
+}
+pub(crate) type Result<T> = std::result::Result<T, Error>;
+impl Error {
+ pub fn new(code: MaStatus, message: impl Into<String>) -> Self {
+ Self {
+ code,
+ message: message.into(),
+ }
+ }
+}
+thread_local! { static LAST_ERROR:RefCell<CString> = RefCell::new(CString::default()); }
+fn error_text(message: &str) {
+ // Error reporting itself must not propagate a second Rust panic through C.
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ LAST_ERROR.with(|slot| {
+ if let Ok(mut slot) = slot.try_borrow_mut() {
+ if let Ok(text) = CString::new(message.replace('\0', "�")) {
+ *slot = text;
+ }
+ }
+ })
+ }));
+}
+pub(crate) fn boundary(work: impl FnOnce() -> Result<()>) -> MaStatus {
+ match catch_unwind(AssertUnwindSafe(|| {
+ error_text("");
+ work()
+ })) {
+ Ok(Ok(())) => MA_OK,
+ Ok(Err(error)) => {
+ error_text(&error.message);
+ error.code
+ }
+ Err(payload) => {
+ let message = payload
+ .downcast_ref::<String>()
+ .map(String::as_str)
+ .or_else(|| payload.downcast_ref::<&str>().copied())
+ .unwrap_or("Rust panic");
+ error_text(message);
+ MA_PANIC
+ }
+ }
+}
+pub(crate) fn last_error() -> *const c_char {
+ catch_unwind(AssertUnwindSafe(|| {
+ LAST_ERROR.with(|slot| {
+ slot.try_borrow()
+ .map(|s| s.as_ptr())
+ .unwrap_or(c"Error text is busy".as_ptr())
+ })
+ }))
+ .unwrap_or(c"Error text unavailable".as_ptr())
+}
+pub(crate) fn check_out<T>(out: *mut T) -> Result<()> {
+ if out.is_null() || !(out as usize).is_multiple_of(align_of::<T>()) {
+ Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "output pointer is NULL or misaligned",
+ ))
+ } else {
+ Ok(())
+ }
+}
+/// Caller must provide readable, aligned memory for count elements, unless count is zero.
+pub(crate) unsafe fn input_slice<'a, T>(data: *const T, count: usize) -> Result<&'a [T]> {
+ if count == 0 {
+ return Ok(&[]);
+ }
+ if data.is_null()
+ || !(data as usize).is_multiple_of(align_of::<T>())
+ || count > isize::MAX as usize / size_of::<T>().max(1)
+ {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "input pointer is NULL/misaligned or length overflows",
+ ));
+ }
+ // SAFETY: The ABI caller guarantees readable memory after the shape checks above.
+ Ok(unsafe { std::slice::from_raw_parts(data, count) })
+}
+/// Caller must provide a readable NUL-terminated string when non-NULL.
+pub(crate) unsafe fn input_str<'a>(text: *const c_char) -> Result<&'a str> {
+ if text.is_null() {
+ return Err(Error::new(MA_INVALID_ARGUMENT, "string pointer is NULL"));
+ }
+ // SAFETY: The ABI caller guarantees a readable NUL-terminated string.
+ unsafe { CStr::from_ptr(text) }
+ .to_str()
+ .map_err(|_| Error::new(MA_INVALID_ARGUMENT, "string must be UTF-8"))
+}
+pub(crate) fn flag(value: u8) -> Result<bool> {
+ match value {
+ 0 => Ok(false),
+ 1 => Ok(true),
+ _ => Err(Error::new(MA_INVALID_ARGUMENT, "boolean must be 0 or 1")),
+ }
+}
diff --git a/native/crates/mesh-avatar-ffi/src/lib.rs b/native/crates/mesh-avatar-ffi/src/lib.rs
new file mode 100644
index 0000000..402f332
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/lib.rs
@@ -0,0 +1,418 @@
+//! A C ABI over the CPU runtime. The checked-in header defines the ownership contract.
+#![deny(unsafe_op_in_unsafe_fn)]
+mod boundary;
+mod state;
+mod types;
+use boundary::{boundary, check_out, flag, input_slice, input_str, Error};
+use mesh_avatar_core::{
+ engine::{expression::OVERLAY_EXPRESSIONS, kana::Vowel, motion::SpeakOptions, rig::PARAMS},
+ format::AvatarPackage,
+ Avatar,
+};
+use std::{collections::BTreeMap, ffi::c_char, io::Cursor, panic::catch_unwind};
+pub use types::*;
+
+static VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes();
+
+/// Static UTF-8 version string. Borrowed for the lifetime of the loaded library.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_version() -> *const c_char {
+ catch_unwind(|| VERSION.as_ptr().cast()).unwrap_or(c"unknown".as_ptr())
+}
+/// ABI revision, currently 1. Zero indicates a contained failure.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_abi_version() -> u32 {
+ catch_unwind(|| 1).unwrap_or(0)
+}
+/// Thread-local UTF-8 error, valid until the next API call on this thread.
+/// Calling this function again does not invalidate it. Never free this pointer.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_last_error() -> *const c_char {
+ boundary::last_error()
+}
+
+/// Open a .mavatar archive or built project folder and create its initial frame.
+/// On failure, *out is zero. Inputs are copied; no caller buffer is retained.
+/// # Safety
+/// path must be a readable UTF-8 NUL-terminated string; out must be writable/aligned.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_open_path(
+ path: *const c_char,
+ out: *mut MaHandle,
+) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ // SAFETY: The caller supplies a writable output slot.
+ unsafe { out.write(0) };
+ // SAFETY: The caller supplies a readable C string; NULL is checked by input_str.
+ let path = unsafe { input_str(path) }?;
+ let avatar = Avatar::open(path).map_err(|e| Error::new(MA_LOAD_ERROR, format!("{e:#}")))?;
+ let handle = state::insert(state::Entry::new(avatar)?)?;
+ // SAFETY: Output slot was checked above and cannot alias library-owned storage.
+ unsafe { out.write(handle) };
+ Ok(())
+ })
+}
+/// Open in-memory .mavatar ZIP bytes. Bytes need only remain valid during this call.
+/// # Safety
+/// bytes must be readable for length bytes (NULL allowed for zero length); out writable/aligned.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_open_bytes(
+ bytes: *const u8,
+ length: usize,
+ out: *mut MaHandle,
+) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ // SAFETY: The caller supplies a writable output slot and readable input bytes.
+ unsafe { out.write(0) };
+ let bytes = unsafe { input_slice(bytes, length) }?;
+ let package = AvatarPackage::from_archive(Cursor::new(bytes))
+ .map_err(|e| Error::new(MA_LOAD_ERROR, format!("{e:#}")))?;
+ let avatar = Avatar::from_package(package)
+ .map_err(|e| Error::new(MA_LOAD_ERROR, format!("{e:#}")))?;
+ let handle = state::insert(state::Entry::new(avatar)?)?;
+ // SAFETY: Validated caller-owned output slot.
+ unsafe { out.write(handle) };
+ Ok(())
+ })
+}
+/// Destroy a handle from any thread. Rejects zero, unknown and already destroyed tokens.
+/// All pointers borrowed from this handle become invalid; callers must finish their reads first.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_destroy(handle: MaHandle) -> MaStatus {
+ boundary(|| state::destroy(handle))
+}
+/// Advance by nonnegative finite seconds (the core caps the step at 0.05).
+/// Invalidates all prior frame/layer pointers. Setters alone leave the cached frame intact.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_tick(handle: MaHandle, dt: f64) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ if !dt.is_finite() || dt < 0.0 {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "dt must be finite and nonnegative",
+ ));
+ }
+ entry.tick(dt)
+ })
+ })
+}
+/// Copy the current frame descriptor; nested pointers remain library-owned.
+/// # Safety
+/// out must be writable/aligned and must not alias borrowed library memory.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_get_frame(handle: MaHandle, out: *mut MaFrame) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ state::with_entry(handle, |entry| {
+ let frame = entry
+ .frame
+ .as_ref()
+ .ok_or_else(|| Error::new(MA_INVALID_STATE, "no current frame"))?;
+ // SAFETY: Caller-owned output was checked; returned pointers borrow entry storage.
+ unsafe { out.write(frame.descriptor()) };
+ Ok(())
+ })
+ })
+}
+/// Copy one layer descriptor. index is zero-based; pointers expire on tick/destroy.
+/// # Safety
+/// out must be writable/aligned and must not alias borrowed library memory.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_get_layer(
+ handle: MaHandle,
+ index: usize,
+ out: *mut MaLayer,
+) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ state::with_entry(handle, |entry| {
+ let frame = entry
+ .frame
+ .as_ref()
+ .ok_or_else(|| Error::new(MA_INVALID_STATE, "no current frame"))?
+ .descriptor();
+ if index >= frame.layer_count {
+ return Err(Error::new(MA_OUT_OF_RANGE, "layer index is out of range"));
+ }
+ // SAFETY: The index was checked against the cached layer allocation.
+ unsafe { out.write(frame.layers.add(index).read()) };
+ Ok(())
+ })
+ })
+}
+/// Copy avatar dimensions and padding.
+/// # Safety
+/// out must be writable/aligned.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_get_info(
+ handle: MaHandle,
+ out: *mut MaAvatarInfo,
+) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ state::with_entry(handle, |entry| {
+ let rig = &entry.avatar.package().rig;
+ // SAFETY: Caller-owned output slot was checked above.
+ unsafe {
+ out.write(MaAvatarInfo {
+ image_width: rig.image.width,
+ image_height: rig.image.height,
+ pad_top: rig.view.pad_top,
+ pad_side: rig.view.pad_side,
+ })
+ };
+ Ok(())
+ })
+ })
+}
+/// Copy texture count. IDs are zero-based indices and stable until destroy.
+/// # Safety
+/// out must be writable/aligned.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_texture_count(handle: MaHandle, out: *mut usize) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ state::with_entry(handle, |entry| {
+ // SAFETY: Caller-owned output slot was checked above.
+ unsafe { out.write(entry.texture_count()) };
+ Ok(())
+ })
+ })
+}
+/// Copy immutable straight-RGBA texture metadata; pointers expire only at destroy.
+/// # Safety
+/// out must be writable/aligned and must not alias borrowed library memory.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_get_texture(
+ handle: MaHandle,
+ index: usize,
+ out: *mut MaTexture,
+) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ state::with_entry(handle, |entry| {
+ let texture = entry.texture(index)?;
+ // SAFETY: Caller-owned output slot was checked above.
+ unsafe { out.write(texture) };
+ Ok(())
+ })
+ })
+}
+/// Replace all parameter overrides. NULL with count=0 clears them. weight must be in [0,1].
+/// Names/values are copied; supported names/ranges follow the core PARAMS plus eyeSmileL [0,1].
+/// At most 128 entries; duplicate names use the last value. Unknown/out-of-range values fail.
+/// # Safety
+/// values must be readable/aligned for count entries and each name a readable UTF-8 C string.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_set_parameters(
+ handle: MaHandle,
+ values: *const MaParameter,
+ count: usize,
+ weight: f64,
+) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ if count > 128 || !weight.is_finite() || !(0.0..=1.0).contains(&weight) {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "invalid parameter count or weight",
+ ));
+ }
+ // SAFETY: The caller supplies readable/aligned entries and C-string names.
+ let values = unsafe { input_slice(values, count) }?;
+ let mut parameters = BTreeMap::new();
+ for parameter in values {
+ let name = unsafe { input_str(parameter.name) }?;
+ let range = PARAMS
+ .iter()
+ .find(|p| p.id == name)
+ .map(|p| (p.min, p.max))
+ .or_else(|| (name == "eyeSmileL").then_some((0.0, 1.0)))
+ .ok_or_else(|| {
+ Error::new(MA_INVALID_ARGUMENT, format!("unknown parameter: {name}"))
+ })?;
+ if !parameter.value.is_finite() || !(range.0..=range.1).contains(&parameter.value) {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ format!("parameter out of range: {name}"),
+ ));
+ }
+ parameters.insert(name.to_string(), parameter.value);
+ }
+ entry.avatar.set_parameters_weighted(parameters, weight);
+ Ok(())
+ })
+ })
+}
+/// Select a live expression: neutral, smile, shy, surprise, halfLidded, angry, sad or wink.
+/// # Safety
+/// name must be a readable UTF-8 NUL-terminated string.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_set_expression(
+ handle: MaHandle,
+ name: *const c_char,
+) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ // SAFETY: Caller supplies a readable C string; NULL/UTF-8 are checked.
+ let name = unsafe { input_str(name) }?;
+ if !OVERLAY_EXPRESSIONS.iter().any(|(id, _)| *id == name) {
+ return Err(Error::new(MA_INVALID_ARGUMENT, "unknown live expression"));
+ }
+ entry.avatar.set_expression(name);
+ Ok(())
+ })
+ })
+}
+/// Emotion tag: neutral, happy, sad, angry, surprised or relaxed. play_motion is 0 or 1.
+/// # Safety
+/// tag must be a readable UTF-8 NUL-terminated string.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_set_emotion(
+ handle: MaHandle,
+ tag: *const c_char,
+ play_motion: u8,
+) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ // SAFETY: Caller supplies a readable C string.
+ let tag = unsafe { input_str(tag) }?;
+ if !["neutral", "happy", "sad", "angry", "surprised", "relaxed"].contains(&tag) {
+ return Err(Error::new(MA_INVALID_ARGUMENT, "unknown emotion"));
+ }
+ entry
+ .avatar
+ .set_emotion_with_motion(tag, flag(play_motion)?);
+ Ok(())
+ })
+ })
+}
+/// Play a built-in motion by its ID, e.g. nod, no, sway or greeting.
+/// # Safety
+/// id must be a readable UTF-8 NUL-terminated string.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_play(handle: MaHandle, id: *const c_char) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ // SAFETY: Caller supplies a readable C string.
+ let id = unsafe { input_str(id) }?;
+ if !entry.avatar.motions().iter().any(|m| m.id == id) {
+ return Err(Error::new(MA_INVALID_ARGUMENT, "unknown motion"));
+ }
+ entry.avatar.play(id);
+ Ok(())
+ })
+ })
+}
+/// Set normalized voice level in [0,1]; finite values only.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_set_voice_level(handle: MaHandle, level: f64) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ if !level.is_finite() || !(0.0..=1.0).contains(&level) {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "voice level must be finite and in [0,1]",
+ ));
+ }
+ entry.avatar.set_voice_level(level);
+ Ok(())
+ })
+ })
+}
+/// Set speaking state: 0 or 1.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_set_speaking(handle: MaHandle, on: u8) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ entry.avatar.set_speaking(flag(on)?);
+ Ok(())
+ })
+ })
+}
+/// Run kana mouth shapes without audio. speed=0 uses the core default; otherwise mora/second,
+/// clamped by the core to [4,12]. looping is 0 or 1.
+/// # Safety
+/// text must be a readable UTF-8 NUL-terminated string; it is copied during this call.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_speak_kana(
+ handle: MaHandle,
+ text: *const c_char,
+ speed: f64,
+ looping: u8,
+) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ // SAFETY: Caller supplies a readable C string.
+ let text = unsafe { input_str(text) }?;
+ if !speed.is_finite() || speed < 0.0 {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "kana speed must be finite and nonnegative",
+ ));
+ }
+ entry.avatar.speak_kana(
+ text,
+ SpeakOptions {
+ speed: (speed > 0.0).then_some(speed),
+ looping: flag(looping)?,
+ },
+ );
+ Ok(())
+ })
+ })
+}
+/// Hold a mouth vowel: a, i, u, e, o or n.
+/// # Safety
+/// vowel must be a readable UTF-8 C string.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_hold_mouth(
+ handle: MaHandle,
+ vowel: *const c_char,
+) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ // SAFETY: Caller supplies a readable C string.
+ let vowel = Vowel::parse(unsafe { input_str(vowel) }?)
+ .ok_or_else(|| Error::new(MA_INVALID_ARGUMENT, "unknown vowel"))?;
+ entry.avatar.hold_mouth(vowel);
+ Ok(())
+ })
+ })
+}
+/// Stop kana and held-vowel lip sync.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_stop_lip_sync(handle: MaHandle) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ entry.avatar.stop_lip_sync();
+ Ok(())
+ })
+ })
+}
+/// Enable automatic idle: 0 or 1.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_set_auto_idle(handle: MaHandle, on: u8) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ entry.avatar.set_auto_idle(flag(on)?);
+ Ok(())
+ })
+ })
+}
+/// Enable automatic motion: 0 or 1.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_set_auto_motion(handle: MaHandle, on: u8) -> MaStatus {
+ boundary(|| {
+ state::with_entry(handle, |entry| {
+ entry.avatar.set_auto_motion(flag(on)?);
+ Ok(())
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/native/crates/mesh-avatar-ffi/src/state.rs b/native/crates/mesh-avatar-ffi/src/state.rs
new file mode 100644
index 0000000..c5c9d35
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/state.rs
@@ -0,0 +1,207 @@
+use crate::{
+ boundary::{Error, Result},
+ types::*,
+};
+use mesh_avatar_core::{Avatar, Frame};
+use std::{
+ collections::BTreeMap,
+ ffi::CString,
+ sync::{
+ atomic::{AtomicU64, Ordering},
+ Arc, Mutex, OnceLock,
+ },
+};
+
+fn ptr_or_null<T>(values: &[T]) -> *const T {
+ if values.is_empty() {
+ std::ptr::null()
+ } else {
+ values.as_ptr()
+ }
+}
+pub(crate) struct CachedFrame {
+ _frame: Frame,
+ _names: Vec<CString>,
+ layers: Vec<MaLayer>,
+ uniforms: MaFaceUniforms,
+}
+// SAFETY: Every raw pointer in layers borrows an allocation owned by _frame/_names.
+// Moving this cache never moves those allocations. All access is under the entry
+// mutex; C callers must synchronize borrowed reads against tick/destroy.
+unsafe impl Send for CachedFrame {}
+impl CachedFrame {
+ fn new(frame: Frame, ids: &BTreeMap<String, u32>) -> Result<Self> {
+ let names: Vec<_> = frame
+ .layers
+ .iter()
+ .map(|l| CString::new(l.name.as_str()))
+ .collect::<std::result::Result<_, _>>()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "layer name contains NUL"))?;
+ let layers = frame
+ .layers
+ .iter()
+ .zip(&names)
+ .map(|(layer, name)| {
+ Ok(MaLayer {
+ name: name.as_ptr(),
+ texture_id: *ids
+ .get(&layer.texture)
+ .ok_or_else(|| Error::new(MA_INVALID_STATE, "missing texture id"))?,
+ positions: ptr_or_null(&layer.positions),
+ uvs: ptr_or_null(&layer.uvs),
+ vertex_count: layer.positions.len() / 2,
+ indices: ptr_or_null(&layer.indices),
+ index_count: layer.indices.len(),
+ rect: layer.rect,
+ alpha: layer.alpha,
+ face: u8::from(layer.face),
+ eye_ball: layer.eye_ball.map_or(-1, |i| i as i32),
+ })
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let u = &frame.uniforms;
+ let uniforms = MaFaceUniforms {
+ angles: u.angles,
+ eye_box: u.eye_box,
+ eye_top: u.eye_top,
+ eye_bot: u.eye_bot,
+ eyes: u.eyes,
+ mouth: u.mouth,
+ mouth_state: u.mouth_state,
+ cheeks: u.cheeks,
+ cheek: u.cheek,
+ };
+ Ok(Self {
+ _frame: frame,
+ _names: names,
+ layers,
+ uniforms,
+ })
+ }
+ pub fn descriptor(&self) -> MaFrame {
+ MaFrame {
+ layers: ptr_or_null(&self.layers),
+ layer_count: self.layers.len(),
+ uniforms: self.uniforms,
+ }
+ }
+}
+pub(crate) struct Entry {
+ pub avatar: Avatar,
+ pub frame: Option<CachedFrame>,
+ pub poisoned: bool,
+ alive: bool,
+ names: Vec<CString>,
+ ids: BTreeMap<String, u32>,
+}
+impl Entry {
+ pub fn new(avatar: Avatar) -> Result<Self> {
+ let names = avatar
+ .textures()
+ .keys()
+ .map(|s| CString::new(s.as_str()))
+ .collect::<std::result::Result<Vec<_>, _>>()
+ .map_err(|_| Error::new(MA_LOAD_ERROR, "texture name contains NUL"))?;
+ let ids = avatar
+ .textures()
+ .keys()
+ .enumerate()
+ .map(|(i, n)| (n.clone(), i as u32))
+ .collect();
+ let mut entry = Self {
+ avatar,
+ frame: None,
+ poisoned: false,
+ alive: true,
+ names,
+ ids,
+ };
+ entry.tick(0.0)?;
+ Ok(entry)
+ }
+ pub fn tick(&mut self, dt: f64) -> Result<()> {
+ self.frame = None; // Invalidate borrowed frame pointers before changing core state.
+ let frame = self.avatar.tick(dt);
+ self.frame = Some(CachedFrame::new(frame, &self.ids)?);
+ Ok(())
+ }
+ pub fn texture_count(&self) -> usize {
+ self.names.len()
+ }
+ pub fn texture(&self, index: usize) -> Result<MaTexture> {
+ let (name, texture) = self
+ .avatar
+ .textures()
+ .iter()
+ .nth(index)
+ .ok_or_else(|| Error::new(MA_OUT_OF_RANGE, "texture index is out of range"))?;
+ Ok(MaTexture {
+ id: self.ids[name],
+ name: self.names[index].as_ptr(),
+ width: texture.width,
+ height: texture.height,
+ rgba: ptr_or_null(&texture.rgba),
+ byte_count: texture.rgba.len(),
+ })
+ }
+}
+type Entries = BTreeMap<MaHandle, Arc<Mutex<Entry>>>;
+static ENTRIES: OnceLock<Mutex<Entries>> = OnceLock::new();
+fn entries() -> &'static Mutex<Entries> {
+ ENTRIES.get_or_init(|| Mutex::new(BTreeMap::new()))
+}
+static NEXT: AtomicU64 = AtomicU64::new(1);
+pub(crate) fn insert(entry: Entry) -> Result<MaHandle> {
+ let id = NEXT
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| v.checked_add(1))
+ .map_err(|_| Error::new(MA_INVALID_STATE, "handle space exhausted"))?;
+ entries()
+ .lock()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "handle registry is poisoned"))?
+ .insert(id, Arc::new(Mutex::new(entry)));
+ Ok(id)
+}
+pub(crate) fn with_entry<T>(
+ handle: MaHandle,
+ work: impl FnOnce(&mut Entry) -> Result<T>,
+) -> Result<T> {
+ let shared = entries()
+ .lock()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "handle registry is poisoned"))?
+ .get(&handle)
+ .cloned()
+ .ok_or_else(|| Error::new(MA_INVALID_HANDLE, "invalid or destroyed handle"))?;
+ let mut entry = shared.lock().map_err(|_| {
+ Error::new(
+ MA_INVALID_STATE,
+ "handle was poisoned by a panic; destroy and reopen it",
+ )
+ })?;
+ if !entry.alive {
+ return Err(Error::new(MA_INVALID_HANDLE, "destroyed handle"));
+ }
+ if entry.poisoned {
+ return Err(Error::new(
+ MA_INVALID_STATE,
+ "handle was poisoned by a panic; destroy and reopen it",
+ ));
+ }
+ entry.poisoned = true;
+ let result = work(&mut entry);
+ entry.poisoned = false;
+ result
+}
+pub(crate) fn destroy(handle: MaHandle) -> Result<()> {
+ let shared = entries()
+ .lock()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "handle registry is poisoned"))?
+ .remove(&handle)
+ .ok_or_else(|| Error::new(MA_INVALID_HANDLE, "invalid or destroyed handle"))?;
+ // Destruction must remain available after a contained panic.
+ let mut entry = shared
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ entry.alive = false;
+ entry.frame = None;
+ Ok(())
+}
diff --git a/native/crates/mesh-avatar-ffi/src/tests.rs b/native/crates/mesh-avatar-ffi/src/tests.rs
new file mode 100644
index 0000000..e89147c
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/tests.rs
@@ -0,0 +1,347 @@
+use super::*;
+use std::{
+ ffi::{CStr, CString},
+ fs,
+ io::Write,
+ mem::MaybeUninit,
+ path::{Path, PathBuf},
+ ptr,
+};
+
+fn sample() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../samples/miko-qipao")
+}
+fn open() -> MaHandle {
+ let path = CString::new(sample().to_str().unwrap()).unwrap();
+ let mut handle = 0;
+ // SAFETY: Valid strings and writable local output slots throughout these tests.
+ assert_eq!(
+ unsafe { mesh_avatar_open_path(path.as_ptr(), &mut handle) },
+ MA_OK
+ );
+ assert_ne!(handle, 0);
+ handle
+}
+fn frame(handle: MaHandle) -> MaFrame {
+ let mut out = MaybeUninit::uninit();
+ assert_eq!(
+ unsafe { mesh_avatar_get_frame(handle, out.as_mut_ptr()) },
+ MA_OK
+ );
+ unsafe { out.assume_init() }
+}
+fn texture(handle: MaHandle, index: usize) -> MaTexture {
+ let mut out = MaybeUninit::uninit();
+ assert_eq!(
+ unsafe { mesh_avatar_get_texture(handle, index, out.as_mut_ptr()) },
+ MA_OK
+ );
+ unsafe { out.assume_init() }
+}
+fn error() -> String {
+ unsafe { CStr::from_ptr(mesh_avatar_last_error()) }
+ .to_str()
+ .unwrap()
+ .to_string()
+}
+
+#[test]
+fn nulls_invalid_tokens_utf8_lengths_and_indices_are_checked() {
+ let h = open();
+ let mut out = 99;
+ assert_eq!(
+ unsafe { mesh_avatar_open_path(ptr::null(), &mut out) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(out, 0);
+ assert_eq!(
+ unsafe { mesh_avatar_open_path(c"missing".as_ptr(), ptr::null_mut()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_open_bytes(ptr::null(), 1, &mut out) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_open_bytes(ptr::without_provenance(1), usize::MAX, &mut out) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(mesh_avatar_tick(0, 0.0), MA_INVALID_HANDLE);
+ assert_eq!(mesh_avatar_destroy(u64::MAX), MA_INVALID_HANDLE);
+ // Invalid handles are rejected without ever following a forged input string pointer.
+ assert_eq!(
+ unsafe { mesh_avatar_set_expression(0, ptr::without_provenance(1)) },
+ MA_INVALID_HANDLE
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_get_frame(h, ptr::null_mut()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_get_frame(h, ptr::without_provenance_mut(1)) },
+ MA_INVALID_ARGUMENT
+ );
+ let invalid = [0xff_u8, 0];
+ assert_eq!(
+ unsafe { mesh_avatar_set_expression(h, invalid.as_ptr().cast()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_set_expression(h, ptr::null()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_set_parameters(h, ptr::null(), 1, 1.0) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_set_parameters(h, ptr::without_provenance(1), 1, 1.0) },
+ MA_INVALID_ARGUMENT
+ );
+ let mut layer = MaybeUninit::uninit();
+ let mut tex = MaybeUninit::uninit();
+ assert_eq!(
+ unsafe { mesh_avatar_get_layer(h, usize::MAX, layer.as_mut_ptr()) },
+ MA_OUT_OF_RANGE
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_get_texture(h, usize::MAX, tex.as_mut_ptr()) },
+ MA_OUT_OF_RANGE
+ );
+ assert_eq!(mesh_avatar_tick(h, f64::NAN), MA_INVALID_ARGUMENT);
+ assert_eq!(mesh_avatar_tick(h, -1.0), MA_INVALID_ARGUMENT);
+ assert_eq!(
+ mesh_avatar_set_voice_level(h, f64::INFINITY),
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(mesh_avatar_set_speaking(h, 2), MA_INVALID_ARGUMENT);
+ assert_eq!(mesh_avatar_set_auto_idle(h, 2), MA_INVALID_ARGUMENT);
+ assert_eq!(
+ unsafe { mesh_avatar_play(h, c"unknown".as_ptr()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_set_emotion(h, c"unknown".as_ptr(), 0) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_speak_kana(h, c"あ".as_ptr(), f64::NAN, 0) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_hold_mouth(h, c"unknown".as_ptr()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(mesh_avatar_tick(h, 0.01), MA_OK);
+ assert!(error().is_empty());
+ assert_eq!(mesh_avatar_destroy(h), MA_OK);
+ assert_eq!(mesh_avatar_destroy(h), MA_INVALID_HANDLE);
+ assert_eq!(mesh_avatar_tick(h, 0.01), MA_INVALID_HANDLE);
+ let next = open();
+ assert_ne!(h, next);
+ mesh_avatar_destroy(next);
+}
+
+#[test]
+fn frame_geometry_uniforms_and_textures_match_core_with_explicit_lifetimes() {
+ let h = open();
+ let mut core = Avatar::open(sample()).unwrap();
+ core.tick(0.0);
+ let before = frame(h);
+ let texture = texture(h, 0);
+ let pixel_copy =
+ unsafe { std::slice::from_raw_parts(texture.rgba, texture.byte_count) }.to_vec();
+ assert_eq!(
+ unsafe {
+ mesh_avatar_set_parameters(
+ h,
+ [MaParameter {
+ name: c"angleX".as_ptr(),
+ value: 20.0,
+ }]
+ .as_ptr(),
+ 1,
+ 1.0,
+ )
+ },
+ MA_OK
+ );
+ assert_eq!(frame(h).layers, before.layers); // A setter does not replace the cached frame.
+ core.set_parameters(BTreeMap::from([("angleX".into(), 20.0)]));
+ assert_eq!(mesh_avatar_tick(h, 0.016), MA_OK);
+ let actual = frame(h);
+ let expected = core.tick(0.016);
+ assert_eq!(actual.layer_count, expected.layers.len());
+ let layers = unsafe { std::slice::from_raw_parts(actual.layers, actual.layer_count) };
+ for (a, b) in layers.iter().zip(&expected.layers) {
+ assert_eq!(unsafe { CStr::from_ptr(a.name) }.to_str().unwrap(), b.name);
+ if a.vertex_count > 0 {
+ assert_eq!(
+ unsafe { std::slice::from_raw_parts(a.positions, a.vertex_count * 2) },
+ b.positions
+ );
+ assert_eq!(
+ unsafe { std::slice::from_raw_parts(a.uvs, a.vertex_count * 2) },
+ b.uvs
+ );
+ } else {
+ assert!(b.positions.is_empty() && b.uvs.is_empty());
+ }
+ if a.index_count > 0 {
+ assert_eq!(
+ unsafe { std::slice::from_raw_parts(a.indices, a.index_count) },
+ b.indices
+ );
+ }
+ assert_eq!(a.alpha, b.alpha);
+ assert_eq!(a.eye_ball, b.eye_ball.map_or(-1, |i| i as i32));
+ assert_eq!(a.face, u8::from(b.face));
+ }
+ assert_eq!(actual.uniforms.angles, expected.uniforms.angles);
+ assert_eq!(actual.uniforms.eye_top, expected.uniforms.eye_top);
+ assert_eq!(actual.uniforms.mouth_state, expected.uniforms.mouth_state);
+ // Texture storage is immutable across ticks, unlike cached frame storage.
+ assert_eq!(
+ unsafe { std::slice::from_raw_parts(texture.rgba, texture.byte_count) },
+ pixel_copy
+ );
+ assert_eq!(texture.rgba, super::tests::texture(h, 0).rgba);
+ assert_eq!(
+ unsafe { mesh_avatar_set_parameters(h, ptr::null(), 0, 1.0) },
+ MA_OK,
+ "{}",
+ error()
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_set_expression(h, c"wink".as_ptr()) },
+ MA_OK
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_set_emotion(h, c"happy".as_ptr(), 1) },
+ MA_OK
+ );
+ assert_eq!(unsafe { mesh_avatar_play(h, c"nod".as_ptr()) }, MA_OK);
+ assert_eq!(mesh_avatar_set_voice_level(h, 0.7), MA_OK);
+ assert_eq!(mesh_avatar_set_speaking(h, 1), MA_OK);
+ assert_eq!(
+ unsafe { mesh_avatar_speak_kana(h, c"こんにちは".as_ptr(), 7.0, 0) },
+ MA_OK
+ );
+ assert_eq!(unsafe { mesh_avatar_hold_mouth(h, c"a".as_ptr()) }, MA_OK);
+ assert_eq!(mesh_avatar_stop_lip_sync(h), MA_OK);
+ assert_eq!(mesh_avatar_set_auto_idle(h, 0), MA_OK);
+ assert_eq!(mesh_avatar_set_auto_motion(h, 0), MA_OK);
+ assert_eq!(mesh_avatar_tick(h, 0.01), MA_OK);
+ assert_eq!(mesh_avatar_destroy(h), MA_OK);
+}
+
+fn archive_bytes() -> Vec<u8> {
+ let source = sample();
+ let package = AvatarPackage::open(&source).unwrap();
+ let mut manifest = serde_json::to_value(&package.manifest).unwrap();
+ manifest
+ .as_object_mut()
+ .unwrap()
+ .retain(|_, value| !value.is_null());
+ let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
+ let options =
+ zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ for (name, bytes) in [
+ ("avatar.json", serde_json::to_vec(&manifest).unwrap()),
+ ("rig.json", serde_json::to_vec(&package.rig).unwrap()),
+ (
+ "built/layers.json",
+ serde_json::to_vec(&package.layers).unwrap(),
+ ),
+ ] {
+ zip.start_file(name, options).unwrap();
+ zip.write_all(&bytes).unwrap();
+ }
+ if let Some(sprites) = &package.sprites {
+ zip.start_file("built/sprites.json", options).unwrap();
+ zip.write_all(&serde_json::to_vec(sprites).unwrap())
+ .unwrap();
+ }
+ for name in package.textures.keys() {
+ let path = format!("built/{name}");
+ zip.start_file(&path, options).unwrap();
+ zip.write_all(&fs::read(source.join(path)).unwrap())
+ .unwrap();
+ }
+ zip.finish().unwrap().into_inner()
+}
+#[test]
+fn archive_input_is_consumed_without_retaining_the_caller_buffer() {
+ let bytes = archive_bytes();
+ let mut h = 0;
+ assert_eq!(
+ unsafe { mesh_avatar_open_bytes(bytes.as_ptr(), bytes.len(), &mut h) },
+ MA_OK,
+ "{}",
+ error()
+ );
+ drop(bytes);
+ assert_eq!(mesh_avatar_tick(h, 0.01), MA_OK);
+ assert!(!texture(h, 0).rgba.is_null());
+ mesh_avatar_destroy(h);
+ assert_eq!(
+ unsafe { mesh_avatar_open_bytes(b"bad".as_ptr(), 3, &mut h) },
+ MA_LOAD_ERROR
+ );
+ assert_eq!(h, 0);
+}
+
+#[test]
+fn handles_migrate_and_serialize_across_threads_and_destroy_can_race_calls() {
+ fn assert_send<T: Send>() {}
+ assert_send::<Avatar>();
+ let h = open();
+ let workers: Vec<_> = (0..4)
+ .map(|_| {
+ std::thread::spawn(move || {
+ for _ in 0..10 {
+ assert_eq!(mesh_avatar_tick(h, 0.001), MA_OK);
+ // Only read copied metadata here; another thread may invalidate nested pointers.
+ assert!(frame(h).layer_count > 0);
+ }
+ })
+ })
+ .collect();
+ for worker in workers {
+ worker.join().unwrap();
+ }
+ let reader = std::thread::spawn(move || {
+ for _ in 0..100 {
+ let status = mesh_avatar_tick(h, 0.001);
+ assert!([MA_OK, MA_INVALID_HANDLE].contains(&status));
+ }
+ });
+ assert_eq!(
+ std::thread::spawn(move || mesh_avatar_destroy(h))
+ .join()
+ .unwrap(),
+ MA_OK
+ );
+ reader.join().unwrap();
+ assert_eq!(mesh_avatar_tick(h, 0.0), MA_INVALID_HANDLE);
+}
+
+#[test]
+fn panics_are_contained_per_handle_and_errors_are_thread_local() {
+ assert_eq!(mesh_avatar_abi_version(), 1);
+ assert!(!unsafe { CStr::from_ptr(mesh_avatar_version()) }
+ .to_bytes()
+ .is_empty());
+ let h = open();
+ let other = open();
+ assert_eq!(
+ boundary(|| state::with_entry(h, |_| panic!("injected core panic"))),
+ MA_PANIC
+ );
+ assert!(error().contains("injected core panic"));
+ assert_eq!(std::thread::spawn(error).join().unwrap(), "");
+ assert_eq!(mesh_avatar_tick(h, 0.0), MA_INVALID_STATE);
+ assert_eq!(mesh_avatar_tick(other, 0.0), MA_OK);
+ assert_eq!(mesh_avatar_destroy(h), MA_OK);
+ assert_eq!(mesh_avatar_destroy(other), MA_OK);
+}
diff --git a/native/crates/mesh-avatar-ffi/src/types.rs b/native/crates/mesh-avatar-ffi/src/types.rs
new file mode 100644
index 0000000..d689ca3
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/types.rs
@@ -0,0 +1,90 @@
+use std::ffi::c_char;
+
+/// Opaque process-wide token. Zero is invalid. Never cast to a pointer or free it.
+pub type MaHandle = u64;
+pub type MaStatus = i32;
+pub const MA_OK: MaStatus = 0;
+pub const MA_INVALID_ARGUMENT: MaStatus = 1;
+pub const MA_INVALID_HANDLE: MaStatus = 2;
+pub const MA_LOAD_ERROR: MaStatus = 3;
+pub const MA_OUT_OF_RANGE: MaStatus = 4;
+pub const MA_INVALID_STATE: MaStatus = 5;
+pub const MA_PANIC: MaStatus = 6;
+
+/// A UTF-8, NUL-terminated parameter name and finite value. Input is copied.
+#[repr(C)]
+pub struct MaParameter {
+ pub name: *const c_char,
+ pub value: f64,
+}
+
+/// Copied FaceUniforms fields in C layout, not a GPU uniform-buffer layout.
+#[repr(C)]
+#[derive(Clone, Copy, Default)]
+pub struct MaFaceUniforms {
+ 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,
+}
+
+/// Borrowed geometry. All pointers (including name) expire at next tick/destroy.
+/// positions and uvs contain vertex_count * 2 floats in x,y / u,v order.
+/// indices contains index_count uint32 values in triangle order; empty arrays are NULL.
+/// Positions use source-image pixels with a top-left origin; UVs address the layer texture.
+/// rect is [x, y, width, height] in source-image pixels.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct MaLayer {
+ pub name: *const c_char,
+ pub texture_id: u32,
+ pub positions: *const f32,
+ pub uvs: *const f32,
+ pub vertex_count: usize,
+ pub indices: *const u32,
+ pub index_count: usize,
+ pub rect: [f64; 4],
+ pub alpha: f64,
+ /// 1 for a face layer, otherwise 0.
+ pub face: u8,
+ /// -1 for no eye-ball shader, 0 or 1 for the corresponding eye.
+ pub eye_ball: i32,
+}
+
+/// Copied descriptor with borrowed layers. layers points to layer_count MaLayer values.
+/// The descriptors and nested pointers expire at next tick/destroy; do not free them.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct MaFrame {
+ pub layers: *const MaLayer,
+ pub layer_count: usize,
+ pub uniforms: MaFaceUniforms,
+}
+
+/// Borrowed immutable texture. name and rgba remain valid until destroy.
+/// RGBA is straight (not premultiplied) RGBA8, top-left origin, tightly packed.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct MaTexture {
+ pub id: u32,
+ pub name: *const c_char,
+ pub width: u32,
+ pub height: u32,
+ pub rgba: *const u8,
+ pub byte_count: usize,
+}
+
+/// Copied dimensions and viewport padding for a host renderer.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct MaAvatarInfo {
+ pub image_width: u32,
+ pub image_height: u32,
+ pub pad_top: f64,
+ pub pad_side: f64,
+}
diff --git a/native/examples/c/Makefile b/native/examples/c/Makefile
new file mode 100644
index 0000000..cce2ff1
--- /dev/null
+++ b/native/examples/c/Makefile
@@ -0,0 +1,18 @@
+CC ?= cc
+NATIVE := ../..
+OUT := $(NATIVE)/target/ffi-example
+LIB := $(NATIVE)/target/release/libmesh_avatar_ffi.a
+CFLAGS ?= -std=c11 -O2 -Wall -Wextra -Werror
+UNAME_S := $(shell uname -s)
+ifeq ($(UNAME_S),Darwin)
+LDLIBS ?= -lm
+else
+LDLIBS ?= -ldl -lpthread -lm
+endif
+
+.PHONY: all run
+all: $(OUT)
+$(OUT): main.c $(NATIVE)/include/mesh_avatar.h $(LIB)
+ $(CC) $(CFLAGS) -I$(NATIVE)/include main.c $(LIB) $(LDLIBS) -o $@
+run: $(OUT)
+ $(OUT) $(NATIVE)/../samples/miko-qipao
diff --git a/native/examples/c/main.c b/native/examples/c/main.c
new file mode 100644
index 0000000..c1fce09
--- /dev/null
+++ b/native/examples/c/main.c
@@ -0,0 +1,68 @@
+#include "mesh_avatar.h"
+#include <math.h>
+#include <stdio.h>
+
+#define CHECK(call) do { \
+ MaStatus status = (call); \
+ if (status != MA_OK) { \
+ fprintf(stderr, "%s failed (%d): %s\n", #call, (int)status, mesh_avatar_last_error()); \
+ goto failed; \
+ } \
+} while (0)
+
+int main(int argc, char **argv) {
+ const char *path = argc > 1 ? argv[1] : "../samples/miko-qipao";
+ MaHandle avatar = 0;
+ printf("Mesh Avatar %s, ABI %u\n", mesh_avatar_version(), mesh_avatar_abi_version());
+ CHECK(mesh_avatar_open_path(path, &avatar));
+ CHECK(mesh_avatar_set_auto_idle(avatar, 0));
+ CHECK(mesh_avatar_set_auto_motion(avatar, 0));
+ MaParameter pose[] = {{"angleX", 15.0}, {"mouthOpen", 0.4}};
+ CHECK(mesh_avatar_set_parameters(avatar, pose, 2, 1.0));
+ CHECK(mesh_avatar_set_expression(avatar, "smile"));
+ CHECK(mesh_avatar_play(avatar, "nod"));
+ for (int i = 0; i < 60; ++i) CHECK(mesh_avatar_tick(avatar, 1.0 / 60.0));
+
+ MaAvatarInfo info;
+ size_t texture_count;
+ CHECK(mesh_avatar_get_info(avatar, &info));
+ CHECK(mesh_avatar_texture_count(avatar, &texture_count));
+ if (!info.image_width || !info.image_height || !texture_count) goto invalid;
+ for (size_t i = 0; i < texture_count; ++i) {
+ MaTexture texture;
+ CHECK(mesh_avatar_get_texture(avatar, i, &texture));
+ if (texture.id != i || !texture.name || !texture.rgba ||
+ texture.byte_count != (size_t)texture.width * texture.height * 4) goto invalid;
+ }
+
+ MaFrame frame;
+ CHECK(mesh_avatar_get_frame(avatar, &frame));
+ if (!frame.layer_count || !frame.layers) goto invalid;
+ size_t vertices = 0, indices = 0;
+ /* Borrowed arrays: read before calling tick/destroy, including on other threads. */
+ for (size_t i = 0; i < frame.layer_count; ++i) {
+ const MaLayer *layer = &frame.layers[i];
+ if (!layer->name || layer->texture_id >= texture_count || !isfinite(layer->alpha)) goto invalid;
+ if (layer->vertex_count && (!layer->positions || !layer->uvs)) goto invalid;
+ if (layer->index_count && !layer->indices) goto invalid;
+ for (size_t j = 0; j < layer->vertex_count * 2; ++j)
+ if (!isfinite(layer->positions[j]) || !isfinite(layer->uvs[j])) goto invalid;
+ for (size_t j = 0; j < layer->index_count; ++j)
+ if (layer->indices[j] >= layer->vertex_count) goto invalid;
+ vertices += layer->vertex_count;
+ indices += layer->index_count;
+ }
+ if (!isfinite(frame.uniforms.angles[0]) || !isfinite(frame.uniforms.mouth_state[0])) goto invalid;
+ printf("%ux%u: %zu textures, %zu layers, %zu vertices, %zu indices\n",
+ info.image_width, info.image_height, texture_count, frame.layer_count, vertices, indices);
+ if (mesh_avatar_get_frame(avatar, NULL) != MA_INVALID_ARGUMENT) goto invalid;
+ CHECK(mesh_avatar_destroy(avatar));
+ if (mesh_avatar_tick(avatar, 0.0) != MA_INVALID_HANDLE) goto invalid;
+ puts("C ABI checks passed");
+ return 0;
+invalid:
+ fputs("Invalid C ABI data or error behavior\n", stderr);
+failed:
+ if (avatar) (void)mesh_avatar_destroy(avatar);
+ return 1;
+}
diff --git a/native/include/mesh_avatar.h b/native/include/mesh_avatar.h
new file mode 100644
index 0000000..893a626
--- /dev/null
+++ b/native/include/mesh_avatar.h
@@ -0,0 +1,304 @@
+/* Experimental CPU-only Mesh Avatar C ABI.
+ *
+ * Handles are opaque uint64 tokens, not pointers. Zero/unknown/destroyed tokens
+ * are rejected, and IDs are never reused. Handles may be used from any thread;
+ * API calls on the same handle are serialized internally.
+ *
+ * All returned pointers are borrowed, read-only library storage: NEVER free or
+ * modify them. Frame/layer pointers (including names, arrays and descriptors)
+ * expire on the next tick or destroy of that handle. Texture name/RGBA pointers
+ * expire only at destroy. Copying a descriptor does not copy the pointed-to data.
+ * Callers MUST synchronize borrowed reads against tick/destroy on other threads.
+ *
+ * Input strings are readable UTF-8 NUL-terminated C strings. Nonempty input
+ * buffers must be readable/aligned for their specified lengths. Output pointers
+ * must be writable/aligned and must not alias inputs or borrowed library data.
+ * NULL pointers, invalid handle tokens and indices are checked; the caller is
+ * still responsible for non-NULL memory validity. Inputs are consumed/copied
+ * during the call and are never retained.
+ *
+ * Return values are MA_* status codes. A failed call sets a thread-local error;
+ * mesh_avatar_last_error returns it until the next API call on that thread.
+ * Default Cargo profiles use unwinding: Rust panics become MA_PANIC. A handle
+ * whose state panicked must be destroyed and reopened; other handles remain usable.
+ * No caller-visible allocation needs a separate free function.
+ * Destroy every handle before unloading the library. All borrowed pointers,
+ * including version/error strings, become invalid when the library is unloaded.
+ */
+
+
+#ifndef MESH_AVATAR_H
+#define MESH_AVATAR_H
+
+/* Generated by cbindgen 0.29.4. Do not edit; run conformance/ffi-header.sh. */
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef int32_t MaStatus;
+
+/**
+ * Opaque process-wide token. Zero is invalid. Never cast to a pointer or free it.
+ */
+typedef uint64_t MaHandle;
+
+/**
+ * Borrowed geometry. All pointers (including name) expire at next tick/destroy.
+ * positions and uvs contain vertex_count * 2 floats in x,y / u,v order.
+ * indices contains index_count uint32 values in triangle order; empty arrays are NULL.
+ * Positions use source-image pixels with a top-left origin; UVs address the layer texture.
+ * rect is [x, y, width, height] in source-image pixels.
+ */
+typedef struct {
+ const char *name;
+ uint32_t texture_id;
+ const float *positions;
+ const float *uvs;
+ size_t vertex_count;
+ const uint32_t *indices;
+ size_t index_count;
+ double rect[4];
+ double alpha;
+ /**
+ * 1 for a face layer, otherwise 0.
+ */
+ uint8_t face;
+ /**
+ * -1 for no eye-ball shader, 0 or 1 for the corresponding eye.
+ */
+ int32_t eye_ball;
+} MaLayer;
+
+/**
+ * Copied FaceUniforms fields in C layout, not a GPU uniform-buffer layout.
+ */
+typedef struct {
+ float angles[3];
+ float eye_box[2][4];
+ float eye_top[2][24];
+ float eye_bot[2][24];
+ float eyes[8];
+ float mouth[4];
+ float mouth_state[4];
+ float cheeks[4];
+ float cheek;
+} MaFaceUniforms;
+
+/**
+ * Copied descriptor with borrowed layers. layers points to layer_count MaLayer values.
+ * The descriptors and nested pointers expire at next tick/destroy; do not free them.
+ */
+typedef struct {
+ const MaLayer *layers;
+ size_t layer_count;
+ MaFaceUniforms uniforms;
+} MaFrame;
+
+/**
+ * Copied dimensions and viewport padding for a host renderer.
+ */
+typedef struct {
+ uint32_t image_width;
+ uint32_t image_height;
+ double pad_top;
+ double pad_side;
+} MaAvatarInfo;
+
+/**
+ * Borrowed immutable texture. name and rgba remain valid until destroy.
+ * RGBA is straight (not premultiplied) RGBA8, top-left origin, tightly packed.
+ */
+typedef struct {
+ uint32_t id;
+ const char *name;
+ uint32_t width;
+ uint32_t height;
+ const uint8_t *rgba;
+ size_t byte_count;
+} MaTexture;
+
+/**
+ * A UTF-8, NUL-terminated parameter name and finite value. Input is copied.
+ */
+typedef struct {
+ const char *name;
+ double value;
+} MaParameter;
+
+#define MA_OK 0
+
+#define MA_INVALID_ARGUMENT 1
+
+#define MA_INVALID_HANDLE 2
+
+#define MA_LOAD_ERROR 3
+
+#define MA_OUT_OF_RANGE 4
+
+#define MA_INVALID_STATE 5
+
+#define MA_PANIC 6
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ * Static UTF-8 version string. Borrowed for the lifetime of the loaded library.
+ */
+const char *mesh_avatar_version(void);
+
+/**
+ * ABI revision, currently 1. Zero indicates a contained failure.
+ */
+uint32_t mesh_avatar_abi_version(void);
+
+/**
+ * Thread-local UTF-8 error, valid until the next API call on this thread.
+ * Calling this function again does not invalidate it. Never free this pointer.
+ */
+const char *mesh_avatar_last_error(void);
+
+/**
+ * Open a .mavatar archive or built project folder and create its initial frame.
+ * On failure, *out is zero. Inputs are copied; no caller buffer is retained.
+ * # Safety
+ * path must be a readable UTF-8 NUL-terminated string; out must be writable/aligned.
+ */
+MaStatus mesh_avatar_open_path(const char *path, MaHandle *out);
+
+/**
+ * Open in-memory .mavatar ZIP bytes. Bytes need only remain valid during this call.
+ * # Safety
+ * bytes must be readable for length bytes (NULL allowed for zero length); out writable/aligned.
+ */
+MaStatus mesh_avatar_open_bytes(const uint8_t *bytes, size_t length, MaHandle *out);
+
+/**
+ * Destroy a handle from any thread. Rejects zero, unknown and already destroyed tokens.
+ * All pointers borrowed from this handle become invalid; callers must finish their reads first.
+ */
+MaStatus mesh_avatar_destroy(MaHandle handle);
+
+/**
+ * Advance by nonnegative finite seconds (the core caps the step at 0.05).
+ * Invalidates all prior frame/layer pointers. Setters alone leave the cached frame intact.
+ */
+MaStatus mesh_avatar_tick(MaHandle handle, double dt);
+
+/**
+ * Copy the current frame descriptor; nested pointers remain library-owned.
+ * # Safety
+ * out must be writable/aligned and must not alias borrowed library memory.
+ */
+MaStatus mesh_avatar_get_frame(MaHandle handle, MaFrame *out);
+
+/**
+ * Copy one layer descriptor. index is zero-based; pointers expire on tick/destroy.
+ * # Safety
+ * out must be writable/aligned and must not alias borrowed library memory.
+ */
+MaStatus mesh_avatar_get_layer(MaHandle handle, size_t index, MaLayer *out);
+
+/**
+ * Copy avatar dimensions and padding.
+ * # Safety
+ * out must be writable/aligned.
+ */
+MaStatus mesh_avatar_get_info(MaHandle handle, MaAvatarInfo *out);
+
+/**
+ * Copy texture count. IDs are zero-based indices and stable until destroy.
+ * # Safety
+ * out must be writable/aligned.
+ */
+MaStatus mesh_avatar_texture_count(MaHandle handle, size_t *out);
+
+/**
+ * Copy immutable straight-RGBA texture metadata; pointers expire only at destroy.
+ * # Safety
+ * out must be writable/aligned and must not alias borrowed library memory.
+ */
+MaStatus mesh_avatar_get_texture(MaHandle handle, size_t index, MaTexture *out);
+
+/**
+ * Replace all parameter overrides. NULL with count=0 clears them. weight must be in [0,1].
+ * Names/values are copied; supported names/ranges follow the core PARAMS plus eyeSmileL [0,1].
+ * At most 128 entries; duplicate names use the last value. Unknown/out-of-range values fail.
+ * # Safety
+ * values must be readable/aligned for count entries and each name a readable UTF-8 C string.
+ */
+MaStatus mesh_avatar_set_parameters(MaHandle handle,
+ const MaParameter *values,
+ size_t count,
+ double weight);
+
+/**
+ * Select a live expression: neutral, smile, shy, surprise, halfLidded, angry, sad or wink.
+ * # Safety
+ * name must be a readable UTF-8 NUL-terminated string.
+ */
+MaStatus mesh_avatar_set_expression(MaHandle handle, const char *name);
+
+/**
+ * Emotion tag: neutral, happy, sad, angry, surprised or relaxed. play_motion is 0 or 1.
+ * # Safety
+ * tag must be a readable UTF-8 NUL-terminated string.
+ */
+MaStatus mesh_avatar_set_emotion(MaHandle handle, const char *tag, uint8_t play_motion);
+
+/**
+ * Play a built-in motion by its ID, e.g. nod, no, sway or greeting.
+ * # Safety
+ * id must be a readable UTF-8 NUL-terminated string.
+ */
+MaStatus mesh_avatar_play(MaHandle handle, const char *id);
+
+/**
+ * Set normalized voice level in [0,1]; finite values only.
+ */
+MaStatus mesh_avatar_set_voice_level(MaHandle handle, double level);
+
+/**
+ * Set speaking state: 0 or 1.
+ */
+MaStatus mesh_avatar_set_speaking(MaHandle handle, uint8_t on);
+
+/**
+ * Run kana mouth shapes without audio. speed=0 uses the core default; otherwise mora/second,
+ * clamped by the core to [4,12]. looping is 0 or 1.
+ * # Safety
+ * text must be a readable UTF-8 NUL-terminated string; it is copied during this call.
+ */
+MaStatus mesh_avatar_speak_kana(MaHandle handle, const char *text, double speed, uint8_t looping);
+
+/**
+ * Hold a mouth vowel: a, i, u, e, o or n.
+ * # Safety
+ * vowel must be a readable UTF-8 C string.
+ */
+MaStatus mesh_avatar_hold_mouth(MaHandle handle, const char *vowel);
+
+/**
+ * Stop kana and held-vowel lip sync.
+ */
+MaStatus mesh_avatar_stop_lip_sync(MaHandle handle);
+
+/**
+ * Enable automatic idle: 0 or 1.
+ */
+MaStatus mesh_avatar_set_auto_idle(MaHandle handle, uint8_t on);
+
+/**
+ * Enable automatic motion: 0 or 1.
+ */
+MaStatus mesh_avatar_set_auto_motion(MaHandle handle, uint8_t on);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+
+#endif /* MESH_AVATAR_H */