Skip to content

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

Render avatars to RGBA buffers through the C ABI and check WASM builds

shinshin8665ae9aeb108d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c1826d0..0a11862 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -93,6 +93,7 @@ jobs:
uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
+ targets: wasm32-unknown-unknown
- name: Cache Cargo build
uses: Swatinem/rust-cache@v2
@@ -108,6 +109,15 @@ jobs:
- name: Run tests
run: cargo test
+ - name: Check core for WASM
+ run: cargo check -p mesh-avatar-core --target wasm32-unknown-unknown
+
+ - name: Lint optional renderer
+ run: cargo clippy -p mesh-avatar-ffi --all-targets --features render -- -D warnings
+
+ - name: Test optional renderer
+ run: cargo test -p mesh-avatar-ffi --features render
+
- name: Install pinned C header generator
run: cargo install cbindgen --version 0.29.4 --locked --root target/header-tools
@@ -119,3 +129,9 @@ jobs:
- name: Build and run C example
run: make -C examples/c run
+
+ - name: Build optional C renderer
+ run: cargo build --release -p mesh-avatar-ffi --features render
+
+ - name: Build and run headless C renderer example
+ run: make -C examples/c run-render
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 3df73ec..e1e26d8 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -1067,6 +1067,8 @@ name = "mesh-avatar-ffi"
version = "0.1.0"
dependencies = [
"mesh-avatar-core",
+ "mesh-avatar-wgpu",
+ "pollster",
"serde_json",
"zip",
]
diff --git a/native/README.ja.md b/native/README.ja.md
index 8b22837..b39f666 100644
--- a/native/README.ja.md
+++ b/native/README.ja.md
@@ -142,8 +142,27 @@ bash native/conformance/ffi-header.sh
bash native/conformance/ffi-header.sh --check
```
-CIも同じバージョンでヘッダーの差分を確認し、ライブラリとCサンプルをビルド・実行します。
-C ABIは実験的な段階です。GPU描画用の関数はまだないため、フレームデータをホスト側のレンダラーで描画してください。
+CIも同じバージョンで両ヘッダーの差分を確認し、ライブラリとCサンプルをビルド・実行します。C ABIは実験的な段階です。
+
+### 任意機能のヘッドレス描画
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
+make -C native/examples/c run-render
+```
+
+描画用には [`mesh_avatar_render.h`](include/mesh_avatar_render.h) を読み込みます。このヘッダーはCPU用ヘッダーを含むため、マクロの指定は不要です。
+描画関数は `render` を有効にしたライブラリでのみ利用できます。通常ビルドの依存先はcoreだけです。macOSでは、C用MakefileがMetalなどの必要なフレームワークをリンクします。
+
+アバターのハンドルと `MaRenderOptions` でレンダラーを作成します。物理ピクセルの幅・高さ、MSAAのサンプル数(1または4)、contain/cover、余白を指定します。余白の推奨値は `mesh_avatar_get_info` で取得できます。
+描画は現在のキャッシュ済みフレームを読み取り、呼び出し側のバッファへRGBA8を上の行から隙間なくコピーします。アニメーションは進みません。バッファは `幅*高さ*4` バイト以上必要で、ストレート/プリマルチプライドのアルファを選べます。
+描画はGPUからの読み戻しが完了するまで待ちます。バッファを保持せず、借用中のフレームデータも無効にしません。リサイズ後もfit・余白・サンプル数は維持されますが、呼び出し側のバッファもサイズに合わせて確保してください。不正なサイズやバッファはエラーとなり、出力バッファは変更されません。
+
+レンダラーはスレッド間で移動でき、同じレンダラー・アバターへの呼び出しは直列に処理されます。アバターを所有しないため、レンダラーを先に破棄してください。アバター破棄後の描画は `MA_INVALID_HANDLE` を返します。封じ込められたpanicの影響を受けたオブジェクトは破棄して作り直してください。
+対応するGPUアダプターがない場合は `MA_GPU_UNAVAILABLE`、それ以外のGPUエラーは `MA_RENDER_ERROR` を返します。サンプルとCIはアダプターがない場合だけ描画をスキップします。
+
+サンプルはアルファの両形式とリサイズを検証し、`native/target/ffi-render.ppm` に保存します。PPMはアルファを持たないため、ストレートRGBAを白背景に合成します。ウィンドウは開きません。
+CIではcoreの `wasm32-unknown-unknown` 向けビルドも確認します。JavaScriptバインディングは含みません。
## チェックと見た目の比較
diff --git a/native/README.md b/native/README.md
index 8418d7a..0718fbf 100644
--- a/native/README.md
+++ b/native/README.md
@@ -184,9 +184,41 @@ 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.
+CI installs that version, verifies both headers have no drift, builds both library
+types, and builds/runs the C examples. The C ABI remains experimental.
+
+### Optional headless rendering
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
+make -C native/examples/c run-render
+```
+
+Include [`mesh_avatar_render.h`](include/mesh_avatar_render.h) for this extension.
+It includes the CPU header and needs no macro; its functions are exported only
+when the library is built with `render`. Default builds depend only on core.
+On macOS, the C Makefile links the required Metal/system frameworks separately.
+
+Create a renderer with an avatar handle and `MaRenderOptions`: physical width/height,
+1 or 4 MSAA samples, contain/cover fit and explicit padding (available from
+`mesh_avatar_get_info`). Rendering reads the current cached frame without ticking
+and copies tightly packed, top-down RGBA8 into a caller-owned buffer of at least
+`width*height*4` bytes. Choose straight or premultiplied alpha. The synchronous
+readback does not retain the buffer or invalidate borrowed frame data. Resize
+keeps fit/padding/samples; resize the caller's buffer too. Invalid sizes/buffers
+return an error without changing the output buffer.
+
+Renderer calls may move between threads and are serialized per renderer and
+avatar. Renderers reference their avatar without owning it; destroy renderers
+before destroying the avatar. Rendering after avatar destruction returns
+`MA_INVALID_HANDLE`. Destroy/recreate objects affected by a contained panic.
+`MA_GPU_UNAVAILABLE` means no compatible adapter was found; other GPU errors use
+`MA_RENDER_ERROR`. The example/CI skip only the unavailable-adapter case.
+
+The example checks both alpha formats and resize, then writes
+`native/target/ffi-render.ppm` (straight RGBA composited over white, since PPM has
+no alpha). It does not open a window. CI also checks the core library for
+`wasm32-unknown-unknown`; JavaScript bindings are not included.
## Checks and visual comparison
diff --git a/native/README.zh.md b/native/README.zh.md
index 1ca112e..88f65f3 100644
--- a/native/README.zh.md
+++ b/native/README.zh.md
@@ -142,7 +142,26 @@ bash native/conformance/ffi-header.sh
bash native/conformance/ffi-header.sh --check
```
-CI使用相同版本检查头文件差异,并构建库、编译和运行C示例。C ABI仍为实验性功能,尚无GPU渲染入口;请用宿主渲染器绘制帧数据。
+CI使用相同版本检查两个头文件的差异,并构建库、编译和运行C示例。C ABI仍为实验性功能。
+
+### 可选的无窗口渲染
+
+```sh
+cargo build --release --manifest-path native/Cargo.toml -p mesh-avatar-ffi --features render
+make -C native/examples/c run-render
+```
+
+扩展使用 [`mesh_avatar_render.h`](include/mesh_avatar_render.h),它包含CPU头文件,无需定义宏。只有用 `render` 功能构建的库才导出这些函数。默认构建仅依赖core。macOS的C Makefile会链接Metal等所需的系统框架。
+
+用头像句柄和 `MaRenderOptions` 创建渲染器,指定物理像素宽高、MSAA采样数(1或4)、contain/cover以及显式留白。可从 `mesh_avatar_get_info` 取得建议的留白值。
+渲染读取当前缓存帧,不推进动画,将紧密排列、从顶行开始的RGBA8复制到调用方提供的缓冲区。缓冲区至少需要 `宽*高*4` 字节,可选择非预乘或预乘Alpha。
+同步调用会等待GPU读回完成,不保留调用方缓冲区,也不使借用的帧指针失效。调整大小会保留fit、留白和采样数;调用方也应按新尺寸分配缓冲区。无效尺寸或缓冲区返回错误,不修改输出缓冲区。
+
+渲染器可以跨线程使用,同一渲染器及头像上的调用会被串行化。渲染器只引用头像,不拥有它;请先销毁渲染器,再销毁头像。头像销毁后渲染返回 `MA_INVALID_HANDLE`。捕获panic后,应销毁并重建受影响的对象。
+没有兼容GPU适配器时返回 `MA_GPU_UNAVAILABLE`;其他GPU错误返回 `MA_RENDER_ERROR`。示例和CI只在没有适配器时跳过渲染。
+
+示例验证两种Alpha格式和尺寸调整,并写入 `native/target/ffi-render.ppm`。PPM不支持Alpha,因此会将非预乘RGBA合成到白色背景上。不会打开窗口。
+CI还检查core的 `wasm32-unknown-unknown` 构建,不包含JavaScript绑定。
## 检查与画面对比
diff --git a/native/conformance/ffi-header.sh b/native/conformance/ffi-header.sh
index ad51fb5..6c35e56 100644
--- a/native/conformance/ffi-header.sh
+++ b/native/conformance/ffi-header.sh
@@ -8,8 +8,13 @@ if [[ "$("$generator" --version)" != "cbindgen 0.29.4" ]]; then
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
+"$generator" --quiet --config crates/mesh-avatar-ffi/cbindgen-render.toml crates/mesh-avatar-ffi/src/render.rs --output target/generated/mesh_avatar_render.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 ;;
+ --check)
+ diff -u include/mesh_avatar.h target/generated/mesh_avatar.h
+ diff -u include/mesh_avatar_render.h target/generated/mesh_avatar_render.h ;;
+ "")
+ cp target/generated/mesh_avatar.h include/mesh_avatar.h
+ cp target/generated/mesh_avatar_render.h include/mesh_avatar_render.h ;;
*) echo "Usage: bash conformance/ffi-header.sh [--check]" >&2; exit 2 ;;
esac
diff --git a/native/crates/mesh-avatar-ffi/Cargo.toml b/native/crates/mesh-avatar-ffi/Cargo.toml
index 822d79e..af4b419 100644
--- a/native/crates/mesh-avatar-ffi/Cargo.toml
+++ b/native/crates/mesh-avatar-ffi/Cargo.toml
@@ -8,8 +8,14 @@ publish.workspace = true
[lib]
crate-type = ["cdylib", "staticlib", "rlib"]
+[features]
+default = []
+render = ["dep:mesh-avatar-wgpu", "dep:pollster"]
+
[dependencies]
mesh-avatar-core.workspace = true
+mesh-avatar-wgpu = { workspace = true, optional = true }
+pollster = { workspace = true, optional = true }
[dev-dependencies]
zip.workspace = true
diff --git a/native/crates/mesh-avatar-ffi/cbindgen-render.toml b/native/crates/mesh-avatar-ffi/cbindgen-render.toml
new file mode 100644
index 0000000..1300b07
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/cbindgen-render.toml
@@ -0,0 +1,30 @@
+language = "C"
+include_guard = "MESH_AVATAR_RENDER_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
+includes = ["mesh_avatar.h"]
+header = """
+/* Optional headless rendering extension to mesh_avatar.h.
+ * Build the library with --features render before linking these functions.
+ * The default CPU-only library does NOT export them. Including this header
+ * requires no macro and does not enable the library feature.
+ *
+ * Renderers use opaque never-reused tokens and per-renderer serialization.
+ * They reference an avatar token without owning it; destroy renderers before
+ * destroying their avatar. Rendering reads the cached frame without ticking.
+ * Raw geometry borrowers must still synchronize their reads against tick/destroy.
+ * All renderer functions use the core MaStatus and thread-local last-error API.
+ * Recover from a contained GPU panic by destroying/reopening the affected objects.
+ * Destroy all avatars/renderers before unloading the library.
+ */
+"""
+
+[parse]
+parse_deps = false
+
+[export]
+item_types = ["constants", "structs", "typedefs", "functions"]
+exclude = ["RenderEntry", "RenderEntries", "Result", "Error"]
diff --git a/native/crates/mesh-avatar-ffi/cbindgen.toml b/native/crates/mesh-avatar-ffi/cbindgen.toml
index 129d835..95a868e 100644
--- a/native/crates/mesh-avatar-ffi/cbindgen.toml
+++ b/native/crates/mesh-avatar-ffi/cbindgen.toml
@@ -40,4 +40,4 @@ parse_deps = false
[export]
item_types = ["constants", "enums", "structs", "typedefs", "functions"]
-exclude = ["Entries", "Entry", "CachedFrame", "Error", "Result"]
+exclude = ["Entries", "Entry", "CachedFrame", "Error", "Result", "RenderEntry", "RenderEntries", "MaRenderer", "MaRenderOptions", "MA_GPU_UNAVAILABLE", "MA_RENDER_ERROR", "MA_FIT_CONTAIN", "MA_FIT_COVER", "MA_RGBA_STRAIGHT", "MA_RGBA_PREMULTIPLIED", "mesh_avatar_renderer_create", "mesh_avatar_renderer_render", "mesh_avatar_renderer_resize", "mesh_avatar_renderer_destroy"]
diff --git a/native/crates/mesh-avatar-ffi/src/lib.rs b/native/crates/mesh-avatar-ffi/src/lib.rs
index 402f332..ddc67fc 100644
--- a/native/crates/mesh-avatar-ffi/src/lib.rs
+++ b/native/crates/mesh-avatar-ffi/src/lib.rs
@@ -1,6 +1,8 @@
//! A C ABI over the CPU runtime. The checked-in header defines the ownership contract.
#![deny(unsafe_op_in_unsafe_fn)]
mod boundary;
+#[cfg(feature = "render")]
+pub mod render;
mod state;
mod types;
use boundary::{boundary, check_out, flag, input_slice, input_str, Error};
diff --git a/native/crates/mesh-avatar-ffi/src/render.rs b/native/crates/mesh-avatar-ffi/src/render.rs
new file mode 100644
index 0000000..2483197
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/render.rs
@@ -0,0 +1,291 @@
+//! Optional headless rendering. Every exported function requires the render feature.
+use crate::{
+ boundary::{boundary, check_out, Error, Result},
+ state,
+ types::*,
+};
+use mesh_avatar_wgpu::{wgpu, Fit, Renderer, ViewOptions};
+use std::{
+ collections::BTreeMap,
+ sync::{Arc, Mutex, OnceLock},
+};
+
+/// Opaque renderer token. Uses a separate registry from avatar handles; zero is invalid.
+pub type MaRenderer = u64;
+pub const MA_GPU_UNAVAILABLE: MaStatus = 7;
+pub const MA_RENDER_ERROR: MaStatus = 8;
+pub const MA_FIT_CONTAIN: u32 = 0;
+pub const MA_FIT_COVER: u32 = 1;
+pub const MA_RGBA_STRAIGHT: u32 = 0;
+pub const MA_RGBA_PREMULTIPLIED: u32 = 1;
+
+/// Physical output pixels, MSAA samples (1 or 4), fit and explicit viewport padding.
+/// Use mesh_avatar_get_info to obtain the avatar's recommended pad_top/pad_side.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct MaRenderOptions {
+ pub width: u32,
+ pub height: u32,
+ pub samples: u32,
+ /// MA_FIT_CONTAIN or MA_FIT_COVER.
+ pub fit: u32,
+ /// Finite and greater than -1.
+ pub pad_top: f64,
+ /// Finite and greater than -0.5.
+ pub pad_side: f64,
+}
+
+struct RenderEntry {
+ renderer: Renderer,
+ device: wgpu::Device,
+ avatar: MaHandle,
+ size: [u32; 2],
+ view: ViewOptions,
+ alive: bool,
+}
+type RenderEntries = BTreeMap<MaRenderer, Arc<Mutex<RenderEntry>>>;
+static RENDERERS: OnceLock<Mutex<RenderEntries>> = OnceLock::new();
+fn renderers() -> &'static Mutex<RenderEntries> {
+ RENDERERS.get_or_init(|| Mutex::new(BTreeMap::new()))
+}
+fn with_renderer<T>(id: MaRenderer, work: impl FnOnce(&mut RenderEntry) -> Result<T>) -> Result<T> {
+ let shared = renderers()
+ .lock()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "renderer registry is poisoned"))?
+ .get(&id)
+ .cloned()
+ .ok_or_else(|| Error::new(MA_INVALID_HANDLE, "invalid or destroyed renderer"))?;
+ let mut entry = shared.lock().map_err(|_| {
+ Error::new(
+ MA_INVALID_STATE,
+ "renderer panicked; destroy and recreate it",
+ )
+ })?;
+ if !entry.alive {
+ return Err(Error::new(MA_INVALID_HANDLE, "destroyed renderer"));
+ }
+ work(&mut entry)
+}
+fn rgba_length(size: [u32; 2]) -> Result<usize> {
+ let bytes = u64::from(size[0]) * u64::from(size[1]);
+ let bytes = bytes.checked_mul(4).filter(|&n| {
+ // The shared renderer also uses u32 pixel arithmetic internally.
+ n <= u64::from(u32::MAX) && n <= isize::MAX as u64
+ });
+ if size.contains(&0) || bytes.is_none() {
+ return Err(Error::new(MA_INVALID_ARGUMENT, "invalid output dimensions"));
+ }
+ Ok(bytes.unwrap() as usize)
+}
+fn validate_target(size: [u32; 2], view: &ViewOptions, limits: &wgpu::Limits) -> Result<usize> {
+ let length = rgba_length(size)?;
+ let transform = view
+ .transform(size)
+ .map_err(|e| Error::new(MA_INVALID_ARGUMENT, e.to_string()))?;
+ let stride = (u64::from(size[0]) * 4).div_ceil(256) * 256;
+ if !transform.iter().all(|v| v.is_finite())
+ || size.iter().any(|&v| v > limits.max_texture_dimension_2d)
+ || stride * u64::from(size[1]) > limits.max_buffer_size
+ {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "output exceeds GPU texture/buffer limits or has an invalid transform",
+ ));
+ }
+ Ok(length)
+}
+fn render_error(error: impl std::fmt::Display) -> Error {
+ Error::new(MA_RENDER_ERROR, format!("GPU render error: {error}"))
+}
+
+/// Create a headless renderer bound to avatar's textures. Requires the render feature.
+/// Returns MA_GPU_UNAVAILABLE only when no compatible adapter can be found; otherwise
+/// GPU initialization failures return MA_RENDER_ERROR. On failure *out is zero.
+/// Calls on a renderer are serialized; it may move between threads. It does not own
+/// the avatar. Destroy the renderer before the avatar; rendering a destroyed avatar fails.
+/// # Safety
+/// options must be readable/aligned; out writable/aligned. Pointers must not alias.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_renderer_create(
+ avatar: MaHandle,
+ options: *const MaRenderOptions,
+ out: *mut MaRenderer,
+) -> MaStatus {
+ boundary(|| {
+ check_out(out)?;
+ // SAFETY: Caller provides a writable output slot; checked for NULL/alignment.
+ unsafe { out.write(0) };
+ state::with_entry(avatar, |entry| {
+ check_out(options.cast_mut())?;
+ // SAFETY: Caller supplies a readable/aligned options value.
+ let options = unsafe { options.read() };
+ let size = [options.width, options.height];
+ rgba_length(size)?;
+ if !matches!(options.samples, 1 | 4) {
+ return Err(Error::new(MA_INVALID_ARGUMENT, "samples must be 1 or 4"));
+ }
+ let fit = match options.fit {
+ MA_FIT_CONTAIN => Fit::Contain,
+ MA_FIT_COVER => Fit::Cover,
+ _ => return Err(Error::new(MA_INVALID_ARGUMENT, "unknown fit mode")),
+ };
+ let image = &entry.avatar.package().rig.image;
+ let view = ViewOptions {
+ image_size: [image.width, image.height],
+ pad_top: options.pad_top,
+ pad_side: options.pad_side,
+ fit,
+ };
+ view.transform(size)
+ .map_err(|e| Error::new(MA_INVALID_ARGUMENT, e.to_string()))?;
+ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
+ let adapter =
+ pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ compatible_surface: None,
+ force_fallback_adapter: false,
+ }))
+ .map_err(|e| {
+ Error::new(
+ MA_GPU_UNAVAILABLE,
+ format!("no compatible GPU adapter: {e}"),
+ )
+ })?;
+ let format = wgpu::TextureFormat::Rgba8Unorm;
+ if !adapter
+ .get_texture_format_features(format)
+ .flags
+ .sample_count_supported(options.samples)
+ {
+ return Err(render_error("requested MSAA count is unavailable"));
+ }
+ let (device, queue) =
+ pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
+ label: Some("mesh avatar C renderer"),
+ ..Default::default()
+ }))
+ .map_err(render_error)?;
+ validate_target(size, &view, &device.limits())?;
+ let renderer = Renderer::new(
+ &device,
+ &queue,
+ format,
+ options.samples,
+ entry.avatar.textures(),
+ )
+ .map_err(render_error)?;
+ let id = state::allocate_handle()?;
+ renderers()
+ .lock()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "renderer registry is poisoned"))?
+ .insert(
+ id,
+ Arc::new(Mutex::new(RenderEntry {
+ renderer,
+ device,
+ avatar,
+ size,
+ view,
+ alive: true,
+ })),
+ );
+ // SAFETY: Validated caller-owned slot.
+ unsafe { out.write(id) };
+ Ok(())
+ })
+ })
+}
+
+/// Render the current cached frame without ticking or invalidating borrowed geometry.
+/// Requires the render feature. rgba must hold at least width*height*4 bytes for the
+/// current size. Writes tightly packed RGBA8, top row first, with transparent clear.
+/// alpha_mode is MA_RGBA_STRAIGHT or MA_RGBA_PREMULTIPLIED. Extra bytes are untouched.
+/// The synchronous call waits for readback. The buffer is never retained and remains
+/// unchanged on failure. The caller must synchronize concurrent access to its buffer.
+/// Calls acquire the renderer before the avatar lock; tick/render/destroy are serialized.
+/// # Safety
+/// rgba must be writable for length bytes, non-NULL, and must not alias library storage.
+#[no_mangle]
+pub unsafe extern "C" fn mesh_avatar_renderer_render(
+ renderer: MaRenderer,
+ rgba: *mut u8,
+ length: usize,
+ alpha_mode: u32,
+) -> MaStatus {
+ boundary(|| {
+ with_renderer(renderer, |entry| {
+ let needed = rgba_length(entry.size)?;
+ if rgba.is_null()
+ || length < needed
+ || length > isize::MAX as usize
+ || !matches!(alpha_mode, MA_RGBA_STRAIGHT | MA_RGBA_PREMULTIPLIED)
+ {
+ return Err(Error::new(
+ MA_INVALID_ARGUMENT,
+ "invalid output buffer or alpha mode",
+ ));
+ }
+ // A renderer lock is always taken before an avatar lock; no API reverses this order.
+ state::with_entry(entry.avatar, |avatar| {
+ let frame = avatar
+ .frame
+ .as_ref()
+ .ok_or_else(|| Error::new(MA_INVALID_STATE, "no current avatar frame"))?;
+ let pixels = if alpha_mode == MA_RGBA_STRAIGHT {
+ entry
+ .renderer
+ .render_rgba(frame.frame(), entry.size, &entry.view)
+ } else {
+ entry
+ .renderer
+ .render_rgba_premultiplied(frame.frame(), entry.size, &entry.view)
+ }
+ .map_err(render_error)?;
+ if pixels.len() != needed {
+ return Err(render_error("unexpected readback size"));
+ }
+ // SAFETY: Caller guarantees writable/nonaliasing memory; size was checked above.
+ unsafe { std::ptr::copy_nonoverlapping(pixels.as_ptr(), rgba, needed) };
+ Ok(())
+ })
+ })
+ })
+}
+
+/// Change physical output size, keeping fit/padding/MSAA. Requires the render feature.
+/// Invalid sizes leave the renderer unchanged. Reallocate caller buffers before rendering.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_renderer_resize(
+ renderer: MaRenderer,
+ width: u32,
+ height: u32,
+) -> MaStatus {
+ boundary(|| {
+ with_renderer(renderer, |entry| {
+ validate_target([width, height], &entry.view, &entry.device.limits())?;
+ entry.size = [width, height];
+ Ok(())
+ })
+ })
+}
+
+/// Destroy a renderer from any thread, including after a contained panic.
+/// Requires the render feature. Rejects zero, unknown or destroyed tokens.
+#[no_mangle]
+pub extern "C" fn mesh_avatar_renderer_destroy(renderer: MaRenderer) -> MaStatus {
+ boundary(|| {
+ let shared = renderers()
+ .lock()
+ .map_err(|_| Error::new(MA_INVALID_STATE, "renderer registry is poisoned"))?
+ .remove(&renderer)
+ .ok_or_else(|| Error::new(MA_INVALID_HANDLE, "invalid or destroyed renderer"))?;
+ let mut entry = shared
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ entry.alive = false;
+ Ok(())
+ })
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/native/crates/mesh-avatar-ffi/src/render/tests.rs b/native/crates/mesh-avatar-ffi/src/render/tests.rs
new file mode 100644
index 0000000..bc3c4ef
--- /dev/null
+++ b/native/crates/mesh-avatar-ffi/src/render/tests.rs
@@ -0,0 +1,288 @@
+use super::*;
+use crate::{mesh_avatar_destroy, mesh_avatar_get_frame, mesh_avatar_open_path, mesh_avatar_tick};
+use std::{ffi::CString, mem::MaybeUninit, path::Path, ptr};
+
+fn avatar() -> MaHandle {
+ let path = CString::new(
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../../samples/miko-qipao")
+ .to_str()
+ .unwrap(),
+ )
+ .unwrap();
+ let mut out = 0;
+ assert_eq!(
+ unsafe { mesh_avatar_open_path(path.as_ptr(), &mut out) },
+ MA_OK
+ );
+ out
+}
+fn options() -> MaRenderOptions {
+ MaRenderOptions {
+ width: 65,
+ height: 80,
+ samples: 1,
+ fit: MA_FIT_CONTAIN,
+ pad_top: 0.15,
+ pad_side: 0.1,
+ }
+}
+fn create(avatar: MaHandle, options: &MaRenderOptions) -> Option<MaRenderer> {
+ let mut out = 0;
+ let status = unsafe { mesh_avatar_renderer_create(avatar, options, &mut out) };
+ if status == MA_GPU_UNAVAILABLE {
+ assert_eq!(out, 0);
+ eprintln!("No compatible GPU adapter; skipping renderer readback test.");
+ return None;
+ }
+ assert_eq!(status, MA_OK);
+ assert_ne!(out, 0);
+ Some(out)
+}
+
+#[test]
+fn invalid_tokens_options_sizes_and_layout_are_checked_before_gpu_use() {
+ assert_eq!(mesh_avatar_renderer_destroy(0), MA_INVALID_HANDLE);
+ assert_eq!(
+ mesh_avatar_renderer_resize(u64::MAX, 1, 1),
+ MA_INVALID_HANDLE
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_render(0, ptr::null_mut(), 0, 0) },
+ MA_INVALID_HANDLE
+ );
+ let mut out = 99;
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_create(0, ptr::null(), &mut out) },
+ MA_INVALID_HANDLE
+ );
+ assert_eq!(out, 0);
+ let h = avatar();
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_create(h, &options(), ptr::null_mut()) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_create(h, ptr::null(), &mut out) },
+ MA_INVALID_ARGUMENT
+ );
+ let misaligned = ptr::dangling::<u8>().cast::<MaRenderOptions>();
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_create(h, misaligned, &mut out) },
+ MA_INVALID_ARGUMENT
+ );
+ for bad in [
+ MaRenderOptions {
+ width: 0,
+ ..options()
+ },
+ MaRenderOptions {
+ width: u32::MAX,
+ height: u32::MAX,
+ ..options()
+ },
+ MaRenderOptions {
+ samples: 2,
+ ..options()
+ },
+ MaRenderOptions {
+ fit: 123,
+ ..options()
+ },
+ MaRenderOptions {
+ pad_top: f64::NAN,
+ ..options()
+ },
+ MaRenderOptions {
+ pad_top: -1.0,
+ ..options()
+ },
+ MaRenderOptions {
+ pad_side: -0.5,
+ ..options()
+ },
+ ] {
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_create(h, &bad, &mut out) },
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(out, 0);
+ }
+ assert_eq!(
+ rgba_length([u32::MAX, 2]).err().unwrap().code,
+ MA_INVALID_ARGUMENT
+ );
+ let limits = wgpu::Limits::default();
+ let view = ViewOptions {
+ image_size: [100, 100],
+ pad_top: 0.0,
+ pad_side: 0.0,
+ fit: Fit::Contain,
+ };
+ assert!(validate_target([limits.max_texture_dimension_2d + 1, 1], &view, &limits).is_err());
+ assert!(validate_target(
+ [8192, 8192],
+ &view,
+ &wgpu::Limits {
+ max_buffer_size: 100,
+ ..limits
+ }
+ )
+ .is_err());
+ assert_eq!(mesh_avatar_destroy(h), MA_OK);
+}
+
+#[test]
+fn readback_preserves_cache_checks_buffers_and_handles_resize_and_both_alpha_modes() {
+ let h = avatar();
+ let Some(r) = create(h, &options()) else {
+ mesh_avatar_destroy(h);
+ return;
+ };
+ let mut before = MaybeUninit::<MaFrame>::uninit();
+ assert_eq!(
+ unsafe { mesh_avatar_get_frame(h, before.as_mut_ptr()) },
+ MA_OK
+ );
+ let before = unsafe { before.assume_init() };
+ let needed = 65 * 80 * 4;
+ let mut straight = vec![77_u8; needed + 8];
+ for (buffer, length, mode) in [
+ (ptr::null_mut(), needed, MA_RGBA_STRAIGHT),
+ (straight.as_mut_ptr(), needed - 1, MA_RGBA_STRAIGHT),
+ (straight.as_mut_ptr(), usize::MAX, MA_RGBA_STRAIGHT),
+ (straight.as_mut_ptr(), needed, 99),
+ ] {
+ assert_eq!(
+ unsafe { mesh_avatar_renderer_render(r, buffer, length, mode) },
+ MA_INVALID_ARGUMENT
+ );
+ }
+ assert!(straight.iter().all(|&v| v == 77));
+ assert_eq!(
+ unsafe {
+ mesh_avatar_renderer_render(r, straight.as_mut_ptr(), straight.len(), MA_RGBA_STRAIGHT)
+ },
+ MA_OK
+ );
+ assert_eq!(&straight[needed..], &[77; 8]);
+ let mut premultiplied = vec![0; needed];
+ assert_eq!(
+ unsafe {
+ mesh_avatar_renderer_render(
+ r,
+ premultiplied.as_mut_ptr(),
+ needed,
+ MA_RGBA_PREMULTIPLIED,
+ )
+ },
+ MA_OK
+ );
+ assert!(straight[..needed]
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .any(|p| p[3] == 0));
+ assert!(straight[..needed]
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .any(|p| p[3] > 0));
+ for (s, p) in straight[..needed]
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .zip(premultiplied.as_chunks::<4>().0.iter())
+ {
+ assert_eq!(s[3], p[3]);
+ for c in 0..3 {
+ let expected = ((u32::from(s[c]) * u32::from(s[3]) + 127) / 255) as u8;
+ assert!(p[c].abs_diff(expected) <= 1);
+ }
+ }
+ let mut after = MaybeUninit::<MaFrame>::uninit();
+ assert_eq!(
+ unsafe { mesh_avatar_get_frame(h, after.as_mut_ptr()) },
+ MA_OK
+ );
+ assert_eq!(before.layers, unsafe { after.assume_init() }.layers);
+ assert_eq!(mesh_avatar_renderer_resize(r, 0, 8), MA_INVALID_ARGUMENT);
+ assert_eq!(
+ mesh_avatar_renderer_resize(r, u32::MAX, 8),
+ MA_INVALID_ARGUMENT
+ );
+ assert_eq!(mesh_avatar_renderer_resize(r, 33, 17), MA_OK);
+ let moved = std::thread::spawn(move || {
+ let mut bytes = vec![0; 33 * 17 * 4];
+ assert_eq!(
+ unsafe {
+ mesh_avatar_renderer_render(r, bytes.as_mut_ptr(), bytes.len(), MA_RGBA_STRAIGHT)
+ },
+ MA_OK
+ );
+ assert!(bytes.as_chunks::<4>().0.iter().any(|p| p[3] != 0));
+ });
+ moved.join().unwrap();
+ // Concurrent tick and render are synchronized without exposing borrowed pixels.
+ let ticking = std::thread::spawn(move || {
+ for _ in 0..20 {
+ assert_eq!(mesh_avatar_tick(h, 0.01), MA_OK);
+ }
+ });
+ let mut bytes = vec![0; 33 * 17 * 4];
+ assert_eq!(
+ unsafe {
+ mesh_avatar_renderer_render(r, bytes.as_mut_ptr(), bytes.len(), MA_RGBA_STRAIGHT)
+ },
+ MA_OK
+ );
+ ticking.join().unwrap();
+ assert_eq!(mesh_avatar_renderer_destroy(h), MA_INVALID_HANDLE);
+ assert_eq!(mesh_avatar_destroy(r), MA_INVALID_HANDLE);
+ assert_eq!(mesh_avatar_renderer_destroy(r), MA_OK);
+ assert_eq!(mesh_avatar_renderer_destroy(r), MA_INVALID_HANDLE);
+ assert_eq!(mesh_avatar_renderer_resize(r, 1, 1), MA_INVALID_HANDLE);
+ assert_eq!(mesh_avatar_destroy(h), MA_OK);
+}
+
+#[test]
+fn cover_msaa_destroyed_avatars_and_renderer_panics_are_contained() {
+ let h = avatar();
+ let Some(r) = create(
+ h,
+ &MaRenderOptions {
+ fit: MA_FIT_COVER,
+ samples: 4,
+ ..options()
+ },
+ ) else {
+ mesh_avatar_destroy(h);
+ return;
+ };
+ let mut bytes = vec![0; 65 * 80 * 4];
+ assert_eq!(
+ unsafe {
+ mesh_avatar_renderer_render(r, bytes.as_mut_ptr(), bytes.len(), MA_RGBA_STRAIGHT)
+ },
+ MA_OK
+ );
+ assert_eq!(
+ boundary(|| with_renderer(r, |_| -> Result<()> { panic!("injected renderer panic") })),
+ MA_PANIC
+ );
+ assert_eq!(mesh_avatar_renderer_resize(r, 16, 16), MA_INVALID_STATE);
+ assert_eq!(mesh_avatar_tick(h, 0.0), MA_OK);
+ assert_eq!(mesh_avatar_renderer_destroy(r), MA_OK);
+ let r2 = create(h, &options()).unwrap();
+ assert_ne!(r, r2);
+ assert_eq!(mesh_avatar_destroy(h), MA_OK);
+ bytes.fill(88);
+ assert_eq!(
+ unsafe {
+ mesh_avatar_renderer_render(r2, bytes.as_mut_ptr(), bytes.len(), MA_RGBA_STRAIGHT)
+ },
+ MA_INVALID_HANDLE
+ );
+ assert!(bytes.iter().all(|&v| v == 88));
+ assert_eq!(mesh_avatar_renderer_destroy(r2), MA_OK);
+}
diff --git a/native/crates/mesh-avatar-ffi/src/state.rs b/native/crates/mesh-avatar-ffi/src/state.rs
index c5c9d35..7a73e3b 100644
--- a/native/crates/mesh-avatar-ffi/src/state.rs
+++ b/native/crates/mesh-avatar-ffi/src/state.rs
@@ -30,6 +30,10 @@ pub(crate) struct CachedFrame {
// mutex; C callers must synchronize borrowed reads against tick/destroy.
unsafe impl Send for CachedFrame {}
impl CachedFrame {
+ #[cfg(feature = "render")]
+ pub fn frame(&self) -> &Frame {
+ &self._frame
+ }
fn new(frame: Frame, ids: &BTreeMap<String, u32>) -> Result<Self> {
let names: Vec<_> = frame
.layers
@@ -152,15 +156,17 @@ fn entries() -> &'static Mutex<Entries> {
}
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"))?;
+ let id = allocate_handle()?;
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 allocate_handle() -> Result<MaHandle> {
+ NEXT.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| v.checked_add(1))
+ .map_err(|_| Error::new(MA_INVALID_STATE, "handle space exhausted"))
+}
pub(crate) fn with_entry<T>(
handle: MaHandle,
work: impl FnOnce(&mut Entry) -> Result<T>,
diff --git a/native/crates/mesh-avatar-wgpu/src/lib.rs b/native/crates/mesh-avatar-wgpu/src/lib.rs
index 1cf1f6d..1b28dad 100644
--- a/native/crates/mesh-avatar-wgpu/src/lib.rs
+++ b/native/crates/mesh-avatar-wgpu/src/lib.rs
@@ -550,6 +550,24 @@ impl Renderer {
frame: &Frame,
size: [u32; 2],
view: &ViewOptions,
+ ) -> Result<Vec<u8>> {
+ self.read_rgba(frame, size, view, true)
+ }
+ /// Render and read back tightly packed premultiplied RGBA8, top row first.
+ pub fn render_rgba_premultiplied(
+ &mut self,
+ frame: &Frame,
+ size: [u32; 2],
+ view: &ViewOptions,
+ ) -> Result<Vec<u8>> {
+ self.read_rgba(frame, size, view, false)
+ }
+ fn read_rgba(
+ &mut self,
+ frame: &Frame,
+ size: [u32; 2],
+ view: &ViewOptions,
+ straight: bool,
) -> Result<Vec<u8>> {
ensure!(
self.format == wgpu::TextureFormat::Rgba8Unorm,
@@ -620,6 +638,10 @@ impl Renderer {
let bytes = buffer.slice(..).get_mapped_range();
let mut out = Vec::with_capacity((size[0] * size[1] * 4) as usize);
for row in bytes.chunks_exact(stride as usize) {
+ if !straight {
+ out.extend_from_slice(&row[..(size[0] * 4) as usize]);
+ continue;
+ }
for p in row[..(size[0] * 4) as usize].as_chunks::<4>().0 {
let alpha = u32::from(p[3]);
let unpremultiply = |value: u8| {
@@ -718,6 +740,16 @@ mod tests {
for (actual, expected) in first[center..center + 4].iter().zip([200_u8, 100, 50, 128]) {
assert!(actual.abs_diff(expected) <= 1);
}
+ let premultiplied = renderer
+ .render_rgba_premultiplied(&frame, [8, 8], &view)
+ .unwrap();
+ assert_eq!(&premultiplied[..4], &[0, 0, 0, 0]);
+ for (actual, expected) in premultiplied[center..center + 4]
+ .iter()
+ .zip([100_u8, 50, 25, 128])
+ {
+ assert!(actual.abs_diff(expected) <= 1);
+ }
for position in frame.layers[0].positions.as_chunks_mut::<2>().0 {
position[0] += 1.0;
}
diff --git a/native/examples/c/Makefile b/native/examples/c/Makefile
index cce2ff1..f5e65ad 100644
--- a/native/examples/c/Makefile
+++ b/native/examples/c/Makefile
@@ -1,18 +1,26 @@
CC ?= cc
NATIVE := ../..
OUT := $(NATIVE)/target/ffi-example
+RENDER_OUT := $(NATIVE)/target/ffi-render-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
+RENDER_LDLIBS ?= -framework Foundation -framework QuartzCore -framework Metal -framework CoreGraphics -framework CoreFoundation -lobjc -liconv -lm
else
LDLIBS ?= -ldl -lpthread -lm
+RENDER_LDLIBS ?= $(LDLIBS)
endif
-.PHONY: all run
+.PHONY: all run render run-render
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
+render: $(RENDER_OUT)
+$(RENDER_OUT): render.c $(NATIVE)/include/mesh_avatar.h $(NATIVE)/include/mesh_avatar_render.h $(LIB)
+ $(CC) $(CFLAGS) -I$(NATIVE)/include render.c $(LIB) $(RENDER_LDLIBS) -o $@
+run-render: $(RENDER_OUT)
+ $(RENDER_OUT) $(NATIVE)/../samples/miko-qipao $(NATIVE)/target/ffi-render.ppm
diff --git a/native/examples/c/render.c b/native/examples/c/render.c
new file mode 100644
index 0000000..a2dadfb
--- /dev/null
+++ b/native/examples/c/render.c
@@ -0,0 +1,88 @@
+#include "mesh_avatar_render.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#define CHECK(call) do { \
+ MaStatus status_ = (call); \
+ if (status_ != MA_OK) { \
+ fprintf(stderr, "%s: %d: %s\n", #call, status_, mesh_avatar_last_error()); \
+ goto cleanup; \
+ } \
+} while (0)
+
+/* PPM has no alpha channel: composite the straight RGBA result over white. */
+static int write_ppm(const char *path, const uint8_t *rgba, uint32_t width, uint32_t height) {
+ FILE *file = fopen(path, "wb");
+ if (!file) { perror(path); return 0; }
+ int ok = fprintf(file, "P6\n%u %u\n255\n", width, height) > 0;
+ size_t pixels = (size_t)width * height;
+ for (size_t i = 0; ok && i < pixels; ++i) {
+ const uint8_t *p = rgba + i * 4;
+ uint8_t rgb[3];
+ for (size_t c = 0; c < 3; ++c) {
+ rgb[c] = (uint8_t)(((unsigned)p[c] * p[3] + 255u * (255u - p[3]) + 127u) / 255u);
+ }
+ ok = fwrite(rgb, 1, sizeof rgb, file) == sizeof rgb;
+ }
+ if (fclose(file) != 0) ok = 0;
+ return ok;
+}
+
+int main(int argc, char **argv) {
+ const char *source = argc > 1 ? argv[1] : "../samples/miko-qipao";
+ const char *output = argc > 2 ? argv[2] : "target/ffi-render.ppm";
+ MaHandle avatar = 0;
+ MaRenderer renderer = 0;
+ MaAvatarInfo info;
+ MaFrame before, after;
+ uint8_t *straight = NULL, *premultiplied = NULL;
+ int result = EXIT_FAILURE;
+ CHECK(mesh_avatar_open_path(source, &avatar));
+ CHECK(mesh_avatar_set_auto_idle(avatar, 0));
+ CHECK(mesh_avatar_set_auto_motion(avatar, 0));
+ CHECK(mesh_avatar_set_expression(avatar, "smile"));
+ CHECK(mesh_avatar_tick(avatar, 1.0 / 60.0));
+ CHECK(mesh_avatar_get_info(avatar, &info));
+ MaRenderOptions options = {257, 320, 4, MA_FIT_CONTAIN, info.pad_top, info.pad_side};
+ MaStatus status = mesh_avatar_renderer_create(avatar, &options, &renderer);
+ if (status == MA_GPU_UNAVAILABLE) {
+ fprintf(stderr, "SKIP: %s\n", mesh_avatar_last_error());
+ result = EXIT_SUCCESS;
+ goto cleanup;
+ }
+ CHECK(status);
+ size_t length = (size_t)options.width * options.height * 4;
+ straight = malloc(length);
+ premultiplied = malloc(length);
+ if (!straight || !premultiplied) { fputs("Allocation failed\n", stderr); goto cleanup; }
+ CHECK(mesh_avatar_get_frame(avatar, &before));
+ CHECK(mesh_avatar_renderer_render(renderer, straight, length, MA_RGBA_STRAIGHT));
+ CHECK(mesh_avatar_renderer_render(renderer, premultiplied, length, MA_RGBA_PREMULTIPLIED));
+ CHECK(mesh_avatar_get_frame(avatar, &after));
+ if (before.layers != after.layers) { fputs("Render replaced cached frame\n", stderr); goto cleanup; }
+ size_t transparent = 0, visible = 0;
+ for (size_t i = 0; i < length; i += 4) {
+ unsigned alpha = straight[i + 3];
+ transparent += alpha == 0;
+ visible += alpha != 0;
+ if (premultiplied[i + 3] != alpha) goto cleanup;
+ for (size_t c = 0; c < 3; ++c) {
+ int expected = (int)(((unsigned)straight[i + c] * alpha + 127u) / 255u);
+ int actual = premultiplied[i + c];
+ if (abs(expected - actual) > 1) { fputs("Alpha conversion mismatch\n", stderr); goto cleanup; }
+ }
+ }
+ if (!visible || !transparent) { fputs("Missing visible/transparent pixels\n", stderr); goto cleanup; }
+ if (!write_ppm(output, straight, options.width, options.height)) goto cleanup;
+ CHECK(mesh_avatar_renderer_resize(renderer, 129, 160));
+ CHECK(mesh_avatar_renderer_render(renderer, straight, length, MA_RGBA_STRAIGHT));
+ printf("Rendered %ux%u RGBA (%zu visible, %zu transparent pixels) to %s; resize and alpha checks passed\n",
+ options.width, options.height, visible, transparent, output);
+ result = EXIT_SUCCESS;
+cleanup:
+ free(straight);
+ free(premultiplied);
+ if (renderer) mesh_avatar_renderer_destroy(renderer);
+ if (avatar) mesh_avatar_destroy(avatar);
+ return result;
+}
diff --git a/native/include/mesh_avatar_render.h b/native/include/mesh_avatar_render.h
new file mode 100644
index 0000000..0e2299a
--- /dev/null
+++ b/native/include/mesh_avatar_render.h
@@ -0,0 +1,116 @@
+/* Optional headless rendering extension to mesh_avatar.h.
+ * Build the library with --features render before linking these functions.
+ * The default CPU-only library does NOT export them. Including this header
+ * requires no macro and does not enable the library feature.
+ *
+ * Renderers use opaque never-reused tokens and per-renderer serialization.
+ * They reference an avatar token without owning it; destroy renderers before
+ * destroying their avatar. Rendering reads the cached frame without ticking.
+ * Raw geometry borrowers must still synchronize their reads against tick/destroy.
+ * All renderer functions use the core MaStatus and thread-local last-error API.
+ * Recover from a contained GPU panic by destroying/reopening the affected objects.
+ * Destroy all avatars/renderers before unloading the library.
+ */
+
+
+#ifndef MESH_AVATAR_RENDER_H
+#define MESH_AVATAR_RENDER_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>
+#include "mesh_avatar.h"
+
+#define MA_FIT_CONTAIN 0
+
+#define MA_FIT_COVER 1
+
+#define MA_RGBA_STRAIGHT 0
+
+#define MA_RGBA_PREMULTIPLIED 1
+
+/**
+ * Physical output pixels, MSAA samples (1 or 4), fit and explicit viewport padding.
+ * Use mesh_avatar_get_info to obtain the avatar's recommended pad_top/pad_side.
+ */
+typedef struct {
+ uint32_t width;
+ uint32_t height;
+ uint32_t samples;
+ /**
+ * MA_FIT_CONTAIN or MA_FIT_COVER.
+ */
+ uint32_t fit;
+ /**
+ * Finite and greater than -1.
+ */
+ double pad_top;
+ /**
+ * Finite and greater than -0.5.
+ */
+ double pad_side;
+} MaRenderOptions;
+
+/**
+ * Opaque renderer token. Uses a separate registry from avatar handles; zero is invalid.
+ */
+typedef uint64_t MaRenderer;
+
+#define MA_GPU_UNAVAILABLE 7
+
+#define MA_RENDER_ERROR 8
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ * Create a headless renderer bound to avatar's textures. Requires the render feature.
+ * Returns MA_GPU_UNAVAILABLE only when no compatible adapter can be found; otherwise
+ * GPU initialization failures return MA_RENDER_ERROR. On failure *out is zero.
+ * Calls on a renderer are serialized; it may move between threads. It does not own
+ * the avatar. Destroy the renderer before the avatar; rendering a destroyed avatar fails.
+ * # Safety
+ * options must be readable/aligned; out writable/aligned. Pointers must not alias.
+ */
+MaStatus mesh_avatar_renderer_create(MaHandle avatar,
+ const MaRenderOptions *options,
+ MaRenderer *out);
+
+/**
+ * Render the current cached frame without ticking or invalidating borrowed geometry.
+ * Requires the render feature. rgba must hold at least width*height*4 bytes for the
+ * current size. Writes tightly packed RGBA8, top row first, with transparent clear.
+ * alpha_mode is MA_RGBA_STRAIGHT or MA_RGBA_PREMULTIPLIED. Extra bytes are untouched.
+ * The synchronous call waits for readback. The buffer is never retained and remains
+ * unchanged on failure. The caller must synchronize concurrent access to its buffer.
+ * Calls acquire the renderer before the avatar lock; tick/render/destroy are serialized.
+ * # Safety
+ * rgba must be writable for length bytes, non-NULL, and must not alias library storage.
+ */
+MaStatus mesh_avatar_renderer_render(MaRenderer renderer,
+ uint8_t *rgba,
+ size_t length,
+ uint32_t alpha_mode);
+
+/**
+ * Change physical output size, keeping fit/padding/MSAA. Requires the render feature.
+ * Invalid sizes leave the renderer unchanged. Reallocate caller buffers before rendering.
+ */
+MaStatus mesh_avatar_renderer_resize(MaRenderer renderer, uint32_t width, uint32_t height);
+
+/**
+ * Destroy a renderer from any thread, including after a contained panic.
+ * Requires the render feature. Rejects zero, unknown or destroyed tokens.
+ */
+MaStatus mesh_avatar_renderer_destroy(MaRenderer renderer);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+
+#endif /* MESH_AVATAR_RENDER_H */